mod libraries;
use std::{
env,
ffi::OsString,
fmt,
path::{Path, PathBuf},
ptr,
sync::OnceLock,
};
pub struct Library {
name: &'static str,
files: &'static [&'static str],
loaded: OnceLock<Result<Vec<File>, LoadError>>,
}
struct File {
library: libloading::Library,
path: PathBuf,
}
impl Library {
#[must_use]
pub const fn new(name: &'static str, files: &'static [&'static str]) -> Self {
Self {
name,
files,
loaded: OnceLock::new(),
}
}
#[must_use]
pub const fn name(&self) -> &'static str {
self.name
}
pub fn load(&self) -> Result<(), LoadError> {
self.files().map(|_| ())
}
pub fn paths(&self) -> Result<Vec<PathBuf>, LoadError> {
Ok(self.files()?.iter().map(|file| file.path.clone()).collect())
}
fn files(&self) -> Result<&[File], LoadError> {
self.loaded
.get_or_init(|| {
if self.files.is_empty() {
return Err(LoadError {
name: self.name,
attempts: Vec::new(),
});
}
self.files
.iter()
.map(|file| open(self.name, file))
.collect()
})
.as_deref()
.map_err(Clone::clone)
}
#[must_use]
pub unsafe fn symbol<F: Copy>(&self, name: &str) -> Option<F> {
let files = self.files().ok()?;
files.iter().find_map(|file| {
unsafe { file.library.get::<F>(name.as_bytes()) }
.ok()
.map(|symbol| *symbol)
})
}
#[must_use]
pub fn absence(&self) -> Absence {
if self.files().is_ok() {
Absence::Symbol
} else {
Absence::Library
}
}
}
impl fmt::Debug for Library {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("Library")
.field("name", &self.name)
.field("files", &self.files)
.finish_non_exhaustive()
}
}
fn open(name: &'static str, file: &'static str) -> Result<File, LoadError> {
let mut attempts = Vec::new();
for candidate in candidates(file) {
match unsafe { libloading::Library::new(&candidate) } {
Ok(library) => {
let (library, path) = locate(library);
return Ok(File {
path: path.unwrap_or_else(|| PathBuf::from(&candidate)),
library,
});
}
Err(error) => attempts.push(Attempt {
path: PathBuf::from(candidate),
reason: error.to_string(),
}),
}
}
Err(LoadError { name, attempts })
}
#[cfg(target_os = "linux")]
fn locate(library: libloading::Library) -> (libloading::Library, Option<PathBuf>) {
use std::{
ffi::{CStr, OsStr, c_char, c_int, c_void},
os::unix::ffi::OsStrExt,
};
use libloading::os::unix::Library as UnixLibrary;
#[repr(C)]
struct LinkMap {
address: usize,
name: *const c_char,
}
const RTLD_DI_LINKMAP: c_int = 2;
#[link(name = "dl")]
unsafe extern "C" {
fn dlinfo(handle: *mut c_void, request: c_int, info: *mut c_void) -> c_int;
}
let handle = UnixLibrary::from(library).into_raw();
let mut map: *const LinkMap = ptr::null();
let found = unsafe { dlinfo(handle, RTLD_DI_LINKMAP, (&raw mut map).cast()) } == 0;
let path = (found && !map.is_null())
.then(|| {
let name = unsafe { CStr::from_ptr((*map).name) };
(!name.is_empty()).then(|| PathBuf::from(OsStr::from_bytes(name.to_bytes())))
})
.flatten();
let library = unsafe { UnixLibrary::from_raw(handle) }.into();
(library, path)
}
#[cfg(not(target_os = "linux"))]
fn locate(library: libloading::Library) -> (libloading::Library, Option<PathBuf>) {
(library, None)
}
fn candidates(file: &str) -> Vec<OsString> {
let mut candidates = vec![OsString::from(file)];
candidates.extend(
directories()
.into_iter()
.map(|directory| directory.join(file))
.filter(|path| path.exists())
.map(PathBuf::into_os_string),
);
candidates
}
fn directories() -> Vec<PathBuf> {
let mut roots = ["CUDA_PATH", "CUDA_HOME"]
.into_iter()
.filter_map(env::var_os)
.map(PathBuf::from)
.collect::<Vec<_>>();
if cfg!(target_os = "windows") {
return roots
.iter()
.flat_map(|root| [root.join("bin").join("x64"), root.join("bin")])
.collect();
}
roots.push(PathBuf::from("/usr/local/cuda"));
let mut directories = roots
.iter()
.flat_map(|root| {
["lib64", "lib", "nvvm/lib64"]
.into_iter()
.map(|directory| root.join(directory))
})
.collect::<Vec<_>>();
directories.push(Path::new("/run/opengl-driver/lib").to_path_buf());
directories
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("failed to load {name}: {}", describe(attempts))]
pub struct LoadError {
pub name: &'static str,
pub attempts: Vec<Attempt>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Attempt {
pub path: PathBuf,
pub reason: String,
}
fn describe(attempts: &[Attempt]) -> String {
if attempts.is_empty() {
return "it has no library on this platform".to_owned();
}
attempts
.iter()
.map(|attempt| attempt.reason.clone())
.collect::<Vec<_>>()
.join("; ")
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Absence {
Library,
Symbol,
}
pub trait Missing {
fn missing(absence: Absence) -> Self;
}
impl Missing for () {
fn missing(_: Absence) -> Self {}
}
impl<T> Missing for *mut T {
fn missing(_: Absence) -> Self {
ptr::null_mut()
}
}
impl<T> Missing for *const T {
fn missing(_: Absence) -> Self {
ptr::null()
}
}
macro_rules! missing_zero {
($($integer:ty),*) => {$(
impl Missing for $integer {
fn missing(_: Absence) -> Self {
0
}
}
)*};
}
missing_zero!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize);
#[macro_export]
macro_rules! missing_status {
($status:ty, library: $library:expr, symbol: $symbol:expr $(,)?) => {
impl $crate::Missing for $status {
fn missing(absence: $crate::Absence) -> Self {
match absence {
$crate::Absence::Library => $library,
$crate::Absence::Symbol => $symbol,
}
}
}
};
}
#[macro_export]
macro_rules! functions {
($library:path; $(
$(#[$meta:meta])*
pub fn $name:ident($($argument:ident: $type:ty),* $(,)?) $(-> $result:ty)?;
)*) => {$(
$(#[$meta])*
pub unsafe extern "C" fn $name($($argument: $type),*) $(-> $result)? {
type Function = unsafe extern "C" fn($($type),*) $(-> $result)?;
static FUNCTION: ::std::sync::OnceLock<::core::option::Option<Function>> =
::std::sync::OnceLock::new();
let function = FUNCTION.get_or_init(|| unsafe {
$library.symbol::<Function>(::core::concat!(::core::stringify!($name), "\0"))
});
match function {
::core::option::Option::Some(function) => unsafe { function($($argument),*) },
::core::option::Option::None => $crate::Missing::missing($library.absence()),
}
}
)*};
($library:path; $(#[$meta:meta])* pub static $name:ident: $type:ty;) => {
$(#[$meta])*
pub unsafe fn $name() -> $type {
static ADDRESS: ::std::sync::OnceLock<::core::option::Option<usize>> =
::std::sync::OnceLock::new();
let address = ADDRESS.get_or_init(|| unsafe {
$library
.symbol::<*const $type>(::core::concat!(::core::stringify!($name), "\0"))
.map(|address| address as usize)
});
match address {
::core::option::Option::Some(address) => unsafe { *(*address as *const $type) },
::core::option::Option::None => $crate::Missing::missing($library.absence()),
}
}
};
}