#!/usr/bin/env python3
"""Map __got/__la_symbol_ptr slots to imported symbol names and find callers of
exit/abort/raise stubs in a fixed-up Mach-O."""
import struct, sys, os, bisect
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from machofix import MachO


def sx21(v):
    return v - (1 << 21) if v & (1 << 20) else v


def func_starts(d):
    n = struct.unpack_from('<I', d, 16)[0]
    o = 32
    fs = None
    for _ in range(n):
        cmd, sz = struct.unpack_from('<II', d, o)
        if cmd == 0x26:
            fs = struct.unpack_from('<II', d, o+8)
        o += sz
    if not fs:
        return []
    off, size = fs
    base = 0; starts = []; i = off
    while i < off+size:
        v = 0; sh = 0
        while True:
            b = d[i]; i += 1
            v |= (b & 0x7f) << sh; sh += 7
            if not b & 0x80: break
        if v == 0: break
        base += v; starts.append(base)
    return starts


def parse(path):
    m = MachO(path)
    d = m.d
    # symbol table names (nlist) -> we need index mapping for indirect symbols
    symoff, nsyms, stroff = m.symtab[0], m.symtab[1], m.symtab[2]
    names = []
    for k in range(nsyms):
        e = symoff + k*16
        strx = struct.unpack_from('<I', d, e)[0]
        end = d.find(b'\0', stroff+strx)
        names.append(d[stroff+strx:end].decode('latin1', 'replace'))
    # LC_DYSYMTAB
    n = struct.unpack_from('<I', d, 16)[0]
    o = 32
    dysym = None
    for _ in range(n):
        cmd, sz = struct.unpack_from('<II', d, o)
        if cmd == 0xb:
            dysym = struct.unpack_from('<18I', d, o+8)
        o += sz
    if not dysym:
        print('no dysymtab'); return
    # indices: ilocalsym=0,nlocalsym=1,iextdefsym=2,nextdefsym=3,iundefsym=4,nundefsym=5,
    # tocoff=6,ntoc=7, modtaboff=8,nmodtab=9, extrefsymoff=10,nextrefsyms=11,
    # indirectsymoff=12,nindirectsyms=13, extreloff=14,nextrel=15,locreloff=16,nlocrel=17
    indirectoff = dysym[12]; nindirect = dysym[13]
    secs = {}
    for seg, sn, ad, sf, sz in m.sections:
        secs[sn] = (ad, sf, sz)
    got = {}
    for secname in ('__got', '__la_symbol_ptr', '__auth_got'):
        if secname not in secs:
            continue
        ad, sf, sz = secs[secname]
        for i in range(sz//8):
            idx = struct.unpack_from('<I', d, indirectoff + (sf//8 + i)*4)[0] if False else None
        # indirect symbol index base = section offset / 8 ... actually index is by entry number
        for i in range(sz//8):
            ii = struct.unpack_from('<I', d, indirectoff + (i + 0)*4)[0]
    # proper: indirect symbols array is indexed per section in order of sections that need them
    # Walk sections in order, consume nindirect entries for those with type S_NON_LAZY_SYMBOL_POINTERS(6)/S_LAZY_SYMBOL_POINTERS(7)/S_SYMBOL_STUBS(8)
    # machofix didn't keep type/flags; reparse sections with type
    ncmds = struct.unpack_from('<I', d, 16)[0]
    o = 32
    rawsecs = []
    for _ in range(ncmds):
        cmd, sz = struct.unpack_from('<II', d, o)
        if cmd == 0x19:
            ns = struct.unpack_from('<I', d, o+64)[0]
            so = o+72
            for _ in range(ns):
                s = d[so:so+80]
                sn = s[:16].split(b'\0')[0].decode()
                ad = struct.unpack_from('<Q', s, 32)[0]
                ssz = struct.unpack_from('<Q', s, 40)[0]
                sf = struct.unpack_from('<I', s, 48)[0]
                flags = struct.unpack_from('<I', s, 64)[0]
                rawsecs.append((sn, ad, sf, ssz, flags))
                so += 80
        o += sz
    indirect_idx = 0
    gotmap = {}
    for sn, ad, sf, ssz, flags in rawsecs:
        typ = flags & 0xFF
        if typ in (6, 7):  # non-lazy / lazy symbol pointers
            for i in range(ssz//8):
                if indirect_idx + i < nindirect:
                    si = struct.unpack_from('<I', d, indirectoff + (indirect_idx+i)*4)[0]
                    if si < len(names):
                        gotmap[sf + i*8] = (names[si], ad + i*8)
            indirect_idx += ssz//8
        elif typ == 8:  # symbol stubs
            indirect_idx += ssz//8  # stub size varies; approximate
    return m, d, gotmap, func_starts(d)


def find_stubs(d, slot_off):
    stubs = []
    for off in range(0, len(d)-8, 4):
        w0 = struct.unpack_from('<I', d, off)[0]
        if (w0 & 0x9F000000) != 0x90000000:
            continue
        imm = sx21(((w0 >> 5) & 0x7FFFF) << 2 | ((w0 >> 29) & 3))
        page = (off & ~0xFFF) + (imm << 12)
        w1 = struct.unpack_from('<I', d, off+4)[0]
        if (w1 & 0xFFC00000) != 0xF9400000:
            continue
        if page + ((w1 >> 10) & 0xFFF)*8 == slot_off:
            stubs.append(off)
    return stubs


def main(path):
    m, d, gotmap, starts = parse(path)
    print('%s: got slots %d, funcs %d' % (os.path.basename(path), len(gotmap), len(starts)))
    bls = []
    for off in range(0, len(d)-4, 4):
        w = struct.unpack_from('<I', d, off)[0]
        if (w & 0xFC000000) != 0x94000000:
            continue
        imm = w & 0x3FFFFFF
        if imm & 0x2000000:
            imm -= 0x4000000
        bls.append((off, off+imm*4))

    def fn(a):
        k = bisect.bisect_right(starts, a)-1
        return starts[k], (starts[k+1] if k+1 < len(starts) else 0)

    interesting = ('_exit', '__exit', '_abort', '_raise', '_kill', '_ptrace',
                   '_thread_terminate', '_thread_suspend', '_UIApplicationMain',
                   '_dlopen', '_dlsym', '_sysctl', '_sysctlbyname', '_fork', '_posix_spawn')
    for slot, (nm, va) in sorted(gotmap.items()):
        if nm in interesting:
            stubs = find_stubs(d, slot)
            calls = []
            for st in stubs:
                calls += [(c, st) for c, t in bls if t == st]
            print('  %-22s slot=%#x va=%#x stubs=%s calls=%s' % (nm, slot, va, [hex(x) for x in stubs], [hex(c) for c, _ in calls]))
            for c, st in calls:
                a, b = fn(c)
                print('      call %#x in func %#x..%#x' % (c, a, b))


if __name__ == '__main__':
    main(sys.argv[1])
