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