#!/usr/bin/env python3
"""objcstubs.py - resolve __objc_stubs -> selector name (chained-fixup aware),
optionally list BL call sites for selectors matching a filter."""
import struct, sys
from machofix import MachO

def build(path):
    m = MachO(path)
    m.resolve_fixups()
    stub = m.sec('__objc_stubs')
    if not stub:
        return m, {}
    base, off, size = stub[2], stub[3], stub[4]
    out = {}
    o = off
    end = off + size - 8
    d = m.d
    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
            sl = m.ptr.get(page + disp)
            if sl and sl[0] == 'va':
                s = m.cstr(m.va2off(sl[1]))
                out[m.off2va(o)] = s
        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]
    filt = sys.argv[2] if len(sys.argv) > 2 else None
    m, stubs = build(path)
    print('stubs resolved:', len(stubs))
    for a, s in sorted(stubs.items()):
        if filt and filt.lower() not in s.lower():
            continue
        calls = bl_sites(m, a)
        print('  0x%x  %-32s calls=%s' % (a, s, [hex(x) for x in calls][:12]))
