"""The disassembler against the datasheet's opcode matrix and the core itself. Every opcode names Table 5-4's mnemonic and a mode that is its column, and for every instruction that does not jump, the core's PC moves past exactly the bytes the disassembler says it occupies, in each M/X width. The slow test reads MAME 0.285's own disassembly of real code (``cpu.trace`` beside each rung 4 trace) and compares it line by line. """ import re from pathlib import Path import pytest from datasheet import OPCODES as TABLE from mame_replay import read_log from w65c816 import W65C816 from w65c816.disasm import ( DECODE_TABLE, disassemble, disassemble_bytes, disassemble_range, operand_size, ) from w65c816.harness import Harness # DS Table 5-4's mode notation -> the disassembler's modes for it. DS_MODES = { "i": {"implied"}, "A": {"accumulator"}, "s": {"stack"}, "#": {"immediate"}, "d": {"direct"}, "d,x": {"direct_x"}, "d,y": {"direct_y"}, "(d)": {"direct_indirect"}, "[d]": {"direct_indirect_long"}, "(d,x)": {"direct_indexed_indirect"}, "(d),y": {"direct_indirect_indexed"}, "[d],y": {"direct_indirect_long_indexed"}, "a": {"absolute"}, "a,x": {"absolute_x"}, "a,y": {"absolute_y"}, "al": {"absolute_long"}, "al,x": {"absolute_long_x"}, "(a)": {"absolute_indirect", "absolute_indirect_long"}, # JMP (a), JML (a) = [a] "(a,x)": {"absolute_indexed_indirect"}, "d,s": {"stack_relative"}, "(d,s),y": {"stack_relative_indirect_indexed"}, "r": {"relative"}, "rl": {"relative_long"}, "xyc": {"block_move"}, } JUMPS = {"BRK", "COP", "JMP", "JML", "JSR", "JSL", "RTI", "RTL", "RTS", "BRL", "MVN", "MVP"} JUMPS |= {"BPL", "BMI", "BVC", "BVS", "BCC", "BCS", "BNE", "BEQ", "BRA", "WAI", "STP"} @pytest.mark.parametrize("opcode", range(256)) def test_mnemonic_and_mode_are_table_5_4s(opcode: int) -> None: mnemonic, mode = TABLE[opcode] decoded, decoded_mode, _, _ = DECODE_TABLE[opcode] assert decoded == mnemonic assert decoded_mode in DS_MODES[mode] @pytest.mark.parametrize("m", [True, False]) @pytest.mark.parametrize("x", [True, False]) def test_the_core_runs_past_exactly_the_decoded_bytes(m: bool, x: bool) -> None: for opcode in range(256): if TABLE[opcode][0] in JUMPS: continue memory = bytearray(1 << 24) memory[0x018000] = opcode cpu = W65C816(memory.__getitem__, memory.__setitem__) cpu.e, cpu.pbr, cpu.pc, cpu.s = 0, 0x01, 0x8000, 0x1FF cpu.p = (0x20 if m else 0) | (0x10 if x else 0) cpu.step() size = 1 + operand_size(opcode, m=m, x=x) assert cpu.pc - 0x8000 == size, f"opcode {opcode:02X}" assert disassemble(memory.__getitem__, 0x018000, m=m, x=x).size == size def test_syntax_is_wdcs() -> None: cases = { "A9 12": "LDA #$12", "A9 34 12": "LDA #$1234", "AD 34 12": "LDA $1234", "AF 56 34 12": "LDA $123456", "BF 56 34 12": "LDA $123456,X", "B5 10": "LDA $10,X", "B6 10": "LDX $10,Y", "A1 10": "LDA ($10,X)", "B1 10": "LDA ($10),Y", "B2 10": "LDA ($10)", "A7 10": "LDA [$10]", "B7 10": "LDA [$10],Y", "A3 04": "LDA $04,S", "B3 04": "LDA ($04,S),Y", "6C 00 90": "JMP ($9000)", "7C 00 90": "JMP ($9000,X)", "DC 00 90": "JML [$9000]", "FC 00 90": "JSR ($9000,X)", "5C 56 34 12": "JML $123456", "54 7F 7E": "MVN $7E,$7F", "44 7F 7E": "MVP $7E,$7F", "D0 FE": "BNE $8000", "82 FD FF": "BRL $8000", "62 00 00": "PER $8003", "F4 34 12": "PEA $1234", "D4 10": "PEI ($10)", "C2 30": "REP #$30", "00 00": "BRK #$00", "0A": "ASL A", "EB": "XBA", } for encoded, text in cases.items(): assert disassemble_bytes(bytes.fromhex(encoded), 0x7E8000).text == text, encoded def test_targets_and_wrapping() -> None: branch = disassemble_bytes(bytes.fromhex("80 FE"), 0x7E8000) assert branch.target == 0x7E8000 and branch.next_address == 0x7E8002 assert disassemble_bytes(bytes.fromhex("EA"), 0x01FFFF).next_address == 0x010000 memory = {0x01FFFF: 0xAD, 0x010000: 0x34, 0x010001: 0x12} wrapped = disassemble(memory.__getitem__, 0x01FFFF) assert wrapped.text == "LDA $1234" # the operand bytes wrap within the bank listing = disassemble_range(bytes(16).__getitem__, 0, 3) assert [i.address for i in listing] == [0, 2, 4] # BRK takes its signature byte with pytest.raises(ValueError, match="takes 2 operand bytes"): disassemble_bytes(bytes.fromhex("AD 34")) TRACES = Path(__file__).resolve().parent / "mame_traces" INSTRUCTION_LINE = re.compile(r"[0-9A-F]{2}:[0-9A-F]{4}: ") TRACED = sorted(d.name for d in TRACES.glob("*") if (d / "cpu.trace").is_file()) # MAME's spellings of the same instructions (g65816ds.cpp): accumulator forms # run together, JML al as JMP, JML (a) in parentheses as the datasheet's # table writes it, a stack offset unpadded, and a space in MVN/MVP's operands. MAME_SPELLINGS = { "ASLA": "ASL A", "LSRA": "LSR A", "ROLA": "ROL A", "RORA": "ROR A", "INA": "INC A", "DEA": "DEC A", } def _mame_text(line: str) -> str: """MAME's line in this disassembler's spelling: ``bne 008034 (-$16)`` -> ``BNE $8034``, ``asla`` -> ``ASL A``, ``jml ($1234)`` -> ``JML [$1234]``.""" text = line.split(": ", 1)[1].strip().upper() words = text.split() if len(words) == 3 and words[2].startswith("(") and len(words[1]) == 6: return f"{words[0]} ${words[1][2:]}" if words[0] == "JML" and words[1].startswith("("): return f"JML [{words[1][1:-1]}]" if words[0] == "JMP" and re.fullmatch(r"\$[0-9A-F]{6}", words[1]): return f"JML {words[1]}" if words[0] in ("MVN", "MVP"): return text.replace(", ", ",") text = re.sub(r"\$([0-9A-F]),S", r"$0\1,S", text) return MAME_SPELLINGS.get(text, text) @pytest.mark.slow @pytest.mark.parametrize("game", TRACED or ["(none)"]) def test_mame_disassembles_real_code_the_same(game: str) -> None: """Every instruction MAME traced from ROM, decoded with the M and X flags MAME's trace line gives, prints as MAME prints it (in upper case).""" if not TRACED: pytest.skip("no MAME traces: python -I scripts/mame_trace.py GAME --io") folder = TRACES / game harness = Harness((folder / "cart.sfc").read_bytes()) differences: dict[str, tuple[str, str]] = {} checked = 0 with (folder / "cpu.trace").open(encoding="latin-1") as listing: # Interrupts add "(interrupted at 00:806D, IRQ 1)" between blank lines. texts = (text for text in listing if INSTRUCTION_LINE.match(text)) for line, text in zip(read_log(folder / "error.log"), texts, strict=False): address = line.address bank, offset = address >> 16, address & 0xFFFF if bank & 0xFE == 0x7E or harness._rom_offset(bank, offset) is None: continue # code in RAM: its bytes are not in the cartridge p = line.registers[8] ours = disassemble(harness.peek, address, m=bool(p & 0x20), x=bool(p & 0x10)) checked += 1 theirs = _mame_text(text) if ours.text != theirs: differences.setdefault(ours.mnemonic, (ours.text, theirs)) assert checked > 0 assert not differences, differences