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