# SPDX-License-Identifier: MIT """Dependency-free execution control and structured debugging records. ``DebugSession`` drives an existing CPU (any object with ``step()`` and ``capture_state()``, or a host whose ``cpu`` attribute is the processor) one boundary at a time, with execute breakpoints, bounded runs, a history ring and, optionally, bus tracking and watchpoints. Tracking records **every cycle**, dummy reads and internal cycles included, so a watchpoint sees the dummy read of a store's destination or of PC that a memory-only view would miss. It never changes what the core does. """ from __future__ import annotations from collections import deque from collections.abc import Iterator from dataclasses import dataclass from enum import Enum from typing import Protocol, runtime_checkable from spc700_python.disasm import ByteReader, Instruction, disassemble from spc700_python.state import CPUState @runtime_checkable class DebugTarget(Protocol): """Minimum processor interface consumed by :class:`DebugSession`.""" def step(self) -> int: """Advance one boundary and return the cycles consumed.""" def capture_state(self) -> CPUState: """Capture the current CPU-owned state.""" class BoundaryKind(Enum): """Kind of work one ``step()`` call starts with.""" INSTRUCTION = "instruction" STOP_IDLE = "stop_idle" # after SLEEP or STOP: one idle cycle class StopReason(Enum): """Why a bounded run returned control.""" BREAKPOINT = "breakpoint" # before the instruction at a breakpoint WATCHPOINT = "watchpoint" # after the step that made a watched cycle STOPPED = "stopped" # the CPU is in SLEEP or STOP STEP_LIMIT = "step_limit" CYCLE_LIMIT = "cycle_limit" #: One cycle as the CPU drove the bus: ``(kind, address, value, dummy)``. ``kind`` is ``"read"``, #: ``"write"`` or ``"internal"``; ``address`` and ``value`` are ``None`` for an internal cycle, #: which has no address (C1); ``dummy`` is true for a read whose value the CPU discards. Access = tuple[str, int | None, int | None, bool] _ACCESS_KINDS = frozenset(("read", "write", "internal")) def _valid_access(access: object) -> bool: if type(access) is not tuple or len(access) != 4: return False kind, address, value, dummy = access if kind not in _ACCESS_KINDS or type(dummy) is not bool: return False if kind == "internal": return address is None and value is None and not dummy return ( type(address) is int and 0 <= address <= 0xFFFF and type(value) is int and 0 <= value <= 0xFF and (kind == "read" or not dummy) ) @dataclass(frozen=True, slots=True) class StepRecord: """Immutable before/after evidence for one processor boundary.""" sequence: int kind: BoundaryKind before: CPUState after: CPUState cycles: int instruction: Instruction | None #: Every cycle the step made, in order, when the session tracks the bus; ``None`` when it #: does not (absent means *not recorded*, not *none*). accesses: tuple[Access, ...] | None = None def __post_init__(self) -> None: if type(self.sequence) is not int or self.sequence < 0: raise ValueError("sequence must be a non-negative integer") if type(self.kind) is not BoundaryKind: raise ValueError("kind must be a BoundaryKind") if type(self.before) is not CPUState or type(self.after) is not CPUState: raise ValueError("before and after must be CPUState values") if type(self.cycles) is not int or self.cycles <= 0: raise ValueError("cycles must be a positive integer") if self.instruction is not None and type(self.instruction) is not Instruction: raise ValueError("instruction must be an Instruction or None") if self.kind is not BoundaryKind.INSTRUCTION and self.instruction is not None: raise ValueError("only instruction boundaries can contain an instruction") if self.accesses is not None and ( type(self.accesses) is not tuple or not all(map(_valid_access, self.accesses)) ): raise ValueError("accesses must be a tuple of (kind, address, value, dummy) or None") if self.accesses is not None and len(self.accesses) != self.cycles: raise ValueError("a tracked step makes exactly one access per cycle") @dataclass(frozen=True, slots=True) class RunResult: """Summary of one bounded run operation.""" reason: StopReason steps: int instructions: int cycles: int state: CPUState last_record: StepRecord | None hits: tuple[Access, ...] = () # for WATCHPOINT: the cycles that stopped the run def __post_init__(self) -> None: if type(self.reason) is not StopReason: raise ValueError("reason must be a StopReason") for name in ("steps", "instructions", "cycles"): value = getattr(self, name) if type(value) is not int or value < 0: raise ValueError(f"{name} must be a non-negative integer") if self.instructions > self.steps: raise ValueError("instructions cannot exceed steps") def next_boundary(state: CPUState) -> BoundaryKind: """What the next ``step()`` starts with, decided exactly as ``SPC700.step()`` decides it.""" return BoundaryKind.STOP_IDLE if state.stopped else BoundaryKind.INSTRUCTION class DebugSession: """Control an existing CPU host without modifying its execution core. ``peek_byte`` must be side-effect-free (the host's memory, not its bus); without it step records carry no disassembly. ``track_accesses=True`` wraps the CPU's ``read_byte``, ``write_byte`` and ``idle`` to record every cycle in :attr:`StepRecord.accesses` and to enable watchpoints; :meth:`close` puts the originals back. """ def __init__( self, target: DebugTarget, *, peek_byte: ByteReader | None = None, history_limit: int = 256, track_accesses: bool = False, ) -> None: if not isinstance(target, DebugTarget): raise TypeError("target must provide step() and capture_state()") if peek_byte is not None and not callable(peek_byte): raise TypeError("peek_byte must be callable or None") if type(history_limit) is not int or history_limit < 0: raise ValueError("history_limit must be a non-negative integer") self.target = target self.cpu = getattr(target, "cpu", target) self.peek_byte = peek_byte self.history_limit = history_limit self.breakpoints: set[int] = set() #: Bus watchpoints: address -> letters of ``r`` (read), ``d`` (dummy read), ``w`` (write). self.watchpoints: dict[int, str] = {} #: Internal-cycle watchpoints, by opcode; ``None`` in the set means any opcode. self.internal_watchpoints: set[int | None] = set() self.total_steps = 0 self.total_instructions = 0 self.total_cycles = 0 self._history: deque[StepRecord] = deque(maxlen=history_limit or 1) self._accesses: list[Access] | None = None self._originals: tuple | None = None if track_accesses: self._wrap_bus() @property def tracking(self) -> bool: """Whether this session is recording the bus.""" return self._originals is not None def _wrap_bus(self) -> None: cpu = self.cpu read_byte, write_byte, idle = cpu.read_byte, cpu.write_byte, cpu.idle self._originals = (read_byte, write_byte, idle) log: list[Access] = [] self._accesses = log def tracked_read(address: int) -> int: value = read_byte(address) & 0xFF log.append(("read", address, value, cpu.dummy)) return value def tracked_write(address: int, value: int) -> None: log.append(("write", address, value & 0xFF, False)) write_byte(address, value) def tracked_idle() -> None: log.append(("internal", None, None, False)) idle() cpu.read_byte, cpu.write_byte, cpu.idle = tracked_read, tracked_write, tracked_idle def close(self) -> None: """Stop tracking and give the CPU its own bus callables back.""" if self._originals is not None: self.cpu.read_byte, self.cpu.write_byte, self.cpu.idle = self._originals self._originals = None self._accesses = None @property def history(self) -> tuple[StepRecord, ...]: """Bounded immutable view of the retained step records.""" return tuple(self._history) def clear_history(self) -> None: """Discard retained records without changing execution totals.""" self._history.clear() def iter_history(self, *, newest_first: bool = False) -> Iterator[StepRecord]: return reversed(self._history) if newest_first else iter(self._history) def add_breakpoint(self, address: int) -> None: """Stop before executing the instruction at a 16-bit address.""" self.breakpoints.add(self._validate_address(address)) def remove_breakpoint(self, address: int) -> None: self.breakpoints.discard(self._validate_address(address)) def add_watchpoint(self, address: int, kind: str = "rdw") -> None: """Stop after any step with a ``r``(ead), ``d``(ummy read) and/or ``w``(rite) at ``address``. Dummy reads have their own letter: they clear timers on the board.""" if not self.tracking: raise ValueError("watchpoints need a session created with track_accesses=True") if not kind or set(kind) - set("rdw") or len(set(kind)) != len(kind): raise ValueError('kind must be a combination of "r", "d" and "w"') self.watchpoints[self._validate_address(address)] = kind def remove_watchpoint(self, address: int) -> None: self.watchpoints.pop(self._validate_address(address), None) def add_internal_watchpoint(self, opcode: int | None = None) -> None: """Stop after any step that makes an internal cycle, of ``opcode`` if given. Internal cycles have no address (C1), so an address watchpoint cannot name them.""" if not self.tracking: raise ValueError("watchpoints need a session created with track_accesses=True") if opcode is not None and (type(opcode) is not int or not 0 <= opcode <= 0xFF): raise ValueError("opcode must be None or an integer in range 0x00..0xFF") self.internal_watchpoints.add(opcode) def remove_internal_watchpoint(self, opcode: int | None = None) -> None: self.internal_watchpoints.discard(opcode) def step(self) -> StepRecord: """Advance exactly one boundary, ignoring execute breakpoints.""" before = self.target.capture_state() kind = next_boundary(before) instruction = None if kind is BoundaryKind.INSTRUCTION and self.peek_byte is not None: instruction = disassemble(self.peek_byte, before.pc) if self._accesses is not None: self._accesses.clear() cycles = self.target.step() if type(cycles) is not int or cycles <= 0: raise ValueError("target step() must return a positive integer cycle count") record = StepRecord( sequence=self.total_steps, kind=kind, before=before, after=self.target.capture_state(), cycles=cycles, instruction=instruction, accesses=None if self._accesses is None else tuple(self._accesses), ) self.total_steps += 1 self.total_cycles += cycles if kind is BoundaryKind.INSTRUCTION: self.total_instructions += 1 if self.history_limit: self._history.append(record) return record def run( self, *, max_steps: int, max_cycles: int | None = None, stop_on_stopped: bool = True ) -> RunResult: """Run until a stop condition or the mandatory finite step budget is reached. Execute breakpoints stop before the instruction; watchpoints stop after the step that made the watched cycle. A CPU in SLEEP or STOP ends the run unless ``stop_on_stopped`` is false. The cycle limit is checked after each boundary and may be exceeded by its cost. """ if type(max_steps) is not int or max_steps <= 0: raise ValueError("max_steps must be a positive integer") if max_cycles is not None and (type(max_cycles) is not int or max_cycles <= 0): raise ValueError("max_cycles must be a positive integer or None") steps = instructions = cycles = 0 last: StepRecord | None = None while steps < max_steps: state = self.target.capture_state() kind = next_boundary(state) if kind is BoundaryKind.INSTRUCTION and state.pc in self.breakpoints: return RunResult(StopReason.BREAKPOINT, steps, instructions, cycles, state, last) if kind is BoundaryKind.STOP_IDLE and stop_on_stopped: return RunResult(StopReason.STOPPED, steps, instructions, cycles, state, last) last = self.step() steps += 1 cycles += last.cycles instructions += last.kind is BoundaryKind.INSTRUCTION hits = self._watch_hits(last) if hits: return RunResult( StopReason.WATCHPOINT, steps, instructions, cycles, last.after, last, hits ) if max_cycles is not None and cycles >= max_cycles: return RunResult( StopReason.CYCLE_LIMIT, steps, instructions, cycles, last.after, last ) state = last.after if last is not None else self.target.capture_state() return RunResult(StopReason.STEP_LIMIT, steps, instructions, cycles, state, last) def _watch_hits(self, record: StepRecord) -> tuple[Access, ...]: if not (self.watchpoints or self.internal_watchpoints) or not record.accesses: return () internal = None in self.internal_watchpoints or self.cpu.opcode in self.internal_watchpoints hits = [] for access in record.accesses: kind, address, _, dummy = access if kind == "internal": if internal: hits.append(access) elif address in self.watchpoints: letter = "w" if kind == "write" else "d" if dummy else "r" if letter in self.watchpoints[address]: hits.append(access) return tuple(hits) @staticmethod def _validate_address(address: int) -> int: if type(address) is not int or not 0 <= address <= 0xFFFF: raise ValueError("address must be an integer in range 0x0000..0xFFFF") return address __all__ = [ "Access", "BoundaryKind", "DebugSession", "DebugTarget", "RunResult", "StepRecord", "StopReason", "next_boundary", ]