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 /// Loads 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)
82 fn test_loading_atoi() {
87 // The C library does not need to be loaded since it is already linked in
88 let lib = match DynamicLibrary::open(None) {
89 Err(error) => panic!("Could not load self as module: {}", error),
93 let atoi: extern fn(*const libc::c_char) -> libc::c_int = unsafe {
94 match lib.symbol("atoi") {
95 Err(error) => panic!("Could not load function atoi: {}", error),
96 Ok(atoi) => mem::transmute::<*mut u8, _>(atoi)
100 let argument = CString::new("1383428980").unwrap();
101 let expected_result = 0x52757374;
102 let result = atoi(argument.as_ptr());
103 if result != expected_result {
104 panic!("atoi({:?}) != {} but equaled {} instead", argument,
105 expected_result, result)
110 fn test_errors_do_not_crash() {
117 // Open /dev/null as a library to get an error, and make sure
118 // that only causes an error, and not a crash.
119 let path = Path::new("/dev/null");
120 match DynamicLibrary::open(Some(&path)) {
122 Ok(_) => panic!("Successfully opened the empty library.")
129 use std::ffi::{CStr, OsStr, CString};
130 use std::os::unix::prelude::*;
134 pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
135 check_for_errors_in(|| {
138 Some(filename) => open_external(filename),
139 None => open_internal(),
145 pub fn open_global_now(filename: &OsStr) -> Result<*mut u8, String> {
146 check_for_errors_in(|| unsafe {
147 let s = CString::new(filename.as_bytes()).unwrap();
148 libc::dlopen(s.as_ptr(), libc::RTLD_GLOBAL | libc::RTLD_NOW) as *mut u8
152 unsafe fn open_external(filename: &OsStr) -> *mut u8 {
153 let s = CString::new(filename.as_bytes()).unwrap();
154 libc::dlopen(s.as_ptr(), libc::RTLD_LAZY) as *mut u8
157 unsafe fn open_internal() -> *mut u8 {
158 libc::dlopen(ptr::null(), libc::RTLD_LAZY) as *mut u8
161 pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where
164 use std::sync::{Mutex, Once, ONCE_INIT};
165 static INIT: Once = ONCE_INIT;
166 static mut LOCK: *mut Mutex<()> = 0 as *mut _;
169 LOCK = Box::into_raw(Box::new(Mutex::new(())));
171 // dlerror isn't thread safe, so we need to lock around this entire
173 let _guard = (*LOCK).lock();
174 let _old_error = libc::dlerror();
178 let last_error = libc::dlerror() as *const _;
179 let ret = if ptr::null() == last_error {
182 let s = CStr::from_ptr(last_error).to_bytes();
183 Err(str::from_utf8(s).unwrap().to_owned())
190 pub unsafe fn symbol(handle: *mut u8,
191 symbol: *const libc::c_char)
192 -> Result<*mut u8, String> {
193 check_for_errors_in(|| {
194 libc::dlsym(handle as *mut libc::c_void, symbol) as *mut u8
197 pub unsafe fn close(handle: *mut u8) {
198 libc::dlclose(handle as *mut libc::c_void); ()
206 use std::os::windows::prelude::*;
209 use libc::{c_uint, c_void, c_char};
212 type HMODULE = *mut u8;
214 type LPCWSTR = *const u16;
215 type LPCSTR = *const i8;
218 fn SetThreadErrorMode(dwNewMode: DWORD,
219 lpOldMode: *mut DWORD) -> c_uint;
220 fn LoadLibraryW(name: LPCWSTR) -> HMODULE;
221 fn GetModuleHandleExW(dwFlags: DWORD,
223 handle: *mut HMODULE) -> BOOL;
224 fn GetProcAddress(handle: HMODULE,
225 name: LPCSTR) -> *mut c_void;
226 fn FreeLibrary(handle: HMODULE) -> BOOL;
229 pub fn open_global_now(filename: &OsStr) -> Result<*mut u8, String> {
233 pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
234 // disable "dll load failed" error dialog.
235 let prev_error_mode = unsafe {
236 // SEM_FAILCRITICALERRORS 0x01
237 let new_error_mode = 1;
238 let mut prev_error_mode = 0;
239 let result = SetThreadErrorMode(new_error_mode,
240 &mut prev_error_mode);
242 return Err(io::Error::last_os_error().to_string())
247 let result = match filename {
249 let filename_str: Vec<_> =
250 filename.encode_wide().chain(Some(0)).collect();
251 let result = unsafe {
252 LoadLibraryW(filename_str.as_ptr())
257 let mut handle = ptr::null_mut();
258 let succeeded = unsafe {
259 GetModuleHandleExW(0 as DWORD, ptr::null(), &mut handle)
262 Err(io::Error::last_os_error().to_string())
264 Ok(handle as *mut u8)
270 SetThreadErrorMode(prev_error_mode, ptr::null_mut());
276 pub unsafe fn symbol(handle: *mut u8,
277 symbol: *const c_char)
278 -> Result<*mut u8, String> {
279 let ptr = GetProcAddress(handle as HMODULE, symbol) as *mut u8;
283 pub unsafe fn close(handle: *mut u8) {
284 FreeLibrary(handle as HMODULE);
287 fn ptr_result<T>(ptr: *mut T) -> Result<*mut T, String> {
289 Err(io::Error::last_os_error().to_string())