#!/usr/bin/env python3
"""Driver native shield call sites via __objc_stubs (selector stubs).

Each stub is 32 bytes:
  adrp x1, page ; ldr x1,[x1,#off] ; adrp x16,got ; ldr x16,[x16,#o] ; br x16 ; brk*3
Resolve selector -> stub, then find bl to that stub in __text.
"""
import struct, sys, time
import capstone, lief

sys.stdout.reconfigure(encoding='utf-8')
PATH = r'E:\ios\work319\patch_src\Payload\Driver.app\Driver'
WANT = {'getDetectFlags', 'getShieldCode', 'addListener:', 'removeListener:',
        'readData', 'get', 'presentViewController:animated:completion:',
        'viewDidLoad', 'viewWillAppear:', 'dismissViewControllerAnimated:completion:'}

b = lief.MachO.parse(PATH).at(0)
base = b.imagebase
blob = open(PATH, 'rb').read()


def rd(va, n):
    return blob[va - base:va - base + n]


def u64(va):
    return struct.unpack('<Q', rd(va, 8))[0]


def cstr(va):
    o = va - base
    e = blob.find(b'\0', o)
    return blob[o:e].decode('utf-8', 'replace')


md = capstone.Cs(capstone.CS_ARCH_ARM64, capstone.CS_MODE_ARM)
md.detail = True

st = b.get_section('__objc_stubs')
print('stubs va %#x size %#x stride 32' % (st.virtual_address, st.size))
sel_to_stub = {}
named = 0
for off in range(0, st.size, 32):
    va = st.virtual_address + off
    ins = list(md.disasm(rd(va, 8), va))
    if len(ins) < 2 or ins[0].mnemonic != 'adrp' or ins[1].mnemonic != 'ldr':
        continue
    try:
        selref = ins[0].operands[1].imm + ins[1].operands[1].mem.disp
        sel = cstr(u64(selref))
    except Exception:
        continue
    named += 1
    sel_to_stub.setdefault(sel, []).append(va)
print('stubs parsed %d, named %d, unique selectors %d' % (st.size // 32, named, len(sel_to_stub)))

print('--- requested selectors ---')
targets = {}
for sel in WANT:
    for s in sel_to_stub.get(sel, []):
        targets[s] = sel
        print('  %-50s stub %#x' % (sel, s))

text = b.get_section('__text')
lo, hi = text.virtual_address, text.virtual_address + text.size
print('--- bl/b call sites (text %#x-%#x) ---' % (lo, hi))
t0 = time.time()
n = 0
for ins in md.disasm(blob[lo - base:hi - base], lo):
    n += 1
    if ins.mnemonic in ('bl', 'b') and ins.operands and ins.operands[0].type == capstone.arm64.ARM64_OP_IMM:
        t = ins.operands[0].imm
        if t in targets:
            print('  %#x -> %-45s (stub %#x)' % (ins.address, targets[t], t))
print('insns %d elapsed %.1fs' % (n, time.time() - t0))
