]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/dynamic_lib.rs
Auto merge of #67312 - cuviper:clone-box-slice, r=SimonSapin
[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     pub(super) unsafe fn close(handle: *mut u8) {
115         libc::dlclose(handle as *mut libc::c_void);
116         ()
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 libc::{c_char, c_uint, c_void};
128
129     type DWORD = u32;
130     type HMODULE = *mut u8;
131     type BOOL = i32;
132     type LPCWSTR = *const u16;
133     type LPCSTR = *const i8;
134
135     extern "system" {
136         fn SetThreadErrorMode(dwNewMode: DWORD, lpOldMode: *mut DWORD) -> c_uint;
137         fn LoadLibraryW(name: LPCWSTR) -> HMODULE;
138         fn GetModuleHandleExW(dwFlags: DWORD, name: LPCWSTR, handle: *mut HMODULE) -> BOOL;
139         fn GetProcAddress(handle: HMODULE, name: LPCSTR) -> *mut c_void;
140         fn FreeLibrary(handle: HMODULE) -> BOOL;
141     }
142
143     pub(super) fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
144         // disable "dll load failed" error dialog.
145         let prev_error_mode = unsafe {
146             // SEM_FAILCRITICALERRORS 0x01
147             let new_error_mode = 1;
148             let mut prev_error_mode = 0;
149             let result = SetThreadErrorMode(new_error_mode, &mut prev_error_mode);
150             if result == 0 {
151                 return Err(io::Error::last_os_error().to_string());
152             }
153             prev_error_mode
154         };
155
156         let result = match filename {
157             Some(filename) => {
158                 let filename_str: Vec<_> = filename.encode_wide().chain(Some(0)).collect();
159                 let result = unsafe { LoadLibraryW(filename_str.as_ptr()) };
160                 ptr_result(result)
161             }
162             None => {
163                 let mut handle = ptr::null_mut();
164                 let succeeded = unsafe { GetModuleHandleExW(0 as DWORD, ptr::null(), &mut handle) };
165                 if succeeded == 0 {
166                     Err(io::Error::last_os_error().to_string())
167                 } else {
168                     Ok(handle as *mut u8)
169                 }
170             }
171         };
172
173         unsafe {
174             SetThreadErrorMode(prev_error_mode, ptr::null_mut());
175         }
176
177         result
178     }
179
180     pub(super) unsafe fn symbol(handle: *mut u8, symbol: *const c_char) -> Result<*mut u8, String> {
181         let ptr = GetProcAddress(handle as HMODULE, symbol) as *mut u8;
182         ptr_result(ptr)
183     }
184
185     pub(super) unsafe fn close(handle: *mut u8) {
186         FreeLibrary(handle as HMODULE);
187     }
188
189     fn ptr_result<T>(ptr: *mut T) -> Result<*mut T, String> {
190         if ptr.is_null() { Err(io::Error::last_os_error().to_string()) } else { Ok(ptr) }
191     }
192 }