"""Recompiler census over a PE image's .pdata. Usage: python -I recomp_census.py [--out DIR] [--limit N] [--top K] Walks every RUNTIME_FUNCTION entry in .pdata (the same table the SEH machinery and tools/pe_inspect.py report on), decodes each function with the x86-64 decoder in tools/x64_recomp.py and runs the translator over it. The report answers the questions the arm64 port needs answered before any machine code gets emitted: * how many functions / code bytes does .pdata claim? * which mnemonics dominate the corpus? * how much of it does the current emitter cover (per-function and overall)? * what are the blockers: decode gaps, unhandled mnemonics, indirect control flow that needs the pc-table dispatch, x87/SIMD/sys instructions? Writes /.recomp.json and /.recomp.md. A wrong input or an --out that cannot be written is one ERROR line and exit code 2. Standard library only; reads the file, never runs it. """ from __future__ import annotations import argparse import json import os import struct import sys from collections import Counter sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import pe_inspect # noqa: E402 import x64_recomp # noqa: E402 DIR_EXCEPTION = pe_inspect.DIR_EXCEPTION MAX_FUNCS = 1 << 20 # .pdata this long is not a table; matches pe_inspect's guard spirit UNW_FLAG_EHANDLER = 0x1 UNW_FLAG_UHANDLER = 0x2 UNW_FLAG_CHAININFO = 0x4 UNW_FLAG_KNOWN_MASK = UNW_FLAG_EHANDLER | UNW_FLAG_UHANDLER | UNW_FLAG_CHAININFO UNW_FLAG_NAMES = { UNW_FLAG_EHANDLER: "EHANDLER", UNW_FLAG_UHANDLER: "UHANDLER", UNW_FLAG_CHAININFO: "CHAINED", } UNWIND_REG_NAMES = ( "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", ) UNWIND_OP_NAMES = { 0: "UWOP_PUSH_NONVOL", 1: "UWOP_ALLOC_LARGE", 2: "UWOP_ALLOC_SMALL", 3: "UWOP_SET_FPREG", 4: "UWOP_SAVE_NONVOL", 5: "UWOP_SAVE_NONVOL_FAR", 6: "UWOP_EPILOG", 7: "UWOP_SPARE_CODE", 8: "UWOP_SAVE_XMM128", 9: "UWOP_SAVE_XMM128_FAR", 10: "UWOP_PUSH_MACHFRAME", } MAX_UNWIND_CHAIN = 64 # insn kinds that always need the pc-table dispatch (target not statically known) INDIRECT_KINDS = ("ret",) def pdata_entries(img): """Sorted [(begin_rva, end_rva, unwind_rva)] from the exception directory.""" rva, size = img.directory(DIR_EXCEPTION) if not rva or size < 12: return [] off = img.offset(rva, size) if off is None: return [] out = [] for i in range(min(size // 12, MAX_FUNCS)): b, e, u = struct.unpack_from("= b: out.append((b, e, u)) out.sort() return out def function_bytes(img, begin, end): """File bytes for [begin_rva, end_rva), or None when it spans sections/headers oddly.""" off = img.offset(begin, end - begin) if off is None: return None return img.data[off:off + (end - begin)] def unwind_flags(img, unwind_rva): """(version, flag_names, code_count) from an UNWIND_INFO header, or None.""" off = img.offset(unwind_rva, 4) if off is None: return None b0, _prolog_size, code_count, _frame = img.data[off:off + 4] flags = b0 >> 3 names = [n for bit, n in UNW_FLAG_NAMES.items() if flags & bit] return (b0 & 7, names, code_count) def _decode_unwind_codes(data, off, count, version, frame_reg): """Decode x64 UNWIND_CODE slots starting at `off`. Returns (ops, error).""" ops = [] idx = 0 seen_epilog = False while idx < count: slot_off = off + idx * 2 code_offset = data[slot_off] op_byte = data[slot_off + 1] op = op_byte & 0x0F info = (op_byte >> 4) & 0x0F name = UNWIND_OP_NAMES.get(op) if name is None: return ops, f"unknown unwind op {op}" if op == 0: # UWOP_PUSH_NONVOL ops.append({"op": name, "code_offset": code_offset, "reg": UNWIND_REG_NAMES[info]}) idx += 1 elif op == 1: # UWOP_ALLOC_LARGE if info == 0: if idx + 2 > count: return ops, "truncated UWOP_ALLOC_LARGE" size = struct.unpack_from(" count: return ops, "truncated UWOP_ALLOC_LARGE" lo, hi = struct.unpack_from(" count: return ops, "truncated UWOP_SAVE_NONVOL" offset = struct.unpack_from(" count: return ops, "truncated UWOP_SAVE_NONVOL_FAR" lo, hi = struct.unpack_from(" count: return ops, "truncated UWOP_SPARE_CODE" ops.append({"op": name, "code_offset": code_offset}) idx += 3 elif op == 8: # UWOP_SAVE_XMM128 if idx + 2 > count: return ops, "truncated UWOP_SAVE_XMM128" offset = struct.unpack_from(" count: return ops, "truncated UWOP_SAVE_XMM128_FAR" lo, hi = struct.unpack_from("> 3) & 0x1F flag_names = [n for bit, n in UNW_FLAG_NAMES.items() if flags & bit] frame_reg = b3 & 0x0F frame_offset = ((b3 >> 4) & 0x0F) * 16 if frame_reg else 0 if hop == 0: base["version"] = version base["flags"] = flag_names base["prolog_size"] = prolog_size base["code_count"] = code_count base["frame_register"] = UNWIND_REG_NAMES[frame_reg] if frame_reg else None base["frame_offset"] = frame_offset elif base["frame_register"] is None and frame_reg: base["frame_register"] = UNWIND_REG_NAMES[frame_reg] base["frame_offset"] = frame_offset if version not in (1, 2): base["error"] = f"unsupported unwind version {version}" return base if flags & ~UNW_FLAG_KNOWN_MASK: base["error"] = f"unknown unwind flags {hex(flags)}" return base if (flags & UNW_FLAG_CHAININFO) and (flags & (UNW_FLAG_EHANDLER | UNW_FLAG_UHANDLER)): base["error"] = "CHAINED combined with EHANDLER/UHANDLER" return base # The UNWIND_CODE array is padded to an even number of 2-byte slots before trailing data. padded_bytes = ((code_count + 1) & ~1) * 2 if code_count: codes_off = img.offset(cur_rva + 4, code_count * 2) if codes_off is None: base["error"] = f"truncated unwind codes at {hex(cur_rva)}" return base ops, err = _decode_unwind_codes(img.data, codes_off, code_count, version, frame_reg) base["ops"].extend(ops) for op in ops: kind = op["op"] if kind == "UWOP_PUSH_NONVOL": base["stack_alloc"] += 8 if op["reg"] not in saved_gpr_set: saved_gpr_set.add(op["reg"]) base["saved_gprs"].append(op["reg"]) elif kind in ("UWOP_ALLOC_SMALL", "UWOP_ALLOC_LARGE"): base["stack_alloc"] += op["size"] elif kind in ("UWOP_SAVE_NONVOL", "UWOP_SAVE_NONVOL_FAR"): if op["reg"] not in saved_gpr_set: saved_gpr_set.add(op["reg"]) base["saved_gprs"].append(op["reg"]) elif kind in ("UWOP_SAVE_XMM128", "UWOP_SAVE_XMM128_FAR"): if op["reg"] not in saved_xmm_set: saved_xmm_set.add(op["reg"]) base["saved_xmms"].append(op["reg"]) elif kind == "UWOP_PUSH_MACHFRAME": base["has_machframe"] = True elif kind == "UWOP_EPILOG": if op.get("at_end") or (op.get("epilog_offset", 0) > 0): base["epilog_count"] += 1 if err is not None: base["error"] = err return base tail_rva = cur_rva + 4 + padded_bytes if flags & UNW_FLAG_CHAININFO: if hop >= MAX_UNWIND_CHAIN: base["error"] = f"chained unwind depth exceeds {MAX_UNWIND_CHAIN}" return base chain_off = img.offset(tail_rva, 12) if chain_off is None: base["error"] = f"truncated chained RUNTIME_FUNCTION at {hex(tail_rva)}" return base _cb, _ce, next_rva = struct.unpack_from(" arm64 recompiler census over .pdata") p.add_argument("image") p.add_argument("--out", default=".") p.add_argument("--limit", type=int, default=0, help="only inspect the first N .pdata functions") p.add_argument("--top", type=int, default=40) a = p.parse_args(argv) try: r = census(a.image, a.limit or None) except pe_inspect.PeFormatError as e: print(f"{a.image}: {e}", file=sys.stderr) return 1 except OSError as e: # missing image, a folder, no permission: one line, not a traceback print(f"ERROR: {e}", file=sys.stderr) return 2 r["top_mnemonics"] = r["top_mnemonics"][:a.top] r["unhandled"] = r["unhandled"][:a.top] name = os.path.basename(a.image) try: # --out naming a file, or a folder that cannot be written os.makedirs(a.out, exist_ok=True) with open(os.path.join(a.out, name + ".recomp.json"), "w", encoding="utf-8", newline="\n") as f: json.dump(r, f, indent=1) with open(os.path.join(a.out, name + ".recomp.md"), "w", encoding="utf-8", newline="\n") as f: f.write(to_markdown(r)) except OSError as e: print(f"ERROR: {e}", file=sys.stderr) return 2 print(f"{r['file']}: {r['pdata_functions']:,} fns, {r['insns']:,} insns, " f"{r['insn_coverage_pct']}% covered, {len(r['unhandled'])} hazard kinds") return 0 if __name__ == "__main__": try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode sys.stdout.reconfigure(errors="replace") except (AttributeError, ValueError, OSError): pass sys.exit(main())