Files
neoLegacy-mac/tools/ghidra/ExportDecompiled.java

75 lines
3.0 KiB
Java

// Export every analyzed function in the current program as one C translation unit.
// @category Iggy
import ghidra.app.decompiler.DecompInterface;
import ghidra.app.decompiler.DecompileResults;
import ghidra.app.script.GhidraScript;
import ghidra.program.model.listing.Function;
import ghidra.program.model.listing.FunctionIterator;
import java.io.File;
import java.io.PrintWriter;
public class ExportDecompiled extends GhidraScript {
@Override
protected void run() throws Exception {
String[] args = getScriptArgs();
if (args.length != 1) {
throw new IllegalArgumentException("expected output directory");
}
File outputDirectory = new File(args[0]);
if (!outputDirectory.isDirectory() && !outputDirectory.mkdirs()) {
throw new IllegalStateException("could not create " + outputDirectory);
}
String programName = currentProgram.getName();
String sourceName = programName.replaceAll("(?i)\\.obj$", "") + ".c";
File output = new File(outputDirectory, sourceName);
DecompInterface decompiler = new DecompInterface();
decompiler.toggleCCode(true);
decompiler.toggleSyntaxTree(true);
if (!decompiler.openProgram(currentProgram)) {
throw new IllegalStateException("decompiler rejected " + programName);
}
int exported = 0;
int failed = 0;
try (PrintWriter writer = new PrintWriter(output, "UTF-8")) {
writer.println("/* Recovered from " + programName + " by Ghidra " + getGhidraVersion() + ". */");
writer.println("/* Function and variable types are provisional until reconciled with the Iggy headers. */");
writer.println();
FunctionIterator functions = currentProgram.getFunctionManager().getFunctions(true);
for (Function function : functions) {
if (monitor.isCancelled()) {
break;
}
if (function.isExternal()) {
continue;
}
writer.println("/* " + function.getEntryPoint() + " " + function.getName(true) + " */");
if (function.getComment() != null && !function.getComment().isEmpty()) {
writer.println("/* " + function.getComment().replace("*/", "* /") + " */");
}
DecompileResults result = decompiler.decompileFunction(function, 180, monitor);
if (result.decompileCompleted() && result.getDecompiledFunction() != null) {
writer.println(result.getDecompiledFunction().getC());
exported++;
} else {
writer.println("/* DECOMPILATION FAILED: " + result.getErrorMessage() + " */");
failed++;
}
writer.println();
}
} finally {
decompiler.dispose();
}
println("Exported " + exported + " functions from " + programName +
" to " + output + " (" + failed + " failed)");
}
}