#!/usr/bin/env python3 # SPDX-License-Identifier: GPL-3.0-or-later """ay-die-model's command line (README.md): one run of lvd2's AY-3-8910 die model, with a manifest. python3 -I run.py --input EVENTS.jsonl --cycles N --out DIR python3 -I run.py --version EVENTS.jsonl: one pin event a line, {"t": clock, "kind": 0-7, "a": 0-255, "b": 0-255}, the testbench's event kinds (README.md). Writes ay.bin (one word per clock), reads.bin (one word per read) and the contract's manifest.json. Needs Icarus Verilog's vvp (PATH or OSS_CAD_SUITE). """ from __future__ import annotations import argparse import datetime import hashlib import json import os import platform import shutil import subprocess import sys import tempfile from pathlib import Path TOOL, VERSION = "ay-die-model", "0.1.0" HERE = Path(__file__).resolve().parent BUILD = HERE / "build" UPSTREAM = {"name": "ay-3-8910_reverse_engineered (deathsoft, lvd)", "url": "https://github.com/lvd2/ay-3-8910_reverse_engineered", "commit": "cf8d14db0aec5ae86ed4f4e6e67bf14c40a42d77", "licence": "GPL-3.0-or-later", "patches": ["trireg-keepers.patch"]} MAX_EVENTS = 4194304 # the testbench's event memory EXIT_OK, EXIT_CHECK, EXIT_USAGE, EXIT_MISSING = 0, 1, 2, 3 class Usage(Exception): pass def tool_commit() -> str: try: head = subprocess.run(["git", "-C", str(HERE), "rev-parse", "HEAD"], capture_output=True, text=True, check=True).stdout.strip() dirty = subprocess.run(["git", "-C", str(HERE), "status", "--porcelain", "--", "."], capture_output=True, text=True, check=True).stdout.strip() except (OSError, subprocess.CalledProcessError): return "unknown" return head + ("-dirty" if dirty else "") def vvp() -> str | None: suite = os.environ.get("OSS_CAD_SUITE") return (shutil.which("vvp", path=f"{suite}/bin") if suite else None) or shutil.which("vvp") def read_events(path: Path) -> list[tuple[int, int, int, int]]: rows = [] for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1): if not line.strip(): continue try: row = json.loads(line) t, kind = int(row["t"]), int(row["kind"]) a, b = int(row.get("a", 0)), int(row.get("b", 0)) except (ValueError, KeyError, TypeError) as error: raise Usage(f"{path}:{number}: {error}") from None if not 0 <= t < 1 << 40 or not 0 <= kind <= 7 or not 0 <= a <= 255 or not 0 <= b <= 255: raise Usage(f"{path}:{number}: 0 <= t < 2**40, kind 0-7, a and b 0-255") rows.append((t, kind, a, b)) if len(rows) > MAX_EVENTS: raise Usage(f"{path}: at most {MAX_EVENTS} events") return sorted(rows, key=lambda r: r[0]) def main(argv: list[str] | None = None) -> int: argv = sys.argv[1:] if argv is None else argv p = argparse.ArgumentParser(prog="run.py", description="Run the AY-3-8910 die model.") p.add_argument("--version", action="store_true") p.add_argument("--input", type=Path, help="pin events (JSON Lines: t, kind, a, b)") p.add_argument("--cycles", type=int, help="input clocks to run and sample") p.add_argument("--out", type=Path) a = p.parse_args(argv) if a.version: print(f"{TOOL} {VERSION} (ay-3-8910_reverse_engineered {UPSTREAM['commit'][:7]})") return EXIT_OK started = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") try: if not (a.input and a.cycles and a.out) or a.cycles < 1: raise Usage("--input, --cycles (>= 1) and --out are required") if not a.input.is_file(): print(f"no such input: {a.input}", file=sys.stderr) return EXIT_MISSING events = read_events(a.input) if not (BUILD / "ay_ref").exists(): print(f"no {BUILD / 'ay_ref'}: run build.sh", file=sys.stderr) return EXIT_MISSING runtime = vvp() if runtime is None: print("vvp (Icarus Verilog) not found: PATH or OSS_CAD_SUITE", file=sys.stderr) return EXIT_MISSING except Usage as error: p.print_usage(sys.stderr) print(f"run.py: {error}", file=sys.stderr) return EXIT_USAGE a.out.mkdir(parents=True, exist_ok=True) out, reads = a.out / "ay.bin", a.out / "reads.bin" with tempfile.TemporaryDirectory(prefix="ay-die-model-") as scratch: hexfile = Path(scratch) / "events.hex" hexfile.write_text("".join(f"{t << 24 | k << 16 | x << 8 | y:016x}\n" for t, k, x, y in events)) subprocess.run([runtime, str(BUILD / "ay_ref"), f"+events={hexfile}", f"+count={len(events)}", f"+out={out}", f"+reads={reads}", f"+clocks={a.cycles}"], check=True, stdout=subprocess.DEVNULL) info = BUILD / "build-info.json" data = a.input.read_bytes() record = { "contract": 0, "tool": TOOL, "tool_version": VERSION, "tool_commit": tool_commit(), "tool_licence": "GPL-3.0-or-later", "upstream": {**UPSTREAM, "build": json.loads(info.read_text()) if info.exists() else "unknown"}, "machine": "ay-3-8910", "inputs": [{"role": "events", "sha1": hashlib.sha1(data).hexdigest(), "size": len(data)}], "args": argv, "seed": 0, "time_origin": "reset", "host": {"os": platform.system().lower(), "arch": platform.machine()}, "started": started, "outputs": [ {"path": "ay.bin", "format": "ay-die-model/pins", "records": out.stat().st_size // 4, "layout": "