#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Record MAME 0.285's per-instruction 65SC02 trace and Mikey/Suzy handshake log for a Lynx cart. Runs the recipe in docs/mame-oracle.md in a fresh directory (default ``tests/mame_traces/``, gitignored) and leaves ``error.log`` there. The ``lynx`` driver needs the 512-byte boot ROM set ``lynx.zip`` (bring your own; ``--rompath`` names the directory that holds it, default: the local MAME set). ``cart`` may be a loose ``.lnx``/``.lyx``/``.o`` or a one-member zip (the member is extracted into the output directory; ROM sets are never copied into the repository). python scripts/mame_trace.py "/path/No-Intro/Atari - Atari Lynx (LNX)/Zaku (World) (Unl).zip" python scripts/mame_trace.py game.lyx --seconds 5 --bios a python scripts/mame_trace.py demo.o --no-trace --seconds 20 --snap ``error.log`` then holds, in execution order: - one line per instruction, before it executes: ``PC A X Y P SP totalcycles`` (hex, cycles decimal). MAME runs the CPU at a flat 4 MHz (16 MHz / 4): ``totalcycles`` counts CPU cycles, not 16 MHz ticks, and MAME has no 4-tick/5-tick distinction (docs/mame-oracle.md); - ``W addr value totalcycles`` for CPU writes to SPRGO ($FC91), SPRSYS ($FC92), SUZYBUSEN ($FC90), SDONEACK ($FD90), CPUSLEEP ($FD91), INTRST/INTSET ($FD80/$FD81), DISPCTL ($FD92), PBKUP ($FD93), MAPCTL ($FFF9), and the timer 0 and 2 registers ($FD00-$FD03, $FD08-$FD0B). ``frames.txt`` gets ``F totalcycles`` once per MAME screen frame; ``summary.txt`` the counts. """ from __future__ import annotations import argparse import collections import os import shutil import subprocess import sys import time import zipfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] MAME = os.environ.get("MAME", shutil.which("mame") or "mame") ROMPATH = os.environ.get("MAME_ROMPATH", "") # the boot ROM's lynx.zip lives here CPU_TAG = ":maincpu" # (first address, length) of the write watchpoints. WATCH = [(0xFC90, 3), (0xFD90, 4), (0xFD80, 2), (0xFFF9, 1), (0xFD00, 4), (0xFD08, 4)] TRACE_LUA = """\ local dbg = manager.machine.debugger dbg.visible_cpu = manager.machine.devices["{cpu}"] dbg:command('trace cpu.trace,,noloop,{{logerror "%X %X %X %X %X %X %d\\\\n",pc,a,x,y,p,sp,totalcycles}}') {watch} dbg:command("go") """ # Notifier subscriptions end when garbage-collected: keep them in globals. STATUS_LUA = """\ local log = io.open("frames.txt", "w") local cpu = manager.machine.devices["{cpu}"] frames_done = 0 status_sub = emu.add_machine_frame_notifier(function() frames_done = frames_done + 1 log:write(string.format("F %d\\n", cpu.state["CURPC"] and manager.machine.time:as_ticks(4000000) or 0)) log:flush() if {snap_at} > 0 and frames_done == {snap_at} then manager.machine.video:snapshot() end end) """ def extract(cart: Path, out: Path) -> Path: if cart.suffix.lower() != ".zip": dest = out / cart.name shutil.copyfile(cart, dest) return dest with zipfile.ZipFile(cart) as z: members = [i for i in z.infolist() if not i.is_dir()] if len(members) != 1: raise SystemExit(f"{cart}: expected one member, found {len(members)}") dest = out / Path(members[0].filename).name dest.write_bytes(z.read(members[0])) return dest def summarize(log: Path) -> list[str]: instructions = 0 writes: collections.Counter[int] = collections.Counter() first = last = None with log.open("rb") as f: for raw in f: parts = raw.split() if len(parts) == 4 and parts[0] == b"W": writes[int(parts[1], 16)] += 1 elif len(parts) == 7: try: cyc = int(parts[6]) except ValueError: continue instructions += 1 first = cyc if first is None else first last = cyc names = {0xFC91: "SPRGO", 0xFC92: "SPRSYS", 0xFC90: "SUZYBUSEN", 0xFD90: "SDONEACK", 0xFD91: "CPUSLEEP", 0xFD80: "INTRST", 0xFD81: "INTSET", 0xFD92: "DISPCTL", 0xFD93: "PBKUP", 0xFFF9: "MAPCTL"} # fmt: skip lines = [f"{instructions:,} instructions, CPU cycles {first}..{last}"] lines.append( "writes: " + ", ".join(f"{names.get(a, f'${a:04X}')} {n}" for a, n in sorted(writes.items())) ) return lines def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("cart", type=Path, help="loose image or one-member zip") parser.add_argument("--seconds", type=int, default=2, help="emulated seconds") parser.add_argument("--no-trace", action="store_true", help="no debugger: frames only") parser.add_argument("--bios", choices=["default", "a"], default="a", help="MAME's two boot ROM saves; 'a' is the common lynxboot.img") # fmt: skip parser.add_argument("--snap", action="store_true", help="save a PNG of the last frame") parser.add_argument("--rompath", default=ROMPATH) parser.add_argument("--out", type=Path) parser.add_argument("--mame", default=MAME) args = parser.parse_args() cart = args.cart.resolve() stem = cart.stem.split(" (")[0].replace(" ", "_") out = (args.out or ROOT / "tests" / "mame_traces" / stem).resolve() if out.exists(): shutil.rmtree(out) out.mkdir(parents=True) image = extract(cart, out) watch = "\n".join( f"dbg:command('wpset {a:x},{n:x},w,1,{{logerror \"W %X %X %d\\\\n\",wpaddr,wpdata,totalcycles; g}}')" for a, n in WATCH ) lua = "" if args.no_trace else TRACE_LUA.format(cpu=CPU_TAG, watch=watch) # 60 screen frames a second in MAME's fixed screen; snapshot near the end. lua += STATUS_LUA.format(cpu=CPU_TAG, snap_at=(args.seconds * 59 if args.snap else 0)) (out / "trace.lua").write_text(lua, encoding="utf-8") version = subprocess.run( [args.mame, "-version"], capture_output=True, text=True, check=True ).stdout.strip() debug = [] if args.no_trace else ["-debug", "-debugger", "none"] # BLL .o files go through the quickload device, but the driver still insists on a cartridge. media = ["-quik" if image.suffix.lower() == ".o" else "-cart", image.name] began = time.monotonic() result = subprocess.run( [args.mame, "lynx", "-rompath", args.rompath, "-bios", args.bios, *media, "-homepath", str(out), "-snapshot_directory", "snap", "-video", "none", "-sound", "none", "-nothrottle", "-noreadconfig", "-skip_gameinfo", *debug, "-log", "-seconds_to_run", str(args.seconds), "-autoboot_script", str(out / "trace.lua")], cwd=out, check=False, capture_output=True, text=True, ) # fmt: skip wall = time.monotonic() - began if result.returncode: print(result.stdout[-2000:], result.stderr[-2000:], file=sys.stderr) return result.returncode frames = (out / "frames.txt").read_text(encoding="utf-8").splitlines() report = [ f"MAME {version}, lynx -bios {args.bios}, {image.name}, {args.seconds} s emulated in {wall:.1f} s", f"{len(frames)} screen frames", ] if not args.no_trace: report += summarize(out / "error.log") (out / "summary.txt").write_text("\n".join(report) + "\n", encoding="utf-8") print("\n".join(report)) print(f"log: {out / 'error.log'}") return 0 if __name__ == "__main__": sys.exit(main())