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