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)]
25 use ffi::{CString, OsString};
26 use path::{Path, PathBuf};
28 #[unstable(feature = "dynamic_lib",
29 reason = "API has not been scrutinized and is highly likely to \
30 either disappear or change",
32 #[rustc_deprecated(since = "1.5.0", reason = "replaced with 'dylib' on crates.io")]
33 pub struct DynamicLibrary {
37 impl Drop for DynamicLibrary {
39 match dl::check_for_errors_in(|| {
41 dl::close(self.handle)
45 Err(str) => panic!("{}", str)
50 #[unstable(feature = "dynamic_lib",
51 reason = "API has not been scrutinized and is highly likely to \
52 either disappear or change",
54 #[rustc_deprecated(since = "1.5.0", reason = "replaced with 'dylib' on crates.io")]
56 /// Lazily open a dynamic library. When passed None it gives a
57 /// handle to the calling process
58 pub fn open(filename: Option<&Path>) -> Result<DynamicLibrary, String> {
59 let maybe_library = dl::open(filename.map(|path| path.as_os_str()));
61 // The dynamic library must not be constructed if there is
62 // an error opening the library so the destructor does not
66 Ok(handle) => Ok(DynamicLibrary { handle: handle })
70 /// Prepends a path to this process's search path for dynamic libraries
71 pub fn prepend_search_path(path: &Path) {
72 let mut search_path = DynamicLibrary::search_path();
73 search_path.insert(0, path.to_path_buf());
74 env::set_var(DynamicLibrary::envvar(), &DynamicLibrary::create_path(&search_path));
77 /// From a slice of paths, create a new vector which is suitable to be an
78 /// environment variable for this platforms dylib search path.
79 pub fn create_path(path: &[PathBuf]) -> OsString {
80 let mut newvar = OsString::new();
81 for (i, path) in path.iter().enumerate() {
82 if i > 0 { newvar.push(DynamicLibrary::separator()); }
88 /// Returns the environment variable for this process's dynamic library
90 pub fn envvar() -> &'static str {
93 } else if cfg!(target_os = "macos") {
100 fn separator() -> &'static str {
101 if cfg!(windows) { ";" } else { ":" }
104 /// Returns the current search path for dynamic libraries being used by this
106 pub fn search_path() -> Vec<PathBuf> {
107 match env::var_os(DynamicLibrary::envvar()) {
108 Some(var) => env::split_paths(&var).collect(),
113 /// Accesses the value at the symbol of the dynamic library.
114 pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<*mut T, String> {
115 // This function should have a lifetime constraint of 'a on
116 // T but that feature is still unimplemented
118 let raw_string = CString::new(symbol).unwrap();
119 let maybe_symbol_value = dl::check_for_errors_in(|| {
120 dl::symbol(self.handle, raw_string.as_ptr())
123 // The value must not be constructed if there is an error so
124 // the destructor does not run.
125 match maybe_symbol_value {
126 Err(err) => Err(err),
127 Ok(symbol_value) => Ok(symbol_value as *mut T)
132 #[cfg(all(test, not(target_os = "ios"), not(target_os = "nacl")))]
140 #[cfg_attr(any(windows,
141 target_os = "android", // FIXME #10379
142 target_env = "musl"), ignore)]
144 fn test_loading_cosine() {
145 // The math library does not need to be loaded since it is already
146 // statically linked in
147 let libm = match DynamicLibrary::open(None) {
148 Err(error) => panic!("Could not load self as module: {}", error),
152 let cosine: extern fn(libc::c_double) -> libc::c_double = unsafe {
153 match libm.symbol("cos") {
154 Err(error) => panic!("Could not load function cos: {}", error),
155 Ok(cosine) => mem::transmute::<*mut u8, _>(cosine)
160 let expected_result = 1.0;
161 let result = cosine(argument);
162 if result != expected_result {
163 panic!("cos({}) != {} but equaled {} instead", argument,
164 expected_result, result)
169 #[cfg(any(target_os = "linux",
171 target_os = "freebsd",
172 target_os = "dragonfly",
173 target_os = "bitrig",
174 target_os = "netbsd",
175 target_os = "openbsd",
176 target_os = "solaris"))]
178 fn test_errors_do_not_crash() {
181 // Open /dev/null as a library to get an error, and make sure
182 // that only causes an error, and not a crash.
183 let path = Path::new("/dev/null");
184 match DynamicLibrary::open(Some(&path)) {
186 Ok(_) => panic!("Successfully opened the empty library.")
191 #[cfg(any(target_os = "linux",
192 target_os = "android",
195 target_os = "freebsd",
196 target_os = "dragonfly",
197 target_os = "bitrig",
198 target_os = "netbsd",
199 target_os = "openbsd",
200 target_os = "solaris",
201 target_os = "emscripten"))]
205 use ffi::{CStr, OsStr};
210 pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
211 check_for_errors_in(|| {
214 Some(filename) => open_external(filename),
215 None => open_internal(),
221 const LAZY: libc::c_int = 1;
223 unsafe fn open_external(filename: &OsStr) -> *mut u8 {
224 let s = filename.to_cstring().unwrap();
225 libc::dlopen(s.as_ptr(), LAZY) as *mut u8
228 unsafe fn open_internal() -> *mut u8 {
229 libc::dlopen(ptr::null(), LAZY) as *mut u8
232 pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where
235 use sync::StaticMutex;
236 static LOCK: StaticMutex = StaticMutex::new();
238 // dlerror isn't thread safe, so we need to lock around this entire
240 let _guard = LOCK.lock();
241 let _old_error = libc::dlerror();
245 let last_error = libc::dlerror() as *const _;
246 let ret = if ptr::null() == last_error {
249 let s = CStr::from_ptr(last_error).to_bytes();
250 Err(str::from_utf8(s).unwrap().to_owned())
257 pub unsafe fn symbol(handle: *mut u8,
258 symbol: *const libc::c_char) -> *mut u8 {
259 libc::dlsym(handle as *mut libc::c_void, symbol) as *mut u8
261 pub unsafe fn close(handle: *mut u8) {
262 libc::dlclose(handle as *mut libc::c_void); ()
266 #[cfg(target_os = "windows")]
272 use os::windows::prelude::*;
277 pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
278 // disable "dll load failed" error dialog.
279 let mut use_thread_mode = true;
280 let prev_error_mode = unsafe {
281 // SEM_FAILCRITICALERRORS 0x01
282 let new_error_mode = 1;
283 let mut prev_error_mode = 0;
284 // Windows >= 7 supports thread error mode.
285 let result = c::SetThreadErrorMode(new_error_mode,
286 &mut prev_error_mode);
288 let err = os::errno();
289 if err == c::ERROR_CALL_NOT_IMPLEMENTED as i32 {
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 = c::SetErrorMode(new_error_mode);
306 let result = match filename {
308 let filename_str: Vec<_> =
309 filename.encode_wide().chain(Some(0)).collect();
310 let result = unsafe {
311 c::LoadLibraryW(filename_str.as_ptr())
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 c::GetModuleHandleExW(0 as c::DWORD, ptr::null(),
328 if succeeded == c::FALSE {
329 let errno = os::errno();
330 Err(os::error_string(errno))
332 Ok(handle as *mut u8)
339 c::SetThreadErrorMode(prev_error_mode, ptr::null_mut());
341 c::SetErrorMode(prev_error_mode);
348 pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where
356 let error = os::errno();
360 Err(format!("Error code {}", error))
365 pub unsafe fn symbol(handle: *mut u8, symbol: *const libc::c_char) -> *mut u8 {
366 c::GetProcAddress(handle as c::HMODULE, symbol) as *mut u8
368 pub unsafe fn close(handle: *mut u8) {
369 c::FreeLibrary(handle as c::HMODULE);
373 #[cfg(target_os = "nacl")]
378 use result::Result::Err;
384 pub fn open(_filename: Option<&OsStr>) -> Result<*mut u8, String> {
385 Err(format!("NaCl + Newlib doesn't impl loading shared objects"))
388 pub fn check_for_errors_in<T, F>(_f: F) -> Result<T, String>
389 where F: FnOnce() -> T,
391 Err(format!("NaCl doesn't support shared objects"))
394 pub unsafe fn symbol(_handle: *mut u8, _symbol: *const libc::c_char) -> *mut u8 {
397 pub unsafe fn close(_handle: *mut u8) { }