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