#!/usr/bin/env python3
"""Find the function containing build-info+0xe0d0, its entry, its callers,
and the check-id constants in the whole function."""
import sys, struct, capstone

sys.stdout.reconfigure(encoding='utf-8')

BI = r'E:\ios\work319\patch_src\Payload\Driver.app\Frameworks\build-info.framework\build-info'
d = open(BI, 'rb').read()
BASE = 0x100000000
md = capstone.Cs(capstone.CS_ARCH_ARM64, capstone.CS_MODE_LITTLE_ENDIAN)


def is_prologue(w):
    """stp x29, x30, [sp, #-imm]!  (pre-indexed, Rt=x29(29), Rn=sp(31), Rt2=x30(30))"""
    if (w & 0x7FC00000) != 0xA9800000:
        return False
    rt = w & 0x1F
    rn = (w >> 5) & 0x1F
    rt2 = (w >> 10) & 0x1F
    return rt == 29 and rn == 31 and rt2 == 30


SITE = 0xe0d0
start = None
for back in range(4, 0x8000, 4):
    p = SITE - back
    if p < 0x4000:
        break
    w, = struct.unpack_from('<I', d, p)
    if is_prologue(w):
        # sanity: from p, sequential decode reaches SITE without hitting ret
        ok = True
        q = p
        for insn in md.disasm(d[p:SITE + 4], p + BASE):
            if insn.mnemonic == 'ret':
                ok = False
                break
            if insn.address - BASE >= SITE:
                break
        if ok:
            start = p
            break
print('function containing 0x%x starts at 0x%09x (delta -0x%x)' % (SITE, start + BASE if start else 0, SITE - (start or 0)))

if start is None:
    sys.exit('no prologue found')

# find callers of `start`
callers = []
for off in range(0x4000, 0x7d0000, 4):
    w, = struct.unpack_from('<I', d, off)
    if (w >> 26) == 0x25:
        imm = w & 0x03FFFFFF
        if imm & 0x02000000:
            imm -= 0x04000000
        if off + imm * 4 == start:
            callers.append(off)
print('BL callers of the function: %d' % len(callers))
for c in callers:
    print('  0x%09x' % (c + BASE))

# scan the whole function for CMP #1/#5/#11 and for w-values moved into args
end = start + 0x2000
consts = []
for off in range(start, min(end, len(d) - 4), 4):
    w, = struct.unpack_from('<I', d, off)
    if (w >> 24) == 0x71:  # CMP (32-bit immediate)
        imm12 = (w >> 10) & 0xFFF
        rn = (w >> 5) & 0x1F
        if imm12 in (1, 2, 3, 4, 5, 11):
            consts.append((off, imm12, rn))
print('CMP consts in function: %s' % [(hex(o + BASE), i, 'w%d' % r) for o, i, r in consts][:30])

# also: disassemble around the site (0xe0c0-0xe180) to see the verdict flow
print()
print('=== 0xe0a0-0xe180 ===')
for insn in md.disasm(d[0xe0a0:0xe180], 0xe0a0 + BASE):
    print('  0x%09x  %-8s %s' % (insn.address, insn.mnemonic, insn.op_str))
