#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Closed-box probes of Mesen2's Cx4: tiny homebrew cartridges, traced headless. Each probe is a short HG51B program (words written here from the encoding in docs/start-here.md) plus an S-CPU stub that sets the chip up the way the games do, starts the program and polls the status. The cartridge is built in a scratch directory (a LoROM image whose header carries the Cx4 chipset bytes F3h/10h, the values a Mega Man X2 header holds), run by the GPL tool mesen2-runner at ``$EMU_TOOLS_GPL/tools/mesen2/run.py`` (machine ``snes-cx4``; Mesen2's library driven through its C API and Lua, as a separate program; its source is never opened) with the Cx4 trace logger and the host stream on, and the trace rows are printed. The same program is run on this core's default model for comparison. A value seen this way is OBSERVED (Mesen2 b9fa69d via mesen2-runner 0.2.0, closed box; each run's ``manifest.json`` says so): an emulator's behaviour, not a hardware fact. Rows are written to ``tests/mesen_probes/-/`` (gitignored), with the probe cartridge itself. python -I scripts/cx4_probe.py # every probe python -I scripts/cx4_probe.py shift stack """ from __future__ import annotations import gzip import os import subprocess import sys import tempfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] #: The closed-box runner's documented path under EMU_TOOLS_GPL (emu-tools docs/contract.md, #: section 5): mesen2-runner, a GPL-3.0-or-later tool, machine snes-cx4. RUNNER = "tools/mesen2/run.py" def mesen2_run() -> str: """The closed-box runner, a GPL tool in emu-tools-gpl, never part of this repository.""" root = os.environ.get("EMU_TOOLS_GPL") if not root or not (Path(root) / RUNNER).exists(): print(f"$EMU_TOOLS_GPL/{RUNNER} not found: set EMU_TOOLS_GPL (emu-tools docs/contract.md)", file=sys.stderr) # fmt: skip raise SystemExit(3) return str(Path(root) / RUNNER) sys.path.insert(0, str(ROOT / "src")) sys.path.insert(0, str(ROOT / "tests")) from hg51b_python.replay import replay # noqa: E402 HALT = 0xFC00 BASE_BANK = 0x01 # program at $01:8000 (file offset 8000h), page n at + n x 512 def ld_a_reg(code: int) -> int: return 0x6000 | code def ld_a_imm(value: int) -> int: return 0x6400 | value def st_a(code: int) -> int: # ST reg,A return 0xE000 | code def r(n: int) -> int: return 0x60 | n CONST = {0x000000: 0x50, 0xFFFFFF: 0x51, 0x800000: 0x56, 0x7FFFFF: 0x57, 0x00FFFF: 0x54} def shift_probe() -> list[int]: """C1: SHR/ASR/ROR/SHL of 800000h and FFFFFFh by 22-31, immediate and register.""" words: list[int] = [] for op_imm, op_reg in ((0xC400, 0xC000), (0xCC00, 0xC800), (0xD400, 0xD000), (0xDC00, 0xD800)): for count in range(22, 32): for source in (0x56, 0x57): words += [ld_a_reg(source), op_imm | count, 0x0000] # NOP: the row after shows A words += [ld_a_imm(count), st_a(r(1)), ld_a_reg(source), op_reg | r(1), 0x0000] return words def truncate_probe() -> list[int]: """C2: flags of ADD/SUB/CMP/SUBR/CMPR on A<<8 and A<<16 with A's high bits set.""" words: list[int] = [] for source in (0x56, 0x51, 0x57, 0x54): for sub in (1, 2, 3): # A<<1, A<<8, A<<16 for base in (0x8400, 0x9400, 0x5400, 0x8C00, 0x4C00): # ADD SUB CMP SUBR CMPR imm for imm in (0x00, 0x01): words += [ld_a_reg(source), base | sub << 8 | imm, 0x0000, 0x0000] return words def stack_probe() -> list[int]: """C4: ten nested calls, then returns until the program halts. Entry 40h calls a chain; subs 0-7 at 42h + 2k are ``JSR next; RTS``; sub 8 at 52h calls sub 9 (58h: mark A = AAh, RTS) and its return site checks A: AAh the first time (set BBh, RTS on), BBh on a second visit (jump to 00h, HALT). A shift-register stack halts at 00h after eight returns (the ninth pulls an empty entry, 0); a ring of eight comes back to 53h with A = BBh and halts through the jump.""" words = [HALT] * 0x40 words += [0x2800 | 0x42, HALT] # 40h: JSR 42h; 41h: HALT for k in range(8): here = 0x42 + 2 * k words += [0x2800 | (here + 2), 0x3C00] # JSR next; RTS words += [0x2800 | 0x58, 0x5400 | 0xBB, 0x0C00 | 0x00, ld_a_imm(0xBB), 0x3C00, HALT] words += [ld_a_imm(0xAA), 0x3C00] # 58h: the deepest return words def far_probe() -> list[list[int]]: """C17 and C5: JMP with bit 8 set (09xxh), bit 9 set (0Axxh), with P = 1.""" page0 = [0x6701, 0x0900 | 0x10] + [HALT] * 14 # LD P,#1; JMP (bit 8) 10h page0 += [ld_a_imm(0x22), 0x0A00 | 0x20] + [HALT] * 14 # 10h: mark; far JMP 20h page0 += [ld_a_imm(0x33), HALT] # 20h (page 0 copy) page0 += [HALT] * (256 - len(page0)) page1 = [HALT] * 0x10 + [ld_a_imm(0x11), HALT] + [HALT] * 14 + [ld_a_imm(0x44), HALT] page1 += [HALT] * (256 - len(page1)) return [page0, page1] def ld_p_probe() -> list[int]: """C11 and C16: LD P,reg with operand codes 00h, 06h, 56h, 66h, 76h; operand 00h reads.""" words = [ld_a_imm(0x12), 0x7D00 | 0x00] # A = 12h for n in range(16): words += [ld_a_imm(0x30 + n), st_a(r(n))] # Rn = 30h + n words += [ld_a_imm(0x5A)] for code in (0x00, 0x06, 0x0C, 0x13, 0x1C, 0x50, 0x51, 0x56, 0x66, 0x76, 0x86, 0xE6): words += [0x6300 | code, 0x0000] # C16: does operand 00h read A? LD MDR,A-operand; ADD A,00h. words += [ld_a_imm(0x21), 0x6100, 0x0000, 0x8000, 0x0000] return words def clear_probe() -> list[int]: """C10: CLEAR (F800h-FBFFh) after A, P, DPR, the RAM buffer and R0 are set.""" words = [ld_a_imm(0x77), 0xE000 | 0x1C, 0x6700 | 0x05, ld_a_imm(0x66), 0xE000 | 0x0C] words += [ld_a_imm(0x55), st_a(r(0)), ld_a_imm(0x44), 0xF800, 0x0000] words += [ld_a_imm(0x44), 0xF9FF, 0x0000, ld_a_imm(0x44), 0xFB00, 0x0000] return words def bus_probe() -> list[int]: """C7: external reads (operand 2Eh, fullsnes 612Eh) each followed by WAIT.""" words = [0x6200 | 0x58, 0x0000] # LD MAR,#008000h (ROM) for _ in range(4): words += [0x6100 | 0x2E, 0x1C00, 0x0000, 0x0000] # LD MDR,BUS; WAIT; NOP; NOP return words PROBES = { "shift": shift_probe, "truncate": truncate_probe, "stack": stack_probe, "far": far_probe, "ldp": ld_p_probe, "clear": clear_probe, "bus": bus_probe, } ENTRY = {"stack": 0x40} CHUNKED = {"shift", "truncate"} # flat lists of 8-word (shift) or 4-word groups def s_cpu_stub(pc: int, *, wait: int = 0x44) -> bytes: """The S-CPU side: the games' setup (MAME host log), start at PB 0, poll bit 6.""" code = bytearray() def sta(value: int, address: int) -> None: code.extend([0xA9, value, 0x8D, address & 0xFF, address >> 8]) code.extend([0x78, 0xD8]) # SEI, CLD sta(0x01, 0x7F51) sta(wait, 0x7F50) sta(0x00, 0x7F52) sta(0x00, 0x7F4C) sta(0x00, 0x7F49) sta(0x80, 0x7F4A) sta(BASE_BANK, 0x7F4B) sta(0x00, 0x7F4D) sta(0x00, 0x7F4E) sta(pc, 0x7F4F) code.extend([0xAD, 0x5E, 0x7F, 0x29, 0x40, 0xD0, 0xF9]) # poll: LDA $7F5E; AND #$40; BNE code.extend([0xAD, 0x5E, 0x7F]) # one last status read code.extend([0x80, 0xFE]) # BRA * return bytes(code) class Stub: """A tiny 65816 emitter (emulation mode, 8-bit A and X) for the host-side probes.""" def __init__(self) -> None: self.code = bytearray([0x78, 0xD8]) # SEI, CLD def sta(self, value: int, address: int) -> Stub: self.code.extend([0xA9, value, 0x8D, address & 0xFF, address >> 8]) return self def setup(self, wait: int = 0x44) -> Stub: for value, address in ((0x01, 0x7F51), (wait, 0x7F50), (0, 0x7F52), (0, 0x7F4C)): self.sta(value, address) for i, value in enumerate((0x00, 0x80, BASE_BANK)): self.sta(value, 0x7F49 + i) return self.sta(0, 0x7F4D).sta(0, 0x7F4E) def reads(self, address: int, count: int) -> Stub: """``count`` reads of ``address`` (LDX #count; LDA abs; DEX; BNE).""" self.code.extend([0xA2, count, 0xAD, address & 0xFF, address >> 8, 0xCA, 0xD0, 0xFA]) return self def read_each(self, addresses: range) -> Stub: for address in addresses: self.code.extend([0xAD, address & 0xFF, address >> 8]) return self def dma(self, source: int, target: int, length: int) -> Stub: for i in range(3): self.sta(source >> 8 * i & 0xFF, 0x7F40 + i) self.sta(length & 0xFF, 0x7F43).sta(length >> 8, 0x7F44) for i in range(3): self.sta(target >> 8 * i & 0xFF, 0x7F45 + i) # $7F47 starts it return self def end(self) -> bytes: return bytes(self.code + bytes([0x80, 0xFE])) # BRA * def dma_stub(source: int, target: int) -> bytes: """C3/C8: a DMA, then try to start the program, unlock ($7F53), start it again.""" stub = Stub().setup().dma(source, target, 64).reads(0x7F5E, 200) stub.sta(0, 0x7F4F).reads(0x7F5E, 60) stub.sta(0, 0x7F53).reads(0x7F5E, 10) return stub.sta(0, 0x7F4F).reads(0x7F5E, 60).end() def mirror_stub() -> bytes: """C13: $7F50-$7F5F read while the program runs (a loop) and after $7F53 stops it.""" stub = Stub().setup().sta(0, 0x7F4F).reads(0x7F5E, 4).read_each(range(0x7F50, 0x7F60)) stub.sta(0, 0x7F53).reads(0x7F5E, 4).read_each(range(0x7F50, 0x7F60)) return stub.end() def preload_stub() -> bytes: """C9: run the program once (page 0 cached), then write $7F48 while halted and poll.""" stub = Stub().setup().sta(0, 0x7F4F).reads(0x7F5E, 100) stub.sta(0, 0x7F48).reads(0x7F5E, 120) stub.sta(1, 0x7F48).reads(0x7F5E, 120) return stub.end() def preload_cold_stub() -> bytes: """C9: write $7F48 with nothing cached (PB 0), then with PB 1 (not cached either).""" stub = Stub().setup().sta(0, 0x7F48).reads(0x7F5E, 120) stub.sta(1, 0x7F4D).sta(0, 0x7F48).reads(0x7F5E, 120) return stub.end() def dma_cost_stub(wait: int) -> bytes: """C8: ROM to data RAM, 1,024 bytes, polled; run with ROM wait 0 and 7 to compare.""" stub = Stub().setup(wait=wait).dma(0x018000, 0x006000, 0x400).reads(0x7F5E, 250) return stub.reads(0x7F5E, 250).end() MARK = [ld_a_imm(0x5A), HALT] HOST_PROBES = { "dma-ram-ram": (lambda: dma_stub(0x006000, 0x006100), MARK), "dma-rom-ram": (lambda: dma_stub(0x018000, 0x006200), MARK), "dma-rom-rom": (lambda: dma_stub(0x018000, 0x018400), MARK), "dma-ram-rom": (lambda: dma_stub(0x006000, 0x018400), MARK), "dma-none-ram": (lambda: dma_stub(0x7E0000, 0x006300), MARK), "mirror": (mirror_stub, [0x0000, 0x0800]), # NOP; JMP 00h (a loop) "preload": (preload_stub, MARK), "preload-cold": (preload_cold_stub, MARK), "dma-cost-w0": (lambda: dma_cost_stub(0x00), MARK), "dma-cost-w7": (lambda: dma_cost_stub(0x77), MARK), } def cartridge(pages: list[list[int]], pc: int, stub: bytes | None = None) -> bytes: rom = bytearray(0x20000) stub = stub or s_cpu_stub(pc) rom[0 : len(stub)] = stub rom[0x7F00] = 0x40 # RTI for NMI/IRQ for n, words in enumerate(pages): data = b"".join(w.to_bytes(2, "little") for w in words) offset = 0x8000 + n * 512 rom[offset : offset + len(data)] = data header = 0x7FB0 rom[header : header + 2] = b"00" rom[header + 2 : header + 6] = b"TEST" rom[header + 0x0F] = 0x10 # chipset subtype: Cx4 title = b"HG51B PROBE".ljust(21) rom[0x7FC0:0x7FD5] = title rom[0x7FD5] = 0x20 # LoROM rom[0x7FD6] = 0xF3 # custom coprocessor (subtype at FFBFh) with ROM rom[0x7FD7] = 0x07 # 128 KiB rom[0x7FD8] = 0x00 rom[0x7FD9] = 0x01 rom[0x7FDA] = 0x33 for vector in range(0x7FE0, 0x8000, 2): rom[vector : vector + 2] = (0xFF00).to_bytes(2, "little") # $FF00: RTI rom[0x7FFC:0x7FFE] = (0x8000).to_bytes(2, "little") rom[0x7FDC:0x7FE0] = b"\xff\xff\x00\x00" total = sum(rom) & 0xFFFF rom[0x7FDC:0x7FDE] = (total ^ 0xFFFF).to_bytes(2, "little") rom[0x7FDE:0x7FE0] = total.to_bytes(2, "little") return bytes(rom) def programs_of(name: str) -> list[list[list[int]]]: if name in HOST_PROBES: return [[HOST_PROBES[name][1]]] """The probe as programs of at most 255 words + HALT (one cartridge run each). A probe returns either pages (a list of 256-word lists) or a flat list of words built from groups of at most 8 words; a flat list longer than a page is cut at a multiple of 8 words, so a group never straddles two runs.""" made = PROBES[name]() if made and isinstance(made[0], list): return [made] # type: ignore[list-item] words: list[int] = made # type: ignore[assignment] size = 248 if name in CHUNKED else 255 return [[[*words[i : i + size], HALT]] for i in range(0, len(words), size)] def run_mesen(name: str, index: int, pages: list[list[int]]) -> Path: out = ROOT / "tests" / "mesen_probes" / f"{name}-{index}" out.mkdir(parents=True, exist_ok=True) with tempfile.TemporaryDirectory(prefix="hg51b-probe-") as scratch: cart = Path(scratch) / f"probe-{name}.sfc" stub = HOST_PROBES[name][0]() if name in HOST_PROBES else None cart.write_bytes(cartridge(pages, ENTRY.get(name, 0), stub)) (out / "probe.sfc").write_bytes(cart.read_bytes()) # our own image (gitignored) # frames 0 to 2 traced (the old harness's --trace-start 0 --trace-frames 3) command = [sys.executable, "-I", mesen2_run(), "--machine", "snes-cx4", "--rom", str(cart), "--frames", "4", "--trace", "cx4-text,host", "--trace-window", "0:3", "--out", str(out), "--timeout", "30"] # fmt: skip # A probe that runs no Cx4 instruction leaves no trace: drop an older run's first. (out / "cx4.trace.gz").unlink(missing_ok=True) for attempt in range(4): # now and then a run writes no trace or hangs: run again done = subprocess.run(["nice", "-n", "19", *command], cwd=ROOT) traced = (out / "cx4.trace.gz").exists() if done.returncode == 0 and (traced or attempt >= 1): break # some probes (a loop stopped by $7F53) leave no trace rows at all return out def rows(out: Path) -> list[str]: if not (out / "cx4.trace.gz").exists(): return [] with gzip.open(out / "cx4.trace.gz", "rt", errors="replace") as source: return source.read().splitlines() def main() -> int: verbose = "-v" in sys.argv names = [a for a in sys.argv[1:] if a != "-v"] or [*PROBES, *HOST_PROBES] for name in names: for index, pages in enumerate(programs_of(name)): out = run_mesen(name, index, pages) lines = rows(out) print(f"== {name}-{index}: {len(lines)} trace rows ({out})") if verbose: for line in lines[:400]: print(line) report = replay((out / "probe.sfc").read_bytes(), out) for line in report.summary(): print(" ", line) return 0 if __name__ == "__main__": raise SystemExit(main())