#!/usr/bin/env python3 """Run one CPS-2 set on MAME 0.285 headless and record what docs/mame-oracle.md describes. Leaves, in ``tests/mame_traces//`` (git-ignored): - ``error.log``: MAME's own log (the ``cps2 decrypt key,key,lower,upper`` line the driver prints) and, unless ``--no-trace``, one line per 68000 instruction:: C curpc sr opcode-as-fetched word-as-data d0 d1 a0 a7 totalcycles beamy beamx frame ``opcode-as-fetched`` is read from the 68000's *opcodes* space (decrypted), ``word-as-data`` from its *program* space (what a data read of the same address returns: the ROM as dumped). ``curpc``, not ``pc``: on MAME's 68000 ``pc`` is already past the first word. - ``z80.trace`` with ``--z80 --no-trace`` (one CPU's action trace per run): one line per Z80 instruction, ``Z pc sp af bc de hl|`` followed by MAME's disassembly. The Z80 is held in reset until the 68000 releases it, so ask for 2-3 seconds. 2 s of ``spf2t`` = 874,738 lines, about 35 s of wall time (measured 2026-11-12). - ``console.txt``: the debugger console after the setup commands (errors show here and nowhere else). - ``devices.txt``: every device that has CPU state, its address spaces and its register symbols, written by the Lua script. - ``opcodes.bin`` / ``program.bin`` with ``--dump N``: the first N bytes of the 68000's opcodes space and program space (big-endian, as the CPU sees them): the decrypted and the encrypted image of the same addresses. The set is read in place from the MAME non-merged tree; nothing is copied. python -I scripts/mame_trace.py spf2t --seconds 2 python -I scripts/mame_trace.py spf2tu --no-trace --dump 0x100000 --seconds 1 python -I scripts/mame_trace.py spf2t --no-trace --z80 --seconds 2 """ from __future__ import annotations import argparse import os import subprocess import sys import time from pathlib import Path ROOT = Path(__file__).resolve().parents[1] MAME = "/usr/games/mame" ROMPATH = os.environ.get("MAME_ROMPATH") DEVICES_LUA = """\ local out = io.open("devices.txt", "w") for tag, dev in pairs(manager.machine.devices) do local ok, state = pcall(function() return dev.state end) if ok and state then local names = {} for name, _ in pairs(state) do names[#names + 1] = name end table.sort(names) if #names > 0 then local spaces = {} for name, space in pairs(dev.spaces) do spaces[#spaces + 1] = string.format("%s(mask %X, %s-bit data)", name, space.address_mask or 0, tostring(space.data_width)) end table.sort(spaces) out:write(tag, " [", dev.shortname, "]\\n spaces: ", table.concat(spaces, ", "), "\\n state: ", table.concat(names, " "), "\\n") end end end out:close() local dbg = manager.machine.debugger dbg.visible_cpu = manager.machine.devices[":maincpu"] """ CONSOLE_LUA = """\ local console = io.open("console.txt", "w") for _, line in ipairs(dbg.consolelog) do console:write(line, "\\n") end console:close() """ TRACE_68K = ( "dbg:command('trace cpu.trace,:maincpu,noloop," '{logerror "C %X %X %X %X %X %X %X %X %d %d %d %d\\\\n",' "curpc,sr,ow@curpc,w@curpc,d0,d1,a0,sp,totalcycles,beamy,beamx,frame}')\n" ) # A trace action is evaluated with the symbols of the CPU that is *visible* # while the machine runs, not of the traced CPU: with :maincpu visible, ``hl`` # is undefined and the Z80 action silently does nothing (the cause of the # 2026-11-11 failure; switching back to :maincpu before ``go`` breaks it again, # measured 2026-11-12). So one CPU's action trace per run. ``af``, ``bc``, # ``de`` resolve as registers, not hex numbers, once :audiocpu is visible. TRACE_Z80 = ( 'dbg.visible_cpu = manager.machine.devices[":audiocpu"]\n' "dbg:command('trace z80.trace,:audiocpu,noloop," '{tracelog "Z %X %X %X %X %X %X|",pc,sp,af,bc,de,hl}\')\n' ) def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("set", help="a MAME CPS-2 set name, for example spf2t") parser.add_argument("--seconds", type=int, default=2, help="emulated seconds") parser.add_argument("--no-trace", action="store_true") parser.add_argument("--z80", action="store_true", help="also trace the Z80") parser.add_argument("--dump", type=lambda s: int(s, 0), default=0, metavar="BYTES") parser.add_argument("--rompath", default=ROMPATH) parser.add_argument("--mame", default=MAME) args = parser.parse_args() if not args.rompath: raise SystemExit("set MAME_ROMPATH to the MAME (non-merged) ROM folder, or pass --rompath") if args.z80 and not args.no_trace: parser.error("--z80 needs --no-trace: one CPU's action trace per run (see TRACE_Z80)") out = ROOT / "tests" / "mame_traces" / args.set out.mkdir(parents=True, exist_ok=True) lua = DEVICES_LUA if args.dump: lua += f"dbg:command('saveo opcodes.bin,0,{args.dump:x}')\n" lua += f"dbg:command('save program.bin,0,{args.dump:x}')\n" if not args.no_trace: lua += TRACE_68K if args.z80: lua += TRACE_Z80 lua += CONSOLE_LUA + 'dbg:command("go")\n' (out / "trace.lua").write_text(lua, encoding="utf-8") version = subprocess.run( [args.mame, "-version"], capture_output=True, text=True, check=True ).stdout.strip() began = time.monotonic() # error.log lands in the working directory. result = subprocess.run( [args.mame, args.set, "-rompath", args.rompath, "-homepath", str(out), "-cfg_directory", "cfg", "-nvram_directory", "nvram", "-snapshot_directory", "snap", "-video", "none", "-sound", "none", "-nothrottle", "-noreadconfig", "-skip_gameinfo", "-debug", "-debugger", "none", "-log", "-seconds_to_run", str(args.seconds), "-autoboot_script", "trace.lua"], cwd=out, check=False, capture_output=True, text=True, ) # fmt: skip wall = time.monotonic() - began if result.returncode: print(result.stderr[-2000:]) return result.returncode counts = {"C": 0, "Z": 0} decrypt = "" with (out / "error.log").open(encoding="utf-8", errors="replace") as log: for line in log: if line[:2] in ("C ", "Z "): counts[line[0]] += 1 elif "cps2 decrypt" in line: decrypt = line.strip() if args.z80 and (out / "z80.trace").exists(): with (out / "z80.trace").open(encoding="utf-8", errors="replace") as trace: counts["Z"] = sum(line.startswith("Z ") for line in trace) print(f"MAME {version}, {args.set}, {args.seconds} s emulated in {wall:.1f} s: {out}") print(f" {decrypt}") print(f" {counts['C']:,} 68000 instructions, {counts['Z']:,} Z80 instructions") return 0 if __name__ == "__main__": sys.exit(main())