Created
February 12, 2020 22:12
-
-
Save zcutlip/90a4dd2fa38173c8ba8ee03ad9f16abb to your computer and use it in GitHub Desktop.
Ghidra Script to List all Basic Block Addresses for a Function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from ghidra.program.model.block import BasicBlockModel | |
from ghidra.util.task import ConsoleTaskMonitor | |
""" | |
Ghidra script to identify the addresses of all basic blocks within a function | |
Prompts for name of a function, and name of an output file. Locates all basic block addreses | |
and writes them to the output file. | |
""" | |
def bb_start_address(basic_block): | |
start = None | |
ranges = basic_block.getAddressRanges() | |
while ranges.hasNext(): | |
r = ranges.next() | |
r_min = r.getMinAddress() | |
start = "0x%s" % str(r_min) | |
break | |
return start | |
def do_function_basic_blocks(function): | |
bb_addresses = [] | |
bm = BasicBlockModel(currentProgram) | |
monitor = ConsoleTaskMonitor() | |
blocks = bm.getCodeBlocksContaining(function.getBody(), monitor) | |
while blocks.hasNext(): | |
bb = blocks.next() | |
addr = bb_start_address(bb) | |
if not addr: | |
raise Exception("Invalid basic block {}".format(bb)) | |
bb_addresses.append(addr) | |
return bb_addresses | |
def run(): | |
func_name = askString("What Function Name", "function") | |
output_file = askString("What File to Write", "output file") | |
func_list=getGlobalFunctions(func_name) | |
if not func_list: | |
raise Exception("No functions found by name: %s" % func_name) | |
func = func_list[0] | |
bb_addresses = do_function_basic_blocks(func) | |
print("Basic block addresses for function {}".format(func_name)) | |
for bb_addr in bb_addresses: | |
print("\t{}".format(bb_addr)) | |
print("Writing output to {}".format(os.path.realpath(output_file))) | |
with open(output_file, "w") as f: | |
for bb_addr in bb_addresses: | |
f.write("{}\n".format(bb_addr)) | |
run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment