// SPDX-License-Identifier: MIT //! Save states (src/state.rs; the reference's tests/test_state.py): a state saved between //! two 68000 steps and loaded into a fresh system continues as the run that was never //! interrupted, on the example cartridges (no ROM): against the reference's own traces //! of them, through `md-trace`'s `--save-at` and `--rewind-at`, and step by step; and //! socket 10, a socket device's own side of a state, with a test-only slot device //! (tests/support/fake_devices.rs, `FakeSavedDevice`). #[path = "support/fake_devices.rs"] mod fake_devices; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; use fake_devices::{FakeAudio, FakeDevice, FakePicture, FakeSavedDevice, Loads, Shared}; use megadrive_rust::sockets::{Picture, PictureLine, PictureRow}; use megadrive_rust::cartridge::Cartridge; use megadrive_rust::io::Device; use megadrive_rust::machine::machine; use megadrive_rust::state::{load_snapshot, load_state, save_snapshot, save_state}; use megadrive_rust::system::System; use megadrive_rust::trace::Run; fn examples() -> PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/examples") } fn image(name: &str) -> Vec { std::fs::read(examples().join(name)).unwrap() } fn system(name: &str, machine_name: &str, pad: &str) -> System { System::new( machine(machine_name).unwrap(), Some(Cartridge::from_image(image(name))), Some([ Device::by_name(pad).unwrap(), Device::by_name("3button").unwrap(), ]), None, ) } /// Every step's clocks and PCs, then the memories, the picture and the sound. fn trail(system: &mut System, steps: usize) -> Vec { let mut out = Vec::with_capacity(steps + 1); for _ in 0..steps { system.step().unwrap(); let pc = system.m68k.capture_state().pc; let md = system.md(); out.push(format!("{} {pc} {} {}", md.mclk, md.z80_mclk, md.z80.pc)); } let audio = system.take_audio(); let board = system.board(); out.push(format!( "{:?} {:?} {:?} {:?} {:?}", board.dev.ram, board.dev.z80_ram, board.vdp.s.vram, board.vdp.s.cram, audio )); out } fn continues(name: &str, machine_name: &str, pad: &str, at: usize) { let mut whole = system(name, machine_name, pad); for _ in 0..at { whole.step().unwrap(); } let data = save_state(&whole).unwrap(); let mut copy = system(name, machine_name, pad); load_state(&mut copy, &data).unwrap(); assert_eq!( save_snapshot(©).unwrap(), save_snapshot(&whole).unwrap(), "{name} at {at}: the loaded state" ); assert_eq!( trail(&mut copy, 4000), trail(&mut whole, 4000), "{name} at {at}" ); assert_eq!( save_snapshot(©).unwrap(), save_snapshot(&whole).unwrap(), "{name} at {at}: at the end" ); } #[test] fn board_tour_continues_from_any_step() { // 198 is inside the VRAM fill and 1,409 has a Z80 instruction held part way by a bus // request, as in the reference's test. for at in [0, 1, 187, 198, 1409, 5000, 23_456] { continues("board-tour.bin", "genesis", "3button", at); } } #[test] fn h32_sprites_on_a_pal_console_with_six_buttons() { continues("h32-sprites.bin", "megadrive", "6button", 30_000); } /// `md-trace --save-at` and `--rewind-at` against the reference's trace of the example. fn traced(cartridge: &str, frames: u64, options: &[(&str, &str)]) { let mut run = Run::new(examples().join(cartridge)); run.frames = frames; for (option, value) in options { let mut value = Some(value.to_string()).into_iter(); run.option(option, &mut || { value.next().ok_or_else(|| "no value".to_string()) }) .unwrap(); } let mut ours = Vec::new(); run.trace(&mut ours).unwrap(); let theirs = std::fs::read_to_string(examples().join(cartridge.replace(".bin", ".trace"))).unwrap(); assert_eq!( String::from_utf8(ours).unwrap(), theirs, "{cartridge} {options:?}" ); } #[test] fn the_reference_traces_through_save_states() { traced( "board-tour.bin", 120, &[ ("--save-at", "40+1777"), ("--save-at", "60"), ("--rewind-at", "80"), ], ); traced( "h32-raster.bin", 60, &[("--save-at", "20+999"), ("--rewind-at", "40")], ); } #[test] fn mismatches_are_refused_and_change_nothing() { let mut source = system("board-tour.bin", "genesis", "3button"); for _ in 0..100 { source.step().unwrap(); } let data = save_state(&source).unwrap(); let refused = |target: &mut System, data: &[u8], want: &str| { let before = save_snapshot(target).unwrap(); let error = load_state(target, data).unwrap_err(); assert!(error.contains(want), "{error:?} does not say {want:?}"); assert_eq!( save_snapshot(target).unwrap(), before, "a refused load changed the system" ); }; let mut garbage = b"garbage".to_vec(); garbage.extend(&data); refused( &mut system("board-tour.bin", "genesis", "3button"), &garbage, "not a megadrive-rust", ); refused( &mut system("h32-sprites.bin", "genesis", "3button"), &data, "another cartridge", ); refused( &mut system("board-tour.bin", "megadrive", "3button"), &data, "not the", ); refused( &mut system("board-tour.bin", "genesis", "6button"), &data, "wired otherwise", ); let mut damaged = data.clone(); damaged.truncate(data.len() - 20); let mut target = system("board-tour.bin", "genesis", "3button"); for _ in 0..50 { target.step().unwrap(); } refused(&mut target, &damaged, "damaged body"); } #[test] fn the_host_settings_stay_the_hosts() { let mut whole = system("board-tour.bin", "genesis", "3button"); whole.audio.sample_rate = 22_050; let data = save_state(&whole).unwrap(); let mut copy = system("board-tour.bin", "genesis", "3button"); copy.audio.sample_rate = 48_000; copy.board().dev.fm.enabled = false; copy.board().vdp.s.rendering = false; load_state(&mut copy, &data).unwrap(); assert_eq!(copy.audio.sample_rate, 48_000); assert!(!copy.board().dev.fm.enabled); assert!(!copy.board().vdp.s.rendering); } #[test] fn one_snapshot_loaded_again_and_again() { // Rewind's and run-ahead's use: the same system takes one snapshot back repeatedly. let mut system = system("board-tour.bin", "genesis", "3button"); for _ in 0..2000 { system.step().unwrap(); } let snapshot = save_snapshot(&system).unwrap(); let first = trail(&mut system, 1500); for _ in 0..3 { load_snapshot(&mut system, &snapshot).unwrap(); assert_eq!(trail(&mut system, 1500), first); } } /// Every line table and every frame table comes back as itself. The long and short H40 /// lines are in force only on an interlaced odd field's VSYNC lines, which no save point /// of the save-state rung happens to land on (its seeded fault "the long and short H40 /// lines swapped" went unseen there), so this holds them directly. #[test] fn every_line_and_frame_table_comes_back_as_itself() { use megadrive_rust::state::{hmode_ref, vmode_ref}; use megadrive_rust::vdp::{tables, HMode, VMode}; #[derive(serde::Serialize, serde::Deserialize)] struct Modes { #[serde(with = "hmode_ref")] h: &'static HMode, #[serde(with = "vmode_ref")] v: &'static VMode, } let t = tables(); let hs = [&t.h32, &t.h40, &t.h40_vsync, &t.h40_long, &t.h40_short]; let vs = [&t.v28_ntsc, &t.v30_ntsc, &t.v28_pal, &t.v30_pal]; for h in hs { for v in vs { let bytes = bincode::serialize(&Modes { h, v }).unwrap(); let back: Modes = bincode::deserialize(&bytes).unwrap(); assert!(std::ptr::eq(back.h, h) && std::ptr::eq(back.v, v)); } } } /// Fields the rung's save points find idle, set to live values and carried through a /// load: the Z80's EI delay (non-zero only straight after an EI), a 6-button pad part way /// through its TH sequence (it times out between frames), and a serial EEPROM part way /// through a transaction (the rung's seeded faults on all three went unseen there). #[test] fn fields_the_rung_finds_idle_survive_a_load() { let mut image = image("board-tour.bin"); image.resize(0x80000, 0xFF); let build = || { System::new( machine("genesis").unwrap(), Some(Cartridge::new(image.clone(), "rom_nbajam_alt", 0, "")), Some([ Device::by_name("6button").unwrap(), Device::by_name("3button").unwrap(), ]), None, ) }; let mut whole = build(); for _ in 0..500 { whole.step().unwrap(); } let mut z80 = whole.md().z80.capture_state(); z80.ei_delay = 1; whole.md().z80.restore_state(&z80); let dev = &mut whole.board().dev; if let Some(Device::Pad6(pad)) = &mut dev.io.ports[0].device { pad.edges = 2; pad.th_level = 0; pad.last_change = 12_345; } else { panic!("a 6-button pad on port 1"); } let eeprom = dev .cartridge .eeprom .as_mut() .expect("the NBA Jam board's EEPROM"); eeprom.address = 0x5A; eeprom.bit = 3; eeprom.reading = true; let data = save_state(&whole).unwrap(); let mut copy = build(); load_state(&mut copy, &data).unwrap(); assert_eq!(copy.md().z80.capture_state().ei_delay, 1); let dev = &mut copy.board().dev; match &dev.io.ports[0].device { Some(Device::Pad6(pad)) => { assert_eq!((pad.edges, pad.th_level, pad.last_change), (2, 0, 12_345)) } _ => panic!("a 6-button pad on port 1"), } let eeprom = dev.cartridge.eeprom.as_ref().unwrap(); assert_eq!( (eeprom.address, eeprom.bit, eeprom.reading), (0x5A, 3, true) ); } // -- socket 10: a socket device's own state ----------------------------------------------- struct DeviceSystem { system: System, s: Shared, ramp: Arc>, test: Arc>, } /// The tour cartridge held by a slot device that saves its own side, its sound source /// among the console's (the reference's `_device_system`). fn device_system(version: u32, sound: bool) -> DeviceSystem { let (mut device, s, test) = FakeSavedDevice::new( Some(Cartridge::from_image(image("board-tour.bin"))), 32_552.08, ); device.version = version; let source = device.source(); let ramp = device.ramp.clone(); let mut system = System::with_sockets( machine("genesis").unwrap(), None, None, None, Some(Box::new(device)), None, ); if sound { system.audio_sources.push(Box::new(source)); } DeviceSystem { system, s, ramp, test, } } /// Steps in chunks, the host taking the sound after each (as a frontend does). fn chunks(system: &mut System, chunks: usize) -> Vec<(i64, u32, Vec<(i32, i32)>)> { let mut out = Vec::new(); for _ in 0..chunks { for _ in 0..700 { system.step().unwrap(); } let pc = system.m68k.capture_state().pc; out.push((system.mclk(), pc, system.take_audio())); } out } #[test] fn a_socket_device_saves_its_own_side() { let mut whole = device_system(1, true); chunks(&mut whole.system, 4); let data = save_state(&whole.system).unwrap(); let name = std::any::type_name::().as_bytes(); // The header names the device twice: in the wiring, and with its state version. assert_eq!(data.windows(name.len()).filter(|w| *w == name).count(), 2); let mut copy = device_system(1, true); load_state(&mut copy.system, &data).unwrap(); assert_eq!(copy.test.lock().unwrap().loads, 1); { let (a, b) = (whole.s.lock().unwrap(), copy.s.lock().unwrap()); assert!(a.clock == b.clock && a.log == b.log && a.catch_ups == b.catch_ups); assert!(!a.catch_ups.is_empty() && a.ranges == b.ranges); } assert_eq!(whole.ramp.lock().unwrap().n, copy.ramp.lock().unwrap().n); assert_eq!( save_snapshot(©.system).unwrap(), save_snapshot(&whole.system).unwrap() ); assert_eq!(chunks(&mut copy.system, 6), chunks(&mut whole.system, 6)); assert_eq!( save_snapshot(©.system).unwrap(), save_snapshot(&whole.system).unwrap() ); assert_eq!(whole.s.lock().unwrap().log, copy.s.lock().unwrap().log); assert_eq!(whole.ramp.lock().unwrap().calls.len(), 10); // A snapshot, rewind's and run-ahead's path, holds the device's side as well. let snapshot = save_snapshot(&whole.system).unwrap(); let after = chunks(&mut whole.system, 2); load_snapshot(&mut whole.system, &snapshot).unwrap(); assert_eq!(chunks(&mut whole.system, 2), after); } /// Socket 8's pending samples and fractional position are the console's state: a load (a /// rewind, a run-ahead frame) continues the source's interpolation where it was, rather /// than restarting it from its next list. #[test] fn the_further_sources_leftovers_survive_a_load() { let mut whole = device_system(1, true); chunks(&mut whole.system, 3); assert_eq!(whole.system.audio.sources.len(), 1); let record = whole.system.audio.sources[0].clone(); assert!(!record.1.is_empty() && record.2 % 1.0 > 0.0); // pending, part way between two let data = save_state(&whole.system).unwrap(); let mut copy = device_system(1, true); load_state(&mut copy.system, &data).unwrap(); assert_eq!(copy.system.audio.sources, vec![record]); // the loading console's source 0 let after = chunks(&mut whole.system, 3); assert_eq!(chunks(&mut copy.system, 3), after); // Without them the sound parts from the run at once: the click per load. let mut dropped = device_system(1, true); load_state(&mut dropped.system, &data).unwrap(); dropped.system.audio.sources.clear(); assert_ne!(chunks(&mut dropped.system, 3)[0].2, after[0].2); } #[test] fn a_device_at_another_state_version_is_refused_before_anything() { let mut whole = device_system(1, true); chunks(&mut whole.system, 2); let data = save_state(&whole.system).unwrap(); let mut target = device_system(2, true); chunks(&mut target.system, 1); let before = save_snapshot(&target.system).unwrap(); let error = load_state(&mut target.system, &data).unwrap_err(); assert!(error.contains("state version 1, not 2"), "{error}"); assert_eq!(save_snapshot(&target.system).unwrap(), before); assert_eq!(target.test.lock().unwrap().loads, 0); // Another device, and no device, are other wiring. let error = load_state(&mut system("board-tour.bin", "genesis", "3button"), &data).unwrap_err(); assert!(error.contains("wired otherwise"), "{error}"); let plain = save_state(&system("board-tour.bin", "genesis", "3button")).unwrap(); let error = load_state(&mut device_system(1, true).system, &plain).unwrap_err(); assert!( error.contains("wired otherwise") || error.contains("another cartridge"), "{error}" ); // A header naming a device version the body was not saved at: the version after the // device's second naming. let name = std::any::type_name::().as_bytes(); let at = data .windows(name.len()) .enumerate() .filter(|(_, w)| *w == name) .map(|(i, _)| i) .nth(1) .unwrap() + name.len(); let mut forged = data.clone(); assert_eq!(forged[at..at + 4], 1u32.to_le_bytes()); forged[at..at + 4].copy_from_slice(&7u32.to_le_bytes()); let error = load_state(&mut device_system(1, true).system, &forged).unwrap_err(); assert!(error.contains("state version 7, not 1"), "{error}"); } #[test] fn a_device_without_the_socket_cannot_be_saved() { let (device, _s) = FakeDevice::slot(Some(Cartridge::from_image(image("board-tour.bin")))); let system = System::with_sockets( machine("genesis").unwrap(), None, None, None, Some(Box::new(device)), None, ); let error = save_state(&system).unwrap_err(); assert!(error.contains("offers no state"), "{error}"); assert!(save_snapshot(&system) .unwrap_err() .contains("offers no state")); } /// A part of the device the console holds (here a second sound source) that the device's /// bytes do not hold would be loaded stale: the save refuses. #[test] fn a_device_part_in_no_devices_value_is_refused() { let mut device = device_system(1, true); let (audio, _) = FakeAudio::new(22_050.0, 1.0, (5.0, 5.0)); device.system.audio_sources.push(Box::new(audio)); let error = save_state(&device.system).unwrap_err(); assert!(error.contains("no device's state holds"), "{error}"); } /// The loading console's parts must be where the saved console's were (the reference's /// `{"wiring": class}`). #[test] fn a_console_without_the_saved_parts_is_refused() { let mut whole = device_system(1, true); chunks(&mut whole.system, 1); let data = save_state(&whole.system).unwrap(); let mut target = device_system(1, false); let before = save_snapshot(&target.system).unwrap(); let error = load_state(&mut target.system, &data).unwrap_err(); assert!(error.contains("not the device part"), "{error}"); assert_eq!(save_snapshot(&target.system).unwrap(), before); } #[test] fn a_device_that_refuses_its_value_changes_nothing() { let mut whole = device_system(1, true); chunks(&mut whole.system, 3); let data = save_state(&whole.system).unwrap(); let mut target = device_system(1, true); chunks(&mut target.system, 1); let before = save_snapshot(&target.system).unwrap(); target.test.lock().unwrap().refuse = true; let error = load_state(&mut target.system, &data).unwrap_err(); assert!(error.contains("refuses this value"), "{error}"); assert_eq!(save_snapshot(&target.system).unwrap(), before); // The device was put back by its own earlier bytes; the run goes on as it would have. assert_eq!(target.test.lock().unwrap().loads, 1); } /// A picture device whose state is the saved device's (it keeps none of its own here). struct HeldPicture(FakePicture); impl Picture for HeldPicture { fn picture_line(&mut self, line: PictureLine) -> Option { self.0.picture_line(line) } fn held_by(&self) -> Option<&'static str> { Some(std::any::type_name::()) } } fn with_picture(mut device: DeviceSystem) -> DeviceSystem { let replace = (0..224).map(|row| (row, 0x010101 * row as u32)).collect(); device.system.attach_picture(Box::new(HeldPicture(FakePicture { lines: Arc::new(Mutex::new(Vec::new())), replace, }))); device } /// The rows the picture device returned and the line waiting to be handed over are the /// console's state: a state saved part way down a frame gives the frame the uninterrupted /// run gives. #[test] fn the_returned_rows_survive_a_load() { let mut whole = with_picture(device_system(1, true)); whole.system.run_frame().unwrap(); for _ in 0..3000 { whole.system.step().unwrap(); } let data = save_state(&whole.system).unwrap(); let mut copy = with_picture(device_system(1, true)); load_state(&mut copy.system, &data).unwrap(); whole.system.run_frame().unwrap(); copy.system.run_frame().unwrap(); let picture = |system: &mut System| { let vdp = &system.board().vdp; vdp.renderer.frame_rgb(&vdp.s) }; let rows = picture(&mut whole.system); assert_eq!(rows[1], vec![0x010101; 320]); // the device's row, from before the save assert_eq!(picture(&mut copy.system), rows); }