#!/usr/bin/env python3 """Run the current project's real-UART cocotb scenario. Forces the verification-venv Python into VPI (blocks OSS CAD tabbypy3 / PYTHONEXECUTABLE poisoning) and keeps the Icarus build tree under an independent TEMP/build directory. """ from __future__ import annotations import os from pathlib import Path import shutil import sys import xml.etree.ElementTree as ET ROOT = Path(__file__).resolve().parents[2] TEST_DIR = Path(__file__).resolve().parent sys.path.insert(0, str(ROOT)) DEFAULT_VERIFY_PYTHON = Path( os.environ.get( "PROD2U_P4_COCOTB_PYTHON", "/root/.cache/prod2u/venvs/verify/bin/python", ) ).expanduser() # Poisonous env vars exported by OSS CAD tabbypy3 / environment scripts. _OSS_CAD_POISON = ( "PYTHONEXECUTABLE", "PYTHONHOME", "PYTHONNOUSERSITE", ) def _resolve_build_dir() -> Path: explicit = os.environ.get("PROD2U_COCOTB_BUILD_DIR", "").strip() if explicit: return Path(explicit).expanduser() temp_root = Path(os.environ.get("TEMP", ROOT / "tmp")) return temp_root / "cocotb" / "prod2u_door_temp_uart_e2e" BUILD_DIR = _resolve_build_dir() RESULTS_XML = BUILD_DIR / "results.xml" def rtl_sources() -> list[Path]: from tools.prod2u_p4_normal_v3_build import PRODUCTION_RTL_SOURCES return [ROOT / relative for relative in PRODUCTION_RTL_SOURCES] def results_xml_has_failures(results: Path) -> bool: root = ET.parse(results).getroot() return bool( root.findall(".//failure") or root.findall(".//error") or sum(int(node.attrib.get("failures", "0")) for node in root.findall(".//testsuite")) or sum(int(node.attrib.get("errors", "0")) for node in root.findall(".//testsuite")) or int(root.attrib.get("failures", "0")) or int(root.attrib.get("errors", "0")) ) def _python_has_cocotb(python_exe: Path) -> bool: import subprocess completed = subprocess.run( [str(python_exe), "-B", "-c", "import cocotb, cocotb_tools"], cwd=str(ROOT), env={k: v for k, v in os.environ.items() if k not in _OSS_CAD_POISON}, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=20, check=False, ) return completed.returncode == 0 def _select_python() -> Path: candidates: list[Path] = [] configured = os.environ.get("PROD2U_P4_COCOTB_PYTHON", "").strip() if configured: candidates.append(Path(configured).expanduser()) candidates.append(DEFAULT_VERIFY_PYTHON) # Prefer configured/verify venv over a possibly poisoned sys.executable. seen: set[str] = set() for candidate in candidates: key = str(candidate) if key in seen: continue seen.add(key) if candidate.is_file() and _python_has_cocotb(candidate): return candidate if Path(sys.executable).is_file() and _python_has_cocotb(Path(sys.executable)): return Path(sys.executable) return DEFAULT_VERIFY_PYTHON def _is_oss_cad_bin(part: str) -> bool: normalized = part.rstrip("/") return normalized.endswith("oss-cad-suite/latest/bin") or normalized.endswith( "oss-cad-suite/bin" ) def _tool_bin_dirs() -> list[str]: """Absolute directories for iverilog/vvp so OSS CAD bin is not required on PATH.""" dirs: list[str] = [] for name in ("iverilog", "vvp"): resolved = shutil.which(name) if resolved: parent = str(Path(resolved).parent) if parent not in dirs and not _is_oss_cad_bin(parent): dirs.append(parent) for fallback in ("/usr/bin", "/bin"): if fallback not in dirs: dirs.append(fallback) return dirs def _sanitize_env(python_exe: Path, build_dir: Path) -> dict[str, str]: """Bind VPI to verification Python and hide OSS CAD python shims. OSS CAD ``bin`` must stay off PATH: even without PYTHONEXECUTABLE, having ``tabbypy3`` visible makes the VPI-embedded interpreter report sys.executable as tabbypy3 (cocotb gpi_embed sanity check fails). """ env = {k: v for k, v in os.environ.items() if k not in _OSS_CAD_POISON} python_bin = str(python_exe.parent) shim_dir = build_dir / "path-shim" shim_dir.mkdir(parents=True, exist_ok=True) for shim_name in ("python", "python3", "python3.13", "tabbypy3", "tabby"): shim_path = shim_dir / shim_name if shim_path.exists() or shim_path.is_symlink(): shim_path.unlink() shim_path.symlink_to(python_exe) path_parts: list[str] = [python_bin, str(shim_dir), *_tool_bin_dirs()] for part in env.get("PATH", "").split(os.pathsep): if not part or _is_oss_cad_bin(part): continue if part not in path_parts: path_parts.append(part) env["PATH"] = os.pathsep.join(path_parts) env["VIRTUAL_ENV"] = str(python_exe.parent.parent) env["PYGPI_PYTHON_BIN"] = str(python_exe) env["PROD2U_P4_COCOTB_PYTHON"] = str(python_exe) # Keep TEMP under the lane build root; cocotb_tools uses build_dir directly. env["TEMP"] = str(build_dir) env["TMP"] = str(build_dir) env["TMPDIR"] = str(build_dir) for key in _OSS_CAD_POISON: env.pop(key, None) # find_libpython may be unavailable while PYTHONEXECUTABLE still poisons this # process; LIBPYTHON_LOC is filled after re-exec in main(). return env def _ensure_running_under(python_exe: Path, build_dir: Path) -> None: """Re-exec under the selected interpreter with a sanitized environment. PYTHONEXECUTABLE poisons sys.executable for the whole process lifetime; the only fix is a clean execve before cocotb_tools/VPI start. """ need_reexec = False if "tabbypy3" in Path(sys.executable).name: need_reexec = True if os.environ.get("PYTHONEXECUTABLE"): need_reexec = True current = Path(sys.executable).expanduser() if str(current) != str(python_exe) and not ( current.parent == python_exe.parent and current.name.startswith("python") ): need_reexec = True if not need_reexec: return os.execve( str(python_exe), [str(python_exe), "-B", str(Path(__file__).resolve()), *sys.argv[1:]], _sanitize_env(python_exe, build_dir), ) def main() -> int: build_dir = _resolve_build_dir() build_dir.mkdir(parents=True, exist_ok=True) results_xml = build_dir / "results.xml" python_exe = _select_python() # Re-exec first when poisoned so subsequent imports see a healthy venv. _ensure_running_under(python_exe, build_dir) sanitized = _sanitize_env(python_exe, build_dir) try: import find_libpython libpython = find_libpython.find_libpython() if libpython: sanitized["LIBPYTHON_LOC"] = libpython except Exception: pass os.environ.clear() os.environ.update(sanitized) # Guard: refuse to proceed if poison remains. if os.environ.get("PYTHONEXECUTABLE"): print( "error: PYTHONEXECUTABLE is set; refusing to run VPI under OSS CAD poison: " f"{os.environ['PYTHONEXECUTABLE']}", file=sys.stderr, ) return 2 if "tabbypy3" in Path(sys.executable).name: print(f"error: sys.executable is OSS CAD tabbypy3: {sys.executable}", file=sys.stderr) return 2 if any(_is_oss_cad_bin(part) for part in os.environ.get("PATH", "").split(os.pathsep)): print("error: OSS CAD bin still on PATH after sanitize", file=sys.stderr) return 2 from cocotb_tools.runner import get_runner runner = get_runner("icarus") _orig_set_env = runner._set_env def _set_env_without_oss_cad_poison() -> None: _orig_set_env() for key in _OSS_CAD_POISON: runner.env.pop(key, None) # Re-assert PATH without OSS CAD (cocotb may append libs_dir only). path_parts = [ part for part in runner.env.get("PATH", "").split(os.pathsep) if part and not _is_oss_cad_bin(part) ] runner.env["PATH"] = os.pathsep.join(path_parts) runner.env["PYGPI_PYTHON_BIN"] = str(python_exe) audit = build_dir / "vpi-env-audit.txt" audit.write_text( "\n".join( [ f"os.PYTHONEXECUTABLE={os.environ.get('PYTHONEXECUTABLE')!r}", f"runner.PYTHONEXECUTABLE={runner.env.get('PYTHONEXECUTABLE')!r}", f"runner.PYGPI_PYTHON_BIN={runner.env.get('PYGPI_PYTHON_BIN')!r}", f"sys.executable={sys.executable!r}", f"PATH_has_oss_cad={any(_is_oss_cad_bin(p) for p in runner.env.get('PATH', '').split(os.pathsep))}", ] ) + "\n", encoding="utf-8", ) if "tabbypy3" in runner.env.get("PYGPI_PYTHON_BIN", ""): raise RuntimeError("PYGPI_PYTHON_BIN resolved to OSS CAD tabbypy3") if runner.env.get("PYTHONEXECUTABLE"): raise RuntimeError( "PYTHONEXECUTABLE still present in runner.env after sanitize: " f"{runner.env['PYTHONEXECUTABLE']}" ) runner._set_env = _set_env_without_oss_cad_poison # type: ignore[method-assign] runner.build( sources=[*rtl_sources(), TEST_DIR / "prod2u_door_temp_uart_top.v"], hdl_toplevel="prod2u_door_temp_uart_top", build_dir=build_dir, build_args=["-I", str(ROOT)], always=True, verbose=False, ) results = Path( runner.test( hdl_toplevel="prod2u_door_temp_uart_top", test_module="test_prod2u_door_temp_uart_e2e", build_dir=build_dir, test_dir=TEST_DIR, results_xml=str(results_xml), extra_env={ "PYGPI_PYTHON_BIN": str(python_exe), "PATH": os.environ["PATH"], "VIRTUAL_ENV": os.environ.get("VIRTUAL_ENV", ""), }, ) ) if not results.is_file() or results_xml_has_failures(results): print(f"cocotb fail results={results}", file=sys.stderr) return 1 print(f"cocotb pass results={results} python={python_exe}") return 0 if __name__ == "__main__": raise SystemExit(main())