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 })
45 /// Load a dynamic library into the global namespace (RTLD_GLOBAL on Unix)
46 /// and do it now (don't use RTLD_LAZY on Unix).
47 pub fn open_global_now(filename: &Path) -> Result<DynamicLibrary, String> {
48 let maybe_library = dl::open_global_now(filename.as_os_str());
51 Ok(handle) => Ok(DynamicLibrary { handle })
55 /// Returns the environment variable for this process's dynamic library
57 pub fn envvar() -> &'static str {
60 } else if cfg!(target_os = "macos") {
62 } else if cfg!(target_os = "haiku") {
69 /// Accesses the value at the symbol of the dynamic library.
70 pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<*mut T, String> {
71 // This function should have a lifetime constraint of 'a on
72 // T but that feature is still unimplemented
74 let raw_string = CString::new(symbol).unwrap();
75 let maybe_symbol_value = dl::symbol(self.handle, raw_string.as_ptr());
77 // The value must not be constructed if there is an error so
78 // the destructor does not run.
79 match maybe_symbol_value {
81 Ok(symbol_value) => Ok(symbol_value as *mut T)
93 fn test_loading_atoi() {
98 // The C library does not need to be loaded since it is already linked in
99 let lib = match DynamicLibrary::open(None) {
100 Err(error) => panic!("Could not load self as module: {}", error),
104 let atoi: extern fn(*const libc::c_char) -> libc::c_int = unsafe {
105 match lib.symbol("atoi") {
106 Err(error) => panic!("Could not load function atoi: {}", error),
107 Ok(atoi) => mem::transmute::<*mut u8, _>(atoi)
111 let argument = CString::new("1383428980").unwrap();
112 let expected_result = 0x52757374;
113 let result = atoi(argument.as_ptr());
114 if result != expected_result {
115 panic!("atoi({:?}) != {} but equaled {} instead", argument,
116 expected_result, result)
121 fn test_errors_do_not_crash() {
128 // Open /dev/null as a library to get an error, and make sure
129 // that only causes an error, and not a crash.
130 let path = Path::new("/dev/null");
131 match DynamicLibrary::open(Some(&path)) {
133 Ok(_) => panic!("Successfully opened the empty library.")
141 use std::ffi::{CStr, OsStr, CString};
142 use std::os::unix::prelude::*;
146 pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
147 check_for_errors_in(|| {
150 Some(filename) => open_external(filename),
151 None => open_internal(),
157 pub fn open_global_now(filename: &OsStr) -> Result<*mut u8, String> {
158 check_for_errors_in(|| unsafe {
159 let s = CString::new(filename.as_bytes()).unwrap();
160 libc::dlopen(s.as_ptr(), libc::RTLD_GLOBAL | libc::RTLD_NOW) as *mut u8
164 unsafe fn open_external(filename: &OsStr) -> *mut u8 {
165 let s = CString::new(filename.as_bytes()).unwrap();
166 libc::dlopen(s.as_ptr(), libc::RTLD_LAZY) as *mut u8
169 unsafe fn open_internal() -> *mut u8 {
170 libc::dlopen(ptr::null(), libc::RTLD_LAZY) as *mut u8
173 pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where
176 use std::sync::{Mutex, Once, ONCE_INIT};
177 static INIT: Once = ONCE_INIT;
178 static mut LOCK: *mut Mutex<()> = 0 as *mut _;
181 LOCK = Box::into_raw(Box::new(Mutex::new(())));
183 // dlerror isn't thread safe, so we need to lock around this entire
185 let _guard = (*LOCK).lock();
186 let _old_error = libc::dlerror();
190 let last_error = libc::dlerror() as *const _;
191 let ret = if ptr::null() == last_error {
194 let s = CStr::from_ptr(last_error).to_bytes();
195 Err(str::from_utf8(s).unwrap().to_owned())
202 pub unsafe fn symbol(handle: *mut u8,
203 symbol: *const libc::c_char)
204 -> Result<*mut u8, String> {
205 check_for_errors_in(|| {
206 libc::dlsym(handle as *mut libc::c_void, symbol) as *mut u8
209 pub unsafe fn close(handle: *mut u8) {
210 libc::dlclose(handle as *mut libc::c_void); ()
218 use std::os::windows::prelude::*;
221 use libc::{c_uint, c_void, c_char};
224 type HMODULE = *mut u8;
226 type LPCWSTR = *const u16;
227 type LPCSTR = *const i8;
230 fn SetThreadErrorMode(dwNewMode: DWORD,
231 lpOldMode: *mut DWORD) -> c_uint;
232 fn LoadLibraryW(name: LPCWSTR) -> HMODULE;
233 fn GetModuleHandleExW(dwFlags: DWORD,
235 handle: *mut HMODULE) -> BOOL;
236 fn GetProcAddress(handle: HMODULE,
237 name: LPCSTR) -> *mut c_void;
238 fn FreeLibrary(handle: HMODULE) -> BOOL;
241 pub fn open_global_now(filename: &OsStr) -> Result<*mut u8, String> {
245 pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
246 // disable "dll load failed" error dialog.
247 let prev_error_mode = unsafe {
248 // SEM_FAILCRITICALERRORS 0x01
249 let new_error_mode = 1;
250 let mut prev_error_mode = 0;
251 let result = SetThreadErrorMode(new_error_mode,
252 &mut prev_error_mode);
254 return Err(io::Error::last_os_error().to_string())
259 let result = match filename {
261 let filename_str: Vec<_> =
262 filename.encode_wide().chain(Some(0)).collect();
263 let result = unsafe {
264 LoadLibraryW(filename_str.as_ptr())
269 let mut handle = ptr::null_mut();
270 let succeeded = unsafe {
271 GetModuleHandleExW(0 as DWORD, ptr::null(), &mut handle)
274 Err(io::Error::last_os_error().to_string())
276 Ok(handle as *mut u8)
282 SetThreadErrorMode(prev_error_mode, ptr::null_mut());
288 pub unsafe fn symbol(handle: *mut u8,
289 symbol: *const c_char)
290 -> Result<*mut u8, String> {
291 let ptr = GetProcAddress(handle as HMODULE, symbol) as *mut u8;
295 pub unsafe fn close(handle: *mut u8) {
296 FreeLibrary(handle as HMODULE);
299 fn ptr_result<T>(ptr: *mut T) -> Result<*mut T, String> {
301 Err(io::Error::last_os_error().to_string())