#!/usr/bin/env python3
"""Find __objc_selref slots for selector strings and code xrefs (ADRP+LDR) to them."""
import struct, sys
from capstone import Cs, CS_ARCH_ARM64, CS_MODE_ARM
from machofix import MachO

path = sys.argv[1]
targets = sys.argv[2:]

m = MachO(path)
m.resolve_fixups()
d = m.d

def find_str_va(s):
    b = s.encode()
    i = d.find(b)
    while i != -1:
        # must be a full c-string
        if i == 0 or d[i-1] == 0:
            j = i + len(b)
            if j < len(d) and d[j] == 0:
                return m.off2va(i)
        i = d.find(b, i+1)
    return None

def xrefs_to(va, n=12):
    out = []
    text = m.sec('__text')
    if not text:
        return out
    seg, sn, addr, off, size = text
    o = off
    end = off + size - 8
    while o < end:
        w0 = struct.unpack_from('<I', d, o)[0]
        if (w0 & 0x9F000000) == 0x90000000:
            w1 = struct.unpack_from('<I', d, o+4)[0]
            if (w1 & 0xFFC00000) == 0xF9400000:
                base = w0 & 0x1F
                rn = w1 & 0x1F
                if base == rn:
                    immhi = (w0 >> 5) & 0x7FFFF
                    immlo = (w0 >> 29) & 3
                    imm = (immhi << 2) | immlo
                    if imm & (1 << 20):
                        imm -= 1 << 21
                    pc = m.off2va(o)
                    page = (pc & ~0xFFF) + (imm << 12)
                    disp = ((w1 >> 10) & 0xFFF) * 8
                    if page + disp == va:
                        out.append((pc, 'ldr', w1 & 0x1F))
        o += 4
    return out

for t in targets:
    sva = find_str_va(t)
    print('== %s  strva=%s' % (t, hex(sva) if sva else None))
    if not sva:
        continue
    # find selref slot(s)
    sr = m.sec('__objc_selrefs')
    slots = []
    if sr:
        seg, sn, addr, off, size = sr
        for k in range(size // 8):
            slot_va = addr + k*8
            info = m.slot(slot_va)
            if info and info[0] == 'va' and info[1] == sva:
                slots.append(slot_va)
    print('   selref slots:', [hex(x) for x in slots])
    for slot in slots:
        xr = xrefs_to(slot)
        print('   xrefs to 0x%x: %s' % (slot, [hex(a) for a, k, r in xr]))
        for pc, kind, rd in xr:
            print('   --- around 0x%x ---' % pc)
            md = Cs(CS_ARCH_ARM64, CS_MODE_ARM)
            o = m.va2off(pc-0x20)
            for i in md.disasm(d[o:o+0x60], pc-0x20):
                mark = '>>' if i.address == pc else '  '
                print('   %s 0x%x  %-8s %s' % (mark, i.address, i.mnemonic, i.op_str))
