#!/usr/bin/env python3
"""Resolve stub symbols via indirect symbol table + print BannedViewController methods."""
import struct, sys
import 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
d = open(PATH, 'rb').read()


def u32(o):
    return struct.unpack_from('<I', d, o)[0]


def u64(va):
    o = va - base
    if o < 0 or o + 8 > len(d):
        return None
    return struct.unpack_from('<Q', d, o)[0]


def ptr(va):
    v = u64(va)
    return None if v is None else (v & 0xFFFFFFFFF)


def cstr(va):
    if va is None:
        return '?'
    o = va - base
    if o < 0 or o >= len(d):
        return '?'
    e = d.find(b'\0', o)
    return d[o:e].decode('utf-8', 'replace')


# --- parse load commands ---
ncmds = u32(16)
off = 32
symtab = None
dysym = None
stubs_sec = None
for _ in range(ncmds):
    cmd, size = struct.unpack_from('<II', d, off)
    if cmd == 0x2:  # LC_SYMTAB
        symtab = struct.unpack_from('<IIII', d, off + 8)
    elif cmd == 0xb:  # LC_DYSYMTAB
        vals = struct.unpack_from('<18I', d, off + 8)
        dysym = vals
    elif cmd == 0x19:  # LC_SEGMENT_64
        nsects = u32(off + 64)
        so = off + 72
        for _s in range(nsects):
            sn = d[so:so + 16].split(b'\0')[0].decode()
            addr = struct.unpack_from('<Q', d, so + 32)[0]
            sz = struct.unpack_from('<Q', d, so + 40)[0]
            sf = u32(so + 48)
            res1 = u32(so + 68)
            if sn == '__stubs':
                stubs_sec = (addr, sz, sf, res1)
            so += 80
    off += size

print('symtab', symtab)
print('dysym indirectsymoff/nindirectsyms', dysym[12], dysym[13] if dysym else None)
print('stubs_sec', stubs_sec)

symoff, nsyms, stroff, strsize = symtab
indoff, nind = dysym[12], dysym[13]


def symname(idx):
    if idx >= nsyms:
        return '?'
    no = symoff + idx * 16
    strx = u32(no)
    so = stroff + strx
    e = d.find(b'\0', so)
    return d[so:e].decode('utf-8', 'replace')


stub_names = {}
if stubs_sec:
    saddr, ssize, sfile, res1 = stubs_sec
    for i in range(ssize // 12):
        idx = u32(indoff + (res1 + i) * 4)
        stub_names[saddr + i * 12] = symname(idx)

print('--- stub symbol lookups ---')
for a in (0x10190bd14, 0x10190bd50, 0x10190bc00, 0x10190bc0c,
          0x10190bd20, 0x101908504, 0x10190c9c8):
    print(hex(a), stub_names.get(a, '?'))

# --- BannedViewController methods ---
def clsname(cls):
    data = ptr(cls + 0x20)
    if not data:
        return '?'
    return cstr(ptr(data + 0x18))


def methods_of(cls):
    data = ptr(cls + 0x20)
    if not data:
        return []
    ml = ptr(data + 0x20)
    if not ml:
        return []
    o = ml - base
    entsize = u32(o)
    count = u32(o + 4)
    rel = bool(entsize & 0x80000000)
    esz = entsize & 0xFFFC
    out = []
    for j in range(count):
        e = o + 8 + j * esz
        if rel:
            sel_va = e + base + struct.unpack_from('<i', d, e)[0]
            imp = e + base + 8 + struct.unpack_from('<i', d, e + 8)[0]
        else:
            sel_va = ptr(e + base)
            imp = ptr(e + base + 16)
        out.append((imp, cstr(sel_va)))
    return out


cl = b.get_section('__objc_classlist')
print('--- BannedViewController ---')
for i in range(cl.size // 8):
    cls = ptr(cl.virtual_address + i * 8)
    if not cls:
        continue
    nm = clsname(cls)
    if 'Banned' in nm:
        meta = ptr(cls)
        print('class', nm, hex(cls), 'meta', hex(meta))
        print('super:', clsname(ptr(cls + 8)))
        for label, c in (('+', meta), ('-', cls)):
            for imp, sel in methods_of(c):
                print('  %s %-70s %#x' % (label, sel, imp))

# also dump every Driver class whose methods fall inside 0x1002b8000-0x1002ba000
print('--- classes with methods near BannedViewController ---')
for i in range(cl.size // 8):
    cls = ptr(cl.virtual_address + i * 8)
    if not cls:
        continue
    nm = clsname(cls)
    for label, c in (('+', ptr(cls)), ('-', cls)):
        for imp, sel in methods_of(c):
            if 0x1002b8000 <= imp < 0x1002ba000:
                print('  %-45s %s %-40s %#x' % (nm, label, sel, imp))
