Ghidra had KAGE_LogMessage marked non-returning, so ~1,200 functions were cut off at their first log call. ApplyProtos clears the flag on any function with a RET, re-disassembles after its calls and regrows the callers: 'does not return' 5337 -> 2355 (all genuine: _invalid_parameter_noinfo_noreturn, _Xlen, _CxxThrowException), dump 1.235M -> 1.299M lines. 596 more prototypes, ~20% with REPENTOGON register notation: param_N lines 44610 -> 42588, in_XMM 1237 -> 734. 12 renames from the agents (HUD::LoadGraphics at 008ed350 = Menu_OnlineLobby::load_member_sprite, Room::MamaMegaExplosion = Weapon::fire_bomb, vector_iterate_noop = PlayerManager::get_total_luck, log_room_transition = RoomTransition::start, ...). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
142 lines
9.9 KiB
Java
142 lines
9.9 KiB
Java
// 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<xmm3>", "int x<edx>", a "float<xmm0>" 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.*;
|
|
import ghidra.app.cmd.function.CreateFunctionCmd;
|
|
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<xmm3>" -> {"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));
|
|
}
|
|
|
|
// Ghidra marked KAGE_LogMessage non-returning, cutting ~1,200 callers off after their first log call. A function with a
|
|
// RET returns: clear the flag, disassemble after each call and regrow the callers' bodies.
|
|
int fix_no_return() throws Exception {
|
|
int n = 0;
|
|
Set<Function> callers = new HashSet<>();
|
|
for (Function f : currentProgram.getFunctionManager().getFunctions(true)) {
|
|
if (!f.hasNoReturn()) continue;
|
|
boolean isReturning = false;
|
|
for (Instruction in : currentProgram.getListing().getInstructions(f.getBody(), true))
|
|
if (in.getMnemonicString().startsWith("RET")) { isReturning = true; break; }
|
|
if (!isReturning) continue;
|
|
f.setNoReturn(false); n++;
|
|
for (Reference r : getReferencesTo(f.getEntryPoint())) {
|
|
Instruction call = r.getReferenceType().isCall() ? getInstructionAt(r.getFromAddress()) : null;
|
|
if (call == null) continue;
|
|
if (call.getFlowOverride() == FlowOverride.CALL_RETURN) call.setFlowOverride(FlowOverride.NONE);
|
|
if (getInstructionAt(call.getMaxAddress().add(1)) == null) disassemble(call.getMaxAddress().add(1));
|
|
Function c = getFunctionContaining(call.getAddress());
|
|
if (c != null) callers.add(c);
|
|
}
|
|
}
|
|
for (Function c : callers) CreateFunctionCmd.fixupFunctionBody(currentProgram, c, monitor);
|
|
return n;
|
|
}
|
|
|
|
public void run() throws Exception {
|
|
println("ApplyProtos: " + fix_no_return() + " functions wrongly marked non-returning fixed");
|
|
dtm = currentProgram.getDataTypeManager();
|
|
Pattern decl = Pattern.compile("^\\s*(?:static\\s+)?(cleanup\\s+)?(?:(__thiscall|__stdcall|__cdecl|__fastcall)\\s+)?(.+?)\\s*((?:[\\w:]+::)?~?\\w+)\\s*\\((.*?)\\)\\s*;");
|
|
Map<String, List<Matcher>> byName = new HashMap<>();
|
|
Map<Matcher, String> 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<Matcher> 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<xmm0>": 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<Variable> ps = new ArrayList<>();
|
|
List<String> 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<xmm3>"
|
|
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");
|
|
}
|
|
}
|