#!/usr/bin/env python3
"""Look up the symbol name of a __stubs entry in the ORIGINAL Apple binary
(build 50's Driver), whose indirect symbol table is the REAL one."""
import struct, sys

sys.stdout.reconfigure(encoding='utf-8')

PATH = r'E:\ios\work319\patch_src\Payload\Driver.app\Driver'
d = open(PATH, 'rb').read()
ncmds, = struct.unpack_from('<I', d, 16)
off = 32
sym = dysym = None
segs, sections = [], []
for _ in range(ncmds):
    cmd, sz = struct.unpack_from('<II', d, off)
    if cmd == 0x2:
        sym = struct.unpack_from('<IIII', d, off + 8)
    elif cmd == 0xB:
        dysym = struct.unpack_from('<' + 'I' * 18, d, off + 8)
    elif cmd == 0x19:
        nm = d[off + 8:off + 24].rstrip(b'\0').decode()
        vm, vs, fo, fs = struct.unpack_from('<QQQQ', d, off + 24)
        segs.append(dict(index=len(segs), name=nm, vmaddr=vm, fileoff=fo, filesize=fs))
        nsects, = struct.unpack_from('<I', d, off + 64)
        so = off + 72
        for i in range(nsects):
            sect = d[so:so + 16].rstrip(b'\0').decode()
            sg = d[so + 16:so + 32].rstrip(b'\0').decode()
            addr, asize = struct.unpack_from('<QQ', d, so + 32)
            foff = struct.unpack_from('<I', d, so + 48)[0]
            flags, r1, r2 = struct.unpack_from('<III', d, so + 56)
            sections.append(dict(sect=sect, seg=sg, addr=addr, size=asize,
                                 fileoff=foff, flags=flags, r1=r1, entsz=16 if (flags & 0x8) else 8))
            so += 80
    off += sz

symoff, nsyms, stroff, strsize = sym
iso, ni = dysym[12], dysym[13]
print('indirect symbol table: off 0x%x count %d' % (iso, ni))
print('sections with indirect symbols:')
stubs = next(s for s in sections if s['sect'] == '__stubs')
lp = next(s for s in sections if s['sect'] == '__la_symbol_ptr')
got = next(s for s in sections if s['sect'] == '__got')
for s in (stubs, lp, got):
    kind = 'S_SYMBOL_STUBS' if s['flags'] & 0x8 else ('S_LAZY_SYMBOL_POINTERS' if s['flags'] & 0x1 else '?')
    n = s['size'] // s['entsz']
    print('   %-18s %-26s reserved1=%-6d count=%d' % (s['sect'], kind, s['r1'], n))


def sym_name(idx):
    if idx >= nsyms:
        return '(out of range %d)' % idx
    strx, typ, sect, desc, val = struct.unpack_from('<IBBHQ', d, symoff + idx * 16)
    e = d.find(b'\x00', stroff + strx)
    return d[stroff + strx:e].decode('utf-8', 'replace')


# the crash was at the call to stub VA 0x18fe118
for target in (0x18FE118, 0x18FE484, 0x18FC6E8, 0x190C47C):
    st = next(s for s in sections if s['sect'] == '__stubs')
    idx = (target - st['fileoff']) // 12
    si = struct.unpack_from('<I', d, iso + (st['r1'] + idx) * 4)[0]
    print('\nstub 0x%x  index %d  indirect symbol idx %d' % (target, idx, si))
    print('   name: %s' % sym_name(si))

# and a few __la_symbol_ptr slots
print('\n__la_symbol_ptr names (first 6):')
for i in range(6):
    si = struct.unpack_from('<I', d, iso + (lp['r1'] + i) * 4)[0]
    print('   slot %d -> %s' % (i, sym_name(si)))
