Files
isaac-port/scripts/source_tree.py
T
shweetandClaude Opus 5.5 c426b91486 Full redump with round 26 (689 locals in 127 functions); src/game/classes.hpp: reconstructed class declarations
classes.tsv (vtable.py --classes): 194 RTTI classes with vftable, direct bases (offsets from the PMD), vtable slots and,
for 176, the exact size from the deleting destructor's sized delete. Sizes flow into structs.hpp (static_assert sizeof)
and, next build, into Ghidra's structs (ApplyTypes 'size' rows) so this[1]._x stops standing in for the tail.
scripts/source_tree.py generates src/game/classes.hpp: 293 classes with real bases, vtables in slot order (overrides,
REPENTOGON slot names, vfunc_N placeholders), fields at their offsets, 2400 method declarations; it compiles with
clang --target=i686-pc-windows-msvc and all 174 sizeof / 1899 offsetof asserts hold. Round 26's prototypes are held.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 19:43:13 -05:00

168 lines
11 KiB
Python

# Generates the reconstructed C++ class declarations 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 named function's
# decompiled signature (dump/all.c). 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. Laid out for the
# game's ABI (i686 MSVC): check with clang++ --target=i686-pc-windows-msvc -fsyntax-only.
# Usage: source_tree.py out.hpp classes.tsv dump_dir zhl_vtables.tsv
import collections, re, sys
out, classesPath, dumpDir, zhlVtablesPath = sys.argv[1:5]
CALLING = re.compile(r'^(?P<ret>.+?)\s*\b(?P<cc>__thiscall|__fastcall|__cdecl|__stdcall)\s+(?P<name>[\w:~]+)\((?P<params>.*)\)\s*$')
IDENT = re.compile(r'^~?[A-Za-z_]\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,
'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 void code;
struct Vector { float x, y; };
'''
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 signatures_load(): # address -> (Class, method, return type, calling convention, params without this)
sigs, addr, head = {}, None, []
for line in open(dumpDir + '/all.c', errors='replace'):
if line.startswith('//@@ '): addr, head = int(line.split()[1], 16), []; continue
if addr is None: continue
if line.rstrip() != '{': head.append(line); continue
block = ''.join(head).strip().split('\n\n')[-1] # the last paragraph before '{' (comments can hold or lose '*/')
text = ' '.join(block.split()) # Ghidra wraps long signatures
match, funcAddr, addr = CALLING.match(text), addr, None
if not match or '::' not in match['name']: continue
cls, method = match['name'].rsplit('::', 1)
params = [p.strip() for p in match['params'].split(',') if p.strip() and p.strip() != 'void']
if match['cc'] == '__thiscall' and params: params = params[1:]
sigs[funcAddr] = (cls, method, match['ret'].strip(), match['cc'], params)
return sigs
def type_names(text):
return {t for t in re.findall(r'[A-Za-z_]\w*', text) if t not in PRIMITIVE and t not in ('const', 'unsigned', 'void', 'struct', 'virtual', 'override')}
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):
if not IDENT.match(method) or method.startswith('FUN_'): return None
shortName = cls.split('::')[-1]
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});'
classes, (fields, fieldBases, sizes), sigs = classes_load(), fields_load(), signatures_load()
zhlSlots = {(c, int(i)): n for c, i, n in (l.rstrip('\n').split('\t') for l in open(zhlVtablesPath))}
names = set(classes) | set(fields) | set(fieldBases)
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}
methods = collections.defaultdict(list)
for addr, sig in sorted(sigs.items()):
if sig[0] in names: methods[sig[0]].append((addr, sig))
done, order, used, canon = {}, [], set(), {}
def class_emit(cls, stack=()):
if cls in done or cls in stack: 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,))
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 and not done[typ][1] 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 = sigs.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]))
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))
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 - {'Vector'}): class_emit(c)
forward = sorted(t for t in used | {c for c in done if '::' not in c} if '::' not in t and t != 'Vector')
with open(out, 'w') as o:
o.write(PRELUDE + '\n#pragma pack(push, 1)\n' + ''.join(f'struct {t};\n' for t in forward) + '\n' + '\n'.join(order) + '#pragma pack(pop)\n')
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')