]> git.lizzy.rs Git - rust.git/blob - src/libstd/dynamic_lib.rs
rollup merge of #20518: nagisa/weighted-bool
[rust.git] / src / libstd / dynamic_lib.rs
1 // Copyright 2013-2014 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 #![experimental]
16 #![allow(missing_docs)]
17
18 use prelude::v1::*;
19
20 use ffi::CString;
21 use mem;
22 use os;
23 use str;
24
25 #[allow(missing_copy_implementations)]
26 pub struct DynamicLibrary {
27     handle: *mut u8
28 }
29
30 impl Drop for DynamicLibrary {
31     fn drop(&mut self) {
32         match dl::check_for_errors_in(|| {
33             unsafe {
34                 dl::close(self.handle)
35             }
36         }) {
37             Ok(()) => {},
38             Err(str) => panic!("{}", str)
39         }
40     }
41 }
42
43 impl DynamicLibrary {
44     // FIXME (#12938): Until DST lands, we cannot decompose &str into
45     // & and str, so we cannot usefully take ToCStr arguments by
46     // reference (without forcing an additional & around &str). So we
47     // are instead temporarily adding an instance for &Path, so that
48     // we can take ToCStr as owned. When DST lands, the &Path instance
49     // should be removed, and arguments bound by ToCStr should be
50     // passed by reference. (Here: in the `open` method.)
51
52     /// Lazily open a dynamic library. When passed None it gives a
53     /// handle to the calling process
54     pub fn open(filename: Option<&Path>) -> Result<DynamicLibrary, String> {
55         unsafe {
56             let maybe_library = dl::check_for_errors_in(|| {
57                 match filename {
58                     Some(name) => dl::open_external(name.as_vec()),
59                     None => dl::open_internal()
60                 }
61             });
62
63             // The dynamic library must not be constructed if there is
64             // an error opening the library so the destructor does not
65             // run.
66             match maybe_library {
67                 Err(err) => Err(err),
68                 Ok(handle) => Ok(DynamicLibrary { handle: handle })
69             }
70         }
71     }
72
73     /// Prepends a path to this process's search path for dynamic libraries
74     pub fn prepend_search_path(path: &Path) {
75         let mut search_path = DynamicLibrary::search_path();
76         search_path.insert(0, path.clone());
77         let newval = DynamicLibrary::create_path(search_path.as_slice());
78         os::setenv(DynamicLibrary::envvar(),
79                    str::from_utf8(newval.as_slice()).unwrap());
80     }
81
82     /// From a slice of paths, create a new vector which is suitable to be an
83     /// environment variable for this platforms dylib search path.
84     pub fn create_path(path: &[Path]) -> Vec<u8> {
85         let mut newvar = Vec::new();
86         for (i, path) in path.iter().enumerate() {
87             if i > 0 { newvar.push(DynamicLibrary::separator()); }
88             newvar.push_all(path.as_vec());
89         }
90         return newvar;
91     }
92
93     /// Returns the environment variable for this process's dynamic library
94     /// search path
95     pub fn envvar() -> &'static str {
96         if cfg!(windows) {
97             "PATH"
98         } else if cfg!(target_os = "macos") {
99             "DYLD_LIBRARY_PATH"
100         } else {
101             "LD_LIBRARY_PATH"
102         }
103     }
104
105     fn separator() -> u8 {
106         if cfg!(windows) {b';'} else {b':'}
107     }
108
109     /// Returns the current search path for dynamic libraries being used by this
110     /// process
111     pub fn search_path() -> Vec<Path> {
112         let mut ret = Vec::new();
113         match os::getenv_as_bytes(DynamicLibrary::envvar()) {
114             Some(env) => {
115                 for portion in
116                         env.as_slice()
117                            .split(|a| *a == DynamicLibrary::separator()) {
118                     ret.push(Path::new(portion));
119                 }
120             }
121             None => {}
122         }
123         return ret;
124     }
125
126     /// Access the value at the symbol of the dynamic library
127     pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<*mut T, String> {
128         // This function should have a lifetime constraint of 'a on
129         // T but that feature is still unimplemented
130
131         let maybe_symbol_value = dl::check_for_errors_in(|| {
132             let raw_string = CString::from_slice(symbol.as_bytes());
133             dl::symbol(self.handle, raw_string.as_ptr())
134         });
135
136         // The value must not be constructed if there is an error so
137         // the destructor does not run.
138         match maybe_symbol_value {
139             Err(err) => Err(err),
140             Ok(symbol_value) => Ok(mem::transmute(symbol_value))
141         }
142     }
143 }
144
145 #[cfg(all(test, not(target_os = "ios")))]
146 mod test {
147     use super::*;
148     use prelude::v1::*;
149     use libc;
150     use mem;
151
152     #[test]
153     #[cfg_attr(any(windows, target_os = "android"), ignore)] // FIXME #8818, #10379
154     fn test_loading_cosine() {
155         // The math library does not need to be loaded since it is already
156         // statically linked in
157         let none: Option<&Path> = None; // appease the typechecker
158         let libm = match DynamicLibrary::open(none) {
159             Err(error) => panic!("Could not load self as module: {}", error),
160             Ok(libm) => libm
161         };
162
163         let cosine: extern fn(libc::c_double) -> libc::c_double = unsafe {
164             match libm.symbol("cos") {
165                 Err(error) => panic!("Could not load function cos: {}", error),
166                 Ok(cosine) => mem::transmute::<*mut u8, _>(cosine)
167             }
168         };
169
170         let argument = 0.0;
171         let expected_result = 1.0;
172         let result = cosine(argument);
173         if result != expected_result {
174             panic!("cos({}) != {} but equaled {} instead", argument,
175                    expected_result, result)
176         }
177     }
178
179     #[test]
180     #[cfg(any(target_os = "linux",
181               target_os = "macos",
182               target_os = "freebsd",
183               target_os = "dragonfly"))]
184     fn test_errors_do_not_crash() {
185         // Open /dev/null as a library to get an error, and make sure
186         // that only causes an error, and not a crash.
187         let path = Path::new("/dev/null");
188         match DynamicLibrary::open(Some(&path)) {
189             Err(_) => {}
190             Ok(_) => panic!("Successfully opened the empty library.")
191         }
192     }
193 }
194
195 #[cfg(any(target_os = "linux",
196           target_os = "android",
197           target_os = "macos",
198           target_os = "ios",
199           target_os = "freebsd",
200           target_os = "dragonfly"))]
201 pub mod dl {
202     pub use self::Rtld::*;
203     use prelude::v1::*;
204
205     use ffi::{self, CString};
206     use str;
207     use libc;
208     use ptr;
209
210     pub unsafe fn open_external(filename: &[u8]) -> *mut u8 {
211         let s = CString::from_slice(filename);
212         dlopen(s.as_ptr(), Lazy as libc::c_int) as *mut u8
213     }
214
215     pub unsafe fn open_internal() -> *mut u8 {
216         dlopen(ptr::null(), Lazy as libc::c_int) 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, MUTEX_INIT};
223         static LOCK: StaticMutex = MUTEX_INIT;
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 = dlerror();
229
230             let result = f();
231
232             let last_error = dlerror() as *const _;
233             let ret = if ptr::null() == last_error {
234                 Ok(result)
235             } else {
236                 let s = ffi::c_str_to_bytes(&last_error);
237                 Err(str::from_utf8(s).unwrap().to_string())
238             };
239
240             ret
241         }
242     }
243
244     pub unsafe fn symbol(handle: *mut u8,
245                          symbol: *const libc::c_char) -> *mut u8 {
246         dlsym(handle as *mut libc::c_void, symbol) as *mut u8
247     }
248     pub unsafe fn close(handle: *mut u8) {
249         dlclose(handle as *mut libc::c_void); ()
250     }
251
252     #[derive(Copy)]
253     pub enum Rtld {
254         Lazy = 1,
255         Now = 2,
256         Global = 256,
257         Local = 0,
258     }
259
260     #[link_name = "dl"]
261     extern {
262         fn dlopen(filename: *const libc::c_char,
263                   flag: libc::c_int) -> *mut libc::c_void;
264         fn dlerror() -> *mut libc::c_char;
265         fn dlsym(handle: *mut libc::c_void,
266                  symbol: *const libc::c_char) -> *mut libc::c_void;
267         fn dlclose(handle: *mut libc::c_void) -> libc::c_int;
268     }
269 }
270
271 #[cfg(target_os = "windows")]
272 pub mod dl {
273     use iter::IteratorExt;
274     use libc;
275     use ops::FnOnce;
276     use os;
277     use ptr;
278     use result::Result;
279     use result::Result::{Ok, Err};
280     use slice::SliceExt;
281     use str::StrExt;
282     use str;
283     use string::String;
284     use vec::Vec;
285
286     pub unsafe fn open_external(filename: &[u8]) -> *mut u8 {
287         // Windows expects Unicode data
288         let filename_str = str::from_utf8(filename).unwrap();
289         let mut filename_str: Vec<u16> = filename_str.utf16_units().collect();
290         filename_str.push(0);
291         LoadLibraryW(filename_str.as_ptr() as *const libc::c_void) as *mut u8
292     }
293
294     pub unsafe fn open_internal() -> *mut u8 {
295         let mut handle = ptr::null_mut();
296         GetModuleHandleExW(0 as libc::DWORD, ptr::null(), &mut handle);
297         handle as *mut u8
298     }
299
300     pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where
301         F: FnOnce() -> T,
302     {
303         unsafe {
304             SetLastError(0);
305
306             let result = f();
307
308             let error = os::errno();
309             if 0 == error {
310                 Ok(result)
311             } else {
312                 Err(format!("Error code {}", error))
313             }
314         }
315     }
316
317     pub unsafe fn symbol(handle: *mut u8, symbol: *const libc::c_char) -> *mut u8 {
318         GetProcAddress(handle as *mut libc::c_void, symbol) as *mut u8
319     }
320     pub unsafe fn close(handle: *mut u8) {
321         FreeLibrary(handle as *mut libc::c_void); ()
322     }
323
324     #[allow(non_snake_case)]
325     extern "system" {
326         fn SetLastError(error: libc::size_t);
327         fn LoadLibraryW(name: *const libc::c_void) -> *mut libc::c_void;
328         fn GetModuleHandleExW(dwFlags: libc::DWORD, name: *const u16,
329                               handle: *mut *mut libc::c_void)
330                               -> *mut libc::c_void;
331         fn GetProcAddress(handle: *mut libc::c_void,
332                           name: *const libc::c_char) -> *mut libc::c_void;
333         fn FreeLibrary(handle: *mut libc::c_void);
334     }
335 }