Coverage for cuda/pathfinder/_static_libs/find_static_lib.py: 98.90%
91 statements
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-03 01:06 +0000
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-03 01:06 +0000
1# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2# SPDX-License-Identifier: Apache-2.0
4import functools
5import os
6from dataclasses import dataclass
7from pathlib import Path
8from typing import NoReturn, TypedDict
10from cuda.pathfinder._utils.env_vars import get_cuda_path_or_home
11from cuda.pathfinder._utils.find_sub_dirs import find_sub_dirs_all_sitepackages
12from cuda.pathfinder._utils.platform_aware import IS_WINDOWS
13from cuda.pathfinder._utils.windows_arch import windows_python_arch
15from .._utils.resolve_path import resolve_path
18class StaticLibNotFoundError(RuntimeError):
19 """Raised when a static library cannot be found."""
22@dataclass(frozen=True)
23class LocatedStaticLib:
24 """Information about a located static library."""
26 name: str
27 abs_path: str
28 filename: str
29 found_via: str
32class _StaticLibInfo(TypedDict):
33 """Static-library metadata with ordered alternatives searched first-to-last."""
35 filename: str
36 ctk_rel_paths: tuple[str, ...]
37 conda_rel_paths: tuple[str, ...]
38 site_packages_dirs: tuple[str, ...]
41def _cudadevrt_info() -> _StaticLibInfo:
42 if not IS_WINDOWS: 1clm
43 return {
44 "filename": "libcudadevrt.a",
45 "ctk_rel_paths": ("lib64", "lib"),
46 "conda_rel_paths": ("lib",),
47 "site_packages_dirs": ("nvidia/cu13/lib", "nvidia/cuda_runtime/lib"),
48 }
50 arch_dir = windows_python_arch() 1clm
51 component_wheel_dirs = ("nvidia/cuda_runtime/lib/x64",) if arch_dir == "x64" else () 1clm
52 conda_fallback_dirs = ("lib",) if arch_dir == "x64" else () 1clm
53 return { 1clm
54 "filename": "cudadevrt.lib",
55 "ctk_rel_paths": (str(Path("lib", arch_dir)),),
56 "conda_rel_paths": (str(Path("lib", arch_dir)), *conda_fallback_dirs),
57 "site_packages_dirs": (f"nvidia/cu13/lib/{arch_dir}", *component_wheel_dirs),
58 }
61_SUPPORTED_STATIC_LIBS_INFO: dict[str, _StaticLibInfo] = {
62 "cudadevrt": _cudadevrt_info(),
63}
65SUPPORTED_STATIC_LIBS: tuple[str, ...] = tuple(sorted(_SUPPORTED_STATIC_LIBS_INFO.keys()))
68def _no_such_file_in_dir(directory: Path, filename: str, error_messages: list[str], attachments: list[str]) -> None:
69 error_messages.append(f"No such file: {directory / filename}") 1a
70 if directory.is_dir(): 1a
71 attachments.append(f' listdir("{directory}"):') 1a
72 for node in sorted(node_path.name for node_path in directory.iterdir()): 1a
73 attachments.append(f" {node}") 1a
74 else:
75 attachments.append(f' Directory does not exist: "{directory}"')
78class _FindStaticLib:
79 def __init__(self, name: str) -> None:
80 if name not in _SUPPORTED_STATIC_LIBS_INFO: 1nadejfghikb
81 raise ValueError(f"Unknown static library: '{name}'. Supported: {', '.join(SUPPORTED_STATIC_LIBS)}") 1n
82 self.name: str = name 1adejfghikb
83 self.config: _StaticLibInfo = _SUPPORTED_STATIC_LIBS_INFO[name] 1adejfghikb
84 self.filename: str = self.config["filename"] 1adejfghikb
85 self.ctk_rel_paths: tuple[str, ...] = self.config["ctk_rel_paths"] 1adejfghikb
86 self.conda_rel_paths: tuple[str, ...] = self.config["conda_rel_paths"] 1adejfghikb
87 self.site_packages_dirs: tuple[str, ...] = self.config["site_packages_dirs"] 1adejfghikb
88 self.error_messages: list[str] = [] 1adejfghikb
89 self.attachments: list[str] = [] 1adejfghikb
91 def try_site_packages(self) -> Path | None:
92 for rel_dir in self.site_packages_dirs: 1adejfghikb
93 sub_dir = tuple(rel_dir.split("/")) 1adejfghikb
94 for abs_dir in find_sub_dirs_all_sitepackages(sub_dir): 1adejfghikb
95 file_path = Path(abs_dir, self.filename) 1kb
96 if file_path.is_file(): 1kb
97 return resolve_path(file_path) 1kb
98 return None 1adejfghib
100 def try_with_conda_prefix(self) -> Path | None:
101 conda_prefix = os.environ.get("CONDA_PREFIX") 1adejfghib
102 if not conda_prefix: 1adejfghib
103 return None 1adefgh
105 anchor = Path(conda_prefix, "Library") if IS_WINDOWS else Path(conda_prefix) 1jib
106 for rel_path in self.conda_rel_paths: 1jib
107 file_path = anchor / rel_path / self.filename 1jib
108 if file_path.is_file(): 1jib
109 return resolve_path(file_path) 1jib
110 return None 1b
112 def try_with_cuda_home(self) -> Path | None:
113 cuda_home = get_cuda_path_or_home() 1adefghb
114 if cuda_home is None: 1adefghb
115 self.error_messages.append("CUDA_HOME/CUDA_PATH not set") 1d
116 return None 1d
118 anchor = Path(cuda_home) 1aefghb
119 for rel_path in self.ctk_rel_paths: 1aefghb
120 file_path = anchor / rel_path / self.filename 1aefghb
121 if file_path.is_file(): 1aefghb
122 return resolve_path(file_path) 1efghb
124 _no_such_file_in_dir( 1a
125 anchor / self.ctk_rel_paths[0],
126 self.filename,
127 self.error_messages,
128 self.attachments,
129 )
130 return None 1a
132 def raise_not_found_error(self) -> NoReturn:
133 err = ", ".join(self.error_messages) if self.error_messages else "No search paths available" 1ad
134 att = "\n".join(self.attachments) if self.attachments else "" 1ad
135 raise StaticLibNotFoundError(f'Failure finding "{self.filename}": {err}\n{att}') 1ad
138def locate_static_lib(name: str) -> LocatedStaticLib:
139 """Locate a static library by name, returning its resolved absolute path.
141 Raises:
142 ValueError: If ``name`` is not a supported static library.
143 StaticLibNotFoundError: If the static library cannot be found.
144 """
145 finder = _FindStaticLib(name) 1nadejfghikb
147 abs_path = finder.try_site_packages() 1adejfghikb
148 if abs_path is not None: 1adejfghikb
149 return LocatedStaticLib( 1kb
150 name=name,
151 abs_path=str(abs_path),
152 filename=finder.filename,
153 found_via="site-packages",
154 )
156 abs_path = finder.try_with_conda_prefix() 1adejfghib
157 if abs_path is not None: 1adejfghib
158 return LocatedStaticLib( 1jib
159 name=name,
160 abs_path=str(abs_path),
161 filename=finder.filename,
162 found_via="conda",
163 )
165 abs_path = finder.try_with_cuda_home() 1adefghb
166 if abs_path is not None: 1adefghb
167 return LocatedStaticLib( 1efghb
168 name=name,
169 abs_path=str(abs_path),
170 filename=finder.filename,
171 found_via="CUDA_PATH",
172 )
174 finder.raise_not_found_error() 1ad
177@functools.cache
178def find_static_lib(name: str) -> str:
179 """Find the resolved absolute path to a static library.
181 Raises:
182 ValueError: If ``name`` is not a supported static library.
183 StaticLibNotFoundError: If the static library cannot be found.
185 Windows on ARM (WoA) Note:
186 On Windows, this API aims to return the path to a static library whose
187 architecture matches the Python interpreter architecture. For example,
188 x64 Python running on an Arm64 machine targets the x64 library, while
189 native Arm64 Python targets the Arm64 library. This differs from
190 ``find_nvidia_binary_utility``, which targets the native machine
191 architecture when selecting architecture-specific executables.
192 """
193 return locate_static_lib(name).abs_path 1adefghik