# SPDX-License-Identifier: MIT """Save states (``savestate.py``): a synthetic machine -- a 68000 counting in RAM and two SH-2s on stand-in boot ROMs counting in SDRAM through the board's bus -- run straight and through a save and a load must end the same, in this process and in a fresh one that has built no console; the file holds no ROM bytes; and a state is refused for another cartridge or boot ROM.""" from __future__ import annotations import os import pickle import subprocess import sys import zlib import pytest from conftest import SYNTHETIC_VECTORS, image, run from megadrive_python.cartridge import Cartridge from megadrive_python.machine import MACHINES from megadrive_python.system import System from sega32x_python import BootROMs, Sega32X, savestate #: addq.w #1,$FF0000 / bra.s back: the 68000 counts. COUNT = "5279 00ff 0000 60f8" def _sh2_rom(size: int) -> bytes: """PC $100, SP in SDRAM: ``mov.l @(2,pc),r1`` ($06000000), then ``add #1,r0`` / ``mov.l r0,@r1`` / ``bra`` back with a ``nop`` in its slot -- a counter in SDRAM.""" rom = bytearray(size) rom[0:4] = (0x100).to_bytes(4, "big") rom[4:8] = (0x0603F000).to_bytes(4, "big") rom[0x100:0x110] = bytes.fromhex("d102 7001 2102 affc 0009 0009 0600 0000") return bytes(rom) STAND_IN = BootROMs(m68k=SYNTHETIC_VECTORS, master=_sh2_rom(2048), slave=_sh2_rom(1024)) def _cartridge() -> Cartridge: return Cartridge(image(COUNT)) def _machine() -> tuple[System, Sega32X]: device = Sega32X(_cartridge(), boot_roms=STAND_IN) system = System(MACHINES["genesis"], None, slot=device) # type: ignore[arg-type] system.board.fm.enabled = False system.attach_video_timing(device) system.attach_picture(device) system.audio_sources.append(device.pwm) board = system.board board.write_word(0xA15106, 1) # RV = 1: the 68000's code stays visible board.write_word(0xA15100, 3) # ADEN | RES: the SH-2s released return system, device def _fingerprint(system: System, device: Sega32X) -> tuple: sh2 = device.sh2 assert sh2 is not None m68k = system.m68k return ( system.mclk, m68k.PC, tuple(m68k.R), m68k.SR, bytes(system.board.ram), bytes(sh2.sdram), tuple(sh2.instructions), tuple((chip.pc, tuple(chip.R), chip.clock) for chip in sh2.chips), system.take_audio(), ) def test_a_loaded_state_runs_on_as_the_straight_run() -> None: straight, straight_device = _machine() run(straight, 3000) data = savestate.dumps(straight, straight_device, frame=7) run(straight, 3000) expected = _fingerprint(straight, straight_device) system, device, header = savestate.loads(data, _cartridge(), boot_roms=STAND_IN) assert header.frame == 7 assert system is not straight and device.sh2 is not None assert device.sh2.sdram[3] and int.from_bytes(system.board.ram[0:2], "big") # counting run(system, 3000) assert _fingerprint(system, device) == expected #: A fresh process: load the state from stdin, run on, write the fingerprint to stdout. #: It builds no console first, so every core's class-level set-up (the 68000's and the #: SH-2s' dispatch tables) must come from the state alone. FRESH = """ import pickle, sys import test_savestate as t from sega32x_python import savestate system, device, _ = savestate.loads(sys.stdin.buffer.read(), t._cartridge(), boot_roms=t.STAND_IN) t.run(system, 3000) sys.stdout.buffer.write(pickle.dumps(t._portable(t._fingerprint(system, device)))) """ def _portable(fingerprint: tuple) -> tuple: """The fingerprint with each sound source replaced by its class name: the samples compare across processes, the source objects do not.""" *rest, audio = fingerprint return (*rest, [(type(source).__name__, samples) for source, samples in audio]) def test_a_state_loads_and_runs_on_in_a_fresh_process() -> None: straight, straight_device = _machine() run(straight, 3000) data = savestate.dumps(straight, straight_device, frame=7) run(straight, 3000) expected = _portable(_fingerprint(straight, straight_device)) env = {**os.environ, "PYTHONPATH": os.pathsep.join(sys.path)} done = subprocess.run([sys.executable, "-c", FRESH], input=data, env=env, capture_output=True, check=False) # fmt: skip assert done.returncode == 0, done.stderr.decode() assert pickle.loads(done.stdout) == expected def test_the_state_holds_no_rom_and_is_refused_for_another() -> None: system, device = _machine() run(system, 500) data = savestate.dumps(system, device) header, start = savestate.read_header(data) pickled = zlib.decompress(data[start:]) assert b"SEGA 32X " not in pickled # the cartridge's header assert bytes.fromhex("d102 7001 2102 affc") not in pickled # boot ROMs assert header.cartridge_sha1 is not None and header.boot_rom_sha1["master"] is not None other = Cartridge(image("60fe")) with pytest.raises(savestate.StateError, match="cartridge SHA-1"): savestate.loads(data, other, boot_roms=STAND_IN) wrong = BootROMs(m68k=SYNTHETIC_VECTORS, master=bytes(2048), slave=STAND_IN.slave) with pytest.raises(savestate.StateError, match="master boot ROM"): savestate.loads(data, _cartridge(), boot_roms=wrong) with pytest.raises(savestate.StateError, match="not a sega32x-python save state"): savestate.loads(b"nonsense", _cartridge(), boot_roms=STAND_IN)