#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Record MAME 0.285's per-instruction SALLY trace and register log for a 7800 cartridge. Runs the recipe in docs/mame-oracle.md in a fresh directory (default ``tests/mame_traces/-``, gitignored) and leaves ``error.log`` there. **Nothing is copied**: the BIOS is read from the MAME set directory through ``-rompath``, and the cartridge is a No-Intro zip reached through a symbolic link named as MAME's software list wants it. Why the link: MAME 0.285's a7800 cart slot loads loose files only as ``.a78`` (128-byte header); a headerless ``.bin`` is refused ("Not a valid A7800 image"). A software-list load takes headerless data, and MAME finds a ROM inside a zip by CRC when the member's name differs. So the script reads the CRC-32 from the zip's directory, looks it up in ``hash/a7800.xml``, links ``/softlist/a7800/.zip`` to the zip in place, and starts ``mame a7800 ``. A dump that is not in the software list cannot be run this way (see docs/mame-oracle.md, trap 1). python scripts/mame_trace.py a7800 ".../Atari - Atari 7800 (BIN)/Asteroids (USA).zip" python scripts/mame_trace.py a7800p ".../Choplifter! (Europe).zip" --seconds 5 --no-trace python scripts/mame_trace.py a7800 --list ".../Atari - Atari 7800 (BIN)" # which zips MAME can run ``error.log`` then holds, in execution order: - one line per instruction, before it executes: ``PC A X Y P SP totalcycles beamx beamy frame`` (hex registers, decimal rest). P is MAME's internal P: mask with $CF before comparing. beamx/beamy are MAME's screen position (454 x 263 NTSC, 454 x 313 PAL) at the instruction's first cycle; - ``R addr value totalcycles`` / ``W addr value totalcycles`` for every CPU access to $00-$3F (TIA, INPTCTRL, MARIA), RIOT I/O $280-$29F, the cartridge sound and control locations $400-$47F, and writes to $4000-$400F and $8000-$BFFF (POKEY at $4000; bank-select writes). ``summary.txt`` gets the cart slot device MAME picked, instruction and access counts, CPU cycles per frame and where the CPU resumes after WSYNC. """ from __future__ import annotations import argparse import collections import os import re import subprocess import sys import time import zipfile from pathlib import Path from a7800_python import romsets ROOT = Path(__file__).resolve().parents[1] MAME = "/usr/games/mame" HASH_DIR = "/usr/share/games/mame/hash" BIOS_DIR = str(romsets.mame_rompath()) # $MAME_ROMPATH: a7800.zip, a7800p.zip # src/mame/atari/a7800.cpp. Both need their BIOS set (a7800.zip, a7800p.zip). DRIVERS = { "a7800": "NTSC, 14.31818 MHz / 8 CPU, 454 x 263", "a7800p": "PAL, 14.187576 MHz / 8 CPU, 454 x 313", } TRACE_LUA = """\ local dbg = manager.machine.debugger dbg.visible_cpu = manager.machine.devices[":maincpu"] dbg:command('trace cpu.trace,,noloop,{logerror "%X %X %X %X %X %X %d %d %d %d\\\\n",\ pc,a,x,y,p,sp,totalcycles,beamx,beamy,frame}') dbg:command('wpset 0,40,r,1,{logerror "R %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}') dbg:command('wpset 0,40,w,1,{logerror "W %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}') dbg:command('wpset 280,20,r,1,{logerror "R %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}') dbg:command('wpset 280,20,w,1,{logerror "W %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}') dbg:command('wpset 400,80,r,1,{logerror "R %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}') dbg:command('wpset 400,80,w,1,{logerror "W %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}') dbg:command('wpset 4000,10,w,1,{logerror "W %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}') dbg:command('wpset 8000,4000,w,1,{logerror "W %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}') dbg:command('wpset ff80,10,w,1,{logerror "W %X %X %d\\\\n",wpaddr,wpdata,totalcycles; g}') dbg:command("go") """ # --writes-only: no debugger at all. Memory taps (MAME's Lua # ``install_write_tap``) on the sound registers log each CPU write with # MAME's machine time, which inside a CPU's timeslice is that CPU's local # time (the cycle of the write). About 1/100 of the instruction trace's # wall time and a few hundred kilobytes a minute. Lines: ``S addr value # seconds`` (seconds as MAME's attotime, 18 decimals). Taps: TIA audio # $15-$1A and its 7800-mode mirrors ($115, $215, $315), INPTCTRL/TIA $01 # (the BIOS's mode writes, a marker), and POKEY at $4000-$400F, $0450-$045F, # $0440-$044F, $0800-$080F; plus reads of $4000-$400F as ``R addr value # seconds`` (RANDOM and the other POKEY read registers). WRITES_LUA = """\ local space = manager.machine.devices[":maincpu"].spaces["program"] local out = io.open("writes.log", "w") local function tap(lo, hi, name) return space:install_write_tap(lo, hi, name, function(offset, data, mask) local t = manager.machine.time out:write(string.format("S %X %X %d.%018d\\n", offset, data & 0xff, t.seconds, t.attoseconds)) end) end taps = {} for _, base in ipairs({0x000, 0x100, 0x200, 0x300}) do table.insert(taps, tap(base + 0x15, base + 0x1a, "tia" .. base)) table.insert(taps, tap(base + 0x01, base + 0x01, "ctl" .. base)) end table.insert(taps, tap(0x4000, 0x400f, "pokey4000")) table.insert(taps, space:install_read_tap(0x4000, 0x400f, "pokeyread", function(offset, data, mask) local t = manager.machine.time out:write(string.format("R %X %X %d.%018d\\n", offset, data & 0xff, t.seconds, t.attoseconds)) end)) table.insert(taps, tap(0x0450, 0x045f, "pokey450")) table.insert(taps, tap(0x0440, 0x044f, "pokey440")) table.insert(taps, tap(0x0800, 0x080f, "pokey800")) emu.add_machine_stop_notifier(function() out:close() end) """ # --nmi-log (with --writes-only): every NMI vector fetch (a read of $FFFA, the # handler entry of a DLI) as ``N frame seconds``, every IRQ/BRK vector fetch # ($FFFE) as ``I frame seconds``, and MARIA's DPPH, DPPL and # CTRL writes as ``M addr value frame seconds``, to nmi.log (MAME's Lua screen # has no vpos: line and clock are computed from the time, 454 x 263 clocks of # 7,159,090 Hz a frame from time 0). At each NMI the display list list is # dumped from memory (``L dpp b0 b1 ...``, 3 bytes per entry, 64 entries) when # it changed since the last dump. NMI_LUA = """\ local space2 = manager.machine.devices[":maincpu"].spaces["program"] local scr = manager.machine.screens[":screen"] local nlog = io.open("nmi.log", "w") local dpph, dppl, dumped = 0, 0, "" local function stamp() local t = manager.machine.time return string.format("%d %d.%018d", scr:frame_number(), t.seconds, t.attoseconds) end taps.nmi = space2:install_read_tap(0xfffa, 0xfffa, "nmi", function(offset, data, mask) nlog:write("N " .. stamp() .. "\\n") local dpp = dpph * 256 + dppl local parts = {} for i = 0, 191 do parts[#parts + 1] = string.format("%02X", space2:read_u8((dpp + i) & 0xffff)) end local text = string.format("L %04X %s\\n", dpp, table.concat(parts, " ")) if text ~= dumped then dumped = text nlog:write(text) end end) taps.irq = space2:install_read_tap(0xfffe, 0xfffe, "irq", function(offset, data, mask) nlog:write("I " .. stamp() .. "\\n") end) taps.maria = space2:install_write_tap(0x2c, 0x3f, "maria", function(offset, data, mask) if offset == 0x2c then dpph = data & 0xff elseif offset == 0x30 then dppl = data & 0xff end if offset == 0x2c or offset == 0x30 or offset == 0x3c then nlog:write(string.format("M %X %X ", offset, data & 0xff) .. stamp() .. "\\n") end end) emu.add_machine_stop_notifier(function() nlog:close() end) """ STATUS_LUA = """\ local slot = "?" for tag, _ in pairs(manager.machine.devices) do if tag:find("^:cartslot:[^:]+$") then slot = tag:sub(11) end end local log = io.open("slot.txt", "w") log:write(slot .. "\\n") log:close() """ def softlist(hash_dir: str) -> dict[int, tuple[str, str, str]]: """CRC-32 -> (software name, slot feature, description), for one-ROM entries.""" text = Path(hash_dir, "a7800.xml").read_text(encoding="utf-8") table = {} for block in re.findall(r"", text, flags=re.DOTALL): name = re.search(r'(.*?)", block).group(1) slot = re.search(r'feature name="slot" value="([^"]+)"', block) crcs = re.findall(r']*crc="([0-9a-f]{8})"', block) if len(crcs) == 1: table[int(crcs[0], 16)] = (name, slot.group(1) if slot else "a78_rom", description) return table def zip_crc(path: Path) -> int: with zipfile.ZipFile(path) as z: members = [i for i in z.infolist() if not i.is_dir()] if len(members) != 1: raise SystemExit(f"{path}: expected one member, found {len(members)}") return members[0].CRC def summarize(log: Path) -> list[str]: instructions = reads = writes = 0 frame_starts: dict[int, int] = {} wsync = collections.Counter() pending_wsync = False previous_cycles = None with log.open("rb") as handle: for raw in handle: parts = raw.split() if len(parts) == 4 and parts[0] in (b"R", b"W"): if parts[0] == b"R": reads += 1 else: writes += 1 if parts[0] == b"W" and int(parts[1], 16) == 0x24: pending_wsync = True continue if len(parts) != 10: continue instructions += 1 cycles, beamx, frame = int(parts[6]), int(parts[7]), int(parts[9]) frame_starts.setdefault(frame, cycles) if pending_wsync and previous_cycles is not None: wsync[beamx] += 1 pending_wsync = False previous_cycles = cycles starts = [frame_starts[f] for f in sorted(frame_starts)] deltas = collections.Counter(b - a for a, b in zip(starts, starts[1:], strict=False)) return [ f"{instructions:,} instructions, {reads:,} logged reads, {writes:,} logged writes", "CPU cycles between the first instructions of successive frames: " + str(deltas.most_common(6)), "beamx of the first instruction after a WSYNC write: " + str(wsync.most_common(8)), ] 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="a one-member No-Intro zip, read in place") parser.add_argument("--list", type=Path, help="a directory of zips: say which MAME can run") parser.add_argument("--seconds", type=int, default=2, help="emulated seconds") parser.add_argument("--no-trace", action="store_true", help="no debugger: slot and speed only") parser.add_argument("--writes-only", action="store_true", help="no debugger: sound-register writes with times to writes.log") parser.add_argument("--nmi-log", action="store_true", help="with --writes-only: NMI vector fetches, DPP/CTRL writes, DLLs to nmi.log") parser.add_argument("--out", type=Path) parser.add_argument("--watch-writes", action="append", default=[], metavar="START,LENGTH", help="also log CPU writes to this hex range (repeatable)") # fmt: skip parser.add_argument("--temp-a78", action="store_true", help="run a temporary headered copy (deleted after the run) instead " "of a software-list link: for dumps MAME's list does not hold") parser.add_argument("--press", metavar="A-B", help="hold both P1 buttons from frame A to frame B (scripted input)") parser.add_argument("--script", nargs="*", default=[], metavar="FRAME:ACTION", help="scripted input as frames_mame.py takes it (console switches, " "stick, buttons), applied at MAME's frame_done count") parser.add_argument("--wavwrite", action="store_true", help="also record MAME's mixed sound output to mame.wav") parser.add_argument("--mame", default=MAME) parser.add_argument("--hash-dir", default=HASH_DIR) parser.add_argument("--bios-dir", default=BIOS_DIR) args = parser.parse_args() table = softlist(args.hash_dir) if args.list: known = 0 zips = sorted(args.list.glob("*.zip")) for path in zips: entry = table.get(zip_crc(path)) known += entry is not None print(f"{entry[0] if entry else '-':12} {entry[1] if entry else '-':14} {path.name}") print(f"{known} of {len(zips)} zips are in MAME's software list") return 0 if args.cart is None: parser.error("a cart zip is required") cart = args.cart.resolve() entry = table.get(zip_crc(cart)) temporary = None if args.temp_a78: # handoff-brief.md Open decision 5 (allowed for detector runs only): a # headered copy in this run's ignored directory, deleted after the run. # Activision dumps go in MAME's chip order (8 KiB halves of every bank # exchanged, cartridge/table.py), the order its a78_act device reads. import dataclasses sys.path.insert(0, str(ROOT / "src")) from a7800_python.cartridge import a78, formats desc = formats.load(cart) payload = desc.payload if desc.scheme == "activision": payload = b"".join(payload[i + 0x2000 : i + 0x4000] + payload[i : i + 0x2000] for i in range(0, len(payload), 0x4000)) # fmt: skip temporary = a78.build(dataclasses.replace(desc, payload=payload)) + payload entry = ("".join(c for c in cart.stem if c.isalnum()).lower(), "a78 header (temporary)", desc.title or cart.stem) # fmt: skip if entry is None: raise SystemExit(f"{cart.name}: CRC not in {args.hash_dir}/a7800.xml; MAME cannot load it headerless") software, slot_feature, description = entry suffix = "-writes" if args.writes_only else "" out = (args.out or ROOT / "tests" / "mame_traces" / f"{args.driver}-{software}{suffix}").resolve() link_dir = out / "softlist" / "a7800" link_dir.mkdir(parents=True, exist_ok=True) link = link_dir / f"{software}.zip" image_args = [software] if temporary is not None: link = out / "temporary.a78" link.write_bytes(temporary) image_args = ["-cart", str(link)] elif not link.is_symlink(): os.symlink(cart, link) for stale in ("error.log", "slot.txt", "summary.txt", "writes.log"): (out / stale).unlink(missing_ok=True) trace = TRACE_LUA if args.writes_only: args.no_trace = True for spec in args.watch_writes: # e.g. 4000,1000: one more write watchpoint, logged alike start, length = spec.split(",") trace = trace.replace( 'dbg:command("go")', f"dbg:command('wpset {start},{length},w,1,{{logerror \"W %X %X %d\\\\n\"," f"wpaddr,wpdata,totalcycles; g}}')\ndbg:command(\"go\")", ) lua = ("" if args.no_trace else trace) + (WRITES_LUA if args.writes_only else "") + STATUS_LUA if args.nmi_log: lua += NMI_LUA if args.press: # both P1 buttons held from frame A to frame B (frame_done count) a, b = (int(x) for x in args.press.split("-")) lua += ( "local pressed_frames = 0\nemu.register_frame_done(function()\n" " pressed_frames = pressed_frames + 1\n" f" local on = (pressed_frames >= {a} and pressed_frames < {b}) and 1 or 0\n" ' local port = manager.machine.ioport.ports[":buttons"]\n' ' port.fields["P1 Button 1"]:set_value(on)\n' ' port.fields["P1 Button 2"]:set_value(on)\nend)\n' ) if args.script: # frames_mame.py's script Lua, with no snapshots import frames_mame lua += (frames_mame.LUA.replace("EVERY", str(10**9)).replace("LAST", str(10**9)) .replace("{SCRIPT}", "{" + frames_mame.lua_script( frames_mame.parse_script(args.script)) + "}") .replace("AT[", "({})[").replace('io.open("snaps.txt", "w")', "nil")) # fmt: skip (out / "trace.lua").write_text(lua, encoding="utf-8") version = subprocess.run( [args.mame, "-version"], capture_output=True, text=True, check=True ).stdout.strip() debug = [] if args.no_trace else ["-debug", "-debugger", "none"] if args.wavwrite: debug += ["-wavwrite", str(out / "mame.wav")] began = time.monotonic() try: subprocess.run( [args.mame, args.driver, *image_args, "-hashpath", args.hash_dir, "-rompath", f"{args.bios_dir};{out / 'softlist'}", "-homepath", str(out), "-snapshot_directory", "snap", "-video", "none", "-sound", "none", "-nothrottle", "-noreadconfig", "-skip_gameinfo", *debug, "-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 finally: link.unlink() # the link (or temporary copy) is only for MAME's run wall = time.monotonic() - began slot = (out / "slot.txt").read_text(encoding="utf-8").strip() report = [ f"MAME {version}, {args.driver}, {software} ({description}), " f"{args.seconds} s emulated in {wall:.1f} s", f"software list slot feature: {slot_feature}; cart slot device: {slot}", ] if not args.no_trace: report += summarize(out / "error.log") if args.writes_only: with (out / "writes.log").open("rb") as handle: report.append(f"{sum(1 for _ in handle):,} sound-register writes in writes.log") (out / "summary.txt").write_text("\n".join(report) + "\n", encoding="utf-8") print("\n".join(report)) print(f"log: {out / 'error.log'}") return 0 if __name__ == "__main__": sys.exit(main())