1 //! Dynamic library facilities.
3 //! A simple wrapper over the platform's dynamic library facilities
8 pub struct DynamicLibrary {
12 impl Drop for DynamicLibrary {
15 dl::close(self.handle)
21 /// Lazily open a dynamic library. When passed None it gives a
22 /// handle to the calling process
23 pub fn open(filename: Option<&Path>) -> Result<DynamicLibrary, String> {
24 let maybe_library = dl::open(filename.map(|path| path.as_os_str()));
26 // The dynamic library must not be constructed if there is
27 // an error opening the library so the destructor does not
31 Ok(handle) => Ok(DynamicLibrary { handle })
35 /// Loads a dynamic library into the global namespace (RTLD_GLOBAL on Unix)
36 /// and do it now (don't use RTLD_LAZY on Unix).
37 pub fn open_global_now(filename: &Path) -> Result<DynamicLibrary, String> {
38 let maybe_library = dl::open_global_now(filename.as_os_str());
41 Ok(handle) => Ok(DynamicLibrary { handle })
45 /// Returns the environment variable for this process's dynamic library
47 pub fn envvar() -> &'static str {
50 } else if cfg!(target_os = "macos") {
52 } else if cfg!(target_os = "haiku") {
59 /// Accesses the value at the symbol of the dynamic library.
60 pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<*mut T, String> {
61 // This function should have a lifetime constraint of 'a on
62 // T but that feature is still unimplemented
64 let raw_string = CString::new(symbol).unwrap();
65 let maybe_symbol_value = dl::symbol(self.handle, raw_string.as_ptr());
67 // The value must not be constructed if there is an error so
68 // the destructor does not run.
69 match maybe_symbol_value {
71 Ok(symbol_value) => Ok(symbol_value as *mut T)
81 use std::ffi::{CStr, OsStr, CString};
82 use std::os::unix::prelude::*;
86 pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
87 check_for_errors_in(|| {
90 Some(filename) => open_external(filename),
91 None => open_internal(),
97 pub fn open_global_now(filename: &OsStr) -> Result<*mut u8, String> {
98 check_for_errors_in(|| unsafe {
99 let s = CString::new(filename.as_bytes()).unwrap();
100 libc::dlopen(s.as_ptr(), libc::RTLD_GLOBAL | libc::RTLD_NOW) as *mut u8
104 unsafe fn open_external(filename: &OsStr) -> *mut u8 {
105 let s = CString::new(filename.as_bytes()).unwrap();
106 libc::dlopen(s.as_ptr(), libc::RTLD_LAZY) as *mut u8
109 unsafe fn open_internal() -> *mut u8 {
110 libc::dlopen(ptr::null(), libc::RTLD_LAZY) as *mut u8
113 pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where
116 use std::sync::{Mutex, Once};
117 static INIT: Once = Once::new();
118 static mut LOCK: *mut Mutex<()> = ptr::null_mut();
121 LOCK = Box::into_raw(Box::new(Mutex::new(())));
123 // dlerror isn't thread safe, so we need to lock around this entire
125 let _guard = (*LOCK).lock();
126 let _old_error = libc::dlerror();
130 let last_error = libc::dlerror() as *const _;
131 let ret = if ptr::null() == last_error {
134 let s = CStr::from_ptr(last_error).to_bytes();
135 Err(str::from_utf8(s).unwrap().to_owned())
142 pub unsafe fn symbol(handle: *mut u8,
143 symbol: *const libc::c_char)
144 -> Result<*mut u8, String> {
145 check_for_errors_in(|| {
146 libc::dlsym(handle as *mut libc::c_void, symbol) as *mut u8
149 pub unsafe fn close(handle: *mut u8) {
150 libc::dlclose(handle as *mut libc::c_void); ()
158 use std::os::windows::prelude::*;
161 use libc::{c_uint, c_void, c_char};
164 type HMODULE = *mut u8;
166 type LPCWSTR = *const u16;
167 type LPCSTR = *const i8;
170 fn SetThreadErrorMode(dwNewMode: DWORD,
171 lpOldMode: *mut DWORD) -> c_uint;
172 fn LoadLibraryW(name: LPCWSTR) -> HMODULE;
173 fn GetModuleHandleExW(dwFlags: DWORD,
175 handle: *mut HMODULE) -> BOOL;
176 fn GetProcAddress(handle: HMODULE,
177 name: LPCSTR) -> *mut c_void;
178 fn FreeLibrary(handle: HMODULE) -> BOOL;
181 pub fn open_global_now(filename: &OsStr) -> Result<*mut u8, String> {
185 pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
186 // disable "dll load failed" error dialog.
187 let prev_error_mode = unsafe {
188 // SEM_FAILCRITICALERRORS 0x01
189 let new_error_mode = 1;
190 let mut prev_error_mode = 0;
191 let result = SetThreadErrorMode(new_error_mode,
192 &mut prev_error_mode);
194 return Err(io::Error::last_os_error().to_string())
199 let result = match filename {
201 let filename_str: Vec<_> =
202 filename.encode_wide().chain(Some(0)).collect();
203 let result = unsafe {
204 LoadLibraryW(filename_str.as_ptr())
209 let mut handle = ptr::null_mut();
210 let succeeded = unsafe {
211 GetModuleHandleExW(0 as DWORD, ptr::null(), &mut handle)
214 Err(io::Error::last_os_error().to_string())
216 Ok(handle as *mut u8)
222 SetThreadErrorMode(prev_error_mode, ptr::null_mut());
228 pub unsafe fn symbol(handle: *mut u8,
229 symbol: *const c_char)
230 -> Result<*mut u8, String> {
231 let ptr = GetProcAddress(handle as HMODULE, symbol) as *mut u8;
235 pub unsafe fn close(handle: *mut u8) {
236 FreeLibrary(handle as HMODULE);
239 fn ptr_result<T>(ptr: *mut T) -> Result<*mut T, String> {
241 Err(io::Error::last_os_error().to_string())