run_prod2u_door_temp_uart_e2e.py 14 KB

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