#!/usr/bin/env python3
"""Parse __objc_stublist, map stubs to selectors, find bl call sites."""
import struct, sys
import capstone, lief

sys.stdout.reconfigure(encoding='utf-8')
PATH = r'E:\ios\work319\patch_src\Payload\Driver.app\Driver'
b = lief.MachO.parse(PATH).at(0)
base = b.imagebase
blob = open(PATH, 'rb').read()
secs = {s.name: s for s in b.sections}


def off(va):
    return va - base


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


def u32(va):
    return struct.unpack('<I', rd(va, 4))[0]


def i32(va):
    return struct.unpack('<i', rd(va, 4))[0]


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


def cstr(va):
    o = off(va)
    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

sl = secs['__objc_stublist']
WANT = {'getDetectFlags', 'getShieldCode', 'addListener:', 'removeListener:',
        'readData', 'get', 'presentViewController:animated:completion:'}
stub_by_sel = {}
print('stublist', hex(sl.virtual_address), sl.size)
for i in range(sl.size // 4):
    a = sl.virtual_address + i * 4
    stub = a + i32(a)
    ins = list(md.disasm(rd(stub, 16), stub))
    if len(ins) < 2:
        continue
    i0, i1 = ins[0], ins[1]
    if i0.mnemonic != 'adrp' or i1.mnemonic != 'ldr':
        continue
    try:
        page = i0.operands[1].imm
        disp = i1.operands[1].mem.disp
    except Exception:
        continue
    selref = page + disp
    try:
        sel = cstr(u64(selref))
    except Exception:
        continue
    if sel in WANT:
        stub_by_sel.setdefault(sel, []).append(stub)
        print('stub %#x -> %s' % (stub, sel))

targets = {}
for sel, stubs in stub_by_sel.items():
    for st in stubs:
        targets[st] = sel
print('target stubs', {hex(k): v for k, v in targets.items()})

text = secs['__text']
lo, hi = text.virtual_address, text.virtual_address + text.size
print('--- bl call sites ---')
for ins in md.disasm(blob[off(lo):off(hi)], lo):
    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 -> %s' % (ins.address, targets[t]))
