]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_metadata/src/dynamic_lib.rs
New upstream version 1.54.0+dfsg1
[rustc.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 { _priv: () }));
74 LOCK.lock().unwrap()
75 }
76
77 pub struct Guard {
78 _priv: (),
79 }
80
81 impl Guard {
82 pub fn get(&mut self) -> Result<(), String> {
83 let msg = unsafe { libc::dlerror() };
84 if msg.is_null() {
85 Ok(())
86 } else {
87 let msg = unsafe { CStr::from_ptr(msg as *const _) };
88 Err(msg.to_string_lossy().into_owned())
89 }
90 }
91
92 pub fn clear(&mut self) {
93 let _ = unsafe { libc::dlerror() };
94 }
95 }
96 }
97
98 pub(super) fn open(filename: &OsStr) -> Result<*mut u8, String> {
99 let s = CString::new(filename.as_bytes()).unwrap();
100
101 let mut dlerror = error::lock();
102 let ret = unsafe { libc::dlopen(s.as_ptr(), libc::RTLD_LAZY | libc::RTLD_LOCAL) };
103
104 if !ret.is_null() {
105 return Ok(ret.cast());
106 }
107
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()))
112 }
113
114 pub(super) unsafe fn symbol(
115 handle: *mut u8,
116 symbol: *const libc::c_char,
117 ) -> Result<*mut u8, String> {
118 let mut dlerror = error::lock();
119
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.
123 dlerror.clear();
124
125 let ret = libc::dlsym(handle as *mut libc::c_void, symbol);
126
127 if !ret.is_null() {
128 return Ok(ret.cast());
129 }
130
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()))
138 }
139
140 pub(super) unsafe fn close(handle: *mut u8) {
141 libc::dlclose(handle as *mut libc::c_void);
142 }
143 }
144
145 #[cfg(windows)]
146 mod dl {
147 use std::ffi::OsStr;
148 use std::io;
149 use std::os::windows::prelude::*;
150 use std::ptr;
151
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;
156
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);
163 if result == 0 {
164 return Err(io::Error::last_os_error().to_string());
165 }
166 prev_error_mode
167 };
168
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);
172
173 unsafe {
174 SetThreadErrorMode(prev_error_mode, ptr::null_mut());
175 }
176
177 result
178 }
179
180 pub(super) unsafe fn symbol(
181 handle: *mut u8,
182 symbol: *const libc::c_char,
183 ) -> Result<*mut u8, String> {
184 let ptr = GetProcAddress(handle as HMODULE, symbol) as *mut u8;
185 ptr_result(ptr)
186 }
187
188 pub(super) unsafe fn close(handle: *mut u8) {
189 FreeLibrary(handle as HMODULE);
190 }
191
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) }
194 }
195 }