#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Record MAME 0.285's per-instruction trace of one of its CMOS 65C02 devices. MAME has one device per variant row of this core (docs/mame-oracle.md), and a driver that needs no media exists for each: row MAME device driver (default media: none) WDC65C02 "WDC W65C02" apple2ee Apple //e enhanced WDC65C02S "WDC W65C02S" (see docs/mame-oracle.md) R65C02 "Rockwell R65C02" cexpert Fidelity Chess Expert G65SC02 "GTE G65SC02" lynx Atari Lynx (needs lynx.zip; a cart is optional) G65SC12 "GTE G65SC12" bbcm BBC Master python -I scripts/mame_trace.py lynx python -I scripts/mame_trace.py lynx --cart game.lnx --seconds 5 python -I scripts/mame_trace.py apple2ee --seconds 2 The run happens in a fresh directory (default ``tests/mame_traces/``, gitignored) and leaves ``error.log`` there: one line per instruction, before it executes, all hex except the last: ``PC A X Y S P totalcycles``. ``totalcycles`` is the CPU device's own count of CPU cycles (not Lynx ticks: MAME's lynx driver runs the G65SC02 at a flat 4 MHz). ROM sets are read in place (never copied) from ``--rompath`` or, by default, the ``MAME_ROMPATH`` environment variable (a merged MAME ROM set); the script stops if neither is given. The MAME binary is ``--mame``, else ``$MAME``, else ``mame`` on PATH. A cart is passed by its own path. MAME is an emulator: this is a detector, never a judge. """ from __future__ import annotations import argparse import os import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] MAME = os.environ.get("MAME", "mame") ROMPATH = os.environ.get("MAME_ROMPATH") # The debugger command runs from Lua because -debugscript is read before the # machine's devices exist under -debugger none (the family's recipe, from # huc6280-python/scripts/mame_trace.py). ``noloop`` stops MAME folding repeated # loops into "(loops for N instructions)" lines. 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\\\\n",pc,a,x,y,sp,p,totalcycles}') dbg:command("go") """ # --bus: also log every access of the CPU's program space, ``R address data`` or # ``W address data`` (hex), between the instruction lines. The replay of rung 5 # (tests/mame_replay.py) feeds the core's reads from them and compares its # writes with them, so that no machine has to be modelled. The taps must stay # in globals or they are garbage-collected (huc6280-python's recipe). BUS_LUA = """\ local space = manager.machine.devices[":maincpu"].spaces["program"] local log = manager.machine bus_read_tap = space:install_read_tap(0x0000, 0xFFFF, "bus_r", function(offset, data, mask) log:logerror(string.format("R %X %X\\n", offset, data)) end) bus_write_tap = space:install_write_tap(0x0000, 0xFFFF, "bus_w", function(offset, data, mask) log:logerror(string.format("W %X %X\\n", offset, data)) end) """ def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("driver", help="lynx, apple2ee, cexpert, bbcm, ...") parser.add_argument("--cart", type=Path, help="a cartridge image, read in place") parser.add_argument("--seconds", type=int, default=2, help="emulated seconds") parser.add_argument("--bus", action="store_true", help="also log every bus access") parser.add_argument("--out", type=Path) parser.add_argument("--mame", default=MAME) parser.add_argument("--rompath", default=ROMPATH) args = parser.parse_args() if not args.rompath: raise SystemExit( "MAME_ROMPATH is not set: point it at a merged MAME ROM set, or pass --rompath" ) out = (args.out or ROOT / "tests" / "mame_traces" / args.driver).resolve() out.mkdir(parents=True, exist_ok=True) lua = (BUS_LUA if args.bus else "") + TRACE_LUA (out / "trace.lua").write_text(lua, encoding="utf-8") version = subprocess.run( [args.mame, "-version"], capture_output=True, text=True, check=True ).stdout.strip() media = ["-cart", str(args.cart.resolve())] if args.cart else [] command = [ args.mame, args.driver, *media, "-rompath", args.rompath, "-homepath", str(out), "-video", "none", "-sound", "none", "-nothrottle", "-noreadconfig", "-skip_gameinfo", "-debug", "-debugger", "none", "-log", "-seconds_to_run", str(args.seconds), "-autoboot_script", str(out / "trace.lua"), ] # fmt: skip result = subprocess.run(command, cwd=out, capture_output=True, text=True, check=False) log = out / "error.log" if result.returncode or not log.exists(): print(result.stdout[-2000:], result.stderr[-2000:], file=sys.stderr) return 1 instructions = accesses = 0 first = [] with log.open(encoding="utf-8", errors="replace") as handle: for line in handle: fields = line.split() if len(fields) == 7 and not line.startswith("["): instructions += 1 if len(first) < 12: first.append(line.rstrip()) elif len(fields) == 4 and fields[1] in ("R", "W"): accesses += 1 print( f"MAME {version}, driver {args.driver}: {instructions:,} instruction lines, " f"{accesses:,} bus accesses in {log}" ) for line in first: print(" " + line) return 0 if instructions else 1 if __name__ == "__main__": sys.exit(main())