From 3d1a81a6796b1e574a2167519e383baf1c71750c Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 13:43:40 +0000 Subject: [PATCH] flybrain-gb: the boundary memory image (MEM-01) One read-only bulk read in the shim, fly_gb_read_memory_image: the address space's memory in address order, the register windows (VRAM, OAM, I/O) read $FF because binjgb's catch-up on a register read moves the exported state. MemoryImage, Cartridge and ImageReader put an image and the ROM behind MemoryReader, so the same macro engine and adapter run over it; the emulator's bank reads go through the same Cartridge. ROM tests prove the read leaves the state byte-identical, equals the single and cached reads, changes nothing downstream, and measure its cost. --- .../flysim/crates/flybrain-gb/csrc/shim.c | 45 +++ .../flysim/crates/flybrain-gb/src/emulator.rs | 70 ++-- services/flysim/crates/flybrain-gb/src/ffi.rs | 2 + .../flysim/crates/flybrain-gb/src/image.rs | 321 ++++++++++++++++++ services/flysim/crates/flybrain-gb/src/lib.rs | 5 + .../flybrain-gb/tests/rom_memory_image.rs | 303 +++++++++++++++++ 6 files changed, 721 insertions(+), 25 deletions(-) create mode 100644 services/flysim/crates/flybrain-gb/src/image.rs create mode 100644 services/flysim/crates/flybrain-gb/tests/rom_memory_image.rs diff --git a/services/flysim/crates/flybrain-gb/csrc/shim.c b/services/flysim/crates/flybrain-gb/csrc/shim.c index 1494e12..f31e934 100644 --- a/services/flysim/crates/flybrain-gb/csrc/shim.c +++ b/services/flysim/crates/flybrain-gb/csrc/shim.c @@ -127,6 +127,51 @@ u8 fly_gb_read_mem(FlyGb* gb, u16 address) { return emulator_read_mem(gb->e, address); } +/* + * The boundary memory image (MEM-01, legacy-gameboy-v1 section 8 as amended + * 2026-09-29): the CPU address space $0000..=$FFFF in address order. + * + * Every *memory* byte is exactly what fly_gb_read_mem returns for it: ROM as + * mapped ($0000-$7FFF), cartridge RAM ($A000-$BFFF), work RAM and its echo + * ($C000-$FDFF), the unused block ($FEA0-$FEFF), high RAM ($FF80-$FFFE) and + * IE ($FFFF). binjgb reads all of these straight out of its arrays. + * + * The *register* windows are not captured and read as FLY_GB_NOT_CAPTURED: + * VRAM ($8000-$9FFF), OAM ($FE00-$FE9F) and I/O, APU and wave RAM + * ($FF00-$FF7F). binjgb's read of those first runs a lazy catch-up + * (ppu_synchronize, timer_/serial_/intr_synchronize, apu_synchronize) that + * rewrites the subsystem's sync bookkeeping, so reading them would change the + * exported state and could not be called read-only. Nothing a task or an + * executor reads lives there (flysim tests/rom_memory_image.rs records every + * address they read). + * + * Read-only: the captured bytes are the same emulator_read_mem the single read + * makes, and nothing but `out` is written. fly_gb_set_buttons stays the only + * write into a running game; there is no memory-write path. + */ +#define FLY_GB_MEMORY_IMAGE_SIZE 0x10000u +#define FLY_GB_NOT_CAPTURED 0xffu + +size_t fly_gb_memory_image_size(void) { return FLY_GB_MEMORY_IMAGE_SIZE; } + +static int fly_gb_captured(u32 address) { + if (address >= 0x8000u && address <= 0x9fffu) return 0; /* VRAM */ + if (address >= 0xfe00u && address <= 0xfe9fu) return 0; /* OAM */ + if (address >= 0xff00u && address <= 0xff7fu) return 0; /* I/O, APU, wave */ + return 1; +} + +int fly_gb_read_memory_image(FlyGb* gb, u8* out, size_t size) { + u32 address; + if (out == NULL || size != FLY_GB_MEMORY_IMAGE_SIZE) return -1; + for (address = 0; address < FLY_GB_MEMORY_IMAGE_SIZE; ++address) { + out[address] = fly_gb_captured(address) + ? emulator_read_mem(gb->e, (u16)address) + : (u8)FLY_GB_NOT_CAPTURED; + } + return 0; +} + u32 fly_gb_audio_frequency(FlyGb* gb) { return emulator_get_audio_buffer(gb->e)->frequency; } diff --git a/services/flysim/crates/flybrain-gb/src/emulator.rs b/services/flysim/crates/flybrain-gb/src/emulator.rs index dd9b3e3..838fd6e 100644 --- a/services/flysim/crates/flybrain-gb/src/emulator.rs +++ b/services/flysim/crates/flybrain-gb/src/emulator.rs @@ -3,10 +3,9 @@ use std::ffi::c_void; use std::fmt; -use sha2::{Digest, Sha256}; - use crate::adapter::MemoryReader; use crate::ffi; +use crate::image::{Cartridge, MEMORY_IMAGE_LEN, MemoryImage}; /// Game Boy screen geometry, from `emulator.h`. pub const SCREEN_WIDTH: usize = 160; @@ -26,10 +25,6 @@ pub const CPU_TICKS_PER_SECOND: u64 = 4_194_304; /// so there is no `NEW_FRAME` event to wait for yet. const MAX_FRAME_ATTEMPTS: u32 = 120; -/// Bytes in one ROM bank (`$4000`), which is how [`Emulator::read_rom_bank`] -/// turns a bank number and a CPU address into an offset in the cartridge image. -const ROM_BANK_BYTES: usize = 0x4000; - /// Audio frequency flysim runs the emulator at. binjgb resamples internally to /// whatever is requested, so this is only a default. pub const DEFAULT_AUDIO_FREQUENCY: u32 = 48_000; @@ -144,9 +139,9 @@ pub struct Emulator { /// The shim owns its own padded copy behind the handle and does not hand it /// back, so this is a second one. It is read-only from here: nothing in this /// workspace writes a ROM byte, and the bank-addressed read is the only - /// reason it is kept. - rom: std::sync::Arc<[u8]>, - rom_sha256: [u8; 32], + /// reason it is kept. The same [`Cartridge`] an image-backed executor holds + /// (MEM-01), so a bank read is one rule over one set of bytes on both sides. + rom: Cartridge, audio_frequency: u32, /// Raw binjgb samples drained since the last [`Emulator::take_audio`]. pending_audio: Vec, @@ -178,8 +173,7 @@ impl Emulator { debug_assert_eq!(unsafe { ffi::fly_gb_frame_buffer_size() }, FRAMEBUFFER_LEN); Ok(Self { gb, - rom: rom.into(), - rom_sha256: Sha256::digest(rom).into(), + rom: Cartridge::new(rom), audio_frequency, pending_audio: Vec::new(), cache: FrameCache::new(), @@ -263,14 +257,45 @@ impl Emulator { /// No bank register is written and the emulator's state does not move: this /// is a read of bytes the process already owns. pub fn read_rom_bank(&self, bank: u8, address: u16) -> Option { - let offset = match address { - 0x0000..=0x3fff => usize::from(address), - 0x4000..=0x7fff => { - usize::from(bank) * ROM_BANK_BYTES + usize::from(address) - ROM_BANK_BYTES - } - _ => return None, - }; - self.rom.get(offset).copied() + self.rom.read_bank(bank, address) + } + + /// The cartridge this emulator runs, as the executor's ROM asset holds it. + pub fn cartridge(&self) -> Cartridge { + self.rom.clone() + } + + /// The boundary memory image: the CPU address space in one bulk read + /// (`legacy-gameboy-v1` section 8, MEM-01). + /// + /// For every memory address ([`crate::image::CAPTURED`]) byte *i* is what + /// [`Emulator::read_uncached`] returns for *i* now, and so what + /// [`Emulator::read_wram`] returns for it anywhere between this frame and + /// the next: the per-frame cache is only ever filled from the same read, and + /// nothing between two frames moves the emulator. The register windows + /// (VRAM, OAM, I/O) read [`crate::image::NOT_CAPTURED`], because binjgb's + /// read of a register runs a catch-up that moves the exported state. + /// + /// Read-only: the emulator's exported state is byte-identical before and + /// after, and a run read in bulk every frame is frame-for-frame identical to + /// one never read (`tests/rom_memory_image.rs`). The per-frame cache is + /// neither consulted nor filled. + pub fn read_memory_image(&self) -> MemoryImage { + let mut image = MemoryImage::zeroed(); + self.read_memory_image_into(&mut image); + image + } + + /// [`Emulator::read_memory_image`] into an image the caller already owns, + /// so a boundary's read allocates nothing. + pub fn read_memory_image_into(&self, image: &mut MemoryImage) { + debug_assert_eq!(unsafe { ffi::fly_gb_memory_image_size() }, MEMORY_IMAGE_LEN); + let out = image.as_mut_bytes(); + let code = + unsafe { ffi::fly_gb_read_memory_image(self.gb, out.as_mut_ptr(), MEMORY_IMAGE_LEN) }; + // The only refusals are a null buffer and a wrong size, and both are + // ruled out by the type. + assert_eq!(code, 0, "fly_gb_read_memory_image refused a {MEMORY_IMAGE_LEN}-byte buffer"); } /// Sample rate of the raw buffer, as binjgb configured it. @@ -345,12 +370,7 @@ impl Emulator { /// SHA-256 of the ROM bytes as supplied, lowercase hex. This is the /// `romSha256` half of the checkpoint compatibility string. pub fn rom_sha256(&self) -> String { - let mut hex = String::with_capacity(64); - for byte in self.rom_sha256 { - use fmt::Write; - let _ = write!(hex, "{byte:02x}"); - } - hex + self.rom.sha256_hex() } /// Emulated CPU ticks since boot. diff --git a/services/flysim/crates/flybrain-gb/src/ffi.rs b/services/flysim/crates/flybrain-gb/src/ffi.rs index 8973a8b..3a2b792 100644 --- a/services/flysim/crates/flybrain-gb/src/ffi.rs +++ b/services/flysim/crates/flybrain-gb/src/ffi.rs @@ -38,6 +38,8 @@ unsafe extern "C" { pub fn fly_gb_set_buttons(gb: *mut FlyGb, mask: u32); pub fn fly_gb_read_mem(gb: *mut FlyGb, address: u16) -> u8; + pub fn fly_gb_memory_image_size() -> usize; + pub fn fly_gb_read_memory_image(gb: *mut FlyGb, out: *mut u8, size: usize) -> c_int; pub fn fly_gb_audio_frequency(gb: *mut FlyGb) -> u32; pub fn fly_gb_audio_size(gb: *mut FlyGb) -> usize; diff --git a/services/flysim/crates/flybrain-gb/src/image.rs b/services/flysim/crates/flybrain-gb/src/image.rs new file mode 100644 index 0000000..17cf036 --- /dev/null +++ b/services/flysim/crates/flybrain-gb/src/image.rs @@ -0,0 +1,321 @@ +//! The boundary memory image and the cartridge beside it (MEM-01). +//! +//! `docs/design/session-framework/legacy-gameboy-v1.md` section 8: on the session framework the +//! macros run in the coordinator's action executor, not beside a live emulator. What they read +//! there is one 64 KiB image of the CPU address space per boundary, carried as an artifact in the +//! observation's `inspection`, plus the ROM as an `AssetRef`. This module is the read side of that +//! seam and nothing else: +//! +//! - [`MemoryImage`] is the image: for every memory address ([`CAPTURED`]) byte *i* is what +//! `fly_gb_read_mem(i)` returned at the boundary, taken in one bulk read by +//! [`crate::Emulator::read_memory_image`]; the register windows read [`NOT_CAPTURED`]. +//! - [`Cartridge`] is the ROM, content-addressed by its SHA-256, answering the bank-addressed +//! reads the image cannot ([`MemoryReader::read_rom`]). +//! - [`ImageReader`] puts the two behind [`MemoryReader`], so the **same** macro engine, scene +//! detector and reward adapter that read a live [`crate::Emulator`] read an image instead. There +//! is no second implementation of any rule: [`crate::pokemon_red::state::PokeState`] takes a +//! `&mut dyn MemoryReader`, and this is one. +//! +//! Nothing here writes to a game. An image is a copy; reading it cannot move an emulator. + +use std::fmt; +use std::sync::Arc; + +use sha2::{Digest, Sha256}; + +use crate::adapter::MemoryReader; + +/// Bytes in one image: `$0000..=$FFFF`. `fly-session-types`' `gameboy::MEMORY_IMAGE_BYTES`. +pub const MEMORY_IMAGE_LEN: usize = 0x1_0000; + +/// The artifact's content type (`legacy-gameboy-v1` section 8: "a listed bus attachment, content +/// type `application/octet-stream`"). The encoding is the raw bytes in address order, nothing +/// before and nothing after, so the artifact's `byteLength` is always [`MEMORY_IMAGE_LEN`]. +pub const MEMORY_IMAGE_CONTENT_TYPE: &str = "application/octet-stream"; + +/// What an address outside [`CAPTURED`] holds in an image: `$FF`, which is also what binjgb +/// returns for a read the hardware refuses (`INVALID_READ_BYTE`). +pub const NOT_CAPTURED: u8 = 0xff; + +/// The address ranges an image captures, inclusive: every *memory* byte of the address space. +/// +/// Each one is exactly what `fly_gb_read_mem` returned at the boundary: ROM as mapped, cartridge +/// RAM, work RAM and its echo, the unused block, high RAM and `IE`. The three *register* windows +/// between them -- VRAM `$8000-$9FFF`, OAM `$FE00-$FE9F`, I/O with the APU and wave RAM +/// `$FF00-$FF7F` -- are not captured and read [`NOT_CAPTURED`]: binjgb's read of a register +/// first runs the subsystem's lazy catch-up (`ppu_synchronize`, `timer_synchronize`, ...), which +/// rewrites its sync bookkeeping, so reading one moves the exported state (`legacy-gameboy-v1` +/// section 8, amendment of 2026-09-29). Nothing the tasks or executors read is in them. +pub const CAPTURED: [(u16, u16); 4] = + [(0x0000, 0x7fff), (0xa000, 0xfdff), (0xfea0, 0xfeff), (0xff80, 0xffff)]; + +/// Whether an image captures `address` ([`CAPTURED`]). +pub fn captured(address: u16) -> bool { + CAPTURED.iter().any(|&(low, high)| (low..=high).contains(&address)) +} + +/// Bytes in one ROM bank (`$4000`). +const ROM_BANK_BYTES: usize = 0x4000; + +/// Why an image or a cartridge was refused. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ImageError { + /// An image is exactly [`MEMORY_IMAGE_LEN`] bytes. + ImageSize { actual: usize }, + /// The cartridge's SHA-256 is not the one the composition names. + RomDigest { expected: String, actual: String }, +} + +impl fmt::Display for ImageError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::ImageSize { actual } => { + write!(f, "a memory image is {MEMORY_IMAGE_LEN} bytes, got {actual}") + } + Self::RomDigest { expected, actual } => { + write!(f, "the cartridge's sha256 is {actual}, the composition names {expected}") + } + } + } +} + +impl std::error::Error for ImageError {} + +/// One boundary's view of the CPU address space. +/// +/// Owned and immutable once taken: it is the payload of an inspection artifact, which the +/// coordinator keeps until the transition that reads it has been evaluated +/// (`state-media-v1` section 3, RT-01a amendment). +#[derive(Clone, PartialEq, Eq)] +pub struct MemoryImage { + bytes: Box<[u8; MEMORY_IMAGE_LEN]>, +} + +impl MemoryImage { + /// An image of zeroes, to be filled by [`crate::Emulator::read_memory_image_into`]. + pub fn zeroed() -> Self { + let bytes: Box<[u8]> = vec![0u8; MEMORY_IMAGE_LEN].into_boxed_slice(); + Self { bytes: bytes.try_into().expect("exactly MEMORY_IMAGE_LEN bytes") } + } + + /// Decode an artifact's bytes. Exactly [`MEMORY_IMAGE_LEN`] of them, or refused. + pub fn from_bytes(bytes: &[u8]) -> Result { + if bytes.len() != MEMORY_IMAGE_LEN { + return Err(ImageError::ImageSize { actual: bytes.len() }); + } + let mut image = Self::zeroed(); + image.bytes.copy_from_slice(bytes); + Ok(image) + } + + /// The artifact's bytes: the address space in address order. + pub fn as_bytes(&self) -> &[u8; MEMORY_IMAGE_LEN] { + &self.bytes + } + + pub(crate) fn as_mut_bytes(&mut self) -> &mut [u8; MEMORY_IMAGE_LEN] { + &mut self.bytes + } + + /// The byte at a CPU address. + pub fn byte(&self, address: u16) -> u8 { + self.bytes[usize::from(address)] + } + + /// SHA-256 of the artifact's bytes, 64 lowercase hex digits: the bus `Digest` encoding. + /// + /// Optional on the live artifact (a transient frame, `state-media-v1` section 1); mandatory + /// only if an image is ever carried in a checkpoint payload. + pub fn sha256_hex(&self) -> String { + hex(&Sha256::digest(self.bytes.as_slice())) + } +} + +impl fmt::Debug for MemoryImage { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("MemoryImage").field("sha256", &self.sha256_hex()).finish() + } +} + +/// The ROM, as the executor holds it: the composition's `AssetRef`, content-addressed. +/// +/// Cheap to clone (one `Arc`). The emulator holds one too, for its own [`MemoryReader::read_rom`], +/// so the live reader and the image reader answer a bank read from the same function over the +/// same bytes. +#[derive(Clone)] +pub struct Cartridge { + bytes: Arc<[u8]>, + sha256: [u8; 32], +} + +impl Cartridge { + /// The cartridge as supplied: the bytes the emulator was given, before its padding. + pub fn new(rom: &[u8]) -> Self { + Self { bytes: rom.into(), sha256: Sha256::digest(rom).into() } + } + + /// The cartridge only if its SHA-256 is `expected` (lowercase hex), which is how the executor + /// refuses a ROM that is not the environment's `contentDigest` (`legacy-gameboy-v1` section 8). + pub fn verified(rom: &[u8], expected: &str) -> Result { + let cartridge = Self::new(rom); + let actual = cartridge.sha256_hex(); + if actual != expected { + return Err(ImageError::RomDigest { expected: expected.to_string(), actual }); + } + Ok(cartridge) + } + + /// SHA-256 of the ROM bytes as supplied, lowercase hex: the compatibility string's `romSha256`, + /// the environment's `contentDigest` and the inspection's `romDigest`. + pub fn sha256_hex(&self) -> String { + hex(&self.sha256) + } + + pub fn len(&self) -> usize { + self.bytes.len() + } + + pub fn is_empty(&self) -> bool { + self.bytes.is_empty() + } + + /// One byte of ROM bank `bank` at CPU address `address`: see [`MemoryReader::read_rom`]. + pub fn read_bank(&self, bank: u8, address: u16) -> Option { + let offset = match address { + 0x0000..=0x3fff => usize::from(address), + 0x4000..=0x7fff => { + usize::from(bank) * ROM_BANK_BYTES + usize::from(address) - ROM_BANK_BYTES + } + _ => return None, + }; + self.bytes.get(offset).copied() + } +} + +impl fmt::Debug for Cartridge { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Cartridge") + .field("sha256", &self.sha256_hex()) + .field("len", &self.bytes.len()) + .finish() + } +} + +/// A [`MemoryReader`] over one boundary's image and the cartridge. +/// +/// What the executor hands the macro engine in Phase B, and the task in Phase C: the same +/// `&mut dyn MemoryReader` the legacy loop hands them with a live emulator behind it. It needs no +/// cache of its own, because an image is already one frame's reads. +#[derive(Debug, Clone, Copy)] +pub struct ImageReader<'a> { + image: &'a MemoryImage, + rom: &'a Cartridge, +} + +impl<'a> ImageReader<'a> { + pub fn new(image: &'a MemoryImage, rom: &'a Cartridge) -> Self { + Self { image, rom } + } + + pub fn image(&self) -> &'a MemoryImage { + self.image + } +} + +impl MemoryReader for ImageReader<'_> { + fn read8(&mut self, address: u16) -> u8 { + self.image.byte(address) + } + + fn read_rom(&mut self, bank: u8, address: u16) -> Option { + self.rom.read_bank(bank, address) + } +} + +fn hex(bytes: &[u8]) -> String { + use fmt::Write; + let mut out = String::with_capacity(bytes.len() * 2); + for byte in bytes { + let _ = write!(out, "{byte:02x}"); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn an_image_is_exactly_the_address_space() { + assert_eq!(MEMORY_IMAGE_LEN, usize::from(u16::MAX) + 1); + assert_eq!( + MemoryImage::from_bytes(&[0; MEMORY_IMAGE_LEN - 1]).unwrap_err(), + ImageError::ImageSize { actual: MEMORY_IMAGE_LEN - 1 } + ); + assert_eq!( + MemoryImage::from_bytes(&[0; MEMORY_IMAGE_LEN + 1]).unwrap_err(), + ImageError::ImageSize { actual: MEMORY_IMAGE_LEN + 1 } + ); + } + + #[test] + fn the_encoding_is_the_bytes_in_address_order() { + let bytes: Vec = (0..MEMORY_IMAGE_LEN).map(|i| (i ^ (i >> 8)) as u8).collect(); + let image = MemoryImage::from_bytes(&bytes).unwrap(); + assert_eq!(image.as_bytes().as_slice(), bytes.as_slice()); + let rom = Cartridge::new(&[0; 0x8000]); + let mut reader = ImageReader::new(&image, &rom); + for address in [0x0000u16, 0x00ff, 0xc000, 0xd35e, 0xff80, 0xffff] { + assert_eq!(reader.read8(address), bytes[usize::from(address)], "{address:#06x}"); + } + // The digest is over exactly those bytes, in the bus `Digest` encoding. + assert_eq!(image.sha256_hex(), hex(&Sha256::digest(&bytes))); + assert_eq!(image.sha256_hex().len(), 64); + assert!(image.sha256_hex().bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))); + } + + #[test] + fn the_captured_ranges_are_the_memory_between_the_register_windows() { + let captured_count = (0..=u16::MAX).filter(|&address| captured(address)).count(); + // 64 KiB less VRAM (8 KiB), OAM (160 B) and I/O (128 B). + assert_eq!(captured_count, MEMORY_IMAGE_LEN - 0x2000 - 0xa0 - 0x80); + for register in [0x8000u16, 0x9fff, 0xfe00, 0xfe9f, 0xff00, 0xff44, 0xff7f] { + assert!(!captured(register), "{register:#06x}"); + } + for memory in [0x0000u16, 0x7fff, 0xa000, 0xc000, 0xdfff, 0xe000, 0xfdff, 0xfea0, 0xff80, 0xffff] { + assert!(captured(memory), "{memory:#06x}"); + } + // Every symbol the Pokémon macros and adapter name is in WRAM or HRAM. + use crate::pokemon_red::symbols::ram; + for symbol in [ram::wCurMap, ram::wPartyCount, ram::wTileMap, ram::wStatusFlags7, ram::wListMenuID] { + assert!(captured(symbol), "{symbol:#06x}"); + } + } + + #[test] + fn a_bank_read_is_the_emulators_rule() { + // Four banks, each byte naming its bank. + let rom: Vec = (0..4 * ROM_BANK_BYTES).map(|i| (i / ROM_BANK_BYTES) as u8).collect(); + let cartridge = Cartridge::new(&rom); + // Bank 0 is always mapped, whatever the bank asked for. + assert_eq!(cartridge.read_bank(3, 0x0100), Some(0)); + assert_eq!(cartridge.read_bank(3, 0x4000), Some(3)); + assert_eq!(cartridge.read_bank(1, 0x7fff), Some(1)); + // A bank the cartridge does not have, and an address that is not ROM. + assert_eq!(cartridge.read_bank(4, 0x4000), None); + assert_eq!(cartridge.read_bank(1, 0x8000), None); + assert_eq!(cartridge.read_bank(1, 0xc000), None); + } + + #[test] + fn a_cartridge_is_refused_under_another_digest() { + let rom = [7u8; 0x8000]; + let digest = Cartridge::new(&rom).sha256_hex(); + assert!(Cartridge::verified(&rom, &digest).is_ok()); + let wrong = "0".repeat(64); + assert!(matches!( + Cartridge::verified(&rom, &wrong), + Err(ImageError::RomDigest { .. }) + )); + } +} diff --git a/services/flysim/crates/flybrain-gb/src/lib.rs b/services/flysim/crates/flybrain-gb/src/lib.rs index 15fec61..d950de3 100644 --- a/services/flysim/crates/flybrain-gb/src/lib.rs +++ b/services/flysim/crates/flybrain-gb/src/lib.rs @@ -20,6 +20,7 @@ pub mod adapter; pub mod compatibility; pub mod emulator; mod ffi; +pub mod image; pub mod macros; mod ordered; pub mod platformer; @@ -32,6 +33,10 @@ pub use adapter::{ adapter_for, adapter_for_with_rom_pin, }; pub use compatibility::Compatibility; +pub use image::{ + CAPTURED, Cartridge, ImageError, ImageReader, MEMORY_IMAGE_CONTENT_TYPE, MEMORY_IMAGE_LEN, + MemoryImage, NOT_CAPTURED, captured, +}; pub use emulator::{ DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator, FRAMEBUFFER_LEN, GbError, SCREEN_HEIGHT, SCREEN_WIDTH, buttons, diff --git a/services/flysim/crates/flybrain-gb/tests/rom_memory_image.rs b/services/flysim/crates/flybrain-gb/tests/rom_memory_image.rs new file mode 100644 index 0000000..575568a --- /dev/null +++ b/services/flysim/crates/flybrain-gb/tests/rom_memory_image.rs @@ -0,0 +1,303 @@ +//! The shim's one bulk read, on the real cartridge (MEM-01, `legacy-gameboy-v1` section 8). +//! +//! Gated on `FLY_ROM` like every ROM test here; skips cleanly without it: +//! +//! ```sh +//! . the operator's rom env script # or FLY_ROM=... alone +//! cargo test --release -p flybrain-gb --test rom_memory_image -- --nocapture +//! ``` +//! +//! What section 8 asks the implementing slice to prove, at every boundary of a run that goes from +//! power-on through the intro, the title and the naming screens into the bedroom: +//! +//! 1. **Read-only.** The emulator's exported state is byte-identical before and after the read. +//! 2. **Equal to the single reads.** Every captured byte equals the `fly_gb_read_mem` call for +//! its address and what the per-frame cached read (the one every task and executor use) +//! returns; every uncaptured one is `$FF`. +//! 3. **Nothing moves downstream.** Two emulators in lockstep, one read in bulk at every boundary +//! and one never, produce the same framebuffers, audio and states frame for frame. +//! 4. **Why the register windows are out.** Reading them one byte at a time, as a full image +//! would, does move the exported state (binjgb's lazy PPU/timer/serial catch-up), which is +//! the amendment of 2026-09-29 to section 8. + +use flybrain_gb::adapter::MemoryReader; +use flybrain_gb::{ + CAPTURED, Cartridge, DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator, ImageReader, + MEMORY_IMAGE_LEN, MemoryImage, NOT_CAPTURED, buttons, captured, +}; + +fn rom() -> Option> { + let path = std::env::var_os("FLY_ROM")?; + match std::fs::read(&path) { + Ok(bytes) => Some(bytes), + Err(error) => panic!("FLY_ROM is set to {path:?} but could not be read: {error}"), + } +} + +fn boot(rom: &[u8]) -> Emulator { + Emulator::new(rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES) + .expect("binjgb should accept the ROM") +} + +/// A pad that gets from power-on into the game and walks: A through the intro and the naming +/// screens (a pulse every sixteen frames), then a slow rotation of directions with A between. +fn pad(frame: u32) -> u8 { + if frame < 3_000 { + if frame % 16 < 2 { buttons::A } else { buttons::NONE } + } else { + match (frame / 24) % 6 { + 0 => buttons::DOWN, + 1 => buttons::RIGHT, + 2 => buttons::UP, + 3 => buttons::A, + 4 => buttons::LEFT, + _ => buttons::START, + } + } +} + +const FRAMES: u32 = 4_200; + +#[test] +fn the_bulk_read_is_read_only_and_equals_the_single_reads() { + let Some(rom) = rom() else { + eprintln!("skipped: FLY_ROM is not set"); + return; + }; + let mut gb = boot(&rom); + let mut image = MemoryImage::zeroed(); + let mut checked = 0u32; + for frame in 0..FRAMES { + gb.set_buttons(pad(frame)); + gb.run_frame().expect("a frame"); + let _ = gb.take_audio_u8(); + + let before = gb.export_state().expect("state"); + gb.read_memory_image_into(&mut image); + let after = gb.export_state().expect("state"); + assert!(before == after, "frame {frame}: the bulk read moved the emulator's state"); + + // Every byte, every 7th frame (a full sweep is 65,536 FFI calls); the WRAM/HRAM windows + // the macros read, every frame. + let full = frame % 7 == 0; + for address in 0..=u16::MAX { + let wanted = full || (0xc000..0xe000).contains(&address) || address >= 0xff80; + if !wanted { + continue; + } + if !captured(address) { + assert_eq!(image.byte(address), NOT_CAPTURED, "frame {frame}: {address:#06x}"); + continue; + } + assert_eq!( + image.byte(address), + gb.read_uncached(address), + "frame {frame}: {address:#06x} differs from the single read" + ); + assert_eq!( + image.byte(address), + gb.read_wram(address), + "frame {frame}: {address:#06x} differs from the cached read" + ); + } + if full { + checked += 1; + } + // The single reads above moved nothing either. + assert!(after == gb.export_state().expect("state"), "frame {frame}: the single reads moved it"); + } + assert!(checked > 500, "{checked} full sweeps"); +} + +#[test] +fn reading_in_bulk_every_frame_changes_nothing_downstream() { + let Some(rom) = rom() else { + eprintln!("skipped: FLY_ROM is not set"); + return; + }; + let mut read = boot(&rom); + let mut plain = boot(&rom); + let mut image = MemoryImage::zeroed(); + for frame in 0..FRAMES { + read.read_memory_image_into(&mut image); + for gb in [&mut read, &mut plain] { + gb.set_buttons(pad(frame)); + gb.run_frame().expect("a frame"); + } + assert_eq!(read.take_audio_u8(), plain.take_audio_u8(), "frame {frame}: audio"); + assert!(read.framebuffer() == plain.framebuffer(), "frame {frame}: framebuffer"); + assert_eq!(read.ticks(), plain.ticks(), "frame {frame}: ticks"); + if frame % 50 == 0 { + assert!( + read.export_state().unwrap() == plain.export_state().unwrap(), + "frame {frame}: state" + ); + } + } + assert!(read.export_state().unwrap() == plain.export_state().unwrap()); +} + +#[test] +fn an_image_reader_answers_what_the_emulator_answers() { + let Some(rom) = rom() else { + eprintln!("skipped: FLY_ROM is not set"); + return; + }; + let mut gb = boot(&rom); + let cartridge = Cartridge::verified(&rom, &gb.rom_sha256()).expect("the emulator's own ROM"); + assert_eq!(cartridge.sha256_hex(), gb.cartridge().sha256_hex()); + for frame in 0..3_200 { + gb.set_buttons(pad(frame)); + gb.run_frame().expect("a frame"); + } + let image = gb.read_memory_image(); + assert_eq!(image.as_bytes().len(), MEMORY_IMAGE_LEN); + let mut reader = ImageReader::new(&image, &cartridge); + for &(low, high) in &CAPTURED { + for address in low..=high { + assert_eq!( + reader.read8(address), + MemoryReader::read8(&mut gb, address), + "{address:#06x}" + ); + } + } + // Every bank the cartridge has, and one past it. + let banks = u8::try_from(rom.len().div_ceil(0x4000)).unwrap_or(u8::MAX); + for bank in 0..=banks { + for address in (0u16..0x8000).step_by(97).chain([0x3fff, 0x4000, 0x7fff, 0x8000, 0xc000]) { + assert_eq!( + reader.read_rom(bank, address), + MemoryReader::read_rom(&mut gb, bank, address), + "bank {bank} {address:#06x}" + ); + } + } +} + +/// The amendment's reason, measured: over the same run, reading any of the three register windows +/// one byte at a time -- which is what a full 64 KiB image through `fly_gb_read_mem` would do -- +/// changes the exported state on some boundary, and reading the captured ranges never does. +#[test] +fn the_register_windows_are_the_reads_that_move_the_state() { + let Some(rom) = rom() else { + eprintln!("skipped: FLY_ROM is not set"); + return; + }; + let mut gb = boot(&rom); + let windows: [(&str, u16, u16); 3] = + [("vram", 0x8000, 0x9fff), ("oam", 0xfe00, 0xfe9f), ("io", 0xff00, 0xff7f)]; + let mut moved = [0u32; 3]; + let mut sampled = 0u32; + for frame in 0..FRAMES { + gb.set_buttons(pad(frame)); + gb.run_frame().expect("a frame"); + if frame % 40 != 0 { + continue; + } + sampled += 1; + for (index, &(_, low, high)) in windows.iter().enumerate() { + // A throwaway copy of this boundary, so each window is measured from the same state. + let state = gb.export_state().expect("state"); + let mut probe = boot(&rom); + probe.import_state(&state).expect("same build"); + for address in low..=high { + let _ = probe.read_uncached(address); + } + if probe.export_state().expect("state") != state { + moved[index] += 1; + } + } + } + eprintln!( + "{sampled} boundaries: {}", + windows + .iter() + .zip(moved) + .map(|((name, ..), n)| format!("{name} moved the state on {n}")) + .collect::>() + .join(", ") + ); + // The PPU's and the timer's catch-ups run on almost every boundary. + assert!(moved[0] > 0, "reading VRAM never moved the state"); + assert!(moved[2] > 0, "reading I/O never moved the state"); +} + +/// The per-boundary cost (MEM-01 deliverable 4), printed for the report rather than asserted: +/// it is wall time on whatever box runs it. What it does assert is only that one read fits +/// comfortably inside a frame (16.74 ms), which a loaded box also meets. +/// +/// - `bulk`: the shim's read into an owned image, which is what the environment pays per boundary; +/// - `copy`: cloning an image (64 KiB `memcpy`), what handing it to a store that copies costs; +/// - `digest`: SHA-256 of the image, which the live artifact may omit; +/// - `single`: the same captured addresses through 57,120 single FFI reads, for comparison. +#[test] +fn the_bulk_read_costs_a_fraction_of_a_frame() { + use std::time::{Duration, Instant}; + let Some(rom) = rom() else { + eprintln!("skipped: FLY_ROM is not set"); + return; + }; + let mut gb = boot(&rom); + for frame in 0..3_200 { + gb.set_buttons(pad(frame)); + gb.run_frame().expect("a frame"); + } + const ROUNDS: usize = 2_000; + let mut bulk = Vec::with_capacity(ROUNDS); + let mut copy = Vec::with_capacity(ROUNDS); + let mut digest = Vec::with_capacity(ROUNDS); + let mut single = Vec::with_capacity(ROUNDS / 20); + let mut image = MemoryImage::zeroed(); + let mut sink = 0u64; + for round in 0..ROUNDS { + gb.set_buttons(pad(3_200 + round as u32)); + gb.run_frame().expect("a frame"); + let start = Instant::now(); + gb.read_memory_image_into(&mut image); + bulk.push(start.elapsed()); + let start = Instant::now(); + let copied = image.clone(); + copy.push(start.elapsed()); + sink += u64::from(copied.byte(0xd35e)); + let start = Instant::now(); + sink += image.sha256_hex().len() as u64; + digest.push(start.elapsed()); + if round % 20 == 0 { + let start = Instant::now(); + for &(low, high) in &CAPTURED { + for address in low..=high { + sink += u64::from(gb.read_uncached(address)); + } + } + single.push(start.elapsed()); + } + } + let stats = |name: &str, samples: &mut Vec| { + samples.sort(); + let at = |q: f64| samples[((samples.len() - 1) as f64 * q) as usize].as_secs_f64() * 1e6; + let mean = samples.iter().sum::().as_secs_f64() * 1e6 / samples.len() as f64; + eprintln!( + "{name:>7}: mean {mean:8.1} us median {:8.1} us p99 {:8.1} us ({} samples)", + at(0.5), + at(0.99), + samples.len() + ); + at(0.5) + }; + let median = stats("bulk", &mut bulk); + stats("copy", &mut copy); + stats("digest", &mut digest); + stats("single", &mut single); + let fps = 59.7275; + eprintln!( + "image {} B/boundary = {:.3} MB/s at {fps} fps; bulk median {:.2}% of a {:.2} ms frame; \ + bulk read throughput {:.0} MB/s (sink {sink})", + MEMORY_IMAGE_LEN, + MEMORY_IMAGE_LEN as f64 * fps / 1e6, + median / 1e3 / (1e3 / fps) * 100.0, + 1e3 / fps, + MEMORY_IMAGE_LEN as f64 / median, + ); + assert!(median < 8_000.0, "a bulk read took {median} us at the median"); +}