Reconstruction layout: generated-src/ (generated) and src/ (curated), CMake, the first takeover: RNG
The decompiled C++ tree moves to generated-src/ (classes.h, C++20); src/ is for code written by hand. A curated function defines the generated declaration and starts its comment with its address, and source_tree.py stops emitting that body. src/rng.cpp takes over RNG (SetSeed, the constructor, Next, RandomInt, RandomFloat, Shuffle) with the shift table read from the exe as a constexpr array; src/log.h names KAGE_LogMessage's levels (1 INFO, 2 NET, 4 WARN, 8 ERROR, 16 ASSERT, from its prefix jump table). CMakeLists.txt builds src/*.cpp against generated-src/classes.h (clean with -Wall -Wextra). structs.hpp and headers.py are retired: scripts/merge_fields.py writes the merged field list, classes.h checks the layout. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2ff2d5d87f
commit
3ce74c6e2d
331 files changed
+485
-7835
No files matched your search
@@ -1,82 +0,0 @@
|
||||
# Generates src/structs.hpp: one C++ struct per class from the confirmed fields (zhl_fields.tsv, lua_fields.tsv,
|
||||
# db/fields.tsv; later files win at the same offset), base-class fields flattened in, gaps as explicit padding, and a
|
||||
# static_assert on every member offset. Only offsets this exe confirms are in these files, so the header is as trustworthy
|
||||
# as the evidence behind them. Pointers are uint32_t (the game is 32-bit), so it compiles on any host.
|
||||
# A "Class<TAB>size<TAB>0x2f00" row (classes.tsv, from the RTTI deleting destructor) pads the struct to its real size.
|
||||
# A db row with type "-" ("Entity<TAB>0x2d4<TAB>- _mass<TAB>why") deletes a wrong field from the earlier files.
|
||||
# Usage: headers.py [--merged fields_out.tsv] out.hpp zhl_fields.tsv lua_fields.tsv db/fields.tsv
|
||||
# --merged also writes the merged field list (what ApplyTypes.java gets)
|
||||
import collections, re, sys
|
||||
args = sys.argv[1:]
|
||||
merged = args.pop(args.index('--merged') + 1) if '--merged' in args else None
|
||||
if merged: args.remove('--merged')
|
||||
out, *srcs = args
|
||||
SIZE = {'bool': 1, 'char': 1, 'int8_t': 1, 'uint8_t': 1, 'unsigned char': 1, 'short': 2, 'int16_t': 2, 'uint16_t': 2,
|
||||
'unsigned short': 2, 'int': 4, 'int32_t': 4, 'uint32_t': 4, 'unsigned int': 4, 'unsigned long': 4, 'long': 4,
|
||||
'float': 4, 'uint64_t': 8, 'int64_t': 8, 'unsigned long long': 8, 'long long': 8, 'double': 8, 'Vector': 8}
|
||||
CTYPE = {'unsigned int': 'uint32_t', 'unsigned long': 'uint32_t', 'long': 'int32_t', 'unsigned short': 'uint16_t',
|
||||
'unsigned char': 'uint8_t', 'unsigned long long': 'uint64_t', 'long long': 'int64_t', 'char': 'int8_t'}
|
||||
fields, bases, sizes, rows = collections.defaultdict(dict), {}, {}, {}
|
||||
for p in srcs:
|
||||
for l in open(p):
|
||||
if l.startswith('#') or not l.strip(): continue
|
||||
c = l.rstrip('\n').split('\t')
|
||||
if c[1] == 'base': bases[c[0]] = c[2]; continue
|
||||
if c[1] == 'size': sizes[c[0]] = int(c[2], 0); continue
|
||||
if c[2].startswith('- '):
|
||||
fields[c[0]].pop(int(c[1], 16), None); rows.pop((c[0], int(c[1], 16)), None); continue
|
||||
rows[(c[0], int(c[1], 16))] = l if l.endswith('\n') else l + '\n'
|
||||
decl = c[2].replace('const ', '').strip()
|
||||
count = re.search(r'\[(\w+)\]\s*$', decl) # "int _trinketsID[2]"
|
||||
if count: decl = decl[:count.start()]
|
||||
typ, name = decl.rsplit(None, 1) if ' ' in decl else (decl, '_unnamed')
|
||||
fields[c[0]][int(c[1], 16)] = (typ.strip(), re.sub(r'\W', '', name), c[3] if len(c) > 3 else '', int(count.group(1), 0) if count else 1)
|
||||
def flat(cls, depth=0):
|
||||
f = dict(flat(bases[cls], depth + 1)) if cls in bases and depth < 8 else {}
|
||||
f.update(fields.get(cls, {}))
|
||||
return f
|
||||
done, order = {}, []
|
||||
STL = [(r'std_string', 0x18), (r'(std_)?vector_bool', 0x10), (r'(std_)?vector_', 0xc), (r'(std_)?deque_', 0x14), (r'std_(map|set|multiset|multimap|list)_', 8)]
|
||||
def size_of(t):
|
||||
if t.endswith('*'): return 4
|
||||
return SIZE.get(t) or done.get(t) or next((n for p, n in STL if re.match(p, t)), None)
|
||||
def emit(cls, stack=()):
|
||||
if cls in done or cls in stack: return
|
||||
f = flat(cls)
|
||||
for t, *_ in f.values():
|
||||
if t in fields and not t.endswith('*'): emit(t, stack + (cls,))
|
||||
lines, asserts, pos = [], [], 0
|
||||
for off in sorted(f):
|
||||
t, name, note, count = f[off]
|
||||
if off < pos: continue # overlaps the previous member (e.g. a union view): keep the first
|
||||
if off > pos: lines.append(f' uint8_t _pad_0x{pos:x}[0x{off - pos:x}];')
|
||||
sz = size_of(t) and size_of(t) * count
|
||||
dim = f'[{count}]' if count > 1 else ''
|
||||
nxt = min([o for o in f if o > off], default=None)
|
||||
if sz and (nxt is None or off + sz <= nxt) and (t in done or t in SIZE or t.endswith('*')): # STL types stay bytes
|
||||
ct = 'uint32_t' if t.endswith('*') else CTYPE.get(t, t)
|
||||
cmt = f' // {t}' if t.endswith('*') else ''
|
||||
lines.append(f' {ct} {name}{dim};{cmt}' + (f' // {note}' if note else ''))
|
||||
asserts.append(f'static_assert(offsetof({cls}, {name}) == 0x{off:x});')
|
||||
pos = off + sz
|
||||
else: # an STL container (its MSVC size) or unknown size: a byte span up to the next member
|
||||
n = min(sz or 1 << 30, nxt - off if nxt else sz or 4)
|
||||
lines.append(f' uint8_t {name}[0x{n:x}]; // {t}' + (f'; {note}' if note else ''))
|
||||
asserts.append(f'static_assert(offsetof({cls}, {name}) == 0x{off:x});')
|
||||
pos = off + n
|
||||
if not lines: return
|
||||
if pos < sizes.get(cls, 0): lines.append(f' uint8_t _pad_0x{pos:x}[0x{sizes[cls] - pos:x}];'); pos = sizes[cls]
|
||||
if cls in sizes: asserts.append(f'static_assert(sizeof({cls}) == 0x{sizes[cls]:x});' if pos == sizes[cls] else f'// {cls}: fields end at 0x{pos:x}, past its real size 0x{sizes[cls]:x}')
|
||||
if pos % 4: lines.append(f' uint8_t _pad_0x{pos:x}[0x{4 - pos % 4:x}];'); pos += 4 - pos % 4 # MSVC alignment padding: arrays get the real stride
|
||||
done[cls] = pos
|
||||
order.append(f'struct {cls} {{' + (f' // : {bases[cls]} (flattened)' if cls in bases else '') + '\n' + '\n'.join(lines) + '\n};\n' + '\n'.join(asserts) + '\n')
|
||||
for c in sorted(set(fields) | set(bases)): emit(c)
|
||||
dupes = [c for c in done if len({v[1] for v in flat(c).values()}) != len(flat(c))] # same name at two offsets
|
||||
with open(out, 'w') as o:
|
||||
o.write('// Generated by scripts/headers.py from the confirmed struct fields of isaac-ng.exe v1.9.7.17. Do not edit:\n'
|
||||
'// add or fix fields in db/fields.tsv and regenerate. Offsets not confirmed in this exe are padding.\n'
|
||||
'#pragma once\n#include <cstddef>\n#include <cstdint>\n\n#pragma pack(push, 1)\n'
|
||||
'struct Vector { float x, y; };\n\n' + '\n'.join(o_ for o_ in order if not o_.startswith('struct Vector ')) + '#pragma pack(pop)\n')
|
||||
if merged:
|
||||
with open(merged, 'w') as o: o.writelines([f'{c}\tbase\t{b}\n' for c, b in bases.items()] + [f'{c}\tsize\t{n:#x}\n' for c, n in sizes.items()] + list(rows.values()))
|
||||
print(f'headers: {len(done)} structs' + (f'; duplicate member names in {dupes}' if dupes else ''))
|
||||
@@ -0,0 +1,23 @@
|
||||
# Merges the confirmed struct fields into the one list ApplyTypes.java and source_tree.py read.
|
||||
# Inputs in order (later rows win at the same class and offset): zhl_fields.tsv, lua_fields.tsv, db/fields.tsv, class sizes.
|
||||
# Rows: "Class<TAB>0x2d4<TAB>type _name<TAB>why", "Class<TAB>base<TAB>Base", "Class<TAB>size<TAB>0x2f00".
|
||||
# A row whose type is "- " ("Entity<TAB>0x2d4<TAB>- _mass<TAB>why") deletes a wrong field from the earlier files.
|
||||
# Usage: merge_fields.py out.tsv in.tsv...
|
||||
import sys
|
||||
|
||||
out, *sources = sys.argv[1:]
|
||||
bases = {}
|
||||
sizes = {}
|
||||
rows = {}
|
||||
for path in sources:
|
||||
for line in open(path):
|
||||
if line.startswith('#') or not line.strip(): continue
|
||||
cols = line.rstrip('\n').split('\t')
|
||||
if cols[1] == 'base': bases[cols[0]] = cols[2]; continue
|
||||
if cols[1] == 'size': sizes[cols[0]] = int(cols[2], 0); continue
|
||||
key = (cols[0], int(cols[1], 16))
|
||||
if cols[2].startswith('- '): rows.pop(key, None); continue
|
||||
rows[key] = line if line.endswith('\n') else line + '\n'
|
||||
with open(out, 'w') as o:
|
||||
o.writelines([f'{c}\tbase\t{b}\n' for c, b in bases.items()] + [f'{c}\tsize\t{n:#x}\n' for c, n in sizes.items()] + list(rows.values()))
|
||||
print(f'merge_fields: {len(rows)} fields, {len(bases)} bases, {len(sizes)} sizes')
|
||||
+12
-8
@@ -1,9 +1,10 @@
|
||||
# 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).
|
||||
# <out>/classes.hpp one class per type: real bases, the vptr implied, own fields at their exact offsets, padding up to
|
||||
# <out>/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
|
||||
# <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.
|
||||
# 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).
|
||||
@@ -17,7 +18,7 @@ POINTER_LIKE = {'EntityPtr'} # REPENTOGON's smart pointer, a raw Entity * in t
|
||||
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++17', '-fsyntax-only', '-ferror-limit=0', '-nostdinc++',
|
||||
CLANG = ['clang++', '--target=x86_64-linux-gnu', '-std=c++20', '-fsyntax-only', '-ferror-limit=0', '-nostdinc++',
|
||||
'-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,
|
||||
@@ -455,7 +456,7 @@ globalDecls += [f'extern {"code" if n.startswith("LAB_") else "undefined4"} {n};
|
||||
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)
|
||||
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:
|
||||
with open(outDir + '/classes.h', 'w') as o:
|
||||
o.write(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) + '\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')
|
||||
@@ -463,10 +464,13 @@ with open(outDir + '/classes.hpp', 'w') as o:
|
||||
# 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), {}
|
||||
srcDir = os.path.join(os.path.dirname(os.path.abspath(outDir)), 'src')
|
||||
curated = {int(a, 16) for root, _, names_ in os.walk(srcDir) for n in names_ if n.endswith(('.cpp', '.h'))
|
||||
for a in re.findall(r'//\s*([0-9a-f]{8})\b', open(os.path.join(root, n), errors='replace').read())}
|
||||
for cls in [c for c in done if not LIBRARY.match(c)]:
|
||||
parts, line = ['#include "classes.hpp"\n'], 2
|
||||
parts, line = ['#include "classes.h"\n'], 2
|
||||
for addr, (_, method, ret, cc, params) in methods.get(cls, []):
|
||||
if addr not in defined: continue
|
||||
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]
|
||||
@@ -482,10 +486,10 @@ 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(''.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,'
|
||||
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')
|
||||
|
||||
if isCheck: # per method: does its body compile against classes.hpp?
|
||||
if isCheck: # per method: does its body compile against classes.h?
|
||||
def file_check(cls):
|
||||
result = subprocess.run(CLANG + ['-I', outDir, f'{outDir}/{files[cls]}'], capture_output=True, text=True)
|
||||
bad = collections.Counter()
|
||||
@@ -498,7 +502,7 @@ if isCheck: # per method: does its body compile against classes.hpp?
|
||||
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))
|
||||
layout = subprocess.run(CLANG[:1] + ['--target=i686-linux-gnu'] + CLANG[2:] + ['-x', 'c++', f'{outDir}/classes.hpp'], capture_output=True, text=True)
|
||||
layout = subprocess.run(CLANG[:1] + ['--target=i686-linux-gnu'] + CLANG[2:] + ['-x', 'c++', f'{outDir}/classes.h'], capture_output=True, text=True)
|
||||
hazards = sum(len(re.findall(r'GHIDRA_CAST<char \*>\([^;]*?\) \+ (?:0x[0-9a-f]+|\d+)\)', open(f'{outDir}/{f}').read())) for f in files.values())
|
||||
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"}')
|
||||
|
||||
Reference in new issue
Block a user