ApplyTypes: std_vector/string/deque/map/set/list members get MSVC layouts (_begin/_end/_capacity ...), structs used as a member type are built even when small (BitSet128 _tearFlags._l, KColor, RNG were dropped), structs padded to a multiple of 4 (PlayerCostumeMap stride 0x10). headers.py prints STL members at their real size and pads to the alignment. Round 6: 99 fields (Manager ItemConfig lists/InfoDisplay/lobby settings, Game transitions/PreloadManager, PersistentGameData arrays, HomingLaser, EntityList), 500 names, 6 corrections (Menu_Challenge::Render, Level::compute_room_distances, ...). 9622 FUN_ left, in_ECX + 0x 17363 -> 16720. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
165 lines
11 KiB
Java
165 lines
11 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 c = container(t);
|
|
if (c != null) return c;
|
|
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
|
|
}
|
|
|
|
DataType container(String t) { // MSVC STL layouts, so v._end - v._begin reads as such instead of field_0x4 - field_0x0
|
|
String kind = t.startsWith("std_string") ? "string" : t.replaceFirst("^(std_)?(vector|deque|map|set|multiset|multimap|list)_.*", "$2");
|
|
String[] m = switch (kind) {
|
|
case "string" -> new String[] {"_size", "_capacity"};
|
|
case "vector" -> new String[] {"_begin", "_end", "_capacity"};
|
|
case "deque" -> new String[] {"_proxy", "_map", "_mapSize", "_offset", "_size"};
|
|
case "map", "set", "multiset", "multimap", "list" -> new String[] {"_head", "_size"};
|
|
default -> null;
|
|
};
|
|
if (m == null) return null;
|
|
StructureDataType s = new StructureDataType("std_" + kind, 0);
|
|
if (kind.equals("string")) s.add(new ArrayDataType(CharDataType.dataType, 16, 1), "_buf", null); // or a char* past 15
|
|
for (String f : m)
|
|
s.add(kind.equals("string") || f.matches("_size|_mapSize|_offset") ? UnsignedIntegerDataType.dataType : new PointerDataType(VoidDataType.dataType), f, null);
|
|
return dtm.addDataType(s, DataTypeConflictHandler.REPLACE_HANDLER);
|
|
}
|
|
|
|
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> used = new HashSet<>(); // struct names used as a member type
|
|
for (List<String[]> fl : fields.values()) for (String[] f : fl) used.add(f[2].replaceAll("\\[.*", "").replace("const ", "").trim().replaceAll("\\s+\\w+$", ""));
|
|
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() % 4 != 0) s.growStructure(4 - s.getLength() % 4); // MSVC pads to the alignment: arrays of it get the real stride
|
|
if (s.getLength() < 0x20 && !methodClasses.contains(cls) && !used.contains(cls)) continue; // skip trivial structs, not member types (BitSet128)
|
|
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");
|
|
}
|
|
}
|