#!/usr/bin/env python3
"""resolve_symbols.py - doc symbol gia lap (bind/export/indirect) cua Mach-O arm64.

  python resolve_symbols.py <binary> export
  python resolve_symbols.py <binary> slot 0x42c1d0 0x42c6e8     # __stubs/__got/__la_symbol_ptr
  python resolve_symbols.py <binary> stub 0x3d1f4c 0x3a6e74     # stub -> symbol (+ slot no load)
  python resolve_symbols.py <binary> objc 0x3a94c0              # __objc_stubs -> selref + selector
  python resolve_symbols.py <binary> sel  0x455f70              # selref -> selector name (qua bind)

Thu tu indirect symbol table = THU TU SECTION trong file:
    __stubs (idx 0..n_st-1) -> __got (n_st..) -> __la_symbol_ptr
=> stub i -> indirect[i]; got j -> indirect[n_st+j]; la k -> indirect[n_st+n_got+k].

Da kiem chung tren 3.19.0:
  - bshield: n_st=269, n_got=61, n_la=269, indirect=599.
  - module C: n_st=447, n_got=149, n_la=443, indirect=1039.
  - stub 0x3a6e74 (idx 417) -> indirect[417] = _swift_getInitializedObjCClass
    va slot no load 0x43d190 (la k=413) -> indirect[1009] = cung symbol (self-consistent).
  - gia thuyet "la -> got -> stubs" bi bac bo: la k=413 se ra indirect[856] = ___cxa_free_exception.

Luu y: __objc_stubs (stub goi objc_msgSend) KHONG nam trong indirect table; phai dung mode 'objc'.
"""
import struct
import sys

SEG_CMD = 0x19
SYMTAB = 0x2
DYSYMTAB = 0xB
DYLD_INFO = (0x22, 0x80000022)
STUB_SIZE = 12


def load(path):
    d = open(path, "rb").read()
    if d[:4] not in (b"\xcf\xfa\xed\xfe", b"\xce\xfa\xed\xfe"):
        raise SystemExit("not a thin 64-bit Mach-O")
    ncmds = struct.unpack_from("<I", d, 16)[0]
    off = 32
    segs, secs = [], []
    symtab = dysym = dyldinfo = None
    for _ in range(ncmds):
        cmd, size = struct.unpack_from("<II", d, off)
        if cmd == SEG_CMD:
            name = d[off + 8:off + 24].rstrip(b"\x00").decode()
            vm, vs, fo, fs = struct.unpack_from("<QQQQ", d, off + 24)
            segs.append((name, vm, vs, fo, fs))
            ns = struct.unpack_from("<I", d, off + 64)[0]
            so = off + 72
            for _i in range(ns):
                sn = d[so:so + 16].rstrip(b"\x00").decode()
                sg = d[so + 16:so + 32].rstrip(b"\x00").decode()
                a, sz = struct.unpack_from("<QQ", d, so + 32)
                f = struct.unpack_from("<I", d, so + 48)[0]
                secs.append((sg, sn, a, sz, f))
                so += 80
        elif cmd == SYMTAB:
            symtab = struct.unpack_from("<4I", d, off + 8)
        elif cmd == DYSYMTAB:
            dysym = struct.unpack_from("<18I", d, off + 8)
        elif cmd in DYLD_INFO:
            dyldinfo = struct.unpack_from("<10I", d, off + 8)
        off += size
    return d, segs, secs, symtab, dysym, dyldinfo


def reader(d, segs):
    def rd(a, n):
        for _n, vm, vs, fo, fs in segs:
            if vm <= a < vm + fs:
                o = fo + (a - vm)
                return d[o:o + n]
        return b""
    return rd


def sym_name(d, symtab, idx):
    symoff, nsyms, stroff, strsize = symtab
    if idx >= nsyms:
        return "BAD_INDEX(%d)" % idx
    o = symoff + idx * 16
    ns, nt, nsec, nd, nv = struct.unpack_from("<IBBHQ", d, o)
    e = d.find(b"\x00", stroff + ns)
    return d[stroff + ns:e].decode("ascii", "replace")


def sec(secs, name):
    for sg, sn, a, sz, f in secs:
        if sn == name:
            return (sg, sn, a, sz, f)
    return None


def indirect(d, dysym):
    off, cnt = dysym[12], dysym[13]
    return [struct.unpack_from("<I", d, off + i * 4)[0] for i in range(cnt)]


def layout(secs):
    """tra ve (stubs, got, la) theo thu tu section trong file + cac base cua indirect."""
    order = [s for s in secs if s[1] in ("__stubs", "__got", "__la_symbol_ptr")]
    base, bases = 0, {}
    for sg, sn, a, sz, f in order:
        cnt = sz // (STUB_SIZE if sn == "__stubs" else 8)
        bases[sn] = base
        base += cnt
    return bases, base


def slot_pos(secs, bases, addr):
    st, got, la = sec(secs, "__stubs"), sec(secs, "__got"), sec(secs, "__la_symbol_ptr")
    if st and st[2] <= addr < st[2] + st[3]:
        return "__stubs", bases["__stubs"] + (addr - st[2]) // STUB_SIZE
    if got and got[2] <= addr < got[2] + got[3]:
        return "__got", bases["__got"] + (addr - got[2]) // 8
    if la and la[2] <= addr < la[2] + la[3]:
        return "__la_symbol_ptr", bases["__la_symbol_ptr"] + (addr - la[2]) // 8
    return None, None


def cmd_export(d, secs, symtab, dysym, dyldinfo):
    if not dyldinfo:
        print("no LC_DYLD_INFO")
        return
    eo, es = dyldinfo[8], dyldinfo[9]
    if es == 0:
        print("export trie empty")
        return
    out = []

    def uleb(i):
        r = sh = 0
        while True:
            b = d[i]
            i += 1
            r |= (b & 0x7F) << sh
            sh += 7
            if not (b & 0x80):
                return r, i

    def walk(o, prefix, depth=0):
        if depth > 64:
            return
        i = o
        tsize, i = uleb(i)
        if tsize:
            out.append(prefix)
        i += tsize
        cnt = d[i]
        i += 1
        for _ in range(cnt):
            e = d.find(b"\x00", i)
            edge = d[i:e].decode("ascii", "replace")
            i = e + 1
            child, i = uleb(i)
            walk(eo + child, prefix + edge, depth + 1)

    walk(eo, "")
    print("export trie @0x%x size=0x%x -> %d ten" % (eo, es, len(out)))
    for n in sorted(out):
        print("  " + n)


def cmd_slot(d, secs, symtab, dysym, addrs):
    bases, total = layout(secs)
    tbl = indirect(d, dysym)
    print("indirect: %d entry (stubs=%d, got=%d, la=%d)"
          % (len(tbl), bases.get("__got", 0) - bases.get("__stubs", 0),
             bases.get("__la_symbol_ptr", 0) - bases.get("__got", 0),
             len(tbl) - bases.get("__la_symbol_ptr", 0)))
    for a in addrs:
        name, pos = slot_pos(secs, bases, a)
        if name is None:
            print("0x%x: khong thuoc __stubs/__got/__la_symbol_ptr" % a)
            continue
        print("0x%x  %-16s indirect[%d] = %s" % (a, name, pos, sym_name(d, symtab, tbl[pos])))


def cmd_stub(d, secs, symtab, dysym, addrs):
    bases, total = layout(secs)
    tbl = indirect(d, dysym)
    for a in addrs:
        name, pos = slot_pos(secs, bases, a)
        if name != "__stubs":
            print("0x%x: khong thuoc __stubs" % a)
            continue
        idx = pos - bases["__stubs"]
        print("0x%x  stub idx=%d  indirect[%d] = %s"
              % (a, idx, pos, sym_name(d, symtab, tbl[pos])))


def cmd_objc(d, secs, symtab, dysym, addrs, bind, rd):
    st = sec(secs, "__objc_stubs")
    if not st:
        print("no __objc_stubs")
        return
    sa, ssz = st[2], st[3]
    n = ssz // 0x20
    for a in addrs:
        if not (sa <= a < sa + ssz):
            print("0x%x: khong thuoc __objc_stubs" % a)
            continue
        idx = (a - sa) // 0x20
        print("0x%x  objc stub idx=%d/%d" % (a, idx, n))
        code = rd(a, 0x14)
        pg1 = pg16 = selref = msgsend = None
        for k in range(0, len(code), 4):
            w, = struct.unpack_from("<I", code, k)
            if (w & 0x9F000000) == 0x90000000:              # adrp
                rd_ = w & 0x1F
                imm = (((w >> 5) & 0x7FFFF) << 2) | ((w >> 29) & 3)
                imm = imm - (1 << 21) if imm & (1 << 20) else imm
                page = ((a + k) & ~0xFFF) + (imm << 12)
                if rd_ == 1:
                    pg1 = page
                elif rd_ == 16:
                    pg16 = page
            elif (w & 0xFFC00000) == 0xF9400000:             # ldr (unsigned offset)
                imm12 = (w >> 10) & 0xFFF
                rn = (w >> 5) & 0x1F
                rdl = w & 0x1F
                if rn == 1 and rdl == 1 and pg1 is not None:
                    selref = pg1 + imm12 * 8
                elif rn == 16 and rdl == 16 and pg16 is not None:
                    msgsend = pg16 + imm12 * 8
        if selref is not None:
            v, txt = sel_target(secs, d, rd, selref)
            print("    selref=0x%x -> %s" % (selref, txt or ("0x%x" % v if v else "?")))
        if msgsend is not None:
            bases, _ = layout(secs)
            nm, pos = slot_pos(secs, bases, msgsend)
            if pos is not None:
                print("    msgSend slot=0x%x -> %s"
                      % (msgsend, sym_name(d, symtab, indirect(d, dysym)[pos])))
            else:
                print("    msgSend slot=0x%x (ngoai bang)" % msgsend)


def parse_bind(d, off, size, segs):
    i, end = off, off + size
    addr, name = 0, None
    out = {}

    def uleb(i):
        r = sh = 0
        while True:
            b = d[i]
            i += 1
            r |= (b & 0x7F) << sh
            sh += 7
            if not (b & 0x80):
                return r, i

    def sleb(i):
        r = sh = 0
        while True:
            b = d[i]
            i += 1
            r |= (b & 0x7F) << sh
            sh += 7
            if not (b & 0x80):
                if b & 0x40:
                    r |= -(1 << sh)
                return r, i

    while i < end:
        b = d[i]
        i += 1
        op, imm = b & 0xF0, b & 0x0F
        if op == 0x00:
            break
        elif op in (0x10, 0x30, 0x50):
            pass
        elif op == 0x20:
            _v, i = uleb(i)
        elif op == 0x40:
            e = d.find(b"\x00", i)
            name = d[i:e].decode("ascii", "replace")
            i = e + 1
        elif op == 0x60:
            _v, i = sleb(i)
        elif op == 0x70:
            v, i = uleb(i)
            addr = segs[imm][1] + v
        elif op == 0x80:
            v, i = uleb(i)
            addr += v
            out[addr] = name
            addr += 8
        elif op == 0x90:
            out[addr] = name
            addr += 8
        elif op == 0xA0:
            v, i = uleb(i)
            out[addr] = name
            addr += 8 + v
        elif op == 0xB0:
            out[addr] = name
            addr += 8 + imm * 8
        elif op == 0xC0:
            cnt, i = uleb(i)
            skip, i = uleb(i)
            for _k in range(cnt):
                out[addr] = name
                addr += 8 + skip
        else:
            break
    return out


def sel_target(secs, d, rd, a):
    """doc selref: tra ve (gia tri tho, ten selector hoac None)."""
    raw = rd(a, 8)
    if len(raw) < 8:
        return None, None
    v = struct.unpack("<Q", raw)[0]
    for sg, sn, sa, ssz, f in secs:
        if sn in ("__objc_methname", "__cstring", "__objc_classname") and sa <= v < sa + ssz:
            e = d.find(b"\x00", f + (v - sa))
            return v, d[f + (v - sa):e].decode("ascii", "replace")
    return v, None


def cmd_sel(d, secs, symtab, dysym, dyldinfo, addrs, bind, rd):
    for a in addrs:
        v, txt = sel_target(secs, d, rd, a)
        if v is None:
            print("0x%x: ngoai vung doc duoc" % a)
        elif txt is not None:
            print("0x%x -> 0x%x  %r" % (a, v, txt))
        else:
            print("0x%x -> 0x%x  (khong phai chuoi; bind=%s)"
                  % (a, v, bind.get(a, "?")))


def main():
    if len(sys.argv) < 3:
        print(__doc__)
        return 1
    path, mode = sys.argv[1], sys.argv[2]
    d, segs, secs, symtab, dysym, dyldinfo = load(path)
    addrs = [int(x, 16) for x in sys.argv[3:]]
    if mode == "export":
        cmd_export(d, secs, symtab, dysym, dyldinfo)
    elif mode == "slot":
        cmd_slot(d, secs, symtab, dysym, addrs)
    elif mode == "stub":
        cmd_stub(d, secs, symtab, dysym, addrs)
    elif mode in ("objc", "sel"):
        if not dyldinfo:
            print("no LC_DYLD_INFO -> khong parse duoc bind")
            return 1
        bind = parse_bind(d, dyldinfo[2], dyldinfo[3], segs)
        rd = reader(d, segs)
        if mode == "objc":
            cmd_objc(d, secs, symtab, dysym, addrs, bind, rd)
        else:
            cmd_sel(d, secs, symtab, dysym, dyldinfo, addrs, bind, rd)
    else:
        print(__doc__)
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())
