#!/usr/bin/env python3 """Record MAME 0.285's per-instruction Z80 trace and I/O log for a cartridge. Runs the recipe in docs/mame-oracle.md in a fresh directory (default ``tests/mame_traces/-``, gitignored) and leaves ``error.log`` there. The BIOS sets are read in place through ``-rompath``; nothing is copied. python scripts/mame_trace.py sms tests/test_roms/.../VDPTEST.sms --seconds 12 python scripts/mame_trace.py sg1000 "$SG/Flicky (Japan) (Rev 1).zip" (``$SG`` being your No-Intro SG-1000 folder, ``romsets.py``.) ``error.log`` then holds, in execution order: - one line per instruction, before it executes: ``PC AF BC DE HL IX IY SP AF' I R totalcycles beamy beamx`` (hex, then decimal; see docs/mame-oracle.md for why BC' DE' HL' are absent); - ``IW port value totalcycles`` for every I/O write and ``IR port value totalcycles`` for every I/O read, where totalcycles is that of the instruction doing the access (MAME stamps the instruction start, not the bus cycle). """ from __future__ import annotations import argparse import os import shutil import subprocess import sys import zipfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) sys.path.insert(0, str(ROOT / "scripts")) from mame_media import cart_arguments # noqa: E402 from sms_python.cartridge import load_image # noqa: E402 MAME = "/usr/games/mame" ROMPATH = os.environ.get("MAME_ROMPATH", "roms") # scripts/romsets.py CART_SUFFIXES = (".sms", ".sg", ".gg", ".sc", ".bin") # The Z80's device tag differs by driver: sg1000.cpp names it ":z80", sms.cpp ":maincpu". CPU_TAG = { "sg1000": ":z80", "sg1000m3": ":z80", "sc3000": ":z80", "sms": ":maincpu", "sms1": ":maincpu", "smspal": ":maincpu", "sms1pal": ":maincpu", "smsj": ":maincpu", "sms1kr": ":maincpu", "gamegear": ":maincpu", "gamegeaj": ":maincpu", } # A logerror action silently stops logging past 14 values, and the watchpoints # only survive the BIOS's $3E remap while an instruction trace is active; both # found 2026-09-18 and recorded in docs/mame-oracle.md. TRACE_LUA = """\ local dbg = manager.machine.debugger dbg.visible_cpu = manager.machine.devices["{tag}"] 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,wpdata,totalcycles; g}}') dbg:command('wpiset 0,100,r,1,{{logerror "IR %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}}') dbg:command("go") -- MAME's Game Gear blends each frame with the last ("LCD Persistence Hack"); -- off, so the exit snapshot is the frame the VDP drew (as compat_sweep.py). local port = manager.machine.ioport.ports[":PERSISTENCE"] if port then port.fields["LCD Persistence Hack"].user_value = 0 end """ def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("driver", choices=sorted(CPU_TAG)) parser.add_argument( "cart", type=Path, help="cartridge image (.sg/.sms/.gg or a zip holding one)" ) 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("--rompath", default=ROMPATH) args = parser.parse_args() cart = args.cart.resolve() out = (args.out or ROOT / "tests" / "mame_traces" / f"{args.driver}-{cart.stem}").resolve() if out.exists(): shutil.rmtree(out) out.mkdir(parents=True) if zipfile.is_zipfile(cart): # MAME loads the *first* member of a zip, which for test-program archives is # often a data file (SMSVDPTest's is a compressed charset). Extract the image. with zipfile.ZipFile(cart) as archive: names = archive.namelist() member = min( (n for n in names if n.lower().endswith(CART_SUFFIXES)), key=lambda n: CART_SUFFIXES.index("." + n.lower().rsplit(".", 1)[-1]), ) cart = out / Path(member).name cart.write_bytes(archive.read(member)) else: shutil.copyfile(cart, out / cart.name) cart = out / cart.name # lockstep_mame.py finds the image next to the log; MAME gets it by its # software-list name where it has one (mame_media.py). media = cart_arguments(load_image(cart), args.driver, out, cart, args.rompath) (out / "trace.lua").write_text(TRACE_LUA.format(tag=CPU_TAG[args.driver]), encoding="utf-8") version = subprocess.run( [args.mame, "-version"], capture_output=True, text=True, check=True ).stdout.strip() # error.log lands in the working directory, not under -homepath. subprocess.run( [args.mame, args.driver, *media, "-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")], cwd=out, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) # fmt: skip instructions = io_events = 0 with (out / "error.log").open("rb") as log: for line in log: if line.startswith((b"IW ", b"IR ")): io_events += 1 elif line[:1].isalnum() and line.count(b" ") == 13: instructions += 1 print(f"MAME {version}: {out / 'error.log'} ({instructions:,} instructions, {io_events:,} I/O)") return 0 if instructions else 1 if __name__ == "__main__": sys.exit(main())