1 //! Dynamic library facilities.
3 //! A simple wrapper over the platform's dynamic library facilities
8 pub struct DynamicLibrary {
12 impl Drop for DynamicLibrary {
14 unsafe { dl::close(self.handle) }
19 /// Lazily open a dynamic library.
20 pub fn open(filename: &Path) -> Result<DynamicLibrary, String> {
21 let maybe_library = dl::open(filename.as_os_str());
23 // The dynamic library must not be constructed if there is
24 // an error opening the library so the destructor does not
28 Ok(handle) => Ok(DynamicLibrary { handle }),
32 /// Accesses the value at the symbol of the dynamic library.
33 pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<*mut T, String> {
34 // This function should have a lifetime constraint of 'a on
35 // T but that feature is still unimplemented
37 let raw_string = CString::new(symbol).unwrap();
38 let maybe_symbol_value = dl::symbol(self.handle, raw_string.as_ptr());
40 // The value must not be constructed if there is an error so
41 // the destructor does not run.
42 match maybe_symbol_value {
44 Ok(symbol_value) => Ok(symbol_value as *mut T),
54 use std::ffi::{CString, OsStr};
55 use std::os::unix::prelude::*;
57 // As of the 2017 revision of the POSIX standard (IEEE 1003.1-2017), it is
58 // implementation-defined whether `dlerror` is thread-safe (in which case it returns the most
59 // recent error in the calling thread) or not thread-safe (in which case it returns the most
60 // recent error in *any* thread).
62 // There's no easy way to tell what strategy is used by a given POSIX implementation, so we
63 // lock around all calls that can modify `dlerror` in this module lest we accidentally read an
64 // error from a different thread. This is bulletproof when we are the *only* code using the
65 // dynamic library APIs at a given point in time. However, it's still possible for us to race
66 // with other code (see #74469) on platforms where `dlerror` is not thread-safe.
69 use std::lazy::SyncLazy;
70 use std::sync::{Mutex, MutexGuard};
72 pub fn lock() -> MutexGuard<'static, Guard> {
73 static LOCK: SyncLazy<Mutex<Guard>> = SyncLazy::new(|| Mutex::new(Guard));
81 pub fn get(&mut self) -> Result<(), String> {
82 let msg = unsafe { libc::dlerror() };
86 let msg = unsafe { CStr::from_ptr(msg as *const _) };
87 Err(msg.to_string_lossy().into_owned())
91 pub fn clear(&mut self) {
92 let _ = unsafe { libc::dlerror() };
97 pub(super) fn open(filename: &OsStr) -> Result<*mut u8, String> {
98 let s = CString::new(filename.as_bytes()).unwrap();
100 let mut dlerror = error::lock();
101 let ret = unsafe { libc::dlopen(s.as_ptr(), libc::RTLD_LAZY | libc::RTLD_LOCAL) };
104 return Ok(ret.cast());
107 // A null return from `dlopen` indicates that an error has definitely occurred, so if
108 // nothing is in `dlerror`, we are racing with another thread that has stolen our error
109 // message. See the explanation on the `dl::error` module for more information.
110 dlerror.get().and_then(|()| Err("Unknown error".to_string()))
113 pub(super) unsafe fn symbol(
115 symbol: *const libc::c_char,
116 ) -> Result<*mut u8, String> {
117 let mut dlerror = error::lock();
119 // Unlike `dlopen`, it's possible for `dlsym` to return null without overwriting `dlerror`.
120 // Because of this, we clear `dlerror` before calling `dlsym` to avoid picking up a stale
121 // error message by accident.
124 let ret = libc::dlsym(handle as *mut libc::c_void, symbol);
127 return Ok(ret.cast());
130 // If `dlsym` returns null but there is nothing in `dlerror` it means one of two things:
131 // - We tried to load a symbol mapped to address 0. This is not technically an error but is
132 // unlikely to occur in practice and equally unlikely to be handled correctly by calling
133 // code. Therefore we treat it as an error anyway.
134 // - An error has occurred, but we are racing with another thread that has stolen our error
135 // message. See the explanation on the `dl::error` module for more information.
136 dlerror.get().and_then(|()| Err("Tried to load symbol mapped to address 0".to_string()))
139 pub(super) unsafe fn close(handle: *mut u8) {
140 libc::dlclose(handle as *mut libc::c_void);
148 use std::os::windows::prelude::*;
151 use winapi::shared::minwindef::HMODULE;
152 use winapi::um::errhandlingapi::SetThreadErrorMode;
153 use winapi::um::libloaderapi::{FreeLibrary, GetProcAddress, LoadLibraryW};
154 use winapi::um::winbase::SEM_FAILCRITICALERRORS;
156 pub(super) fn open(filename: &OsStr) -> Result<*mut u8, String> {
157 // disable "dll load failed" error dialog.
158 let prev_error_mode = unsafe {
159 let new_error_mode = SEM_FAILCRITICALERRORS;
160 let mut prev_error_mode = 0;
161 let result = SetThreadErrorMode(new_error_mode, &mut prev_error_mode);
163 return Err(io::Error::last_os_error().to_string());
168 let filename_str: Vec<_> = filename.encode_wide().chain(Some(0)).collect();
169 let result = unsafe { LoadLibraryW(filename_str.as_ptr()) } as *mut u8;
170 let result = ptr_result(result);
173 SetThreadErrorMode(prev_error_mode, ptr::null_mut());
179 pub(super) unsafe fn symbol(
181 symbol: *const libc::c_char,
182 ) -> Result<*mut u8, String> {
183 let ptr = GetProcAddress(handle as HMODULE, symbol) as *mut u8;
187 pub(super) unsafe fn close(handle: *mut u8) {
188 FreeLibrary(handle as HMODULE);
191 fn ptr_result<T>(ptr: *mut T) -> Result<*mut T, String> {
192 if ptr.is_null() { Err(io::Error::last_os_error().to_string()) } else { Ok(ptr) }