# 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 :class:`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). """ from __future__ import annotations import hashlib import io import json import shutil import subprocess import zipfile import zlib from dataclasses import dataclass, field from importlib import resources from pathlib import Path from .mappings import CLASSES, Cartridge, make_port from .walk import guess_16k __all__ = ["CAR_TYPES", "Cart", "CartridgeError", "load_cartridge", "table"] class CartridgeError(ValueError): """A file that is not a 5200 cartridge, or one whose mapping cannot be settled.""" #: 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. CAR_TYPES = { 4: "32k", 6: "16k-two", 7: "bbsb", 16: "16k-one", 19: "8k", 20: "4k", 71: "supercart", 72: "supercart", 73: "supercart", 74: "supercart", 159: "bbsb", } SIZE_CLASS = {0x1000: "4k", 0x2000: "8k", 0x8000: "32k", 0xA000: "bbsb"} # DOC (cartridge.md) SUPERCART_SIZES = (0x10000, 0x20000, 0x40000, 0x80000) # DOC: [A800] DOC/cart.txt types 71-74 @dataclass class Cart: """The one internal description of a cartridge (docs/cartridge.md).""" payload: bytes mapping: str mapping_from: str # "size" | "car-header" | "table" | "measured" | "caller" | "guess" title: str sha1: str crc32: str source: str = "" # where the payload came from (path, member) car_type: int | None = None car_checksum_ok: bool | None = None notes: list[str] = field(default_factory=list) controllers: tuple[str, ...] = ("stick", "keypad") table_row: dict | None = None measured_row: dict | None = None # the observed-boot row for this payload, if any @property def size(self) -> int: return len(self.payload) def port(self) -> Cartridge: """A fresh cartridge-port object for the board.""" return make_port(self.mapping, self.payload) _TABLE: dict | None = None def table() -> dict: """The cartridge table (``table.json``, built by scripts/build_cart_table.py).""" global _TABLE if _TABLE is None: text = resources.files(__package__).joinpath("table.json").read_text("utf-8") _TABLE = json.loads(text) return _TABLE def _read_archive(data: bytes, name: str, member: str | None) -> tuple[bytes, str]: """(member bytes, member name) from a zip or 7z held in memory, or the bytes themselves.""" if data[:4] == b"PK\x03\x04": with zipfile.ZipFile(io.BytesIO(data)) as archive: names = [i.filename for i in archive.infolist() if not i.is_dir()] chosen = _choose(names, member, name) return archive.read(chosen), chosen if data[:6] == b"7z\xbc\xaf\x27\x1c": return _read_7z(data, name, member) return data, name def _choose(names: list[str], member: str | None, name: str) -> str: if member is not None: if member not in names: raise CartridgeError(f"{name}: no member {member!r}") return member candidates = [n for n in names if not n.lower().endswith((".txt", ".nfo", ".xml", ".diz"))] if len(candidates) != 1: raise CartridgeError(f"{name}: {len(candidates)} candidate members; name one: {candidates}") return candidates[0] def _read_7z(data: bytes, name: str, member: str | None) -> tuple[bytes, str]: """py7zr if importable, else the 7z program through a pipe (open decision 7).""" try: import py7zr # type: ignore[import-not-found] except ImportError: py7zr = None if py7zr is not None: with py7zr.SevenZipFile(io.BytesIO(data)) as archive: names = list(archive.getnames()) chosen = _choose(names, member, name) extracted = archive.read([chosen]) return extracted[chosen].read(), chosen program = shutil.which("7z") or shutil.which("7za") or shutil.which("7zr") if program is None: raise CartridgeError( f"{name}: a 7z archive needs py7zr (pip install py7zr) or the 7z program" ) listing = subprocess.run( [program, "l", "-ba", "-slt", "-si"], input=data, capture_output=True, check=False ) names = [] for line in listing.stdout.decode("utf-8", "replace").splitlines(): if line.startswith("Path = "): names.append(line[7:]) if not names and listing.returncode != 0: # Some 7z builds cannot list from a pipe: fall back to the file on disk. raise CartridgeError(f"{name}: 7z could not list the archive from a pipe") chosen = _choose(names, member, name) out = subprocess.run( [program, "e", "-so", "-si", chosen], input=data, capture_output=True, check=True ) return out.stdout, chosen def _read_7z_path(path: Path, member: str | None) -> tuple[bytes, str]: try: import py7zr # type: ignore[import-not-found] except ImportError: py7zr = None if py7zr is not None: return _read_7z(path.read_bytes(), str(path), member) program = shutil.which("7z") or shutil.which("7za") or shutil.which("7zr") if program is None: raise CartridgeError( f"{path}: a 7z archive needs py7zr (pip install py7zr) or the 7z program" ) listing = subprocess.run( [program, "l", "-ba", "-slt", str(path)], capture_output=True, text=True, check=True ).stdout names = [line[7:] for line in listing.splitlines() if line.startswith("Path = ")] chosen = _choose(names, member, str(path)) out = subprocess.run([program, "e", "-so", str(path), chosen], capture_output=True, check=True) return out.stdout, chosen def _strip_car(data: bytes, name: str) -> tuple[bytes, int | None, bool | None]: """(payload, CART type or None, checksum matched or None).""" if data[:4] == b"CART" and len(data) % 4096 == 16 and len(data) > 16: kind = int.from_bytes(data[4:8], "big") checksum = int.from_bytes(data[8:12], "big") payload = data[16:] if kind not in CAR_TYPES: raise CartridgeError( f"{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] return payload, kind, (sum(data[16:]) & 0xFFFFFFFF) == checksum return data, None, None def _fixed_part_first(payload: bytes) -> bool: """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. """ def vector_ok(end: int) -> bool: vector = payload[end - 2] | payload[end - 1] << 8 return 0x8000 <= vector < 0xC000 return vector_ok(0x2000) and not vector_ok(len(payload)) def _trailer_title(payload: bytes) -> str: """The 20 screen-code characters the BIOS shows, as text (best effort).""" if len(payload) < 0x1000 or len(payload) > 0x8000: return "" raw = payload[-24:-4] chars = [] for code in raw: code &= 0x3F chars.append(chr(code + 0x20) if code < 0x40 else " ") return "".join(chars).strip() def load_cartridge( source: str | Path | bytes, *, mapping: str | None = None, member: str | None = None, ) -> Cart: """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. """ if isinstance(source, bytes | bytearray): name = "" data, chosen = _read_archive(bytes(source), name, member) else: path = Path(source) name = str(path) raw = path.read_bytes() if raw[:6] == b"7z\xbc\xaf\x27\x1c": data, chosen = _read_7z_path(path, member) else: data, chosen = _read_archive(raw, name, member) payload, car_type, checksum_ok = _strip_car(data, name) notes: list[str] = [] if checksum_ok is False: notes.append("CART header checksum does not match the payload (reported, not fatal)") size = len(payload) if size == 0 or size % 4096: raise CartridgeError(f"{name}: {size} bytes is not a multiple of 4096") raw_sha1 = hashlib.sha1(payload).hexdigest() if size == 0xA000 and car_type is None and _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] notes.append("40K image in fixed-8K-first order (type 159 / MAME layout): reordered") sha1 = hashlib.sha1(payload).hexdigest() crc = f"{zlib.crc32(payload):08x}" rows = table() row = rows["sha1"].get(sha1) or rows["sha1"].get(raw_sha1) if row is None and size == 0xA000: # The table's Bounty Bob row is keyed by MAME's (fixed-first) layout. alternative = hashlib.sha1(payload[0x8000:] + payload[:0x8000]).hexdigest() row = rows["sha1"].get(alternative) crc_row = rows["crc32"].get(crc) # Rows from the CC0 seed: an a5200.xml SHA-1 row first, else an .hsi CRC row. seed_mapping = (row or {}).get("mapping") or (crc_row or {}).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. measured = rows.get("measured", {}).get(sha1) or {} measured_mapping = measured.get("mapping") if measured.get("reading") in CLASSES else None header_mapping = CAR_TYPES.get(car_type) if car_type is not None else None if mapping is not None: if mapping not in CLASSES: raise CartridgeError(f"unknown mapping {mapping!r}; one of {sorted(CLASSES)}") chosen_mapping, mapping_from = mapping, "caller" elif size in SIZE_CLASS: chosen_mapping, mapping_from = SIZE_CLASS[size], "size" elif size in SUPERCART_SIZES: chosen_mapping, mapping_from = "supercart", "size" elif size == 0x4000 and measured_mapping is not None and measured_mapping != seed_mapping: # A confirmed observed-boot row the CC0 seed does not give, or contradicts. chosen_mapping, mapping_from = measured_mapping, "measured" if seed_mapping is not None: notes.append( f"CONFLICT: MAME's CC0 list says {seed_mapping}; measured here: {measured_mapping} " f"({measured.get('evidence', '')}); the measured row wins (docs/cartridge.md " f"'Measured rows': the seed is detector-tier data, the observed boot meets the " f"confirmation rule of open decision 3)" ) elif size == 0x4000 and seed_mapping is not None: chosen_mapping, mapping_from = seed_mapping, "table" elif header_mapping is not None: chosen_mapping, mapping_from = header_mapping, "car-header" elif size == 0x4000: guess, detail = guess_16k(payload) if guess is None: raise CartridgeError( f"{name}: a 16K image in no table, and the static walk cannot tell one chip " f"from two ({detail}); pass mapping='16k-one' or '16k-two'" ) chosen_mapping, mapping_from = guess, "guess" notes.append(f"mapping {guess} is a GUESS from the static walk ({detail})") else: raise CartridgeError(f"{name}: no 5200 cartridge class is {size} bytes") if mapping_from == "table" and measured_mapping == chosen_mapping: notes.append(f"the observed-boot row measured here agrees ({measured_mapping})") elif measured.get("reading") in ("both", "neither") and mapping_from == "guess": notes.append(f"observed boot here: {measured['reading']} readings reach a picture") if ( header_mapping is not None and mapping_from in ("table", "measured") and header_mapping != chosen_mapping ): notes.append( f"CART header says {header_mapping}; the table says {chosen_mapping} (table wins)" ) if chosen_mapping in SIZE_CLASS.values() and mapping_from != "caller": expect = {v: k for k, v in SIZE_CLASS.items()}[chosen_mapping] if size != expect: raise CartridgeError(f"{name}: {chosen_mapping} needs {expect} bytes, not {size}") title_row = row or crc_row or measured title = title_row.get("title") or _trailer_title(payload) return Cart( payload=payload, mapping=chosen_mapping, mapping_from=mapping_from, title=title, sha1=sha1, crc32=crc, source=f"{name}" + (f" :: {chosen}" if chosen != name else ""), car_type=car_type, car_checksum_ok=checksum_ok, notes=notes, table_row=row or crc_row or (measured or None), measured_row=measured or None, ) def make_car(payload: bytes, car_type: int) -> bytes: """An Atari800 CART file around ``payload`` (for tests and conversions).""" checksum = sum(payload) & 0xFFFFFFFF return ( b"CART" + car_type.to_bytes(4, "big") + checksum.to_bytes(4, "big") + bytes(4) + bytes(payload) )