#!/usr/bin/env python3
"""Trace the block-screen / Safari-redirect flow in build-info and friends."""
import struct, bisect, sys, os
from machofix import MachO

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


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 sx21(v):
    return v - (1 << 21) if v & (1 << 20) else v


def bl_targets(d, starts, lo=None, hi=None):
    """yield (call_off, target) for bl instructions"""
    out = []
    for off in range(0, len(d)-4, 4):
        if lo is not None and off < lo: continue
        if hi is not None and off >= hi: break
        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 stubs_for_slot(d, slot_off):
    """find adrp+ldr pairs that reference the given file offset as a pointer slot"""
    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 report(path, label):
    m = MachO(path)
    m.resolve_fixups()
    d = m.d
    starts = func_starts(d)

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

    # find selector string slots
    print('='*100)
    print(label, os.path.basename(path))
    print('='*100)
    for sel in (b'openURL:options:completionHandler:', b'openURL:', b'canOpenURL:',
                b'presentViewController:animated:completion:', b'dismissViewControllerAnimated:completion:'):
        s = d.find(sel+b'\0')
        if s < 0:
            continue
        slots = [o for o, v in m.ptr.items() if v == ('va', s)]
        print('\nselector %-45s str=%#x slots=%s' % (sel.decode(), s, [hex(x) for x in slots]))
        for slot in slots:
            stubs = stubs_for_slot(d, slot)
            print('  stub slots:')
            for st in stubs:
                # find all bl to this stub
                callers = [c for c, t in bl_targets(d, starts) 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))

    # termination imports
    print('\n-- termination imports --')
    for slot, val in sorted(m.ptr.items()):
        if val[0] == 'bind' and val[1] in ('_exit', '__exit', '_abort', '_raise', '_kill', '_ptrace', '_thread_terminate', '_thread_suspend'):
            stubs = stubs_for_slot(d, slot)
            callers = []
            for st in stubs:
                callers += [(c, st) for c, t in bl_targets(d, starts) if t == st]
            print('%-18s slot=%#x stubs=%s' % (val[1], slot, [hex(x) for x in stubs]))
            for c, st in callers:
                a, b = fn(c)
                print('    call %#x (stub %#x) in func %#x..%#x' % (c, st, a, b))


if __name__ == '__main__':
    for rel, lab in ((r'Frameworks\build-info.framework\build-info', 'build-info'),
                     (r'Frameworks\bshield.framework\bshield', 'bshield')):
        report(os.path.join(ROOT, rel), lab)
