Files
isaac-port/scripts/ApplyTypes.java
T
shweetandClaude Opus 5.5 3f1e276667 ApplyTypes: a field of unknown type (std_map, DeathmatchManager) names its first dword instead of being dropped
Shows &g_game->_deathmatchManager (462 uses of field_0x26614) and lets ItemConfig grow past a 4-byte stub, so Manager
accesses read (g_manager->_itemConfig).field_0xc. Takes effect on the next build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 17:52:42 -04:00

143 lines
8.8 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*.
// Args: merged fields.tsv [this_types.tsv: methods whose ECX use fits their class]
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() >= 4 ? d : null; // placeholder structs (EntityPtr) too: a name beats field_0x
}
void addFields(StructureDataType s, String cls, int depth) {
if (depth > 8) return;
if (base.containsKey(cls)) addFields(s, base.get(cls), depth + 1);
List<String[]> own = new ArrayList<>(fields.getOrDefault(cls, List.of()));
own.sort(Comparator.comparingInt(f -> Integer.decode(f[1]))); // in offset order, so an embedded struct beats views into it
for (int i = 0; i < own.size(); i++) {
String[] f = own.get(i);
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);
int off = Integer.decode(f[1]);
int room = i + 1 < own.size() ? Integer.decode(own.get(i + 1)[1]) - off : 4;
if (dt == null && !arr.find(0) && room > 0) // unknown type (std_map, DeathmatchManager): name its first dword
dt = room >= 4 ? Undefined4DataType.dataType : new ArrayDataType(ByteDataType.dataType, room, 1);
else if (dt != null && arr.find(0)) dt = new ArrayDataType(dt, Integer.decode(arr.group(1)), dt.getLength());
if (dt == null) continue;
String nm = decl.trim().replaceAll(".*\\s", "").replaceAll("[^\\w]", "");
try {
DataTypeComponent in = off < s.getLength() ? s.getComponentContaining(off) : null;
if (in != null && in.getOffset() != off && in.getDataType() != DataType.DEFAULT) continue; // inside a placed member (Entity 0xdc is _sprite._offset): keep the member
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++;
}
}
// Lua aliases: the Lua Sprite and Color classes are ANM2 and ColorMod, so their methods' `this` gets that layout
for (String[] al : new String[][] {{"Sprite", "ANM2"}, {"Color", "ColorMod"}}) {
DataType t = dtm.getDataType(new CategoryPath("/"), al[1]);
if (!(t instanceof Structure)) continue;
Structure copy = (Structure) t.copy(dtm);
copy.setName(al[0]);
dtm.addDataType(copy, DataTypeConflictHandler.REPLACE_HANDLER);
}
// methods whose ECX offsets fit their class (scripts/this_types.py) become __thiscall, typing `this`
int fitted = 0;
if (getScriptArgs().length > 1) for (String l : Files.readAllLines(Paths.get(getScriptArgs()[1]))) {
Function f = getFunctionAt(toAddr(l.split("\t")[0]));
if (f == null || "__thiscall".equals(f.getCallingConventionName())) continue;
Namespace ns = f.getParentNamespace();
if (!(ns instanceof GhidraClass)) try { st.convertNamespaceToClass(ns); } catch (Exception e) { continue; }
f.setCallingConvention("__thiscall");
fitted++;
}
// per-type AI routines take the entity in ECX: NpcAI (dispatcher) and FamiliarAI (Entity_Familiar::Update cases,
// their ECX reads all land in Entity_Familiar fields); FamiliarAI ones with stack arguments are left alone
int ain = 0;
for (String[] ai : new String[][] {{"NpcAI", "Entity_NPC", "npc"}, {"FamiliarAI", "Entity_Familiar", "familiar"}}) {
DataType npcPtr = new PointerDataType(dtm.getDataType(new CategoryPath("/"), ai[1]));
Namespace aiNs = st.getNamespace(ai[0], global);
if (aiNs != null) for (Symbol sym : st.getSymbols(aiNs)) {
Function f = getFunctionAt(sym.getAddress());
if (f == null || (ai[0].equals("FamiliarAI") && f.getStackPurgeSize() != 0)) continue;
f.setCallingConvention("__fastcall");
f.replaceParameters(Function.FunctionUpdateType.DYNAMIC_STORAGE_FORMAL_PARAMS, true, SourceType.USER_DEFINED,
new ParameterImpl(ai[2], npcPtr, currentProgram));
ain++;
}
}
println("ApplyTypes: " + classes.size() + " structs, " + typed + " thiscall methods, " + fitted + " fitted by ECX use, " + ain + " NpcAI/FamiliarAI params");
}
}