# -*- coding: utf-8 -*-
"""scan_callers.py <binary> <hex_target> [...] - tim BL toi dia chi dich."""
import struct, sys, re
from capstone import Cs, CS_ARCH_ARM64, CS_MODE_ARM

def parse(p):
    d = open(p, 'rb').read()
    magic, cputype, cpusub, filetype, ncmds, sizeofcmds, flags = struct.unpack_from('<IiiIIII', d, 0)
    segs = []
    off = 32
    for _ in range(ncmds):
        cmd, size = struct.unpack_from('<II', d, off)
        if cmd == 0x19:
            name = d[off+8:off+24].rstrip(b'\x00').decode()
            vmaddr, vmsize, fileoff, filesize = struct.unpack_from('<QQQQ', d, off+24)
            segs.append((name, vmaddr, vmsize, fileoff, filesize))
        off += size
    return d, segs

def main():
    path = sys.argv[1]
    targets = set(int(x, 16) for x in sys.argv[2:])
    d, segs = parse(path)
    for name, vm, vs, fo, fs in segs:
        if name != '__TEXT':
            continue
        text = d[fo:fo+fs]
        md = Cs(CS_ARCH_ARM64, CS_MODE_ARM)
        md.skipdata = True
        # thu thap call target lam moc function start
        insns = [(i.address, i.mnemonic, i.op_str) for i in md.disasm(text, vm)]
        starts = set()
        for a, mn, ops in insns:
            if mn == 'bl':
                m = re.search(r'#(0x[0-9a-f]+)', ops)
                if m:
                    starts.add(int(m.group(1), 16))
        for a, mn, ops in insns:
            if mn != 'bl':
                continue
            m = re.search(r'#(0x[0-9a-f]+)', ops)
            if not m:
                continue
            t = int(m.group(1), 16)
            if t in targets:
                best = max([s for s in starts if s <= a], default=0)
                print('call@0x%x -> 0x%x   func~0x%x' % (a, t, best))

if __name__ == '__main__':
    main()
