#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Run MAME 0.285's Atari Portfolio driver headless and summarise what the CPU does. MAME is an emulator (tier 5): this is a detector, never a judge. Its Portfolio files (``atari/pofo.cpp``, ``video/hd61830.cpp``, ``sound/pcd3311.cpp``, ``bus/pofo/*``) carry ``license:BSD-3-Clause`` lines (read through the first 200 bytes only, 2026-11-26) and are treated as closed boxes all the same (docs/validation.md, open decision 2). The run happens in a fresh directory (default ``tests/mame_traces/``, git-ignored) and leaves: - ``cpu.trace``: MAME's own per-instruction trace (disassembly); - ``error.log``: per instruction ``CS IP OPCODE AX FLAGS totalcycles`` (hex except the last), plus ``IOR port data`` / ``IOW port data`` for every CPU I/O access (Lua taps on the whole 16-bit I/O space) and ``HLT`` counts. Printed: instructions, cycles, cycles per instruction, the distinct I/O ports read and written with counts (the ASIC's register map as the BIOS uses it, OBSERVED from MAME), the share of time at HLT, and the most common opcodes. MAME_ROMPATH=... python -I scripts/mame_trace.py --seconds 4 MAME_ROMPATH=... python -I scripts/mame_trace.py --driver pofo2 --seconds 4 The firmware is read in place from MAME_ROMPATH (MAME opens the zips itself). Nothing is copied. One MAME process at a time (the family's rule): wrap the call in ``flock`` when other agents may run MAME. """ 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 machine = manager.machine local cpu = machine.devices[":u1"] local iospace = cpu.spaces["io"] io_read_tap = iospace:install_read_tap(0x0000, 0xFFFF, "io_r", function(offset, data, mask) machine:logerror(string.format("IOR %X %X %X\\n", offset, data, mask)) end) io_write_tap = iospace:install_write_tap(0x0000, 0xFFFF, "io_w", function(offset, data, mask) machine:logerror(string.format("IOW %X %X %X\\n", offset, data, mask)) end) local dbg = machine.debugger dbg.visible_cpu = cpu dbg:command('trace cpu.trace,,noloop,{logerror "%X %X %X %X %X %d\\\\n",cs,ip,b@curpc,ax,curflags,totalcycles}') dbg:command("go") """ def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--driver", default="pofo", help="pofo (DIP DOS 1.072) or pofo2 (1.680)") parser.add_argument("--seconds", type=int, default=4, 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", "") out = (args.out or ROOT / "tests" / "mame_traces" / args.driver).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, *(["-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() reads: Counter[int] = Counter() writes: Counter[int] = Counter() write_values: dict[int, Counter[int]] = {} 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) == 4 and fields[0] in ("IOR", "IOW"): port, data = int(fields[1], 16), int(fields[2], 16) if fields[0] == "IOR": reads[port] += 1 else: writes[port] += 1 write_values.setdefault(port, Counter())[data] += 1 elif len(fields) == 6 and not line.startswith("["): try: opcode, cycles = int(fields[2], 16), int(fields[5]) except ValueError: continue opcodes[opcode] += 1 first_line = first_line or line.strip() 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) print(f"MAME {version}, driver {args.driver}, {args.seconds} s") print(f"first trace line (CS IP opcode AX flags cycles): {first_line}") print(f"instructions {instructions:,}; cycles {span:,}; cycles/instruction {span / instructions:.3f}") print(f"HLT ($F4) executed x{opcodes[0xF4]}; distinct opcodes {len(opcodes)}") print("I/O ports read (port x count): " + ", ".join(f"{p:04X}x{n}" for p, n in sorted(reads.items()))) print("I/O ports written (port x count [values]): " + ", ".join( f"{p:04X}x{n} [{' '.join(f'{v:02X}' for v in sorted(write_values[p])[:8])}{' ...' if len(write_values[p]) > 8 else ''}]" for p, n in sorted(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())