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 { _priv: () }
));
82 pub fn get(&mut self) -> Result
<(), String
> {
83 let msg
= unsafe { libc::dlerror() }
;
87 let msg
= unsafe { CStr::from_ptr(msg as *const _) }
;
88 Err(msg
.to_string_lossy().into_owned())
92 pub fn clear(&mut self) {
93 let _
= unsafe { libc::dlerror() }
;
98 pub(super) fn open(filename
: &OsStr
) -> Result
<*mut u8, String
> {
99 let s
= CString
::new(filename
.as_bytes()).unwrap();
101 let mut dlerror
= error
::lock();
102 let ret
= unsafe { libc::dlopen(s.as_ptr(), libc::RTLD_LAZY | libc::RTLD_LOCAL) }
;
105 return Ok(ret
.cast());
108 // A null return from `dlopen` indicates that an error has definitely occurred, so if
109 // nothing is in `dlerror`, we are racing with another thread that has stolen our error
110 // message. See the explanation on the `dl::error` module for more information.
111 dlerror
.get().and_then(|()| Err("Unknown error".to_string()))
114 pub(super) unsafe fn symbol(
116 symbol
: *const libc
::c_char
,
117 ) -> Result
<*mut u8, String
> {
118 let mut dlerror
= error
::lock();
120 // Unlike `dlopen`, it's possible for `dlsym` to return null without overwriting `dlerror`.
121 // Because of this, we clear `dlerror` before calling `dlsym` to avoid picking up a stale
122 // error message by accident.
125 let ret
= libc
::dlsym(handle
as *mut libc
::c_void
, symbol
);
128 return Ok(ret
.cast());
131 // If `dlsym` returns null but there is nothing in `dlerror` it means one of two things:
132 // - We tried to load a symbol mapped to address 0. This is not technically an error but is
133 // unlikely to occur in practice and equally unlikely to be handled correctly by calling
134 // code. Therefore we treat it as an error anyway.
135 // - An error has occurred, but we are racing with another thread that has stolen our error
136 // message. See the explanation on the `dl::error` module for more information.
137 dlerror
.get().and_then(|()| Err("Tried to load symbol mapped to address 0".to_string()))
140 pub(super) unsafe fn close(handle
: *mut u8) {
141 libc
::dlclose(handle
as *mut libc
::c_void
);
149 use std
::os
::windows
::prelude
::*;
152 use winapi
::shared
::minwindef
::HMODULE
;
153 use winapi
::um
::errhandlingapi
::SetThreadErrorMode
;
154 use winapi
::um
::libloaderapi
::{FreeLibrary, GetProcAddress, LoadLibraryW}
;
155 use winapi
::um
::winbase
::SEM_FAILCRITICALERRORS
;
157 pub(super) fn open(filename
: &OsStr
) -> Result
<*mut u8, String
> {
158 // disable "dll load failed" error dialog.
159 let prev_error_mode
= unsafe {
160 let new_error_mode
= SEM_FAILCRITICALERRORS
;
161 let mut prev_error_mode
= 0;
162 let result
= SetThreadErrorMode(new_error_mode
, &mut prev_error_mode
);
164 return Err(io
::Error
::last_os_error().to_string());
169 let filename_str
: Vec
<_
> = filename
.encode_wide().chain(Some(0)).collect();
170 let result
= unsafe { LoadLibraryW(filename_str.as_ptr()) }
as *mut u8;
171 let result
= ptr_result(result
);
174 SetThreadErrorMode(prev_error_mode
, ptr
::null_mut());
180 pub(super) unsafe fn symbol(
182 symbol
: *const libc
::c_char
,
183 ) -> Result
<*mut u8, String
> {
184 let ptr
= GetProcAddress(handle
as HMODULE
, symbol
) as *mut u8;
188 pub(super) unsafe fn close(handle
: *mut u8) {
189 FreeLibrary(handle
as HMODULE
);
192 fn ptr_result
<T
>(ptr
: *mut T
) -> Result
<*mut T
, String
> {
193 if ptr
.is_null() { Err(io::Error::last_os_error().to_string()) }
else { Ok(ptr) }