114 lines
6.3 KiB
Java
114 lines
6.3 KiB
Java
// 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;
|
|
}
|
|
DataType d = dtm.getDataType(new CategoryPath("/"), t); // embedded struct built by an earlier pass
|
|
return d instanceof Structure && d.getLength() >= 0x20 ? d : 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())) {
|
|
java.util.regex.Matcher arr = java.util.regex.Pattern.compile("\\[(\\w+)\\]\\s*$").matcher(f[2]); // "int _trinketsID[2]"
|
|
String decl = arr.find() ? f[2].substring(0, arr.start()) : f[2];
|
|
DataType dt = prim(decl);
|
|
if (dt == null) continue;
|
|
if (arr.find(0)) dt = new ArrayDataType(dt, Integer.decode(arr.group(1)), dt.getLength());
|
|
int off = Integer.decode(f[1]);
|
|
String nm = decl.trim().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());
|
|
// classes with ZHL __thiscall methods get a struct even with no confirmed field, so `this` is still typed
|
|
Set<String> methodClasses = new HashSet<>();
|
|
for (Function f : currentProgram.getListing().getFunctions(true)) {
|
|
String cm = f.getComment();
|
|
if (cm != null && cm.contains("__thiscall") && !f.getParentNamespace().isGlobal()) methodClasses.add(f.getParentNamespace().getName());
|
|
}
|
|
classes.addAll(methodClasses);
|
|
int typed = 0;
|
|
for (int pass = 0; pass < 3; pass++) // later passes embed structs (Entity._sprite is an ANM2) built by earlier ones
|
|
for (String cls : classes) {
|
|
StructureDataType s = new StructureDataType(cls, 4);
|
|
addFields(s, cls, 0);
|
|
if (s.getLength() < 0x20 && !methodClasses.contains(cls)) 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 (pass < 2) continue;
|
|
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");
|
|
}
|
|
}
|