# SPDX-License-Identifier: MIT """Immutable snapshots of the HG51B: registers, flags, stack, cache, DMA, bus port, memories. ``HG51B.capture_state()`` returns a :class:`CPUState`; ``restore_state`` puts one back. A full capture carries the data RAM and the two cache pages (a save state); with ``memory=False`` they are ``None`` (traces and the debugger take one per instruction), and restoring such a state leaves the memories alone. Integers and booleans only, so a state compares with ``==`` and serialises with :meth:`CPUState.to_dict`. """ from __future__ import annotations from dataclasses import asdict, dataclass #: The registers a trace records per instruction (the Mesen2 trace logger's columns and more). TRACE_REGISTERS = ( "pb", "pc", "a", "p", "mul", "mdr", "rom", "ram", "mar", "dpr", "r", "n", "z", "c", "v", "stack", "sp", ) # fmt: skip @dataclass(frozen=True, slots=True) class CPUState: # The processor (start-here.md "Registers"). pb: int = 0 # program bank, 15 bits: the page the running code is in pc: int = 0 # word within the cache page, 8 bits a: int = 0 p: int = 0 # page register, 15 bits mul: int = 0 # 48-bit product: MH = bits 47-24, ML = bits 23-0 mdr: int = 0 rom: int = 0 ram: int = 0 mar: int = 0 dpr: int = 0 r: tuple[int, ...] = (0,) * 16 n: bool = False z: bool = False c: bool = False v: bool = False stack: tuple[int, ...] = (0,) * 8 # PB << 8 | PC; entry 0 is the top (C4 "ares") sp: int = 0 # used by the "ring-observed" stack model only # The SNES side and control. irq_flag: bool = False irq_line: bool = False lock: bool = False halted: bool = True irq_disabled: bool = False single_rom: bool = True vectors: bytes = bytes(32) wait_rom: int = 3 wait_ram: int = 3 suspend_enabled: bool = False suspend_duration: int = 0 # The cache (U2). cache_enabled: bool = False cache_page: int = 0 cache_preload: bool = False cache_lock: tuple[bool, bool] = (False, False) cache_address: tuple[int, int] = (-1, -1) # -1: the page holds nothing cache_base: int = 0 cache_pb: int = 0 cache_pc: int = 0 cache_pos: int = -1 # bytes of the load in flight done; -1 none cache_target: int = 0 cache_from: int = 0 # DMA (U15) and the bus port (U10). dma_enabled: bool = False dma_source: int = 0 dma_target: int = 0 dma_length: int = 0 dma_pos: int = 0 bus_enabled: bool = False bus_reading: bool = False bus_writing: bool = False bus_pending: int = 0 bus_address: int = 0 mul_pending: int = -1 # C6 with MUL_LATENCY = 1 # Counters. clock: int = 0 instructions: int = 0 debt: int = 0 # The memories (None in a registers-only capture). data_ram: bytes | None = None program_ram: tuple[tuple[int, ...], tuple[int, ...]] | None = None def __post_init__(self) -> None: if len(self.r) != 16 or len(self.stack) != 8 or len(self.vectors) != 32: raise ValueError("r needs 16 entries, stack 8 and vectors 32 bytes") if self.data_ram is not None and len(self.data_ram) != 3072: raise ValueError("data_ram must be 3,072 bytes") for name, limit in (("pb", 0x7FFF), ("pc", 0xFF), ("a", 0xFFFFFF), ("p", 0x7FFF)): value = getattr(self, name) if type(value) is not int or not 0 <= value <= limit: raise ValueError(f"{name} must be an integer in 0..0x{limit:X}") @property def mh(self) -> int: return self.mul >> 24 @property def ml(self) -> int: return self.mul & 0xFFFFFF def registers(self) -> dict[str, object]: """The per-instruction view: :data:`TRACE_REGISTERS`, tuples as lists.""" out: dict[str, object] = {} for name in TRACE_REGISTERS: value = getattr(self, name) out[name] = list(value) if isinstance(value, tuple) else value return out def to_dict(self) -> dict[str, object]: """Every field as JSON-friendly values (bytes as hex strings).""" out = asdict(self) for name in ("vectors", "data_ram"): if out[name] is not None: out[name] = out[name].hex() return out __all__ = ["TRACE_REGISTERS", "CPUState"]