| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430 |
- """Tests for user-mode OSS CAD Suite bootstrap safety guards."""
- from __future__ import annotations
- import contextlib
- import io
- import shutil
- import subprocess
- import sys
- import tempfile
- import unittest
- import zipfile
- from pathlib import Path
- from unittest import mock
- sys.dont_write_bytecode = True
- ROOT = Path(__file__).resolve().parents[2]
- sys.path.insert(0, str(ROOT / "tools"))
- import bootstrap_oss_cad_suite as bootstrap # noqa: E402
- POWERSHELL = shutil.which("powershell.exe")
- def ps_literal(path: Path) -> str:
- return "'" + str(path).replace("'", "''") + "'"
- def run_powershell(command: str) -> subprocess.CompletedProcess[str]:
- if POWERSHELL is None:
- raise unittest.SkipTest("Windows PowerShell is unavailable")
- return subprocess.run(
- [POWERSHELL, "-NoProfile", "-NonInteractive", "-Command", command],
- cwd=ROOT,
- text=True,
- capture_output=True,
- check=False,
- timeout=60,
- )
- class BootstrapOssCadSuiteTests(unittest.TestCase):
- def test_default_paths_use_path_home_not_administration_literal(self) -> None:
- for path in [bootstrap.DEFAULT_ROOT, bootstrap.DEFAULT_DOWNLOAD_DIR, bootstrap.DEFAULT_COCOTB_VENV]:
- self.assertIn(str(Path.home()), str(path))
- self.assertNotIn(r"C:\Users\Administration", str(path))
- self.assertEqual(
- bootstrap.DEFAULT_COCOTB_VENV.name,
- "prod2u-p4-actuator-trace-cocotb-venv",
- )
- def test_tool_status_does_not_accept_extensionless_verilator_launcher(self) -> None:
- with tempfile.TemporaryDirectory() as temporary:
- root = Path(temporary)
- bin_dir = root / "bin"
- bin_dir.mkdir()
- (bin_dir / "verilator").write_text("extensionless launcher", encoding="ascii")
- status = bootstrap.tool_status(root)
- self.assertEqual(status["tools"]["verilator"]["status"], "missing")
- self.assertIsNone(status["tools"]["verilator"]["path"])
- def test_print_env_binds_native_verilator_before_exposing_toolchain_path(self) -> None:
- with tempfile.TemporaryDirectory() as temporary:
- root = Path(temporary)
- bin_dir = root / "bin"
- lib_dir = root / "lib"
- bin_dir.mkdir()
- lib_dir.mkdir()
- verilator_root = root / "share" / "verilator"
- verilator_root.mkdir(parents=True)
- native = bin_dir / "verilator_bin.exe"
- native.write_bytes(b"MZnative")
- smtbmc = bin_dir / "yosys-smtbmc.exe.exe"
- smtbmc.write_bytes(b"MZsmtbmc")
- (bin_dir / "verilator").write_text(
- "extensionless launcher",
- encoding="ascii",
- )
- stdout = io.StringIO()
- with contextlib.redirect_stdout(stdout):
- result = bootstrap.main(
- ["--install-root", str(root), "--print-env"]
- )
- output = stdout.getvalue()
- output_lines = output.splitlines()
- self.assertEqual(result, 0)
- self.assertEqual(len(output_lines), 1)
- self.assertIn(str(bootstrap.ACTIVATION_SCRIPT), output_lines[0])
- self.assertIn(str(root.resolve()), output_lines[0])
- def test_print_env_runs_native_verilator_with_complete_runtime_environment(self) -> None:
- with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
- root = Path(temporary) / "suite"
- native = root / "bin" / "verilator_bin.exe"
- native.parent.mkdir(parents=True)
- (root / "lib").mkdir()
- verilator_root = root / "share" / "verilator"
- verilator_root.mkdir(parents=True)
- native.write_bytes(b"MZplaceholder")
- (root / "bin" / "yosys-smtbmc.exe.exe").write_bytes(b"MZsmtbmc")
- stdout = io.StringIO()
- with contextlib.redirect_stdout(stdout):
- bootstrap.main(["--install-root", str(root), "--print-env"])
- env_commands = stdout.getvalue().rstrip()
- native.unlink()
- required_lib = str(root / "lib").replace('"', '""')
- required_verilator_root = str(verilator_root).replace('"', '""')
- command = f"""
- $ErrorActionPreference = "Stop"
- $source = @'
- using System;
- using System.IO;
- public static class FakeVerilator {{
- public static int Main(string[] args) {{
- string required = Path.GetFullPath(@"{required_lib}").TrimEnd('\\\\');
- string requiredRoot = Path.GetFullPath(@"{required_verilator_root}").TrimEnd('\\\\');
- string path = Environment.GetEnvironmentVariable("PATH") ?? "";
- string configuredRoot = Environment.GetEnvironmentVariable("VERILATOR_ROOT") ?? "";
- if (configuredRoot.Length == 0 ||
- !String.Equals(
- Path.GetFullPath(configuredRoot).TrimEnd('\\\\'),
- requiredRoot,
- StringComparison.OrdinalIgnoreCase)) {{
- Console.Error.WriteLine("VERILATOR_ROOT is missing or incorrect");
- return 87;
- }}
- foreach (string entry in path.Split(';')) {{
- if (entry.Length > 0 && String.Equals(
- Path.GetFullPath(entry).TrimEnd('\\\\'),
- required,
- StringComparison.OrdinalIgnoreCase)) {{
- Console.WriteLine("Fake Verilator 1.0");
- return 0;
- }}
- }}
- Console.Error.WriteLine("runtime library directory is missing from PATH");
- return 86;
- }}
- }}
- '@
- Add-Type -TypeDefinition $source -OutputAssembly {ps_literal(native)} -OutputType ConsoleApplication
- $envCommands = @'
- {env_commands}
- '@
- Invoke-Expression $envCommands
- $resolved = Get-Command verilator -ErrorAction Stop
- Write-Output "resolved=$($resolved.Definition)"
- verilator --version
- $versionExit = $LASTEXITCODE
- Write-Output "version_exit=$versionExit"
- exit $versionExit
- """
- completed = run_powershell(command)
- self.assertEqual(completed.returncode, 0, completed.stdout + completed.stderr)
- self.assertIn(f"resolved={native}", completed.stdout)
- self.assertIn("Fake Verilator 1.0", completed.stdout)
- def test_print_env_child_powershell_never_uses_extensionless_verilator(self) -> None:
- with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
- root = Path(temporary) / "suite"
- native = root / "bin" / "verilator_bin.exe"
- wrapper = root / "bin" / "verilator"
- child_script = Path(temporary) / "child-verilator-check.ps1"
- native.parent.mkdir(parents=True)
- (root / "lib").mkdir()
- (root / "share" / "verilator").mkdir(parents=True)
- native.write_bytes(b"MZplaceholder")
- wrapper.write_text("#!/usr/bin/env perl\n", encoding="ascii")
- (root / "bin" / "yosys-smtbmc.exe.exe").write_bytes(b"MZsmtbmc")
- child_script.write_text(
- """$ErrorActionPreference = "Stop"
- $resolved = Get-Command verilator -ErrorAction Stop
- if ([System.IO.Path]::GetFullPath($resolved.Definition) -eq
- [System.IO.Path]::GetFullPath($env:EXPECTED_UNSAFE_VERILATOR)) {
- Write-Error "child PowerShell resolved the extensionless Verilator wrapper"
- exit 91
- }
- verilator --version
- exit $LASTEXITCODE
- """,
- encoding="utf-8-sig",
- )
- stdout = io.StringIO()
- with contextlib.redirect_stdout(stdout):
- bootstrap.main(["--install-root", str(root), "--print-env"])
- env_commands = stdout.getvalue().rstrip()
- native.unlink()
- command = f"""
- $ErrorActionPreference = "Stop"
- $source = @'
- using System;
- public static class FakeVerilator {{
- public static int Main(string[] args) {{
- Console.WriteLine("Fake Verilator 1.0");
- return 0;
- }}
- }}
- '@
- Add-Type -TypeDefinition $source -OutputAssembly {ps_literal(native)} -OutputType ConsoleApplication
- $envCommands = @'
- {env_commands}
- '@
- Invoke-Expression $envCommands
- $env:EXPECTED_UNSAFE_VERILATOR = {ps_literal(wrapper)}
- & (Join-Path $PSHOME "powershell.exe") -NoProfile -NonInteractive -File {ps_literal(child_script)}
- exit $LASTEXITCODE
- """
- completed = run_powershell(command)
- self.assertEqual(completed.returncode, 0, completed.stdout + completed.stderr)
- self.assertIn("Fake Verilator 1.0", completed.stdout)
- def test_print_env_is_idempotent_when_evaluated_repeatedly(self) -> None:
- with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
- root = Path(temporary) / "suite"
- native = root / "bin" / "verilator_bin.exe"
- native.parent.mkdir(parents=True)
- (root / "lib").mkdir()
- (root / "share" / "verilator").mkdir(parents=True)
- native.write_bytes(b"MZplaceholder")
- (root / "bin" / "yosys-smtbmc.exe.exe").write_bytes(b"MZsmtbmc")
- stdout = io.StringIO()
- with contextlib.redirect_stdout(stdout):
- bootstrap.main(["--install-root", str(root), "--print-env"])
- env_commands = stdout.getvalue().rstrip()
- shim_dir = bootstrap.TOOLCHAIN_SHIM_DIR.resolve()
- command = f"""
- $envCommands = @'
- {env_commands}
- '@
- Invoke-Expression $envCommands
- Invoke-Expression $envCommands
- $shim = [System.IO.Path]::GetFullPath({ps_literal(shim_dir)})
- $count = @(
- $env:PATH -split ";" |
- Where-Object {{ $_ -and [System.IO.Path]::GetFullPath($_) -eq $shim }}
- ).Count
- Write-Output "shim_count=$count"
- """
- completed = run_powershell(command)
- self.assertEqual(completed.returncode, 0, completed.stdout + completed.stderr)
- self.assertIn("shim_count=1", completed.stdout)
- def test_print_env_rejects_extensionless_only_verilator_before_path_output(self) -> None:
- with tempfile.TemporaryDirectory() as temporary:
- root = Path(temporary)
- bin_dir = root / "bin"
- bin_dir.mkdir()
- (bin_dir / "verilator").write_text(
- "extensionless launcher",
- encoding="ascii",
- )
- stdout = io.StringIO()
- with contextlib.redirect_stdout(stdout):
- with self.assertRaisesRegex(SystemExit, "native Verilator"):
- bootstrap.main(
- ["--install-root", str(root), "--print-env"]
- )
- self.assertEqual(stdout.getvalue(), "")
- def test_print_env_rejects_incomplete_native_runtime_before_output(self) -> None:
- for missing in ("lib", "share"):
- with self.subTest(missing=missing), tempfile.TemporaryDirectory() as temporary:
- root = Path(temporary)
- bin_dir = root / "bin"
- bin_dir.mkdir()
- (bin_dir / "verilator_bin.exe").write_bytes(b"MZnative")
- if missing != "lib":
- (root / "lib").mkdir()
- if missing != "share":
- (root / "share" / "verilator").mkdir(parents=True)
- stdout = io.StringIO()
- with contextlib.redirect_stdout(stdout):
- with self.assertRaisesRegex(SystemExit, missing):
- bootstrap.main(
- ["--install-root", str(root), "--print-env"]
- )
- self.assertEqual(stdout.getvalue(), "")
- def test_print_env_rejects_missing_smtbmc_before_output(self) -> None:
- with tempfile.TemporaryDirectory() as temporary:
- root = Path(temporary)
- bin_dir = root / "bin"
- bin_dir.mkdir()
- (bin_dir / "verilator_bin.exe").write_bytes(b"MZnative")
- (root / "lib").mkdir()
- (root / "share" / "verilator").mkdir(parents=True)
- stdout = io.StringIO()
- with contextlib.redirect_stdout(stdout):
- with self.assertRaisesRegex(SystemExit, "SMTBMC"):
- bootstrap.main(
- ["--install-root", str(root), "--print-env"]
- )
- self.assertEqual(stdout.getvalue(), "")
- def test_safe_toolchain_root_rejects_workspace_root(self) -> None:
- with self.assertRaises(ValueError):
- bootstrap._assert_safe_toolchain_root(ROOT)
- def test_zip_extract_rejects_parent_traversal_member(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- base = Path(tmp) / "CodexToolchains" / "CPLD"
- archive = Path(tmp) / "bad.zip"
- with zipfile.ZipFile(archive, "w") as zf:
- zf.writestr("../escape.txt", "bad")
- with mock.patch.object(bootstrap, "DEFAULT_TOOLCHAIN_BASE", base):
- with self.assertRaises(ValueError):
- bootstrap.extract_archive(archive, base / "oss-cad-suite" / "latest")
- def test_extract_archive_refuses_to_replace_unowned_install_root(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- base = Path(tmp) / "CodexToolchains" / "CPLD"
- install_root = base / "oss-cad-suite" / "latest"
- install_root.mkdir(parents=True)
- archive = Path(tmp) / "tool.zip"
- with zipfile.ZipFile(archive, "w") as zf:
- zf.writestr("bin/iverilog.exe", "fake")
- with mock.patch.object(bootstrap, "DEFAULT_TOOLCHAIN_BASE", base):
- with self.assertRaises(RuntimeError):
- bootstrap.extract_archive(archive, install_root)
- def test_install_latest_writes_owner_marker_and_manifest(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- base = Path(tmp) / "CodexToolchains" / "CPLD"
- download_dir = base / "downloads"
- archive = download_dir / "oss-cad-suite-windows-x64-test.exe"
- release = {
- "tag_name": "test",
- "assets": [
- {
- "name": archive.name,
- "browser_download_url": "https://example.invalid/tool.exe",
- "size": 1,
- }
- ],
- }
- def fake_download(_url: str, output: Path) -> None:
- output.parent.mkdir(parents=True, exist_ok=True)
- output.write_text("fake sfx", encoding="utf-8")
- def fake_extract(_archive: Path, install_root: Path) -> None:
- (install_root / "bin").mkdir(parents=True, exist_ok=True)
- for tool in bootstrap.REQUIRED_TOOLS:
- (install_root / "bin" / f"{tool}.exe").write_text("fake", encoding="utf-8")
- with mock.patch.object(bootstrap, "DEFAULT_TOOLCHAIN_BASE", base):
- payload = bootstrap.install_latest_windows_x64(
- install_root=base / "oss-cad-suite" / "latest",
- download_dir=download_dir,
- release_payload=release,
- download_func=fake_download,
- extract_func=fake_extract,
- )
- install_root = Path(payload["install_root"])
- self.assertEqual(payload["status"], "present")
- self.assertTrue((install_root / bootstrap.OWNER_MARKER_NAME).is_file())
- self.assertTrue((install_root / bootstrap.INSTALL_MANIFEST_NAME).is_file())
- def test_install_cocotb_venv_installs_extended_user_mode_packages(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- base = Path(tmp) / "CodexToolchains" / "CPLD"
- source_python = Path(tmp) / "python.exe"
- source_python.write_text("python", encoding="utf-8")
- venv_dir = base / "venvs" / "prod2u-p4-actuator-trace-cocotb-venv"
- venv_python = venv_dir / "Scripts" / "python.exe"
- commands: list[list[str]] = []
- def fake_run_checked(cmd: list[str], **_kwargs):
- commands.append(cmd)
- if cmd[:3] == [str(source_python), "-m", "venv"]:
- venv_python.parent.mkdir(parents=True, exist_ok=True)
- venv_python.write_text("python", encoding="utf-8")
- if cmd[-1].startswith("import cocotb"):
- return mock.Mock(returncode=0, stdout=bootstrap.DEFAULT_COCOTB_VERSION + "\n", stderr="")
- return mock.Mock(returncode=0, stdout="", stderr="")
- with mock.patch.object(bootstrap, "DEFAULT_TOOLCHAIN_BASE", base), \
- mock.patch.object(bootstrap, "run_checked", side_effect=fake_run_checked):
- payload = bootstrap.install_cocotb_venv(venv_dir=venv_dir, python_exe=source_python)
- install_commands = [" ".join(cmd) for cmd in commands if "install" in cmd]
- joined = "\n".join(install_commands)
- self.assertEqual(payload["status"], "present")
- self.assertIn("pytest", joined)
- self.assertIn("hypothesis", joined)
- self.assertIn("pyserial", joined)
- self.assertTrue((venv_dir / bootstrap.OWNER_MARKER_NAME).is_file())
- self.assertTrue((venv_dir / bootstrap.INSTALL_MANIFEST_NAME).is_file())
- def test_uninstall_owned_toolchain_dry_run_does_not_delete_marker_owned_root(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- base = Path(tmp) / "CodexToolchains" / "CPLD"
- install_root = base / "oss-cad-suite" / "latest"
- install_root.mkdir(parents=True)
- bootstrap._write_owner_marker(install_root, "oss_cad_suite", {"test": True})
- payload = bootstrap.uninstall_owned_toolchain(install_root=install_root, cocotb_venv=base / "venv", dry_run=True)
- self.assertEqual(payload["schema"], "offline-toolchain-uninstall-v1")
- self.assertEqual(payload["mode"], "dry_run")
- self.assertEqual(payload["status"], "pass")
- self.assertTrue(install_root.exists())
- self.assertEqual(payload["targets"][0]["action"], "would_delete")
- def test_uninstall_owned_toolchain_refuses_unowned_path(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- base = Path(tmp) / "CodexToolchains" / "CPLD"
- install_root = base / "oss-cad-suite" / "latest"
- install_root.mkdir(parents=True)
- payload = bootstrap.uninstall_owned_toolchain(install_root=install_root, cocotb_venv=base / "venv", dry_run=False)
- self.assertEqual(payload["status"], "blocked_not_owned")
- self.assertTrue(install_root.exists())
- if __name__ == "__main__":
- unittest.main()
|