]> git.lizzy.rs Git - rust.git/blob - src/libstd/unstable/dynamic_lib.rs
rustc: Add search paths to dylib load paths
[rust.git] / src / libstd / unstable / dynamic_lib.rs
1 // Copyright 2013 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 use c_str::ToCStr;
20 use cast;
21 use ops::*;
22 use option::*;
23 use os;
24 use path::GenericPath;
25 use path;
26 use result::*;
27 use str;
28
29 pub struct DynamicLibrary { handle: *u8}
30
31 impl Drop for DynamicLibrary {
32     fn drop(&mut self) {
33         match dl::check_for_errors_in(|| {
34             unsafe {
35                 dl::close(self.handle)
36             }
37         }) {
38             Ok(()) => {},
39             Err(str) => fail!("{}", str)
40         }
41     }
42 }
43
44 impl DynamicLibrary {
45     /// Lazily open a dynamic library. When passed None it gives a
46     /// handle to the calling process
47     pub fn open(filename: Option<&path::Path>) -> Result<DynamicLibrary, ~str> {
48         unsafe {
49             let maybe_library = dl::check_for_errors_in(|| {
50                 match filename {
51                     Some(name) => dl::open_external(name),
52                     None => dl::open_internal()
53                 }
54             });
55
56             // The dynamic library must not be constructed if there is
57             // an error opening the library so the destructor does not
58             // run.
59             match maybe_library {
60                 Err(err) => Err(err),
61                 Ok(handle) => Ok(DynamicLibrary { handle: handle })
62             }
63         }
64     }
65
66     /// Appends a path to the system search path for dynamic libraries
67     pub fn add_search_path(path: &path::Path) {
68         let (envvar, sep) = if cfg!(windows) {
69             ("PATH", ';' as u8)
70         } else if cfg!(target_os = "macos") {
71             ("DYLD_LIBRARY_PATH", ':' as u8)
72         } else {
73             ("LD_LIBRARY_PATH", ':' as u8)
74         };
75         let newenv = os::getenv_as_bytes(envvar).unwrap_or(~[]);
76         let newenv = newenv + &[sep] + path.as_vec();
77         os::setenv(envvar, str::from_utf8(newenv).unwrap());
78     }
79
80     /// Access the value at the symbol of the dynamic library
81     pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<T, ~str> {
82         // This function should have a lifetime constraint of 'a on
83         // T but that feature is still unimplemented
84
85         let maybe_symbol_value = dl::check_for_errors_in(|| {
86             symbol.with_c_str(|raw_string| {
87                 dl::symbol(self.handle, raw_string)
88             })
89         });
90
91         // The value must not be constructed if there is an error so
92         // the destructor does not run.
93         match maybe_symbol_value {
94             Err(err) => Err(err),
95             Ok(symbol_value) => Ok(cast::transmute(symbol_value))
96         }
97     }
98 }
99
100 #[cfg(test)]
101 mod test {
102     use super::*;
103     use prelude::*;
104     use libc;
105
106     #[test]
107     #[ignore(cfg(windows))] // FIXME #8818
108     #[ignore(cfg(target_os="android"))] // FIXME(#10379)
109     fn test_loading_cosine() {
110         // The math library does not need to be loaded since it is already
111         // statically linked in
112         let libm = match DynamicLibrary::open(None) {
113             Err(error) => fail!("Could not load self as module: {}", error),
114             Ok(libm) => libm
115         };
116
117         let cosine: extern fn(libc::c_double) -> libc::c_double = unsafe {
118             match libm.symbol("cos") {
119                 Err(error) => fail!("Could not load function cos: {}", error),
120                 Ok(cosine) => cosine
121             }
122         };
123
124         let argument = 0.0;
125         let expected_result = 1.0;
126         let result = cosine(argument);
127         if result != expected_result {
128             fail!("cos({:?}) != {:?} but equaled {:?} instead", argument,
129                    expected_result, result)
130         }
131     }
132
133     #[test]
134     #[cfg(target_os = "linux")]
135     #[cfg(target_os = "macos")]
136     #[cfg(target_os = "freebsd")]
137     fn test_errors_do_not_crash() {
138         // Open /dev/null as a library to get an error, and make sure
139         // that only causes an error, and not a crash.
140         let path = GenericPath::new("/dev/null");
141         match DynamicLibrary::open(Some(&path)) {
142             Err(_) => {}
143             Ok(_) => fail!("Successfully opened the empty library.")
144         }
145     }
146 }
147
148 #[cfg(target_os = "linux")]
149 #[cfg(target_os = "android")]
150 #[cfg(target_os = "macos")]
151 #[cfg(target_os = "freebsd")]
152 pub mod dl {
153     use c_str::ToCStr;
154     use libc;
155     use path;
156     use ptr;
157     use str;
158     use result::*;
159
160     pub unsafe fn open_external(filename: &path::Path) -> *u8 {
161         filename.with_c_str(|raw_name| {
162             dlopen(raw_name, Lazy as libc::c_int) as *u8
163         })
164     }
165
166     pub unsafe fn open_internal() -> *u8 {
167         dlopen(ptr::null(), Lazy as libc::c_int) as *u8
168     }
169
170     pub fn check_for_errors_in<T>(f: || -> T) -> Result<T, ~str> {
171         use unstable::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
172         static mut lock: StaticNativeMutex = NATIVE_MUTEX_INIT;
173         unsafe {
174             // dlerror isn't thread safe, so we need to lock around this entire
175             // sequence
176             let _guard = lock.lock();
177             let _old_error = dlerror();
178
179             let result = f();
180
181             let last_error = dlerror();
182             let ret = if ptr::null() == last_error {
183                 Ok(result)
184             } else {
185                 Err(str::raw::from_c_str(last_error))
186             };
187
188             ret
189         }
190     }
191
192     pub unsafe fn symbol(handle: *u8, symbol: *libc::c_char) -> *u8 {
193         dlsym(handle as *libc::c_void, symbol) as *u8
194     }
195     pub unsafe fn close(handle: *u8) {
196         dlclose(handle as *libc::c_void); ()
197     }
198
199     pub enum RTLD {
200         Lazy = 1,
201         Now = 2,
202         Global = 256,
203         Local = 0,
204     }
205
206     #[link_name = "dl"]
207     extern {
208         fn dlopen(filename: *libc::c_char, flag: libc::c_int) -> *libc::c_void;
209         fn dlerror() -> *libc::c_char;
210         fn dlsym(handle: *libc::c_void, symbol: *libc::c_char) -> *libc::c_void;
211         fn dlclose(handle: *libc::c_void) -> libc::c_int;
212     }
213 }
214
215 #[cfg(target_os = "win32")]
216 pub mod dl {
217     use libc;
218     use os;
219     use path::GenericPath;
220     use path;
221     use ptr;
222     use result::{Ok, Err, Result};
223
224     pub unsafe fn open_external(filename: &path::Path) -> *u8 {
225         os::win32::as_utf16_p(filename.as_str().unwrap(), |raw_name| {
226             LoadLibraryW(raw_name as *libc::c_void) as *u8
227         })
228     }
229
230     pub unsafe fn open_internal() -> *u8 {
231         let handle = ptr::null();
232         GetModuleHandleExW(0 as libc::DWORD, ptr::null(), &handle as **libc::c_void);
233         handle as *u8
234     }
235
236     pub fn check_for_errors_in<T>(f: || -> T) -> Result<T, ~str> {
237         unsafe {
238             SetLastError(0);
239
240             let result = f();
241
242             let error = os::errno();
243             if 0 == error {
244                 Ok(result)
245             } else {
246                 Err(format!("Error code {}", error))
247             }
248         }
249     }
250
251     pub unsafe fn symbol(handle: *u8, symbol: *libc::c_char) -> *u8 {
252         GetProcAddress(handle as *libc::c_void, symbol) as *u8
253     }
254     pub unsafe fn close(handle: *u8) {
255         FreeLibrary(handle as *libc::c_void); ()
256     }
257
258     extern "system" {
259         fn SetLastError(error: libc::size_t);
260         fn LoadLibraryW(name: *libc::c_void) -> *libc::c_void;
261         fn GetModuleHandleExW(dwFlags: libc::DWORD, name: *u16,
262                               handle: **libc::c_void) -> *libc::c_void;
263         fn GetProcAddress(handle: *libc::c_void, name: *libc::c_char) -> *libc::c_void;
264         fn FreeLibrary(handle: *libc::c_void);
265     }
266 }