# SPDX-License-Identifier: MIT """Run MAME 0.285 (a closed box) on an Atari 8-bit machine: a short CPU trace, chip writes, a picture. MAME_ROMPATH=... python -I scripts/mame_trace.py a800xl --seconds 3 --snapshot 150 MAME_ROMPATH=... python -I scripts/mame_trace.py a800 --seconds 3 --cart "$NO_INTRO_DIR/Atari - 8-bit Family/Galaxian (USA).zip" MAME_ROMPATH=... python -I scripts/mame_trace.py a800xl --no-trace --seconds 10 --snapshot 500 Everything lands in reference/mame/[-]/ (git-ignored): error.log holds one line per instruction (``PC A X Y P SP totalcycles VCOUNT``, VCOUNT read through the debugger without side effects), ``W addr value totalcycles`` for each CPU write to GTIA ($D000), POKEY ($D200), the PIA ($D300) and ANTIC ($D400), and an ``F`` line per MAME frame; summary.txt the counts. A cartridge is read in place from its zip and written into the run directory only. Every output is OBSERVED (an emulator, tier 5): a detector, never a judge. One MAME process at a time; keep runs to a few seconds. """ from __future__ import annotations import argparse import collections import itertools import os import shutil import subprocess import sys import time import zipfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] MACHINES = ("a400", "a800", "a800pal", "a1200xl", "a600xl", "a800xl", "a800xlp", "a65xe", "a130xe", "xegs") CHIPS = {0xD0: "GTIA", 0xD2: "POKEY", 0xD3: "PIA", 0xD4: "ANTIC"} TRACE_LUA = """\ local dbg = manager.machine.debugger dbg.visible_cpu = manager.machine.devices[":maincpu"] dbg:command('trace cpu.trace,,noloop,{logerror "%X %X %X %X %X %X %d %X\\\\n",pc,a,x,y,p,sp,totalcycles,b@d40b}') dbg:command('wpset d000,20,w,1,{logerror "W %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}') dbg:command('wpset d200,10,w,1,{logerror "W %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}') dbg:command('wpset d300,4,w,1,{logerror "W %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}') dbg:command('wpset d400,10,w,1,{logerror "W %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}') dbg:command("go") """ # Notifier subscriptions are collected unless held in globals. FRAMES_LUA = """\ frame_n = 0 frame_sub = emu.add_machine_frame_notifier(function() frame_n = frame_n + 1 manager.machine:logerror("F\\n") if frame_n == {snap} then manager.machine.video:snapshot() end end) """ def summarize(log: Path) -> list[str]: instructions = 0 marks: list[int] = [] pending = False writes: collections.Counter[str] = collections.Counter() portb: list[str] = [] regions: collections.Counter[str] = collections.Counter() with log.open("rb") as handle: for raw in handle: parts = raw.split() if not parts: continue if parts[-1] == b"F" and len(parts) <= 2: pending = True continue if parts[0] == b"W" and len(parts) == 4: address, value = int(parts[1], 16), int(parts[2], 16) writes[CHIPS.get(address >> 8, "?")] += 1 if address == 0xD301 and len(portb) < 8: portb.append(f"${value:02X}@{int(parts[3])}") continue if len(parts) == 8: try: pc = int(parts[0], 16) except ValueError: continue instructions += 1 regions[f"${pc >> 12:X}xxx"] += 1 if pending: marks.append(int(parts[6])) pending = False deltas = collections.Counter(b - a for a, b in itertools.pairwise(marks)) return [ f"{instructions:,} instructions, {len(marks)} frame marks", f"cycles between frame marks (most common): {deltas.most_common(4)}", "CPU writes by chip: " + ", ".join(f"{k} {v:,}" for k, v in sorted(writes.items())), f"first PORTB ($D301) writes: {portb}", "instructions by 4K page: " + ", ".join(f"{k} {v:,}" for k, v in sorted(regions.items())), ] def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("machine", choices=MACHINES) parser.add_argument("--cart", type=Path, help="a one-member zip or loose cartridge image") parser.add_argument("--seconds", type=int, default=3) parser.add_argument("--snapshot", type=int, default=0, metavar="FRAME") parser.add_argument("--no-trace", action="store_true") args = parser.parse_args() rompath = os.environ.get("MAME_ROMPATH") if not rompath: sys.exit("mame_trace: set MAME_ROMPATH") name = args.machine + (f"-{args.cart.stem.split(' (')[0].replace(' ', '_')}" if args.cart else "") out = ROOT / "reference" / "mame" / name if out.exists(): trash = ROOT / "trash" / time.strftime("%Y%m%d-%H%M%S") trash.mkdir(parents=True, exist_ok=True) shutil.move(str(out), trash / name) out.mkdir(parents=True) media: list[str] = [] if args.cart: if args.cart.suffix.lower() == ".zip": with zipfile.ZipFile(args.cart) as archive: (member,) = archive.infolist() image = out / Path(member.filename).name image.write_bytes(archive.read(member)) else: image = out / args.cart.name shutil.copyfile(args.cart, image) media = ["-cart1", str(image)] lua = ("" if args.no_trace else TRACE_LUA) + FRAMES_LUA.replace("{snap}", str(args.snapshot)) (out / "trace.lua").write_text(lua, encoding="utf-8") debug = [] if args.no_trace else ["-debug", "-debugger", "none"] command = ["nice", "mame", args.machine, "-rompath", rompath, *media, "-homepath", str(out), "-snapshot_directory", str(out / "snap"), "-cfg_directory", str(out / "cfg"), "-nvram_directory", str(out / "nvram"), "-video", "none", "-sound", "none", "-nothrottle", "-noreadconfig", "-skip_gameinfo", *debug, "-log", "-seconds_to_run", str(args.seconds), "-autoboot_script", str(out / "trace.lua")] began = time.monotonic() result = subprocess.run(command, cwd=out, capture_output=True, text=True, check=False) lines = [" ".join(c if " " not in c else repr(c) for c in command).replace(rompath, "$MAME_ROMPATH"), f"exit {result.returncode} after {time.monotonic() - began:.1f} s wall", *[line for line in (result.stdout + result.stderr).splitlines() if line.strip()][:12]] if (out / "error.log").exists(): lines += summarize(out / "error.log") snaps = sorted((out / "snap").rglob("*.png")) if (out / "snap").exists() else [] lines.append("snapshots: " + ", ".join(str(p.relative_to(out)) for p in snaps)) (out / "summary.txt").write_text("\n".join(lines) + "\n", encoding="utf-8") print("\n".join(lines)) return result.returncode if __name__ == "__main__": sys.exit(main())