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.
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.
11 //! Dynamic library facilities.
13 //! A simple wrapper over the platform's dynamic library facilities
15 #![unstable(feature = "std_misc")]
16 #![allow(missing_docs)]
21 use ffi::{CString, OsString};
23 use path::{Path, PathBuf};
25 pub struct DynamicLibrary {
29 impl Drop for DynamicLibrary {
31 match dl::check_for_errors_in(|| {
33 dl::close(self.handle)
37 Err(str) => panic!("{}", str)
43 /// Lazily open a dynamic library. When passed None it gives a
44 /// handle to the calling process
45 pub fn open(filename: Option<&Path>) -> Result<DynamicLibrary, String> {
46 let maybe_library = dl::open(filename.map(|path| path.as_os_str()));
48 // The dynamic library must not be constructed if there is
49 // an error opening the library so the destructor does not
53 Ok(handle) => Ok(DynamicLibrary { handle: handle })
57 /// Prepends a path to this process's search path for dynamic libraries
58 pub fn prepend_search_path(path: &Path) {
59 let mut search_path = DynamicLibrary::search_path();
60 search_path.insert(0, path.to_path_buf());
61 env::set_var(DynamicLibrary::envvar(), &DynamicLibrary::create_path(&search_path));
64 /// From a slice of paths, create a new vector which is suitable to be an
65 /// environment variable for this platforms dylib search path.
66 pub fn create_path(path: &[PathBuf]) -> OsString {
67 let mut newvar = OsString::new();
68 for (i, path) in path.iter().enumerate() {
69 if i > 0 { newvar.push(DynamicLibrary::separator()); }
75 /// Returns the environment variable for this process's dynamic library
77 pub fn envvar() -> &'static str {
80 } else if cfg!(target_os = "macos") {
87 fn separator() -> &'static str {
88 if cfg!(windows) { ";" } else { ":" }
91 /// Returns the current search path for dynamic libraries being used by this
93 pub fn search_path() -> Vec<PathBuf> {
94 match env::var_os(DynamicLibrary::envvar()) {
95 Some(var) => env::split_paths(&var).collect(),
100 /// Accesses the value at the symbol of the dynamic library.
101 pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<*mut T, String> {
102 // This function should have a lifetime constraint of 'a on
103 // T but that feature is still unimplemented
105 let raw_string = CString::new(symbol).unwrap();
106 let maybe_symbol_value = dl::check_for_errors_in(|| {
107 dl::symbol(self.handle, raw_string.as_ptr())
110 // The value must not be constructed if there is an error so
111 // the destructor does not run.
112 match maybe_symbol_value {
113 Err(err) => Err(err),
114 Ok(symbol_value) => Ok(mem::transmute(symbol_value))
119 #[cfg(all(test, not(target_os = "ios")))]
128 #[cfg_attr(any(windows,
129 target_os = "android", // FIXME #10379
130 target_env = "musl"), ignore)]
131 fn test_loading_cosine() {
132 // The math library does not need to be loaded since it is already
133 // statically linked in
134 let libm = match DynamicLibrary::open(None) {
135 Err(error) => panic!("Could not load self as module: {}", error),
139 let cosine: extern fn(libc::c_double) -> libc::c_double = unsafe {
140 match libm.symbol("cos") {
141 Err(error) => panic!("Could not load function cos: {}", error),
142 Ok(cosine) => mem::transmute::<*mut u8, _>(cosine)
147 let expected_result = 1.0;
148 let result = cosine(argument);
149 if result != expected_result {
150 panic!("cos({}) != {} but equaled {} instead", argument,
151 expected_result, result)
156 #[cfg(any(target_os = "linux",
158 target_os = "freebsd",
159 target_os = "dragonfly",
160 target_os = "bitrig",
161 target_os = "openbsd"))]
162 fn test_errors_do_not_crash() {
163 // Open /dev/null as a library to get an error, and make sure
164 // that only causes an error, and not a crash.
165 let path = Path::new("/dev/null");
166 match DynamicLibrary::open(Some(&path)) {
168 Ok(_) => panic!("Successfully opened the empty library.")
173 #[cfg(any(target_os = "linux",
174 target_os = "android",
177 target_os = "freebsd",
178 target_os = "dragonfly",
179 target_os = "bitrig",
180 target_os = "openbsd"))]
184 use ffi::{CStr, OsStr};
189 pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
190 check_for_errors_in(|| {
193 Some(filename) => open_external(filename),
194 None => open_internal(),
200 const LAZY: libc::c_int = 1;
202 unsafe fn open_external(filename: &OsStr) -> *mut u8 {
203 let s = filename.to_cstring().unwrap();
204 dlopen(s.as_ptr(), LAZY) as *mut u8
207 unsafe fn open_internal() -> *mut u8 {
208 dlopen(ptr::null(), LAZY) as *mut u8
211 pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where
214 use sync::{StaticMutex, MUTEX_INIT};
215 static LOCK: StaticMutex = MUTEX_INIT;
217 // dlerror isn't thread safe, so we need to lock around this entire
219 let _guard = LOCK.lock();
220 let _old_error = dlerror();
224 let last_error = dlerror() as *const _;
225 let ret = if ptr::null() == last_error {
228 let s = CStr::from_ptr(last_error).to_bytes();
229 Err(str::from_utf8(s).unwrap().to_string())
236 pub unsafe fn symbol(handle: *mut u8,
237 symbol: *const libc::c_char) -> *mut u8 {
238 dlsym(handle as *mut libc::c_void, symbol) as *mut u8
240 pub unsafe fn close(handle: *mut u8) {
241 dlclose(handle as *mut libc::c_void); ()
245 fn dlopen(filename: *const libc::c_char,
246 flag: libc::c_int) -> *mut libc::c_void;
247 fn dlerror() -> *mut libc::c_char;
248 fn dlsym(handle: *mut libc::c_void,
249 symbol: *const libc::c_char) -> *mut libc::c_void;
250 fn dlclose(handle: *mut libc::c_void) -> libc::c_int;
254 #[cfg(target_os = "windows")]
260 use libc::consts::os::extra::ERROR_CALL_NOT_IMPLEMENTED;
262 use os::windows::prelude::*;
264 use sys::c::compat::kernel32::SetThreadErrorMode;
266 pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
267 // disable "dll load failed" error dialog.
268 let mut use_thread_mode = true;
269 let prev_error_mode = unsafe {
270 // SEM_FAILCRITICALERRORS 0x01
271 let new_error_mode = 1;
272 let mut prev_error_mode = 0;
273 // Windows >= 7 supports thread error mode.
274 let result = SetThreadErrorMode(new_error_mode, &mut prev_error_mode);
276 let err = os::errno();
277 if err as libc::c_int == ERROR_CALL_NOT_IMPLEMENTED {
278 use_thread_mode = false;
279 // SetThreadErrorMode not found. use fallback solution:
280 // SetErrorMode() Note that SetErrorMode is process-wide so
281 // this can cause race condition! However, since even
282 // Windows APIs do not care of such problem (#20650), we
283 // just assume SetErrorMode race is not a great deal.
284 prev_error_mode = SetErrorMode(new_error_mode);
294 let result = match filename {
296 let filename_str: Vec<_> =
297 filename.encode_wide().chain(Some(0).into_iter()).collect();
298 let result = unsafe {
299 LoadLibraryW(filename_str.as_ptr() as *const libc::c_void)
301 // beware: Vec/String may change errno during drop!
302 // so we get error here.
303 if result == ptr::null_mut() {
304 let errno = os::errno();
305 Err(os::error_string(errno))
307 Ok(result as *mut u8)
311 let mut handle = ptr::null_mut();
312 let succeeded = unsafe {
313 GetModuleHandleExW(0 as libc::DWORD, ptr::null(), &mut handle)
315 if succeeded == libc::FALSE {
316 let errno = os::errno();
317 Err(os::error_string(errno))
319 Ok(handle as *mut u8)
326 SetThreadErrorMode(prev_error_mode, ptr::null_mut());
328 SetErrorMode(prev_error_mode);
335 pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where
343 let error = os::errno();
347 Err(format!("Error code {}", error))
352 pub unsafe fn symbol(handle: *mut u8, symbol: *const libc::c_char) -> *mut u8 {
353 GetProcAddress(handle as *mut libc::c_void, symbol) as *mut u8
355 pub unsafe fn close(handle: *mut u8) {
356 FreeLibrary(handle as *mut libc::c_void); ()
359 #[allow(non_snake_case)]
361 fn SetLastError(error: libc::size_t);
362 fn LoadLibraryW(name: *const libc::c_void) -> *mut libc::c_void;
363 fn GetModuleHandleExW(dwFlags: libc::DWORD, name: *const u16,
364 handle: *mut *mut libc::c_void) -> libc::BOOL;
365 fn GetProcAddress(handle: *mut libc::c_void,
366 name: *const libc::c_char) -> *mut libc::c_void;
367 fn FreeLibrary(handle: *mut libc::c_void);
368 fn SetErrorMode(uMode: libc::c_uint) -> libc::c_uint;