#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Ask MAME 0.285's POKEY questions through its a5200 driver, as a closed box. MAME is a **detector** (tier 5): it finds differences, it never decides who is right. Its source is never opened (docs/restart.md, rule 1); the released binary is run where its POKEY lives: in the Atari 5200 driver, whose POKEY sits at $E800-$E80F, with a probe cartridge this script writes. Environment: ``MAME`` (the binary, default ``mame`` on PATH), ``MAME_ROMPATH`` (the directory holding ``a5200.zip``), optional ``MAME_HASHPATH``. python -I scripts/mame_pokey.py # run, print the summary python -I scripts/mame_pokey.py --seconds 3 --out /some/dir What happens: 1. A 32K probe cartridge is generated here from the byte list below (no assembler, no third-party code). $BFFD = $FF makes the 5200 BIOS jump through $BFFE at once, without its logo. 2. MAME runs headless with the debugger scripted: a watchpoint on $E800-$E80F logs every POKEY read and write with the CPU's ``totalcycles``. 3. ``error.log`` is parsed into the experiments' answers and written to ``summary.txt`` beside it (default ``tests/mame_traces/pokey-probe``, ignored). The experiments (docs/mame-oracle.md has the results and what hardware says): - **init**: SKCTL = 0 for a while, then 3, then eight RANDOM reads four cycles apart: the phase of the 17-bit counter after initialisation mode is released. - **timer**: for AUDF1 in 0, 1, 5 with channel 1 on the 1.79 MHz clock: write STIMER, then read IRQST d cycles later, for a range of d: the first d at which bit 0 reads 0 is the timer's first underflow, as software sees it. Traps: the BIOS is read in place from the MAME set (never copied). ANTIC steals cycles from the CPU even with its display off; each measurement starts with a write to WSYNC so that it runs in the same part of a scan line, and MAME's ANTIC is not cycle-exact about which cycles it steals, so only the differences between ``totalcycles`` values inside one measurement mean anything. """ from __future__ import annotations import argparse import os import shutil import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] MAME = os.environ.get("MAME", "mame") HASHPATH = os.environ.get("MAME_HASHPATH", "") ROMPATH = os.environ.get("MAME_ROMPATH", "") POKEY = 0xE800 AUDF1, AUDC1, AUDCTL, STIMER, RANDOM, IRQEN, SKCTL = 0, 1, 8, 9, 10, 14, 15 IRQST = 14 NMIEN, DMACTL, WSYNC = 0xD40E, 0xD400, 0xD40A #: extra cycles between the STIMER write and the IRQST read (0, then 2 upward) DELAYS = [0, *range(2, 17)] PERIODS = [0, 1, 5] class Program: """A list of 6502 bytes, built one instruction at a time.""" def __init__(self, origin: int) -> None: self.origin = origin self.code = bytearray() def lda(self, value: int) -> None: self.code += bytes([0xA9, value]) def sta(self, address: int) -> None: self.code += bytes([0x8D, address & 0xFF, address >> 8]) def lda_absolute(self, address: int) -> None: self.code += bytes([0xAD, address & 0xFF, address >> 8]) def poke(self, address: int, value: int) -> None: self.lda(value) self.sta(address) def wait(self, cycles: int) -> None: """Any number of cycles but 1: NOPs (2 each), with one BIT $00 (3) for an odd count.""" if cycles == 1: raise ValueError("one cycle cannot be waited") if cycles % 2: self.code += bytes([0x24, 0x00]) cycles -= 3 self.code += bytes([0xEA]) * (cycles // 2) def here(self) -> int: return self.origin + len(self.code) def probe_cart() -> bytes: p = Program(0x4000) p.code += bytes([0x78, 0xD8, 0xA2, 0xFF, 0x9A]) # SEI, CLD, LDX #$FF, TXS p.poke(NMIEN, 0) p.poke(DMACTL, 0) p.poke(POKEY + IRQEN, 0) # init: hold initialisation mode for 40 cycles, release it, read RANDOM eight times p.poke(POKEY + AUDCTL, 0) p.poke(POKEY + SKCTL, 0) p.wait(40) p.poke(POKEY + SKCTL, 3) for _ in range(8): p.lda_absolute(POKEY + RANDOM) # timer: STIMER to the first IRQST read with bit 0 low p.poke(POKEY + AUDCTL, 0x40) p.poke(POKEY + AUDC1, 0xA0) for period in PERIODS: for delay in DELAYS: p.poke(POKEY + IRQEN, 0) p.poke(POKEY + AUDF1, 200) p.sta(POKEY + STIMER) p.poke(POKEY + IRQEN, 1) p.poke(POKEY + AUDF1, period) p.sta(WSYNC) p.wait(4) p.sta(POKEY + STIMER) p.wait(delay) p.lda_absolute(POKEY + IRQST) p.poke(POKEY + IRQEN, 0) loop = p.here() p.code += bytes([0x4C, loop & 0xFF, loop >> 8]) # JMP loop image = bytearray([0xFF]) * 0x8000 image[: len(p.code)] = p.code image[0x7FFD] = 0xFF # diagnostic cartridge: the BIOS jumps through $BFFE image[0x7FFE] = 0x00 image[0x7FFF] = 0x40 return bytes(image) DEBUG_LUA = """\ local dbg = manager.machine.debugger dbg.visible_cpu = manager.machine.devices[":maincpu"] dbg:command('wpset e800,10,w,1,{logerror "W %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}') dbg:command('wpset e800,10,r,1,{logerror "R %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}') dbg:command("go") """ def accesses(log: Path) -> list[tuple[str, int, int, int]]: found = [] for raw in log.read_text(encoding="utf-8", errors="replace").splitlines(): parts = raw.split() if len(parts) == 4 and parts[0] in ("R", "W"): found.append((parts[0], int(parts[1], 16) & 0xF, int(parts[2], 16), int(parts[3]))) return found def summarize(log: Path) -> list[str]: rows = accesses(log) lines = [f"{len(rows)} POKEY accesses logged"] release = next((i for i, r in enumerate(rows) if r[:3] == ("W", SKCTL, 3)), None) if release is not None: base = rows[release][3] reads = [r for r in rows[release + 1 : release + 9] if r[0] == "R" and r[1] == RANDOM] lines.append( "init: RANDOM after SKCTL=3 (cycles after the write: value): " + ", ".join(f"+{r[3] - base}: ${r[2]:02X}" for r in reads) ) # each measurement ends with the one IRQST read that follows a STIMER write results: dict[int, list[tuple[int, int]]] = {} period = None for before, row in zip(rows, rows[1:]): if row[:2] == ("W", AUDF1) and row[2] != 200: period = row[2] if row[:2] == ("R", IRQST) and before[:2] == ("W", STIMER) and period is not None: results.setdefault(period, []).append((row[3] - before[3], row[2])) for period, pairs in sorted(results.items()): first = next((gap for gap, value in sorted(pairs) if not value & 1), None) lines.append( f"timer: AUDF1={period}: IRQST read (cycles after the STIMER write: value) " + " ".join(f"{gap}:{value:02X}" for gap, value in sorted(pairs)) ) lines.append( f"timer: AUDF1={period}: bit 0 first reads 0 at +{first}" f" (hardware, Altirra manual and Acid800: +{8 + period})" ) return lines def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--seconds", type=int, default=2, help="emulated seconds") parser.add_argument("--rompath", default=ROMPATH, help="directory holding a5200.zip") parser.add_argument("--out", type=Path) parser.add_argument("--mame", default=MAME) args = parser.parse_args() if not args.rompath: parser.error("set MAME_ROMPATH (or --rompath) to the directory holding a5200.zip") out = (args.out or ROOT / "tests" / "mame_traces" / "pokey-probe").resolve() if out.exists(): shutil.rmtree(out) out.mkdir(parents=True) (out / "probe.bin").write_bytes(probe_cart()) (out / "probe.lua").write_text(DEBUG_LUA, encoding="utf-8") version = subprocess.run( [args.mame, "-version"], capture_output=True, text=True, check=True ).stdout.strip() # error.log lands in the working directory, not under -homepath. result = subprocess.run( [args.mame, "a5200", "-rompath", args.rompath, "-cart", "probe.bin", *(["-hashpath", HASHPATH] if HASHPATH else []), "-homepath", str(out), "-video", "none", "-sound", "none", "-nothrottle", "-noreadconfig", "-skip_gameinfo", "-debug", "-debugger", "none", "-log", "-seconds_to_run", str(args.seconds), "-autoboot_script", str(out / "probe.lua")], cwd=out, check=False, capture_output=True, text=True, ) # fmt: skip if result.returncode: print(result.stdout + result.stderr) return result.returncode report = [f"MAME {version}, driver a5200, {args.seconds} s", *summarize(out / "error.log")] (out / "summary.txt").write_text("\n".join(report) + "\n", encoding="utf-8") print("\n".join(report)) return 0 if __name__ == "__main__": sys.exit(main())