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