This is a cheatsheet I use for Ghidra scripting.
NOTE: Some of these functions use each other 😄
Get Python Bytes from Address
1
2
| def get_bytes(address, size):
return bytes(map(lambda b: b & 0xff, getBytes(address, size)))
|
Get Section Bytes (Program Tree)
1
2
3
| def get_section_bytes(section_name):
section = getMemoryBlock(section_name)
return get_bytes(section.getStart(), section.getSize())
|
Get Executable Path
1
| currentProgram.getExecutablePath()
|
Get Program Start Address
1
| currentProgram.getMinAddress()
|
Get Program End Address
1
| currentProgram.getMaxAddress()
|
1
2
3
4
| 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
1
| createBookmark(addr, 'category', 'description')
|
Functions
1
2
3
4
5
| 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
1
2
3
4
5
| 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
1
2
3
4
| def get_label(address):
result = currentProgram.getListing().getCodeUnitAt(address)
if result is None: return None
return result.getLabel()
|
Listing
1
2
3
4
5
6
7
| 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()
|