run_prod2u_door_temp_uart_e2e.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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. DEFAULT_VERIFY_PYTHON = Path(
  17. os.environ.get(
  18. "PROD2U_P4_COCOTB_PYTHON",
  19. "/root/.cache/prod2u/venvs/verify/bin/python",
  20. )
  21. ).expanduser()
  22. # Poisonous env vars exported by OSS CAD tabbypy3 / environment scripts.
  23. _OSS_CAD_POISON = (
  24. "PYTHONEXECUTABLE",
  25. "PYTHONHOME",
  26. "PYTHONNOUSERSITE",
  27. )
  28. def _resolve_build_dir() -> Path:
  29. explicit = os.environ.get("PROD2U_COCOTB_BUILD_DIR", "").strip()
  30. if explicit:
  31. return Path(explicit).expanduser()
  32. temp_root = Path(os.environ.get("TEMP", ROOT / "tmp"))
  33. return temp_root / "cocotb" / "prod2u_door_temp_uart_e2e"
  34. BUILD_DIR = _resolve_build_dir()
  35. RESULTS_XML = BUILD_DIR / "results.xml"
  36. def rtl_sources() -> list[Path]:
  37. from tools.prod2u_p4_normal_v3_build import PRODUCTION_RTL_SOURCES
  38. return [ROOT / relative for relative in PRODUCTION_RTL_SOURCES]
  39. def results_xml_has_failures(results: Path) -> bool:
  40. root = ET.parse(results).getroot()
  41. return bool(
  42. root.findall(".//failure")
  43. or root.findall(".//error")
  44. or sum(int(node.attrib.get("failures", "0")) for node in root.findall(".//testsuite"))
  45. or sum(int(node.attrib.get("errors", "0")) for node in root.findall(".//testsuite"))
  46. or int(root.attrib.get("failures", "0"))
  47. or int(root.attrib.get("errors", "0"))
  48. )
  49. def _python_has_cocotb(python_exe: Path) -> bool:
  50. import subprocess
  51. completed = subprocess.run(
  52. [str(python_exe), "-B", "-c", "import cocotb, cocotb_tools"],
  53. cwd=str(ROOT),
  54. env={k: v for k, v in os.environ.items() if k not in _OSS_CAD_POISON},
  55. text=True,
  56. stdout=subprocess.PIPE,
  57. stderr=subprocess.PIPE,
  58. timeout=20,
  59. check=False,
  60. )
  61. return completed.returncode == 0
  62. def _select_python() -> Path:
  63. candidates: list[Path] = []
  64. configured = os.environ.get("PROD2U_P4_COCOTB_PYTHON", "").strip()
  65. if configured:
  66. candidates.append(Path(configured).expanduser())
  67. candidates.append(DEFAULT_VERIFY_PYTHON)
  68. # Prefer configured/verify venv over a possibly poisoned sys.executable.
  69. seen: set[str] = set()
  70. for candidate in candidates:
  71. key = str(candidate)
  72. if key in seen:
  73. continue
  74. seen.add(key)
  75. if candidate.is_file() and _python_has_cocotb(candidate):
  76. return candidate
  77. if Path(sys.executable).is_file() and _python_has_cocotb(Path(sys.executable)):
  78. return Path(sys.executable)
  79. return DEFAULT_VERIFY_PYTHON
  80. def _is_oss_cad_bin(part: str) -> bool:
  81. normalized = part.rstrip("/")
  82. return normalized.endswith("oss-cad-suite/latest/bin") or normalized.endswith(
  83. "oss-cad-suite/bin"
  84. )
  85. def _tool_bin_dirs() -> list[str]:
  86. """Absolute directories for iverilog/vvp so OSS CAD bin is not required on PATH."""
  87. dirs: list[str] = []
  88. for name in ("iverilog", "vvp"):
  89. resolved = shutil.which(name)
  90. if resolved:
  91. parent = str(Path(resolved).parent)
  92. if parent not in dirs and not _is_oss_cad_bin(parent):
  93. dirs.append(parent)
  94. for fallback in ("/usr/bin", "/bin"):
  95. if fallback not in dirs:
  96. dirs.append(fallback)
  97. return dirs
  98. def _sanitize_env(python_exe: Path, build_dir: Path) -> dict[str, str]:
  99. """Bind VPI to verification Python and hide OSS CAD python shims.
  100. OSS CAD ``bin`` must stay off PATH: even without PYTHONEXECUTABLE, having
  101. ``tabbypy3`` visible makes the VPI-embedded interpreter report
  102. sys.executable as tabbypy3 (cocotb gpi_embed sanity check fails).
  103. """
  104. env = {k: v for k, v in os.environ.items() if k not in _OSS_CAD_POISON}
  105. python_bin = str(python_exe.parent)
  106. shim_dir = build_dir / "path-shim"
  107. shim_dir.mkdir(parents=True, exist_ok=True)
  108. for shim_name in ("python", "python3", "python3.13", "tabbypy3", "tabby"):
  109. shim_path = shim_dir / shim_name
  110. if shim_path.exists() or shim_path.is_symlink():
  111. shim_path.unlink()
  112. shim_path.symlink_to(python_exe)
  113. path_parts: list[str] = [python_bin, str(shim_dir), *_tool_bin_dirs()]
  114. for part in env.get("PATH", "").split(os.pathsep):
  115. if not part or _is_oss_cad_bin(part):
  116. continue
  117. if part not in path_parts:
  118. path_parts.append(part)
  119. env["PATH"] = os.pathsep.join(path_parts)
  120. env["VIRTUAL_ENV"] = str(python_exe.parent.parent)
  121. env["PYGPI_PYTHON_BIN"] = str(python_exe)
  122. env["PROD2U_P4_COCOTB_PYTHON"] = str(python_exe)
  123. # Keep TEMP under the lane build root; cocotb_tools uses build_dir directly.
  124. env["TEMP"] = str(build_dir)
  125. env["TMP"] = str(build_dir)
  126. env["TMPDIR"] = str(build_dir)
  127. for key in _OSS_CAD_POISON:
  128. env.pop(key, None)
  129. # find_libpython may be unavailable while PYTHONEXECUTABLE still poisons this
  130. # process; LIBPYTHON_LOC is filled after re-exec in main().
  131. return env
  132. def _ensure_running_under(python_exe: Path, build_dir: Path) -> None:
  133. """Re-exec under the selected interpreter with a sanitized environment.
  134. PYTHONEXECUTABLE poisons sys.executable for the whole process lifetime; the
  135. only fix is a clean execve before cocotb_tools/VPI start.
  136. """
  137. need_reexec = False
  138. if "tabbypy3" in Path(sys.executable).name:
  139. need_reexec = True
  140. if os.environ.get("PYTHONEXECUTABLE"):
  141. need_reexec = True
  142. current = Path(sys.executable).expanduser()
  143. if str(current) != str(python_exe) and not (
  144. current.parent == python_exe.parent and current.name.startswith("python")
  145. ):
  146. need_reexec = True
  147. if not need_reexec:
  148. return
  149. os.execve(
  150. str(python_exe),
  151. [str(python_exe), "-B", str(Path(__file__).resolve()), *sys.argv[1:]],
  152. _sanitize_env(python_exe, build_dir),
  153. )
  154. def main() -> int:
  155. build_dir = _resolve_build_dir()
  156. build_dir.mkdir(parents=True, exist_ok=True)
  157. results_xml = build_dir / "results.xml"
  158. python_exe = _select_python()
  159. # Re-exec first when poisoned so subsequent imports see a healthy venv.
  160. _ensure_running_under(python_exe, build_dir)
  161. sanitized = _sanitize_env(python_exe, build_dir)
  162. try:
  163. import find_libpython
  164. libpython = find_libpython.find_libpython()
  165. if libpython:
  166. sanitized["LIBPYTHON_LOC"] = libpython
  167. except Exception:
  168. pass
  169. os.environ.clear()
  170. os.environ.update(sanitized)
  171. # Guard: refuse to proceed if poison remains.
  172. if os.environ.get("PYTHONEXECUTABLE"):
  173. print(
  174. "error: PYTHONEXECUTABLE is set; refusing to run VPI under OSS CAD poison: "
  175. f"{os.environ['PYTHONEXECUTABLE']}",
  176. file=sys.stderr,
  177. )
  178. return 2
  179. if "tabbypy3" in Path(sys.executable).name:
  180. print(f"error: sys.executable is OSS CAD tabbypy3: {sys.executable}", file=sys.stderr)
  181. return 2
  182. if any(_is_oss_cad_bin(part) for part in os.environ.get("PATH", "").split(os.pathsep)):
  183. print("error: OSS CAD bin still on PATH after sanitize", file=sys.stderr)
  184. return 2
  185. from cocotb_tools.runner import get_runner
  186. runner = get_runner("icarus")
  187. _orig_set_env = runner._set_env
  188. def _set_env_without_oss_cad_poison() -> None:
  189. _orig_set_env()
  190. for key in _OSS_CAD_POISON:
  191. runner.env.pop(key, None)
  192. # Re-assert PATH without OSS CAD (cocotb may append libs_dir only).
  193. path_parts = [
  194. part
  195. for part in runner.env.get("PATH", "").split(os.pathsep)
  196. if part and not _is_oss_cad_bin(part)
  197. ]
  198. runner.env["PATH"] = os.pathsep.join(path_parts)
  199. runner.env["PYGPI_PYTHON_BIN"] = str(python_exe)
  200. audit = build_dir / "vpi-env-audit.txt"
  201. audit.write_text(
  202. "\n".join(
  203. [
  204. f"os.PYTHONEXECUTABLE={os.environ.get('PYTHONEXECUTABLE')!r}",
  205. f"runner.PYTHONEXECUTABLE={runner.env.get('PYTHONEXECUTABLE')!r}",
  206. f"runner.PYGPI_PYTHON_BIN={runner.env.get('PYGPI_PYTHON_BIN')!r}",
  207. f"sys.executable={sys.executable!r}",
  208. f"PATH_has_oss_cad={any(_is_oss_cad_bin(p) for p in runner.env.get('PATH', '').split(os.pathsep))}",
  209. ]
  210. )
  211. + "\n",
  212. encoding="utf-8",
  213. )
  214. if "tabbypy3" in runner.env.get("PYGPI_PYTHON_BIN", ""):
  215. raise RuntimeError("PYGPI_PYTHON_BIN resolved to OSS CAD tabbypy3")
  216. if runner.env.get("PYTHONEXECUTABLE"):
  217. raise RuntimeError(
  218. "PYTHONEXECUTABLE still present in runner.env after sanitize: "
  219. f"{runner.env['PYTHONEXECUTABLE']}"
  220. )
  221. runner._set_env = _set_env_without_oss_cad_poison # type: ignore[method-assign]
  222. runner.build(
  223. sources=[*rtl_sources(), TEST_DIR / "prod2u_door_temp_uart_top.v"],
  224. hdl_toplevel="prod2u_door_temp_uart_top",
  225. build_dir=build_dir,
  226. build_args=["-I", str(ROOT)],
  227. always=True,
  228. verbose=False,
  229. )
  230. results = Path(
  231. runner.test(
  232. hdl_toplevel="prod2u_door_temp_uart_top",
  233. test_module="test_prod2u_door_temp_uart_e2e",
  234. build_dir=build_dir,
  235. test_dir=TEST_DIR,
  236. results_xml=str(results_xml),
  237. extra_env={
  238. "PYGPI_PYTHON_BIN": str(python_exe),
  239. "PATH": os.environ["PATH"],
  240. "VIRTUAL_ENV": os.environ.get("VIRTUAL_ENV", ""),
  241. },
  242. )
  243. )
  244. if not results.is_file() or results_xml_has_failures(results):
  245. print(f"cocotb fail results={results}", file=sys.stderr)
  246. return 1
  247. print(f"cocotb pass results={results} python={python_exe}")
  248. return 0
  249. if __name__ == "__main__":
  250. raise SystemExit(main())