Coverage for cuda/pathfinder/_dynamic_libs/search_steps.py: 97.58%

124 statements  

« 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 

3 

4"""Composable search steps for locating NVIDIA libraries. 

5 

6Each find step is a callable with signature:: 

7 

8 (SearchContext) -> FindResult | None 

9 

10Find steps locate a library file on disk without loading it. The 

11orchestrator in :mod:`load_nvidia_dynamic_lib` handles loading, the 

12already-loaded check, and dependency resolution. 

13 

14Step sequences are defined per search strategy so that adding a new 

15step or strategy only requires adding a function and a tuple entry. 

16 

17This module is intentionally platform-agnostic: it does not branch on the 

18current operating system. Platform differences are routed through the 

19:data:`~cuda.pathfinder._dynamic_libs.search_platform.PLATFORM` instance. 

20""" 

21 

22import glob 

23import os 

24from collections.abc import Callable, Iterator 

25from dataclasses import dataclass, field 

26from typing import NoReturn, cast 

27 

28from cuda.pathfinder._dynamic_libs.lib_descriptor import LibDescriptor 

29from cuda.pathfinder._dynamic_libs.load_dl_common import DynamicLibNotFoundError 

30from cuda.pathfinder._dynamic_libs.search_platform import PLATFORM, SearchPlatform 

31from cuda.pathfinder._utils.env_vars import get_cuda_path_or_home 

32from cuda.pathfinder._utils.path_sort import numeric_aware_path_sort_key 

33 

34from .._utils.resolve_path import resolve_path 

35 

36# --------------------------------------------------------------------------- 

37# Data types 

38# --------------------------------------------------------------------------- 

39 

40 

41@dataclass 

42class FindResult: 

43 """A library file located on disk (not yet loaded).""" 

44 

45 abs_path: str 

46 found_via: str 

47 

48 

49@dataclass 

50class SearchContext: 

51 """Mutable state accumulated during the search cascade.""" 

52 

53 desc: LibDescriptor 

54 platform: SearchPlatform = PLATFORM 

55 error_messages: list[str] = field(default_factory=list) 

56 attachments: list[str] = field(default_factory=list) 

57 

58 @property 

59 def libname(self) -> str: 

60 return self.desc.name # type: ignore[no-any-return] # mypy can't resolve new sibling module 2mb

61 

62 @property 

63 def lib_searched_for(self) -> str: 

64 return cast(str, self.platform.lib_searched_for(self.desc)) 2x | nbob} ~

65 

66 def raise_not_found(self) -> NoReturn: 

67 err = ", ".join(self.error_messages) 1x|}~

68 att = "\n".join(self.attachments) 1x|}~

69 raise DynamicLibNotFoundError(f'Failure finding "{self.lib_searched_for}": {err}\n{att}') 1x|}~

70 

71 

72#: Type alias for a find step callable. 

73FindStep = Callable[[SearchContext], FindResult | None] 

74 

75 

76def _iter_lib_dirs(root: str, rel_dirs: tuple[str, ...]) -> Iterator[str]: 

77 """Yield existing library directories under *root* in descriptor order.""" 

78 for rel_path in rel_dirs: 2a c b g i U V # W d h e y z ab$ % ' I A B C D E F G H J K L M N O P Q f l m n o p q R Y Z r s t u v w

79 for dirname in sorted(glob.glob(os.path.join(root, rel_path))): 2a c b g i U V # W d h e y z ab$ % ' I A B C D E F G H J K L M N O P Q f l m n o p q Y Z r s t u v w

80 if os.path.isdir(dirname): 1acbiUVWdheyz$%'IABCDEFGHJKLMNOPQflmnopqrstuvw

81 yield str(resolve_path(dirname)) 1acbiUVWdheyz$%'IABCDEFGHJKLMNOPQflmnopqrstuvw

82 

83 

84def _iter_lib_dirs_using_anchor( 

85 desc: LibDescriptor, 

86 platform: SearchPlatform, 

87 anchor_point: str, 

88) -> Iterator[str]: 

89 """Yield existing library directories under *anchor_point* in descriptor order.""" 

90 yield from _iter_lib_dirs(anchor_point, platform.anchor_rel_dirs(desc)) 2ab$ % '

91 

92 

93def _find_lib_dir_using_anchor(desc: LibDescriptor, platform: SearchPlatform, anchor_point: str) -> str | None: 

94 """Find the first library directory under *anchor_point*.""" 

95 return next(_iter_lib_dirs_using_anchor(desc, platform, anchor_point), None) 2ab$ % '

96 

97 

98def _find_using_lib_dir(ctx: SearchContext, lib_dir: str | None) -> str | None: 

99 """Find a library file in a resolved lib directory.""" 

100 if lib_dir is None: 1acbiUVWdheyzIABCDEFGHJKLMNOPQflmnopqrstuvw

101 return None 

102 return cast( 1acbiUVWdheyzIABCDEFGHJKLMNOPQflmnopqrstuvw

103 str | None, 

104 ctx.platform.find_in_lib_dir( 

105 lib_dir, 

106 ctx.desc, 

107 ctx.error_messages, 

108 ctx.attachments, 

109 ), 

110 ) 

111 

112 

113def _find_under_root( 

114 ctx: SearchContext, 

115 root: str, 

116 rel_dirs: tuple[str, ...], 

117 found_via: str, 

118) -> FindResult | None: 

119 """Resolve *rel_dirs* under *root*, then find the requested library.""" 

120 for lib_dir in _iter_lib_dirs(root, rel_dirs): 1acbgiUV#WdheyzIABCDEFGHJKLMNOPQflmnopqRYZrstuvw

121 abs_path = _find_using_lib_dir(ctx, lib_dir) 1acbiUVWdheyzIABCDEFGHJKLMNOPQflmnopqrstuvw

122 if abs_path is not None: 1acbiUVWdheyzIABCDEFGHJKLMNOPQflmnopqrstuvw

123 return FindResult(abs_path, found_via) 1acbiUVWdheyzIABCDJKLNOQflmnopqstuvw

124 return None 1g#EFGHMPRYZr

125 

126 

127def _find_under_anchor_root(ctx: SearchContext, root: str, found_via: str) -> FindResult | None: 

128 """Resolve the descriptor's general anchors under *root*.""" 

129 return _find_under_root(ctx, root, ctx.platform.anchor_rel_dirs(ctx.desc), found_via) 1acbgiUV#WdhyzIABCDEFGHJKLMNOPQRvw

130 

131 

132def _derive_ctk_root_linux(resolved_lib_path: str) -> str | None: 

133 """Derive CTK root from Linux canary path. 

134 

135 Supports: 

136 - ``$CTK_ROOT/lib64/libfoo.so.*`` 

137 - ``$CTK_ROOT/lib/libfoo.so.*`` 

138 - ``$CTK_ROOT/targets/<triple>/lib64/libfoo.so.*`` 

139 - ``$CTK_ROOT/targets/<triple>/lib/libfoo.so.*`` 

140 """ 

141 lib_dir = os.path.dirname(resolved_lib_path) 2c b S g 3 4 5 6 7 bbT k j

142 basename = os.path.basename(lib_dir) 2c b S g 3 4 5 6 7 bbT k j

143 if basename in ("lib64", "lib"): 2c b S g 3 4 5 6 7 bbT k j

144 parent = os.path.dirname(lib_dir) 1cbg34567kj

145 grandparent = os.path.dirname(parent) 1cbg34567kj

146 if os.path.basename(grandparent) == "targets": 1cbg34567kj

147 return os.path.dirname(grandparent) 167

148 return parent 1cbg345kj

149 return None 2c b S g bbT k j

150 

151 

152def _derive_ctk_root_windows(resolved_lib_path: str) -> str | None: 

153 """Derive CTK root from Windows canary path. 

154 

155 Supports: 

156 - ``$CTK_ROOT/bin/x64/foo.dll`` (CTK 13 style) 

157 - ``$CTK_ROOT/bin/arm64/foo.dll`` (Windows on Arm CTK 13 style) 

158 - ``$CTK_ROOT/bin/foo.dll`` (CTK 12 style) 

159 """ 

160 import ntpath 1cbSg(8)9!*Tkj

161 

162 lib_dir = ntpath.dirname(resolved_lib_path) 1cbSg(8)9!*Tkj

163 basename = ntpath.basename(lib_dir).lower() 1cbSg(8)9!*Tkj

164 if basename in ("x64", "arm64"): 1cbSg(8)9!*Tkj

165 parent = ntpath.dirname(lib_dir) 189!j

166 if ntpath.basename(parent).lower() == "bin": 189!j

167 return ntpath.dirname(parent) 189!j

168 elif basename == "bin": 1cbSg()*Tk

169 return ntpath.dirname(lib_dir) 1cbg()k

170 return None 1S*T

171 

172 

173def derive_ctk_root(resolved_lib_path: str) -> str | None: 

174 """Derive CTK root from a resolved canary library path.""" 

175 ctk_root = _derive_ctk_root_linux(resolved_lib_path) 2c b S g fbgbT k j

176 if ctk_root is not None: 2c b S g fbgbT k j

177 return ctk_root 2c b g fbk j

178 return _derive_ctk_root_windows(resolved_lib_path) 2c b S g gbT k j

179 

180 

181def find_via_ctk_root(ctx: SearchContext, ctk_root: str) -> FindResult | None: 

182 """Find a library under a previously derived CTK root.""" 

183 return _find_under_anchor_root(ctx, ctk_root, "system-ctk-root") 1cbgUV#W

184 

185 

186# --------------------------------------------------------------------------- 

187# Find steps 

188# --------------------------------------------------------------------------- 

189 

190 

191def find_in_site_packages(ctx: SearchContext) -> FindResult | None: 

192 """Search pip wheel install locations.""" 

193 rel_dirs = ctx.platform.site_packages_rel_dirs(ctx.desc) 2a d h 0 X e 1 f 2 + , - . / : ; = ? @ [ ] ^ _ hb` {

194 if not rel_dirs: 2a d h 0 X e 1 f 2 + , - . / : ; = ? @ [ ] ^ _ hb` {

195 return None 2hb

196 abs_path = ctx.platform.find_in_site_packages( 1adh0Xe1f2+,-./:;=?@[]^_`{

197 rel_dirs, 

198 ctx.desc, 

199 ctx.error_messages, 

200 ctx.attachments, 

201 ) 

202 if abs_path is not None: 1adh0Xe1f2+,-./:;=?@[]^_`{

203 return FindResult(abs_path, "site-packages") 1012+,./:;=_

204 return None 1adhXef-?@[]^`{

205 

206 

207def find_in_conda(ctx: SearchContext) -> FindResult | None: 

208 """Search ``$CONDA_PREFIX``.""" 

209 conda_prefix = os.environ.get("CONDA_PREFIX") 2a d h X e y z A B C D E F G H ibjbR

210 if not conda_prefix: 2a d h X e y z A B C D E F G H ibjbR

211 return None 2a d X e ibjb

212 anchor = ctx.platform.conda_anchor_point(conda_prefix) 1hyzABCDEFGHR

213 return _find_under_anchor_root(ctx, anchor, "conda") 1hyzABCDEFGHR

214 

215 

216def find_in_install_root_env_vars(ctx: SearchContext) -> FindResult | None: 

217 """Search installation roots named by descriptor-specific environment variables.""" 

218 rel_dirs = ctx.platform.install_root_env_rel_dirs(ctx.desc) 1abixdeflmnopqYZrstu

219 for env_var in ctx.platform.install_root_env_vars(ctx.desc): 1abixdeflmnopqYZrstu

220 root = os.environ.get(env_var) 1eflmnopqYZrstu

221 if not root: 1eflmnopqYZrstu

222 continue 

223 result = _find_under_root(ctx, root, rel_dirs, env_var) 1eflmnopqYZrstu

224 if result is not None: 1eflmnopqYZrstu

225 return result 1eflmnopqstu

226 return None 1abixdYZr

227 

228 

229def find_in_cuda_path(ctx: SearchContext) -> FindResult | None: 

230 """Search ``$CUDA_PATH`` / ``$CUDA_HOME`` as fallback toolkit roots. 

231 

232 This step runs after native system search on both platforms. On Windows, 

233 native ``LoadLibraryExW(..., 0)`` search can already discover CTK DLLs 

234 through ``PATH``, subject to the process's DLL search policy. These roots 

235 do not override earlier discoveries or pin the runtime toolkit. 

236 

237 The returned ``found_via`` is always ``"CUDA_PATH"`` regardless of which 

238 environment variable actually provided the value. 

239 """ 

240 cuda_home = get_cuda_path_or_home() 2a b i x d I J K L M N O P kbQ R

241 if cuda_home is None: 2a b i x d I J K L M N O P kbQ R

242 return None 2b x kb

243 return _find_under_anchor_root(ctx, cuda_home, "CUDA_PATH") 1aidIJKLMNOPQR

244 

245 

246def find_in_program_files_roots(ctx: SearchContext) -> FindResult | None: 

247 """Search descriptor-configured installation roots under Program Files.""" 

248 for root_glob in ctx.platform.program_files_root_globs(ctx.desc): 1bxRvw

249 for root in sorted(glob.glob(root_glob), key=numeric_aware_path_sort_key, reverse=True): 1vw

250 if not os.path.isdir(root): 1vw

251 continue 

252 result = _find_under_anchor_root(ctx, str(resolve_path(root)), "ProgramFiles") 1vw

253 if result is not None: 1vw

254 return result 1vw

255 return None 1bxR

256 

257 

258# --------------------------------------------------------------------------- 

259# Step sequences per strategy 

260# --------------------------------------------------------------------------- 

261 

262#: Find steps that run before the already-loaded check and system search. 

263EARLY_FIND_STEPS: tuple[FindStep, ...] = (find_in_site_packages, find_in_conda) 

264 

265#: Find steps that run after system search fails. 

266LATE_FIND_STEPS: tuple[FindStep, ...] = ( 

267 find_in_install_root_env_vars, 

268 find_in_cuda_path, 

269 find_in_program_files_roots, 

270) 

271 

272 

273# --------------------------------------------------------------------------- 

274# Cascade runner 

275# --------------------------------------------------------------------------- 

276 

277 

278def run_find_steps(ctx: SearchContext, steps: tuple[FindStep, ...]) -> FindResult | None: 

279 """Run find steps in order, returning the first hit.""" 

280 for step in steps: 2a b i x d h 0 X e 1 f 2 lbcbdbeb

281 result = step(ctx) 2a b i x d h 0 X e 1 f 2 cbdbeb

282 if result is not None: 2a b i x d h 0 X e 1 f 2 cbdbeb

283 return result 2a i d h 0 e 1 f 2 cbeb

284 return None 2a b x d X e lbdb