#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Run MAME 0.285's Mega Duck driver headless and summarise what the CPU executes and writes. MAME is an emulator (tier 5): a detector, never a judge. Its Mega Duck files (the driver ``nintendo/gb.cpp``, ``bus/gameboy/mdslot.cpp``, ``rom.cpp``, ``video/gb_lcd.cpp``, ``sound/gb.cpp``) are BSD-3-Clause by their ``license:`` lines, but this repository treats MAME as a closed box (the Phase 0 brief): their bodies are not opened. The run happens in a fresh directory (default ``tests/mame_traces/-``, git-ignored) and leaves ``error.log`` with: - per instruction ``PC SP totalcycles`` (hex except the last; MAME's expression parser reads ``a``-``f``, ``af``, ``bc``, ``de`` as hex numbers, not the LR35902's registers, so only PC and SP are logged: found 2026-11-26), and - ``IOW address data`` for every CPU write to FF00-FFFF and ``BANKW address data`` for every write to 0000-7FFF and B000 (the cartridge's bank registers), by Lua write taps. The summary: instructions, cycles, cycles per instruction, the I/O registers written (so the Mega Duck's relocated registers show), and the bank writes. MAME_ROMPATH=... python -I scripts/mame_trace.py --cart "$NO_INTRO_DIR/Welback - Mega Duck/" --seconds 3 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(0xFF00, 0xFFFF, "io_w", function(offset, data, mask) machine:logerror(string.format("IOW %X %X\\n", offset, data)) end) bank_write_tap = space:install_write_tap(0x0000, 0x7FFF, "bank_w", function(offset, data, mask) machine:logerror(string.format("BANKW %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 %d\\\\n",pc,sp,totalcycles}') dbg:command("go") """ def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--driver", default="megaduck", help="megaduck or mduckspa") 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 instructions = 0 mnemonics: Counter[str] = Counter() io_writes: Counter[int] = Counter() bank_writes: Counter[tuple[int, int]] = Counter() first_pc = None 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) == 3 and fields[0] == "BANKW": bank_writes[(int(fields[1], 16), int(fields[2], 16))] += 1 elif len(fields) == 3 and not line.startswith("["): cycles = int(fields[2]) instructions += 1 if first_pc is None: first_pc = fields first_cycle = cycles if first_cycle is None else first_cycle last_cycle = cycles trace = out / "cpu.trace" if trace.exists(): with trace.open(encoding="utf-8", errors="replace") as handle: for line in handle: parts = line.split(":", 1) if len(parts) == 2 and parts[1].split(): mnemonics[parts[1].split()[0]] += 1 if not instructions: print("no instruction lines", file=sys.stderr) return 1 span = (last_cycle or 0) - (first_cycle or 0) print(f"MAME {version}, driver {args.driver}, cart {args.cart.name}, {args.seconds} s") print(f"first trace line: {' '.join(first_pc or [])}") print(f"instructions {instructions:,}; cycles {span:,}; cycles/instruction {span / instructions:.3f}") print(f"halt x{mnemonics['halt']}, stop x{mnemonics['stop']} (from MAME's disassembly trace)") print("I/O registers written (address x count): " + ", ".join(f"{a:04X}x{n}" for a, n in sorted(io_writes.items()))) print("cartridge-space writes (address=value x count): " + (", ".join(f"{a:04X}={v:02X}x{n}" for (a, v), n in sorted(bank_writes.items())) or "none")) return 0 if __name__ == "__main__": sys.exit(main())