# SPDX-License-Identifier: MIT """Trace MAME 0.285's Signetics 2650 headless, as a closed-box detector (docs/mame-oracle.md). python -I scripts/mame_trace.py --cart "$NO_INTRO_DIR/Interton - VC 4000/Golf (Europe).zip" python -I scripts/mame_trace.py --driver arcadia --cart "$NO_INTRO_DIR/Emerson - Arcadia 2001/Escape (USA, Europe).zip" python -I scripts/mame_trace.py --driver elektor # the TVGC monitor ROM, no cartridge Runs a short trace (default 3 frames) and writes reference/mame/-/: run.log with one line per instruction ("S pc ps r0 r1 r2 r3 totalcycles", ps = PSU<<8 | PSL, the registers as MAME shows them for the selected bank), disasm.txt (MAME's own trace file: one disassembled line per instruction) and summary.txt: the mnemonics executed, with counts, and the cycles each instruction took (from totalcycles deltas, in clock periods). The summary is what a core's first rungs use to choose test cases. MAME is a detector, never a judge. Its 2650 files are BSD-3-Clause; none is fetched or read here. """ from __future__ import annotations import argparse import collections import os import re import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] FIELDS = "pc,ps,r0,r1,r2,r3" def lua(frames: int) -> str: fmt = " ".join(["S"] + ["%X"] * len(FIELDS.split(",")) + ["%d"]) return "\n".join([ "local dbg = manager.machine.debugger", 'dbg.visible_cpu = manager.machine.devices[":maincpu"]', f"dbg:command('trace disasm.txt,:maincpu,noloop,{{logerror \"{fmt}\\\\n\",{FIELDS},totalcycles}}')", 'dbg:command("go")', "count = 0", "notifier = emu.add_machine_frame_notifier(function()", " count = count + 1", f" if count == {frames} then manager.machine:exit() end", "end)", ]) + "\n" # fmt: skip def summarise(out: Path) -> str: mnemonics = collections.Counter() disasm = out / "disasm.txt" if disasm.exists(): for line in disasm.read_text(encoding="utf-8", errors="replace").splitlines(): match = re.match(r"\s*(?:[0-9A-Fa-f]+:)?[0-9A-Fa-f]+:\s+(\S+)", line) if match: mnemonics[match.group(1).split(",")[0].lower()] += 1 cycles = collections.Counter() last = None for line in (out / "run.log").read_text(encoding="utf-8", errors="replace").splitlines(): if line.startswith("S "): total = int(line.split()[-1]) if last is not None: cycles[total - last] += 1 last = total lines = [f"instructions: {sum(cycles.values()) + 1}", "clock periods per instruction: " + ", ".join(f"{k}: {v}" for k, v in sorted(cycles.items())), f"distinct mnemonics: {len(mnemonics)}"] # fmt: skip lines += [f" {name:8} {count}" for name, count in mnemonics.most_common()] return "\n".join(lines) + "\n" def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--driver", default="vc4000", help="vc4000, arcadia, elektor, or a clone") parser.add_argument("--cart", help="a cartridge image or zip (not for elektor)") parser.add_argument("--frames", type=int, default=3) parser.add_argument("--rompath", default=os.environ.get("MAME_ROMPATH", "")) parser.add_argument("--mame", default="mame") args = parser.parse_args() if not args.cart and args.driver != "elektor": print("a cartridge is required (--cart, e.g. from $NO_INTRO_DIR)", file=sys.stderr) return 2 stem = re.sub(r"[^A-Za-z0-9]+", "_", Path(args.cart).stem)[:24] if args.cart else "nocart" out = ROOT / "reference" / "mame" / f"{args.driver}-{stem}" out.mkdir(parents=True, exist_ok=True) (out / "run.lua").write_text(lua(args.frames), encoding="utf-8") command = [ args.mame, args.driver, "-homepath", str(out), "-video", "none", "-sound", "none", "-nothrottle", "-noreadconfig", "-skip_gameinfo", "-log", "-debug", "-debugger", "none", "-seconds_to_run", str(args.frames // 50 + 5), "-autoboot_script", str(out / "run.lua"), ] # fmt: skip if args.rompath: command += ["-rompath", args.rompath] if args.cart: command += ["-cart", args.cart] result = subprocess.run(["nice", *command], cwd=out, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) # fmt: skip (out / "stdout.txt").write_text(result.stdout, encoding="utf-8") if (out / "error.log").exists(): (out / "error.log").replace(out / "run.log") (out / "summary.txt").write_text(summarise(out), encoding="utf-8") print(f"exit {result.returncode}; output in {out.relative_to(ROOT)}") return result.returncode if __name__ == "__main__": sys.exit(main())