# SPDX-License-Identifier: MIT """Run MAME 0.285's System 1 / System 2 driver headless, as a closed-box detector. python -I scripts/mame_trace.py wboyu --frames 3 # trace the main Z80 python -I scripts/mame_trace.py wboyu --frames 3 --cpu sound # ... the sound Z80 python -I scripts/mame_trace.py choplift --frames 3 --cpu mcu # ... the 8751 python -I scripts/mame_trace.py wboyu --snap 20 # no trace: run, save a PNG python -I scripts/mame_trace.py flicky --views 0,8000 # opcode view vs data view MAME is run, never read (docs/mame-oracle.md). The romsets come from MAME_ROMPATH (non-merged sets: one zip holds the whole machine). Output goes to reference/mame/-/ (git-ignored): run.log with one line per instruction ("S pc totalcycles"), the I/O port accesses the main-CPU watchpoints log ("P r|w port data totalcycles"), snap/*.png, and for --views two summaries of how MAME's opcode space (what the CPU executes on M1 fetches) and program space (what operand and data reads see) differ over a range. --views writes only counts, never the bytes themselves. One MAME process at a time; a few emulated seconds at most. """ from __future__ import annotations import argparse import os import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] CPUS = {"main": ":maincpu", "sound": ":soundcpu", "mcu": ":mcu"} FIELDS = {"main": "pc,af,sp", "sound": "pc,af,sp", "mcu": "pc,acc,sp"} def lua(cpu: str, frames: int, trace: bool, ports: bool, views: tuple[int, int] | None, out: Path) -> str: # fmt: skip lines = ["local dbg = manager.machine.debugger"] if (trace or views) else [] if trace: names = FIELDS[cpu].split(",") fmt = " ".join(["S"] + ["%X"] * len(names) + ["%d"]) lines += [ f'dbg.visible_cpu = manager.machine.devices["{CPUS[cpu]}"]', f"dbg:command('trace S.trace,{CPUS[cpu]},noloop," f'{{logerror "{fmt}\\\\n",{FIELDS[cpu]},totalcycles}}\')', ] if ports and cpu != "mcu": # watchpoints on the traced (visible) Z80 for kind in ("r", "w"): lines.append( f"dbg:command('wpiset 0,100,{kind},1," f'{{logerror "P {kind} %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}}\')' ) lines.append( # every write to the main CPU's memory "dbg:command('wpset 0,10000,w,1," '{logerror "W %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}\')' ) lines.append('dbg:command("go")') lines += ["count = 0", "notifier = emu.add_machine_frame_notifier(function()", " count = count + 1"] # fmt: skip if views: start, length = views lines += [ " if count == 2 then", ' local cpu = manager.machine.devices[":maincpu"]', ' local prog = cpu.spaces["program"]', ' local op = cpu.spaces["opcodes"] or prog -- a plain Z80 has no opcode space', " local same, differ, outside = 0, 0, 0", " local hist = {}", f" for a = {start}, {start + length - 1} do", " local p, o = prog:read_u8(a), op:read_u8(a)", " if p == o then same = same + 1 else differ = differ + 1 end", " if ((p ~ o) & 0x57) ~= 0 then outside = outside + 1 end", " local key = (a & 0x1111) .. ':' .. ((p ~ o) & 0xA8)", " hist[key] = (hist[key] or 0) + 1", " end", f' local f = io.open("{out / "views.txt"}", "w")', f' f:write(string.format("range %X-%X same %d differ %d outside-0xA8 %d\\n", ' f"{start}, {start + length - 1}, same, differ, outside))", ' f:write("key (address & 0x1111):(xor & 0xA8) -> count\\n")', " local keys = {}", " for k in pairs(hist) do keys[#keys + 1] = k end", " table.sort(keys)", ' for _, k in ipairs(keys) do f:write(k .. " " .. hist[k] .. "\\n") end', " local function crc(space, a0, n)", " local c = 0xFFFFFFFF", " for a = a0, a0 + n - 1 do", " c = c ~ space:read_u8(a)", " for _ = 1, 8 do", " if (c & 1) == 1 then c = (c >> 1) ~ 0xEDB88320 else c = c >> 1 end", " end", " end", " return (~c) & 0xFFFFFFFF", " end", " for _, n in ipairs({0x2000, 0x4000, 0x8000}) do", f" for a = {start}, {start + length - 1}, n do", ' f:write(string.format("crc %X %X program %08x opcodes %08x\\n", a, n, ' "crc(prog, a, n), crc(op, a, n)))", " end", " end", " f:close()", " end", ] lines += [ f" if count == {frames} then", " manager.machine.video:snapshot()", " manager.machine:exit()", " end", "end)", ] return "\n".join(lines) + "\n" def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("machine", help="a MAME machine name: wboy, flicky, choplift, ...") parser.add_argument("--cpu", default="main", choices=sorted(CPUS)) parser.add_argument("--frames", type=int, default=0, help="trace this many frames") parser.add_argument("--snap", type=float, default=0, help="untraced run of N seconds") parser.add_argument("--ports", action="store_true", help="log main-CPU I/O port accesses") parser.add_argument("--views", help="'start,length' (hex): opcode vs program space counts") parser.add_argument("--mame", default="mame") args = parser.parse_args() rompath = os.environ.get("MAME_ROMPATH") if not rompath: print("set MAME_ROMPATH (it must hold the machine's zip)", file=sys.stderr) return 2 trace = args.frames > 0 views = tuple(int(v, 16) for v in args.views.split(",")) if args.views else None frames = args.frames if trace else 3 if views else max(1, round(args.snap * 60)) what = args.cpu if trace else "views" if views else "snap" out = ROOT / "reference" / "mame" / f"{args.machine}-{what}" out.mkdir(parents=True, exist_ok=True) script = out / "run.lua" script.write_text(lua(args.cpu, frames, trace, args.ports, views, out), encoding="utf-8") command = [ args.mame, args.machine, "-rompath", rompath, "-homepath", str(out), "-cfg_directory", str(out / "cfg"), "-nvram_directory", str(out / "nvram"), "-snapshot_directory", str(out / "snap"), "-video", "none", "-sound", "none", "-nothrottle", "-noreadconfig", "-skip_gameinfo", "-log", "-seconds_to_run", str(int(frames / 50) + 5), "-autoboot_script", str(script), ] # fmt: skip if trace or views: command += ["-debug", "-debugger", "none"] 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") log = out / "error.log" if log.exists(): log.replace(out / "run.log") (out / "S.trace").unlink(missing_ok=True) # the debugger's disassembly; run.log has the state print(f"exit {result.returncode}; output in {out.relative_to(ROOT)}") return result.returncode if __name__ == "__main__": sys.exit(main())