Coverage for cuda/pathfinder/_binaries/find_nvidia_binary_utility.py: 97.06%
102 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) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2# SPDX-License-Identifier: Apache-2.0
4import functools
5import os
6from collections.abc import Iterable
8from cuda.pathfinder._binaries import supported_nvidia_binaries, windows_nsight
9from cuda.pathfinder._utils.ctk_root_canary import CTK_ROOT_CANARY_ANCHOR_LIBNAMES
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
14from .._utils.resolve_path import resolve_path
17class UnsupportedBinaryError(Exception):
18 def __init__(self, utility: str) -> None:
19 super().__init__(utility) 16
20 self.utility = utility 16
22 def __str__(self) -> str:
23 supported_utilities = ", ".join(supported_nvidia_binaries.SUPPORTED_BINARIES) 16
24 return f"Binary '{self.utility}' is not supported. Supported utilities are: {supported_utilities}" 16
27def _normalize_utility_name(utility_name: str) -> str:
28 """Normalize utility name by adding .exe on Windows if needed."""
29 if IS_WINDOWS and not utility_name.lower().endswith((".exe", ".bat", ".cmd")): 1rstcYVOGQWumaefgnbhidojpklqvPwxyzCDEFBRXZAHIJKLMNST
30 return f"{utility_name}.exe" 1cOmaefgnbhidojpklqvPwxyzCDEFBRXZHIJKLMNST
31 return utility_name 1rstcYVGQWumaefgnbhidojpklqA
34def _is_executable_candidate(path: str) -> bool:
35 if not os.path.isfile(path): 10123rstcmaefgnbhidojpklq4
36 return False 10cmaefgnbhidojpklq
37 if IS_WINDOWS: 10123rstcmnopq4
38 return True 1012cmnopq
39 return os.access(path, os.X_OK) 10123rstcmnopq4
42def _ctk_bin_subdirs(root: str) -> list[str]:
43 if IS_WINDOWS: 1rstcOGumaefgnbhidojpklqvAMN
44 return [ 1cOmefgnhiojpklqvMN
45 os.path.join(root, "bin", "x64"),
46 os.path.join(root, "bin", "x86_64"),
47 os.path.join(root, "bin"),
48 ]
49 return [os.path.join(root, "bin")] 1rstcGumaefgnbhidojpklqA
52def _resolve_candidate_paths(candidates: Iterable[str]) -> str | None:
53 """Return the first executable candidate, preserving candidate order."""
54 seen: set[str] = set() 1abdPwxyzCDEFBXZHIJKL4
55 for candidate in candidates: 1abdPwxyzCDEFBXZHIJKL4
56 if candidate in seen: 1aPwxyzCDEFBHIJKL4
57 continue
58 seen.add(candidate) 1aPwxyzCDEFBHIJKL4
59 if _is_executable_candidate(candidate): 1aPwxyzCDEFBHIJKL4
60 return str(resolve_path(candidate)) 1PwxyzCDEFBHIJKL4
61 return None 1abdwxyzBXZ
64def _find_windows_compute_sanitizer(ctk_root: str) -> str | None:
65 return _resolve_candidate_paths( 1aHIJKL
66 (
67 os.path.join(ctk_root, "bin", "compute-sanitizer.bat"),
68 os.path.join(ctk_root, "compute-sanitizer", "compute-sanitizer.exe"),
69 )
70 )
73def _resolve_ctk_root_via_canary() -> str | None:
74 from cuda.pathfinder._dynamic_libs.load_nvidia_dynamic_lib import resolve_ctk_root_via_canary 1caefgbhidjkl
76 ctk_root: str | None = resolve_ctk_root_via_canary(CTK_ROOT_CANARY_ANCHOR_LIBNAMES[0]) 1caefgbhidjkl
77 return ctk_root 1caefgbhidjkl
80def _resolve_in_trusted_dirs(normalized_name: str, dirs: list[str]) -> str | None:
81 """Resolve ``normalized_name`` against ``dirs`` in order."""
82 seen: set[str] = set() 101723rstcYVOGQWumaefgnbhidojpklqvCDEFRZAMNST5
83 for directory in dirs: 101723rstcYVOGQWumaefgnbhidojpklqvCDEFRZAMNST5
84 if directory in seen: 101723rstcVOGQumaefgnbhidojpklqvCDEFRAMNST5
85 continue
86 assert directory 101723rstcVOGQumaefgnbhidojpklqvCDEFRAMNST5
87 seen.add(directory) 10123rstcVOGQumaefgnbhidojpklqvCDEFRAMNST5
88 candidate = os.path.join(directory, normalized_name) 10123rstcVOGQumaefgnbhidojpklqvCDEFRAMNST5
89 if _is_executable_candidate(candidate): 10123rstcVOGQumaefgnbhidojpklqvCDEFRAMNST5
90 return str(resolve_path(candidate)) 10123rstcVGQmnopqRMNST5
91 return None 1013rstcYOGWumaefgnbhidojpklqvCDEFZAMN
94def _resolve_names_in_trusted_dirs(candidate_names: tuple[str, ...], dirs: list[str]) -> str | None:
95 """Resolve ordered candidate names within each trusted directory."""
96 seen: set[str] = set() 1abPwxyzBXHIJKL
97 for directory in dirs: 1abPwxyzBXHIJKL
98 if directory in seen: 1wxyzB
99 continue
100 assert directory 1wxyzB
101 seen.add(directory) 1wxyzB
102 found = _resolve_candidate_paths(os.path.join(directory, name) for name in candidate_names) 1wxyzB
103 if found is not None: 1wxyzB
104 return found 1B
105 return None 1abPwxyzXHIJKL
108@functools.cache
109def find_nvidia_binary_utility(utility_name: str) -> str | None:
110 """Locate a CUDA binary utility executable.
112 Args:
113 utility_name (str): The name of the binary utility to find
114 (e.g., ``"nvdisasm"``, ``"cuobjdump"``). On Windows, the ``.exe``
115 extension will be automatically appended if not present. The function
116 also recognizes ``.bat`` and ``.cmd`` files on Windows.
118 Returns:
119 str or None: Resolved absolute path to the discovered executable, or
120 ``None`` if the utility cannot be found. Symlinks and parent-directory
121 components are resolved to identify the selected executable.
123 Raises:
124 UnsupportedBinaryError: If ``utility_name`` is not in the supported set
125 (see ``SUPPORTED_BINARY_UTILITIES``).
126 RuntimeError: If a native Windows architecture needed for an
127 architecture-specific utility layout cannot be determined, or an
128 installed Nsight product has incomplete or invalid registry data.
130 Windows on ARM (WoA) Note:
131 Binary utilities execute in separate processes and do not need to match
132 the Python process architecture. When choosing among architecture-specific
133 Windows layouts, this API deliberately targets the native machine
134 architecture rather than the Python interpreter architecture. For
135 example, standalone ``nsys`` and ``ncu`` discovery under x64 Python on an
136 Arm64 machine selects the Arm64 target. This differs from
137 ``load_nvidia_dynamic_lib`` and ``find_static_lib``, which target the
138 Python interpreter architecture.
140 Search order:
141 1. **NVIDIA Python wheels**
143 - Scan installed distributions (``site-packages``) for binary layouts
144 shipped in NVIDIA wheels (e.g., ``cuda-nvcc``).
146 2. **Conda environments**
148 - Check Conda-style installation prefixes via ``CONDA_PREFIX``
149 environment variable, which use platform-specific bin directory
150 layouts (``Library/bin`` on Windows, ``bin`` on Linux).
152 3. **Library-specific standalone installations**
154 - Search the installation paths for the CUDA Toolkit, Nsight Systems,
155 and Nsight Compute.
157 3.1. **Nsight installations**: On Windows, locate Nsight Systems and
158 Nsight Compute from their installer registry entries. Select
159 architecture-specific binaries using the native machine
160 architecture, independent of Python. Lookup of the standalone
161 ``nsys`` and ``ncu`` CLIs is terminal; a miss does not fall
162 through to CUDA Toolkit locations.
164 3.2. **CUDA Toolkit installation**: Use ``CUDA_PATH`` or ``CUDA_HOME``
165 (in that order), searching ``bin/x64``, ``bin/x86_64``, and
166 ``bin`` subdirectories on Windows, or just ``bin`` on Linux.
168 4. **CTK-root canary fallback**
170 - For utilities that reach this step after the earlier searches miss,
171 resolve the ``cudart`` library through the OS dynamic loader, derive
172 the CUDA Toolkit root from it, and search that root's bin layout.
174 Note:
175 Results are cached using ``@functools.cache`` for performance. The cache
176 persists for the lifetime of the process.
178 On Windows, executables are identified by their file extensions
179 (``.exe``, ``.bat``, ``.cmd``). On Unix-like systems, executables
180 are identified by the ``X_OK`` (execute) permission bit.
182 Lookup is restricted to the trusted directories and the canary-derived
183 CTK root listed above.
185 Example:
186 >>> from cuda.pathfinder import find_nvidia_binary_utility
187 >>> nvdisasm = find_nvidia_binary_utility("nvdisasm")
188 >>> if nvdisasm:
189 ... print(f"Found nvdisasm at: {nvdisasm}")
190 """
191 if utility_name not in supported_nvidia_binaries.SUPPORTED_BINARIES: 1rstcYVOGQWumaefgnbhidojpklqvPwxyzCDEFBRXZAHIJKLMNST6
192 raise UnsupportedBinaryError(utility_name) 16
194 # 1. Search in site-packages (NVIDIA wheels)
195 candidate_dirs = supported_nvidia_binaries.SITE_PACKAGES_BINDIRS.get(utility_name, ()) 1rstcYVOGQWumaefgnbhidojpklqvPwxyzCDEFBRXZAHIJKLMNST
196 dirs = [] 1rstcYVOGQWumaefgnbhidojpklqvPwxyzCDEFBRXZAHIJKLMNST
198 for sub_dir in candidate_dirs: 1rstcYVOGQWumaefgnbhidojpklqvPwxyzCDEFBRXZAHIJKLMNST
199 dirs.extend(find_sub_dirs_all_sitepackages(sub_dir.split(os.sep))) 1rstcQWumaefgnbhidojpklqvwxyzCDEFBRST
201 # 2. Search in Conda environment
202 if (conda_prefix := os.environ.get("CONDA_PREFIX")) is not None: 1rstcYVOGQWumaefgnbhidojpklqvPwxyzCDEFBRXZAHIJKLMNST
203 if IS_WINDOWS: 1VQuvwxyzCDEFBRAST
204 dirs.append(os.path.join(conda_prefix, "Library", "bin")) 1vwxyzCDEFBRST
205 else:
206 dirs.append(os.path.join(conda_prefix, "bin")) 1VQuA
208 normalized_name = _normalize_utility_name(utility_name) 1rstcYVOGQWumaefgnbhidojpklqvPwxyzCDEFBRXZAHIJKLMNST
209 if IS_WINDOWS and utility_name in ("compute-sanitizer", "ncu"): 1rstcYVOGQWumaefgnbhidojpklqvPwxyzCDEFBRXZAHIJKLMNST
210 candidate_names = (f"{utility_name}.bat", normalized_name) 1abPwxyzBXHIJKL
211 found = _resolve_names_in_trusted_dirs(candidate_names, dirs) 1abPwxyzBXHIJKL
212 else:
213 found = _resolve_in_trusted_dirs(normalized_name, dirs) 1rstcYVOGQWumaefgnbhidojpklqvCDEFRZAMNST
214 if found is not None: 1rstcYVOGQWumaefgnbhidojpklqvPwxyzCDEFBRXZAHIJKLMNST
215 return found 1VQBRST
217 # 3. Search library-specific standalone installations.
218 # 3.1. Standalone Nsight CLI lookup is terminal; CTK does not contain nsys/ncu.
219 if IS_WINDOWS and utility_name == "nsys": 1rstcYOGWumaefgnbhidojpklqvPwxyzCDEFXZAHIJKLMN
220 return _resolve_candidate_paths(windows_nsight.nsys_candidate_paths()) 1dCDEFZ
221 if IS_WINDOWS and utility_name == "ncu": 1rstcYOGWumaefgnbhidojpklqvPwxyzXAHIJKLMN
222 return _resolve_candidate_paths(windows_nsight.ncu_candidate_paths()) 1bPwxyzX
224 # 3.2. Search in CUDA Toolkit (CUDA_PATH/CUDA_HOME).
225 if (cuda_path := get_cuda_path_or_home()) is not None: 1rstcYOGWumaefgnbhidojpklqvAHIJKLMN
226 if IS_WINDOWS and utility_name == "compute-sanitizer": 1rstcumaefgnbhidojpklqvAHIJKMN
227 found = _find_windows_compute_sanitizer(cuda_path) 1aHIJK
228 else:
229 found = _resolve_in_trusted_dirs(normalized_name, _ctk_bin_subdirs(cuda_path)) 1rstcumaefgnbhidojpklqvAMN
230 if found is not None: 1rstcumaefgnbhidojpklqvAHIJKMN
231 return found 1rstcmnopqHIJKMN
233 # 4. CTK-root canary fallback.
234 ctk_root = _resolve_ctk_root_via_canary() 1cYOGWuaefgbhidjklvAL
235 if ctk_root is not None: 1cYOGWuaefgbhidjklvAL
236 if IS_WINDOWS and utility_name == "compute-sanitizer": 1OGL
237 return _find_windows_compute_sanitizer(ctk_root) 1L
238 return _resolve_in_trusted_dirs(normalized_name, _ctk_bin_subdirs(ctk_root)) 1OG
239 return None 1cYWuaefgbhidjklvA