#!/usr/bin/env python3
"""stubnames.py - resolve __stubs entries to imported symbol names via LIEF bindings."""
import struct, sys
import lief
from machofix import MachO

def build(path):
    m = MachO(path)
    b = lief.MachO.parse(path).at(0)
    bind = {}
    for x in b.bindings:
        bind[x.address] = str(x.symbol.name)
    st = m.sec('__stubs')
    out = {}
    if not st:
        return m, out
    base, off, size = st[2], st[3], st[4]
    d = m.d
    o = off
    end = off + size - 8
    while o < end:
        w0 = struct.unpack_from('<I', d, o)[0]
        w1 = struct.unpack_from('<I', d, o+4)[0]
        if (w0 & 0x9F000000) == 0x90000000 and (w1 & 0xFFC00000) == 0xF9400000:
            immhi = (w0 >> 5) & 0x7FFFF
            immlo = (w0 >> 29) & 3
            imm = (immhi << 2) | immlo
            if imm & (1 << 20):
                imm -= (1 << 21)
            page = (o & ~0xFFF) + (imm << 12)
            disp = ((w1 >> 10) & 0xFFF) * 8
            got = m.off2va(page + disp)
            name = bind.get(got) or bind.get(page+disp)
            out[m.off2va(o)] = name or ('?0x%x' % (page+disp))
        o += 4
    return m, out

def bl_sites(m, target):
    t = m.sec('__text')
    off, size = t[3], t[4]
    hits = []
    o = off
    end = off + size - 4
    d = m.d
    while o < end:
        w = struct.unpack_from('<I', d, o)[0]
        if (w & 0xFC000000) == 0x94000000:
            imm = w & 0x3FFFFFF
            if imm & (1 << 25):
                imm -= (1 << 26)
            if m.off2va(o) + imm * 4 == target:
                hits.append(m.off2va(o))
        o += 4
    return hits

if __name__ == '__main__':
    path = sys.argv[1]
    m, stubs = build(path)
    filt = sys.argv[2] if len(sys.argv) > 2 else None
    print('stubs:', len(stubs))
    for a, s in sorted(stubs.items()):
        if filt and filt.lower() not in s.lower():
            continue
        print('  0x%x  %-40s calls=%s' % (a, s, [hex(x) for x in bl_sites(m, a)][:10]))
