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