# SPDX-License-Identifier: MIT """Capture lockstep: replay a logic-analyser capture of a real 65C02 through the core (rung 4). The captures are David Banks's (docs/validation.md, "Logic-analyser captures of real 65C02s"): one 16-bit sample per CPU cycle, holding the data bus, RnW, SYNC, RDY and RST of a BBC Master (a GTE/CMD G65SC12) or a BBC B fitted with a Rockwell R65C02. **Tier 1**: what the chip did. There is no address bus. The replay steps the core and answers each bus callback from the next sample: - a read returns the captured data byte, so the core follows the real chip's data whatever the machine around it did; - per cycle it compares: read or write against RnW; ``cpu.sync`` against SYNC; a written byte against the data bus. Any difference is a **mismatch** and ends the replay there (the two are no longer in step); - it keeps a memory model (what each address was last seen to hold, following the machine's paging: :class:`Paging`) and compares every read's captured byte with it. A read whose byte differs from the model is a **model difference**, counted by opcode and cycle number: a dummy read from the wrong address shows up as its slot differing in most executions, which is how the capture decides addresses it does not record (U4). Memory-mapped I/O (``$FC00-$FEFF``) is not modelled. Interrupt entries are injected where the capture shows one: the next three cycles after two reads are writes, and it is not a ``BRK`` (a ``BRK`` fetches ``$00`` and pushes P with B set). The request is an IRQ if the core's poll would take one there, else an NMI; the count of each is reported. If the core would take neither (its poll rule says no interrupt can start at this boundary) the replay reports that as a mismatch: the capture then contradicts the poll rule. Samples with RDY low are dropped: the machine is holding the processor and the cycle repeats (the Master stretches accesses to its slow I/O this way). The starting state. A reset capture starts at the reset sequence. A, X, Y and S are unknown there (zero here: the boot code loads them before it uses them, and a use before that would be a mismatch), and so are N, V, Z and C: when the first push of P differs from the core's only in flags no instruction has yet been seen to disagree about, the replay is restarted with those flags as the chip had them, and the report says so (``adopted``). The other captures start in the middle of a run: the registers are taken from the capture decoder's reconstruction (``decode6502``, a GPL program run as an external tool) at the first instruction where it knows every register and flag, and the lockstep starts there. A wrong starting state would show as mismatches. """ from __future__ import annotations import array import gzip import os import shutil import subprocess from collections import Counter from dataclasses import dataclass, field from pathlib import Path from w65c02_python import G65SC02, R65C02 from w65c02_python._dispatch import opcodes_for from w65c02_python.debug import BoundaryKind, next_boundary ROOT = Path(__file__).resolve().parents[1] BUILD = ROOT / "reference" / "build" #: The capture decoder (GPL-3.0), built outside this repository by emu-tools-gpl's 6502decoder #: tool since 2026-11-25 (reference/build/decode6502 before), at its path under EMU_TOOLS_GPL. DECODER = ( Path(os.environ.get("EMU_TOOLS_GPL", "$EMU_TOOLS_GPL")) / "tools/6502decoder/build/decode6502" ) CAPTURE_DIRS = ( ROOT / "reference" / "src" / "6502Decoder" / "test", ROOT / "reference" / "captures" / "hoglet-extended", ) FETCH_HINT = ( "captures not fetched or decode6502 not built: python -I scripts/fetch_references.py, then " "build_tools.py (EMU_TOOLS_GPL set: the decoder is $EMU_TOOLS_GPL/" + "tools/6502decoder/build/decode6502" + ")" ) # Sample bits (the decoder's default assignments; its --help). RNW = 0x0100 SYNC = 0x0200 RDY = 0x0400 RST = 0x4000 #: machine -> (row, decoder options). The captures of each machine. MACHINES = { "master": (G65SC02, ["--machine=master"]), "beebr65c02": (R65C02, ["--machine=beeb", "--cpu=r65c02"]), } CAPTURES = { "master": ("reset", "dormann_d65c10", "clark_bcd_full", "dormann_d6502"), "beebr65c02": ("reset", "dormann_d65c11", "clark_bcd_full", "dormann_d6502"), } IO_FIRST = 0xFC00 # FRED, JIM and SHEILA: memory-mapped I/O on both machines IO_END = 0xFF00 ROMSEL = 0xFE30 # the paged-ROM latch ACCCON = 0xFE34 # the Master's access control latch BANKS = 20 FLAGS_UNKNOWN_AT_RESET = 0xC3 # N V Z C # Where a model byte came from. READ = 0 WRITTEN = 1 ROM = 2 # a write here was seen not to stay: the address is ROM or empty class Paging: """Which memory an address means: the machine's paging, so the model follows it. A bank is a separate 64 KB of model. BBC B (Advanced User Guide, "Paged ROMs"): ``$8000-$BFFF`` is the sideways ROM the low four bits of ROMSEL select (the latch is write-only at ``$FE30-$FE3F``). BBC Master (Master Reference Manual part 1, "Memory"): the same, and ROMSEL bit 7 maps 4 KB of RAM at ``$8000-$8FFF``; ACCCON bit 3 (Y) maps 8 KB of RAM over the MOS at ``$C000-$DFFF``; ``$3000-$7FFF`` is shadow memory when ACCCON bit 2 (X) is set, or when bit 1 (E) is set and the code running is the VDU driver at ``$C000-$DFFF``. These are the machines', not the processor's. """ def __init__(self, machine: str) -> None: self.master = machine == "master" self.romsel = 0 self.acccon = 0 def written(self, address: int, value: int) -> None: if self.master: if address == ROMSEL: self.romsel = value elif address == ACCCON: self.acccon = value elif ROMSEL <= address < ROMSEL + 0x10: self.romsel = value def bank(self, address: int, pc: int) -> int: """The bank ``address`` is in when code at ``pc`` accesses it (0: not paged).""" if address < 0x8000: if self.master and address >= 0x3000: acccon = self.acccon if acccon & 0x04 or (acccon & 0x02 and 0xC000 <= pc < 0xE000): return 18 # shadow return 0 if address < 0xC000: if self.master and self.romsel & 0x80 and address < 0x9000: return 17 return 1 + (self.romsel & 0x0F) if address < 0xE000 and self.master and self.acccon & 0x08: return 19 return 0 class Mismatch(Exception): """The core and the capture are no longer in step.""" @dataclass class Report: """What one replay found.""" machine: str capture: str instructions: int = 0 cycles: int = 0 interrupts: Counter = field(default_factory=Counter) # "irq", "nmi", "reset" cycles_by_opcode: dict[int, Counter] = field(default_factory=dict) #: (opcode or "irq"/"nmi"/"reset", cycle number from 1) -> reads that differed from the model model_differences: Counter = field(default_factory=Counter) model_examples: dict = field(default_factory=dict) #: how many reads of each (opcode, cycle) slot agreed with a known model byte model_agreed: Counter = field(default_factory=Counter) #: every read of each slot: the rest were of I/O or of a byte the model had not seen reads: Counter = field(default_factory=Counter) #: addresses at or above $8000 where a byte the core wrote was later read back different #: (ROM, or an empty socket): the machine's memory map, not a difference writes_not_kept: int = 0 #: flags the chip held at reset, learnt from its first push of P: {"p": (mask, bits)} adopted: dict = field(default_factory=dict) start: str = "" mismatch: str | None = None ended: str = "" @property def ok(self) -> bool: return self.mismatch is None and not self.model_differences def raw_path(machine: str, capture: str) -> Path: """The unpacked capture in reference/build (unpacking it on first use).""" raw = BUILD / f"{machine}_{capture}.bin" if not raw.exists(): for base in CAPTURE_DIRS: packed = base / machine / f"{capture}.bin.gz" if packed.exists(): BUILD.mkdir(parents=True, exist_ok=True) with gzip.open(packed, "rb") as source, raw.open("wb") as target: shutil.copyfileobj(source, target, 1 << 20) break else: raise FileNotFoundError(f"{machine}/{capture}.bin.gz; {FETCH_HINT}") return raw def captures_present() -> bool: """The two reset captures are fetched and the decoder is built.""" if not DECODER.exists(): return False try: raw_path("master", "reset") raw_path("beebr65c02", "reset") except FileNotFoundError: return False return True def load_samples(path: Path) -> array.array: """The capture's 16-bit little-endian samples.""" samples = array.array("H") data = path.read_bytes() samples.frombytes(data[: len(data) & ~1]) return samples def decoder_start(machine: str, path: Path) -> tuple[int, dict[str, int]]: """Where the capture decoder first knows every register, and what it says they are. Returns the sample number of the following instruction and the registers before it. The decoder prints one line per instruction: sample number, address, bytes, disassembly, cycles, and the state after the instruction. """ command = [str(DECODER), "--phi2=", "--mem=00F", *MACHINES[machine][1]] command += ["-a", "-h", "-i", "-y", "-s", "-Y", str(path)] process = subprocess.Popen(command, stdout=subprocess.PIPE, text=True, errors="replace") assert process.stdout is not None state = None try: for line in process.stdout: fields = [part.strip() for part in line.split(" : ")] if len(fields) < 6 or "!!" in line: state = None continue if state is not None and "?" not in fields[1]: state["pc"] = int(fields[1], 16) return int(fields[0], 16) - 1, state # the decoder counts samples from 1 if "?" in line: state = None continue values = dict(item.split("=") for item in fields[5].split()) p = 0x20 for flag, bit in (("N", 0x80), ("V", 0x40), ("D", 0x08), ("I", 0x04), ("Z", 0x02)): p |= bit if values[flag] == "1" else 0 p |= 0x01 if values["C"] == "1" else 0 state = { "a": int(values["A"], 16), "x": int(values["X"], 16), "y": int(values["Y"], 16), "s": int(values["SP"], 16), "p": p, } finally: process.kill() process.wait() raise RuntimeError("the decoder never knew every register") def replay( machine: str, capture: str, *, max_instructions: int | None = None, row: type | None = None ) -> Report: """Replay one capture through the machine's row (or ``row``) and report.""" path = raw_path(machine, capture) raw = load_samples(path) registers: dict[str, int] = {} at_reset = not raw[0] & RST if at_reset: start = 0 while not raw[start] & RST: start += 1 while not raw[start] & SYNC: # the reset sequence is counted from its SYNC cycle start += 1 origin = f"the reset sequence at sample {start}" else: start, registers = decoder_start(machine, path) if not raw[start] & SYNC: raise RuntimeError(f"sample {start} is not an opcode fetch: the decoder's numbering?") origin = f"sample {start}, registers from the capture decoder" # Drop the cycles the machine held the processor in (RDY low). samples = array.array("H", (sample for sample in raw[start:] if sample & RDY)) del raw adopted: dict = {} while True: report, flags = _replay( machine, capture, samples, registers, at_reset, adopted, max_instructions, row ) report.start = origin if flags is None: return report mask, bits = adopted.get("p", (0, 0)) adopted["p"] = (mask | flags[0], bits | flags[1]) def _replay( machine: str, capture: str, samples: array.array, registers: dict[str, int], at_reset: bool, adopted: dict, max_instructions: int | None, row: type | None, ) -> tuple[Report, tuple[int, int] | None]: cpu_class = row or MACHINES[machine][0] report = Report(machine, capture, adopted=dict(adopted)) paging = Paging(machine) bank = paging.bank memory = [-1] * (BANKS << 16) source = bytearray(BANKS << 16) # where each model byte came from: READ, WRITTEN or ROM position = 0 step_start = 0 slot: object = None # None for an instruction, else "irq" / "nmi" / "reset" differences = report.model_differences agreed = report.model_agreed reads = report.reads def read_byte(address: int) -> int: nonlocal position sample = samples[position] position += 1 if not sample & RNW: raise Mismatch(f"the core reads ${address:04X}; the chip wrote ${sample & 0xFF:02X}") if bool(sample & SYNC) != cpu.sync: raise Mismatch(f"SYNC is {int(bool(sample & SYNC))}; the core's sync is {cpu.sync}") data = sample & 0xFF cycle = position - step_start # The slot: the sequence, or the opcode (in its fetch cycle, the byte being fetched). key = (slot if slot is not None else data if cycle == 1 else cpu.opcode, cycle) reads[key] += 1 if IO_FIRST <= address < IO_END: return data if slot == "reset" and 3 <= cycle <= 5: return data # S is unknown at reset: these three reads are at an unknown address index = bank(address, cpu.pc) << 16 | address known = memory[index] if known == data: agreed[key] += 1 source[index] = READ else: if known >= 0: if source[index] == WRITTEN and address >= 0x8000: # The byte the core wrote here did not stay: ROM, or nothing # there. Later writes to it are ignored. source[index] = ROM report.writes_not_kept += 1 else: differences[key] += 1 if key not in report.model_examples: report.model_examples[key] = ( f"instruction {report.instructions}, ${address:04X}: " f"model ${known:02X}, bus ${data:02X}" ) memory[index] = data return data def write_byte(address: int, value: int) -> None: nonlocal position sample = samples[position] position += 1 if sample & RNW: raise Mismatch(f"the core writes ${address:04X}; the chip read ${sample & 0xFF:02X}") if sample & SYNC: raise Mismatch("SYNC is 1 in a write cycle") if sample & 0xFF != value: raise Mismatch( f"the core writes ${value:02X} to ${address:04X}; the chip wrote " f"${sample & 0xFF:02X}" ) if IO_FIRST <= address < IO_END: paging.written(address, value) return index = bank(address, cpu.pc) << 16 | address if source[index] != ROM: memory[index] = value source[index] = WRITTEN cpu = cpu_class(read_byte, write_byte) for name, value in registers.items(): setattr(cpu, name, value) if at_reset: cpu.request_reset() if not samples[2] & RNW: # The part writes PCH, PCL and P at reset: what they were before is # unknown, so the capture's own bytes are taken (only the direction # of these three cycles is judged). cpu.pc = (samples[2] & 0xFF) << 8 | samples[3] & 0xFF cpu.p = (samples[4] & 0xEF) | 0x20 mask, bits = adopted.get("p", (0, 0)) after_reset_p = (mask, bits) mnemonics = [entry[2] for _, entry in sorted(opcodes_for(cpu_class).items())] counts = report.cycles_by_opcode limit = len(samples) - 16 # an instruction is at most 8 cycles: stay clear of the end flags_fix = None try: while position < limit: if max_instructions is not None and report.instructions >= max_instructions: report.ended = "instruction limit" break step_start = position if cpu.reset_pending: slot = "reset" elif _interrupt_ahead(samples, position): cpu.request_maskable_interrupt() kind = next_boundary(cpu.capture_state()) if kind is not BoundaryKind.IRQ: cpu.clear_maskable_interrupt() cpu.request_non_maskable_interrupt() kind = next_boundary(cpu.capture_state()) if kind is not BoundaryKind.NMI: raise Mismatch( "the capture shows an interrupt entry here; the core's poll takes " f"none at this boundary (after opcode ${cpu.opcode:02X})" ) slot = kind.value else: slot = None cycles = cpu.step() if cycles != position - step_start: raise Mismatch(f"step() returned {cycles} for {position - step_start} callbacks") if slot is None: report.instructions += 1 opcode = cpu.opcode seen = counts.get(opcode) if seen is None: seen = counts[opcode] = Counter() seen[cycles] += 1 else: report.interrupts[slot] += 1 if slot == "irq": cpu.clear_maskable_interrupt() elif slot == "reset" and after_reset_p[0]: # The flags the chip held at reset, learnt on an earlier pass. cpu.p = (cpu.p & ~after_reset_p[0]) | after_reset_p[1] else: report.ended = "end of capture" except Mismatch as exc: name = slot if slot is not None else f"${cpu.opcode:02X} {mnemonics[cpu.opcode]}" context = " ".join( f"{sample & 0xFF:02X}{'' if sample & RNW else 'w'}{'S' if sample & SYNC else ''}" for sample in samples[max(0, step_start - 8) : step_start + 10] ) report.mismatch = ( f"instruction {report.instructions}, cycle {position - step_start} of {name} " f"(PC ${cpu.pc:04X}): {exc}; samples around: {context}" ) report.ended = "mismatch" # A push of P whose only differences are flags unknown at reset and not # yet learnt: restart with them. pushes_p = (slot is None and cpu.opcode == 0x08 and position - step_start == 3) or ( slot in ("irq", "nmi") and position - step_start == 5 ) if at_reset and pushes_p and not samples[position - 1] & RNW: wrong = (samples[position - 1] ^ cpu.p) & 0xCF # bits 4 and 5 are not flags if wrong and not wrong & ~FLAGS_UNKNOWN_AT_RESET and not wrong & mask: flags_fix = (wrong, samples[position - 1] & wrong) report.cycles = position return report, flags_fix def _interrupt_ahead(samples: array.array, position: int) -> bool: """Whether the sequence starting at ``position`` is an interrupt entry. Cycles 3, 4 and 5 are writes only in an interrupt entry and in ``BRK`` (and in a G65SC12's reset); ``BRK`` fetches ``$00`` and pushes P with B set. """ if samples[position + 2] & RNW or samples[position + 3] & RNW or samples[position + 4] & RNW: return False return not (samples[position] & 0xFF == 0x00 and samples[position + 4] & 0x10) # -- rung 4b: George Foot's capture, the data bus only ---------------------------------- FOOT = ROOT / "reference" / "captures" / "foot-w65c02-dormann-data14.bin.gz" #: The capture's first nine bytes end with a reset vector (`$00 $FE`), and the bytes after #: them are the code at `$FE00` (`LDX #$40`, `STX $0203`, ...): the replay starts there. FOOT_START = 9 #: The board's device registers, as the capture shows them: reads of `$FF40` and `$FF50` #: return bytes that change by themselves (the program polls them: 29,021 and 60,969 reads #: differ from the read before), and the first thing the code does is write `$FF60`. They #: are left out of the memory model, as the BBC's I/O is. FOOT_IO_FIRST = 0xFF40 FOOT_IO_END = 0xFF70 def replay_data_only(row: type, max_instructions: int | None = None) -> Report: """Replay Foot's capture (6502Decoder issue #10) through ``row``: rung 4b. One byte per cycle: the data bus of a 65C02 with bit instructions running Dormann's 65C02 test on Foot's own board. There is no RnW and no SYNC, so cycle boundaries and directions cannot be compared: only a written byte against the bus, and every read's byte against the memory model. That is enough to show a wrong cycle count or a wrong dummy address (the replay falls out of step, or the slot differs from the model). A, X, Y, S and the flags are unknown at the start (the code loads them before it uses them); there are no interrupts in the capture. """ with gzip.open(FOOT, "rb") as handle: data = handle.read() report = Report("foot", "dormann", start=f"byte {FOOT_START}, the code at the reset vector") memory = [-1] * 0x10000 source = bytearray(0x10000) position = step_start = FOOT_START differences, agreed, reads = report.model_differences, report.model_agreed, report.reads def read_byte(address: int) -> int: nonlocal position value = data[position] position += 1 cycle = position - step_start key = (value if cycle == 1 else cpu.opcode, cycle) reads[key] += 1 if FOOT_IO_FIRST <= address < FOOT_IO_END: return value known = memory[address] if known == value: agreed[key] += 1 source[address] = READ else: if known >= 0: if source[address] == WRITTEN and address >= 0x8000: source[address] = ROM report.writes_not_kept += 1 else: differences[key] += 1 if key not in report.model_examples: report.model_examples[key] = ( f"instruction {report.instructions}, ${address:04X}: " f"model ${known:02X}, bus ${value:02X}" ) memory[address] = value return value def write_byte(address: int, value: int) -> None: nonlocal position captured = data[position] position += 1 if captured != value: raise Mismatch( f"the core writes ${value:02X} to ${address:04X}; the bus held ${captured:02X}" ) if source[address] != ROM: memory[address] = value source[address] = WRITTEN cpu = row(read_byte, write_byte) cpu.pc = data[FOOT_START - 1] << 8 | data[FOOT_START - 2] counts = report.cycles_by_opcode limit = len(data) - 16 try: while position < limit: if max_instructions is not None and report.instructions >= max_instructions: report.ended = "instruction limit" break step_start = position before = cpu.pc cycles = cpu.step() report.instructions += 1 counts.setdefault(cpu.opcode, Counter())[cycles] += 1 if cpu.pc == before: report.ended = f"the program's trap at ${before:04X}" break else: report.ended = "end of capture" except Mismatch as exc: context = " ".join(f"{byte:02X}" for byte in data[max(0, step_start - 8) : step_start + 10]) report.mismatch = ( f"instruction {report.instructions}, cycle {position - step_start} of opcode " f"${cpu.opcode:02X} (PC ${cpu.pc:04X}): {exc}; bytes around: {context}" ) report.ended = "mismatch" report.cycles = position - FOOT_START return report def format_report(report: Report, slots: int = 40) -> str: headline = ( f"{report.machine}/{report.capture}: {report.instructions:,} instructions, " f"{report.cycles:,} cycles, interrupts {dict(report.interrupts)}; ended: {report.ended}" ) lines = [headline, f" started at {report.start}"] if report.adopted: mask, bits = report.adopted["p"] lines.append( f" adopted: flags unknown at reset, mask ${mask:02X} = ${bits:02X} " "(from the chip's first push of P)" ) if report.mismatch: lines.append(f" MISMATCH {report.mismatch}") lines.append( f" reads that agreed with a known model byte: {sum(report.model_agreed.values()):,}; " f"that differed: {sum(report.model_differences.values()):,}; " f"ROM addresses written to: {report.writes_not_kept:,}" ) for key, count in sorted(report.model_differences.items(), key=lambda item: -item[1])[:slots]: opcode, cycle = key name = opcode if isinstance(opcode, str) else f"${opcode:02X}" lines.append( f" model difference: {name} cycle {cycle}: {count:,} " f"(agreed {report.model_agreed.get(key, 0):,}); first: {report.model_examples[key]}" ) return "\n".join(lines)