diff --git a/README.md b/README.md index 47aee39..b4b9ee8 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,10 @@ is consistent. Types: structs built from the confirmed REPENTOGON fields, plus `lua_fields.tsv` (about 100 fields REPENTOGON lacks, read from the game's own trivial Lua getters, e.g. Entity 0x334 `_targetPosition`) and `db/fields.tsv`. Embedded structs are typed too (`npc->_sprite._animState._isPlaying`). -ZHL `__thiscall` methods get a typed `this`, and every `NpcAI::` routine is +**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; the comment says `prototype: REPENTOGON, confirmed by RET n`). Methods of a class get a typed `this` +even without a prototype, and 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 7afe3c4..6b31276 100755 --- a/build.sh +++ b/build.sh @@ -18,6 +18,7 @@ apply_db() { # db names -> struct types (zhl + db fields) G -process isaac-ng.exe -noanalysis -postScript ApplyDb.java "$D/db/names.tsv" grep -hv '^#' "$D/zhl_fields.tsv" "$D/lua_fields.tsv" "$D/db/fields.tsv" > "$D/build_fields.tsv" # later lines win G -process isaac-ng.exe -noanalysis -postScript ApplyTypes.java "$D/build_fields.tsv" + G -process isaac-ng.exe -noanalysis -postScript ApplyProtos.java "$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 P headers.py "$D/src/structs.hpp" "$D/zhl_fields.tsv" "$D/lua_fields.tsv" "$D/db/fields.tsv" echo '#include "structs.hpp"' | g++ -std=c++17 -fsyntax-only -I"$D/src" -x c++ - \ diff --git a/scripts/ApplyProtos.java b/scripts/ApplyProtos.java new file mode 100644 index 0000000..8b28211 --- /dev/null +++ b/scripts/ApplyProtos.java @@ -0,0 +1,86 @@ +// 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. Arg: zhl dir +import ghidra.app.script.GhidraScript; +import ghidra.program.model.data.*; +import ghidra.program.model.listing.*; +import ghidra.program.model.symbol.SourceType; +import java.nio.file.*; +import java.util.*; +import java.util.regex.*; + +public class ApplyProtos extends GhidraScript { + DataTypeManager dtm; + + DataType type(String t) { // null = unknown (by-value struct we do not have, or unparseable) + t = t.replace("const ", "").replace("struct ", "").replace("&", "*").trim(); + int ptr = 0; + while (t.endsWith("*")) { ptr++; t = t.substring(0, t.length() - 1).trim(); } + DataType base; + switch (t) { + case "void": base = VoidDataType.dataType; break; + case "bool": case "char": case "int8_t": case "uint8_t": case "unsigned char": base = ByteDataType.dataType; break; + case "short": case "int16_t": case "uint16_t": case "unsigned short": base = ShortDataType.dataType; break; + case "int": case "int32_t": case "long": base = IntegerDataType.dataType; break; + case "unsigned int": case "uint32_t": case "unsigned long": base = UnsignedIntegerDataType.dataType; break; + case "float": base = FloatDataType.dataType; break; + case "double": base = DoubleDataType.dataType; break; + case "long long": case "int64_t": base = LongLongDataType.dataType; break; + case "unsigned long long": case "uint64_t": base = UnsignedLongLongDataType.dataType; break; + default: + base = t.matches("\\w+") ? dtm.getDataType(new CategoryPath("/"), t) : null; + if (base == null && ptr == 0) return null; + if (base == null) base = VoidDataType.dataType; + } + for (int i = 0; i < ptr; i++) base = new PointerDataType(base); + return ptr == 0 && base instanceof Structure && base.getLength() < 4 ? null : base; // empty placeholder struct + } + + 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*;"); + Map> byName = new HashMap<>(); + for (Path p : Files.newDirectoryStream(Paths.get(getScriptArgs()[0]), "*.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); + } + int applied = 0, rejected = 0, unknown = 0; + for (Function f : currentProgram.getListing().getFunctions(true)) { + List cands = byName.get(f.getName(true).replace("_", "")); + if (cands == null || f.getName(true).startsWith("NpcAI::")) continue; + int purge = f.getStackPurgeSize(); + 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)); + } + 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: REPENTOGON, confirmed by RET " + purge); + applied++; done = true; break; + } + if (!done) rejected++; + } + println("ApplyProtos: " + applied + " applied, " + rejected + " rejected (stack purge disagrees or unknown types), " + unknown + " purge unknown"); + } +}