How do i export the binary code of a function in Ghidra (Ghidra script)

1.6k views Asked by At

I want to write a ghidra script in python (jython) that exports to a .bin file the binary code of all the functions in the current program.

I came up with this code but i am not sure how i should use the export() function in the BinaryExporter class

Function signature: export(java.io.File file, DomainObject domainObj, AddressSetView addrSet, TaskMonitor monitor)

How should i fill in the arguments? Is there a better way to do that?

from ghidra.app.util.exporter import BinaryExporter


function_ASVs = [] #all functions address set view
exporter = BinaryExporter()

fm = currentProgram.getFunctionManager()
functions = fm.getFunctions(True)
for f in functions:
    function_ASVs.append(f.getBody())


with open("C:\Users\Me\Desktop\target_file.bin", "w") as f:
    for asv in function_ASVs:
        ret = exporter.export(f, currentProgram, asv, ???)
1

There are 1 answers

0
j-ratz On

monitor is a field that GhidraScript inherits from FlatProgramAPI. The ??? in your question should be monitor.

I don't use python, but I think you could condense your script to something like:

from ghidra.app.util.exporter import BinaryExporter

asv = AddressSet()
exporter = BinaryExporter()

for f in currentProgram.getFunctionManager().getFunctions(True):
    asv.add(f.getBody())

with open("C:\Users\Me\Desktop\target_file.bin", "w") as f:
    ret = exporter.export(f, currentProgram, asv, monitor)