#!/usr/bin/env python3
"""blx.py - find BL/B call sites to a target VA inside __text."""
import struct, sys
from machofix import MachO

def bl_sites(m, target):
    text = m.sec('__text')
    addr, off, size = text[2], text[3], text[4]
    hits = []
    o = off
    end = off + size - 4
    while o < end:
        w = struct.unpack_from('<I', m.d, o)[0]
        if (w & 0xFC000000) == 0x94000000:
            imm = w & 0x3FFFFFF
            if imm & (1 << 25):
                imm -= (1 << 26)
            if m.off2va(o) + imm * 4 == target:
                hits.append(m.off2va(o))
        o += 4
    return hits

if __name__ == '__main__':
    m = MachO(sys.argv[1])
    for a in sys.argv[2:]:
        t = int(a, 0)
        print('0x%x <-' % t, [hex(x) for x in bl_sites(m, t)])
