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