# SPDX-License-Identifier: MIT """The tooling at the family bar: state, debug session, trace, console, the command line.""" import io import json import pytest from spc700_python import SPC700, CPUState from spc700_python.__main__ import main from spc700_python.console import CommandDebugger, CommandError, format_state, parse_number from spc700_python.debug import BoundaryKind, DebugSession, StepRecord, StopReason from spc700_python.harness import Harness from spc700_python.trace import ( compare_step_records, first_trace_divergence, read_trace, step_record_from_dict, step_record_to_dict, write_trace, ) #: MOV A,#$12; MOV $FD,A (reads $FD first); NOP; MUL YA; CALL $0310; SLEEP PROGRAM = bytes.fromhex("e812 c4fd 00 cf 3f1003 ef") SUBROUTINE = bytes.fromhex("bc 6f") # INC A; RET def host() -> Harness: harness = Harness() harness.load_program(PROGRAM, 0x0300) harness.ram[0x0310 : 0x0310 + len(SUBROUTINE)] = SUBROUTINE return harness def session(harness: Harness | None = None, **options) -> DebugSession: harness = harness or host() return DebugSession(harness.cpu, peek_byte=harness.peek, track_accesses=True, **options) def test_step_records_every_cycle_with_the_dummy_flag(): debug = session() debug.step() record = debug.step() assert record.instruction.text == "MOV $FD, A" assert record.accesses == ( ("read", 0x0302, 0xC4, False), ("read", 0x0303, 0xFD, False), ("read", 0x00FD, 0, True), ("write", 0x00FD, 0x12, False), ) def test_watchpoint_sees_the_dummy_read_of_a_store(): debug = session() debug.add_watchpoint(0x00FD, "d") result = debug.run(max_steps=10) assert result.reason is StopReason.WATCHPOINT assert result.hits == (("read", 0x00FD, 0, True),) def test_watchpoint_kinds_are_separate(): debug = session() debug.add_watchpoint(0x00FD, "r") # a real read: the store makes none assert debug.run(max_steps=3).reason is StopReason.STEP_LIMIT debug = session() debug.add_watchpoint(0x0305, "d") assert debug.run(max_steps=10).reason is StopReason.WATCHPOINT def test_internal_watchpoint_stops_on_mul_only(): debug = session() debug.add_internal_watchpoint(0xCF) result = debug.run(max_steps=20) assert result.reason is StopReason.WATCHPOINT assert result.last_record.instruction.mnemonic == "MUL" assert len(result.hits) == 7 assert result.hits[0] == ("internal", None, None, False) def test_watchpoints_need_tracking(): harness = host() debug = DebugSession(harness.cpu) with pytest.raises(ValueError): debug.add_watchpoint(0) with pytest.raises(ValueError): debug.add_internal_watchpoint() def test_breakpoint_and_stopped(): debug = session() debug.add_breakpoint(0x0305) result = debug.run(max_steps=100) assert result.reason is StopReason.BREAKPOINT assert result.state.pc == 0x0305 debug.remove_breakpoint(0x0305) result = debug.run(max_steps=100) assert result.reason is StopReason.STOPPED assert result.state.stopped assert debug.step().kind is BoundaryKind.STOP_IDLE def test_close_restores_the_bus(): harness = host() original = harness.cpu.read_byte debug = DebugSession(harness.cpu, track_accesses=True) debug.close() assert harness.cpu.read_byte == original assert not debug.tracking def test_trace_round_trips_and_compares(): debug = session() records = [debug.step() for _ in range(6)] stream = io.StringIO() assert write_trace(records, stream) == 6 stream.seek(0) again = list(read_trace(stream)) assert first_trace_divergence(records, again) is None encoded = step_record_to_dict(records[1]) assert encoded["cycles"] == 4 assert encoded["accesses"][2] == ["read", 0x00FD, 0, True] # a port in another language may omit the text del encoded["instruction"]["mnemonic"], encoded["instruction"]["operands"] assert step_record_from_dict(json.loads(json.dumps(encoded))) == records[1] def test_trace_sees_a_different_bus_cycle(): debug = session() record = debug.step() other = StepRecord( record.sequence, record.kind, record.before, record.after, record.cycles, record.instruction, (record.accesses[0], ("read", 0x0302, 0x12, True)), ) paths = [difference.path for difference in compare_step_records(record, other)] assert paths == ["accesses"] def test_trace_rejects_a_bad_version(): debug = session() encoded = step_record_to_dict(debug.step()) encoded["version"] = 2 with pytest.raises(ValueError): step_record_from_dict(encoded) def test_console_commands(): debugger = CommandDebugger(session()) assert debugger.execute("regs").lines == format_state(CPUState(pc=0x300)) assert "MOV A, #$12" in debugger.execute("d 0x300 1").lines[0] assert debugger.execute("m $300 2").lines == ("0300 E8 12",) assert "#0" in debugger.execute("step").lines[0] assert "dummy read 00FD" in ( debugger.execute("watch 0xFD d").lines[0] and debugger.execute("run 10").lines[0] ) debugger.execute("unwatch 0xFD") debugger.execute("watchidle 0xCF") assert debugger.execute("breakpoints").lines == ("watchidle CF",) assert "internal" in debugger.execute("run 10").lines[0] debugger.execute("unwatchidle 0xCF") assert debugger.execute("over").lines # steps CALL through its RET assert debugger.session.cpu.a == 1 # MUL left YA = 0, the subroutine's INC A ran assert debugger.session.cpu.pc == 0x0309 debugger.execute("set ya 0x1234") assert (debugger.session.cpu.y, debugger.session.cpu.a) == (0x12, 0x34) assert debugger.execute("quit").quit def test_console_errors(): debugger = CommandDebugger(session()) for command in ("nonsense", "break", "set Q 1", "set A 256", "watch 0 z", "run"): with pytest.raises(CommandError): debugger.execute(command) with pytest.raises(CommandError): parse_number("zz") def test_console_interact(): debugger = CommandDebugger(session()) out = io.StringIO() debugger.interact(io.StringIO("regs\nbogus\nquit\n"), out) assert "PC=0300" in out.getvalue() assert "error:" in out.getvalue() def test_command_line_prints_the_port_log(tmp_path, capsys): program = bytes.fromhex("8f05f4 2ffe") # MOV $F4,#$05; BRA self path = tmp_path / "program.bin" path.write_bytes(program) trace = tmp_path / "out.jsonl" assert main([str(path), "--org", "0x400", "--trace", str(trace)]) == 0 captured = capsys.readouterr() assert "$F4 = $05" in captured.out assert "self-branch" in captured.err records = [json.loads(line) for line in trace.read_text().splitlines()] assert records[0]["instruction"]["mnemonic"] == "MOV" assert records[0]["accesses"][3] == ["read", 0xF4, 0, True] def test_command_line_debug_batch(tmp_path, capsys): path = tmp_path / "program.bin" path.write_bytes(bytes.fromhex("e812 2ffe")) assert main([str(path), "--debug", "--batch", "-c", "step", "-c", "quit"]) == 0 assert "MOV A, #$12" in capsys.readouterr().out def test_cpu_is_a_debug_target_without_a_host(): memory = bytearray(0x10000) debug = DebugSession(SPC700(memory.__getitem__, memory.__setitem__)) assert debug.step().cycles == 2