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