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)]
20 use iter::IteratorExt;
24 use option::Option::{None, Some};
26 use path::{Path,GenericPath};
28 use result::Result::{Err, Ok};
29 use slice::{AsSlice,SlicePrelude};
34 #[allow(missing_copy_implementations)]
35 pub struct DynamicLibrary {
39 impl Drop for DynamicLibrary {
41 match dl::check_for_errors_in(|| {
43 dl::close(self.handle)
47 Err(str) => panic!("{}", str)
53 // FIXME (#12938): Until DST lands, we cannot decompose &str into
54 // & and str, so we cannot usefully take ToCStr arguments by
55 // reference (without forcing an additional & around &str). So we
56 // are instead temporarily adding an instance for &Path, so that
57 // we can take ToCStr as owned. When DST lands, the &Path instance
58 // should be removed, and arguments bound by ToCStr should be
59 // passed by reference. (Here: in the `open` method.)
61 /// Lazily open a dynamic library. When passed None it gives a
62 /// handle to the calling process
63 pub fn open<T: ToCStr>(filename: Option<T>)
64 -> Result<DynamicLibrary, String> {
66 let mut filename = filename;
67 let maybe_library = dl::check_for_errors_in(|| {
68 match filename.take() {
69 Some(name) => dl::open_external(name),
70 None => dl::open_internal()
74 // The dynamic library must not be constructed if there is
75 // an error opening the library so the destructor does not
79 Ok(handle) => Ok(DynamicLibrary { handle: handle })
84 /// Prepends a path to this process's search path for dynamic libraries
85 pub fn prepend_search_path(path: &Path) {
86 let mut search_path = DynamicLibrary::search_path();
87 search_path.insert(0, path.clone());
88 let newval = DynamicLibrary::create_path(search_path.as_slice());
89 os::setenv(DynamicLibrary::envvar(),
90 str::from_utf8(newval.as_slice()).unwrap());
93 /// From a slice of paths, create a new vector which is suitable to be an
94 /// environment variable for this platforms dylib search path.
95 pub fn create_path(path: &[Path]) -> Vec<u8> {
96 let mut newvar = Vec::new();
97 for (i, path) in path.iter().enumerate() {
98 if i > 0 { newvar.push(DynamicLibrary::separator()); }
99 newvar.push_all(path.as_vec());
104 /// Returns the environment variable for this process's dynamic library
106 pub fn envvar() -> &'static str {
109 } else if cfg!(target_os = "macos") {
116 fn separator() -> u8 {
117 if cfg!(windows) {b';'} else {b':'}
120 /// Returns the current search path for dynamic libraries being used by this
122 pub fn search_path() -> Vec<Path> {
123 let mut ret = Vec::new();
124 match os::getenv_as_bytes(DynamicLibrary::envvar()) {
128 .split(|a| *a == DynamicLibrary::separator()) {
129 ret.push(Path::new(portion));
137 /// Access the value at the symbol of the dynamic library
138 pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<*mut T, String> {
139 // This function should have a lifetime constraint of 'a on
140 // T but that feature is still unimplemented
142 let maybe_symbol_value = dl::check_for_errors_in(|| {
143 symbol.with_c_str(|raw_string| {
144 dl::symbol(self.handle, raw_string)
148 // The value must not be constructed if there is an error so
149 // the destructor does not run.
150 match maybe_symbol_value {
151 Err(err) => Err(err),
152 Ok(symbol_value) => Ok(mem::transmute(symbol_value))
157 #[cfg(all(test, not(target_os = "ios")))]
165 #[cfg_attr(any(windows, target_os = "android"), ignore)] // FIXME #8818, #10379
166 fn test_loading_cosine() {
167 // The math library does not need to be loaded since it is already
168 // statically linked in
169 let none: Option<Path> = None; // appease the typechecker
170 let libm = match DynamicLibrary::open(none) {
171 Err(error) => panic!("Could not load self as module: {}", error),
175 let cosine: extern fn(libc::c_double) -> libc::c_double = unsafe {
176 match libm.symbol("cos") {
177 Err(error) => panic!("Could not load function cos: {}", error),
178 Ok(cosine) => mem::transmute::<*mut u8, _>(cosine)
183 let expected_result = 1.0;
184 let result = cosine(argument);
185 if result != expected_result {
186 panic!("cos({}) != {} but equaled {} instead", argument,
187 expected_result, result)
192 #[cfg(any(target_os = "linux",
194 target_os = "freebsd",
195 target_os = "dragonfly"))]
196 fn test_errors_do_not_crash() {
197 // Open /dev/null as a library to get an error, and make sure
198 // that only causes an error, and not a crash.
199 let path = Path::new("/dev/null");
200 match DynamicLibrary::open(Some(&path)) {
202 Ok(_) => panic!("Successfully opened the empty library.")
207 #[cfg(any(target_os = "linux",
208 target_os = "android",
211 target_os = "freebsd",
212 target_os = "dragonfly"))]
214 pub use self::Rtld::*;
216 use c_str::{CString, ToCStr};
221 use result::Result::{Err, Ok};
224 pub unsafe fn open_external<T: ToCStr>(filename: T) -> *mut u8 {
225 filename.with_c_str(|raw_name| {
226 dlopen(raw_name, Lazy as libc::c_int) as *mut u8
230 pub unsafe fn open_internal() -> *mut u8 {
231 dlopen(ptr::null(), Lazy as libc::c_int) as *mut u8
234 pub fn check_for_errors_in<T>(f: || -> T) -> Result<T, String> {
235 use sync::{StaticMutex, MUTEX_INIT};
236 static LOCK: StaticMutex = MUTEX_INIT;
238 // dlerror isn't thread safe, so we need to lock around this entire
240 let _guard = LOCK.lock();
241 let _old_error = dlerror();
245 let last_error = dlerror() as *const _;
246 let ret = if ptr::null() == last_error {
249 Err(String::from_str(CString::new(last_error, false).as_str()
257 pub unsafe fn symbol(handle: *mut u8,
258 symbol: *const libc::c_char) -> *mut u8 {
259 dlsym(handle as *mut libc::c_void, symbol) as *mut u8
261 pub unsafe fn close(handle: *mut u8) {
262 dlclose(handle as *mut libc::c_void); ()
272 impl Copy for Rtld {}
276 fn dlopen(filename: *const libc::c_char,
277 flag: libc::c_int) -> *mut libc::c_void;
278 fn dlerror() -> *mut libc::c_char;
279 fn dlsym(handle: *mut libc::c_void,
280 symbol: *const libc::c_char) -> *mut libc::c_void;
281 fn dlclose(handle: *mut libc::c_void) -> libc::c_int;
285 #[cfg(target_os = "windows")]
288 use iter::IteratorExt;
293 use result::Result::{Ok, Err};
294 use slice::SlicePrelude;
300 pub unsafe fn open_external<T: ToCStr>(filename: T) -> *mut u8 {
301 // Windows expects Unicode data
302 let filename_cstr = filename.to_c_str();
303 let filename_str = str::from_utf8(filename_cstr.as_bytes_no_nul()).unwrap();
304 let mut filename_str: Vec<u16> = filename_str.utf16_units().collect();
305 filename_str.push(0);
306 LoadLibraryW(filename_str.as_ptr() as *const libc::c_void) as *mut u8
309 pub unsafe fn open_internal() -> *mut u8 {
310 let mut handle = ptr::null_mut();
311 GetModuleHandleExW(0 as libc::DWORD, ptr::null(), &mut handle);
315 pub fn check_for_errors_in<T>(f: || -> T) -> Result<T, String> {
321 let error = os::errno();
325 Err(format!("Error code {}", error))
330 pub unsafe fn symbol(handle: *mut u8, symbol: *const libc::c_char) -> *mut u8 {
331 GetProcAddress(handle as *mut libc::c_void, symbol) as *mut u8
333 pub unsafe fn close(handle: *mut u8) {
334 FreeLibrary(handle as *mut libc::c_void); ()
337 #[allow(non_snake_case)]
339 fn SetLastError(error: libc::size_t);
340 fn LoadLibraryW(name: *const libc::c_void) -> *mut libc::c_void;
341 fn GetModuleHandleExW(dwFlags: libc::DWORD, name: *const u16,
342 handle: *mut *mut libc::c_void)
343 -> *mut libc::c_void;
344 fn GetProcAddress(handle: *mut libc::c_void,
345 name: *const libc::c_char) -> *mut libc::c_void;
346 fn FreeLibrary(handle: *mut libc::c_void);