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