#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Write the lockstep scenarios (conformance/README.md has the format). make_scenarios.py [--roms] Writes to ``conformance/scenarios/`` (committed; nothing third-party in them): - ``workout-*``: a hand-assembled program that crosses every interrupt corner the frame and the core share (CLI, SEI, REP/SEP of I, PLP, WAI with I clear and set, BRK, COP, MVN between bytes, XCE both ways), under seeded random IRQ, NMI and ABORT requests between steps and inside bus cycles (two in one cycle included), RDY stalls with requests in their held cycles, and resets; in emulation and native mode. - ``random-memory-*``: 16 MiB of seeded random bytes (vectors included) from reset or from a random native or emulation state, under the same kinds of random requests: every opcode in every mode, reached by real execution. With ``--roms``, also writes to the gitignored ``external/scenarios/`` one scenario per test ROM the reference's rungs 2 and 3 run (gilyon's cputest-full and -basic, krom's 23 CPU tests), run in the harness to the ROM's own end (``until_spin``), found through ``$W65C816_PYTHON``'s ``reference/``. Stdlib only; the generator's random numbers are baked into the files. """ from __future__ import annotations import argparse import json import os import random from pathlib import Path ROOT = Path(__file__).resolve().parents[1] SCENARIOS = ROOT / "conformance" / "scenarios" EXTERNAL = ROOT / "external" / "scenarios" HARNESS_DMA = SCENARIOS / "rom-harness-dma.sfc" ACTIONS = ("irq", "irq", "irq_clear", "irq_clear", "nmi", "abort", "nmi_clear") # The workout: a loop at $8000, every vector but reset at a handler ($9000) # that returns with RTI. WORKOUT = bytes.fromhex( "58" # 8000 CLI "ea" # 8001 NOP "78" # 8002 SEI "c204" # 8003 REP #$04 "e204" # 8005 SEP #$04 "08" # 8007 PHP "58" # 8008 CLI "28" # 8009 PLP "58" # 800A CLI "cb" # 800B WAI (I clear) "18" # 800C CLC "fb" # 800D XCE (native) "c230" # 800E REP #$30 "a90300" # 8010 LDA #$0003 "a20010" # 8013 LDX #$1000 "a00020" # 8016 LDY #$2000 "540000" # 8019 MVN $00,$00 "78" # 801C SEI "cb" # 801D WAI (I set) "e230" # 801E SEP #$30 "38" # 8020 SEC "fb" # 8021 XCE (emulation) "00ea" # 8022 BRK #$EA "02ea" # 8024 COP #$EA "e602" # 8026 INC $02 "4c0080" # 8028 JMP $8000 ) HANDLER = bytes.fromhex("40") # 9000 RTI VECTORS = {0xFFE4: 0x9000, 0xFFE6: 0x9000, 0xFFE8: 0x9000, 0xFFEA: 0x9000, 0xFFEE: 0x9000, 0xFFF4: 0x9000, 0xFFF8: 0x9000, 0xFFFA: 0x9000, 0xFFFC: 0x8000, 0xFFFE: 0x9000} # fmt: skip def random_events( rng: random.Random, steps: int, per_step: float, per_access: float, resets: float ) -> tuple[list, list]: events = [] for step in range(steps): if rng.random() < per_step: events.append({"step": step, "action": rng.choice(ACTIONS)}) if rng.random() < resets: events.append({"step": step, "action": "reset"}) accesses = steps * 5 for access in range(accesses): if rng.random() < per_access: events.append({"access": access, "action": rng.choice(ACTIONS)}) if rng.random() < 0.1: # a second change in the same cycle events.append({"access": access, "action": rng.choice(ACTIONS)}) stalls = [] for access in range(accesses): if rng.random() < per_access / 4: during = [ {"cycle": rng.randint(1, 3), "action": rng.choice(ACTIONS)} for _ in range(rng.randint(0, 2)) ] stalls.append({"access": access, "halted": rng.randint(1, 3), "during": during}) return events, stalls def workout(seed: int, native: bool) -> dict: rng = random.Random(seed) memory = [ {"address": 0x8000, "hex": WORKOUT.hex()}, {"address": 0x9000, "hex": HANDLER.hex()}, ] for vector, target in VECTORS.items(): memory.append({"address": vector, "hex": bytes((target & 0xFF, target >> 8)).hex()}) steps = 20_000 events, stalls = random_events(rng, steps, 0.03, 0.006, 0.00075) scenario = {"memory": memory, "reset": True, "steps": steps, "events": events, "stalls": stalls} if native: # Reset, then the program's own XCE: start from a native state instead. scenario["reset"] = False scenario["registers"] = {"pc": 0x800E, "e": 0, "p": 0x00, "s": 0x01FF} return scenario def random_memory(seed: int) -> dict: rng = random.Random(seed) steps = 20_000 events, stalls = random_events(rng, steps, 0.01, 0.002, 0.004) # STP is 1 in 256 scenario = { "fill": [{"seed": rng.getrandbits(32), "address": 0, "length": 1 << 24}], "steps": steps, "events": events, "stalls": stalls, } start = seed % 3 if start == 0: scenario["reset"] = True else: e = start == 2 p = rng.getrandbits(8) | (0x30 if e else 0) x, y = rng.getrandbits(16), rng.getrandbits(16) if p & 0x10: x, y = x & 0xFF, y & 0xFF scenario["registers"] = { "a": rng.getrandbits(16), "x": x, "y": y, "s": 0x0100 | rng.getrandbits(8) if e else rng.getrandbits(16), "d": rng.getrandbits(16) if rng.random() < 0.5 else rng.getrandbits(8) << 8, "dbr": rng.getrandbits(8), "pbr": rng.getrandbits(8), "pc": rng.getrandbits(16), "p": p, "e": int(e), } # fmt: skip return scenario def write(folder: Path, name: str, scenario: dict) -> None: folder.mkdir(parents=True, exist_ok=True) (folder / f"{name}.json").write_text(json.dumps(scenario, separators=(",", ":")) + "\n") def roms(reference: Path) -> None: cputest = reference / "reference" / "roms" / "snes-tests-v1.4" / "cputest" for name in ("cputest-full", "cputest-basic"): write(EXTERNAL, f"rom-{name}", {"rom": str(cputest / f"{name}.sfc"), "steps": 5_000_000, "until_spin": True}) # fmt: skip krom = reference / "reference" / "src" / "PeterLemon-SNES" / "CPUTest" / "CPU" for folder in sorted(krom.iterdir()): rom = folder / f"CPU{folder.name}.sfc" if rom.is_file(): scenario = {"rom": str(rom), "steps": 3_000_000, "until_spin": True} if folder.name == "MSC": scenario["reset_on_stop"] = 1 # "Please Reset To PASS STP" (rung 3) write(EXTERNAL, f"rom-krom-{folder.name}", scenario) def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--roms", action="store_true") args = parser.parse_args() for index, native in enumerate((False, True, False, True)): write(SCENARIOS, f"workout-{index}", workout(1000 + index, native)) for seed in range(12): write(SCENARIOS, f"random-memory-{seed}", random_memory(seed)) # The harness's DMA where the test ROMs do not reach it (a mode other than 0): a # hand-assembled 32 KiB LoROM, a mode 1 DMA into the WRAM port ($2180/$2181 alternately, # so the second byte moves the port's address), then a load of what landed at $22. rom = bytearray(0x8000) rom[0:0x2B] = bytes.fromhex( "78 a901 8d0043 a980 8d0143 a900 8d0243 a990 8d0343 9c0443" # SEI; channel 0: mode 1, "a904 8d0543 9c0643 a901 8d0b42" # B $80, A $00:9000, 4 bytes; MDMAEN = 1 "a522 8530 80fe" # LDA $22; STA $30; BRA * ) # fmt: skip rom[0x1000:0x1004] = bytes.fromhex("11223344") rom[0x7FFC:0x7FFE] = bytes.fromhex("0080") # reset vector $8000 HARNESS_DMA.write_bytes(bytes(rom)) write(SCENARIOS, "rom-harness-dma", {"rom": HARNESS_DMA.name, "steps": 1000, "until_spin": True}) if args.roms: # Resolved, so the scenario's text (the reference cache's key) does not # depend on how the checkout was named. reference = Path(os.environ.get("W65C816_PYTHON", ROOT.parent / "65816-python")).resolve() roms(reference) return 0 if __name__ == "__main__": raise SystemExit(main())