// SPDX-License-Identifier: MIT //! A whole console: SALLY (6502-rust's Mos6502) on the [`Board`], with a cartridge, //! started through the BIOS or directly. //! //! **SALLY** is Atari's C014806, an NMOS 6502 with a HALT pin; HALT is board //! logic around the bus callbacks (DOC: [MT84] 2.1, C1; docs/timing.md "SALLY's //! HALT"), so the type adds nothing to the core but its name. //! //! **Starting.** The certified path is the BIOS, found by hash //! ([`crate::machine`]); the board then starts exactly as the console does, with //! INPTCTRL at 0 (DOC: [SG]). The other path, `start = "direct"`, is labelled "BIOS //! skipped": INPTCTRL is preset to $07 (locked, MARIA on, cartridge mapped) and //! HALT enabled, the CPU runs the cartridge's reset vector, and RAM, the TIA and //! RIOT state and the position on the frame differ from a real start //! (docs/start-here.md "Two machines in one case"; Open decision 7). The preset is //! a labelled convenience, not a hardware value. //! //! Rust-forced differences (a7800-python `system.py` at d6b220d): `Sally` is a type //! alias (`Mos6502`), not a subclass; the CPU owns the board (its bus), so //! `system.board` is [`System::board`] / [`System::board_mut`]; `mode_log` is shared with //! the board's `on_inptctrl` closure (`Rc>`); `from_rom` takes a //! [`Source`] and [`LoadOptions`]; constructors return `Result` where Python raises; //! `run_until`'s `done` is handed the system. use std::cell::RefCell; use std::io::Read; use std::rc::Rc; use sha2::{Digest, Sha256}; use sixfiveohtwo::Mos6502; use crate::board::{Board, EXT, LOCK, MEN}; use crate::cartridge::connector::Cartridge; use crate::cartridge::description::{hex, CartDescription}; use crate::cartridge::formats::{self, LoadOptions, Source}; use crate::controllers::ProLine; use crate::machine::{bios_by_sha256, bios_place, Machine}; use crate::romsets::mame_rompath; /// Atari C014806: the NMOS 6502 with HALT (the board holds its clock). pub type Sally = Mos6502; /// The machine's first BIOS image found in place below `$MAME_ROMPATH`, by hash /// (None when the variable is unset or no image matches). pub fn find_bios(machine: &Machine) -> Option> { let sets = mame_rompath().ok()?; for bios in machine.bios { let Some((archive, member)) = bios_place(bios.sha256) else { continue; }; let path = sets.join(archive); if !path.exists() { continue; } let file = std::fs::File::open(&path).ok()?; let mut zip = zip::ZipArchive::new(file).ok()?; let mut data = Vec::new(); zip.by_name(member).ok()?.read_to_end(&mut data).ok()?; if hex(&Sha256::digest(&data)) == bios.sha256 { return Some(data); } } None } /// The BIOS row's name for `image`, or an error if the hash is not a known BIOS. pub fn check_bios(image: &[u8]) -> Result<&'static str, String> { let digest = hex(&Sha256::digest(image)); match bios_by_sha256(&digest) { Some(bios) => Ok(bios.name), None => Err(format!("not a known 7800 BIOS (SHA-256 {digest})")), } } /// Machine + cartridge, powered on. pub struct System { pub machine: Machine, pub description: Option, pub start: &'static str, pub bios_name: String, pub cpu: Sally, pub instructions: u64, pub mode_log: Rc>>, // (clock, INPTCTRL value) per write pub controllers: ProLine, } impl System { pub fn new( cartridge: Box, machine: Machine, bios: Option>, start: &'static str, description: Option, ) -> Result { if start != "bios" && start != "direct" { return Err("start is 'bios' or 'direct'".to_string()); } let (bios, bios_name) = if start == "bios" { let bios = match bios { Some(b) => b, None => find_bios(&machine).ok_or_else(|| { format!( "no BIOS for {} found by hash below $MAME_ROMPATH (a7800.zip, a7800p.zip); pass bios= or start='direct'", machine.name ) })?, }; let name = check_bios(&bios)?.to_string(); (Some(bios), name) } else { (None, "BIOS skipped (direct start, labelled)".to_string()) }; let mut board = Board::new(machine, cartridge, bios); let mode_log = Rc::new(RefCell::new(Vec::new())); let log = mode_log.clone(); board.on_inptctrl = Some(Box::new(move |clocks, value| log.borrow_mut().push((clocks, value)))); let controllers = ProLine::new(&mut board.tia, board.riot.clone()); let cpu = Mos6502::new(board); let mut system = System { machine, description, start, bios_name, cpu, instructions: 0, mode_log, controllers, }; system.power(); Ok(system) } /// Load `rom` through the one loader (cartridge/formats.rs) and power on. pub fn from_rom( rom: Source, machine: Machine, options: &LoadOptions, bios: Option>, start: &'static str, ) -> Result { let description = formats::load(rom, options).map_err(|e| e.message)?; if description.console != "7800" { return Err("2600 dumps run in 2600 mode (milestone 6)".to_string()); } let cartridge = formats::build(&description)?; System::new(cartridge, machine, bios, start, Some(description)) } pub fn board(&self) -> &Board { &self.cpu.bus } pub fn board_mut(&mut self) -> &mut Board { &mut self.cpu.bus } pub fn power(&mut self) { let power = self.machine.power_on; let cpu = &mut self.cpu; cpu.a = power.a; cpu.x = power.x; cpu.y = power.y; cpu.s = power.s; cpu.p = power.p; if self.start == "direct" { let board = &mut cpu.bus; board.inptctrl = LOCK | MEN | EXT; board.locked = true; board.inptctrl_writes = 2; board.maria.enabled = true; board.maria.granted = false; } cpu.frame.request_reset(); } // -- running --------------------------------------------------------------- pub fn clocks(&self) -> u64 { self.board().clocks } /// "bios", "7800" or "2600" from the INPTCTRL latch. pub fn mode(&self) -> &'static str { let board = self.board(); if board.inptctrl & EXT == 0 { return "bios"; } if board.inptctrl & MEN != 0 { "7800" } else { "2600" } } /// One instruction (or reset, or interrupt entry); returns MARIA clocks it took. pub fn step(&mut self) -> u64 { let before = self.board().clocks; self.cpu.step(); self.instructions += 1; self.board().clocks - before } pub fn run_clocks(&mut self, clocks: u64) { let end = self.board().clocks + clocks; let mut count = 0; while self.cpu.bus.clocks < end { self.cpu.step(); count += 1; } self.instructions += count; } /// Run until MARIA has started `frames` more frames. pub fn run_frames(&mut self, frames: u64) { let target = self.cpu.bus.maria.frame + frames; let mut count = 0; while self.cpu.bus.maria.frame < target { self.cpu.step(); count += 1; } self.instructions += count; } pub fn run_until(&mut self, mut done: impl FnMut(&System) -> bool, max_clocks: u64) -> bool { let end = self.board().clocks + max_clocks; while self.cpu.bus.clocks < end { self.cpu.step(); self.instructions += 1; if done(self) { return true; } } false } } /// `System(cartridge, machine, start="direct")` and the BIOS start, for tests and tools. pub fn direct(cartridge: Box, machine: Machine) -> System { System::new(cartridge, machine, None, "direct", None).expect("a direct start needs no BIOS") } /// `formats.load` of a source with the defaults. pub fn load_default(source: Source) -> Result { formats::load(source, &LoadOptions::default()).map_err(|e| e.message) }