# SPDX-License-Identifier: MIT """Trace the Dreamcast's SH-4 (MAME 0.285's SH7091) headless: a closed-box detector. python -I scripts/mame_trace.py --start 0 --frames 3 # from reset python -I scripts/mame_trace.py --start 1000 --frames 3 # a window in the boot ROM's menu MAME runs the `dc` driver with no disc (the boot ROM shows its swirl, then its Set Date/Time screen on an empty flash and NVRAM). From frame --start for --frames frames every SH-4 instruction is logged as "S pc sr pr r15 totalcycles"; the run then prints a summary (instructions, MAME's cycles, cycles per instruction, distinct PCs, the PCs that cover 90 % of the window) and writes it to summary.txt beside the log. Output goes to reference/mame/-f/ (git-ignored); MAME's disassembly file is moved to trash/ (never deleted). docs/mame-oracle.md says what the figures can and cannot decide. Traps: -nodrc is required (the SH-4 recompiler bypasses the trace); one traced frame is about 130 MB of log and about a minute of wall time on a loaded machine; MAME's SH-4 charges its own cycle counts (no dual issue modelled that we could see), so its cycles are a detector's, never the chip's. """ from __future__ import annotations import argparse import collections import os import shutil import subprocess import sys import time from pathlib import Path ROOT = Path(__file__).resolve().parents[1] def lua(start: int, frames: int) -> str: trace = ("dbg:command('trace S.trace,:maincpu,noloop," '{logerror "S %X %X %X %X %d\\\\n",pc,sr,pr,r15,totalcycles}\')') # fmt: skip return "\n".join([ "dbg = manager.machine.debugger", 'dbg.visible_cpu = manager.machine.devices[":maincpu"]', trace if start == 0 else "", 'dbg:command("go")', "count = 0", "notifier = emu.add_machine_frame_notifier(function()", " count = count + 1", f" if count == {start} then {trace} end" if start else "", f" if count == {start + frames} then manager.machine:exit() end", "end)", ]) + "\n" # fmt: skip def summarise(log: Path) -> str: pcs: collections.Counter[str] = collections.Counter() first = last = None with log.open(encoding="utf-8", errors="replace") as handle: for line in handle: if not line.startswith("S "): continue fields = line.split() if len(fields) < 6: continue pcs[fields[1]] += 1 cycles = int(fields[5]) first = cycles if first is None else first last = cycles total = sum(pcs.values()) if not total: return "no traced instructions\n" covered = need = 0 for _, count in pcs.most_common(): covered += count need += 1 if covered >= 0.9 * total: break span = last - first return (f"instructions {total}\nMAME cycles {span}\ncycles per instruction {span / total:.3f}\n" f"distinct PCs {len(pcs)}\nPCs covering 90 % {need}\n" f"top PCs {pcs.most_common(8)}\n") # fmt: skip def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--driver", default="dc", help="dc, dcjp, dceu, dcdev") parser.add_argument("--start", type=int, default=0, help="frame to start tracing (0: reset)") parser.add_argument("--frames", type=int, default=3, help="frames to trace") parser.add_argument("--rompath", default=os.environ.get("MAME_ROMPATH")) parser.add_argument("--mame", default="mame") args = parser.parse_args() if not args.rompath: print("set MAME_ROMPATH (it must hold dc.zip)", file=sys.stderr) return 2 out = ROOT / "reference" / "mame" / f"{args.driver}-f{args.start}" out.mkdir(parents=True, exist_ok=True) (out / "run.lua").write_text(lua(args.start, args.frames), encoding="utf-8") command = [ args.mame, args.driver, "-rompath", args.rompath, "-homepath", str(out), "-cfg_directory", str(out / "cfg"), "-nvram_directory", str(out / "nvram"), "-video", "none", "-sound", "none", "-nothrottle", "-noreadconfig", "-skip_gameinfo", "-log", "-nodrc", "-debug", "-debugger", "none", "-seconds_to_run", str(int((args.start + args.frames) / 50) + 30), "-autoboot_script", str(out / "run.lua"), ] # fmt: skip 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") if (out / "S.trace").exists(): trash = ROOT / "trash" / time.strftime("%Y%m%d-%H%M%S") trash.mkdir(parents=True, exist_ok=True) shutil.move(str(out / "S.trace"), trash / "S.trace") summary = summarise(out / "run.log") if (out / "run.log").exists() else "no log\n" (out / "summary.txt").write_text(summary, encoding="utf-8") print(summary, end="") print(f"exit {result.returncode}; output in {out.relative_to(ROOT)}") return result.returncode if __name__ == "__main__": sys.exit(main())