#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Run a scenario on 65816-python and write its boundary trace (the reference's half). reference_trace.py SCENARIO.json [--out TRACE.jsonl] The same scenario format as ``src/bin/trace.rs`` (conformance/README.md), run on the reference core through its own ``W65C816Session`` with access tracking, each record made by its own ``step_record_to_dict`` and written as its ``write_trace`` writes one (sorted keys, no spaces), less the instruction's ``mnemonic`` and ``operands``: the disassembly is Python-side tooling, and the reference's reader rebuilds it from the bytes. A trace written here therefore equals the crate's byte for byte when the two cores agree. Run it with the reference's interpreter. """ from __future__ import annotations import argparse import json import sys from pathlib import Path from sixfiveohtwo.trace import step_record_to_dict from w65c816 import W65C816 from w65c816.debug import W65C816Session from w65c816.harness import SPIN_OPCODES, Harness, load_rom REGISTERS = ("a", "x", "y", "s", "d", "dbr", "pbr", "pc", "p", "e") def fill_random(memory: bytearray, fill: dict) -> None: """A 32-bit xorshift, one byte per step (src/bin/trace.rs's fill_random).""" state = fill["seed"] | 1 address = fill["address"] for offset in range(fill["length"]): state ^= (state << 13) & 0xFFFFFFFF state ^= state >> 17 state ^= (state << 5) & 0xFFFFFFFF memory[(address + offset) & 0xFFFFFF] = state >> 24 def act(cpu, action: str) -> None: { "irq": cpu.request_maskable_interrupt, "irq_clear": cpu.clear_maskable_interrupt, "nmi": cpu.request_non_maskable_interrupt, "nmi_clear": cpu.clear_non_maskable_interrupt, "abort": cpu.request_abort, "reset": cpu.request_reset, }[action]() class Host: """Flat 16 MiB memory, the scenario's in-cycle requests and its RDY stalls.""" def __init__(self, memory: bytearray, during: dict, stalls: dict) -> None: self.memory = memory self.during = during self.stalls = stalls self.count = 0 self.cpu = None def cycle(self) -> None: index = self.count self.count += 1 cpu = self.cpu for action in self.during.get(index, ()): act(cpu, action) stall = self.stalls.get(index) if stall is not None: cpu.note_stall() for cycle in range(1, stall["halted"] + 1): for event in stall.get("during", ()): if event["cycle"] == cycle: act(cpu, event["action"]) cpu.note_stall() def read_byte(self, address: int) -> int: self.cycle() return self.memory[address] def write_byte(self, address: int, value: int) -> None: self.cycle() self.memory[address] = value def idle(self, address: int) -> None: self.cycle() def flat(path: Path, scenario: dict): memory = bytearray(1 << 24) for fill in scenario.get("fill", ()): fill_random(memory, fill) for block in scenario.get("memory", ()): if "hex" in block: data = bytes.fromhex(block["hex"]) else: file = Path(block["file"]) data = (file if file.is_absolute() else path.parent / file).read_bytes() if "length" in block: data = data[: block["length"]] for offset, byte in enumerate(data): memory[(block["address"] + offset) & 0xFFFFFF] = byte during: dict[int, list[str]] = {} between: dict[int, list[str]] = {} for event in scenario.get("events", ()): if "step" in event: between.setdefault(event["step"], []).append(event["action"]) else: during.setdefault(event["access"], []).append(event["action"]) stalls = {stall["access"]: stall for stall in scenario.get("stalls", ())} host = Host(memory, during, stalls) cpu = W65C816(host.read_byte, host.write_byte, host.idle) host.cpu = cpu return cpu, memory.__getitem__, between def records(path: Path): scenario = json.loads(path.read_text()) harness = None if "rom" in scenario: rom = Path(scenario["rom"]) harness = Harness(load_rom(rom if rom.is_absolute() else path.parent / rom)) cpu, peek, between = harness.cpu, harness.inspect, {} else: cpu, peek, between = flat(path, scenario) registers = scenario.get("registers", {}) for name in REGISTERS: if name in registers: setattr(cpu, name, registers[name]) if scenario.get("reset"): cpu.request_reset() session = W65C816Session(cpu, peek_byte=peek, track_accesses=scenario.get("accesses", True)) until_spin = "rom" in scenario and scenario.get("until_spin", False) resets = scenario.get("reset_on_stop", 0) for sequence in range(scenario["steps"]): for action in between.get(sequence, ()): act(cpu, action) before = cpu.pbr << 16 | cpu.pc yield session.step() if until_spin: # Harness.run's stop conditions, in its order; rung 3 resets # CPUMSC once after its STP. if cpu.stopped: if resets: resets -= 1 cpu.request_reset() continue break if (cpu.pbr << 16 | cpu.pc) == before and harness.peek(before) in SPIN_OPCODES: break def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("scenario", type=Path) parser.add_argument("--out", type=Path) args = parser.parse_args() stream = args.out.open("w") if args.out else sys.stdout with stream: for record in records(args.scenario): encoded = step_record_to_dict(record) instruction = encoded["instruction"] if instruction is not None: del instruction["mnemonic"], instruction["operands"] stream.write(json.dumps(encoded, separators=(",", ":"), sort_keys=True) + "\n") return 0 if __name__ == "__main__": sys.exit(main())