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 = "dynamic_lib",
16 reason = "API has not been scrutinized and is highly likely to \
17 either disappear or change",
19 #![allow(missing_docs)]
24 use ffi::{CString, OsString};
26 use path::{Path, PathBuf};
28 pub struct DynamicLibrary {
32 impl Drop for DynamicLibrary {
34 match dl::check_for_errors_in(|| {
36 dl::close(self.handle)
40 Err(str) => panic!("{}", str)
46 /// Lazily open a dynamic library. When passed None it gives a
47 /// handle to the calling process
48 pub fn open(filename: Option<&Path>) -> Result<DynamicLibrary, String> {
49 let maybe_library = dl::open(filename.map(|path| path.as_os_str()));
51 // The dynamic library must not be constructed if there is
52 // an error opening the library so the destructor does not
56 Ok(handle) => Ok(DynamicLibrary { handle: handle })
60 /// Prepends a path to this process's search path for dynamic libraries
61 pub fn prepend_search_path(path: &Path) {
62 let mut search_path = DynamicLibrary::search_path();
63 search_path.insert(0, path.to_path_buf());
64 env::set_var(DynamicLibrary::envvar(), &DynamicLibrary::create_path(&search_path));
67 /// From a slice of paths, create a new vector which is suitable to be an
68 /// environment variable for this platforms dylib search path.
69 pub fn create_path(path: &[PathBuf]) -> OsString {
70 let mut newvar = OsString::new();
71 for (i, path) in path.iter().enumerate() {
72 if i > 0 { newvar.push(DynamicLibrary::separator()); }
78 /// Returns the environment variable for this process's dynamic library
80 pub fn envvar() -> &'static str {
83 } else if cfg!(target_os = "macos") {
90 fn separator() -> &'static str {
91 if cfg!(windows) { ";" } else { ":" }
94 /// Returns the current search path for dynamic libraries being used by this
96 pub fn search_path() -> Vec<PathBuf> {
97 match env::var_os(DynamicLibrary::envvar()) {
98 Some(var) => env::split_paths(&var).collect(),
103 /// Accesses the value at the symbol of the dynamic library.
104 pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<*mut T, String> {
105 // This function should have a lifetime constraint of 'a on
106 // T but that feature is still unimplemented
108 let raw_string = CString::new(symbol).unwrap();
109 let maybe_symbol_value = dl::check_for_errors_in(|| {
110 dl::symbol(self.handle, raw_string.as_ptr())
113 // The value must not be constructed if there is an error so
114 // the destructor does not run.
115 match maybe_symbol_value {
116 Err(err) => Err(err),
117 Ok(symbol_value) => Ok(mem::transmute(symbol_value))
122 #[cfg(all(test, not(target_os = "ios")))]
131 #[cfg_attr(any(windows,
132 target_os = "android", // FIXME #10379
133 target_env = "musl"), ignore)]
134 fn test_loading_cosine() {
135 // The math library does not need to be loaded since it is already
136 // statically linked in
137 let libm = match DynamicLibrary::open(None) {
138 Err(error) => panic!("Could not load self as module: {}", error),
142 let cosine: extern fn(libc::c_double) -> libc::c_double = unsafe {
143 match libm.symbol("cos") {
144 Err(error) => panic!("Could not load function cos: {}", error),
145 Ok(cosine) => mem::transmute::<*mut u8, _>(cosine)
150 let expected_result = 1.0;
151 let result = cosine(argument);
152 if result != expected_result {
153 panic!("cos({}) != {} but equaled {} instead", argument,
154 expected_result, result)
159 #[cfg(any(target_os = "linux",
161 target_os = "freebsd",
162 target_os = "dragonfly",
163 target_os = "bitrig",
164 target_os = "netbsd",
165 target_os = "openbsd"))]
166 fn test_errors_do_not_crash() {
167 // Open /dev/null as a library to get an error, and make sure
168 // that only causes an error, and not a crash.
169 let path = Path::new("/dev/null");
170 match DynamicLibrary::open(Some(&path)) {
172 Ok(_) => panic!("Successfully opened the empty library.")
177 #[cfg(any(target_os = "linux",
178 target_os = "android",
181 target_os = "freebsd",
182 target_os = "dragonfly",
183 target_os = "bitrig",
184 target_os = "netbsd",
185 target_os = "openbsd"))]
189 use ffi::{CStr, OsStr};
194 pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
195 check_for_errors_in(|| {
198 Some(filename) => open_external(filename),
199 None => open_internal(),
205 const LAZY: libc::c_int = 1;
207 unsafe fn open_external(filename: &OsStr) -> *mut u8 {
208 let s = filename.to_cstring().unwrap();
209 dlopen(s.as_ptr(), LAZY) as *mut u8
212 unsafe fn open_internal() -> *mut u8 {
213 dlopen(ptr::null(), LAZY) as *mut u8
216 pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where
219 use sync::StaticMutex;
220 static LOCK: StaticMutex = StaticMutex::new();
222 // dlerror isn't thread safe, so we need to lock around this entire
224 let _guard = LOCK.lock();
225 let _old_error = dlerror();
229 let last_error = dlerror() as *const _;
230 let ret = if ptr::null() == last_error {
233 let s = CStr::from_ptr(last_error).to_bytes();
234 Err(str::from_utf8(s).unwrap().to_owned())
241 pub unsafe fn symbol(handle: *mut u8,
242 symbol: *const libc::c_char) -> *mut u8 {
243 dlsym(handle as *mut libc::c_void, symbol) as *mut u8
245 pub unsafe fn close(handle: *mut u8) {
246 dlclose(handle as *mut libc::c_void); ()
250 fn dlopen(filename: *const libc::c_char,
251 flag: libc::c_int) -> *mut libc::c_void;
252 fn dlerror() -> *mut libc::c_char;
253 fn dlsym(handle: *mut libc::c_void,
254 symbol: *const libc::c_char) -> *mut libc::c_void;
255 fn dlclose(handle: *mut libc::c_void) -> libc::c_int;
259 #[cfg(target_os = "windows")]
265 use libc::consts::os::extra::ERROR_CALL_NOT_IMPLEMENTED;
267 use os::windows::prelude::*;
269 use sys::c::SetThreadErrorMode;
271 pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
272 // disable "dll load failed" error dialog.
273 let mut use_thread_mode = true;
274 let prev_error_mode = unsafe {
275 // SEM_FAILCRITICALERRORS 0x01
276 let new_error_mode = 1;
277 let mut prev_error_mode = 0;
278 // Windows >= 7 supports thread error mode.
279 let result = SetThreadErrorMode(new_error_mode, &mut prev_error_mode);
281 let err = os::errno();
282 if err as libc::c_int == ERROR_CALL_NOT_IMPLEMENTED {
283 use_thread_mode = false;
284 // SetThreadErrorMode not found. use fallback solution:
285 // SetErrorMode() Note that SetErrorMode is process-wide so
286 // this can cause race condition! However, since even
287 // Windows APIs do not care of such problem (#20650), we
288 // just assume SetErrorMode race is not a great deal.
289 prev_error_mode = SetErrorMode(new_error_mode);
299 let result = match filename {
301 let filename_str: Vec<_> =
302 filename.encode_wide().chain(Some(0)).collect();
303 let result = unsafe {
304 LoadLibraryW(filename_str.as_ptr() as *const libc::c_void)
306 // beware: Vec/String may change errno during drop!
307 // so we get error here.
308 if result == ptr::null_mut() {
309 let errno = os::errno();
310 Err(os::error_string(errno))
312 Ok(result as *mut u8)
316 let mut handle = ptr::null_mut();
317 let succeeded = unsafe {
318 GetModuleHandleExW(0 as libc::DWORD, ptr::null(), &mut handle)
320 if succeeded == libc::FALSE {
321 let errno = os::errno();
322 Err(os::error_string(errno))
324 Ok(handle as *mut u8)
331 SetThreadErrorMode(prev_error_mode, ptr::null_mut());
333 SetErrorMode(prev_error_mode);
340 pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where
348 let error = os::errno();
352 Err(format!("Error code {}", error))
357 pub unsafe fn symbol(handle: *mut u8, symbol: *const libc::c_char) -> *mut u8 {
358 GetProcAddress(handle as *mut libc::c_void, symbol) as *mut u8
360 pub unsafe fn close(handle: *mut u8) {
361 FreeLibrary(handle as *mut libc::c_void); ()
364 #[allow(non_snake_case)]
366 fn SetLastError(error: libc::size_t);
367 fn LoadLibraryW(name: *const libc::c_void) -> *mut libc::c_void;
368 fn GetModuleHandleExW(dwFlags: libc::DWORD, name: *const u16,
369 handle: *mut *mut libc::c_void) -> libc::BOOL;
370 fn GetProcAddress(handle: *mut libc::c_void,
371 name: *const libc::c_char) -> *mut libc::c_void;
372 fn FreeLibrary(handle: *mut libc::c_void);
373 fn SetErrorMode(uMode: libc::c_uint) -> libc::c_uint;