# -*- coding: utf-8 -*-
"""indirect_dump.py — in toàn bộ indirect symbol table + undefined symbols của Mach-O."""
import struct, sys

d = open(sys.argv[1], 'rb').read()
magic, cputype, cpusub, filetype, ncmds, sizeofcmds, flags = struct.unpack_from('<IiiIIII', d, 0)
off = 32
symtab = dysym = None
for i in range(ncmds):
    cmd, size = struct.unpack_from('<II', d, off)
    if cmd == 0x02:
        symtab = struct.unpack_from('<IIII', d, off+8)
    elif cmd == 0x0b:
        dysym = struct.unpack_from('<' + 'I'*18, d, off+8)
    off += size

symoff, nsyms, stroff, strsize = symtab
iundef, nundef = dysym[4], dysym[5]
indoff, nind = dysym[12], dysym[13]
print('nsyms=%d nundef=%d(indirectsymoff=0x%x n=%d)' % (nsyms, nundef, indoff, nind))

def name(idx):
    n_strx, n_type, n_sect, n_desc, n_value = struct.unpack_from('<IBBHQ', d, symoff + idx*16)
    e = d.index(b'\x00', stroff + n_strx)
    return d[stroff+n_strx:e].decode(errors='replace'), n_type, n_value

print('\n== INDIRECT SYMBOLS (index -> name) ==')
for i in range(nind):
    ent = struct.unpack_from('<I', d, indoff + i*4)[0]
    if ent == 0x40000000 or ent == 0x80000000 or ent >= 0xffffff00:
        print('%3d: (special 0x%x)' % (i, ent))
        continue
    try:
        nm, t, v = name(ent)
        print('%3d: %s (type=%x val=0x%x)' % (i, nm, t, v))
    except Exception as e:
        print('%3d: ERR %s' % (i, e))
