// Applies db/locals.tsv (function address, decompiler local name, new name [, C type]) by decompiling each listed // function and committing the renamed HighVariable to the database, so later decompiles keep the name. Arg: locals.tsv import ghidra.app.script.GhidraScript; import ghidra.app.decompiler.*; import ghidra.program.model.data.*; import ghidra.program.model.listing.*; import ghidra.program.model.pcode.*; import ghidra.program.model.symbol.SourceType; import ghidra.util.data.DataTypeParser; import java.nio.file.*; import java.util.*; public class ApplyLocals extends GhidraScript { public void run() throws Exception { Map> byFn = new LinkedHashMap<>(); for (String line : Files.readAllLines(Paths.get(getScriptArgs()[0]))) { if (line.isBlank() || line.startsWith("#")) continue; String[] c = line.split("\t"); byFn.computeIfAbsent(String.format("%08x", Long.parseLong(c[0].replace("0x", ""), 16)), k -> new ArrayList<>()).add(c); } DecompInterface di = new DecompInterface(); DecompileOptions opts = new DecompileOptions(); opts.setMaxPayloadMBytes(1024); opts.setMaxInstructions(400000); // UseCard exceeds the 100k default ("Bad instruction count exceeded") di.setOptions(opts); di.openProgram(currentProgram); DataTypeParser parser = new DataTypeParser(currentProgram.getDataTypeManager(), null, null, DataTypeParser.AllowedDataTypes.ALL); int n = 0; for (var e : byFn.entrySet()) { Function f = getFunctionAt(toAddr(e.getKey())); DecompileResults r = f == null ? null : di.decompileFunction(f, 900, monitor); if (r == null || !r.decompileCompleted()) { println("ApplyLocals: cannot decompile " + e.getKey() + (r == null ? "" : ": " + r.getErrorMessage())); continue; } Map syms = new HashMap<>(); for (Iterator it = r.getHighFunction().getLocalSymbolMap().getSymbols(); it.hasNext(); ) { HighSymbol s = it.next(); syms.put(s.getName(), s); } for (String[] c : e.getValue()) { if (syms.containsKey(c[2])) continue; // already applied HighSymbol s = syms.get(c[1]); if (s == null) { println("ApplyLocals: " + e.getKey() + " has no local " + c[1]); continue; } DataType t = c.length > 3 && !c[3].isBlank() ? parser.parse(c[3]) : null; HighFunctionDBUtil.updateDBVariable(s, c[2], t, SourceType.USER_DEFINED); n++; } } di.dispose(); println("ApplyLocals: " + n + " locals"); } }