Coverage for cuda/pathfinder/_dynamic_libs/load_dl_linux.py: 80.83%
120 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
4from __future__ import annotations
6import ctypes
7import ctypes.util
8import os
9import sys
10import warnings
11from typing import TYPE_CHECKING, cast
13from cuda.pathfinder._dynamic_libs.load_dl_common import LoadedDL
15if TYPE_CHECKING:
16 from cuda.pathfinder._dynamic_libs.lib_descriptor import LibDescriptor
18if sys.platform == "linux":
19 CDLL_MODE = os.RTLD_NOW | os.RTLD_GLOBAL
20else:
21 CDLL_MODE = 0
24def _load_libdl() -> ctypes.CDLL:
25 # In normal glibc-based Linux environments, find_library("dl") should return
26 # something like "libdl.so.2". In minimal or stripped-down environments
27 # (no ldconfig/gcc, incomplete linker cache), this can return None even
28 # though libdl is present. In that case, we fall back to the stable SONAME.
29 name = ctypes.util.find_library("dl") or "libdl.so.2"
30 try:
31 return ctypes.CDLL(name)
32 except OSError as e:
33 raise RuntimeError(f"Could not load {name!r} (required for dlinfo/dlerror on Linux)") from e
36LIBDL = _load_libdl()
38# dlinfo
39LIBDL.dlinfo.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p]
40LIBDL.dlinfo.restype = ctypes.c_int
42# dlerror (thread-local error string; cleared after read)
43LIBDL.dlerror.argtypes = []
44LIBDL.dlerror.restype = ctypes.c_char_p
46# First appeared in 2004-era glibc. Universally correct on Linux for all practical purposes.
47RTLD_DI_LINKMAP = 2
48RTLD_DI_ORIGIN = 6
51class _LinkMapLNameView(ctypes.Structure):
52 """
53 Prefix-only view of glibc's `struct link_map` used **solely** to read `l_name`.
55 Background:
56 - `dlinfo(handle, RTLD_DI_LINKMAP, ...)` returns a `struct link_map*`.
57 - The first few members of `struct link_map` (including `l_name`) have been
58 stable on glibc for decades and are documented as debugger-visible.
59 - We only need the offset/layout of `l_name`, not the full struct.
61 Safety constraints:
62 - This is a **partial** definition (prefix). It must only be used via a pointer
63 returned by `dlinfo(...)`.
64 - Do **not** instantiate it or pass it **by value** to any C function.
65 - Do **not** access any members beyond those declared here.
66 - Do **not** rely on `ctypes.sizeof(LinkMapPrefix)` for allocation.
68 Rationale:
69 - Defining only the leading fields avoids depending on internal/unstable
70 tail members while keeping code more readable than raw pointer arithmetic.
71 """
73 _fields_ = (
74 ("l_addr", ctypes.c_void_p), # ElfW(Addr)
75 ("l_name", ctypes.c_char_p), # char*
76 )
79# Defensive assertions, mainly to document the invariants we depend on
80assert _LinkMapLNameView.l_addr.offset == 0
81assert _LinkMapLNameView.l_name.offset == ctypes.sizeof(ctypes.c_void_p)
84def _dl_last_error() -> str | None:
85 msg_bytes = cast(bytes | None, LIBDL.dlerror())
86 if not msg_bytes:
87 return None # no pending error
88 # Never raises; undecodable bytes are mapped to U+DC80..U+DCFF
89 return msg_bytes.decode("utf-8", "surrogateescape")
92def l_name_for_dynamic_library(libname: str, handle: ctypes.CDLL) -> str:
93 lm_view = ctypes.POINTER(_LinkMapLNameView)() 1ab
94 rc = LIBDL.dlinfo(ctypes.c_void_p(handle._handle), RTLD_DI_LINKMAP, ctypes.byref(lm_view)) 1ab
95 if rc != 0: 1ab
96 err = _dl_last_error()
97 raise OSError(f"dlinfo failed for {libname=!r} (rc={rc})" + (f": {err}" if err else ""))
98 if not lm_view: # NULL link_map** 1ab
99 raise OSError(f"dlinfo returned NULL link_map pointer for {libname=!r}")
101 l_name_bytes = lm_view.contents.l_name 1ab
102 if not l_name_bytes: 1ab
103 raise OSError(f"dlinfo returned empty link_map->l_name for {libname=!r}")
105 path = os.fsdecode(l_name_bytes) 1ab
106 if not path: 1ab
107 raise OSError(f"dlinfo returned empty l_name string for {libname=!r}")
109 return path 1ab
112def l_origin_for_dynamic_library(libname: str, handle: ctypes.CDLL) -> str:
113 l_origin_buf = ctypes.create_string_buffer(4096) 1ab
114 rc = LIBDL.dlinfo(ctypes.c_void_p(handle._handle), RTLD_DI_ORIGIN, l_origin_buf) 1ab
115 if rc != 0: 1ab
116 err = _dl_last_error()
117 raise OSError(f"dlinfo failed for {libname=!r} (rc={rc})" + (f": {err}" if err else ""))
119 path = os.fsdecode(l_origin_buf.value) 1ab
120 if not path: 1ab
121 raise OSError(f"dlinfo returned empty l_origin string for {libname=!r}")
123 return path 1ab
126def abs_path_for_dynamic_library(libname: str, handle: ctypes.CDLL) -> str:
127 l_name = l_name_for_dynamic_library(libname, handle) 1ab
128 l_origin = l_origin_for_dynamic_library(libname, handle) 1ab
129 return os.path.join(l_origin, os.path.basename(l_name)) 1ab
132if sys.platform == "linux":
134 def check_if_already_loaded_from_elsewhere(desc: LibDescriptor) -> LoadedDL | None:
135 for soname in desc.linux_sonames: 1acbl
136 try: 1acbl
137 handle = ctypes.CDLL(soname, mode=os.RTLD_NOLOAD) 1acbl
138 except OSError: 1acbl
139 continue 1acbl
140 else:
141 return LoadedDL(
142 abs_path_for_dynamic_library(desc.name, handle),
143 True,
144 handle._handle,
145 "was-already-loaded-from-elsewhere",
146 )
147 return None 1acbl
149 def _load_lib(desc: LibDescriptor, filename: str) -> ctypes.CDLL:
150 cdll_mode = CDLL_MODE 1acb
151 if desc.requires_rtld_deepbind: 1acb
152 cdll_mode |= os.RTLD_DEEPBIND
153 return ctypes.CDLL(filename, cdll_mode) 1acb
154else:
156 def check_if_already_loaded_from_elsewhere(_desc: LibDescriptor) -> LoadedDL | None:
157 raise RuntimeError(f"check_if_already_loaded_from_elsewhere() is not supported on platform {sys.platform!r}")
159 def _load_lib(_desc: LibDescriptor, _filename: str) -> ctypes.CDLL:
160 raise RuntimeError(f"_load_lib() is not supported on platform {sys.platform!r}")
163def load_with_system_search(desc: LibDescriptor) -> LoadedDL | None:
164 """Try to load a library using the native Linux dynamic-loader search path.
166 Args:
167 desc: Descriptor for the library to load
169 Returns:
170 A LoadedDL object if successful, None if the library cannot be loaded
172 """
173 for soname in desc.linux_sonames: 1acbm
174 try: 1acbm
175 handle = _load_lib(desc, soname) 1acbm
176 except OSError: 1acm
177 pass 1acm
178 else:
179 abs_path = abs_path_for_dynamic_library(desc.name, handle) 1ab
180 assert abs_path 1ab
181 return LoadedDL(abs_path, False, handle._handle, "system-search") 1ab
182 return None 1acm
185def _preload_nvrtc_builtins(found_path: str, found_via: str | None) -> None:
186 # Let Conda packaging provide sibling lookup through RPATH.
187 if found_via == "conda": 1adnfghiekj
188 return 1n
189 real_path = os.path.realpath(found_path) 1adfghiekj
190 version = os.path.basename(real_path).removeprefix("libnvrtc.so.").split(".") 1adfghiekj
191 if found_via == "site-packages": 1adfghiekj
192 # Retain only the historical 13.0 wheel workaround.
193 if version[0] != "13": 1hij
194 return
195 major, minor = 13, 0 1hij
196 else:
197 if len(version) < 2 or not (version[0].isdigit() and version[1].isdigit()): 1adfgek
198 warnings.warn( 1k
199 f"Cannot determine the NVRTC version from {real_path}; not preloading its builtins",
200 RuntimeWarning,
201 stacklevel=2,
202 )
203 return 1k
204 major, minor = version[0], version[1] 1adfge
205 sibling = os.path.join(os.path.dirname(real_path), f"libnvrtc-builtins.so.{major}.{minor}") 1adfghiej
206 if not os.path.isfile(sibling): 1adfghiej
207 if found_via != "site-packages": 1iej
208 warnings.warn(f"NVRTC builtins sibling not found: {sibling}", RuntimeWarning, stacklevel=2) 1e
209 return 1iej
210 # If preloading fails, NVRTC's own builtins lookup may still succeed.
211 try: 1adfgh
212 ctypes.CDLL(sibling, CDLL_MODE) 1adfgh
213 except OSError as e: 1d
214 warnings.warn( 1d
215 f"Failed to preload {sibling} for {found_path}: {e}; NVRTC may fail when it loads its builtins itself",
216 RuntimeWarning,
217 stacklevel=2,
218 )
221def load_with_abs_path(desc: LibDescriptor, found_path: str, found_via: str | None = None) -> LoadedDL:
222 """Load a dynamic library from the given path.
224 Args:
225 desc: Descriptor for the library to load.
226 found_path: The absolute path to the library file.
227 found_via: Label indicating how the path was discovered.
229 Returns:
230 A LoadedDL object representing the loaded library.
232 Raises:
233 RuntimeError: If the library cannot be loaded.
234 """
235 try: 1acd
236 handle = _load_lib(desc, found_path) 1acd
237 except OSError as e:
238 raise RuntimeError(f"Failed to dlopen {found_path}: {e}") from e
239 if desc.name == "nvrtc": 1acd
240 _preload_nvrtc_builtins(found_path, found_via) 1ad
241 return LoadedDL(found_path, False, handle._handle, found_via) 1acd