# SPDX-License-Identifier: MIT """Execution control and structured records for debugging, without changing the core. ``DebugSession`` drives a core (or a :class:`~gsu_python.harness.Harness`, whose ``gsu`` it uses) one instruction at a time with PC breakpoints (the 24-bit address of the opcode about to run, exact in a delay slot), Game Pak RAM and register watchpoints, a bounded history, and records of the S-CPU's accesses (it wraps ``read_io``/``write_io`` until :meth:`close`) and of every PLOT. RAM accesses are derived from the instruction form and the state before it (the GSU's loads and stores; the pixel write-back is reported as PLOT records). """ from __future__ import annotations from collections import deque from dataclasses import dataclass from enum import Enum from gsu_python._decode import TABLE from gsu_python.core import GSU from gsu_python.disasm import Instruction, disassemble from gsu_python.state import CPUState #: One Game Pak RAM access by the GSU: ``("r" or "w", offset from 70:0000, byte)``. RamAccess = tuple[str, int, int] _WORD_LOADS = {"ldw", "lm", "lms"} _WORD_STORES = {"stw", "sm", "sms", "sbk"} @dataclass(frozen=True, slots=True) class HostAccess: """An S-CPU access: ``direction`` ``"R"``/``"W"``, the address, the byte (``None`` for a read the chip did not drive), and the instruction count when it happened.""" direction: str address: int value: int | None instruction: int @dataclass(frozen=True, slots=True) class PlotRecord: """A PLOT: the pixel, the colour register, and the instruction count.""" x: int y: int colr: int instruction: int class StopReason(Enum): BREAKPOINT = "breakpoint" WATCHPOINT = "watchpoint" REGISTER_WATCHPOINT = "register_watchpoint" STOPPED = "stopped" # the GSU executed STOP (GO = 0) STEP_LIMIT = "step_limit" @dataclass(frozen=True, slots=True) class StepRecord: """Before/after evidence for one instruction.""" sequence: int address: int before: CPUState after: CPUState instruction: Instruction clocks: int 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(gsu: GSU) -> list[list]: """The RAM bytes the next instruction reads or writes, from its form and the current state (a write's value is ``None`` until :meth:`DebugSession.step` reads it back).""" sfr = gsu.sfr form = TABLE[sfr >> 8 & 3 | sfr >> 10 & 4][gsu.pipeline] key = form.key r15 = gsu.r[15] if key in ("ldw", "ldb", "stw", "stb"): address = gsu.r[form.n] elif key in ("lm", "sm"): address = gsu.peek_code(r15) | gsu.peek_code(r15 + 1) << 8 elif key in ("lms", "sms"): address = gsu.peek_code(r15) << 1 elif key == "sbk": address = gsu.ramaddr else: return [] base = gsu.rambr << 16 size = len(gsu.ram) or 1 addresses = [address, address ^ 1] if key in _WORD_LOADS | _WORD_STORES else [address] kind = "r" if key in _WORD_LOADS or key == "ldb" else "w" return [[kind, (base | a) % size, gsu.ram[(base | a) % size] if kind == "r" else None] for a in addresses] # fmt: skip def live_instruction(gsu: GSU) -> Instruction: """The opcode the next ``step`` executes, decoded in the live prefix state: the opcode is the pipeline byte, its operands come from R15 on (in a delay slot, from the target: U1).""" address = gsu.pipeline_address r15 = gsu.r[15] def read(at: int) -> int: offset = (at - address) & 0xFFFF return gsu.pipeline if offset == 0 else gsu.peek_code((r15 + offset - 1) & 0xFFFF) sfr = gsu.sfr return disassemble(read, address & 0xFFFF, alt=sfr >> 8 & 3, b=bool(sfr & 0x1000), sreg=gsu.sreg, dreg=gsu.dreg, fold=False) # fmt: skip class DebugSession: """Control a core without modifying how it executes.""" def __init__(self, target, *, history_limit: int = 256) -> None: gsu = getattr(target, "gsu", target) if not isinstance(gsu, GSU): raise TypeError("target must be a GSU or have one as .gsu") if type(history_limit) is not int or history_limit < 0: raise ValueError("history_limit must be a non-negative integer") self.gsu = gsu self.history_limit = history_limit self.breakpoints: set[int] = set() #: RAM offset (from 70:0000) -> letters of ``r`` and/or ``w``. self.watchpoints: dict[int, str] = {} #: Registers (0-15) whose change stops a run. self.register_watchpoints: set[int] = set() self.host_log: list[HostAccess] = [] self.plots: list[PlotRecord] = [] self.total_steps = 0 self._history: deque[StepRecord] = deque(maxlen=history_limit or 1) self._wrap() def _wrap(self) -> None: gsu = self.gsu read_io, write_io = gsu.read_io, gsu.write_io def tracked_read(address: int) -> int | None: value = read_io(address) self.host_log.append(HostAccess("R", address & 0xFFFF, value, self.total_steps)) return value def tracked_write(address: int, value: int) -> None: write_io(address, value) self.host_log.append(HostAccess("W", address & 0xFFFF, value & 0xFF, self.total_steps)) gsu.read_io, gsu.write_io = tracked_read, tracked_write def close(self) -> None: """Give the core its own host methods back.""" for name in ("read_io", "write_io"): self.gsu.__dict__.pop(name, None) @property def history(self) -> tuple[StepRecord, ...]: return tuple(self._history) def add_breakpoint(self, address: int) -> None: """Stop before the instruction whose opcode is at the 24-bit ``address``.""" self.breakpoints.add(address & 0xFFFFFF) def remove_breakpoint(self, address: int) -> None: self.breakpoints.discard(address & 0xFFFFFF) def add_watchpoint(self, offset: int, kind: str = "rw") -> None: """Stop after a step that reads (``r``) or writes (``w``) RAM byte ``offset``.""" if not kind or set(kind) - set("rw"): raise ValueError('kind must be "r", "w" or "rw"') self.watchpoints[offset] = kind def remove_watchpoint(self, offset: int) -> None: self.watchpoints.pop(offset, None) def add_register_watchpoint(self, n: int) -> None: if not 0 <= n <= 15: raise ValueError("register must be 0-15") self.register_watchpoints.add(n) def step(self) -> StepRecord: """Execute one instruction (ignoring breakpoints); a stopped core records nothing.""" gsu = self.gsu before = gsu.capture_state(cache=False) address = gsu.pipeline_address sfr = gsu.sfr instruction = live_instruction(gsu) found = ram_accesses(gsu) is_plot = ( TABLE[sfr >> 8 & 3 | sfr >> 10 & 4][gsu.pipeline].key == "plot" ) # fmt: skip if is_plot: self.plots.append( PlotRecord(gsu.r[1] & 0xFF, gsu.r[2] & 0xFF, gsu.colr, self.total_steps) ) clocks = gsu.step() for access in found: if access[0] == "w": access[2] = gsu.ram[access[1]] record = StepRecord( sequence=self.total_steps, address=address, before=before, after=gsu.capture_state(cache=False), instruction=instruction, clocks=clocks, ram_accesses=tuple((k, o, v) for k, o, v in found), ) 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, STOP 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 gsu = self.gsu for steps in range(max_steps): if not gsu.running: return RunResult(StopReason.STOPPED, steps, gsu.capture_state(cache=False), last) if gsu.pipeline_address in self.breakpoints and steps: state = gsu.capture_state(cache=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) changed = tuple( n for n in self.register_watchpoints if last.before.r[n] != last.after.r[n] ) if changed: return RunResult( StopReason.REGISTER_WATCHPOINT, steps + 1, last.after, last, changed ) return RunResult(StopReason.STEP_LIMIT, max_steps, gsu.capture_state(cache=False), last) __all__ = [ "DebugSession", "HostAccess", "PlotRecord", "RamAccess", "RunResult", "StepRecord", "StopReason", "live_instruction", "ram_accesses", ]