diff options
| author | NotRexed <therealnothingfn@gmail.com> | 2026-11-20 15:22:16 -0500 |
|---|---|---|
| committer | NotRexed <therealnothingfn@gmail.com> | 2026-11-20 15:22:16 -0500 |
| commit | db0dc8bd5ebce6e2bc27d47085f7f104eb3037d3 (patch) | |
| tree | 4fb3edca45f8b4dd3368c6ac2a0e4fdc8ed7065c /tools/rtti_scan.py | |
Initial commit: Leonida, build-it-yourself PC port groundwork
Shader pipeline (carve, FSSM unpack, gfx1013 disassembly, RDNA2 to SPIR-V),
asset export via rpf9-explorer's Core (submodule), PE loader and shim
skeleton, and make_game.py, which builds from the user's own copy of the game.
No game data, keys or executables are included.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'tools/rtti_scan.py')
| -rw-r--r-- | tools/rtti_scan.py | 120 |
1 files changed, 120 insertions, 0 deletions
diff --git a/tools/rtti_scan.py b/tools/rtti_scan.py new file mode 100644 index 000000000..01fab1e1f --- /dev/null +++ b/tools/rtti_scan.py | |||
| @@ -0,0 +1,120 @@ | |||
| 1 | """Recover C++ class names, hierarchies and vtables from an x64 MSVC PE via RTTI. | ||
| 2 | |||
| 3 | x64 RTTI uses image-relative (RVA) fields: | ||
| 4 | TypeDescriptor { u64 pVFTable; u64 spare; char name[] = ".?AVClass@ns@@" } | ||
| 5 | CompleteObjectLocator { u32 signature(=1); u32 offset; u32 cdOffset; u32 rvaTypeDescriptor; | ||
| 6 | u32 rvaClassHierarchy; u32 rvaSelf } | ||
| 7 | ClassHierarchyDescriptor { u32 signature; u32 attributes; u32 numBaseClasses; u32 rvaBaseClassArray } | ||
| 8 | BaseClassDescriptor { u32 rvaTypeDescriptor; u32 numContainedBases; i32 mdisp, pdisp, vdisp; u32 attrs; | ||
| 9 | u32 rvaClassHierarchy } | ||
| 10 | A vtable is preceded (at -8) by a pointer to its CompleteObjectLocator. | ||
| 11 | |||
| 12 | Usage: | ||
| 13 | python -I rtti_scan.py <image> [--out file.json] | ||
| 14 | Output: classes (demangled-ish name, type descriptor RVA, base classes) and vtables (RVA, class, offset in the | ||
| 15 | complete object, number of slots that point into executable sections). | ||
| 16 | """ | ||
| 17 | import argparse | ||
| 18 | import json | ||
| 19 | import re | ||
| 20 | import struct | ||
| 21 | import sys | ||
| 22 | |||
| 23 | import pefile | ||
| 24 | |||
| 25 | |||
| 26 | def simple_name(mangled: str) -> str: | ||
| 27 | """'.?AVFoo@bar@@' -> 'bar::Foo' (enough to read; full demangling isn't needed here).""" | ||
| 28 | m = re.match(r"\.\?A[VUW](.*)@@$", mangled) | ||
| 29 | if not m: | ||
| 30 | return mangled | ||
| 31 | parts = [p for p in m.group(1).split("@") if p] | ||
| 32 | return "::".join(reversed(parts)) | ||
| 33 | |||
| 34 | |||
| 35 | def main(): | ||
| 36 | ap = argparse.ArgumentParser() | ||
| 37 | ap.add_argument("image") | ||
| 38 | ap.add_argument("--out") | ||
| 39 | a = ap.parse_args() | ||
| 40 | pe = pefile.PE(a.image, fast_load=True) | ||
| 41 | base = pe.OPTIONAL_HEADER.ImageBase | ||
| 42 | img = pe.get_memory_mapped_image() | ||
| 43 | exec_ranges = [(s.VirtualAddress, s.VirtualAddress + s.Misc_VirtualSize) for s in pe.sections | ||
| 44 | if s.Characteristics & 0x20000000] | ||
| 45 | |||
| 46 | def is_exec(rva): | ||
| 47 | return any(lo <= rva < hi for lo, hi in exec_ranges) | ||
| 48 | |||
| 49 | def u32(rva): | ||
| 50 | return struct.unpack_from("<I", img, rva)[0] | ||
| 51 | |||
| 52 | # 1. Type descriptors: '.?AV' / '.?AU' strings, 16 bytes after the descriptor start. | ||
| 53 | tds = {} | ||
| 54 | for m in re.finditer(rb"\.\?A[VUW][\x21-\x7e]{1,2000}?@@\x00", img): | ||
| 55 | rva = m.start() - 16 | ||
| 56 | if rva >= 0: | ||
| 57 | tds[rva] = m.group(0)[:-1].decode("latin-1") | ||
| 58 | |||
| 59 | # 2. Complete object locators: signature 1 and rvaSelf == own RVA. | ||
| 60 | cols = {} | ||
| 61 | for m in re.finditer(rb"\x01\x00\x00\x00", img): | ||
| 62 | rva = m.start() | ||
| 63 | if rva % 4 or rva + 24 > len(img): | ||
| 64 | continue | ||
| 65 | sig, off, cd, rtd, rchd, rself = struct.unpack_from("<6I", img, rva) | ||
| 66 | if rself == rva and rtd in tds: | ||
| 67 | cols[rva] = {"offset": off, "td": rtd, "chd": rchd} | ||
| 68 | |||
| 69 | # 3. Class hierarchies. | ||
| 70 | classes = {} | ||
| 71 | for rva, col in cols.items(): | ||
| 72 | td = col["td"] | ||
| 73 | if td in classes: | ||
| 74 | continue | ||
| 75 | chd = col["chd"] | ||
| 76 | try: | ||
| 77 | _, attrs, nbase, rarr = struct.unpack_from("<4I", img, chd) | ||
| 78 | bases = [] | ||
| 79 | for i in range(1, min(nbase, 256)): | ||
| 80 | bcd = u32(rarr + 4 * i) | ||
| 81 | btd = u32(bcd) | ||
| 82 | if btd in tds: | ||
| 83 | bases.append(simple_name(tds[btd])) | ||
| 84 | except struct.error: | ||
| 85 | attrs, bases = 0, [] | ||
| 86 | classes[td] = {"name": simple_name(tds[td]), "mangled": tds[td], "td_rva": td, | ||
| 87 | "multiple": bool(attrs & 1), "virtual": bool(attrs & 2), "bases": bases} | ||
| 88 | |||
| 89 | # 4. Vtables: a qword equal to (image base + COL rva), followed by code pointers. | ||
| 90 | vtables = [] | ||
| 91 | col_vas = {base + rva: rva for rva in cols} | ||
| 92 | for sec in pe.sections: | ||
| 93 | if sec.Characteristics & 0x20000000: | ||
| 94 | continue | ||
| 95 | lo, hi = sec.VirtualAddress, sec.VirtualAddress + sec.Misc_VirtualSize | ||
| 96 | for p in range(lo - lo % 8, hi - 8, 8): | ||
| 97 | q = struct.unpack_from("<Q", img, p)[0] | ||
| 98 | if q in col_vas: | ||
| 99 | vt = p + 8 | ||
| 100 | n = 0 | ||
| 101 | while vt + 8 * (n + 1) <= len(img): | ||
| 102 | f = struct.unpack_from("<Q", img, vt + 8 * n)[0] - base | ||
| 103 | if not (0 <= f < len(img) and is_exec(f)): | ||
| 104 | break | ||
| 105 | n += 1 | ||
| 106 | col = cols[col_vas[q]] | ||
| 107 | vtables.append({"rva": vt, "class": classes.get(col["td"], {}).get("name", "?"), | ||
| 108 | "offset_in_object": col["offset"], "slots": n}) | ||
| 109 | out = {"image": a.image, "type_descriptors": len(tds), "classes": sorted(classes.values(), key=lambda c: c["name"]), | ||
| 110 | "vtables": sorted(vtables, key=lambda v: v["rva"])} | ||
| 111 | path = a.out or re.sub(r"\.(exe|dll)$", "", a.image, flags=re.I) + ".rtti.json" | ||
| 112 | with open(path, "w", encoding="utf-8") as f: | ||
| 113 | json.dump(out, f, indent=1) | ||
| 114 | print(f"{a.image}: {len(tds)} type descriptors, {len(classes)} classes with RTTI, {len(vtables)} vtables -> {path}") | ||
| 115 | for c in out["classes"][:5]: | ||
| 116 | print(" ", c["name"], "<-", ", ".join(c["bases"][:4])) | ||
| 117 | |||
| 118 | |||
| 119 | if __name__ == "__main__": | ||
| 120 | sys.exit(main()) | ||