#!/usr/bin/env python3 """Record every TMS99x8 port access MAME 0.285 makes on a ColecoVision or SG-1000. Runs a headless MAME (no per-instruction trace: only I/O watchpoints on the VDP's port block) in a fresh directory, default ``tests/mame_traces/-`` (git-ignored), and leaves there: - ``error.log``: one line per VDP port access, in order:: W R port and data in hex, the rest decimal. ``totalcycles`` is the Z80's clock count at the *start* of the instruction that made the access (MAME's watchpoint convention); ``beamy``/``beamx`` are the screen position then. Port bit 0 is the chip's MODE pin: even = data, odd = control/status. - ``vram.bin``: the chip's 16K of VRAM when the run ends, so a replay of the log can be checked against the chip's final memory as well as the picture; - ``snap//0000.png``: MAME's snapshot of the last frame; - ``summary.txt``: counts. python -I scripts/mame_vdp_log.py coleco CART.7z --seconds 5 python -I scripts/mame_vdp_log.py sg1000 CART.7z --seconds 5 Recipe and results: docs/mame-oracle.md. One MAME at a time; a few seconds. """ from __future__ import annotations import argparse import os 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") # driver: (VDP port block as MAME decodes it, the chip, the Z80's device tag). # A wrong CPU tag makes MAME 0.285 segfault on the first wpiset (found here). DRIVERS = { "coleco": ((0xA0, 0xBF), "TMS9928A", ":maincpu"), "colecop": ((0xA0, 0xBF), "TMS9929A", ":maincpu"), "sg1000": ((0x80, 0xBF), "TMS9918A", ":z80"), } IMAGE = {".col", ".rom", ".bin", ".sg"} LUA = """\ local dbg = manager.machine.debugger dbg.visible_cpu = manager.machine.devices["{cpu}"] dbg:command('wpiset {lo:X},{size:X},w,1,{{logerror "W %X %X %d %d %d\\\\n",wpaddr&0xff,wpdata,totalcycles,beamy,beamx; g}}') dbg:command('wpiset {lo:X},{size:X},r,1,{{logerror "R %X %X %d %d %d\\\\n",wpaddr&0xff,wpdata,totalcycles,beamy,beamx; g}}') dbg:command("go") vdp_device = nil for tag, device in pairs(manager.machine.devices) do if device.shortname:match("^tms9") then vdp_device = device end end stop_notifier = emu.add_machine_stop_notifier(function() local space = vdp_device.spaces["vram"] local out = io.open("{out}/vram.bin", "wb") for address = 0, 0x3FFF do out:write(string.char(space:read_u8(address))) end out:close() end) presses = {{{presses}}} press_notifier = emu.register_periodic(function() local now = manager.machine.time.seconds for _, press in ipairs(presses) do local field = manager.machine.ioport.ports[press[1]].fields[press[2]] field:set_value((now >= press[3] and now < press[3] + 0.25) and 1 or 0) end end) """ def extract(cart: Path, out: Path) -> Path: """The image inside a .zip/.7z, extracted into ``out`` (read in place otherwise).""" if cart.suffix.lower() not in {".zip", ".7z"}: return cart 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=5, help="emulated seconds (an integer)") parser.add_argument( "--press", action="append", default=[], metavar="PORT:FIELD@SECONDS", help="hold an input for 0.25 s at that emulated time, e.g. 'STD_KEYPAD1:1 (pad 1)@14'", ) # fmt: skip 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 = args.cart.resolve().stem.split(" (")[0].replace(" ", "_") if args.cart else "nocart" 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) (lo, hi), chip, cpu = DRIVERS[args.driver] lua = LUA.replace("{lo:X}", f"{lo:X}").replace("{size:X}", f"{hi - lo + 1:X}").replace("{cpu}", cpu) presses = [] for press in args.press: where, _, second = press.rpartition("@") port, _, field = where.partition(":") presses.append(f'{{":{port}", "{field}", {float(second)}}}') lua = lua.replace("{{{presses}}}", "PRESSES") lua = lua.replace("{{", "{").replace("}}", "}").replace("{out}", str(out)) lua = lua.replace("PRESSES", "{" + ", ".join(presses) + "}") (out / "vdp.lua").write_text(lua, encoding="utf-8") command = [args.mame, args.driver] if args.cart: command += ["-cart", str(extract(args.cart.resolve(), out))] 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), "-debug", "-debugger", "none", "-autoboot_script", str(out / "vdp.lua"), ] # fmt: skip 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 = {"W data": 0, "W control": 0, "R data": 0, "R status": 0} status_f = 0 for line in (out / "error.log").read_text(encoding="ascii", errors="replace").splitlines(): fields = line.split() if len(fields) != 6 or fields[0] not in {"W", "R"}: continue control = int(fields[1], 16) & 1 key = f"{fields[0]} {('control' if fields[0] == 'W' else 'status') if control else 'data'}" counts[key] += 1 if key == "R status" and int(fields[2], 16) & 0x80: status_f += 1 summary = ( f"MAME {version}, {args.driver} ({chip}), {args.cart.name if args.cart else 'no cartridge'}, " f"{args.seconds} s emulated in {wall:.1f} s wall\n" + "".join(f" {key}: {value:,}\n" for key, value in counts.items()) + f" status reads with F set: {status_f:,}\n" ) (out / "summary.txt").write_text(summary, encoding="utf-8") print(summary, end="") return 0 if __name__ == "__main__": sys.exit(main())