use std::path::{Path, PathBuf};
use libloading::Library;
use crate::error::{KitError, KitResult};
pub struct LoadedPlugin<T> {
_lib: Library,
entry: *const T,
path: PathBuf,
}
impl<T> LoadedPlugin<T> {
pub fn entry(&self) -> *const T {
self.entry
}
pub fn path(&self) -> &Path {
&self.path
}
}
pub unsafe fn open<T>(path: &Path, symbol: &[u8]) -> KitResult<LoadedPlugin<T>> {
let lib = Library::new(path).map_err(|source| KitError::LibraryLoad {
path: path.to_path_buf(),
source: Box::new(source),
})?;
let entry = {
let f: libloading::Symbol<'_, unsafe extern "C" fn() -> *const T> =
lib.get(symbol).map_err(|source| {
if is_symbol_not_found(&source) {
KitError::SymbolMissing {
symbol: String::from_utf8_lossy(symbol).into_owned(),
}
} else {
KitError::LibraryLoad {
path: path.to_path_buf(),
source: Box::new(source),
}
}
})?;
f()
};
if entry.is_null() {
return Err(KitError::NullEntry);
}
Ok(LoadedPlugin {
_lib: lib,
entry,
path: path.to_path_buf(),
})
}
fn is_symbol_not_found(e: &libloading::Error) -> bool {
#[cfg(unix)]
{
matches!(
e,
libloading::Error::DlSym { .. } | libloading::Error::DlSymUnknown
)
}
#[cfg(windows)]
{
matches!(
e,
libloading::Error::GetProcAddress { .. } | libloading::Error::GetProcAddressUnknown
)
}
#[cfg(not(any(unix, windows)))]
{
let _ = e;
false
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn opening_a_non_library_reports_an_error() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("garbage.bin");
std::fs::write(&path, b"this is not a shared object").unwrap();
let got = unsafe { open::<u32>(&path, b"whatever") };
assert!(
matches!(got, Err(KitError::LibraryLoad { .. })),
"expected LibraryLoad, got {:?}",
got.err()
);
}
}