Skip to content

Instantly share code, notes, and snippets.

@zcutlip
Created February 12, 2020 22:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zcutlip/90a4dd2fa38173c8ba8ee03ad9f16abb to your computer and use it in GitHub Desktop.
Save zcutlip/90a4dd2fa38173c8ba8ee03ad9f16abb to your computer and use it in GitHub Desktop.
Ghidra Script to List all Basic Block Addresses for a Function
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