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