// 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 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.*; 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 } 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+)?(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(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)) { 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) { 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)); } 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++; } println("ApplyProtos: " + applied + " applied, " + rejected + " rejected (stack purge disagrees or unknown types), " + unknown + " purge unknown"); } }