From 36ae4cbfb894c42566b5157d0a036ac4d16ae462 Mon Sep 17 00:00:00 2001 From: shweet Date: Sun, 25 Oct 2026 20:25:00 -0400 Subject: [PATCH] ApplyProtos: REPENTOGON register notation (float r, int x, float returns, static cleanup) via custom storage Whole-program optimisation passes many floats in XMM registers and some arguments in ECX/EDX with the caller popping the stack; those declarations were skipped. Every prototype is now applied with explicit storage (this in ECX for __thiscall). Tested on a project copy: 1103 -> 1158 applied from the existing files (REPENTOGON's register declarations now fit), e.g. void __thiscall Game::SetBloom(Game *this,int Time,float Strength). Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- db/protos.zhl | 2 + scripts/ApplyProtos.java | 80 ++++++++++++++++++++++++++-------------- 3 files changed, 58 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index cc7c732..045349e 100644 --- a/README.md +++ b/README.md @@ -89,7 +89,9 @@ 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). +1,150 functions with `db/protos.zhl`; the comment says `prototype: REPENTOGON, confirmed by RET n` or names the db file). +Whole-program optimisation gives some functions other registers; REPENTOGON's notation covers them: `float r`, +`int x`, a `float` return, and `static cleanup` for a caller that pops the stack (RET n cannot check those). 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 diff --git a/db/protos.zhl b/db/protos.zhl index 92d9075..ec7600c 100644 --- a/db/protos.zhl +++ b/db/protos.zhl @@ -1,5 +1,7 @@ // Function signatures you have worked out, REPENTOGON syntax, one per line. Applied only where the callee's RET n agrees // with the declared stack parameters (scripts/ApplyProtos.java). Tried before REPENTOGON's declaration of the same name. +// Other registers, REPENTOGON notation: `__thiscall void Game::SetBloom(int time, float strength);`, a `float` +// return, `static cleanup bool Entity::ForceCollide(Entity* a, Entity* b, bool isLow);` (caller pops the stack). __fastcall void seed_fart_sound_override(int* soundId); // plain RET, only ECX read (no EDX/stack); callers lea ecx,[local] holding sound id 0x50/0x4d/0x109, write 0x25 back __thiscall void KAGE::Network::Multiplayer::ConstLobby::~ConstLobby(); // plain RET; ECX this: vftable store at [ecx], releases control block at this+8 __thiscall Vector* Vector::Normalized(Vector* outResult); // RET 0x4; ECX = source vector, [ebp+8] out, returns it diff --git a/scripts/ApplyProtos.java b/scripts/ApplyProtos.java index 7d9dc0a..3ffbb5e 100644 --- a/scripts/ApplyProtos.java +++ b/scripts/ApplyProtos.java @@ -1,6 +1,8 @@ // Applies REPENTOGON's function declarations (zhl dir) as prototypes, but only where this exe confirms them: for // __thiscall/__stdcall/__fastcall the callee pops its stack arguments (RET n), so the declared stack parameter sizes must -// add up to the purge Ghidra found; __cdecl must purge 0. Overloads pick the declaration that fits; db/protos.zhl may also declare free functions. Args: dirs of *.zhl +// add up to the purge Ghidra found; __cdecl and REPENTOGON's "static cleanup" must purge 0. Whole-program optimisation +// passes some arguments in other registers: "float radius", "int x", a "float" return (custom storage). +// Overloads pick the declaration that fits; db/protos.zhl may also declare free functions. Args: dirs of *.zhl import ghidra.app.script.GhidraScript; import ghidra.program.model.data.*; import ghidra.program.model.listing.*; @@ -36,16 +38,27 @@ public class ApplyProtos extends GhidraScript { return ptr == 0 && base instanceof Structure && base.getLength() < 4 ? null : base; // empty placeholder struct } + static String[] reg(String d) { // "float radius" -> {"float radius", "XMM3"}; no annotation -> {d, null} + Matcher m = Pattern.compile("^(.*?)\\s*<(\\w+)>$").matcher(d.trim()); + return m.matches() && m.group(2).matches("(?i)xmm\\d|e[abcd]x|e[sd]i|ebx|st0") ? new String[] {m.group(1), m.group(2).toUpperCase()} : new String[] {d, null}; + } + + VariableStorage at(String r, int size) throws Exception { // a register of the value's size: XMM3 -> XMM3_Da, ECX -> CL for a bool + if (r.startsWith("XMM")) r += size == 8 ? "_Qa" : "_Da"; + else if (size < 4 && r.matches("E[ABCD]X")) r = r.charAt(1) + (size == 1 ? "L" : "X"); + return new VariableStorage(currentProgram, currentProgram.getRegister(r)); + } + public void run() throws Exception { dtm = currentProgram.getDataTypeManager(); - Pattern decl = Pattern.compile("^\\s*(?:static\\s+)?(__thiscall|__stdcall|__cdecl|__fastcall)\\s+(.+?)\\s*((?:[\\w:]+::)?~?\\w+)\\s*\\((.*?)\\)\\s*;"); + Pattern decl = Pattern.compile("^\\s*(?:static\\s+)?(cleanup\\s+)?(?:(__thiscall|__stdcall|__cdecl|__fastcall)\\s+)?(.+?)\\s*((?:[\\w:]+::)?~?\\w+)\\s*\\((.*?)\\)\\s*;"); Map> byName = new HashMap<>(); Map from = new IdentityHashMap<>(); for (String dir : getScriptArgs()) // db/ first: its declarations are tried before REPENTOGON's for (Path p : Files.newDirectoryStream(Paths.get(dir), "*.zhl")) for (String l : Files.readAllLines(p, java.nio.charset.StandardCharsets.ISO_8859_1)) { Matcher m = decl.matcher(l); - if (m.find()) { byName.computeIfAbsent(m.group(3).replace("_", ""), k -> new ArrayList<>()).add(m); from.put(m, dir.contains("repentogon") ? "REPENTOGON" : "db/" + p.getFileName()); } + if (m.find()) { byName.computeIfAbsent(m.group(4).replace("_", ""), k -> new ArrayList<>()).add(m); from.put(m, dir.contains("repentogon") ? "REPENTOGON" : "db/" + p.getFileName()); } } int applied = 0, rejected = 0, unknown = 0; for (Function f : currentProgram.getListing().getFunctions(true)) { @@ -55,31 +68,44 @@ public class ApplyProtos extends GhidraScript { if (purge < 0 || purge > 0x400) { unknown++; continue; } boolean done = false; for (Matcher m : cands) { - String cc = m.group(1); - DataType ret = type(m.group(2)); - List ps = new ArrayList<>(); - int stack = 0, regs = cc.equals("__fastcall") ? 2 : 0; - boolean ok = ret != null; - String args = m.group(4).trim(); - if (ok && !args.isEmpty() && !args.equals("void")) - for (String a : args.split(",")) { - a = a.replaceAll("=.*", "").trim(); - Matcher nm = Pattern.compile("^(.*?)([A-Za-z_]\\w*)$").matcher(a); - String t = nm.matches() && nm.group(1).trim().length() > 0 ? nm.group(1) : a, n = nm.matches() && nm.group(1).trim().length() > 0 ? nm.group(2) : "p" + ps.size(); - DataType dt = type(t); - if (dt == null || dt instanceof VoidDataType) { ok = false; break; } - int slot = (dt.getLength() + 3) & ~3; - if (regs > 0 && slot == 4 && !(dt instanceof FloatDataType)) regs--; else stack += slot; - ps.add(new ParameterImpl(n, dt, currentProgram)); + boolean cleanup = m.group(1) != null; // REPENTOGON "cleanup": the caller pops the stack arguments + String cc = m.group(2) != null ? m.group(2) : "__cdecl"; + String[] rt = reg(m.group(3)); // "float": returned in XMM0 instead of EAX/ST0 + DataType ret = type(rt[0]); + if (ret == null || ret instanceof Structure) continue; // a struct returned by value goes through a hidden pointer + try { + List ps = new ArrayList<>(); + List regs = new ArrayList<>(cc.equals("__thiscall") ? List.of("ECX") : cc.equals("__fastcall") ? List.of("ECX", "EDX") : List.of()); + int stack = 4; // the first stack argument sits above the return address + boolean ok = true; + if (cc.equals("__thiscall")) { + DataType cls = dtm.getDataType(new CategoryPath("/"), f.getParentNamespace().getName()); + ps.add(new ParameterImpl("this", new PointerDataType(cls != null ? cls : VoidDataType.dataType), at(regs.remove(0), 4), currentProgram)); } - int expect = cc.equals("__cdecl") ? 0 : stack; - if (!ok || expect != purge) continue; - f.setCallingConvention(cc); - f.setReturnType(ret, SourceType.USER_DEFINED); - f.replaceParameters(Function.FunctionUpdateType.DYNAMIC_STORAGE_FORMAL_PARAMS, true, SourceType.USER_DEFINED, ps.toArray(new ParameterImpl[0])); - String cm = f.getComment() == null ? "" : f.getComment() + "\n"; - if (!cm.contains("prototype:")) f.setComment(cm + "prototype: " + from.get(m) + ", confirmed by RET " + purge); - applied++; done = true; break; + String args = m.group(5).trim(); + if (!args.isEmpty() && !args.equals("void")) + for (String a : args.split(",")) { + String[] ar = reg(a.replaceAll("=.*", "").trim()); // "float radius" + Matcher nm = Pattern.compile("^(.*?)([A-Za-z_]\\w*)$").matcher(ar[0]); + boolean named = nm.matches() && nm.group(1).trim().length() > 0; + DataType dt = type(named ? nm.group(1) : ar[0]); + if (dt == null || dt instanceof VoidDataType) { ok = false; break; } + VariableStorage vs; + if (ar[1] != null) vs = at(ar[1], dt.getLength()); + else if (!regs.isEmpty() && dt.getLength() <= 4 && !(dt instanceof FloatDataType)) vs = at(regs.remove(0), dt.getLength()); + else { vs = new VariableStorage(currentProgram, stack, dt.getLength()); stack += (dt.getLength() + 3) & ~3; } + ps.add(new ParameterImpl(named ? nm.group(2) : "p" + ps.size(), dt, vs, currentProgram)); + } + int expect = cleanup || cc.equals("__cdecl") ? 0 : stack - 4; + if (!ok || expect != purge) continue; + VariableStorage rs = ret instanceof VoidDataType ? VariableStorage.VOID_STORAGE : rt[1] != null ? at(rt[1], ret.getLength()) + : ret instanceof FloatDataType || ret instanceof DoubleDataType ? at("ST0", 10) + : ret.getLength() == 8 ? new VariableStorage(currentProgram, currentProgram.getRegister("EDX"), currentProgram.getRegister("EAX")) : at("EAX", ret.getLength()); + f.updateFunction(cc, new ReturnParameterImpl(ret, rs, currentProgram), ps, Function.FunctionUpdateType.CUSTOM_STORAGE, true, SourceType.USER_DEFINED); + String cm = f.getComment() == null ? "" : f.getComment() + "\n"; + if (!cm.contains("prototype:")) f.setComment(cm + "prototype: " + from.get(m) + (purge > 0 ? ", confirmed by RET " + purge : stack > 4 ? ", caller cleans up (RET n cannot check it)" : "")); + applied++; done = true; break; + } catch (Exception e) { println("ApplyProtos: " + f.getName(true) + ": " + e.getMessage()); } } if (!done) rejected++; }