#!/usr/bin/env python3
"""Find bl callers of target addresses in a Mach-O __text."""
import struct, sys
import capstone, lief

sys.stdout.reconfigure(encoding='utf-8')
PATH = sys.argv[1]
TARGETS = {int(x, 16) for x in sys.argv[2:]}
b = lief.MachO.parse(PATH).at(0)
base = b.imagebase
d = open(PATH, 'rb').read()
text = b.get_section('__text')
lo, hi = text.virtual_address, text.virtual_address + text.size
md = capstone.Cs(capstone.CS_ARCH_ARM64, capstone.CS_MODE_ARM)
md.detail = True
print('targets', [hex(t) for t in TARGETS])
for ins in md.disasm(d[lo - base:hi - base], lo):
    if ins.mnemonic in ('bl', 'b') and ins.operands and ins.operands[0].type == capstone.arm64.ARM64_OP_IMM:
        t = ins.operands[0].imm
        if t in TARGETS:
            print('  %#x -> %#x' % (ins.address, t))
