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::{AsOsStr, 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 // FIXME (#12938): Until DST lands, we cannot decompose &str into
44 // & and str, so we cannot usefully take ToCStr arguments by
45 // reference (without forcing an additional & around &str). So we
46 // are instead temporarily adding an instance for &Path, so that
47 // we can take ToCStr as owned. When DST lands, the &Path instance
48 // should be removed, and arguments bound by ToCStr should be
49 // passed by reference. (Here: in the `open` method.)
51 /// Lazily open a dynamic library. When passed None it gives a
52 /// handle to the calling process
53 pub fn open(filename: Option<&Path>) -> Result<DynamicLibrary, String> {
54 let maybe_library = dl::open(filename.map(|path| path.as_os_str()));
56 // The dynamic library must not be constructed if there is
57 // an error opening the library so the destructor does not
61 Ok(handle) => Ok(DynamicLibrary { handle: handle })
65 /// Prepends a path to this process's search path for dynamic libraries
66 pub fn prepend_search_path(path: &Path) {
67 let mut search_path = DynamicLibrary::search_path();
68 search_path.insert(0, path.to_path_buf());
69 env::set_var(DynamicLibrary::envvar(), &DynamicLibrary::create_path(&search_path));
72 /// From a slice of paths, create a new vector which is suitable to be an
73 /// environment variable for this platforms dylib search path.
74 pub fn create_path(path: &[PathBuf]) -> OsString {
75 let mut newvar = OsString::new();
76 for (i, path) in path.iter().enumerate() {
77 if i > 0 { newvar.push(DynamicLibrary::separator()); }
83 /// Returns the environment variable for this process's dynamic library
85 pub fn envvar() -> &'static str {
88 } else if cfg!(target_os = "macos") {
95 fn separator() -> &'static str {
96 if cfg!(windows) { ";" } else { ":" }
99 /// Returns the current search path for dynamic libraries being used by this
101 pub fn search_path() -> Vec<PathBuf> {
102 match env::var_os(DynamicLibrary::envvar()) {
103 Some(var) => env::split_paths(&var).collect(),
108 /// Access the value at the symbol of the dynamic library
109 pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<*mut T, String> {
110 // This function should have a lifetime constraint of 'a on
111 // T but that feature is still unimplemented
113 let raw_string = CString::new(symbol).unwrap();
114 let maybe_symbol_value = dl::check_for_errors_in(|| {
115 dl::symbol(self.handle, raw_string.as_ptr())
118 // The value must not be constructed if there is an error so
119 // the destructor does not run.
120 match maybe_symbol_value {
121 Err(err) => Err(err),
122 Ok(symbol_value) => Ok(mem::transmute(symbol_value))
127 #[cfg(all(test, not(target_os = "ios")))]
136 #[cfg_attr(any(windows, target_os = "android"), ignore)] // FIXME #8818, #10379
137 fn test_loading_cosine() {
138 // The math library does not need to be loaded since it is already
139 // statically linked in
140 let libm = match DynamicLibrary::open(None) {
141 Err(error) => panic!("Could not load self as module: {}", error),
145 let cosine: extern fn(libc::c_double) -> libc::c_double = unsafe {
146 match libm.symbol("cos") {
147 Err(error) => panic!("Could not load function cos: {}", error),
148 Ok(cosine) => mem::transmute::<*mut u8, _>(cosine)
153 let expected_result = 1.0;
154 let result = cosine(argument);
155 if result != expected_result {
156 panic!("cos({}) != {} but equaled {} instead", argument,
157 expected_result, result)
162 #[cfg(any(target_os = "linux",
164 target_os = "freebsd",
165 target_os = "dragonfly",
166 target_os = "bitrig",
167 target_os = "openbsd"))]
168 fn test_errors_do_not_crash() {
169 // Open /dev/null as a library to get an error, and make sure
170 // that only causes an error, and not a crash.
171 let path = Path::new("/dev/null");
172 match DynamicLibrary::open(Some(&path)) {
174 Ok(_) => panic!("Successfully opened the empty library.")
179 #[cfg(any(target_os = "linux",
180 target_os = "android",
183 target_os = "freebsd",
184 target_os = "dragonfly",
185 target_os = "bitrig",
186 target_os = "openbsd"))]
190 use ffi::{CStr, OsStr};
193 use os::unix::prelude::*;
196 pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
197 check_for_errors_in(|| {
200 Some(filename) => open_external(filename),
201 None => open_internal(),
207 const LAZY: libc::c_int = 1;
209 unsafe fn open_external(filename: &OsStr) -> *mut u8 {
210 let s = filename.to_cstring().unwrap();
211 dlopen(s.as_ptr(), LAZY) as *mut u8
214 unsafe fn open_internal() -> *mut u8 {
215 dlopen(ptr::null(), LAZY) as *mut u8
218 pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where
221 use sync::{StaticMutex, MUTEX_INIT};
222 static LOCK: StaticMutex = MUTEX_INIT;
224 // dlerror isn't thread safe, so we need to lock around this entire
226 let _guard = LOCK.lock();
227 let _old_error = dlerror();
231 let last_error = dlerror() as *const _;
232 let ret = if ptr::null() == last_error {
235 let s = CStr::from_ptr(last_error).to_bytes();
236 Err(str::from_utf8(s).unwrap().to_string())
243 pub unsafe fn symbol(handle: *mut u8,
244 symbol: *const libc::c_char) -> *mut u8 {
245 dlsym(handle as *mut libc::c_void, symbol) as *mut u8
247 pub unsafe fn close(handle: *mut u8) {
248 dlclose(handle as *mut libc::c_void); ()
252 fn dlopen(filename: *const libc::c_char,
253 flag: libc::c_int) -> *mut libc::c_void;
254 fn dlerror() -> *mut libc::c_char;
255 fn dlsym(handle: *mut libc::c_void,
256 symbol: *const libc::c_char) -> *mut libc::c_void;
257 fn dlclose(handle: *mut libc::c_void) -> libc::c_int;
261 #[cfg(target_os = "windows")]
266 use libc::consts::os::extra::ERROR_CALL_NOT_IMPLEMENTED;
269 use os::windows::prelude::*;
270 use option::Option::{self, Some, None};
273 use result::Result::{Ok, Err};
276 use sys::c::compat::kernel32::SetThreadErrorMode;
278 pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
279 // disable "dll load failed" error dialog.
280 let mut use_thread_mode = true;
281 let prev_error_mode = unsafe {
282 // SEM_FAILCRITICALERRORS 0x01
283 let new_error_mode = 1;
284 let mut prev_error_mode = 0;
285 // Windows >= 7 supports thread error mode.
286 let result = SetThreadErrorMode(new_error_mode, &mut prev_error_mode);
288 let err = os::errno();
289 if err as libc::c_int == ERROR_CALL_NOT_IMPLEMENTED {
290 use_thread_mode = false;
291 // SetThreadErrorMode not found. use fallback solution:
292 // SetErrorMode() Note that SetErrorMode is process-wide so
293 // this can cause race condition! However, since even
294 // Windows APIs do not care of such problem (#20650), we
295 // just assume SetErrorMode race is not a great deal.
296 prev_error_mode = SetErrorMode(new_error_mode);
306 let result = match filename {
308 let filename_str: Vec<_> =
309 filename.encode_wide().chain(Some(0).into_iter()).collect();
310 let result = unsafe {
311 LoadLibraryW(filename_str.as_ptr() as *const libc::c_void)
313 // beware: Vec/String may change errno during drop!
314 // so we get error here.
315 if result == ptr::null_mut() {
316 let errno = os::errno();
317 Err(os::error_string(errno))
319 Ok(result as *mut u8)
323 let mut handle = ptr::null_mut();
324 let succeeded = unsafe {
325 GetModuleHandleExW(0 as libc::DWORD, ptr::null(), &mut handle)
327 if succeeded == libc::FALSE {
328 let errno = os::errno();
329 Err(os::error_string(errno))
331 Ok(handle as *mut u8)
338 SetThreadErrorMode(prev_error_mode, ptr::null_mut());
340 SetErrorMode(prev_error_mode);
347 pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where
355 let error = os::errno();
359 Err(format!("Error code {}", error))
364 pub unsafe fn symbol(handle: *mut u8, symbol: *const libc::c_char) -> *mut u8 {
365 GetProcAddress(handle as *mut libc::c_void, symbol) as *mut u8
367 pub unsafe fn close(handle: *mut u8) {
368 FreeLibrary(handle as *mut libc::c_void); ()
371 #[allow(non_snake_case)]
373 fn SetLastError(error: libc::size_t);
374 fn LoadLibraryW(name: *const libc::c_void) -> *mut libc::c_void;
375 fn GetModuleHandleExW(dwFlags: libc::DWORD, name: *const u16,
376 handle: *mut *mut libc::c_void) -> libc::BOOL;
377 fn GetProcAddress(handle: *mut libc::c_void,
378 name: *const libc::c_char) -> *mut libc::c_void;
379 fn FreeLibrary(handle: *mut libc::c_void);
380 fn SetErrorMode(uMode: libc::c_uint) -> libc::c_uint;