ソースを参照

fix(verify): LD-safe cocotb python selection and Icarus shims

Prefer PRODU2_VERIFY_PYTHON over bare libexec, stop re-exec loops, and expose iverilog/vvp via absolute exec wrappers so UART E2E runs without oss-cad-suite/bin on PATH.

Co-authored-by: Cursor <cursoragent@cursor.com>
root 3 ヶ月 前
親
コミット
d92a575788

+ 88 - 19
tests/cocotb/run_prod2u_door_temp_uart_e2e.py

@@ -19,12 +19,21 @@ ROOT = Path(__file__).resolve().parents[2]
 TEST_DIR = Path(__file__).resolve().parent
 TEST_DIR = Path(__file__).resolve().parent
 sys.path.insert(0, str(ROOT))
 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()
+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.
 # Poisonous env vars exported by OSS CAD tabbypy3 / environment scripts.
 _OSS_CAD_POISON = (
 _OSS_CAD_POISON = (
@@ -107,9 +116,41 @@ def _is_oss_cad_bin(part: str) -> bool:
     )
     )
 
 
 
 
-def _tool_bin_dirs() -> list[str]:
-    """Absolute directories for iverilog/vvp so OSS CAD bin is not required on PATH."""
+def _tool_bin_dirs(shim_dir: 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] = []
     dirs: list[str] = []
+    if shim_dir is not None:
+        shim_dir.mkdir(parents=True, exist_ok=True)
+        for name in ("iverilog", "vvp"):
+            resolved = shutil.which(name)
+            if not resolved:
+                for candidate in (
+                    Path("/data/prod2u/oss-cad-suite/latest/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
+            # OSS CAD iverilog/vvp are shell wrappers using $0-relative paths;
+            # symlinks break them. Emit absolute exec wrappers instead.
+            wrapper = shim_dir / name
+            if wrapper.exists() or wrapper.is_symlink():
+                wrapper.unlink()
+            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"):
     for name in ("iverilog", "vvp"):
         resolved = shutil.which(name)
         resolved = shutil.which(name)
         if resolved:
         if resolved:
@@ -139,7 +180,7 @@ def _sanitize_env(python_exe: Path, build_dir: Path) -> dict[str, str]:
             shim_path.unlink()
             shim_path.unlink()
         shim_path.symlink_to(python_exe)
         shim_path.symlink_to(python_exe)
 
 
-    path_parts: list[str] = [python_bin, str(shim_dir), *_tool_bin_dirs()]
+    path_parts: list[str] = [python_bin, str(shim_dir), *_tool_bin_dirs(shim_dir)]
     for part in env.get("PATH", "").split(os.pathsep):
     for part in env.get("PATH", "").split(os.pathsep):
         if not part or _is_oss_cad_bin(part):
         if not part or _is_oss_cad_bin(part):
             continue
             continue
@@ -160,6 +201,33 @@ def _sanitize_env(python_exe: Path, build_dir: Path) -> dict[str, str]:
     return env
     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:
 def _ensure_running_under(python_exe: Path, build_dir: Path) -> None:
     """Re-exec under the selected interpreter with a sanitized environment.
     """Re-exec under the selected interpreter with a sanitized environment.
 
 
@@ -171,17 +239,16 @@ def _ensure_running_under(python_exe: Path, build_dir: Path) -> None:
         need_reexec = True
         need_reexec = True
     if os.environ.get("PYTHONEXECUTABLE"):
     if os.environ.get("PYTHONEXECUTABLE"):
         need_reexec = True
         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")
-    ):
+    if not _already_under_selected_python(python_exe):
         need_reexec = True
         need_reexec = True
     if not need_reexec:
     if not need_reexec:
         return
         return
+    env = _sanitize_env(python_exe, build_dir)
+    env["PROD2U_COCOTB_REEXEC_DONE"] = "1"
     os.execve(
     os.execve(
         str(python_exe),
         str(python_exe),
         [str(python_exe), "-B", str(Path(__file__).resolve()), *sys.argv[1:]],
         [str(python_exe), "-B", str(Path(__file__).resolve()), *sys.argv[1:]],
-        _sanitize_env(python_exe, build_dir),
+        env,
     )
     )
 
 
 
 
@@ -225,20 +292,22 @@ def main() -> int:
 
 
     runner = get_runner("icarus")
     runner = get_runner("icarus")
 
 
-    _orig_set_env = runner._set_env
+    _orig_set_env_common = runner._set_env_common
 
 
-    def _set_env_without_oss_cad_poison() -> None:
-        _orig_set_env()
+    def _set_env_common_without_oss_cad_poison() -> None:
+        _orig_set_env_common()
         for key in _OSS_CAD_POISON:
         for key in _OSS_CAD_POISON:
             runner.env.pop(key, None)
             runner.env.pop(key, None)
-        # Re-assert PATH without OSS CAD (cocotb may append libs_dir only).
+        # Re-assert PATH without OSS CAD python shims (cocotb may append libs_dir only).
         path_parts = [
         path_parts = [
             part
             part
             for part in runner.env.get("PATH", "").split(os.pathsep)
             for part in runner.env.get("PATH", "").split(os.pathsep)
             if part and not _is_oss_cad_bin(part)
             if part and not _is_oss_cad_bin(part)
         ]
         ]
         runner.env["PATH"] = os.pathsep.join(path_parts)
         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["PYGPI_PYTHON_BIN"] = str(python_exe)
+        runner.env.pop("PYTHONEXECUTABLE", None)
         audit = build_dir / "vpi-env-audit.txt"
         audit = build_dir / "vpi-env-audit.txt"
         audit.write_text(
         audit.write_text(
             "\n".join(
             "\n".join(
@@ -261,7 +330,7 @@ def main() -> int:
                 f"{runner.env['PYTHONEXECUTABLE']}"
                 f"{runner.env['PYTHONEXECUTABLE']}"
             )
             )
 
 
-    runner._set_env = _set_env_without_oss_cad_poison  # type: ignore[method-assign]
+    runner._set_env_common = _set_env_common_without_oss_cad_poison  # type: ignore[method-assign]
 
 
     runner.build(
     runner.build(
         sources=[*rtl_sources(), TEST_DIR / "prod2u_door_temp_uart_top.v"],
         sources=[*rtl_sources(), TEST_DIR / "prod2u_door_temp_uart_top.v"],

+ 50 - 16
tools/prod2u_p4_harness.py

@@ -34,6 +34,7 @@ from prod2u_p4_normal_v3_build import (  # noqa: E402
     build_synthesis_input_manifest,
     build_synthesis_input_manifest,
 )
 )
 from generate_project import load_project, render_adc  # noqa: E402
 from generate_project import load_project, render_adc  # noqa: E402
+from tool_env import ensure_safe_sys_executable, safe_python  # noqa: E402
 
 
 # Linux-first: resolve TD from PATH / env. Windows absolute path kept only as last-resort legacy hint.
 # Linux-first: resolve TD from PATH / env. Windows absolute path kept only as last-resort legacy hint.
 _TD_HOME = Path(os.environ.get("ANLOGIC_TD_HOME", "/data/anlogic/TD_Release_2026.1_SP2_NL"))
 _TD_HOME = Path(os.environ.get("ANLOGIC_TD_HOME", "/data/anlogic/TD_Release_2026.1_SP2_NL"))
@@ -62,12 +63,20 @@ DEFAULT_TOOLCHAIN_ROOT = Path(
         str(_default_prod2u_toolchain_base() / "oss-cad-suite" / "latest"),
         str(_default_prod2u_toolchain_base() / "oss-cad-suite" / "latest"),
     )
     )
 )
 )
-DEFAULT_VENV_ROOT = Path(
-    os.environ.get(
-        "PRODU2_VERIFY_VENV_ROOT",
-        str(Path.home() / ".cache" / "prod2u" / "venvs"),
-    )
-)
+def _default_verify_venv_root() -> Path:
+    override = os.environ.get("PRODU2_VERIFY_VENV_ROOT", "").strip()
+    if override:
+        return Path(override)
+    verify_venv = os.environ.get("PRODU2_VERIFY_VENV", "").strip()
+    if verify_venv:
+        return Path(verify_venv).expanduser().resolve().parent
+    persistent = Path("/data/prod2u/venvs")
+    if persistent.is_dir():
+        return persistent
+    return Path.home() / ".cache" / "prod2u" / "venvs"
+
+
+DEFAULT_VENV_ROOT = _default_verify_venv_root()
 PROFILE = "prod2u_p4_normal_v3"
 PROFILE = "prod2u_p4_normal_v3"
 RUNTIME_PROFILE = "prod2u-door-temp-115200-v1"
 RUNTIME_PROFILE = "prod2u-door-temp-115200-v1"
 TOP_MODULE = "prod2u_p4_normal_v3_top"
 TOP_MODULE = "prod2u_p4_normal_v3_top"
@@ -1559,15 +1568,31 @@ def _run_cocotb(
             if shim_path.exists() or shim_path.is_symlink():
             if shim_path.exists() or shim_path.is_symlink():
                 shim_path.unlink()
                 shim_path.unlink()
             shim_path.symlink_to(Path(python_exe).expanduser())
             shim_path.symlink_to(Path(python_exe).expanduser())
-        path_parts: list[str] = [python_bin, str(shim_dir)]
+        # Expose iverilog/vvp via private shims — never put oss-cad-suite/bin on PATH
+        # (that resurrects tabbypy3 as the VPI sys.executable).
         for name in ("iverilog", "vvp"):
         for name in ("iverilog", "vvp"):
             resolved = resolve_tool(name)
             resolved = resolve_tool(name)
+            if not resolved:
+                for fallback in (
+                    Path("/usr/local/bin") / name,
+                    Path("/usr/bin") / name,
+                    Path("/data/prod2u/oss-cad-suite/latest/bin") / name,
+                ):
+                    if fallback.is_file() and os.access(fallback, os.X_OK):
+                        resolved = str(fallback)
+                        break
             if resolved:
             if resolved:
-                parent = str(Path(resolved).parent)
-                if parent not in path_parts and "oss-cad-suite" not in parent:
-                    path_parts.append(parent)
-            # Prefer /usr/local wrappers so VPI spawn keeps iverilog without OSS CAD bin
-            # (OSS CAD bin would resurrect tabbypy3 as sys.executable).
+                wrapper = shim_dir / name
+                if wrapper.exists() or wrapper.is_symlink():
+                    wrapper.unlink()
+                wrapper.write_text(
+                    "#!/bin/sh\n"
+                    f'exec "{resolved}" "$@"\n',
+                    encoding="ascii",
+                )
+                wrapper.chmod(0o755)
+        path_parts: list[str] = [python_bin, str(shim_dir)]
+        for name in ("iverilog", "vvp"):
             for fallback in (Path("/usr/local/bin") / name, Path("/usr/bin") / name):
             for fallback in (Path("/usr/local/bin") / name, Path("/usr/bin") / name):
                 if fallback.is_file() and os.access(fallback, os.X_OK):
                 if fallback.is_file() and os.access(fallback, os.X_OK):
                     parent = str(fallback.parent)
                     parent = str(fallback.parent)
@@ -1650,9 +1675,17 @@ def python_has_cocotb(python_exe: str | Path, work_root: Path) -> bool:
 
 
 def cocotb_python(work_root: Path) -> str:
 def cocotb_python(work_root: Path) -> str:
     candidates: list[Path] = []
     candidates: list[Path] = []
-    configured = os.environ.get("PROD2U_P4_COCOTB_PYTHON", "").strip()
-    if configured:
-        candidates.append(Path(configured))
+    for key in ("PROD2U_P4_COCOTB_PYTHON", "PRODU2_VERIFY_PYTHON"):
+        configured = os.environ.get(key, "").strip()
+        if configured:
+            candidates.append(Path(configured))
+    # Prefer LD-safe wrapper over bare libexec sys.executable (see tools/tool_env.py).
+    candidates.append(Path(safe_python()))
+    verify_venv = os.environ.get("PRODU2_VERIFY_VENV", "").strip()
+    if verify_venv:
+        for name in ("python", "python3"):
+            candidates.append(Path(verify_venv).expanduser() / "bin" / name)
+    candidates.append(Path("/data/prod2u/venvs/verify/bin/python"))
     candidates.append(Path(sys.executable))
     candidates.append(Path(sys.executable))
     if DEFAULT_VENV_ROOT.is_dir():
     if DEFAULT_VENV_ROOT.is_dir():
         candidates.extend(sorted(DEFAULT_VENV_ROOT.glob("*/Scripts/python.exe")))
         candidates.extend(sorted(DEFAULT_VENV_ROOT.glob("*/Scripts/python.exe")))
@@ -1669,7 +1702,7 @@ def cocotb_python(work_root: Path) -> str:
         seen.add(key)
         seen.add(key)
         if expanded.is_file() and python_has_cocotb(expanded, work_root):
         if expanded.is_file() and python_has_cocotb(expanded, work_root):
             return str(expanded)
             return str(expanded)
-    return str(Path(sys.executable).expanduser())
+    return safe_python()
 
 
 
 
 def hdl_target_manifest_evidence(backend: str) -> dict[str, Any]:
 def hdl_target_manifest_evidence(backend: str) -> dict[str, Any]:
@@ -4631,6 +4664,7 @@ def build_parser() -> argparse.ArgumentParser:
 
 
 def main(argv: Sequence[str] | None = None) -> int:
 def main(argv: Sequence[str] | None = None) -> int:
     args = build_parser().parse_args(argv)
     args = build_parser().parse_args(argv)
+    ensure_safe_sys_executable()
     return int(args.func(args))
     return int(args.func(args))
 
 
 
 

+ 5 - 0
tools/run_verification_matrix.py

@@ -279,6 +279,11 @@ def _run_harness_lane(
     work_root.mkdir(parents=True, exist_ok=True)
     work_root.mkdir(parents=True, exist_ok=True)
     log_root.mkdir(parents=True, exist_ok=True)
     log_root.mkdir(parents=True, exist_ok=True)
     isolation = lane_isolation_env(work_root, task=lane)
     isolation = lane_isolation_env(work_root, task=lane)
+    isolation["PRODU2_VERIFY_PYTHON"] = _safe_python()
+    isolation.setdefault(
+        "PRODU2_VERIFY_VENV",
+        os.environ.get("PRODU2_VERIFY_VENV", "/data/prod2u/venvs/verify"),
+    )
     cmd = [
     cmd = [
         _safe_python(),
         _safe_python(),
         "-B",
         "-B",