#!/usr/bin/env python3
# indirect_sym.py - map __la_symbol_ptr slot -> symbol name qua LC_DYSYMTAB
import struct, sys, json

BIN = r"vn.gsm.md_6473405044_3.15.0_DecryptIPA_by_TTJB\Payload\Driver.app\Driver"
SLOTS = [int(x, 16) for x in sys.argv[1:]] or [0x101E34FA0]

data = open(BIN, "rb").read()
magic, cpu, sub, ftype, ncmds, sizeofcmds, flags, res = struct.unpack_from("<IiiIIIII", data, 0)
off = 32
symtab = None
dysym = None
sections = {}
for _ in range(ncmds):
    cmd, cmdsize = struct.unpack_from("<II", data, off)
    if cmd == 0x2:  # LC_SYMTAB
        symtab = struct.unpack_from("<IIII", data, off + 8)
    elif cmd == 0xB:  # LC_DYSYMTAB
        vals = struct.unpack_from("<18I", data, off + 8)
        dysym = vals
    elif cmd == 0x19:  # LC_SEGMENT_64
        name = data[off + 8:off + 24].rstrip(b"\0").decode()
        vmaddr, vmsize, fileoff, filesize = struct.unpack_from("<QQQQ", data, off + 24)
        nsects = struct.unpack_from("<I", data, off + 64)[0]
        so = off + 72
        for _ in range(nsects):
            sname = data[so:so + 16].rstrip(b"\0").decode()
            addr, size = struct.unpack_from("<QQ", data, so + 32)
            ss = data[so + 16:so + 32].rstrip(b"\0").decode()
            sflags = struct.unpack_from("<I", data, so + 64)[0]
            sres1 = struct.unpack_from("<I", data, so + 68)[0]
            sections[f"{ss},{sname}"] = (addr, size, struct.unpack_from("<I", data, so + 48)[0], sflags, sres1)
            so += 80
    off += cmdsize

symoff, nsyms, stroff, strsize = symtab
# LC_DYSYMTAB layout after cmd/cmdsize: ilocalsym,nlocalsym,iextdefsym,nextdefsym,
# iundefsym,nundefsym,tocoff,ntoc,modtaboff,nmodtab,extrefsymoff,nextrefsyms,
# indirectsymoff,nindirectsyms,extreloff,nextrel,locreloff,nlocrel
(i_localsym, n_localsym, i_extdef, n_extdef, i_undef, n_undef,
 tocoff, ntoc, modtaboff, nmodtab, extrefoff, nextref,
 indirectsymoff, nindirect, extreloff, nextrel, locreloff, nlocrel) = dysym
print(f"symtab: nsyms={nsyms}; indirectsymoff={indirectsymoff:#x} nindirect={nindirect}")

def sym_name(idx):
    e = symoff + 16 * idx
    strx = struct.unpack_from("<I", data, e)[0]
    end = data.find(b"\0", stroff + strx)
    return data[stroff + strx:end].decode("ascii", "replace")

def slot_sym(va):
    for key, (addr, size, soff, sflags, sres1) in sections.items():
        if addr <= va < addr + size:
            idx_in_sec = (va - addr) // 8
            print(f"  slot {va:#x} in {key} (flags={sflags:#x}, reserved1={sres1}): index_in_section={idx_in_sec}")
            return key, idx_in_sec, sres1
    return None, None, None

# Indirect table order is given by each section's reserved1
for va in SLOTS:
    key, idxs, res1 = slot_sym(va)
    if key is None:
        continue
    sidx = struct.unpack_from("<I", data, indirectsymoff + 4 * (res1 + idxs))[0]
    print(f"  indirect index {res1 + idxs} -> sym idx {sidx} -> {sym_name(sidx)}")
