]> git.lizzy.rs Git - rust.git/blob - src/libstd/unstable/dynamic_lib.rs
auto merge of #7197 : rkbodenner/rust/doc-for-lib-move, 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 ptr;
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 finalize(&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         do dl::check_for_errors_in {
46             unsafe {
47                 DynamicLibrary { handle:
48                     match filename {
49                         Some(name) => dl::open_external(name),
50                         None => dl::open_internal()
51                     }
52                 }
53             }
54         }
55     }
56
57     /// Access the value at the symbol of the dynamic library
58     pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<T, ~str> {
59         // This function should have a lifetime constraint of 'self on
60         // T but that feature is still unimplemented
61
62         do dl::check_for_errors_in {
63             let symbol_value = do symbol.as_c_str |raw_string| {
64                 dl::symbol(self.handle, raw_string)
65             };
66
67             cast::transmute(symbol_value)
68         }
69     }
70 }
71
72 #[test]
73 #[ignore(cfg(windows))]
74 priv fn test_loading_cosine () {
75     // The math library does not need to be loaded since it is already
76     // statically linked in
77     let libm = match DynamicLibrary::open(None) {
78         Err (error) => fail!("Could not load self as module: %s", error),
79         Ok (libm) => libm
80     };
81
82     // Unfortunately due to issue #6194 it is not possible to call
83     // this as a C function
84     let cosine: extern fn(libc::c_double) -> libc::c_double = unsafe {
85         match libm.symbol("cos") {
86             Err (error) => fail!("Could not load function cos: %s", error),
87             Ok (cosine) => cosine
88         }
89     };
90
91     let argument = 0.0;
92     let expected_result = 1.0;
93     let result = cosine(argument);
94     if result != expected_result {
95         fail!("cos(%?) != %? but equaled %? instead", argument,
96               expected_result, result)
97     }
98 }
99
100 #[cfg(target_os = "linux")]
101 #[cfg(target_os = "android")]
102 #[cfg(target_os = "macos")]
103 #[cfg(target_os = "freebsd")]
104 mod dl {
105     use libc;
106     use path;
107     use ptr;
108     use str;
109     use task;
110     use result::*;
111
112     pub unsafe fn open_external(filename: &path::Path) -> *libc::c_void {
113         do filename.to_str().as_c_str |raw_name| {
114             dlopen(raw_name, Lazy as libc::c_int)
115         }
116     }
117
118     pub unsafe fn open_internal() -> *libc::c_void {
119         dlopen(ptr::null(), Lazy as libc::c_int)
120     }
121
122     pub fn check_for_errors_in<T>(f: &fn()->T) -> Result<T, ~str> {
123         unsafe {
124             do task::atomically {
125                 let _old_error = dlerror();
126
127                 let result = f();
128
129                 let last_error = dlerror();
130                 if ptr::null() == last_error {
131                     Ok(result)
132                 } else {
133                     Err(str::raw::from_c_str(last_error))
134                 }
135             }
136         }
137     }
138
139     pub unsafe fn symbol(handle: *libc::c_void, symbol: *libc::c_char) -> *libc::c_void {
140         dlsym(handle, symbol)
141     }
142     pub unsafe fn close(handle: *libc::c_void) {
143         dlclose(handle); ()
144     }
145
146     pub enum RTLD {
147         Lazy = 1,
148         Now = 2,
149         Global = 256,
150         Local = 0,
151     }
152
153     #[link_name = "dl"]
154     extern {
155         fn dlopen(filename: *libc::c_char, flag: libc::c_int) -> *libc::c_void;
156         fn dlerror() -> *libc::c_char;
157         fn dlsym(handle: *libc::c_void, symbol: *libc::c_char) -> *libc::c_void;
158         fn dlclose(handle: *libc::c_void) -> libc::c_int;
159     }
160 }
161
162 #[cfg(target_os = "win32")]
163 mod dl {
164     use os;
165     use libc;
166     use path;
167     use ptr;
168     use str;
169     use task;
170     use result::*;
171
172     pub unsafe fn open_external(filename: &path::Path) -> *libc::c_void {
173         do os::win32::as_utf16_p(filename.to_str()) |raw_name| {
174             LoadLibraryW(raw_name)
175         }
176     }
177
178     pub unsafe fn open_internal() -> *libc::c_void {
179         let mut handle = ptr::null();
180         GetModuleHandleExW(0 as libc::DWORD, ptr::null(), &handle as **libc::c_void);
181         handle
182     }
183
184     pub fn check_for_errors_in<T>(f: &fn()->T) -> Result<T, ~str> {
185         unsafe {
186             do task::atomically {
187                 SetLastError(0);
188
189                 let result = f();
190
191                 let error = os::errno();
192                 if 0 == error {
193                     Ok(result)
194                 } else {
195                     Err(fmt!("Error code %?", error))
196                 }
197             }
198         }
199     }
200     pub unsafe fn symbol(handle: *libc::c_void, symbol: *libc::c_char) -> *libc::c_void {
201         GetProcAddress(handle, symbol)
202     }
203     pub unsafe fn close(handle: *libc::c_void) {
204         FreeLibrary(handle); ()
205     }
206
207     #[link_name = "kernel32"]
208     extern "stdcall" {
209         fn SetLastError(error: u32);
210         fn LoadLibraryW(name: *u16) -> *libc::c_void;
211         fn GetModuleHandleExW(dwFlags: libc::DWORD, name: *u16,
212                               handle: **libc::c_void) -> *libc::c_void;
213         fn GetProcAddress(handle: *libc::c_void, name: *libc::c_char) -> *libc::c_void;
214         fn FreeLibrary(handle: *libc::c_void);
215     }
216 }