#!/usr/bin/env python3
"""xref.py - find ADRP+ADD / ADRP+LDR references to target VAs in a Mach-O arm64 binary."""
import struct, sys

def load(path):
    d = open(path, 'rb').read()
    ncmds = struct.unpack_from('<I', d, 16)[0]
    off = 32
    segs = []
    text = None
    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]
            segs.append((seg, vm, fo, fs))
            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()
                addr = struct.unpack_from('<Q', s, 32)[0]
                sz = struct.unpack_from('<Q', s, 40)[0]
                sf = struct.unpack_from('<I', s, 48)[0]
                if sn == '__text':
                    text = (addr, sf, sz)
                so += 80
        off += size
    return d, segs, text

def va2off(segs, va):
    for seg, vm, fo, fs in segs:
        if vm <= va < vm+fs:
            return fo + (va-vm)
    return None

def off2va(segs, o):
    for seg, vm, fo, fs in segs:
        if fo <= o < fo+fs:
            return vm + (o-fo)
    return None

def xrefs(d, segs, text, target):
    addr, sf, sz = text
    out = []
    end = sf+sz-8
    o = sf
    while o < end:
        w0 = struct.unpack_from('<I', d, o)[0]
        # ADRP: 1xx10000
        if (w0 & 0x9F000000) == 0x90000000:
            w1 = struct.unpack_from('<I', d, o+4)[0]
            # ADD imm: 10001x...  (64-bit)
            if (w1 & 0xFFC00000) == 0x91000000:
                rd = w0 & 0x1F
                rn = w1 & 0x1F
                if rd == rn:
                    immhi = (w0 >> 5) & 0x7FFFF
                    immlo = (w0 >> 29) & 0x3
                    imm = (immhi << 2) | immlo
                    if imm & (1 << 20):
                        imm -= (1 << 21)
                    pc = off2va(segs, o)
                    if pc is None:
                        o += 4; continue
                    page = (pc & ~0xFFF) + (imm << 12)
                    add = ((w1 >> 10) & 0xFFF) << ((w1 >> 22) & 1)
                    if page + add == target:
                        out.append((pc, 'add', rd))
            # LDR (unsigned offset) 64-bit: 1111100101
            if (w1 & 0xFFC00000) == 0xF9400000:
                base = w0 & 0x1F
                rn = w1 & 0x1F
                if base == rn:
                    rd = w1 & 0x1F
                    immhi = (w0 >> 5) & 0x7FFFF
                    immlo = (w0 >> 29) & 0x3
                    imm = (immhi << 2) | immlo
                    if imm & (1 << 20):
                        imm -= (1 << 21)
                    pc = off2va(segs, o)
                    if pc is None:
                        o += 4; continue
                    page = (pc & ~0xFFF) + (imm << 12)
                    disp = ((w1 >> 10) & 0xFFF) * 8
                    if page + disp == target:
                        out.append((pc, 'ldr', rd))
        o += 4
    return out

if __name__ == '__main__':
    path = sys.argv[1]
    d, segs, text = load(path)
    print('text: addr=0x%x off=0x%x size=0x%x' % text)
    for a in sys.argv[2:]:
        t = int(a, 0)
        print('\n== target 0x%x (file 0x%x)' % (t, va2off(segs, t) or 0))
        for pc, kind, rd in xrefs(d, segs, text, t):
            print('  0x%x  %s x%d' % (pc, kind, rd))
