]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/dynamic_lib.rs
Rollup merge of #70762 - RalfJung:miri-leak-check, r=oli-obk
[rust.git] / src / librustc_metadata / 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. When passed None it gives a
20     /// handle to the calling process
21     pub fn open(filename: Option<&Path>) -> Result<DynamicLibrary, String> {
22         let maybe_library = dl::open(filename.map(|path| path.as_os_str()));
23
24         // The dynamic library must not be constructed if there is
25         // an error opening the library so the destructor does not
26         // run.
27         match maybe_library {
28             Err(err) => Err(err),
29             Ok(handle) => Ok(DynamicLibrary { handle }),
30         }
31     }
32
33     /// Accesses the value at the symbol of the dynamic library.
34     pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<*mut T, String> {
35         // This function should have a lifetime constraint of 'a on
36         // T but that feature is still unimplemented
37
38         let raw_string = CString::new(symbol).unwrap();
39         let maybe_symbol_value = dl::symbol(self.handle, raw_string.as_ptr());
40
41         // The value must not be constructed if there is an error so
42         // the destructor does not run.
43         match maybe_symbol_value {
44             Err(err) => Err(err),
45             Ok(symbol_value) => Ok(symbol_value as *mut T),
46         }
47     }
48 }
49
50 #[cfg(test)]
51 mod tests;
52
53 #[cfg(unix)]
54 mod dl {
55     use std::ffi::{CStr, CString, OsStr};
56     use std::os::unix::prelude::*;
57     use std::ptr;
58     use std::str;
59
60     pub(super) fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
61         check_for_errors_in(|| unsafe {
62             match filename {
63                 Some(filename) => open_external(filename),
64                 None => open_internal(),
65             }
66         })
67     }
68
69     unsafe fn open_external(filename: &OsStr) -> *mut u8 {
70         let s = CString::new(filename.as_bytes()).unwrap();
71         libc::dlopen(s.as_ptr(), libc::RTLD_LAZY) as *mut u8
72     }
73
74     unsafe fn open_internal() -> *mut u8 {
75         libc::dlopen(ptr::null(), libc::RTLD_LAZY) as *mut u8
76     }
77
78     fn check_for_errors_in<T, F>(f: F) -> Result<T, String>
79     where
80         F: FnOnce() -> T,
81     {
82         use std::sync::{Mutex, Once};
83         static INIT: Once = Once::new();
84         static mut LOCK: *mut Mutex<()> = ptr::null_mut();
85         unsafe {
86             INIT.call_once(|| {
87                 LOCK = Box::into_raw(Box::new(Mutex::new(())));
88             });
89             // dlerror isn't thread safe, so we need to lock around this entire
90             // sequence
91             let _guard = (*LOCK).lock();
92             let _old_error = libc::dlerror();
93
94             let result = f();
95
96             let last_error = libc::dlerror() as *const _;
97             if ptr::null() == last_error {
98                 Ok(result)
99             } else {
100                 let s = CStr::from_ptr(last_error).to_bytes();
101                 Err(str::from_utf8(s).unwrap().to_owned())
102             }
103         }
104     }
105
106     pub(super) unsafe fn symbol(
107         handle: *mut u8,
108         symbol: *const libc::c_char,
109     ) -> Result<*mut u8, String> {
110         check_for_errors_in(|| libc::dlsym(handle as *mut libc::c_void, symbol) as *mut u8)
111     }
112
113     pub(super) unsafe fn close(handle: *mut u8) {
114         libc::dlclose(handle as *mut libc::c_void);
115     }
116 }
117
118 #[cfg(windows)]
119 mod dl {
120     use std::ffi::OsStr;
121     use std::io;
122     use std::os::windows::prelude::*;
123     use std::ptr;
124
125     use winapi::shared::minwindef::HMODULE;
126     use winapi::um::errhandlingapi::SetThreadErrorMode;
127     use winapi::um::libloaderapi::{FreeLibrary, GetModuleHandleExW, GetProcAddress, LoadLibraryW};
128     use winapi::um::winbase::SEM_FAILCRITICALERRORS;
129
130     pub(super) fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
131         // disable "dll load failed" error dialog.
132         let prev_error_mode = unsafe {
133             let new_error_mode = SEM_FAILCRITICALERRORS;
134             let mut prev_error_mode = 0;
135             let result = SetThreadErrorMode(new_error_mode, &mut prev_error_mode);
136             if result == 0 {
137                 return Err(io::Error::last_os_error().to_string());
138             }
139             prev_error_mode
140         };
141
142         let result = match filename {
143             Some(filename) => {
144                 let filename_str: Vec<_> = filename.encode_wide().chain(Some(0)).collect();
145                 let result = unsafe { LoadLibraryW(filename_str.as_ptr()) } as *mut u8;
146                 ptr_result(result)
147             }
148             None => {
149                 let mut handle = ptr::null_mut();
150                 let succeeded = unsafe { GetModuleHandleExW(0, ptr::null(), &mut handle) };
151                 if succeeded == 0 {
152                     Err(io::Error::last_os_error().to_string())
153                 } else {
154                     Ok(handle as *mut u8)
155                 }
156             }
157         };
158
159         unsafe {
160             SetThreadErrorMode(prev_error_mode, ptr::null_mut());
161         }
162
163         result
164     }
165
166     pub(super) unsafe fn symbol(
167         handle: *mut u8,
168         symbol: *const libc::c_char,
169     ) -> Result<*mut u8, String> {
170         let ptr = GetProcAddress(handle as HMODULE, symbol) as *mut u8;
171         ptr_result(ptr)
172     }
173
174     pub(super) unsafe fn close(handle: *mut u8) {
175         FreeLibrary(handle as HMODULE);
176     }
177
178     fn ptr_result<T>(ptr: *mut T) -> Result<*mut T, String> {
179         if ptr.is_null() { Err(io::Error::last_os_error().to_string()) } else { Ok(ptr) }
180     }
181 }