# SPDX-License-Identifier: MIT """Execution control and structured records for debugging, without changing the core. ``DebugSession`` drives a core (or a :class:`~upd7725_python.harness.Harness`, whose ``dsp`` it uses) one instruction at a time with PC breakpoints, data RAM watchpoints, host-access watchpoints and a bounded history. The DSP has no bus, so its RAM accesses are derived from the instruction word and the state before it (``ram_accesses``): MEM as SRC, P = RAM in a binary ALU op, the second register of @KLM, and @MEM as DST, in U1's order. Host accesses (``read_dr``, ``write_dr``, ``read_sr``) are made by the board, not by ``step``; the session wraps those three methods to record them (:attr:`host_log`) until :meth:`close`. """ from __future__ import annotations from collections import deque from dataclasses import dataclass from enum import Enum from upd7725_python import _fields as f from upd7725_python.cpu import UPD7725 from upd7725_python.disasm import Instruction, disassemble from upd7725_python.state import CPUState #: One data RAM access by the DSP: ``("r" or "w", word index, value)``. RamAccess = tuple[str, int, int] @dataclass(frozen=True, slots=True) class HostAccess: """One host access through the port: ``direction`` ``"R"``/``"W"``, ``port`` ``"DR"`` or ``"SR"``, the byte, and the instruction count when it happened (between instructions).""" direction: str port: str value: int instruction: int class StopReason(Enum): BREAKPOINT = "breakpoint" # before the instruction at a breakpoint WATCHPOINT = "watchpoint" # after a step that touched a watched RAM word HOST_WATCHPOINT = "host_watchpoint" # after a watched host access STEP_LIMIT = "step_limit" @dataclass(frozen=True, slots=True) class StepRecord: """Before/after evidence for one instruction.""" sequence: int before: CPUState after: CPUState instruction: Instruction ram_accesses: tuple[RamAccess, ...] @dataclass(frozen=True, slots=True) class RunResult: reason: StopReason steps: int state: CPUState last_record: StepRecord | None hits: tuple = () def ram_accesses(word: int, before: CPUState, ram: list[int]) -> list[list]: """The data RAM words an instruction reads and writes, from its word and the state and RAM before it, in U1's order (C14: P = RAM reads before @MEM writes). A write's value is ``None`` here; :meth:`DebugSession.step` fills it in from the RAM after the step.""" out: list[list] = [] k = f.kind(word) dp = before.dp if k in (f.OP, f.RT): if f.src(word) == 15: # MEM out.append(["r", dp, ram[dp]]) if f.alu(word) in f.BINARY_ALU and f.p_select(word) == 0: # P = RAM out.append(["r", dp, ram[dp]]) elif k != f.LD: return out destination = f.dst(word) if destination == 12: # @KLM: K = RAM[DP | 40h] (U5) out.append(["r", dp | 0x40, ram[dp | 0x40]]) elif destination == 15: # @MEM out.append(["w", dp, None]) return out class DebugSession: """Control a core without modifying how it executes.""" def __init__(self, target, *, history_limit: int = 256) -> None: dsp = getattr(target, "dsp", target) if not isinstance(dsp, UPD7725): raise TypeError("target must be a UPD7725 or have one as .dsp") if type(history_limit) is not int or history_limit < 0: raise ValueError("history_limit must be a non-negative integer") self.dsp = dsp self.history_limit = history_limit self.breakpoints: set[int] = set() #: RAM word index -> letters of ``r`` and/or ``w``. self.watchpoints: dict[int, str] = {} #: Host watchpoints: (direction, port) pairs, e.g. ("W", "DR"). self.host_watchpoints: set[tuple[str, str]] = set() self.host_log: list[HostAccess] = [] self.total_steps = 0 self._history: deque[StepRecord] = deque(maxlen=history_limit or 1) self._host_hits: list[HostAccess] = [] self._originals = (dsp.read_dr, dsp.write_dr, dsp.read_sr) self._wrap_host() def _wrap_host(self) -> None: dsp = self.dsp read_dr, write_dr, read_sr = self._originals def record(direction: str, port: str, value: int) -> None: access = HostAccess(direction, port, value, self.total_steps) self.host_log.append(access) if (direction, port) in self.host_watchpoints: self._host_hits.append(access) def tracked_read_dr() -> int: value = read_dr() record("R", "DR", value) return value def tracked_write_dr(value: int) -> None: write_dr(value) record("W", "DR", value & 0xFF) def tracked_read_sr() -> int: value = read_sr() record("R", "SR", value) return value dsp.read_dr, dsp.write_dr, dsp.read_sr = tracked_read_dr, tracked_write_dr, tracked_read_sr def close(self) -> None: """Give the core its own host methods back.""" for name in ("read_dr", "write_dr", "read_sr"): self.dsp.__dict__.pop(name, None) @property def history(self) -> tuple[StepRecord, ...]: return tuple(self._history) def add_breakpoint(self, address: int) -> None: self.breakpoints.add(self._address(address)) def remove_breakpoint(self, address: int) -> None: self.breakpoints.discard(self._address(address)) def add_watchpoint(self, index: int, kind: str = "rw") -> None: """Stop after a step that reads (``r``) or writes (``w``) data RAM word ``index``.""" if not kind or set(kind) - set("rw"): raise ValueError('kind must be "r", "w" or "rw"') if not 0 <= index < len(self.dsp.ram): raise ValueError("index must be a data RAM word") self.watchpoints[index] = kind def remove_watchpoint(self, index: int) -> None: self.watchpoints.pop(index, None) def add_host_watchpoint(self, direction: str, port: str) -> None: """Stop after a host access: direction ``R``/``W``, port ``DR``/``SR``.""" if direction not in ("R", "W") or port not in ("DR", "SR"): raise ValueError("direction must be R or W and port DR or SR") self.host_watchpoints.add((direction, port)) def step(self) -> StepRecord: """Execute one instruction, ignoring breakpoints.""" dsp = self.dsp before = dsp.capture_state(ram=False) word = dsp.program[before.pc] found = ram_accesses(word, before, dsp.ram) dsp.step() for access in found: if access[0] == "w": access[2] = dsp.ram[access[1]] accesses = tuple((kind, index, value) for kind, index, value in found) record = StepRecord( sequence=self.total_steps, before=before, after=dsp.capture_state(ram=False), instruction=disassemble(word, before.pc), ram_accesses=accesses, ) self.total_steps += 1 if self.history_limit: self._history.append(record) return record def run(self, *, max_steps: int) -> RunResult: """Run until a breakpoint, a watchpoint, or ``max_steps`` instructions.""" if type(max_steps) is not int or max_steps <= 0: raise ValueError("max_steps must be a positive integer") last = None self._host_hits.clear() for steps in range(max_steps): if self.dsp.pc in self.breakpoints: state = self.dsp.capture_state(ram=False) return RunResult(StopReason.BREAKPOINT, steps, state, last) last = self.step() hits = tuple( access for access in last.ram_accesses if access[1] in self.watchpoints and access[0] in self.watchpoints[access[1]] ) if hits: return RunResult(StopReason.WATCHPOINT, steps + 1, last.after, last, hits) return RunResult(StopReason.STEP_LIMIT, max_steps, self.dsp.capture_state(ram=False), last) def take_host_hits(self) -> tuple[HostAccess, ...]: """Watched host accesses since the last call (the board makes them between runs).""" hits = tuple(self._host_hits) self._host_hits.clear() return hits def _address(self, address: int) -> int: if type(address) is not int or not 0 <= address <= self.dsp.model.pc_mask: raise ValueError("address must be a program address") return address __all__ = [ "DebugSession", "HostAccess", "RamAccess", "RunResult", "StepRecord", "StopReason", "ram_accesses", ]