# SPDX-License-Identifier: MIT """Whole-machine save states: the Mega Drive, the 32X and both SH-2s, at a frame boundary. The machine is a graph of plain Python objects (megadrive-python's System, this package's Sega32X, sh2-python's two SH7604s), so a state is that graph pickled -- every register, RAM, cache line, pipeline slot, write-buffer end, FIFO, pending sample and scheduled event the objects hold, without a list of fields to keep up to date. The cores' own state records are not enough at their pins: megadrive-python 5c6d1b7 has no save-state API at all, and sh2-python's ``capture_state``/``restore_state`` keeps the registers, the pipeline and the modules' registers but not the cache's lines or the write buffer's end, so neither is used here. What is not written, and how it comes back: - **ROM and BIOS bytes.** The cartridge's immutable images (each ``bytes`` attribute of the Cartridge) and the three boot ROMs are written as names (pickle's persistent IDs) and re-attached on load from the cartridge and boot ROMs the caller hands over, which must have the SHA-1s the header records. Any other immutable ``bytes`` of 4 KB or more stops the save (:class:`StateError`): no image is ever written into a state file. - **Module-level objects** of the three packages (megadrive-python's ``H32``/``H40`` modes with their lambdas, the machines tables, sh2-python's decode tables) are written as references and are the same objects after loading, so identity checks still hold. - **The SH-2s' bus and pin callbacks** are closures (``sh2side.py``); they are written as placeholders and made again by :meth:`SH2Side.rewire`. - Nothing else is worked around: m68000-python and sh2-python build their dispatch tables on first read, not in the constructor (m68000-python c827cca, sh2-python d4665d5), and megadrive-python keeps socket 8's leftovers by source (5c6d1b7), so a machine unpickled in a fresh process that has built no console runs as it is (docs/megadrive-python-state-pr.md; ``tests/test_savestate.py`` loads in one). Debugger hooks (``SH2Side.on_step``, ``chip.observe``, a wrapped ``chip.read``) are the caller's functions: unset them before saving (a closure stops the save). The file: :data:`MAGIC`, a 4-byte big-endian length, a JSON header (:class:`Header`), then the pickle, zlib-compressed. The header is checked on load before anything is unpickled: format, every core's revision, the board's, the cartridge's and boot ROMs' SHA-1s. A pickle runs code of the classes it names, so load only states you made. """ from __future__ import annotations import hashlib import importlib import io import json import pickle import subprocess import sys import types import zlib from dataclasses import asdict, dataclass, field from importlib import metadata from pathlib import Path from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from megadrive_python.cartridge import Cartridge from megadrive_python.system import System from .bootrom import BootROMs from .slot import Sega32X MAGIC = b"sega32x-python state\n" #: Raised when what a state holds changes meaning; a state of another format is refused. FORMAT = 2 #: The cores whose revisions a state records and requires (distribution names): the #: Mega Drive board, the SH-2s, and the Mega Drive's own chips beneath its board. CORES = ("megadrive-python", "sh2-python", "m68000-python", "z80-python", "ym2612-python", "sn76489-python") # fmt: skip #: The packages whose module-level objects are written by reference: the cores' and ours. PACKAGES = (*(name.replace("-", "_") for name in CORES), "sega32x_python") #: Immutable ``bytes`` this long or longer must be a named image, never written. LARGE_BYTES = 4096 class StateError(ValueError): """A state cannot be written, or does not belong to this board, cartridge or BIOS.""" @dataclass(frozen=True) class Header: """What a state was made from, checked on load (all but ``python`` and ``frame``).""" format: int #: Frames run before the state was taken (the next frame to run is ``frame + 1``). frame: int #: sega32x-python's git revision (``-dirty-`` and a source digest when the package #: has uncommitted changes: :func:`board_revision`). board: str #: Each core's commit (from its installed metadata) or version. cores: dict[str, str] #: The interpreter that wrote it (informative: the pickle is not interpreter-bound). python: str cartridge_sha1: str | None #: "m68k", "master", "slave": each boot ROM's SHA-1 (None for one not fitted). boot_rom_sha1: dict[str, str | None] = field(default_factory=dict) def _sha1(data: bytes | None) -> str | None: return None if data is None else hashlib.sha1(data).hexdigest() def board_revision() -> str: """sega32x-python's git revision, or its version outside a checkout; with changes not committed under the package, ``-dirty-`` and a digest of its source, so a state saved before an edit is refused after it.""" here = Path(__file__).resolve().parent def git(*args: str) -> str: done = subprocess.run( ["git", "-C", str(here), *args], capture_output=True, text=True, check=False ) return done.stdout.strip() if done.returncode == 0 else "" revision = git("rev-parse", "HEAD") if not revision: return "version " + metadata.version("sega32x-python") if not git("status", "--porcelain", "--", str(here)): return revision digest = hashlib.sha1() for path in sorted(here.rglob("*.py")): digest.update(path.relative_to(here).as_posix().encode() + b"\0" + path.read_bytes()) return f"{revision}-dirty-{digest.hexdigest()[:12]}" def core_revisions() -> dict[str, str]: """Each core's commit as pip recorded it (``direct_url.json``), else its version.""" revisions = {} for name in CORES: distribution = metadata.distribution(name) try: commit = json.loads(distribution.read_text("direct_url.json") or "{}") revisions[name] = commit["vcs_info"]["commit_id"] except (KeyError, ValueError): revisions[name] = "version " + distribution.version return revisions def _boot_roms(device: Sega32X) -> dict[str, bytes | None]: """The device's boot ROM images by role.""" side = device.sh2 return { "m68k": device.vector_rom, "master": side.roms[0] if side is not None else None, "slave": side.roms[1] if side is not None else None, } def _images(cartridge: Cartridge | None, boot_roms: dict[str, bytes | None]) -> dict[str, bytes]: """The images a state names instead of writing: role -> bytes.""" images = {f"boot.{role}": image for role, image in boot_roms.items() if image is not None} if cartridge is not None: for name, value in vars(cartridge).items(): if isinstance(value, bytes): images[f"cartridge.{name}"] = value return images def _module_objects() -> dict[int, tuple[str, str, Any]]: """id -> (module, name, key) for the three packages' module-level objects and the values of their module-level dicts (key None for the object itself). Scalars and strings are left to pickle: their identity means nothing.""" found: dict[int, tuple[str, str, Any]] = {} plain = (int, float, complex, str, bool, type(None), types.ModuleType) for module_name, module in sorted(sys.modules.items()): if module is None or module_name.split(".")[0] not in PACKAGES: continue for name, value in sorted(vars(module).items()): if isinstance(value, plain) or name.startswith("__"): continue found.setdefault(id(value), (module_name, name, None)) if isinstance(value, dict): for key, item in value.items(): if isinstance(key, str | int) and not isinstance(item, plain): found.setdefault(id(item), (module_name, name, key)) return found class _Pickler(pickle.Pickler): """Names the images, module-level objects and SH-2 callbacks instead of writing them. (The tables are set after construction: PyPy 3.11's ``_pickle`` takes a subclass's extra constructor arguments for its own.)""" _images: dict[int, str] _modules: dict[int, tuple[str, str, Any]] def persistent_id(self, obj: Any) -> Any: key = id(obj) role = self._images.get(key) if role is not None: return ("image", role) where = self._modules.get(key) if where is not None: return ("module", *where) if isinstance(obj, types.FunctionType) and "" in obj.__qualname__: if obj.__qualname__.startswith("SH2Side."): return ("rewire",) raise StateError(f"cannot save the closure {obj.__module__}.{obj.__qualname__}") if type(obj) is bytes and len(obj) >= LARGE_BYTES: raise StateError(f"{len(obj):,} immutable bytes not known as an image: not saved") return None class _Unpickler(pickle.Unpickler): """Resolves what :class:`_Pickler` named.""" _images: dict[str, bytes] def persistent_load(self, pid: Any) -> Any: kind = pid[0] if kind == "image": try: return self._images[pid[1]] except KeyError: raise StateError(f"the state needs the image {pid[1]}, not given") from None if kind == "module": _, module_name, name, key = pid value = getattr(importlib.import_module(module_name), name) return value if key is None else value[key] if kind == "rewire": return None # SH2Side.rewire puts the callbacks back raise StateError(f"unknown reference {pid!r}") def header_for(system: System, device: Sega32X, frame: int) -> Header: """The header a state of this machine would carry.""" cartridge = device.cartridge return Header( format=FORMAT, frame=frame, board=board_revision(), cores=core_revisions(), python=f"{sys.implementation.name} {sys.version.split()[0]}", cartridge_sha1=_sha1(cartridge.image) if cartridge is not None else None, boot_rom_sha1={role: _sha1(image) for role, image in _boot_roms(device).items()}, ) def dumps(system: System, device: Sega32X, *, frame: int = 0) -> bytes: """The state of ``system`` (with ``device`` in its slot) as bytes. Take it between frames (or between ``System.step`` calls): nothing else is in flight then.""" header = header_for(system, device, frame) buffer = io.BytesIO() images = _images(device.cartridge, _boot_roms(device)) limit = sys.getrecursionlimit() sys.setrecursionlimit(max(limit, 100_000)) try: pickler = _Pickler(buffer, protocol=pickle.HIGHEST_PROTOCOL) pickler._images = {id(image): role for role, image in images.items()} pickler._modules = _module_objects() pickler.dump((system, device)) finally: sys.setrecursionlimit(limit) text = json.dumps(asdict(header), sort_keys=True).encode() return MAGIC + len(text).to_bytes(4, "big") + text + zlib.compress(buffer.getvalue(), 1) def save(path: str | Path, system: System, device: Sega32X, *, frame: int = 0) -> int: """Write the state to ``path``; returns its size in bytes.""" data = dumps(system, device, frame=frame) Path(path).write_bytes(data) return len(data) def read_header(data: bytes) -> tuple[Header, int]: """The header of a state, and where its pickle starts.""" if not data.startswith(MAGIC): raise StateError("not a sega32x-python save state") at = len(MAGIC) length = int.from_bytes(data[at : at + 4], "big") values = json.loads(data[at + 4 : at + 4 + length]) if values.get("format") != FORMAT: raise StateError(f"state format {values.get('format')}, this board reads {FORMAT}") return Header(**values), at + 4 + length def check(header: Header, cartridge: Cartridge | None, boot_roms: dict[str, bytes | None], *, any_board: bool = False) -> None: # fmt: skip """Refuse a state made on other cores, another board revision (unless ``any_board``), or from another cartridge or boot ROMs than the ones given.""" problems = [] cores = core_revisions() for name, revision in header.cores.items(): if cores.get(name) != revision: problems.append(f"{name} {revision} (installed: {cores.get(name)})") board = board_revision() if header.board != board and not any_board: problems.append(f"board {header.board} (this one: {board})") image = cartridge.image if cartridge is not None else None if header.cartridge_sha1 != _sha1(image): problems.append(f"cartridge SHA-1 {header.cartridge_sha1} (given: {_sha1(image)})") for role, sha1 in header.boot_rom_sha1.items(): if sha1 != _sha1(boot_roms.get(role)): problems.append(f"{role} boot ROM SHA-1 {sha1} (given: {_sha1(boot_roms.get(role))})") if problems: raise StateError("the state was made from " + "; ".join(problems)) def loads(data: bytes, cartridge: Cartridge | None, *, boot_roms: BootROMs | None = None, vector_rom: bytes | None = None, any_board: bool = False) -> tuple[System, Sega32X, Header]: # fmt: skip """The machine in ``data``. ``cartridge`` is built the way the saved one was (e.g. ``console.cartridge_for(image)``): only its images are used, its state is the saved one. ``boot_roms`` (or a bare ``vector_rom`` for a test without SH-2s) as they were.""" header, start = read_header(data) roms: dict[str, bytes | None] = {"m68k": vector_rom, "master": None, "slave": None} if boot_roms is not None: roms = {"m68k": boot_roms.m68k, "master": boot_roms.master, "slave": boot_roms.slave} check(header, cartridge, roms, any_board=any_board) limit = sys.getrecursionlimit() sys.setrecursionlimit(max(limit, 100_000)) try: payload = io.BytesIO(zlib.decompress(data[start:])) unpickler = _Unpickler(payload) unpickler._images = _images(cartridge, roms) system, device = unpickler.load() finally: sys.setrecursionlimit(limit) if device.sh2 is not None: device.sh2.rewire() return system, device, header def load(path: str | Path, cartridge: Cartridge | None, *, boot_roms: BootROMs | None = None, vector_rom: bytes | None = None, any_board: bool = False) -> tuple[System, Sega32X, Header]: # fmt: skip """:func:`loads` of the file at ``path``.""" return loads(Path(path).read_bytes(), cartridge, boot_roms=boot_roms, vector_rom=vector_rom, any_board=any_board) # fmt: skip __all__ = [ "FORMAT", "MAGIC", "Header", "StateError", "check", "dumps", "header_for", "load", "loads", "read_header", "save", ]