#!/usr/bin/env python3 """Run a CPS-3 set headless on MAME and record what the oracle recipe needs. Writes into ``tests/runs//`` (git-ignored): - ``symbols.txt``: the main CPU's tag, its debugger register symbols with their reset values, the address spaces, and the device list; - ``trace.log``: one line per instruction for the first ``--trace-seconds`` of emulated time: the word at PC in the opcode space (decrypted) and in the program space (as the data bus reads it), R0, R15, PR, SR, then MAME's disassembly; - ``state.txt``: PC, SR and the PPU/DMA-facing state sampled once per emulated second until ``--seconds``; - ``final.png``: the last frame; ``error.log``: MAME's own log. MAME is run with -video none, so the snapshot is rendered by the software snapshot path only. One MAME process, a few emulated seconds: see docs/mame-oracle.md for the traps. python -I scripts/mame_trace.py redearthnr1 --seconds 4 --trace-seconds 0.02 """ from __future__ import annotations import argparse import os import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] # MAME's non-merged sets and its (merged) CHDs, from the environment. ROMPATH = ";".join(p for p in (os.environ.get("MAME_ROMPATH"), os.environ.get("MAME_CHDS")) if p) LUA = r""" local out = "%(out)s" local cpu = manager.machine.devices[":maincpu"] local dbg = manager.machine.debugger local f = io.open(out .. "/symbols.txt", "w") f:write("cpu tag: " .. cpu.tag .. " shortname: " .. cpu.shortname .. "\n") f:write("clock: " .. tostring(cpu.clock) .. "\n") for name, space in pairs(cpu.spaces) do f:write("space: " .. name .. "\n") end local names = {} for name, entry in pairs(cpu.state) do names[#names + 1] = name end table.sort(names) for _, name in ipairs(names) do f:write(string.format("state %%-10s = %%X\n", name, cpu.state[name].value)) end for tag, dev in pairs(manager.machine.devices) do f:write("device " .. tag .. " (" .. dev.shortname .. ")\n") end f:close() dbg.visible_cpu = cpu dbg:command('trace ' .. out .. '/trace.log,,noloop,{tracelog "%%04X %%04X R0=%%08X R15=%%08X PR=%%08X SR=%%08X ",ow@pc,pw@pc,r0,r15,pr,sr}') tracing = true next_sample = 1.0 state_file = io.open(out .. "/state.txt", "w") prog = cpu.spaces["program"] function cps3_tick() local now = manager.machine.time:as_double() if tracing and now >= %(trace_seconds)f then dbg:command("trace off") tracing = false end if now >= next_sample then state_file:write(string.format("t=%%.3f frame=%%d pc=%%08X sr=%%08X dma_status=%%04X\n", now, manager.machine.screens[":screen"]:frame_number(), cpu.state["PC"].value, cpu.state["SR"].value, prog:read_u16(0x040c000c))) next_sample = next_sample + 1.0 end if now >= %(seconds)f then state_file:close() manager.machine.video:snapshot() manager.machine:exit() end end cps3_sub = emu.add_machine_frame_notifier(cps3_tick) dbg:command("go") """ def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("set", help="a MAME set name, e.g. redearthnr1, sfiii") parser.add_argument("--seconds", type=float, default=4.0, help="emulated seconds to run") parser.add_argument("--trace-seconds", type=float, default=0.02, help="emulated seconds traced") parser.add_argument("--rompath", default=ROMPATH) args = parser.parse_args() if not args.rompath: raise SystemExit("set MAME_ROMPATH to the MAME (non-merged) ROM folder, or pass --rompath") out = ROOT / "tests" / "runs" / args.set out.mkdir(parents=True, exist_ok=True) script = out / "trace.lua" script.write_text( LUA % {"out": str(out), "seconds": args.seconds, "trace_seconds": args.trace_seconds}, encoding="utf-8", ) command = [ "mame", args.set, "-rompath", args.rompath, "-video", "none", "-sound", "none", "-nothrottle", "-noreadconfig", "-skip_gameinfo", "-debug", "-debugger", "none", "-log", "-nvram_directory", str(out / "nvram"), "-cfg_directory", str(out / "cfg"), "-snapshot_directory", str(out / "snap"), "-snapname", "final", "-autoboot_script", str(script), "-seconds_to_run", str(int(args.seconds) + 30), ] done = subprocess.run(command, cwd=out, capture_output=True, text=True, check=False, timeout=900) sys.stdout.write(done.stdout[-2000:]) sys.stderr.write(done.stderr[-2000:]) for name in ("symbols.txt", "trace.log", "state.txt", "error.log"): path = out / name print(f"{name}: {path.stat().st_size if path.exists() else 'MISSING'}") return done.returncode if __name__ == "__main__": sys.exit(main())