Skip to content

Instantly share code, notes, and snippets.

@c3rb3ru5d3d53c
Last active January 21, 2023 15:35
Show Gist options
  • Save c3rb3ru5d3d53c/de02e869f64a551bfcd78fb318668292 to your computer and use it in GitHub Desktop.
Save c3rb3ru5d3d53c/de02e869f64a551bfcd78fb318668292 to your computer and use it in GitHub Desktop.
Ghidra Python Cheatsheet

Ghidra Python Cheatsheet

This is a cheatsheet I use for Ghidra scripting.

NOTE: Some of these functions use each other 😄

Get Python Bytes from Address

def get_bytes(address, size):
	return bytes(map(lambda b: b & 0xff, getBytes(address, size)))

Get Section Bytes (Program Tree)

def get_section_bytes(section_name):
	section = getMemoryBlock(section_name)
	return get_bytes(section.getStart(), section.getSize())

Get Executable Path

currentProgram.getExecutablePath()

Get Program Start Address

currentProgram.getMinAddress()

Get Program End Address

currentProgram.getMaxAddress()

Comments

from ghidra.program.model.listing import CodeUnit
cu = currentProgram.getListing().getCodeUnitAt(addr)
cu.getComment(CodeUnit.EOL_COMMENT)
cu.setComment(CodeUnit.EOL_COMMENT, "Comment text")

Bookmarks

createBookmark(addr, 'category', 'description')

Functions

from ghidra.program.model.symbol import SourceType
fm = currentProgram.getFunctionManager()
f = fm.getFunctionAt(currentAddress)
f = fm.getFunctionContaining(currentAddress)
f.setName("test", SourceType.USER_DEFINED)

Addresses

def get_address(address: int):
	return currentProgram.getAddressFactory().getAddress(str(hex(address)))
address = get_address(0x400000)
next_address = address.add(5)
current_address = currentLocation.getAddress()

Labels

def get_label(address):
	result = currentProgram.getListing().getCodeUnitAt(address)
	if result is None: return None
	return result.getLabel()

Listing

def get_codeunit(address):
	return currentProgram.getListing().getCodeUnitAt(address)
codeunit = get_codeunit(address)
mnemonic = codeunit.getMnemonicString()
number_operands = codeunit.getNumOperands()
next_codeunit = codeunit.getNext()
prev_codeunit = codeunit.getPrev()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment