#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Show that the judges can fail: seed one fault into a copy of src/ and run every rung on it. Each fault below changes a few lines of the core in a scratch copy (the tree is not touched) and every judge is run against that copy: rung 0 (the tables), rung 1 (SingleStepTests, the smoke sample), rung 2 (Dormann's two programs), rung 3 (Clark's decimal test), rung 4 (the capture lockstep, the first million instructions of every capture), rung 6 (the directed tests) and rung 8 (the tooling). The report says which rungs caught each fault and with what tier: - a fault no rung catches means no judge covers the rule: the report says so and the exit status is 1; - a fault only rung 1 catches rests on tier 5 (an emulator-generated corpus) and is listed as such. python scripts/seeded_faults.py # every fault (about 40 minutes) python scripts/seeded_faults.py --only decimal # faults whose name contains a word python scripts/seeded_faults.py --check # only check that every fault applies python scripts/seeded_faults.py --json out.json Run it with the project's CPython; the judges themselves run under ``.venv-pypy`` (the long ones) and ``.venv`` (pytest). At most ``--jobs`` faults at a time (default 3: each runs one judge process at a time). The judges find the faulted copy through ``PYTHONPATH``, so this one script and its judges cannot run with ``-I``; they read only the repository's own code and the data the other runners read. Do not edit ``src/`` or ``tests/`` while it runs: every judge is started from the working tree. The result of the last full run is in docs/validation.md, "Rung 7". """ # ruff: noqa: ISC004 # (each fault's text and replacement are source lines, joined from one literal per line) from __future__ import annotations import argparse import json import os import shutil import subprocess import sys import tempfile from concurrent.futures import ThreadPoolExecutor from pathlib import Path ROOT = Path(__file__).resolve().parents[1] SOURCE = ROOT / "src" / "w65c02_python" PYPY = str(ROOT / ".venv-pypy" / "bin" / "python") CPYTHON = str(ROOT / ".venv" / "bin" / "python") PYTEST = ["-m", "pytest", "-q", "-x", "-p", "no:cacheprovider"] #: rung -> (what it is, its tier, the command). A judge fails by a non-zero exit status. JUDGES = { "0": ("tables", "tier 2 and CAP", [CPYTHON, *PYTEST, "tests/test_tables.py"]), "1": ( "SingleStepTests, 250 cases a file", "tier 5", [PYPY, "scripts/run_single_step.py", "--limit", "250", "--jobs", "1"], ), "2": ( "Dormann's extended and functional tests", "tier 1 for two rows", [PYPY, "scripts/run_programs.py", "--program", "extended", "--program", "functional"], ), "3": ( "Clark's decimal test", "tier 1 for two rows", [PYPY, "scripts/run_programs.py", "--program", "decimal"], ), "4": ( "capture lockstep, 1,000,000 instructions a capture", "tier 1", [PYPY, "scripts/run_capture.py", "--max-instructions", "1000000", "--jobs", "1"], ), "6": ("directed tests", "tiers 2 and 3", [CPYTHON, *PYTEST, "tests/test_directed.py"]), "8": ("tooling", "the hooks", [CPYTHON, *PYTEST, "tests/test_tooling.py"]), } # (name, file under src/w65c02_python, text, replacement). The text must occur exactly once. FAULTS = [ # -- cycles: dropped, added, a write for a read ---------------------------------------- ( "a dropped dummy cycle: PLA without its read of the stack", "_control.py", '"""PLA -- pull A (DS Table 6-4)."""\n self._fetch_discard()\n' " self._read(0x0100 | self.s)\n", '"""PLA -- pull A (DS Table 6-4)."""\n self._fetch_discard()\n' " self._extra -= 1\n", ), ( "a dropped dummy cycle: one-byte instructions take one cycle (TAX)", "_loads.py", '"""TAX -- transfer A to X (DS Table 6-4)."""\n self._fetch_discard()\n', '"""TAX -- transfer A to X (DS Table 6-4)."""\n self._extra -= 1\n', ), ( "a write for a read: read-modify-write writes twice, as the NMOS part", "_core.py", " value = self._read(address)\n self._read(address)\n", " value = self._read(address)\n self._write(address, value)\n", ), ( "the decimal cycle missing", "_alu.py", " self._fetch_discard()\n self._extra += 1\n", " pass\n", ), ( "INC and DEC abs,X take six cycles within a page, as the shifts (C11)", "_dispatch.py", '0xFE: ("inc", "ea_abx_fixed", "INC", "abx", 7),', '0xFE: ("inc", "ea_abx", "INC", "abx", 6),', ), ( "ASL abs,X always takes seven cycles, as the NMOS part", "_dispatch.py", '0x1E: ("asl", "ea_abx", "ASL", "abx", 6),', '0x1E: ("asl", "ea_abx_fixed", "ASL", "abx", 7),', ), ( "STA abs,X takes four cycles within a page", "_dispatch.py", '0x9D: ("sta", "ea_abx_fixed", "STA", "abx", 5),', '0x9D: ("sta", "ea_abx", "STA", "abx", 4),', ), ( "JMP (abs) keeps the NMOS part's page-wrap bug", "_control.py", " low = self._read(pointer)\n" " self.pc = self._read((pointer + 1) & 0xFFFF) << 8 | low\n\n" " def _op_jmp_abxind", " low = self._read(pointer)\n" " self.pc = self._read(pointer & 0xFF00 | (pointer + 1) & 0xFF) << 8 | low\n\n" " def _op_jmp_abxind", ), # -- the NOP classes -------------------------------------------------------------------- ( "a wrong NOP length: the x2 NOPs are one byte", "_nops.py", '`02 22 42 62 82 C2 E2` (DS Table 7-1; CAP: `02` 2)."""\n self._fetch()', '`02 22 42 62 82 C2 E2` (DS Table 7-1; CAP: `02` 2)."""\n self._fetch_discard()', ), ( "a wrong NOP length: one-cycle NOPs take two cycles, as $EA", "_dispatch.py", 'ONE_CYCLE_NOP: Row = ("nop_one_cycle", None, "NOP", "imp", 1)', 'ONE_CYCLE_NOP: Row = ("nop", None, "NOP", "imp", 2)', ), ( "a wrong NOP length: $5C takes four cycles, as the corpus has it (C1)", "_nops.py", " for _ in range(4):\n self._read(0xFFFF)", " self._extra -= 4", ), ( "a wrong NOP length: $44 is three bytes", "_dispatch.py", '0x44: ("nop_zp", None, "NOP", "zp", 3),', '0x44: ("nop_abs", None, "NOP", "abs", 4),', ), ( "a wrong NOP length: $DC and $FC are two bytes", "_nops.py", " address = self._fetch_word()\n if self.nop_dc_fc_reads", " address = self._fetch()\n self._fetch_discard()\n" " if self.nop_dc_fc_reads", ), # -- the rows' distinguishing cells ----------------------------------------------------- ( "rows swapped: the G65SC02 has the bit instructions", "cpu.py", " bit_instructions = False # C2\n", " bit_instructions = True # C2\n", ), ( "rows swapped: the R65C02 has WAI and STP, as MAME's (C5)", "cpu.py", " wai_stp = False # U3: `$CB` and `$DB` are one-byte, one-cycle NOPs\n", " wai_stp = True # U3: `$CB` and `$DB` are one-byte, one-cycle NOPs\n", ), ( "rows swapped: the R65C02 writes the stack at reset", "cpu.py", " reset_writes_stack = False # CAP\n", " reset_writes_stack = True # CAP\n", ), ( "rows swapped: the G65SC02 reads the stack at reset", "cpu.py", " reset_writes_stack = True # CAP; GDS Table V\n", " reset_writes_stack = False # CAP; GDS Table V\n", ), ( "rows swapped: the Lynx II's cell has no bit instructions (C12)", "cpu.py", " bit_instructions = True # C12: LT, tier 3 with hardware-derived expectations\n", " bit_instructions = False # C12: LT, tier 3 with hardware-derived expectations\n", ), ( "rows swapped: the W65C02S has no WAI or STP", "cpu.py", " wai_stp = True\n reset_writes_stack = False # U1: unknown; the default\n", " wai_stp = False\n reset_writes_stack = False # U1: unknown; the default\n", ), # -- flags and results ------------------------------------------------------------------ ( "D not cleared by an interrupt entry", "_control.py", " self.p = (self.p | I) & ~D # D cleared by interrupts too (DS Table 7-1)\n", " self.p = self.p | I\n", ), ( "D not cleared by BRK", "_control.py", ' # D is cleared on the 65C02 (DS Table 7-1 "Decimal flag"; CL section 6).\n' " self.p = (self.p | I) & ~D\n", " self.p = self.p | I\n", ), ( "D not cleared by reset", "_control.py", ' self.p = (self.p | I) & ~D # DS Table 7-1 "Decimal flag"\n', " self.p = self.p | I\n", ), ( "an interrupt entry pushes P with B set", "_control.py", " self._push(self.p | U) # B clear: what tells an IRQ from a BRK (CL section 6)\n", " self._push(self.p | U | B)\n", ), ( "BRK is one byte: the return address is PC + 1", "_control.py", " self._fetch() # the signature byte: read and skipped\n", " self._fetch_discard()\n", ), ( "BIT #imm copies N and V from the operand", "_alu.py", " self.p = (self.p & ~Z) | (0 if self.a & operand else Z)\n", " self.p = (self.p & ~(N | V | Z)) | (operand & (N | V)) " "| (0 if self.a & operand else Z)\n", ), ( "TSB takes Z from the stored result, as the HuC6280", "_bits.py", " self.p = (self.p & ~Z) | (0 if self.a & value else Z) " "# Z from the test, not the result\n", " self.p = (self.p & ~Z) | (0 if self.a | value else Z)\n", ), ( "decimal ADC takes V from the binary sum", "_alu.py", " overflow = decimal_add_overflow(a, operand, p & C)\n", " overflow = ~(a ^ operand) & (a ^ (a + operand + (p & C))) & 0x80\n", ), ( "decimal SBC keeps the NMOS part's result for invalid digits (BC 4d dropped)", "_alu.py", " if low < 0:\n total -= 0x06 # BC 4d\n", " if low < 0 and (total & 0x0F) > 0x09:\n total -= 0x06\n", ), ( "decimal ADC gives N and Z of the binary sum, as the NMOS part", "_alu.py", " self.a = result\n" ' # N and Z are the result\'s in decimal mode too: "valid flags" (DS Table 7-1).\n' " self.p = (p & ~(N | V | Z | C)) | NZ[result] | (V if overflow else 0) | carry\n", " self.a = result\n" " self.p = (p & ~(N | V | Z | C)) | NZ[(a + operand + (p & C)) & 0xFF] " "| (V if overflow else 0) | carry\n", ), ( "RMB and SMB act on the wrong bit", "_bits.py", " mask = 1 << ((self.opcode >> 4) & 7)\n zp = self._fetch()\n" " value = self._read(zp)\n" " self._read(zp) # read-modify-write: two reads, one write (DS Table 7-1)\n", " mask = 1 << ((self.opcode >> 5) & 7)\n zp = self._fetch()\n" " value = self._read(zp)\n self._read(zp)\n", ), # -- dummy-read addresses: the corpus's, back in (C10, C13 to C18) and MAME's (U9) ------ ( "corpus address: zp,X reads the unindexed zero-page address (C18)", "_core.py", " zp = self._fetch()\n" " self._read((self.pc - 1) & 0xFFFF) # CAP, both parts; SST reads `zp` instead " "(C18)\n", " zp = self._fetch()\n self._read(zp)\n", ), ( "corpus address: an indexed store within a page re-reads PC+2 (C14)", "_core.py", " address = (base + self.x) & 0xFFFF\n" " self._read((self.pc - 1) & 0xFFFF if (address ^ base) & 0xFF00 else address)\n", " address = (base + self.x) & 0xFFFF\n self._read((self.pc - 1) & 0xFFFF)\n", ), ( "corpus address: STA (zp),Y re-reads PC+1 (C15)", "_core.py", " base = self._read(high_address) << 8 | low\n self._read(high_address)\n", " base = self._read(high_address) << 8 | low\n" " self._read((self.pc - 1) & 0xFFFF)\n", ), ( "corpus address: a branch across a page reads the old page (C16)", "_control.py", " if (target ^ pc) & 0xFF00:\n self._fetch_discard()\n" " self._extra += 1\n self.pc = target\n\n def _op_bpl", " if (target ^ pc) & 0xFF00:\n" " self._read(pc & 0xFF00 | target & 0x00FF)\n" " self._extra += 1\n self.pc = target\n\n def _op_bpl", ), ( "corpus address: JMP (abs) reads the pointer first (C17)", "_control.py", " self._read((self.pc - 1) & 0xFFFF)\n low = self._read(pointer)\n" " self.pc = self._read((pointer + 1) & 0xFFFF) << 8 | low\n", " low = self._read(pointer)\n" " self._read(pointer & 0xFF00 | (pointer + 1) & 0x00FF)\n" " self.pc = self._read((pointer + 1) & 0xFFFF) << 8 | low\n", ), ( "corpus address: the decimal cycle re-reads the last operand byte (C13)", "_alu.py", " self._fetch_discard()\n self._extra += 1\n", " self._read((self.pc - 1) & 0xFFFF)\n self._extra += 1\n", ), ( "corpus address: $DC and $FC re-read PC+2 (C10)", "_nops.py", ' nop_dc_fc_reads = "absolute"\n', ' nop_dc_fc_reads = "operand"\n', ), ( "MAME's reading: $5C reads the next opcode's address (U9)", "_nops.py", ' nop_5c_reads = "ff_page"\n', ' nop_5c_reads = "pc"\n', ), # -- the poll, the pins, WAI ------------------------------------------------------------ ( "CLI admits a pending IRQ at once", "_control.py", " self._polled_i = self.p & I # this instruction's poll saw the old I (U5)\n", "", ), ( "one-cycle NOPs poll (U7)", "_nops.py", " one_cycle_nops_poll = False\n", " one_cycle_nops_poll = True\n", ), ( "an operand read looks the bus callable up before its addressing cycles", "_core.py", " def _rd_zp(self) -> int:\n address = self._fetch()\n" " return self._read(address)\n", " def _rd_zp(self) -> int:\n return self._read(self._fetch())\n", ), ( "SYNC is not raised in the first cycle of an interrupt entry", "_control.py", " # the entries are counted from a SYNC cycle), then reads PC again.\n" " self.sync = self.fetch = True\n", " # the entries are counted from a SYNC cycle), then reads PC again.\n" " self.fetch = True\n", ), ( "WAI waits even when IRQ is already low", "_control.py", " if not self._requests & (IRQ_LINE | NMI_LATCH):\n self.waiting = True\n" " self.halted = True\n", " self.waiting = True\n self.halted = True\n", ), ( "the disassembler gives BBR and BBS two bytes", "_dispatch.py", '"ind": 3, "idx": 2, "idy": 2, "zpind": 2, "abxind": 3, "rel": 2, "zprel": 3,', '"ind": 3, "idx": 2, "idy": 2, "zpind": 2, "abxind": 3, "rel": 2, "zprel": 2,', ), ] def mutated_copy(scratch: Path, fault: tuple[str, str, str, str] | None) -> Path: """A copy of src/ in ``scratch`` with one fault applied (none: the control).""" target = scratch / "src" / "w65c02_python" shutil.copytree(SOURCE, target, ignore=shutil.ignore_patterns("__pycache__")) if fault is not None: _name, file, old, new = fault text = (target / file).read_text(encoding="utf-8") if text.count(old) != 1: raise SystemExit( f"fault {fault[0]!r}: its text occurs {text.count(old)} times in {file}" ) (target / file).write_text(text.replace(old, new), encoding="utf-8") return scratch / "src" def run_fault(task: tuple[tuple[str, str, str, str] | None, list[str]]) -> tuple[str, dict]: """Run the judges on one fault; returns its name and rung -> whether the judge failed.""" fault, rungs = task name = "control: no fault" if fault is None else fault[0] caught = {} with tempfile.TemporaryDirectory(prefix="w65c02-fault-") as scratch: source = mutated_copy(Path(scratch), fault) environment = {**os.environ, "PYTHONPATH": str(source), "PYPY_GC_NURSERY": "1M"} where = subprocess.run( [CPYTHON, "-c", "import w65c02_python; print(w65c02_python.__file__)"], cwd=ROOT, env=environment, capture_output=True, text=True, check=False, ) # fmt: skip if where.returncode == 0 and not where.stdout.startswith(str(source)): raise SystemExit(f"the judges would not import the copy: {where.stdout.strip()}") for rung in rungs: result = subprocess.run( ["nice", "-n", "19", *JUDGES[rung][2]], cwd=ROOT, env=environment, capture_output=True, text=True, check=False, ) # fmt: skip caught[rung] = result.returncode != 0 return name, caught def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--only", action="append", help="faults whose name contains this") parser.add_argument("--rung", choices=sorted(JUDGES), action="append", help="default: all") parser.add_argument("--check", action="store_true", help="apply every fault, run nothing") parser.add_argument("--no-control", action="store_true", help="skip the unfaulted run") parser.add_argument("--jobs", type=int, default=3) parser.add_argument("--json", type=Path) args = parser.parse_args() faults = [ fault for fault in FAULTS if not args.only or any(word in fault[0] for word in args.only) ] if len({fault[0] for fault in FAULTS}) != len(FAULTS): raise SystemExit("two faults share a name") for fault in faults: with tempfile.TemporaryDirectory(prefix="w65c02-fault-") as scratch: mutated_copy(Path(scratch), fault) if args.check: print(f"{len(faults)} faults apply, each to exactly one place") return 0 rungs = args.rung or sorted(JUDGES) print("judges: " + "; ".join(f"rung {r}: {JUDGES[r][0]} ({JUDGES[r][1]})" for r in rungs)) tasks = [(fault, rungs) for fault in ([] if args.no_control else [None]) + faults] results = {} uncaught, tier5 = [], [] with ThreadPoolExecutor(max_workers=args.jobs) as pool: for name, caught in pool.map(run_fault, tasks): results[name] = caught by = [rung for rung, failed in caught.items() if failed] print(f"{name}: caught by rungs {' '.join(by) if by else '(none)'}", flush=True) if name.startswith("control"): if by: raise SystemExit("the judges fail without a fault: nothing can be concluded") elif not by: uncaught.append(name) elif by == ["1"]: tier5.append(name) print(f"\n{len(faults)} faults, {len(faults) - len(uncaught)} caught") for name in tier5: print(f" caught only by rung 1, so resting on tier 5: {name}") for name in uncaught: print(f" NOT CAUGHT by any rung: {name}") if args.json: args.json.write_text(json.dumps(results, indent=1)) return 1 if uncaught else 0 if __name__ == "__main__": sys.exit(main())