toolchain_probe.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. #!/usr/bin/env python3
  2. """Read-only toolchain probe for the Prod2U P4 actuator/Trace harness."""
  3. from __future__ import annotations
  4. import importlib.util
  5. import json
  6. import os
  7. import shutil
  8. import subprocess
  9. import sys
  10. from datetime import datetime, timezone
  11. from pathlib import Path
  12. from typing import Any
  13. sys.dont_write_bytecode = True
  14. ROOT = Path(__file__).resolve().parents[1]
  15. TD_EXE = Path(r"C:\Anlogic\TD_Release_2026.1_SP1.198.412\bin\td.exe")
  16. TD_CLI = Path(r"C:\Anlogic\TD_Release_2026.1_SP1.198.412\bin\td_commands_prompt.exe")
  17. GIT_EXE = Path(r"C:\Program Files\Git\cmd\git.exe")
  18. DEFAULT_TOOLCHAIN_BASE = Path.home() / "CodexToolchains" / "CPLD"
  19. DEFAULT_OSS_CAD_SUITE_ROOT = DEFAULT_TOOLCHAIN_BASE / "oss-cad-suite" / "latest"
  20. DEFAULT_COCOTB_VENV_PYTHON = (
  21. DEFAULT_TOOLCHAIN_BASE
  22. / "venvs"
  23. / "prod2u-p4-actuator-trace-cocotb-venv"
  24. / "Scripts"
  25. / "python.exe"
  26. )
  27. def _toolchain_root_env_vars() -> list[str]:
  28. return ["PROD2U_P4_TOOLCHAIN_ROOT", "OSS_CAD_SUITE_ROOT"]
  29. def _candidate_tool_paths(name: str) -> list[Path]:
  30. candidates: list[Path] = []
  31. env_roots = [os.environ.get(name) for name in _toolchain_root_env_vars()]
  32. if name == "verilator":
  33. executable_names = ["verilator_bin.exe", "verilator.exe"]
  34. else:
  35. executable_names = [name]
  36. if name != "verilator" and not name.lower().endswith(".exe"):
  37. executable_names.append(f"{name}.exe")
  38. for root_text in env_roots:
  39. if not root_text:
  40. continue
  41. root = Path(root_text)
  42. for exe_name in executable_names:
  43. candidates.append(root / "bin" / exe_name)
  44. candidates.append(root / exe_name)
  45. for exe_name in executable_names:
  46. candidates.append(DEFAULT_OSS_CAD_SUITE_ROOT / "bin" / exe_name)
  47. return candidates
  48. def _native_verilator_binary(path: str | Path) -> str | None:
  49. candidate = Path(path).expanduser().resolve()
  50. if candidate.name.lower() not in {"verilator_bin.exe", "verilator.exe"}:
  51. return None
  52. return str(candidate) if candidate.is_file() else None
  53. def _toolchain_roots() -> list[Path]:
  54. roots: list[Path] = []
  55. for name in _toolchain_root_env_vars():
  56. value = os.environ.get(name)
  57. if value:
  58. roots.append(Path(value))
  59. roots.append(DEFAULT_OSS_CAD_SUITE_ROOT)
  60. return roots
  61. def _tool_env() -> dict[str, str]:
  62. env = os.environ.copy()
  63. env.setdefault("PYTHONDONTWRITEBYTECODE", "1")
  64. path_parts: list[str] = []
  65. for root in _toolchain_roots():
  66. bin_dir = root / "bin"
  67. lib_dir = root / "lib"
  68. verilator_root = root / "share" / "verilator"
  69. smtbmc = root / "bin" / "yosys-smtbmc.exe.exe"
  70. if bin_dir.is_dir():
  71. path_parts.append(str(bin_dir))
  72. if lib_dir.is_dir():
  73. path_parts.append(str(lib_dir))
  74. if verilator_root.is_dir() and "VERILATOR_ROOT" not in env:
  75. env["VERILATOR_ROOT"] = str(verilator_root)
  76. if smtbmc.is_file() and "SMTBMC" not in env:
  77. env["SMTBMC"] = str(smtbmc)
  78. if path_parts:
  79. env["PATH"] = os.pathsep.join(path_parts + [env.get("PATH", "")])
  80. return env
  81. def _version_from_command(cmd: list[str], timeout: int = 10) -> str | None:
  82. try:
  83. result = subprocess.run(
  84. cmd,
  85. cwd=ROOT,
  86. env=_tool_env(),
  87. text=True,
  88. stdout=subprocess.PIPE,
  89. stderr=subprocess.PIPE,
  90. timeout=timeout,
  91. )
  92. except (OSError, subprocess.TimeoutExpired):
  93. return None
  94. text = (result.stdout or result.stderr).strip()
  95. return text.splitlines()[0] if text else None
  96. def _td_cli_version(timeout: int = 20) -> dict[str, str | None]:
  97. if not TD_CLI.is_file():
  98. return {"release": None, "build": None}
  99. probe_dir = ROOT / "tmp" / "toolchain_probe"
  100. probe_dir.mkdir(parents=True, exist_ok=True)
  101. try:
  102. result = subprocess.run(
  103. [str(TD_CLI)],
  104. input="exit\n",
  105. cwd=probe_dir,
  106. text=True,
  107. stdout=subprocess.PIPE,
  108. stderr=subprocess.PIPE,
  109. timeout=timeout,
  110. )
  111. except (OSError, subprocess.TimeoutExpired):
  112. return {"release": None, "build": None}
  113. text = "\n".join([result.stdout, result.stderr])
  114. release = None
  115. build = None
  116. import re
  117. release_match = re.search(r"Release_20[0-9.]+(?:_SP[0-9]+)?", text)
  118. build_match = re.search(r"\b\d+\.\d+\.\d+\.\d{4,}\b", text)
  119. if release_match:
  120. release = release_match.group(0)
  121. if build_match:
  122. build = build_match.group(0)
  123. return {"release": release, "build": build}
  124. def _path_status(name: str, *, explicit_path: Path | None = None, version_args: list[str] | None = None) -> dict[str, Any]:
  125. resolved_path: str | None = None
  126. discovery = "explicit_path" if explicit_path else "PATH"
  127. if name == "verilator":
  128. for candidate in _candidate_tool_paths(name):
  129. resolved_path = _native_verilator_binary(candidate)
  130. if resolved_path:
  131. discovery = "env_or_default_toolchain_root"
  132. break
  133. if not resolved_path:
  134. for executable in ("verilator_bin.exe", "verilator.exe"):
  135. path_from_path = shutil.which(executable)
  136. if path_from_path:
  137. resolved_path = _native_verilator_binary(path_from_path)
  138. if resolved_path:
  139. discovery = "PATH"
  140. break
  141. elif explicit_path and explicit_path.is_file():
  142. resolved_path = str(explicit_path)
  143. else:
  144. path_from_path = shutil.which(name)
  145. if path_from_path:
  146. resolved_path = path_from_path
  147. discovery = "PATH"
  148. else:
  149. for candidate in _candidate_tool_paths(name):
  150. if candidate.is_file():
  151. resolved_path = str(candidate)
  152. discovery = "env_or_default_toolchain_root"
  153. break
  154. payload: dict[str, Any] = {
  155. "name": name,
  156. "status": "present" if resolved_path else "missing",
  157. "path": resolved_path,
  158. "discovery": discovery if resolved_path else "not_found",
  159. "fact_class": "local_detected_fact",
  160. }
  161. if resolved_path and version_args:
  162. payload["version"] = _version_from_command([resolved_path, *version_args])
  163. return payload
  164. def _python_module_status(module: str, *, python_exe: Path | None = None) -> dict[str, Any]:
  165. if python_exe is not None and python_exe.is_file():
  166. script = (
  167. "import importlib.util; "
  168. f"spec=importlib.util.find_spec({module!r}); "
  169. "print('' if spec is None or spec.origin is None else spec.origin); "
  170. "raise SystemExit(0 if spec is not None else 1)"
  171. )
  172. try:
  173. result = subprocess.run(
  174. [str(python_exe), "-c", script],
  175. cwd=ROOT,
  176. text=True,
  177. stdout=subprocess.PIPE,
  178. stderr=subprocess.PIPE,
  179. timeout=20,
  180. )
  181. except (OSError, subprocess.TimeoutExpired):
  182. result = None
  183. if result is not None:
  184. path = result.stdout.strip() if result.returncode == 0 else None
  185. return {
  186. "name": f"python_module:{module}",
  187. "status": "present" if result.returncode == 0 else "missing",
  188. "path": path,
  189. "python": str(python_exe),
  190. "fact_class": "local_detected_fact",
  191. }
  192. spec = importlib.util.find_spec(module)
  193. return {
  194. "name": f"python_module:{module}",
  195. "status": "present" if spec else "missing",
  196. "path": None if spec is None or spec.origin is None else spec.origin,
  197. "python": sys.executable,
  198. "fact_class": "local_detected_fact",
  199. }
  200. def _cocotb_python() -> Path:
  201. configured = os.environ.get("PROD2U_P4_COCOTB_PYTHON")
  202. if configured:
  203. return Path(configured)
  204. return DEFAULT_COCOTB_VENV_PYTHON
  205. def _serial_ports() -> dict[str, Any]:
  206. powershell = shutil.which("powershell") or shutil.which("pwsh")
  207. if not powershell:
  208. return {"status": "unknown", "ports": [], "reason": "PowerShell not found"}
  209. script = "Get-CimInstance Win32_SerialPort | Select-Object -ExpandProperty DeviceID"
  210. try:
  211. result = subprocess.run(
  212. [powershell, "-NoProfile", "-Command", script],
  213. text=True,
  214. stdout=subprocess.PIPE,
  215. stderr=subprocess.PIPE,
  216. timeout=10,
  217. )
  218. except (OSError, subprocess.TimeoutExpired):
  219. return {"status": "unknown", "ports": [], "reason": "serial query failed"}
  220. ports = [line.strip() for line in result.stdout.splitlines() if line.strip()]
  221. return {
  222. "status": "detected" if ports else "not_detected",
  223. "ports": ports,
  224. "fact_class": "local_detected_fact",
  225. }
  226. def probe_toolchain() -> dict[str, Any]:
  227. tools = {
  228. "td": _path_status("td", explicit_path=TD_EXE),
  229. "td_cli": _path_status("td_commands_prompt", explicit_path=TD_CLI),
  230. "python": {
  231. "name": "python",
  232. "status": "present",
  233. "path": sys.executable,
  234. "version": sys.version.split()[0],
  235. "fact_class": "local_detected_fact",
  236. },
  237. "git": _path_status("git", explicit_path=GIT_EXE, version_args=["--version"]),
  238. "iverilog": _path_status("iverilog", version_args=["-V"]),
  239. "vvp": _path_status("vvp", version_args=["-V"]),
  240. "verilator": _path_status("verilator", version_args=["--version"]),
  241. "yosys": _path_status("yosys", version_args=["-V"]),
  242. "sby": _path_status("sby", version_args=["--version"]),
  243. "vsim": _path_status("vsim", version_args=["-version"]),
  244. "cocotb": _python_module_status("cocotb", python_exe=_cocotb_python()),
  245. }
  246. tools["td_cli"]["version"] = _td_cli_version()
  247. pyserial = _python_module_status("serial")
  248. jsonschema = _python_module_status("jsonschema")
  249. def backend_status(required: list[str], present: bool) -> str:
  250. return "available" if present else "blocked_missing_tool"
  251. return {
  252. "schema": "prod2u-p4-actuator-trace-toolchain-probe-v1",
  253. "status": "pass",
  254. "generated_at": datetime.now(timezone.utc).isoformat(),
  255. "fact_classes": {
  256. "external_fact": "Current/public vendor or project documentation, cited in docs.",
  257. "local_detected_fact": "Observed on this machine by this read-only probe.",
  258. "project_defined_strategy": "Chosen by this project harness, not a chip-vendor requirement.",
  259. "not_verified": "Available only after manual or hardware evidence is collected.",
  260. },
  261. "tools": tools,
  262. "toolchain_search": {
  263. "env_vars": _toolchain_root_env_vars(),
  264. "preferred_env_vars": ["PROD2U_P4_TOOLCHAIN_ROOT", "OSS_CAD_SUITE_ROOT"],
  265. "cocotb_env_vars": ["PROD2U_P4_COCOTB_PYTHON"],
  266. "default_oss_cad_suite_root": str(DEFAULT_OSS_CAD_SUITE_ROOT),
  267. "default_cocotb_python": str(DEFAULT_COCOTB_VENV_PYTHON),
  268. "fact_class": "project_defined_strategy",
  269. },
  270. "serial_ports": _serial_ports(),
  271. "uart_receipt_backends": {
  272. "pyserial": pyserial,
  273. "jsonschema": jsonschema,
  274. "fallback": "powershell_dotnet_limited serial enumeration and builtin_limited schema validation",
  275. "strict_gate_boundary": "Strict UART gates must record backend capability and cannot pass unknown COM ports without allowlist.",
  276. "fact_class": "local_detected_fact",
  277. },
  278. "verification_backends": {
  279. "icarus": {
  280. "status": backend_status(["iverilog", "vvp"], tools["iverilog"]["status"] == "present" and tools["vvp"]["status"] == "present"),
  281. "required_tools": ["iverilog", "vvp"],
  282. "fact_class": "project_defined_strategy",
  283. },
  284. "verilator": {
  285. "status": backend_status(["verilator"], tools["verilator"]["status"] == "present"),
  286. "required_tools": ["verilator"],
  287. "fact_class": "project_defined_strategy",
  288. },
  289. "cocotb": {
  290. "status": backend_status(
  291. ["python_module:cocotb", "iverilog", "vvp"],
  292. tools["cocotb"]["status"] == "present"
  293. and tools["iverilog"]["status"] == "present"
  294. and tools["vvp"]["status"] == "present",
  295. ),
  296. "required_tools": ["python_module:cocotb", "iverilog", "vvp"],
  297. "fact_class": "project_defined_strategy",
  298. },
  299. "formal_sby": {
  300. "status": backend_status(["sby", "yosys"], tools["sby"]["status"] == "present" and tools["yosys"]["status"] == "present"),
  301. "required_tools": ["sby", "yosys"],
  302. "fact_class": "project_defined_strategy",
  303. },
  304. "td": {
  305. "status": "available" if tools["td_cli"]["status"] == "present" else "blocked_missing_tool",
  306. "required_tools": ["td_commands_prompt.exe"],
  307. "required_release": "Release_2026.1_SP1",
  308. "required_build": "6.2.2.198412",
  309. "fact_class": "local_detected_fact",
  310. },
  311. },
  312. "authority_boundary": "Tool presence only enables a verification layer. It does not prove RTL, board wiring, or mechanical behavior.",
  313. }
  314. def main() -> int:
  315. print(json.dumps(probe_toolchain(), indent=2))
  316. return 0
  317. if __name__ == "__main__":
  318. raise SystemExit(main())