SWE-agent takes a GitHub issue and tries to automatically fix it, using your LM of choice. It can also be employed for offensive cybersecurity or competitive coding challenges. [NeurIPS 2024]
Automatically detect `main` function in Ghidra output
Meet Udeshicc6cc8f1e282
diff --git a/config/commands/decompile.py b/config/commands/decompile.pyindex c4978605..bcc99c7a 100644--- a/config/commands/decompile.py+++ b/config/commands/decompile.py@@ -25,7 +25,7 @@ GHIDRA_BINARY = "analyzeHeadless"class Decompile:def __init__(self):- self._decomp_cache = {}+ passdef __call__(self,path: Annotated[str,"path to the binary to decompile"],@@ -38,38 +38,46 @@ class Decompile:return self.decompile(path, function)def find_function(self, dis, function):+ """Returns the name of the function found in the dict"""if function in dis["functions"]:- return dis["functions"][function]+ return function# Looking for main entry point, so try other names alsoif function == "main":+ if "main" in dis:+ return dis["main"]if "_start" in dis["functions"]:- return dis["functions"]["_start"]+ return "_start"if "invoke_main" in dis["functions"]:- return dis["functions"]["invoke_main"]+ return "invoke_main"+ if "entry" in dis["functions"]:+ return "entry"# Check if requesting radare2 unnamed function with addressif re.match(r"fcn\.[0-9a-f]+$", function):addr = function[4:]if addr in dis["addresses"]:- return dis["functions"][dis["addresses"][addr]]+ return dis["addresses"][addr]# Nothing foundreturn Nonedef decompile(self, binary, function):# Look for the decompilation output in "decomp"basename = Path(binary).name- if basename not in self._decomp_cache:- decomp_output = Path(f"decomp/{basename}.decomp.json")- if decomp_output.exists():- self._decomp_cache[basename] = json.loads(decomp_output.read_text())- else:- if not self.run_ghidra(basename, decomp_output):- return f"Error: Decompilation for {binary} not available"- self._decomp_cache[basename] = json.loads(decomp_output.read_text())+ decomp_output = Path(f"ghidra_out/{basename}.decomp.json")+ if not decomp_output.exists():+ if not self.run_ghidra(basename, decomp_output):+ return f"Error: Decompilation for {binary} not available"+ self.ghidra_out = json.loads(decomp_output.read_text())- if found := self.find_function(self._decomp_cache[basename], function):- return f"Decompilation Found!\n{found}"+ if found := self.find_function(self.ghidra_out, function):+ ret = self.ghidra_out["functions"][found]+ if found == function:+ # Exact name found+ return f"Decompilation Found!\n{ret}"+ else:+ return f"Function {function} not found! Instead, here is the decompilation of equivalent function {found}:\n{ret}"else:- return f"Error: Function {function} not found in {binary}.\nThese are the available functions found: {", ".join(self._decomp_cache[basename]['functions'].keys())}"+ funclist = ", ".join(self.ghidra_out['functions'].keys())+ return f"Error: Function {function} not found in {binary}.\nThese are the available functions found: {funclist}"def run_ghidra(self, binary, output):real_binary = Path(binary)diff --git a/config/commands/disassemble.py b/config/commands/disassemble.pynew file mode 100644index 00000000..13ec1504--- /dev/null+++ b/config/commands/disassemble.py@@ -0,0 +1,104 @@+#!/root/miniconda3/bin/python++# @yaml+# signature: disassemble <binary_path> <function_name>+# docstring: Disassembles a binary and prints the disassembly of a given function name+# arguments:+# binary_path:+# type: file path+# description: The path to the binary to be disassembled+# required: true+# function_name:+# type: string+# description: The function name to be disassembled, or main by default+# required: false++import argparse+import subprocess+import re+import json+import tempfile+from typing import Annotated+from pathlib import Path++GHIDRA_BINARY = "analyzeHeadless"++class Disassemble:+ def __init__(self):+ pass++ def __call__(self,+ path: Annotated[str,"path to the binary to disassemble"],+ function: Annotated[str,"the function to disassemble"] = 'main'):+ """Disassemble a function from a binary using Ghidra."""+ if path is None or not Path(path).is_file():+ return f"Error: Binary {path} does not exist! Please try again with a real binary file."+ if function is None:+ function = "main"+ return self.disassemble(path, function)++ def find_function(self, dis, function):+ """Returns the name of the function found in the dict"""+ if function in dis["functions"]:+ return function+ # Looking for main entry point, so try other names also+ if function == "main":+ if "main" in dis:+ return dis["main"]+ if "_start" in dis["functions"]:+ return "_start"+ if "invoke_main" in dis["functions"]:+ return "invoke_main"+ if "entry" in dis["functions"]:+ return "entry"+ # Check if requesting radare2 unnamed function with address+ if re.match(r"fcn\.[0-9a-f]+$", function):+ addr = function[4:]+ if addr in dis["addresses"]:+ return dis["addresses"][addr]+ # Nothing found+ return None++ def disassemble(self, binary, function):+ # Look for the disassembly output in "disas"+ basename = Path(binary).name+ disas_output = Path(f"ghidra_out/{basename}.disas.json")+ if not disas_output.exists():+ if not self.run_ghidra(basename, disas_output):+ return f"Error: Disassembly for {binary} not available"+ self.ghidra_out = json.loads(disas_output.read_text())++ if found := self.find_function(self.ghidra_out, function):+ ret = self.ghidra_out["functions"][found]+ if found == function:+ # Exact name found+ return f"Disassembly Found!\n{ret}"+ else:+ return f"Function {function} not found! Instead, here is the disassembly of equivalent function {found}:\n{ret}"+ else:+ funclist = ", ".join(self.ghidra_out["functions"].keys())+ return f"Error: Function {function} not found in {binary}.\nThese are the available functions found: {funclist}"++ def run_ghidra(self, binary, output):+ real_binary = Path(binary)+ if not real_binary or not real_binary.exists():+ return False+ output.parent.mkdir(parents=True, exist_ok=True)+ with tempfile.TemporaryDirectory() as tmpdir:+ tmpdir = Path(tmpdir)+ subprocess.run(+ [GHIDRA_BINARY, tmpdir, "DummyProj", "-scriptpath", '/ghidra_scripts',+ "-import", real_binary, "-postscript", "DisassembleToJson.java", output],+ check=False, capture_output=True,+ )+ return output.exists()+++if __name__ == "__main__":+ parser = argparse.ArgumentParser(+ description="Print the contents of a Python file, skipping lengthy function and method definitions."+ )+ parser.add_argument("file_path", type=str, help="The path to the binary to be disassembled")+ parser.add_argument("--function_name", type=str, help="The function name to be disassembled", required=False, default="main")+ args = parser.parse_args()+ print(Disassemble()(args.file_path, args.function_name))diff --git a/docker/ghidra_scripts/DecompileToJson.java b/docker/ghidra_scripts/DecompileToJson.javaindex 60b8b709..cbcc5ded 100644--- a/docker/ghidra_scripts/DecompileToJson.java+++ b/docker/ghidra_scripts/DecompileToJson.java@@ -19,9 +19,21 @@ public class DecompileToJson extends GhidraScript {log = LogManager.getLogger(DecompileToJson.class);}+ public String find_main(HashMap<String, String> function_map) {+ // Find the `main` function from the `__libc_start_main` call+ if (!function_map.containsKey("entry")) return null;+ String entry = function_map.get("entry");+ int libc = entry.indexOf("__libc_start_main(");+ if (libc == -1) return null;+ int funcend = entry.indexOf(',', libc);+ if (funcend == -1) return null;+ return entry.substring(libc + 18, funcend);+ }+public void export(String filename) {Gson gson = new GsonBuilder().setPrettyPrinting().create();File outputFile = new File(filename);+ String main_func = null;HashMap<String, String> function_map = new HashMap<String, String>();HashMap<String, String> address_map = new HashMap<String, String>();DecompInterface ifc = new DecompInterface();@@ -39,9 +51,15 @@ public class DecompileToJson extends GhidraScript {System.out.println(func.getName());}- HashMap<String, HashMap<String, String>> json_data = new HashMap<String, HashMap<String, String>>();+ if (!function_map.containsKey("main"))+ main_func = find_main(function_map);++ //HashMap<String, HashMap<String, String>> json_data = new HashMap<String, HashMap<String, String>>();+ HashMap<String, Object> json_data = new HashMap<String, Object>();json_data.put("functions", function_map);json_data.put("addresses", address_map);+ if (main_func != null)+ json_data.put("main", main_func);// Convert the HashMap to JSONString json = gson.toJson(json_data);@@ -58,4 +76,4 @@ public class DecompileToJson extends GhidraScript {String[] args = getScriptArgs();export(args[0]);}-}\ No newline at end of file+}diff --git a/docker/ghidra_scripts/DisassembleToJson.java b/docker/ghidra_scripts/DisassembleToJson.javaindex 80dbd24a..214dff01 100644--- a/docker/ghidra_scripts/DisassembleToJson.java+++ b/docker/ghidra_scripts/DisassembleToJson.java@@ -105,11 +105,45 @@ public class DisassembleToJson extends GhidraScript {return offsetStr;}+ public String find_main(HashMap<String, String> function_map) {+ // Find the `main` function from the `__libc_start_main` call+ if (!function_map.containsKey("entry")) return null;+ String entry = function_map.get("entry");+ int libc = entry.indexOf("CALL <EXTERNAL>::__libc_start_main");+ if (libc == -1) {+ // Does not have symbol for __libc_start_main+ // These two instructions are checked:+ // PUSH <func-ptr>+ // CALL <start-func>+ // The <func-ptr> is the main function.+ libc = entry.indexOf("CALL FUN_");+ if (libc == -1) return null;+ entry = entry.substring(0, libc);+ int push = entry.lastIndexOf("PUSH FUN_");+ if (push == -1) return null;+ int funcend = entry.indexOf('\n', push);+ return entry.substring(push + 12, funcend);+ } else {+ // Has symbol for __libc_start_main+ // These two instructions are checked:+ // MOV RDI,<func-ptr>+ // CALL EXTERNAL::__libc_start_main+ // The <func-ptr> is the main function.+ entry = entry.substring(0, libc);+ int rdi = entry.lastIndexOf("MOV RDI,");+ if (rdi == -1) return null;+ int funcend = entry.indexOf('\n', rdi);+ if (funcend == -1) return null;+ return entry.substring(rdi + 16, funcend);+ }+ }+public void export(String filename) {Gson gson = new GsonBuilder().setPrettyPrinting().create();File outputFile = new File(filename);HashMap<String, String> function_map = new HashMap<String, String>();HashMap<String, String> address_map = new HashMap<String, String>();+ String main_func = null;// Formatter for disassembled codeTemplateSimplifier simplifier = new TemplateSimplifier();@@ -241,9 +275,14 @@ public class DisassembleToJson extends GhidraScript {address_map.put(func.getEntryPoint().toString(), func.getName());}- HashMap<String, HashMap<String, String>> json_data = new HashMap<String, HashMap<String, String>>();+ if (!function_map.containsKey("main"))+ main_func = find_main(function_map);++ HashMap<String, Object> json_data = new HashMap<String, Object>();json_data.put("functions", function_map);json_data.put("addresses", address_map);+ if (main_func != null)+ json_data.put("main", main_func);// Convert the HashMap to JSONString json = gson.toJson(json_data);@@ -260,4 +299,4 @@ public class DisassembleToJson extends GhidraScript {String[] args = getScriptArgs();export(args[0]);}-}\ No newline at end of file+}