// SPDX-License-Identifier: MIT //! The loader's front door: every form a 5200 cartridge arrives in, one description out. //! //! `load_cartridge(path_or_bytes)` is the only way in (docs/cartridge.md //! "Formats and the loader's front door"). It accepts a raw dump or an Atari800 //! CART (`.car`) file, loose or inside a zip or 7z archive; detection is by //! content, never by extension, and nothing is written anywhere. The result is //! a [`Cart`] whose `mapping` comes, in this order of authority, from the //! caller, the size, this repository's table (keyed by the payload's SHA-1), a //! CART header, or, for a 16K payload nobody knows, the static walk as a //! labelled guess (open decision 3: refuse only when the walk abstains). //! //! The table has two kinds of 16K rows: the CC0 seed (MAME's two hash files) and //! observed-boot rows measured here (the `measured` section). An observed-boot //! row is used where the seed is silent; where it agrees with the seed the seed //! row stands; where it contradicts the seed the measured row wins and the //! conflict is reported in `Cart.notes` (docs/cartridge.md "Measured rows"). //! //! Evidence tags: the order of authority is a policy (open decision 3, decided //! 2026-11-12), not hardware behaviour. The size classes are DOC (docs/cartridge.md //! "Classes": [FAQ], [AHRM] 13.2, MAME's CC0 list). Seed rows are a detector's //! data (MAME's CC0 list: OBSERVED-grade, tier 5); observed-boot rows are this //! board's own boots of each dump under both readings, judged by eye (the //! board's run, not hardware: provisional in docs/claims.md). //! //! A transcription of a5200-python's `cartridge/__init__.py` (at cf82d44). `table.json` is //! the reference's file, copied byte for byte (MIT for its own rows; the seed rows are MAME's //! CC0 data, see NOTICE) and compiled in. Rust-forced differences: //! //! - `load_cartridge` takes a [`Source`] (a path or bytes) and returns `Result`; the table is `serde_json::Value`, and Python's truthiness tests on its //! rows (`row or crc_row`, `.get("mapping") or ...`) are spelled out by `truthy`. //! - A 7z archive is read with the `7z` program (Python prefers `py7zr` when it is importable, //! else the same program); the bytes are the same. //! - `Cart.table_row` / `measured_row` hold the JSON rows. //! - `load_cartridge_with_table` takes the table as an argument, where Python's tests //! monkeypatch the module's `_TABLE`. pub mod mappings; pub mod walk; use std::io::{Cursor, Read}; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::sync::OnceLock; use serde_json::Value; use sha1::{Digest, Sha1}; use mappings::{class, CLASS_NAMES}; pub use mappings::{make_port, Cartridge}; use walk::guess_16k; /// A file that is not a 5200 cartridge, or one whose mapping cannot be settled. #[derive(Debug, Clone, PartialEq)] pub struct CartridgeError(pub String); impl std::fmt::Display for CartridgeError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&self.0) } } impl std::error::Error for CartridgeError {} fn err(text: String) -> Result { Err(CartridgeError(text)) } /// Atari800 CART header type numbers for the 5200 (DOC: [A800] DOC/cart.txt, /// a documentation file in a GPL-2.0+ project). Only the documented type /// numbers are used, a fact about the file format; nothing of Atari800's code. /// 159 is Bounty Bob in the alternative image order, reordered to type 7's /// order on load. pub fn car_types(kind: u32) -> Option<&'static str> { Some(match kind { 4 => "32k", 6 => "16k-two", 7 => "bbsb", 16 => "16k-one", 19 => "8k", 20 => "4k", 71..=74 => "supercart", 159 => "bbsb", _ => return None, }) } /// DOC (cartridge.md) fn size_class(size: usize) -> Option<&'static str> { Some(match size { 0x1000 => "4k", 0x2000 => "8k", 0x8000 => "32k", 0xA000 => "bbsb", _ => return None, }) } const SUPERCART_SIZES: [usize; 4] = [0x10000, 0x20000, 0x40000, 0x80000]; // DOC: [A800] DOC/cart.txt types 71-74 /// The one internal description of a cartridge (docs/cartridge.md). #[derive(Clone, Debug, PartialEq)] pub struct Cart { pub payload: Vec, pub mapping: String, pub mapping_from: String, // "size" | "car-header" | "table" | "measured" | "caller" | "guess" pub title: String, pub sha1: String, pub crc32: String, pub source: String, // where the payload came from (path, member) pub car_type: Option, pub car_checksum_ok: Option, pub notes: Vec, pub controllers: Vec, pub table_row: Option, pub measured_row: Option, // the observed-boot row for this payload, if any } impl Cart { pub fn size(&self) -> usize { self.payload.len() } /// A fresh cartridge-port object for the board. pub fn port(&self) -> Cartridge { make_port(&self.mapping, &self.payload) } } /// The cartridge table (`table.json`, built by scripts/build_cart_table.py). pub fn table() -> &'static Value { static TABLE: OnceLock = OnceLock::new(); TABLE.get_or_init(|| serde_json::from_str(include_str!("table.json")).expect("table.json")) } /// Python's truth value of a JSON value (None, "", {} and 0 are false). fn truthy(value: Option<&Value>) -> Option<&Value> { match value { None | Some(Value::Null) => None, Some(Value::String(s)) if s.is_empty() => None, Some(Value::Object(o)) if o.is_empty() => None, Some(Value::Bool(false)) => None, Some(Value::Number(n)) if n.as_f64() == Some(0.0) => None, other => other, } } fn text(value: Option<&Value>) -> Option { truthy(value).and_then(|v| v.as_str()).map(str::to_string) } fn sha1_hex(data: &[u8]) -> String { let mut hasher = Sha1::new(); hasher.update(data); hasher .finalize() .iter() .map(|b| format!("{b:02x}")) .collect() } /// (member bytes, member name) from a zip or 7z held in memory, or the bytes themselves. fn _read_archive( data: Vec, name: &str, member: Option<&str>, ) -> Result<(Vec, String), CartridgeError> { if data.starts_with(b"PK\x03\x04") { let mut archive = zip::ZipArchive::new(Cursor::new(data)) .map_err(|e| CartridgeError(format!("{name}: {e}")))?; let mut names = Vec::new(); for index in 0..archive.len() { let file = archive .by_index(index) .map_err(|e| CartridgeError(format!("{name}: {e}")))?; if !file.is_dir() { names.push(file.name().to_string()); } } let chosen = _choose(&names, member, name)?; let mut file = archive .by_name(&chosen) .map_err(|e| CartridgeError(format!("{name}: {e}")))?; let mut out = Vec::new(); file.read_to_end(&mut out) .map_err(|e| CartridgeError(format!("{name}: {e}")))?; return Ok((out, chosen)); } if data.starts_with(b"7z\xbc\xaf\x27\x1c") { return _read_7z(&data, name, member); } Ok((data, name.to_string())) } fn _choose(names: &[String], member: Option<&str>, name: &str) -> Result { if let Some(member) = member { if !names.iter().any(|n| n == member) { return err(format!("{name}: no member {member:?}")); } return Ok(member.to_string()); } let candidates: Vec<&String> = names .iter() .filter(|n| { let lower = n.to_lowercase(); ![".txt", ".nfo", ".xml", ".diz"] .iter() .any(|ext| lower.ends_with(ext)) }) .collect(); if candidates.len() != 1 { return err(format!( "{name}: {} candidate members; name one: {candidates:?}", candidates.len() )); } Ok(candidates[0].clone()) } fn seven_zip() -> Option { for program in ["7z", "7za", "7zr"] { for dir in std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()) { let candidate = dir.join(program); if candidate.is_file() { return Some(candidate); } } } None } /// The 7z program through a pipe (open decision 7). fn _read_7z( data: &[u8], name: &str, member: Option<&str>, ) -> Result<(Vec, String), CartridgeError> { let Some(program) = seven_zip() else { return err(format!( "{name}: a 7z archive needs py7zr (pip install py7zr) or the 7z program" )); }; let run = |args: &[&str]| -> Result { let mut child = Command::new(&program) .args(args) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() .map_err(|e| CartridgeError(format!("{name}: {e}")))?; let mut stdin = child.stdin.take().unwrap(); let input = data.to_vec(); let writer = std::thread::spawn(move || { use std::io::Write; let _ = stdin.write_all(&input); }); let output = child .wait_with_output() .map_err(|e| CartridgeError(format!("{name}: {e}")))?; let _ = writer.join(); Ok(output) }; let listing = run(&["l", "-ba", "-slt", "-si"])?; let names: Vec = String::from_utf8_lossy(&listing.stdout) .lines() .filter_map(|line| line.strip_prefix("Path = ").map(str::to_string)) .collect(); if names.is_empty() && !listing.status.success() { // Some 7z builds cannot list from a pipe: fall back to the file on disk. return err(format!("{name}: 7z could not list the archive from a pipe")); } let chosen = _choose(&names, member, name)?; let out = run(&["e", "-so", "-si", &chosen])?; if !out.status.success() { return err(format!("{name}: 7z failed")); } Ok((out.stdout, chosen)) } fn _read_7z_path(path: &Path, member: Option<&str>) -> Result<(Vec, String), CartridgeError> { let shown = path.display().to_string(); let Some(program) = seven_zip() else { return err(format!( "{shown}: a 7z archive needs py7zr (pip install py7zr) or the 7z program" )); }; let listing = Command::new(&program) .args(["l", "-ba", "-slt"]) .arg(path) .output() .map_err(|e| CartridgeError(format!("{shown}: {e}")))?; if !listing.status.success() { return err(format!("{shown}: 7z could not list the archive")); } let names: Vec = String::from_utf8_lossy(&listing.stdout) .lines() .filter_map(|line| line.strip_prefix("Path = ").map(str::to_string)) .collect(); let chosen = _choose(&names, member, &shown)?; let out = Command::new(&program) .args(["e", "-so"]) .arg(path) .arg(&chosen) .output() .map_err(|e| CartridgeError(format!("{shown}: {e}")))?; if !out.status.success() { return err(format!("{shown}: 7z failed")); } Ok((out.stdout, chosen)) } /// (payload, CART type or None, checksum matched or None). type Stripped = (Vec, Option, Option); fn _strip_car(data: Vec, name: &str) -> Result { if data.starts_with(b"CART") && data.len() % 4096 == 16 && data.len() > 16 { let kind = u32::from_be_bytes(data[4..8].try_into().unwrap()); let checksum = u32::from_be_bytes(data[8..12].try_into().unwrap()); let mut payload = data[16..].to_vec(); if car_types(kind).is_none() { return err(format!( "{name}: CART type {kind} is an 8-bit computer cartridge, not a 5200 one" )); } if kind == 159 { // Bounty Bob, fixed 8K first: reorder to type 7's order payload = [&payload[0x2000..], &payload[..0x2000]].concat(); } let sum = data[16..] .iter() .fold(0u32, |acc, &b| acc.wrapping_add(b as u32)); return Ok((payload, Some(kind), Some(sum == checksum))); } Ok((data, None, None)) } /// Whether a 40K Bounty Bob image holds its fixed 8K (with the trailer) first. /// /// The fixed 8K is seen at $8000-$BFFF, so its last two bytes are the start /// vector and point into $8000-$BFFF; a switched bank's last bytes need not. fn _fixed_part_first(payload: &[u8]) -> bool { let vector_ok = |end: usize| -> bool { let vector = payload[end - 2] as usize | (payload[end - 1] as usize) << 8; (0x8000..0xC000).contains(&vector) }; vector_ok(0x2000) && !vector_ok(payload.len()) } /// The 20 screen-code characters the BIOS shows, as text (best effort). fn _trailer_title(payload: &[u8]) -> String { if payload.len() < 0x1000 || payload.len() > 0x8000 { return String::new(); } let raw = &payload[payload.len() - 24..payload.len() - 4]; let mut chars = String::new(); for &code in raw { let code = code & 0x3F; chars.push(if code < 0x40 { char::from(code + 0x20) } else { ' ' }); } chars.trim().to_string() } /// Where a cartridge comes from: a path or bytes (Python's `str | Path | bytes`). pub enum Source<'a> { Path(&'a Path), Bytes(&'a [u8]), } /// Load a cartridge from a path or bytes, read in place, and describe it. /// /// `mapping` overrides everything (one of "4k", "8k", "16k-one", "16k-two", /// "32k", "bbsb", "supercart"); `member` names the file inside an archive /// with more than one candidate. pub fn load_cartridge( source: Source, mapping: Option<&str>, member: Option<&str>, ) -> Result { load_cartridge_with_table(table(), source, mapping, member) } /// `load_cartridge` against a given table (Python's tests replace the module's `_TABLE`). pub fn load_cartridge_with_table( rows: &Value, source: Source, mapping: Option<&str>, member: Option<&str>, ) -> Result { let name; let (data, chosen) = match source { Source::Bytes(bytes) => { name = "".to_string(); _read_archive(bytes.to_vec(), &name, member)? } Source::Path(path) => { name = path.display().to_string(); let raw = std::fs::read(path).map_err(|e| CartridgeError(format!("{name}: {e}")))?; if raw.starts_with(b"7z\xbc\xaf\x27\x1c") { _read_7z_path(path, member)? } else { _read_archive(raw, &name, member)? } } }; let (mut payload, car_type, checksum_ok) = _strip_car(data, &name)?; let mut notes: Vec = Vec::new(); if checksum_ok == Some(false) { notes.push("CART header checksum does not match the payload (reported, not fatal)".into()); } let size = payload.len(); if size == 0 || size % 4096 != 0 { return err(format!("{name}: {size} bytes is not a multiple of 4096")); } let raw_sha1 = sha1_hex(&payload); if size == 0xA000 && car_type.is_none() && _fixed_part_first(&payload) { // A raw Bounty Bob dump in the fixed-8K-first order (MAME's layout, // Atari800 type 159): reorder to type 7's order so both hash alike. payload = [&payload[0x2000..], &payload[..0x2000]].concat(); notes.push("40K image in fixed-8K-first order (type 159 / MAME layout): reordered".into()); } let sha1 = sha1_hex(&payload); let crc = format!("{:08x}", crc32fast::hash(&payload)); let mut row = truthy(rows["sha1"].get(&sha1)).or_else(|| truthy(rows["sha1"].get(&raw_sha1))); if row.is_none() && size == 0xA000 { // The table's Bounty Bob row is keyed by MAME's (fixed-first) layout. let alternative = sha1_hex(&[&payload[0x8000..], &payload[..0x8000]].concat()); row = truthy(rows["sha1"].get(&alternative)); } let crc_row = truthy(rows["crc32"].get(&crc)); // Rows from the CC0 seed: an a5200.xml SHA-1 row first, else an .hsi CRC row. let seed_mapping = text(row.and_then(|r| r.get("mapping"))) .or_else(|| text(crc_row.and_then(|r| r.get("mapping")))); // Observed-boot rows measured here (docs/cartridge.md "Measured rows"): only a // row whose boot settled one reading carries a mapping; "both"/"neither" do not. let measured = rows.get("measured").and_then(|m| truthy(m.get(&sha1))); let reading = measured .and_then(|m| m.get("reading")) .and_then(|v| v.as_str()); let measured_mapping = if reading.is_some_and(|r| CLASS_NAMES.contains(&r)) { measured .and_then(|m| m.get("mapping")) .and_then(|v| v.as_str()) .map(str::to_string) } else { None }; let header_mapping = car_type.and_then(car_types); let chosen_mapping: String; let mapping_from: &str; if let Some(mapping) = mapping { if class(mapping).is_none() { let mut sorted = CLASS_NAMES.to_vec(); sorted.sort(); return err(format!("unknown mapping {mapping:?}; one of {sorted:?}")); } chosen_mapping = mapping.to_string(); mapping_from = "caller"; } else if let Some(class) = size_class(size) { chosen_mapping = class.to_string(); mapping_from = "size"; } else if SUPERCART_SIZES.contains(&size) { chosen_mapping = "supercart".to_string(); mapping_from = "size"; } else if size == 0x4000 && measured_mapping.is_some() && measured_mapping != seed_mapping { // A confirmed observed-boot row the CC0 seed does not give, or contradicts. let measured_mapping = measured_mapping.clone().unwrap(); if let Some(seed) = &seed_mapping { let evidence = measured .and_then(|m| m.get("evidence")) .and_then(|v| v.as_str()) .unwrap_or(""); notes.push(format!( "CONFLICT: MAME's CC0 list says {seed}; measured here: {measured_mapping} \ ({evidence}); the measured row wins (docs/cartridge.md \ 'Measured rows': the seed is detector-tier data, the observed boot meets the \ confirmation rule of open decision 3)" )); } chosen_mapping = measured_mapping; mapping_from = "measured"; } else if size == 0x4000 && seed_mapping.is_some() { chosen_mapping = seed_mapping.clone().unwrap(); mapping_from = "table"; } else if let Some(header) = header_mapping { chosen_mapping = header.to_string(); mapping_from = "car-header"; } else if size == 0x4000 { let (guess, detail) = guess_16k(&payload); let Some(guess) = guess else { return err(format!( "{name}: a 16K image in no table, and the static walk cannot tell one chip \ from two ({detail}); pass mapping='16k-one' or '16k-two'" )); }; chosen_mapping = guess.to_string(); mapping_from = "guess"; notes.push(format!( "mapping {guess} is a GUESS from the static walk ({detail})" )); } else { return err(format!("{name}: no 5200 cartridge class is {size} bytes")); } if mapping_from == "table" && measured_mapping.as_deref() == Some(chosen_mapping.as_str()) { notes.push(format!( "the observed-boot row measured here agrees ({})", measured_mapping.as_deref().unwrap() )); } else if matches!(reading, Some("both") | Some("neither")) && mapping_from == "guess" { notes.push(format!( "observed boot here: {} readings reach a picture", reading.unwrap() )); } if let Some(header) = header_mapping { if (mapping_from == "table" || mapping_from == "measured") && header != chosen_mapping { notes.push(format!( "CART header says {header}; the table says {chosen_mapping} (table wins)" )); } } if ["4k", "8k", "32k", "bbsb"].contains(&chosen_mapping.as_str()) && mapping_from != "caller" { let expect = match chosen_mapping.as_str() { "4k" => 0x1000, "8k" => 0x2000, "32k" => 0x8000, _ => 0xA000, }; if size != expect { return err(format!( "{name}: {chosen_mapping} needs {expect} bytes, not {size}" )); } } let title_row = row.or(crc_row).or(measured); let title = text(title_row.and_then(|r| r.get("title"))).unwrap_or_else(|| _trailer_title(&payload)); let source = if chosen != name { format!("{name} :: {chosen}") } else { name.clone() }; Ok(Cart { payload, mapping: chosen_mapping, mapping_from: mapping_from.to_string(), title, sha1, crc32: crc, source, car_type, car_checksum_ok: checksum_ok, notes, controllers: vec!["stick".into(), "keypad".into()], table_row: row.or(crc_row).or(measured).cloned(), measured_row: measured.cloned(), }) } /// An Atari800 CART file around `payload` (for tests and conversions). pub fn make_car(payload: &[u8], car_type: u32) -> Vec { let checksum = payload .iter() .fold(0u32, |acc, &b| acc.wrapping_add(b as u32)); let mut out = b"CART".to_vec(); out.extend(car_type.to_be_bytes()); out.extend(checksum.to_be_bytes()); out.extend([0u8; 4]); out.extend(payload); out }