#!/usr/bin/env python3
"""Find msgSend stubs for a selector string and their BL callers in build-info."""
import struct, sys

sys.stdout.reconfigure(encoding='utf-8')
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'
data = open(PATH, 'rb').read()
md = Cs(CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN)


def u64(o):
    return struct.unpack_from('<Q', data, o)[0]


def find_str(s):
    b = s.encode()
    out = []
    i = data.find(b)
    while i >= 0:
        out.append(i)
        i = data.find(b, i + 1)
    return out


def find_ptrs(val):
    out = []
    pat = struct.pack('<Q', val)
    i = data.find(pat)
    while i >= 0:
        out.append(i)
        i = data.find(pat, i + 1)
    return out


def scan_stubs(selref_addrs):
    """Scan the msgSend stub table region for adrp x1/ldr x1 patterns matching selrefs."""
    hits = {}
    lo, hi = 0x75c000, 0x764000
    for va in range(lo, hi, 4):
        if data[va:va + 4] != b'\x21\x00\x00\x90' and (data[va] & 0x9f) != 0x01:
            pass
        ins = list(md.disasm(data[va:va + 8], va))
        if len(ins) < 2 or ins[0].mnemonic != 'adrp' or ins[1].mnemonic != 'ldr':
            continue
        try:
            page = int(ins[0].op_str.split('#')[1], 16)
            imm = int(ins[1].op_str.split('#')[1].rstrip(']'), 16)
        except Exception:
            continue
        tgt = page + imm
        if tgt in selref_addrs:
            hits.setdefault(tgt, []).append(va)
    return hits


def find_bl_callers(target, limit=40):
    out = []
    for va in range(0, len(data) - 4, 4):
        w = struct.unpack_from('<I', data, va)[0]
        if (w & 0xFC000000) == 0x94000000:  # bl
            imm = w & 0x03FFFFFF
            if imm & 0x02000000:
                imm -= 0x04000000
            if va + imm * 4 == target:
                out.append(va)
                if len(out) >= limit:
                    break
    return out


for name in ['application:didFinishLaunchingWithOptions:',
             'configurationForConnectingSceneSession:options:',
             'window', 'setWindow:', 'rootViewController', 'setRootViewController:',
             'runWithEntrypoint:', 'sharedApplication', 'delegate']:
    strs = find_str(name)
    print('\n== %r -> str offsets %s' % (name, [hex(s) for s in strs][:4]))
    for s in strs[:2]:
        ptrs = find_ptrs(s)
        if not ptrs:
            continue
        print('   ptr refs:', [hex(p) for p in ptrs][:6])
        hits = scan_stubs(set(ptrs))
        for selref, stubs in hits.items():
            print('   selref 0x%x stubs %s' % (selref, [hex(x) for x in stubs]))
            for st in stubs[:2]:
                callers = find_bl_callers(st)
                print('      callers of 0x%x: %s' % (st, [hex(c) for c in callers][:12]))
