# SPDX-License-Identifier: MIT """MAME lockstep (rung 5): replay MAME 0.285's trace of a machine through the core. MAME is an emulator (tier 5): **a detector, never a judge**. Its trace finds differences; each one is then settled by the highest tier that speaks to it (docs/mame-oracle.md). The trace is ``scripts/mame_trace.py --bus``: for every instruction a line ``PC A X Y SP P totalcycles`` written before it executes, followed by one line per access MAME's CPU made, ``R address data`` or ``W address data``. The replay needs no model of the machine around the CPU: - the core starts from the first line's registers and then runs on its own; - each read is answered from MAME's reads of the same address during the same instruction (in order, the last value repeating), else from the last value seen at that address, else it is counted as unknown (a dummy read at an address MAME's cycle list does not touch: the two disagree about dummy addresses, C9) and answered with ``$FF``; - after each instruction the core's PC, A, X, Y, S and P (without bits 4 and 5, which MAME keeps set) are compared with the next line, its writes with MAME's writes (address and value, in order), and its cycle count with the difference of the two ``totalcycles``; - an interrupt has no line of its own: it shows as the next line's PC at a vector's target with S three lower, and MAME's accesses then hold the three pushes and the two vector reads. The replay requests that interrupt (IRQ or NMI by the vector MAME read) and steps the core once more. A difference is recorded under a category with its first examples, the core's registers are set from MAME's line, and the replay goes on: one disagreement does not hide the next. """ from __future__ import annotations from collections import Counter, deque from collections.abc import Iterator from dataclasses import dataclass, field from pathlib import Path from w65c02_python import G65SC02, R65C02, W65C02S, CPUState from w65c02_python._dispatch import opcodes_for ROOT = Path(__file__).resolve().parents[1] TRACES = ROOT / "tests" / "mame_traces" TRACE_HINT = "no MAME trace: python -I scripts/mame_trace.py --bus --seconds 3" #: MAME driver -> the row its CPU device corresponds to (docs/mame-oracle.md). DRIVERS = { "lynx": G65SC02, "bbcm": G65SC02, "apple2ee": G65SC02, "cexpert": R65C02, # MAME's "WDC W65C02S" device: two chess computers that need no media. "cmmb103": W65C02S, "arbv2": W65C02S, } REGISTERS = ("PC", "A", "X", "Y", "S", "P") Access = tuple[str, int, int] Line = tuple[int, int, int, int, int, int, int] # pc a x y s p totalcycles def trace_path(driver: str) -> Path: return TRACES / driver / "error.log" def has_bus_trace(driver: str) -> bool: """Whether the driver's trace exists and was recorded with ``--bus``.""" path = trace_path(driver) if not path.is_file(): return False with path.open(encoding="utf-8", errors="replace") as handle: for _ in range(200): fields = handle.readline().split() if len(fields) == 4 and fields[1] in ("R", "W"): return True return False def records(path: Path, limit: int | None = None) -> Iterator[tuple[Line, list[Access]]]: """Each instruction line with the bus accesses that belong to it. MAME fetches an opcode at the end of the instruction before, so the read of an instruction's opcode is logged just before its line: it is moved to the front of that instruction's accesses. """ current: Line | None = None accesses: list[Access] = [] count = 0 with path.open(encoding="utf-8", errors="replace") as handle: for text in handle: fields = text.split() if len(fields) == 4 and fields[1] in ("R", "W"): # "[luaengine] R FF80 78" accesses.append((fields[1], int(fields[2], 16), int(fields[3], 16))) elif len(fields) == 7 and not text.startswith("["): pc, a, x, y, s, p = (int(value, 16) for value in fields[:6]) line = (pc, a, x, y, s & 0xFF, p, int(fields[6])) fetch = [] if accesses and accesses[-1][:2] == ("R", pc): fetch = [accesses.pop()] if current is not None: yield current, accesses count += 1 if limit is not None and count >= limit: return current, accesses = line, fetch @dataclass class Report: """What one replay found.""" driver: str row: str instructions: int = 0 interrupts: Counter = field(default_factory=Counter) agreed: int = 0 # instructions whose registers, writes and cycles all agreed #: category -> count; categories name what differed and the opcode differences: Counter = field(default_factory=Counter) examples: dict = field(default_factory=dict) unknown_reads: int = 0 def differ(self, category: str, detail: str) -> None: self.differences[category] += 1 if category not in self.examples: self.examples[category] = f"instruction {self.instructions}: {detail}" def replay(driver: str, limit: int | None = None, row: type | None = None) -> Report: """Replay the driver's trace on its row (or ``row``).""" cpu_class = row or DRIVERS[driver] report = Report(driver, cpu_class.__name__) mnemonics = [entry[2] for _, entry in sorted(opcodes_for(cpu_class).items())] memory: dict[int, int] = {} reads: dict[int, deque] = {} writes: deque = deque() wrong_writes: list[str] = [] def read_byte(address: int) -> int: queue = reads.get(address) if queue: value = queue.popleft() if len(queue) > 1 else queue[0] memory[address] = value return value value = memory.get(address) if value is None: report.unknown_reads += 1 return 0xFF return value def write_byte(address: int, value: int) -> None: memory[address] = value if not writes: wrong_writes.append(f"${value:02X} to ${address:04X}, MAME wrote nothing more") else: want = writes.popleft() if want != (address, value): wrong_writes.append( f"${value:02X} to ${address:04X}, MAME ${want[1]:02X} to ${want[0]:04X}" ) cpu = cpu_class(read_byte, write_byte) # `limit` steps need one more line: the state the last of them must produce. stream = records(trace_path(driver), None if limit is None else limit + 1) try: before, accesses = next(stream) except StopIteration: return report cpu.restore_state(_state(before)) # Each instruction is `before` with the accesses that followed its line; the # next line, `after`, is what it must have produced. for after, next_accesses in stream: reads.clear() writes.clear() wrong_writes.clear() for kind, address, value in accesses: if kind == "R": reads.setdefault(address, deque()).append(value) else: writes.append((address, value)) clean = True interrupt = _interrupt(before, after, accesses) if interrupt is None: cycles = cpu.step() name = f"${cpu.opcode:02X} {mnemonics[cpu.opcode]}" report.instructions += 1 else: # MAME logged this line and then took an interrupt in its place. last = f"${cpu.opcode:02X} {mnemonics[cpu.opcode]}" name = f"the {interrupt} entry" if interrupt == "nmi": cpu.request_non_maskable_interrupt() else: cpu.request_maskable_interrupt() cycles = cpu.step() cpu.clear_maskable_interrupt() cpu.clear_non_maskable_interrupt() report.interrupts[interrupt] += 1 if cpu.s != after[4]: clean = False report.differ( f"an {interrupt} MAME takes after {last}, the core's poll one instruction later", f"at ${before[0]:04X}", ) state = (cpu.pc, cpu.a, cpu.x, cpu.y, cpu.s, cpu.p & 0xCF) want = (*after[:5], after[5] & 0xCF) if clean and state != want: clean = False fields = [ f"{label} ${got:X} (MAME ${wanted:X})" for label, got, wanted in zip(REGISTERS, state, want, strict=True) if got != wanted ] report.differ(f"registers after {name}", f"at ${before[0]:04X}: {', '.join(fields)}") if clean and (wrong_writes or writes): clean = False detail = wrong_writes[0] if wrong_writes else f"MAME also wrote {list(writes)}" report.differ(f"writes of {name}", f"at ${before[0]:04X}: the core wrote {detail}") delta = after[6] - before[6] if clean and cycles != delta: clean = False report.differ(f"cycles of {name}: core {cycles}, MAME {delta}", f"at ${before[0]:04X}") if clean: report.agreed += 1 else: # Take MAME's state and go on: one disagreement must not hide the next. cpu.restore_state(_state(after)) before, accesses = after, next_accesses return report def _interrupt(before: Line, after: Line, accesses: list[Access]) -> str | None: """Whether MAME took an interrupt in place of the instruction at ``before``, and which. MAME writes the trace line when it has fetched an opcode, then decides whether to run it or to enter an interrupt: an entry shows as S three lower with the line's own PC pushed (``BRK`` pushes PC + 2). """ pc, s = before[0], before[4] if after[4] != (s - 3) & 0xFF: return None pushed = [(address, value) for kind, address, value in accesses if kind == "W"] if pushed[:2] != [(0x0100 | s, pc >> 8), (0x0100 | (s - 1) & 0xFF, pc & 0xFF)]: return None vectors = {address for kind, address, _value in accesses if kind == "R"} return "nmi" if 0xFFFA in vectors and 0xFFFE not in vectors else "irq" def _state(line: Line) -> CPUState: """A trace line's registers as a CPU state (MAME prints P with bits 4 and 5 set).""" pc, a, x, y, s, p, _cycles = line return CPUState(a=a, x=x, y=y, s=s, pc=pc, p=(p | 0x20) & ~0x10) def format_report(report: Report, categories: int = 30) -> str: different = sum(report.differences.values()) headline = ( f"{report.driver} on {report.row}: {report.instructions:,} instructions and " f"{sum(report.interrupts.values()):,} interrupt entries {dict(report.interrupts)}; " f"{report.agreed:,} agree in registers, writes and cycles, {different:,} differ; " f"reads of an address MAME never touched: {report.unknown_reads:,}" ) lines = [headline] for category, count in report.differences.most_common(categories): lines.append(f" {count:>9,} {category}; first: {report.examples[category]}") return "\n".join(lines)