# SPDX-License-Identifier: MIT """Deterministic JSON Lines traces: one record per instruction, one per S-CPU access. Schema (version 1), one JSON object per line: - ``{"type": "step", "version": 1, "sequence": n, "address": PBR:address of the opcode, "bytes": [...], "text": "..", "clocks": input clocks, "before": {...}, "after": {...}, "ram": [[kind, offset, value]]}`` where the register dictionaries hold r0-r15, sfr (with R), pbr, rombr, rambr, cbr, scbr, scmr, colr, por, cfgr, clsr, sreg, dreg, pipeline and ramaddr, and ``ram`` lists the GSU's Game Pak RAM accesses (``debug.ram_accesses``); - ``{"type": "host", "version": 1, "direction": "R"|"W", "address": .., "value": .., "instruction": n}``, an S-CPU access made after ``n`` instructions (``value`` null where the chip did not drive the bus). Two cores that write equal traces for the same program and host stream are, as far as the S-CPU and the RAM can tell, the same chip; ``first_divergence`` compares two traces. """ from __future__ import annotations import json from collections.abc import Iterable, Iterator from itertools import zip_longest from typing import TextIO from gsu_python import _sfr from gsu_python.debug import HostAccess, StepRecord from gsu_python.state import CPUState TRACE_SCHEMA_VERSION = 1 FIELDS = ("pbr", "rombr", "rambr", "cbr", "scbr", "scmr", "colr", "por", "cfgr", "clsr", "sreg", "dreg", "pipeline", "ramaddr") # fmt: skip def registers(state: CPUState) -> dict[str, int]: out = {f"r{i}": value for i, value in enumerate(state.r)} out["sfr"] = state.sfr | (_sfr.R if state.clock < state.rom_ready else 0) for name in FIELDS: out[name] = getattr(state, name) return out def step_to_dict(record: StepRecord) -> dict[str, object]: return { "type": "step", "version": TRACE_SCHEMA_VERSION, "sequence": record.sequence, "address": record.address, "bytes": list(record.instruction.raw), "text": record.instruction.text, "clocks": record.clocks, "before": registers(record.before), "after": registers(record.after), "ram": [list(access) for access in record.ram_accesses], } def host_to_dict(access: HostAccess) -> dict[str, object]: return { "type": "host", "version": TRACE_SCHEMA_VERSION, "direction": access.direction, "address": access.address, "value": access.value, "instruction": access.instruction, } def encode(record: StepRecord | HostAccess) -> str: data = step_to_dict(record) if isinstance(record, StepRecord) else host_to_dict(record) return json.dumps(data, separators=(",", ":"), sort_keys=True) def write_trace(records: Iterable[StepRecord | HostAccess], stream: TextIO) -> int: count = 0 for record in records: stream.write(encode(record) + "\n") count += 1 return count def read_trace(stream: TextIO) -> Iterator[dict[str, object]]: """Yield the records as dictionaries, checking type and version.""" for number, line in enumerate(stream, start=1): if not line.strip(): continue record = json.loads(line) if record.get("version") != TRACE_SCHEMA_VERSION or record.get("type") not in ( "step", "host", ): raise ValueError(f"line {number}: not a version {TRACE_SCHEMA_VERSION} record") yield record def first_divergence( left: Iterable[dict[str, object]], right: Iterable[dict[str, object]] ) -> tuple[int, dict | None, dict | None] | None: """The first position where two traces differ (ignoring ``text``), or ``None``.""" for position, (a, b) in enumerate(zip_longest(left, right)): if a is None or b is None: return position, a, b if {k: v for k, v in a.items() if k != "text"} != { k: v for k, v in b.items() if k != "text" }: return position, a, b return None __all__ = [ "TRACE_SCHEMA_VERSION", "encode", "first_divergence", "host_to_dict", "read_trace", "registers", "step_to_dict", "write_trace", ]