std\sys\pal\windows/
mod.rs

1#![allow(missing_docs, nonstandard_style)]
2#![forbid(unsafe_op_in_unsafe_fn)]
3
4use crate::ffi::{OsStr, OsString};
5use crate::io::ErrorKind;
6use crate::mem::MaybeUninit;
7use crate::os::windows::ffi::{OsStrExt, OsStringExt};
8use crate::path::PathBuf;
9use crate::sys::pal::windows::api::wide_str;
10use crate::time::Duration;
11
12#[macro_use]
13pub mod compat;
14
15pub mod api;
16
17pub mod c;
18#[cfg(not(target_vendor = "win7"))]
19pub mod futex;
20pub mod handle;
21pub mod os;
22pub mod pipe;
23pub mod thread;
24pub mod time;
25cfg_select! {
26    not(target_vendor = "uwp") => {
27        pub mod stack_overflow;
28    }
29    _ => {
30        pub mod stack_overflow_uwp;
31        pub use self::stack_overflow_uwp as stack_overflow;
32    }
33}
34
35/// Map a [`Result<T, WinError>`] to [`io::Result<T>`](crate::io::Result<T>).
36pub trait IoResult<T> {
37    fn io_result(self) -> crate::io::Result<T>;
38}
39impl<T> IoResult<T> for Result<T, api::WinError> {
40    fn io_result(self) -> crate::io::Result<T> {
41        self.map_err(|e| crate::io::Error::from_raw_os_error(e.code as i32))
42    }
43}
44
45// SAFETY: must be called only once during runtime initialization.
46// NOTE: this is not guaranteed to run, for example when Rust code is called externally.
47pub unsafe fn init(_argc: isize, _argv: *const *const u8, _sigpipe: u8) {
48    unsafe {
49        stack_overflow::init();
50
51        // Normally, `thread::spawn` will call `Thread::set_name` but since this thread already
52        // exists, we have to call it ourselves.
53        thread::Thread::set_name_wide(wide_str!("main"));
54    }
55}
56
57// SAFETY: must be called only once during runtime cleanup.
58// NOTE: this is not guaranteed to run, for example when the program aborts.
59pub unsafe fn cleanup() {
60    crate::sys::net::cleanup();
61}
62
63#[inline]
64pub fn is_interrupted(_errno: i32) -> bool {
65    false
66}
67
68pub fn decode_error_kind(errno: i32) -> ErrorKind {
69    use ErrorKind::*;
70
71    match errno as u32 {
72        c::ERROR_ACCESS_DENIED => return PermissionDenied,
73        c::ERROR_ALREADY_EXISTS => return AlreadyExists,
74        c::ERROR_FILE_EXISTS => return AlreadyExists,
75        c::ERROR_BROKEN_PIPE => return BrokenPipe,
76        c::ERROR_FILE_NOT_FOUND
77        | c::ERROR_PATH_NOT_FOUND
78        | c::ERROR_INVALID_DRIVE
79        | c::ERROR_BAD_NETPATH
80        | c::ERROR_BAD_NET_NAME => return NotFound,
81        c::ERROR_NO_DATA => return BrokenPipe,
82        c::ERROR_INVALID_NAME | c::ERROR_BAD_PATHNAME => return InvalidFilename,
83        c::ERROR_INVALID_PARAMETER => return InvalidInput,
84        c::ERROR_NOT_ENOUGH_MEMORY | c::ERROR_OUTOFMEMORY => return OutOfMemory,
85        c::ERROR_SEM_TIMEOUT
86        | c::WAIT_TIMEOUT
87        | c::ERROR_DRIVER_CANCEL_TIMEOUT
88        | c::ERROR_OPERATION_ABORTED
89        | c::ERROR_SERVICE_REQUEST_TIMEOUT
90        | c::ERROR_COUNTER_TIMEOUT
91        | c::ERROR_TIMEOUT
92        | c::ERROR_RESOURCE_CALL_TIMED_OUT
93        | c::ERROR_CTX_MODEM_RESPONSE_TIMEOUT
94        | c::ERROR_CTX_CLIENT_QUERY_TIMEOUT
95        | c::FRS_ERR_SYSVOL_POPULATE_TIMEOUT
96        | c::ERROR_DS_TIMELIMIT_EXCEEDED
97        | c::DNS_ERROR_RECORD_TIMED_OUT
98        | c::ERROR_IPSEC_IKE_TIMED_OUT
99        | c::ERROR_RUNLEVEL_SWITCH_TIMEOUT
100        | c::ERROR_RUNLEVEL_SWITCH_AGENT_TIMEOUT => return TimedOut,
101        c::ERROR_CALL_NOT_IMPLEMENTED => return Unsupported,
102        c::ERROR_HOST_UNREACHABLE => return HostUnreachable,
103        c::ERROR_NETWORK_UNREACHABLE => return NetworkUnreachable,
104        c::ERROR_DIRECTORY => return NotADirectory,
105        c::ERROR_DIRECTORY_NOT_SUPPORTED => return IsADirectory,
106        c::ERROR_DIR_NOT_EMPTY => return DirectoryNotEmpty,
107        c::ERROR_WRITE_PROTECT => return ReadOnlyFilesystem,
108        c::ERROR_DISK_FULL | c::ERROR_HANDLE_DISK_FULL => return StorageFull,
109        c::ERROR_SEEK_ON_DEVICE => return NotSeekable,
110        c::ERROR_DISK_QUOTA_EXCEEDED => return QuotaExceeded,
111        c::ERROR_FILE_TOO_LARGE => return FileTooLarge,
112        c::ERROR_BUSY => return ResourceBusy,
113        c::ERROR_POSSIBLE_DEADLOCK => return Deadlock,
114        c::ERROR_NOT_SAME_DEVICE => return CrossesDevices,
115        c::ERROR_TOO_MANY_LINKS => return TooManyLinks,
116        c::ERROR_FILENAME_EXCED_RANGE => return InvalidFilename,
117        c::ERROR_CANT_RESOLVE_FILENAME => return FilesystemLoop,
118        _ => {}
119    }
120
121    match errno {
122        c::WSAEACCES => PermissionDenied,
123        c::WSAEADDRINUSE => AddrInUse,
124        c::WSAEADDRNOTAVAIL => AddrNotAvailable,
125        c::WSAECONNABORTED => ConnectionAborted,
126        c::WSAECONNREFUSED => ConnectionRefused,
127        c::WSAECONNRESET => ConnectionReset,
128        c::WSAEINVAL => InvalidInput,
129        c::WSAENOTCONN => NotConnected,
130        c::WSAEWOULDBLOCK => WouldBlock,
131        c::WSAETIMEDOUT => TimedOut,
132        c::WSAEHOSTUNREACH => HostUnreachable,
133        c::WSAENETDOWN => NetworkDown,
134        c::WSAENETUNREACH => NetworkUnreachable,
135        c::WSAEDQUOT => QuotaExceeded,
136
137        _ => Uncategorized,
138    }
139}
140
141pub fn unrolled_find_u16s(needle: u16, haystack: &[u16]) -> Option<usize> {
142    let ptr = haystack.as_ptr();
143    let mut start = haystack;
144
145    // For performance reasons unfold the loop eight times.
146    while start.len() >= 8 {
147        macro_rules! if_return {
148            ($($n:literal,)+) => {
149                $(
150                    if start[$n] == needle {
151                        return Some(((&start[$n] as *const u16).addr() - ptr.addr()) / 2);
152                    }
153                )+
154            }
155        }
156
157        if_return!(0, 1, 2, 3, 4, 5, 6, 7,);
158
159        start = &start[8..];
160    }
161
162    for c in start {
163        if *c == needle {
164            return Some(((c as *const u16).addr() - ptr.addr()) / 2);
165        }
166    }
167    None
168}
169
170pub fn to_u16s<S: AsRef<OsStr>>(s: S) -> crate::io::Result<Vec<u16>> {
171    fn inner(s: &OsStr) -> crate::io::Result<Vec<u16>> {
172        // Most paths are ASCII, so reserve capacity for as much as there are bytes
173        // in the OsStr plus one for the null-terminating character. We are not
174        // wasting bytes here as paths created by this function are primarily used
175        // in an ephemeral fashion.
176        let mut maybe_result = Vec::with_capacity(s.len() + 1);
177        maybe_result.extend(s.encode_wide());
178
179        if unrolled_find_u16s(0, &maybe_result).is_some() {
180            return Err(crate::io::const_error!(
181                ErrorKind::InvalidInput,
182                "strings passed to WinAPI cannot contain NULs",
183            ));
184        }
185        maybe_result.push(0);
186        Ok(maybe_result)
187    }
188    inner(s.as_ref())
189}
190
191// Many Windows APIs follow a pattern of where we hand a buffer and then they
192// will report back to us how large the buffer should be or how many bytes
193// currently reside in the buffer. This function is an abstraction over these
194// functions by making them easier to call.
195//
196// The first callback, `f1`, is passed a (pointer, len) pair which can be
197// passed to a syscall. The `ptr` is valid for `len` items (u16 in this case).
198// The closure is expected to:
199// - On success, return the actual length of the written data *without* the null terminator.
200//   This can be 0. In this case the last_error must be left unchanged.
201// - On insufficient buffer space,
202//   - either return the required length *with* the null terminator,
203//   - or set the last-error to ERROR_INSUFFICIENT_BUFFER and return `len`.
204// - On other failure, return 0 and set last_error.
205//
206// This is how most but not all syscalls indicate the required buffer space.
207// Other syscalls may need translation to match this protocol.
208//
209// Once the syscall has completed (errors bail out early) the second closure is
210// passed the data which has been read from the syscall. The return value
211// from this closure is then the return value of the function.
212pub fn fill_utf16_buf<F1, F2, T>(mut f1: F1, f2: F2) -> crate::io::Result<T>
213where
214    F1: FnMut(*mut u16, u32) -> u32,
215    F2: FnOnce(&[u16]) -> T,
216{
217    // Start off with a stack buf but then spill over to the heap if we end up
218    // needing more space.
219    //
220    // This initial size also works around `GetFullPathNameW` returning
221    // incorrect size hints for some short paths:
222    // https://github.com/dylni/normpath/issues/5
223    let mut stack_buf: [MaybeUninit<u16>; 512] = [MaybeUninit::uninit(); 512];
224    let mut heap_buf: Vec<MaybeUninit<u16>> = Vec::new();
225    unsafe {
226        let mut n = stack_buf.len();
227        loop {
228            let buf = if n <= stack_buf.len() {
229                &mut stack_buf[..]
230            } else {
231                let extra = n - heap_buf.len();
232                heap_buf.reserve(extra);
233                // We used `reserve` and not `reserve_exact`, so in theory we
234                // may have gotten more than requested. If so, we'd like to use
235                // it... so long as we won't cause overflow.
236                n = heap_buf.capacity().min(u32::MAX as usize);
237                // Safety: MaybeUninit<u16> does not need initialization
238                heap_buf.set_len(n);
239                &mut heap_buf[..]
240            };
241
242            // This function is typically called on windows API functions which
243            // will return the correct length of the string, but these functions
244            // also return the `0` on error. In some cases, however, the
245            // returned "correct length" may actually be 0!
246            //
247            // To handle this case we call `SetLastError` to reset it to 0 and
248            // then check it again if we get the "0 error value". If the "last
249            // error" is still 0 then we interpret it as a 0 length buffer and
250            // not an actual error.
251            c::SetLastError(0);
252            let k = match f1(buf.as_mut_ptr().cast::<u16>(), n as u32) {
253                0 if api::get_last_error().code == 0 => 0,
254                0 => return Err(crate::io::Error::last_os_error()),
255                n => n,
256            } as usize;
257            if k == n && api::get_last_error().code == c::ERROR_INSUFFICIENT_BUFFER {
258                n = n.saturating_mul(2).min(u32::MAX as usize);
259            } else if k > n {
260                n = k;
261            } else if k == n {
262                // It is impossible to reach this point.
263                // On success, k is the returned string length excluding the null.
264                // On failure, k is the required buffer length including the null.
265                // Therefore k never equals n.
266                unreachable!();
267            } else {
268                // Safety: First `k` values are initialized.
269                let slice: &[u16] = buf[..k].assume_init_ref();
270                return Ok(f2(slice));
271            }
272        }
273    }
274}
275
276pub fn os2path(s: &[u16]) -> PathBuf {
277    PathBuf::from(OsString::from_wide(s))
278}
279
280pub fn truncate_utf16_at_nul(v: &[u16]) -> &[u16] {
281    match unrolled_find_u16s(0, v) {
282        // don't include the 0
283        Some(i) => &v[..i],
284        None => v,
285    }
286}
287
288pub fn ensure_no_nuls<T: AsRef<OsStr>>(s: T) -> crate::io::Result<T> {
289    if s.as_ref().encode_wide().any(|b| b == 0) {
290        Err(crate::io::const_error!(ErrorKind::InvalidInput, "nul byte found in provided data"))
291    } else {
292        Ok(s)
293    }
294}
295
296pub trait IsZero {
297    fn is_zero(&self) -> bool;
298}
299
300macro_rules! impl_is_zero {
301    ($($t:ident)*) => ($(impl IsZero for $t {
302        fn is_zero(&self) -> bool {
303            *self == 0
304        }
305    })*)
306}
307
308impl_is_zero! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
309
310pub fn cvt<I: IsZero>(i: I) -> crate::io::Result<I> {
311    if i.is_zero() { Err(crate::io::Error::last_os_error()) } else { Ok(i) }
312}
313
314pub fn dur2timeout(dur: Duration) -> u32 {
315    // Note that a duration is a (u64, u32) (seconds, nanoseconds) pair, and the
316    // timeouts in windows APIs are typically u32 milliseconds. To translate, we
317    // have two pieces to take care of:
318    //
319    // * Nanosecond precision is rounded up
320    // * Greater than u32::MAX milliseconds (50 days) is rounded up to INFINITE
321    //   (never time out).
322    dur.as_secs()
323        .checked_mul(1000)
324        .and_then(|ms| ms.checked_add((dur.subsec_nanos() as u64) / 1_000_000))
325        .and_then(|ms| ms.checked_add(if dur.subsec_nanos() % 1_000_000 > 0 { 1 } else { 0 }))
326        .map(|ms| if ms > <u32>::MAX as u64 { c::INFINITE } else { ms as u32 })
327        .unwrap_or(c::INFINITE)
328}
329
330/// Use `__fastfail` to abort the process
331///
332/// In Windows 8 and later, this will terminate the process immediately without
333/// running any in-process exception handlers. In earlier versions of Windows,
334/// this sequence of instructions will be treated as an access violation, which
335/// will still terminate the process but might run some exception handlers.
336///
337/// https://docs.microsoft.com/en-us/cpp/intrinsics/fastfail
338#[cfg(not(miri))] // inline assembly does not work in Miri
339pub fn abort_internal() -> ! {
340    unsafe {
341        cfg_select! {
342            any(target_arch = "x86", target_arch = "x86_64") => {
343                core::arch::asm!("int $$0x29", in("ecx") c::FAST_FAIL_FATAL_APP_EXIT, options(noreturn, nostack));
344            }
345            all(target_arch = "arm", target_feature = "thumb-mode") => {
346                core::arch::asm!(".inst 0xDEFB", in("r0") c::FAST_FAIL_FATAL_APP_EXIT, options(noreturn, nostack));
347            }
348            any(target_arch = "aarch64", target_arch = "arm64ec") => {
349                core::arch::asm!("brk 0xF003", in("x0") c::FAST_FAIL_FATAL_APP_EXIT, options(noreturn, nostack));
350            }
351            _ => {
352                core::intrinsics::abort();
353            }
354        }
355    }
356}
357
358#[cfg(miri)]
359pub fn abort_internal() -> ! {
360    crate::intrinsics::abort();
361}
362
363/// Align the inner value to 8 bytes.
364///
365/// This is enough for almost all of the buffers we're likely to work with in
366/// the Windows APIs we use.
367#[repr(C, align(8))]
368#[derive(Copy, Clone)]
369pub(crate) struct Align8<T: ?Sized>(pub T);