#!/usr/bin/env python3
"""Annotated disassembly for Driver (va2off = va - 0x100000000). Resolves
adrp/ldr slots to ObjC class names, selector strings, or C strings."""
import struct, sys
import capstone

BASE = 0x100000000


def sx21(v):
    return v - (1 << 21) if v & (1 << 20) else v


class Ann:
    def __init__(self, path):
        self.d = open(path, 'rb').read()
        self.md = capstone.Cs(capstone.CS_ARCH_ARM64, capstone.CS_MODE_ARM)
        self.md.detail = False

    def off(self, va):
        return va - BASE

    def q(self, slot_off):
        # adrp targets are PC-relative to the file offset we disassemble at,
        # so the computed slot is a file offset.
        o = slot_off
        if 0 <= o <= len(self.d) - 8:
            return struct.unpack_from('<Q', self.d, o)[0]
        return None

    def cstr(self, va):
        o = self.off(va)
        if not (0 <= o < len(self.d)):
            return None
        e = self.d.find(b'\0', o)
        if e < 0 or e - o > 160:
            return None
        try:
            s = self.d[o:e].decode('utf-8')
        except Exception:
            return None
        return s if all(0x20 <= ord(c) < 0x7f for c in s) else None

    def class_name(self, clsva):
        o = self.off(clsva)
        if not (0 <= o < len(self.d) - 40):
            return None
        try:
            data = struct.unpack_from('<Q', self.d, o + 32)[0] & ~7
            do = self.off(data)
            namep = struct.unpack_from('<Q', self.d, do + 24)[0]
            return self.cstr(namep)
        except Exception:
            return None

    def annotate(self, lo, hi):
        regs = {}
        for ins in self.md.disasm(self.d[lo:hi], lo):
            note = ''
            ops = ins.op_str
            if ins.mnemonic == 'adrp':
                try:
                    r = ops.split(',')[0].strip()
                    regs[r] = int(ops.split('#')[1], 0)
                except Exception:
                    pass
            elif ins.mnemonic in ('ldr', 'ldur') and '[' in ops:
                try:
                    base = ops.split('[')[1].split(']')[0]
                    parts = [x.strip() for x in base.split(',')]
                    b = parts[0]
                    if b in regs:
                        disp = int(parts[1].lstrip('#'), 0) if len(parts) > 1 else 0
                        slot = regs[b] + disp
                        raw = self.q(slot)
                        if raw:
                            cn = self.class_name(raw)
                            if cn:
                                note = '; CLASS %s' % cn
                            else:
                                s = self.cstr(raw)
                                if s:
                                    note = '; "%s"' % s
                                else:
                                    note = '; slot %#x = %#x' % (slot, raw)
                except Exception:
                    pass
            print('%#011x  %-9s %-46s %s' % (BASE + ins.address, ins.mnemonic, ops, note))


if __name__ == '__main__':
    p = sys.argv[1]
    lo = int(sys.argv[2], 0)
    hi = int(sys.argv[3], 0)
    Ann(p).annotate(lo, hi)
