Skip to main content

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