std\sys\pal\windows/api.rs
1//! # Safe(r) wrappers around Windows API functions.
2//!
3//! This module contains fairly thin wrappers around Windows API functions,
4//! aimed at centralising safety instead of having unsafe blocks spread
5//! throughout higher level code. This makes it much easier to audit FFI safety.
6//!
7//! Not all functions can be made completely safe without more context but in
8//! such cases we should still endeavour to reduce the caller's burden of safety
9//! as much as possible.
10//!
11//! ## Guidelines for wrappers
12//!
13//! Items here should be named similarly to their raw Windows API name, except
14//! that they follow Rust's case conventions. E.g. function names are
15//! lower_snake_case. The idea here is that it should be easy for a Windows
16//! C/C++ programmer to identify the underlying function that's being wrapped
17//! while not looking too out of place in Rust code.
18//!
19//! Every use of an `unsafe` block must have a related SAFETY comment, even if
20//! it's trivially safe (for example, see `get_last_error`). Public unsafe
21//! functions must document what the caller has to do to call them safely.
22//!
23//! Avoid unchecked `as` casts. For integers, either assert that the integer
24//! is in range or use `try_into` instead. For pointers, prefer to use
25//! `ptr.cast::<Type>()` when possible.
26//!
27//! This module must only depend on core and not on std types as the eventual
28//! hope is to have std depend on sys and not the other way around.
29//! However, some amount of glue code may currently be necessary so such code
30//! should go in sys/pal/windows/mod.rs rather than here. See `IoResult` as an example.
31
32use core::ffi::c_void;
33use core::marker::PhantomData;
34
35use super::c;
36
37/// Creates a null-terminated UTF-16 string from a str.
38pub macro wide_str($str:literal) {{
39 const _: () = {
40 if core::slice::memchr::memchr(0, $str.as_bytes()).is_some() {
41 panic!("null terminated strings cannot contain interior nulls");
42 }
43 };
44 crate::sys::pal::windows::api::utf16!(concat!($str, '\0'))
45}}
46
47/// Creates a UTF-16 string from a str without null termination.
48pub macro utf16($str:expr) {{
49 const UTF8: &str = $str;
50 const UTF16_LEN: usize = crate::sys::pal::windows::api::utf16_len(UTF8);
51 const UTF16: [u16; UTF16_LEN] = crate::sys::pal::windows::api::to_utf16(UTF8);
52 &UTF16
53}}
54
55#[cfg(test)]
56mod tests;
57
58/// Gets the UTF-16 length of a UTF-8 string, for use in the wide_str macro.
59pub const fn utf16_len(s: &str) -> usize {
60 let s = s.as_bytes();
61 let mut i = 0;
62 let mut len = 0;
63 while i < s.len() {
64 // the length of a UTF-8 encoded code-point is given by the number of
65 // leading ones, except in the case of ASCII.
66 let utf8_len = match s[i].leading_ones() {
67 0 => 1,
68 n => n as usize,
69 };
70 i += utf8_len;
71 // Note that UTF-16 surrogates (U+D800 to U+DFFF) are not encodable as UTF-8,
72 // so (unlike with WTF-8) we don't have to worry about how they'll get re-encoded.
73 len += if utf8_len < 4 { 1 } else { 2 };
74 }
75 len
76}
77
78/// Const convert UTF-8 to UTF-16, for use in the wide_str macro.
79///
80/// Note that this is designed for use in const contexts so is not optimized.
81pub const fn to_utf16<const UTF16_LEN: usize>(s: &str) -> [u16; UTF16_LEN] {
82 let mut output = [0_u16; UTF16_LEN];
83 let mut pos = 0;
84 let s = s.as_bytes();
85 let mut i = 0;
86 while i < s.len() {
87 match s[i].leading_ones() {
88 // Decode UTF-8 based on its length.
89 // See https://en.wikipedia.org/wiki/UTF-8
90 0 => {
91 // ASCII is the same in both encodings
92 output[pos] = s[i] as u16;
93 i += 1;
94 pos += 1;
95 }
96 2 => {
97 // Bits: 110xxxxx 10xxxxxx
98 output[pos] = ((s[i] as u16 & 0b11111) << 6) | (s[i + 1] as u16 & 0b111111);
99 i += 2;
100 pos += 1;
101 }
102 3 => {
103 // Bits: 1110xxxx 10xxxxxx 10xxxxxx
104 output[pos] = ((s[i] as u16 & 0b1111) << 12)
105 | ((s[i + 1] as u16 & 0b111111) << 6)
106 | (s[i + 2] as u16 & 0b111111);
107 i += 3;
108 pos += 1;
109 }
110 4 => {
111 // Bits: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
112 let mut c = ((s[i] as u32 & 0b111) << 18)
113 | ((s[i + 1] as u32 & 0b111111) << 12)
114 | ((s[i + 2] as u32 & 0b111111) << 6)
115 | (s[i + 3] as u32 & 0b111111);
116 // re-encode as UTF-16 (see https://en.wikipedia.org/wiki/UTF-16)
117 // - Subtract 0x10000 from the code point
118 // - For the high surrogate, shift right by 10 then add 0xD800
119 // - For the low surrogate, take the low 10 bits then add 0xDC00
120 c -= 0x10000;
121 output[pos] = ((c >> 10) + 0xD800) as u16;
122 output[pos + 1] = ((c & 0b1111111111) + 0xDC00) as u16;
123 i += 4;
124 pos += 2;
125 }
126 // valid UTF-8 cannot have any other values
127 _ => unreachable!(),
128 }
129 }
130 output
131}
132
133/// Helper method for getting the size of `T` as a u32.
134/// Errors at compile time if the size would overflow.
135///
136/// While a type larger than u32::MAX is unlikely, it is possible if only because of a bug.
137/// However, one key motivation for this function is to avoid the temptation to
138/// use frequent `as` casts. This is risky because they are too powerful.
139/// For example, the following will compile today:
140///
141/// `size_of::<u64> as u32`
142///
143/// Note that `size_of` is never actually called, instead a function pointer is
144/// converted to a `u32`. Clippy would warn about this but, alas, it's not run
145/// on the standard library.
146const fn win32_size_of<T: Sized>() -> u32 {
147 // Const assert that the size does not exceed u32::MAX.
148 // Uses a trait to workaround restriction on using generic types in inner items.
149 trait Win32SizeOf: Sized {
150 const WIN32_SIZE_OF: u32 = {
151 let size = size_of::<Self>();
152 assert!(size <= u32::MAX as usize);
153 size as u32
154 };
155 }
156 impl<T: Sized> Win32SizeOf for T {}
157
158 T::WIN32_SIZE_OF
159}
160
161/// The `SetFileInformationByHandle` function takes a generic parameter by
162/// making the user specify the type (class), a pointer to the data and its
163/// size. This trait allows attaching that information to a Rust type so that
164/// [`set_file_information_by_handle`] can be called safely.
165///
166/// This trait is designed so that it can support variable sized types.
167/// However, currently Rust's std only uses fixed sized structures.
168///
169/// # Safety
170///
171/// * `as_ptr` must return a pointer to memory that is readable up to `size` bytes.
172/// * `CLASS` must accurately reflect the type pointed to by `as_ptr`. E.g.
173/// the `FILE_BASIC_INFO` structure has the class `FileBasicInfo`.
174pub unsafe trait SetFileInformation {
175 /// The type of information to set.
176 const CLASS: i32;
177 /// A pointer to the file information to set.
178 fn as_ptr(&self) -> *const c_void;
179 /// The size of the type pointed to by `as_ptr`.
180 fn size(&self) -> u32;
181}
182/// Helper trait for implementing `SetFileInformation` for statically sized types.
183unsafe trait SizedSetFileInformation: Sized {
184 const CLASS: i32;
185}
186unsafe impl<T: SizedSetFileInformation> SetFileInformation for T {
187 const CLASS: i32 = T::CLASS;
188 fn as_ptr(&self) -> *const c_void {
189 (&raw const *self).cast::<c_void>()
190 }
191 fn size(&self) -> u32 {
192 win32_size_of::<Self>()
193 }
194}
195
196// SAFETY: FILE_BASIC_INFO, FILE_END_OF_FILE_INFO, FILE_ALLOCATION_INFO,
197// FILE_DISPOSITION_INFO, FILE_DISPOSITION_INFO_EX and FILE_IO_PRIORITY_HINT_INFO
198// are all plain `repr(C)` structs that only contain primitive types.
199// The given information classes correctly match with the struct.
200unsafe impl SizedSetFileInformation for c::FILE_BASIC_INFO {
201 const CLASS: i32 = c::FileBasicInfo;
202}
203unsafe impl SizedSetFileInformation for c::FILE_END_OF_FILE_INFO {
204 const CLASS: i32 = c::FileEndOfFileInfo;
205}
206unsafe impl SizedSetFileInformation for c::FILE_ALLOCATION_INFO {
207 const CLASS: i32 = c::FileAllocationInfo;
208}
209unsafe impl SizedSetFileInformation for c::FILE_DISPOSITION_INFO {
210 const CLASS: i32 = c::FileDispositionInfo;
211}
212unsafe impl SizedSetFileInformation for c::FILE_DISPOSITION_INFO_EX {
213 const CLASS: i32 = c::FileDispositionInfoEx;
214}
215unsafe impl SizedSetFileInformation for c::FILE_IO_PRIORITY_HINT_INFO {
216 const CLASS: i32 = c::FileIoPriorityHintInfo;
217}
218
219#[inline]
220pub fn set_file_information_by_handle<T: SetFileInformation>(
221 handle: c::HANDLE,
222 info: &T,
223) -> Result<(), WinError> {
224 unsafe fn set_info(
225 handle: c::HANDLE,
226 class: i32,
227 info: *const c_void,
228 size: u32,
229 ) -> Result<(), WinError> {
230 unsafe {
231 let result = c::SetFileInformationByHandle(handle, class, info, size);
232 (result != 0).then_some(()).ok_or_else(get_last_error)
233 }
234 }
235 // SAFETY: The `SetFileInformation` trait ensures that this is safe.
236 unsafe { set_info(handle, T::CLASS, info.as_ptr(), info.size()) }
237}
238
239/// Gets the error from the last function.
240/// This must be called immediately after the function that sets the error to
241/// avoid the risk of another function overwriting it.
242pub fn get_last_error() -> WinError {
243 // SAFETY: This just returns a thread-local u32 and has no other effects.
244 unsafe { WinError { code: c::GetLastError() } }
245}
246
247/// An error code as returned by [`get_last_error`].
248///
249/// This is usually a 16-bit Win32 error code but may be a 32-bit HRESULT or NTSTATUS.
250/// Check the documentation of the Windows API function being called for expected errors.
251#[derive(Clone, Copy, PartialEq, Eq)]
252#[repr(transparent)]
253pub struct WinError {
254 pub code: u32,
255}
256impl WinError {
257 pub const fn new(code: u32) -> Self {
258 Self { code }
259 }
260}
261
262// Error code constants.
263// The constant names should be the same as the winapi constants except for the leading `ERROR_`.
264// Due to the sheer number of codes, error codes should only be added here on an as-needed basis.
265// However, they should never be removed as the assumption is they may be useful again in the future.
266#[allow(unused)]
267impl WinError {
268 /// Success is not an error.
269 /// Some Windows APIs do use this to distinguish between a zero return and an error return
270 /// but we should never return this to users as an error.
271 pub const SUCCESS: Self = Self::new(c::ERROR_SUCCESS);
272 // tidy-alphabetical-start
273 pub const ACCESS_DENIED: Self = Self::new(c::ERROR_ACCESS_DENIED);
274 pub const ALREADY_EXISTS: Self = Self::new(c::ERROR_ALREADY_EXISTS);
275 pub const BAD_NETPATH: Self = Self::new(c::ERROR_BAD_NETPATH);
276 pub const BAD_NET_NAME: Self = Self::new(c::ERROR_BAD_NET_NAME);
277 pub const CANT_ACCESS_FILE: Self = Self::new(c::ERROR_CANT_ACCESS_FILE);
278 pub const DELETE_PENDING: Self = Self::new(c::ERROR_DELETE_PENDING);
279 pub const DIRECTORY: Self = Self::new(c::ERROR_DIRECTORY);
280 pub const DIR_NOT_EMPTY: Self = Self::new(c::ERROR_DIR_NOT_EMPTY);
281 pub const FILE_NOT_FOUND: Self = Self::new(c::ERROR_FILE_NOT_FOUND);
282 pub const INSUFFICIENT_BUFFER: Self = Self::new(c::ERROR_INSUFFICIENT_BUFFER);
283 pub const INVALID_FUNCTION: Self = Self::new(c::ERROR_INVALID_FUNCTION);
284 pub const INVALID_HANDLE: Self = Self::new(c::ERROR_INVALID_HANDLE);
285 pub const INVALID_PARAMETER: Self = Self::new(c::ERROR_INVALID_PARAMETER);
286 pub const NOT_FOUND: Self = Self::new(c::ERROR_NOT_FOUND);
287 pub const NOT_SUPPORTED: Self = Self::new(c::ERROR_NOT_SUPPORTED);
288 pub const NO_MORE_FILES: Self = Self::new(c::ERROR_NO_MORE_FILES);
289 pub const OPERATION_ABORTED: Self = Self::new(c::ERROR_OPERATION_ABORTED);
290 pub const PATH_NOT_FOUND: Self = Self::new(c::ERROR_PATH_NOT_FOUND);
291 pub const SHARING_VIOLATION: Self = Self::new(c::ERROR_SHARING_VIOLATION);
292 pub const TIMEOUT: Self = Self::new(c::ERROR_TIMEOUT);
293 // tidy-alphabetical-end
294}
295
296/// A wrapper around a UNICODE_STRING that is equivalent to `&[u16]`.
297///
298/// It is preferable to use the `unicode_str!` macro as that contains mitigations for #143078.
299///
300/// If the MaximumLength field of the underlying UNICODE_STRING is greater than
301/// the Length field then you can test if the string is null terminated by inspecting
302/// the u16 directly after the string. You cannot otherwise depend on nul termination.
303#[derive(Copy, Clone)]
304pub struct UnicodeStrRef<'a> {
305 s: c::UNICODE_STRING,
306 lifetime: PhantomData<&'a [u16]>,
307}
308
309static EMPTY_STRING_NULL_TERMINATED: &[u16] = &[0];
310
311impl UnicodeStrRef<'_> {
312 const fn new(slice: &[u16], is_null_terminated: bool) -> Self {
313 let (len, max_len, ptr) = if slice.is_empty() {
314 (0, 2, EMPTY_STRING_NULL_TERMINATED.as_ptr().cast_mut())
315 } else {
316 let len = slice.len() - (is_null_terminated as usize);
317 (len * 2, size_of_val(slice), slice.as_ptr().cast_mut())
318 };
319 Self {
320 s: c::UNICODE_STRING { Length: len as _, MaximumLength: max_len as _, Buffer: ptr },
321 lifetime: PhantomData,
322 }
323 }
324
325 pub const fn from_slice_with_nul(slice: &[u16]) -> Self {
326 if !slice.is_empty() {
327 debug_assert!(slice[slice.len() - 1] == 0);
328 }
329 Self::new(slice, true)
330 }
331
332 pub const fn from_slice(slice: &[u16]) -> Self {
333 Self::new(slice, false)
334 }
335
336 /// Returns a pointer to the underlying UNICODE_STRING
337 pub const fn as_ptr(&self) -> *const c::UNICODE_STRING {
338 &self.s
339 }
340}
341
342/// Create a UnicodeStringRef from a literal str or a u16 array.
343///
344/// To mitigate #143078, when using a literal str the created UNICODE_STRING
345/// will be nul terminated. The MaximumLength field of the UNICODE_STRING will
346/// be set greater than the Length field to indicate that a nul may be present.
347///
348/// If using a u16 array, the array is used exactly as provided and you cannot
349/// count on the string being nul terminated.
350/// This should generally be used for strings that come from the OS.
351///
352/// **NOTE:** we lack a UNICODE_STRING builder type as we don't currently have
353/// a use for it. If needing to dynamically build a UNICODE_STRING, the builder
354/// should try to ensure there's a nul one past the end of the string.
355pub macro unicode_str {
356 ($str:literal) => {const {
357 crate::sys::pal::windows::api::UnicodeStrRef::from_slice_with_nul(
358 crate::sys::pal::windows::api::wide_str!($str),
359 )
360 }},
361 ($array:expr) => {
362 crate::sys::pal::windows::api::UnicodeStrRef::from_slice(
363 $array,
364 )
365 }
366}