"""The tooling: CPUState, the debug session, traces, the console and ``python -m``. The session, records, trace functions and console are 6502-python's, subclassed through their hooks; these tests hold the W65C816 parts: every boundary kind is what the bus shows (the vector fetched, or an IO cycle while halted), accesses are one per cycle with the cycle's pins, and traces read back equal. """ import io import json from dataclasses import replace import pytest from w65c816 import W65C816 from w65c816.__main__ import main from w65c816.console import W65C816Debugger from w65c816.debug import BoundaryKind, W65C816Session, next_boundary from w65c816.state import CPUState from w65c816.trace import first_trace_divergence, read_trace, write_trace # Native vectors: NMI $9000, IRQ $9100, ABORT $9200; reset $8000. VECTORS = {0xFFEA: 0x9000, 0xFFEE: 0x9100, 0xFFE8: 0x9200, 0xFFFC: 0x8000} PROGRAM = bytes( [ 0x18, # 8000 CLC 0xFB, # 8001 XCE: native 0x58, # 8002 CLI 0xEA, # 8003 NOP 0xEA, # 8004 NOP 0xCB, # 8005 WAI 0xEA, # 8006 NOP 0xDB, # 8007 STP ] ) RTI = 0x40 BY_VECTOR = { 0xFFFC: BoundaryKind.RESET, 0xFFEA: BoundaryKind.NMI, 0xFFEE: BoundaryKind.IRQ, 0xFFE8: BoundaryKind.ABORT, } def machine() -> tuple[W65C816, bytearray]: memory = bytearray(1 << 24) memory[0x8000 : 0x8000 + len(PROGRAM)] = PROGRAM for vector, handler in VECTORS.items(): memory[vector], memory[vector + 1] = handler & 0xFF, handler >> 8 if vector != 0xFFFC: memory[handler] = RTI cpu = W65C816(memory.__getitem__, memory.__setitem__) cpu.request_reset() return cpu, memory def observed(record) -> BoundaryKind: """The kind the bus shows, independent of next_boundary.""" vectors = [address for kind, address, _ in record.accesses if "v" in kind] if vectors and vectors[0] in BY_VECTOR: # no instruction here reads these return BY_VECTOR[vectors[0]] if record.before.waiting and len(record.accesses) == 1: return BoundaryKind.WAIT_IDLE # an IO cycle, or the waking program read (U11) if [kind for kind, _, _ in record.accesses] == ["i"]: return BoundaryKind.STOP_IDLE return BoundaryKind.INSTRUCTION def run_scenario() -> list: """Every kind of boundary once, in a planned order.""" cpu, memory = machine() session = W65C816Session(cpu, peek_byte=memory.__getitem__, track_accesses=True) records = [session.step() for _ in range(4)] # reset, CLC, XCE, CLI cpu.request_maskable_interrupt() # CLI's poll saw I set: NOP runs first records += [session.step(), session.step()] # NOP, IRQ entry cpu.clear_maskable_interrupt() records.append(session.step()) # RTI cpu.request_non_maskable_interrupt() records += [session.step(), session.step()] # NMI entry, RTI cpu.request_abort() records += [session.step(), session.step()] # ABORT entry, RTI records += [session.step(), session.step(), session.step()] # NOP, WAI, waiting cpu.request_non_maskable_interrupt() records += [session.step(), session.step(), session.step()] # wakes, NMI, RTI records += [session.step(), session.step(), session.step()] # NOP, STP, stopped return records def test_every_boundary_kind_is_what_the_bus_shows() -> None: records = run_scenario() kinds = [record.kind for record in records] assert kinds == [ BoundaryKind.RESET, *[BoundaryKind.INSTRUCTION] * 4, BoundaryKind.IRQ, BoundaryKind.INSTRUCTION, BoundaryKind.NMI, BoundaryKind.INSTRUCTION, BoundaryKind.ABORT, *[BoundaryKind.INSTRUCTION] * 3, BoundaryKind.WAIT_IDLE, BoundaryKind.WAIT_IDLE, BoundaryKind.NMI, *[BoundaryKind.INSTRUCTION] * 3, BoundaryKind.STOP_IDLE, ] for record in records: assert observed(record) is record.kind, record assert next_boundary(record.before) is record.kind def test_accesses_are_one_per_cycle_with_the_pins() -> None: records = run_scenario() for record in records: assert len(record.accesses) == record.cycles clc = records[1] assert clc.instruction.text == "CLC" assert clc.accesses == (("rdp", 0x8000, 0x18), ("i", 0x8001, 0)) irq = records[5] assert [kind for kind, _, _ in irq.accesses] == [ "rdp", "i", "wd", "wd", "wd", "wd", "rdv", "rdv", ] def test_state_round_trips_and_a_restored_cpu_runs_the_same() -> None: cpu, memory = machine() for _ in range(4): cpu.step() cpu.request_maskable_interrupt() cpu.request_abort() state = cpu.capture_state() assert state.polled_i is True and state.abort_pending and state.maskable_interrupt_pending twin = W65C816(memory.__getitem__, memory.__setitem__) twin.restore_state(state) assert twin.capture_state() == state for _ in range(6): assert cpu.step() == twin.step() assert cpu.capture_state() == twin.capture_state() def test_a_new_cpu_captures_the_defaults_and_bad_states_are_refused() -> None: cpu, _ = machine() assert cpu.capture_state() == CPUState(reset_pending=True) with pytest.raises(ValueError, match="emulation mode"): CPUState(p=0x04) with pytest.raises(ValueError, match="8-bit"): replace(CPUState(e=0, p=0x10), x=0x1234) with pytest.raises(ValueError, match="halted"): CPUState(waiting=True) with pytest.raises(TypeError): cpu.restore_state(object()) def test_a_trace_reads_back_equal_and_finds_a_divergence() -> None: records = run_scenario() stream = io.StringIO() write_trace(records, stream) stream.seek(0) assert list(read_trace(stream)) == records first = json.loads(stream.getvalue().splitlines()[1]) assert first["instruction"] == { "address": 0x8000, "data": "18", "mnemonic": "CLC", "operands": [], } changed = [*records[:3], replace(records[3], cycles=records[3].cycles + 1), *records[4:]] divergence = first_trace_divergence(records, changed) assert divergence.position == 3 assert [d.path for d in divergence.differences] == ["cycles"] def test_the_console_speaks_65816() -> None: cpu, memory = machine() session = W65C816Session(cpu, peek_byte=memory.__getitem__, track_accesses=True) debugger = W65C816Debugger(session) assert debugger.execute("step").lines == ("#0 00:0000 reset -> PC=00:8000 +7",) assert debugger.execute("registers").lines[0] == ( "PC=00:8000 A=0000 X=0000 Y=0000 S=01FC D=0000 DB=00 P=34 --1B-I-- E=1" ) assert debugger.execute("d $008000 3").lines == ( "00:8000 18 CLC", "00:8001 FB XCE", "00:8002 58 CLI", ) assert debugger.execute("break $008004").lines == ("breakpoint added at 00:8004",) assert debugger.execute("c").lines[-1].startswith("stopped=breakpoint steps=4") debugger.execute("set P $00") assert debugger.execute("set X $1234").lines[0].startswith("PC=00:8004 A=0000 X=1234") debugger.execute("set P $10") assert cpu.x == 0x34 # 8-bit index registers keep a zero high byte assert debugger.execute("abort").lines == ("ABORT latched; taken at the next boundary",) assert debugger.execute("s").lines == ("#5 00:8004 abort -> PC=00:9200 +8",) def test_python_m_runs_a_rom_and_writes_a_trace(tmp_path, capsys) -> None: rom = bytearray(0x8000) rom[0:4] = PROGRAM[:2] + bytes([0x80, 0xFE]) # CLC, XCE, BRA self rom[0x7FFC], rom[0x7FFD] = 0x00, 0x80 path = tmp_path / "spin.sfc" path.write_bytes(bytes(rom)) trace = tmp_path / "spin.jsonl" assert main([str(path), "--trace", str(trace)]) == 0 assert capsys.readouterr().out == "spin after 14 cycles at 00:8002 (lorom)\n" records = list(read_trace(trace.open())) assert [record.kind for record in records] == [ BoundaryKind.RESET, *[BoundaryKind.INSTRUCTION] * 3, ] assert main([str(path), "--batch", "-c", "step 2"]) == 0 assert "00:8001 FB XCE -> PC=00:8002 +2" in capsys.readouterr().out