#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Record MAME 0.285's per-instruction 6502 trace and chip-register log for a 5200 cartridge. Runs the recipe in docs/mame-oracle.md in a fresh directory (default ``tests/mame_traces/-``, gitignored) and leaves ``error.log`` there. The BIOS is read in place from the MAME set directory (``--rompath``, default ``$MAME_ROMPATH``); the cartridge may be a loose image, a No-Intro zip or a 7z (its one member is extracted into the output directory, never next to the set). python scripts/mame_trace.py a5200 "$NO_INTRO_DIR/Atari - Atari 5200/Pac-Man (USA).zip" python scripts/mame_trace.py a5200a path/to/cart.a52 --seconds 5 python scripts/mame_trace.py a5200 path/to/cart.zip --no-trace --seconds 30 ``error.log`` then holds, in execution order: - one line per instruction, before it executes: ``PC A X Y P SP totalcycles VCOUNT`` (hex, cycles decimal). P is MAME's internal P (bits 4 and 5 read 1): mask with $CF before comparing. SP carries the page ($1xx). VCOUNT is ANTIC's $D40B read through the debugger (no side effects): the scan line divided by two; - ``W addr value totalcycles`` for every CPU write to GTIA ($C000-$C0FF), ANTIC ($D400-$D4FF) and POKEY ($E800-$E8FF, $EB00-$EBFF), and ``R addr value totalcycles`` for every CPU read of POKEY and of GTIA. ``totalcycles`` counts CPU cycles only as MAME's m6502 sees them: see docs/mame-oracle.md for how MAME accounts ANTIC's stolen cycles, which is the reason this trace is an instruction-order detector and not a cycle judge. A ``[luaengine] F`` line marks each MAME screen frame; ``frames.txt`` gets the machine time of each; ``summary.txt`` the counts and the histogram of CPU cycles between frame marks. """ from __future__ import annotations import argparse import collections import itertools import shutil import subprocess import sys import time import zipfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "scripts")) from romsets import mame_hashpath, mame_program, mame_rompath # noqa: E402 # MAME's machine names (its -listfull): a5200 = BIOS CO19156 (4-port), a5200a = CO19156A. DRIVERS = {"a5200": "4-port BIOS", "a5200a": "rev A BIOS"} CPU_TAG = ":maincpu" # A logerror action silently drops lines past 14 values (found on the Z80 # boards); 8 here. b@ reads in debugger expressions have side effects disabled. 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 %X\\\\n",\ pc,a,x,y,p,sp,totalcycles,b@d40b}}') dbg:command('wpset c000,100,w,1,{{logerror "W %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}}') dbg:command('wpset c000,100,r,1,{{logerror "R %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}}') dbg:command('wpset d400,100,w,1,{{logerror "W %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}}') dbg:command('wpset e800,100,w,1,{{logerror "W %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}}') dbg:command('wpset e800,100,r,1,{{logerror "R %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}}') dbg:command('wpset eb00,100,w,1,{{logerror "W %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}}') dbg:command('wpset eb00,100,r,1,{{logerror "R %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}}') dbg:command("go") """ # Notifier subscriptions are unsubscribed when garbage-collected: keep them in # globals. A Lua device has no totalcycles, so the frame mark goes into # error.log itself (machine:logerror) and takes its cycle from the # instruction line that follows it. FRAMES_LUA = """\ local log = io.open("frames.txt", "w") status_sub = emu.add_machine_frame_notifier(function() manager.machine:logerror("F\\n") log:write(string.format("F %s\\n", tostring(manager.machine.time))) log:flush() end) """ def extract(cart: Path, out: Path) -> Path: suffix = cart.suffix.lower() if suffix == ".zip": 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 if suffix == ".7z": subprocess.run( ["7z", "e", "-y", f"-o{out}", str(cart)], check=True, stdout=subprocess.DEVNULL ) found = [p for p in out.iterdir() if p.suffix.lower() in (".a52", ".bin", ".rom", ".car")] if len(found) != 1: raise SystemExit(f"{cart}: expected one image, found {len(found)}") return found[0] dest = out / cart.name shutil.copyfile(cart, dest) return dest def summarize(log: Path) -> list[str]: instructions = 0 frame_cycles: list[int] = [] mark = False counts: collections.Counter[str] = collections.Counter() first_cart_pc = None nmien = [] wsync = 0 with log.open("rb") as f: for raw in f: parts = raw.split() if not parts: continue if parts[-1] == b"F" and len(parts) <= 2: # "[luaengine] F" mark = True continue if parts[0] in (b"R", b"W") and len(parts) == 4: address, value = int(parts[1], 16), int(parts[2], 16) chip = {0xC0: "GTIA", 0xD4: "ANTIC", 0xE8: "POKEY", 0xEB: "POKEY"}[address >> 8] counts[f"{chip} {parts[0].decode()}"] += 1 if chip == "ANTIC" and parts[0] == b"W": if address & 0xF == 0xA: wsync += 1 if address & 0xF == 0xE: nmien.append((value, int(parts[3]))) continue if len(parts) == 8: try: pc = int(parts[0], 16) except ValueError: continue instructions += 1 if mark: frame_cycles.append(int(parts[6])) mark = False if first_cart_pc is None and 0x4000 <= pc < 0xC000: first_cart_pc = (pc, int(parts[6]), instructions) deltas = collections.Counter(b - a for a, b in itertools.pairwise(frame_cycles)) lines = [ f"{instructions:,} instructions", f"CPU cycles between frame marks: {deltas.most_common(6)}", ] lines.append("register accesses: " + ", ".join(f"{k} {v:,}" for k, v in sorted(counts.items()))) lines.append(f"WSYNC writes: {wsync:,}; NMIEN writes (value, cycle): {nmien[:6]}") if first_cart_pc: pc, cycle, n = first_cart_pc lines.append(f"first instruction in the cartridge: ${pc:04X} at cycle {cycle:,} (#{n:,})") else: lines.append("the program never reached the cartridge") return lines 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, help="loose image, one-member zip or 7z") 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("--snapshot", type=int, metavar="FRAME", help="save that frame as a PNG") parser.add_argument("--rompath", help="directory holding a5200.zip (default $MAME_ROMPATH)") parser.add_argument("--out", type=Path) parser.add_argument("--mame", default=mame_program(), help="default $MAME, else mame on PATH") args = parser.parse_args() args.rompath = args.rompath or str(mame_rompath()) cart = args.cart.resolve() stem = cart.stem.split(" (")[0].replace(" ", "_") out = (args.out or ROOT / "tests" / "mame_traces" / f"{args.driver}-{stem}").resolve() if out.exists(): shutil.rmtree(out) out.mkdir(parents=True) image = extract(cart, out) lua = "" if args.no_trace else TRACE_LUA.format(cpu=CPU_TAG) lua += FRAMES_LUA.format(cpu=CPU_TAG) if args.snapshot: # MAME also writes one more PNG as it exits; with -video none the # frames still render (checked: the BIOS logo at frame 150). lua += ( "local snap_n = 0\n" "snap_sub = emu.add_machine_frame_notifier(function()\n" " snap_n = snap_n + 1\n" f" if snap_n == {args.snapshot} then manager.machine.video:snapshot() end\n" "end)\n" ) (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"] began = time.monotonic() # error.log lands in the working directory, not under -homepath. result = subprocess.run( [args.mame, args.driver, "-rompath", args.rompath, "-cart", image.name, # -noreadconfig drops the system hashpath; without a5200.hsi MAME maps # every loose 16K image as one chip (Pac-Man then shows a black screen). "-hashpath", str(mame_hashpath()), "-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 + result.stderr) return result.returncode frames = (out / "frames.txt").read_text(encoding="utf-8").splitlines() report = [ f"MAME {version}, {args.driver}, {image.name}, {args.seconds} s emulated in {wall:.1f} s", f"{len(frames)} 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())