]> git.proxmox.com Git - rustc.git/blob - src/librustc_back/dynamic_lib.rs
Imported Upstream version 1.9.0+dfsg1
[rustc.git] / src / librustc_back / dynamic_lib.rs
1 // Copyright 2013-2015 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 //! Dynamic library facilities.
12 //!
13 //! A simple wrapper over the platform's dynamic library facilities
14
15 use std::env;
16 use std::ffi::{CString, OsString};
17 use std::path::{Path, PathBuf};
18
19 pub struct DynamicLibrary {
20 handle: *mut u8
21 }
22
23 impl Drop for DynamicLibrary {
24 fn drop(&mut self) {
25 unsafe {
26 dl::close(self.handle)
27 }
28 }
29 }
30
31 impl DynamicLibrary {
32 /// Lazily open a dynamic library. When passed None it gives a
33 /// handle to the calling process
34 pub fn open(filename: Option<&Path>) -> Result<DynamicLibrary, String> {
35 let maybe_library = dl::open(filename.map(|path| path.as_os_str()));
36
37 // The dynamic library must not be constructed if there is
38 // an error opening the library so the destructor does not
39 // run.
40 match maybe_library {
41 Err(err) => Err(err),
42 Ok(handle) => Ok(DynamicLibrary { handle: handle })
43 }
44 }
45
46 /// Prepends a path to this process's search path for dynamic libraries
47 pub fn prepend_search_path(path: &Path) {
48 let mut search_path = DynamicLibrary::search_path();
49 search_path.insert(0, path.to_path_buf());
50 env::set_var(DynamicLibrary::envvar(), &DynamicLibrary::create_path(&search_path));
51 }
52
53 /// From a slice of paths, create a new vector which is suitable to be an
54 /// environment variable for this platforms dylib search path.
55 pub fn create_path(path: &[PathBuf]) -> OsString {
56 let mut newvar = OsString::new();
57 for (i, path) in path.iter().enumerate() {
58 if i > 0 { newvar.push(DynamicLibrary::separator()); }
59 newvar.push(path);
60 }
61 return newvar;
62 }
63
64 /// Returns the environment variable for this process's dynamic library
65 /// search path
66 pub fn envvar() -> &'static str {
67 if cfg!(windows) {
68 "PATH"
69 } else if cfg!(target_os = "macos") {
70 "DYLD_LIBRARY_PATH"
71 } else {
72 "LD_LIBRARY_PATH"
73 }
74 }
75
76 fn separator() -> &'static str {
77 if cfg!(windows) { ";" } else { ":" }
78 }
79
80 /// Returns the current search path for dynamic libraries being used by this
81 /// process
82 pub fn search_path() -> Vec<PathBuf> {
83 match env::var_os(DynamicLibrary::envvar()) {
84 Some(var) => env::split_paths(&var).collect(),
85 None => Vec::new(),
86 }
87 }
88
89 /// Accesses the value at the symbol of the dynamic library.
90 pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<*mut T, String> {
91 // This function should have a lifetime constraint of 'a on
92 // T but that feature is still unimplemented
93
94 let raw_string = CString::new(symbol).unwrap();
95 let maybe_symbol_value = dl::symbol(self.handle, raw_string.as_ptr());
96
97 // The value must not be constructed if there is an error so
98 // the destructor does not run.
99 match maybe_symbol_value {
100 Err(err) => Err(err),
101 Ok(symbol_value) => Ok(symbol_value as *mut T)
102 }
103 }
104 }
105
106 #[cfg(test)]
107 mod tests {
108 use super::*;
109 use libc;
110 use std::mem;
111
112 #[test]
113 fn test_loading_cosine() {
114 if cfg!(windows) {
115 return
116 }
117
118 // The math library does not need to be loaded since it is already
119 // statically linked in
120 let libm = match DynamicLibrary::open(None) {
121 Err(error) => panic!("Could not load self as module: {}", error),
122 Ok(libm) => libm
123 };
124
125 let cosine: extern fn(libc::c_double) -> libc::c_double = unsafe {
126 match libm.symbol("cos") {
127 Err(error) => panic!("Could not load function cos: {}", error),
128 Ok(cosine) => mem::transmute::<*mut u8, _>(cosine)
129 }
130 };
131
132 let argument = 0.0;
133 let expected_result = 1.0;
134 let result = cosine(argument);
135 if result != expected_result {
136 panic!("cos({}) != {} but equaled {} instead", argument,
137 expected_result, result)
138 }
139 }
140
141 #[test]
142 fn test_errors_do_not_crash() {
143 use std::path::Path;
144
145 if !cfg!(unix) {
146 return
147 }
148
149 // Open /dev/null as a library to get an error, and make sure
150 // that only causes an error, and not a crash.
151 let path = Path::new("/dev/null");
152 match DynamicLibrary::open(Some(&path)) {
153 Err(_) => {}
154 Ok(_) => panic!("Successfully opened the empty library.")
155 }
156 }
157 }
158
159 #[cfg(unix)]
160 mod dl {
161 use libc;
162 use std::ffi::{CStr, OsStr, CString};
163 use std::os::unix::prelude::*;
164 use std::ptr;
165 use std::str;
166
167 pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
168 check_for_errors_in(|| {
169 unsafe {
170 match filename {
171 Some(filename) => open_external(filename),
172 None => open_internal(),
173 }
174 }
175 })
176 }
177
178 const LAZY: libc::c_int = 1;
179
180 unsafe fn open_external(filename: &OsStr) -> *mut u8 {
181 let s = CString::new(filename.as_bytes()).unwrap();
182 libc::dlopen(s.as_ptr(), LAZY) as *mut u8
183 }
184
185 unsafe fn open_internal() -> *mut u8 {
186 libc::dlopen(ptr::null(), LAZY) as *mut u8
187 }
188
189 pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where
190 F: FnOnce() -> T,
191 {
192 use std::sync::StaticMutex;
193 static LOCK: StaticMutex = StaticMutex::new();
194 unsafe {
195 // dlerror isn't thread safe, so we need to lock around this entire
196 // sequence
197 let _guard = LOCK.lock();
198 let _old_error = libc::dlerror();
199
200 let result = f();
201
202 let last_error = libc::dlerror() as *const _;
203 let ret = if ptr::null() == last_error {
204 Ok(result)
205 } else {
206 let s = CStr::from_ptr(last_error).to_bytes();
207 Err(str::from_utf8(s).unwrap().to_owned())
208 };
209
210 ret
211 }
212 }
213
214 pub unsafe fn symbol(handle: *mut u8,
215 symbol: *const libc::c_char)
216 -> Result<*mut u8, String> {
217 check_for_errors_in(|| {
218 libc::dlsym(handle as *mut libc::c_void, symbol) as *mut u8
219 })
220 }
221 pub unsafe fn close(handle: *mut u8) {
222 libc::dlclose(handle as *mut libc::c_void); ()
223 }
224 }
225
226 #[cfg(windows)]
227 mod dl {
228 use std::ffi::OsStr;
229 use std::io;
230 use std::os::windows::prelude::*;
231 use std::ptr;
232
233 use libc::{c_uint, c_void, c_char};
234
235 type DWORD = u32;
236 type HMODULE = *mut u8;
237 type BOOL = i32;
238 type LPCWSTR = *const u16;
239 type LPCSTR = *const i8;
240
241 extern "system" {
242 fn SetThreadErrorMode(dwNewMode: DWORD,
243 lpOldMode: *mut DWORD) -> c_uint;
244 fn LoadLibraryW(name: LPCWSTR) -> HMODULE;
245 fn GetModuleHandleExW(dwFlags: DWORD,
246 name: LPCWSTR,
247 handle: *mut HMODULE) -> BOOL;
248 fn GetProcAddress(handle: HMODULE,
249 name: LPCSTR) -> *mut c_void;
250 fn FreeLibrary(handle: HMODULE) -> BOOL;
251 }
252
253 pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
254 // disable "dll load failed" error dialog.
255 let prev_error_mode = unsafe {
256 // SEM_FAILCRITICALERRORS 0x01
257 let new_error_mode = 1;
258 let mut prev_error_mode = 0;
259 let result = SetThreadErrorMode(new_error_mode,
260 &mut prev_error_mode);
261 if result == 0 {
262 return Err(io::Error::last_os_error().to_string())
263 }
264 prev_error_mode
265 };
266
267 let result = match filename {
268 Some(filename) => {
269 let filename_str: Vec<_> =
270 filename.encode_wide().chain(Some(0)).collect();
271 let result = unsafe {
272 LoadLibraryW(filename_str.as_ptr())
273 };
274 ptr_result(result)
275 }
276 None => {
277 let mut handle = ptr::null_mut();
278 let succeeded = unsafe {
279 GetModuleHandleExW(0 as DWORD, ptr::null(), &mut handle)
280 };
281 if succeeded == 0 {
282 Err(io::Error::last_os_error().to_string())
283 } else {
284 Ok(handle as *mut u8)
285 }
286 }
287 };
288
289 unsafe {
290 SetThreadErrorMode(prev_error_mode, ptr::null_mut());
291 }
292
293 result
294 }
295
296 pub unsafe fn symbol(handle: *mut u8,
297 symbol: *const c_char)
298 -> Result<*mut u8, String> {
299 let ptr = GetProcAddress(handle as HMODULE, symbol) as *mut u8;
300 ptr_result(ptr)
301 }
302
303 pub unsafe fn close(handle: *mut u8) {
304 FreeLibrary(handle as HMODULE);
305 }
306
307 fn ptr_result<T>(ptr: *mut T) -> Result<*mut T, String> {
308 if ptr.is_null() {
309 Err(io::Error::last_os_error().to_string())
310 } else {
311 Ok(ptr)
312 }
313 }
314 }