# SPDX-License-Identifier: MIT """Execution control and structured records for debugging, without changing the core. ``DebugSession`` drives a core (or a :class:`~hg51b_python.harness.Harness`, whose ``cx`` it uses) one instruction at a time, with breakpoints on PB:PC, watchpoints on data RAM bytes, watchpoints on the S-CPU's accesses and on the chip's bus reads, and a bounded history. It observes by wrapping the instance's ``read``/``write`` (the S-CPU side) and ``_bus_read`` (the ROM bus) until :meth:`close`; the data RAM bytes an instruction touches are derived from its word and the state before it (RDRAM/WRRAM: A or DPR + imm, folded: U3). Cache loads and DMA transfers are noticed as they start and finish. """ from __future__ import annotations from collections import deque from dataclasses import dataclass from enum import Enum from hg51b_python._decode import OPS from hg51b_python.cpu import HG51B from hg51b_python.disasm import Instruction, disassemble from hg51b_python.state import CPUState #: One data RAM access by an instruction: ("r" or "w", byte address, value). RamAccess = tuple[str, int, int] @dataclass(frozen=True, slots=True) class HostAccess: """An S-CPU access: ``direction`` "R"/"W", the address, the byte, and the instruction count and chip clock when it happened.""" direction: str address: int value: int instruction: int clock: int @dataclass(frozen=True, slots=True) class BusEvent: """A cache load or DMA starting or finishing, or one chip bus read.""" kind: str # "cache", "dma", "bus" phase: str # "start", "end" or "read" address: int # cache: the ROM address; dma: the source; bus: the address read detail: int # cache: the cache page; dma: the target; bus: the byte clock: int class StopReason(Enum): BREAKPOINT = "breakpoint" WATCHPOINT = "watchpoint" HOST_WATCHPOINT = "host_watchpoint" BUS_WATCHPOINT = "bus_watchpoint" IDLE = "idle" # the chip halted (or was idle) with nothing pending STEP_LIMIT = "step_limit" @dataclass(frozen=True, slots=True) class StepRecord: sequence: int before: CPUState after: CPUState instruction: Instruction ram_accesses: tuple[RamAccess, ...] clocks: int # including any cache load that had to happen first @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) -> list[list]: """The data RAM byte an instruction reads or writes (a write's value filled in later).""" key = OPS[word >> 8][0] if key in ("rdram_a", "wrram_a"): address = before.a elif key in ("rdram_imm", "wrram_imm"): address = before.dpr + (word & 0xFF) else: return [] address &= 0xFFF if address >= 0xC00: address -= 0x400 return [["r" if key.startswith("rd") else "w", address, None]] class DebugSession: """Control a core without modifying how it executes.""" def __init__(self, target, *, history_limit: int = 256) -> None: cx = getattr(target, "cx", target) if not isinstance(cx, HG51B): raise TypeError("target must be an HG51B or have one as .cx") if type(history_limit) is not int or history_limit < 0: raise ValueError("history_limit must be a non-negative integer") self.cx = cx self.history_limit = history_limit self.breakpoints: set[int] = set() # PB << 8 | PC self.watchpoints: dict[int, str] = {} # data RAM byte -> "r", "w" or "rw" self.host_watchpoints: dict[int, str] = {} # S-CPU address (16 bits) -> "R"/"W"/"RW" self.bus_watchpoints: set[int] = set() # chip bus addresses self.host_log: list[HostAccess] = [] self.bus_log: list[BusEvent] = [] self.log_bus_reads = False self.total_steps = 0 self._history: deque[StepRecord] = deque(maxlen=history_limit or 1) self._host_hits: list[HostAccess] = [] self._bus_hits: list[BusEvent] = [] self._cache_was = cx.cache_enabled self._dma_was = cx.dma_enabled self._wrap() def _wrap(self) -> None: cx = self.cx read, write, bus_read = cx.read, cx.write, cx._bus_read def tracked_read(address: int) -> int: value = read(address) self._host("R", address, value) return value def tracked_write(address: int, value: int) -> None: write(address, value) self._host("W", address, value & 0xFF) self._notice() def tracked_bus_read(address: int) -> int: value = bus_read(address) if self.log_bus_reads or address in self.bus_watchpoints: event = BusEvent("bus", "read", address, value & 0xFF, cx.clock) if self.log_bus_reads: self.bus_log.append(event) if address in self.bus_watchpoints: self._bus_hits.append(event) return value cx.read, cx.write, cx._bus_read = tracked_read, tracked_write, tracked_bus_read self._original_bus_read = bus_read def close(self) -> None: """Give the core its own methods back.""" for name in ("read", "write"): self.cx.__dict__.pop(name, None) self.cx._bus_read = self._original_bus_read def _host(self, direction: str, address: int, value: int) -> None: access = HostAccess(direction, address & 0xFFFF, value, self.cx.instructions, self.cx.clock) self.host_log.append(access) kinds = self.host_watchpoints.get(address & 0xFFFF) if kinds and direction in kinds: self._host_hits.append(access) def _notice(self) -> None: """Record cache loads and DMA starting or finishing.""" cx = self.cx if cx.cache_enabled != self._cache_was: phase = "start" if cx.cache_enabled else "end" if cx._cache_pos >= 0: address = cx._cache_from elif cx.cache_enabled: # a preload: the page is decided at the next clock address = (cx.cache_base + (cx.pb << 9)) & 0xFFFFFF else: address = cx.cache_address[cx._cache_target] self.bus_log.append(BusEvent("cache", phase, address, cx._cache_target, cx.clock)) self._cache_was = cx.cache_enabled if cx.dma_enabled != self._dma_was: phase = "start" if cx.dma_enabled else "end" self.bus_log.append(BusEvent("dma", phase, cx.dma_source, cx.dma_target, cx.clock)) self._dma_was = cx.dma_enabled # ----- breakpoints and watchpoints ------------------------------------------------- @property def history(self) -> tuple[StepRecord, ...]: return tuple(self._history) def add_breakpoint(self, address: int) -> None: """``address`` = PB << 8 | PC.""" if type(address) is not int or not 0 <= address <= 0x7FFFFF: raise ValueError("address must be PB << 8 | PC") self.breakpoints.add(address) def remove_breakpoint(self, address: int) -> None: self.breakpoints.discard(address) def add_watchpoint(self, index: int, kind: str = "rw") -> None: if not kind or set(kind) - set("rw"): raise ValueError('kind must be "r", "w" or "rw"') if not 0 <= index < len(self.cx.data_ram): raise ValueError("index must be a data RAM byte") self.watchpoints[index] = kind def remove_watchpoint(self, index: int) -> None: self.watchpoints.pop(index, None) def add_host_watchpoint(self, address: int, kind: str = "RW") -> None: if not kind or set(kind) - set("RW"): raise ValueError('kind must be "R", "W" or "RW"') self.host_watchpoints[address & 0xFFFF] = kind def add_bus_watchpoint(self, address: int) -> None: self.bus_watchpoints.add(address & 0xFFFFFF) def take_host_hits(self) -> tuple[HostAccess, ...]: hits = tuple(self._host_hits) self._host_hits.clear() return hits # ----- execution ------------------------------------------------------------------- def step(self) -> StepRecord | None: """Run until one instruction has executed (doing any cache load, DMA or suspend first); ``None`` when the chip is idle and nothing would ever execute.""" cx = self.cx start_clock = cx.clock before_count = cx.instructions while cx.instructions == before_count: if not cx.running and not cx.suspend_enabled: self._notice() return None ready = not ( cx.lock or cx.suspend_enabled or cx.cache_enabled or cx.dma_enabled or cx.halted ) if ready: address = (cx.cache_base + (cx.pb << 9)) & 0xFFFFFF if address in cx.cache_address: # the next unit executes this word before = cx.capture_state(memory=False) word = cx.program_ram[cx.cache_address.index(address)][cx.pc] found = ram_accesses(word, before) if found and found[0][0] == "r": found[0][2] = cx.data_ram[found[0][1]] cx.step() self._notice() if cx.instructions == before_count: continue # the lookup started a load after all for access in found: if access[0] == "w": access[2] = cx.data_ram[access[1]] record = StepRecord( sequence=self.total_steps, before=before, after=cx.capture_state(memory=False), instruction=disassemble(word, before.pb << 8 | before.pc), ram_accesses=tuple((k, i, v) for k, i, v in found), clocks=cx.clock - start_clock, ) self.total_steps += 1 if self.history_limit: self._history.append(record) return record cx.step() self._notice() if cx.clock - start_clock > 10_000_000 and cx.lock: return None # locked: nothing will execute until $7F53 return None def run(self, *, max_steps: int) -> RunResult: """Run until a breakpoint, a watchpoint, the chip going idle, or ``max_steps``.""" if type(max_steps) is not int or max_steps <= 0: raise ValueError("max_steps must be a positive integer") cx = self.cx last = None self._bus_hits.clear() for steps in range(max_steps): if cx.pb << 8 | cx.pc in self.breakpoints and not cx.halted and steps: return RunResult(StopReason.BREAKPOINT, steps, cx.capture_state(memory=False), last) record = self.step() if record is None: return RunResult(StopReason.IDLE, steps, cx.capture_state(memory=False), last) last = record hits = tuple( access for access in record.ram_accesses if access[1] in self.watchpoints and access[0] in self.watchpoints[access[1]] ) if hits: return RunResult(StopReason.WATCHPOINT, steps + 1, record.after, record, hits) if self._bus_hits: hits = tuple(self._bus_hits) self._bus_hits.clear() return RunResult(StopReason.BUS_WATCHPOINT, steps + 1, record.after, record, hits) return RunResult(StopReason.STEP_LIMIT, max_steps, cx.capture_state(memory=False), last) __all__ = [ "BusEvent", "DebugSession", "HostAccess", "RamAccess", "RunResult", "StepRecord", "StopReason", "ram_accesses", ]