#!/usr/bin/env python3
"""Find the ban-decision gating the openURL call at build-info+0x290bf0:
locate the enclosing function, disassemble backwards to the entry, and dump
the conditional branches leading into the openURL block."""
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)

OPEN_CALL = 0x290bf0


def is_prologue(w):
    if (w & 0x7FC00000) == 0xA9800000:
        rt = w & 0x1F
        rn = (w >> 5) & 0x1F
        rt2 = (w >> 10) & 0x1F
        return rt == 29 and rn == 31 and rt2 == 30
    return False


def is_subsp(w):
    return (w & 0xFFC003FF) == 0xD10003FF


# scan back for prologue (stp x29 pre-index OR sub sp) crossing no more than 0x4000
start = None
for back in range(4, 0x4000, 4):
    p = OPEN_CALL - back
    w, = struct.unpack_from('<I', d, p)
    if is_prologue(w) or is_subsp(w):
        # sanity: linear decode from p reaches OPEN_CALL without ret
        ok = True
        for insn in md.disasm(d[p:OPEN_CALL + 4], p + BASE):
            if insn.mnemonic == 'ret' and insn.address - BASE < OPEN_CALL:
                ok = False
                break
            if insn.address - BASE >= OPEN_CALL:
                break
        if ok:
            start = p
            break
print('enclosing function start: 0x%09x (delta -0x%x)' % (start + BASE, OPEN_CALL - start))

# disassemble the function from start to a bit past the openURL call
print()
print('=== %s .. %s ===' % (hex(start + BASE), hex(OPEN_CALL + 0x20 + BASE)))
prev_branch_target = None
for insn in md.disasm(d[start:OPEN_CALL + 0x20], start + BASE):
    line = '  0x%09x  %-8s %s' % (insn.address, insn.mnemonic, insn.op_str)
    if insn.mnemonic == 'bl' and '0x100760e60' in insn.op_str:
        line += '   <<< openURL'
    print(line)
