Skip to main content

singe_loader/
lib.rs

1// Loads NVIDIA libraries at run time, so a crate that calls them builds without them and its binary starts without them.
2// A missing library or symbol becomes a value of the function's return type, never a failed link or start.
3
4mod libraries;
5
6use std::{
7    env,
8    ffi::OsString,
9    fmt,
10    path::{Path, PathBuf},
11    ptr,
12    sync::OnceLock,
13};
14
15// One library behind a set of declarations, made of every file in `files`, each of which must load.
16// A symbol is looked up in each file in order, as NPP's functions are spread over eleven.
17// The NVIDIA libraries have constructors of their own, such as `Library::cusparse`, which name their files on each platform.
18pub struct Library {
19    name: &'static str,
20    files: &'static [&'static str],
21    loaded: OnceLock<Result<Vec<File>, LoadError>>,
22}
23
24// A file of a library, loaded, and where the loader found it.
25struct File {
26    library: libloading::Library,
27    path: PathBuf,
28}
29
30impl Library {
31    #[must_use]
32    pub const fn new(name: &'static str, files: &'static [&'static str]) -> Self {
33        Self {
34            name,
35            files,
36            loaded: OnceLock::new(),
37        }
38    }
39
40    #[must_use]
41    pub const fn name(&self) -> &'static str {
42        self.name
43    }
44
45    // Loads every file once, and keeps them loaded for the life of the process, which every cached function relies on.
46    pub fn load(&self) -> Result<(), LoadError> {
47        self.files().map(|_| ())
48    }
49
50    // Where each file loaded from, in order, loading them if they are not yet.
51    pub fn paths(&self) -> Result<Vec<PathBuf>, LoadError> {
52        Ok(self.files()?.iter().map(|file| file.path.clone()).collect())
53    }
54
55    fn files(&self) -> Result<&[File], LoadError> {
56        self.loaded
57            .get_or_init(|| {
58                if self.files.is_empty() {
59                    return Err(LoadError {
60                        name: self.name,
61                        attempts: Vec::new(),
62                    });
63                }
64
65                self.files
66                    .iter()
67                    .map(|file| open(self.name, file))
68                    .collect()
69            })
70            .as_deref()
71            .map_err(Clone::clone)
72    }
73
74    // Looks up `name`, a symbol's name ending in a nul byte, as a function of type `F`.
75    //
76    // # Safety
77    //
78    // `F` must be the symbol's actual type.
79    #[must_use]
80    pub unsafe fn symbol<F: Copy>(&self, name: &str) -> Option<F> {
81        let files = self.files().ok()?;
82        files.iter().find_map(|file| {
83            // SAFETY: the caller guarantees `F` is the symbol's type, and `files` keeps the library loaded.
84            unsafe { file.library.get::<F>(name.as_bytes()) }
85                .ok()
86                .map(|symbol| *symbol)
87        })
88    }
89
90    // Why a function of this library is missing: its library, or only its symbol.
91    #[must_use]
92    pub fn absence(&self) -> Absence {
93        if self.files().is_ok() {
94            Absence::Symbol
95        } else {
96            Absence::Library
97        }
98    }
99}
100
101impl fmt::Debug for Library {
102    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
103        formatter
104            .debug_struct("Library")
105            .field("name", &self.name)
106            .field("files", &self.files)
107            .finish_non_exhaustive()
108    }
109}
110
111// Opens `file` by name, through the system loader's search, and then in the directories NVIDIA installs to.
112fn open(name: &'static str, file: &'static str) -> Result<File, LoadError> {
113    let mut attempts = Vec::new();
114    for candidate in candidates(file) {
115        // SAFETY: loading an NVIDIA library runs only its initializers, which have no preconditions.
116        match unsafe { libloading::Library::new(&candidate) } {
117            Ok(library) => {
118                let (library, path) = locate(library);
119                return Ok(File {
120                    path: path.unwrap_or_else(|| PathBuf::from(&candidate)),
121                    library,
122                });
123            }
124            Err(error) => attempts.push(Attempt {
125                path: PathBuf::from(candidate),
126                reason: error.to_string(),
127            }),
128        }
129    }
130    Err(LoadError { name, attempts })
131}
132
133// Asks the Linux loader for the file it opened, which a bare file name does not say.
134#[cfg(target_os = "linux")]
135fn locate(library: libloading::Library) -> (libloading::Library, Option<PathBuf>) {
136    use std::{
137        ffi::{CStr, OsStr, c_char, c_int, c_void},
138        os::unix::ffi::OsStrExt,
139    };
140
141    use libloading::os::unix::Library as UnixLibrary;
142
143    // The start of glibc's `struct link_map`, which is all `dlinfo` callers may read.
144    #[repr(C)]
145    struct LinkMap {
146        address: usize,
147        name: *const c_char,
148    }
149
150    const RTLD_DI_LINKMAP: c_int = 2;
151
152    #[link(name = "dl")]
153    unsafe extern "C" {
154        fn dlinfo(handle: *mut c_void, request: c_int, info: *mut c_void) -> c_int;
155    }
156
157    let handle = UnixLibrary::from(library).into_raw();
158    let mut map: *const LinkMap = ptr::null();
159    // SAFETY: `handle` is a live handle `dlopen` returned, and `RTLD_DI_LINKMAP` writes one pointer to `map`.
160    let found = unsafe { dlinfo(handle, RTLD_DI_LINKMAP, (&raw mut map).cast()) } == 0;
161    let path = (found && !map.is_null())
162        .then(|| {
163            // SAFETY: the loader owns the map and its nul-terminated name while the library stays loaded.
164            let name = unsafe { CStr::from_ptr((*map).name) };
165            (!name.is_empty()).then(|| PathBuf::from(OsStr::from_bytes(name.to_bytes())))
166        })
167        .flatten();
168    // SAFETY: `handle` came from `into_raw` above and is owned again here.
169    let library = unsafe { UnixLibrary::from_raw(handle) }.into();
170    (library, path)
171}
172
173#[cfg(not(target_os = "linux"))]
174fn locate(library: libloading::Library) -> (libloading::Library, Option<PathBuf>) {
175    (library, None)
176}
177
178fn candidates(file: &str) -> Vec<OsString> {
179    let mut candidates = vec![OsString::from(file)];
180    candidates.extend(
181        directories()
182            .into_iter()
183            .map(|directory| directory.join(file))
184            .filter(|path| path.exists())
185            .map(PathBuf::into_os_string),
186    );
187    candidates
188}
189
190// Where NVIDIA installs libraries on this platform, searched after the system loader's own search.
191fn directories() -> Vec<PathBuf> {
192    let mut roots = ["CUDA_PATH", "CUDA_HOME"]
193        .into_iter()
194        .filter_map(env::var_os)
195        .map(PathBuf::from)
196        .collect::<Vec<_>>();
197    if cfg!(target_os = "windows") {
198        // CUDA 13 moved its DLLs from `bin` to `bin\x64`; the driver's and NVML's are in `System32`, which the system search covers.
199        return roots
200            .iter()
201            .flat_map(|root| [root.join("bin").join("x64"), root.join("bin")])
202            .collect();
203    }
204
205    roots.push(PathBuf::from("/usr/local/cuda"));
206    let mut directories = roots
207        .iter()
208        .flat_map(|root| {
209            ["lib64", "lib", "nvvm/lib64"]
210                .into_iter()
211                .map(|directory| root.join(directory))
212        })
213        .collect::<Vec<_>>();
214    // NixOS puts the driver's libraries here.
215    directories.push(Path::new("/run/opengl-driver/lib").to_path_buf());
216    directories
217}
218
219// A library that would not load, with each place tried and why it failed.
220#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
221#[error("failed to load {name}: {}", describe(attempts))]
222pub struct LoadError {
223    pub name: &'static str,
224    pub attempts: Vec<Attempt>,
225}
226
227#[derive(Debug, Clone, PartialEq, Eq)]
228pub struct Attempt {
229    pub path: PathBuf,
230    pub reason: String,
231}
232
233fn describe(attempts: &[Attempt]) -> String {
234    if attempts.is_empty() {
235        return "it has no library on this platform".to_owned();
236    }
237
238    attempts
239        .iter()
240        .map(|attempt| attempt.reason.clone())
241        .collect::<Vec<_>>()
242        .join("; ")
243}
244
245// Why a function could not be called.
246#[derive(Debug, Clone, Copy, PartialEq, Eq)]
247pub enum Absence {
248    Library,
249    Symbol,
250}
251
252// What a function returns when it cannot be called.
253pub trait Missing {
254    fn missing(absence: Absence) -> Self;
255}
256
257impl Missing for () {
258    fn missing(_: Absence) -> Self {}
259}
260
261impl<T> Missing for *mut T {
262    fn missing(_: Absence) -> Self {
263        ptr::null_mut()
264    }
265}
266
267impl<T> Missing for *const T {
268    fn missing(_: Absence) -> Self {
269        ptr::null()
270    }
271}
272
273macro_rules! missing_zero {
274    ($($integer:ty),*) => {$(
275        impl Missing for $integer {
276            fn missing(_: Absence) -> Self {
277                0
278            }
279        }
280    )*};
281}
282
283missing_zero!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize);
284
285// Implements `Missing` for a library's status type, with the status for a missing library and for a missing symbol.
286#[macro_export]
287macro_rules! missing_status {
288    ($status:ty, library: $library:expr, symbol: $symbol:expr $(,)?) => {
289        impl $crate::Missing for $status {
290            fn missing(absence: $crate::Absence) -> Self {
291                match absence {
292                    $crate::Absence::Library => $library,
293                    $crate::Absence::Symbol => $symbol,
294                }
295            }
296        }
297    };
298}
299
300// 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.
301#[macro_export]
302macro_rules! functions {
303    ($library:path; $(
304        $(#[$meta:meta])*
305        pub fn $name:ident($($argument:ident: $type:ty),* $(,)?) $(-> $result:ty)?;
306    )*) => {$(
307        $(#[$meta])*
308        pub unsafe extern "C" fn $name($($argument: $type),*) $(-> $result)? {
309            type Function = unsafe extern "C" fn($($type),*) $(-> $result)?;
310            static FUNCTION: ::std::sync::OnceLock<::core::option::Option<Function>> =
311                ::std::sync::OnceLock::new();
312            // SAFETY: `Function` is the declaration bindgen wrote from the library's header.
313            let function = FUNCTION.get_or_init(|| unsafe {
314                $library.symbol::<Function>(::core::concat!(::core::stringify!($name), "\0"))
315            });
316            match function {
317                // SAFETY: the caller upholds the C function's contract.
318                ::core::option::Option::Some(function) => unsafe { function($($argument),*) },
319                ::core::option::Option::None => $crate::Missing::missing($library.absence()),
320            }
321        }
322    )*};
323    // A variable the library exports, read through a function of its name, since its value is only known once the library loads.
324    ($library:path; $(#[$meta:meta])* pub static $name:ident: $type:ty;) => {
325        $(#[$meta])*
326        pub unsafe fn $name() -> $type {
327            // The variable's address, kept as an integer so the cache can be shared between threads.
328            static ADDRESS: ::std::sync::OnceLock<::core::option::Option<usize>> =
329                ::std::sync::OnceLock::new();
330            // SAFETY: the variable is declared with the type bindgen wrote from the library's header.
331            let address = ADDRESS.get_or_init(|| unsafe {
332                $library
333                    .symbol::<*const $type>(::core::concat!(::core::stringify!($name), "\0"))
334                    .map(|address| address as usize)
335            });
336            match address {
337                // SAFETY: the address is the loaded library's variable, which stays loaded.
338                ::core::option::Option::Some(address) => unsafe { *(*address as *const $type) },
339                ::core::option::Option::None => $crate::Missing::missing($library.absence()),
340            }
341        }
342    };
343}