#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Run MAME 0.285's Gamate driver headless and summarise what the CPU executes. MAME is an emulator (tier 5): this is a detector, never a judge. Its Gamate driver file (``bitcorp/gamate.cpp``) is GPL-2.0+ by its ``license:`` line and is never opened; the video and cartridge files are BSD-3-Clause but are treated as closed boxes too (the Phase 0 brief). 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 4000-5FFF (audio, UART, LCD) and ``CW address data`` for every write to cartridge space 6000-DFFF (protection, banking). The summary: instructions, cycles, cycles per instruction, the opcodes outside the 151 documented NMOS 6502 opcodes (which would be 65C02-only instructions or NMOS undocumented ones: the CPU-row question, docs/cpu.md), the I/O and cartridge writes. MAME_ROMPATH=... python -I scripts/mame_trace.py --cart "" --seconds 3 python -I scripts/mame_trace.py --bios newer --cart "" --seconds 2 The cart is read in place (MAME opens the zip itself); the BIOS comes from MAME's own set in ``$MAME_ROMPATH``. Nothing is copied. Run one MAME at a time (the family's rule). """ 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") # The 151 opcodes MOS documented for the NMOS 6502 (MCS6500 programming manual, appendix). NMOS_DOCUMENTED = frozenset( bytes.fromhex( "00 01 05 06 08 09 0A 0D 0E 10 11 15 16 18 19 1D 1E 20 21 24 25 26 28 29 2A 2C 2D 2E" " 30 31 35 36 38 39 3D 3E 40 41 45 46 48 49 4A 4C 4D 4E 50 51 55 56 58 59 5D 5E 60 61" " 65 66 68 69 6A 6C 6D 6E 70 71 75 76 78 79 7D 7E 81 84 85 86 88 8A 8C 8D 8E 90 91 94" " 95 96 98 99 9A 9D A0 A1 A2 A4 A5 A6 A8 A9 AA AC AD AE B0 B1 B4 B5 B6 B8 B9 BA BC BD" " BE C0 C1 C4 C5 C6 C8 C9 CA CC CD CE D0 D1 D5 D6 D8 D9 DD DE E0 E1 E4 E5 E6 E8 E9 EA" " EC ED EE F0 F1 F5 F6 F8 F9 FD FE" ) ) assert len(NMOS_DOCUMENTED) == 151 LUA = """\ local space = manager.machine.devices[":maincpu"].spaces["program"] local machine = manager.machine io_write_tap = space:install_write_tap(0x4000, 0x5FFF, "io_w", function(offset, data, mask) machine:logerror(string.format("IOW %X %X\\n", offset, data)) end) cart_write_tap = space:install_write_tap(0x6000, 0xDFFF, "cart_w", function(offset, data, mask) machine:logerror(string.format("CW %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="gamate") parser.add_argument("--bios", default="default", help="default (gamate_bios_umc.bin) or newer (gamate_bios_bit.bin)") 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.bios}-{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, "-bios", args.bios, "-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() cart_writes: Counter[int] = Counter() first_cycle = last_cycle = None first_line = 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) == 3 and fields[0] == "CW": cart_writes[int(fields[1], 16)] += 1 elif len(fields) == 8 and not line.startswith("["): try: opcode, cycles = int(fields[1], 16), int(fields[7]) except ValueError: continue first_line = first_line or line.strip() 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) outside = {op: n for op, n in opcodes.items() if op not in NMOS_DOCUMENTED} print(f"MAME {version}, driver {args.driver}, bios {args.bios}, cart {args.cart.name}, {args.seconds} s") print(f"first trace line: {first_line}") print(f"instructions {instructions:,}; cycles {span:,}; cycles/instruction {span / instructions:.3f}") print(f"distinct opcodes executed: {len(opcodes)}") print("opcodes outside the 151 documented NMOS opcodes: " + (", ".join(f"${op:02X} x{n}" for op, n in sorted(outside.items())) or "none")) print("I/O writes 4000-5FFF (address x count): " + ", ".join(f"{a:04X}x{n}" for a, n in sorted(io_writes.items()))) print("cartridge-space writes (address x count): " + ", ".join(f"{a:04X}x{n}" for a, n in sorted(cart_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())