#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Trace MAME 0.285's SM8500-family CPU in its Game.com driver; tabulate opcodes and cycles. MAME is an emulator (tier 5): this is a detector, never a judge. Its CPU files (``src/devices/cpu/sm8500/*``) are BSD-3-Clause by their ``license:`` lines and are still **not opened** (docs/validation.md, decision 2); only the binary runs. The run happens in a fresh directory (default ``tests/mame_traces/gamecom-``, gitignored) and leaves ``error.log`` with one line per instruction, before it executes: ``PC OPCODE PS SP totalcycles`` (hex except the last). The summary printed: - instructions, cycles, cycles per instruction, distinct first opcode bytes executed; - per first opcode byte: executions and MAME's cycle delta to the next instruction (min / most common / max). Deltas include interrupt entries and MAME's own model of the instruction timing; they are what MAME says, nothing more. MAME_ROMPATH=... python -I scripts/mame_trace.py --seconds 2 # the BIOS alone MAME_ROMPATH=... python -I scripts/mame_trace.py --cart "" --seconds 3 python -I scripts/mame_trace.py --reuse --cart "" # summarise again The BIOS (gamecom.zip: internal.bin, external.bin) is read in place from MAME_ROMPATH. """ from __future__ import annotations import argparse import os import subprocess import sys from collections import Counter, defaultdict from pathlib import Path ROOT = Path(__file__).resolve().parents[1] MAME = os.environ.get("MAME", "mame") LUA = """\ local dbg = manager.machine.debugger dbg.visible_cpu = manager.machine.devices[":maincpu"] dbg:command('trace cpu.trace,,noloop,{logerror "%X %X %X %X %d\\\\n",pc,b@pc,ps,sp,totalcycles}') dbg:command("go") """ def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--cart", type=Path, help="a cartridge zip or .tgc for slot 1, read in place") parser.add_argument("--seconds", type=int, default=2, 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") parser.add_argument("--table", type=Path, help="write the per-opcode table here") args = parser.parse_args() rompath = os.environ.get("MAME_ROMPATH") if not rompath and not args.reuse: raise SystemExit("MAME_ROMPATH is not set (the Game.com BIOS is read from gamecom.zip there)") stem = "".join(c if c.isalnum() else "_" for c in args.cart.stem)[:40] if args.cart else "bios" out = (args.out or ROOT / "tests" / "mame_traces" / f"gamecom-{stem}").resolve() out.mkdir(parents=True, exist_ok=True) log = out / "error.log" if not (args.reuse and log.exists()): (out / "trace.lua").write_text(LUA, encoding="utf-8") media = ["-cart1", str(args.cart.resolve())] if args.cart else [] command = [ args.mame, "gamecom", *media, "-rompath", rompath, "-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 result = subprocess.run(command, cwd=out, capture_output=True, text=True, check=False) if result.returncode or not log.exists(): print(result.stdout[-2000:], result.stderr[-2000:], file=sys.stderr) return 1 counts: Counter[int] = Counter() deltas: dict[int, Counter[int]] = defaultdict(Counter) first_line = None previous = None first_cycle = last_cycle = 0 with log.open(encoding="utf-8", errors="replace") as handle: for line in handle: fields = line.split() if len(fields) != 5 or line.startswith("["): continue try: opcode, cycles = int(fields[1], 16), int(fields[4]) int(fields[0], 16) except ValueError: continue if first_line is None: first_line, first_cycle = line.strip(), cycles counts[opcode] += 1 if previous is not None: deltas[previous[0]][cycles - previous[1]] += 1 previous = (opcode, cycles) last_cycle = cycles instructions = sum(counts.values()) if not instructions: print("no instruction lines", file=sys.stderr) return 1 span = last_cycle - first_cycle version = subprocess.run([args.mame, "-version"], capture_output=True, text=True).stdout.strip() print(f"MAME {version}, gamecom, cart {args.cart.name if args.cart else '(none: BIOS only)'}, {args.seconds} s") print(f"first line: {first_line}") print(f"instructions {instructions:,}; cycles {span:,}; cycles/instruction {span / instructions:.3f}") print(f"distinct first opcode bytes executed: {len(counts)} of 256") rows = [] for opcode in sorted(counts): spread = deltas.get(opcode, Counter()) if spread: common = spread.most_common(1)[0][0] rows.append(f"{opcode:02X} {counts[opcode]:>10,} {min(spread):>4} {common:>4} {max(spread):>5}") else: rows.append(f"{opcode:02X} {counts[opcode]:>10,} - - -") table = "op executions min mode max\n" + "\n".join(rows) + "\n" if args.table: args.table.write_text(table, encoding="utf-8") print(f"per-opcode table: {args.table}") print("top opcodes: " + ", ".join(f"{op:02X} x{n:,}" for op, n in counts.most_common(10))) return 0 if __name__ == "__main__": sys.exit(main())