use crate::Result;
use libloading::{Library, Symbol};
use std::sync::Mutex;
pub struct LibHandle(Mutex<Library>);
impl LibHandle {
#[cfg(windows)]
fn load_library(path: &str) -> std::result::Result<Library, libloading::Error> {
use libloading::os::windows::{
Library as WindowsLibrary, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS,
LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR,
};
if path.contains('\\') || path.contains('/') {
unsafe {
WindowsLibrary::load_with_flags(
path,
LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS,
)
.map(Into::into)
}
} else {
unsafe { Library::new(path) }
}
}
#[cfg(not(windows))]
fn load_library(path: &str) -> std::result::Result<Library, libloading::Error> {
unsafe { Library::new(path) }
}
pub fn new(name: &str, end: Option<&str>) -> Result<LibHandle> {
let ext = if cfg!(windows) {
".dll"
} else if cfg!(target_os = "macos") {
".dylib"
} else {
".so"
};
let lib_name = format!("{}{}{}", name, ext, end.unwrap_or(""));
let mut lib_paths = vec![lib_name.clone()];
if cfg!(windows) {
lib_paths.push(format!("C:\\radare2\\bin\\{}", lib_name));
if let Ok(entries) = std::fs::read_dir("C:\\radare2") {
for entry in entries.flatten() {
if entry.file_type().is_ok_and(|ft| ft.is_dir()) {
let version_path = format!("{}\\bin\\{}", entry.path().display(), lib_name);
lib_paths.push(version_path);
}
}
}
}
for lib_path in &lib_paths {
if let Ok(lib) = Self::load_library(lib_path) {
return Ok(LibHandle(Mutex::new(lib)));
}
}
Err(Self::load_library(&lib_paths[0]).unwrap_err().into())
}
pub unsafe fn load_sym<T>(&mut self, name: &str) -> Result<T> {
let lib = self.0.lock().unwrap();
let sym: Symbol<T> = lib.get(name.as_bytes())?;
Ok(std::mem::transmute_copy::<_, T>(&*sym))
}
}