run_prod2u_door_temp_uart_e2e.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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. # Prefer configured/verify venv over a possibly poisoned sys.executable.
  76. seen: set[str] = set()
  77. for candidate in candidates:
  78. key = str(candidate)
  79. if key in seen:
  80. continue
  81. seen.add(key)
  82. if candidate.is_file() and _python_has_cocotb(candidate):
  83. return candidate
  84. if Path(sys.executable).is_file() and _python_has_cocotb(Path(sys.executable)):
  85. return Path(sys.executable)
  86. return DEFAULT_VERIFY_PYTHON
  87. def _is_oss_cad_bin(part: str) -> bool:
  88. normalized = part.rstrip("/")
  89. return normalized.endswith("oss-cad-suite/latest/bin") or normalized.endswith(
  90. "oss-cad-suite/bin"
  91. )
  92. def _tool_bin_dirs(shim_dir: Path | None = None) -> list[str]:
  93. """Dirs with iverilog/vvp without exposing OSS CAD python shims on PATH.
  94. Host often only has Icarus inside oss-cad-suite/bin. Putting that whole bin
  95. on PATH resurrects tabbypy3 for VPI; instead symlink iverilog/vvp into a
  96. private shim dir when no system install exists.
  97. """
  98. dirs: list[str] = []
  99. if shim_dir is not None:
  100. shim_dir.mkdir(parents=True, exist_ok=True)
  101. for name in ("iverilog", "vvp"):
  102. resolved = shutil.which(name)
  103. if not resolved:
  104. for candidate in (
  105. Path("/data/prod2u/oss-cad-suite/latest/bin") / name,
  106. Path("/usr/local/bin") / name,
  107. Path("/usr/bin") / name,
  108. ):
  109. if candidate.is_file() and os.access(candidate, os.X_OK):
  110. resolved = str(candidate)
  111. break
  112. if not resolved:
  113. continue
  114. # OSS CAD iverilog/vvp are shell wrappers using $0-relative paths;
  115. # symlinks break them. Emit absolute exec wrappers instead.
  116. wrapper = shim_dir / name
  117. if wrapper.exists() or wrapper.is_symlink():
  118. wrapper.unlink()
  119. wrapper.write_text(
  120. "#!/bin/sh\n"
  121. f'exec "{resolved}" "$@"\n',
  122. encoding="ascii",
  123. )
  124. wrapper.chmod(0o755)
  125. dirs.append(str(shim_dir))
  126. for name in ("iverilog", "vvp"):
  127. resolved = shutil.which(name)
  128. if resolved:
  129. parent = str(Path(resolved).parent)
  130. if parent not in dirs and not _is_oss_cad_bin(parent):
  131. dirs.append(parent)
  132. for fallback in ("/usr/local/bin", "/usr/bin", "/bin"):
  133. if fallback not in dirs:
  134. dirs.append(fallback)
  135. return dirs
  136. def _sanitize_env(python_exe: Path, build_dir: Path) -> dict[str, str]:
  137. """Bind VPI to verification Python and hide OSS CAD python shims.
  138. OSS CAD ``bin`` must stay off PATH: even without PYTHONEXECUTABLE, having
  139. ``tabbypy3`` visible makes the VPI-embedded interpreter report
  140. sys.executable as tabbypy3 (cocotb gpi_embed sanity check fails).
  141. """
  142. env = {k: v for k, v in os.environ.items() if k not in _OSS_CAD_POISON}
  143. python_bin = str(python_exe.parent)
  144. shim_dir = build_dir / "path-shim"
  145. shim_dir.mkdir(parents=True, exist_ok=True)
  146. for shim_name in ("python", "python3", "python3.13", "tabbypy3", "tabby"):
  147. shim_path = shim_dir / shim_name
  148. if shim_path.exists() or shim_path.is_symlink():
  149. shim_path.unlink()
  150. shim_path.symlink_to(python_exe)
  151. path_parts: list[str] = [python_bin, str(shim_dir), *_tool_bin_dirs(shim_dir)]
  152. for part in env.get("PATH", "").split(os.pathsep):
  153. if not part or _is_oss_cad_bin(part):
  154. continue
  155. if part not in path_parts:
  156. path_parts.append(part)
  157. env["PATH"] = os.pathsep.join(path_parts)
  158. env["VIRTUAL_ENV"] = str(python_exe.parent.parent)
  159. env["PYGPI_PYTHON_BIN"] = str(python_exe)
  160. env["PROD2U_P4_COCOTB_PYTHON"] = str(python_exe)
  161. # Keep TEMP under the lane build root; cocotb_tools uses build_dir directly.
  162. env["TEMP"] = str(build_dir)
  163. env["TMP"] = str(build_dir)
  164. env["TMPDIR"] = str(build_dir)
  165. for key in _OSS_CAD_POISON:
  166. env.pop(key, None)
  167. # find_libpython may be unavailable while PYTHONEXECUTABLE still poisons this
  168. # process; LIBPYTHON_LOC is filled after re-exec in main().
  169. return env
  170. def _already_under_selected_python(python_exe: Path) -> bool:
  171. """True when this process was launched via the LD-safe wrapper for python_exe.
  172. OSS CAD wrappers report sys.executable as bare libexec/python3.11 even when
  173. argv0 was venv/bin/python or py3bin/python3.11. Re-execing on that mismatch
  174. loops forever.
  175. """
  176. if os.environ.get("PROD2U_COCOTB_REEXEC_DONE") == "1":
  177. return True
  178. current = Path(sys.executable).expanduser()
  179. selected = python_exe.expanduser()
  180. if str(current) == str(selected):
  181. return True
  182. if current.parent == selected.parent and current.name.startswith("python"):
  183. return True
  184. # Same wrapper family: venv/bin/python -> py3bin -> libexec
  185. try:
  186. if current.resolve() == selected.resolve():
  187. return True
  188. except OSError:
  189. pass
  190. marker = os.environ.get("PROD2U_P4_COCOTB_PYTHON", "").strip()
  191. if marker and Path(marker).expanduser() == selected and "libexec" in current.as_posix():
  192. return True
  193. return False
  194. def _ensure_running_under(python_exe: Path, build_dir: Path) -> None:
  195. """Re-exec under the selected interpreter with a sanitized environment.
  196. PYTHONEXECUTABLE poisons sys.executable for the whole process lifetime; the
  197. only fix is a clean execve before cocotb_tools/VPI start.
  198. """
  199. need_reexec = False
  200. if "tabbypy3" in Path(sys.executable).name:
  201. need_reexec = True
  202. if os.environ.get("PYTHONEXECUTABLE"):
  203. need_reexec = True
  204. if not _already_under_selected_python(python_exe):
  205. need_reexec = True
  206. if not need_reexec:
  207. return
  208. env = _sanitize_env(python_exe, build_dir)
  209. env["PROD2U_COCOTB_REEXEC_DONE"] = "1"
  210. os.execve(
  211. str(python_exe),
  212. [str(python_exe), "-B", str(Path(__file__).resolve()), *sys.argv[1:]],
  213. env,
  214. )
  215. def main() -> int:
  216. build_dir = _resolve_build_dir()
  217. build_dir.mkdir(parents=True, exist_ok=True)
  218. results_xml = build_dir / "results.xml"
  219. python_exe = _select_python()
  220. # Re-exec first when poisoned so subsequent imports see a healthy venv.
  221. _ensure_running_under(python_exe, build_dir)
  222. sanitized = _sanitize_env(python_exe, build_dir)
  223. try:
  224. import find_libpython
  225. libpython = find_libpython.find_libpython()
  226. if libpython:
  227. sanitized["LIBPYTHON_LOC"] = libpython
  228. except Exception:
  229. pass
  230. os.environ.clear()
  231. os.environ.update(sanitized)
  232. # Guard: refuse to proceed if poison remains.
  233. if os.environ.get("PYTHONEXECUTABLE"):
  234. print(
  235. "error: PYTHONEXECUTABLE is set; refusing to run VPI under OSS CAD poison: "
  236. f"{os.environ['PYTHONEXECUTABLE']}",
  237. file=sys.stderr,
  238. )
  239. return 2
  240. if "tabbypy3" in Path(sys.executable).name:
  241. print(f"error: sys.executable is OSS CAD tabbypy3: {sys.executable}", file=sys.stderr)
  242. return 2
  243. if any(_is_oss_cad_bin(part) for part in os.environ.get("PATH", "").split(os.pathsep)):
  244. print("error: OSS CAD bin still on PATH after sanitize", file=sys.stderr)
  245. return 2
  246. from cocotb_tools.runner import get_runner
  247. runner = get_runner("icarus")
  248. _orig_set_env_common = runner._set_env_common
  249. def _set_env_common_without_oss_cad_poison() -> None:
  250. _orig_set_env_common()
  251. for key in _OSS_CAD_POISON:
  252. runner.env.pop(key, None)
  253. # Re-assert PATH without OSS CAD python shims (cocotb may append libs_dir only).
  254. path_parts = [
  255. part
  256. for part in runner.env.get("PATH", "").split(os.pathsep)
  257. if part and not _is_oss_cad_bin(part)
  258. ]
  259. runner.env["PATH"] = os.pathsep.join(path_parts)
  260. # Prefer LD-safe wrapper; bare libexec sys.executable breaks VPI children.
  261. runner.env["PYGPI_PYTHON_BIN"] = str(python_exe)
  262. runner.env.pop("PYTHONEXECUTABLE", None)
  263. audit = build_dir / "vpi-env-audit.txt"
  264. audit.write_text(
  265. "\n".join(
  266. [
  267. f"os.PYTHONEXECUTABLE={os.environ.get('PYTHONEXECUTABLE')!r}",
  268. f"runner.PYTHONEXECUTABLE={runner.env.get('PYTHONEXECUTABLE')!r}",
  269. f"runner.PYGPI_PYTHON_BIN={runner.env.get('PYGPI_PYTHON_BIN')!r}",
  270. f"sys.executable={sys.executable!r}",
  271. f"PATH_has_oss_cad={any(_is_oss_cad_bin(p) for p in runner.env.get('PATH', '').split(os.pathsep))}",
  272. ]
  273. )
  274. + "\n",
  275. encoding="utf-8",
  276. )
  277. if "tabbypy3" in runner.env.get("PYGPI_PYTHON_BIN", ""):
  278. raise RuntimeError("PYGPI_PYTHON_BIN resolved to OSS CAD tabbypy3")
  279. if runner.env.get("PYTHONEXECUTABLE"):
  280. raise RuntimeError(
  281. "PYTHONEXECUTABLE still present in runner.env after sanitize: "
  282. f"{runner.env['PYTHONEXECUTABLE']}"
  283. )
  284. runner._set_env_common = _set_env_common_without_oss_cad_poison # type: ignore[method-assign]
  285. runner.build(
  286. sources=[*rtl_sources(), TEST_DIR / "prod2u_door_temp_uart_top.v"],
  287. hdl_toplevel="prod2u_door_temp_uart_top",
  288. build_dir=build_dir,
  289. build_args=["-I", str(ROOT)],
  290. always=True,
  291. verbose=False,
  292. )
  293. results = Path(
  294. runner.test(
  295. hdl_toplevel="prod2u_door_temp_uart_top",
  296. test_module="test_prod2u_door_temp_uart_e2e",
  297. build_dir=build_dir,
  298. test_dir=TEST_DIR,
  299. results_xml=str(results_xml),
  300. extra_env={
  301. "PYGPI_PYTHON_BIN": str(python_exe),
  302. "PATH": os.environ["PATH"],
  303. "VIRTUAL_ENV": os.environ.get("VIRTUAL_ENV", ""),
  304. },
  305. )
  306. )
  307. if not results.is_file() or results_xml_has_failures(results):
  308. print(f"cocotb fail results={results}", file=sys.stderr)
  309. return 1
  310. print(f"cocotb pass results={results} python={python_exe}")
  311. return 0
  312. if __name__ == "__main__":
  313. raise SystemExit(main())