Struct fields only where this exe confirms them; 600 verified fields; generated src/structs.hpp

REPENTOGON targets 1.9.7.12 and its offsets drift, so they are no longer trusted by themselves:
scripts/zhl_fields.py (replaces fix_offsets.py) keeps a REPENTOGON field only when a getter or the
game's Lua field table confirms it, or it sits between two confirmed fields with the same shift.
8 agents verified the rest against code (Game/Manager/Entity_Player shift in steps; Room, ANM2,
EntityConfig unshifted). src/structs.hpp is generated from the confirmed fields with static_asserts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shweetandClaude Opus 5.5 committed 2026-10-24 21:37:10 -04:00
1 parent d2b8a9229a
commit 5d1b595294
11 files changed
+5713 -1608

No files matched your search

+5 -2
View File
@@ -35,10 +35,13 @@ public class ApplyTypes extends GhidraScript {
if (depth > 8) return;
if (base.containsKey(cls)) addFields(s, base.get(cls), depth + 1);
for (String[] f : fields.getOrDefault(cls, List.of())) {
DataType dt = prim(f[2]);
java.util.regex.Matcher arr = java.util.regex.Pattern.compile("\\[(\\w+)\\]\\s*$").matcher(f[2]); // "int _trinketsID[2]"
String decl = arr.find() ? f[2].substring(0, arr.start()) : f[2];
DataType dt = prim(decl);
if (dt == null) continue;
if (arr.find(0)) dt = new ArrayDataType(dt, Integer.decode(arr.group(1)), dt.getLength());
int off = Integer.decode(f[1]);
String nm = f[2].replaceAll(".*\\s", "").replaceAll("[^\\w]", "");
String nm = decl.trim().replaceAll(".*\\s", "").replaceAll("[^\\w]", "");
try {
if (off + dt.getLength() > s.getLength()) s.growStructure(off + dt.getLength() - s.getLength());
s.replaceAtOffset(off, dt, dt.getLength(), nm, null);
+66
View File
@@ -0,0 +1,66 @@
# 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.
# Usage: headers.py out.hpp zhl_fields.tsv lua_fields.tsv db/fields.tsv
import collections, re, sys
out, *srcs = sys.argv[1:]
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 = 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
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 = {}, []
def size_of(t):
if t.endswith('*'): return 4
return SIZE.get(t) or done.get(t)
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):
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: # unknown size: a byte span up to the next member
n = (nxt - off) if nxt else 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
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')
print(f'headers: {len(done)} structs' + (f'; duplicate member names in {dupes}' if dupes else ''))
+57
View File
@@ -0,0 +1,57 @@
# REPENTOGON's struct offsets target an older exe (1.9.7.12); fields drift as the game adds members, so they are only
# kept where THIS exe confirms them. Evidence ("anchors"): a trivial getter in the corpus ("Class::GetFoo" returning
# this+N anchors field "_foo" at N) or the game's Lua field table (lua_bindings.tsv: "EntityNPC State field+0xb64").
# A field is kept when it is anchored, or lies between two anchors of its class with the same shift; everything else
# is dropped (the decompiler then shows field_0xNNN) until db/fields.tsv confirms it. Base-class rows are always kept.
# Usage: zhl_fields.py all.c zhl_dir lua_bindings.tsv out.tsv [names.tsv: addr \t Class::Member, overrides corpus names]
# Prints per class: kept/total and the shifts seen.
import collections, glob, os, re, sys
src, zdir, lua, fout = sys.argv[1:5]
rename = dict(l.split('\t')[:2] for l in open(sys.argv[5])) if len(sys.argv) > 5 else {}
norm = lambda s: re.sub(r'^(get|is|has)', '', s.lower().lstrip('_'))
cls_of = lambda c: {'Item': 'ItemConfig_Item', 'Card': 'ItemConfig_Card', 'PillEffect': 'ItemConfig_Pill', 'Costume': 'ItemConfig_Costume',
'GridEntityDoor': 'GridEntity_Door'}.get(c, re.sub(r'^Entity(?=[A-Z])', 'Entity_', c))
# raw fields: "int _a : 0x0, _b : 0x4;" is two fields
raw, bases = collections.defaultdict(list), []
for f in sorted(glob.glob(os.path.join(zdir, '*.zhl'))):
struct_ = None
for l in open(f, errors='replace'):
m = re.match(r'^\s*struct\s+(\w+)', l)
if m:
struct_ = m.group(1)
b = re.search(r':\s*public\s+(\w+)', l)
if b: bases.append((struct_, b.group(1)))
if not (struct_ and re.match(r'^\s*([\w:<>,\s\*&]+?)\s*:\s*(0x[0-9a-fA-F]+)\s*;', l)): continue
parts = re.findall(r'([^,:]+?)\s*:\s*(0x[0-9a-fA-F]+)', l.split(';')[0])
ftype = parts[0][0].split()[:-1]
for decl, off in parts:
words = decl.split()
raw[struct_].append((int(off, 16), ' '.join(words if len(words) > 1 else ftype + words)))
anchor = {} # (class, normalised member) -> offset in this exe
name, n = None, 0
for line in open(src, errors='replace'):
if line.startswith('//@@ '): name, n = rename.get(line.split()[1], line.split()[2]), 0; continue
n += 1
m = n < 14 and '::' in name and re.search(r'return (?:\*\([\w ]+\*\)\((?:in_ECX|this|param_1) \+ (0x[0-9a-f]+)\)|(?:in_ECX|this|param_1) \+ (0x[0-9a-f]+));', line)
if m:
cls, meth = name.rsplit('::', 1)
anchor.setdefault((cls_of(cls), norm(meth)), int(m.group(1) or m.group(2), 16))
for l in open(lua):
c = l.rstrip('\n').split('\t')
m = len(c) > 2 and re.match(r'field\+(0x[0-9a-f]+)$', c[2])
if m: anchor[(cls_of(c[0]), norm(c[1]))] = int(m.group(1), 16) # the game's own table wins over a getter guess
with open(fout, 'w') as o:
for c, b in bases: o.write(f'{c}\tbase\t{b}\n')
for c, fields in sorted(raw.items()):
shifts = sorted((off, anchor[(c, norm(d.split()[-1]))] - off) for off, d in fields if (c, norm(d.split()[-1])) in anchor)
kept = 0
for off, d in fields:
lo = [s for a, s in shifts if a <= off]; hi = [s for a, s in shifts if a >= off]
if (c, norm(d.split()[-1])) in anchor: new = anchor[(c, norm(d.split()[-1]))]
elif lo and hi and lo[-1] == hi[0]: new = off + lo[-1]
else: continue
o.write(f'{c}\t0x{new:x}\t{d}\n'); kept += 1
if shifts: print(f'{c}: kept {kept}/{len(fields)}, shifts ' + ' '.join(f'{a:x}{s:+#x}' for a, s in shifts if s))
+1 -18
View File
@@ -87,21 +87,4 @@ with open(os.path.join(os.path.dirname(out), 'zhl_vtables.tsv'), 'w') as o:
name = nm.group(1) if nm else None
if name and name != 'skip': o.write('%s\t%d\t%s\n' % (cls, slot, name))
slot += 1
# struct fields from zhl: struct \t offset \t type name
with open(os.path.join(os.path.dirname(out), 'zhl_fields.tsv'), 'w') as o:
for f in sorted(glob.glob(os.path.join(zdir, '*.zhl'))):
struct_ = None
for l in open(f, errors='replace'):
m = structP.match(l)
if m:
struct_ = m.group(1)
b = re.search(r':\s*public\s+(\w+)', l)
if b: o.write('%s\tbase\t%s\n' % (struct_, b.group(1)))
m = re.match(r'^\s*([\w:<>,\s\*&]+?)\s*:\s*(0x[0-9a-fA-F]+)\s*;', l)
if not (m and struct_): continue
parts = re.findall(r'([^,:]+?)\s*:\s*(0x[0-9a-fA-F]+)', l.split(';')[0]) # "int _a : 0x0, _b : 0x4;" is two fields
ftype = parts[0][0].split()[:-1]
for decl, off in parts:
words = decl.split()
o.write('%s\t%s\t%s\n' % (struct_, off.lower(), ' '.join((words if len(words) > 1 else ftype + words))))
# struct fields: scripts/zhl_fields.py (keeps only the ones this exe confirms)