#!/usr/bin/env python3
"""Resolve a Driver import stub VA -> symbol name via __stubs + indirect symbol table."""
import struct, sys

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

PATH = r'E:\ios\work319\patch_src_orig\Driver'
d = open(PATH, 'rb').read()
magic, cpu, sub, ft, ncmds, size, flags, res = struct.unpack_from('<IiiIIIII', d, 0)
off = 32
sections = []          # (sectname, segname, addr, size, offset)
symoff = nsyms = stroff = 0
indirectsymoff = nindirectsyms = 0
for _ in range(ncmds):
    cmd, sz = struct.unpack_from('<II', d, off)
    if cmd == 0x19:  # LC_SEGMENT_64
        nsects = struct.unpack_from('<I', d, off + 64)[0]
        so = off + 72
        for s in range(nsects):
            sect = d[so:so + 16].rstrip(b'\x00').decode()
            seg = d[so + 16:so + 32].rstrip(b'\x00').decode()
            addr, sz2 = struct.unpack_from('<QQ', d, so + 32)
            foff = struct.unpack_from('<I', d, so + 48)[0]
            sections.append((sect, seg, addr, sz2, foff))
            so += 80
    elif cmd == 0x2:
        symoff, nsyms, stroff, strsize = struct.unpack_from('<IIII', d, off + 8)
    elif cmd == 0xb:
        indirectsymoff, nindirectsyms = struct.unpack_from('<II', d, off + 56)
    off += sz


def symname(i):
    strx = struct.unpack_from('<I', d, symoff + i * 16)[0]
    e = d.find(b'\x00', stroff + strx)
    return d[stroff + strx:e].decode('utf-8', 'replace')


BASE = 0x100000000


def resolve(va):
    for sect, seg, addr, sz2, foff in sections:
        start = addr - BASE if addr >= BASE else addr
        if sect in ('__stubs', '__auth_stubs') and start <= va < start + sz2:
            idx = (va - start) // 12
            si = struct.unpack_from('<I', d, indirectsymoff + (idx + 0) * 4)[0]
            return sect, symname(si)
    return None, None


if __name__ == '__main__':
    targets = [int(x, 16) for x in sys.argv[1:]] or [0x18fe118, 0x190bd14, 0x190bd2c, 0x190bd50,
                                                      0x190c6b0, 0x19379c0, 0x191eda0, 0x190a9d0, 0x19098a8,
                                                      0x190989c, 0x190c794, 0x190a934, 0x2153fc, 0x3bc4c0,
                                                      0x18fd38c, 0x18fe118, 0x1938240, 0x192a620, 0x193cbc0,
                                                      0x19379c0]
    for t in targets:
        sect, nm = resolve(t)
        print('0x%08x  %-12s %s' % (t, sect or '?', nm or '?'))
