"""Side-effect-free structured disassembly for the WDC 65C816. The decode table is built from the opcode map the core executes (``_dispatch.OPCODES``), so the disassembler cannot disagree with the core about which opcode is which instruction or how it addresses memory. Syntax is WDC's (DS section 6, Table 5-4's mode names), as MAME prints it in upper case: ``LDA #$12`` or ``LDA #$1234`` (the width M or X gives), ``LDA $12``, ``LDA $1234``, ``LDA $123456``, ``LDA $12,X``, ``LDA ($12,X)``, ``LDA ($12),Y``, ``LDA [$12],Y``, ``LDA $12,S``, ``LDA ($12,S),Y``, ``JMP ($1234,X)``, ``JML [$1234]``, ``MVN $7E,$7F`` (source bank, then destination, as written; the bytes are the other way round), and branches with their 16-bit target in the program bank. Immediate operands are one byte or two by the M or X flag, so :func:`disassemble` takes the flags (``m`` and ``x`` True for 8 bits, as the pins show them); :func:`disassemble_bytes` reads the width from how many bytes it is given. """ from __future__ import annotations from collections.abc import Callable, Sequence from dataclasses import dataclass from w65c816._dispatch import OPCODES ByteReader = Callable[[int], int] #: Addressing modes, as ``Instruction.mode`` reports them (DS Table 5-4's #: column headings, in words). MODES = ( "implied", "accumulator", "stack", "immediate", "direct", "direct_x", "direct_y", "direct_indirect", "direct_indirect_long", "direct_indexed_indirect", "direct_indirect_indexed", "direct_indirect_long_indexed", "absolute", "absolute_x", "absolute_y", "absolute_long", "absolute_long_x", "absolute_indirect", "absolute_indirect_long", "absolute_indexed_indirect", "stack_relative", "stack_relative_indirect_indexed", "relative", "relative_long", "block_move", ) # The dispatch's mode names -> (mode, operand bytes, text template). "{}" is # the operand in hex, as wide as its bytes. _DATA_MODES = { "imm_m": ("immediate", "m", "#${}"), "imm_x": ("immediate", "x", "#${}"), "dp": ("direct", 1, "${}"), "dpx": ("direct_x", 1, "${},X"), "dpy": ("direct_y", 1, "${},Y"), "ind": ("direct_indirect", 1, "(${})"), "ind_long": ("direct_indirect_long", 1, "[${}]"), "idx": ("direct_indexed_indirect", 1, "(${},X)"), "idy": ("direct_indirect_indexed", 1, "(${}),Y"), "idy_w": ("direct_indirect_indexed", 1, "(${}),Y"), "ind_long_y": ("direct_indirect_long_indexed", 1, "[${}],Y"), "abs": ("absolute", 2, "${}"), "abx": ("absolute_x", 2, "${},X"), "abx_w": ("absolute_x", 2, "${},X"), "aby": ("absolute_y", 2, "${},Y"), "aby_w": ("absolute_y", 2, "${},Y"), "long": ("absolute_long", 3, "${}"), "long_x": ("absolute_long_x", 3, "${},X"), "sr": ("stack_relative", 1, "${},S"), "sr_y": ("stack_relative_indirect_indexed", 1, "(${},S),Y"), } # Handlers that decode their own operands -> (mnemonic, mode, bytes, template). _SELF_MODES = { "brk": ("BRK", "stack", 1, "#${}"), "cop": ("COP", "stack", 1, "#${}"), "wdm": ("WDM", "implied", 1, "#${}"), "rep": ("REP", "immediate", 1, "#${}"), "sep": ("SEP", "immediate", 1, "#${}"), "jmp": ("JMP", "absolute", 2, "${}"), "jsr": ("JSR", "absolute", 2, "${}"), "jml": ("JML", "absolute_long", 3, "${}"), "jsl": ("JSL", "absolute_long", 3, "${}"), "jmp_ind": ("JMP", "absolute_indirect", 2, "(${})"), "jmp_idx": ("JMP", "absolute_indexed_indirect", 2, "(${},X)"), "jsr_idx": ("JSR", "absolute_indexed_indirect", 2, "(${},X)"), "jml_ind": ("JML", "absolute_indirect_long", 2, "[${}]"), "pea": ("PEA", "stack", 2, "${}"), "pei": ("PEI", "stack", 1, "(${})"), "per": ("PER", "stack", 2, None), # relative long, shown as its target "brl": ("BRL", "relative_long", 2, None), "mvn": ("MVN", "block_move", 2, None), "mvp": ("MVP", "block_move", 2, None), } _BRANCHES = frozenset(("bpl", "bmi", "bvc", "bvs", "bcc", "bcs", "bne", "beq", "bra")) _STACK = frozenset( ["pha", "phb", "phd", "phk", "php", "phx", "phy", "pla", "plb", "pld", "plp", "plx", "ply", "rti", "rtl", "rts"] ) # fmt: skip @dataclass(frozen=True, slots=True) class Instruction: """One decoded instruction and the exact bytes it occupies.""" address: int # 24 bits: PBR << 16 | PC data: bytes mnemonic: str operands: tuple[str, ...] = () mode: str = "implied" #: The address the operand names -- direct-page offset, absolute or long #: address, pointer, or branch target -- before any indexing; None for #: implied, immediate and block-move forms. target: int | None = None def __post_init__(self) -> None: if type(self.address) is not int or not 0 <= self.address <= 0xFFFFFF: raise ValueError("address must be an integer in range 0x000000..0xFFFFFF") if type(self.data) is not bytes or not self.data: raise ValueError("data must contain at least one byte") if type(self.mnemonic) is not str or not self.mnemonic: raise ValueError("mnemonic must not be empty") if type(self.operands) is not tuple or not all(type(o) is str for o in self.operands): raise ValueError("operands must be a tuple of strings") if self.mode not in MODES: raise ValueError(f"mode must be one of {MODES}") @property def size(self) -> int: """Number of encoded bytes.""" return len(self.data) @property def next_address(self) -> int: """The address after the instruction: PC wraps within the program bank.""" return self.address & 0xFF0000 | (self.address + self.size) & 0xFFFF @property def text(self) -> str: """Canonical human-readable assembly text.""" return self.mnemonic if not self.operands else f"{self.mnemonic} {','.join(self.operands)}" def _form(opcode: int) -> tuple[str, str, int | str, str | None]: """(mnemonic, mode, operand bytes or "m"/"x", template) for one opcode.""" handler, mode = OPCODES[opcode] if mode is not None: data_mode, size, template = _DATA_MODES[mode] mnemonic = "BIT" if handler == "bit_imm" else handler.upper() return mnemonic, data_mode, size, template if handler in _SELF_MODES: return _SELF_MODES[handler] if handler in _BRANCHES: return handler.upper(), "relative", 1, None if handler.endswith("_a"): return handler[:-2].upper(), "accumulator", 0, "A" return handler.upper(), "stack" if handler in _STACK else "implied", 0, None #: (mnemonic, mode, operand bytes or "m"/"x", template) for each of the 256 opcodes. DECODE_TABLE: tuple[tuple[str, str, int | str, str | None], ...] = tuple( _form(opcode) for opcode in range(256) ) def operand_size(opcode: int, *, m: bool = True, x: bool = True) -> int: """Operand bytes after ``opcode`` with the M and X flags given (True = 8-bit).""" size = DECODE_TABLE[opcode][2] if size == "m": return 1 if m else 2 if size == "x": return 1 if x else 2 return size def _decode(data: bytes, address: int) -> Instruction: mnemonic, mode, _, template = DECODE_TABLE[data[0]] operand = int.from_bytes(data[1:], "little") width = 2 * (len(data) - 1) bank = address & 0xFF0000 operands: tuple[str, ...] = () target = None if mode in ("relative", "relative_long") or mnemonic == "PER": offset = operand - (0x100 if width == 2 else 0x10000) * (operand >> (4 * width - 1)) target = bank | (address + len(data) + offset) & 0xFFFF operands = (f"${target & 0xFFFF:04X}",) elif mode == "block_move": destination, source = data[1], data[2] operands = (f"${source:02X}", f"${destination:02X}") elif template == "A": operands = ("A",) elif template is not None: # Split at the commas, as 6502-python does: "($12,X)" -> "($12", "X)". operands = tuple(template.format(f"{operand:0{width}X}").split(",")) if mode != "immediate" and mnemonic not in ("BRK", "COP", "WDM"): target = operand return Instruction(address, bytes(data), mnemonic, operands, mode, target) def disassemble(reader: ByteReader, address: int, *, m: bool = True, x: bool = True) -> Instruction: """Decode the instruction at 24-bit ``address`` using only ``reader``. ``reader`` must be side-effect-free (a peek, not the host's bus read). ``m`` and ``x`` are the flags the instruction will run with (True: 8-bit), which set an immediate operand's width. The bytes after the opcode wrap within the bank, as the program counter does. """ if type(address) is not int or not 0 <= address <= 0xFFFFFF: raise ValueError("address must be an integer in range 0x000000..0xFFFFFF") bank = address & 0xFF0000 opcode = _byte(reader, address) size = operand_size(opcode, m=m, x=x) data = bytes( (opcode, *(_byte(reader, bank | (address + n) & 0xFFFF) for n in range(1, size + 1))) ) return _decode(data, address) def disassemble_bytes(data: Sequence[int] | bytes, address: int = 0) -> Instruction: """Decode exactly one instruction from ``data``, whose first byte sits at ``address``: an immediate operand is as wide as the bytes given.""" copy = bytes(data) if not copy: raise ValueError("data must not be empty") size = DECODE_TABLE[copy[0]][2] if size in ("m", "x"): if len(copy) not in (2, 3): raise ValueError(f"an immediate operand is 1 or 2 bytes, not {len(copy) - 1}") elif len(copy) != 1 + size: raise ValueError(f"opcode ${copy[0]:02X} takes {size} operand bytes, not {len(copy) - 1}") return _decode(copy, address) def disassemble_range( reader: ByteReader, address: int, count: int, *, m: bool = True, x: bool = True ) -> list[Instruction]: """Decode ``count`` consecutive instructions, all with the same M and X.""" listing = [] for _ in range(count): instruction = disassemble(reader, address, m=m, x=x) listing.append(instruction) address = instruction.next_address return listing def _byte(reader: ByteReader, address: int) -> int: value = reader(address) if type(value) is not int or not 0 <= value <= 0xFF: raise ValueError(f"byte reader returned a non-byte value at 0x{address:06X}") return value __all__ = [ "DECODE_TABLE", "MODES", "ByteReader", "Instruction", "disassemble", "disassemble_bytes", "disassemble_range", "operand_size", ]