From cbb2f465ecc0ebc916aa959fed205d812b93527f Mon Sep 17 00:00:00 2001 From: shweet Date: Sun, 25 Oct 2026 16:08:01 -0400 Subject: [PATCH] Typed this for ~780 more methods whose ECX reads fit their class's confirmed fields; Sprite/Color = ANM2/ColorMod Co-Authored-By: Claude Opus 5.5 --- .gitignore | 1 + README.md | 6 ++++-- build.sh | 5 +++-- scripts/ApplyTypes.java | 22 ++++++++++++++++++++-- scripts/this_types.py | 34 ++++++++++++++++++++++++++++++++++ 5 files changed, 62 insertions(+), 6 deletions(-) create mode 100644 scripts/this_types.py diff --git a/.gitignore b/.gitignore index 58a37b8..f6f3d23 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,4 @@ __pycache__/ /dump.new/ /dump.old/ +/build_this.tsv diff --git a/README.md b/README.md index 624fa1e..85f68a0 100644 --- a/README.md +++ b/README.md @@ -87,8 +87,10 @@ read from the game's own trivial Lua getters, e.g. Entity 0x334 `_targetPosition are typed too (`npc->_sprite._animState._isPlaying`). **Prototypes** come from REPENTOGON's declarations only where this exe confirms them: a `__thiscall`/`__stdcall` callee pops its own stack arguments (`RET n`), so the declared parameters must add up to `n` (`scripts/ApplyProtos.java`, about -600 functions, plus `db/protos.zhl`; the comment says `prototype: REPENTOGON, confirmed by RET n` or names the db file). Methods of a class get a typed `this` -even without a prototype, and every `NpcAI::` routine is +600 functions, plus `db/protos.zhl`; the comment says `prototype: REPENTOGON, confirmed by RET n` or names the db file). +Methods with a REPENTOGON `__thiscall` declaration get a typed `this`; so does any other `Class::method` whose reads +from ECX land at least 60% inside Class's confirmed fields (`scripts/this_types.py`, ~800 methods; the Lua `Sprite` and +`Color` classes are ANM2 and ColorMod). Every `NpcAI::` routine is `__fastcall (Entity_NPC *npc)`, so you read `npc->_state`, `npc->_variant`, `npc->_i1` rather than `param_1[0x2d9]`. Unknown offsets still show as `field_0xNNN` or `*(int *)(p + 0xNNN)`. Look them up with `find.sh field` or `find.sh lua` (the Lua table has authoritative offsets such as `EntityNPC State field+0xb64`). diff --git a/build.sh b/build.sh index 42a8efa..b9de865 100755 --- a/build.sh +++ b/build.sh @@ -19,7 +19,8 @@ apply_db() { # db names -> struct types (zhl + db fields) P headers.py --merged "$D/build_fields.tsv" "$D/src/structs.hpp" "$D/zhl_fields.tsv" "$D/lua_fields.tsv" "$D/db/fields.tsv" # later rows win, "-" deletes echo '#include "structs.hpp"' | g++ -std=c++17 -fsyntax-only -I"$D/src" -x c++ - \ || echo "src/structs.hpp does not compile: a db/fields.tsv offset contradicts another" >&2 - G -process isaac-ng.exe -noanalysis -postScript ApplyTypes.java "$D/build_fields.tsv" + P this_types.py "$D/dump/all.c" "$D/build_fields.tsv" "$D/build_this.tsv" + G -process isaac-ng.exe -noanalysis -postScript ApplyTypes.java "$D/build_fields.tsv" "$D/build_this.tsv" G -process isaac-ng.exe -noanalysis -postScript ApplyProtos.java "$D/db" "$D/repentogon/libzhl/functions" # only where RET n agrees G -process isaac-ng.exe -noanalysis -postScript ApplyLocals.java "$D/db/locals.tsv" # after types: names refer to that decompile } @@ -47,7 +48,7 @@ if [ "$1" = --db ]; then awk -F'\t' -v a="$(printf '%08x' $((16#${A#0x})))" '$1 == a "" {print $2}' "$D/dump/functions.tsv"; done) | sort -u | sed 's/[][().*+?^$|]/\\&/g' | paste -sd'|'))\$" DECOMP_TIMEOUT=900 "$D/decompile.sh" --live "$RX" 100000 | awk -v d="$D" '/^\/\/@@ /{f=d "/retry_" $2 ".c"} {print > f}' for F in "$D"/retry_*.c; do P splice.py "$D/dump/all.c" "$F" || true; done - command rm -f "$D"/retry_*.c "$D/build_fields.tsv" + command rm -f "$D"/retry_*.c "$D/build_fields.tsv" "$D/build_this.tsv" P apply_db.py "$D/db/names.tsv" "$D/dump"; exit fi diff --git a/scripts/ApplyTypes.java b/scripts/ApplyTypes.java index 6a7491a..017022b 100644 --- a/scripts/ApplyTypes.java +++ b/scripts/ApplyTypes.java @@ -1,6 +1,6 @@ // Builds structs from zhl_fields.tsv (class, offset|base, type name), turns those namespaces into classes so // `this` gets typed, merges Lua-named namespaces (EntityPlayer -> Entity_Player), types NpcAI::* param 1 as Entity_NPC*. -// Arg: zhl_fields.tsv +// Args: merged fields.tsv [this_types.tsv: methods whose ECX use fits their class] import ghidra.app.script.GhidraScript; import ghidra.program.model.data.*; import ghidra.program.model.listing.*; @@ -100,6 +100,24 @@ public class ApplyTypes extends GhidraScript { typed++; } } + // Lua aliases: the Lua Sprite and Color classes are ANM2 and ColorMod, so their methods' `this` gets that layout + for (String[] al : new String[][] {{"Sprite", "ANM2"}, {"Color", "ColorMod"}}) { + DataType t = dtm.getDataType(new CategoryPath("/"), al[1]); + if (!(t instanceof Structure)) continue; + Structure copy = (Structure) t.copy(dtm); + copy.setName(al[0]); + dtm.addDataType(copy, DataTypeConflictHandler.REPLACE_HANDLER); + } + // methods whose ECX offsets fit their class (scripts/this_types.py) become __thiscall, typing `this` + int fitted = 0; + if (getScriptArgs().length > 1) for (String l : Files.readAllLines(Paths.get(getScriptArgs()[1]))) { + Function f = getFunctionAt(toAddr(l.split("\t")[0])); + if (f == null || "__thiscall".equals(f.getCallingConventionName())) continue; + Namespace ns = f.getParentNamespace(); + if (!(ns instanceof GhidraClass)) try { st.convertNamespaceToClass(ns); } catch (Exception e) { continue; } + f.setCallingConvention("__thiscall"); + fitted++; + } // NpcAI routines are __fastcall(npc in ECX) DataType npcPtr = new PointerDataType(dtm.getDataType(new CategoryPath("/"), "Entity_NPC")); Namespace ai = st.getNamespace("NpcAI", global); @@ -112,6 +130,6 @@ public class ApplyTypes extends GhidraScript { new ParameterImpl("npc", npcPtr, currentProgram)); ain++; } - println("ApplyTypes: " + classes.size() + " structs, " + typed + " thiscall methods, " + ain + " NpcAI params"); + println("ApplyTypes: " + classes.size() + " structs, " + typed + " thiscall methods, " + fitted + " fitted by ECX use, " + ain + " NpcAI params"); } } diff --git a/scripts/this_types.py b/scripts/this_types.py new file mode 100644 index 0000000..6ed63e2 --- /dev/null +++ b/scripts/this_types.py @@ -0,0 +1,34 @@ +# Which named methods (Class::method, from Lua, db or ZHL without a declaration) really get a Class object in ECX: +# at least 60% of the distinct offsets they read from in_ECX must fall inside Class's confirmed fields (5+ known). +# ApplyTypes.java then makes them __thiscall, so `this` is typed. Lua aliases: Sprite = ANM2, Color = ColorMod. +# Usage: this_types.py all.c merged_fields.tsv out.tsv (out: address \t class \t hits/offsets \t name) +import collections, re, sys +src, fields_tsv, out = sys.argv[1:4] +ALIAS = {'Sprite': 'ANM2', 'Color': 'ColorMod'} +SIZE = {'bool': 1, 'char': 1, 'int8_t': 1, 'uint8_t': 1, 'short': 2, 'int16_t': 2, 'uint16_t': 2, 'double': 8, 'uint64_t': 8, + 'int64_t': 8, 'Vector': 8, 'ColorMod': 0x2c, 'ANM2': 0x114, 'KColor': 0x10, 'BitSet128': 0x10, 'RNG': 0x10, + 'std_string': 0x18, 'AnimationState': 0x20} +spans, base = collections.defaultdict(list), {} +for l in open(fields_tsv): + c = l.rstrip('\n').split('\t') + if c[1] == 'base': base[c[0]] = c[2]; continue + d = c[2].strip(); n = re.search(r'\[(\w+)\]\s*$', d) + if n: d = d[:n.start()] + t = d.rsplit(None, 1)[0].replace('const ', '') if ' ' in d else d + spans[c[0]].append((int(c[1], 16), (4 if t.endswith('*') else SIZE.get(t, 4)) * (int(n.group(1), 0) if n else 1))) +def known(cls): + r = [] + while cls: r += spans.get(cls, []); cls = base.get(cls) + return r +rows, addr, name, offs = [], None, None, set() +def flush(): + if not (name and '::' in name and offs) or re.match(r'(FUN_|NpcAI|NpcHelper|std::|Catch|Unwind)', name): return + ns = name.rsplit('::', 1)[0]; cls = ALIAS.get(ns, ns); k = known(cls) + hit = sum(1 for o in offs if any(a <= o < a + s for a, s in k)) + if len(k) >= 5 and hit / len(offs) >= 0.6: rows.append(f'{addr}\t{cls}\t{hit}/{len(offs)}\t{name}\n') +for line in open(src, errors='replace'): + if line.startswith('//@@ '): flush(); _, addr, name = line.split()[:3]; offs = set(); continue + offs.update(int(m.group(1), 16) for m in re.finditer(r'in_ECX \+ (0x[0-9a-f]+)', line)) +flush() +open(out, 'w').writelines(rows) +print(f'this_types: {len(rows)} methods')