"""Compare pinned native functions between two local images; no process access or patching."""
import argparse
import hashlib
import json
import pathlib

import pefile
from capstone import Cs, CS_ARCH_X86, CS_MODE_64
from capstone.x86 import X86_OP_IMM, X86_OP_MEM, X86_REG_RIP

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--source', required=True, type=pathlib.Path)
parser.add_argument('--target', required=True, type=pathlib.Path)
parser.add_argument('--output', required=True, type=pathlib.Path)
parser.add_argument('--rva', action='append', required=True, type=lambda value: int(value, 0))
args = parser.parse_args()
source_raw, target_raw = args.source.read_bytes(), args.target.read_bytes()
source, target = pefile.PE(data=source_raw, fast_load=True), pefile.PE(data=target_raw, fast_load=True)
for selected_image in (source, target):
    selected_image.parse_data_directories(directories=[pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_EXCEPTION']])
source_functions = {entry.struct.BeginAddress for entry in source.DIRECTORY_ENTRY_EXCEPTION}
decoder = Cs(CS_ARCH_X86, CS_MODE_64)
decoder.detail = True
target_functions = {entry.struct.BeginAddress for entry in target.DIRECTORY_ENTRY_EXCEPTION}
target_sections = [(section.VirtualAddress, section.get_data()) for section in target.sections if section.Characteristics & 0x20000000]


def signature(rva, limit):
    code = source.get_data(rva, limit + 15)
    length = 0
    mask = bytearray(b'\xff' * len(code))
    instructions = []
    for instruction in decoder.disasm(code, rva):
        start = instruction.address - rva
        if start + instruction.size > limit:
            break
        instructions.append({'offset': start, 'text': instruction.mnemonic + ' ' + instruction.op_str})
        if instruction.disp_size and any(operand.type == X86_OP_MEM and operand.mem.base == X86_REG_RIP for operand in instruction.operands):
            for offset in range(instruction.disp_offset, instruction.disp_offset + instruction.disp_size):
                mask[start + offset] = 0
        if instruction.imm_size and (instruction.mnemonic.startswith('j') or instruction.mnemonic == 'call'):
            for offset in range(instruction.imm_offset, instruction.imm_offset + instruction.imm_size):
                mask[start + offset] = 0
        length = start + instruction.size
        if instruction.mnemonic.startswith('ret'):
            break
    return code[:length], mask[:length], instructions


results = []
for rva in args.rva:
    selected = None
    for limit in (768, 384, 192, 96, 64, 40):
        code, mask, instructions = signature(rva, limit)
        runs, start = [], None
        for index, byte in enumerate(mask + b'\0'):
            if byte and start is None:
                start = index
            elif not byte and start is not None:
                runs.append((index - start, start))
                start = None
        if not runs or sum(bool(byte) for byte in mask) < 20:
            continue
        run_length, anchor_offset = max(runs)
        anchor = code[anchor_offset:anchor_offset + min(run_length, 24)]
        matches = []
        for section_rva, data in target_sections:
            at = 0
            while (at := data.find(anchor, at)) >= 0:
                candidate = at - anchor_offset
                candidate_rva = section_rva + candidate
                entry = candidate_rva in target_functions or (rva not in source_functions and candidate > 0 and candidate_rva % 16 == 0 and data[candidate - 1] == 0xcc)
                if (candidate >= 0 and entry
                        and candidate + len(code) <= len(data)
                        and all(not mask[index] or value == data[candidate + index] for index, value in enumerate(code))):
                    matches.append(candidate_rva)
                at += 1
        selected = {'sourceRva': hex(rva), 'matches': [hex(value) for value in matches],
                    'signatureBytes': len(code), 'fixedBytes': sum(bool(byte) for byte in mask),
                    'sourceBytes': code.hex(), 'mask': mask.hex(), 'sourceInstructions': instructions}
        if len(matches) == 1:
            selected['targetRva'] = hex(matches[0])
            selected['targetBytes'] = target.get_data(matches[0], len(code)).hex()
            break
    results.append(selected or {'sourceRva': hex(rva), 'matches': [], 'reason': 'Function too short to match uniquely'})

report = {'scope': 'Static instruction correspondence only; field meaning, native ABI and runtime behavior require separate verification',
          'sourceSha256': hashlib.sha256(source_raw).hexdigest(), 'targetSha256': hashlib.sha256(target_raw).hexdigest(),
          'functions': results}
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(report, indent=2), encoding='utf-8')
print(json.dumps({'functions': [{'source': row['sourceRva'], 'target': row.get('targetRva'), 'matches': len(row['matches'])} for row in results]}))
