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 use std::ffi::CString;
18 pub struct DynamicLibrary {
22 impl Drop for DynamicLibrary {
25 dl::close(self.handle)
31 /// Lazily open a dynamic library. When passed None it gives a
32 /// handle to the calling process
33 pub fn open(filename: Option<&Path>) -> Result<DynamicLibrary, String> {
34 let maybe_library = dl::open(filename.map(|path| path.as_os_str()));
36 // The dynamic library must not be constructed if there is
37 // an error opening the library so the destructor does not
41 Ok(handle) => Ok(DynamicLibrary { handle: handle })
45 /// Returns the environment variable for this process's dynamic library
47 pub fn envvar() -> &'static str {
50 } else if cfg!(target_os = "macos") {
52 } else if cfg!(target_os = "haiku") {
59 /// Accesses the value at the symbol of the dynamic library.
60 pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<*mut T, String> {
61 // This function should have a lifetime constraint of 'a on
62 // T but that feature is still unimplemented
64 let raw_string = CString::new(symbol).unwrap();
65 let maybe_symbol_value = dl::symbol(self.handle, raw_string.as_ptr());
67 // The value must not be constructed if there is an error so
68 // the destructor does not run.
69 match maybe_symbol_value {
71 Ok(symbol_value) => Ok(symbol_value as *mut T)
83 fn test_loading_cosine() {
88 // The math library does not need to be loaded since it is already
89 // statically linked in
90 let libm = match DynamicLibrary::open(None) {
91 Err(error) => panic!("Could not load self as module: {}", error),
95 let cosine: extern fn(libc::c_double) -> libc::c_double = unsafe {
96 match libm.symbol("cos") {
97 Err(error) => panic!("Could not load function cos: {}", error),
98 Ok(cosine) => mem::transmute::<*mut u8, _>(cosine)
103 let expected_result = 1.0;
104 let result = cosine(argument);
105 if result != expected_result {
106 panic!("cos({}) != {} but equaled {} instead", argument,
107 expected_result, result)
112 fn test_errors_do_not_crash() {
119 // Open /dev/null as a library to get an error, and make sure
120 // that only causes an error, and not a crash.
121 let path = Path::new("/dev/null");
122 match DynamicLibrary::open(Some(&path)) {
124 Ok(_) => panic!("Successfully opened the empty library.")
132 use std::ffi::{CStr, OsStr, CString};
133 use std::os::unix::prelude::*;
137 pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
138 check_for_errors_in(|| {
141 Some(filename) => open_external(filename),
142 None => open_internal(),
148 const LAZY: libc::c_int = 1;
150 unsafe fn open_external(filename: &OsStr) -> *mut u8 {
151 let s = CString::new(filename.as_bytes()).unwrap();
152 libc::dlopen(s.as_ptr(), LAZY) as *mut u8
155 unsafe fn open_internal() -> *mut u8 {
156 libc::dlopen(ptr::null(), LAZY) as *mut u8
159 pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where
162 use std::sync::{Mutex, Once, ONCE_INIT};
163 static INIT: Once = ONCE_INIT;
164 static mut LOCK: *mut Mutex<()> = 0 as *mut _;
167 LOCK = Box::into_raw(Box::new(Mutex::new(())));
169 // dlerror isn't thread safe, so we need to lock around this entire
171 let _guard = (*LOCK).lock();
172 let _old_error = libc::dlerror();
176 let last_error = libc::dlerror() as *const _;
177 let ret = if ptr::null() == last_error {
180 let s = CStr::from_ptr(last_error).to_bytes();
181 Err(str::from_utf8(s).unwrap().to_owned())
188 pub unsafe fn symbol(handle: *mut u8,
189 symbol: *const libc::c_char)
190 -> Result<*mut u8, String> {
191 check_for_errors_in(|| {
192 libc::dlsym(handle as *mut libc::c_void, symbol) as *mut u8
195 pub unsafe fn close(handle: *mut u8) {
196 libc::dlclose(handle as *mut libc::c_void); ()
204 use std::os::windows::prelude::*;
207 use libc::{c_uint, c_void, c_char};
210 type HMODULE = *mut u8;
212 type LPCWSTR = *const u16;
213 type LPCSTR = *const i8;
216 fn SetThreadErrorMode(dwNewMode: DWORD,
217 lpOldMode: *mut DWORD) -> c_uint;
218 fn LoadLibraryW(name: LPCWSTR) -> HMODULE;
219 fn GetModuleHandleExW(dwFlags: DWORD,
221 handle: *mut HMODULE) -> BOOL;
222 fn GetProcAddress(handle: HMODULE,
223 name: LPCSTR) -> *mut c_void;
224 fn FreeLibrary(handle: HMODULE) -> BOOL;
227 pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
228 // disable "dll load failed" error dialog.
229 let prev_error_mode = unsafe {
230 // SEM_FAILCRITICALERRORS 0x01
231 let new_error_mode = 1;
232 let mut prev_error_mode = 0;
233 let result = SetThreadErrorMode(new_error_mode,
234 &mut prev_error_mode);
236 return Err(io::Error::last_os_error().to_string())
241 let result = match filename {
243 let filename_str: Vec<_> =
244 filename.encode_wide().chain(Some(0)).collect();
245 let result = unsafe {
246 LoadLibraryW(filename_str.as_ptr())
251 let mut handle = ptr::null_mut();
252 let succeeded = unsafe {
253 GetModuleHandleExW(0 as DWORD, ptr::null(), &mut handle)
256 Err(io::Error::last_os_error().to_string())
258 Ok(handle as *mut u8)
264 SetThreadErrorMode(prev_error_mode, ptr::null_mut());
270 pub unsafe fn symbol(handle: *mut u8,
271 symbol: *const c_char)
272 -> Result<*mut u8, String> {
273 let ptr = GetProcAddress(handle as HMODULE, symbol) as *mut u8;
277 pub unsafe fn close(handle: *mut u8) {
278 FreeLibrary(handle as HMODULE);
281 fn ptr_result<T>(ptr: *mut T) -> Result<*mut T, String> {
283 Err(io::Error::last_os_error().to_string())