1mod libraries;
5
6use std::{
7 env,
8 ffi::OsString,
9 fmt,
10 path::{Path, PathBuf},
11 ptr,
12 sync::OnceLock,
13};
14
15pub struct Library {
19 name: &'static str,
20 files: &'static [&'static str],
21 loaded: OnceLock<Result<Vec<File>, LoadError>>,
22}
23
24struct 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 pub fn load(&self) -> Result<(), LoadError> {
47 self.files().map(|_| ())
48 }
49
50 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 #[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 unsafe { file.library.get::<F>(name.as_bytes()) }
85 .ok()
86 .map(|symbol| *symbol)
87 })
88 }
89
90 #[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
111fn open(name: &'static str, file: &'static str) -> Result<File, LoadError> {
113 let mut attempts = Vec::new();
114 for candidate in candidates(file) {
115 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#[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 #[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 let found = unsafe { dlinfo(handle, RTLD_DI_LINKMAP, (&raw mut map).cast()) } == 0;
161 let path = (found && !map.is_null())
162 .then(|| {
163 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 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
190fn 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 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 directories.push(Path::new("/run/opengl-driver/lib").to_path_buf());
216 directories
217}
218
219#[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
247pub enum Absence {
248 Library,
249 Symbol,
250}
251
252pub 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#[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#[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 let function = FUNCTION.get_or_init(|| unsafe {
314 $library.symbol::<Function>(::core::concat!(::core::stringify!($name), "\0"))
315 });
316 match function {
317 ::core::option::Option::Some(function) => unsafe { function($($argument),*) },
319 ::core::option::Option::None => $crate::Missing::missing($library.absence()),
320 }
321 }
322 )*};
323 ($library:path; $(#[$meta:meta])* pub static $name:ident: $type:ty;) => {
325 $(#[$meta])*
326 pub unsafe fn $name() -> $type {
327 static ADDRESS: ::std::sync::OnceLock<::core::option::Option<usize>> =
329 ::std::sync::OnceLock::new();
330 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 ::core::option::Option::Some(address) => unsafe { *(*address as *const $type) },
339 ::core::option::Option::None => $crate::Missing::missing($library.absence()),
340 }
341 }
342 };
343}