# SPDX-License-Identifier: MIT """Debugging and tracing on 6502-python's tools, with the board's own events. - :func:`session` gives a ``sixfiveohtwo.DebugSession`` on the board (breakpoints, memory watchpoints, history) with a side-effect-free peek. - :class:`BeamWatch` stops a run at an ANTIC beam position or on a write to a chip register (GTIA $C0xx, ANTIC $D4xx, POKEY $E8xx by register number). - :func:`trace_jsonl` writes one JSON line per CPU step in 6502-python's trace schema (``step_record_to_dict``) plus the board's bus events of that step: machine-cycle time, kind ("R", "W", "D" ANTIC DMA, "S" a read repeated while WSYNC holds RDY), address, value, and ANTIC's line/cycle. """ from __future__ import annotations import json from typing import TextIO from sixfiveohtwo import DebugSession from sixfiveohtwo.trace import step_record_to_dict CHIPS = { # DOC: the memory map ([AHRM] 13.2, 13.4; [FSM] decoder sheet) "gtia": (0xC000, 0xD000, 0x1F), "antic": (0xD400, 0xD500, 0x0F), "pokey": (0xE800, 0xF000, 0x0F), } def session(board, **kwargs) -> DebugSession: return DebugSession(board, peek_byte=board.peek, **kwargs) class BeamWatch: """Run the board until ANTIC reaches (line, cycle) or a chip register is written.""" def __init__(self, board) -> None: self.board = board self.register_writes: set[tuple[str, int]] = set() self.hit: tuple | None = None board.bus_observers.append(self._observe) def watch_register(self, chip: str, register: int) -> None: self.register_writes.add((chip, register)) def _observe(self, kind: str, address: int, value: int, cycle: int) -> None: if kind != "W" or not self.register_writes: return for chip, (low, high, mask) in CHIPS.items(): if low <= address < high and (chip, address & mask) in self.register_writes: antic = self.board.antic self.hit = (chip, address & mask, value, antic.vcount, antic.hcount, cycle) def run_to_beam(self, line: int, cycle: int, limit: int = 10_000_000) -> bool: antic = self.board.antic start = self.board.cycles while self.board.cycles - start < limit: if antic.vcount == line and antic.hcount >= cycle: return True self.board.step() return False def run_to_register_write(self, limit: int = 10_000_000) -> tuple | None: self.hit = None start = self.board.cycles while self.hit is None and self.board.cycles - start < limit: self.board.step() return self.hit def trace_jsonl(board, stream: TextIO, steps: int) -> int: """Trace ``steps`` CPU steps to ``stream``; returns the number written.""" events: list[list] = [] antic = board.antic def observe(kind: str, address: int, value: int, cycle: int) -> None: events.append([cycle, kind, address, value, antic.vcount, antic.hcount]) board.bus_observers.append(observe) debug = session(board) try: for _ in range(steps): events.clear() record = debug.step() line = step_record_to_dict(record) line["bus"] = list(events) stream.write(json.dumps(line) + "\n") finally: board.bus_observers.remove(observe) debug.close() return steps