Salvage Repentance+ 1.9.7.17 decompilation toolkit, notes and name database
Ghidra 12.2 project and full dump of isaac-ng.exe v1.9.7.17, query scripts, notes indexed by entity, anm2/rooms reimplementations, and db/ (names + fields) that build.sh re-applies. Fixes awk numeric address comparison in find.sh/decompile.sh. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
ad8f933086
124 files changed
+1366681
No files matched your search
@@ -0,0 +1,32 @@
|
||||
// Applies db/names.tsv (address, Qualified::Name, note) as forced renames with a "DB: note" comment. Arg: names.tsv
|
||||
import ghidra.app.script.GhidraScript;
|
||||
import ghidra.program.model.address.*;
|
||||
import ghidra.program.model.listing.*;
|
||||
import ghidra.program.model.symbol.*;
|
||||
import java.nio.file.*;
|
||||
|
||||
public class ApplyDb extends GhidraScript {
|
||||
public void run() throws Exception {
|
||||
SymbolTable st = currentProgram.getSymbolTable();
|
||||
int n = 0;
|
||||
for (String line : Files.readAllLines(Paths.get(getScriptArgs()[0]))) {
|
||||
if (line.isBlank() || line.startsWith("#")) continue;
|
||||
String[] c = line.split("\t", 3);
|
||||
Address a = toAddr(c[0]);
|
||||
Function fn = getFunctionAt(a);
|
||||
if (fn == null) { disassemble(a); fn = createFunction(a, null); }
|
||||
if (fn == null) { println("ApplyDb: no function at " + c[0]); continue; }
|
||||
String[] parts = c[1].split("::");
|
||||
Namespace ns = currentProgram.getGlobalNamespace();
|
||||
for (int k = 0; k < parts.length - 1; k++) {
|
||||
Namespace n2 = st.getNamespace(parts[k], ns);
|
||||
ns = n2 != null ? n2 : st.createNameSpace(ns, parts[k], SourceType.USER_DEFINED);
|
||||
}
|
||||
fn.setParentNamespace(ns);
|
||||
fn.setName(parts[parts.length - 1], SourceType.USER_DEFINED);
|
||||
fn.setComment("DB: " + (c.length > 2 ? c[2] : ""));
|
||||
n++;
|
||||
}
|
||||
println("ApplyDb: " + n + " names");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// Applies names from zhl_matches.tsv (va, Qualified::Name, quality, decl). Arg: tsv path
|
||||
import ghidra.app.script.GhidraScript;
|
||||
import ghidra.program.model.address.*;
|
||||
import ghidra.program.model.listing.*;
|
||||
import ghidra.program.model.symbol.*;
|
||||
import java.nio.file.*;
|
||||
|
||||
public class ApplyNames extends GhidraScript {
|
||||
public void run() throws Exception {
|
||||
SymbolTable st = currentProgram.getSymbolTable();
|
||||
int n = 0;
|
||||
for (Function f : currentProgram.getListing().getFunctions(true)) { // idempotent: undo previous runs
|
||||
String cm = f.getComment();
|
||||
if (cm == null || !cm.startsWith("ZHL [")) continue;
|
||||
f.setComment(null);
|
||||
f.setParentNamespace(currentProgram.getGlobalNamespace());
|
||||
f.setName(null, SourceType.DEFAULT);
|
||||
}
|
||||
for (String line : Files.readAllLines(Paths.get(getScriptArgs()[0]))) {
|
||||
String[] c = line.split("\t", 4);
|
||||
Address a = toAddr(c[0]);
|
||||
Function fn = getFunctionAt(a);
|
||||
if (fn == null) { disassemble(a); fn = createFunction(a, null); }
|
||||
String[] parts = c[1].split("::");
|
||||
Namespace ns = currentProgram.getGlobalNamespace();
|
||||
for (int k = 0; k < parts.length - 1; k++) {
|
||||
Namespace n2 = st.getNamespace(parts[k], ns);
|
||||
ns = n2 != null ? n2 : st.createNameSpace(ns, parts[k], SourceType.USER_DEFINED);
|
||||
}
|
||||
String leaf = parts[parts.length - 1];
|
||||
if (fn == null) { st.createLabel(a, leaf, ns, SourceType.USER_DEFINED); continue; }
|
||||
try { fn.setParentNamespace(ns); fn.setName(leaf, SourceType.USER_DEFINED); }
|
||||
catch (Exception e) { fn.setName(leaf + "_" + c[0], SourceType.USER_DEFINED); }
|
||||
fn.setComment("ZHL [" + c[2] + "] " + c[3]);
|
||||
n++;
|
||||
}
|
||||
// vtable slots: name still-unnamed virtuals via RTTI "<ns>::<Class>::vftable" labels
|
||||
int v = 0;
|
||||
java.util.Map<String, Address> vft = new java.util.HashMap<>();
|
||||
for (Symbol s : st.getAllSymbols(false)) {
|
||||
if (!s.getName().equals("vftable") || s.getParentNamespace() == null) continue;
|
||||
vft.putIfAbsent(s.getParentNamespace().getName(), s.getAddress());
|
||||
}
|
||||
for (String line : Files.readAllLines(Paths.get(getScriptArgs()[1]))) {
|
||||
String[] c = line.split(" ");
|
||||
Address t = vft.get(c[0]);
|
||||
if (t == null) continue;
|
||||
Address a = toAddr(getInt(t.add(4L * Integer.parseInt(c[1]))) & 0xffffffffL);
|
||||
Function fn = getFunctionAt(a);
|
||||
if (fn == null) { disassemble(a); fn = createFunction(a, null); }
|
||||
if (fn == null || fn.getSymbol().getSource() != SourceType.DEFAULT) continue; // already named (inherited or ZHL)
|
||||
Namespace ns = st.getNamespace(c[0], currentProgram.getGlobalNamespace());
|
||||
if (ns == null) ns = st.createNameSpace(currentProgram.getGlobalNamespace(), c[0], SourceType.USER_DEFINED);
|
||||
fn.setParentNamespace(ns);
|
||||
fn.setName(c[2], SourceType.USER_DEFINED);
|
||||
fn.setComment("ZHL [vtable slot " + c[1] + "]");
|
||||
v++;
|
||||
}
|
||||
// Lua binding targets (optional 3rd tsv, same format): only name functions nothing else named
|
||||
int l = 0;
|
||||
if (getScriptArgs().length > 2) for (String line : Files.readAllLines(Paths.get(getScriptArgs()[2]))) {
|
||||
String[] c = line.split(" ", 4);
|
||||
Address a = toAddr(c[0]);
|
||||
Function fn = getFunctionAt(a);
|
||||
if (fn == null) { disassemble(a); fn = createFunction(a, null); }
|
||||
if (fn == null || fn.getSymbol().getSource() != SourceType.DEFAULT) continue;
|
||||
String[] parts = c[1].split("::");
|
||||
Namespace ns = st.getNamespace(parts[0], currentProgram.getGlobalNamespace());
|
||||
if (ns == null) ns = st.createNameSpace(currentProgram.getGlobalNamespace(), parts[0], SourceType.USER_DEFINED);
|
||||
fn.setParentNamespace(ns);
|
||||
try { fn.setName(parts[1], SourceType.USER_DEFINED); } catch (Exception e) { fn.setName(parts[1] + "_" + c[0], SourceType.USER_DEFINED); }
|
||||
fn.setComment("ZHL [lua] " + c[3]);
|
||||
l++;
|
||||
}
|
||||
println("ApplyNames: " + n + " sig, " + v + " vtable, " + l + " lua");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
// 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
|
||||
import ghidra.app.script.GhidraScript;
|
||||
import ghidra.program.model.data.*;
|
||||
import ghidra.program.model.listing.*;
|
||||
import ghidra.program.model.symbol.*;
|
||||
import java.nio.file.*;
|
||||
import ghidra.program.model.listing.ParameterImpl;
|
||||
import java.util.*;
|
||||
|
||||
public class ApplyTypes extends GhidraScript {
|
||||
Map<String, List<String[]>> fields = new LinkedHashMap<>();
|
||||
Map<String, String> base = new HashMap<>();
|
||||
DataTypeManager dtm;
|
||||
DataType vec;
|
||||
|
||||
DataType prim(String t) {
|
||||
t = t.replaceAll("\\s+\\w+$", "").replace("const ", "").trim(); // drop field name
|
||||
if (t.endsWith("*")) return new PointerDataType(VoidDataType.dataType);
|
||||
switch (t) {
|
||||
case "int": case "int32_t": case "unsigned int": case "uint32_t": case "unsigned long": case "long": return IntegerDataType.dataType;
|
||||
case "float": return FloatDataType.dataType;
|
||||
case "bool": case "char": case "uint8_t": case "int8_t": case "unsigned char": return ByteDataType.dataType;
|
||||
case "short": case "unsigned short": case "uint16_t": case "int16_t": return ShortDataType.dataType;
|
||||
case "unsigned long long": case "uint64_t": case "long long": return QWordDataType.dataType;
|
||||
case "double": return DoubleDataType.dataType;
|
||||
case "Vector": return vec;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
void addFields(StructureDataType s, String cls, int depth) {
|
||||
if (depth > 8) return;
|
||||
if (base.containsKey(cls)) addFields(s, base.get(cls), depth + 1);
|
||||
for (String[] f : fields.getOrDefault(cls, List.of())) {
|
||||
DataType dt = prim(f[2]);
|
||||
if (dt == null) continue;
|
||||
int off = Integer.decode(f[1]);
|
||||
String nm = f[2].replaceAll(".*\\s", "").replaceAll("[^\\w]", "");
|
||||
try {
|
||||
if (off + dt.getLength() > s.getLength()) s.growStructure(off + dt.getLength() - s.getLength());
|
||||
s.replaceAtOffset(off, dt, dt.getLength(), nm, null);
|
||||
} catch (Exception e) { /* overlapping/odd field: skip */ }
|
||||
}
|
||||
}
|
||||
|
||||
public void run() throws Exception {
|
||||
dtm = currentProgram.getDataTypeManager();
|
||||
StructureDataType v = new StructureDataType("Vector", 0);
|
||||
v.add(FloatDataType.dataType, "x", null);
|
||||
v.add(FloatDataType.dataType, "y", null);
|
||||
vec = dtm.addDataType(v, DataTypeConflictHandler.REPLACE_HANDLER);
|
||||
for (String l : Files.readAllLines(Paths.get(getScriptArgs()[0]))) {
|
||||
String[] c = l.split("\t");
|
||||
if (c[1].equals("base")) base.put(c[0], c[2]);
|
||||
else fields.computeIfAbsent(c[0], k -> new ArrayList<>()).add(c);
|
||||
}
|
||||
SymbolTable st = currentProgram.getSymbolTable();
|
||||
Namespace global = currentProgram.getGlobalNamespace();
|
||||
Set<String> classes = new TreeSet<>(fields.keySet());
|
||||
classes.addAll(base.keySet());
|
||||
int typed = 0;
|
||||
for (String cls : classes) {
|
||||
StructureDataType s = new StructureDataType(cls, 4);
|
||||
addFields(s, cls, 0);
|
||||
if (s.getLength() < 0x20) continue; // skip trivial structs
|
||||
DataType dt = dtm.addDataType(s, DataTypeConflictHandler.REPLACE_HANDLER);
|
||||
Namespace ns = st.getNamespace(cls, global);
|
||||
if (ns == null) ns = st.createClass(global, cls, SourceType.USER_DEFINED);
|
||||
else if (!(ns instanceof GhidraClass)) ns = st.convertNamespaceToClass(ns);
|
||||
Namespace alias = st.getNamespace(cls.replace("_", ""), global);
|
||||
if (alias != null && !alias.equals(ns))
|
||||
for (Symbol sym : st.getSymbols(alias)) {
|
||||
if (sym.getSymbolType() != SymbolType.FUNCTION) continue;
|
||||
try { sym.setNamespace(ns); } catch (Exception e) { /* name clash: keep in alias ns */ }
|
||||
}
|
||||
for (Symbol sym : st.getSymbols(ns)) {
|
||||
Function f = getFunctionAt(sym.getAddress());
|
||||
String cm = f == null ? null : f.getComment();
|
||||
if (cm == null || !(cm.contains("__thiscall") || cm.contains("vtable slot"))) continue;
|
||||
f.setCallingConvention("__thiscall"); // Ghidra then types `this` as <cls>*
|
||||
typed++;
|
||||
}
|
||||
}
|
||||
// NpcAI routines are __fastcall(npc in ECX)
|
||||
DataType npcPtr = new PointerDataType(dtm.getDataType(new CategoryPath("/"), "Entity_NPC"));
|
||||
Namespace ai = st.getNamespace("NpcAI", global);
|
||||
int ain = 0;
|
||||
if (ai != null) for (Symbol sym : st.getSymbols(ai)) {
|
||||
Function f = getFunctionAt(sym.getAddress());
|
||||
if (f == null) continue;
|
||||
f.setCallingConvention("__fastcall");
|
||||
f.replaceParameters(Function.FunctionUpdateType.DYNAMIC_STORAGE_FORMAL_PARAMS, true, SourceType.USER_DEFINED,
|
||||
new ParameterImpl("npc", npcPtr, currentProgram));
|
||||
ain++;
|
||||
}
|
||||
println("ApplyTypes: " + classes.size() + " structs, " + typed + " thiscall methods, " + ain + " NpcAI params");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// Live decompile. Args: address-or-regex [maxResults]. Matches names by regex (full qualified name) or entry address.
|
||||
import ghidra.app.script.GhidraScript;
|
||||
import ghidra.app.decompiler.*;
|
||||
import ghidra.program.model.address.*;
|
||||
import ghidra.program.model.listing.*;
|
||||
import java.util.regex.*;
|
||||
import java.io.*;
|
||||
|
||||
public class Decompile extends GhidraScript {
|
||||
public void run() throws Exception {
|
||||
String q = getScriptArgs()[0];
|
||||
int max = getScriptArgs().length > 1 ? Integer.parseInt(getScriptArgs()[1]) : 20;
|
||||
DecompInterface di = new DecompInterface();
|
||||
DecompileOptions opts = new DecompileOptions();
|
||||
opts.setMaxPayloadMBytes(1024); // UseActiveItem-sized switches overflow the 50MB default
|
||||
di.setOptions(opts);
|
||||
di.openProgram(currentProgram);
|
||||
Function only = null;
|
||||
if (q.matches("(0x)?[0-9a-fA-F]{6,8}")) {
|
||||
Address a = toAddr(q.replace("0x", ""));
|
||||
only = getFunctionContaining(a);
|
||||
}
|
||||
Pattern p = Pattern.compile(q);
|
||||
PrintStream o = new PrintStream(new FileOutputStream(getScriptArgs()[2]));
|
||||
int n = 0;
|
||||
for (Function f : currentProgram.getListing().getFunctions(true)) {
|
||||
if (only != null ? f != only : !p.matcher(f.getName(true)).find()) continue;
|
||||
if (n++ >= max) { o.println("// ... more matches truncated"); break; }
|
||||
DecompileResults r = di.decompileFunction(f, Integer.parseInt(System.getenv().getOrDefault("DECOMP_TIMEOUT", "180")), monitor);
|
||||
o.println("//@@ " + f.getEntryPoint() + " " + f.getName(true));
|
||||
o.println(r.decompileCompleted() ? r.getDecompiledFunction().getC() : "/* failed: " + r.getErrorMessage() + " */");
|
||||
}
|
||||
o.close();
|
||||
di.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// Args: address count outfile. Prints instructions starting at address.
|
||||
import ghidra.app.script.GhidraScript;
|
||||
import ghidra.program.model.listing.*;
|
||||
import java.io.*;
|
||||
public class Disasm extends GhidraScript {
|
||||
public void run() throws Exception {
|
||||
String[] a = getScriptArgs();
|
||||
try (PrintWriter o = new PrintWriter(a[2])) {
|
||||
Instruction in = getInstructionAt(toAddr(a[0]));
|
||||
if (in == null) in = getInstructionAfter(toAddr(a[0]));
|
||||
for (int i = 0; in != null && i < Integer.parseInt(a[1]); i++, in = in.getNext())
|
||||
o.println(in.getAddress() + " " + in);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
// Dumps decompiled C of every function + index, strings-with-xrefs, call edges. Arg: output dir
|
||||
import ghidra.app.script.GhidraScript;
|
||||
import ghidra.app.decompiler.*;
|
||||
import ghidra.program.model.address.*;
|
||||
import ghidra.program.model.listing.*;
|
||||
import ghidra.program.model.symbol.*;
|
||||
import ghidra.program.model.data.StringDataInstance;
|
||||
import java.io.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.*;
|
||||
|
||||
public class DumpAll extends GhidraScript {
|
||||
public void run() throws Exception {
|
||||
File out = new File(getScriptArgs()[0]);
|
||||
out.mkdirs();
|
||||
Listing listing = currentProgram.getListing();
|
||||
ReferenceManager rm = currentProgram.getReferenceManager();
|
||||
|
||||
try (PrintWriter idx = new PrintWriter(new File(out, "functions.tsv"));
|
||||
PrintWriter calls = new PrintWriter(new File(out, "calls.tsv"))) {
|
||||
for (Function f : listing.getFunctions(true)) {
|
||||
idx.println(f.getEntryPoint() + "\t" + f.getName(true) + "\t" + f.getBody().getNumAddresses());
|
||||
for (Function c : f.getCalledFunctions(monitor)) calls.println(f.getEntryPoint() + "\t" + c.getEntryPoint());
|
||||
}
|
||||
}
|
||||
|
||||
try (PrintWriter st = new PrintWriter(new File(out, "strings.tsv"))) {
|
||||
for (Data d : listing.getDefinedData(true)) {
|
||||
if (!d.hasStringValue()) continue;
|
||||
String s = String.valueOf(d.getValue()).replace("\t", "\\t").replace("\n", "\\n");
|
||||
StringBuilder who = new StringBuilder();
|
||||
for (Reference r : rm.getReferencesTo(d.getAddress())) {
|
||||
Function f = getFunctionContaining(r.getFromAddress());
|
||||
who.append(f == null ? r.getFromAddress().toString() : f.getEntryPoint() + ":" + f.getName(true)).append(' ');
|
||||
}
|
||||
st.println(d.getAddress() + "\t" + s + "\t" + who.toString().trim());
|
||||
}
|
||||
}
|
||||
|
||||
List<Function> fns = new ArrayList<>();
|
||||
for (Function f : listing.getFunctions(true)) if (!f.isThunk()) fns.add(f);
|
||||
int nThreads = Math.max(1, Runtime.getRuntime().availableProcessors() - 2);
|
||||
String[] results = new String[fns.size()];
|
||||
AtomicInteger next = new AtomicInteger();
|
||||
List<Thread> threads = new ArrayList<>();
|
||||
for (int t = 0; t < nThreads; t++) {
|
||||
Thread th = new Thread(() -> {
|
||||
DecompInterface di = new DecompInterface();
|
||||
DecompileOptions opts = new DecompileOptions();
|
||||
opts.setMaxPayloadMBytes(1024); // UseActiveItem-sized switches overflow the 50MB default
|
||||
di.setOptions(opts);
|
||||
di.openProgram(currentProgram);
|
||||
int i;
|
||||
while ((i = next.getAndIncrement()) < fns.size()) {
|
||||
Function f = fns.get(i);
|
||||
DecompileResults r = di.decompileFunction(f, 900, TaskMonitor_dummy());
|
||||
String c = r != null && r.decompileCompleted() ? r.getDecompiledFunction().getC() : "/* decompile failed: " + (r == null ? "" : r.getErrorMessage()) + " */\n";
|
||||
results[i] = "//@@ " + f.getEntryPoint() + " " + f.getName(true) + "\n" + c + "\n";
|
||||
if (i % 2000 == 0) System.out.println("decompiled " + i + "/" + fns.size());
|
||||
}
|
||||
di.dispose();
|
||||
});
|
||||
th.start();
|
||||
threads.add(th);
|
||||
}
|
||||
for (Thread th : threads) th.join();
|
||||
try (PrintWriter all = new PrintWriter(new File(out, "all.c"))) { for (String s : results) all.print(s); }
|
||||
println("dumped " + fns.size());
|
||||
}
|
||||
static ghidra.util.task.TaskMonitor TaskMonitor_dummy() { return ghidra.util.task.TaskMonitor.DUMMY; }
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
// Recovers Lua registrations from disassembly (catches the ones whose name the decompiler drops, e.g. Sprite:Play).
|
||||
// Args: registrationFuncAddr classes.txt out.tsv (classes.txt = known Lua class names, one per line)
|
||||
// Writes va \t Class::Member \t lua \t decl (ApplyNames format)
|
||||
import ghidra.app.script.GhidraScript;
|
||||
import ghidra.program.model.address.*;
|
||||
import ghidra.program.model.listing.*;
|
||||
import ghidra.program.model.symbol.*;
|
||||
import java.io.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
|
||||
public class LuaAsm extends GhidraScript {
|
||||
public void run() throws Exception {
|
||||
String[] a = getScriptArgs();
|
||||
Set<String> classes = new HashSet<>(Files.readAllLines(Paths.get(a[1])));
|
||||
Function reg = getFunctionAt(toAddr(a[0]));
|
||||
String cls = null, str = null;
|
||||
Address fn = null;
|
||||
try (PrintWriter o = new PrintWriter(a[2])) {
|
||||
for (Instruction in : currentProgram.getListing().getInstructions(reg.getBody(), true)) {
|
||||
if (in.getFlowType().isCall()) {
|
||||
if (str != null && fn != null && cls != null)
|
||||
o.println(fn + "\t" + cls + "::" + str + "\tlua\tLua binding " + cls + ":" + str);
|
||||
else if (str != null && fn == null && classes.contains(str)) cls = str;
|
||||
str = null; fn = null;
|
||||
continue;
|
||||
}
|
||||
for (Reference r : in.getReferencesFrom()) {
|
||||
Data d = getDataAt(r.getToAddress());
|
||||
if (d != null && d.hasStringValue()) { str = String.valueOf(d.getValue()); continue; }
|
||||
if (d == null && r.getReferenceType().isData() && getInstructionAt(r.getToAddress()) != null) fn = r.getToAddress();
|
||||
else if (getFunctionAt(r.getToAddress()) != null && !r.getReferenceType().isCall()) fn = r.getToAddress();
|
||||
}
|
||||
// short names Ghidra did not define as strings: MOV reg, imm pointing at ASCII
|
||||
if (str == null) for (Object op : in.getOpObjects(in.getNumOperands() - 1 < 0 ? 0 : in.getNumOperands() - 1)) {
|
||||
if (!(op instanceof ghidra.program.model.scalar.Scalar)) continue;
|
||||
long v = ((ghidra.program.model.scalar.Scalar) op).getUnsignedValue();
|
||||
if (v < 0x400000 || v > 0x2000000) continue;
|
||||
try {
|
||||
byte[] b = getBytes(toAddr(v), 32);
|
||||
int n = 0;
|
||||
while (n < 32 && b[n] != 0 && (Character.isLetterOrDigit(b[n]) || b[n] == '_')) n++;
|
||||
if (n > 1 && n < 32 && b[n] == 0) str = new String(b, 0, n);
|
||||
} catch (Exception e) { }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
// Resolves the Entity_NPC AI dispatch (byte index table + jump table, keyed by entity type) and names the AI routines.
|
||||
// Args: dispatcherAddr Global.zhl out.tsv
|
||||
// Writes: type \t ENTITY_NAME \t caseBlock \t calls made in that case block (addr:name ...)
|
||||
// Renames each still-unnamed first callee to NpcAI::<ENTITY_NAME> (run without -readOnly to persist).
|
||||
import ghidra.app.script.GhidraScript;
|
||||
import ghidra.program.model.address.*;
|
||||
import ghidra.program.model.listing.*;
|
||||
import ghidra.program.model.scalar.Scalar;
|
||||
import ghidra.program.model.symbol.*;
|
||||
import java.io.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.regex.*;
|
||||
|
||||
public class NpcTable extends GhidraScript {
|
||||
public void run() throws Exception {
|
||||
String[] a = getScriptArgs();
|
||||
Map<Integer, String> names = new HashMap<>();
|
||||
boolean inEnum = false;
|
||||
Pattern ep = Pattern.compile("^\\s*(ENTITY_\\w+)\\s*=\\s*(\\d+)");
|
||||
for (String l : Files.readAllLines(Paths.get(a[1]))) {
|
||||
if (l.contains("enum eEntityType")) inEnum = true;
|
||||
else if (inEnum && l.contains("}")) break;
|
||||
Matcher m = ep.matcher(l);
|
||||
if (inEnum && m.find()) names.putIfAbsent(Integer.parseInt(m.group(2)), m.group(1));
|
||||
}
|
||||
|
||||
// find "CMP EAX,limit / JA / MOVZX EAX,byte ptr [EAX+idx] / JMP [EAX*4+jt]" preceded by "SUB/ADD EAX,-base" or LEA
|
||||
Function disp = getFunctionAt(toAddr(a[0]));
|
||||
if (disp.getSymbol().getSource() == SourceType.DEFAULT) disp.setName("Entity_NPC_UpdateAI_dispatch", SourceType.USER_DEFINED);
|
||||
Instruction in = getInstructionAt(toAddr(a[0]));
|
||||
long idx = 0, jt = 0, limit = 0;
|
||||
for (int i = 0; i < 400 && in != null; i++, in = in.getNext()) {
|
||||
String s = in.toString();
|
||||
if (s.startsWith("CMP EAX,")) limit = ((Scalar) in.getOpObjects(1)[0]).getValue();
|
||||
if (s.startsWith("MOVZX EAX,byte ptr [EAX +")) idx = Long.decode(s.replaceAll(".*\\+ (0x[0-9a-f]+)\\].*", "$1"));
|
||||
if (s.startsWith("JMP dword ptr [EAX*0x4 +") && idx != 0) { jt = Long.decode(s.replaceAll(".*\\+ (0x[0-9a-f]+)\\].*", "$1")); break; }
|
||||
}
|
||||
long base = 10; // switch is on (type - 10); see "param_1[10] - 10U" in the decompile
|
||||
println(String.format("idx=%x jt=%x limit=%d", idx, jt, limit));
|
||||
SymbolTable st = currentProgram.getSymbolTable();
|
||||
Namespace ns = st.getNamespace("NpcAI", null);
|
||||
if (ns == null) ns = st.createNameSpace(null, "NpcAI", SourceType.USER_DEFINED);
|
||||
Address end = in.getNext().getAddress();
|
||||
try (PrintWriter o = new PrintWriter(a[2])) {
|
||||
for (long t = 0; t <= limit; t++) {
|
||||
int bi = getByte(toAddr(idx + t)) & 0xff;
|
||||
Address blk = toAddr(getInt(toAddr(jt + 4L * bi)) & 0xffffffffL);
|
||||
StringBuilder calls = new StringBuilder();
|
||||
Function first = null;
|
||||
Instruction x = getInstructionAt(blk);
|
||||
for (int i = 0; i < 60 && x != null; i++, x = x.getNext()) {
|
||||
String s = x.toString();
|
||||
if (s.startsWith("CALL")) {
|
||||
Address[] fl = x.getFlows();
|
||||
Function f = fl.length > 0 ? getFunctionAt(fl[0]) : null;
|
||||
if (f != null) { calls.append(f.getEntryPoint()).append(':').append(f.getName(true)).append(' '); if (first == null) first = f; }
|
||||
}
|
||||
if (s.startsWith("JMP") && !s.contains("[") || s.startsWith("RET")) break;
|
||||
}
|
||||
int type = (int) (t + base);
|
||||
String nm = names.getOrDefault(type, "TYPE_" + type);
|
||||
if (first != null && first.getSymbol().getSource() == SourceType.DEFAULT) {
|
||||
first.setParentNamespace(ns);
|
||||
first.setName(nm, SourceType.USER_DEFINED);
|
||||
first.setComment("NPC AI for entity type " + type + " (from dispatcher " + a[0] + ")");
|
||||
}
|
||||
o.println(type + "\t" + nm + "\t" + blk + "\t" + calls.toString().trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
# Applies db/names.tsv to the dump in place (no Ghidra): headers, call sites, functions.tsv, strings.tsv, npc_ai.tsv.
|
||||
# Only names change; types/fields need build.sh --db. Safe to re-run. Usage: apply_db.py names.tsv dumpdir
|
||||
import re, sys
|
||||
db, d = sys.argv[1:3]
|
||||
fns = dict(l.rstrip('\n').split('\t')[:2] for l in open(f'{d}/functions.tsv'))
|
||||
ren = {}
|
||||
for l in open(db):
|
||||
if l.strip() and not l.startswith('#'):
|
||||
a, new = l.rstrip('\n').split('\t')[:2]
|
||||
if a in fns and list(fns.values()).count(fns[a]) == 1: ren[a] = (fns[a], new)
|
||||
# FUN_<addr> is unique; a qualified old name is replaced only where it is a whole token
|
||||
# (strings.tsv and npc_ai.tsv list users as addr:name, rewritten by address)
|
||||
old2new = {o: n for o, n in ren.values() if o != n}
|
||||
pat = re.compile(r'(?<!\w)(?<!::)(' + '|'.join(sorted(map(re.escape, old2new), key=len, reverse=True)) + r')(?![\w:])')
|
||||
users = re.compile(r'\b(' + '|'.join(ren) + r'):[^\s]+')
|
||||
def fix(s): return users.sub(lambda m: m.group(1) + ':' + ren[m.group(1)][1], pat.sub(lambda m: old2new[m.group(1)], s) if old2new else s)
|
||||
for f in ('all.c', 'strings.tsv', 'npc_ai.tsv'):
|
||||
p = f'{d}/{f}'; s = open(p).read(); open(p, 'w').write(fix(s))
|
||||
rows = [l.split('\t', 2) for l in open(f'{d}/functions.tsv')]
|
||||
open(f'{d}/functions.tsv', 'w').writelines(f'{a}\t{ren[a][1] if a in ren else n}\t{r}' for a, n, r in rows)
|
||||
print(f'apply_db: {len(ren)} renamed')
|
||||
@@ -0,0 +1,33 @@
|
||||
# REPENTOGON's struct offsets target an older exe; fields drift as the game adds members.
|
||||
# Re-anchors zhl_fields.tsv using trivial getters in the decompiled corpus ("Class::GetFoo" returning *(this+N)
|
||||
# anchors field "_foo" at N); every field shifts by the delta of the nearest anchor at or below it.
|
||||
# Usage: fix_offsets.py all.c zhl_fields.tsv out.tsv [names.tsv: addr \t Class::Member, overrides corpus names]
|
||||
import re, sys
|
||||
src, fin, fout = sys.argv[1:4]
|
||||
rename = dict(l.split('\t')[:2] for l in open(sys.argv[4])) if len(sys.argv) > 4 else {}
|
||||
norm = lambda s: re.sub(r'^(get|is|has)', '', s.lower().lstrip('_'))
|
||||
getters = {} # (class, normname) -> exe offset
|
||||
name, n = None, 0
|
||||
for line in open(src, errors='replace'):
|
||||
if line.startswith('//@@ '): name, n = rename.get(line.split()[1], line.split()[2]), 0; continue
|
||||
n += 1
|
||||
m = n < 14 and name and re.search(r'return (?:\*\([\w ]+\*\)\(\w+ \+ (0x[0-9a-f]+)\)|\w+->(\w+));', line)
|
||||
if m and '::' in name and m.group(1):
|
||||
cls, meth = name.rsplit('::', 1)
|
||||
cls = {'EntityPlayer': 'Entity_Player', 'EntityNPC': 'Entity_NPC'}.get(cls, cls)
|
||||
getters[(cls, norm(meth))] = int(m.group(1), 16)
|
||||
rows = [l.rstrip('\n').split('\t') for l in open(fin)]
|
||||
anchors = {}
|
||||
for r in rows:
|
||||
if r[1] == 'base': continue
|
||||
key = (r[0], norm(r[2].split()[-1]))
|
||||
if key in getters: anchors.setdefault(r[0], []).append((int(r[1], 16), getters[key] - int(r[1], 16)))
|
||||
with open(fout, 'w') as o:
|
||||
for r in rows:
|
||||
if r[1] != 'base' and r[0] in anchors:
|
||||
off = int(r[1], 16)
|
||||
below = [d for a, d in sorted(anchors[r[0]]) if a <= off]
|
||||
r[1] = '0x%x' % (off + (below[-1] if below else 0))
|
||||
o.write('\t'.join(r) + '\n')
|
||||
for c, a in sorted(anchors.items()):
|
||||
print(c, ' '.join('%x%+d' % x for x in sorted(a) if x[1]))
|
||||
@@ -0,0 +1,43 @@
|
||||
# Extracts the game's Lua API registrations from the decompiled corpus.
|
||||
# Usage: lua_bindings.py exe all.c out_dir -> lua_bindings.tsv (class, member, target addr or field offset)
|
||||
# lua_names.tsv (va, Class::Member, lua, decl) for ApplyNames
|
||||
import re, sys, os, struct
|
||||
exe, src, outdir = sys.argv[1:4]
|
||||
data = open(exe, 'rb').read()
|
||||
pe = struct.unpack_from('<I', data, 0x3c)[0]
|
||||
optsz = struct.unpack_from('<H', data, pe + 20)[0]
|
||||
base = struct.unpack_from('<I', data, pe + 52)[0]
|
||||
secs = [struct.unpack_from('<III', data, pe + 24 + optsz + 40 * i + 12) for i in range(struct.unpack_from('<H', data, pe + 6)[0])]
|
||||
def cstr(m): # short strings Ghidra left as &DAT_xxxxxxxx -> "literal"
|
||||
va = int(m.group(1), 16) - base
|
||||
for sva, rsz, raw in secs:
|
||||
if sva <= va < sva + rsz:
|
||||
off = raw + va - sva
|
||||
s = data[off:data.index(b'\0', off)]
|
||||
if 0 < len(s) < 40 and re.fullmatch(rb'\w+', s): return '"%s"' % s.decode()
|
||||
return m.group(0)
|
||||
classP = re.compile(r'\(\s*(?:local_\w+|&?[\w]+)\s*,\s*"([A-Z]\w+)"\s*\)|\(\s*"([A-Z]\w+)"\s*,\s*(?:[a-z]Var\d+|local_\w+)\s*\)')
|
||||
funcP = re.compile(r'\(\s*"(\w+)"\s*,\s*&?(?:FUN_|LAB_)([0-9a-f]{8})')
|
||||
namedP = re.compile(r'\(\s*"(\w+)"\s*,\s*([A-Za-z_][\w:]*::\w+)\s*[,)]')
|
||||
offP = re.compile(r'\(\s*"(\w+)"\s*,\s*(0x[0-9a-f]+|\d+)\s*,\s*1\s*\)')
|
||||
cls = None
|
||||
rows, names = [], []
|
||||
for line in open(src, errors='replace'):
|
||||
line = re.sub(r'&DAT_([0-9a-f]{8})', cstr, line)
|
||||
if line.startswith('//@@ '): cls = None; continue
|
||||
m = classP.search(line)
|
||||
if m: cls = m.group(1) or m.group(2); continue
|
||||
if not cls: continue
|
||||
m = funcP.search(line)
|
||||
if m:
|
||||
rows.append((cls, m.group(1), m.group(2)))
|
||||
names.append('%s\t%s::%s\tlua\tLua binding %s:%s\n' % (m.group(2), cls, m.group(1), cls, m.group(1)))
|
||||
continue
|
||||
m = namedP.search(line)
|
||||
if m: rows.append((cls, m.group(1), m.group(2))); continue
|
||||
m = offP.search(line)
|
||||
if m: rows.append((cls, m.group(1), 'field+0x%x' % int(m.group(2), 0)))
|
||||
with open(os.path.join(outdir, 'lua_bindings.tsv'), 'w') as o:
|
||||
for r in rows: o.write('\t'.join(r) + '\n')
|
||||
with open(os.path.join(outdir, 'lua_names.tsv'), 'w') as o: o.writelines(names)
|
||||
print(len(rows), 'bindings,', len(names), 'nameable')
|
||||
@@ -0,0 +1,20 @@
|
||||
# Regenerates the "Entity notes" table in notes/README.md from the "## " headings of notes/**/*.md.
|
||||
# A heading is indexed when it names an address (6-8 hex digits). Usage: notes_index.py notesdir
|
||||
import glob, os, re, sys
|
||||
d = sys.argv[1]
|
||||
rows = []
|
||||
for p in sorted(glob.glob(f'{d}/*/*.md')):
|
||||
if '/_tools/' in p: continue
|
||||
for line in open(p):
|
||||
if not line.startswith('## '): continue
|
||||
addrs = re.findall(r'\b(?:0x)?(00[4-9a][0-9a-f]{5}|[4-9a][0-9a-f]{5})\b', line)
|
||||
if not addrs: continue
|
||||
h = line[3:].strip().replace('|', '/')
|
||||
name = re.split(r'[:(—@]| - ', h)[0].strip(' .')
|
||||
rows.append(f"| {name} | {' '.join('0x' + a.lstrip('0') for a in dict.fromkeys(addrs))} | {h} | [{os.path.relpath(p, d)}]({os.path.relpath(p, d)}) |")
|
||||
readme = f'{d}/README.md'
|
||||
s = open(readme).read()
|
||||
a, b = s.index('<!-- index -->') + len('<!-- index -->'), s.index('<!-- /index -->')
|
||||
table = '\n| entity | address | heading (what the note covers, status) | file |\n|---|---|---|---|\n' + '\n'.join(sorted(rows, key=str.lower)) + '\n'
|
||||
open(readme, 'w').write(s[:a] + table + s[b:])
|
||||
print(f'notes_index: {len(rows)} rows')
|
||||
@@ -0,0 +1,16 @@
|
||||
# Usage: read_value.py exe VA -> int32 / float / double / string at a virtual address (for DAT_xxxxxxxx constants)
|
||||
import struct, sys
|
||||
data = open(sys.argv[1], 'rb').read()
|
||||
va = int(sys.argv[2], 16)
|
||||
pe = struct.unpack_from('<I', data, 0x3c)[0]
|
||||
optsz = struct.unpack_from('<H', data, pe + 20)[0]
|
||||
rva = va - struct.unpack_from('<I', data, pe + 52)[0]
|
||||
for i in range(struct.unpack_from('<H', data, pe + 6)[0]):
|
||||
sva, rsz, raw = struct.unpack_from('<III', data, pe + 24 + optsz + 40 * i + 12)
|
||||
if sva <= rva < sva + rsz:
|
||||
o = raw + rva - sva
|
||||
b = data[o:o + 8]
|
||||
s = data[o:data.index(b'\0', o)][:60]
|
||||
print('int32 %d uint32 0x%08x float %r double %r str %r' % (struct.unpack('<i', b[:4])[0], struct.unpack('<I', b[:4])[0], struct.unpack('<f', b[:4])[0], struct.unpack('<d', b)[0], s))
|
||||
break
|
||||
else: print('not in a file-backed section (uninitialised .data/.bss: runtime value)')
|
||||
@@ -0,0 +1,8 @@
|
||||
# Replaces one function's block in all.c with a separately decompiled one. Usage: splice.py all.c new.c
|
||||
import sys
|
||||
src, new = sys.argv[1:3]
|
||||
s, n = open(src).read(), open(new).read()
|
||||
if 'failed:' in n: sys.exit('still failed: ' + n[:200])
|
||||
i = s.index(n.split('\n')[0].rsplit(' ', 1)[0] + ' ') # "//@@ <addr> "
|
||||
j = s.find('\n//@@ ', i + 5) + 1 or len(s)
|
||||
open(src, 'w').write(s[:i] + n.rstrip('\n') + '\n\n' + s[j:])
|
||||
@@ -0,0 +1,102 @@
|
||||
# Matches libzhl signatures against the exe. Usage: zhl_match.py exe zhl_dir out.tsv
|
||||
# exact unique match -> "exact"; else longest unique prefix (>=20 bytes) -> "prefixN"
|
||||
import re, sys, struct, glob, os
|
||||
exe, zdir, out = sys.argv[1:4]
|
||||
data = open(exe, 'rb').read()
|
||||
pe = struct.unpack_from('<I', data, 0x3c)[0]
|
||||
nsec = struct.unpack_from('<H', data, pe + 6)[0]
|
||||
optsz = struct.unpack_from('<H', data, pe + 20)[0]
|
||||
base = struct.unpack_from('<I', data, pe + 24 + 28)[0]
|
||||
secs = []
|
||||
for i in range(nsec):
|
||||
o = pe + 24 + optsz + 40 * i
|
||||
va, rsz, raw = struct.unpack_from('<III', data, o + 12)
|
||||
secs.append((raw, raw + rsz, va))
|
||||
def to_va(off):
|
||||
for raw, end, va in secs:
|
||||
if raw <= off < end: return base + va + off - raw
|
||||
def rx(sig, n):
|
||||
return re.compile(b''.join(b'.' if sig[i:i+2] == '??' else re.escape(bytes([int(sig[i:i+2], 16)])) for i in range(0, n, 2)), re.S)
|
||||
def hits(sig, n, limit=2):
|
||||
r = []
|
||||
for m in rx(sig, n).finditer(data):
|
||||
r.append(m.start())
|
||||
if len(r) >= limit: break
|
||||
return r
|
||||
sigP = re.compile(r'^\s*"([0-9a-fA-F?]+)"\s*:\s*$')
|
||||
structP = re.compile(r'^\s*struct\s+(\w+)')
|
||||
nameP = re.compile(r'([A-Za-z_][\w:~]*)\s*\(')
|
||||
stats = {}
|
||||
rows = []
|
||||
if True:
|
||||
for f in sorted(glob.glob(os.path.join(zdir, '*.zhl'))):
|
||||
lines = open(f, errors='replace').read().split('\n')
|
||||
struct_ = None
|
||||
for i, l in enumerate(lines):
|
||||
m = structP.match(l)
|
||||
if m: struct_ = m.group(1)
|
||||
m = sigP.match(l)
|
||||
if not m: continue
|
||||
decl = ''
|
||||
j = i + 1
|
||||
while j < len(lines) and ';' not in decl: decl += lines[j].strip() + ' '; j += 1
|
||||
nm = nameP.search(re.sub(r'<[^>]*>', '', decl))
|
||||
if not nm: continue
|
||||
name = nm.group(1)
|
||||
if '::' not in name and struct_: name = struct_ + '::' + name
|
||||
sig = m.group(1)
|
||||
h = hits(sig, len(sig))
|
||||
q = 'exact' if len(h) == 1 else ('multi' if h else None)
|
||||
if not h:
|
||||
lo, hi = 40, len(sig) # binary search longest prefix with >=1 hit
|
||||
if len(sig) > lo and hits(sig, lo):
|
||||
while hi - lo > 2:
|
||||
mid = (lo + hi) // 4 * 2
|
||||
if hits(sig, mid): lo = mid
|
||||
else: hi = mid
|
||||
h = hits(sig, lo)
|
||||
q = 'prefix%d/%d' % (lo // 2, len(sig) // 2) if len(h) == 1 else 'multi'
|
||||
stats[(q or 'miss').split('/')[0][:6]] = stats.get((q or 'miss').split('/')[0][:6], 0) + 1
|
||||
if q and q != 'multi':
|
||||
rows.append((to_va(h[0]), name, q, decl.strip()))
|
||||
from collections import Counter
|
||||
dup = Counter(r[0] for r in rows)
|
||||
with open(out, 'w') as o:
|
||||
for r in rows:
|
||||
if dup[r[0]] > 1 and r[2] != 'exact': continue # prefix match collided with another name
|
||||
o.write('%08x\t%s\t%s\t%s\n' % r)
|
||||
print(stats)
|
||||
|
||||
# vtables: class \t slot \t name (slot names come from decls or "skip; // Name" comments)
|
||||
with open(os.path.join(os.path.dirname(out), 'zhl_vtables.tsv'), 'w') as o:
|
||||
for f in sorted(glob.glob(os.path.join(zdir, '*.zhl'))):
|
||||
txt = open(f, errors='replace').read()
|
||||
for m in re.finditer(r'struct\s+(\w+)[^{]*\{(.*?)__vtable\s*\{(.*?)\n\s*\};', txt, re.S):
|
||||
cls, body = m.group(1), m.group(3)
|
||||
body = re.sub(r'"[^"]*"\s*:', '', body)
|
||||
entries = re.findall(r'\s*(skip\s*;[^\n]*|[^;]*?;)', body, re.S)
|
||||
slot = 0
|
||||
for e in entries:
|
||||
e = e.strip()
|
||||
if not e: continue
|
||||
if e.startswith('skip'):
|
||||
nm = re.search(r'//\s*(\w+)', e)
|
||||
name = nm.group(1) if nm else None
|
||||
else:
|
||||
nm = nameP.search(re.sub(r'<[^>]*>', '', e))
|
||||
name = nm.group(1) if nm else None
|
||||
if name and name != 'skip': o.write('%s\t%d\t%s\n' % (cls, slot, name))
|
||||
slot += 1
|
||||
|
||||
# struct fields from zhl: struct \t offset \t type name
|
||||
with open(os.path.join(os.path.dirname(out), 'zhl_fields.tsv'), 'w') as o:
|
||||
for f in sorted(glob.glob(os.path.join(zdir, '*.zhl'))):
|
||||
struct_ = None
|
||||
for l in open(f, errors='replace'):
|
||||
m = structP.match(l)
|
||||
if m:
|
||||
struct_ = m.group(1)
|
||||
b = re.search(r':\s*public\s+(\w+)', l)
|
||||
if b: o.write('%s\tbase\t%s\n' % (struct_, b.group(1)))
|
||||
m = re.match(r'^\s*([\w:<>,\s\*&]+?)\s*:\s*(0x[0-9a-fA-F]+)\s*;', l)
|
||||
if m and struct_: o.write('%s\t%s\t%s\n' % (struct_, m.group(2).lower(), ' '.join(m.group(1).split())))
|
||||
Reference in new issue
Block a user