#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Run a lockstep scenario on arm7tdmi-python and write its slice trace (the reference's half). The same scenarios and the same lines as ``src/bin/arm7-trace.rs`` (its documentation has the format), run on the reference core: a test ROM in the reference's own minimal harness (``arm7tdmi_python.harness.Harness`` with an observer), or random memory with a random state and the IRQ and FIQ lines changed between instructions. Run with the reference's interpreter, the pinned clone first on its path (scripts/env.sh). reference_trace.py SCENARIO.json [--out TRACE] [--detail FROM TO] """ from __future__ import annotations import argparse import json import os import struct import sys import zlib from pathlib import Path from arm7tdmi_python import ARM7TDMI, CODE, CPUState from arm7tdmi_python.harness import EnteredBIOS, Harness PACK = struct.Struct(" None: self.bus = bytearray() self.detail = False self.lines: list[str] = [] def record(self, kind: int, size: int, address: int, value: int, access: int) -> None: self.bus += PACK(kind, size, address, value, access) if self.detail: self.lines.append(f" {kind} {size} {address:08x} {value:08x} {access}") def words_hex(words) -> str: return " ".join(f"{w:08x}" for w in words) class Slicer: def __init__(self, slice_: int, log: Log, out, detail) -> None: self.slice, self.log, self.out, self.detail = slice_, log, out, detail self.steps = self.cycles = self.in_slice = 0 self.states = bytearray() def in_detail(self, step: int) -> bool: return self.detail is not None and self.detail[0] <= step < self.detail[1] def after_step(self, cpu, cycles: int) -> None: self.steps += 1 self.cycles += cycles self.in_slice += 1 words = cpu.capture_state().to_sst() self.states += struct.pack(" None: bus = zlib.crc32(self.log.bus) state = zlib.crc32(self.states) if self.detail is None: self.out.write(f"{self.steps} {self.cycles} {bus:08x} {state:08x} {words_hex(words)}\n") self.log.bus.clear() self.states.clear() self.in_slice = 0 def run_rom(scenario: dict, out, detail) -> None: rom = Path(scenario["rom"].replace("$TEST_ROMS", os.environ.get("TEST_ROMS", ""))).read_bytes() log = Log() log.detail = detail is not None and detail[0] <= 0 < detail[1] def observer(kind: str, address: int, width: int, access: int, value: int) -> None: code = {"read": 1, "write": 2}.get(kind, 3) if kind == "read" and access & CODE: code = 0 log.record(code, width // 8, address, value, access) harness = Harness(rom, observer=observer) out.write(f"start {harness.cycles} {zlib.crc32(log.bus):08x} {words_hex(harness.cpu.capture_state().to_sst())}\n") log.bus.clear() log.lines.clear() slicer = Slicer(scenario.get("slice", 1), log, out, detail) max_steps = scenario.get("max_steps", 1_000_000) cpu = harness.cpu while True: if harness.at_branch_to_self(): end = f"end branch-to-self r12={cpu.r[12]} cycles={harness.cycles}" break if slicer.steps >= max_steps: end = f"end max-steps cycles={harness.cycles}" break try: cycles = cpu.step() except EnteredBIOS as error: end = f"end bios r12={cpu.r[12]} cycles={harness.cycles} {error}" break slicer.after_step(cpu, cycles) if slicer.in_slice: slicer.flush(cpu.capture_state().to_sst()) out.write(end + "\n") def run_fuzz(scenario: dict, base: Path, out, detail) -> None: memory = bytearray((base / scenario["memory"]).read_bytes()) mask = scenario["mask"] log = Log() log.detail = detail is not None and detail[0] <= 0 < detail[1] cpu = None def read(address: int, width: int, access: int) -> int: offset = (address & ~(width // 8 - 1)) & mask value = int.from_bytes(memory[offset : offset + width // 8], "little") log.record(0 if access & CODE else 1, width // 8, address, value, access) return value def write(address: int, width: int, value: int, access: int) -> None: offset = (address & ~(width // 8 - 1)) & mask memory[offset : offset + width // 8] = value.to_bytes(width // 8, "little") log.record(2, width // 8, address, value, access) def idle(address: int) -> None: log.record(3, 0, address, 0, 1 if cpu.coprocessor_cycle else 0) cpu = ARM7TDMI(read, write, idle) s = scenario["state"] cpu.restore_state( CPUState( registers=list(s["registers"]), banks=[list(b) for b in s["banks"]], cpsr=s["cpsr"], spsr=list(s["spsr"]), pipeline=list(s["pipeline"]), next_fetch_seq=s["next_fetch_seq"], ) ) lines = scenario["lines"] next_line = 0 slicer = Slicer(scenario.get("slice", 16), log, out, detail) while slicer.steps < scenario["steps"]: while next_line < len(lines) and lines[next_line][0] == slicer.steps: cpu.irq = bool(lines[next_line][1]) cpu.fiq = bool(lines[next_line][2]) next_line += 1 try: cycles = cpu.step() except IndexError: # A Thumb step with an ARM word in the pipeline (MSR set T: reported upstream, # docs/status.md "Reported to the reference"): both sides must stop here alike. out.write(f"end crash steps={slicer.steps} cycles={slicer.cycles}\n") return slicer.after_step(cpu, cycles) if slicer.in_slice: slicer.flush(cpu.capture_state().to_sst()) out.write(f"end steps={slicer.steps} cycles={slicer.cycles}\n") def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("scenario", type=Path) parser.add_argument("--out", type=Path) parser.add_argument("--detail", nargs=2, type=int) args = parser.parse_args() scenario = json.loads(args.scenario.read_text()) out = args.out.open("w") if args.out else sys.stdout with out: if scenario["kind"] == "rom": run_rom(scenario, out, args.detail) else: run_fuzz(scenario, args.scenario.parent, out, args.detail) return 0 if __name__ == "__main__": sys.exit(main())