singe_loader/lib.rs
1//! Loads the NVIDIA libraries behind Singe's `*-sys` crates at run time, so a program that uses them builds and starts on a machine without them.
2//! A function whose library or symbol is missing returns a fixed value of its return type instead of failing to link.
3//!
4//! This crate provides:
5//!
6//! - **[`Library`]:** one library made of one or more files, with a `const` constructor per NVIDIA library, such as [`Library::cublas()`] or [`Library::nvjpeg2k()`], and [`Library::new`] for any other.
7//! - **[`functions!`]:** turns the declarations of a bindgen `extern "C"` block into functions of the same names and signatures that look up their symbol on first call.
8//! - **[`Missing`]:** what a function returns when it cannot be called: zero for integers, null for pointers, and nothing for [`()`](prim@unit), with [`missing_status!`] and [`missing_value!`] to implement it for a library's own types.
9//! - **[`take_absence`]:** returns and clears the [`Absence`] that the last status-returning call on the current thread recorded, so a safe wrapper can turn that status into a load error.
10//! - **[`LoadError`]:** a library with no files on this platform, a library that would not load, with each [`Attempt`] the loader made, or a missing symbol.
11//!
12//! # Example
13//!
14//! Load cuBLAS and print where each of its files was found, or each place the loader tried:
15//!
16//! ```rust,no_run
17//! use singe_loader::{Library, LoadError};
18//!
19//! static CUBLAS: Library = Library::cublas();
20//!
21//! fn main() -> anyhow::Result<()> {
22//! match CUBLAS.paths() {
23//! Ok(paths) => {
24//! for path in paths {
25//! println!("{} loaded from {}", CUBLAS.name(), path.display());
26//! }
27//! }
28//! Err(LoadError::NotFound { library, attempts }) => {
29//! for attempt in &attempts {
30//! println!("{library}: {}: {}", attempt.path.display(), attempt.reason);
31//! }
32//! }
33//! Err(error) => return Err(error.into()),
34//! }
35//! Ok(())
36//! }
37//! ```
38//!
39//! A library loads at most once and stays loaded for the life of the process, so the functions that cached its symbols stay valid.
40//! Its load result is cached too: a library that failed to load returns the same [`LoadError`] on every later call.
41//!
42//! # Search order
43//!
44//! The loader tries each file by name through the system loader's search first, then in the library directories under `CUDA_PATH` and `CUDA_HOME`, and on Linux under `/usr/local/cuda` and in `/run/opengl-driver/lib`.
45//! The NVIDIA libraries have file names only on Linux and Windows; elsewhere, loading one returns [`LoadError::Unsupported`].
46
47mod libraries;
48
49use std::{
50 cell::Cell,
51 env,
52 ffi::{CStr, OsString},
53 fmt,
54 path::{Path, PathBuf},
55 ptr,
56 sync::OnceLock,
57};
58
59/// One library behind a set of declarations, made of every file in `files`, each of which must load.
60///
61/// A symbol is looked up in each file in order, as NPP's functions are spread over eleven.
62/// The NVIDIA libraries have constructors of their own, such as [`Library::cusparse`], which name their files on each platform.
63pub struct Library {
64 name: &'static str,
65 files: &'static [&'static str],
66 loaded: OnceLock<Result<Vec<File>, LoadError>>,
67}
68
69// A file of a library, loaded, and where the loader found it.
70struct File {
71 library: libloading::Library,
72 path: PathBuf,
73}
74
75impl Library {
76 /// Creates a library named `name` from the files that make it up on this platform.
77 #[must_use]
78 pub const fn new(name: &'static str, files: &'static [&'static str]) -> Self {
79 Self {
80 name,
81 files,
82 loaded: OnceLock::new(),
83 }
84 }
85
86 /// Returns the library's name, such as `cuSPARSE`.
87 #[must_use]
88 pub const fn name(&self) -> &'static str {
89 self.name
90 }
91
92 /// Loads every file once, and keeps them loaded for the life of the process, which every cached function relies on.
93 ///
94 /// # Errors
95 ///
96 /// Returns an error if the library has no files on this platform or a file would not load.
97 pub fn load(&self) -> Result<(), LoadError> {
98 self.files().map(|_| ())
99 }
100
101 /// Returns where each file loaded from, in order, loading them if they are not yet.
102 ///
103 /// # Errors
104 ///
105 /// Returns an error if the library would not load.
106 pub fn paths(&self) -> Result<Vec<PathBuf>, LoadError> {
107 Ok(self.files()?.iter().map(|file| file.path.clone()).collect())
108 }
109
110 fn files(&self) -> Result<&[File], LoadError> {
111 self.loaded
112 .get_or_init(|| {
113 if self.files.is_empty() {
114 return Err(LoadError::Unsupported { library: self.name });
115 }
116
117 self.files
118 .iter()
119 .map(|file| open(self.name, file))
120 .collect()
121 })
122 .as_deref()
123 .map_err(Clone::clone)
124 }
125
126 /// Looks up the symbol `name` in each file in order, as a value of type `F`.
127 ///
128 /// Returns `None` if the library would not load or no file exports `name`.
129 ///
130 /// # Safety
131 ///
132 /// `F` must be the symbol's actual type.
133 #[doc(hidden)]
134 #[must_use]
135 pub unsafe fn symbol<F: Copy>(&self, name: &CStr) -> Option<F> {
136 let files = self.files().ok()?;
137 files.iter().find_map(|file| {
138 // SAFETY: the caller guarantees `F` is the symbol's type, and `files` keeps the library loaded.
139 unsafe { file.library.get::<F>(name.to_bytes_with_nul()) }
140 .ok()
141 .map(|symbol| *symbol)
142 })
143 }
144
145 /// Returns why the function `symbol` of this library is missing: its library, or only its symbol.
146 #[doc(hidden)]
147 #[must_use]
148 pub fn absence(&'static self, symbol: &'static str) -> Absence {
149 if self.files().is_ok() {
150 Absence::Symbol {
151 library: self,
152 name: symbol,
153 }
154 } else {
155 Absence::Library(self)
156 }
157 }
158}
159
160impl fmt::Debug for Library {
161 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
162 formatter
163 .debug_struct("Library")
164 .field("name", &self.name)
165 .field("files", &self.files)
166 .finish_non_exhaustive()
167 }
168}
169
170// Opens `file` by name, through the system loader's search, and then in the directories NVIDIA installs to.
171fn open(name: &'static str, file: &'static str) -> Result<File, LoadError> {
172 let mut attempts = Vec::new();
173 for candidate in candidates(file) {
174 // SAFETY: loading an NVIDIA library runs only its initializers, which have no preconditions.
175 match unsafe { libloading::Library::new(&candidate) } {
176 Ok(library) => {
177 let (library, path) = locate(library);
178 return Ok(File {
179 path: path.unwrap_or_else(|| PathBuf::from(&candidate)),
180 library,
181 });
182 }
183 Err(error) => attempts.push(Attempt {
184 path: PathBuf::from(candidate),
185 reason: error.to_string(),
186 }),
187 }
188 }
189 Err(LoadError::NotFound {
190 library: name,
191 attempts,
192 })
193}
194
195// Asks glibc's loader for the file it opened, which a bare file name does not say.
196// `dlinfo` and the layout of `struct link_map` are glibc's, so other C libraries skip the lookup.
197#[cfg(all(target_os = "linux", target_env = "gnu"))]
198fn locate(library: libloading::Library) -> (libloading::Library, Option<PathBuf>) {
199 use std::{
200 ffi::{OsStr, c_char, c_int, c_void},
201 os::unix::ffi::OsStrExt,
202 };
203
204 use libloading::os::unix::Library as UnixLibrary;
205
206 // The start of glibc's `struct link_map`, which is all `dlinfo` callers may read.
207 #[repr(C)]
208 struct LinkMap {
209 address: usize,
210 name: *const c_char,
211 }
212
213 const RTLD_DI_LINKMAP: c_int = 2;
214
215 #[link(name = "dl")]
216 unsafe extern "C" {
217 fn dlinfo(handle: *mut c_void, request: c_int, info: *mut c_void) -> c_int;
218 }
219
220 let handle = UnixLibrary::from(library).into_raw();
221 let mut map: *const LinkMap = ptr::null();
222 // SAFETY: `handle` is a live handle `dlopen` returned, and `RTLD_DI_LINKMAP` writes one pointer to `map`.
223 let found = unsafe { dlinfo(handle, RTLD_DI_LINKMAP, (&raw mut map).cast()) } == 0;
224 let path = (found && !map.is_null())
225 .then(|| {
226 // SAFETY: the loader owns the map and its nul-terminated name while the library stays loaded.
227 let name = unsafe { CStr::from_ptr((*map).name) };
228 (!name.is_empty()).then(|| PathBuf::from(OsStr::from_bytes(name.to_bytes())))
229 })
230 .flatten();
231 // SAFETY: `handle` came from `into_raw` above and is owned again here.
232 let library = unsafe { UnixLibrary::from_raw(handle) }.into();
233 (library, path)
234}
235
236#[cfg(not(all(target_os = "linux", target_env = "gnu")))]
237fn locate(library: libloading::Library) -> (libloading::Library, Option<PathBuf>) {
238 (library, None)
239}
240
241fn candidates(file: &str) -> Vec<OsString> {
242 let mut candidates = vec![OsString::from(file)];
243 candidates.extend(
244 directories()
245 .into_iter()
246 .map(|directory| directory.join(file))
247 .filter(|path| path.exists())
248 .map(PathBuf::into_os_string),
249 );
250 candidates
251}
252
253// Where NVIDIA installs libraries on this platform, searched after the system loader's own search.
254fn directories() -> Vec<PathBuf> {
255 let mut roots = ["CUDA_PATH", "CUDA_HOME"]
256 .into_iter()
257 .filter_map(env::var_os)
258 .map(PathBuf::from)
259 .collect::<Vec<_>>();
260 if cfg!(target_os = "windows") {
261 // CUDA 13 moved its DLLs from `bin` to `bin\x64`; the driver's and NVML's are in `System32`, which the system search covers.
262 return roots
263 .iter()
264 .flat_map(|root| [root.join("bin").join("x64"), root.join("bin")])
265 .collect();
266 }
267
268 roots.push(PathBuf::from("/usr/local/cuda"));
269 let mut directories = roots
270 .iter()
271 .flat_map(|root| {
272 ["lib64", "lib", "nvvm/lib64"]
273 .into_iter()
274 .map(|directory| root.join(directory))
275 })
276 .collect::<Vec<_>>();
277 // NixOS puts the driver's libraries here.
278 directories.push(Path::new("/run/opengl-driver/lib").to_path_buf());
279 directories
280}
281
282/// A library or symbol that would not load.
283#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
284#[non_exhaustive]
285pub enum LoadError {
286 /// The library has no files on this platform.
287 #[error("{library} is not available on this platform")]
288 Unsupported {
289 /// Name of the library.
290 library: &'static str,
291 },
292 /// A file of the library would not load, with each place tried and why it failed.
293 #[error("failed to load {library}: {}", describe(attempts))]
294 NotFound {
295 /// Name of the library.
296 library: &'static str,
297 /// Each place tried, in order.
298 attempts: Vec<Attempt>,
299 },
300 /// The library loaded but lacks a symbol, as an older version of it would.
301 #[error("{library} has no symbol `{symbol}`")]
302 MissingSymbol {
303 /// Name of the library.
304 library: &'static str,
305 /// Name of the missing symbol.
306 symbol: &'static str,
307 },
308}
309
310/// One place the loader tried a library file, and why it failed.
311#[derive(Debug, Clone, PartialEq, Eq)]
312#[non_exhaustive]
313pub struct Attempt {
314 /// The path or file name tried.
315 pub path: PathBuf,
316 /// The system loader's reason.
317 pub reason: String,
318}
319
320fn describe(attempts: &[Attempt]) -> String {
321 attempts
322 .iter()
323 .map(|attempt| attempt.reason.clone())
324 .collect::<Vec<_>>()
325 .join("; ")
326}
327
328/// Why a function could not be called.
329#[derive(Debug, Clone, Copy)]
330pub enum Absence {
331 /// Its library would not load.
332 Library(&'static Library),
333 /// Its library loaded but lacks the symbol `name`.
334 Symbol {
335 /// The library looked in.
336 library: &'static Library,
337 /// Name of the missing symbol.
338 name: &'static str,
339 },
340}
341
342impl Absence {
343 /// Returns the library the function belongs to.
344 #[must_use]
345 pub const fn library(self) -> &'static Library {
346 match self {
347 Self::Library(library) | Self::Symbol { library, .. } => library,
348 }
349 }
350
351 /// Returns the error describing this absence.
352 #[must_use]
353 pub fn into_error(self) -> LoadError {
354 match self {
355 Self::Library(library) => match library.load() {
356 Err(error) => error,
357 // A library's load result is cached, so one recorded as absent never loads later.
358 Ok(()) => LoadError::Unsupported {
359 library: library.name,
360 },
361 },
362 Self::Symbol { library, name } => LoadError::MissingSymbol {
363 library: library.name,
364 symbol: name,
365 },
366 }
367 }
368}
369
370thread_local! {
371 static ABSENCE: Cell<Option<Absence>> = const { Cell::new(None) };
372}
373
374/// Returns and clears the absence the last status-returning function called on this thread recorded.
375///
376/// A function whose library or symbol is missing records it before returning its status, and one that runs clears the record.
377#[must_use]
378pub fn take_absence() -> Option<Absence> {
379 ABSENCE.take()
380}
381
382#[doc(hidden)]
383pub fn record_absence(absence: Absence) {
384 ABSENCE.set(Some(absence));
385}
386
387#[doc(hidden)]
388pub fn clear_absence() {
389 ABSENCE.set(None);
390}
391
392/// What a function returns when it cannot be called.
393pub trait Missing: Sized {
394 /// Returns the value standing for a call that could not be made for `absence`.
395 fn missing(absence: Absence) -> Self;
396
397 /// Passes through the result of a call that was made.
398 ///
399 /// Status types override it to clear the thread's recorded absence, so a later failure is not blamed on an earlier missing function.
400 #[doc(hidden)]
401 #[must_use]
402 fn made(self) -> Self {
403 self
404 }
405}
406
407impl Missing for () {
408 fn missing(_: Absence) -> Self {}
409}
410
411impl<T> Missing for *mut T {
412 fn missing(_: Absence) -> Self {
413 ptr::null_mut()
414 }
415}
416
417impl<T> Missing for *const T {
418 fn missing(_: Absence) -> Self {
419 ptr::null()
420 }
421}
422
423macro_rules! missing_zero {
424 ($($integer:ty),*) => {$(
425 impl Missing for $integer {
426 fn missing(_: Absence) -> Self {
427 0
428 }
429 }
430 )*};
431}
432
433missing_zero!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize);
434
435/// Implements [`Missing`] for a library's status type, with the status for a missing library and for a missing symbol.
436///
437/// A missing call records its [`Absence`] for [`take_absence`], and a call that runs clears the record.
438#[macro_export]
439macro_rules! missing_status {
440 ($status:ty, library: $library:expr, symbol: $symbol:expr $(,)?) => {
441 impl $crate::Missing for $status {
442 fn missing(absence: $crate::Absence) -> Self {
443 $crate::record_absence(absence);
444 match absence {
445 $crate::Absence::Library(_) => $library,
446 $crate::Absence::Symbol { .. } => $symbol,
447 }
448 }
449
450 fn made(self) -> Self {
451 $crate::clear_absence();
452 self
453 }
454 }
455 };
456}
457
458/// Implements [`Missing`] for a value type that is not a status, returning `$value` and recording nothing.
459#[macro_export]
460macro_rules! missing_value {
461 ($type:ty, $value:expr $(,)?) => {
462 impl $crate::Missing for $type {
463 fn missing(_: $crate::Absence) -> Self {
464 $value
465 }
466 }
467 };
468}
469
470// The `&CStr` naming a function or variable, for `Library::symbol`.
471#[doc(hidden)]
472#[macro_export]
473macro_rules! symbol_name {
474 ($name:ident) => {{
475 const NAME: &::core::ffi::CStr = match ::core::ffi::CStr::from_bytes_with_nul(
476 ::core::concat!(::core::stringify!($name), "\0").as_bytes(),
477 ) {
478 ::core::result::Result::Ok(name) => name,
479 ::core::result::Result::Err(_) => {
480 ::core::panic!("a symbol name has no interior nul byte")
481 }
482 };
483 NAME
484 }};
485}
486
487/// Turns the declarations of an `extern "C"` block, as bindgen writes them, into functions of the same names and signatures that look up their symbol in `$library` on first call.
488#[macro_export]
489macro_rules! functions {
490 ($library:path; $(
491 $(#[$meta:meta])*
492 pub fn $name:ident($($argument:ident: $type:ty),* $(,)?) $(-> $result:ty)?;
493 )*) => {$(
494 $(#[$meta])*
495 pub unsafe extern "C" fn $name($($argument: $type),*) $(-> $result)? {
496 type Function = unsafe extern "C" fn($($type),*) $(-> $result)?;
497 static FUNCTION: ::std::sync::OnceLock<::core::option::Option<Function>> =
498 ::std::sync::OnceLock::new();
499 // SAFETY: `Function` is the declaration bindgen wrote from the library's header.
500 let function = FUNCTION.get_or_init(|| unsafe {
501 $library.symbol::<Function>($crate::symbol_name!($name))
502 });
503 match function {
504 // SAFETY: `function` has the declared signature, and this function's caller meets the C function's preconditions.
505 ::core::option::Option::Some(function) => $crate::Missing::made(unsafe { function($($argument),*) }),
506 ::core::option::Option::None => $crate::Missing::missing($library.absence(::core::stringify!($name))),
507 }
508 }
509 )*};
510 // A variable the library exports, read through a function of its name, since its value is only known once the library loads.
511 ($library:path; $(#[$meta:meta])* pub static $name:ident: $type:ty;) => {
512 $(#[$meta])*
513 pub unsafe fn $name() -> $type {
514 // The variable's address, kept as an exposed integer so the cache can be shared between threads.
515 static ADDRESS: ::std::sync::OnceLock<::core::option::Option<usize>> =
516 ::std::sync::OnceLock::new();
517 // SAFETY: the variable is declared with the type bindgen wrote from the library's header.
518 let address = ADDRESS.get_or_init(|| unsafe {
519 $library
520 .symbol::<*const $type>($crate::symbol_name!($name))
521 .map(<*const $type>::expose_provenance)
522 });
523 match address {
524 // SAFETY: the address is the loaded library's variable, which stays loaded for the life of the process.
525 ::core::option::Option::Some(address) => unsafe {
526 *::core::ptr::with_exposed_provenance::<$type>(*address)
527 },
528 ::core::option::Option::None => {
529 $crate::Missing::missing($library.absence(::core::stringify!($name)))
530 }
531 }
532 }
533 };
534}