#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Which DLL entries raise a DLI: ``probes/dliprobe.s`` on the board, MAME and ProSystem. Six phases, each counting NMIs over 16 frames (the program's header says what each phase sets up). Assembled with ca65/ld65 (cc65 2.19) into ``tests/probe_builds/`` (ignored) in an NTSC and a PAL zone layout, headered by this repository's converter, and run: - on the board, NTSC and PAL, started directly (the probe is unsigned); - on MAME 0.285 as ``a7800p`` (the PAL BIOS checks only the region byte), the PAL layout, results read through MAME's Lua (``probes.py``'s recipe); - on ProSystem (BIOS-less, NTSC) through ``scripts/prosystem_run.py --dump``, run as a black box. python scripts/dli_probe.py [--mame] [--prosystem] [--fault NAME] """ from __future__ import annotations import argparse import os import subprocess import sys 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 a7800_python.cartridge import a78 # noqa: E402 from a7800_python.cartridge.connector import Linear # noqa: E402 from a7800_python.cartridge.description import CartDescription # noqa: E402 from a7800_python.machine import NTSC, PAL # noqa: E402 from a7800_python.system import System # noqa: E402 from probes import BIOS_DIR, BUILD, CC65, LUA, MAME # noqa: E402 PHASES = [ "entry 0 only (first zone, read at VBLANK's end)", "entry 5 only (middle zone, control)", "entry LAST+1 only (read on the last DMA line)", "entry LAST+2 only (never read)", "every entry, DMA off", "every entry, DMA on", "entry LAST+1, zones end one line early", "entry LAST+1, zones end one line late (never read)", ] # The board's rule (maria.py, [GLD] sheet 17, docs/gld-reading.md): a DLI for # every DLL entry with the bit that DMA reads, at the end of that DMA: the VBE # fetch reads entry 0, each zone's last line reads the next entry; the flag is # cleared only when a line DMA starts, so phase 2's flag (last DMA line) also # raises an NMI after the next VBE fetch: 2 a frame. 16 frames a phase. EXPECTED = {"ntsc": [16, 16, 32, 0, 0, 16 * 17, 16, 0], "pal": [16, 16, 32, 0, 0, 16 * 20, 16, 0]} def build(pal: bool) -> tuple[bytes, Path]: BUILD.mkdir(parents=True, exist_ok=True) name = "dli-pal" if pal else "dli-ntsc" obj, binary = BUILD / f"{name}.o", BUILD / f"{name}.bin" subprocess.run([str(CC65 / "ca65"), f"-DPAL={int(pal)}", "-o", str(obj), str(ROOT / "probes/dliprobe.s")], check=True) # fmt: skip subprocess.run([str(CC65 / "ld65"), "-C", str(ROOT / "probes/probe.cfg"), "-o", str(binary), str(obj)], check=True) # fmt: skip rom = binary.read_bytes() headered = BUILD / f"{name}.a78" desc = CartDescription(payload=rom, title=f"dliprobe {name}", region="pal" if pal else "ntsc") headered.write_bytes(a78.build(desc) + rom) return rom, headered def results(raw: bytes) -> list[int]: """The eight phase counts, then phase 6's passes from the DLI to VBLANK ($2220).""" return [raw[2 * i] | raw[2 * i + 1] << 8 for i in range(len(PHASES))] + [raw[0x20]] A7800 = ROOT / "reference/build-a7800/a7800-linux/a7800" # A7800 5.2 is built on an older MAME: its Lua has manager:machine() (a function). A7800_LUA = """ local m = type(manager.machine) == "function" and manager:machine() or manager.machine local space = m.devices[":maincpu"].spaces["program"] emu.register_frame_done(function() if space:read_u8(0x2280) == 0xA5 then local out = {} for i = 0, 63 do out[#out + 1] = string.format("%02x", space:read_u8(0x2200 + i)) end local f = io.open("result.txt", "w"); f:write(table.concat(out)); f:close() m:exit() end end) """ def run_a7800(headered: Path) -> list[int] | None: """A7800 5.2 (the prebuilt binary, run as a black box), a7800p, headless as mame-oracle.md says (SDL offscreen, -video soft -window).""" out = BUILD / "a7800-dli-pal" out.mkdir(exist_ok=True) (out / "probe.lua").write_text(A7800_LUA) result = out / "result.txt" result.unlink(missing_ok=True) subprocess.run([str(A7800), "a7800p", "-cart", str(headered), "-rompath", BIOS_DIR, "-homepath", str(out), "-video", "soft", "-window", "-sound", "none", "-nothrottle", "-noreadconfig", "-skip_gameinfo", "-seconds_to_run", "20", "-autoboot_script", str(out / "probe.lua")], cwd=out, env={**os.environ, "SDL_VIDEODRIVER": "offscreen"}, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) # fmt: skip if not result.exists(): return None return results(bytes.fromhex(result.read_text())) def run_board(rom: bytes, machine, faults: set[str]) -> list[int] | None: system = System(Linear(rom), machine, start="direct") system.board.faults |= faults ram = system.board.ram done = system.run_until(lambda: ram[0x2280 - 0x1800] == 0xA5, max_clocks=machine.frame_clocks * 260) # fmt: skip return results(bytes(ram[0x2200 - 0x1800 : 0x2240 - 0x1800])) if done else None def run_mame(headered: Path) -> list[int] | None: out = BUILD / "mame-dli-pal" out.mkdir(exist_ok=True) (out / "probe.lua").write_text(LUA) result = out / "result.txt" result.unlink(missing_ok=True) subprocess.run([MAME, "a7800p", "-cart", str(headered), "-rompath", BIOS_DIR, "-homepath", str(out), "-video", "none", "-sound", "none", "-nothrottle", "-noreadconfig", "-skip_gameinfo", "-seconds_to_run", "20", "-autoboot_script", str(out / "probe.lua")], cwd=out, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) # fmt: skip if not result.exists(): return None return results(bytes.fromhex(result.read_text())) def run_prosystem(headered: Path) -> list[int] | None: text = subprocess.run([sys.executable, str(ROOT / "scripts/prosystem_run.py"), str(headered), "--frames", "260", "--every", "1000", "--dump", "2200:81"], capture_output=True, text=True).stdout # fmt: skip for line in text.splitlines(): if line.startswith("RAM 2200:"): raw = bytes.fromhex(line.split(": ")[1]) return results(raw) if raw[0x80] == 0xA5 else None # $2280: all phases done return None def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--mame", action="store_true") parser.add_argument("--prosystem", action="store_true") parser.add_argument("--a7800", action="store_true", help="also A7800 5.2 (black box)") parser.add_argument("--fault", action="append", default=[]) args = parser.parse_args() rom_n, head_n = build(False) rom_p, head_p = build(True) columns = { "board NTSC": run_board(rom_n, NTSC, set(args.fault)), "board PAL": run_board(rom_p, PAL, set(args.fault)), } if args.mame: columns["MAME a7800p"] = run_mame(head_p) if args.a7800: columns["A7800 a7800p"] = run_a7800(head_p) if args.prosystem: columns["ProSys NTSC"] = run_prosystem(head_n) columns["ProSys PAL"] = run_prosystem(head_p) print(f"{'phase':52}" + "".join(f"{k:>14}" for k in columns) + f"{'expected':>14}") for i, label in enumerate(PHASES): row = "".join(f"{(v[i] if v else '-')!s:>14}" for v in columns.values()) print(f"{i} {label:50}{row}{EXPECTED['ntsc'][i]:>8}/{EXPECTED['pal'][i]}") row = "".join(f"{(v[-1] if v else '-')!s:>14}" for v in columns.values()) print(f" {'phase 6: 11-cycle passes from the DLI to VBLANK':50}{row}") ok = (columns["board NTSC"] and columns["board NTSC"][:-1] == EXPECTED["ntsc"] and columns["board PAL"] and columns["board PAL"][:-1] == EXPECTED["pal"]) # fmt: skip print("board matches the [SG] rule as the board reads it:", "PASS" if ok else "FAIL") return 0 if ok else 1 if __name__ == "__main__": sys.exit(main())