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
16 use std::ffi::{CString, OsString};
17 use std::path::{Path, PathBuf};
19 pub struct DynamicLibrary {
23 impl Drop for DynamicLibrary {
26 dl::close(self.handle)
32 /// Lazily open a dynamic library. When passed None it gives a
33 /// handle to the calling process
34 pub fn open(filename: Option<&Path>) -> Result<DynamicLibrary, String> {
35 let maybe_library = dl::open(filename.map(|path| path.as_os_str()));
37 // The dynamic library must not be constructed if there is
38 // an error opening the library so the destructor does not
42 Ok(handle) => Ok(DynamicLibrary { handle: handle })
46 /// Prepends a path to this process's search path for dynamic libraries
47 pub fn prepend_search_path(path: &Path) {
48 let mut search_path = DynamicLibrary::search_path();
49 search_path.insert(0, path.to_path_buf());
50 env::set_var(DynamicLibrary::envvar(), &DynamicLibrary::create_path(&search_path));
53 /// From a slice of paths, create a new vector which is suitable to be an
54 /// environment variable for this platforms dylib search path.
55 pub fn create_path(path: &[PathBuf]) -> OsString {
56 let mut newvar = OsString::new();
57 for (i, path) in path.iter().enumerate() {
58 if i > 0 { newvar.push(DynamicLibrary::separator()); }
64 /// Returns the environment variable for this process's dynamic library
66 pub fn envvar() -> &'static str {
69 } else if cfg!(target_os = "macos") {
71 } else if cfg!(target_os = "haiku") {
78 fn separator() -> &'static str {
79 if cfg!(windows) { ";" } else { ":" }
82 /// Returns the current search path for dynamic libraries being used by this
84 pub fn search_path() -> Vec<PathBuf> {
85 match env::var_os(DynamicLibrary::envvar()) {
86 Some(var) => env::split_paths(&var).collect(),
91 /// Accesses the value at the symbol of the dynamic library.
92 pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<*mut T, String> {
93 // This function should have a lifetime constraint of 'a on
94 // T but that feature is still unimplemented
96 let raw_string = CString::new(symbol).unwrap();
97 let maybe_symbol_value = dl::symbol(self.handle, raw_string.as_ptr());
99 // The value must not be constructed if there is an error so
100 // the destructor does not run.
101 match maybe_symbol_value {
102 Err(err) => Err(err),
103 Ok(symbol_value) => Ok(symbol_value as *mut T)
115 fn test_loading_cosine() {
120 // The math library does not need to be loaded since it is already
121 // statically linked in
122 let libm = match DynamicLibrary::open(None) {
123 Err(error) => panic!("Could not load self as module: {}", error),
127 let cosine: extern fn(libc::c_double) -> libc::c_double = unsafe {
128 match libm.symbol("cos") {
129 Err(error) => panic!("Could not load function cos: {}", error),
130 Ok(cosine) => mem::transmute::<*mut u8, _>(cosine)
135 let expected_result = 1.0;
136 let result = cosine(argument);
137 if result != expected_result {
138 panic!("cos({}) != {} but equaled {} instead", argument,
139 expected_result, result)
144 fn test_errors_do_not_crash() {
151 // Open /dev/null as a library to get an error, and make sure
152 // that only causes an error, and not a crash.
153 let path = Path::new("/dev/null");
154 match DynamicLibrary::open(Some(&path)) {
156 Ok(_) => panic!("Successfully opened the empty library.")
164 use std::ffi::{CStr, OsStr, CString};
165 use std::os::unix::prelude::*;
169 pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
170 check_for_errors_in(|| {
173 Some(filename) => open_external(filename),
174 None => open_internal(),
180 const LAZY: libc::c_int = 1;
182 unsafe fn open_external(filename: &OsStr) -> *mut u8 {
183 let s = CString::new(filename.as_bytes()).unwrap();
184 libc::dlopen(s.as_ptr(), LAZY) as *mut u8
187 unsafe fn open_internal() -> *mut u8 {
188 libc::dlopen(ptr::null(), LAZY) as *mut u8
191 pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where
194 use std::sync::{Mutex, Once, ONCE_INIT};
195 static INIT: Once = ONCE_INIT;
196 static mut LOCK: *mut Mutex<()> = 0 as *mut _;
199 LOCK = Box::into_raw(Box::new(Mutex::new(())));
201 // dlerror isn't thread safe, so we need to lock around this entire
203 let _guard = (*LOCK).lock();
204 let _old_error = libc::dlerror();
208 let last_error = libc::dlerror() as *const _;
209 let ret = if ptr::null() == last_error {
212 let s = CStr::from_ptr(last_error).to_bytes();
213 Err(str::from_utf8(s).unwrap().to_owned())
220 pub unsafe fn symbol(handle: *mut u8,
221 symbol: *const libc::c_char)
222 -> Result<*mut u8, String> {
223 check_for_errors_in(|| {
224 libc::dlsym(handle as *mut libc::c_void, symbol) as *mut u8
227 pub unsafe fn close(handle: *mut u8) {
228 libc::dlclose(handle as *mut libc::c_void); ()
236 use std::os::windows::prelude::*;
239 use libc::{c_uint, c_void, c_char};
242 type HMODULE = *mut u8;
244 type LPCWSTR = *const u16;
245 type LPCSTR = *const i8;
248 fn SetThreadErrorMode(dwNewMode: DWORD,
249 lpOldMode: *mut DWORD) -> c_uint;
250 fn LoadLibraryW(name: LPCWSTR) -> HMODULE;
251 fn GetModuleHandleExW(dwFlags: DWORD,
253 handle: *mut HMODULE) -> BOOL;
254 fn GetProcAddress(handle: HMODULE,
255 name: LPCSTR) -> *mut c_void;
256 fn FreeLibrary(handle: HMODULE) -> BOOL;
259 pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
260 // disable "dll load failed" error dialog.
261 let prev_error_mode = unsafe {
262 // SEM_FAILCRITICALERRORS 0x01
263 let new_error_mode = 1;
264 let mut prev_error_mode = 0;
265 let result = SetThreadErrorMode(new_error_mode,
266 &mut prev_error_mode);
268 return Err(io::Error::last_os_error().to_string())
273 let result = match filename {
275 let filename_str: Vec<_> =
276 filename.encode_wide().chain(Some(0)).collect();
277 let result = unsafe {
278 LoadLibraryW(filename_str.as_ptr())
283 let mut handle = ptr::null_mut();
284 let succeeded = unsafe {
285 GetModuleHandleExW(0 as DWORD, ptr::null(), &mut handle)
288 Err(io::Error::last_os_error().to_string())
290 Ok(handle as *mut u8)
296 SetThreadErrorMode(prev_error_mode, ptr::null_mut());
302 pub unsafe fn symbol(handle: *mut u8,
303 symbol: *const c_char)
304 -> Result<*mut u8, String> {
305 let ptr = GetProcAddress(handle as HMODULE, symbol) as *mut u8;
309 pub unsafe fn close(handle: *mut u8) {
310 FreeLibrary(handle as HMODULE);
313 fn ptr_result<T>(ptr: *mut T) -> Result<*mut T, String> {
315 Err(io::Error::last_os_error().to_string())