]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/dynamic_lib.rs
Rollup merge of #56363 - Lucretiel:patch-3, r=shepmaster
[rust.git] / src / librustc_metadata / dynamic_lib.rs
1 // Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Dynamic library facilities.
12 //!
13 //! A simple wrapper over the platform's dynamic library facilities
14
15 use std::ffi::CString;
16 use std::path::Path;
17
18 pub struct DynamicLibrary {
19     handle: *mut u8
20 }
21
22 impl Drop for DynamicLibrary {
23     fn drop(&mut self) {
24         unsafe {
25             dl::close(self.handle)
26         }
27     }
28 }
29
30 impl DynamicLibrary {
31     /// Lazily open a dynamic library. When passed None it gives a
32     /// handle to the calling process
33     pub fn open(filename: Option<&Path>) -> Result<DynamicLibrary, String> {
34         let maybe_library = dl::open(filename.map(|path| path.as_os_str()));
35
36         // The dynamic library must not be constructed if there is
37         // an error opening the library so the destructor does not
38         // run.
39         match maybe_library {
40             Err(err) => Err(err),
41             Ok(handle) => Ok(DynamicLibrary { handle })
42         }
43     }
44
45     /// Load a dynamic library into the global namespace (RTLD_GLOBAL on Unix)
46     /// and do it now (don't use RTLD_LAZY on Unix).
47     pub fn open_global_now(filename: &Path) -> Result<DynamicLibrary, String> {
48         let maybe_library = dl::open_global_now(filename.as_os_str());
49         match maybe_library {
50             Err(err) => Err(err),
51             Ok(handle) => Ok(DynamicLibrary { handle })
52         }
53     }
54
55     /// Returns the environment variable for this process's dynamic library
56     /// search path
57     pub fn envvar() -> &'static str {
58         if cfg!(windows) {
59             "PATH"
60         } else if cfg!(target_os = "macos") {
61             "DYLD_LIBRARY_PATH"
62         } else if cfg!(target_os = "haiku") {
63             "LIBRARY_PATH"
64         } else {
65             "LD_LIBRARY_PATH"
66         }
67     }
68
69     /// Accesses the value at the symbol of the dynamic library.
70     pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<*mut T, String> {
71         // This function should have a lifetime constraint of 'a on
72         // T but that feature is still unimplemented
73
74         let raw_string = CString::new(symbol).unwrap();
75         let maybe_symbol_value = dl::symbol(self.handle, raw_string.as_ptr());
76
77         // The value must not be constructed if there is an error so
78         // the destructor does not run.
79         match maybe_symbol_value {
80             Err(err) => Err(err),
81             Ok(symbol_value) => Ok(symbol_value as *mut T)
82         }
83     }
84 }
85
86 #[cfg(test)]
87 mod tests {
88     use super::*;
89     use libc;
90     use std::mem;
91
92     #[test]
93     fn test_loading_atoi() {
94         if cfg!(windows) {
95             return
96         }
97
98         // The C library does not need to be loaded since it is already linked in
99         let lib = match DynamicLibrary::open(None) {
100             Err(error) => panic!("Could not load self as module: {}", error),
101             Ok(lib) => lib
102         };
103
104         let atoi: extern fn(*const libc::c_char) -> libc::c_int = unsafe {
105             match lib.symbol("atoi") {
106                 Err(error) => panic!("Could not load function atoi: {}", error),
107                 Ok(atoi) => mem::transmute::<*mut u8, _>(atoi)
108             }
109         };
110
111         let argument = CString::new("1383428980").unwrap();
112         let expected_result = 0x52757374;
113         let result = atoi(argument.as_ptr());
114         if result != expected_result {
115             panic!("atoi({:?}) != {} but equaled {} instead", argument,
116                    expected_result, result)
117         }
118     }
119
120     #[test]
121     fn test_errors_do_not_crash() {
122         use std::path::Path;
123
124         if !cfg!(unix) {
125             return
126         }
127
128         // Open /dev/null as a library to get an error, and make sure
129         // that only causes an error, and not a crash.
130         let path = Path::new("/dev/null");
131         match DynamicLibrary::open(Some(&path)) {
132             Err(_) => {}
133             Ok(_) => panic!("Successfully opened the empty library.")
134         }
135     }
136 }
137
138 #[cfg(unix)]
139 mod dl {
140     use libc;
141     use std::ffi::{CStr, OsStr, CString};
142     use std::os::unix::prelude::*;
143     use std::ptr;
144     use std::str;
145
146     pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
147         check_for_errors_in(|| {
148             unsafe {
149                 match filename {
150                     Some(filename) => open_external(filename),
151                     None => open_internal(),
152                 }
153             }
154         })
155     }
156
157     pub fn open_global_now(filename: &OsStr) -> Result<*mut u8, String> {
158         check_for_errors_in(|| unsafe {
159             let s = CString::new(filename.as_bytes()).unwrap();
160             libc::dlopen(s.as_ptr(), libc::RTLD_GLOBAL | libc::RTLD_NOW) as *mut u8
161         })
162     }
163
164     unsafe fn open_external(filename: &OsStr) -> *mut u8 {
165         let s = CString::new(filename.as_bytes()).unwrap();
166         libc::dlopen(s.as_ptr(), libc::RTLD_LAZY) as *mut u8
167     }
168
169     unsafe fn open_internal() -> *mut u8 {
170         libc::dlopen(ptr::null(), libc::RTLD_LAZY) as *mut u8
171     }
172
173     pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where
174         F: FnOnce() -> T,
175     {
176         use std::sync::{Mutex, Once, ONCE_INIT};
177         static INIT: Once = ONCE_INIT;
178         static mut LOCK: *mut Mutex<()> = 0 as *mut _;
179         unsafe {
180             INIT.call_once(|| {
181                 LOCK = Box::into_raw(Box::new(Mutex::new(())));
182             });
183             // dlerror isn't thread safe, so we need to lock around this entire
184             // sequence
185             let _guard = (*LOCK).lock();
186             let _old_error = libc::dlerror();
187
188             let result = f();
189
190             let last_error = libc::dlerror() as *const _;
191             let ret = if ptr::null() == last_error {
192                 Ok(result)
193             } else {
194                 let s = CStr::from_ptr(last_error).to_bytes();
195                 Err(str::from_utf8(s).unwrap().to_owned())
196             };
197
198             ret
199         }
200     }
201
202     pub unsafe fn symbol(handle: *mut u8,
203                          symbol: *const libc::c_char)
204                          -> Result<*mut u8, String> {
205         check_for_errors_in(|| {
206             libc::dlsym(handle as *mut libc::c_void, symbol) as *mut u8
207         })
208     }
209     pub unsafe fn close(handle: *mut u8) {
210         libc::dlclose(handle as *mut libc::c_void); ()
211     }
212 }
213
214 #[cfg(windows)]
215 mod dl {
216     use std::ffi::OsStr;
217     use std::io;
218     use std::os::windows::prelude::*;
219     use std::ptr;
220
221     use libc::{c_uint, c_void, c_char};
222
223     type DWORD = u32;
224     type HMODULE = *mut u8;
225     type BOOL = i32;
226     type LPCWSTR = *const u16;
227     type LPCSTR = *const i8;
228
229     extern "system" {
230         fn SetThreadErrorMode(dwNewMode: DWORD,
231                               lpOldMode: *mut DWORD) -> c_uint;
232         fn LoadLibraryW(name: LPCWSTR) -> HMODULE;
233         fn GetModuleHandleExW(dwFlags: DWORD,
234                               name: LPCWSTR,
235                               handle: *mut HMODULE) -> BOOL;
236         fn GetProcAddress(handle: HMODULE,
237                           name: LPCSTR) -> *mut c_void;
238         fn FreeLibrary(handle: HMODULE) -> BOOL;
239     }
240
241     pub fn open_global_now(filename: &OsStr) -> Result<*mut u8, String> {
242         open(Some(filename))
243     }
244
245     pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
246         // disable "dll load failed" error dialog.
247         let prev_error_mode = unsafe {
248             // SEM_FAILCRITICALERRORS 0x01
249             let new_error_mode = 1;
250             let mut prev_error_mode = 0;
251             let result = SetThreadErrorMode(new_error_mode,
252                                             &mut prev_error_mode);
253             if result == 0 {
254                 return Err(io::Error::last_os_error().to_string())
255             }
256             prev_error_mode
257         };
258
259         let result = match filename {
260             Some(filename) => {
261                 let filename_str: Vec<_> =
262                     filename.encode_wide().chain(Some(0)).collect();
263                 let result = unsafe {
264                     LoadLibraryW(filename_str.as_ptr())
265                 };
266                 ptr_result(result)
267             }
268             None => {
269                 let mut handle = ptr::null_mut();
270                 let succeeded = unsafe {
271                     GetModuleHandleExW(0 as DWORD, ptr::null(), &mut handle)
272                 };
273                 if succeeded == 0 {
274                     Err(io::Error::last_os_error().to_string())
275                 } else {
276                     Ok(handle as *mut u8)
277                 }
278             }
279         };
280
281         unsafe {
282             SetThreadErrorMode(prev_error_mode, ptr::null_mut());
283         }
284
285         result
286     }
287
288     pub unsafe fn symbol(handle: *mut u8,
289                          symbol: *const c_char)
290                          -> Result<*mut u8, String> {
291         let ptr = GetProcAddress(handle as HMODULE, symbol) as *mut u8;
292         ptr_result(ptr)
293     }
294
295     pub unsafe fn close(handle: *mut u8) {
296         FreeLibrary(handle as HMODULE);
297     }
298
299     fn ptr_result<T>(ptr: *mut T) -> Result<*mut T, String> {
300         if ptr.is_null() {
301             Err(io::Error::last_os_error().to_string())
302         } else {
303             Ok(ptr)
304         }
305     }
306 }