# SPDX-License-Identifier: MIT """Rung 4: replay a Mesen2 recording in lockstep and classify every divergence. A recording (``$EMU_TOOLS_GPL/tools/mesen2/run.py --machine snes-cx4 --trace cx4-text,host``, the GPL tool mesen2-runner, run by ``scripts/record_mesen_windows.py``) is two files from one Mesen2 2.1.1 run of a cartridge from power-on: - ``host.txt.gz``: every S-CPU read and write of $6000-$7FFF, in order, per frame, with Mesen2's master clock on each start write ($7F47, $7F48, $7F4F); - ``cx4.trace.gz``: the Cx4 trace logger's lines for a window of frames, one per instruction, the registers **before** it, with its Cx4 cycle count (``CC:``). The replay runs the core on the same cartridge from power-on and applies the host stream in order. Mesen2's clock model is not the core's (C7, C8, C9), so the stream is applied by events, not by time: a start write first runs the core until it is idle (the games only start an idle chip); a status read that Mesen2 answered "idle" runs the core until it is idle and compares all eight bits, one it answered "running" advances the core by ``poll_clocks`` and compares bit 6 only; any other read compares the byte. Each $7F4F write opens a *run*; the trace's lines are split into runs by the start writes' stamps (master clock x 20,000,000 / 21,477,270: the 20 MHz crystal over the NTSC master clock), and for runs inside the trace window the core is stepped one unit at a time and its state before every instruction is compared with the trace line: PB, PC, A, P, the four flags, MAR, MDR, DPR, MH, ML, R0-R15. A difference is a *divergence*: it is recorded with the instruction that produced it, classified by C entry where the instruction says which, and the core adopts Mesen2's registers to go on (so one cause is counted once). Mesen2 is a detector, never the judge (validation.md): a divergence is a question for the C entries, not a failure of the core. """ from __future__ import annotations import gzip import re from bisect import bisect_right from collections import Counter from collections.abc import Iterator from dataclasses import dataclass, field from pathlib import Path from hg51b_python._decode import OPS from hg51b_python.cpu import HG51B from hg51b_python.disasm import text as disassemble_text from hg51b_python.harness import Harness #: Chip clocks per master clock: the 20 MHz crystal (fullsnes "External Oscillators") over #: the NTSC master clock, 21,477,270 Hz. Converting the trace's stamps with it lines the #: recorded runs up (rung 4), which is the evidence it is the ratio Mesen2 uses. MESEN2_CLOCK_RATIO = 20_000_000 / 21_477_270 _LINE = re.compile( r"^(?P
[0-9A-F]{6})\s+[0-9A-F]{6} (?P\d+) (?P Counter:
return Counter(d.entry for d in self.divergences)
def summary(self) -> list[str]:
lines = [
f"host events {self.events}, runs {self.runs}"
f" ({self.runs_compared} in the trace window)",
f"instructions compared {self.instructions_compared} of {self.trace_lines} trace lines"
f" ({self.trace_lines_unmatched} outside compared runs,"
f" {self.trace_lines_dropped} dropped: the cycle count went backwards)",
f"divergences {len(self.divergences)}: {dict(self.entries())}",
f"run length mismatches {len(self.run_length_mismatches)}",
f"S-CPU reads compared {self.reads_compared}, mismatches {len(self.read_mismatches)}",
f"status polls the core answered differently (timing only): {dict(self.status_timing)}",
f"writes while the core ran {self.writes_while_running}; "
f"starts while it was busy {self.starts_while_busy}",
f"deepest stack {self.deepest_stack}; register shift counts {dict(self.shift_counts)}",
f"far jumps (target PB, already cached) {dict(self.far_jumps)}",
f"shifted ALU ops {dict(self.shifted_total)}; A< str:
"""Name the C entry a divergence belongs to, from the instruction that produced it."""
if previous is None:
return "start"
key, sub = OPS[previous >> 8]
names = set(registers)
if key.startswith(("shr", "asr", "ror", "shl")):
return "C1"
if key.startswith(("add", "sub", "subr", "cmp", "cmpr")) and sub and names <= {"flags", "a"}:
return "C2"
if names <= {"mh", "ml"}:
return "C6"
if names <= {"mdr"}:
return "C7"
if key == "rts" and names & {"pb", "pc"}:
return "C4"
if key in ("jmp", "jsr") and names & {"pb"}:
return "C5/C17"
if key == "ld_p_reg" and names <= {"p"}:
return "C11"
if key == "clear":
return "C10"
if previous & 0x7F == 0 and key.endswith("_reg"):
return "C16"
return "unclassified"
class Replay:
def __init__(
self,
rom: bytes,
host: list[HostEvent],
trace: list[TraceLine],
*,
core: type[HG51B] = HG51B,
poll_clocks: int = 64,
max_divergences: int = 1000,
) -> None:
self.harness = Harness(rom, core=core)
self.cx = self.harness.cx
self.host = host
self.trace = trace
self.poll_clocks = poll_clocks
self.max_divergences = max_divergences
self.report = ReplayReport(events=len(host), trace_lines=len(trace))
# Split the trace into runs by the start writes' cycle stamps.
starts: list[int] = []
entries: list[tuple[int, int]] = [] # (PB, PC) each run starts at
pb = 0
for e in host:
if e.write and e.address & 0x0C00 == 0x0C00:
register = e.address & 0x3FF
if register == 0x34D:
pb = pb & 0x7F00 | e.value
elif register == 0x34E:
pb = pb & 0xFF | (e.value & 0x7F) << 8
elif register == 0x34F and e.stamp is not None:
starts.append(int(e.stamp * MESEN2_CLOCK_RATIO))
entries.append((pb, e.value))
self._runs: dict[int, list[TraceLine]] = {}
for line in trace:
run = bisect_right(starts, line.cycle) - 1
self._runs.setdefault(run, []).append(line)
first = min(self._runs, default=None)
if first is not None and first >= 0:
head = self._runs[first][0]
if (head.pb, (head.address >> 1) & 0xFF) != entries[first]:
del self._runs[first] # the window opened mid-run
self._run = -1
self._lines: list[TraceLine] | None = None
self._k = 0
self._base = 0
# ----- driving the core ------------------------------------------------------------
def _advance(self, clocks: int | None) -> None:
"""Run ``clocks`` (None: until idle); unit by unit while a traced run executes."""
cx = self.cx
if self._lines is None:
if clocks is None:
guard = 0
while cx.running:
cx.run(256)
guard += 256
if guard > 400_000_000:
raise RuntimeError("the core did not go idle")
else:
cx.run(clocks)
return
target = None if clocks is None else cx.clock + clocks - cx._debt
while cx.running if target is None else cx.clock < target:
if self._lines is None: # comparison stopped mid-run (control flow diverged)
if target is None:
self._advance(None)
else:
cx.run(target - cx.clock)
return
ready = not (
cx.lock or cx.suspend_enabled or cx.cache_enabled or cx.dma_enabled or cx.halted
)
if ready and self._k < len(self._lines) and self._k == cx.instructions - self._first:
self._compare(self._lines[self._k])
if self._lines is None:
continue
before = cx.instructions
cx.step()
if cx.instructions != before:
self._observe()
self._k += 1
if target is not None:
cx._debt = max(0, cx.clock - target)
def _observe(self) -> None:
cx = self.cx
depth = sum(1 for entry in cx.stack if entry)
self.report.deepest_stack = max(self.report.deepest_stack, depth)
def _compare(self, line: TraceLine) -> None:
cx = self.cx
report = self.report
report.instructions_compared += 1
# The word about to run: from whichever cache page holds PB (after a far jump the
# lookup that selects it has not happened yet), or the trace's when a load is due.
address = (cx.cache_base + (cx.pb << 9)) & 0xFFFFFF
if address in cx.cache_address:
word = cx.program_ram[cx.cache_address.index(address)][cx.pc]
else:
word = line.word
previous = self._previous
self._previous = word
key = OPS[word >> 8][0]
if key in ("shr_reg", "asr_reg", "ror_reg", "shl_reg"):
report.shift_counts[
cx._get(word) & 0x1F if word & 0x7F not in (0x2E, 0x2F) else -1
] += 1
sub = word >> 8 & 3
if sub and key.startswith(("add", "sub", "cmp", "xnor", "xor", "and", "or")):
name = key.upper().replace("_", " ") + f" A<<{(0, 1, 8, 16)[sub]}"
report.shifted_total[name] += 1
adder = key.startswith(("add", "sub", "cmp")) # C2 is about the adder only
if adder and cx.a << (0, 1, 8, 16)[sub] > 0xFFFFFF:
report.shifted_wide[f"{name} @ {cx.pb:04X}:{cx.pc:02X}"] += 1
after_mul = previous is not None and OPS[previous >> 8][0].startswith("mul")
if after_mul and key.endswith("_reg") and word & 0x7F in (0x01, 0x02):
report.mul_then_read += 1
if key in ("jmp", "jsr") and word & 0x200:
cached = (cx.cache_base + (cx.p << 9)) & 0xFFFFFF in cx.cache_address
report.far_jumps[(cx.p, cached)] += 1
mine = {
"a": cx.a, "p": cx.p, "mar": cx.mar, "mdr": cx.mdr, "dpr": cx.dpr,
"mh": cx.mul >> 24, "ml": cx.mul & 0xFFFFFF,
} # fmt: skip
for i in range(16):
mine[f"r{i}"] = cx.r[i]
differ = {k: (mine[k], line.values[k]) for k in mine if mine[k] != line.values[k]}
flags = "".join(
(letter.upper() if getattr(cx, letter) else letter) for letter in ("c", "z", "v", "n")
)
if flags != line.flags:
differ["flags"] = (int(flags.encode().hex(), 16), int(line.flags.encode().hex(), 16))
pc = ((line.address - self._base - line.pb * 512) >> 1) & 0xFF
if cx.pb != line.pb:
differ["pb"] = (cx.pb, line.pb)
if cx.pc != pc:
differ["pc"] = (cx.pc, pc)
if word != line.word and "pc" not in differ and "pb" not in differ:
differ["word"] = (word, line.word)
if not differ:
return
if len(report.divergences) < self.max_divergences:
report.divergences.append(
Divergence(
self._run,
self._k,
line.frame,
previous,
line.word,
differ,
classify(previous, differ, cx),
)
)
# Adopt Mesen2's registers so one cause is counted once.
cx.a, cx.p, cx.mar, cx.mdr, cx.dpr = (
line.values[k] for k in ("a", "p", "mar", "mdr", "dpr")
)
cx.mul = line.values["mh"] << 24 | line.values["ml"]
cx.r[:] = [line.values[f"r{i}"] for i in range(16)]
cx.c, cx.z, cx.v, cx.n = (ch.isupper() for ch in line.flags)
if "pb" in differ or "pc" in differ:
self._lines = None # control flow left Mesen2's: stop comparing this run
# ----- the stream ------------------------------------------------------------------
def run(self) -> ReplayReport:
cx, report = self.cx, self.report
self._previous = None
self._first = 0
for event in self.host:
address = event.address
io = address & 0x0C00 == 0x0C00
register = address & 0x3FF if io else -1
if event.write:
if register in (0x347, 0x348, 0x34F):
if cx.running:
report.starts_while_busy += 1
self._advance(None)
self._close_run()
for _ in range(event.count):
cx.write(address, event.value)
if register == 0x34F:
self._open_run()
continue
if cx.running:
report.writes_while_running += event.count
for _ in range(event.count):
cx.write(address, event.value)
if register in (0x349, 0x34A, 0x34B):
self._base = cx.cache_base
continue
if io and 0x353 <= register < 0x360: # status
if event.value & 0x40:
for _ in range(event.count):
if not cx.running:
report.status_timing["core idle, Mesen2 running"] += 1
self._advance(self.poll_clocks)
continue
self._advance(None)
report.reads_compared += 1
got = cx.read(address)
if got != event.value:
report.read_mismatches.append(
(event.frame, address, got, event.value, "status")
)
continue
for _ in range(event.count):
report.reads_compared += 1
got = cx.read(address)
if got != event.value and cx.running:
report.status_timing["read while running"] += 1
self._advance(None)
got = cx.read(address)
if got != event.value:
why = "data RAM" if not io else "I/O"
report.read_mismatches.append((event.frame, address, got, event.value, why))
self._advance(None)
self._close_run()
report.trace_lines_unmatched = report.trace_lines - sum(
len(lines) for lines in self._runs.values()
)
return report
def _open_run(self) -> None:
self._run += 1
self.report.runs += 1
lines = self._runs.get(self._run)
if lines:
self.report.runs_compared += 1
self._lines = lines
self._k = 0
self._first = self.cx.instructions
self._previous = None
else:
self._lines = None
def _close_run(self) -> None:
if self._lines is not None:
executed = self.cx.instructions - self._first
truncated = self._lines[-1] is self.trace[-1] and executed > len(self._lines)
if executed != len(self._lines) and not truncated: # the window may end mid-run
self.report.run_length_mismatches.append((self._run, executed, len(self._lines)))
self._lines = None
def replay(
rom: bytes,
recording: str | Path,
*,
core: type[HG51B] = HG51B,
poll_clocks: int = 64,
) -> ReplayReport:
"""Replay ``recording`` (a directory with ``host.txt.gz`` and ``cx4.trace.gz``)."""
directory = Path(recording)
host = read_host(directory / "host.txt.gz")
trace_path = directory / "cx4.trace.gz"
trace = list(read_trace(trace_path)) if trace_path.exists() else []
trace, dropped = monotonic(trace)
report = Replay(rom, host, trace, core=core, poll_clocks=poll_clocks).run()
report.trace_lines_dropped = dropped
return report
def monotonic(trace: list[TraceLine]) -> tuple[list[TraceLine], int]:
"""Cut the trace where its cycle count goes backwards. Mesen2's trace logger writes
rows from a ring buffer, and the rows flushed by ``StopLogTraceToFile`` can repeat
older ones (measured: 144 rows 156 cycles back at the end of a 299,416-row window)."""
for i in range(1, len(trace)):
if trace[i].cycle < trace[i - 1].cycle:
return trace[:i], len(trace) - i
return trace, 0
__all__ = [
"MESEN2_CLOCK_RATIO",
"Divergence",
"HostEvent",
"Replay",
"ReplayReport",
"TraceLine",
"classify",
"monotonic",
"read_host",
"read_trace",
"replay",
]