]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/dynamic_lib.rs
Remove support for self-opening
[rust.git] / src / librustc_metadata / dynamic_lib.rs
1 //! Dynamic library facilities.
2 //!
3 //! A simple wrapper over the platform's dynamic library facilities
4
5 use std::ffi::CString;
6 use std::path::Path;
7
8 pub struct DynamicLibrary {
9     handle: *mut u8,
10 }
11
12 impl Drop for DynamicLibrary {
13     fn drop(&mut self) {
14         unsafe { dl::close(self.handle) }
15     }
16 }
17
18 impl DynamicLibrary {
19     /// Lazily open a dynamic library.
20     pub fn open(filename: &Path) -> Result<DynamicLibrary, String> {
21         let maybe_library = dl::open(filename.as_os_str());
22
23         // The dynamic library must not be constructed if there is
24         // an error opening the library so the destructor does not
25         // run.
26         match maybe_library {
27             Err(err) => Err(err),
28             Ok(handle) => Ok(DynamicLibrary { handle }),
29         }
30     }
31
32     /// Accesses the value at the symbol of the dynamic library.
33     pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<*mut T, String> {
34         // This function should have a lifetime constraint of 'a on
35         // T but that feature is still unimplemented
36
37         let raw_string = CString::new(symbol).unwrap();
38         let maybe_symbol_value = dl::symbol(self.handle, raw_string.as_ptr());
39
40         // The value must not be constructed if there is an error so
41         // the destructor does not run.
42         match maybe_symbol_value {
43             Err(err) => Err(err),
44             Ok(symbol_value) => Ok(symbol_value as *mut T),
45         }
46     }
47 }
48
49 #[cfg(test)]
50 mod tests;
51
52 #[cfg(unix)]
53 mod dl {
54     use std::ffi::{CStr, CString, OsStr};
55     use std::os::unix::prelude::*;
56     use std::ptr;
57     use std::str;
58
59     pub(super) fn open(filename: &OsStr) -> Result<*mut u8, String> {
60         check_for_errors_in(|| unsafe {
61             let s = CString::new(filename.as_bytes()).unwrap();
62             libc::dlopen(s.as_ptr(), libc::RTLD_LAZY) as *mut u8
63         })
64     }
65
66     fn check_for_errors_in<T, F>(f: F) -> Result<T, String>
67     where
68         F: FnOnce() -> T,
69     {
70         use std::sync::{Mutex, Once};
71         static INIT: Once = Once::new();
72         static mut LOCK: *mut Mutex<()> = ptr::null_mut();
73         unsafe {
74             INIT.call_once(|| {
75                 LOCK = Box::into_raw(Box::new(Mutex::new(())));
76             });
77             // dlerror isn't thread safe, so we need to lock around this entire
78             // sequence
79             let _guard = (*LOCK).lock();
80             let _old_error = libc::dlerror();
81
82             let result = f();
83
84             let last_error = libc::dlerror() as *const _;
85             if ptr::null() == last_error {
86                 Ok(result)
87             } else {
88                 let s = CStr::from_ptr(last_error).to_bytes();
89                 Err(str::from_utf8(s).unwrap().to_owned())
90             }
91         }
92     }
93
94     pub(super) unsafe fn symbol(
95         handle: *mut u8,
96         symbol: *const libc::c_char,
97     ) -> Result<*mut u8, String> {
98         check_for_errors_in(|| libc::dlsym(handle as *mut libc::c_void, symbol) as *mut u8)
99     }
100
101     pub(super) unsafe fn close(handle: *mut u8) {
102         libc::dlclose(handle as *mut libc::c_void);
103     }
104 }
105
106 #[cfg(windows)]
107 mod dl {
108     use std::ffi::OsStr;
109     use std::io;
110     use std::os::windows::prelude::*;
111     use std::ptr;
112
113     use winapi::shared::minwindef::HMODULE;
114     use winapi::um::errhandlingapi::SetThreadErrorMode;
115     use winapi::um::libloaderapi::{FreeLibrary, GetProcAddress, LoadLibraryW};
116     use winapi::um::winbase::SEM_FAILCRITICALERRORS;
117
118     pub(super) fn open(filename: &OsStr) -> Result<*mut u8, String> {
119         // disable "dll load failed" error dialog.
120         let prev_error_mode = unsafe {
121             let new_error_mode = SEM_FAILCRITICALERRORS;
122             let mut prev_error_mode = 0;
123             let result = SetThreadErrorMode(new_error_mode, &mut prev_error_mode);
124             if result == 0 {
125                 return Err(io::Error::last_os_error().to_string());
126             }
127             prev_error_mode
128         };
129
130         let filename_str: Vec<_> = filename.encode_wide().chain(Some(0)).collect();
131         let result = unsafe { LoadLibraryW(filename_str.as_ptr()) } as *mut u8;
132         let result = ptr_result(result);
133
134         unsafe {
135             SetThreadErrorMode(prev_error_mode, ptr::null_mut());
136         }
137
138         result
139     }
140
141     pub(super) unsafe fn symbol(
142         handle: *mut u8,
143         symbol: *const libc::c_char,
144     ) -> Result<*mut u8, String> {
145         let ptr = GetProcAddress(handle as HMODULE, symbol) as *mut u8;
146         ptr_result(ptr)
147     }
148
149     pub(super) unsafe fn close(handle: *mut u8) {
150         FreeLibrary(handle as HMODULE);
151     }
152
153     fn ptr_result<T>(ptr: *mut T) -> Result<*mut T, String> {
154         if ptr.is_null() { Err(io::Error::last_os_error().to_string()) } else { Ok(ptr) }
155     }
156 }