#!/usr/bin/env python3
"""stubmap.py - decode __objc_stubs in a Mach-O, resolve each to its selector,
then find all BL call sites to a given selector's stub."""
import struct, sys

def segs_of(d):
    ncmds = struct.unpack_from('<I', d, 16)[0]
    off = 32
    segs = []
    for _ in range(ncmds):
        cmd, size = struct.unpack_from('<II', d, off)
        if cmd == 0x19:
            seg = d[off+8:off+24].split(b'\0')[0].decode()
            vm = struct.unpack_from('<Q', d, off+24)[0]
            fo = struct.unpack_from('<Q', d, off+40)[0]
            fs = struct.unpack_from('<Q', d, off+48)[0]
            ns = struct.unpack_from('<I', d, off+64)[0]
            so = off+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]
                sz = struct.unpack_from('<Q', s, 40)[0]
                sf = struct.unpack_from('<I', s, 48)[0]
                segs.append((seg, sn, ad, sf, sz))
                so += 80
        off += size
    return segs

def rd_cstr(d, o):
    e = d.find(b'\0', o)
    return d[o:e].decode('ascii', 'replace')

def main(path):
    d = open(path, 'rb').read()
    segs = segs_of(d)
    def find(name):
        for s in segs:
            if s[1] == name:
                return s
        return None
    objc_stubs = find('__objc_stubs')
    selrefs = find('__objc_selrefs')
    methname = find('__objc_methname')
    text = find('__text')
    print('stubs @0x%x' % objc_stubs[2])

    # decode each stub: adrp xN, page ; ldr xN,[xN,#off] ; br xN
    stub_to_sel = {}
    o = objc_stubs[3]
    end = o + objc_stubs[4]
    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) & 0x3
            imm = (immhi << 2) | immlo
            if imm & (1 << 20):
                imm -= (1 << 21)
            page = ((o) & ~0xFFF) + (imm << 12)
            disp = ((w1 >> 10) & 0xFFF) * 8
            tgt = page + disp
            if selrefs[2] <= tgt < selrefs[2] + selrefs[4]:
                so = selrefs[3] + (tgt - selrefs[2])
                selptr = struct.unpack_from('<Q', d, so)[0]
                if methname[2] <= selptr < methname[2] + methname[4]:
                    mo = methname[3] + (selptr - methname[2])
                    stub_to_sel[o] = rd_cstr(d, mo)
        o += 12
    print('decoded stubs:', len(stub_to_sel))
    return d, segs, text, stub_to_sel

if __name__ == '__main__':
    d, segs, text, m = main(sys.argv[1])
    target = sys.argv[2] if len(sys.argv) > 2 else None
    if target:
        addrs = [a for a, s in m.items() if s == target]
        print('stubs for %r: %s' % (target, [hex(a) for a in addrs]))
        # find bl
        for sa in addrs:
            o = text[3]
            end = o + text[4] - 4
            hits = []
            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 (o + imm * 4) == sa:
                        hits.append(o)
                o += 4
            print('  bl @', [hex(h) for h in hits])
