#!/usr/bin/env python3 """Record MAME 0.285's per-instruction Z80 trace and I/O log for the ColecoVision. Runs the recipe of docs/mame-oracle.md in a fresh directory (default ``tests/mame_traces/-``, gitignored) and leaves ``error.log`` there. The ``coleco`` driver needs the 8K BIOS (``coleco.zip``, ``colecop.zip`` for PAL): ``--rompath`` points at the MAME sets, read in place. A ``.zip``/``.7z`` cartridge is extracted into the run directory with ``7z``. python -I scripts/mame_trace.py coleco --seconds 2 # no cartridge: the BIOS alone python -I scripts/mame_trace.py coleco CART.zip --seconds 3 python -I scripts/mame_trace.py colecop CART.zip --seconds 3 --no-trace # snapshot only python -I scripts/mame_trace.py coleco CART.rom --exp sgm # with the Super Game Module ``error.log`` then holds, in execution order: - ``PC AF BC DE HL IX IY SP AF' I R totalcycles beamy beamx``: one line per instruction, before it executes (hex; the last three decimal). A ``logerror`` action silently logs nothing with more than 14 values (found by sms-python), so BC', DE', HL', IFF1/2 and IM are left out; - ``IW port data totalcycles`` and ``IR port data totalcycles``: every I/O write and read (the port is the low 8 bits of the address); - MAME's own ``logerror`` lines from the devices, if any. ``totalcycles`` counts Z80 clocks (3.579545 MHz); MAME's ``coleco`` driver adds one clock to every M1 cycle (``z80_set_m1_cycles(4+1)``) and holds the CPU through the SN76489A's READY. """ from __future__ import annotations import argparse import os import shutil import subprocess import sys import time from pathlib import Path ROOT = Path(__file__).resolve().parents[1] MAME = "/usr/games/mame" ROMPATH = os.environ.get("MAME_ROMPATH") DRIVERS = { "coleco": "ColecoVision (NTSC), TMS9928A", "colecop": "ColecoVision (PAL), TMS9929A", } IMAGE = {".col", ".rom", ".bin"} TRACE_LUA = """\ local dbg = manager.machine.debugger dbg.visible_cpu = manager.machine.devices[":maincpu"] dbg:command('trace z80.trace,,noloop,{logerror "%X %X %X %X %X %X %X %X %X %X %X %d %d %d\\\\n",\ pc,af,bc,de,hl,ix,iy,sp,af2,i,r,totalcycles,beamy,beamx}') dbg:command('wpiset 0,100,w,1,{logerror "IW %X %X %d\\\\n",wpaddr&0xff,wpdata,totalcycles; g}') dbg:command('wpiset 0,100,r,1,{logerror "IR %X %X %d\\\\n",wpaddr&0xff,wpdata,totalcycles; g}') dbg:command("go") """ def extract(cart: Path, out: Path) -> Path: """The image inside a .zip/.7z, extracted into ``out``; a plain image is copied.""" if cart.suffix.lower() not in {".zip", ".7z"}: target = out / cart.name shutil.copyfile(cart, target) return target subprocess.run(["7z", "e", "-y", f"-o{out}", str(cart)], check=True, stdout=subprocess.DEVNULL) found = [p for p in out.iterdir() if p.suffix.lower() in IMAGE] if len(found) != 1: raise SystemExit(f"expected one image in {cart.name}, found {[p.name for p in found]}") return found[0] def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("driver", choices=sorted(DRIVERS)) parser.add_argument("cart", type=Path, nargs="?", help="image, or a .zip/.7z holding one") parser.add_argument("--seconds", type=int, default=2, help="emulated seconds (an integer)") parser.add_argument("--no-trace", action="store_true", help="no debugger: a snapshot only") parser.add_argument("--exp", choices=["sgm"], help="expansion port device") parser.add_argument("--rompath", default=ROMPATH) parser.add_argument("--out", type=Path) parser.add_argument("--mame", default=MAME) args = parser.parse_args() if not args.rompath: raise SystemExit("set MAME_ROMPATH to the MAME (non-merged) ROM folder, or pass --rompath") stem = "nocart" if args.cart: stem = args.cart.resolve().stem.split(" (")[0].replace(" ", "_") out = (args.out or ROOT / "tests" / "mame_traces" / f"{args.driver}-{stem}").resolve() if out.exists(): raise SystemExit(f"{out} exists: move it aside or pass --out (a run never overwrites)") out.mkdir(parents=True) command = [args.mame, args.driver] if args.cart: command += ["-cart", extract(args.cart.resolve(), out).name] if args.exp: command += ["-exp", args.exp] command += [ "-rompath", args.rompath, "-homepath", str(out), "-snapshot_directory", "snap", "-video", "none", "-sound", "none", "-nothrottle", "-noreadconfig", "-skip_gameinfo", "-log", "-seconds_to_run", str(args.seconds), ] # fmt: skip if not args.no_trace: (out / "trace.lua").write_text(TRACE_LUA, encoding="utf-8") command += ["-debug", "-debugger", "none", "-autoboot_script", str(out / "trace.lua")] version = subprocess.run([args.mame, "-version"], capture_output=True, text=True).stdout.strip() began = time.monotonic() # error.log lands in the working directory, not under -homepath. subprocess.run(command, cwd=out, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) wall = time.monotonic() - began counts = {"instructions": 0, "IW": 0, "IR": 0} log = out / "error.log" if log.exists(): with log.open("rb") as handle: for line in handle: if line.startswith(b"IW "): counts["IW"] += 1 elif line.startswith(b"IR "): counts["IR"] += 1 elif line.count(b" ") == 13: counts["instructions"] += 1 print(f"MAME {version}, {args.driver}, {args.seconds} s emulated in {wall:.1f} s: {log}") if not args.no_trace: print( f" {counts['instructions']:,} instructions, {counts['IW']:,} I/O writes, {counts['IR']:,} I/O reads" ) return 0 if __name__ == "__main__": sys.exit(main())