]> git.lizzy.rs Git - rust.git/blob - src/libstd/unstable/dynamic_lib.rs
auto merge of #9133 : dcrewi/rust/bigint-random-range, r=huonw
[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(&mut 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     #[ignore] // FIXME #9137 this library isn't thread-safe
95     fn test_loading_cosine() {
96         // The math library does not need to be loaded since it is already
97         // statically linked in
98         let libm = match DynamicLibrary::open(None) {
99             Err(error) => fail!("Could not load self as module: %s", error),
100             Ok(libm) => libm
101         };
102
103         // Unfortunately due to issue #6194 it is not possible to call
104         // this as a C function
105         let cosine: extern fn(libc::c_double) -> libc::c_double = unsafe {
106             match libm.symbol("cos") {
107                 Err(error) => fail!("Could not load function cos: %s", error),
108                 Ok(cosine) => cosine
109             }
110         };
111
112         let argument = 0.0;
113         let expected_result = 1.0;
114         let result = cosine(argument);
115         if result != expected_result {
116             fail!("cos(%?) != %? but equaled %? instead", argument,
117                   expected_result, result)
118         }
119     }
120
121     #[test]
122     #[cfg(target_os = "linux")]
123     #[cfg(target_os = "macos")]
124     #[cfg(target_os = "freebsd")]
125     #[ignore] // FIXME #9137 this library isn't thread-safe
126     fn test_errors_do_not_crash() {
127         // Open /dev/null as a library to get an error, and make sure
128         // that only causes an error, and not a crash.
129         let path = GenericPath::from_str("/dev/null");
130         match DynamicLibrary::open(Some(&path)) {
131             Err(_) => {}
132             Ok(_) => fail!("Successfully opened the empty library.")
133         }
134     }
135 }
136
137 #[cfg(target_os = "linux")]
138 #[cfg(target_os = "android")]
139 #[cfg(target_os = "macos")]
140 #[cfg(target_os = "freebsd")]
141 mod dl {
142     use c_str::ToCStr;
143     use libc;
144     use path;
145     use ptr;
146     use str;
147     use unstable::sync::atomically;
148     use result::*;
149
150     pub unsafe fn open_external(filename: &path::Path) -> *libc::c_void {
151         #[fixed_stack_segment]; #[inline(never)];
152         do filename.with_c_str |raw_name| {
153             dlopen(raw_name, Lazy as libc::c_int)
154         }
155     }
156
157     pub unsafe fn open_internal() -> *libc::c_void {
158         #[fixed_stack_segment]; #[inline(never)];
159
160         dlopen(ptr::null(), Lazy as libc::c_int)
161     }
162
163     pub fn check_for_errors_in<T>(f: &fn()->T) -> Result<T, ~str> {
164         #[fixed_stack_segment]; #[inline(never)];
165
166         unsafe {
167             do atomically {
168                 let _old_error = dlerror();
169
170                 let result = f();
171
172                 let last_error = dlerror();
173                 if ptr::null() == last_error {
174                     Ok(result)
175                 } else {
176                     Err(str::raw::from_c_str(last_error))
177                 }
178             }
179         }
180     }
181
182     pub unsafe fn symbol(handle: *libc::c_void, symbol: *libc::c_char) -> *libc::c_void {
183         #[fixed_stack_segment]; #[inline(never)];
184
185         dlsym(handle, symbol)
186     }
187     pub unsafe fn close(handle: *libc::c_void) {
188         #[fixed_stack_segment]; #[inline(never)];
189
190         dlclose(handle); ()
191     }
192
193     pub enum RTLD {
194         Lazy = 1,
195         Now = 2,
196         Global = 256,
197         Local = 0,
198     }
199
200     #[link_name = "dl"]
201     extern {
202         fn dlopen(filename: *libc::c_char, flag: libc::c_int) -> *libc::c_void;
203         fn dlerror() -> *libc::c_char;
204         fn dlsym(handle: *libc::c_void, symbol: *libc::c_char) -> *libc::c_void;
205         fn dlclose(handle: *libc::c_void) -> libc::c_int;
206     }
207 }
208
209 #[cfg(target_os = "win32")]
210 mod dl {
211     use os;
212     use libc;
213     use path;
214     use ptr;
215     use unstable::sync::atomically;
216     use result::*;
217
218     pub unsafe fn open_external(filename: &path::Path) -> *libc::c_void {
219         #[fixed_stack_segment]; #[inline(never)];
220         do os::win32::as_utf16_p(filename.to_str()) |raw_name| {
221             LoadLibraryW(raw_name)
222         }
223     }
224
225     pub unsafe fn open_internal() -> *libc::c_void {
226         #[fixed_stack_segment]; #[inline(never)];
227         let handle = ptr::null();
228         GetModuleHandleExW(0 as libc::DWORD, ptr::null(), &handle as **libc::c_void);
229         handle
230     }
231
232     pub fn check_for_errors_in<T>(f: &fn()->T) -> Result<T, ~str> {
233         #[fixed_stack_segment]; #[inline(never)];
234         unsafe {
235             do atomically {
236                 SetLastError(0);
237
238                 let result = f();
239
240                 let error = os::errno();
241                 if 0 == error {
242                     Ok(result)
243                 } else {
244                     Err(fmt!("Error code %?", error))
245                 }
246             }
247         }
248     }
249     pub unsafe fn symbol(handle: *libc::c_void, symbol: *libc::c_char) -> *libc::c_void {
250         #[fixed_stack_segment]; #[inline(never)];
251         GetProcAddress(handle, symbol)
252     }
253     pub unsafe fn close(handle: *libc::c_void) {
254         #[fixed_stack_segment]; #[inline(never)];
255         FreeLibrary(handle); ()
256     }
257
258     #[cfg(target_arch = "x86")]
259     #[link_name = "kernel32"]
260     extern "stdcall" {
261         fn SetLastError(error: u32);
262         fn LoadLibraryW(name: *u16) -> *libc::c_void;
263         fn GetModuleHandleExW(dwFlags: libc::DWORD, name: *u16,
264                               handle: **libc::c_void) -> *libc::c_void;
265         fn GetProcAddress(handle: *libc::c_void, name: *libc::c_char) -> *libc::c_void;
266         fn FreeLibrary(handle: *libc::c_void);
267     }
268
269     #[cfg(target_arch = "x86_64")]
270     #[link_name = "kernel32"]
271     extern {
272         fn SetLastError(error: u32);
273         fn LoadLibraryW(name: *u16) -> *libc::c_void;
274         fn GetModuleHandleExW(dwFlags: libc::DWORD, name: *u16,
275                               handle: **libc::c_void) -> *libc::c_void;
276         fn GetProcAddress(handle: *libc::c_void, name: *libc::c_char) -> *libc::c_void;
277         fn FreeLibrary(handle: *libc::c_void);
278     }
279 }