use libc::{c_int, c_void, dlclose, dlerror, dlopen, dlsym, RTLD_LAZY, RTLD_LOCAL};
use std::ffi::{CStr, OsStr};
use std::io::{Error as IoError, ErrorKind};
use std::os::unix::ffi::OsStrExt;
use std::ptr::null_mut;
use crate::Error;
const DEFAULT_FLAGS: c_int = RTLD_LOCAL | RTLD_LAZY;
use std::sync::Mutex;
lazy_static! {
static ref DLERROR_MUTEX: Mutex<()> = Mutex::new(());
}
pub type Handle = *mut c_void;
#[inline]
pub unsafe fn get_sym(handle: Handle, name: &CStr) -> Result<*mut (), Error> {
let _lock = DLERROR_MUTEX.lock();
let _ = dlerror();
let symbol = dlsym(handle, name.as_ptr());
if symbol.is_null() {
let msg = dlerror();
if !msg.is_null() {
return Err(Error::SymbolGettingError(IoError::new(
ErrorKind::Other,
CStr::from_ptr(msg).to_string_lossy().to_string(),
)));
}
}
Ok(symbol as *mut ())
}
#[inline]
pub unsafe fn open_lib(name: &OsStr) -> Result<Handle, Error> {
let mut v: Vec<u8> = Vec::new();
let cstr = if name.len() > 0 && name.as_bytes()[name.len() - 1] == 0 {
CStr::from_bytes_with_nul_unchecked(name.as_bytes())
} else {
v.extend_from_slice(name.as_bytes());
v.push(0);
CStr::from_bytes_with_nul_unchecked(v.as_slice())
};
let _lock = DLERROR_MUTEX.lock();
let handle = dlopen(cstr.as_ptr(), DEFAULT_FLAGS);
if handle.is_null() {
Err(Error::OpeningLibraryError(IoError::new(
ErrorKind::Other,
CStr::from_ptr(dlerror()).to_string_lossy().to_string(),
)))
} else {
Ok(handle)
}
}
#[inline]
pub fn close_lib(handle: Handle) -> Handle {
let result = unsafe { dlclose(handle) };
if result != 0 {
panic!("Call to dlclose() failed");
}
null_mut()
}