#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Run MAME 0.285's Supervision driver headless and summarise what the CPU executes. MAME is an emulator (tier 5): this is a detector, never a judge, and its source (svision.cpp, svis_snd.cpp: GPL-2.0+) is never opened. The run happens in a fresh directory (default ``tests/mame_traces/-``, gitignored) and leaves: - ``cpu.trace``: MAME's own per-instruction trace (disassembly), and - ``error.log``: per instruction ``PC OPCODE A X Y SP P totalcycles`` (hex except the last), plus ``IOW address data`` for every CPU write to 2000-20FF (a Lua write tap). The summary printed: instructions, cycles, cycles per instruction, the opcodes that matter for choosing the 65C02 row (the bit instructions $x7/$xF, WAI $CB, STP $DB), and the I/O registers written. MAME_ROMPATH=... python -I scripts/mame_trace.py --cart "" --seconds 3 python -I scripts/mame_trace.py --driver svisionn --cart "" --seconds 2 The cart is read in place (MAME opens the zip itself). Nothing is copied. """ from __future__ import annotations import argparse import os import subprocess import sys from collections import Counter from pathlib import Path ROOT = Path(__file__).resolve().parents[1] MAME = os.environ.get("MAME", "mame") LUA = """\ local space = manager.machine.devices[":maincpu"].spaces["program"] local machine = manager.machine io_write_tap = space:install_write_tap(0x2000, 0x20FF, "io_w", function(offset, data, mask) machine:logerror(string.format("IOW %X %X\\n", offset, data)) end) 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 %X %d\\\\n",pc,b@pc,a,x,y,sp,p,totalcycles}') dbg:command("go") """ def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--driver", default="svision", help="svision, svisions, svisionn, svisionp, tvlinkp") parser.add_argument("--cart", type=Path, required=True, help="a cartridge image or its zip, read in place") parser.add_argument("--seconds", type=int, default=3, help="emulated seconds") parser.add_argument("--out", type=Path) parser.add_argument("--mame", default=MAME) parser.add_argument("--reuse", action="store_true", help="summarise an existing run's error.log") args = parser.parse_args() rompath = os.environ.get("MAME_ROMPATH", "") stem = "".join(c if c.isalnum() else "_" for c in args.cart.stem)[:40] out = (args.out or ROOT / "tests" / "mame_traces" / f"{args.driver}-{stem}").resolve() out.mkdir(parents=True, exist_ok=True) (out / "trace.lua").write_text(LUA, encoding="utf-8") version = subprocess.run([args.mame, "-version"], capture_output=True, text=True, check=True).stdout.strip() command = [ args.mame, args.driver, "-cart", str(args.cart.resolve()), *(["-rompath", rompath] if rompath else []), "-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 log = out / "error.log" result = None if not (args.reuse and log.exists()): result = subprocess.run(command, cwd=out, capture_output=True, text=True, check=False) if (result and result.returncode) or not log.exists(): if result: print(result.stdout[-2000:], result.stderr[-2000:], file=sys.stderr) return 1 opcodes: Counter[int] = Counter() io_writes: Counter[int] = Counter() first_cycle = last_cycle = None with log.open(encoding="utf-8", errors="replace") as handle: for line in handle: fields = line.split() if fields[:1] == ["[luaengine]"]: fields = fields[1:] if len(fields) == 3 and fields[0] == "IOW": io_writes[int(fields[1], 16)] += 1 elif len(fields) == 8 and not line.startswith("["): opcode, cycles = int(fields[1], 16), int(fields[7]) opcodes[opcode] += 1 first_cycle = cycles if first_cycle is None else first_cycle last_cycle = cycles instructions = sum(opcodes.values()) if not instructions: print("no instruction lines", file=sys.stderr) return 1 span = (last_cycle or 0) - (first_cycle or 0) bit_ops = {op: n for op, n in opcodes.items() if op & 0x0F in (0x07, 0x0F)} print(f"MAME {version}, driver {args.driver}, cart {args.cart.name}, {args.seconds} s") print(f"instructions {instructions:,}; cycles {span:,}; cycles/instruction {span / instructions:.3f}") print(f"distinct opcodes executed: {len(opcodes)}") print("bit-instruction opcodes ($x7/$xF) executed: " + (", ".join(f"${op:02X} x{n}" for op, n in sorted(bit_ops.items())) or "none")) print(f"WAI ($CB) x{opcodes[0xCB]}, STP ($DB) x{opcodes[0xDB]}") print("I/O registers written (address x count): " + ", ".join(f"{a:04X}x{n}" for a, n in sorted(io_writes.items()))) print("top opcodes: " + ", ".join(f"${op:02X} x{n}" for op, n in opcodes.most_common(12))) return 0 if __name__ == "__main__": sys.exit(main())