# SPDX-License-Identifier: MIT """Run MAME 0.285 headless on an MSX machine as a closed-box detector (docs/mame-oracle.md). MAME_ROMPATH=... python -I scripts/mame_trace.py cf2700 --seconds 3 MAME_ROMPATH=... python -I scripts/mame_trace.py cf2700 --cart CART.zip --seconds 5 MAME_ROMPATH=... python -I scripts/mame_trace.py hb75p --seconds 4 --no-trace # snapshot only Each run gets a fresh directory under reference/mame/ (git-ignored; a run never overwrites one). With the trace on, MAME's `error.log` holds, in order: - `PC OP AF BC DE HL IX IY SP I R totalcycles beamy beamx`: one line per instruction, before it executes (OP is the byte at PC; hex, the last three decimal; `logerror` drops lines with more than 14 values); - `IW port data totalcycles` / `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 its devices. `totalcycles` counts Z80 clocks at 3.579545 MHz. The summary printed at the end gives the instruction count, the I/O counts per port, and the clock deltas of the commonest single-byte opcodes (so the M1 wait MAME applies can be read off the trace, not off its source, which this repository never opens). A cartridge zip is extracted into the run directory; nothing outside reference/ is written. MAME is a tier-5 detector: what it does is a reading to compare against, never a verdict. """ from __future__ import annotations import argparse import collections import os import subprocess import sys import time import zipfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] 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,b@pc,af,bc,de,hl,ix,iy,sp,i,r,totalcycles,beamy,beamx}') dbg:command('wpiset 0,10000,w,1,{logerror "IW %X %X %d\\\\n",wpaddr&0xff,wpdata,totalcycles; g}') dbg:command('wpiset 0,10000,r,1,{logerror "IR %X %X %d\\\\n",wpaddr&0xff,wpdata,totalcycles; g}') dbg:command("go") """ def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("machine", help="a MAME msx/ machine name (scripts/census.py mame lists them)") parser.add_argument("--cart", type=Path, help="a cartridge image, or a .zip holding one (slot 1)") parser.add_argument("--seconds", type=int, default=3, help="emulated seconds (an integer)") parser.add_argument("--no-trace", action="store_true", help="no debugger: a snapshot only") parser.add_argument("--mame", default="mame") args = parser.parse_args() rompath = os.environ.get("MAME_ROMPATH") if not rompath: sys.exit("set MAME_ROMPATH (see README.md)") stem = args.cart.stem.split(" (")[0].replace(" ", "_") if args.cart else "nocart" out = ROOT / "reference" / "mame" / f"{args.machine}-{stem}-{args.seconds}s" if out.exists(): sys.exit(f"{out.relative_to(ROOT)} exists: move it aside first (a run never overwrites)") out.mkdir(parents=True) command = [args.mame, args.machine] if args.cart: image = args.cart if image.suffix.lower() == ".zip": with zipfile.ZipFile(image) as archive: members = [m for m in archive.namelist() if not m.endswith("/")] if len(members) != 1: sys.exit(f"expected one image in {image.name}, found {members}") target = out / Path(members[0]).name target.write_bytes(archive.read(members[0])) image = target command += ["-cart1", str(image)] command += [ "-rompath", 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, check=False).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 print(f"MAME {version}, {args.machine}, {args.seconds} s emulated in {wall:.1f} s wall: " f"{out.relative_to(ROOT)}") # fmt: skip log = out / "error.log" if args.no_trace or not log.exists(): return 0 instructions = 0 ports = collections.Counter() deltas: dict[int, collections.Counter] = collections.defaultdict(collections.Counter) previous: tuple[int, int] | None = None # (opcode, totalcycles) of the last instruction with log.open("rb") as handle: for raw in handle: fields = raw.split() if fields[:1] in ([b"IW"], [b"IR"]) and len(fields) == 4: ports[(fields[0].decode(), int(fields[1], 16))] += 1 previous = None # an I/O line inside an instruction: skip that delta continue if len(fields) != 14: continue instructions += 1 pc, cycles = int(fields[1], 16), int(fields[11]) # keyed by opcode byte if previous is not None: deltas[previous[0]][cycles - previous[1]] += 1 previous = (pc, cycles) print(f" {instructions:,} instructions; I/O per port: " + ", ".join(f"{k[0]} {k[1]:02X}h={v:,}" for k, v in sorted(ports.items()))) # fmt: skip (out / "summary.txt").write_text( f"instructions {instructions}\n" + "".join(f"{k[0]} {k[1]:02X} {v}\n" for k, v in sorted(ports.items())), encoding="utf-8", ) # Clock deltas per first opcode byte (the instruction just run): NOP (00) shows the M1 wait. for opcode in (0x00, 0x3E, 0x7E, 0x23, 0xD3, 0xDB, 0xED, 0xDD, 0xCB, 0x10, 0x18, 0x20): if opcode in deltas: print(f" opcode {opcode:02X}: clock deltas {dict(deltas[opcode].most_common(4))}") return 0 if __name__ == "__main__": sys.exit(main())