bootstrap_oss_cad_suite.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. #!/usr/bin/env python3
  2. """Explicit OSS CAD Suite bootstrap helper for Prod2U P4 verification.
  3. This script is intentionally not called by the normal harness. It never
  4. installs tools implicitly; the user must run it directly and choose a download
  5. or extraction action.
  6. """
  7. from __future__ import annotations
  8. import argparse
  9. import hashlib
  10. import json
  11. import os
  12. import shutil
  13. import sys
  14. import urllib.request
  15. import zipfile
  16. import subprocess
  17. from pathlib import Path
  18. from typing import Any
  19. def _default_toolchain_base() -> Path:
  20. if sys.platform.startswith("linux"):
  21. override = os.environ.get("PRODU2_TOOLCHAIN_BASE", "").strip()
  22. if override:
  23. return Path(override)
  24. # Durable volume survives container rebuild; overlay ~/.cache does not.
  25. persistent = Path("/data/prod2u")
  26. if persistent.is_dir() or os.access("/data", os.W_OK):
  27. return persistent
  28. return Path.home() / ".cache" / "prod2u"
  29. return Path.home() / "CodexToolchains" / "CPLD"
  30. DEFAULT_TOOLCHAIN_BASE = _default_toolchain_base()
  31. DEFAULT_ROOT = DEFAULT_TOOLCHAIN_BASE / "oss-cad-suite" / "latest"
  32. DEFAULT_DOWNLOAD_DIR = DEFAULT_TOOLCHAIN_BASE / "downloads"
  33. DEFAULT_COCOTB_VENV = (
  34. DEFAULT_TOOLCHAIN_BASE / "venvs" / "prod2u-p4-actuator-trace-cocotb-venv"
  35. )
  36. DEFAULT_BUNDLED_PYTHON = Path.home() / ".cache" / "codex-runtimes" / "codex-primary-runtime" / "dependencies" / "python" / "python.exe"
  37. DEFAULT_COCOTB_VERSION = "1.9.2"
  38. DEFAULT_EXTRA_PYTHON_PACKAGES = ["pytest", "hypothesis", "pyserial", "pyserial-asyncio"]
  39. OWNER_MARKER_NAME = ".cpld_toolchain_owner.json"
  40. INSTALL_MANIFEST_NAME = ".cpld_toolchain_manifest.json"
  41. TOOLCHAIN_SHIM_DIR = Path(__file__).resolve().parent / "toolchain_shims"
  42. VERILATOR_SHIM = TOOLCHAIN_SHIM_DIR / "verilator.ps1"
  43. ACTIVATION_SCRIPT = Path(__file__).resolve().parent / "activate_verification_toolchain.ps1"
  44. RELEASES_URL = "https://github.com/YosysHQ/oss-cad-suite-build/releases"
  45. LATEST_API_URL = "https://api.github.com/repos/YosysHQ/oss-cad-suite-build/releases/latest"
  46. REQUIRED_TOOLS = ["iverilog", "vvp", "verilator", "yosys", "sby"]
  47. def _verilator_candidates(bin_dir: Path) -> tuple[Path, ...]:
  48. # Prefer the platform-native binary; never accept the extensionless
  49. # shell/batch launcher named plain "verilator". Include both Linux and
  50. # Windows native names so unit fixtures and cross-extracted trees resolve.
  51. linux_native = (bin_dir / "verilator_bin",)
  52. windows_native = (bin_dir / "verilator_bin.exe", bin_dir / "verilator.exe")
  53. if sys.platform.startswith("linux"):
  54. return linux_native + windows_native
  55. return windows_native + linux_native
  56. def tool_status(root: Path) -> dict[str, Any]:
  57. bin_dir = root / "bin"
  58. tools = {}
  59. for name in REQUIRED_TOOLS:
  60. if name == "verilator":
  61. candidates = _verilator_candidates(bin_dir)
  62. else:
  63. candidates = (bin_dir / f"{name}.exe", bin_dir / name)
  64. path = next((candidate for candidate in candidates if candidate.is_file()), None)
  65. tools[name] = {
  66. "status": "present" if path is not None else "missing",
  67. "path": str(path.resolve()) if path is not None else None,
  68. }
  69. return {
  70. "schema": "prod2u-p4-actuator-trace-oss-cad-suite-bootstrap-v1",
  71. "install_root": str(root),
  72. "owner_marker": str(root / OWNER_MARKER_NAME),
  73. "bin_dir": str(bin_dir),
  74. "tools": tools,
  75. "releases_url": RELEASES_URL,
  76. "env": {
  77. "PROD2U_P4_TOOLCHAIN_ROOT": str(root),
  78. "OSS_CAD_SUITE_ROOT": str(root),
  79. "VERILATOR": tools["verilator"]["path"],
  80. "path_addition": str(bin_dir),
  81. },
  82. "authority_boundary": "This helper only downloads/extracts a user-selected OSS CAD Suite archive; it does not prove those tools pass this project.",
  83. }
  84. def _assert_under(parent: Path, target: Path, label: str) -> Path:
  85. parent_resolved = parent.resolve()
  86. target_resolved = target.resolve()
  87. if target_resolved != parent_resolved and parent_resolved not in target_resolved.parents:
  88. raise ValueError(f"{label} must stay under {parent_resolved}: {target_resolved}")
  89. return target_resolved
  90. def _assert_safe_toolchain_root(path: Path) -> Path:
  91. resolved = path.resolve()
  92. home = Path.home().resolve()
  93. base = DEFAULT_TOOLCHAIN_BASE.resolve()
  94. _assert_under(base, resolved, "toolchain path")
  95. if resolved in {home, home.parent, Path(resolved.anchor), base}:
  96. raise ValueError(f"unsafe toolchain root: {resolved}")
  97. # Never install into the source checkout that ships this helper (or nested paths).
  98. workspace_root = Path(__file__).resolve().parents[1]
  99. if resolved == workspace_root or workspace_root in resolved.parents:
  100. raise ValueError(f"unsafe toolchain root: {resolved}")
  101. return resolved
  102. def _write_owner_marker(root: Path, component: str, payload: dict[str, Any]) -> None:
  103. root.mkdir(parents=True, exist_ok=True)
  104. marker = {
  105. "schema": "cpld-toolchain-owner-v1",
  106. "component": component,
  107. "root": str(root),
  108. "safety": {
  109. "opens_com_ports": False,
  110. "toggles_dtr_rts": False,
  111. "installs_drivers": False,
  112. "programs_flash": False,
  113. "touches_real_board_io": False,
  114. },
  115. "payload": payload,
  116. }
  117. (root / OWNER_MARKER_NAME).write_text(json.dumps(marker, indent=2) + "\n", encoding="utf-8")
  118. def _write_install_manifest(root: Path, payload: dict[str, Any]) -> Path:
  119. manifest_path = root / INSTALL_MANIFEST_NAME
  120. manifest_path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
  121. return manifest_path
  122. def _is_owned(root: Path, component: str | None = None) -> bool:
  123. marker = root / OWNER_MARKER_NAME
  124. if not marker.is_file():
  125. return False
  126. if component is None:
  127. return True
  128. try:
  129. payload = json.loads(marker.read_text(encoding="utf-8-sig"))
  130. except json.JSONDecodeError:
  131. return False
  132. return payload.get("component") == component
  133. def sha256(path: Path) -> str:
  134. digest = hashlib.sha256()
  135. with path.open("rb") as handle:
  136. for chunk in iter(lambda: handle.read(1024 * 1024), b""):
  137. digest.update(chunk)
  138. return digest.hexdigest()
  139. def powershell_literal(value: str | Path) -> str:
  140. return "'" + str(value).replace("'", "''") + "'"
  141. def fetch_latest_release() -> dict[str, Any]:
  142. request = urllib.request.Request(
  143. LATEST_API_URL,
  144. headers={"User-Agent": "prod2u-p4-actuator-trace-toolchain-bootstrap"},
  145. )
  146. with urllib.request.urlopen(request, timeout=30) as response:
  147. return json.loads(response.read().decode("utf-8"))
  148. def select_windows_x64_asset(release_payload: dict[str, Any]) -> dict[str, Any]:
  149. for asset in release_payload.get("assets", []):
  150. name = asset.get("name", "")
  151. if name.startswith("oss-cad-suite-windows-x64-") and name.endswith(".exe"):
  152. if asset.get("browser_download_url"):
  153. return asset
  154. raise ValueError("No oss-cad-suite-windows-x64-*.exe asset found in release payload")
  155. def select_linux_x64_asset(release_payload: dict[str, Any]) -> dict[str, Any]:
  156. for asset in release_payload.get("assets", []):
  157. name = asset.get("name", "")
  158. if name.startswith("oss-cad-suite-linux-x64-") and name.endswith(".tgz"):
  159. if asset.get("browser_download_url"):
  160. return asset
  161. raise ValueError("No oss-cad-suite-linux-x64-*.tgz asset found in release payload")
  162. def _is_tar_archive(path: Path) -> bool:
  163. lowered = path.name.lower()
  164. return lowered.endswith(".tgz") or lowered.endswith(".tar.gz") or lowered.endswith(".tar")
  165. def _curl_env() -> dict[str, str]:
  166. env = os.environ.copy()
  167. for key in (
  168. "http_proxy",
  169. "https_proxy",
  170. "HTTP_PROXY",
  171. "HTTPS_PROXY",
  172. "ALL_PROXY",
  173. "all_proxy",
  174. ):
  175. env.pop(key, None)
  176. return env
  177. def download_file(url: str, output: Path) -> None:
  178. output.parent.mkdir(parents=True, exist_ok=True)
  179. curl = shutil.which("curl.exe") or shutil.which("curl")
  180. if curl:
  181. cmd = [
  182. curl,
  183. "-L",
  184. "--fail",
  185. "-C",
  186. "-",
  187. "--retry",
  188. "3",
  189. "--connect-timeout",
  190. "30",
  191. "--output",
  192. str(output),
  193. url,
  194. ]
  195. try:
  196. result = subprocess.run(
  197. cmd,
  198. text=True,
  199. stdout=subprocess.PIPE,
  200. stderr=subprocess.PIPE,
  201. timeout=7200,
  202. env=_curl_env(),
  203. )
  204. except subprocess.TimeoutExpired as exc:
  205. raise RuntimeError(f"curl download timed out; rerun the command to resume: {exc}") from exc
  206. if result.returncode != 0:
  207. detail = (result.stdout + result.stderr)[-2000:]
  208. raise RuntimeError(f"curl download failed with returncode {result.returncode}: {detail}")
  209. else:
  210. temp_output = output.with_suffix(output.suffix + ".part")
  211. if temp_output.exists():
  212. temp_output.unlink()
  213. request = urllib.request.Request(
  214. url,
  215. headers={"User-Agent": "prod2u-p4-actuator-trace-toolchain-bootstrap"},
  216. )
  217. with urllib.request.urlopen(request, timeout=60) as response, temp_output.open("wb") as handle:
  218. shutil.copyfileobj(response, handle)
  219. if not temp_output.is_file() or temp_output.stat().st_size == 0:
  220. raise RuntimeError(f"download produced empty file: {temp_output}")
  221. temp_output.replace(output)
  222. if not output.is_file() or output.stat().st_size == 0:
  223. raise RuntimeError(f"download produced empty file: {output}")
  224. def extract_archive(archive: Path, install_root: Path) -> None:
  225. install_root = _assert_safe_toolchain_root(install_root)
  226. install_root.parent.mkdir(parents=True, exist_ok=True)
  227. suffix = archive.suffix.lower()
  228. if suffix == ".zip":
  229. staging = install_root.with_name(install_root.name + ".staging")
  230. if staging.exists():
  231. if not _is_owned(staging, "oss_cad_suite_staging"):
  232. raise RuntimeError(f"refusing to replace unowned staging directory: {staging}")
  233. shutil.rmtree(staging)
  234. staging.mkdir(parents=True, exist_ok=True)
  235. _write_owner_marker(staging, "oss_cad_suite_staging", {"archive": str(archive)})
  236. with zipfile.ZipFile(archive) as zf:
  237. for member in zf.namelist():
  238. _assert_under(staging, staging / member, "zip member")
  239. zf.extractall(staging)
  240. if install_root.exists():
  241. if not _is_owned(install_root, "oss_cad_suite"):
  242. raise RuntimeError(f"refusing to replace unowned install root: {install_root}")
  243. shutil.rmtree(install_root)
  244. staging.rename(install_root)
  245. _write_owner_marker(install_root, "oss_cad_suite", {"archive": str(archive)})
  246. elif suffix == ".exe":
  247. if install_root.exists():
  248. if not _is_owned(install_root, "oss_cad_suite"):
  249. raise RuntimeError(f"refusing to replace unowned install root: {install_root}")
  250. shutil.rmtree(install_root)
  251. install_root.mkdir(parents=True, exist_ok=True)
  252. _write_owner_marker(install_root, "oss_cad_suite", {"archive": str(archive), "extractor": "sfx"})
  253. commands = [
  254. [str(archive), "-y", f"-o{install_root}"],
  255. [str(archive), "/S", f"/D={install_root}"],
  256. ]
  257. last_result: subprocess.CompletedProcess[str] | None = None
  258. for cmd in commands:
  259. try:
  260. last_result = subprocess.run(cmd, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=300)
  261. except (OSError, subprocess.TimeoutExpired):
  262. continue
  263. if (install_root / "bin").is_dir() or (install_root / "oss-cad-suite" / "bin").is_dir():
  264. break
  265. _promote_nested_install_root(install_root)
  266. if not (install_root / "bin").is_dir():
  267. detail = "" if last_result is None else (last_result.stdout + last_result.stderr)[-2000:]
  268. raise RuntimeError(f"OSS CAD Suite SFX extraction did not create bin directory: {detail}")
  269. elif _is_tar_archive(archive):
  270. staging = install_root.with_name(install_root.name + ".staging")
  271. if staging.exists():
  272. if not _is_owned(staging, "oss_cad_suite_staging"):
  273. raise RuntimeError(f"refusing to replace unowned staging directory: {staging}")
  274. shutil.rmtree(staging)
  275. staging.mkdir(parents=True, exist_ok=True)
  276. _write_owner_marker(staging, "oss_cad_suite_staging", {"archive": str(archive)})
  277. tar = shutil.which("tar")
  278. if not tar:
  279. raise RuntimeError("tar executable not found; cannot extract OSS CAD Suite archive")
  280. try:
  281. subprocess.run(
  282. [tar, "-xzf", str(archive), "-C", str(staging)],
  283. text=True,
  284. stdout=subprocess.PIPE,
  285. stderr=subprocess.PIPE,
  286. timeout=1200,
  287. check=True,
  288. )
  289. except subprocess.CalledProcessError as exc:
  290. detail = (exc.stdout or "") + (exc.stderr or "")
  291. raise RuntimeError(f"tar extraction failed: {detail[-2000:]}") from exc
  292. _promote_nested_install_root(staging)
  293. if not (staging / "bin").is_dir():
  294. raise RuntimeError(f"OSS CAD Suite tar extraction did not create bin directory: {staging}")
  295. if install_root.exists():
  296. if not _is_owned(install_root, "oss_cad_suite"):
  297. raise RuntimeError(f"refusing to replace unowned install root: {install_root}")
  298. shutil.rmtree(install_root)
  299. staging.rename(install_root)
  300. _write_owner_marker(install_root, "oss_cad_suite", {"archive": str(archive), "extractor": "tar"})
  301. else:
  302. raise ValueError(f"Unsupported archive type: {archive}")
  303. _promote_nested_install_root(install_root)
  304. def _promote_nested_install_root(install_root: Path) -> None:
  305. nested = install_root / "oss-cad-suite"
  306. if not (nested / "bin").is_dir():
  307. return
  308. temp_root = install_root.with_name(install_root.name + ".nested")
  309. if temp_root.exists():
  310. shutil.rmtree(temp_root)
  311. nested.rename(temp_root)
  312. for child in list(install_root.iterdir()):
  313. if child == temp_root:
  314. continue
  315. if child.is_dir():
  316. shutil.rmtree(child)
  317. else:
  318. child.unlink()
  319. for child in temp_root.iterdir():
  320. child.rename(install_root / child.name)
  321. temp_root.rmdir()
  322. def _finalize_install(
  323. *,
  324. install_root: Path,
  325. release: dict[str, Any],
  326. asset: dict[str, Any],
  327. archive: Path,
  328. ) -> dict[str, Any]:
  329. archive_hash = sha256(archive)
  330. payload = tool_status(install_root)
  331. payload.update({
  332. "status": "present" if all(item["status"] == "present" for item in payload["tools"].values()) else "fail",
  333. "release_tag": release.get("tag_name"),
  334. "asset": {
  335. "name": asset.get("name"),
  336. "browser_download_url": asset.get("browser_download_url"),
  337. "size": asset.get("size"),
  338. },
  339. "archive": str(archive),
  340. "sha256": archive_hash,
  341. "manifest": str(install_root / INSTALL_MANIFEST_NAME),
  342. "safety": {
  343. "opens_com_ports": False,
  344. "toggles_dtr_rts": False,
  345. "installs_drivers": False,
  346. "programs_flash": False,
  347. "touches_real_board_io": False,
  348. },
  349. })
  350. _write_owner_marker(install_root, "oss_cad_suite", payload)
  351. _write_install_manifest(install_root, payload)
  352. report_path = install_root / "toolchain-install-report.json"
  353. report_path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
  354. if payload["status"] != "present":
  355. missing = [name for name, info in payload["tools"].items() if info["status"] != "present"]
  356. raise RuntimeError("OSS CAD Suite install missing required tools: " + ", ".join(missing))
  357. return payload
  358. def install_latest_windows_x64(
  359. *,
  360. install_root: Path,
  361. download_dir: Path,
  362. release_payload: dict[str, Any] | None = None,
  363. download_func=download_file,
  364. extract_func=extract_archive,
  365. ) -> dict[str, Any]:
  366. release = release_payload or fetch_latest_release()
  367. install_root = _assert_safe_toolchain_root(install_root)
  368. asset = select_windows_x64_asset(release)
  369. archive = download_dir / asset["name"]
  370. download_func(asset["browser_download_url"], archive)
  371. extract_func(archive, install_root)
  372. return _finalize_install(
  373. install_root=install_root,
  374. release=release,
  375. asset=asset,
  376. archive=archive,
  377. )
  378. def install_latest_linux_x64(
  379. *,
  380. install_root: Path,
  381. download_dir: Path,
  382. release_payload: dict[str, Any] | None = None,
  383. download_func=download_file,
  384. extract_func=extract_archive,
  385. ) -> dict[str, Any]:
  386. release = release_payload or fetch_latest_release()
  387. install_root = _assert_safe_toolchain_root(install_root)
  388. asset = select_linux_x64_asset(release)
  389. archive = download_dir / asset["name"]
  390. download_func(asset["browser_download_url"], archive)
  391. extract_func(archive, install_root)
  392. return _finalize_install(
  393. install_root=install_root,
  394. release=release,
  395. asset=asset,
  396. archive=archive,
  397. )
  398. def run_checked(cmd: list[str], *, cwd: Path | None = None, timeout: int = 600) -> subprocess.CompletedProcess[str]:
  399. result = subprocess.run(
  400. cmd,
  401. cwd=cwd,
  402. text=True,
  403. stdout=subprocess.PIPE,
  404. stderr=subprocess.PIPE,
  405. timeout=timeout,
  406. )
  407. if result.returncode != 0:
  408. detail = (result.stdout + result.stderr)[-3000:]
  409. raise RuntimeError(f"command failed with returncode {result.returncode}: {' '.join(cmd)}\n{detail}")
  410. return result
  411. def uninstall_owned_toolchain(
  412. *,
  413. install_root: Path = DEFAULT_ROOT,
  414. cocotb_venv: Path = DEFAULT_COCOTB_VENV,
  415. dry_run: bool = True,
  416. include_downloads: bool = False,
  417. download_dir: Path = DEFAULT_DOWNLOAD_DIR,
  418. ) -> dict[str, Any]:
  419. targets = [install_root, cocotb_venv]
  420. if include_downloads:
  421. targets.append(download_dir)
  422. actions: list[dict[str, Any]] = []
  423. status = "pass"
  424. for target in targets:
  425. exists = target.exists()
  426. owned = target.is_dir() and _is_owned(target)
  427. item: dict[str, Any] = {
  428. "path": str(target),
  429. "exists": exists,
  430. "owned": owned,
  431. "action": "not_present",
  432. }
  433. if exists and not owned:
  434. item["action"] = "blocked_not_owned"
  435. status = "blocked_not_owned"
  436. elif exists and owned and dry_run:
  437. item["action"] = "would_delete"
  438. elif exists and owned:
  439. shutil.rmtree(target)
  440. item["action"] = "deleted"
  441. actions.append(item)
  442. return {
  443. "schema": "offline-toolchain-uninstall-v1",
  444. "status": status,
  445. "mode": "dry_run" if dry_run else "apply",
  446. "targets": actions,
  447. "cleanup_policy": {
  448. "default": "dry_run",
  449. "requires_owner_marker": True,
  450. "owner_marker_name": OWNER_MARKER_NAME,
  451. "actual_delete_requires_apply": True,
  452. },
  453. "safety": {
  454. "opens_com_ports": False,
  455. "toggles_dtr_rts": False,
  456. "installs_drivers": False,
  457. "programs_flash": False,
  458. "touches_real_board_io": False,
  459. },
  460. "authority_boundary": "Uninstall only removes marker-owned user-mode toolchain paths and never probes serial ports, installs drivers, programs flash, or touches real hardware.",
  461. }
  462. def install_cocotb_venv(
  463. *,
  464. venv_dir: Path,
  465. python_exe: Path,
  466. cocotb_version: str = DEFAULT_COCOTB_VERSION,
  467. extra_packages: list[str] | None = None,
  468. ) -> dict[str, Any]:
  469. if not python_exe.is_file():
  470. raise FileNotFoundError(f"Python executable not found: {python_exe}")
  471. venv_dir = _assert_safe_toolchain_root(venv_dir)
  472. venv_python = venv_dir / "Scripts" / "python.exe"
  473. if not venv_python.is_file():
  474. run_checked([str(python_exe), "-m", "venv", str(venv_dir)])
  475. if not venv_python.is_file():
  476. raise RuntimeError(f"venv creation did not create Python executable: {venv_python}")
  477. run_checked([str(venv_python), "-m", "pip", "install", "--upgrade", "pip"], timeout=1200)
  478. packages = [f"cocotb=={cocotb_version}"] + list(extra_packages if extra_packages is not None else DEFAULT_EXTRA_PYTHON_PACKAGES)
  479. run_checked([str(venv_python), "-m", "pip", "install", *packages], timeout=1200)
  480. verify = run_checked([str(venv_python), "-c", "import cocotb; print(cocotb.__version__)"])
  481. detected_version = verify.stdout.strip().splitlines()[-1] if verify.stdout.strip() else None
  482. payload = {
  483. "schema": "prod2u-p4-actuator-trace-cocotb-venv-bootstrap-v1",
  484. "status": "present" if detected_version == cocotb_version else "fail",
  485. "venv_dir": str(venv_dir),
  486. "python": str(venv_python),
  487. "source_python": str(python_exe),
  488. "cocotb_version": detected_version,
  489. "requested_cocotb_version": cocotb_version,
  490. "extra_packages": list(extra_packages if extra_packages is not None else DEFAULT_EXTRA_PYTHON_PACKAGES),
  491. "manifest": str(venv_dir / INSTALL_MANIFEST_NAME),
  492. "safety": {
  493. "opens_com_ports": False,
  494. "toggles_dtr_rts": False,
  495. "installs_drivers": False,
  496. "programs_flash": False,
  497. "touches_real_board_io": False,
  498. },
  499. "authority_boundary": "This helper only creates a local Python venv and installs cocotb; it does not prove cocotb tests pass this project.",
  500. }
  501. _write_owner_marker(venv_dir, "cocotb_venv", payload)
  502. _write_install_manifest(venv_dir, payload)
  503. report_path = venv_dir / "cocotb-venv-install-report.json"
  504. report_path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
  505. if payload["status"] != "present":
  506. raise RuntimeError(f"cocotb version verification failed: expected {cocotb_version}, got {detected_version}")
  507. return payload
  508. def build_parser() -> argparse.ArgumentParser:
  509. parser = argparse.ArgumentParser(description=__doc__)
  510. parser.add_argument("--install-root", type=Path, default=DEFAULT_ROOT)
  511. parser.add_argument("--download-dir", type=Path, default=DEFAULT_DOWNLOAD_DIR)
  512. parser.add_argument("--cocotb-venv", type=Path, default=DEFAULT_COCOTB_VENV)
  513. parser.add_argument("--python-exe", type=Path, default=DEFAULT_BUNDLED_PYTHON)
  514. parser.add_argument("--cocotb-version", default=DEFAULT_COCOTB_VERSION)
  515. parser.add_argument("--install-latest-windows-x64", action="store_true")
  516. parser.add_argument("--install-latest-linux-x64", action="store_true")
  517. parser.add_argument("--install-cocotb-venv", action="store_true")
  518. parser.add_argument("--download-url", help="Explicit OSS CAD Suite zip URL. See releases URL in --json output.")
  519. parser.add_argument("--download-to", type=Path, help="Destination zip path for --download-url.")
  520. parser.add_argument("--extract-zip", type=Path, help="Extract a previously downloaded OSS CAD Suite zip.")
  521. parser.add_argument("--extract-archive", type=Path, help="Extract a previously downloaded OSS CAD Suite archive.")
  522. parser.add_argument("--print-env", action="store_true", help="Print PowerShell environment commands.")
  523. parser.add_argument("--json", action="store_true")
  524. return parser
  525. def main(argv: list[str] | None = None) -> int:
  526. args = build_parser().parse_args(argv)
  527. if args.download_url:
  528. if not args.download_to:
  529. raise SystemExit("--download-to is required with --download-url")
  530. download_file(args.download_url, args.download_to)
  531. if args.install_latest_windows_x64:
  532. payload = install_latest_windows_x64(install_root=args.install_root, download_dir=args.download_dir)
  533. print(json.dumps(payload, indent=2) if args.json else f"installed: {payload['install_root']}")
  534. return 0
  535. if args.install_latest_linux_x64:
  536. payload = install_latest_linux_x64(install_root=args.install_root, download_dir=args.download_dir)
  537. print(json.dumps(payload, indent=2) if args.json else f"installed: {payload['install_root']}")
  538. return 0
  539. if args.install_cocotb_venv:
  540. payload = install_cocotb_venv(
  541. venv_dir=args.cocotb_venv,
  542. python_exe=args.python_exe,
  543. cocotb_version=args.cocotb_version,
  544. )
  545. print(json.dumps(payload, indent=2) if args.json else f"installed: {payload['venv_dir']}")
  546. return 0
  547. if args.extract_zip:
  548. extract_archive(args.extract_zip, args.install_root)
  549. if args.extract_archive:
  550. extract_archive(args.extract_archive, args.install_root)
  551. payload = _finalize_install(
  552. install_root=_assert_safe_toolchain_root(args.install_root),
  553. release={"tag_name": "local-archive"},
  554. asset={"name": args.extract_archive.name, "browser_download_url": None, "size": args.extract_archive.stat().st_size},
  555. archive=args.extract_archive,
  556. )
  557. print(json.dumps(payload, indent=2) if args.json else f"installed: {payload['install_root']}")
  558. return 0
  559. payload = tool_status(args.install_root)
  560. if args.print_env:
  561. native_verilator = payload["tools"]["verilator"]["path"]
  562. if not isinstance(native_verilator, str) or not native_verilator:
  563. raise SystemExit(
  564. "native Verilator executable is missing; refusing to expose the extensionless wrapper"
  565. )
  566. if not VERILATOR_SHIM.is_file():
  567. raise SystemExit(
  568. f"native Verilator command shim is missing: {VERILATOR_SHIM}"
  569. )
  570. if not ACTIVATION_SCRIPT.is_file():
  571. raise SystemExit(
  572. f"verification toolchain activation script is missing: {ACTIVATION_SCRIPT}"
  573. )
  574. lib_dir = args.install_root / "lib"
  575. if not lib_dir.is_dir():
  576. raise SystemExit(
  577. "native Verilator lib directory is missing; refusing to expose the toolchain bin directory"
  578. )
  579. verilator_root = args.install_root / "share" / "verilator"
  580. if not verilator_root.is_dir():
  581. raise SystemExit(
  582. "native Verilator share directory is missing; refusing to expose the toolchain bin directory"
  583. )
  584. smtbmc = next(
  585. (
  586. candidate
  587. for candidate in (
  588. args.install_root / "bin" / "yosys-smtbmc.exe.exe",
  589. args.install_root / "bin" / "yosys-smtbmc.exe",
  590. args.install_root / "bin" / "yosys-smtbmc",
  591. )
  592. if candidate.is_file()
  593. ),
  594. None,
  595. )
  596. if smtbmc is None:
  597. raise SystemExit(
  598. "SMTBMC executable is missing; refusing to expose an incomplete formal toolchain"
  599. )
  600. print(
  601. f"& {powershell_literal(ACTIVATION_SCRIPT)} "
  602. f"-ToolchainRoot {powershell_literal(args.install_root.resolve())}"
  603. )
  604. return 0
  605. if args.json:
  606. print(json.dumps(payload, indent=2))
  607. else:
  608. print(f"install_root: {payload['install_root']}")
  609. print(f"releases: {payload['releases_url']}")
  610. for name, status in payload["tools"].items():
  611. print(f"{name}: {status['status']} {status['path'] or ''}")
  612. return 0
  613. if __name__ == "__main__":
  614. raise SystemExit(main())