#!/usr/bin/env python3
"""Enumerate all +load methods in Driver; flag those containing calls to the fatal family."""
import struct, sys
import capstone, lief

sys.stdout.reconfigure(encoding='utf-8')
P = r'patch_src\Payload\Driver.app\Driver'
b = lief.MachO.parse(P).at(0)
base = b.imagebase
d = open(P, 'rb').read()

FATAL = {0x18fc6e8, 0x190c47c, 0x18fe118, 0x18fe484}


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):
    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')


def clsname(cls):
    if not cls:
        return '?'
    data = ptr(cls + 0x20)
    if not data:
        return '?'
    nm = ptr(data + 0x18)
    if not nm:
        return '?'
    return cstr(nm)


def methods_of(data_va):
    ml = ptr(data_va + 0x20)
    if not ml:
        return []
    o = ml - base
    if o < 0 or o + 8 > len(d):
        return []
    entsize = struct.unpack_from('<I', d, o)[0]
    count = struct.unpack_from('<I', d, o + 4)[0]
    if count > 100000:
        return []
    rel = bool(entsize & 0x80000000)
    esz = entsize & 0xFFFC
    out = []
    for j in range(count):
        e = o + 8 + j * esz
        try:
            if rel:
                sel_field = e + base
                slot = sel_field + struct.unpack_from('<i', d, e)[0]
                name_va = u64(slot) & 0xFFFFFFFFF
                sel = cstr(name_va)
                imp = e + base + 8 + struct.unpack_from('<i', d, e + 8)[0]
            else:
                sel = cstr(ptr(e + base))
                imp = ptr(e + base + 16)
        except Exception:
            continue
        out.append((sel, imp))
    return out


md = capstone.Cs(capstone.CS_ARCH_ARM64, capstone.CS_MODE_ARM)
md.skipdata = True


def has_fatal_call(imp, span=0x400):
    hits = []
    for i in md.disasm(d[imp - base:imp - base + span], imp):
        if i.mnemonic == 'bl' and i.operands and i.operands[0].type == capstone.arm64.ARM64_OP_IMM:
            if i.operands[0].imm in FATAL:
                hits.append(i.address)
    return hits


cl = b.get_section('__objc_classlist')
loads = []
for i in range(cl.size // 8):
    cls = ptr(cl.virtual_address + i * 8)
    if not cls:
        continue
    name = clsname(cls)
    meta = ptr(cls)
    for label, c in (('+', meta), ('-', cls)):
        for sel, imp in methods_of(c or 0):
            if sel == 'load':
                hits = has_fatal_call(imp)
                loads.append((name, label, imp, hits))

for secname in ('__objc_catlist', '__objc_catlist2'):
    cs = b.get_section(secname)
    if not cs:
        continue
    for i in range(cs.size // 8):
        cat = ptr(cs.virtual_address + i * 8)
        if not cat:
            continue
        cname = cstr(ptr(cat)) if ptr(cat) else '?'
        cls = ptr(cat + 8)
        base_name = clsname(cls) if cls else '?'
        for label, c in (('+', ptr(cat + 16)), ('-', ptr(cat + 24))):
            if not c:
                continue
            for sel, imp in methods_of(c):
                if sel == 'load':
                    hits = has_fatal_call(imp)
                    loads.append((base_name + '(' + cname + ')', label, imp, hits))

print('+load methods found:', len(loads))
for name, label, imp, hits in loads:
    flag = 'FATAL-CALLS: ' + ','.join(hex(h) for h in hits) if hits else 'clean'
    print('  %s %s %#x  %s' % (name, label, imp, flag))
