]> git.lizzy.rs Git - rust.git/blob - src/libstd/dynamic_lib.rs
Auto merge of #23861 - Manishearth:rollup, r=Manishearth
[rust.git] / src / libstd / 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 #![unstable(feature = "std_misc")]
16 #![allow(missing_docs)]
17
18 use prelude::v1::*;
19
20 use env;
21 use ffi::{AsOsStr, CString, OsString};
22 use mem;
23 use path::{Path, PathBuf};
24
25 pub struct DynamicLibrary {
26     handle: *mut u8
27 }
28
29 impl Drop for DynamicLibrary {
30     fn drop(&mut self) {
31         match dl::check_for_errors_in(|| {
32             unsafe {
33                 dl::close(self.handle)
34             }
35         }) {
36             Ok(()) => {},
37             Err(str) => panic!("{}", str)
38         }
39     }
40 }
41
42 impl DynamicLibrary {
43     // FIXME (#12938): Until DST lands, we cannot decompose &str into
44     // & and str, so we cannot usefully take ToCStr arguments by
45     // reference (without forcing an additional & around &str). So we
46     // are instead temporarily adding an instance for &Path, so that
47     // we can take ToCStr as owned. When DST lands, the &Path instance
48     // should be removed, and arguments bound by ToCStr should be
49     // passed by reference. (Here: in the `open` method.)
50
51     /// Lazily open a dynamic library. When passed None it gives a
52     /// handle to the calling process
53     pub fn open(filename: Option<&Path>) -> Result<DynamicLibrary, String> {
54         let maybe_library = dl::open(filename.map(|path| path.as_os_str()));
55
56         // The dynamic library must not be constructed if there is
57         // an error opening the library so the destructor does not
58         // run.
59         match maybe_library {
60             Err(err) => Err(err),
61             Ok(handle) => Ok(DynamicLibrary { handle: handle })
62         }
63     }
64
65     /// Prepends a path to this process's search path for dynamic libraries
66     pub fn prepend_search_path(path: &Path) {
67         let mut search_path = DynamicLibrary::search_path();
68         search_path.insert(0, path.to_path_buf());
69         env::set_var(DynamicLibrary::envvar(), &DynamicLibrary::create_path(&search_path));
70     }
71
72     /// From a slice of paths, create a new vector which is suitable to be an
73     /// environment variable for this platforms dylib search path.
74     pub fn create_path(path: &[PathBuf]) -> OsString {
75         let mut newvar = OsString::new();
76         for (i, path) in path.iter().enumerate() {
77             if i > 0 { newvar.push(DynamicLibrary::separator()); }
78             newvar.push(path);
79         }
80         return newvar;
81     }
82
83     /// Returns the environment variable for this process's dynamic library
84     /// search path
85     pub fn envvar() -> &'static str {
86         if cfg!(windows) {
87             "PATH"
88         } else if cfg!(target_os = "macos") {
89             "DYLD_LIBRARY_PATH"
90         } else {
91             "LD_LIBRARY_PATH"
92         }
93     }
94
95     fn separator() -> &'static str {
96         if cfg!(windows) { ";" } else { ":" }
97     }
98
99     /// Returns the current search path for dynamic libraries being used by this
100     /// process
101     pub fn search_path() -> Vec<PathBuf> {
102         match env::var_os(DynamicLibrary::envvar()) {
103             Some(var) => env::split_paths(&var).collect(),
104             None => Vec::new(),
105         }
106     }
107
108     /// Access the value at the symbol of the dynamic library
109     pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<*mut T, String> {
110         // This function should have a lifetime constraint of 'a on
111         // T but that feature is still unimplemented
112
113         let raw_string = CString::new(symbol).unwrap();
114         let maybe_symbol_value = dl::check_for_errors_in(|| {
115             dl::symbol(self.handle, raw_string.as_ptr())
116         });
117
118         // The value must not be constructed if there is an error so
119         // the destructor does not run.
120         match maybe_symbol_value {
121             Err(err) => Err(err),
122             Ok(symbol_value) => Ok(mem::transmute(symbol_value))
123         }
124     }
125 }
126
127 #[cfg(all(test, not(target_os = "ios")))]
128 mod test {
129     use super::*;
130     use prelude::v1::*;
131     use libc;
132     use mem;
133     use path::Path;
134
135     #[test]
136     #[cfg_attr(any(windows, target_os = "android"), ignore)] // FIXME #8818, #10379
137     fn test_loading_cosine() {
138         // The math library does not need to be loaded since it is already
139         // statically linked in
140         let libm = match DynamicLibrary::open(None) {
141             Err(error) => panic!("Could not load self as module: {}", error),
142             Ok(libm) => libm
143         };
144
145         let cosine: extern fn(libc::c_double) -> libc::c_double = unsafe {
146             match libm.symbol("cos") {
147                 Err(error) => panic!("Could not load function cos: {}", error),
148                 Ok(cosine) => mem::transmute::<*mut u8, _>(cosine)
149             }
150         };
151
152         let argument = 0.0;
153         let expected_result = 1.0;
154         let result = cosine(argument);
155         if result != expected_result {
156             panic!("cos({}) != {} but equaled {} instead", argument,
157                    expected_result, result)
158         }
159     }
160
161     #[test]
162     #[cfg(any(target_os = "linux",
163               target_os = "macos",
164               target_os = "freebsd",
165               target_os = "dragonfly",
166               target_os = "bitrig",
167               target_os = "openbsd"))]
168     fn test_errors_do_not_crash() {
169         // Open /dev/null as a library to get an error, and make sure
170         // that only causes an error, and not a crash.
171         let path = Path::new("/dev/null");
172         match DynamicLibrary::open(Some(&path)) {
173             Err(_) => {}
174             Ok(_) => panic!("Successfully opened the empty library.")
175         }
176     }
177 }
178
179 #[cfg(any(target_os = "linux",
180           target_os = "android",
181           target_os = "macos",
182           target_os = "ios",
183           target_os = "freebsd",
184           target_os = "dragonfly",
185           target_os = "bitrig",
186           target_os = "openbsd"))]
187 mod dl {
188     use prelude::v1::*;
189
190     use ffi::{CStr, OsStr};
191     use str;
192     use libc;
193     use os::unix::prelude::*;
194     use ptr;
195
196     pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
197         check_for_errors_in(|| {
198             unsafe {
199                 match filename {
200                     Some(filename) => open_external(filename),
201                     None => open_internal(),
202                 }
203             }
204         })
205     }
206
207     const LAZY: libc::c_int = 1;
208
209     unsafe fn open_external(filename: &OsStr) -> *mut u8 {
210         let s = filename.to_cstring().unwrap();
211         dlopen(s.as_ptr(), LAZY) as *mut u8
212     }
213
214     unsafe fn open_internal() -> *mut u8 {
215         dlopen(ptr::null(), LAZY) as *mut u8
216     }
217
218     pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where
219         F: FnOnce() -> T,
220     {
221         use sync::{StaticMutex, MUTEX_INIT};
222         static LOCK: StaticMutex = MUTEX_INIT;
223         unsafe {
224             // dlerror isn't thread safe, so we need to lock around this entire
225             // sequence
226             let _guard = LOCK.lock();
227             let _old_error = dlerror();
228
229             let result = f();
230
231             let last_error = dlerror() as *const _;
232             let ret = if ptr::null() == last_error {
233                 Ok(result)
234             } else {
235                 let s = CStr::from_ptr(last_error).to_bytes();
236                 Err(str::from_utf8(s).unwrap().to_string())
237             };
238
239             ret
240         }
241     }
242
243     pub unsafe fn symbol(handle: *mut u8,
244                          symbol: *const libc::c_char) -> *mut u8 {
245         dlsym(handle as *mut libc::c_void, symbol) as *mut u8
246     }
247     pub unsafe fn close(handle: *mut u8) {
248         dlclose(handle as *mut libc::c_void); ()
249     }
250
251     extern {
252         fn dlopen(filename: *const libc::c_char,
253                   flag: libc::c_int) -> *mut libc::c_void;
254         fn dlerror() -> *mut libc::c_char;
255         fn dlsym(handle: *mut libc::c_void,
256                  symbol: *const libc::c_char) -> *mut libc::c_void;
257         fn dlclose(handle: *mut libc::c_void) -> libc::c_int;
258     }
259 }
260
261 #[cfg(target_os = "windows")]
262 mod dl {
263     use ffi::OsStr;
264     use iter::Iterator;
265     use libc;
266     use libc::consts::os::extra::ERROR_CALL_NOT_IMPLEMENTED;
267     use ops::FnOnce;
268     use sys::os;
269     use os::windows::prelude::*;
270     use option::Option::{self, Some, None};
271     use ptr;
272     use result::Result;
273     use result::Result::{Ok, Err};
274     use string::String;
275     use vec::Vec;
276     use sys::c::compat::kernel32::SetThreadErrorMode;
277
278     pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
279         // disable "dll load failed" error dialog.
280         let mut use_thread_mode = true;
281         let prev_error_mode = unsafe {
282             // SEM_FAILCRITICALERRORS 0x01
283             let new_error_mode = 1;
284             let mut prev_error_mode = 0;
285             // Windows >= 7 supports thread error mode.
286             let result = SetThreadErrorMode(new_error_mode, &mut prev_error_mode);
287             if result == 0 {
288                 let err = os::errno();
289                 if err as libc::c_int == ERROR_CALL_NOT_IMPLEMENTED {
290                     use_thread_mode = false;
291                     // SetThreadErrorMode not found. use fallback solution:
292                     // SetErrorMode() Note that SetErrorMode is process-wide so
293                     // this can cause race condition!  However, since even
294                     // Windows APIs do not care of such problem (#20650), we
295                     // just assume SetErrorMode race is not a great deal.
296                     prev_error_mode = SetErrorMode(new_error_mode);
297                 }
298             }
299             prev_error_mode
300         };
301
302         unsafe {
303             SetLastError(0);
304         }
305
306         let result = match filename {
307             Some(filename) => {
308                 let filename_str: Vec<_> =
309                     filename.encode_wide().chain(Some(0).into_iter()).collect();
310                 let result = unsafe {
311                     LoadLibraryW(filename_str.as_ptr() as *const libc::c_void)
312                 };
313                 // beware: Vec/String may change errno during drop!
314                 // so we get error here.
315                 if result == ptr::null_mut() {
316                     let errno = os::errno();
317                     Err(os::error_string(errno))
318                 } else {
319                     Ok(result as *mut u8)
320                 }
321             }
322             None => {
323                 let mut handle = ptr::null_mut();
324                 let succeeded = unsafe {
325                     GetModuleHandleExW(0 as libc::DWORD, ptr::null(), &mut handle)
326                 };
327                 if succeeded == libc::FALSE {
328                     let errno = os::errno();
329                     Err(os::error_string(errno))
330                 } else {
331                     Ok(handle as *mut u8)
332                 }
333             }
334         };
335
336         unsafe {
337             if use_thread_mode {
338                 SetThreadErrorMode(prev_error_mode, ptr::null_mut());
339             } else {
340                 SetErrorMode(prev_error_mode);
341             }
342         }
343
344         result
345     }
346
347     pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where
348         F: FnOnce() -> T,
349     {
350         unsafe {
351             SetLastError(0);
352
353             let result = f();
354
355             let error = os::errno();
356             if 0 == error {
357                 Ok(result)
358             } else {
359                 Err(format!("Error code {}", error))
360             }
361         }
362     }
363
364     pub unsafe fn symbol(handle: *mut u8, symbol: *const libc::c_char) -> *mut u8 {
365         GetProcAddress(handle as *mut libc::c_void, symbol) as *mut u8
366     }
367     pub unsafe fn close(handle: *mut u8) {
368         FreeLibrary(handle as *mut libc::c_void); ()
369     }
370
371     #[allow(non_snake_case)]
372     extern "system" {
373         fn SetLastError(error: libc::size_t);
374         fn LoadLibraryW(name: *const libc::c_void) -> *mut libc::c_void;
375         fn GetModuleHandleExW(dwFlags: libc::DWORD, name: *const u16,
376                               handle: *mut *mut libc::c_void) -> libc::BOOL;
377         fn GetProcAddress(handle: *mut libc::c_void,
378                           name: *const libc::c_char) -> *mut libc::c_void;
379         fn FreeLibrary(handle: *mut libc::c_void);
380         fn SetErrorMode(uMode: libc::c_uint) -> libc::c_uint;
381     }
382 }