# -*- coding: utf-8 -*-
"""stub_resolve.py — resolve tên symbol thật của các stub trong Mach-O (dùng indirect symbol table).
Usage: python stub_resolve.py <macho> <offset_hex> [offset2 ...]
"""
import struct, sys, bisect

def load(p):
    d = open(p, 'rb').read()
    magic, cputype, cpusub, filetype, ncmds, sizeofcmds, flags = struct.unpack_from('<IiiIIII', d, 0)
    off = 32
    symtab = dysym = None
    stub_sections = []  # (name, addr, size, stride, istart)
    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)
        elif cmd == 0x19:
            nsects = struct.unpack_from('<I', d, off+64)[0]
            so = off + 72
            for s in range(nsects):
                sect = d[so:so+80]
                name = sect[0:16].rstrip(b'\x00').decode()
                addr, segsize, foff, align, reloff, nreloc, sflags, r1, r2, r3 = struct.unpack_from('<QQIIIIIIII', sect, 32)
                if sflags == 0x8 or sflags == 0x9:  # S_SYMBOL_STUBS / S_GARBAGE_COLLECTIBLE_STUBS
                    stub_sections.append((name, addr, sflags, r2, r1))
                so += 80
        off += size
    return d, symtab, dysym, stub_sections

def sym_name(d, symtab, idx):
    symoff, nsyms, stroff, strsize = symtab
    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

if __name__ == '__main__':
    p = sys.argv[1]
    d, symtab, dysym, stubs = load(p)
    print('stub sections: %d, nsyms=%d, indirsyms=%d (indirectsymoff=0x%x)' % (
        len(stubs), symtab[1], dysym[13] if dysym else -1, dysym[12] if dysym else 0))
    for a in sys.argv[2:]:
        v = int(a, 16)
        hit = None
        for name, addr, sflags, stride, istart in stubs:
            if addr <= v < addr + stride * ((istart and 0) or 1):
                pass
        for name, addr, sflags, stride, istart in stubs:
            # số stub = size/stride — tính từ size section: không có trong tuple, dùng khoảng cách tới stub kế
            if addr <= v:
                idx = (v - addr) // stride
                isym = istart + idx
                try:
                    nm, t = sym_name(d, symtab, isym)
                    print('0x%x (%s #%d) -> %s' % (v, name, idx, nm))
                    hit = True
                    break
                except Exception as e:
                    print('0x%x: lỗi đọc indirect #%d: %s' % (v, isym, e))
                    hit = True
                    break
        if not hit:
            print('0x%x: KHÔNG thuộc section stub nào' % v)
