#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Run MAME's CD-i headless as a closed-box detector: I/O access census, trace, screenshot. MAME is a closed box here: the binary is run, its source is never read. For --frames frames this taps every SCC68070 read and write outside DRAM and ROM (the window 0x300000-0x3FFFFF and the MCD212's registers at 0x4FFFE0-0x4FFFFF), counts them per 256-byte block, logs the first --limit writes, optionally runs the debugger's instruction trace for --trace-frames frames starting at --trace-at, and saves a screenshot. MAME_ROMPATH=... python -I scripts/mame_run.py --frames 600 MAME_ROMPATH=... python -I scripts/mame_run.py --frames 600 --trace-at 500 --trace-frames 50 Everything lands in tests/mame_traces/ (git-ignored): io.log, blocks.txt, trace.log, snap//0000.png, error.log. The firmware comes from $MAME_ROMPATH, by SHA-1 (docs/bios-and-models.md). One MAME process at a time. """ from __future__ import annotations import argparse import os import re import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] RUNS = ROOT / "tests" / "mame_traces" LUA = """ cpu = manager.machine.devices[":maincpu"] space = cpu.spaces["program"] log = io.open("io.log", "w") blocks = {{}} writes = 0 reads = 0 function count(kind, offset) local key = string.format("%s %06X", kind, offset & 0xFFFF00) blocks[key] = (blocks[key] or 0) + 1 end wtap1 = space:install_write_tap(0x300000, 0x3fffff, "iow", function(offset, data, mask) writes = writes + 1 count("W", offset) if writes <= {limit} then log:write(string.format("%.9f W %06X %04X %04X\\n", manager.machine.time:as_double(), offset, data, mask)) end end) wtap2 = space:install_write_tap(0x4fffe0, 0x4fffff, "vdscw", function(offset, data, mask) writes = writes + 1 count("W", offset) if writes <= {limit} then log:write(string.format("%.9f W %06X %04X %04X\\n", manager.machine.time:as_double(), offset, data, mask)) end end) rtap1 = space:install_read_tap(0x300000, 0x3fffff, "ior", function(offset, data, mask) reads = reads + 1 count("R", offset) end) rtap2 = space:install_read_tap(0x4fffe0, 0x4fffff, "vdscr", function(offset, data, mask) reads = reads + 1 count("R", offset) end) frames = 0 dbg = manager.machine.debugger sub = emu.add_machine_frame_notifier(function() frames = frames + 1 if dbg and frames == {trace_at} then print(string.format("TRACE_START %.9f", manager.machine.time:as_double())) dbg:command("trace trace.log,:maincpu") end if dbg and frames == {trace_end} then dbg:command("trace off,:maincpu") print(string.format("TRACE_END %.9f", manager.machine.time:as_double())) end if frames == {frames} then log:close() local out = io.open("blocks.txt", "w") local keys = {{}} for k in pairs(blocks) do keys[#keys + 1] = k end table.sort(keys) for _, k in ipairs(keys) do out:write(string.format("%s %d\\n", k, blocks[k])) end out:close() manager.machine.video:snapshot() print("ACCESSES " .. reads .. " reads " .. writes .. " writes " .. frames .. " frames") manager.machine:exit() end end) """ def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--machine", default="cdimono1") parser.add_argument("--bios", default="mcdi200") parser.add_argument("--frames", type=int, default=300) parser.add_argument("--limit", type=int, default=100_000, help="most writes logged") parser.add_argument("--trace-at", type=int, default=0, help="frame to start the trace (0: none)") parser.add_argument("--trace-frames", type=int, default=50) parser.add_argument("--cdrom", type=Path, help="a .cue or .chd to mount (optional)") parser.add_argument("--mame", default="mame") args = parser.parse_args() rompath = os.environ.get("MAME_ROMPATH") if not rompath: print("set MAME_ROMPATH", file=sys.stderr) return 2 RUNS.mkdir(parents=True, exist_ok=True) trace_at = args.trace_at or -1 script = RUNS / "run.lua" script.write_text(LUA.format(limit=args.limit, frames=args.frames, trace_at=trace_at, trace_end=trace_at + args.trace_frames), encoding="utf-8") command = [ "nice", args.mame, args.machine, "-bios", args.bios, "-rompath", rompath, "-video", "none", "-sound", "none", "-nothrottle", "-noreadconfig", "-skip_gameinfo", "-snapshot_directory", "snap", "-nvram_directory", "nvram", "-cfg_directory", "cfg", "-autoboot_script", str(script), "-seconds_to_run", str(args.frames // 50 + 5), ] if args.trace_at: command[2:2] = ["-debug", "-debugger", "none"] if args.cdrom: command += ["-cdrom", str(args.cdrom.resolve())] result = subprocess.run(command, cwd=RUNS, capture_output=True, text=True, check=False) lines = [line for line in result.stdout.splitlines() if line.startswith("ACCESSES")] if not lines: print(result.stdout[-2000:], result.stderr[-2000:], sep="\n", file=sys.stderr) return 1 print(lines[0], "->", RUNS) for line in result.stdout.splitlines(): if line.startswith("TRACE_"): print(line) trace = RUNS / "trace.log" if args.trace_at and trace.exists(): # MAME's trace collapses a repeating loop into "(loops for N instructions)". listed = collapsed = 0 with trace.open(encoding="latin-1") as handle: for line in handle: if re.match(r"[0-9A-F]{8}:", line): listed += 1 elif match := re.search(r"loops for (\d+) instructions", line): collapsed += int(match.group(1)) print(f"trace: {listed} listed + {collapsed} collapsed = {listed + collapsed} " f"instructions over {args.trace_frames} frames -> {trace}") snaps = sorted((RUNS / "snap" / args.machine).glob("*.png")) if snaps: print("screenshot", snaps[-1]) return 0 if __name__ == "__main__": sys.exit(main())