DecompileToJson.java 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import java.io.File;
  2. import java.io.FileWriter;
  3. import java.io.IOException;
  4. import java.util.HashMap;
  5. import org.apache.logging.log4j.LogManager;
  6. import org.apache.logging.log4j.Logger;
  7. import ghidra.app.script.GhidraScript;
  8. import ghidra.app.decompiler.DecompInterface;
  9. import ghidra.app.decompiler.DecompileResults;
  10. import com.google.gson.*;
  11. public class DecompileToJson extends GhidraScript {
  12. private static Logger log;
  13. public DecompileToJson() {
  14. log = LogManager.getLogger(DecompileToJson.class);
  15. }
  16. public String find_main(HashMap<String, String> function_map) {
  17. // Find the `main` function from the `__libc_start_main` call
  18. if (!function_map.containsKey("entry")) return null;
  19. String entry = function_map.get("entry");
  20. int libc = entry.indexOf("__libc_start_main(");
  21. if (libc == -1) return null;
  22. int funcend = entry.indexOf(',', libc);
  23. if (funcend == -1) return null;
  24. return entry.substring(libc + 18, funcend);
  25. }
  26. public void export(String filename) {
  27. Gson gson = new GsonBuilder().setPrettyPrinting().create();
  28. File outputFile = new File(filename);
  29. String main_func = null;
  30. HashMap<String, String> function_map = new HashMap<String, String>();
  31. HashMap<String, String> address_map = new HashMap<String, String>();
  32. DecompInterface ifc = new DecompInterface();
  33. ifc.openProgram(currentProgram);
  34. for (var func : currentProgram.getListing().getFunctions(Boolean.TRUE)) {
  35. DecompileResults res = ifc.decompileFunction(func,0,monitor);
  36. if (!res.decompileCompleted()) {
  37. System.err.println(res.getErrorMessage());
  38. continue;
  39. }
  40. String code = res.getDecompiledFunction().getC();
  41. function_map.put(func.getName(), code);
  42. address_map.put(func.getEntryPoint().toString(), func.getName());
  43. System.out.println(func.getName());
  44. }
  45. if (!function_map.containsKey("main"))
  46. main_func = find_main(function_map);
  47. //HashMap<String, HashMap<String, String>> json_data = new HashMap<String, HashMap<String, String>>();
  48. HashMap<String, Object> json_data = new HashMap<String, Object>();
  49. json_data.put("functions", function_map);
  50. json_data.put("addresses", address_map);
  51. if (main_func != null)
  52. json_data.put("main", main_func);
  53. // Convert the HashMap to JSON
  54. String json = gson.toJson(json_data);
  55. // Write JSON to file
  56. try (FileWriter writer = new FileWriter(outputFile)) {
  57. writer.write(json);
  58. } catch (IOException e) {
  59. e.printStackTrace();
  60. }
  61. }
  62. @Override
  63. public void run() throws Exception {
  64. String[] args = getScriptArgs();
  65. export(args[0]);
  66. }
  67. }