"""Reader for the MAME 0.285 trace of docs/mame-oracle.md, and a lockstep replay. ``error.log`` holds one line per instruction, logged *before* it executes:: PC AF BC DE HL IX IY SP AF' I R totalcycles beamy beamx (the first eleven hex, the last three decimal), and one line per port access:: IW port data totalcycles IR port data totalcycles where ``totalcycles`` is the start of the instruction that made the access. MAME is a detector (tier 5): a difference found here is a question, not a verdict. """ from __future__ import annotations from collections.abc import Iterator from dataclasses import dataclass from pathlib import Path REGISTERS = ("pc", "af", "bc", "de", "hl", "ix", "iy", "sp", "af2", "i", "r") @dataclass(frozen=True, slots=True) class Instruction: pc: int af: int bc: int de: int hl: int ix: int iy: int sp: int af2: int i: int r: int cycles: int beamy: int beamx: int @dataclass(frozen=True, slots=True) class PortAccess: kind: str # "IW" or "IR" port: int value: int cycles: int def read_log(path: str | Path) -> Iterator[Instruction | PortAccess]: """The events of an ``error.log`` in order; other lines are skipped.""" with open(path, "rb") as handle: for raw in handle: fields = raw.split() if not fields: continue head = fields[0] if head in (b"IW", b"IR") and len(fields) == 4: yield PortAccess(head.decode(), int(fields[1], 16), int(fields[2], 16), int(fields[3])) elif len(fields) == 14: try: values = [int(f, 16) for f in fields[:11]] tail = [int(f) for f in fields[11:]] except ValueError: continue yield Instruction(*values, *tail) def cpu_registers(cpu) -> tuple[int, ...]: """The board CPU's registers in the log's order (R as all eight bits).""" return ( cpu.pc, (cpu.a << 8) | cpu._f, (cpu.b << 8) | cpu.c, (cpu.d << 8) | cpu.e, (cpu.h << 8) | cpu.l, cpu.ix, cpu.iy, cpu.sp, cpu.af_, cpu.i, cpu.r, ) @dataclass class LockstepResult: instructions: int = 0 port_writes: int = 0 port_reads: int = 0 interrupt_steps: int = 0 halt_steps: int = 0 first_difference: str | None = None differences: int = 0 def summary(self) -> str: return ( f"{self.instructions} instructions, {self.port_writes} I/O writes, " f"{self.port_reads} I/O reads, {self.interrupt_steps} interrupt responses, " f"{self.differences} differences" + (f"; first: {self.first_difference}" if self.first_difference else "") ) def lockstep( board, events: Iterator[Instruction | PortAccess], *, limit: int | None = None, max_differences: int = 1 ) -> LockstepResult: """Replay ``events`` against ``board`` (built with ``io_log=[]`` and :func:`~colecovision_python.machine.mame_options`). Before each logged instruction the board's registers and clock must equal the log's; the port accesses logged after an instruction must equal, in order, the ones the board made during it. Board steps that are not instructions (an NMI or interrupt response) are taken between log lines, as MAME's trace logs only instructions. Stops after ``max_differences`` differences or ``limit`` instructions. """ result = LockstepResult() cpu = board.cpu io_log = board.io_log pending_io: list[tuple] = [] def differ(text: str) -> bool: result.differences += 1 if result.first_difference is None: result.first_difference = text return result.differences >= max_differences def check_io(event: PortAccess) -> bool: if not pending_io: return differ(f"MAME {event} but the board made no further port access") kind, port, value, start, _ = pending_io.pop(0) if (kind, port, value, start) != (event.kind, event.port, event.value, event.cycles): return differ(f"port access: board {(kind, hex(port), hex(value), start)}, MAME {event}") return False for event in events: if isinstance(event, PortAccess): if event.kind == "IW": result.port_writes += 1 else: result.port_reads += 1 if check_io(event): break continue if pending_io: if differ(f"board made extra port accesses {pending_io} before {event}"): break pending_io.clear() # Take interrupt responses (the core accepts them at step boundaries). while cpu.pc != event.pc and ( cpu.non_maskable_interrupt_pending or (cpu.maskable_interrupt_pending and cpu.iff1) ): board.step() result.interrupt_steps += 1 mine = (*cpu_registers(cpu), board.clock) theirs = ( event.pc, event.af, event.bc, event.de, event.hl, event.ix, event.iy, event.sp, event.af2, event.i, event.r, event.cycles, ) if mine != theirs: names = (*REGISTERS, "cycles") diffs = [ f"{n} board {a:X} MAME {b:X}" for n, a, b in zip(names, mine, theirs, strict=False) if a != b ] if differ(f"instruction {result.instructions} at PC {event.pc:04X}: " + ", ".join(diffs)): break result.instructions += 1 if limit is not None and result.instructions >= limit: break del io_log[:] board.step() pending_io.extend(io_log) return result