run_prod2u_door_temp_uart_e2e.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. #!/usr/bin/env python3
  2. """Run the current project's real-UART cocotb scenario.
  3. Forces the verification-venv Python into VPI (blocks OSS CAD tabbypy3 /
  4. PYTHONEXECUTABLE poisoning) and keeps the Icarus build tree under an
  5. independent TEMP/build directory.
  6. """
  7. from __future__ import annotations
  8. import os
  9. from pathlib import Path
  10. import shutil
  11. import sys
  12. import xml.etree.ElementTree as ET
  13. ROOT = Path(__file__).resolve().parents[2]
  14. TEST_DIR = Path(__file__).resolve().parent
  15. sys.path.insert(0, str(ROOT))
  16. def _default_verify_python() -> Path:
  17. for key in ("PROD2U_P4_COCOTB_PYTHON", "PRODU2_VERIFY_PYTHON"):
  18. value = os.environ.get(key, "").strip()
  19. if value:
  20. return Path(value).expanduser()
  21. for candidate in (
  22. Path("/data/prod2u/venvs/verify/bin/python"),
  23. Path.home() / ".cache" / "prod2u" / "venvs" / "verify" / "bin" / "python",
  24. ):
  25. if candidate.is_file():
  26. return candidate
  27. return Path("/data/prod2u/venvs/verify/bin/python")
  28. DEFAULT_VERIFY_PYTHON = _default_verify_python()
  29. # Poisonous env vars exported by OSS CAD tabbypy3 / environment scripts.
  30. _OSS_CAD_POISON = (
  31. "PYTHONEXECUTABLE",
  32. "PYTHONHOME",
  33. "PYTHONNOUSERSITE",
  34. )
  35. def _resolve_build_dir() -> Path:
  36. explicit = os.environ.get("PROD2U_COCOTB_BUILD_DIR", "").strip()
  37. if explicit:
  38. return Path(explicit).expanduser()
  39. temp_root = Path(os.environ.get("TEMP", ROOT / "tmp"))
  40. return temp_root / "cocotb" / "prod2u_door_temp_uart_e2e"
  41. BUILD_DIR = _resolve_build_dir()
  42. RESULTS_XML = BUILD_DIR / "results.xml"
  43. def rtl_sources() -> list[Path]:
  44. from tools.prod2u_p4_normal_v3_build import PRODUCTION_RTL_SOURCES
  45. return [ROOT / relative for relative in PRODUCTION_RTL_SOURCES]
  46. def results_xml_has_failures(results: Path) -> bool:
  47. root = ET.parse(results).getroot()
  48. return bool(
  49. root.findall(".//failure")
  50. or root.findall(".//error")
  51. or sum(int(node.attrib.get("failures", "0")) for node in root.findall(".//testsuite"))
  52. or sum(int(node.attrib.get("errors", "0")) for node in root.findall(".//testsuite"))
  53. or int(root.attrib.get("failures", "0"))
  54. or int(root.attrib.get("errors", "0"))
  55. )
  56. def _python_has_cocotb(python_exe: Path) -> bool:
  57. import subprocess
  58. completed = subprocess.run(
  59. [str(python_exe), "-B", "-c", "import cocotb, cocotb_tools"],
  60. cwd=str(ROOT),
  61. env={k: v for k, v in os.environ.items() if k not in _OSS_CAD_POISON},
  62. text=True,
  63. stdout=subprocess.PIPE,
  64. stderr=subprocess.PIPE,
  65. timeout=20,
  66. check=False,
  67. )
  68. return completed.returncode == 0
  69. def _select_python() -> Path:
  70. candidates: list[Path] = []
  71. configured = os.environ.get("PROD2U_P4_COCOTB_PYTHON", "").strip()
  72. if configured:
  73. candidates.append(Path(configured).expanduser())
  74. candidates.append(DEFAULT_VERIFY_PYTHON)
  75. # The persistent OSS Python wrapper carries the matching shared library
  76. # and bundled cocotb. Prefer its non-tabbypy3 entrypoint before falling
  77. # back to a poisoned sys.executable reported by the vendor wrapper.
  78. candidates.append(Path("/data/prod2u/oss-cad-suite/latest/py3bin/python3.11"))
  79. # Prefer configured/verify venv over a possibly poisoned sys.executable.
  80. seen: set[str] = set()
  81. for candidate in candidates:
  82. key = str(candidate)
  83. if key in seen:
  84. continue
  85. seen.add(key)
  86. if candidate.is_file() and _python_has_cocotb(candidate):
  87. return candidate
  88. if Path(sys.executable).is_file() and _python_has_cocotb(Path(sys.executable)):
  89. return Path(sys.executable)
  90. return DEFAULT_VERIFY_PYTHON
  91. def _is_oss_cad_bin(part: str) -> bool:
  92. normalized = part.rstrip("/")
  93. return normalized.endswith("oss-cad-suite/latest/bin") or normalized.endswith(
  94. "oss-cad-suite/bin"
  95. )
  96. def _tool_bin_dirs(shim_dir: Path | None = None, python_exe: Path | None = None) -> list[str]:
  97. """Dirs with iverilog/vvp without exposing OSS CAD python shims on PATH.
  98. Host often only has Icarus inside oss-cad-suite/bin. Putting that whole bin
  99. on PATH resurrects tabbypy3 for VPI; instead symlink iverilog/vvp into a
  100. private shim dir when no system install exists.
  101. """
  102. dirs: list[str] = []
  103. if shim_dir is not None:
  104. shim_dir.mkdir(parents=True, exist_ok=True)
  105. oss_top = Path("/data/prod2u/oss-cad-suite/latest")
  106. for name in ("iverilog", "vvp"):
  107. resolved = shutil.which(name)
  108. # A controlled Python re-exec preserves this run's shim directory
  109. # on PATH. Never regenerate a shim that execs itself.
  110. if resolved and Path(resolved).parent.resolve() == shim_dir.resolve():
  111. resolved = None
  112. if not resolved:
  113. for candidate in (
  114. oss_top / "bin" / name,
  115. Path("/usr/local/bin") / name,
  116. Path("/usr/bin") / name,
  117. ):
  118. if candidate.is_file() and os.access(candidate, os.X_OK):
  119. resolved = str(candidate)
  120. break
  121. if not resolved:
  122. continue
  123. wrapper = shim_dir / name
  124. if wrapper.exists() or wrapper.is_symlink():
  125. wrapper.unlink()
  126. resolved_path = Path(resolved)
  127. libexec = oss_top / "libexec" / name
  128. if (
  129. name == "vvp"
  130. and python_exe is not None
  131. and libexec.is_file()
  132. and "oss-cad-suite" in resolved_path.as_posix()
  133. ):
  134. # OSS bin/vvp exports PYTHONEXECUTABLE=tabbypy3; bypass that wrapper.
  135. py = python_exe.expanduser()
  136. wrapper.write_text(
  137. "#!/bin/sh\n"
  138. f'export PYGPI_PYTHON_BIN="{py}"\n'
  139. f'export PYTHONEXECUTABLE="{py}"\n'
  140. f'export PRODU2_VERIFY_PYTHON="{py}"\n'
  141. "unset PYTHONHOME\n"
  142. f'exec "{oss_top}/lib/ld-linux-x86-64.so.2" --inhibit-cache --inhibit-rpath "" '
  143. f'--library-path "{oss_top}/lib" "{libexec}" "$@"\n',
  144. encoding="ascii",
  145. )
  146. else:
  147. wrapper.write_text(
  148. "#!/bin/sh\n"
  149. f'exec "{resolved}" "$@"\n',
  150. encoding="ascii",
  151. )
  152. wrapper.chmod(0o755)
  153. dirs.append(str(shim_dir))
  154. for name in ("iverilog", "vvp"):
  155. resolved = shutil.which(name)
  156. if resolved:
  157. parent = str(Path(resolved).parent)
  158. if parent not in dirs and not _is_oss_cad_bin(parent):
  159. dirs.append(parent)
  160. for fallback in ("/usr/local/bin", "/usr/bin", "/bin"):
  161. if fallback not in dirs:
  162. dirs.append(fallback)
  163. return dirs
  164. def _sanitize_env(python_exe: Path, build_dir: Path) -> dict[str, str]:
  165. """Bind VPI to verification Python and hide OSS CAD python shims.
  166. OSS CAD ``bin`` must stay off PATH: even without PYTHONEXECUTABLE, having
  167. ``tabbypy3`` visible makes the VPI-embedded interpreter report
  168. sys.executable as tabbypy3 (cocotb gpi_embed sanity check fails).
  169. """
  170. env = {k: v for k, v in os.environ.items() if k not in _OSS_CAD_POISON}
  171. python_bin = str(python_exe.parent)
  172. shim_dir = build_dir / "path-shim"
  173. shim_dir.mkdir(parents=True, exist_ok=True)
  174. for shim_name in ("python", "python3", "python3.13", "tabbypy3", "tabby"):
  175. shim_path = shim_dir / shim_name
  176. if shim_path.exists() or shim_path.is_symlink():
  177. shim_path.unlink()
  178. shim_path.symlink_to(python_exe)
  179. path_parts: list[str] = [python_bin, str(shim_dir), *_tool_bin_dirs(shim_dir, python_exe)]
  180. for part in env.get("PATH", "").split(os.pathsep):
  181. if not part or _is_oss_cad_bin(part):
  182. continue
  183. if part not in path_parts:
  184. path_parts.append(part)
  185. env["PATH"] = os.pathsep.join(path_parts)
  186. env["VIRTUAL_ENV"] = str(python_exe.parent.parent)
  187. env["PYGPI_PYTHON_BIN"] = str(python_exe)
  188. env["PROD2U_P4_COCOTB_PYTHON"] = str(python_exe)
  189. # Keep TEMP under the lane build root; cocotb_tools uses build_dir directly.
  190. env["TEMP"] = str(build_dir)
  191. env["TMP"] = str(build_dir)
  192. env["TMPDIR"] = str(build_dir)
  193. for key in _OSS_CAD_POISON:
  194. env.pop(key, None)
  195. # find_libpython may be unavailable while PYTHONEXECUTABLE still poisons this
  196. # process; LIBPYTHON_LOC is filled after re-exec in main().
  197. return env
  198. def _already_under_selected_python(python_exe: Path) -> bool:
  199. """True when this process was launched via the LD-safe wrapper for python_exe.
  200. OSS CAD wrappers report sys.executable as bare libexec/python3.11 even when
  201. argv0 was venv/bin/python or py3bin/python3.11. Re-execing on that mismatch
  202. loops forever.
  203. """
  204. if os.environ.get("PROD2U_COCOTB_REEXEC_DONE") == "1":
  205. return True
  206. current = Path(sys.executable).expanduser()
  207. selected = python_exe.expanduser()
  208. if str(current) == str(selected):
  209. return True
  210. if current.parent == selected.parent and current.name.startswith("python"):
  211. return True
  212. # Same wrapper family: venv/bin/python -> py3bin -> libexec
  213. try:
  214. if current.resolve() == selected.resolve():
  215. return True
  216. except OSError:
  217. pass
  218. marker = os.environ.get("PROD2U_P4_COCOTB_PYTHON", "").strip()
  219. if marker and Path(marker).expanduser() == selected and "libexec" in current.as_posix():
  220. return True
  221. return False
  222. def _ensure_running_under(python_exe: Path, build_dir: Path) -> None:
  223. """Re-exec under the selected interpreter with a sanitized environment.
  224. PYTHONEXECUTABLE poisons sys.executable for the whole process lifetime; the
  225. only fix is a clean execve before cocotb_tools/VPI start.
  226. """
  227. if os.environ.get("PROD2U_COCOTB_REEXEC_DONE") == "1":
  228. # OSS CAD's selected wrapper legitimately injects these again while
  229. # launching libexec/python. The marker proves the one controlled
  230. # re-exec already happened; clear the wrapper residue here instead of
  231. # recursively execing the same wrapper forever.
  232. for key in _OSS_CAD_POISON:
  233. os.environ.pop(key, None)
  234. return
  235. need_reexec = False
  236. if "tabbypy3" in Path(sys.executable).name:
  237. need_reexec = True
  238. if os.environ.get("PYTHONEXECUTABLE"):
  239. need_reexec = True
  240. if not _already_under_selected_python(python_exe):
  241. need_reexec = True
  242. if not need_reexec:
  243. return
  244. env = _sanitize_env(python_exe, build_dir)
  245. env["PROD2U_COCOTB_REEXEC_DONE"] = "1"
  246. os.execve(
  247. str(python_exe),
  248. [str(python_exe), "-B", str(Path(__file__).resolve()), *sys.argv[1:]],
  249. env,
  250. )
  251. def main() -> int:
  252. build_dir = _resolve_build_dir()
  253. build_dir.mkdir(parents=True, exist_ok=True)
  254. results_xml = build_dir / "results.xml"
  255. python_exe = _select_python()
  256. # Re-exec first when poisoned so subsequent imports see a healthy venv.
  257. _ensure_running_under(python_exe, build_dir)
  258. sanitized = _sanitize_env(python_exe, build_dir)
  259. try:
  260. import find_libpython
  261. libpython = find_libpython.find_libpython()
  262. if libpython:
  263. sanitized["LIBPYTHON_LOC"] = libpython
  264. except Exception:
  265. pass
  266. os.environ.clear()
  267. os.environ.update(sanitized)
  268. # Guard: refuse to proceed if poison remains.
  269. if os.environ.get("PYTHONEXECUTABLE"):
  270. print(
  271. "error: PYTHONEXECUTABLE is set; refusing to run VPI under OSS CAD poison: "
  272. f"{os.environ['PYTHONEXECUTABLE']}",
  273. file=sys.stderr,
  274. )
  275. return 2
  276. if (
  277. "tabbypy3" in Path(sys.executable).name
  278. and os.environ.get("PROD2U_COCOTB_REEXEC_DONE") != "1"
  279. ):
  280. print(f"error: sys.executable is OSS CAD tabbypy3: {sys.executable}", file=sys.stderr)
  281. return 2
  282. if any(_is_oss_cad_bin(part) for part in os.environ.get("PATH", "").split(os.pathsep)):
  283. print("error: OSS CAD bin still on PATH after sanitize", file=sys.stderr)
  284. return 2
  285. from cocotb_tools.runner import get_runner
  286. runner = get_runner("icarus")
  287. # cocotb_tools hard-codes -g2012 before user build_args. Replace that
  288. # single dialect selection so the command exactly matches the passing
  289. # Legacy Icarus lane instead of passing two conflicting -g options.
  290. _orig_build_command = runner._build_command
  291. def _build_command_g2005_sv():
  292. commands = _orig_build_command()
  293. return [
  294. ["-g2005-sv" if arg == "-g2012" else arg for arg in command]
  295. for command in commands
  296. ]
  297. runner._build_command = _build_command_g2005_sv # type: ignore[method-assign]
  298. _orig_set_env_common = runner._set_env_common
  299. def _set_env_common_without_oss_cad_poison() -> None:
  300. _orig_set_env_common()
  301. for key in _OSS_CAD_POISON:
  302. runner.env.pop(key, None)
  303. # Re-assert PATH without OSS CAD python shims (cocotb may append libs_dir only).
  304. path_parts = [
  305. part
  306. for part in runner.env.get("PATH", "").split(os.pathsep)
  307. if part and not _is_oss_cad_bin(part)
  308. ]
  309. runner.env["PATH"] = os.pathsep.join(path_parts)
  310. # Prefer LD-safe wrapper; bare libexec sys.executable breaks VPI children.
  311. runner.env["PYGPI_PYTHON_BIN"] = str(python_exe)
  312. runner.env.pop("PYTHONEXECUTABLE", None)
  313. audit = build_dir / "vpi-env-audit.txt"
  314. audit.write_text(
  315. "\n".join(
  316. [
  317. f"os.PYTHONEXECUTABLE={os.environ.get('PYTHONEXECUTABLE')!r}",
  318. f"runner.PYTHONEXECUTABLE={runner.env.get('PYTHONEXECUTABLE')!r}",
  319. f"runner.PYGPI_PYTHON_BIN={runner.env.get('PYGPI_PYTHON_BIN')!r}",
  320. f"sys.executable={sys.executable!r}",
  321. f"PATH_has_oss_cad={any(_is_oss_cad_bin(p) for p in runner.env.get('PATH', '').split(os.pathsep))}",
  322. ]
  323. )
  324. + "\n",
  325. encoding="utf-8",
  326. )
  327. if "tabbypy3" in runner.env.get("PYGPI_PYTHON_BIN", ""):
  328. raise RuntimeError("PYGPI_PYTHON_BIN resolved to OSS CAD tabbypy3")
  329. if runner.env.get("PYTHONEXECUTABLE"):
  330. raise RuntimeError(
  331. "PYTHONEXECUTABLE still present in runner.env after sanitize: "
  332. f"{runner.env['PYTHONEXECUTABLE']}"
  333. )
  334. runner._set_env_common = _set_env_common_without_oss_cad_poison # type: ignore[method-assign]
  335. runner.build(
  336. sources=[*rtl_sources(), TEST_DIR / "prod2u_door_temp_uart_top.v"],
  337. hdl_toplevel="prod2u_door_temp_uart_top",
  338. build_dir=build_dir,
  339. build_args=["-I", str(ROOT)],
  340. always=True,
  341. verbose=False,
  342. )
  343. results = Path(
  344. runner.test(
  345. hdl_toplevel="prod2u_door_temp_uart_top",
  346. test_module="test_prod2u_door_temp_uart_e2e",
  347. build_dir=build_dir,
  348. test_dir=TEST_DIR,
  349. results_xml=str(results_xml),
  350. extra_env={
  351. "PYGPI_PYTHON_BIN": str(python_exe),
  352. "PATH": os.environ["PATH"],
  353. "VIRTUAL_ENV": os.environ.get("VIRTUAL_ENV", ""),
  354. },
  355. )
  356. )
  357. if not results.is_file() or results_xml_has_failures(results):
  358. print(f"cocotb fail results={results}", file=sys.stderr)
  359. return 1
  360. print(f"cocotb pass results={results} python={python_exe}")
  361. return 0
  362. if __name__ == "__main__":
  363. raise SystemExit(main())