#!/usr/bin/env python3
"""Trace the verdict-assembly function (containing build-info+0xe0d0) and its
callers: find the check-ID constants (1, 5, 11) and the decision chain."""
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 decode(word):
    return word


def find_function_start(off, maxback=0x2000):
    """scan back for a likely prologue: stp x29, x30, [sp, #-..]!  (a9..7bfd / f8..)"""
    for back in range(4, maxback, 4):
        p = off - back
        w, = struct.unpack_from('<I', d, p)
        # stp x29, x30, [sp, #-N]! = 0xA9xx7BFD
        if (w & 0xFFE07FFF) == 0xA9007BFD and (w >> 22) & 0x1FF:  # pre-index store pair
            if (w & 0x7FC00000) == 0xA9800000 or True:
                # crude: look for stp with x29/x30 and writeback
                if (w & 0x7C00) == 0x7C00 or ((w >> 15) & 0x1F) == 29:
                    return p
    return None


# find callers of the verdict assembly site region: BL instructions targeting
# anywhere in [0xe0c0, 0xe140]
lo, hi = 0xe0c0, 0xe140
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
        tgt = off + imm * 4
        if lo <= tgt < hi:
            callers.append((off, tgt))
print('BL callers into verdict-assembly region [0x%x,0x%x): %d' % (lo, hi, len(callers)))
for c, t in callers:
    print('  from 0x%09x -> 0x%09x' % (c + BASE, t + BASE))

# for each caller, disassemble a window BEFORE it to find the check-id setup
# (mov w?, #1 / #11 / #5 etc.) and the surrounding function
print()
for c, t in callers[:4]:
    print('=== caller 0x%09x (window 0x-80..+16) ===' % (c + BASE))
    for insn in md.disasm(d[c - 80:c + 16], c - 80):
        mark = ' <<< BL' if insn.address == c else ''
        print('  0x%09x  %-8s %s%s' % (insn.address + BASE, insn.mnemonic, insn.op_str, mark))
    print()

# find function start of each caller and scan the WHOLE function for cmp #11 / #1 / #5
print('=== check-id constants near callers ===')
for c, t in callers[:4]:
    fs = find_function_start(c)
    if fs is None:
        print('  caller 0x%09x: function start not found' % (c + BASE))
        continue
    # find function end: next ret after a long stretch, cap at 0x1000
    end = min(fs + 0x1000, len(d) - 4)
    consts = []
    for off in range(fs, end, 4):
        w, = struct.unpack_from('<I', d, off)
        # CMP Wn, #imm  = 0x7100_0000 | ... ; check (w >> 24) == 0x71
        if (w >> 24) == 0x71:
            imm12 = (w >> 10) & 0xFFF
            rn = (w >> 5) & 0x1F
            if imm12 in (1, 5, 11, 2, 3, 4):
                consts.append((off, imm12, rn))
    print('  caller fn 0x%09x..0x%09x: CMP consts: %s' % (fs + BASE, end + BASE,
          [(hex(o + BASE), i, 'w%d' % r) for o, i, r in consts][:20]))
