#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Census of the local Atari 5200 dumps: sizes, cartridge classes, the 16K layout question. Reads every archive in place (zip with the standard library, 7z through the ``7z`` program writing to a pipe); nothing is extracted to disk and nothing is written next to the sets. python scripts/count_carts.py # the local sets, table to stdout python scripts/count_carts.py --tsv out.tsv # one row per dump as well python scripts/count_carts.py DIR [DIR ...] # other directories The local sets are ``$NO_INTRO_DIR/Atari - Atari 5200`` and any folders in ``$A5200_EXTRA_DIRS`` (scripts/romsets.py). For each dump it records the size, CRC-32 and SHA-1, the class MAME 0.285's CC0 software list gives it (``$MAME_HASHPATH/a5200.xml``, matched by SHA-1: ``a5200_rom``, ``a5200_2chips``, ``a5200_bbsb``, ``a5200_supercart``), the cartridge trailer (start vector at $BFFE, the byte at $BFFD the BIOS tests, the two "year" bytes at $BFFC/$BFFD, see docs/cartridge.md), and, for 16K images, this script's own answer to "one chip or two": A 16K image is either one 16K ROM at $8000-$BFFF, seen again at $4000-$7FFF, or two 8K ROMs: the first at $4000-$5FFF and again at $6000-$7FFF, the second at $8000-$9FFF and again at $A000-$BFFF. The two readings agree at $4000-$5FFF and $A000-$BFFF and differ at $6000-$9FFF. The script walks the program from its start vector under both readings (documented opcodes only, following JMP, JSR and both sides of every branch) and counts how often the walk reaches an undocumented opcode or leaves the cartridge into unmapped space (faults), and how many instructions it reaches. The wrong reading soon lands in data and stops, so the reading that reaches at least four times as many instructions (and at least 200) wins; otherwise the answer is "either" (the walk never entered $6000-$9FFF, or both readings run). Fault counts are printed but do not decide: they were tried first and were wrong on 9 of 43 dumps. This is a static guess, labelled as such: docs/cartridge.md compares it with MAME's list. The walk is this repository's own; it is not taken from any emulator. """ from __future__ import annotations import argparse import collections import hashlib import re import subprocess import sys import xml.etree.ElementTree as ET import zipfile import zlib from pathlib import Path from romsets import cartridge_sets, mame_hashpath # scripts/romsets.py SOFTLIST = mame_hashpath() / "a5200.xml" HASHINFO = mame_hashpath() / "a5200.hsi" BIOS_SHA1 = { "6ad7a1e8c9fad486fbec9498cb48bf5bc3adc530": "BIOS 4-port (CO19156)", "1d2a3f00109d75d2d79fecb565775eb95b7d04d5": "BIOS rev A (CO19156A)", } # Lengths of the documented NMOS 6502 opcodes; 0 marks an undocumented one. _LEN1 = ( "00 08 0a 18 28 2a 38 40 48 4a 58 60 68 6a 78 88 8a 98 9a a8 aa b8 ba c8 ca d8 e8 ea f8" ) _LEN3 = ( "0d 0e 19 1d 1e 20 2c 2d 2e 39 3d 3e 4c 4d 4e 59 5d 5e 6c 6d 6e 79 7d 7e 8c 8d 8e" " 99 9d ac ad ae b9 bc bd be cc cd ce d9 dd de ec ed ee f9 fd fe" ) _LEN2 = ( "01 05 06 09 10 11 15 16 21 24 25 26 29 30 31 35 36 41 45 46 49 50 51 55 56 61 65 66" " 69 70 71 75 76 81 84 85 86 90 91 94 95 96 a0 a1 a2 a4 a5 a6 a9 b0 b1 b4 b5 b6 c0 c1" " c4 c5 c6 c9 d0 d1 d5 d6 e0 e1 e4 e5 e6 e9 f0 f1 f5 f6" ) LENGTH = [0] * 256 for _text, _n in ((_LEN1, 1), (_LEN2, 2), (_LEN3, 3)): for _op in _text.split(): LENGTH[int(_op, 16)] = _n BRANCHES = {0x10, 0x30, 0x50, 0x70, 0x90, 0xB0, 0xD0, 0xF0} STOPS = {0x00, 0x40, 0x60, 0x4C, 0x6C} # BRK, RTI, RTS, JMP, JMP () def members(archive: Path) -> list[tuple[str, bytes]]: """(name, bytes) of every file in a zip or 7z, read through memory.""" if archive.suffix.lower() == ".zip": with zipfile.ZipFile(archive) as z: return [(i.filename, z.read(i)) for i in z.infolist() if not i.is_dir()] if archive.suffix.lower() == ".7z": listing = subprocess.run( ["7z", "l", "-ba", "-slt", str(archive)], capture_output=True, text=True, check=True ).stdout names = re.findall(r"^Path = (.+)$", listing, flags=re.MULTILINE) out = [] for name in names: data = subprocess.run( ["7z", "e", "-so", str(archive), name], capture_output=True, check=True ).stdout out.append((name, data)) return out return [(archive.name, archive.read_bytes())] def softlist() -> dict[str, tuple[str, str, str]]: """SHA-1 of the whole image -> (MAME short name, slot, supported).""" table: dict[str, tuple[str, str, str]] = {} if not SOFTLIST.exists(): return table for software in ET.parse(SOFTLIST).getroot().iter("software"): slot = "a5200_rom" for feature in software.iter("feature"): if feature.get("name") == "slot": slot = feature.get("value", slot) roms = [r for r in software.iter("rom") if r.get("sha1")] if len(roms) == 1: table[roms[0].get("sha1", "")] = ( software.get("name", "?"), slot, software.get("supported", "yes"), ) return table def hashinfo() -> dict[str, str]: """CRC-32 -> extrainfo from MAME's a5200.hsi (CC0; "" when the entry has none).""" table: dict[str, str] = {} if not HASHINFO.exists(): return table for entry in ET.parse(HASHINFO).getroot().iter("hash"): extra = entry.find("extrainfo") text = (extra.text or "").strip() if extra is not None else "" table[entry.get("crc32", "").lower()] = text return table def certain_class(data: bytes, slot: str, extra: str | None) -> tuple[str, str]: """(mirroring class, where the answer comes from) using public data only.""" size = len(data) if size == 0xA000: return "bbsb", "size" if slot != "a5200_bbsb" else "a5200.xml" if size in (0x1000, 0x2000, 0x8000): return f"{size // 1024}k", "size" if size != 0x4000: return "?", "unknown size" if data[:0x2000] == data[0x2000:]: return "16k-either", "halves identical" if slot in ("a5200_rom", "a5200_2chips"): return ("16k-two" if slot == "a5200_2chips" else "16k-one"), "a5200.xml" if extra is not None and not extra.endswith("?"): return ("16k-two" if extra == "A13MIRRORING" else "16k-one"), "a5200.hsi" return "16k-?", "unknown" def layout(data: bytes, kind: str) -> dict[int, int]: """Address -> file offset for the cartridge window $4000-$BFFF.""" size = len(data) table = {} for address in range(0x4000, 0xC000): if size == 0x8000: offset = address - 0x4000 elif size == 0x4000 and kind == "two": offset = ((address - 0x4000) & 0x1FFF) + (0x2000 if address >= 0x8000 else 0) elif size == 0x4000: offset = address & 0x3FFF elif size in (0x2000, 0x1000): # 8K sits at $A000-$BFFF and is seen again at $8000; 4K repeats. # $4000-$7FFF is left unmapped here (see docs/cartridge.md C-items). if address < 0x8000: continue offset = address & (size - 1) else: continue table[address] = offset return table def walk(data: bytes, kind: str, limit: int = 20000) -> tuple[int, int, int]: """(instructions reached, faults, instructions inside $6000-$9FFF).""" table = layout(data, kind) if 0xBFFE not in table: return 0, 0, 0 start = data[table[0xBFFE]] | data[table[0xBFFF]] << 8 todo = [start] seen: set[int] = set() faults = middle = 0 while todo and len(seen) < limit: pc = todo.pop() while pc not in seen and len(seen) < limit: if pc >= 0xC000: # POKEY, BIOS: outside the image, not a fault break if pc not in table or pc + 2 not in table: faults += 1 # RAM or an unmapped hole: programs do not run there at start break opcode = data[table[pc]] length = LENGTH[opcode] if not length: faults += 1 break seen.add(pc) middle += 0x6000 <= pc < 0xA000 low, high = data[table[pc + 1]], data[table[pc + 2]] if opcode in BRANCHES: todo.append((pc + 2 + (low - 256 if low & 0x80 else low)) & 0xFFFF) elif opcode in (0x20, 0x4C): todo.append(low | high << 8) if opcode in STOPS: break pc += length return len(seen), faults, middle def sixteen_k(data: bytes) -> tuple[str, str]: if data[:0x2000] == data[0x2000:]: return "either", "halves identical" one, two = walk(data, "one"), walk(data, "two") detail = f"one {one[0]}i/{one[1]}f/{one[2]}m two {two[0]}i/{two[1]}f/{two[2]}m" # The wrong reading soon lands in data or in the other chip's code and # stops; the right one keeps going. Reach decides; faults are shown only. low, high = sorted((one[0], two[0])) if high < 4 * max(low, 1) or high < 200: return "either", detail return ("one" if one[0] > two[0] else "two"), detail def trailer(data: bytes) -> str: if len(data) < 0x1000 or len(data) > 0x8000: return "-" start = data[-2] | data[-1] << 8 return f"start ${start:04X} $BFFC/D {data[-4]:02X} {data[-3]:02X}" def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("sets", nargs="*", type=Path) parser.add_argument("--tsv", type=Path, help="write one row per dump") args = parser.parse_args() args.sets = args.sets or cartridge_sets() known = softlist() extras = hashinfo() disagreements = [] rows = [] seen_hashes: dict[str, str] = {} for directory in args.sets: sizes: collections.Counter[int] = collections.Counter() slots: collections.Counter[str] = collections.Counter() guesses: collections.Counter[str] = collections.Counter() agree: collections.Counter[str] = collections.Counter() logo: collections.Counter[str] = collections.Counter() tags: collections.Counter[str] = collections.Counter() sources: collections.Counter[str] = collections.Counter() unknown16: collections.Counter[str] = collections.Counter() archives = sorted( p for p in directory.iterdir() if p.suffix.lower() in (".zip", ".7z", ".a52", ".bin") ) new = 0 for archive in archives: for name, data in members(archive): digest = hashlib.sha1(data).hexdigest() crc = f"{zlib.crc32(data):08x}" if digest in BIOS_SHA1: print(f" {BIOS_SHA1[digest]}: {archive.name} ({len(data)} bytes, crc {crc})") continue new += digest not in seen_hashes seen_hashes.setdefault(digest, archive.name) sizes[len(data)] += 1 short, slot, supported = known.get(digest, ("-", "not listed", "-")) slots[slot] += 1 extra = extras.get(crc) klass, source = certain_class(data, slot, extra) sources[source] += 1 if slot in ("a5200_rom", "a5200_2chips") and extra is not None and len(data) == 0x4000: if (extra == "A13MIRRORING") != (slot == "a5200_2chips"): disagreements.append(f"{archive.name}: xml {slot}, hsi '{extra}'") guess = detail = "-" if len(data) == 0x4000: guess, detail = sixteen_k(data) guesses[guess] += 1 if klass == "16k-?": unknown16[guess] += 1 if slot in ("a5200_rom", "a5200_2chips"): mame = "two" if slot == "a5200_2chips" else "one" verdict = "agree" if guess == mame else guess agree[f"MAME {mame}, walk {verdict}"] += 1 if 0x1000 <= len(data) <= 0x8000: logo["$BFFD = $FF (no logo)" if data[-3] == 0xFF else "logo"] += 1 for tag in re.findall(r"\(([^)]+)\)", archive.stem): key = re.sub(r"[ \d-].*", "", tag) if key in ("Proto", "Beta", "Demo", "Unl", "Alt", "Rev"): tags[key] += 1 rows.append( (directory.name, archive.name, name, len(data), crc, digest, short, slot, supported, guess, detail, trailer(data), klass, source) ) # fmt: skip print(f"\n{directory}\n {len(archives)} archives, {new} images not seen in an earlier set") print(" sizes: " + ", ".join(f"{k // 1024}K x{v}" for k, v in sorted(sizes.items()))) print(" MAME 0.285 a5200.xml slot: " + ", ".join(f"{k} {v}" for k, v in slots.most_common())) print(" 16K by this script's walk: " + ", ".join(f"{k} {v}" for k, v in guesses.most_common())) print(" 16K, walk against MAME: " + ", ".join(f"{k}: {v}" for k, v in sorted(agree.items()))) print(" class from public data: " + ", ".join(f"{k} {v}" for k, v in sources.most_common())) print(" 16K with no public answer, by walk: " + ", ".join(f"{k} {v}" for k, v in unknown16.most_common())) print(" trailer: " + ", ".join(f"{k} {v}" for k, v in logo.most_common())) print(" name tags: " + ", ".join(f"{k} {v}" for k, v in tags.most_common())) print("\nxml against hsi on 16K images in both: " + ("; ".join(sorted(set(disagreements))) or "no disagreement")) if args.tsv: header = "set\tarchive\tmember\tsize\tcrc32\tsha1\tmame\tslot\tsupported\twalk\tdetail\ttrailer\tclass\tsource" lines = ["\t".join(str(v) for v in row) for row in rows] args.tsv.write_text("\n".join([header, *lines]) + "\n", encoding="utf-8") print(f"\nwrote {args.tsv} ({len(rows)} rows)") return 0 if __name__ == "__main__": sys.exit(main())