Generated stubs: the build links into a Linux executable that runs as far as src/ goes

source_tree.py writes generated-src/stubs.cpp: every function, vtable slot and import src/ has not taken over, defined
as a stub that prints 'Reached <name> <address>, not reconstructed yet' and stops. CMake builds src/*.cpp + stubs into
the isaac executable, so each run names the next function to curate. src/main.cpp hands over to the game's IsaacMain.
Classes with only parameterised constructors get a defaulted one, so stub constructors of their holders compile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shweetandClaude Opus 5.5 committed 2026-11-19 21:44:40 -05:00
1 parent 9d4d4f5c64
commit 2b108ca729
5 files changed
+25103 -2

No files matched your search

+27 -1
View File
@@ -5,6 +5,8 @@
# <out>/<class>.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.
# <out>/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).
@@ -357,7 +359,8 @@ def width_of(typ, depth=0): # bytes of a field type: primitives, laid-out clas
return None
done, order, used, canon, defined = {}, [], set(), {}, {} # defined: address -> the declaration its body is defined with
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
parent = base.get(cls) if base.get(cls) in names else None
@@ -412,6 +415,7 @@ def class_emit(cls, stack=()):
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))
slotAddrs = set(slots)
for addr, (_, method, ret, cc, params) in methods.get(cls, []):
key = (method, ', '.join(params))
@@ -420,7 +424,10 @@ def class_emit(cls, stack=()):
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 '')
@@ -443,6 +450,7 @@ for addr, (cls, method, ret, cc, params, thisParam, _) in sorted(funcs.items()):
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()
@@ -479,12 +487,14 @@ for line in open(dumpDir + '/data.tsv', errors='replace') if os.path.exists(dump
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]
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 and t not in enums and t not in typedefs and t not in STD_NAMES)
@@ -520,6 +530,22 @@ for cls in [c for c in done if not LIBRARY.match(c)]:
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}
stubText = ''.join(stub_define(o, d, a) for o, d, a in stubs if a not in curated)
with open(outDir + '/stubs.cpp', 'w') as o:
o.write(generated_rename('// Generated by scripts/source_tree.py: every function src/ has not taken over yet, as a stub that stops the game\n'
'// where it is reached, so a build runs exactly as far as the curated code goes.\n#include "classes.h"\n\n'
'[[noreturn]] static void generated_stub(const char* name)\n{\n fprintf(stderr, "Reached %s, not reconstructed yet\\n", name);\n exit(1);\n}\n\n'
+ '\n'.join(dataStubs) + '\n\n' + stubText))
print(f'source_tree: {len(curated)} functions taken over by src/, {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')