#!/usr/bin/env python3
"""Find Driver call sites (bl) to objc_msgSend stubs for shield selectors."""
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}

WANT = ('getDetectFlags', 'getShieldCode', 'addListener:', 'removeListener:',
        'readData', 'get', 'ShieldData', 'ShieldAPI', 'isJailbroken',
        'isDeveloperMode', 'isRepack', 'detect')

stubs = {}
print('--- matching symbols ---')
for s in b.symbols:
    if not s.name:
        continue
    if s.name.startswith('_objc_msgSend$'):
        sel = s.name[len('_objc_msgSend$'):]
        if sel in ('getDetectFlags', 'getShieldCode', 'addListener:', 'removeListener:', 'readData', 'get'):
            stubs[s.value] = s.name
            print(hex(s.value), s.name)
    elif any(k in s.name for k in ('Shield', 'Detect', 'Banned')):
        print(hex(s.value), s.name)

if not stubs:
    print('no stubs found')
    sys.exit()

text = secs['__text']
lo, hi = text.virtual_address, text.virtual_address + text.size
md = capstone.Cs(capstone.CS_ARCH_ARM64, capstone.CS_MODE_ARM)
md.detail = True
print('--- bl call sites ---')
hits = []
for ins in md.disasm(blob[lo - base:hi - base], lo):
    if ins.mnemonic in ('bl', 'b') and ins.operands and ins.operands[0].type == capstone.arm64.ARM64_OP_IMM:
        tgt = ins.operands[0].imm
        if tgt in stubs:
            hits.append((ins.address, stubs[tgt]))
for a, n in hits:
    print('  %#x -> %s' % (a, n))
