// SPDX-License-Identifier: MIT //! The one loader: every file format people have, to one CartDescription. //! //! docs/cartridge.md "Formats: one loader". `load(source)` takes a path or //! bytes and answers, in this order (decided 2026-11-12 in the reference, //! handoff-brief.md "Open decisions" 2, 3, 7): //! //! 1. **Container**: `.zip` (one image member; text and pictures beside it are //! ignored; two images is an error naming them), `.7z` through the `7z` program, //! ProSystem's `.cdf` refused (SOUPER's asset manifest, milestone 7), anything else //! read whole. Nothing is ever written beside the input. //! 2. **A78 header** (recognised by content, not by extension): stripped; its //! fields are stated with source "a78 header v". //! 3. **The table** (cartridge/table.rs: MAME's CC0 list and rows the reference //! confirmed), by the payload's bytes. A table row beats the header; every field where //! they differ is reported in `notes`; `trust="header"` or `"table"` //! overrides. On a miss the lookup is retried with the header's size field //! applied and with uniform leading/trailing fill trimmed to a smaller //! standard size: a hit that way is "matched after trimming". //! 4. **a2600-python's identification by hash** (its MAME 2600 list, through //! a2600-rust): a 2600 dump. //! 5. **The BIOS's own test** (cartridge/bios_test.rs) when a BIOS image is //! found: "2600" sends the image to a2600-rust; "7800" goes on. //! 6. **Unknown headerless 7800 image**: 48 KiB or less loads as linear, TIA //! only, ProLine sticks, with `certainty = "size"`; larger is refused //! ([`Refused`]) with the payload's SHA-256 and the three ways forward. //! //! Identity is the payload's SHA-256 (`CartDescription::sha256`). //! //! Loader policy (formats, order, sizes, trimming) is not a hardware claim; the facts it //! relies on are DOC (the A78 specification, MAME's CC0 list) or the BIOS's own code. //! //! Rust-forced differences (a7800-python `cartridge/formats.py` at d6b220d): the zip //! reader is the `zip` crate (Python's `zipfile`); `.7z` output is parsed as the //! reference parses `7z l -slt`; a source is [`Source`] (a path or bytes); overrides are //! `(name, Value)` pairs; errors are `Result`s. The BIOS search is `system::find_bios`. use std::path::Path; use std::process::Command; use super::a78; use super::connector::{Cartridge, Linear}; use super::description::{CartDescription, Refused, Value, SOURCES}; use super::table; pub const NOT_IMAGES: [&str; 16] = [ ".txt", ".nfo", ".diz", ".jpg", ".jpeg", ".png", ".gif", ".pdf", ".md", ".htm", ".html", ".xml", ".dat", ".url", ".sfv", ".md5", ]; // Dump sizes to try when trimming fill: loader policy, not a hardware value. pub const STANDARD_SIZES: [usize; 13] = [ 4 * 1024, 8 * 1024, 16 * 1024, 32 * 1024, 48 * 1024, 52 * 1024, 64 * 1024, 96 * 1024, 128 * 1024, 144 * 1024, 256 * 1024, 272 * 1024, 512 * 1024, ]; pub const LINEAR_LIMIT: usize = 0xC000; // 48 KiB: the largest a flat mapping from $4000 holds (DOC: Stolberg) /// What to load: a file or the image's bytes. #[derive(Clone, Copy, Debug)] pub enum Source<'a> { Path(&'a Path), Bytes(&'a [u8]), } fn not_image(name: &str) -> bool { let lower = name.to_lowercase(); NOT_IMAGES.iter().any(|s| lower.ends_with(s)) } fn suffix(path: &Path) -> String { path.extension() .map(|e| format!(".{}", e.to_string_lossy().to_lowercase())) .unwrap_or_default() } fn file_name(path: &Path) -> String { path.file_name() .map(|n| n.to_string_lossy().into_owned()) .unwrap_or_default() } /// (a name for messages, the image's bytes), from a file, an archive or bytes. pub fn read_source(source: Source) -> Result<(String, Vec), Refused> { let path = match source { Source::Bytes(bytes) => return Ok(("".to_string(), bytes.to_vec())), Source::Path(path) => path, }; let suffix = suffix(path); let name = file_name(path); if NOT_IMAGES.contains(&suffix.as_str()) { return Err(Refused::new(format!( "{name}: a {suffix} file is not a cartridge image" ))); } if suffix == ".cdf" { return Err(Refused::new(format!( "{name}: ProSystem .cdf manifests (SOUPER assets) are not supported yet" ))); } if suffix == ".zip" { let file = std::fs::File::open(path).map_err(|e| Refused::new(format!("{name}: {e}")))?; let mut archive = zip::ZipArchive::new(file).map_err(|e| Refused::new(format!("{name}: {e}")))?; let mut members = Vec::new(); for i in 0..archive.len() { let entry = archive.by_index(i).map_err(|e| Refused::new(format!("{name}: {e}")))?; if !entry.is_dir() && !not_image(entry.name()) { members.push(entry.name().to_string()); } } if members.len() != 1 { let names = if members.is_empty() { "none".to_string() } else { members.join(", ") }; return Err(Refused::new(format!( "{name}: expected one cartridge image in the zip, found {names}" ))); } let mut entry = archive .by_name(&members[0]) .map_err(|e| Refused::new(format!("{name}: {e}")))?; let mut data = Vec::new(); std::io::Read::read_to_end(&mut entry, &mut data).map_err(|e| Refused::new(format!("{name}: {e}")))?; return Ok((format!("{name}:{}", members[0]), data)); } if suffix == ".7z" { let listing = match Command::new("7z").args(["l", "-slt"]).arg(path).output() { Ok(out) if out.status.success() => String::from_utf8_lossy(&out.stdout).into_owned(), Ok(out) => { return Err(Refused::new(format!( "{name}: 7z failed: {}", String::from_utf8_lossy(&out.stderr) ))) } Err(_) => { return Err(Refused::new(format!( "{name}: .7z needs the 7z program, which was not found" ))) } }; let body = match listing.split_once("----------") { Some((_, rest)) => rest.to_string(), None => listing.clone(), }; let mut members = Vec::new(); for entry in body.split("\n\n") { let mut path_name = None; let mut folder = false; for line in entry.lines() { if let Some(value) = line.strip_prefix("Path = ") { if path_name.is_none() { path_name = Some(value.to_string()); } } if line.starts_with("Folder = +") { folder = true; } } if let Some(member) = path_name { if !folder && !not_image(&member) { members.push(member); } } } if members.len() != 1 { let names = if members.is_empty() { "none".to_string() } else { members.join(", ") }; return Err(Refused::new(format!( "{name}: expected one cartridge image in the 7z, found {names}" ))); } let out = Command::new("7z") .args(["x", "-so"]) .arg(path) .arg(&members[0]) .output() .map_err(|e| Refused::new(format!("{name}: {e}")))?; return Ok((format!("{name}:{}", members[0]), out.stdout)); } let data = std::fs::read(path).map_err(|e| Refused::new(format!("{name}: {e}")))?; Ok((name, data)) } fn uniform(data: &[u8]) -> bool { data.iter().all(|&b| b == data[0]) } /// Smaller payloads the same cartridge might be, each with how it was obtained. pub fn trimmed_candidates(payload: &[u8], header_size: Option) -> Vec<(Vec, String)> { let mut out = Vec::new(); if let Some(size) = header_size { if size != 0 && size < payload.len() { out.push((payload[..size].to_vec(), format!("header size field {size}"))); } } for size in STANDARD_SIZES { if size >= payload.len() { break; } let cut = payload.len() - size; if uniform(&payload[..cut]) { out.push((payload[cut..].to_vec(), format!("{cut} bytes of leading fill removed"))); } if uniform(&payload[size..]) { out.push(( payload[..size].to_vec(), format!("{cut} bytes of trailing fill removed"), )); } } out } fn trims_to(long: &[u8], short: &[u8]) -> bool { if long.len() < short.len() { return false; } let cut = long.len() - short.len(); if &long[cut..] == short && uniform(&long[..cut]) { return true; } &long[..short.len()] == short && uniform(&long[short.len()..]) } /// "identical", "matched after trimming" (uniform fill removed from the /// longer), or None. A bankset payload is two images, SALLY's then MARIA's /// (docs/cartridge.md "Banksets"), and an EPROM-padded copy pads each half: /// with `bankset` the halves are matched separately. pub fn match_payloads(a: &[u8], b: &[u8], bankset: bool) -> Option<&'static str> { if a == b { return Some("identical"); } let (long, short) = if a.len() > b.len() { (a, b) } else { (b, a) }; if trims_to(long, short) { return Some("matched after trimming"); } if bankset && long.len() % 2 == 0 && short.len() % 2 == 0 { let (lh, sh) = (long.len() / 2, short.len() / 2); if trims_to(&long[..lh], &short[..sh]) && trims_to(&long[lh..], &short[sh..]) { return Some("matched after trimming (each bankset half)"); } } None } fn from_row(desc: &CartDescription, row: &table::Row) -> CartDescription { let controllers = if row.lightgun { ("lightgun".to_string(), "proline".to_string()) } else { desc.controllers.clone() }; let mut fields: Vec<(&str, Value)> = vec![ ("scheme", Value::s(&row.scheme)), ("at_4000", Value::s(&row.at_4000)), ("pokey", Value::Pokey(row.pokey.clone())), ("hsc", Value::Bool(row.hsc)), ("xm", Value::Bool(row.xm)), ("controllers", Value::Pair(controllers.0, controllers.1)), ("title", Value::s(&row.title)), ]; if row.region != "unknown" { fields.push(("region", Value::s(&row.region))); } desc.with_fields(&row.source, &fields) } fn apply_header(desc: &CartDescription, header: &a78::Header) -> CartDescription { let source = if header.version == 3 || header.version == 4 { format!("a78 header v{}", header.version) } else { "a78 header".to_string() }; let mut fields: Vec<(&str, Value)> = header.fields.iter().map(|(n, v)| (*n, v.clone())).collect(); if !header.title.is_empty() { match fields.iter_mut().find(|(n, _)| *n == "title") { Some(entry) => entry.1 = Value::s(&header.title), None => fields.push(("title", Value::s(&header.title))), } } desc.with_fields(&source, &fields) } pub const BUILD_FIELDS: [&str; 8] = ["scheme", "at_4000", "pokey", "bankset", "ym2151", "hsc", "xm", "region"]; fn repr(value: &Value) -> String { match value { Value::Str(s) => format!("'{s}'"), Value::Bool(b) => if *b { "True" } else { "False" }.to_string(), Value::Pokey(p) => match p.len() { 0 => "()".to_string(), 1 => format!("({},)", p[0]), _ => format!("({})", p.iter().map(|a| a.to_string()).collect::>().join(", ")), }, other => format!("{other:?}"), } } /// The loader's options (the reference's keyword arguments). #[derive(Clone, Debug, Default)] pub struct LoadOptions<'a> { pub overrides: Option>, pub trust: Option<&'a str>, pub bios: Option<&'a [u8]>, pub skip_bios_test: bool, // use_bios_test=False } /// The one front door (see the module header). pub fn load(source: Source, options: &LoadOptions) -> Result { let (name, data) = read_source(source)?; let use_bios_test = !options.skip_bios_test; let mut header = None; let mut notes: Vec = Vec::new(); let payload: Vec = if a78::is_a78(&data) { let parsed = a78::parse(&data).map_err(|e| Refused::new(e.0))?; let payload = data[a78::HEADER..].to_vec(); if parsed.size != 0 && parsed.size != payload.len() { notes.push(format!( "header size field {} differs from the payload's {}", parsed.size, payload.len() )); } header = Some(parsed); payload } else { data }; if payload.is_empty() { return Err(Refused::new(format!("{name}: empty image"))); } let member = name.rsplit(':').next().unwrap_or(&name); let stem = Path::new(member) .file_stem() .map(|s| s.to_string_lossy().into_owned()) .unwrap_or_default(); let mut desc = CartDescription::new(&payload); desc.title = stem; let mut row = table::lookup(&payload); if row.is_none() { for (candidate, how) in trimmed_candidates(&payload, header.as_ref().map(|h| h.size)) { row = table::lookup(&candidate); if row.is_some() { notes.push(format!("matched after trimming ({how})")); let title = desc.title.clone(); desc = CartDescription::new(&candidate); desc.title = title; break; } } } let with_header = header.as_ref().map(|h| apply_header(&desc, h)); let with_row = row.as_ref().map(|r| from_row(&desc, r)); let mut chosen = match (with_header, with_row) { (Some(h), Some(t)) => { for field in BUILD_FIELDS { let (hv, tv) = (h.get(field), t.get(field)); if hv != tv { notes.push(format!( "header and table differ on {field}: header {}, table {}", repr(&hv), repr(&tv) )); } } if options.trust == Some("header") { notes.push("--trust header: the header's fields are used".to_string()); Some(h) } else { Some(t) } } (h, t) => t.or(h), }; if chosen.is_none() { if let Some(overrides) = options.overrides.as_ref() { if overrides.iter().any(|(n, _)| *n == "scheme") { chosen = Some(desc.clone()); // the user typed the image: the override is the whole description notes.push("headerless and in no table: described by the override alone".to_string()); } } } let mut chosen = match chosen { Some(c) => c, None => unknown_headerless( &desc, &name, if use_bios_test { options.bios } else { None }, &mut notes, use_bios_test, )?, }; if let Some(overrides) = options.overrides.as_ref() { chosen = chosen.with_fields("override", overrides); } let certainty = certainty(&chosen); let mut all_notes = notes; all_notes.extend(chosen.notes.iter().cloned()); chosen.certainty = certainty; chosen.notes = all_notes; Ok(chosen) } fn certainty(desc: &CartDescription) -> String { let rank = |s: &str| SOURCES.iter().position(|x| *x == s).unwrap_or(SOURCES.len()); let sources: Vec = ["scheme", "at_4000", "pokey"] .iter() .map(|f| desc.provenance_of(f).unwrap_or("default").to_string()) .collect(); // max() keeps the first of equal ranks, as Python's does let mut best = sources[0].clone(); for s in &sources[1..] { if rank(s) > rank(&best) { best = s.clone(); } } best } fn unknown_headerless( desc: &CartDescription, name: &str, bios: Option<&[u8]>, notes: &mut Vec, use_bios_test: bool, ) -> Result { let payload = &desc.payload; let (family, source, title) = match a2600::cartridge::identify(payload, &a2600::cartridge::mame_hash()) { Ok((family, _super_chip, source, title)) => (Some(family), Some(source), title), Err(_) => (None, None, None), }; if source.as_deref() == Some("MAME softlist") { let title = title.unwrap_or_else(|| desc.title.clone()); return Ok(desc.with_fields( "softlist", &[ ("console", Value::s("2600")), ("a2600_scheme", Value::OptStr(family)), ("title", Value::Str(title)), ], )); } let mut verdict: Option<&str> = None; let mut region = "unknown"; if use_bios_test && payload.len() <= LINEAR_LIMIT { use super::bios_test::bios_verdict_default; use crate::machine::{NTSC, PAL}; use crate::system::find_bios; let ntsc = match bios { Some(b) => Some(b.to_vec()), None => find_bios(&NTSC), }; if let Some(ntsc) = ntsc { let v = bios_verdict_default(&ntsc, payload).map_err(Refused::new)?; verdict = Some(v); notes.push(format!("BIOS test: an NTSC console starts this image in {v} mode")); if v == "7800" { region = "ntsc"; } } let pal = if verdict != Some("7800") { find_bios(&PAL) } else { None }; if let Some(pal) = pal { // The PAL BIOS checks the region byte only (C8; its own code): a 7800 verdict // there after a 2600 verdict on NTSC is a PAL (or unsigned) 7800 image. let pal_verdict = bios_verdict_default(&pal, payload).map_err(Refused::new)?; notes.push(format!( "BIOS test: a PAL console starts this image in {pal_verdict} mode" )); if pal_verdict == "7800" { region = if verdict == Some("2600") { "pal" } else { "unknown" }; verdict = Some("7800"); } else if verdict.is_none() { verdict = Some(pal_verdict); } } if verdict.is_none() { notes.push("no BIOS image found: the BIOS test was not run".to_string()); } } if verdict == Some("2600") { return Ok(desc.with_fields( "bios test", &[("console", Value::s("2600")), ("a2600_scheme", Value::OptStr(family))], )); } if payload.len() <= LINEAR_LIMIT { notes.push("typed by size alone: linear, TIA only, ProLine sticks (labelled)".to_string()); return Ok(desc.with_fields( "size", &[ ("scheme", Value::s("linear")), ("at_4000", Value::s("none")), ("pokey", Value::Pokey(Vec::new())), ("region", Value::s(region)), ], )); } let sha256 = desc.sha256(); Err(Refused { message: format!( "{name}: a {}-byte headerless image in no table (SHA-256 {sha256}). Its scheme cannot be read from the bytes. Ways forward: an .a78 of the same game, an override (e.g. --as supergame,ram@4000,pokey@450), or a confirmed table row.", payload.len() ), sha256, }) } /// `supergame,ram@4000,pokey@450` -> override fields. pub fn parse_as(text: &str) -> Result, String> { let mut fields: Vec<(&'static str, Value)> = vec![("pokey", Value::Pokey(Vec::new()))]; let put = |fields: &mut Vec<(&'static str, Value)>, name: &'static str, value: Value| match fields .iter_mut() .find(|(n, _)| *n == name) { Some(entry) => entry.1 = value, None => fields.push((name, value)), }; let mut pokey = Vec::new(); for part in text.split(',').map(|p| p.trim()).filter(|p| !p.is_empty()) { if ["linear", "supergame", "activision", "absolute", "souper"].contains(&part) { put(&mut fields, "scheme", Value::s(part)); } else if let Some(address) = part.strip_prefix("pokey@") { pokey.push(u16::from_str_radix(address, 16).map_err(|e| e.to_string())?); } else if let Some(kind) = part.strip_suffix("@4000") { let option = match kind { "ram" => "ram16", "rom" => "rom", "bank6" => "fixed-bank", "mram" => "mirror-ram-2k", _ => return Err(format!("unknown hardware word '{part}'")), }; put(&mut fields, "at_4000", Value::s(option)); } else if ["hsc", "xm", "ym2151", "bankset"].contains(&part) { let name: &'static str = match part { "hsc" => "hsc", "xm" => "xm", "ym2151" => "ym2151", _ => "bankset", }; put(&mut fields, name, Value::Bool(true)); } else if part == "bankram" { // bankset RAM: 2 x 16 KiB at $4000, by HALT (DOC: wiki) put(&mut fields, "at_4000", Value::s("ram32-halt")); } else if part == "pal" || part == "ntsc" { put(&mut fields, "region", Value::s(part)); } else { return Err(format!("unknown hardware word '{part}'")); } } put(&mut fields, "pokey", Value::Pokey(pokey)); Ok(fields) } /// The connector object for a 7800 description (schemes grow by milestone). pub fn build(desc: &CartDescription) -> Result, String> { if desc.console != "7800" { return Err("a 2600 dump is built by a2600-python".to_string()); } if desc.scheme == "linear" && desc.at_4000 == "none" && desc.pokey.is_empty() && !desc.bankset { return Ok(Box::new(Linear::new(&desc.payload)?)); } super::schemes::build(desc) }