# SPDX-License-Identifier: MIT """Rung 5: srg320's P65C816 VHDL, run under GHDL on SingleStepTests initial states. ``tb_p65c816.vhd`` (a GPL tool kept outside this repository, $EMU_TOOLS_GPL/tools/65816-python/) loads each case by running a loader program (:func:`loader`) after a reset, then logs every bus cycle of the case's instruction. This module writes the stimulus, runs the testbench (``scripts/build_referees.py p65c816-tb`` builds it), parses the log, and runs the same case through the core so the two can be compared cycle by cycle: address, read or write, the value written (or read, on a VDA/VPA read), and VDA, VPA, VPB and MLB. P65C816 is emulator-derived (hand-written HDL, proven on FPGA against games, not traced from a die; validation.md): a third opinion where the datasheet and SingleStepTests disagree (C1-C3), never a judge. """ from __future__ import annotations import subprocess import tempfile from dataclasses import dataclass from pathlib import Path from single_step import initial_state from w65c816 import W65C816 ROOT = Path(__file__).resolve().parents[1] TESTBENCH = ROOT / "reference" / "build" / "p65c816-tb" / "tb_p65c816" BUILD_HINT = "P65C816 testbench not built: python -I scripts/build_referees.py p65c816-tb" REGISTERS = ("pc", "s", "p", "a", "x", "y", "dbr", "d", "pbr", "e") LOADER_BASES = (0x8000, 0x4000, 0xC000, 0x2000) BLOCK_MOVES = (0x44, 0x54) # MVP, MVN: the corpus runs the whole move def ram_opcode(case: dict) -> int: initial = case["initial"] return dict(initial["ram"]).get(initial["pbr"] << 16 | initial["pc"], 0) @dataclass(frozen=True, slots=True) class Cycle: """One bus cycle as both sides report it. ``value`` is None where it means nothing: an IO cycle's.""" address: int value: int | None write: bool vda: bool vpa: bool vpb: bool mlb: bool @property def io(self) -> bool: return not (self.vda or self.vpa or self.write) def text(self) -> str: pins = "".join( letter if on else "-" for letter, on in zip("dpvl", (self.vda, self.vpa, self.vpb, self.mlb), strict=True) ) value = "--" if self.value is None else f"{self.value:02X}" return f"{'w' if self.write else 'r'} {self.address:06X} {value} {pins}" def loader(state: dict, base: int) -> tuple[bytes, int]: """A bank-0 program at ``base`` that leaves the CPU in ``state`` and JMLs to its PBR:PC; and the address of that JML. After reset (emulation mode), in native mode: D through TCD, DBR through PHA/PLB, then S set so that a PEA puts P's byte where the final PLP pulls it and leaves S at its value; X and Y are loaded as 16 bits in native mode, then emulation mode is entered with SEC/XCE (after the PEA, whose bytes are written in native mode so the page wrap does not move them), then A, all before that PLP, since loads change N and Z. """ s, p, e = state["s"], state["p"], state["e"] code = bytearray([0x18, 0xFB, 0xC2, 0x30]) # CLC, XCE, REP #$30 code += bytes([0xA9, state["d"] & 0xFF, state["d"] >> 8, 0x5B]) # LDA #d, TCD code += bytes([0xE2, 0x20, 0xA9, state["dbr"], 0x48, 0xAB]) # SEP #$20, LDA, PHA, PLB start = (s + 1) & 0xFFFF # the PEA's high byte here, P's byte at s code += bytes([0xC2, 0x30, 0xA9, start & 0xFF, start >> 8, 0x1B]) # REP #$30, LDA, TCS code += bytes([0xF4, p, p]) # PEA: P's byte at s, S = s - 1 # X and Y as 16 bits in native mode, so their high bytes are set (to 0 # when the case has 8-bit index registers) whatever emulation mode keeps. code += bytes([0xA2, state["x"] & 0xFF, state["x"] >> 8]) # LDX #16 code += bytes([0xA0, state["y"] & 0xFF, state["y"] >> 8]) # LDY #16 if e: code += bytes([0x38, 0xFB]) # SEC, XCE: emulation mode, S in page one code += bytes([0xA9, state["a"] >> 8, 0xEB, 0xA9, state["a"] & 0xFF]) # B, XBA, A else: code += bytes([0xA9, state["a"] & 0xFF, state["a"] >> 8]) # LDA #16 code += bytes([0x28]) # PLP jml = base + len(code) code += bytes([0x5C, state["pc"] & 0xFF, state["pc"] >> 8, state["pbr"]]) return bytes(code), jml def stimulus(case_id: int, case: dict) -> str: """Three stimulus lines for one SST case (tb_p65c816.vhd's format).""" state = initial_state(case["initial"]) stack = {(state["s"] + k) & 0xFFFF for k in (-2, -1, 0, 1)} for base in LOADER_BASES: code, jml = loader(state, base) if not stack & set(range(base, base + len(code))): break else: raise ValueError("no loader base clear of the stack") pairs = {base + n: byte for n, byte in enumerate(code)} pairs[0xFFFC], pairs[0xFFFD] = base & 0xFF, base >> 8 ram = case["initial"]["ram"] block = ram_opcode(case) in BLOCK_MOVES cycles = sum(1 for row in case["cycles"] if row[0] is not None) cap = cycles if block else 2 * cycles + 8 head = f"{case_id} {len(pairs)} {len(ram)} {jml} {cap} {int(block)}" loader_line = " ".join(f"{a} {v}" for a, v in sorted(pairs.items())) ram_line = " ".join(f"{a} {v}" for a, v in ram) return f"{head}\n{loader_line}\n{ram_line}\n" def run_testbench(cases: list[dict]) -> list[list[Cycle] | None]: """Each case's cycles from P65C816 (None where the loader failed).""" with tempfile.TemporaryDirectory() as scratch: stim = Path(scratch) / "stimulus.txt" out = Path(scratch) / "bus.txt" stim.write_text("".join(stimulus(i, case) for i, case in enumerate(cases))) run = subprocess.run( [str(TESTBENCH), f"-gstimulus={stim}", f"-goutput={out}"], cwd=scratch, capture_output=True, text=True, check=False, ) # fmt: skip if run.returncode: name = cases[0]["name"] if cases else "?" raise RuntimeError(f"tb_p65c816 failed on {name}...: {run.stderr[-600:]}") results: list[list[Cycle] | None] = [] current: list[Cycle] | None = None for line in out.read_text().splitlines(): words = line.split() if words[0] == "C": current = [] elif words[0] == "E": results.append(current) elif words[0] == "X": current = None elif current is not None: address, value = int(words[0]), int(words[1]) write, vda, vpa = words[2] == "0", words[3] == "1", words[4] == "1" io = not (vda or vpa or write) current.append( Cycle(address, None if io else value, write, vda, vpa, words[5] == "0", words[6] == "0") ) # fmt: skip return results def run_core(case: dict) -> list[Cycle]: """The core's cycles for one case, as SingleStepTests counts them.""" state = initial_state(case["initial"]) memory = dict(case["initial"]["ram"]) seen: list[Cycle] = [] def read_byte(address: int) -> int: value = memory.get(address, 0) seen.append(Cycle(address, value, False, cpu.vda, cpu.vpa, cpu.vpb, cpu.mlb)) return value def write_byte(address: int, value: int) -> None: memory[address] = value seen.append(Cycle(address, value, True, cpu.vda, cpu.vpa, cpu.vpb, cpu.mlb)) def idle(address: int) -> None: seen.append(Cycle(address, None, False, cpu.vda, cpu.vpa, cpu.vpb, cpu.mlb)) cpu = W65C816(read_byte, write_byte, idle) for name in REGISTERS: setattr(cpu, name, state[name]) cpu.step() if ram_opcode(case) in BLOCK_MOVES: # the corpus runs the whole move expected = sum(1 for row in case["cycles"] if row[0] is not None) while len(seen) < expected: cpu.step() return seen def run_corpus(case: dict) -> list[Cycle]: """SingleStepTests' own cycles for one case.""" cycles = [] for address, value, flags in case["cycles"]: if address is None: continue # WAI and STP end with the stopped clock write = flags[3] == "w" vda, vpa = flags[0] == "d", flags[1] == "p" io = not (vda or vpa or write) cycles.append( Cycle(address, None if io else value, write, vda, vpa, flags[2] == "v", flags[7] == "l") ) return cycles CATEGORIES = ("count", "rw", "vda", "vpa", "vpb", "mlb", "value", "address", "io_address") def differences(left: list[Cycle], right: list[Cycle]) -> set[str]: """The categories in which two cycle lists differ: the cycle count, read or write, a pin, a value, the address of a cycle that reads or writes, or the address of an IO cycle (which nothing reads).""" found = set() if len(left) != len(right): found.add("count") for a, b in zip(left, right, strict=False): if a.write != b.write: found.add("rw") for pin in ("vda", "vpa", "vpb", "mlb"): if getattr(a, pin) != getattr(b, pin): found.add(pin) if a.value is not None and b.value is not None and a.value != b.value: found.add("value") if a.address != b.address: found.add("io_address" if a.io and b.io else "address") return found def vote(core: list[Cycle], hdl: list[Cycle], corpus: list[Cycle]) -> dict[str, str]: """Who stands alone in each category where the three differ: "HDL alone" (the core and the corpus agree), "corpus alone" (the HDL sides with the core), "core alone" (the HDL sides with the corpus), or "all differ".""" core_vs_hdl = differences(core, hdl) corpus_vs_hdl = differences(corpus, hdl) core_vs_corpus = differences(core, corpus) sides = {} for category in core_vs_hdl | corpus_vs_hdl | core_vs_corpus: if category not in core_vs_corpus: sides[category] = "HDL alone" elif category not in core_vs_hdl: sides[category] = "corpus alone" elif category not in corpus_vs_hdl: sides[category] = "core alone" else: sides[category] = "all differ" return sides