// SPDX-License-Identifier: BSD-3-Clause // // DecompileAt.java - Ghidra post-script: decompile the function containing a // given address (no auto-analysis required). // // Usage (via scripts/ghidra_decompile.sh): // analyzeHeadless -import -noanalysis \ // -postScript DecompileAt.java [outfile] import ghidra.app.script.GhidraScript; import ghidra.app.decompiler.DecompInterface; import ghidra.app.decompiler.DecompileResults; import ghidra.program.model.address.Address; import ghidra.program.model.listing.Function; import java.io.FileWriter; public class DecompileAt extends GhidraScript { @Override public void run() throws Exception { String[] args = getScriptArgs(); if (args.length < 1) { println("usage: DecompileAt.java [outfile]"); return; } long target = Long.parseUnsignedLong(args[0].replaceFirst("^0x", ""), 16); Address addr = toAddr(target); Function f = getFunctionContaining(addr); if (f == null) { disassemble(addr); f = createFunction(addr, null); } if (f == null) { println("// no function at 0x" + Long.toHexString(target)); return; } DecompInterface dif = new DecompInterface(); dif.toggleCCode(true); dif.toggleSyntaxTree(true); dif.openProgram(currentProgram); DecompileResults res = dif.decompileFunction(f, 120, monitor); StringBuilder sb = new StringBuilder(); sb.append("// function ").append(f.getName()) .append(" at 0x").append(Long.toHexString(f.getEntryPoint().getOffset())) .append(" containing 0x").append(Long.toHexString(target)).append("\n"); if (res != null && res.decompileCompleted()) { sb.append(res.getDecompiledFunction().getC()); } else { sb.append("// decompilation failed\n"); } String text = sb.toString(); if (args.length > 1) { try (FileWriter w = new FileWriter(args[1])) { w.write(text); } } println(text); } }