#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Record MAME 0.285's per-instruction 6507 trace and TIA/RIOT register log for a 2600 cartridge. Runs the recipe in docs/mame-oracle.md in a fresh directory (default ``tests/mame_traces/-``, gitignored) and leaves ``error.log`` there. The a2600 drivers need no BIOS. ``cart`` may be a loose image or a No-Intro zip (its one member is extracted into the output directory; the ROM sets themselves are never copied into the repo). python scripts/mame_trace.py a2600 "$NO_INTRO_DIR/Atari - Atari 2600/Combat (USA, Europe) (Atari Anthology).zip" python scripts/mame_trace.py a2600 path/to/pitfall.a26 --seconds 5 python scripts/mame_trace.py a2600p "path/to/Adventure (Europe).zip" --no-trace --seconds 30 python scripts/mame_trace.py a2600 "path/to/Kaboom! (USA).zip" --left pad --slot a26_2k_4k ``error.log`` then holds, in execution order: - one line per instruction, before it executes: ``PC A X Y P SP totalcycles INTIM TIMINT`` (hex, then decimal cycles, then hex). P is MAME's internal P: bits 4 (B) and 5 always read 1, so mask with $CF before comparing. SP carries the page ($1xx). PC is the 13-bit-masked address only if the program jumped there: a cart linked at $F000 traces as $Fxxx. INTIM ($0284) and TIMINT ($0285) are read through the debugger, which disables side effects, so logging them clears no flag; - ``R addr value totalcycles`` / ``W addr value totalcycles`` for every CPU access to TIA $00-$7F (zero-page mirror only), RIOT I/O $280-$29F, and the bankswitch hotspots $1FE0-$1FFF. Accesses through other mirrors (e.g. $0100+) are not logged; ``frames.txt`` gets the cart slot device MAME picked and ``F frame_cycles`` once per MAME screen frame (the TIA's own frame origin, see below). TIA beam position: MAME's TIA has no beam counter. It derives the beam from the CPU clock: ``x = 3*((totalcycles - frame_cycles) % 76) - 68``, ``y = (totalcycles - frame_cycles) // 76``, where ``frame_cycles`` is re-anchored to the start of the current line whenever VSYNC's D1 rises (src/mame/atari/tia.cpp current_x/current_y, VSYNC_w). The debugger's ``beamx``/``beamy``/``frame`` belong to MAME's free-running 228x262 screen and do not follow VSYNC, so they are not logged. ``summary.txt`` gets the detected cart slot device, the VSYNC-to-VSYNC cycle deltas and the WSYNC stall histogram computed from the log. """ 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] MAME = shutil.which("mame") or "mame" # the MAME 0.285 binary on PATH (--mame to choose) # src/mame/atari/a2600.cpp: a2600 = NTSC (3.579575 MHz in the source, sic), # a2600p = PAL. Both are cart consoles; the SECAM TIA is not modelled. DRIVERS = { "a2600": "6507 @ xtal/3, TIA NTSC, 262-line screen", "a2600p": "6507 @ xtal/3, TIA PAL, 312-line screen", } CPU_TAG = ":maincpu" # A logerror action silently drops lines past 14 values (found on the Z80 # boards); 9 here. b@ reads in debugger expressions have side effects # disabled, so INTIM/TIMINT can be sampled every instruction. 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 %X\\\\n",\ pc,a,x,y,p,sp,totalcycles,b@284,b@285}}') dbg:command('wpset 0,80,r,1,{{logerror "R %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}}') dbg:command('wpset 0,80,w,1,{{logerror "W %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}}') dbg:command('wpset 280,20,r,1,{{logerror "R %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}}') dbg:command('wpset 280,20,w,1,{{logerror "W %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}}') dbg:command('wpset 1fe0,20,r,1,{{logerror "R %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}}') dbg:command('wpset 1fe0,20,w,1,{{logerror "W %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}}') dbg:command("go") """ # Notifier subscriptions are unsubscribed when garbage-collected: keep them in # globals. The TIA's frame origin is a save-state item, readable from Lua. STATUS_LUA = """\ local slot = "?" for tag, _ in pairs(manager.machine.devices) do if tag:find("^:cartslot:[^:]+$") then slot = tag:sub(11) end end local log = io.open("frames.txt", "w") log:write("slot " .. slot .. "\\n") local items = manager.machine.devices[":tia_video"].items local fc = emu.item(items["0/frame_cycles"]) status_sub = emu.add_machine_frame_notifier(function() log:write(string.format("F %d\\n", fc:read(0))) log:flush() 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 reads = writes = 0 vsync_starts = [] wsync_gaps = collections.Counter() prev = None # (pc, cycles) of the previous instruction line pending_wsync = None vsync_on = False with log.open("rb") as f: for raw in f: parts = raw.split() if not parts: continue if parts[0] in (b"R", b"W") and len(parts) == 4: addr, value, cyc = int(parts[1], 16), int(parts[2], 16), int(parts[3]) if parts[0] == b"R": reads += 1 continue writes += 1 reg = addr & 0x3F if addr < 0x80 else None if reg == 0x00: on = bool(value & 2) if on and not vsync_on: vsync_starts.append(cyc) vsync_on = on elif reg == 0x02: pending_wsync = cyc continue if len(parts) == 9 and parts[0] != b"F": instructions += 1 cyc = int(parts[6]) if pending_wsync is not None and prev is not None: # cycles from the STA WSYNC instruction's start to the next # instruction's start wsync_gaps[(cyc - prev[1], (cyc) % 76)] += 1 pending_wsync = None prev = (int(parts[0], 16), cyc) deltas = [b - a for a, b in itertools.pairwise(vsync_starts)] lines = [ f"{instructions:,} instructions, {reads:,} logged reads, {writes:,} logged writes", f"VSYNC starts: {len(vsync_starts)}; deltas (cycles): {collections.Counter(deltas).most_common(6)}", " = lines: " + ", ".join(f"{d / 76:g}" for d, _ in collections.Counter(deltas).most_common(6)), "WSYNC (instruction length incl. stall, next-instruction cycle mod 76): " + str(wsync_gaps.most_common(8)), ] 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 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( "--slot", help="force the cart slot device (e.g. a26_f8, a26_e0; mame a2600 -listslots)" ) parser.add_argument("--left", help="left controller (joy, pad, keypad, wheel, trakball, ...)") parser.add_argument("--right", help="right controller") 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" / 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 += STATUS_LUA.format(cpu=CPU_TAG) (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"] # -cartslot overrides the heuristic; -joyportN swaps the controller. extra = [] for flag, value in ( ("-cartslot", args.slot), ("-joyport1", args.left), ("-joyport2", args.right), ): if value: extra += [flag, value] began = time.monotonic() # error.log lands in the working directory, not under -homepath. A loose # -cart file is typed by MAME's heuristics (bus/vcs/vcs_slot.cpp # identify_cart_type), not by the a2600 software list. subprocess.run( [args.mame, args.driver, *extra, "-cart", image.name, "-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=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) # fmt: skip wall = time.monotonic() - began 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"cart slot device: {frames[0].split()[1] if frames else '?'}", ] 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())