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>
126 lines
10 KiB
Python
126 lines
10 KiB
Python
# Agent rounds that name local variables (db/locals.tsv) and write prototypes (db/protos.zhl). Run from the repo root.
|
|
# locals_round.py pick <round> <min_left> <max_lines> [<earlier_round> ... <prev_round>]
|
|
# <round>/all_snapshot.c must be a copy of dump/all.c. Writes <round>/l_<agent>.tsv: named game functions with at least
|
|
# <min_left> default-named locals, biggest backlog first, at most <max_lines> lines per agent. Functions whose
|
|
# prototypes <prev_round> wrote (and their callers) are skipped: they renumber once those prototypes are applied.
|
|
# So are the earlier rounds' own targets.
|
|
# locals_round.py brief <round> writes <round>/wf.js, the 8-agent Workflow script (run it with Workflow scriptPath)
|
|
# locals_round.py locals <round> agents' l_out_*.tsv -> db/locals.tsv, checked against the snapshot (apply in the next build)
|
|
# locals_round.py protos <round> agents' lp_out_*.zhl -> db/protos.zhl (only AFTER the build that applied <round>'s locals)
|
|
# Agents write l_out_<agent>.tsv (address, decompiler name, new name[, C type]) and lp_out_<agent>.zhl (REPENTOGON syntax).
|
|
import collections, glob, re, sys
|
|
|
|
AGENT_COUNT = 8
|
|
DEFAULT_NAME = re.compile(r'\b(?:[a-z]{1,4}Var\d+|[a-zA-Z]{0,4}Stack_[0-9a-f]+|local_[0-9a-f]+)\b')
|
|
NOT_RENAMEABLE = re.compile(r'(this|param_\d+)$|in_|extraout|unaff')
|
|
LIBRARY = re.compile(r'^(FUN_|Catch|Unwind|std::|png_|jpeg_|jinit|vorbis|_vorbis|ov_|ogg|th_|oc_|theora|stb_|tdefl|tinfl|mz_|'
|
|
r'inflate|deflate|lua|luaL|luabridge|glfw|_glfw|mi_|_mi_|rapidxml|json|EOS_|SteamAPI|Steam|steamstub|__|_|`|'
|
|
r'FID_|libyuv|I420|ARGB|curl|sha1|crc32|zlib|clown|Clown|VideoClip|TheoraVideo|tolua|utf8|Gamepad_|KHR|epoxy|wgl|gl[A-Z])')
|
|
PROTOTYPE = re.compile(r'^\s*(?:static\s+)?(?:cleanup\s+)?(?:__\w+call\s+)?.+?\s*((?:[\w:]+::)?~?\w+)\s*\(.*?\)\s*;')
|
|
|
|
BRIEF = r'''export const meta = {
|
|
name: '__NAME__',
|
|
description: 'Second pass: name the default-named locals left in the largest already-named game functions (8 agents)',
|
|
phases: [{ title: 'Locals' }],
|
|
}
|
|
const R = '__ROUND__'
|
|
const locals = i => `Repo: /home/anon/sda/Personal/Repos/isaac-decomp — Ghidra decompilation of The Binding of Isaac: Repentance+ (isaac-ng.exe v1.9.7.17, 32-bit MSVC). Read README.md "Quick use" and "Naming you will see", the header of db/locals.tsv, and scripts/ApplyLocals.java (it decompiles the function, finds the local by its current decompiler name and commits the new name to the Ghidra database). Do NOT edit repo files; do not run build.sh or decompile.sh --live. Read functions from ${R}/all_snapshot.c (a stable copy of dump/all.c; a function starts at its '//@@ <address> <name>' line): the names there (iVar3, local_2c, pEVar12, uVar7, fVar2, bVar1, puVar4 ...) are exactly what ApplyLocals will see in the next build, so use them verbatim.
|
|
|
|
Goal: make these functions read like source by naming their local variables. This is a SECOND PASS: earlier rounds already named some locals in these functions (the camelCase names you see), but many default names are left. Name only the remaining default-named locals (iVarN, uVarN, pEVarN, fVarN, local_xx, xStack_xx ...); keep the existing names, and use them to understand the code. If an existing name is clearly wrong and the variable has one role, add a row renaming it (existing name<TAB>correct name). To retype a variable without renaming it (e.g. an undefined4 that starts an 11-dword ColorMod, a std_string, a char *[N] table), write the same name in columns 2 and 3 and the type in column 4. Report other problems (wrong struct fields, misnamed functions, wrong this types) in your final message. The 4th input column counts the default names left. Input: ${R}/l_${i}.tsv — lines<TAB>address<TAB>name. For each function, go through its locals (the declarations at the top) and name every one whose role you can establish:
|
|
- Only rename a variable that has ONE role in the whole function. MSVC reuses register temporaries and stack slots, and Ghidra sometimes merges them into one name: check EVERY use (grep -n '\\b<var>\\b' within the function's line range) before naming. If a variable is reused for unrelated things, skip it, or give it a neutral name only if the roles are of one kind (e.g. scratchVec, tmpEntity, rngResult).
|
|
- Good targets: entity/player/npc pointers (pEVar5 -> spawnedTear, player, target), loop counters (iVar3 -> slot, i), item/collectible ids, RNG results, counts, flags (bVar1 -> isGreedMode; booleans start with is), Vectors on the stack (local_2c -> spawnPos; a two-float stack pair used as x/y is a Vector), sprite/anm2 pointers, timers.
|
|
- Names: camelCase, descriptive of the game meaning (soulHearts, chargeBarFrame, isTainted), not of the type. Do not rename \`this\` or param_N (parameters come from prototypes), in_ECX / in_XMM / extraout_ / unaff_ / CONCAT variables, or globals.
|
|
- A type in the 4th column only when certain and it changes readability (e.g. a local_ pair that is a Vector: \`Vector\`; an int that is really an Entity_Player pointer: \`Entity_Player *\`); otherwise leave it empty. Ghidra type syntax: \`Entity_Player *\`, \`Vector\`, \`float\`, \`int\`.
|
|
Output: append rows to ${R}/l_out_${i}.tsv: function address (8 hex digits)<TAB>decompiler name<TAB>newName[<TAB>C type]. Aim for most locals of each function; quality over count. Also, if a listed function has no "prototype:" line in its header comment and you can tell its parameters, append a REPENTOGON-syntax prototype line to ${R}/lp_out_${i}.zhl (format and RET n rule: db/protos.zhl header and scripts/ApplyProtos.java; check RET n with ./decompile.sh --asm or objdump of bin/isaac-ng.exe). Final message: per function, locals named / skipped (reused), and anything notable (wrong names or fields you noticed).`
|
|
await parallel([0, 1, 2, 3, 4, 5, 6, 7].map(i => () => agent(locals(i), { label: `locals ${i}`, phase: 'Locals' })))
|
|
return 'done'
|
|
'''
|
|
|
|
|
|
def snapshot_load(roundDir):
|
|
bodies = collections.defaultdict(list)
|
|
current = None
|
|
for line in open(roundDir + '/all_snapshot.c', errors='replace'):
|
|
if line.startswith('//@@ '):
|
|
current = tuple(line.split()[1:3])
|
|
continue
|
|
if current: bodies[current].append(line)
|
|
return {key: ''.join(lines) for key, lines in bodies.items()}
|
|
|
|
|
|
def protos_load(roundDir):
|
|
known = {line.split('\t')[1] for line in open('dump/functions.tsv')}
|
|
for path in sorted(glob.glob(roundDir + '/lp_out_*.zhl')):
|
|
for line in open(path):
|
|
match = PROTOTYPE.match(line)
|
|
if match and not line.lstrip().startswith('//') and match.group(1) in known:
|
|
yield match.group(1), line.rstrip('\n') + '\n'
|
|
|
|
|
|
def round_pick(roundDir, minLeft, maxLines, *prevRounds):
|
|
held = {name for name, _ in protos_load(prevRounds[-1])} if prevRounds else set()
|
|
heldAddrs = {line.split('\t')[0] for line in open('dump/functions.tsv') if line.split('\t')[1] in held}
|
|
skipped = heldAddrs | {line.split()[0] for line in open('dump/calls.tsv') if line.split()[1] in heldAddrs}
|
|
for prevRound in prevRounds: # what earlier rounds left is mostly reused slots their agents chose to skip
|
|
skipped |= {line.split('\t')[1] for path in glob.glob(prevRound + '/l_[0-9]*.tsv') for line in open(path) if not line.startswith('#')}
|
|
|
|
rows = []
|
|
for (addr, name), body in snapshot_load(roundDir).items():
|
|
if addr in skipped or LIBRARY.match(name) or 'decompile failed' in body[:500]: continue
|
|
left = len(set(DEFAULT_NAME.findall(body)))
|
|
if left >= minLeft: rows.append((left, body.count('\n'), addr, name))
|
|
rows.sort(reverse=True)
|
|
|
|
bins = [[0, []] for _ in range(AGENT_COUNT)]
|
|
for left, lineCount, addr, name in rows:
|
|
target = min(bins, key=lambda b: b[0])
|
|
if target[0] + lineCount > maxLines: continue
|
|
target[0] += lineCount
|
|
target[1].append(f'{lineCount}\t{addr}\t{name}\t{left}\n')
|
|
for agent, (_, picked) in enumerate(bins):
|
|
open(f'{roundDir}/l_{agent}.tsv', 'w').writelines(['# lines\taddress\tname\tdefault names left\n'] + picked)
|
|
print(len(rows), 'eligible,', sum(len(b[1]) for b in bins), 'picked:', [b[1][0].split('\t')[2] for b in bins if b[1]])
|
|
|
|
|
|
def locals_merge(roundDir):
|
|
bodies = {addr: body for (addr, _), body in snapshot_load(roundDir).items()}
|
|
seen = {tuple(line.split('\t')[:2]) for line in open('db/locals.tsv') if not line.startswith('#')}
|
|
newNames = collections.defaultdict(set)
|
|
rows, rejected = [], collections.Counter()
|
|
for path in sorted(glob.glob(roundDir + '/l_out_*.tsv')):
|
|
for line in open(path):
|
|
cols = line.rstrip('\n').split('\t')
|
|
if len(cols) < 3 or line.startswith('#'): continue
|
|
addr = cols[0].lower().replace('0x', '').zfill(8)
|
|
body = bodies.get(addr, '')
|
|
isRetypeOnly = cols[1] == cols[2] and len(cols) > 3 and cols[3].strip()
|
|
reason = ('nofunc' if not body else
|
|
'noname' if not re.search(r'\b%s\b' % re.escape(cols[1]), body) else
|
|
'param' if NOT_RENAMEABLE.match(cols[1]) else
|
|
'dup' if (addr, cols[1]) in seen else
|
|
'badname' if not re.fullmatch(r'[A-Za-z_]\w*', cols[2]) else
|
|
'clash' if not isRetypeOnly and (cols[2] in newNames[addr] or re.search(r'\b%s\b' % re.escape(cols[2]), body)) else None)
|
|
if reason:
|
|
rejected[reason] += 1
|
|
continue
|
|
seen.add((addr, cols[1]))
|
|
newNames[addr].add(cols[2])
|
|
rows.append('\t'.join([addr] + cols[1:4]) + '\n')
|
|
open('db/locals.tsv', 'a').writelines(rows)
|
|
print(len(rows), 'locals merged in', len(newNames), 'functions; rejected', dict(rejected))
|
|
|
|
|
|
def protos_merge(roundDir):
|
|
existing = {line.split('//')[0].strip() for line in open('db/protos.zhl')}
|
|
rows = [line for _, line in protos_load(roundDir) if line.split('//')[0].strip() not in existing]
|
|
open('db/protos.zhl', 'a').writelines(dict.fromkeys(rows))
|
|
print(len(dict.fromkeys(rows)), 'protos merged')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
command, args = sys.argv[1], sys.argv[2:]
|
|
if command == 'pick': round_pick(args[0], int(args[1]), int(args[2]), *args[3:])
|
|
elif command == 'brief': open(args[0] + '/wf.js', 'w').write(BRIEF.replace('__NAME__', 'decomp-' + args[0].rstrip('/').split('/')[-1] + '-locals').replace('__ROUND__', args[0].rstrip('/')))
|
|
elif command == 'locals': locals_merge(*args)
|
|
elif command == 'protos': protos_merge(*args)
|