#!/usr/bin/env python3 """Record MAME 0.285's per-instruction CP1610 trace for an Intellivision cartridge. Runs the recipe in docs/mame-oracle.md in a fresh directory (default ``tests/mame_traces/-``, gitignored) and leaves ``error.log`` and a snapshot there. The drivers need MAME's ROM sets (``intv.zip`` etc.); the default ``--rompath`` is the local non-merged set, read in place. A ``.zip`` or ``.7z`` cartridge is extracted into the run directory; nothing is written elsewhere. python -I scripts/mame_trace.py intv "/Astrosmash (USA, Europe).zip" --seconds 2 python -I scripts/mame_trace.py intv --no-cart --seconds 1 python -I scripts/mame_trace.py intv "" --no-trace --seconds 10 # snapshot only ``error.log`` then holds one line per instruction, before it executes: C R7 R0 R1 R2 R3 R4 R5 R6 flags totalcycles frame beamy hex except the last three (decimal). R7 is the program counter, R6 the stack pointer. ``flags`` is MAME's ``curflags`` (S=$80 Z=$40 OV=$20 C=$10, as cp1610.cpp defines them; ``genflags`` is not a symbol and silently drops the action). ``totalcycles`` counts CP1610 clocks at 894,886 Hz in MAME's own accounting, in which the STIC's bus requests cost the CPU nothing (the intended lump subtraction has no effect: docs/mame-oracle.md), so it is not a bus-timing oracle. """ from __future__ import annotations import argparse import os import shutil import subprocess import sys import time from pathlib import Path ROOT = Path(__file__).resolve().parents[1] MAME = "/usr/games/mame" ROMPATH = os.environ.get("MAME_ROMPATH") DRIVERS = { "intv": "Intellivision (NTSC), exec.bin + GROM", "intvsrs": "Sears Super Video Arcade", "intv2": "Intellivision II", "intvoice": "Intellivision with Intellivoice", "intvecs": "Intellivision with ECS (and Intellivoice)", } IMAGES = {".int", ".bin", ".rom", ".itv"} TRACE_LUA = """\ local dbg = manager.machine.debugger dbg.visible_cpu = manager.machine.devices[":maincpu"] dbg:command('trace cpu.trace,:maincpu,noloop,{logerror "C %04X %04X %04X %04X %04X %04X %04X %04X %02X %d %d %d\\\\n",\ r7,r0,r1,r2,r3,r4,r5,r6,curflags,totalcycles,frame,beamy}') dbg:command("go") """ def extract(cart: Path, out: Path) -> Path: """The cartridge image inside a .zip/.7z, extracted into ``out``; a plain image is copied.""" if cart.suffix.lower() not in {".7z", ".zip"}: target = out / cart.name shutil.copyfile(cart, target) return target subprocess.run(["7z", "e", "-y", f"-o{out}", str(cart)], check=True, stdout=subprocess.DEVNULL) images = [p for p in out.iterdir() if p.suffix.lower() in IMAGES] if len(images) != 1: raise SystemExit(f"expected one image in {cart.name}, found {[p.name for p in images]}") return images[0] def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("driver", choices=sorted(DRIVERS)) parser.add_argument("cart", type=Path, nargs="?", help="image, or a .zip/.7z holding one") parser.add_argument("--no-cart", action="store_true", help="empty cartridge port") parser.add_argument("--seconds", type=int, default=1, help="emulated seconds (integer)") parser.add_argument("--no-trace", action="store_true", help="snapshot only, no debugger") parser.add_argument("--rompath", default=ROMPATH) parser.add_argument("--out", type=Path) parser.add_argument("--mame", default=MAME) args = parser.parse_args() if not args.rompath: raise SystemExit("set MAME_ROMPATH to the MAME (non-merged) ROM folder, or pass --rompath") if not args.cart and not args.no_cart: parser.error("give a cartridge or --no-cart") stem = "nocart" if args.cart: stem = args.cart.resolve().stem.split(" (")[0].replace(" ", "_") out = (args.out or ROOT / "tests" / "mame_traces" / f"{args.driver}-{stem}").resolve() if out.exists(): raise SystemExit(f"{out} exists: move it into trash/ first (a stale error.log survives)") out.mkdir(parents=True) media = [] if args.cart: media = ["-cart", extract(args.cart.resolve(), out).name] script = [] if not args.no_trace: (out / "trace.lua").write_text(TRACE_LUA, encoding="utf-8") script = ["-debug", "-debugger", "none", "-autoboot_script", str(out / "trace.lua")] version = subprocess.run( [args.mame, "-version"], capture_output=True, text=True, check=True ).stdout.strip() began = time.monotonic() # error.log lands in the working directory, not under -homepath. subprocess.run( [args.mame, args.driver, *media, "-rompath", args.rompath, "-homepath", str(out), "-snapshot_directory", "snap", "-video", "none", "-sound", "none", "-nothrottle", "-noreadconfig", "-skip_gameinfo", "-log", "-seconds_to_run", str(args.seconds), *script], cwd=out, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) # fmt: skip wall = time.monotonic() - began print(f"MAME {version}, {args.driver}, {args.seconds} s emulated in {wall:.1f} s: {out}") if not args.no_trace: summarise(out / "error.log") return 0 def summarise(log: Path) -> None: """Instruction count, the largest cycle gap between instructions, interrupt spacing. A bus-steal model that charged the CPU would show as a gap of hundreds of cycles once a frame; MAME 0.285 shows none (largest gap 21 on Astrosmash). """ count, largest, previous, entries = 0, 0, None, [] if log.exists(): with log.open(encoding="ascii", errors="replace") as handle: for line in handle: if not line.startswith("C "): continue fields = line.split() cycles = int(fields[10]) count += 1 if previous is not None: largest = max(largest, cycles - previous) if fields[1] == "1004": entries.append(cycles) previous = cycles print(f" {count:,} instructions; largest gap between instructions {largest} cycles") if len(entries) > 2: spacing = (entries[-1] - entries[1]) / (len(entries) - 2) print(f" {len(entries)} interrupt entries ($1004), {spacing:,.1f} cycles apart on average") if __name__ == "__main__": sys.exit(main())