"""Save states (state.py): a run saved and loaded continues exactly as the one that wasn't. The quick tests run a small program written here on every kind of machine; scripts/state_roundtrip.py and the slow test do the same with real cartridges. """ from __future__ import annotations import json import zlib import pytest from sms_python.board import MACHINES from sms_python.cartridge import make_cartridge from sms_python.sf7000 import DISK_SIZE from sms_python.state import Rewind, StateError, load_state, save_state from sms_python.system import System # Turns the display and the frame interrupt on, then loops writing a counter to # the VDP's data port; the interrupt reads the status, counts in RAM and writes # the count to the PSG. PROGRAM = bytearray(0x4000) PROGRAM[0x0000:0x0009] = bytes.fromhex("f3 ed56 31f0df c38000") # DI; IM 1; LD SP; JP $0080 PROGRAM[0x0038:0x0047] = bytes.fromhex("f5 dbbf 3a00c0 3c 3200c0 d37f f1 fb c9") PROGRAM[0x0080:0x009D] = bytes.fromhex( "3ee0 d3bf 3e81 d3bf" # register 1 = $E0 "3e00 d3bf 3ec0 d3bf fb" # address $0000, CRAM (or VRAM on a TMS9918A); EI "3a00c0 d3be 23 2201c0 18f5" # the loop ) PROGRAM = bytes(PROGRAM) def build(name: str) -> System: machine = MACHINES[name] if machine.disk_unit: ipl = make_cartridge(PROGRAM[:0x2000], "rom") return System(machine, None, ipl, disk=bytearray(range(256)) * (DISK_SIZE // 256)) return System(machine, make_cartridge(PROGRAM, "sega")) def trace(system: System, frames: int) -> list[tuple]: out = [] for _ in range(frames): frame = system.run_frame() cpu, vdp = system.cpu, system.board.vdp out.append( ( tuple(map(tuple, frame)), tuple(system.board.take_samples()), cpu.capture_state(), (system.cycles, system.instructions, vdp.line, vdp.m, vdp.address), bytes(vdp.vram), bytes(vdp.cram), bytes(system.board.ram), ) ) return out @pytest.mark.parametrize( "name", ["sg1000", "sc3000pal", "sf7000", "smsj", "gamegear", "megadrive-pbc"] ) def test_a_loaded_state_continues_as_the_run(name: str) -> None: first = build(name) for _ in range(20): first.run_frame() first.run_cycles(12_345) # mid-frame state = save_state(first) expected = trace(first, 12) second = build(name) for _ in range(3): # loading overwrites, it does not rely on power-on values second.run_frame() load_state(second, state) assert trace(second, 12) == expected assert first.board.read_byte(0xC000) != 0 # the program ran: its interrupt counted def test_a_state_can_be_loaded_into_the_system_it_came_from() -> None: system = build("sms2") for _ in range(10): system.run_frame() state = save_state(system) expected = trace(system, 5) load_state(system, state) assert trace(system, 5) == expected def test_shared_memory_stays_shared() -> None: # A Dahjee board's RAM replaces the console's: one bytearray, two owners. system = System(MACHINES["sg1000"], make_cartridge(PROGRAM, "dahjee_typeb")) disk_system = build("sf7000") disk = disk_system.board.disk_unit.fdc.disk for _ in range(5): system.run_frame() state, disk_state = save_state(system), save_state(disk_system) system.board.ram[5] = 0x77 disk[5] = 0x77 load_state(system, state) load_state(disk_system, disk_state) assert system.board.ram is system.board.cartridge.work_ram and system.board.ram[5] != 0x77 assert disk_system.board.disk_unit.fdc.disk is disk and disk[5] == 5 def test_the_fm_chip_s_custom_instrument_is_saved() -> None: system = build("smsj") opll = system.board.opll def write(register: int, value: int) -> None: opll.write(0, register) opll.run(72) # the chip takes a write as its clock runs opll.write(1, value) opll.run(72) # The custom instrument is registers $00-$07 and what the chip decodes from # them; a note on channel 0 plays it. All of it must come back, and the chip # must then go on exactly as it would have. writes = ((0x00, 0x5A), (0x01, 0x21), (0x05, 0xF0), (0x30, 0x00), (0x10, 0x20), (0x20, 0x17)) for register, value in writes: write(register, value) opll.take_outputs() def snapshot() -> tuple: return bytes(opll.registers), list(opll.multiplier), list(opll.level), list(opll.phase) state = save_state(system) saved = snapshot() opll.run(72 * 100) expected = opll.take_outputs() write(0x00, 0x21) assert bytes(opll.registers) != saved[0] load_state(system, state) assert snapshot() == saved opll.run(72 * 100) assert opll.take_outputs() == expected and max(melody for melody, _ in expected) > 0 def test_a_state_is_refused_by_another_cartridge_or_machine() -> None: state = save_state(build("sms2")) other = System(MACHINES["sms2"], make_cartridge(PROGRAM[:-1] + b"\x01", "sega")) with pytest.raises(StateError, match="another cartridge"): load_state(other, state) with pytest.raises(StateError, match="not the"): load_state(build("sms1"), state) with pytest.raises(StateError, match="not a save state"): load_state(build("sms2"), b"not a state") def test_a_state_holds_no_code() -> None: """Loading creates only these packages' classes: a state naming another is refused.""" system = build("sms2") body = json.loads(zlib.decompress(save_state(system))) body["board"]["fields"]["io"] = {"object": "subprocess.Popen", "fields": {}} with pytest.raises(StateError, match="not a class"): load_state(system, zlib.compress(json.dumps(body).encode())) assert b"rom" in zlib.decompress(save_state(system)) # the ROM is named, not held assert len(save_state(system)) < len(PROGRAM) def test_rewind_steps_back_and_stops_at_the_oldest() -> None: system = build("sms2") rewind = Rewind(system, every=2, keep=3) assert not rewind.back() # nothing kept yet seen = [] for _ in range(8): # states at frames 0, 2, 4, 6; the first is dropped rewind.record() seen.append(system.cycles) system.run_frame() for expected in (seen[6], seen[4], seen[2], seen[2]): assert rewind.back() and system.cycles == expected