This post shortly gives a few examples to get started with scripting Ghidra using Python.
Where to get help
- look at the online API
- use the Python interpreter directly available in Ghidra (Window -> Python) and use
help(...)
- hit
F1
inside the Python interpreter
How to run a script
Open the script manager (Window -> Script Manager) and create a new Python script.
If developping your script outside of Ghidra, make sure to hit the refresh
button before re-running the script in Ghidra.
How to code
Some available objects:
currentProgram
: the current active programcurrentAddress
: the address where the cursor ismonitor
: a task monitor to allow user to interact with the script
Below are a few snippets that could be helpful for getting started in Ghidra scripting with Python.
Find function's entry point from an address
value = 0x7ff7cf42b901
## transform to a Ghidra Address object
addr = toAddr(value)
## get the containing function
fn = getFunctionContaining(addr)
## get the function's entry point
entry = fn.getEntryPoint()
print(fn.getName())
print(entry.toString())
Find callers and callees for function
## let fn be a function
callers = fn.getCallingFunctions(monitor)
print(callers)
callees = fn.getCalledFunctions(monitor)
print(callees)
Get decompiled C code from a function (see decompileFunction api)
import ghidra.app.decompiler as decomp
## let addr be a valid Address
fn = getFunctionContaining(addr)
## get the decompiler interface
iface = decomp.DecompInterface()
## decompile the function
iface.openProgram(fn.getProgram())
d = iface.decompileFunction(fn, 5, monitor)
## get the C code as string
if not d.decompileCompleted():
print(d.getErrorMessage())
else:
code = d.getDecompiledFunction()
ccode = code.getC()
print(ccode)
Add custom bookmarks (see createBookmark api) - check the bookmarks in Ghidra in Window -> Bookmarks
## let fn be a function
pos1 = fn.getEntryPoint()
addr = 0x7ff7cf32b901
pos2 = toAddr(addr)
## add bookmarks
category = 'my-bookmark'
createBookmark(pos1, category, 'addr-{}'.format(pos1.toString()))
createBookmark(pos2, category, 'addr-{}'.format(pos2.toString()))
References: