]> git.lizzy.rs Git - rust.git/blob - src/librustc_back/dynamic_lib.rs
Haiku: add missing cases of using LIBRARY_PATH
[rust.git] / src / librustc_back / dynamic_lib.rs
1 // Copyright 2013-2015 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 use std::env;
16 use std::ffi::{CString, OsString};
17 use std::path::{Path, PathBuf};
18
19 pub struct DynamicLibrary {
20     handle: *mut u8
21 }
22
23 impl Drop for DynamicLibrary {
24     fn drop(&mut self) {
25         unsafe {
26             dl::close(self.handle)
27         }
28     }
29 }
30
31 impl DynamicLibrary {
32     /// Lazily open a dynamic library. When passed None it gives a
33     /// handle to the calling process
34     pub fn open(filename: Option<&Path>) -> Result<DynamicLibrary, String> {
35         let maybe_library = dl::open(filename.map(|path| path.as_os_str()));
36
37         // The dynamic library must not be constructed if there is
38         // an error opening the library so the destructor does not
39         // run.
40         match maybe_library {
41             Err(err) => Err(err),
42             Ok(handle) => Ok(DynamicLibrary { handle: handle })
43         }
44     }
45
46     /// Prepends a path to this process's search path for dynamic libraries
47     pub fn prepend_search_path(path: &Path) {
48         let mut search_path = DynamicLibrary::search_path();
49         search_path.insert(0, path.to_path_buf());
50         env::set_var(DynamicLibrary::envvar(), &DynamicLibrary::create_path(&search_path));
51     }
52
53     /// From a slice of paths, create a new vector which is suitable to be an
54     /// environment variable for this platforms dylib search path.
55     pub fn create_path(path: &[PathBuf]) -> OsString {
56         let mut newvar = OsString::new();
57         for (i, path) in path.iter().enumerate() {
58             if i > 0 { newvar.push(DynamicLibrary::separator()); }
59             newvar.push(path);
60         }
61         return newvar;
62     }
63
64     /// Returns the environment variable for this process's dynamic library
65     /// search path
66     pub fn envvar() -> &'static str {
67         if cfg!(windows) {
68             "PATH"
69         } else if cfg!(target_os = "macos") {
70             "DYLD_LIBRARY_PATH"
71         } else if cfg!(target_os = "haiku") {
72             "LIBRARY_PATH"
73         } else {
74             "LD_LIBRARY_PATH"
75         }
76     }
77
78     fn separator() -> &'static str {
79         if cfg!(windows) { ";" } else { ":" }
80     }
81
82     /// Returns the current search path for dynamic libraries being used by this
83     /// process
84     pub fn search_path() -> Vec<PathBuf> {
85         match env::var_os(DynamicLibrary::envvar()) {
86             Some(var) => env::split_paths(&var).collect(),
87             None => Vec::new(),
88         }
89     }
90
91     /// Accesses the value at the symbol of the dynamic library.
92     pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<*mut T, String> {
93         // This function should have a lifetime constraint of 'a on
94         // T but that feature is still unimplemented
95
96         let raw_string = CString::new(symbol).unwrap();
97         let maybe_symbol_value = dl::symbol(self.handle, raw_string.as_ptr());
98
99         // The value must not be constructed if there is an error so
100         // the destructor does not run.
101         match maybe_symbol_value {
102             Err(err) => Err(err),
103             Ok(symbol_value) => Ok(symbol_value as *mut T)
104         }
105     }
106 }
107
108 #[cfg(test)]
109 mod tests {
110     use super::*;
111     use libc;
112     use std::mem;
113
114     #[test]
115     fn test_loading_cosine() {
116         if cfg!(windows) {
117             return
118         }
119
120         // The math library does not need to be loaded since it is already
121         // statically linked in
122         let libm = match DynamicLibrary::open(None) {
123             Err(error) => panic!("Could not load self as module: {}", error),
124             Ok(libm) => libm
125         };
126
127         let cosine: extern fn(libc::c_double) -> libc::c_double = unsafe {
128             match libm.symbol("cos") {
129                 Err(error) => panic!("Could not load function cos: {}", error),
130                 Ok(cosine) => mem::transmute::<*mut u8, _>(cosine)
131             }
132         };
133
134         let argument = 0.0;
135         let expected_result = 1.0;
136         let result = cosine(argument);
137         if result != expected_result {
138             panic!("cos({}) != {} but equaled {} instead", argument,
139                    expected_result, result)
140         }
141     }
142
143     #[test]
144     fn test_errors_do_not_crash() {
145         use std::path::Path;
146
147         if !cfg!(unix) {
148             return
149         }
150
151         // Open /dev/null as a library to get an error, and make sure
152         // that only causes an error, and not a crash.
153         let path = Path::new("/dev/null");
154         match DynamicLibrary::open(Some(&path)) {
155             Err(_) => {}
156             Ok(_) => panic!("Successfully opened the empty library.")
157         }
158     }
159 }
160
161 #[cfg(unix)]
162 mod dl {
163     use libc;
164     use std::ffi::{CStr, OsStr, CString};
165     use std::os::unix::prelude::*;
166     use std::ptr;
167     use std::str;
168
169     pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
170         check_for_errors_in(|| {
171             unsafe {
172                 match filename {
173                     Some(filename) => open_external(filename),
174                     None => open_internal(),
175                 }
176             }
177         })
178     }
179
180     const LAZY: libc::c_int = 1;
181
182     unsafe fn open_external(filename: &OsStr) -> *mut u8 {
183         let s = CString::new(filename.as_bytes()).unwrap();
184         libc::dlopen(s.as_ptr(), LAZY) as *mut u8
185     }
186
187     unsafe fn open_internal() -> *mut u8 {
188         libc::dlopen(ptr::null(), LAZY) as *mut u8
189     }
190
191     pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where
192         F: FnOnce() -> T,
193     {
194         use std::sync::{Mutex, Once, ONCE_INIT};
195         static INIT: Once = ONCE_INIT;
196         static mut LOCK: *mut Mutex<()> = 0 as *mut _;
197         unsafe {
198             INIT.call_once(|| {
199                 LOCK = Box::into_raw(Box::new(Mutex::new(())));
200             });
201             // dlerror isn't thread safe, so we need to lock around this entire
202             // sequence
203             let _guard = (*LOCK).lock();
204             let _old_error = libc::dlerror();
205
206             let result = f();
207
208             let last_error = libc::dlerror() as *const _;
209             let ret = if ptr::null() == last_error {
210                 Ok(result)
211             } else {
212                 let s = CStr::from_ptr(last_error).to_bytes();
213                 Err(str::from_utf8(s).unwrap().to_owned())
214             };
215
216             ret
217         }
218     }
219
220     pub unsafe fn symbol(handle: *mut u8,
221                          symbol: *const libc::c_char)
222                          -> Result<*mut u8, String> {
223         check_for_errors_in(|| {
224             libc::dlsym(handle as *mut libc::c_void, symbol) as *mut u8
225         })
226     }
227     pub unsafe fn close(handle: *mut u8) {
228         libc::dlclose(handle as *mut libc::c_void); ()
229     }
230 }
231
232 #[cfg(windows)]
233 mod dl {
234     use std::ffi::OsStr;
235     use std::io;
236     use std::os::windows::prelude::*;
237     use std::ptr;
238
239     use libc::{c_uint, c_void, c_char};
240
241     type DWORD = u32;
242     type HMODULE = *mut u8;
243     type BOOL = i32;
244     type LPCWSTR = *const u16;
245     type LPCSTR = *const i8;
246
247     extern "system" {
248         fn SetThreadErrorMode(dwNewMode: DWORD,
249                               lpOldMode: *mut DWORD) -> c_uint;
250         fn LoadLibraryW(name: LPCWSTR) -> HMODULE;
251         fn GetModuleHandleExW(dwFlags: DWORD,
252                               name: LPCWSTR,
253                               handle: *mut HMODULE) -> BOOL;
254         fn GetProcAddress(handle: HMODULE,
255                           name: LPCSTR) -> *mut c_void;
256         fn FreeLibrary(handle: HMODULE) -> BOOL;
257     }
258
259     pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
260         // disable "dll load failed" error dialog.
261         let prev_error_mode = unsafe {
262             // SEM_FAILCRITICALERRORS 0x01
263             let new_error_mode = 1;
264             let mut prev_error_mode = 0;
265             let result = SetThreadErrorMode(new_error_mode,
266                                             &mut prev_error_mode);
267             if result == 0 {
268                 return Err(io::Error::last_os_error().to_string())
269             }
270             prev_error_mode
271         };
272
273         let result = match filename {
274             Some(filename) => {
275                 let filename_str: Vec<_> =
276                     filename.encode_wide().chain(Some(0)).collect();
277                 let result = unsafe {
278                     LoadLibraryW(filename_str.as_ptr())
279                 };
280                 ptr_result(result)
281             }
282             None => {
283                 let mut handle = ptr::null_mut();
284                 let succeeded = unsafe {
285                     GetModuleHandleExW(0 as DWORD, ptr::null(), &mut handle)
286                 };
287                 if succeeded == 0 {
288                     Err(io::Error::last_os_error().to_string())
289                 } else {
290                     Ok(handle as *mut u8)
291                 }
292             }
293         };
294
295         unsafe {
296             SetThreadErrorMode(prev_error_mode, ptr::null_mut());
297         }
298
299         result
300     }
301
302     pub unsafe fn symbol(handle: *mut u8,
303                          symbol: *const c_char)
304                          -> Result<*mut u8, String> {
305         let ptr = GetProcAddress(handle as HMODULE, symbol) as *mut u8;
306         ptr_result(ptr)
307     }
308
309     pub unsafe fn close(handle: *mut u8) {
310         FreeLibrary(handle as HMODULE);
311     }
312
313     fn ptr_result<T>(ptr: *mut T) -> Result<*mut T, String> {
314         if ptr.is_null() {
315             Err(io::Error::last_os_error().to_string())
316         } else {
317             Ok(ptr)
318         }
319     }
320 }