#!/usr/bin/env python3
"""Disassemble build-info at VA (=file offset, vmaddr=0) with capstone; find BL callers of an address."""
import sys, struct
from capstone import Cs, CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN

PATH = r'E:\ios\work319\patch_src\Payload\Driver.app\Frameworks\build-info.framework\build-info'
md = Cs(CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN)
md.detail = True


def load():
    return open(PATH, 'rb').read()


def dis(data, va, n=40):
    out = []
    for i in md.disasm(data[va:va + n * 4], va):
        out.append('0x%06x  %-8s %s' % (i.address, i.mnemonic, i.op_str))
        if len(out) >= n:
            break
    return out


def find_callers(data, target, limit=20):
    """Scan .text for 'bl #target'. Cheap linear scan over all 4-byte words."""
    callers = []
    n = len(data) // 4
    for idx in range(n):
        off = idx * 4
        w = struct.unpack_from('<I', data, off)[0]
        if (w >> 26) == 0x25:  # BL
            imm = w & 0x03FFFFFF
            if imm & 0x02000000:
                imm -= 0x04000000
            dst = off + imm * 4
            if dst == target:
                callers.append(off)
                if len(callers) >= limit:
                    break
    return callers


if __name__ == '__main__':
    data = load()
    va = int(sys.argv[1], 16) if len(sys.argv) > 1 else 0x29900
    mode = sys.argv[2] if len(sys.argv) > 2 else 'dis'
    if mode == 'dis':
        print('=== build-info @ 0x%x ===' % va)
        for line in dis(data, va, 45):
            print(line)
    elif mode == 'callers':
        print('callers of 0x%x:' % va)
        for c in find_callers(data, va):
            print('  0x%x' % c)
