# -*- coding: utf-8 -*-
"""
scan_import_calls.py - tim cac call site (BL) toi stub cua symbol nhay cam.

Khong can analysis: doc Mach-O, dung LC_DYSYMTAB indirect symbol table de map
stub -> ten symbol, roi quet __TEXT tim BL co dich la stub do.
"""
import struct, sys, os

WANT = {
    '_exit', '_abort', '_kill', '_raise', '_posix_spawn', '_syscall', '_ptrace',
    '_task_info', '_task_get_exception_ports', '_sysctl', '_getppid',
    '_proc_pidinfo', '_csops', '_csops_audittoken', '_mprotect', '_vm_protect',
    '_dlopen', '_dlsym', '_getenv', '_fork', '_execve', '_setjmp', '_longjmp',
    '_sysctlbypid', '_thread_get_state', '_thread_info', '_mach_vm_protect',
}

def parse(p):
    d = open(p, 'rb').read()
    magic, cputype, cpusub, filetype, ncmds, sizeofcmds, flags = struct.unpack_from('<IiiIIII', d, 0)
    segs = []
    sections = []
    symtab = None
    dysymtab = None
    off = 32
    for _ in range(ncmds):
        cmd, size = struct.unpack_from('<II', d, off)
        if cmd == 0x19:
            name = d[off+8:off+24].rstrip(b'\x00').decode()
            vmaddr, vmsize, fileoff, filesize = struct.unpack_from('<QQQQ', d, off+24)
            segs.append((name, vmaddr, vmsize, fileoff, filesize))
            nsects, = struct.unpack_from('<I', d, off + 64)
            so = off + 72
            for _i in range(nsects):
                sname = d[so:so+16].rstrip(b'\x00').decode()
                segname = d[so+16:so+32].rstrip(b'\x00').decode()
                addr, sz = struct.unpack_from('<QQ', d, so+32)
                foff, = struct.unpack_from('<I', d, so+48)
                sections.append((segname, sname, addr, sz, foff))
                so += 80
        elif cmd == 0x2:   # LC_SYMTAB
            symtab = struct.unpack_from('<IIII', d, off+8)
        elif cmd == 0xb:   # LC_DYSYMTAB
            dysymtab = struct.unpack_from('<18I', d, off+8)
        off += size
    return d, segs, sections, symtab, dysymtab

def symname(d, symtab, idx):
    symoff, nsyms, stroff, strsize = symtab
    o = symoff + idx * 16
    if o + 16 > len(d):
        return None
    n_strx, n_type, n_sect, n_desc, n_value = struct.unpack_from('<IBBHQ', d, o)
    if n_strx >= strsize:
        return None
    s = stroff + n_strx
    e = d.find(b'\x00', s)
    return d[s:e].decode('ascii', 'replace')

def stub_map(d, sections, symtab, dysymtab):
    """tra ve dict vmaddr stub -> ten symbol"""
    if not symtab or not dysymtab:
        return {}
    symoff, nsyms, stroff, strsize = symtab
    indirectsymoff = dysymtab[12]
    nindirectsyms = dysymtab[13]
    ind = list(struct.unpack_from('<%dI' % nindirectsyms, d, indirectsymoff)) if nindirectsyms else []
    out = {}
    for segname, sname, addr, sz, foff in sections:
        if sname not in ('__stubs', '__got', '__la_symbol_ptr', '__auth_stubs'):
            continue
        entsize = 12 if 'stubs' in sname else 8
        n = sz // entsize
        start = None
        # tim offset cua section nay trong indirect symbol table
        # thu tu chuan: __stubs, __got, __la_symbol_ptr
        order = [s for s in sections if s[1] in ('__stubs', '__auth_stubs', '__got', '__la_symbol_ptr')]
        acc = 0
        for s in order:
            cnt = s[3] // (12 if 'stubs' in s[1] else 8)
            if s is not None and (s[0], s[1], s[2]) == (segname, sname, addr):
                start = acc
                break
            acc += cnt
        if start is None:
            continue
        for i in range(n):
            k = start + i
            if k >= len(ind):
                break
            nm = symname(d, symtab, ind[k])
            if nm:
                out[addr + i * entsize] = nm
    return out

def scan_bl(d, segs, targets):
    """quet __TEXT tim BL co dich nam trong targets (set vmaddr)"""
    text = next((s for s in segs if s[0] == '__TEXT'), None)
    if not text:
        return []
    _, vm, vs, fo, fs = text
    hits = []
    for o in range(fo, fo + fs - 4, 4):
        w, = struct.unpack_from('<I', d, o)
        if (w & 0xFC000000) != 0x94000000:
            continue
        imm = w & 0x03FFFFFF
        if imm & 0x02000000:
            imm -= 0x04000000
        pc = vm + (o - fo)
        tgt = pc + (imm << 2)
        if tgt in targets:
            hits.append((pc, tgt))
    return hits

def main():
    for p in sys.argv[1:]:
        if not os.path.exists(p):
            print('MISSING', p); continue
        d, segs, sections, symtab, dysymtab = parse(p)
        sm = stub_map(d, sections, symtab, dysymtab)
        interesting = {a: n for a, n in sm.items() if n in WANT}
        print('=== %s  (%d bytes)' % (os.path.basename(p), len(d)))
        print('    stubs mapped: %d ; interesting: %d' % (len(sm), len(interesting)))
        if not interesting:
            continue
        by_sym = {}
        for a, n in interesting.items():
            by_sym.setdefault(n, []).append(a)
        for n, addrs in sorted(by_sym.items()):
            hits = scan_bl(d, segs, set(addrs))
            if not hits:
                continue
            print('  %-28s stub=0x%x  callers=%d' % (n, addrs[0], len(hits)))
            for pc, tgt in hits[:24]:
                print('       call @ 0x%x' % pc)

if __name__ == '__main__':
    main()
