use core::{
ffi::{CStr, c_void},
fmt,
marker::PhantomData,
ptr::NonNull,
};
pub const SUPPORTED: bool = cfg!(any(
all(target_os = "linux", not(all(target_env = "musl", target_feature = "crt-static"))),
target_os = "macos",
windows
));
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Error {
Unsupported,
LoadFailed,
Closed,
MissingSymbol,
CloseFailed,
InvalidPath,
}
impl fmt::Display for Error {
fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result {
out.write_str(match self {
Self::Unsupported => "native dynamic loading is unavailable on this target",
Self::LoadFailed => "the native library could not be loaded",
Self::Closed => "the native library handle is closed",
Self::MissingSymbol => "the native symbol was not found",
Self::CloseFailed => "the native library could not be closed",
Self::InvalidPath => "the native path is not correctly NUL terminated",
})
}
}
impl core::error::Error for Error {}
pub struct Library {
handle: Option<NonNull<c_void>>,
_local: PhantomData<*mut ()>,
}
impl Library {
pub unsafe fn open(path: &CStr) -> Result<Self, Error> {
if !SUPPORTED {
return Err(Error::Unsupported);
}
let handle = unsafe { platform::open(path.as_ptr()) };
Self::from_opened(handle)
}
#[cfg(windows)]
pub unsafe fn open_wide(path: &[u16]) -> Result<Self, Error> {
if path.last() != Some(&0) || path[..path.len().saturating_sub(1)].contains(&0) {
return Err(Error::InvalidPath);
}
Self::from_opened(unsafe { platform::open_wide(path.as_ptr()) })
}
fn from_opened(handle: *mut c_void) -> Result<Self, Error> {
NonNull::new(handle).map(|handle| Self { handle: Some(handle), _local: PhantomData }).ok_or(Error::LoadFailed)
}
pub fn symbol(&self, name: &CStr) -> Result<*mut c_void, Error> {
let handle = self.handle.ok_or(Error::Closed)?;
NonNull::new(unsafe { platform::symbol(handle.as_ptr(), name.as_ptr()) })
.map(NonNull::as_ptr)
.ok_or(Error::MissingSymbol)
}
pub fn same_image(&self, other: &Self) -> bool {
self.handle.is_some() && self.handle == other.handle
}
pub fn is_open(&self) -> bool {
self.handle.is_some()
}
pub unsafe fn close(&mut self) -> Result<(), Error> {
if let Some(handle) = self.handle {
if !unsafe { platform::close(handle.as_ptr()) } {
return Err(Error::CloseFailed);
}
self.handle = None;
}
Ok(())
}
}
#[cfg(any(
all(target_os = "linux", not(all(target_env = "musl", target_feature = "crt-static"))),
target_os = "macos"
))]
mod platform {
use core::ffi::{c_char, c_int, c_void};
#[cfg_attr(target_os = "linux", link(name = "dl"))]
unsafe extern "C" {
fn dlopen(path: *const c_char, mode: c_int) -> *mut c_void;
fn dlsym(handle: *mut c_void, name: *const c_char) -> *mut c_void;
fn dlclose(handle: *mut c_void) -> c_int;
}
pub unsafe fn open(path: *const c_char) -> *mut c_void {
#[cfg(target_os = "macos")]
const LOCAL: c_int = 4;
#[cfg(target_os = "linux")]
const LOCAL: c_int = 0;
unsafe { dlopen(path, 2 | LOCAL) }
}
pub unsafe fn symbol(handle: *mut c_void, name: *const c_char) -> *mut c_void {
unsafe { dlsym(handle, name) }
}
pub unsafe fn close(handle: *mut c_void) -> bool {
unsafe { dlclose(handle) == 0 }
}
}
#[cfg(windows)]
mod platform {
use core::ffi::{c_char, c_void};
#[link(name = "kernel32")]
unsafe extern "system" {
fn LoadLibraryExA(path: *const c_char, file: *mut c_void, flags: u32) -> *mut c_void;
fn LoadLibraryExW(path: *const u16, file: *mut c_void, flags: u32) -> *mut c_void;
fn GetProcAddress(handle: *mut c_void, name: *const c_char) -> *mut c_void;
fn FreeLibrary(handle: *mut c_void) -> i32;
}
const SEARCH_DEFAULT_DIRS: u32 = 0x1000;
pub unsafe fn open(path: *const c_char) -> *mut c_void {
unsafe { LoadLibraryExA(path, core::ptr::null_mut(), SEARCH_DEFAULT_DIRS) }
}
pub unsafe fn open_wide(path: *const u16) -> *mut c_void {
unsafe { LoadLibraryExW(path, core::ptr::null_mut(), SEARCH_DEFAULT_DIRS) }
}
pub unsafe fn symbol(handle: *mut c_void, name: *const c_char) -> *mut c_void {
unsafe { GetProcAddress(handle, name) }
}
pub unsafe fn close(handle: *mut c_void) -> bool {
unsafe { FreeLibrary(handle) != 0 }
}
}
#[cfg(not(any(
all(target_os = "linux", not(all(target_env = "musl", target_feature = "crt-static"))),
target_os = "macos",
windows
)))]
mod platform {
use core::ffi::{c_char, c_void};
pub unsafe fn open(_: *const c_char) -> *mut c_void {
core::ptr::null_mut()
}
pub unsafe fn symbol(_: *mut c_void, _: *const c_char) -> *mut c_void {
core::ptr::null_mut()
}
pub unsafe fn close(_: *mut c_void) -> bool {
false
}
}