// SPDX-License-Identifier: MIT //! The minimal harness: a host that is not a GBA, for test ROMs that need only memory. //! //! Transcribed from `arm7tdmi_python/harness.py`. It maps what jsmolka's and alyosha-tas's CPU //! tests touch (the reference's docs/handoff-brief.md "The minimal harness"): the cartridge ROM //! at `0x08000000` (mirrored through `0x0DFFFFFF`), 256 KiB at `0x02000000`, 32 KiB at //! `0x03000000`, I/O at `0x04000000` as plain RAM except DISPSTAT (`0x04000004`), whose VBlank //! bit toggles on every read so a wait for VBlank completes, palette, VRAM and OAM as RAM, and //! 64 KiB of SRAM at `0x0E000000`. Like the GBA's bus it ignores the low address bits a width //! does not use. There is no BIOS: a fetch below `0x00004000` (an SWI or any exception) stops //! the run with an error. //! //! It starts as the GBA's BIOS leaves a cartridge: System mode, ARM state, PC `0x08000000`, //! SP_sys `0x03007F00`, SP_irq `0x03007FA0`, SP_svc `0x03007FE0` (GBATEK "BIOS RAM Usage"), //! and stops when the next instruction is a branch to itself. //! //! The reference stops a run in the middle of an instruction by raising `EnteredBIOS` from the //! bus callback. Rust has no exceptions; the transcription unwinds the same way with //! `std::panic::resume_unwind` (which does not run the panic hook) and catches it in //! [`Harness::run`], so the CPU is left exactly where the reference's is. A build with //! `panic = "abort"` (such as a wasm one) cannot use the harness's BIOS stop. use std::panic::{self, AssertUnwindSafe}; use crate::core::{Bus, ARM7TDMI}; use crate::state::CPUState; pub const SYS: u32 = 0x1F; pub const SVC_BANK: usize = 2; pub const IRQ_BANK: usize = 4; pub const ARM_BRANCH_TO_SELF: u32 = 0xEAFF_FFFE; pub const THUMB_BRANCH_TO_SELF: u32 = 0xE7FE; pub const DISPSTAT: u32 = 0x0400_0004; /// kind, address, width, access, value pub type Observer = Box; fn le_u16(data: &[u8], at: usize) -> u32 { u16::from_le_bytes([data[at], data[at + 1]]) as u32 } fn le_u32(data: &[u8], at: usize) -> u32 { u32::from_le_bytes([data[at], data[at + 1], data[at + 2], data[at + 3]]) } /// `int.bit_length()`. fn bit_length(value: u64) -> u32 { 64 - value.leading_zeros() } /// The loadable segments of a 32-bit little-endian ARM ELF executable, as (physical /// address, bytes), and its entry point (bit 0 set for Thumb). The physical address is where /// a GBA image's `.data` sits in ROM before its start-up code copies it to RAM. #[allow(clippy::type_complexity)] pub fn elf_image(data: &[u8]) -> Result<(Vec<(u32, Vec)>, u32), String> { if data.len() < 52 || &data[..4] != b"\x7fELF" || data[4] != 1 || data[5] != 1 { return Err("not a 32-bit little-endian ELF file".into()); } let (machine, entry) = (le_u16(data, 18), le_u32(data, 24)); if machine != 40 { return Err(format!("ELF machine {machine} is not ARM (40)")); } let table = le_u32(data, 28) as usize; let (size, count) = (le_u16(data, 42) as usize, le_u16(data, 44) as usize); let mut segments = Vec::new(); for n in 0..count { let header = &data[table + n * size..table + (n + 1) * size]; let (kind, offset, physical, file_size) = ( le_u32(header, 0), le_u32(header, 4) as usize, le_u32(header, 12), le_u32(header, 16) as usize, ); if kind == 1 && file_size != 0 { // PT_LOAD segments.push((physical, data[offset..offset + file_size].to_vec())); } } Ok((segments, entry)) } /// The program fetched from the BIOS region: an SWI or an exception, which this host has /// no BIOS for. jsmolka's result screen divides with SWI 6 only when a test failed, so this is /// how such a failure ends; `r12` holds the result register at that point. #[derive(Clone, Debug, PartialEq, Eq)] pub struct EnteredBIOS { pub message: String, pub r12: u32, } /// Why [`Harness::run`] stopped without reaching a branch to itself. #[derive(Clone, Debug, PartialEq, Eq)] pub enum RunError { EnteredBIOS(EnteredBIOS), /// The reference's `TimeoutError`. Timeout(String), } /// The payload the bus unwinds with (the reference's raise). struct BiosAccess(String); pub struct Region { pub memory: Vec, pub mask: u32, // address bits that select a byte inside the region (its mirror) } /// The harness's memory: the reference's `Harness` less its CPU (a Rust bus cannot hold /// the CPU that calls it). pub struct HarnessBus { pub regions: Vec, /// `regions` by address bits 31:24 (the reference's dict). pub pages: [Option; 256], pub rom: usize, // the ROM's index in `regions` pub vblank: bool, pub observer: Option, pub cycles: u64, } impl HarnessBus { fn locate(&self, address: u32, width: u32) -> (Option, usize) { let region = self.pages[(address >> 24) as usize]; let address = address & !(width / 8 - 1); // the bus ignores the low bits the width does not use match region { Some(index) => (Some(index), (address & self.regions[index].mask) as usize), None => (None, 0), } } } impl Bus for HarnessBus { fn read(&mut self, address: u32, width: u32, access: u32) -> u32 { if address < 0x4000 { panic::resume_unwind(Box::new(BiosAccess(format!( "fetch or read at {address:08x}: no BIOS in the harness" )))); } if address & !3 == DISPSTAT { self.vblank = self.vblank; let io = self.pages[0x04].expect("I/O is mapped"); let memory = &mut self.regions[io].memory; memory[4] = (memory[4] & !1) | self.vblank as u8; } let (region, offset) = self.locate(address, width); let value = match region { Some(index) => { // The reference reads a slice, `memory[offset : offset + width // 8]`: a ROM // smaller than the access (the two bytes an empty image starts with) gives // only the bytes it has. let memory = &self.regions[index].memory; let mut value = 0u32; for byte in (0..(width / 8) as usize).rev() { value = value << 8 | memory.get(offset + byte).copied().unwrap_or(0) as u32; } value } None => 0, }; self.cycles += 1; if let Some(observer) = self.observer.as_mut() { observer("read", address, width, access, value); } value } fn write(&mut self, address: u32, width: u32, value: u32, access: u32) { let (region, offset) = self.locate(address, width); if let Some(index) = region { if index != self.rom { let memory = &mut self.regions[index].memory; for byte in 0..(width / 8) as usize { memory[offset + byte] = (value >> (8 * byte)) as u8; } } } self.cycles += 1; if let Some(observer) = self.observer.as_mut() { observer("write", address, width, access, value); } } fn idle(&mut self, address: u32, _coprocessor_cycle: bool) { self.cycles += 1; if let Some(observer) = self.observer.as_mut() { observer("internal", address, 0, 0, 0); } } } pub struct Harness { pub cpu: ARM7TDMI, } impl Harness { pub fn new(rom: &[u8], observer: Option) -> Self { let size = 1usize << bit_length((rom.len() as u64).saturating_sub(1).max(1)); let mut image = rom.to_vec(); image.resize(size, 0); let mut regions = Vec::new(); let mut pages = [None; 256]; for (page, length, mask) in [ (0x02, 0x40000, 0x3FFFF), (0x03, 0x8000, 0x7FFF), (0x04, 0x400, 0x3FF), (0x05, 0x400, 0x3FF), (0x06, 0x20000, 0x1FFFF), (0x07, 0x400, 0x3FF), (0x0E, 0x10000, 0xFFFF), ] { pages[page] = Some(regions.len()); regions.push(Region { memory: vec![0; length], mask, }); } let rom_index = regions.len(); regions.push(Region { memory: image, mask: (size - 1) as u32, }); for page in pages.iter_mut().take(0x0E).skip(0x08) { *page = Some(rom_index); // one Region, so a resize reaches every mirror } let bus = HarnessBus { regions, pages, rom: rom_index, vblank: false, observer, cycles: 0, }; let mut cpu = ARM7TDMI::new(bus); let mut banks = [[0u32; 7]; 6]; banks[SVC_BANK][5] = 0x0300_7FE0; banks[IRQ_BANK][5] = 0x0300_7FA0; let mut registers = [0u32; 16]; registers[13] = 0x0300_7F00; cpu.restore_state(&CPUState { registers, banks, cpsr: SYS, ..CPUState::default() }); let mut harness = Harness { cpu }; harness.guarded(|cpu| cpu.start_at(0x0800_0000)).ok(); harness } /// Run `body` on the CPU, turning the bus's BIOS stop back into a value (the reference's /// `except EnteredBIOS`). fn guarded(&mut self, body: impl FnOnce(&mut ARM7TDMI)) -> Result<(), String> { let cpu = &mut self.cpu; match panic::catch_unwind(AssertUnwindSafe(|| body(cpu))) { Ok(()) => Ok(()), Err(payload) => match payload.downcast::() { Ok(access) => { // The reference's step() ends the LDM^ glitch in a `finally`. self.cpu.end_glitch(); Err(access.0) } Err(other) => panic::resume_unwind(other), }, } } pub fn cycles(&self) -> u64 { self.cpu.bus.cycles } /// The byte at `address` without a bus cycle or any side effect (DISPSTAT does not /// toggle): for disassembly and memory views. Unmapped addresses read 0. pub fn peek(&self, address: u32) -> u8 { let bus = &self.cpu.bus; match bus.pages[((address >> 24) & 0xFF) as usize] { Some(index) => { let region = &bus.regions[index]; region.memory[(address & region.mask) as usize] } None => 0, } } /// Copy `data` into memory at `address`, cartridge ROM included (it grows, to the /// next power of two, if the image runs past its end); no bus cycles. pub fn load(&mut self, address: u32, data: &[u8]) -> Result<(), String> { let bus = &mut self.cpu.bus; if (0x08..0x0E).contains(&(address >> 24)) { let end = (address & 0x01FF_FFFF) as usize + data.len(); let rom = &mut bus.regions[bus.rom]; if end > rom.memory.len() { let size = 1usize << bit_length((end as u64 - 1).max(1)); rom.memory.resize(size, 0); rom.mask = (size - 1) as u32; // every ROM page shares this Region } } for (offset, &byte) in data.iter().enumerate() { let target = address.wrapping_add(offset as u32); match bus.pages[(target >> 24) as usize] { Some(index) => { let region = &mut bus.regions[index]; let at = (target & region.mask) as usize; region.memory[at] = byte; } None => return Err(format!("nothing is mapped at {target:08X}")), } } Ok(()) } /// Start running at `address`, in Thumb state if `thumb` (two refill fetches). pub fn start(&mut self, address: u32, thumb: bool) -> Result<(), String> { let mut state = self.cpu.capture_state(); state.cpsr = (state.cpsr & !0x20) | if thumb { 0x20 } else { 0 }; self.cpu.restore_state(&state); self.guarded(|cpu| cpu.start_at(address)) } // ------------------------------------------------------------------ running pub fn at_branch_to_self(&self) -> bool { let cpu = &self.cpu; if cpu.thumb() { return cpu.pipeline[0] == THUMB_BRANCH_TO_SELF; } cpu.pipeline[0] == ARM_BRANCH_TO_SELF } /// One `step()` (its cycles), with the BIOS stop as an error carrying R12 (the /// reference's `run` loop body, for hosts that step themselves). pub fn step(&mut self) -> Result { let mut cycles = 0; self.guarded(|cpu| { cycles = cpu.step(); }) .map(|()| cycles) .map_err(|message| EnteredBIOS { message, r12: self.cpu.r[12], }) } /// Run until a branch to itself; return R12, the jsmolka/alyosha-tas result register /// (0 = all passed, otherwise the first failing test's number). pub fn run(&mut self, max_cycles: u64) -> Result { while !self.at_branch_to_self() { if self.cycles() >= max_cycles { return Err(RunError::Timeout(format!( "no branch to itself within {} cycles", thousands(max_cycles) ))); } self.step().map_err(RunError::EnteredBIOS)?; } Ok(self.cpu.r[12]) } } /// `f"{n:,}"`. pub fn thousands(n: u64) -> String { let digits = n.to_string(); let mut out = String::new(); for (index, ch) in digits.chars().enumerate() { if index != 0 && (digits.len() - index) % 3 == 0 { out.push(','); } out.push(ch); } out } #[cfg(test)] mod tests { use super::*; #[test] fn branch_to_self_stops_and_bios_is_an_error() { let mut harness = Harness::new(&0xEAFF_FFFEu32.to_le_bytes(), None); assert_eq!(harness.run(50_000_000), Ok(0)); assert_eq!(harness.cycles(), 2); let mut swi = Harness::new(&0xEF00_0000u32.to_le_bytes(), None); // SWI 0 assert!(matches!(swi.run(50_000_000), Err(RunError::EnteredBIOS(_)))); } #[test] fn thousands_separators() { assert_eq!(thousands(0), "0"); assert_eq!(thousands(999), "999"); assert_eq!(thousands(1000), "1,000"); assert_eq!(thousands(50_000_000), "50,000,000"); } }