# Generates the reconstructed C++ tree from what the build knows: RTTI classes (classes.tsv: size from the deleting # destructor, direct bases, vtable slots), confirmed fields (dump/zhl_fields.tsv) and every decompiled function (dump/all.c). # /classes.h one class per type: real bases, the vptr implied, own fields at their exact offsets, padding up to # the real size, virtual methods in slot order and the other methods as declarations # /.cpp that class's method bodies as decompiled; Ghidra's Class::method(obj, args) calls become # ((Class *)(obj))->Class::method(args) (a direct call, as in the binary) # A function src/ took over (a curated file with its address in a comment, // 0040ed50) is declared but not emitted. # /stubs.cpp every function, vtable slot and import src/ has not taken over, defined as a stub that stops the # game where it is reached: src/ + stubs.cpp link into a game that runs as far as curation goes # Targets 64-bit Linux. The original 32-bit layout is kept as LAYOUT32 asserts, checked with -m32. # --check compiles every .cpp for x86_64, reports how many methods compile and how many raw offset accesses remain # (each one is a 64-bit hazard until it becomes a named field). # Fields come from the build's merged list with db/fields.tsv (and any --fields file) on top, so a field added there # shows up in classes.h without a Ghidra rebuild. # Usage: source_tree.py out_dir classes.tsv dump_dir zhl_vtables.tsv [--check] [--fields extra.tsv ...] import collections, concurrent.futures, os, re, subprocess, sys outDir, classesPath, dumpDir, zhlVtablesPath = sys.argv[1:5] isCheck = '--check' in sys.argv overlayPaths = [sys.argv[i + 1] for i, arg in enumerate(sys.argv) if arg == '--fields'] # more field rows, after db/fields.tsv CALLING = re.compile(r'^(?P.+?)\s*\b(?:(?P__thiscall|__fastcall|__cdecl|__stdcall)\s+)?(?P[\w:~]+)\((?P.*)\)\s*$') POINTER_LIKE = {'EntityPtr'} # REPENTOGON's smart pointer, a raw Entity * in the decompiled code LIBRARY = re.compile(r'^(std|rapidxml|theoraplayer|luabridge|stb_vorbis|Concurrency)(::|$)') # third party: declared, not reconstructed IDENT = re.compile(r'^~?[A-Za-z_]\w*$') INTRINSIC = re.compile(r'\b(CONCAT|SUB|ZEXT|SEXT|CARRY|SCARRY|SBORROW)(\d+)\(') CLANG = ['clang++', '--target=x86_64-linux-gnu', '-std=c++20', '-fsyntax-only', '-ferror-limit=0', '-Wno-invalid-offsetof', '-Wno-pragma-once-outside-header', '-w'] PRIMITIVE = {'bool': 1, 'char': 1, 'byte': 1, 'undefined': 1, 'undefined1': 1, 'short': 2, 'ushort': 2, 'word': 2, 'undefined2': 2, 'int': 4, 'uint': 4, 'float': 4, 'dword': 4, 'undefined4': 4, 'long': 4, 'ulong': 4, 'double': 8, 'Vector': 8, 'longlong': 8, 'ulonglong': 8, 'undefined8': 8, 'uint32_t': 4, 'int32_t': 4, 'uint8_t': 1, 'int8_t': 1, 'uint16_t': 2, 'int16_t': 2, 'uint64_t': 8, 'int64_t': 8, 'unsigned int': 4, 'unsigned char': 1} PRELUDE = '''// Generated by scripts/source_tree.py. Do not edit: fix names, fields and prototypes in db/ and rebuild. #pragma once #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include typedef long long __int64; // The original 32-bit layout, checked with -m32: offsets and sizes there are the evidence, not the 64-bit target #if __SIZEOF_POINTER__ == 4 #define LAYOUT32(...) static_assert(__VA_ARGS__) #else #define LAYOUT32(...) #endif typedef void code(...); // Ghidra's p-code intrinsics, as 64-bit bit patterns (CONCATxy: x and y bytes; SUBxy(v, n): y bytes from byte n of x) template inline uint64_t ghidra_bits(T v) { uint64_t r = 0; __builtin_memcpy(&r, &v, sizeof(T) < 8 ? sizeof(T) : 8); return r; } inline uint64_t ghidra_mask(int n) { return n >= 8 ? ~0ull : (1ull << 8 * n) - 1; } #define GHIDRA_CONCAT(x, y, a, b) ((ghidra_bits(a) << 8 * (y)) | (ghidra_bits(b) & ghidra_mask(y))) #define GHIDRA_SUB(x, y, v, n) ((ghidra_bits(v) >> 8 * (n)) & ghidra_mask(y)) #define GHIDRA_ZEXT(x, y, v) (ghidra_bits(v) & ghidra_mask(x)) #define GHIDRA_SEXT(x, y, v) ((uint64_t)((int64_t)(ghidra_bits(v) << (64 - 8 * (x))) >> (64 - 8 * (x)))) #define GHIDRA_CARRY(x, a, b) ((ghidra_bits(a) & ghidra_mask(x)) + (ghidra_bits(b) & ghidra_mask(x)) > ghidra_mask(x)) #define GHIDRA_SCARRY(x, a, b) ghidra_scarry(x, ghidra_bits(a), ghidra_bits(b)) #define GHIDRA_SBORROW(x, a, b) ghidra_sborrow(x, ghidra_bits(a), ghidra_bits(b)) inline int64_t ghidra_signed(int x, uint64_t v) { return (int64_t)(v << (64 - 8 * x)) >> (64 - 8 * x); } inline bool ghidra_scarry(int x, uint64_t a, uint64_t b) { int64_t s = ghidra_signed(x, a) + ghidra_signed(x, b); return s != ghidra_signed(x, (uint64_t)s); } inline bool ghidra_sborrow(int x, uint64_t a, uint64_t b) { int64_t s = ghidra_signed(x, a) - ghidra_signed(x, b); return s != ghidra_signed(x, (uint64_t)s); } template inline T ABS(T v) { return v < 0 ? -v : v; } template inline T SQRT(T v) { return __builtin_sqrt(v); } inline code *swi(int) { return 0; } // int3 / int 0x29: a breakpoint or fast-fail inline void halt_baddata() {} // (int)x / (uint)x as decompiled: a number stays 32-bit, a pointer keeps its full width (pointer math on 64-bit) template inline auto GHIDRA_INT(T v) { if constexpr (__is_pointer(T) || __is_class(T)) return (intptr_t)v; else return (int)v; } template inline auto GHIDRA_UINT(T v) { if constexpr (__is_pointer(T) || __is_class(T)) return (uintptr_t)(intptr_t)v; else return (uint)v; } // A pointer cast as decompiled: a float or double operand holds the pointer's bits (MSVC copies through XMM registers) template inline To GHIDRA_CAST(From v) { if constexpr (__is_same(From, float) || __is_same(From, double)) { uintptr_t bits = 0; __builtin_memcpy(&bits, &v, sizeof(v) < sizeof(bits) ? sizeof(v) : sizeof(bits)); return (To)bits; } else return (To)v; } // A smart pointer the decompiled code handles as a raw pointer: built from 0 or a pointer, converts back, compares #define GHIDRA_POINTER_LIKE(Self) \ void *_ptr; \ Self(intptr_t value = 0) : _ptr((void *)value) {} \ Self(const void *value) : _ptr((void *)value) {} \ template operator T *() const { return (T *)_ptr; } \ explicit operator intptr_t() const { return (intptr_t)_ptr; } \ friend bool operator==(Self a, Self b) { return a._ptr == b._ptr; } \ friend bool operator!=(Self a, Self b) { return a._ptr != b._ptr; } extern void *ExceptionList; // FS:[0], the SEH chain head extern double __uint_to_double_fixup[2]; // MSVC CRT: +2^32 for a uint whose top bit was set ''' # Ghidra's primitive type names, written as the standard types they are (Ghidra's ulong is 4 bytes, glibc's is 8) GHIDRA_RENAMES = {'undefined': 'uint8_t', 'undefined1': 'uint8_t', 'byte': 'uint8_t', 'uchar': 'uint8_t', 'undefined2': 'uint16_t', 'word': 'uint16_t', 'ushort': 'uint16_t', 'undefined4': 'uint32_t', 'dword': 'uint32_t', 'uint': 'uint32_t', 'ulong': 'uint32_t', 'undefined8': 'uint64_t', 'ulonglong': 'uint64_t', 'qword': 'uint64_t', 'longlong': 'int64_t', 'float10': 'long double'} PRELUDE_TYPES = set(GHIDRA_RENAMES) | {'code', '__int64'} def generated_rename(text): # Ghidra's primitive names -> standard types, the MSVC STL stand-ins out of the real std's way text = re.sub(r'\b(' + '|'.join(GHIDRA_RENAMES) + r')\b', lambda m: GHIDRA_RENAMES[m[1]], text) return re.sub(r'\bstd::', 'msvc::', re.sub(r'\bnamespace std\b', 'namespace msvc', text)) def std_names_load(): # every name the C library headers declare: the real declaration wins over Ghidra's copy includes = ''.join(re.findall(r'#include <\w+>\n', PRELUDE)) text = subprocess.run(['clang++', '-std=c++20', '-E', '-P', '-x', 'c++', '-'], input=includes, capture_output=True, text=True).stdout return set(re.findall(r'[A-Za-z_]\w*', text)) def snake(name): return re.sub(r'(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])', '_', name).replace('__', '_').lower() def classes_load(): rows = {} for line in open(classesPath): if line.startswith('#'): continue cls, _, _, size, bases, attrs, slots = line.rstrip('\n').split('\t') rows[cls] = {'size': int(size, 0) if size != '-' else None, 'attrs': int(attrs), 'bases': [] if bases == '-' else [(b.rsplit('@', 1)[0], int(b.rsplit('@', 1)[1], 0)) for b in bases.split(',')], 'slots': [int(a, 16) for a in slots.split(',') if a]} return rows def container_name(typ): # vector_DamageEvent -> std_vector: the MSVC layouts ApplyTypes gives Ghidra (one per kind) if typ.startswith('std_string'): return 'std_string' if re.fullmatch(r'(std_)?vector_bool', typ): return 'std_vector_bool' match = re.fullmatch(r'(?:std_)?(vector|deque|map|set|multiset|multimap|list)_\w+', typ) return f'std_{match[1]}' if match else typ def fields_load(): fields, bases, sizes = collections.defaultdict(dict), {}, {} overlays = [os.path.join(os.path.dirname(os.path.abspath(dumpDir)), 'db', 'fields.tsv')] + overlayPaths for line in [l for path in [dumpDir + '/zhl_fields.tsv'] + overlays if os.path.exists(path) for l in open(path)]: cols = line.rstrip('\n').split('\t') if line.startswith('#') or len(cols) < 3: continue if cols[1] == 'base': bases[cols[0]] = cols[2]; continue if cols[1] == 'size': sizes[cols[0]] = int(cols[2], 0); continue if cols[2].startswith('- '): fields[cols[0]].pop(int(cols[1], 16), None); continue # a deleted wrong field decl = cols[2].replace('const ', '').strip() count = re.search(r'\[(\w+)\]\s*$', decl) if count: decl = decl[:count.start()] typ, name = decl.rsplit(None, 1) if ' ' in decl else (decl, '_unnamed') fields[cols[0]][int(cols[1], 16)] = (container_name(typ.strip()), re.sub(r'\W', '', name), int(count.group(1), 0) if count else 1) return fields, bases, sizes def functions_load(): # address -> (Class, method, return type, calling convention, params without this, this param, body) funcs, headers = {}, {} for chunk in open(dumpDir + '/all.c', errors='replace').read().split('\n//@@ ')[1:]: headers[int(chunk.split(None, 1)[0], 16)] = chunk.split('\n', 1)[0].split(None, 1)[-1] head, _, rest = chunk.partition('\n{\n') block = head.strip().split('\n\n')[-1] # the last paragraph before '{' (comments can hold or lose '*/') match = CALLING.match(' '.join(block.split())) # Ghidra wraps long signatures if not rest or not match or match['ret'].rstrip().endswith((':', '~')) or re.search(r'[<(]', match['ret'] + match['params'].replace('(*', '')): continue # templates, array returns: not yet cls, _, method = match['name'].rpartition('::') params = [p.strip() for p in match['params'].split(',') if p.strip() and p.strip() != 'void'] thisParam = params.pop(0) if match['cc'] == '__thiscall' and params else None funcs[int(chunk.split(None, 1)[0], 16)] = (cls, method, match['ret'].strip(), match['cc'] or '', params, thisParam, rest[:rest.rfind('\n}')]) claimed = set(headers.values()) for addr, f in funcs.items(): # a stale prototype naming another function's address takes its own header's name name = f'{f[0]}::{f[1]}' if f[0] else f[1] if headers[addr] != name and name in claimed: funcs[addr] = headers[addr].rpartition('::')[::2] + f[2:] return funcs def types_load(): # Ghidra's own types (dump/types.tsv): structs and unions with components, typedefs, enums structs, typedefs, enums = {}, {}, {} path = dumpDir + '/types.tsv' for line in open(path, errors='replace') if os.path.exists(path) else []: cols = line.rstrip('\n').split('\t') if line.startswith('#'): continue if cols[0] in ('S', 'U'): structs[cols[1]] = (int(cols[2]), []) elif cols[0] == 'F' and cols[1] in structs: structs[cols[1]][1].append((int(cols[2]), cols[3], cols[4])) elif cols[0] == 'T': typedefs[cols[1]] = cols[2] elif cols[0] == 'E': enums[cols[1]] = (int(cols[2]), []) elif cols[0] == 'V' and cols[1] in enums: enums[cols[1]][1].append((cols[2], int(cols[3]))) return structs, typedefs, enums def component_parse(display): # Ghidra display type -> (C type, element count) display = display.replace('const ', '').strip() dims = [int(d) for d in re.findall(r'\[(\d+)\]', display)] base = re.sub(r'\[\d*\]', '', display).strip() base = {'pointer': 'void *', 'string': 'char', 'TerminatedCString': 'char', 'unicode': 'uint16_t', 'qword': 'uint64_t'}.get(base, base) count = 1 for d in dims: count *= d return base, count def type_names(text): return {t for t in re.findall(r'[A-Za-z_]\w*(?:::\w+)*', text) if t not in PRIMITIVE and t not in ('const', 'unsigned', 'signed', 'void', 'struct', 'virtual', 'override', '__int64', 'size_t', 'wchar_t', 'long', 'short')} def sig_types(ret, params): # type names only: each parameter without its name return type_names(ret + ' ' + ' '.join(p.rsplit(None, 1)[0] if ' ' in p.strip() else p for p in params)) def method_declare(cls, method, ret, cc, params, isVirtual): shortName = cls.split('::')[-1] if not IDENT.match(method) or method.startswith('FUN_') or method != shortName and method in typeNames: return None # an ICF name like EntityRef would hide the type args = ', '.join(params) if method == shortName: return f' {shortName}({args});' if method == '~' + shortName: return f' {"virtual " if isVirtual else ""}~{shortName}();' prefix = 'virtual ' if isVirtual else 'static ' if cc != '__thiscall' else '' return f' {prefix}{ret} {method}({args});' def fields_rewrite(text): # bytes Ghidra has no field for, as explicit offsets: EXPR->field_0x1c, EXPR.field_0x1c, EXPR._0_4_ out, pos = [], 0 for match in re.finditer(r'(->|\.)(?:field_0x([0-9a-f]+)|_(\d+)_(\d+)_)\b', text): start = match.start() while start > pos: # walk back over the postfix expression: names, (...), [...], -> and . ch = text[start - 1] if ch in ')]': depth, start = 1, start - 1 while start > pos and depth: start -= 1; depth += {')': 1, ']': 1, '(': -1, '[': -1}.get(text[start], 0) elif ch.isalnum() or ch == '_': start -= 1 elif text[start - 2:start] == '->': start -= 2 elif ch == '.': start -= 1 else: break expr = text[start:match.start()] address = f'(char *)({expr})' if match[1] == '->' else f'(char *)&({expr})' offset, width = (int(match[2], 16), 1) if match[2] else (int(match[3]), int(match[4])) typ = {1: 'undefined1', 2: 'undefined2', 4: 'undefined4', 8: 'undefined8'}.get(width, 'undefined1') out.append(text[pos:start] + f'(*({typ} *)({address} + 0x{offset:x}))'); pos = match.end() return ''.join(out) + text[pos:] def offsets_rewrite(text): # *(T *)((int)p + 0x10) -> *(T *)((char *)p + 0x10): byte arithmetic on a pointer, not an int return re.sub(r'(\*\([\w ]+\*+\)\()\((?:int|uint)\)((?:\w+(?:->|\.))*\w+|\([^()]*\)) \+ ', r'\1(char *)\2 + ', text) def operand_end(text, i): # end of the unary expression starting at i: prefix ops, casts, a primary, then postfix n = len(text) def group(j): # j at an opening bracket: index after its match depth = 0 while j < n: depth += {'(': 1, '[': 1, ')': -1, ']': -1}.get(text[j], 0); j += 1 if depth == 0: return j return n while i < n and text[i] in ' *&-!~': i += 1 cast = re.match(r'\([\w ]+\*?\s*\)', text[i:]) # a nested cast applies to the operand after it if cast and not re.fullmatch(r'\(\s*\w+\s*\)', cast[0]) or cast and cast[0][1:-1].strip() in PRIMITIVE: return operand_end(text, i + len(cast[0])) if i < n and text[i] == '(': i = group(i) else: m = re.match(r"[\w.]+|'[^']*'|\"[^\"]*\"", text[i:]) i += len(m[0]) if m else 0 while i < n: if text[i] in '([': i = group(i) elif text.startswith('->', i): i += 2; i += len(re.match(r'\w*', text[i:])[0]) elif text[i] == '.' and i + 1 < n and (text[i + 1].isalpha() or text[i + 1] == '_'): i += 1; i += len(re.match(r'\w*', text[i:])[0]) else: break return i def int_casts_rewrite(text): # (int)expr -> GHIDRA_INT(expr), (uint)expr -> GHIDRA_UINT(expr) out, pos = [], 0 for match in re.finditer(r'\((int|uint)\)', text): if match.start() < pos: continue end = operand_end(text, match.end()) inner = int_casts_rewrite(text[match.end():end]) out.append(text[pos:match.start()] + f'GHIDRA_{match[1].upper()}({inner})'); pos = end return ''.join(out) + text[pos:] def pointer_casts_rewrite(text): # (T *)expr -> GHIDRA_CAST(expr) out, pos = [], 0 for match in re.finditer(r'\(((?:struct )?(?:\w+::)*\w+ ?\*+)\)', text): if match.start() < pos or match[1].startswith(('code', 'void')): continue end = operand_end(text, match.end()) if end == match.end(): continue inner = pointer_casts_rewrite(text[match.end():end]) out.append(text[pos:match.start()] + f'GHIDRA_CAST<{match[1]}>({inner})'); pos = end return ''.join(out) + text[pos:] def virtuals_rewrite(text, varTypes): # (**(code **)(*(int *)X + 0x24))(args) -> X->Method(args), X's class from its declaration def slot_call(match): var, offset = match[1], int(match[2], 0) cls = varTypes.get(var) if cls not in canon or offset % 4 or not 0 < offset // 4 < len(canon[cls]): return match[0] return f'{var}->{re.search(r"(~?\w+)\(", canon[cls][offset // 4]).group(1)}(' return re.sub(r'\(\*\*\(code \*\*\)\(\*\(\w+ \*\)(\w+) \+ (0x[0-9a-f]+|\d+)\)\)\(', slot_call, text) def calls_rewrite(text, members): # Class::method(obj, args) -> ((Class *)(obj))->Class::method(args), innermost first out, pos = [], 0 for match in re.finditer(r'\b((?:\w+::)*\w+)::(~?\w+)\(', text): if match.start() < pos: continue depth, end = 1, match.end() while end < len(text) and depth: depth += {'(': 1, ')': -1}.get(text[end], 0); end += 1 inner = calls_rewrite(text[match.end():end - 1], members) full = f'{match[1]}::{match[2]}' if full not in members: out.append(text[pos:match.end()] + inner + ')'); pos = end; continue depth, split = 0, len(inner) for i, ch in enumerate(inner): depth += {'(': 1, ')': -1}.get(ch, 0) if ch == ',' and depth == 0: split = i; break obj, args = inner[:split].strip(), inner[split + 1:].strip() target = 'this' if obj == 'this' else f'(({match[1]} *)({obj}))' out.append(text[pos:match.start()] + f'{target}->{full}({args})'); pos = end return ''.join(out) + text[pos:] classes, (fields, fieldBases, sizes), funcs = classes_load(), fields_load(), functions_load() ghidraStructs, typedefs, enums = types_load() mentioned = set(re.findall(r'[A-Za-z_]\w*', ' '.join(f[6] + ' ' + f[2] + ' ' + ' '.join(f[4]) for f in funcs.values()))) mentioned |= {component_parse(t)[0].rstrip(' *') for row in fields.values() for t, *_ in row.values()} for extra in ('externals.tsv', 'data.tsv'): # imports and globals name Win32 and CRT types the bodies may not if os.path.exists(f'{dumpDir}/{extra}'): mentioned |= set(re.findall(r'[A-Za-z_]\w*', open(f'{dumpDir}/{extra}', errors='replace').read())) wanted, queue = set(), [t for t in mentioned if t in ghidraStructs or t in typedefs] while queue: # the closure over by-value and pointer members and typedef targets t = queue.pop() if t in wanted: continue wanted.add(t) refs = [component_parse(d)[0].rstrip(' *') for _, d, _ in ghidraStructs.get(t, (0, []))[1]] + [component_parse(typedefs.get(t, ''))[0].rstrip(' *')] queue += [r for r in refs if r in ghidraStructs or r in typedefs] STD_NAMES = std_names_load() for t in sorted(wanted & set(ghidraStructs)): if t in fields or t in classes or not IDENT.match(t) or t in PRIMITIVE or t in PRELUDE_TYPES or t in STD_NAMES: continue taken = set() for off, display, fname in ghidraStructs[t][1]: typ, count = component_parse(display) if count == 0: continue # a flexible array member: no storage of its own name = re.sub(r'\W', '_', fname) or f'field_0x{off:x}' if name in taken: name += f'_0x{off:x}' taken.add(name); fields[t][off] = (typ, name, count) if ghidraStructs[t][1]: sizes[t] = ghidraStructs[t][0] # a field-less one is Ghidra's 4-byte placeholder, not a size else: fields[t] zhlSlots = {(c, int(i)): n for c, i, n in (l.rstrip('\n').split('\t') for l in open(zhlVtablesPath))} QUALIFIED = re.compile(r'^\w+(::\w+)*$') names = set(classes) | set(fields) | set(fieldBases) | {f[0] for f in funcs.values() if f[3] == '__thiscall' and QUALIFIED.match(f[0])} namespaces = {'std'} | {c.rsplit('::', i)[0] for c in classes for i in range(1, c.count('::') + 1)} - set(classes) - set(fields) # KAGE, KAGE::Graphics ... names -= namespaces base = {c: (classes[c]['bases'][0][0] if c in classes and classes[c]['bases'] else fieldBases.get(c)) for c in names} size = {c: (classes.get(c, {}).get('size') or sizes.get(c)) for c in names} typeNames = {c.rpartition('::')[2] for c in names} | {t for f in funcs.values() for t in sig_types(f[2], f[4])} methods = collections.defaultdict(list) for addr, f in sorted(funcs.items()): if f[0] in names: methods[f[0]].append((addr, f[:5])) def width_of(typ, depth=0): # bytes of a field type: primitives, laid-out classes, typedefs and enums by their target if typ.endswith('*'): return 4 if typ in PRIMITIVE: return PRIMITIVE[typ] if typ in done: return done[typ][0] if typ in enums: return enums[typ][0] if typ in typedefs and depth < 8 and '(' not in typedefs[typ]: target, count = component_parse(typedefs[typ]) inner = width_of(target, depth + 1) return inner * count if inner else None return None done, order, used, canon, defined = {}, [], set(), {}, {} stubs, dataStubs = [], [] # (owner, declaration, address): everything src/ has not taken over, defined as a stub # defined: address -> the declaration its body is defined with def class_emit(cls, stack=()): if cls in done or cls in stack or cls in PRELUDE_TYPES: return if cls in curatedClasses or cls.rpartition('::')[0] in curatedClasses: return # declared by src/ (a nested class with its outer one), only forward-declared here parent = base.get(cls) if base.get(cls) in names and base.get(cls) not in curatedClasses and (base.get(cls) or '').rpartition('::')[0] not in curatedClasses else None # a src/ parent (or one nested in a src/ class) stays bytes if parent: class_emit(parent, stack + (cls,)) namespace, _, shortName = cls.rpartition('::') isNested = namespace in names # Cutscene::ANM2Part: declared inside Cutscene, defined after it if isNested: class_emit(namespace, stack + (cls,)) for typ, *_ in fields.get(cls, {}).values(): # a member held by value needs its type laid out first if typ in names and not typ.endswith('*'): class_emit(typ, stack + (cls,)) info = classes.get(cls, {}) isPolymorphic = bool(info.get('slots')) or (parent and done.get(parent, (0, False))[1]) pos = done[parent][0] if parent else 4 if isPolymorphic else 0 lines, asserts = [], [] own = {o: f for o, f in fields.get(cls, {}).items() if o >= pos} for off in sorted(own): typ, name, count = own[off] if off < pos: continue if off > pos: lines.append(f' uint8_t _pad_0x{pos:x}[0x{off - pos:x}];') nxt = min([o for o in own if o > off], default=size.get(cls) or off + 4) isPointer = typ.endswith('*') width = 4 if isPointer else width_of(typ) dim = f'[{count}]' if count > 1 else '' if width and off + width * count <= nxt: lines.append(f' {typ} {name}{dim};'); used.update(type_names(typ)); pos = off + width * count else: # STL containers and types without a known layout stay bytes until they are modelled lines.append(f' uint8_t {name}[0x{nxt - off:x}]; // {typ}{dim}'); pos = nxt asserts.append(f'LAYOUT32(offsetof({cls}, {name}) == 0x{off:x});') if size.get(cls) and pos < size[cls]: lines.append(f' uint8_t _pad_0x{pos:x}[0x{size[cls] - pos:x}];'); pos = size[cls] if size.get(cls): asserts.append(f'LAYOUT32(sizeof({cls}) == 0x{size[cls]:x});' if pos == size[cls] else f'// {cls}: deleting destructor says 0x{size[cls]:x}, below its layout 0x{pos:x} (ICF-shared destructor?)') # Virtual methods, in slot order so the vtable layout matches: a slot this class introduces is declared with its # function's name and signature (vfunc_N when it has none), an override reuses the introducing declaration. slots, parentSlots = info.get('slots', []), classes.get(parent, {}).get('slots', []) canon[cls] = list(canon.get(parent, [])) decls, seen = [], set() for i, addr in enumerate(slots): if i < len(parentSlots) and addr == parentSlots[i]: continue # inherited unchanged sig = funcs.get(addr) if i == 0 and size.get(cls): decl = f'virtual ~{shortName}();' # slot 0 is the deleting destructor elif i < len(canon[cls]): decl = canon[cls][i].replace('virtual ', '', 1).rstrip(';') + ' override;' elif sig and IDENT.match(sig[1]) and sig[1] != shortName and f' {sig[1]}({", ".join(sig[4])});' not in ''.join(canon[cls]): decl = f'virtual {sig[2]} {sig[1]}({", ".join(sig[4])});' elif (cls, i) in zhlSlots and f' {zhlSlots[cls, i]}(' not in ''.join(canon[cls]): # REPENTOGON's declared layout names the slot decl = f'virtual {sig[2] if sig else "void"} {zhlSlots[cls, i]}({", ".join(sig[4]) if sig else ""});' else: decl = f'virtual void vfunc_{i}();' if i >= len(canon[cls]): canon[cls].append('virtual ~Base();' if decl.startswith('virtual ~') else decl) if decl.startswith('virtual ~'): seen.update({'~' + shortName, sig[1] if sig else None}) elif i < len(parentSlots): seen.add(sig[1] if sig else None) else: seen.add((sig[1], ', '.join(sig[4])) if sig else None) seen.add(re.search(r'(~?\w+)\(', decl).group(1)) if sig: used.update(sig_types(sig[2], sig[4])) if sig and sig[0] == cls and not decl.startswith('virtual ~') and decl.endswith(f'({", ".join(sig[4])});' if 'override' not in decl else f'({", ".join(sig[4])}) override;'): defined[addr] = decl decls.append(f' {decl} // {addr:08x} slot {i}' + (f' {sig[0]}::{sig[1]}' if sig and sig[0] != cls else '')) stubs.append((cls, decl, addr, True)) slotAddrs = set(slots) for addr, (_, method, ret, cc, params) in methods.get(cls, []): key = (method, ', '.join(params)) if addr in slotAddrs or key in seen or method in seen: continue decl = method_declare(cls, method, ret, cc, params, False) if not decl: continue seen.add(key); used.update(sig_types(ret, params)); defined[addr] = decl.strip() decls.append(decl + f' // {addr:08x}') stubs.append((cls, decl, addr)) if cls in POINTER_LIKE: lines = [f' GHIDRA_POINTER_LIKE({shortName})'] constructors = [d for d in decls if re.match(rf'\s+{shortName}\(', d)] if constructors and not any(re.match(rf'\s+{shortName}\(\)', d) for d in constructors): decls.append(f' {shortName}() = default;') # members still need one nested = [c.rpartition('::')[2] for c in names if c.rpartition('::')[0] == cls] body = '\n'.join([f' struct {n};' for n in sorted(nested)] + decls + ([''] if decls and lines else []) + lines) head = f'struct {cls if isNested else shortName}' + (f' : {parent}' if parent else '') text = f'{head} {{\n{body}\n}};\n' order.append((f'namespace {namespace} {{\n{text}}}\n' if namespace and not isNested else text) + '\n'.join(asserts) + '\n') done[cls] = (pos, bool(isPolymorphic)) srcDir = os.path.join(os.path.dirname(os.path.abspath(outDir)), 'src') NAMESPACE_BLOCK = re.compile(r'^namespace ([\w:]+)\s*\{(.*?)^\}$', re.M | re.S) # a src/ namespace closes with a lone } at column 0 def curated_classes_load(): # src/ defines these itself: top-level classes, and A::B::Name for those in a namespace A::B block found = set() for root, _, names_ in os.walk(srcDir): for text in [open(os.path.join(root, n), errors='replace').read() for n in names_ if n.endswith('.h')]: for namespace, body in NAMESPACE_BLOCK.findall(text): found |= {f'{namespace}::{m}' for m in re.findall(r'^\s*(?:struct|class) (\w+)\b[^;]*$', body, re.M)} found |= set(re.findall(r'^(?:struct|class) (\w+)\b[^;]*$', NAMESPACE_BLOCK.sub('', text), re.M)) return found curatedClasses = curated_classes_load() def curated_load(): # addresses src/ took over: the one starting a comment, and every one in a (a, b, c to d) list on it found, addresses = set(), sorted(funcs) for root, _, files_ in os.walk(srcDir): for name in [f for f in files_ if f.endswith(('.cpp', '.h'))]: for comment in re.findall(r'//(.*)', open(os.path.join(root, name), errors='replace').read()): lists = re.findall(r'\(((?:[0-9a-f]{8}(?:\s*(?:,|to)\s*)?)+)\)', comment) lead = re.match(r'\s*([0-9a-f]{8})\b', comment) for item in lists + ([lead[1]] if lead else []): for low, high in re.findall(r'([0-9a-f]{8})(?:\s*to\s*([0-9a-f]{8}))?', item): high = high or low found |= {a for a in addresses if int(low, 16) <= a <= int(high, 16)} | {int(low, 16)} return found curated = curated_load() for c in sorted(names): class_emit(c) intrinsics = sorted({m.group(1) + m.group(2) for f in funcs.values() for m in INTRINSIC.finditer(f[6])}) def intrinsic_define(name): # CONCAT412: x=4, y=12; ZEXT1632: x=16, y=32 (a leading 12/16 is a two-digit size) kind = re.match(r'[A-Z]+', name).group(); digits = name[len(kind):] if kind in ('CARRY', 'SCARRY', 'SBORROW'): return f'#define {name}(a, b) GHIDRA_{kind}({digits}, a, b)\n' split = 2 if digits[:2] in ('12', '16') and len(digits) > 2 else 1 args = 'v, n' if kind == 'SUB' else 'a, b' if kind == 'CONCAT' else 'v' return f'#define {name}({args}) GHIDRA_{kind}({digits[:split]}, {digits[split:]}, {args})\n' # Everything that is not a method of a class above: free functions (FUN_ too) and namespace functions, as declared free, freeSeen = collections.defaultdict(list), set() for addr, (cls, method, ret, cc, params, thisParam, _) in sorted(funcs.items()): if addr in curated or cls in done or cls in curatedClasses or (cls or '').rpartition('::')[0] in curatedClasses or not IDENT.match(method) or (cls and not QUALIFIED.match(cls)) or (cls, method) in freeSeen or (not cls and method in STD_NAMES): continue freeSeen.add((cls, method)) if thisParam: params = [re.sub(r'\bthis$', 'self', thisParam)] + params free[cls].append(f'{ret} {method}({", ".join(params)}); // {addr:08x}') stubs.append((cls, f'{ret} {method}({", ".join(params)});', addr)) used.update(sig_types(ret, params)) # Ghidra enums and typedefs the code names (each enum constant once: they share one scope) aliases, constants = [], set() for t in sorted(wanted & set(enums)): if t in done or not IDENT.match(t) or t in STD_NAMES: continue size, values = enums[t] values = [(n, v) for n, v in values if IDENT.match(n) and n not in constants] constants.update(n for n, _ in values) underlying = ('int' if any(v < 0 for _, v in values) else 'uint') + str(8 * size) + '_t' aliases.append(f'enum {t} : {underlying} {{ ' + ', '.join(f'{n} = {v}' for n, v in values) + ' };') aliased = set() def typedef_emit(t, depth=0): # a typedef after the typedefs it names if t in aliased or t in done or t in enums or t in PRIMITIVE or t in PRELUDE_TYPES or t in STD_NAMES or not IDENT.match(t) or depth > 16: return aliased.add(t) target, count = component_parse(typedefs[t]) if '(' in target or t in type_names(target): target, count = 'void *', 1 # function pointers, self references: opaque for dep in type_names(target): if dep in typedefs: typedef_emit(dep, depth + 1) used.update(type_names(target)) aliases.append(f'typedef {target} {t}' + (f'[{count}]' if count > 1 else '') + ';') for t in sorted(wanted & set(typedefs)): typedef_emit(t) # Globals (dump/data.tsv), imported functions (dump/externals.tsv) and code addresses used as values (LAB_) taken = {f[1] for f in funcs.values()} | {c.rpartition('::')[2] for c in done} | constants | set(re.findall(r'(\w+)(?:\[\d*\])?;', PRELUDE)) | STD_NAMES globalDecls = [] for line in open(dumpDir + '/data.tsv', errors='replace') if os.path.exists(dumpDir + '/data.tsv') else []: if line.startswith('#'): continue _, name, typePath, length = line.rstrip('\n').split('\t') if not IDENT.match(name) or name in taken: continue taken.add(name) typ, count = component_parse(typePath.rpartition('/')[2] if not typePath.endswith('*') else typePath[typePath.rfind('/', 0, typePath.find(' ') if ' ' in typePath else None) + 1:]) if typ == 'undefined' and int(length) in (0, 4): typ = 'undefined4' if not re.fullmatch(r'[A-Za-z_][\w:]*( \*+)?', typ): typ, count = 'undefined', max(int(length), 1) # PNG-Image, void *32 ... if count > 1 and not width_of(typ): typ, count = 'undefined', int(length) # an array of a type with no layout: bytes used.update(type_names(typ)) globalDecls.append(f'extern {typ} {name}' + (f'[{count}]' if count > 1 else '') + ';') if typ.endswith('*') or typ in PRIMITIVE or typ in PRELUDE_TYPES: dataStubs.append(f'{typ} {name}' + (f'[{count}]' if count > 1 else '') + '{};') for line in open(dumpDir + '/externals.tsv', errors='replace') if os.path.exists(dumpDir + '/externals.tsv') else []: cols = line.rstrip('\n').split('\t') match = not line.startswith('#') and len(cols) == 3 and CALLING.match(cols[2]) if not match or not IDENT.match(match['name']) or match['name'] in taken or re.search(r'[<(]', match['ret'] + match['params']): continue taken.add(match['name']); used.update(sig_types(match['ret'], [p for p in match['params'].split(',') if p.strip()])) globalDecls.append(f'{match["ret"]} {match["name"]}({re.sub(r"\bthis\b", "self", match["params"])}); // {cols[0]}') stubs.append(('', f'{match["ret"]} {match["name"]}({re.sub(r"\bthis\b", "self", match["params"])});', None)) labels = sorted({m for f in funcs.values() for m in re.findall(r'\b(LAB_[0-9a-f]+|register0x[0-9a-f]+|_?DAT_[0-9a-f]+|PTR_\w+_[0-9a-f]{8})\b', f[6])} - taken) # auto labels data.tsv lacks globalDecls += [f'extern {"code" if n.startswith("LAB_") else "undefined4"} {n};' for n in labels] dataStubs += [f'undefined4 {n}{{}};' for n in labels if not n.startswith('LAB_')] forward = sorted(t for t in used | {c for c in done if '::' not in c} | curatedClasses if '::' not in t and t not in PRELUDE_TYPES and t not in enums and t not in typedefs and t not in STD_NAMES) declarations = ''.join(f'namespace {ns} {{\n' + '\n'.join(d) + '\n}\n' if ns else '\n'.join(d) + '\n' for ns, d in sorted(free.items())) os.makedirs(outDir, exist_ok=True) with open(outDir + '/classes.h', 'w') as o: o.write(generated_rename(PRELUDE + ''.join(intrinsic_define(n) for n in intrinsics) + '\n#if __SIZEOF_POINTER__ == 4\n#pragma pack(push, 1)\n#endif\n' + ''.join(f'struct {t};\n' for t in forward) + ''.join(f'namespace {c.rpartition("::")[0]} {{ struct {c.rpartition("::")[2]}; }}\n' for c in sorted(curatedClasses) if '::' in c) + '\n' + '\n'.join(aliases) + '\n\n' + '\n'.join(order) + '#if __SIZEOF_POINTER__ == 4\n#pragma pack(pop)\n#endif\n\n' + declarations + '\n' + '\n'.join(globalDecls) + '\n')) # One .cpp per class: each body under the declaration it was declared with; a renamed `this` gets an alias. members = {f'{f[0]}::{f[1]}' for f in funcs.values() if f[3] == '__thiscall' and f[0] in done} spans, files = collections.defaultdict(list), {} for cls in [c for c in done if not LIBRARY.match(c)]: parts, line = ['#include "classes.h"\n'], 2 for addr, (_, method, ret, cc, params) in methods.get(cls, []): if addr not in defined or addr in curated: continue decl = re.sub(r'^(virtual|static) |\s*override(?=;)|;$', '', defined[addr]) name = re.search(r'(~?\w+)\(', decl).group(1) thisParam = funcs[addr][5] alias = f' {thisParam} = this;\n' if thisParam and not re.search(r'\bthis$', thisParam) else '' varTypes = {m[2]: m[1] for m in re.finditer(r'^\s+((?:\w+::)*\w+)\s*\*\s*(\w+);', funcs[addr][6], re.M)} varTypes.update({p.rsplit('*', 1)[1].strip(): p.rsplit('*', 1)[0].strip() for p in params if '*' in p}) varTypes['this'] = cls body = pointer_casts_rewrite(int_casts_rewrite(calls_rewrite(virtuals_rewrite(offsets_rewrite(fields_rewrite(funcs[addr][6])), varTypes), members))) text = f'\n// {addr:08x}\n{decl.replace(name + "(", cls + "::" + name + "(", 1)}\n{{\n{alias}{body}\n}}\n' spans[cls].append((line + 1, line + text.count('\n'), addr)); line += text.count('\n'); parts.append(text) if len(parts) > 1: path = '/'.join(snake(p) for p in cls.split('::')) + '.cpp' files[cls] = path os.makedirs(os.path.dirname(f'{outDir}/{path}') or outDir, exist_ok=True) open(f'{outDir}/{path}', 'w').write(generated_rename(''.join(parts))) def stub_define(owner, decl, addr): # a declaration as a definition that stops the game where it is reached text = re.sub(r'\s*override(?=;)', '', re.sub(r'^\s*(virtual|static) ', '', decl.strip())).rstrip(';') name = re.search(r'(~?\w+)\(', text).group(1) for part in re.findall(r'[^,()]+', text[:text.index('(')].rsplit(None, 1)[0] if ' ' in text[:text.index('(')] else '') + re.findall(r'[^,()]+', text[text.index('(') + 1:]): base = part.strip().rsplit(None, 1)[0] if ' ' in part.strip() and '*' not in part else part.strip() if '*' not in part and base in incomplete: return '' # a by-value type with no layout cannot be defined yet label = (f'{owner}::' if owner else '') + name + (f' {addr:08x}' if addr else '') return text.replace(name + '(', (f'{owner}::' if owner else '') + name + '(', 1) + f' {{ generated_stub("{label}"); }}\n' incomplete = {t for t in forward if t not in done} | {c for c in curatedClasses if '::' in c} srcTexts = [open(os.path.join(root, n), errors='replace').read() for root, _, names_ in os.walk(srcDir) for n in names_ if n.endswith('.cpp')] def src_defines(owner, method): # src/ defines owner::method: qualified, or by its short name at top level or inside its namespace block space, _, short = owner.rpartition('::') pattern = re.compile(rf'(?\([^;]*?\) \+ (?:0x[0-9a-f]+|\d+)\)', open(f'{outDir}/{f}').read())) for f in files.values()) calls = collections.defaultdict(set) # the boot path: what Manager::Init reaches, the first milestone to curate for line in open(dumpDir + '/calls.tsv'): caller, callee = line.split() if ':' not in callee: calls[int(caller, 16)].add(int(callee, 16)) # EXTERNAL:... are imports boot, queue = set(), [a for a, f in funcs.items() if f[0] == 'Manager' and f[1] == 'Init'] while queue: a = queue.pop() if a not in boot and a in funcs and not LIBRARY.match(funcs[a][0]): boot.add(a); queue += calls[a] print(f'source_tree --check: boot path {len(boot & curated)}/{len(boot)} functions curated') print(f'source_tree --check: {clean}/{total} method bodies compile for x86_64 ({100 * clean / max(total, 1):.1f}%),' f' {hazards} raw offset accesses, 32-bit layout asserts {"hold" if layout.returncode == 0 else "FAIL"}') for message, n in errors.most_common(15): print(f' {n:6d} {message}')