I am using ghidra to do reverse engineering of a binary. I am using the following script to get the disassembly of the blocks containing instruction 'RET' across all functions:

from ghidra.program.model.block import SimpleBlockModel
from ghidra.program.model.block import BasicBlockModel
from ghidra.program.model.block import CodeBlockModel
from ghidra.util.task import ConsoleTaskMonitor
from ghidra.program.model.listing import Listing
from ghidra.util.task import TaskMonitor
from binascii import hexlify

def print_disassembly(block):
    listing = currentProgram.getListing()
    ins_iter = listing.getInstructions(block, True)

    while ins_iter.hasNext():
        ins = ins_iter.next()
        print "{} {}".format(ins.getAddressString(False, True), ins)

def print_disassembly2(block, addrSet):
    listing = currentProgram.getListing()
    codeUnits = listing.getCodeUnits(addrSet, True) # true means 'forward'

    for codeUnit in codeUnits:
        print("0x{} : {:16} {}".format(codeUnit.getAddress(), hexlify(codeUnit.getBytes()), codeUnit.toString()))

blockModel = BasicBlockModel(currentProgram)
monitor = ConsoleTaskMonitor()

func = getFirstFunction()
while func is not None:
      print("Basic block details for function: ", func.getName())
      blocks = blockModel.getCodeBlocksContaining(func.getBody(), monitor)
      # print first block
      block = blocks.next()
      # only print blocks that contain "interesting" instruction
      while block:
            listing = currentProgram.getListing()
            ins_iter = listing.getInstructions(block, True)
            found = False
            for instruction in ins_iter:
                addr = instruction.getAddress()
                oper = instruction.getMnemonicString()
                if (oper.startswith('RET')):
                    # or oper.startswith('J') and instruction.getRegister(0)):
                    found = True
            if (found):
                adrSet = func.getBody()
            block = blocks.next()
      func = getFunctionAfter(func)

Now I want to get the first predecessor block of the block containing 'RET' and the successive blocks(there may be cases where there are no predecessor blocks, then only the successor blocks may be printed). How do I do that?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.