1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
extern crate winapi;
extern crate kernel32;
use util::{ensure_compatible_types, cstr_cow_from_bytes};
use std::ffi::{OsStr, OsString};
use std::{fmt, io, marker, mem, ptr};
use std::os::windows::ffi::{OsStrExt, OsStringExt};
use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering};
pub struct Library(winapi::HMODULE);
unsafe impl Send for Library {}
unsafe impl Sync for Library {}
impl Library {
#[inline]
pub fn new<P: AsRef<OsStr>>(filename: P) -> ::Result<Library> {
let wide_filename: Vec<u16> = filename.as_ref().encode_wide().chain(Some(0)).collect();
let _guard = ErrorModeGuard::new();
let ret = with_get_last_error(|| {
let handle = unsafe { kernel32::LoadLibraryW(wide_filename.as_ptr()) };
if handle.is_null() {
None
} else {
Some(Library(handle))
}
}).map_err(|e| e.unwrap_or_else(||
panic!("LoadLibraryW failed but GetLastError did not report the error")
));
drop(wide_filename);
ret
}
pub unsafe fn get<T>(&self, symbol: &[u8]) -> ::Result<Symbol<T>> {
ensure_compatible_types::<T, winapi::FARPROC>();
let symbol = try!(cstr_cow_from_bytes(symbol));
with_get_last_error(|| {
let symbol = kernel32::GetProcAddress(self.0, symbol.as_ptr());
if symbol.is_null() {
None
} else {
Some(Symbol {
pointer: symbol,
pd: marker::PhantomData
})
}
}).map_err(|e| e.unwrap_or_else(||
panic!("GetProcAddress failed but GetLastError did not report the error")
))
}
pub unsafe fn get_ordinal<T>(&self, ordinal: winapi::WORD) -> ::Result<Symbol<T>> {
ensure_compatible_types::<T, winapi::FARPROC>();
with_get_last_error(|| {
let ordinal = ordinal as usize as *mut _;
let symbol = kernel32::GetProcAddress(self.0, ordinal);
if symbol.is_null() {
None
} else {
Some(Symbol {
pointer: symbol,
pd: marker::PhantomData
})
}
}).map_err(|e| e.unwrap_or_else(||
panic!("GetProcAddress failed but GetLastError did not report the error")
))
}
}
impl Drop for Library {
fn drop(&mut self) {
with_get_last_error(|| {
if unsafe { kernel32::FreeLibrary(self.0) == 0 } {
None
} else {
Some(())
}
}).unwrap()
}
}
impl fmt::Debug for Library {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
unsafe {
let mut buf: [winapi::WCHAR; 1024] = mem::uninitialized();
let len = kernel32::GetModuleFileNameW(self.0,
(&mut buf[..]).as_mut_ptr(), 1024) as usize;
if len == 0 {
f.write_str(&format!("Library@{:p}", self.0))
} else {
let string: OsString = OsString::from_wide(&buf[..len]);
f.write_str(&format!("Library@{:p} from {:?}", self.0, string))
}
}
}
}
pub struct Symbol<T> {
pointer: winapi::FARPROC,
pd: marker::PhantomData<T>
}
unsafe impl<T: Send> Send for Symbol<T> {}
unsafe impl<T: Sync> Sync for Symbol<T> {}
impl<T> Clone for Symbol<T> {
fn clone(&self) -> Symbol<T> {
Symbol { ..*self }
}
}
impl<T> ::std::ops::Deref for Symbol<T> {
type Target = T;
fn deref(&self) -> &T {
unsafe {
mem::transmute(&self.pointer)
}
}
}
impl<T> fmt::Debug for Symbol<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(&format!("Symbol@{:p}", self.pointer))
}
}
static USE_ERRORMODE: AtomicBool = ATOMIC_BOOL_INIT;
struct ErrorModeGuard(winapi::DWORD);
impl ErrorModeGuard {
fn new() -> ErrorModeGuard {
let mut ret = ErrorModeGuard(0);
if !USE_ERRORMODE.load(Ordering::Acquire) {
if unsafe { kernel32::SetThreadErrorMode(1, &mut ret.0) == 0
&& kernel32::GetLastError() == winapi::ERROR_CALL_NOT_IMPLEMENTED } {
USE_ERRORMODE.store(true, Ordering::Release);
} else {
return ret;
}
}
ret.0 = unsafe { kernel32::SetErrorMode(1) };
ret
}
}
impl Drop for ErrorModeGuard {
fn drop(&mut self) {
unsafe {
if !USE_ERRORMODE.load(Ordering::Relaxed) {
kernel32::SetThreadErrorMode(self.0, ptr::null_mut());
} else {
kernel32::SetErrorMode(self.0);
}
}
}
}
fn with_get_last_error<T, F>(closure: F) -> Result<T, Option<io::Error>>
where F: FnOnce() -> Option<T> {
closure().ok_or_else(|| {
let error = unsafe { kernel32::GetLastError() };
if error == 0 {
None
} else {
Some(io::Error::from_raw_os_error(error as i32))
}
})
}
#[test]
fn works_getlasterror() {
let lib = Library::new("kernel32.dll").unwrap();
let gle: Symbol<unsafe extern "system" fn() -> winapi::DWORD> = unsafe {
lib.get(b"GetLastError").unwrap()
};
unsafe {
kernel32::SetLastError(42);
assert_eq!(kernel32::GetLastError(), gle())
}
}
#[test]
fn works_getlasterror0() {
let lib = Library::new("kernel32.dll").unwrap();
let gle: Symbol<unsafe extern "system" fn() -> winapi::DWORD> = unsafe {
lib.get(b"GetLastError\0").unwrap()
};
unsafe {
kernel32::SetLastError(42);
assert_eq!(kernel32::GetLastError(), gle())
}
}