# 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.hpp 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) # Laid out for the game's ABI (i686 MSVC). --check compiles every .cpp and reports how many methods compile. # Usage: source_tree.py out_dir classes.tsv dump_dir zhl_vtables.tsv [--check] import collections, concurrent.futures, os, re, subprocess, sys outDir, classesPath, dumpDir, zhlVtablesPath = sys.argv[1:5] isCheck = '--check' in sys.argv CALLING = re.compile(r'^(?P.+?)\s*\b(?:(?P__thiscall|__fastcall|__cdecl|__stdcall)\s+)?(?P[\w:~]+)\((?P.*)\)\s*$') IDENT = re.compile(r'^~?[A-Za-z_]\w*$') INTRINSIC = re.compile(r'\b(CONCAT|SUB|ZEXT|SEXT|CARRY|SCARRY|SBORROW)(\d+)\(') CLANG = ['clang++', '--target=i686-pc-windows-msvc', '-std=c++17', '-fsyntax-only', '-ferror-limit=0', '-fms-extensions', '-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 typedef unsigned char uint8_t; typedef signed char int8_t; typedef unsigned short uint16_t; typedef short int16_t; typedef unsigned int uint32_t; typedef int int32_t; typedef unsigned long long uint64_t; typedef long long int64_t; #define offsetof(type, member) __builtin_offsetof(type, member) typedef uint8_t undefined, undefined1, byte; typedef uint16_t undefined2, word, ushort; typedef uint32_t undefined4, dword, uint, ulong; typedef uint64_t undefined8, ulonglong; typedef int64_t longlong; typedef unsigned char uchar; typedef long double float10; 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() {} 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 ''' PRELUDE_TYPES = set(re.findall(r'(\w+)(?=[,;])', ' '.join(re.findall(r'typedef [^;]*;', PRELUDE)))) | {'code'} # typedef names 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 fields_load(): fields, bases, sizes = collections.defaultdict(dict), {}, {} for line in open(dumpDir + '/zhl_fields.tsv'): 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 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)] = (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 = {} for chunk in open(dumpDir + '/all.c', errors='replace').read().split('\n//@@ ')[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}')]) return funcs 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): # EXPR->field_0x1c / EXPR.field_0x1c (a byte Ghidra had no field for) -> the byte at that offset out, pos = [], 0 for match in re.finditer(r'(->|\.)field_0x([0-9a-f]+)\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})' out.append(text[pos:start] + f'(*(undefined1 *)({address} + 0x{match[2]}))'); pos = match.end() return ''.join(out) + text[pos:] 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() 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])) done, order, used, canon, defined = {}, [], set(), {}, {} # 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 parent = base.get(cls) if base.get(cls) in names else None 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 PRIMITIVE.get(typ) or (done[typ][0] if typ in done else None) 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'static_assert(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'static_assert(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 '')) 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}') 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)) 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 cls in done or not IDENT.match(method) or (cls and not QUALIFIED.match(cls)) or (cls, method) in freeSeen: continue freeSeen.add((cls, method)) if thisParam: params = [re.sub(r'\bthis$', 'self', thisParam)] + params free[cls].append(f'{ret} {cc + " " if cc else ""}{method}({", ".join(params)}); // {addr:08x}') used.update(sig_types(ret, params)) forward = sorted(t for t in used | {c for c in done if '::' not in c} if '::' not in t and t not in PRELUDE_TYPES) 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.hpp', 'w') as o: o.write(PRELUDE + ''.join(intrinsic_define(n) for n in intrinsics) + '\n#pragma pack(push, 1)\n' + ''.join(f'struct {t};\n' for t in forward) + '\n' + '\n'.join(order) + '#pragma pack(pop)\n\n' + declarations) # 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 done: parts, line = ['#include "classes.hpp"\n'], 2 for addr, (_, method, ret, cc, params) in methods.get(cls, []): if addr not in defined: 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 '' body = calls_rewrite(fields_rewrite(funcs[addr][6]), 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(''.join(parts)) print(f'source_tree: {len(done)} classes, {sum(1 for c in done if size.get(c))} sized, {sum(len(v) for v in methods.values())} methods,' f' {sum(len(s) for s in spans.values())} bodies in {len(files)} .cpp files') if isCheck: # per method: does its body compile against classes.hpp? def file_check(cls): result = subprocess.run(CLANG + ['-I', outDir, f'{outDir}/{files[cls]}'], capture_output=True, text=True) bad = collections.Counter() for match in re.finditer(r'^[^:\n]+\.cpp:(\d+):\d+: error: (.*)$', result.stderr, re.M): fn = next((a for lo, hi, a in spans[cls] if lo <= int(match[1]) <= hi), None) bad[fn] += 1 errors[re.sub(r"'[^']*'", "X", match[2])] += 1 return cls, bad errors = collections.Counter() with concurrent.futures.ThreadPoolExecutor(os.cpu_count()) as pool: results = list(pool.map(file_check, files)) total = sum(len(spans[c]) for c in files) clean = sum(1 for c, bad in results for lo, hi, a in spans[c] if not bad.get(a)) print(f'source_tree --check: {clean}/{total} method bodies compile ({100 * clean / max(total, 1):.1f}%)') for message, n in errors.most_common(15): print(f' {n:6d} {message}')