#!/usr/bin/env python3 # SPDX-License-Identifier: GPL-3.0-or-later """nuked-harness's command line (README.md): one run of a Nuked chip model on a write script. python3 -I run.py --machine CHIP --input WRITES.jsonl --cycles N --out DIR [--stride N] python3 -I run.py --version CHIP: ym2612, ym3438 (Nuked-OPN2), ym2413, ds1001 (Nuked-OPLL), psg (Nuked-PSG), ym2151, ym2164 (Nuked-OPM). Writes the harness's record stream and the contract's manifest.json. """ from __future__ import annotations import argparse import datetime import hashlib import json import platform import struct import subprocess import sys import tempfile from pathlib import Path TOOL, VERSION = "nuked-harness", "0.1.0" HERE = Path(__file__).resolve().parent BUILD = HERE / "build" UPSTREAMS = { "Nuked-OPN2": ("335747d78cb0abbc3b55b004e62dad9763140115", "LGPL-2.1-or-later"), "Nuked-OPLL": ("1269cf5a783b65583b50fa2464d08be75830aaa0", "GPL-2.0-or-later"), "Nuked-PSG": ("d15a168c676f4669e23660be9225b34ad7c1764e", "GPL-2.0-or-later"), "Nuked-OPM": ("f209e6ed3712032b641d53ce8fb24824eae6adc3", "LGPL-2.1-or-later"), } # machine: (upstream, harness binary, chip argument, record format, record layout) MACHINES = { "ym2612": ("Nuked-OPN2", "opn2-events", "ym2612", "nuked/opn2", " str: return hashlib.sha1(data).hexdigest() def tool_commit() -> str: try: head = subprocess.run(["git", "-C", str(HERE), "rev-parse", "HEAD"], capture_output=True, text=True, check=True).stdout.strip() # fmt: skip dirty = subprocess.run(["git", "-C", str(HERE), "status", "--porcelain", "--", "."], capture_output=True, text=True, check=True).stdout.strip() # fmt: skip except (OSError, subprocess.CalledProcessError): return "unknown" return head + ("-dirty" if dirty else "") def read_writes(path: Path, machine: str) -> list[tuple[int, int, int]]: """(time, kind, data) sorted by time; kind is the port (0-3), or 2 with OPM for /IC.""" 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 = int(row["t"]) if "ic" in row: if not machine.startswith("ym21"): raise ValueError("ic is for ym2151 and ym2164") rows.append((t, 2, 1 if row["ic"] else 0)) continue port, data = int(row.get("port", 0)), int(row["data"]) except (ValueError, KeyError, TypeError) as error: raise Usage(f"{path}:{number}: {error}") from None ports = 1 if machine == "psg" else 2 if machine.startswith(("ym21", "ym2413", "ds1")) else 4 if t < 0 or not 0 <= port < ports or not 0 <= data <= 255: raise Usage(f"{path}:{number}: t >= 0, port below {ports}, data 0-255") rows.append((t, port, data)) return sorted(rows, key=lambda r: r[0]) def run_harness(machine: str, writes, cycles: int, stride: int, work: Path) -> bytes: upstream, binary, chip, _, layout = MACHINES[machine] exe = BUILD / binary if binary == "opll-stream": # commands on standard input, one record per clock call commands, now = [], 0 for t, port, data in writes: if t >= cycles: break if t > now: commands.append(f"c {t - now}") now = t commands.append(f"w {port} {data}") commands.append(f"c {cycles - now}") done = subprocess.run([str(exe), chip], input="\n".join(commands).encode() + b"\n", capture_output=True, check=True) # fmt: skip size = struct.calcsize(layout) data = done.stdout return b"".join(data[i : i + size] for i in range(0, len(data), size * stride)) events = work / "events.bin" if binary == "psg-events": events.write_bytes(b"".join(struct.pack(" int: argv = sys.argv[1:] if argv is None else argv p = argparse.ArgumentParser(prog="run.py", description="Run a Nuked chip model on writes.") p.add_argument("--version", action="store_true") p.add_argument("--machine", choices=sorted(MACHINES)) p.add_argument("--input", type=Path, help="write script (JSON Lines: t, port, data)") p.add_argument("--cycles", type=int, help="harness calls to run (the machine's clock)") p.add_argument("--stride", type=int, default=1, help="keep one record in N") p.add_argument("--out", type=Path) a = p.parse_args(argv) if a.version: pins = ", ".join(f"{n} {c[:7]}" for n, (c, _) in UPSTREAMS.items()) print(f"{TOOL} {VERSION} ({pins})") return EXIT_OK started = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") try: if not (a.machine and a.input and a.cycles and a.out) or a.cycles < 1 or a.stride < 1: raise Usage("--machine, --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 upstream, binary, _, fmt, layout = MACHINES[a.machine] if not (BUILD / binary).exists(): print(f"no {BUILD / binary}: run build.sh", file=sys.stderr) return EXIT_MISSING writes = read_writes(a.input, a.machine) 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) with tempfile.TemporaryDirectory(prefix="nuked-") as scratch: data = run_harness(a.machine, writes, a.cycles, a.stride, Path(scratch)) name = f"{a.machine}.bin" (a.out / name).write_bytes(data) info = BUILD / "build-info.json" commit, licence = UPSTREAMS[upstream] record = { "contract": 0, "tool": TOOL, "tool_version": VERSION, "tool_commit": tool_commit(), "tool_licence": "GPL-3.0-or-later", "upstream": {"name": upstream, "url": f"https://github.com/nukeykt/{upstream}", "commit": commit, "licence": licence, "patches": [], "build": json.loads(info.read_text()) if info.exists() else "unknown"}, "machine": a.machine, "inputs": [{"role": "writes", "sha1": sha1(a.input.read_bytes()), "size": a.input.stat().st_size}], "args": argv, "seed": 0, "time_origin": "reset", "host": {"os": platform.system().lower(), "arch": platform.machine()}, "started": started, "outputs": [{"path": name, "format": fmt, "records": len(data) // struct.calcsize(layout), "layout": layout, "stride": a.stride}], "status": "ok", "evidence": "OBSERVED", } # fmt: skip (a.out / "manifest.json").write_text(json.dumps(record, indent=1) + "\n", encoding="utf-8") return EXIT_OK if __name__ == "__main__": raise SystemExit(main())