# 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 board whose ``cpu`` attribute is the :class:`~arm7tdmi_python.ARM7TDMI`) one boundary at a time: execute breakpoints, run-until, step-over, bounded runs and a history ring. With ``track_accesses=True`` it also records **every bus cycle**, internal and coprocessor cycles included, each typed N, S, I or C with the address the core drove, and watchpoints see all of them. It never changes what the core does. See docs/debugging.md. """ from __future__ import annotations from collections import deque from collections.abc import Callable, Iterator from dataclasses import dataclass from enum import Enum from typing import Protocol, runtime_checkable from arm7tdmi_python.access import CODE, LOCK, SEQ from arm7tdmi_python.disasm import ByteReader, Instruction, disassemble_arm, disassemble_thumb from arm7tdmi_python.state import CPUState MASK32 = 0xFFFFFFFF THUMB = 0x20 @runtime_checkable class DebugTarget(Protocol): """Minimum interface consumed by :class:`DebugSession`.""" def step(self) -> int: """Advance one boundary and return the bus cycles it made.""" def capture_state(self) -> CPUState: """Capture the current CPU-owned state.""" class BoundaryKind(Enum): """What one ``step()`` call does.""" INSTRUCTION = "instruction" IRQ = "irq" # the IRQ entry sequence instead of an instruction FIQ = "fiq" class StopReason(Enum): """Why a bounded run returned control.""" BREAKPOINT = "breakpoint" # before the instruction at a breakpoint UNTIL = "until" # before the instruction at the run's target address RETURNED = "returned" # step-over: at the instruction after the one stepped over WATCHPOINT = "watchpoint" # after the step that touched a watched address CONDITION = "condition" # the run's ``stop_when`` became true STEP_LIMIT = "step_limit" CYCLE_LIMIT = "cycle_limit" _KINDS = ("read", "write", "internal", "coprocessor") @dataclass(frozen=True, slots=True) class BusCycle: """One bus cycle as the core reported it (the TRM's pins, before any board mapping such as :func:`~arm7tdmi_python.gba_access`).""" kind: str # read, write, internal or coprocessor address: int width: int = 0 # 8, 16 or 32 for a read or write; 0 otherwise access: int = 0 # SEQ | CODE | LOCK value: int | None = None # the value moved; None for internal and coprocessor cycles def __post_init__(self) -> None: if self.kind not in _KINDS: raise ValueError(f"kind must be one of {_KINDS}") if type(self.address) is not int or not 0 <= self.address <= MASK32: raise ValueError("address must be a 32-bit unsigned integer") @property def type(self) -> str: """``N``, ``S``, ``I`` or ``C`` (TRM 3.3). A fetch after an I cycle is S on the pins (merged IS); the GBA times it as N, which ``gba_access`` applies.""" if self.kind == "internal": return "I" if self.kind == "coprocessor": return "C" return "S" if self.access & SEQ else "N" @property def text(self) -> str: if self.value is None: return f"{self.type} {self.kind:<11} {self.address:08X}" tags = "".join(t for bit, t in ((CODE, " code"), (LOCK, " lock")) if self.access & bit) digits = self.width // 4 return ( f"{self.type} {self.kind:<11} {self.address:08X} " f"{self.width:>2}-bit {self.value:0{digits}X}{tags}" ) @dataclass(frozen=True, slots=True) class StepRecord: """Immutable before/after evidence for one boundary.""" sequence: int kind: BoundaryKind address: int # the instruction's address (for IRQ/FIQ, the one the entry replaced) before: CPUState after: CPUState cycles: int #: The instruction the core ran, decoded from its pipeline (what it actually executed, #: whatever memory holds now); ``None`` for an interrupt entry. instruction: Instruction | None #: Every bus 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[BusCycle, ...] | None = None def __post_init__(self) -> None: if type(self.kind) is not BoundaryKind: raise ValueError("kind must be a BoundaryKind") if type(self.cycles) is not int or self.cycles < 0: raise ValueError("cycles must be a non-negative integer") if self.kind is not BoundaryKind.INSTRUCTION and self.instruction is not None: raise ValueError("only instruction boundaries carry an instruction") @dataclass(frozen=True, slots=True) class RunResult: """Summary of one bounded run.""" reason: StopReason steps: int instructions: int cycles: int state: CPUState last_record: StepRecord | None hits: tuple[BusCycle, ...] = () # for WATCHPOINT: the cycles that stopped the run def instruction_address(state: CPUState) -> int: """The address of the instruction the next ``step()`` runs: R15 less the pipeline's two fetches (8 in ARM state, 4 in Thumb), DS 3.4.""" thumb = state.cpsr & THUMB return (state.registers[15] - (4 if thumb else 8)) & (~1 if thumb else ~3) & MASK32 def next_instruction(state: CPUState) -> Instruction: """The instruction in the pipeline that the next ``step()`` runs (no memory needed).""" address = instruction_address(state) if state.cpsr & THUMB: return disassemble_thumb(state.pipeline[0], address) return disassemble_arm(state.pipeline[0], address) def next_boundary(cpu: object) -> BoundaryKind: """What the next ``step()`` does, decided exactly as ``ARM7TDMI.step()`` decides it.""" pending = cpu.pending_interrupt() # type: ignore[attr-defined] if pending == 0x11: return BoundaryKind.FIQ if pending == 0x12: return BoundaryKind.IRQ return BoundaryKind.INSTRUCTION def is_call(instruction: Instruction) -> bool: """BL, a combined Thumb BL pair, either BL half, or SWI: what step-over runs through.""" return instruction.mnemonic.startswith(("BL", "SWI")) and not instruction.mnemonic.startswith( "BLX" ) 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); the console's memory view and listings need it, step records do not (they decode the pipeline). ``track_accesses=True`` wraps the core's ``read``, ``write`` and ``idle`` callbacks to record every bus cycle in :attr:`StepRecord.accesses` and to enable watchpoints; :meth:`close` puts the host's callbacks back. The target may be a whole board whose ``cpu`` attribute is the processor: its ``step()`` then decides what one boundary is. """ 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() #: Watchpoints: start address -> (kinds, length); kinds is a string of ``r`` (read), #: ``w`` (write), ``i`` (internal and coprocessor cycles). self.watchpoints: dict[int, tuple[str, int]] = {} 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[BusCycle] | None = None self._originals: tuple | None = None if track_accesses: self._wrap_bus() # ----- the 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, write, idle = cpu._bus_read, cpu._bus_write, cpu._bus_idle self._originals = (read, write, idle) log: list[BusCycle] = [] self._accesses = log def tracked_read(address: int, width: int, access: int) -> int: value = read(address, width, access) log.append(BusCycle("read", address, width, access, value & ((1 << width) - 1))) return value def tracked_write(address: int, width: int, value: int, access: int) -> None: log.append(BusCycle("write", address, width, access, value)) write(address, width, value, access) def tracked_idle(address: int) -> None: log.append(BusCycle("coprocessor" if cpu.coprocessor_cycle else "internal", address)) idle(address) cpu._bus_read, cpu._bus_write, cpu._bus_idle = tracked_read, tracked_write, tracked_idle def close(self) -> None: """Stop tracking and give the core the host's callbacks back.""" if self._originals is not None: self.cpu._bus_read, self.cpu._bus_write, self.cpu._bus_idle = self._originals self._originals = None self._accesses = None # ----- history, breakpoints, watchpoints ------------------------------------------- @property def history(self) -> tuple[StepRecord, ...]: """Bounded immutable view of the retained step records.""" return tuple(self._history) def clear_history(self) -> None: 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 running the instruction at ``address``.""" self.breakpoints.add(_address(address)) def remove_breakpoint(self, address: int) -> None: self.breakpoints.discard(_address(address)) def add_watchpoint(self, address: int, kind: str = "rw", length: int = 1) -> None: """Stop after any step with a ``r``(ead), ``w``(rite) and/or ``i``(nternal) cycle that touches ``length`` bytes from ``address``. A read or write touches the bytes its width covers at the address aligned to that width (what memory sees); an internal or coprocessor cycle touches the one address the core drove.""" if not self.tracking: raise ValueError("watchpoints need a session created with track_accesses=True") if not kind or set(kind) - set("rwi") or len(set(kind)) != len(kind): raise ValueError('kind must be a combination of "r", "w" and "i"') if type(length) is not int or length <= 0: raise ValueError("length must be a positive integer") self.watchpoints[_address(address)] = (kind, length) def remove_watchpoint(self, address: int) -> None: self.watchpoints.pop(_address(address), None) def _watch_hits(self, record: StepRecord) -> tuple[BusCycle, ...]: if not self.watchpoints or not record.accesses: return () hits = [] for cycle in record.accesses: letter = {"read": "r", "write": "w"}.get(cycle.kind, "i") if cycle.width: size = cycle.width // 8 first = cycle.address & ~(size - 1) & MASK32 else: size, first = 1, cycle.address for start, (kinds, length) in self.watchpoints.items(): if letter in kinds and first < start + length and start < first + size: hits.append(cycle) break return tuple(hits) # ----- stepping -------------------------------------------------------------------- def step(self) -> StepRecord: """Advance exactly one boundary, ignoring breakpoints.""" before = self.target.capture_state() kind = next_boundary(self.cpu) instruction = next_instruction(before) if kind is BoundaryKind.INSTRUCTION else None 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 non-negative cycle count") record = StepRecord( sequence=self.total_steps, kind=kind, address=instruction_address(before), 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, until: int | None = None, stop_when: Callable[[], bool] | None = None, ) -> RunResult: """Run until a stop condition or the mandatory finite step budget. Breakpoints and ``until`` stop before the instruction at their address (an interrupt entry is not an instruction, so it never stops there); watchpoints stop after the step that touched the watched bytes; ``stop_when`` is checked before each step. The cycle limit is checked after each step and may be exceeded by that step's 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() if next_boundary(self.cpu) is BoundaryKind.INSTRUCTION: address = instruction_address(state) if until is not None and address == until: return RunResult(StopReason.UNTIL, steps, instructions, cycles, state, last) if address in self.breakpoints: return RunResult( StopReason.BREAKPOINT, steps, instructions, cycles, state, last ) if stop_when is not None and stop_when(): return RunResult(StopReason.CONDITION, 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 step_over(self, *, max_steps: int = 1_000_000) -> RunResult: """Step one instruction; if it is a call (BL, a Thumb BL pair, SWI), run until the instruction after it, with SP and the mode back where they were, so a recursive call that passes through the return address does not stop it. A breakpoint, watchpoint or the step limit still stops it first.""" before = self.target.capture_state() instruction = next_instruction(before) call = next_boundary(self.cpu) is BoundaryKind.INSTRUCTION and is_call(instruction) size = instruction.size if call and instruction.mnemonic == "BL.HI": # the first half of a Thumb pair size = 4 returns_to = (instruction.address + size) & MASK32 first = self.step() steps, cycles, last = 1, first.cycles, first instructions = int(first.kind is BoundaryKind.INSTRUCTION) hits = self._watch_hits(first) if hits: return RunResult( StopReason.WATCHPOINT, 1, instructions, cycles, first.after, first, hits ) if not call or instruction_address(first.after) == returns_to: return RunResult(StopReason.RETURNED, 1, instructions, cycles, first.after, first) sp, mode = before.registers[13], before.cpsr & 0x1F while steps < max_steps: state = self.target.capture_state() at_instruction = next_boundary(self.cpu) is BoundaryKind.INSTRUCTION address = instruction_address(state) back = address == returns_to and state.cpsr & 0x1F == mode if at_instruction and back and state.registers[13] == sp: return RunResult(StopReason.RETURNED, steps, instructions, cycles, state, last) if at_instruction and address in self.breakpoints: return RunResult(StopReason.BREAKPOINT, 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 ) return RunResult(StopReason.STEP_LIMIT, steps, instructions, cycles, last.after, last) def _address(address: int) -> int: if type(address) is not int or not 0 <= address <= MASK32: raise ValueError("address must be a 32-bit unsigned integer") return address __all__ = [ "BoundaryKind", "BusCycle", "DebugSession", "DebugTarget", "RunResult", "StepRecord", "StopReason", "instruction_address", "is_call", "next_boundary", "next_instruction", ]