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 #![rustc_deprecated(since = "1.5.0", reason = "replaced with 'dylib' on crates.io")]
20 #![allow(missing_docs)]
26 use ffi::{CString, OsString};
27 use path::{Path, PathBuf};
29 pub struct DynamicLibrary {
33 impl Drop for DynamicLibrary {
35 match dl::check_for_errors_in(|| {
37 dl::close(self.handle)
41 Err(str) => panic!("{}", str)
47 /// Lazily open a dynamic library. When passed None it gives a
48 /// handle to the calling process
49 pub fn open(filename: Option<&Path>) -> Result<DynamicLibrary, String> {
50 let maybe_library = dl::open(filename.map(|path| path.as_os_str()));
52 // The dynamic library must not be constructed if there is
53 // an error opening the library so the destructor does not
57 Ok(handle) => Ok(DynamicLibrary { handle: handle })
61 /// Prepends a path to this process's search path for dynamic libraries
62 pub fn prepend_search_path(path: &Path) {
63 let mut search_path = DynamicLibrary::search_path();
64 search_path.insert(0, path.to_path_buf());
65 env::set_var(DynamicLibrary::envvar(), &DynamicLibrary::create_path(&search_path));
68 /// From a slice of paths, create a new vector which is suitable to be an
69 /// environment variable for this platforms dylib search path.
70 pub fn create_path(path: &[PathBuf]) -> OsString {
71 let mut newvar = OsString::new();
72 for (i, path) in path.iter().enumerate() {
73 if i > 0 { newvar.push(DynamicLibrary::separator()); }
79 /// Returns the environment variable for this process's dynamic library
81 pub fn envvar() -> &'static str {
84 } else if cfg!(target_os = "macos") {
91 fn separator() -> &'static str {
92 if cfg!(windows) { ";" } else { ":" }
95 /// Returns the current search path for dynamic libraries being used by this
97 pub fn search_path() -> Vec<PathBuf> {
98 match env::var_os(DynamicLibrary::envvar()) {
99 Some(var) => env::split_paths(&var).collect(),
104 /// Accesses the value at the symbol of the dynamic library.
105 pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<*mut T, String> {
106 // This function should have a lifetime constraint of 'a on
107 // T but that feature is still unimplemented
109 let raw_string = CString::new(symbol).unwrap();
110 let maybe_symbol_value = dl::check_for_errors_in(|| {
111 dl::symbol(self.handle, raw_string.as_ptr())
114 // The value must not be constructed if there is an error so
115 // the destructor does not run.
116 match maybe_symbol_value {
117 Err(err) => Err(err),
118 Ok(symbol_value) => Ok(symbol_value as *mut T)
123 #[cfg(all(test, not(target_os = "ios"), not(target_os = "nacl")))]
132 #[cfg_attr(any(windows,
133 target_os = "android", // FIXME #10379
134 target_env = "musl"), ignore)]
136 fn test_loading_cosine() {
137 // The math library does not need to be loaded since it is already
138 // statically linked in
139 let libm = match DynamicLibrary::open(None) {
140 Err(error) => panic!("Could not load self as module: {}", error),
144 let cosine: extern fn(libc::c_double) -> libc::c_double = unsafe {
145 match libm.symbol("cos") {
146 Err(error) => panic!("Could not load function cos: {}", error),
147 Ok(cosine) => mem::transmute::<*mut u8, _>(cosine)
152 let expected_result = 1.0;
153 let result = cosine(argument);
154 if result != expected_result {
155 panic!("cos({}) != {} but equaled {} instead", argument,
156 expected_result, result)
161 #[cfg(any(target_os = "linux",
163 target_os = "freebsd",
164 target_os = "dragonfly",
165 target_os = "bitrig",
166 target_os = "netbsd",
167 target_os = "openbsd"))]
169 fn test_errors_do_not_crash() {
170 // Open /dev/null as a library to get an error, and make sure
171 // that only causes an error, and not a crash.
172 let path = Path::new("/dev/null");
173 match DynamicLibrary::open(Some(&path)) {
175 Ok(_) => panic!("Successfully opened the empty library.")
180 #[cfg(any(target_os = "linux",
181 target_os = "android",
184 target_os = "freebsd",
185 target_os = "dragonfly",
186 target_os = "bitrig",
187 target_os = "netbsd",
188 target_os = "openbsd"))]
192 use ffi::{CStr, OsStr};
197 pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
198 check_for_errors_in(|| {
201 Some(filename) => open_external(filename),
202 None => open_internal(),
208 const LAZY: libc::c_int = 1;
210 unsafe fn open_external(filename: &OsStr) -> *mut u8 {
211 let s = filename.to_cstring().unwrap();
212 libc::dlopen(s.as_ptr(), LAZY) as *mut u8
215 unsafe fn open_internal() -> *mut u8 {
216 libc::dlopen(ptr::null(), LAZY) as *mut u8
219 pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where
222 use sync::StaticMutex;
223 static LOCK: StaticMutex = StaticMutex::new();
225 // dlerror isn't thread safe, so we need to lock around this entire
227 let _guard = LOCK.lock();
228 let _old_error = libc::dlerror();
232 let last_error = libc::dlerror() as *const _;
233 let ret = if ptr::null() == last_error {
236 let s = CStr::from_ptr(last_error).to_bytes();
237 Err(str::from_utf8(s).unwrap().to_owned())
244 pub unsafe fn symbol(handle: *mut u8,
245 symbol: *const libc::c_char) -> *mut u8 {
246 libc::dlsym(handle as *mut libc::c_void, symbol) as *mut u8
248 pub unsafe fn close(handle: *mut u8) {
249 libc::dlclose(handle as *mut libc::c_void); ()
253 #[cfg(target_os = "windows")]
259 use os::windows::prelude::*;
264 pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
265 // disable "dll load failed" error dialog.
266 let mut use_thread_mode = true;
267 let prev_error_mode = unsafe {
268 // SEM_FAILCRITICALERRORS 0x01
269 let new_error_mode = 1;
270 let mut prev_error_mode = 0;
271 // Windows >= 7 supports thread error mode.
272 let result = c::SetThreadErrorMode(new_error_mode,
273 &mut prev_error_mode);
275 let err = os::errno();
276 if err == c::ERROR_CALL_NOT_IMPLEMENTED as i32 {
277 use_thread_mode = false;
278 // SetThreadErrorMode not found. use fallback solution:
279 // SetErrorMode() Note that SetErrorMode is process-wide so
280 // this can cause race condition! However, since even
281 // Windows APIs do not care of such problem (#20650), we
282 // just assume SetErrorMode race is not a great deal.
283 prev_error_mode = c::SetErrorMode(new_error_mode);
293 let result = match filename {
295 let filename_str: Vec<_> =
296 filename.encode_wide().chain(Some(0)).collect();
297 let result = unsafe {
298 c::LoadLibraryW(filename_str.as_ptr())
300 // beware: Vec/String may change errno during drop!
301 // so we get error here.
302 if result == ptr::null_mut() {
303 let errno = os::errno();
304 Err(os::error_string(errno))
306 Ok(result as *mut u8)
310 let mut handle = ptr::null_mut();
311 let succeeded = unsafe {
312 c::GetModuleHandleExW(0 as c::DWORD, ptr::null(),
315 if succeeded == c::FALSE {
316 let errno = os::errno();
317 Err(os::error_string(errno))
319 Ok(handle as *mut u8)
326 c::SetThreadErrorMode(prev_error_mode, ptr::null_mut());
328 c::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 c::GetProcAddress(handle as c::HMODULE, symbol) as *mut u8
355 pub unsafe fn close(handle: *mut u8) {
356 c::FreeLibrary(handle as c::HMODULE);
360 #[cfg(target_os = "nacl")]
365 use result::Result::Err;
371 pub fn open(_filename: Option<&OsStr>) -> Result<*mut u8, String> {
372 Err(format!("NaCl + Newlib doesn't impl loading shared objects"))
375 pub fn check_for_errors_in<T, F>(_f: F) -> Result<T, String>
376 where F: FnOnce() -> T,
378 Err(format!("NaCl doesn't support shared objects"))
381 pub unsafe fn symbol(_handle: *mut u8, _symbol: *const libc::c_char) -> *mut u8 {
384 pub unsafe fn close(_handle: *mut u8) { }