]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/dynamic_lib.rs
Auto merge of #46696 - kennytm:rollup, r=kennytm
[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: handle })
42         }
43     }
44
45     /// Returns the environment variable for this process's dynamic library
46     /// search path
47     pub fn envvar() -> &'static str {
48         if cfg!(windows) {
49             "PATH"
50         } else if cfg!(target_os = "macos") {
51             "DYLD_LIBRARY_PATH"
52         } else if cfg!(target_os = "haiku") {
53             "LIBRARY_PATH"
54         } else {
55             "LD_LIBRARY_PATH"
56         }
57     }
58
59     /// Accesses the value at the symbol of the dynamic library.
60     pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<*mut T, String> {
61         // This function should have a lifetime constraint of 'a on
62         // T but that feature is still unimplemented
63
64         let raw_string = CString::new(symbol).unwrap();
65         let maybe_symbol_value = dl::symbol(self.handle, raw_string.as_ptr());
66
67         // The value must not be constructed if there is an error so
68         // the destructor does not run.
69         match maybe_symbol_value {
70             Err(err) => Err(err),
71             Ok(symbol_value) => Ok(symbol_value as *mut T)
72         }
73     }
74 }
75
76 #[cfg(test)]
77 mod tests {
78     use super::*;
79     use libc;
80     use std::mem;
81
82     #[test]
83     fn test_loading_cosine() {
84         if cfg!(windows) {
85             return
86         }
87
88         // The math library does not need to be loaded since it is already
89         // statically linked in
90         let libm = match DynamicLibrary::open(None) {
91             Err(error) => panic!("Could not load self as module: {}", error),
92             Ok(libm) => libm
93         };
94
95         let cosine: extern fn(libc::c_double) -> libc::c_double = unsafe {
96             match libm.symbol("cos") {
97                 Err(error) => panic!("Could not load function cos: {}", error),
98                 Ok(cosine) => mem::transmute::<*mut u8, _>(cosine)
99             }
100         };
101
102         let argument = 0.0;
103         let expected_result = 1.0;
104         let result = cosine(argument);
105         if result != expected_result {
106             panic!("cos({}) != {} but equaled {} instead", argument,
107                    expected_result, result)
108         }
109     }
110
111     #[test]
112     fn test_errors_do_not_crash() {
113         use std::path::Path;
114
115         if !cfg!(unix) {
116             return
117         }
118
119         // Open /dev/null as a library to get an error, and make sure
120         // that only causes an error, and not a crash.
121         let path = Path::new("/dev/null");
122         match DynamicLibrary::open(Some(&path)) {
123             Err(_) => {}
124             Ok(_) => panic!("Successfully opened the empty library.")
125         }
126     }
127 }
128
129 #[cfg(unix)]
130 mod dl {
131     use libc;
132     use std::ffi::{CStr, OsStr, CString};
133     use std::os::unix::prelude::*;
134     use std::ptr;
135     use std::str;
136
137     pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
138         check_for_errors_in(|| {
139             unsafe {
140                 match filename {
141                     Some(filename) => open_external(filename),
142                     None => open_internal(),
143                 }
144             }
145         })
146     }
147
148     const LAZY: libc::c_int = 1;
149
150     unsafe fn open_external(filename: &OsStr) -> *mut u8 {
151         let s = CString::new(filename.as_bytes()).unwrap();
152         libc::dlopen(s.as_ptr(), LAZY) as *mut u8
153     }
154
155     unsafe fn open_internal() -> *mut u8 {
156         libc::dlopen(ptr::null(), LAZY) as *mut u8
157     }
158
159     pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where
160         F: FnOnce() -> T,
161     {
162         use std::sync::{Mutex, Once, ONCE_INIT};
163         static INIT: Once = ONCE_INIT;
164         static mut LOCK: *mut Mutex<()> = 0 as *mut _;
165         unsafe {
166             INIT.call_once(|| {
167                 LOCK = Box::into_raw(Box::new(Mutex::new(())));
168             });
169             // dlerror isn't thread safe, so we need to lock around this entire
170             // sequence
171             let _guard = (*LOCK).lock();
172             let _old_error = libc::dlerror();
173
174             let result = f();
175
176             let last_error = libc::dlerror() as *const _;
177             let ret = if ptr::null() == last_error {
178                 Ok(result)
179             } else {
180                 let s = CStr::from_ptr(last_error).to_bytes();
181                 Err(str::from_utf8(s).unwrap().to_owned())
182             };
183
184             ret
185         }
186     }
187
188     pub unsafe fn symbol(handle: *mut u8,
189                          symbol: *const libc::c_char)
190                          -> Result<*mut u8, String> {
191         check_for_errors_in(|| {
192             libc::dlsym(handle as *mut libc::c_void, symbol) as *mut u8
193         })
194     }
195     pub unsafe fn close(handle: *mut u8) {
196         libc::dlclose(handle as *mut libc::c_void); ()
197     }
198 }
199
200 #[cfg(windows)]
201 mod dl {
202     use std::ffi::OsStr;
203     use std::io;
204     use std::os::windows::prelude::*;
205     use std::ptr;
206
207     use libc::{c_uint, c_void, c_char};
208
209     type DWORD = u32;
210     type HMODULE = *mut u8;
211     type BOOL = i32;
212     type LPCWSTR = *const u16;
213     type LPCSTR = *const i8;
214
215     extern "system" {
216         fn SetThreadErrorMode(dwNewMode: DWORD,
217                               lpOldMode: *mut DWORD) -> c_uint;
218         fn LoadLibraryW(name: LPCWSTR) -> HMODULE;
219         fn GetModuleHandleExW(dwFlags: DWORD,
220                               name: LPCWSTR,
221                               handle: *mut HMODULE) -> BOOL;
222         fn GetProcAddress(handle: HMODULE,
223                           name: LPCSTR) -> *mut c_void;
224         fn FreeLibrary(handle: HMODULE) -> BOOL;
225     }
226
227     pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
228         // disable "dll load failed" error dialog.
229         let prev_error_mode = unsafe {
230             // SEM_FAILCRITICALERRORS 0x01
231             let new_error_mode = 1;
232             let mut prev_error_mode = 0;
233             let result = SetThreadErrorMode(new_error_mode,
234                                             &mut prev_error_mode);
235             if result == 0 {
236                 return Err(io::Error::last_os_error().to_string())
237             }
238             prev_error_mode
239         };
240
241         let result = match filename {
242             Some(filename) => {
243                 let filename_str: Vec<_> =
244                     filename.encode_wide().chain(Some(0)).collect();
245                 let result = unsafe {
246                     LoadLibraryW(filename_str.as_ptr())
247                 };
248                 ptr_result(result)
249             }
250             None => {
251                 let mut handle = ptr::null_mut();
252                 let succeeded = unsafe {
253                     GetModuleHandleExW(0 as DWORD, ptr::null(), &mut handle)
254                 };
255                 if succeeded == 0 {
256                     Err(io::Error::last_os_error().to_string())
257                 } else {
258                     Ok(handle as *mut u8)
259                 }
260             }
261         };
262
263         unsafe {
264             SetThreadErrorMode(prev_error_mode, ptr::null_mut());
265         }
266
267         result
268     }
269
270     pub unsafe fn symbol(handle: *mut u8,
271                          symbol: *const c_char)
272                          -> Result<*mut u8, String> {
273         let ptr = GetProcAddress(handle as HMODULE, symbol) as *mut u8;
274         ptr_result(ptr)
275     }
276
277     pub unsafe fn close(handle: *mut u8) {
278         FreeLibrary(handle as HMODULE);
279     }
280
281     fn ptr_result<T>(ptr: *mut T) -> Result<*mut T, String> {
282         if ptr.is_null() {
283             Err(io::Error::last_os_error().to_string())
284         } else {
285             Ok(ptr)
286         }
287     }
288 }