// SPDX-License-Identifier: MIT //! A minimal SNES-shaped host for CPU test ROMs: enough machine to run them, no //! PPU (`harness.py`). //! //! Not a SNES (that is snes-python's job): a LoROM or HiROM cartridge, 128 KiB //! of WRAM at $7E-$7F mirrored at $0000-$1FFF of banks $00-$3F/$80-$BF, and the //! few registers CPU test ROMs touch on their way to drawing a verdict (the //! reference's docs/validation.md, "The minimal harness"): //! //! - the VRAM port ($2115-$2119) into a 64 KiB array, so the text a ROM prints //! can be read back with [`Machine::screen`]; //! - the WRAM port ($2180-$2183), the multiplier and divider ($4202-$4206, //! results at once), and general-purpose DMA ($420B, $43x0-$43x6), done //! instantly between two cycles; //! - a "frame" of `frame_cycles` CPU cycles whose last eighth is vblank: //! $4210 bit 7 sets as it starts and clears when read, $4212 bit 7 is high //! through it, and an NMI is raised there when $4200 bit 7 enables it; //! - the APU ports ($2140-$2143) read $AA, $BB, 0, 0 until written, then echo //! what was written, which satisfies the IPL handshake's wait loops; //! - open bus elsewhere: the last value on the data bus. //! //! Timing is the CPU's cycle count only: every callback is one cycle whatever //! the region's speed, no DRAM refresh, no DMA cycles. Only the order of events //! matters to the ROMs this runs. //! //! Differences forced by Rust: //! //! - The reference's `Harness` owns the CPU and is its bus; a subclass (rung 3's //! `TextLog`, rung 4's `Replay`) overrides `_tick`, `read_byte`, //! `write_byte`, `idle`, `io_read`, `io_write` and `_dma`. Here the bus is //! [`Machine`], generic over [`Hooks`], whose default methods are the //! reference's (`base_*`); a subclass is a `Hooks` type that overrides the //! methods its Python class overrides, and calls `base_*` where the Python //! calls `super()`. The machine dispatches through the hooks wherever the //! Python calls a method on `self`, so an override is seen where it would be. //! - `_tick` reaches the CPU's NMI input through the frame the callback gets. //! - `load_rom` reads `.sfc`/`.smc` files only; the reference's `.zip` and //! `.7z` extraction (a convenience for its command line) is not transcribed. //! - `run`'s `step` argument (a debug session's step) is [`Harness::run_with`]. use sixfiveohtwo::frame::Frame; use crate::core::{Bus, Signals, W65C816}; /// Bytes moved to B-bus addresses $21xx + offset, per DMA transfer mode ($43x0 bits 0-2). pub const DMA_PATTERNS: [&[u8]; 8] = [ &[0], &[0, 1], &[0, 0], &[0, 0, 1, 1], &[0, 1, 2, 3], &[0, 1, 0, 1], &[0, 0], &[0, 0, 1, 1], ]; pub const VRAM_STEPS: [u32; 4] = [1, 32, 128, 128]; pub const WRAM_SIZE: u32 = 0x20000; /// Jump-to-self opcodes: BRA, JMP a, JML al. A ROM that has finished spins on one. pub const SPIN_OPCODES: [u8; 3] = [0x80, 0x4C, 0x5C]; /// Why [`Harness::run`] stopped, and when. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct RunResult { pub reason: &'static str, // "spin", "stopped", "condition" or "cycles" pub cycles: u64, pub pc: u32, // 24-bit, PBR:PC } pub fn lorom_offset(bank: u32, offset: u32) -> Option { if offset >= 0x8000 || (0x40..0x7E).contains(&(bank & 0x7F)) { return Some(((bank & 0x7F) << 15 | (offset & 0x7FFF)) as usize); } None } pub fn hirom_offset(bank: u32, offset: u32) -> Option { // Banks $C0-$FF are ROM throughout; only $7E-$7F are WRAM, not $FE-$FF. if offset >= 0x8000 || (0x40..0x7E).contains(&(bank & 0x7F)) || bank >= 0xFE { return Some(((bank & 0x3F) << 16 | offset) as usize); } None } /// A cartridge image from `.sfc`/`.smc`, without the 512-byte copier header /// some dumps carry. pub fn load_rom(path: &std::path::Path) -> std::io::Result> { let data = std::fs::read(path)?; Ok(if data.len() % 0x8000 == 512 { data[512..].to_vec() } else { data }) } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Mapping { LoRom, HiRom, } /// LoROM or HiROM, by which header's checksum complement adds up. pub fn detect_mapping(rom: &[u8]) -> Mapping { for (name, base) in [(Mapping::LoRom, 0x7FC0), (Mapping::HiRom, 0xFFC0)] { if rom.len() >= base + 0x20 { let checksum = rom[base + 0x1E] as u16 | (rom[base + 0x1F] as u16) << 8; let complement = rom[base + 0x1C] as u16 | (rom[base + 0x1D] as u16) << 8; if checksum ^ complement == 0xFFFF { return name; } } } Mapping::LoRom } /// The methods a subclass of the reference's `Harness` may override; each /// default is the `Harness` method itself. pub trait Hooks: Sized { fn tick(machine: &mut Machine, frame: &mut Frame) { machine.base_tick(frame); } fn read_byte( machine: &mut Machine, address: u32, frame: &mut Frame, _signals: Signals, ) -> u8 { machine.base_read_byte(address, frame) } fn write_byte( machine: &mut Machine, address: u32, value: u8, frame: &mut Frame, _signals: Signals, ) { machine.base_write_byte(address, value, frame); } fn idle(machine: &mut Machine, _address: u32, frame: &mut Frame, _signals: Signals) { Self::tick(machine, frame); } fn io_read(machine: &mut Machine, offset: u32) -> u8 { machine.base_io_read(offset) } fn io_write(machine: &mut Machine, offset: u32, value: u8) { machine.base_io_write(offset, value); } fn dma(machine: &mut Machine, channel: usize) { machine.base_dma(channel); } } /// The plain harness: no overrides. #[derive(Clone, Copy, Debug, Default)] pub struct Plain; impl Hooks for Plain {} /// The harness's machine: WRAM, VRAM, the cartridge and the registers above. pub struct Machine { pub rom: Vec, pub mapping: Mapping, pub wram: Vec, pub vram: Vec, pub frame_cycles: u64, pub cycles: u64, pub open_bus: u8, pub vram_address: u32, pub vram_control: u8, pub wram_address: u32, pub nmi_enable: u8, pub nmi_flag: bool, pub apu_ports: [u8; 4], pub math: [u8; 8], // $4202-$4206 written, results at $4214-$4217 pub dma: [u8; 0x80], // $4300-$437F /// The subclass's own state. pub hooks: H, } impl Bus for Machine { fn read(&mut self, address: u32, frame: &mut Frame, signals: Signals) -> u8 { H::read_byte(self, address, frame, signals) } fn write(&mut self, address: u32, value: u8, frame: &mut Frame, signals: Signals) { H::write_byte(self, address, value, frame, signals); } fn idle(&mut self, address: u32, frame: &mut Frame, signals: Signals) { H::idle(self, address, frame, signals); } } impl Machine { pub fn new(rom: &[u8], mapping: Option, frame_cycles: u64, hooks: H) -> Self { Machine { rom: rom.to_vec(), mapping: mapping.unwrap_or_else(|| detect_mapping(rom)), wram: vec![0; WRAM_SIZE as usize], vram: vec![0; 0x10000], frame_cycles, cycles: 0, open_bus: 0, vram_address: 0, vram_control: 0, wram_address: 0, nmi_enable: 0, nmi_flag: false, apu_ports: [0xAA, 0xBB, 0, 0], math: [0; 8], dma: [0; 0x80], hooks, } } fn rom_offset(&self, bank: u32, offset: u32) -> Option { match self.mapping { Mapping::LoRom => lorom_offset(bank, offset), Mapping::HiRom => hirom_offset(bank, offset), } } // -- the bus --------------------------------------------------------- pub fn base_tick(&mut self, frame: &mut Frame) { self.cycles += 1; let position = self.cycles % self.frame_cycles; if position == self.frame_cycles - self.frame_cycles / 8 { self.nmi_flag = true; if self.nmi_enable & 0x80 != 0 { frame.request_non_maskable_interrupt(); } } } pub fn in_vblank(&self) -> bool { self.cycles % self.frame_cycles >= self.frame_cycles - self.frame_cycles / 8 } pub fn base_read_byte(&mut self, address: u32, frame: &mut Frame) -> u8 { H::tick(self, frame); let value = self.peek(address); self.open_bus = value; value } pub fn base_write_byte(&mut self, address: u32, value: u8, frame: &mut Frame) { H::tick(self, frame); self.open_bus = value; self.poke(address, value); } /// Read `address` as the bus would, without a cycle (DMA's A-bus side). pub fn peek(&mut self, address: u32) -> u8 { let (bank, offset) = (address >> 16, address & 0xFFFF); if bank & 0xFE == 0x7E { return self.wram[((bank & 1) << 16 | offset) as usize]; } if bank & 0x7F < 0x40 && offset < 0x8000 { if offset < 0x2000 { return self.wram[offset as usize]; } return H::io_read(self, offset); } if let Some(rom) = self.rom_offset(bank, offset) { if !self.rom.is_empty() { return self.rom[rom % self.rom.len()]; } } self.open_bus } /// Read `address` with no side effects at all, for a debugger: WRAM and /// ROM as [`Machine::peek`] reads them; I/O registers as the open bus, /// since reading one can change it ($4210, $2180). pub fn inspect(&mut self, address: u32) -> u8 { let (bank, offset) = (address >> 16, address & 0xFFFF); if bank & 0x7F < 0x40 && (0x2000..0x8000).contains(&offset) { return self.open_bus; } self.peek(address) } pub fn poke(&mut self, address: u32, value: u8) { let (bank, offset) = (address >> 16, address & 0xFFFF); if bank & 0xFE == 0x7E { self.wram[((bank & 1) << 16 | offset) as usize] = value; } else if bank & 0x7F < 0x40 && offset < 0x8000 { if offset < 0x2000 { self.wram[offset as usize] = value; } else { H::io_write(self, offset, value); } } } // -- registers ------------------------------------------------------- pub fn base_io_read(&mut self, offset: u32) -> u8 { if (0x2140..0x2180).contains(&offset) { return self.apu_ports[(offset & 3) as usize]; } if offset == 0x2180 { let value = self.wram[self.wram_address as usize]; self.wram_address = (self.wram_address + 1) % WRAM_SIZE; return value; } if offset == 0x4210 { let value = if self.nmi_flag { 0x82 } else { 0x02 }; // bit 7 NMI flag, version 2 self.nmi_flag = false; return value | self.open_bus & 0x70; } if offset == 0x4211 { return self.open_bus & 0x7F; } if offset == 0x4212 { return (if self.in_vblank() { 0x80 } else { 0 }) | self.open_bus & 0x3E; } if (0x4214..=0x4217).contains(&offset) { return self.math[(offset - 0x4214 + 4) as usize]; } if (0x4218..=0x421F).contains(&offset) { return 0; // no buttons held } if (0x4300..0x4380).contains(&offset) { return self.dma[(offset - 0x4300) as usize]; } self.open_bus } pub fn base_io_write(&mut self, offset: u32, value: u8) { if offset == 0x2115 { self.vram_control = value; } else if offset == 0x2116 { self.vram_address = self.vram_address & 0xFF00 | value as u32; } else if offset == 0x2117 { self.vram_address = (value as u32) << 8 | self.vram_address & 0xFF; } else if offset == 0x2118 || offset == 0x2119 { let high = offset == 0x2119; self.vram[((self.vram_address << 1 | high as u32) & 0xFFFF) as usize] = value; if high == (self.vram_control & 0x80 != 0) { let step = VRAM_STEPS[(self.vram_control & 3) as usize]; self.vram_address = (self.vram_address + step) & 0xFFFF; } } else if (0x2140..0x2180).contains(&offset) { self.apu_ports[(offset & 3) as usize] = value; } else if offset == 0x2180 { self.wram[self.wram_address as usize] = value; self.wram_address = (self.wram_address + 1) % WRAM_SIZE; } else if (0x2181..=0x2183).contains(&offset) { let shift = (offset - 0x2181) * 8; let address = self.wram_address & !(0xFF << shift) | (value as u32) << shift; self.wram_address = address % WRAM_SIZE; } else if offset == 0x4200 { self.nmi_enable = value; } else if (0x4202..=0x4206).contains(&offset) { self.math[(offset - 0x4202) as usize] = value; self.arithmetic(offset); } else if offset == 0x420B { for channel in 0..8 { if value >> channel & 1 != 0 { H::dma(self, channel); } } } else if (0x4300..0x4380).contains(&offset) { self.dma[(offset - 0x4300) as usize] = value; } } /// $4203 starts an 8x8 multiply, $4206 a 16/8 divide; both finish at once. fn arithmetic(&mut self, offset: u32) { let [multiplicand, multiplier, dividend_low, dividend_high, divisor, ..] = self.math; if offset == 0x4203 { let product = multiplicand as u32 * multiplier as u32; self.math[4..8].copy_from_slice(&[ dividend_low, dividend_high, (product & 0xFF) as u8, (product >> 8) as u8, ]); } else if offset == 0x4206 { let dividend = dividend_low as u32 | (dividend_high as u32) << 8; let (quotient, remainder) = if divisor != 0 { (dividend / divisor as u32, dividend % divisor as u32) } else { (0xFFFF, dividend) }; self.math[4..8].copy_from_slice(&[ (quotient & 0xFF) as u8, (quotient >> 8) as u8, (remainder & 0xFF) as u8, (remainder >> 8) as u8, ]); } } /// One general-purpose DMA channel, all at once (A-bus to B-bus or back). pub fn base_dma(&mut self, channel: usize) { let mut registers = [0u8; 16]; registers.copy_from_slice(&self.dma[channel * 16..channel * 16 + 16]); let (control, b_address) = (registers[0], registers[1] as u32); let mut a_offset = registers[2] as u32 | (registers[3] as u32) << 8; let a_bank = registers[4] as u32; let mut count = registers[5] as u32 | (registers[6] as u32) << 8; if count == 0 { count = 0x10000; } let pattern = DMA_PATTERNS[(control & 7) as usize]; let a_step: i32 = if control & 0x08 != 0 { 0 } else if control & 0x10 != 0 { -1 } else { 1 }; for index in 0..count as usize { let b_target = 0x2100 | (b_address + pattern[index % pattern.len()] as u32) & 0xFF; let a_target = a_bank << 16 | a_offset; if control & 0x80 != 0 { let value = H::io_read(self, b_target); self.poke(a_target, value); } else { let value = self.peek(a_target); H::io_write(self, b_target, value); } a_offset = a_offset.wrapping_add(a_step as u32) & 0xFFFF; } let base = channel * 16; self.dma[base + 2] = (a_offset & 0xFF) as u8; self.dma[base + 3] = (a_offset >> 8) as u8; self.dma[base + 5] = 0; self.dma[base + 6] = 0; } // -- reading results ------------------------------------------------- /// The text of a 32-column tilemap at VRAM word `map_word`, one line per /// row: each entry's low byte as ASCII, anything unprintable as a space. pub fn screen(&self, map_word: usize, rows: usize) -> Vec { let mut lines = Vec::with_capacity(rows); for row in 0..rows { let base = (map_word + row * 32) * 2; let text: String = (0..32) .map(|column| { let code = self.vram.get(base + column * 2).copied().unwrap_or(0); if (0x20..0x7F).contains(&code) { code as char } else { ' ' } }) .collect(); lines.push(text.trim_end().to_string()); } lines } } /// Run a ROM on a W65C816 with WRAM, a cartridge and the registers above /// (`Harness`). /// /// `cpu` is the core, reset requested and ready to [`Harness::run`]; /// `cpu.bus` is the [`Machine`], whose `wram` and `vram` the ROM's results /// can be read from. pub struct Harness { pub cpu: W65C816>, } impl Harness { pub fn new(rom: &[u8]) -> Self { Harness::with_hooks(rom, None, 30_000, Plain) } } impl Harness { pub fn with_hooks(rom: &[u8], mapping: Option, frame_cycles: u64, hooks: H) -> Self { let mut cpu = W65C816::new(Machine::new(rom, mapping, frame_cycles, hooks)); cpu.frame.request_reset(); Harness { cpu } } pub fn machine(&mut self) -> &mut Machine { &mut self.cpu.bus } /// Step until the ROM spins on a jump to itself, STP, `until(self)` /// (checked after each instruction) or `max_cycles` more cycles. pub fn run( &mut self, max_cycles: u64, until: Option<&mut dyn FnMut(&mut Self) -> bool>, ) -> RunResult { self.run_with(max_cycles, until, &mut |cpu| { cpu.step(); }) } /// [`Harness::run`] with `step` in place of `cpu.step` (the reference's /// `run(..., step=...)`: a debug session's, to trace the run). pub fn run_with( &mut self, max_cycles: u64, mut until: Option<&mut dyn FnMut(&mut Self) -> bool>, step: &mut dyn FnMut(&mut W65C816>), ) -> RunResult { let limit = self.cpu.bus.cycles + max_cycles; let mut reason = "cycles"; while self.cpu.bus.cycles < limit { let before = (self.cpu.pbr as u32) << 16 | self.cpu.pc as u32; step(&mut self.cpu); if self.cpu.stopped { reason = "stopped"; break; } let after = (self.cpu.pbr as u32) << 16 | self.cpu.pc as u32; if after == before && SPIN_OPCODES.contains(&self.cpu.bus.peek(before)) { reason = "spin"; break; } if let Some(until) = until.as_mut() { if until(self) { reason = "condition"; break; } } } RunResult { reason, cycles: self.cpu.bus.cycles, pc: (self.cpu.pbr as u32) << 16 | self.cpu.pc as u32, } } }