#!/usr/bin/env python3
"""Find objc selector uses and their callers, for plain-VA (already fixed-up) binaries."""
import struct, bisect, os, sys

ROOT = r'E:\ios\work319\patch_src\Payload\Driver.app'


def sx21(v):
    return v - (1 << 21) if v & (1 << 20) else v


def func_starts(d):
    n = struct.unpack_from('<I', d, 16)[0]
    o = 32
    fs = None
    for _ in range(n):
        cmd, sz = struct.unpack_from('<II', d, o)
        if cmd == 0x26:
            fs = struct.unpack_from('<II', d, o+8)
        o += sz
    if not fs:
        return []
    off, size = fs
    base = 0
    starts = []
    i = off
    while i < off+size:
        v = 0; sh = 0
        while True:
            b = d[i]; i += 1
            v |= (b & 0x7f) << sh; sh += 7
            if not b & 0x80: break
        if v == 0: break
        base += v; starts.append(base)
    return starts


def find_slots(d, va):
    slots = []
    for off in range(0, len(d)-8, 8):
        raw = struct.unpack_from('<Q', d, off)[0]
        if (raw & 0xFFFFFFFFF) == va:
            slots.append(off)
    return slots


def stubs_for_slot(d, slot_off):
    stubs = []
    for off in range(0, len(d)-8, 4):
        w0 = struct.unpack_from('<I', d, off)[0]
        if (w0 & 0x9F000000) != 0x90000000:
            continue
        imm = sx21(((w0 >> 5) & 0x7FFFF) << 2 | ((w0 >> 29) & 3))
        page = (off & ~0xFFF) + (imm << 12)
        w1 = struct.unpack_from('<I', d, off+4)[0]
        if (w1 & 0xFFC00000) != 0xF9400000:
            continue
        if page + ((w1 >> 10) & 0xFFF)*8 == slot_off:
            stubs.append(off)
    return stubs


def bl_targets(d):
    out = []
    for off in range(0, len(d)-4, 4):
        w = struct.unpack_from('<I', d, off)[0]
        if (w & 0xFC000000) != 0x94000000:
            continue
        imm = w & 0x3FFFFFF
        if imm & 0x2000000:
            imm -= 0x4000000
        out.append((off, off+imm*4))
    return out


def analyze(path, label, sels):
    d = open(path, 'rb').read()
    starts = func_starts(d)
    bls = bl_targets(d)

    def fn(a):
        k = bisect.bisect_right(starts, a)-1
        return starts[k], (starts[k+1] if k+1 < len(starts) else 0)

    print('='*96)
    print('%s  (%s, %d bytes, %d funcs)' % (label, os.path.basename(path), len(d), len(starts)))
    print('='*96)
    for sel in sels:
        s = d.find(sel+b'\0')
        if s < 0:
            print('  [missing] %s' % sel.decode())
            continue
        slots = find_slots(d, s)
        print('  %-42s str=%#x slots=%s' % (sel.decode(), s, [hex(x) for x in slots]))
        for slot in slots:
            for st in stubs_for_slot(d, slot):
                callers = [c for c, t in bls if t == st]
                print('     stub %#x  callers=%s' % (st, [hex(c) for c in callers]))
                for c in callers:
                    a, b = fn(c)
                    print('        %#x  in func %#x..%#x  (size %#x)' % (c, a, b, b-a))


SELS = [
    b'openURL:options:completionHandler:',
    b'openURL:',
    b'canOpenURL:',
    b'SFSafariViewController',
    b'initWithURL:',
    b'presentViewController:animated:completion:',
]

TARGETS = [
    (r'Driver', 'Driver'),
    (r'Frameworks\build-info.framework\build-info', 'build-info'),
    (r'Frameworks\bshield.framework\bshield', 'bshield'),
    (r'Frameworks\app_settings.framework\app_settings', 'app_settings'),
]

for rel, lab in TARGETS:
    p = os.path.join(ROOT, rel)
    if os.path.exists(p):
        analyze(p, lab, SELS)
