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