# SPDX-License-Identifier: MIT """Save states: the whole console between two 68000 steps, as bytes, and back. The specification is docs/save-states.md; this module is its implementation. A save state is everything that changes as the console runs: the two CPUs (each core's own ``capture_state``), the system's scheduler, the board and its bus arbiter, the VDP with its FIFO, DMA and renderer, the I/O chip and the devices in its ports, the FM chip and the PSG (ym2612-python, sn76489-python), the analogue path's filters, and the cartridge with its mapper, battery RAM, EEPROM and, on Virtua Racing, the SVP's DSP (ssp1601-python). It is *not* the wiring: a state is loaded into a :class:`~megadrive_python.system.System` built from the same cartridge on the same machine with the same devices, which already holds the configuration (``Machine``, the VDP's mode tables, the ROM image), the callables that connect the parts and the references between them. Loading writes the saved values into that system's objects in place, so the references the host holds (a pad, the renderer) stay valid. **What is saved**, by walking the object graph from the system: every attribute of every object whose class belongs to one of :data:`MODULES`, depth first in attribute order, as plain data. Not saved (docs/save-states.md, "What is not saved"): - callables, and lists of them (the wiring: bus handlers, catch-up hooks, the DSP's dispatch table); - configuration: frozen dataclasses (``Machine``, the chips' variants), classes, and any object a module of :data:`MODULES` holds at its top level, or in a container there (the VDP's ``H40``, ``V28_NTSC``, the HV units, the EEPROM boards, the sound chips' tables): written by name, never by content, so a mode switch is saved as which mode, and loading never writes into a shared table; - the CPU objects (their ``capture_state`` is saved instead); - immutable byte strings: the ROM image and the windows built from it at power-on; - the host's settings (:data:`HOST`: the output sample rate, the FM generator's on/off switch) and pure caches (:data:`SKIPPED`). A second path to an object or to a mutable container already saved is written as a reference to the first path, so sharing (the cartridge on the bus and the one in the slot, an EEPROM and the cartridge RAM it is given) is restored as it was saved. **The format**: :data:`MAGIC`, a four-byte length and a JSON header (format, version, the cartridge's SHA-1, the machine's name and the wiring), checked before anything else is read, then the zlib-compressed JSON body. It holds no code: loading creates nothing but this package's (and its cores') own classes and plain data. **Equivalence** is the test (tests/test_state.py, scripts/state_roundtrip.py): a run saved between two 68000 steps and loaded into a fresh system continues exactly as the run that was never interrupted -- every 68000 and Z80 instruction, every picture, every sample. """ from __future__ import annotations import base64 import dataclasses import enum import hashlib import json import struct import sys import types import zlib from typing import TYPE_CHECKING, Any from m68000_python.state import CPUState as M68000State from z80_python.state import CPUState as Z80State if TYPE_CHECKING: from .system import System #: The first eight bytes of every state. MAGIC = b"MDPYSTAT" FORMAT = "megadrive-python state" #: Refused up front when it differs. Raise it whenever a saved attribute is added, #: removed, renamed or changes meaning anywhere in the graph (cores included). VERSION = 2 #: Packages whose objects are part of the state. MODULES = ("megadrive_python", "ym2612_python", "sn76489_python", "ssp1601_python") #: Attributes that are not state: pure caches, rebuilt by need from what is saved. #: ``System._z80_timings`` maps an instruction's bytes to z80-python's access offsets. SKIPPED = {"_z80_timings"} #: The host's settings, by class and attribute: the loading system keeps its own. HOST = { ("megadrive_python.audio.AudioPath", "sample_rate"), ("ym2612_python.chip.YM2612", "enabled"), ("megadrive_python.vdp.VDP", "rendering"), ("megadrive_python.vdp.VDP", "undrawn_frame"), } #: Immutable tables built from the ROM at power-on, by class and attribute: written as #: ``{"image": n}``, as the ROM's own bytes are, and the loading system's own kept (the #: header's SHA-1 has said it is the same cartridge). Each must be a tuple. IMAGES = {("megadrive_python.svp.SVP", "rom_words")} _HEADER_LENGTH = struct.Struct(">I") class StateError(ValueError): """A state that cannot be saved from, or loaded into, this system.""" # -- what identifies the console a state belongs to ------------------------------- def _images(system: System) -> list[bytes]: """The cartridge images, in order: the slot's cartridge, the patch ROM of a lock-on board, the cartridge plugged into its top, and so on.""" out: list[bytes] = [] cartridge = system.board.slot_cartridge while cartridge is not None: out.append(cartridge.image) patch = getattr(cartridge, "patch", b"") if patch: out.append(patch) cartridge = getattr(cartridge, "sub", None) return out def rom_sha1(system: System) -> str: """SHA-1 of the cartridge images (``_images``), joined; "" for an empty slot.""" images = _images(system) if not images: return "" digest = hashlib.sha1() for image in images: digest.update(image) return digest.hexdigest() def _wiring(system: System) -> dict: """What the system was built with besides the cartridge and the machine: the boot ROM, the devices in the control ports and the expansion sockets. A state is loaded only into a system wired the same.""" board = system.board tmss = board.tmss_rom return { "tmss_rom": hashlib.sha1(tmss.image).hexdigest() if tmss is not None else "", "ports": [ _qualified(port.device) if port.device is not None else "" for port in board.io.ports ], "slot": _qualified(board.slot) if board.slot is not None else "", "port": _qualified(board.port) if board.port is not None else "", } def _header(system: System) -> dict: return { "format": FORMAT, "version": VERSION, "rom_sha1": rom_sha1(system), "machine": system.machine.name, "wiring": _wiring(system), } # -- what counts as state ----------------------------------------------------------- def _ours(value: object) -> bool: return type(value).__module__.split(".", 1)[0] in MODULES def _qualified(value: object) -> str: cls = type(value) return f"{cls.__module__}.{cls.__qualname__}" def _frozen(value: object) -> bool: params = getattr(type(value), "__dataclass_params__", None) return dataclasses.is_dataclass(value) and params is not None and params.frozen def _wiring_value(value: object) -> bool: """A callable that is not one of our objects, or a list or tuple of them only.""" if isinstance( value, (types.FunctionType, types.MethodType, types.BuiltinFunctionType, types.BuiltinMethodType), ): return True if callable(value) and not _ours(value) and not isinstance(value, type): return True if type(value) in (list, tuple) and value: # A dispatch table: callables, with None in the holes (the SSP1601's). items = [item for item in value if item is not None] # type: ignore[union-attr] return bool(items) and all(_wiring_value(item) for item in items) return False def _fields(value: object) -> dict[str, Any]: """An object's attributes: its ``__dict__``, and its ``__slots__`` up the classes.""" fields = dict(getattr(value, "__dict__", {})) for cls in type(value).__mro__: for name in getattr(cls, "__slots__", ()): if name not in fields and name != "__dict__" and hasattr(value, name): fields[name] = getattr(value, name) return fields _CONFIG: dict[int, tuple[str, object]] = {} _CONFIG_BY_NAME: dict[str, object] = {} _CONFIG_MODULES: tuple[str, ...] = () def _configuration() -> dict[int, tuple[str, object]]: """Every object the packages of :data:`MODULES` hold at module level, and everything reachable from one (through containers and the attributes of their objects), by identity: ``"module:NAME"`` and paths below it (``"module:NAME.attr[3]"``). Built again whenever another of their modules has been imported; the modules' tables are built at import and never replaced. The whole reach matters, not just the top: a console holds parts of shared tables directly (the VDP's ``slots`` is the ``H40`` line table's ``slots_active`` list), and such a part saved by value would be loaded *into* the table every console shares. """ global _CONFIG, _CONFIG_MODULES names = tuple( sorted( name for name, module in sys.modules.items() if module is not None and name.split(".", 1)[0] in MODULES ) ) if names == _CONFIG_MODULES: return _CONFIG found: dict[int, tuple[str, object]] = {} scalars = (types.ModuleType, type, int, float, str, bool, bytes) def reach(value: Any, label: str) -> None: if value is None or isinstance(value, scalars) or _wiring_value(value): return kind = type(value) if kind in (tuple, frozenset): # Written by value (an empty tuple is one object everywhere); what an # immutable container holds may still be configuration. items: Any = enumerate(value) if kind is tuple else enumerate(sorted(value, key=repr)) else: if id(value) in found: return found[id(value)] = (label, value) if kind is list: items = enumerate(value) elif kind is dict: items = enumerate(value.values()) elif kind is set: items = enumerate(sorted(value, key=repr)) elif _ours(value) or _frozen(value): for name, attribute in _fields(value).items(): reach(attribute, f"{label}.{name}") return else: return for i, item in items: reach(item, f"{label}[{i}]") for module_name in names: if module_name == __name__: continue for name, value in sorted(vars(sys.modules[module_name]).items()): if not callable(value): reach(value, f"{module_name}:{name}") _CONFIG, _CONFIG_MODULES = found, names _CONFIG_BY_NAME.clear() _CONFIG_BY_NAME.update(dict(found.values())) return found def _named(label: str) -> object: """The configuration object ``label`` names, importing its module if this process has not yet.""" _configuration() if label not in _CONFIG_BY_NAME: module = label.split(":", 1)[0] if module.split(".", 1)[0] in MODULES and module not in sys.modules: import contextlib import importlib with contextlib.suppress(ImportError): importlib.import_module(module) _configuration() try: return _CONFIG_BY_NAME[label] except KeyError: raise StateError(f"no such configuration: {label}") from None # -- saving ------------------------------------------------------------------------- class _Encoder: def __init__(self, system: System, skipped: set[str] | None = None) -> None: self.skipped = SKIPPED if skipped is None else skipped self.seen: dict[int, str] = {} self.cpus = {id(system.m68k), id(system.z80)} self.config = _configuration() self.keep: list[object] = [] # what ``seen`` names, kept alive while saving def value(self, value: Any, path: str) -> Any: if value is None or type(value) in (bool, int, str, float): return value if isinstance(value, enum.Enum): return {"enum": _qualified(value), "name": value.name} if type(value) is bytes: # Configuration: the ROM image and what was built from it at power-on. return {"image": len(value)} config = self.config.get(id(value)) if config is not None and config[1] is value: return {"config": config[0]} kind = type(value) if kind in (bytearray, list, dict, set): # Mutable containers keep their identity: a second path is a reference. if id(value) in self.seen: return {"ref": self.seen[id(value)]} self.seen[id(value)] = path self.keep.append(value) if kind is bytearray: return {"bytearray": base64.b64encode(value).decode()} if kind is list: return [self.value(item, f"{path}[{i}]") for i, item in enumerate(value)] if kind is set: return {"set": sorted((self.value(item, path) for item in value), key=repr)} return { "dict": [ [self.value(k, path), self.value(v, f"{path}[{k!r}]")] for k, v in value.items() ] } if kind is tuple: return {"tuple": [self.value(item, f"{path}[{i}]") for i, item in enumerate(value)]} if kind is frozenset: return {"frozenset": sorted((self.value(item, path) for item in value), key=repr)} if isinstance(value, tuple) and _ours(value): # a NamedTuple of ours return { "namedtuple": _qualified(value), "items": [self.value(item, f"{path}[{i}]") for i, item in enumerate(value)], } if _ours(value) and not _frozen(value) and not isinstance(value, type): if id(value) in self.seen: return {"ref": self.seen[id(value)]} self.seen[id(value)] = path self.keep.append(value) return self.object(value, path) raise StateError(f"{path}: cannot save a {_qualified(value)}") def object(self, value: object, path: str) -> dict: qualified = _qualified(value) fields = {} for name, attribute in _fields(value).items(): if name in self.skipped or (qualified, name) in HOST or id(attribute) in self.cpus: continue if _frozen(attribute) or isinstance(attribute, (type, types.ModuleType)): continue # configuration, or a class if _wiring_value(attribute): continue # a function, a bound method, a list of them: wiring if (qualified, name) in IMAGES: if type(attribute) is not tuple: raise StateError(f"{path}.{name}: a ROM table that is not a tuple") fields[name] = {"image": len(attribute)} continue fields[name] = self.value(attribute, f"{path}.{name}") return {"object": qualified, "fields": fields} def _body(system: System, skipped: set[str] | None = None) -> dict: encoder = _Encoder(system, skipped) return { "m68k": dataclasses.asdict(system.m68k.capture_state()), "z80": dataclasses.asdict(system.z80.capture_state()), "system": encoder.value(system, "system"), } def machine_state(system: System) -> dict: """Everything of ``system``'s state but its picture: :func:`save_state`'s body, as a value to compare, with the renderer holding only the fields software can see the effects of (``render.SEEN``). Two runs of one cartridge, one drawing its frames and one not (``VDP.rendering``), give equal values at every step.""" from .render import SEEN body = _body(system) def strip(encoded: Any) -> None: if type(encoded) is list: for item in encoded: strip(item) elif type(encoded) is dict: if encoded.get("object") == "megadrive_python.render.Renderer": encoded["fields"] = {k: v for k, v in encoded["fields"].items() if k in SEEN} return for item in encoded.values(): strip(item) strip(body["system"]) return body def save_state(system: System) -> bytes: """The state of ``system`` as bytes, between two of its steps (``System.step``).""" if system._in_z80: raise StateError("a state is saved between steps, not inside the Z80's catch-up") header = json.dumps(_header(system), separators=(",", ":")).encode() body = json.dumps(_body(system), separators=(",", ":")).encode() return MAGIC + _HEADER_LENGTH.pack(len(header)) + header + zlib.compress(body, 6) # -- loading ------------------------------------------------------------------------ def _class(name: str) -> type: """A class of one of :data:`MODULES` by its qualified name (never anything else).""" import importlib module, _, qualname = name.rpartition(".") while module and module.split(".", 1)[0] in MODULES: try: found: Any = importlib.import_module(module) except ModuleNotFoundError: module, _, outer = module.rpartition(".") qualname = f"{outer}.{qualname}" continue for part in qualname.split("."): found = getattr(found, part, None) if isinstance(found, type): return found break raise StateError(f"not a class a state may hold: {name}") class _Decoder: """Applies an encoded graph to a system, in place where it can. The encoder writes each object and each mutable container once, at the first path that reaches it, and a reference at every later one. The decoder walks in the same order, keeps what it restores by that path, and gives a reference what was restored there, so sharing is as it was saved. An existing object or container is updated in place only by the first path that claims it; another path saved with one of its own gets a new one. """ def __init__(self) -> None: self.objects: dict[str, object] = {} self.claimed: set[int] = set() _configuration() def reference(self, encoded: dict) -> object: try: return self.objects[encoded["ref"]] except KeyError: raise StateError(f"a reference to nothing saved: {encoded['ref']}") from None def fresh(self, encoded: Any, path: str) -> Any: """A value built from ``encoded`` with nothing to update in place.""" if encoded is None or type(encoded) in (bool, int, str, float): return encoded if type(encoded) is list: out: Any = [] self.objects[path] = out out.extend(self.fresh(item, f"{path}[{i}]") for i, item in enumerate(encoded)) return out if "ref" in encoded: return self.reference(encoded) if "config" in encoded: return _named(encoded["config"]) if "enum" in encoded: return _class(encoded["enum"])[encoded["name"]] if "image" in encoded: raise StateError(f"{path}: a ROM image where the system has none") if "bytearray" in encoded: out = bytearray(base64.b64decode(encoded["bytearray"])) self.objects[path] = out return out if "tuple" in encoded: return tuple( self.fresh(item, f"{path}[{i}]") for i, item in enumerate(encoded["tuple"]) ) if "frozenset" in encoded: return frozenset(self.fresh(item, path) for item in encoded["frozenset"]) if "set" in encoded: out = set() self.objects[path] = out out.update(self.fresh(item, path) for item in encoded["set"]) return out if "dict" in encoded: out = {} self.objects[path] = out for k, v in encoded["dict"]: key = self.fresh(k, path) out[key] = self.fresh(v, f"{path}[{key!r}]") return out if "namedtuple" in encoded: items = [self.fresh(item, f"{path}[{i}]") for i, item in enumerate(encoded["items"])] return _class(encoded["namedtuple"])(*items) if "object" in encoded: cls = _class(encoded["object"]) obj = cls.__new__(cls) self.objects[path] = obj for name, value in encoded["fields"].items(): setattr(obj, name, self.fresh(value, f"{path}.{name}")) return obj raise StateError(f"cannot load {str(encoded)[:80]}") def _claim(self, current: object, path: str) -> bool: if id(current) in self.claimed or id(current) in _CONFIG: # Never write into configuration: every console shares it. return False self.claimed.add(id(current)) self.objects[path] = current return True def into(self, current: Any, encoded: Any, path: str) -> Any: """``encoded`` applied to ``current``: updated in place where it is an object or a mutable container of the same kind not yet claimed, else built fresh. Returns the value the attribute should hold.""" if isinstance(encoded, dict): if "ref" in encoded: return self.reference(encoded) if "image" in encoded: if type(current) not in (bytes, tuple) or len(current) != encoded["image"]: raise StateError(f"{path}: not the ROM image the state was saved with") return current if "object" in encoded: if ( _ours(current) and _qualified(current) == encoded["object"] and self._claim(current, path) ): self.apply(current, encoded["fields"], path) return current return self.fresh(encoded, path) if "bytearray" in encoded and type(current) is bytearray and self._claim(current, path): current[:] = base64.b64decode(encoded["bytearray"]) return current if "dict" in encoded and type(current) is dict and self._claim(current, path): pairs = [] for k, v in encoded["dict"]: key = self.fresh(k, path) pairs.append((key, self.into(current.get(key), v, f"{path}[{key!r}]"))) current.clear() current.update(pairs) return current if "set" in encoded and type(current) is set and self._claim(current, path): items = [self.fresh(item, path) for item in encoded["set"]] current.clear() current.update(items) return current if ( "tuple" in encoded and type(current) is tuple and len(current) == len(encoded["tuple"]) ): return tuple( self.into(c, e, f"{path}[{i}]") for i, (c, e) in enumerate(zip(current, encoded["tuple"], strict=True)) ) return self.fresh(encoded, path) if type(encoded) is list and type(current) is list and self._claim(current, path): old = current items = [ self.into(old[i] if i < len(old) else None, item, f"{path}[{i}]") for i, item in enumerate(encoded) ] current[:] = items return current return self.fresh(encoded, path) def apply(self, obj: object, fields: dict, path: str) -> None: for name, encoded in fields.items(): setattr(obj, name, self.into(getattr(obj, name, None), encoded, f"{path}.{name}")) def read_header(data: bytes) -> tuple[dict, int]: """The header of a state and where its body starts; raises :class:`StateError` for anything that is not a megadrive-python state of this version.""" if data[: len(MAGIC)] != MAGIC or len(data) < len(MAGIC) + _HEADER_LENGTH.size: raise StateError("not a megadrive-python save state") (length,) = _HEADER_LENGTH.unpack_from(data, len(MAGIC)) start = len(MAGIC) + _HEADER_LENGTH.size try: header = json.loads(data[start : start + length]) except ValueError as error: raise StateError(f"a damaged header: {error}") from None if header.get("format") != FORMAT: raise StateError(f"not a {FORMAT}") if header.get("version") != VERSION: raise StateError(f"a state of version {header.get('version')}, not {VERSION}") return header, start + length def check_header(system: System, header: dict) -> None: """Refuse a state of another cartridge, machine or wiring.""" if header["rom_sha1"] != rom_sha1(system): raise StateError("a state of another cartridge") if header["machine"] != system.machine.name: raise StateError(f"a state of the {header['machine']}, not the {system.machine.name}") wiring = _wiring(system) for key, saved in header["wiring"].items(): if wiring.get(key) != saved: raise StateError(f"a state of a console wired otherwise ({key}: {saved})") def load_state(system: System, data: bytes) -> None: """Put ``system`` in the state ``data`` was saved from (the same cartridge, machine and wiring). Everything is checked before anything is changed: the header, then the body decoded and the CPUs' states validated by their cores.""" header, start = read_header(data) check_header(system, header) try: body = json.loads(zlib.decompress(data[start:])) except (zlib.error, ValueError) as error: raise StateError(f"a damaged body: {error}") from None try: m68k = M68000State( **{k: tuple(v) if type(v) is list else v for k, v in body["m68k"].items()} ) z80 = Z80State(**body["z80"]) except (TypeError, ValueError) as error: raise StateError(f"a CPU state its core refuses: {error}") from None # All or nothing: should the graph fail to apply part way, the system is put back # as it was before the load began. before = _body(system) try: _Decoder().into(system, body["system"], "system") except Exception as error: _Decoder().into(system, before["system"], "system") raise StateError(f"a body this system cannot take: {error}") from None system.m68k.restore_state(m68k) system.z80.restore_state(z80)