#!/usr/bin/env python3
# callers.py - find BL callers of targets, recursive up to depth N
import struct, json, sys
sys.path.insert(0, "analysis")
from xref_macho import Bin, decode_ops

def main(scan_path, bin_path, target_hexes, depth=3):
    scan = json.load(open(scan_path, encoding="utf-8"))
    b = Bin(bin_path, scan)
    text = b.text
    # build BL edge list
    edges = {}   # target -> [site]
    off, size = text["offset"], text["size"]
    va0 = text["addr"]
    for i in range(0, size - 4, 4):
        w = struct.unpack_from("<I", b.data, off + i)[0]
        if (w & 0xFC000000) == 0x94000000:
            imm = (w & 0x3FFFFFF)
            if imm & 0x2000000:
                imm -= 0x4000000
            tgt = va0 + i + (imm << 2)
            edges.setdefault(tgt, []).append(va0 + i)
    # function starts
    starts = [b.image_base + o for o in scan["info"]["funcstarts"]] if scan["info"]["funcstarts"] else []
    starts = sorted(set(s for s in starts if text["addr"] <= s < text["addr"] + text["size"]))
    import bisect
    def func_of(pc):
        i = bisect.bisect_right(starts, pc) - 1
        if i < 0:
            return None
        s = starts[i]
        e = starts[i + 1] if i + 1 < len(starts) else text["addr"] + text["size"]
        return s, e

    frontier = []
    for t in target_hexes:
        tv = int(t, 16)
        sites = edges.get(tv, [])
        print(f"\ntarget {tv:#x}: {len(sites)} direct BL sites")
        for s in sites:
            f = func_of(s)
            print(f"  bl @ {s:#x}  in func {f[0]:#x}-{f[1]:#x}" if f else f"  bl @ {s:#x} (no func)")
            frontier.append((f[0] if f else s, 1))
    seen = set(frontier)
    d = 1
    # BFS upward
    while d < depth:
        nxt = []
        for fs, lv in frontier:
            sites = edges.get(fs, [])
            for s in sites:
                f = func_of(s)
                key = (f[0] if f else s)
                if key in seen:
                    continue
                seen.add(key)
                print(f"  depth{lv+1}: caller func {key:#x}  (bl @ {s:#x} -> {fs:#x})")
                nxt.append((key, lv + 1))
        frontier = nxt
        d += 1

if __name__ == "__main__":
    main(sys.argv[1], sys.argv[2], sys.argv[3:])
