# SPDX-License-Identifier: MIT """Deterministic JSON Lines traces: one record per instruction, S-CPU access, cache load and DMA. Schema (version 1), one JSON object per line, keys sorted: - ``{"type": "step", "version": 1, "sequence": n, "pb": .., "pc": .., "word": .., "text": "..", "clocks": .., "before": {...}, "after": {...}, "ram": [[kind, byte, value]]}`` where ``before``/``after`` are :meth:`CPUState.registers` (``state.TRACE_REGISTERS``); - ``{"type": "host", "version": 1, "direction": "R"|"W", "address": .., "value": .., "instruction": n, "clock": c}``: an S-CPU access to $6000-$7FFF; - ``{"type": "cache"|"dma", "version": 1, "phase": "start"|"end", "address": .., "detail": .., "clock": c}``: a cache page load (the ROM address and the cache page) or a DMA (source and target) starting or ending. Two cores that write equal traces for the same cartridge and host stream are, as far as the S-CPU and the ROM bus 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 hg51b_python.debug import BusEvent, HostAccess, StepRecord TRACE_SCHEMA_VERSION = 1 def to_dict(record: StepRecord | HostAccess | BusEvent) -> dict[str, object]: if isinstance(record, StepRecord): return { "type": "step", "version": TRACE_SCHEMA_VERSION, "sequence": record.sequence, "pb": record.before.pb, "pc": record.before.pc, "word": record.instruction.word, "text": record.instruction.text, "clocks": record.clocks, "before": record.before.registers(), "after": record.after.registers(), "ram": [list(access) for access in record.ram_accesses], } if isinstance(record, HostAccess): return { "type": "host", "version": TRACE_SCHEMA_VERSION, "direction": record.direction, "address": record.address, "value": record.value, "instruction": record.instruction, "clock": record.clock, } return { "type": record.kind, "version": TRACE_SCHEMA_VERSION, "phase": record.phase, "address": record.address, "detail": record.detail, "clock": record.clock, } def encode(record: StepRecord | HostAccess | BusEvent) -> str: return json.dumps(to_dict(record), separators=(",", ":"), sort_keys=True) def write_trace(records: Iterable[StepRecord | HostAccess | BusEvent], 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", "cache", "dma", "bus", ): 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 class TraceWriter: """Stream a :class:`~hg51b_python.debug.DebugSession`'s records to a file as they happen: call :meth:`flush` after host accesses or steps (``step`` does it).""" def __init__(self, session, stream: TextIO) -> None: self.session = session self.stream = stream self._host = 0 self._bus = 0 self.records = 0 def flush(self) -> None: session = self.session pending: list[HostAccess | BusEvent] = [*session.host_log[self._host :]] pending += session.bus_log[self._bus :] pending.sort(key=lambda record: record.clock) for record in pending: self.stream.write(encode(record) + "\n") self.records += len(pending) self._host = len(session.host_log) self._bus = len(session.bus_log) def step(self) -> StepRecord | None: record = self.session.step() self.flush() if record is not None: self.stream.write(encode(record) + "\n") self.records += 1 return record __all__ = [ "TRACE_SCHEMA_VERSION", "TraceWriter", "encode", "first_divergence", "read_trace", "to_dict", "write_trace", ]