1 //! Dynamic library facilities.
3 //! A simple wrapper over the platform's dynamic library facilities
8 pub struct DynamicLibrary {
12 impl Drop for DynamicLibrary {
15 dl::close(self.handle)
21 /// Lazily open a dynamic library. When passed None it gives a
22 /// handle to the calling process
23 pub fn open(filename: Option<&Path>) -> Result<DynamicLibrary, String> {
24 let maybe_library = dl::open(filename.map(|path| path.as_os_str()));
26 // The dynamic library must not be constructed if there is
27 // an error opening the library so the destructor does not
31 Ok(handle) => Ok(DynamicLibrary { handle })
35 /// Load a dynamic library into the global namespace (RTLD_GLOBAL on Unix)
36 /// and do it now (don't use RTLD_LAZY on Unix).
37 pub fn open_global_now(filename: &Path) -> Result<DynamicLibrary, String> {
38 let maybe_library = dl::open_global_now(filename.as_os_str());
41 Ok(handle) => Ok(DynamicLibrary { 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_atoi() {
88 // The C library does not need to be loaded since it is already linked in
89 let lib = match DynamicLibrary::open(None) {
90 Err(error) => panic!("Could not load self as module: {}", error),
94 let atoi: extern fn(*const libc::c_char) -> libc::c_int = unsafe {
95 match lib.symbol("atoi") {
96 Err(error) => panic!("Could not load function atoi: {}", error),
97 Ok(atoi) => mem::transmute::<*mut u8, _>(atoi)
101 let argument = CString::new("1383428980").unwrap();
102 let expected_result = 0x52757374;
103 let result = atoi(argument.as_ptr());
104 if result != expected_result {
105 panic!("atoi({:?}) != {} but equaled {} instead", argument,
106 expected_result, result)
111 fn test_errors_do_not_crash() {
118 // Open /dev/null as a library to get an error, and make sure
119 // that only causes an error, and not a crash.
120 let path = Path::new("/dev/null");
121 match DynamicLibrary::open(Some(&path)) {
123 Ok(_) => panic!("Successfully opened the empty library.")
131 use std::ffi::{CStr, OsStr, CString};
132 use std::os::unix::prelude::*;
136 pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
137 check_for_errors_in(|| {
140 Some(filename) => open_external(filename),
141 None => open_internal(),
147 pub fn open_global_now(filename: &OsStr) -> Result<*mut u8, String> {
148 check_for_errors_in(|| unsafe {
149 let s = CString::new(filename.as_bytes()).unwrap();
150 libc::dlopen(s.as_ptr(), libc::RTLD_GLOBAL | libc::RTLD_NOW) as *mut u8
154 unsafe fn open_external(filename: &OsStr) -> *mut u8 {
155 let s = CString::new(filename.as_bytes()).unwrap();
156 libc::dlopen(s.as_ptr(), libc::RTLD_LAZY) as *mut u8
159 unsafe fn open_internal() -> *mut u8 {
160 libc::dlopen(ptr::null(), libc::RTLD_LAZY) as *mut u8
163 pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where
166 use std::sync::{Mutex, Once, ONCE_INIT};
167 static INIT: Once = ONCE_INIT;
168 static mut LOCK: *mut Mutex<()> = 0 as *mut _;
171 LOCK = Box::into_raw(Box::new(Mutex::new(())));
173 // dlerror isn't thread safe, so we need to lock around this entire
175 let _guard = (*LOCK).lock();
176 let _old_error = libc::dlerror();
180 let last_error = libc::dlerror() as *const _;
181 let ret = if ptr::null() == last_error {
184 let s = CStr::from_ptr(last_error).to_bytes();
185 Err(str::from_utf8(s).unwrap().to_owned())
192 pub unsafe fn symbol(handle: *mut u8,
193 symbol: *const libc::c_char)
194 -> Result<*mut u8, String> {
195 check_for_errors_in(|| {
196 libc::dlsym(handle as *mut libc::c_void, symbol) as *mut u8
199 pub unsafe fn close(handle: *mut u8) {
200 libc::dlclose(handle as *mut libc::c_void); ()
208 use std::os::windows::prelude::*;
211 use libc::{c_uint, c_void, c_char};
214 type HMODULE = *mut u8;
216 type LPCWSTR = *const u16;
217 type LPCSTR = *const i8;
220 fn SetThreadErrorMode(dwNewMode: DWORD,
221 lpOldMode: *mut DWORD) -> c_uint;
222 fn LoadLibraryW(name: LPCWSTR) -> HMODULE;
223 fn GetModuleHandleExW(dwFlags: DWORD,
225 handle: *mut HMODULE) -> BOOL;
226 fn GetProcAddress(handle: HMODULE,
227 name: LPCSTR) -> *mut c_void;
228 fn FreeLibrary(handle: HMODULE) -> BOOL;
231 pub fn open_global_now(filename: &OsStr) -> Result<*mut u8, String> {
235 pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
236 // disable "dll load failed" error dialog.
237 let prev_error_mode = unsafe {
238 // SEM_FAILCRITICALERRORS 0x01
239 let new_error_mode = 1;
240 let mut prev_error_mode = 0;
241 let result = SetThreadErrorMode(new_error_mode,
242 &mut prev_error_mode);
244 return Err(io::Error::last_os_error().to_string())
249 let result = match filename {
251 let filename_str: Vec<_> =
252 filename.encode_wide().chain(Some(0)).collect();
253 let result = unsafe {
254 LoadLibraryW(filename_str.as_ptr())
259 let mut handle = ptr::null_mut();
260 let succeeded = unsafe {
261 GetModuleHandleExW(0 as DWORD, ptr::null(), &mut handle)
264 Err(io::Error::last_os_error().to_string())
266 Ok(handle as *mut u8)
272 SetThreadErrorMode(prev_error_mode, ptr::null_mut());
278 pub unsafe fn symbol(handle: *mut u8,
279 symbol: *const c_char)
280 -> Result<*mut u8, String> {
281 let ptr = GetProcAddress(handle as HMODULE, symbol) as *mut u8;
285 pub unsafe fn close(handle: *mut u8) {
286 FreeLibrary(handle as HMODULE);
289 fn ptr_result<T>(ptr: *mut T) -> Result<*mut T, String> {
291 Err(io::Error::last_os_error().to_string())