1 // Copyright 2013-2014 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
16 #![allow(missing_docs)]
25 #[allow(missing_copy_implementations)]
26 pub struct DynamicLibrary {
30 impl Drop for DynamicLibrary {
32 match dl::check_for_errors_in(|| {
34 dl::close(self.handle)
38 Err(str) => panic!("{}", str)
44 // FIXME (#12938): Until DST lands, we cannot decompose &str into
45 // & and str, so we cannot usefully take ToCStr arguments by
46 // reference (without forcing an additional & around &str). So we
47 // are instead temporarily adding an instance for &Path, so that
48 // we can take ToCStr as owned. When DST lands, the &Path instance
49 // should be removed, and arguments bound by ToCStr should be
50 // passed by reference. (Here: in the `open` method.)
52 /// Lazily open a dynamic library. When passed None it gives a
53 /// handle to the calling process
54 pub fn open(filename: Option<&Path>) -> Result<DynamicLibrary, String> {
56 let maybe_library = dl::check_for_errors_in(|| {
58 Some(name) => dl::open_external(name.as_vec()),
59 None => dl::open_internal()
63 // The dynamic library must not be constructed if there is
64 // an error opening the library so the destructor does not
68 Ok(handle) => Ok(DynamicLibrary { handle: handle })
73 /// Prepends a path to this process's search path for dynamic libraries
74 pub fn prepend_search_path(path: &Path) {
75 let mut search_path = DynamicLibrary::search_path();
76 search_path.insert(0, path.clone());
77 let newval = DynamicLibrary::create_path(search_path.as_slice());
78 os::setenv(DynamicLibrary::envvar(),
79 str::from_utf8(newval.as_slice()).unwrap());
82 /// From a slice of paths, create a new vector which is suitable to be an
83 /// environment variable for this platforms dylib search path.
84 pub fn create_path(path: &[Path]) -> Vec<u8> {
85 let mut newvar = Vec::new();
86 for (i, path) in path.iter().enumerate() {
87 if i > 0 { newvar.push(DynamicLibrary::separator()); }
88 newvar.push_all(path.as_vec());
93 /// Returns the environment variable for this process's dynamic library
95 pub fn envvar() -> &'static str {
98 } else if cfg!(target_os = "macos") {
105 fn separator() -> u8 {
106 if cfg!(windows) {b';'} else {b':'}
109 /// Returns the current search path for dynamic libraries being used by this
111 pub fn search_path() -> Vec<Path> {
112 let mut ret = Vec::new();
113 match os::getenv_as_bytes(DynamicLibrary::envvar()) {
117 .split(|a| *a == DynamicLibrary::separator()) {
118 ret.push(Path::new(portion));
126 /// Access the value at the symbol of the dynamic library
127 pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<*mut T, String> {
128 // This function should have a lifetime constraint of 'a on
129 // T but that feature is still unimplemented
131 let maybe_symbol_value = dl::check_for_errors_in(|| {
132 let raw_string = CString::from_slice(symbol.as_bytes());
133 dl::symbol(self.handle, raw_string.as_ptr())
136 // The value must not be constructed if there is an error so
137 // the destructor does not run.
138 match maybe_symbol_value {
139 Err(err) => Err(err),
140 Ok(symbol_value) => Ok(mem::transmute(symbol_value))
145 #[cfg(all(test, not(target_os = "ios")))]
153 #[cfg_attr(any(windows, target_os = "android"), ignore)] // FIXME #8818, #10379
154 fn test_loading_cosine() {
155 // The math library does not need to be loaded since it is already
156 // statically linked in
157 let none: Option<&Path> = None; // appease the typechecker
158 let libm = match DynamicLibrary::open(none) {
159 Err(error) => panic!("Could not load self as module: {}", error),
163 let cosine: extern fn(libc::c_double) -> libc::c_double = unsafe {
164 match libm.symbol("cos") {
165 Err(error) => panic!("Could not load function cos: {}", error),
166 Ok(cosine) => mem::transmute::<*mut u8, _>(cosine)
171 let expected_result = 1.0;
172 let result = cosine(argument);
173 if result != expected_result {
174 panic!("cos({}) != {} but equaled {} instead", argument,
175 expected_result, result)
180 #[cfg(any(target_os = "linux",
182 target_os = "freebsd",
183 target_os = "dragonfly"))]
184 fn test_errors_do_not_crash() {
185 // Open /dev/null as a library to get an error, and make sure
186 // that only causes an error, and not a crash.
187 let path = Path::new("/dev/null");
188 match DynamicLibrary::open(Some(&path)) {
190 Ok(_) => panic!("Successfully opened the empty library.")
195 #[cfg(any(target_os = "linux",
196 target_os = "android",
199 target_os = "freebsd",
200 target_os = "dragonfly"))]
202 pub use self::Rtld::*;
205 use ffi::{self, CString};
210 pub unsafe fn open_external(filename: &[u8]) -> *mut u8 {
211 let s = CString::from_slice(filename);
212 dlopen(s.as_ptr(), Lazy as libc::c_int) as *mut u8
215 pub unsafe fn open_internal() -> *mut u8 {
216 dlopen(ptr::null(), Lazy as libc::c_int) as *mut u8
219 pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where
222 use sync::{StaticMutex, MUTEX_INIT};
223 static LOCK: StaticMutex = MUTEX_INIT;
225 // dlerror isn't thread safe, so we need to lock around this entire
227 let _guard = LOCK.lock();
228 let _old_error = dlerror();
232 let last_error = dlerror() as *const _;
233 let ret = if ptr::null() == last_error {
236 let s = ffi::c_str_to_bytes(&last_error);
237 Err(str::from_utf8(s).unwrap().to_string())
244 pub unsafe fn symbol(handle: *mut u8,
245 symbol: *const libc::c_char) -> *mut u8 {
246 dlsym(handle as *mut libc::c_void, symbol) as *mut u8
248 pub unsafe fn close(handle: *mut u8) {
249 dlclose(handle as *mut libc::c_void); ()
262 fn dlopen(filename: *const libc::c_char,
263 flag: libc::c_int) -> *mut libc::c_void;
264 fn dlerror() -> *mut libc::c_char;
265 fn dlsym(handle: *mut libc::c_void,
266 symbol: *const libc::c_char) -> *mut libc::c_void;
267 fn dlclose(handle: *mut libc::c_void) -> libc::c_int;
271 #[cfg(target_os = "windows")]
273 use iter::IteratorExt;
279 use result::Result::{Ok, Err};
286 pub unsafe fn open_external(filename: &[u8]) -> *mut u8 {
287 // Windows expects Unicode data
288 let filename_str = str::from_utf8(filename).unwrap();
289 let mut filename_str: Vec<u16> = filename_str.utf16_units().collect();
290 filename_str.push(0);
291 LoadLibraryW(filename_str.as_ptr() as *const libc::c_void) as *mut u8
294 pub unsafe fn open_internal() -> *mut u8 {
295 let mut handle = ptr::null_mut();
296 GetModuleHandleExW(0 as libc::DWORD, ptr::null(), &mut handle);
300 pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where
308 let error = os::errno();
312 Err(format!("Error code {}", error))
317 pub unsafe fn symbol(handle: *mut u8, symbol: *const libc::c_char) -> *mut u8 {
318 GetProcAddress(handle as *mut libc::c_void, symbol) as *mut u8
320 pub unsafe fn close(handle: *mut u8) {
321 FreeLibrary(handle as *mut libc::c_void); ()
324 #[allow(non_snake_case)]
326 fn SetLastError(error: libc::size_t);
327 fn LoadLibraryW(name: *const libc::c_void) -> *mut libc::c_void;
328 fn GetModuleHandleExW(dwFlags: libc::DWORD, name: *const u16,
329 handle: *mut *mut libc::c_void)
330 -> *mut libc::c_void;
331 fn GetProcAddress(handle: *mut libc::c_void,
332 name: *const libc::c_char) -> *mut libc::c_void;
333 fn FreeLibrary(handle: *mut libc::c_void);