#!/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)) def _default_verify_python() -> Path: for key in ("PROD2U_P4_COCOTB_PYTHON", "PRODU2_VERIFY_PYTHON"): value = os.environ.get(key, "").strip() if value: return Path(value).expanduser() for candidate in ( Path("/data/prod2u/venvs/verify/bin/python"), Path.home() / ".cache" / "prod2u" / "venvs" / "verify" / "bin" / "python", ): if candidate.is_file(): return candidate return Path("/data/prod2u/venvs/verify/bin/python") DEFAULT_VERIFY_PYTHON = _default_verify_python() # 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) # The persistent OSS Python wrapper carries the matching shared library # and bundled cocotb. Prefer its non-tabbypy3 entrypoint before falling # back to a poisoned sys.executable reported by the vendor wrapper. candidates.append(Path("/data/prod2u/oss-cad-suite/latest/py3bin/python3.11")) # 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(shim_dir: Path | None = None, python_exe: Path | None = None) -> list[str]: """Dirs with iverilog/vvp without exposing OSS CAD python shims on PATH. Host often only has Icarus inside oss-cad-suite/bin. Putting that whole bin on PATH resurrects tabbypy3 for VPI; instead symlink iverilog/vvp into a private shim dir when no system install exists. """ dirs: list[str] = [] if shim_dir is not None: shim_dir.mkdir(parents=True, exist_ok=True) oss_top = Path("/data/prod2u/oss-cad-suite/latest") for name in ("iverilog", "vvp"): resolved = shutil.which(name) # A controlled Python re-exec preserves this run's shim directory # on PATH. Never regenerate a shim that execs itself. if resolved and Path(resolved).parent.resolve() == shim_dir.resolve(): resolved = None if not resolved: for candidate in ( oss_top / "bin" / name, Path("/usr/local/bin") / name, Path("/usr/bin") / name, ): if candidate.is_file() and os.access(candidate, os.X_OK): resolved = str(candidate) break if not resolved: continue wrapper = shim_dir / name if wrapper.exists() or wrapper.is_symlink(): wrapper.unlink() resolved_path = Path(resolved) libexec = oss_top / "libexec" / name if ( name == "vvp" and python_exe is not None and libexec.is_file() and "oss-cad-suite" in resolved_path.as_posix() ): # OSS bin/vvp exports PYTHONEXECUTABLE=tabbypy3; bypass that wrapper. py = python_exe.expanduser() wrapper.write_text( "#!/bin/sh\n" f'export PYGPI_PYTHON_BIN="{py}"\n' f'export PYTHONEXECUTABLE="{py}"\n' f'export PRODU2_VERIFY_PYTHON="{py}"\n' "unset PYTHONHOME\n" f'exec "{oss_top}/lib/ld-linux-x86-64.so.2" --inhibit-cache --inhibit-rpath "" ' f'--library-path "{oss_top}/lib" "{libexec}" "$@"\n', encoding="ascii", ) else: wrapper.write_text( "#!/bin/sh\n" f'exec "{resolved}" "$@"\n', encoding="ascii", ) wrapper.chmod(0o755) dirs.append(str(shim_dir)) 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/local/bin", "/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(shim_dir, python_exe)] 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 _already_under_selected_python(python_exe: Path) -> bool: """True when this process was launched via the LD-safe wrapper for python_exe. OSS CAD wrappers report sys.executable as bare libexec/python3.11 even when argv0 was venv/bin/python or py3bin/python3.11. Re-execing on that mismatch loops forever. """ if os.environ.get("PROD2U_COCOTB_REEXEC_DONE") == "1": return True current = Path(sys.executable).expanduser() selected = python_exe.expanduser() if str(current) == str(selected): return True if current.parent == selected.parent and current.name.startswith("python"): return True # Same wrapper family: venv/bin/python -> py3bin -> libexec try: if current.resolve() == selected.resolve(): return True except OSError: pass marker = os.environ.get("PROD2U_P4_COCOTB_PYTHON", "").strip() if marker and Path(marker).expanduser() == selected and "libexec" in current.as_posix(): return True return False 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. """ if os.environ.get("PROD2U_COCOTB_REEXEC_DONE") == "1": # OSS CAD's selected wrapper legitimately injects these again while # launching libexec/python. The marker proves the one controlled # re-exec already happened; clear the wrapper residue here instead of # recursively execing the same wrapper forever. for key in _OSS_CAD_POISON: os.environ.pop(key, None) return need_reexec = False if "tabbypy3" in Path(sys.executable).name: need_reexec = True if os.environ.get("PYTHONEXECUTABLE"): need_reexec = True if not _already_under_selected_python(python_exe): need_reexec = True if not need_reexec: return env = _sanitize_env(python_exe, build_dir) env["PROD2U_COCOTB_REEXEC_DONE"] = "1" os.execve( str(python_exe), [str(python_exe), "-B", str(Path(__file__).resolve()), *sys.argv[1:]], env, ) 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 and os.environ.get("PROD2U_COCOTB_REEXEC_DONE") != "1" ): 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") # cocotb_tools hard-codes -g2012 before user build_args. Replace that # single dialect selection so the command exactly matches the passing # Legacy Icarus lane instead of passing two conflicting -g options. _orig_build_command = runner._build_command def _build_command_g2005_sv(): commands = _orig_build_command() return [ ["-g2005-sv" if arg == "-g2012" else arg for arg in command] for command in commands ] runner._build_command = _build_command_g2005_sv # type: ignore[method-assign] _orig_set_env_common = runner._set_env_common def _set_env_common_without_oss_cad_poison() -> None: _orig_set_env_common() for key in _OSS_CAD_POISON: runner.env.pop(key, None) # Re-assert PATH without OSS CAD python shims (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) # Prefer LD-safe wrapper; bare libexec sys.executable breaks VPI children. runner.env["PYGPI_PYTHON_BIN"] = str(python_exe) runner.env.pop("PYTHONEXECUTABLE", None) 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_common = _set_env_common_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())