Skip to main content
  1. Posts/

Ghidra Python3 Scripting Cheatsheet

·2 mins
Research Reverse-Engineering Ghidra
Table of Contents

Introduction
#

This is a collection of python3 snippets for scripting on Ghidra. New snippets will be added over time.

Using python3 with Ghidra currently requires the installation of the Ghidrathon extension.

Every snippet assumes that the currentProgram variable was already defined.

currentProgram = currentProgram()

Addresses
#

Most functions that take addresses as arguments don’t accept integers. Instead, they require objects of type ghidra.program.model.address.

Creating an addresse from a string
#

address = currentProgram.getAddressFactory().getAddress(string_addr)

Creating an addresse from an integer
#

address = currentProgram.getAddressFactory().getDefaultAddressSpace().getAddress(int_addr)

Symbols
#

Symbols are accessed through the SymbolTable class.

Creating labels
#

from ghidra.program.model.symbol import SourceType

currentProgram.getSymbolTable().createLabel(addr, name, SourceType.USER_DEFINED)

Find the address of a function
#

from ghidra.program.model.symbol import SymbolType

# Find the target function in the symbol table
for symbol in symbolTable.getSymbols(FUNCTION_NAME):
    if symbol.getSymbolType() == SymbolType.FUNCTION:
        func_addr = symbol.getAddress()
        # Do something with the function address

Functions
#

Functions are queried and created through the FunctionManager.

Getting the function at a specified address
#

func = currentProgram.getFunctionManager().getFunctionAt(func_addr)

Renaming functions
#

from ghidra.program.model.symbol import SourceType

functionManager = currentProgram.getFunctionManager()

func = functionManager.getFunctionAt(func_addr)
if func is None:
    # No function defined, we create one
    func_body = CreateFunctionCmd(func_addr)
    functionManager.createFunction(name,
                                   func_addr,
                                   func_body.getFunctionBody(currentProgram, func_addr),
                                   SourceType.USER_DEFINED)
else:
    # Function already exists, just change the name
    func.setName(name, SourceType.USER_DEFINED)

References
#

The XReferenceUtils class can be used to query all references to a code unit.

Iterating over string references
#

from ghidra.program.util import DefinedDataIterator
from ghidra.app.util import XReferenceUtils

# Iterate over strings
for string in DefinedDataIterator.definedStrings(currentProgram):
    # Iterate over their references
    for str_ref in XReferenceUtils.getXReferences(string, 1000):
        # Take the FROM part of the reference
        str_ref_addr = str_ref.getFromAddress()
        # Do something with the reference