]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_metadata/src/dynamic_lib.rs
Rollup merge of #88624 - kellerkindt:master, r=JohnTitor
[rust.git] / compiler / rustc_metadata / src / dynamic_lib.rs
1 //! Dynamic library facilities.
2 //!
3 //! A simple wrapper over the platform's dynamic library facilities
4
5 use std::ffi::CString;
6 use std::path::Path;
7
8 pub struct DynamicLibrary {
9     handle: *mut u8,
10 }
11
12 impl Drop for DynamicLibrary {
13     fn drop(&mut self) {
14         unsafe { dl::close(self.handle) }
15     }
16 }
17
18 impl DynamicLibrary {
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());
22
23         // The dynamic library must not be constructed if there is
24         // an error opening the library so the destructor does not
25         // run.
26         match maybe_library {
27             Err(err) => Err(err),
28             Ok(handle) => Ok(DynamicLibrary { handle }),
29         }
30     }
31
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
36
37         let raw_string = CString::new(symbol).unwrap();
38         let maybe_symbol_value = dl::symbol(self.handle, raw_string.as_ptr());
39
40         // The value must not be constructed if there is an error so
41         // the destructor does not run.
42         match maybe_symbol_value {
43             Err(err) => Err(err),
44             Ok(symbol_value) => Ok(symbol_value as *mut T),
45         }
46     }
47 }
48
49 #[cfg(test)]
50 mod tests;
51
52 #[cfg(unix)]
53 mod dl {
54     use std::ffi::{CString, OsStr};
55     use std::os::unix::prelude::*;
56
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).
61     //
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.
67     mod error {
68         use std::ffi::CStr;
69         use std::lazy::SyncLazy;
70         use std::sync::{Mutex, MutexGuard};
71
72         pub fn lock() -> MutexGuard<'static, Guard> {
73             static LOCK: SyncLazy<Mutex<Guard>> = SyncLazy::new(|| Mutex::new(Guard));
74             LOCK.lock().unwrap()
75         }
76
77         #[non_exhaustive]
78         pub struct Guard;
79
80         impl Guard {
81             pub fn get(&mut self) -> Result<(), String> {
82                 let msg = unsafe { libc::dlerror() };
83                 if msg.is_null() {
84                     Ok(())
85                 } else {
86                     let msg = unsafe { CStr::from_ptr(msg as *const _) };
87                     Err(msg.to_string_lossy().into_owned())
88                 }
89             }
90
91             pub fn clear(&mut self) {
92                 let _ = unsafe { libc::dlerror() };
93             }
94         }
95     }
96
97     pub(super) fn open(filename: &OsStr) -> Result<*mut u8, String> {
98         let s = CString::new(filename.as_bytes()).unwrap();
99
100         let mut dlerror = error::lock();
101         let ret = unsafe { libc::dlopen(s.as_ptr(), libc::RTLD_LAZY | libc::RTLD_LOCAL) };
102
103         if !ret.is_null() {
104             return Ok(ret.cast());
105         }
106
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()))
111     }
112
113     pub(super) unsafe fn symbol(
114         handle: *mut u8,
115         symbol: *const libc::c_char,
116     ) -> Result<*mut u8, String> {
117         let mut dlerror = error::lock();
118
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.
122         dlerror.clear();
123
124         let ret = libc::dlsym(handle as *mut libc::c_void, symbol);
125
126         if !ret.is_null() {
127             return Ok(ret.cast());
128         }
129
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()))
137     }
138
139     pub(super) unsafe fn close(handle: *mut u8) {
140         libc::dlclose(handle as *mut libc::c_void);
141     }
142 }
143
144 #[cfg(windows)]
145 mod dl {
146     use std::ffi::OsStr;
147     use std::io;
148     use std::os::windows::prelude::*;
149     use std::ptr;
150
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;
155
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);
162             if result == 0 {
163                 return Err(io::Error::last_os_error().to_string());
164             }
165             prev_error_mode
166         };
167
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);
171
172         unsafe {
173             SetThreadErrorMode(prev_error_mode, ptr::null_mut());
174         }
175
176         result
177     }
178
179     pub(super) unsafe fn symbol(
180         handle: *mut u8,
181         symbol: *const libc::c_char,
182     ) -> Result<*mut u8, String> {
183         let ptr = GetProcAddress(handle as HMODULE, symbol) as *mut u8;
184         ptr_result(ptr)
185     }
186
187     pub(super) unsafe fn close(handle: *mut u8) {
188         FreeLibrary(handle as HMODULE);
189     }
190
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) }
193     }
194 }