use core::ffi::{CStr, c_void};
use core::ptr::NonNull;
use nadir_sys::dynlib;
use nadir_sys::linux::libc::{RTLD_LOCAL, RTLD_NOW, dlerror, dlopen, dlsym};
pub(super) struct Library {
handle: NonNull<c_void>,
}
impl Library {
pub(super) unsafe fn open(name: &CStr) -> Result<Self, String> {
let handle = unsafe { dlopen(name.as_ptr(), RTLD_NOW | RTLD_LOCAL) };
match NonNull::new(handle) {
Some(handle) => Ok(Self { handle }),
None => Err(last_error()),
}
}
}
fn last_error() -> String {
let message = dlerror();
if message.is_null() {
return "the loader gave no reason".to_string();
}
let message = unsafe { CStr::from_ptr(message) };
message.to_string_lossy().into_owned()
}
impl dynlib::Library for Library {
fn symbol(&self, name: &CStr) -> *const c_void {
unsafe { dlsym(self.handle.as_ptr(), name.as_ptr()) }
}
}
#[cfg(test)]
mod tests {
use nadir_sys::dynlib::Library as _;
use super::*;
#[test]
fn a_loaded_library_finds_its_symbols_and_no_others() {
let libc = unsafe { Library::open(c"libc.so.6") }.unwrap();
assert!(!libc.symbol(c"malloc").is_null());
assert!(libc.symbol(c"nadir_platform_has_no_such_symbol").is_null());
}
#[test]
fn a_missing_library_gives_the_loaders_reason() {
let result = unsafe { Library::open(c"libnadir-platform-has-no-such-library.so.0") };
let reason = result.err().unwrap();
assert!(
reason.contains("libnadir-platform-has-no-such-library.so.0"),
"{reason}"
);
}
}