#!/usr/bin/env python3
"""Scan __objc_stubs for stubs loading specific selref slots; print selector names."""
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()

WANT = {0x101f818a8, 0x101f75c00, 0x101f77f50}
# also print any stub whose selector name contains these
NAMES = ('get', 'getDetectFlags', 'addListener', 'removeListener', 'Shield')


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('scan stubs for selrefs', [hex(x) for x in WANT])
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:
        continue
    try:
        selref = ins[0].operands[1].imm + ins[1].operands[1].mem.disp
    except Exception:
        continue
    if selref in WANT:
        try:
            sel = cstr(u64(selref))
        except Exception:
            sel = '?'
        print('  stub %#x selref %#x sel %r' % (va, selref, sel))

# Also list all stubs whose selector name matches NAMES exactly or contains 'Shield'
print('--- selector-name matches ---')
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:
        continue
    try:
        selref = ins[0].operands[1].imm + ins[1].operands[1].mem.disp
        sel = cstr(u64(selref))
    except Exception:
        continue
    if sel in ('get', 'getDetectFlags', 'addListener:', 'removeListener:', 'readData') or 'Shield' in sel:
        print('  stub %#x sel %r' % (va, sel))
