#!/usr/bin/env python3
"""Find the function containing 0xe0d0: scan back for `sub sp, sp, #imm` prologue
(crossing RET boundaries), then forward for the end (RET), then callers + consts."""
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
RET = 0xD65F03C0
md = capstone.Cs(capstone.CS_ARCH_ARM64, capstone.CS_MODE_LITTLE_ENDIAN)

SITE = 0xe0d0


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


def is_stp_x29_pre(w):
    if (w & 0x7FC00000) != 0xA9800000:
        return False
    return (w & 0x1F) == 29 and ((w >> 5) & 0x1F) == 31 and ((w >> 10) & 0x1F) == 30


start = None
for back in range(4, 0x30000, 4):
    p = SITE - back
    if p < 0x4000:
        break
    w, = struct.unpack_from('<I', d, p)
    if is_subsp(w) or is_stp_x29_pre(w):
        start = p
        break
print('function start: 0x%09x (delta -0x%x)' % (start + BASE, SITE - start))

# function end: first RET after start scanning forward, skipping embedded data is
# unreliable; instead walk back from the next known boundary — use linear scan
end = None
for off in range(start, min(start + 0x8000, len(d) - 4), 4):
    w, = struct.unpack_from('<I', d, off)
    if w == RET and off > SITE:
        end = off
        break
print('first RET after site: 0x%09x (func size ~0x%x)' % (end + BASE, end - 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))

consts = []
for off in range(start, end, 4):
    w, = struct.unpack_from('<I', d, off)
    if (w >> 24) == 0x71:
        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: %s' % [(hex(o + BASE), i, 'w%d' % r) for o, i, r in consts][:40])

print()
print('=== around the site 0xe0c0-0xe140 ===')
for insn in md.disasm(d[0xe0c0:0xe140], 0xe0c0 + BASE):
    print('  0x%09x  %-8s %s' % (insn.address, insn.mnemonic, insn.op_str))
