#!/usr/bin/env python3 """Explicit OSS CAD Suite bootstrap helper for Prod2U P4 verification. This script is intentionally not called by the normal harness. It never installs tools implicitly; the user must run it directly and choose a download or extraction action. """ from __future__ import annotations import argparse import hashlib import json import os import shutil import sys import urllib.request import zipfile import subprocess from pathlib import Path from typing import Any def _default_toolchain_base() -> Path: if sys.platform.startswith("linux"): override = os.environ.get("PRODU2_TOOLCHAIN_BASE", "").strip() if override: return Path(override) # Durable volume survives container rebuild; overlay ~/.cache does not. persistent = Path("/data/prod2u") if persistent.is_dir() or os.access("/data", os.W_OK): return persistent return Path.home() / ".cache" / "prod2u" return Path.home() / "CodexToolchains" / "CPLD" DEFAULT_TOOLCHAIN_BASE = _default_toolchain_base() DEFAULT_ROOT = DEFAULT_TOOLCHAIN_BASE / "oss-cad-suite" / "latest" DEFAULT_DOWNLOAD_DIR = DEFAULT_TOOLCHAIN_BASE / "downloads" DEFAULT_COCOTB_VENV = ( DEFAULT_TOOLCHAIN_BASE / "venvs" / "prod2u-p4-actuator-trace-cocotb-venv" ) DEFAULT_BUNDLED_PYTHON = Path.home() / ".cache" / "codex-runtimes" / "codex-primary-runtime" / "dependencies" / "python" / "python.exe" DEFAULT_COCOTB_VERSION = "1.9.2" DEFAULT_EXTRA_PYTHON_PACKAGES = ["pytest", "hypothesis", "pyserial", "pyserial-asyncio"] OWNER_MARKER_NAME = ".cpld_toolchain_owner.json" INSTALL_MANIFEST_NAME = ".cpld_toolchain_manifest.json" TOOLCHAIN_SHIM_DIR = Path(__file__).resolve().parent / "toolchain_shims" VERILATOR_SHIM = TOOLCHAIN_SHIM_DIR / "verilator.ps1" ACTIVATION_SCRIPT = Path(__file__).resolve().parent / "activate_verification_toolchain.ps1" RELEASES_URL = "https://github.com/YosysHQ/oss-cad-suite-build/releases" LATEST_API_URL = "https://api.github.com/repos/YosysHQ/oss-cad-suite-build/releases/latest" REQUIRED_TOOLS = ["iverilog", "vvp", "verilator", "yosys", "sby"] def _verilator_candidates(bin_dir: Path) -> tuple[Path, ...]: # Prefer the platform-native binary; never accept the extensionless # shell/batch launcher named plain "verilator". Include both Linux and # Windows native names so unit fixtures and cross-extracted trees resolve. linux_native = (bin_dir / "verilator_bin",) windows_native = (bin_dir / "verilator_bin.exe", bin_dir / "verilator.exe") if sys.platform.startswith("linux"): return linux_native + windows_native return windows_native + linux_native def tool_status(root: Path) -> dict[str, Any]: bin_dir = root / "bin" tools = {} for name in REQUIRED_TOOLS: if name == "verilator": candidates = _verilator_candidates(bin_dir) else: candidates = (bin_dir / f"{name}.exe", bin_dir / name) path = next((candidate for candidate in candidates if candidate.is_file()), None) tools[name] = { "status": "present" if path is not None else "missing", "path": str(path.resolve()) if path is not None else None, } return { "schema": "prod2u-p4-actuator-trace-oss-cad-suite-bootstrap-v1", "install_root": str(root), "owner_marker": str(root / OWNER_MARKER_NAME), "bin_dir": str(bin_dir), "tools": tools, "releases_url": RELEASES_URL, "env": { "PROD2U_P4_TOOLCHAIN_ROOT": str(root), "OSS_CAD_SUITE_ROOT": str(root), "VERILATOR": tools["verilator"]["path"], "path_addition": str(bin_dir), }, "authority_boundary": "This helper only downloads/extracts a user-selected OSS CAD Suite archive; it does not prove those tools pass this project.", } def _assert_under(parent: Path, target: Path, label: str) -> Path: parent_resolved = parent.resolve() target_resolved = target.resolve() if target_resolved != parent_resolved and parent_resolved not in target_resolved.parents: raise ValueError(f"{label} must stay under {parent_resolved}: {target_resolved}") return target_resolved def _assert_safe_toolchain_root(path: Path) -> Path: resolved = path.resolve() home = Path.home().resolve() base = DEFAULT_TOOLCHAIN_BASE.resolve() _assert_under(base, resolved, "toolchain path") if resolved in {home, home.parent, Path(resolved.anchor), base}: raise ValueError(f"unsafe toolchain root: {resolved}") # Never install into the source checkout that ships this helper (or nested paths). workspace_root = Path(__file__).resolve().parents[1] if resolved == workspace_root or workspace_root in resolved.parents: raise ValueError(f"unsafe toolchain root: {resolved}") return resolved def _write_owner_marker(root: Path, component: str, payload: dict[str, Any]) -> None: root.mkdir(parents=True, exist_ok=True) marker = { "schema": "cpld-toolchain-owner-v1", "component": component, "root": str(root), "safety": { "opens_com_ports": False, "toggles_dtr_rts": False, "installs_drivers": False, "programs_flash": False, "touches_real_board_io": False, }, "payload": payload, } (root / OWNER_MARKER_NAME).write_text(json.dumps(marker, indent=2) + "\n", encoding="utf-8") def _write_install_manifest(root: Path, payload: dict[str, Any]) -> Path: manifest_path = root / INSTALL_MANIFEST_NAME manifest_path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") return manifest_path def _is_owned(root: Path, component: str | None = None) -> bool: marker = root / OWNER_MARKER_NAME if not marker.is_file(): return False if component is None: return True try: payload = json.loads(marker.read_text(encoding="utf-8-sig")) except json.JSONDecodeError: return False return payload.get("component") == component def sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def powershell_literal(value: str | Path) -> str: return "'" + str(value).replace("'", "''") + "'" def fetch_latest_release() -> dict[str, Any]: request = urllib.request.Request( LATEST_API_URL, headers={"User-Agent": "prod2u-p4-actuator-trace-toolchain-bootstrap"}, ) with urllib.request.urlopen(request, timeout=30) as response: return json.loads(response.read().decode("utf-8")) def select_windows_x64_asset(release_payload: dict[str, Any]) -> dict[str, Any]: for asset in release_payload.get("assets", []): name = asset.get("name", "") if name.startswith("oss-cad-suite-windows-x64-") and name.endswith(".exe"): if asset.get("browser_download_url"): return asset raise ValueError("No oss-cad-suite-windows-x64-*.exe asset found in release payload") def select_linux_x64_asset(release_payload: dict[str, Any]) -> dict[str, Any]: for asset in release_payload.get("assets", []): name = asset.get("name", "") if name.startswith("oss-cad-suite-linux-x64-") and name.endswith(".tgz"): if asset.get("browser_download_url"): return asset raise ValueError("No oss-cad-suite-linux-x64-*.tgz asset found in release payload") def _is_tar_archive(path: Path) -> bool: lowered = path.name.lower() return lowered.endswith(".tgz") or lowered.endswith(".tar.gz") or lowered.endswith(".tar") def _curl_env() -> dict[str, str]: env = os.environ.copy() for key in ( "http_proxy", "https_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "all_proxy", ): env.pop(key, None) return env def download_file(url: str, output: Path) -> None: output.parent.mkdir(parents=True, exist_ok=True) curl = shutil.which("curl.exe") or shutil.which("curl") if curl: cmd = [ curl, "-L", "--fail", "-C", "-", "--retry", "3", "--connect-timeout", "30", "--output", str(output), url, ] try: result = subprocess.run( cmd, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=7200, env=_curl_env(), ) except subprocess.TimeoutExpired as exc: raise RuntimeError(f"curl download timed out; rerun the command to resume: {exc}") from exc if result.returncode != 0: detail = (result.stdout + result.stderr)[-2000:] raise RuntimeError(f"curl download failed with returncode {result.returncode}: {detail}") else: temp_output = output.with_suffix(output.suffix + ".part") if temp_output.exists(): temp_output.unlink() request = urllib.request.Request( url, headers={"User-Agent": "prod2u-p4-actuator-trace-toolchain-bootstrap"}, ) with urllib.request.urlopen(request, timeout=60) as response, temp_output.open("wb") as handle: shutil.copyfileobj(response, handle) if not temp_output.is_file() or temp_output.stat().st_size == 0: raise RuntimeError(f"download produced empty file: {temp_output}") temp_output.replace(output) if not output.is_file() or output.stat().st_size == 0: raise RuntimeError(f"download produced empty file: {output}") def extract_archive(archive: Path, install_root: Path) -> None: install_root = _assert_safe_toolchain_root(install_root) install_root.parent.mkdir(parents=True, exist_ok=True) suffix = archive.suffix.lower() if suffix == ".zip": staging = install_root.with_name(install_root.name + ".staging") if staging.exists(): if not _is_owned(staging, "oss_cad_suite_staging"): raise RuntimeError(f"refusing to replace unowned staging directory: {staging}") shutil.rmtree(staging) staging.mkdir(parents=True, exist_ok=True) _write_owner_marker(staging, "oss_cad_suite_staging", {"archive": str(archive)}) with zipfile.ZipFile(archive) as zf: for member in zf.namelist(): _assert_under(staging, staging / member, "zip member") zf.extractall(staging) if install_root.exists(): if not _is_owned(install_root, "oss_cad_suite"): raise RuntimeError(f"refusing to replace unowned install root: {install_root}") shutil.rmtree(install_root) staging.rename(install_root) _write_owner_marker(install_root, "oss_cad_suite", {"archive": str(archive)}) elif suffix == ".exe": if install_root.exists(): if not _is_owned(install_root, "oss_cad_suite"): raise RuntimeError(f"refusing to replace unowned install root: {install_root}") shutil.rmtree(install_root) install_root.mkdir(parents=True, exist_ok=True) _write_owner_marker(install_root, "oss_cad_suite", {"archive": str(archive), "extractor": "sfx"}) commands = [ [str(archive), "-y", f"-o{install_root}"], [str(archive), "/S", f"/D={install_root}"], ] last_result: subprocess.CompletedProcess[str] | None = None for cmd in commands: try: last_result = subprocess.run(cmd, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=300) except (OSError, subprocess.TimeoutExpired): continue if (install_root / "bin").is_dir() or (install_root / "oss-cad-suite" / "bin").is_dir(): break _promote_nested_install_root(install_root) if not (install_root / "bin").is_dir(): detail = "" if last_result is None else (last_result.stdout + last_result.stderr)[-2000:] raise RuntimeError(f"OSS CAD Suite SFX extraction did not create bin directory: {detail}") elif _is_tar_archive(archive): staging = install_root.with_name(install_root.name + ".staging") if staging.exists(): if not _is_owned(staging, "oss_cad_suite_staging"): raise RuntimeError(f"refusing to replace unowned staging directory: {staging}") shutil.rmtree(staging) staging.mkdir(parents=True, exist_ok=True) _write_owner_marker(staging, "oss_cad_suite_staging", {"archive": str(archive)}) tar = shutil.which("tar") if not tar: raise RuntimeError("tar executable not found; cannot extract OSS CAD Suite archive") try: subprocess.run( [tar, "-xzf", str(archive), "-C", str(staging)], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=1200, check=True, ) except subprocess.CalledProcessError as exc: detail = (exc.stdout or "") + (exc.stderr or "") raise RuntimeError(f"tar extraction failed: {detail[-2000:]}") from exc _promote_nested_install_root(staging) if not (staging / "bin").is_dir(): raise RuntimeError(f"OSS CAD Suite tar extraction did not create bin directory: {staging}") if install_root.exists(): if not _is_owned(install_root, "oss_cad_suite"): raise RuntimeError(f"refusing to replace unowned install root: {install_root}") shutil.rmtree(install_root) staging.rename(install_root) _write_owner_marker(install_root, "oss_cad_suite", {"archive": str(archive), "extractor": "tar"}) else: raise ValueError(f"Unsupported archive type: {archive}") _promote_nested_install_root(install_root) def _promote_nested_install_root(install_root: Path) -> None: nested = install_root / "oss-cad-suite" if not (nested / "bin").is_dir(): return temp_root = install_root.with_name(install_root.name + ".nested") if temp_root.exists(): shutil.rmtree(temp_root) nested.rename(temp_root) for child in list(install_root.iterdir()): if child == temp_root: continue if child.is_dir(): shutil.rmtree(child) else: child.unlink() for child in temp_root.iterdir(): child.rename(install_root / child.name) temp_root.rmdir() def _finalize_install( *, install_root: Path, release: dict[str, Any], asset: dict[str, Any], archive: Path, ) -> dict[str, Any]: archive_hash = sha256(archive) payload = tool_status(install_root) payload.update({ "status": "present" if all(item["status"] == "present" for item in payload["tools"].values()) else "fail", "release_tag": release.get("tag_name"), "asset": { "name": asset.get("name"), "browser_download_url": asset.get("browser_download_url"), "size": asset.get("size"), }, "archive": str(archive), "sha256": archive_hash, "manifest": str(install_root / INSTALL_MANIFEST_NAME), "safety": { "opens_com_ports": False, "toggles_dtr_rts": False, "installs_drivers": False, "programs_flash": False, "touches_real_board_io": False, }, }) _write_owner_marker(install_root, "oss_cad_suite", payload) _write_install_manifest(install_root, payload) report_path = install_root / "toolchain-install-report.json" report_path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") if payload["status"] != "present": missing = [name for name, info in payload["tools"].items() if info["status"] != "present"] raise RuntimeError("OSS CAD Suite install missing required tools: " + ", ".join(missing)) return payload def install_latest_windows_x64( *, install_root: Path, download_dir: Path, release_payload: dict[str, Any] | None = None, download_func=download_file, extract_func=extract_archive, ) -> dict[str, Any]: release = release_payload or fetch_latest_release() install_root = _assert_safe_toolchain_root(install_root) asset = select_windows_x64_asset(release) archive = download_dir / asset["name"] download_func(asset["browser_download_url"], archive) extract_func(archive, install_root) return _finalize_install( install_root=install_root, release=release, asset=asset, archive=archive, ) def install_latest_linux_x64( *, install_root: Path, download_dir: Path, release_payload: dict[str, Any] | None = None, download_func=download_file, extract_func=extract_archive, ) -> dict[str, Any]: release = release_payload or fetch_latest_release() install_root = _assert_safe_toolchain_root(install_root) asset = select_linux_x64_asset(release) archive = download_dir / asset["name"] download_func(asset["browser_download_url"], archive) extract_func(archive, install_root) return _finalize_install( install_root=install_root, release=release, asset=asset, archive=archive, ) def run_checked(cmd: list[str], *, cwd: Path | None = None, timeout: int = 600) -> subprocess.CompletedProcess[str]: result = subprocess.run( cmd, cwd=cwd, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout, ) if result.returncode != 0: detail = (result.stdout + result.stderr)[-3000:] raise RuntimeError(f"command failed with returncode {result.returncode}: {' '.join(cmd)}\n{detail}") return result def uninstall_owned_toolchain( *, install_root: Path = DEFAULT_ROOT, cocotb_venv: Path = DEFAULT_COCOTB_VENV, dry_run: bool = True, include_downloads: bool = False, download_dir: Path = DEFAULT_DOWNLOAD_DIR, ) -> dict[str, Any]: targets = [install_root, cocotb_venv] if include_downloads: targets.append(download_dir) actions: list[dict[str, Any]] = [] status = "pass" for target in targets: exists = target.exists() owned = target.is_dir() and _is_owned(target) item: dict[str, Any] = { "path": str(target), "exists": exists, "owned": owned, "action": "not_present", } if exists and not owned: item["action"] = "blocked_not_owned" status = "blocked_not_owned" elif exists and owned and dry_run: item["action"] = "would_delete" elif exists and owned: shutil.rmtree(target) item["action"] = "deleted" actions.append(item) return { "schema": "offline-toolchain-uninstall-v1", "status": status, "mode": "dry_run" if dry_run else "apply", "targets": actions, "cleanup_policy": { "default": "dry_run", "requires_owner_marker": True, "owner_marker_name": OWNER_MARKER_NAME, "actual_delete_requires_apply": True, }, "safety": { "opens_com_ports": False, "toggles_dtr_rts": False, "installs_drivers": False, "programs_flash": False, "touches_real_board_io": False, }, "authority_boundary": "Uninstall only removes marker-owned user-mode toolchain paths and never probes serial ports, installs drivers, programs flash, or touches real hardware.", } def install_cocotb_venv( *, venv_dir: Path, python_exe: Path, cocotb_version: str = DEFAULT_COCOTB_VERSION, extra_packages: list[str] | None = None, ) -> dict[str, Any]: if not python_exe.is_file(): raise FileNotFoundError(f"Python executable not found: {python_exe}") venv_dir = _assert_safe_toolchain_root(venv_dir) venv_python = venv_dir / "Scripts" / "python.exe" if not venv_python.is_file(): run_checked([str(python_exe), "-m", "venv", str(venv_dir)]) if not venv_python.is_file(): raise RuntimeError(f"venv creation did not create Python executable: {venv_python}") run_checked([str(venv_python), "-m", "pip", "install", "--upgrade", "pip"], timeout=1200) packages = [f"cocotb=={cocotb_version}"] + list(extra_packages if extra_packages is not None else DEFAULT_EXTRA_PYTHON_PACKAGES) run_checked([str(venv_python), "-m", "pip", "install", *packages], timeout=1200) verify = run_checked([str(venv_python), "-c", "import cocotb; print(cocotb.__version__)"]) detected_version = verify.stdout.strip().splitlines()[-1] if verify.stdout.strip() else None payload = { "schema": "prod2u-p4-actuator-trace-cocotb-venv-bootstrap-v1", "status": "present" if detected_version == cocotb_version else "fail", "venv_dir": str(venv_dir), "python": str(venv_python), "source_python": str(python_exe), "cocotb_version": detected_version, "requested_cocotb_version": cocotb_version, "extra_packages": list(extra_packages if extra_packages is not None else DEFAULT_EXTRA_PYTHON_PACKAGES), "manifest": str(venv_dir / INSTALL_MANIFEST_NAME), "safety": { "opens_com_ports": False, "toggles_dtr_rts": False, "installs_drivers": False, "programs_flash": False, "touches_real_board_io": False, }, "authority_boundary": "This helper only creates a local Python venv and installs cocotb; it does not prove cocotb tests pass this project.", } _write_owner_marker(venv_dir, "cocotb_venv", payload) _write_install_manifest(venv_dir, payload) report_path = venv_dir / "cocotb-venv-install-report.json" report_path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") if payload["status"] != "present": raise RuntimeError(f"cocotb version verification failed: expected {cocotb_version}, got {detected_version}") return payload def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--install-root", type=Path, default=DEFAULT_ROOT) parser.add_argument("--download-dir", type=Path, default=DEFAULT_DOWNLOAD_DIR) parser.add_argument("--cocotb-venv", type=Path, default=DEFAULT_COCOTB_VENV) parser.add_argument("--python-exe", type=Path, default=DEFAULT_BUNDLED_PYTHON) parser.add_argument("--cocotb-version", default=DEFAULT_COCOTB_VERSION) parser.add_argument("--install-latest-windows-x64", action="store_true") parser.add_argument("--install-latest-linux-x64", action="store_true") parser.add_argument("--install-cocotb-venv", action="store_true") parser.add_argument("--download-url", help="Explicit OSS CAD Suite zip URL. See releases URL in --json output.") parser.add_argument("--download-to", type=Path, help="Destination zip path for --download-url.") parser.add_argument("--extract-zip", type=Path, help="Extract a previously downloaded OSS CAD Suite zip.") parser.add_argument("--extract-archive", type=Path, help="Extract a previously downloaded OSS CAD Suite archive.") parser.add_argument("--print-env", action="store_true", help="Print PowerShell environment commands.") parser.add_argument("--json", action="store_true") return parser def main(argv: list[str] | None = None) -> int: args = build_parser().parse_args(argv) if args.download_url: if not args.download_to: raise SystemExit("--download-to is required with --download-url") download_file(args.download_url, args.download_to) if args.install_latest_windows_x64: payload = install_latest_windows_x64(install_root=args.install_root, download_dir=args.download_dir) print(json.dumps(payload, indent=2) if args.json else f"installed: {payload['install_root']}") return 0 if args.install_latest_linux_x64: payload = install_latest_linux_x64(install_root=args.install_root, download_dir=args.download_dir) print(json.dumps(payload, indent=2) if args.json else f"installed: {payload['install_root']}") return 0 if args.install_cocotb_venv: payload = install_cocotb_venv( venv_dir=args.cocotb_venv, python_exe=args.python_exe, cocotb_version=args.cocotb_version, ) print(json.dumps(payload, indent=2) if args.json else f"installed: {payload['venv_dir']}") return 0 if args.extract_zip: extract_archive(args.extract_zip, args.install_root) if args.extract_archive: extract_archive(args.extract_archive, args.install_root) payload = _finalize_install( install_root=_assert_safe_toolchain_root(args.install_root), release={"tag_name": "local-archive"}, asset={"name": args.extract_archive.name, "browser_download_url": None, "size": args.extract_archive.stat().st_size}, archive=args.extract_archive, ) print(json.dumps(payload, indent=2) if args.json else f"installed: {payload['install_root']}") return 0 payload = tool_status(args.install_root) if args.print_env: native_verilator = payload["tools"]["verilator"]["path"] if not isinstance(native_verilator, str) or not native_verilator: raise SystemExit( "native Verilator executable is missing; refusing to expose the extensionless wrapper" ) if not VERILATOR_SHIM.is_file(): raise SystemExit( f"native Verilator command shim is missing: {VERILATOR_SHIM}" ) if not ACTIVATION_SCRIPT.is_file(): raise SystemExit( f"verification toolchain activation script is missing: {ACTIVATION_SCRIPT}" ) lib_dir = args.install_root / "lib" if not lib_dir.is_dir(): raise SystemExit( "native Verilator lib directory is missing; refusing to expose the toolchain bin directory" ) verilator_root = args.install_root / "share" / "verilator" if not verilator_root.is_dir(): raise SystemExit( "native Verilator share directory is missing; refusing to expose the toolchain bin directory" ) smtbmc = next( ( candidate for candidate in ( args.install_root / "bin" / "yosys-smtbmc.exe.exe", args.install_root / "bin" / "yosys-smtbmc.exe", args.install_root / "bin" / "yosys-smtbmc", ) if candidate.is_file() ), None, ) if smtbmc is None: raise SystemExit( "SMTBMC executable is missing; refusing to expose an incomplete formal toolchain" ) print( f"& {powershell_literal(ACTIVATION_SCRIPT)} " f"-ToolchainRoot {powershell_literal(args.install_root.resolve())}" ) return 0 if args.json: print(json.dumps(payload, indent=2)) else: print(f"install_root: {payload['install_root']}") print(f"releases: {payload['releases_url']}") for name, status in payload["tools"].items(): print(f"{name}: {status['status']} {status['path'] or ''}") return 0 if __name__ == "__main__": raise SystemExit(main())