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