// Applies db/globals.tsv (address, name, C type, evidence): labels the global and lays down its type, so a Game* global // makes every access read g_game->_field. Types: primitives, a struct name, or pointers to them ("Game*"). Arg: globals.tsv import ghidra.app.script.GhidraScript; import ghidra.program.model.address.Address; import ghidra.program.model.data.*; import ghidra.program.model.symbol.SourceType; import java.nio.file.*; public class ApplyGlobals extends GhidraScript { DataType type(DataTypeManager dtm, String t) { t = t.replace("const ", "").trim(); int ptr = 0; while (t.endsWith("*")) { ptr++; t = t.substring(0, t.length() - 1).trim(); } DataType b; switch (t) { case "void": b = VoidDataType.dataType; break; case "bool": case "char": case "uint8_t": case "int8_t": b = ByteDataType.dataType; break; case "short": case "uint16_t": case "int16_t": b = ShortDataType.dataType; break; case "int": case "int32_t": b = IntegerDataType.dataType; break; case "uint32_t": case "unsigned int": b = UnsignedIntegerDataType.dataType; break; case "float": b = FloatDataType.dataType; break; case "double": b = DoubleDataType.dataType; break; case "uint64_t": case "int64_t": b = QWordDataType.dataType; break; default: b = dtm.getDataType(new CategoryPath("/"), t); } if (b == null) b = ptr > 0 ? VoidDataType.dataType : null; if (b == null) return null; for (int i = 0; i < ptr; i++) b = new PointerDataType(b); return b; } public void run() throws Exception { DataTypeManager dtm = currentProgram.getDataTypeManager(); int n = 0, typed = 0; for (String line : Files.readAllLines(Paths.get(getScriptArgs()[0]))) { if (line.isBlank() || line.startsWith("#")) continue; String[] c = line.split("\t"); Address a = toAddr(c[0].replace("0x", "")); createLabel(a, c[1], true, SourceType.USER_DEFINED); n++; DataType t = c.length > 2 ? type(dtm, c[2]) : null; if (t == null || t instanceof VoidDataType) continue; try { clearListing(a, a.add(t.getLength() - 1)); createData(a, t); typed++; } catch (Exception e) { println("ApplyGlobals: cannot type " + c[0] + " as " + c[2] + ": " + e.getMessage()); } } println("ApplyGlobals: " + n + " globals, " + typed + " typed"); } }