summaryrefslogtreecommitdiffstats
path: root/library/std/src/sys/windows
diff options
context:
space:
mode:
Diffstat (limited to 'library/std/src/sys/windows')
-rw-r--r--library/std/src/sys/windows/alloc.rs246
-rw-r--r--library/std/src/sys/windows/alloc/tests.rs9
-rw-r--r--library/std/src/sys/windows/args.rs406
-rw-r--r--library/std/src/sys/windows/args/tests.rs91
-rw-r--r--library/std/src/sys/windows/c.rs1340
-rw-r--r--library/std/src/sys/windows/c/errors.rs1883
-rw-r--r--library/std/src/sys/windows/cmath.rs92
-rw-r--r--library/std/src/sys/windows/compat.rs273
-rw-r--r--library/std/src/sys/windows/env.rs9
-rw-r--r--library/std/src/sys/windows/fs.rs1399
-rw-r--r--library/std/src/sys/windows/handle.rs335
-rw-r--r--library/std/src/sys/windows/handle/tests.rs22
-rw-r--r--library/std/src/sys/windows/io.rs80
-rw-r--r--library/std/src/sys/windows/locks/condvar.rs52
-rw-r--r--library/std/src/sys/windows/locks/mod.rs6
-rw-r--r--library/std/src/sys/windows/locks/mutex.rs57
-rw-r--r--library/std/src/sys/windows/locks/rwlock.rs42
-rw-r--r--library/std/src/sys/windows/memchr.rs5
-rw-r--r--library/std/src/sys/windows/mod.rs323
-rw-r--r--library/std/src/sys/windows/net.rs476
-rw-r--r--library/std/src/sys/windows/os.rs328
-rw-r--r--library/std/src/sys/windows/os/tests.rs13
-rw-r--r--library/std/src/sys/windows/os_str.rs226
-rw-r--r--library/std/src/sys/windows/path.rs333
-rw-r--r--library/std/src/sys/windows/path/tests.rs137
-rw-r--r--library/std/src/sys/windows/pipe.rs538
-rw-r--r--library/std/src/sys/windows/process.rs847
-rw-r--r--library/std/src/sys/windows/process/tests.rs222
-rw-r--r--library/std/src/sys/windows/rand.rs35
-rw-r--r--library/std/src/sys/windows/stack_overflow.rs42
-rw-r--r--library/std/src/sys/windows/stack_overflow_uwp.rs11
-rw-r--r--library/std/src/sys/windows/stdio.rs422
-rw-r--r--library/std/src/sys/windows/stdio_uwp.rs87
-rw-r--r--library/std/src/sys/windows/thread.rs125
-rw-r--r--library/std/src/sys/windows/thread_local_dtor.rs28
-rw-r--r--library/std/src/sys/windows/thread_local_key.rs238
-rw-r--r--library/std/src/sys/windows/thread_parker.rs255
-rw-r--r--library/std/src/sys/windows/time.rs224
38 files changed, 11257 insertions, 0 deletions
diff --git a/library/std/src/sys/windows/alloc.rs b/library/std/src/sys/windows/alloc.rs
new file mode 100644
index 000000000..fdc81cdea
--- /dev/null
+++ b/library/std/src/sys/windows/alloc.rs
@@ -0,0 +1,246 @@
+#![deny(unsafe_op_in_unsafe_fn)]
+
+use crate::alloc::{GlobalAlloc, Layout, System};
+use crate::ffi::c_void;
+use crate::ptr;
+use crate::sync::atomic::{AtomicPtr, Ordering};
+use crate::sys::c;
+use crate::sys::common::alloc::{realloc_fallback, MIN_ALIGN};
+
+#[cfg(test)]
+mod tests;
+
+// Heap memory management on Windows is done by using the system Heap API (heapapi.h)
+// See https://docs.microsoft.com/windows/win32/api/heapapi/
+
+// Flag to indicate that the memory returned by `HeapAlloc` should be zeroed.
+const HEAP_ZERO_MEMORY: c::DWORD = 0x00000008;
+
+extern "system" {
+ // Get a handle to the default heap of the current process, or null if the operation fails.
+ //
+ // SAFETY: Successful calls to this function within the same process are assumed to
+ // always return the same handle, which remains valid for the entire lifetime of the process.
+ //
+ // See https://docs.microsoft.com/windows/win32/api/heapapi/nf-heapapi-getprocessheap
+ fn GetProcessHeap() -> c::HANDLE;
+
+ // Allocate a block of `dwBytes` bytes of memory from a given heap `hHeap`.
+ // The allocated memory may be uninitialized, or zeroed if `dwFlags` is
+ // set to `HEAP_ZERO_MEMORY`.
+ //
+ // Returns a pointer to the newly-allocated memory or null if the operation fails.
+ // The returned pointer will be aligned to at least `MIN_ALIGN`.
+ //
+ // SAFETY:
+ // - `hHeap` must be a non-null handle returned by `GetProcessHeap`.
+ // - `dwFlags` must be set to either zero or `HEAP_ZERO_MEMORY`.
+ //
+ // Note that `dwBytes` is allowed to be zero, contrary to some other allocators.
+ //
+ // See https://docs.microsoft.com/windows/win32/api/heapapi/nf-heapapi-heapalloc
+ fn HeapAlloc(hHeap: c::HANDLE, dwFlags: c::DWORD, dwBytes: c::SIZE_T) -> c::LPVOID;
+
+ // Reallocate a block of memory behind a given pointer `lpMem` from a given heap `hHeap`,
+ // to a block of at least `dwBytes` bytes, either shrinking the block in place,
+ // or allocating at a new location, copying memory, and freeing the original location.
+ //
+ // Returns a pointer to the reallocated memory or null if the operation fails.
+ // The returned pointer will be aligned to at least `MIN_ALIGN`.
+ // If the operation fails the given block will never have been freed.
+ //
+ // SAFETY:
+ // - `hHeap` must be a non-null handle returned by `GetProcessHeap`.
+ // - `dwFlags` must be set to zero.
+ // - `lpMem` must be a non-null pointer to an allocated block returned by `HeapAlloc` or
+ // `HeapReAlloc`, that has not already been freed.
+ // If the block was successfully reallocated at a new location, pointers pointing to
+ // the freed memory, such as `lpMem`, must not be dereferenced ever again.
+ //
+ // Note that `dwBytes` is allowed to be zero, contrary to some other allocators.
+ //
+ // See https://docs.microsoft.com/windows/win32/api/heapapi/nf-heapapi-heaprealloc
+ fn HeapReAlloc(
+ hHeap: c::HANDLE,
+ dwFlags: c::DWORD,
+ lpMem: c::LPVOID,
+ dwBytes: c::SIZE_T,
+ ) -> c::LPVOID;
+
+ // Free a block of memory behind a given pointer `lpMem` from a given heap `hHeap`.
+ // Returns a nonzero value if the operation is successful, and zero if the operation fails.
+ //
+ // SAFETY:
+ // - `hHeap` must be a non-null handle returned by `GetProcessHeap`.
+ // - `dwFlags` must be set to zero.
+ // - `lpMem` must be a pointer to an allocated block returned by `HeapAlloc` or `HeapReAlloc`,
+ // that has not already been freed.
+ // If the block was successfully freed, pointers pointing to the freed memory, such as `lpMem`,
+ // must not be dereferenced ever again.
+ //
+ // Note that `lpMem` is allowed to be null, which will not cause the operation to fail.
+ //
+ // See https://docs.microsoft.com/windows/win32/api/heapapi/nf-heapapi-heapfree
+ fn HeapFree(hHeap: c::HANDLE, dwFlags: c::DWORD, lpMem: c::LPVOID) -> c::BOOL;
+}
+
+// Cached handle to the default heap of the current process.
+// Either a non-null handle returned by `GetProcessHeap`, or null when not yet initialized or `GetProcessHeap` failed.
+static HEAP: AtomicPtr<c_void> = AtomicPtr::new(ptr::null_mut());
+
+// Get a handle to the default heap of the current process, or null if the operation fails.
+// If this operation is successful, `HEAP` will be successfully initialized and contain
+// a non-null handle returned by `GetProcessHeap`.
+#[inline]
+fn init_or_get_process_heap() -> c::HANDLE {
+ let heap = HEAP.load(Ordering::Relaxed);
+ if heap.is_null() {
+ // `HEAP` has not yet been successfully initialized
+ let heap = unsafe { GetProcessHeap() };
+ if !heap.is_null() {
+ // SAFETY: No locking is needed because within the same process,
+ // successful calls to `GetProcessHeap` will always return the same value, even on different threads.
+ HEAP.store(heap, Ordering::Release);
+
+ // SAFETY: `HEAP` contains a non-null handle returned by `GetProcessHeap`
+ heap
+ } else {
+ // Could not get the current process heap.
+ ptr::null_mut()
+ }
+ } else {
+ // SAFETY: `HEAP` contains a non-null handle returned by `GetProcessHeap`
+ heap
+ }
+}
+
+// Get a non-null handle to the default heap of the current process.
+// SAFETY: `HEAP` must have been successfully initialized.
+#[inline]
+unsafe fn get_process_heap() -> c::HANDLE {
+ HEAP.load(Ordering::Acquire)
+}
+
+// Header containing a pointer to the start of an allocated block.
+// SAFETY: Size and alignment must be <= `MIN_ALIGN`.
+#[repr(C)]
+struct Header(*mut u8);
+
+// Allocate a block of optionally zeroed memory for a given `layout`.
+// SAFETY: Returns a pointer satisfying the guarantees of `System` about allocated pointers,
+// or null if the operation fails. If this returns non-null `HEAP` will have been successfully
+// initialized.
+#[inline]
+unsafe fn allocate(layout: Layout, zeroed: bool) -> *mut u8 {
+ let heap = init_or_get_process_heap();
+ if heap.is_null() {
+ // Allocation has failed, could not get the current process heap.
+ return ptr::null_mut();
+ }
+
+ // Allocated memory will be either zeroed or uninitialized.
+ let flags = if zeroed { HEAP_ZERO_MEMORY } else { 0 };
+
+ if layout.align() <= MIN_ALIGN {
+ // SAFETY: `heap` is a non-null handle returned by `GetProcessHeap`.
+ // The returned pointer points to the start of an allocated block.
+ unsafe { HeapAlloc(heap, flags, layout.size()) as *mut u8 }
+ } else {
+ // Allocate extra padding in order to be able to satisfy the alignment.
+ let total = layout.align() + layout.size();
+
+ // SAFETY: `heap` is a non-null handle returned by `GetProcessHeap`.
+ let ptr = unsafe { HeapAlloc(heap, flags, total) as *mut u8 };
+ if ptr.is_null() {
+ // Allocation has failed.
+ return ptr::null_mut();
+ }
+
+ // Create a correctly aligned pointer offset from the start of the allocated block,
+ // and write a header before it.
+
+ let offset = layout.align() - (ptr.addr() & (layout.align() - 1));
+ // SAFETY: `MIN_ALIGN` <= `offset` <= `layout.align()` and the size of the allocated
+ // block is `layout.align() + layout.size()`. `aligned` will thus be a correctly aligned
+ // pointer inside the allocated block with at least `layout.size()` bytes after it and at
+ // least `MIN_ALIGN` bytes of padding before it.
+ let aligned = unsafe { ptr.add(offset) };
+ // SAFETY: Because the size and alignment of a header is <= `MIN_ALIGN` and `aligned`
+ // is aligned to at least `MIN_ALIGN` and has at least `MIN_ALIGN` bytes of padding before
+ // it, it is safe to write a header directly before it.
+ unsafe { ptr::write((aligned as *mut Header).offset(-1), Header(ptr)) };
+
+ // SAFETY: The returned pointer does not point to the to the start of an allocated block,
+ // but there is a header readable directly before it containing the location of the start
+ // of the block.
+ aligned
+ }
+}
+
+// All pointers returned by this allocator have, in addition to the guarantees of `GlobalAlloc`, the
+// following properties:
+//
+// If the pointer was allocated or reallocated with a `layout` specifying an alignment <= `MIN_ALIGN`
+// the pointer will be aligned to at least `MIN_ALIGN` and point to the start of the allocated block.
+//
+// If the pointer was allocated or reallocated with a `layout` specifying an alignment > `MIN_ALIGN`
+// the pointer will be aligned to the specified alignment and not point to the start of the allocated block.
+// Instead there will be a header readable directly before the returned pointer, containing the actual
+// location of the start of the block.
+#[stable(feature = "alloc_system_type", since = "1.28.0")]
+unsafe impl GlobalAlloc for System {
+ #[inline]
+ unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
+ // SAFETY: Pointers returned by `allocate` satisfy the guarantees of `System`
+ let zeroed = false;
+ unsafe { allocate(layout, zeroed) }
+ }
+
+ #[inline]
+ unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
+ // SAFETY: Pointers returned by `allocate` satisfy the guarantees of `System`
+ let zeroed = true;
+ unsafe { allocate(layout, zeroed) }
+ }
+
+ #[inline]
+ unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
+ let block = {
+ if layout.align() <= MIN_ALIGN {
+ ptr
+ } else {
+ // The location of the start of the block is stored in the padding before `ptr`.
+
+ // SAFETY: Because of the contract of `System`, `ptr` is guaranteed to be non-null
+ // and have a header readable directly before it.
+ unsafe { ptr::read((ptr as *mut Header).offset(-1)).0 }
+ }
+ };
+
+ // SAFETY: because `ptr` has been successfully allocated with this allocator,
+ // `HEAP` must have been successfully initialized.
+ let heap = unsafe { get_process_heap() };
+
+ // SAFETY: `heap` is a non-null handle returned by `GetProcessHeap`,
+ // `block` is a pointer to the start of an allocated block.
+ unsafe { HeapFree(heap, 0, block as c::LPVOID) };
+ }
+
+ #[inline]
+ unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
+ if layout.align() <= MIN_ALIGN {
+ // SAFETY: because `ptr` has been successfully allocated with this allocator,
+ // `HEAP` must have been successfully initialized.
+ let heap = unsafe { get_process_heap() };
+
+ // SAFETY: `heap` is a non-null handle returned by `GetProcessHeap`,
+ // `ptr` is a pointer to the start of an allocated block.
+ // The returned pointer points to the start of an allocated block.
+ unsafe { HeapReAlloc(heap, 0, ptr as c::LPVOID, new_size) as *mut u8 }
+ } else {
+ // SAFETY: `realloc_fallback` is implemented using `dealloc` and `alloc`, which will
+ // correctly handle `ptr` and return a pointer satisfying the guarantees of `System`
+ unsafe { realloc_fallback(self, ptr, layout, new_size) }
+ }
+ }
+}
diff --git a/library/std/src/sys/windows/alloc/tests.rs b/library/std/src/sys/windows/alloc/tests.rs
new file mode 100644
index 000000000..674a3e1d9
--- /dev/null
+++ b/library/std/src/sys/windows/alloc/tests.rs
@@ -0,0 +1,9 @@
+use super::{Header, MIN_ALIGN};
+use crate::mem;
+
+#[test]
+fn alloc_header() {
+ // Header must fit in the padding before an aligned pointer
+ assert!(mem::size_of::<Header>() <= MIN_ALIGN);
+ assert!(mem::align_of::<Header>() <= MIN_ALIGN);
+}
diff --git a/library/std/src/sys/windows/args.rs b/library/std/src/sys/windows/args.rs
new file mode 100644
index 000000000..01f262982
--- /dev/null
+++ b/library/std/src/sys/windows/args.rs
@@ -0,0 +1,406 @@
+//! The Windows command line is just a string
+//! <https://docs.microsoft.com/en-us/archive/blogs/larryosterman/the-windows-command-line-is-just-a-string>
+//!
+//! This module implements the parsing necessary to turn that string into a list of arguments.
+
+#[cfg(test)]
+mod tests;
+
+use crate::ffi::OsString;
+use crate::fmt;
+use crate::io;
+use crate::marker::PhantomData;
+use crate::num::NonZeroU16;
+use crate::os::windows::prelude::*;
+use crate::path::PathBuf;
+use crate::ptr::NonNull;
+use crate::sys::c;
+use crate::sys::process::ensure_no_nuls;
+use crate::sys::windows::os::current_exe;
+use crate::vec;
+
+use core::iter;
+
+/// This is the const equivalent to `NonZeroU16::new(n).unwrap()`
+///
+/// FIXME: This can be removed once `Option::unwrap` is stably const.
+/// See the `const_option` feature (#67441).
+const fn non_zero_u16(n: u16) -> NonZeroU16 {
+ match NonZeroU16::new(n) {
+ Some(n) => n,
+ None => panic!("called `unwrap` on a `None` value"),
+ }
+}
+
+pub fn args() -> Args {
+ // SAFETY: `GetCommandLineW` returns a pointer to a null terminated UTF-16
+ // string so it's safe for `WStrUnits` to use.
+ unsafe {
+ let lp_cmd_line = c::GetCommandLineW();
+ let parsed_args_list = parse_lp_cmd_line(WStrUnits::new(lp_cmd_line), || {
+ current_exe().map(PathBuf::into_os_string).unwrap_or_else(|_| OsString::new())
+ });
+
+ Args { parsed_args_list: parsed_args_list.into_iter() }
+ }
+}
+
+/// Implements the Windows command-line argument parsing algorithm.
+///
+/// Microsoft's documentation for the Windows CLI argument format can be found at
+/// <https://docs.microsoft.com/en-us/cpp/cpp/main-function-command-line-args?view=msvc-160#parsing-c-command-line-arguments>
+///
+/// A more in-depth explanation is here:
+/// <https://daviddeley.com/autohotkey/parameters/parameters.htm#WIN>
+///
+/// Windows includes a function to do command line parsing in shell32.dll.
+/// However, this is not used for two reasons:
+///
+/// 1. Linking with that DLL causes the process to be registered as a GUI application.
+/// GUI applications add a bunch of overhead, even if no windows are drawn. See
+/// <https://randomascii.wordpress.com/2018/12/03/a-not-called-function-can-cause-a-5x-slowdown/>.
+///
+/// 2. It does not follow the modern C/C++ argv rules outlined in the first two links above.
+///
+/// This function was tested for equivalence to the C/C++ parsing rules using an
+/// extensive test suite available at
+/// <https://github.com/ChrisDenton/winarg/tree/std>.
+fn parse_lp_cmd_line<'a, F: Fn() -> OsString>(
+ lp_cmd_line: Option<WStrUnits<'a>>,
+ exe_name: F,
+) -> Vec<OsString> {
+ const BACKSLASH: NonZeroU16 = non_zero_u16(b'\\' as u16);
+ const QUOTE: NonZeroU16 = non_zero_u16(b'"' as u16);
+ const TAB: NonZeroU16 = non_zero_u16(b'\t' as u16);
+ const SPACE: NonZeroU16 = non_zero_u16(b' ' as u16);
+
+ let mut ret_val = Vec::new();
+ // If the cmd line pointer is null or it points to an empty string then
+ // return the name of the executable as argv[0].
+ if lp_cmd_line.as_ref().and_then(|cmd| cmd.peek()).is_none() {
+ ret_val.push(exe_name());
+ return ret_val;
+ }
+ let mut code_units = lp_cmd_line.unwrap();
+
+ // The executable name at the beginning is special.
+ let mut in_quotes = false;
+ let mut cur = Vec::new();
+ for w in &mut code_units {
+ match w {
+ // A quote mark always toggles `in_quotes` no matter what because
+ // there are no escape characters when parsing the executable name.
+ QUOTE => in_quotes = !in_quotes,
+ // If not `in_quotes` then whitespace ends argv[0].
+ SPACE | TAB if !in_quotes => break,
+ // In all other cases the code unit is taken literally.
+ _ => cur.push(w.get()),
+ }
+ }
+ // Skip whitespace.
+ code_units.advance_while(|w| w == SPACE || w == TAB);
+ ret_val.push(OsString::from_wide(&cur));
+
+ // Parse the arguments according to these rules:
+ // * All code units are taken literally except space, tab, quote and backslash.
+ // * When not `in_quotes`, space and tab separate arguments. Consecutive spaces and tabs are
+ // treated as a single separator.
+ // * A space or tab `in_quotes` is taken literally.
+ // * A quote toggles `in_quotes` mode unless it's escaped. An escaped quote is taken literally.
+ // * A quote can be escaped if preceded by an odd number of backslashes.
+ // * If any number of backslashes is immediately followed by a quote then the number of
+ // backslashes is halved (rounding down).
+ // * Backslashes not followed by a quote are all taken literally.
+ // * If `in_quotes` then a quote can also be escaped using another quote
+ // (i.e. two consecutive quotes become one literal quote).
+ let mut cur = Vec::new();
+ let mut in_quotes = false;
+ while let Some(w) = code_units.next() {
+ match w {
+ // If not `in_quotes`, a space or tab ends the argument.
+ SPACE | TAB if !in_quotes => {
+ ret_val.push(OsString::from_wide(&cur[..]));
+ cur.truncate(0);
+
+ // Skip whitespace.
+ code_units.advance_while(|w| w == SPACE || w == TAB);
+ }
+ // Backslashes can escape quotes or backslashes but only if consecutive backslashes are followed by a quote.
+ BACKSLASH => {
+ let backslash_count = code_units.advance_while(|w| w == BACKSLASH) + 1;
+ if code_units.peek() == Some(QUOTE) {
+ cur.extend(iter::repeat(BACKSLASH.get()).take(backslash_count / 2));
+ // The quote is escaped if there are an odd number of backslashes.
+ if backslash_count % 2 == 1 {
+ code_units.next();
+ cur.push(QUOTE.get());
+ }
+ } else {
+ // If there is no quote on the end then there is no escaping.
+ cur.extend(iter::repeat(BACKSLASH.get()).take(backslash_count));
+ }
+ }
+ // If `in_quotes` and not backslash escaped (see above) then a quote either
+ // unsets `in_quote` or is escaped by another quote.
+ QUOTE if in_quotes => match code_units.peek() {
+ // Two consecutive quotes when `in_quotes` produces one literal quote.
+ Some(QUOTE) => {
+ cur.push(QUOTE.get());
+ code_units.next();
+ }
+ // Otherwise set `in_quotes`.
+ Some(_) => in_quotes = false,
+ // The end of the command line.
+ // Push `cur` even if empty, which we do by breaking while `in_quotes` is still set.
+ None => break,
+ },
+ // If not `in_quotes` and not BACKSLASH escaped (see above) then a quote sets `in_quote`.
+ QUOTE => in_quotes = true,
+ // Everything else is always taken literally.
+ _ => cur.push(w.get()),
+ }
+ }
+ // Push the final argument, if any.
+ if !cur.is_empty() || in_quotes {
+ ret_val.push(OsString::from_wide(&cur[..]));
+ }
+ ret_val
+}
+
+pub struct Args {
+ parsed_args_list: vec::IntoIter<OsString>,
+}
+
+impl fmt::Debug for Args {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ self.parsed_args_list.as_slice().fmt(f)
+ }
+}
+
+impl Iterator for Args {
+ type Item = OsString;
+ fn next(&mut self) -> Option<OsString> {
+ self.parsed_args_list.next()
+ }
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ self.parsed_args_list.size_hint()
+ }
+}
+
+impl DoubleEndedIterator for Args {
+ fn next_back(&mut self) -> Option<OsString> {
+ self.parsed_args_list.next_back()
+ }
+}
+
+impl ExactSizeIterator for Args {
+ fn len(&self) -> usize {
+ self.parsed_args_list.len()
+ }
+}
+
+/// A safe iterator over a LPWSTR
+/// (aka a pointer to a series of UTF-16 code units terminated by a NULL).
+struct WStrUnits<'a> {
+ // The pointer must never be null...
+ lpwstr: NonNull<u16>,
+ // ...and the memory it points to must be valid for this lifetime.
+ lifetime: PhantomData<&'a [u16]>,
+}
+impl WStrUnits<'_> {
+ /// Create the iterator. Returns `None` if `lpwstr` is null.
+ ///
+ /// SAFETY: `lpwstr` must point to a null-terminated wide string that lives
+ /// at least as long as the lifetime of this struct.
+ unsafe fn new(lpwstr: *const u16) -> Option<Self> {
+ Some(Self { lpwstr: NonNull::new(lpwstr as _)?, lifetime: PhantomData })
+ }
+ fn peek(&self) -> Option<NonZeroU16> {
+ // SAFETY: It's always safe to read the current item because we don't
+ // ever move out of the array's bounds.
+ unsafe { NonZeroU16::new(*self.lpwstr.as_ptr()) }
+ }
+ /// Advance the iterator while `predicate` returns true.
+ /// Returns the number of items it advanced by.
+ fn advance_while<P: FnMut(NonZeroU16) -> bool>(&mut self, mut predicate: P) -> usize {
+ let mut counter = 0;
+ while let Some(w) = self.peek() {
+ if !predicate(w) {
+ break;
+ }
+ counter += 1;
+ self.next();
+ }
+ counter
+ }
+}
+impl Iterator for WStrUnits<'_> {
+ // This can never return zero as that marks the end of the string.
+ type Item = NonZeroU16;
+ fn next(&mut self) -> Option<NonZeroU16> {
+ // SAFETY: If NULL is reached we immediately return.
+ // Therefore it's safe to advance the pointer after that.
+ unsafe {
+ let next = self.peek()?;
+ self.lpwstr = NonNull::new_unchecked(self.lpwstr.as_ptr().add(1));
+ Some(next)
+ }
+ }
+}
+
+#[derive(Debug)]
+pub(crate) enum Arg {
+ /// Add quotes (if needed)
+ Regular(OsString),
+ /// Append raw string without quoting
+ Raw(OsString),
+}
+
+enum Quote {
+ // Every arg is quoted
+ Always,
+ // Whitespace and empty args are quoted
+ Auto,
+ // Arg appended without any changes (#29494)
+ Never,
+}
+
+pub(crate) fn append_arg(cmd: &mut Vec<u16>, arg: &Arg, force_quotes: bool) -> io::Result<()> {
+ let (arg, quote) = match arg {
+ Arg::Regular(arg) => (arg, if force_quotes { Quote::Always } else { Quote::Auto }),
+ Arg::Raw(arg) => (arg, Quote::Never),
+ };
+
+ // If an argument has 0 characters then we need to quote it to ensure
+ // that it actually gets passed through on the command line or otherwise
+ // it will be dropped entirely when parsed on the other end.
+ ensure_no_nuls(arg)?;
+ let arg_bytes = arg.bytes();
+ let (quote, escape) = match quote {
+ Quote::Always => (true, true),
+ Quote::Auto => {
+ (arg_bytes.iter().any(|c| *c == b' ' || *c == b'\t') || arg_bytes.is_empty(), true)
+ }
+ Quote::Never => (false, false),
+ };
+ if quote {
+ cmd.push('"' as u16);
+ }
+
+ let mut backslashes: usize = 0;
+ for x in arg.encode_wide() {
+ if escape {
+ if x == '\\' as u16 {
+ backslashes += 1;
+ } else {
+ if x == '"' as u16 {
+ // Add n+1 backslashes to total 2n+1 before internal '"'.
+ cmd.extend((0..=backslashes).map(|_| '\\' as u16));
+ }
+ backslashes = 0;
+ }
+ }
+ cmd.push(x);
+ }
+
+ if quote {
+ // Add n backslashes to total 2n before ending '"'.
+ cmd.extend((0..backslashes).map(|_| '\\' as u16));
+ cmd.push('"' as u16);
+ }
+ Ok(())
+}
+
+pub(crate) fn make_bat_command_line(
+ script: &[u16],
+ args: &[Arg],
+ force_quotes: bool,
+) -> io::Result<Vec<u16>> {
+ // Set the start of the command line to `cmd.exe /c "`
+ // It is necessary to surround the command in an extra pair of quotes,
+ // hence the trailing quote here. It will be closed after all arguments
+ // have been added.
+ let mut cmd: Vec<u16> = "cmd.exe /c \"".encode_utf16().collect();
+
+ // Push the script name surrounded by its quote pair.
+ cmd.push(b'"' as u16);
+ // Windows file names cannot contain a `"` character or end with `\\`.
+ // If the script name does then return an error.
+ if script.contains(&(b'"' as u16)) || script.last() == Some(&(b'\\' as u16)) {
+ return Err(io::const_io_error!(
+ io::ErrorKind::InvalidInput,
+ "Windows file names may not contain `\"` or end with `\\`"
+ ));
+ }
+ cmd.extend_from_slice(script.strip_suffix(&[0]).unwrap_or(script));
+ cmd.push(b'"' as u16);
+
+ // Append the arguments.
+ // FIXME: This needs tests to ensure that the arguments are properly
+ // reconstructed by the batch script by default.
+ for arg in args {
+ cmd.push(' ' as u16);
+ append_arg(&mut cmd, arg, force_quotes)?;
+ }
+
+ // Close the quote we left opened earlier.
+ cmd.push(b'"' as u16);
+
+ Ok(cmd)
+}
+
+/// Takes a path and tries to return a non-verbatim path.
+///
+/// This is necessary because cmd.exe does not support verbatim paths.
+pub(crate) fn to_user_path(mut path: Vec<u16>) -> io::Result<Vec<u16>> {
+ use crate::ptr;
+ use crate::sys::windows::fill_utf16_buf;
+
+ // UTF-16 encoded code points, used in parsing and building UTF-16 paths.
+ // All of these are in the ASCII range so they can be cast directly to `u16`.
+ const SEP: u16 = b'\\' as _;
+ const QUERY: u16 = b'?' as _;
+ const COLON: u16 = b':' as _;
+ const U: u16 = b'U' as _;
+ const N: u16 = b'N' as _;
+ const C: u16 = b'C' as _;
+
+ // Early return if the path is too long to remove the verbatim prefix.
+ const LEGACY_MAX_PATH: usize = 260;
+ if path.len() > LEGACY_MAX_PATH {
+ return Ok(path);
+ }
+
+ match &path[..] {
+ // `\\?\C:\...` => `C:\...`
+ [SEP, SEP, QUERY, SEP, _, COLON, SEP, ..] => unsafe {
+ let lpfilename = path[4..].as_ptr();
+ fill_utf16_buf(
+ |buffer, size| c::GetFullPathNameW(lpfilename, size, buffer, ptr::null_mut()),
+ |full_path: &[u16]| {
+ if full_path == &path[4..path.len() - 1] { full_path.into() } else { path }
+ },
+ )
+ },
+ // `\\?\UNC\...` => `\\...`
+ [SEP, SEP, QUERY, SEP, U, N, C, SEP, ..] => unsafe {
+ // Change the `C` in `UNC\` to `\` so we can get a slice that starts with `\\`.
+ path[6] = b'\\' as u16;
+ let lpfilename = path[6..].as_ptr();
+ fill_utf16_buf(
+ |buffer, size| c::GetFullPathNameW(lpfilename, size, buffer, ptr::null_mut()),
+ |full_path: &[u16]| {
+ if full_path == &path[6..path.len() - 1] {
+ full_path.into()
+ } else {
+ // Restore the 'C' in "UNC".
+ path[6] = b'C' as u16;
+ path
+ }
+ },
+ )
+ },
+ // For everything else, leave the path unchanged.
+ _ => Ok(path),
+ }
+}
diff --git a/library/std/src/sys/windows/args/tests.rs b/library/std/src/sys/windows/args/tests.rs
new file mode 100644
index 000000000..82c32d08c
--- /dev/null
+++ b/library/std/src/sys/windows/args/tests.rs
@@ -0,0 +1,91 @@
+use crate::ffi::OsString;
+use crate::sys::windows::args::*;
+
+fn chk(string: &str, parts: &[&str]) {
+ let mut wide: Vec<u16> = OsString::from(string).encode_wide().collect();
+ wide.push(0);
+ let parsed =
+ unsafe { parse_lp_cmd_line(WStrUnits::new(wide.as_ptr()), || OsString::from("TEST.EXE")) };
+ let expected: Vec<OsString> = parts.iter().map(|k| OsString::from(k)).collect();
+ assert_eq!(parsed.as_slice(), expected.as_slice(), "{:?}", string);
+}
+
+#[test]
+fn empty() {
+ chk("", &["TEST.EXE"]);
+ chk("\0", &["TEST.EXE"]);
+}
+
+#[test]
+fn single_words() {
+ chk("EXE one_word", &["EXE", "one_word"]);
+ chk("EXE a", &["EXE", "a"]);
+ chk("EXE 😅", &["EXE", "😅"]);
+ chk("EXE 😅🤦", &["EXE", "😅🤦"]);
+}
+
+#[test]
+fn official_examples() {
+ chk(r#"EXE "abc" d e"#, &["EXE", "abc", "d", "e"]);
+ chk(r#"EXE a\\\b d"e f"g h"#, &["EXE", r"a\\\b", "de fg", "h"]);
+ chk(r#"EXE a\\\"b c d"#, &["EXE", r#"a\"b"#, "c", "d"]);
+ chk(r#"EXE a\\\\"b c" d e"#, &["EXE", r"a\\b c", "d", "e"]);
+}
+
+#[test]
+fn whitespace_behavior() {
+ chk(" test", &["", "test"]);
+ chk(" test", &["", "test"]);
+ chk(" test test2", &["", "test", "test2"]);
+ chk(" test test2", &["", "test", "test2"]);
+ chk("test test2 ", &["test", "test2"]);
+ chk("test test2 ", &["test", "test2"]);
+ chk("test ", &["test"]);
+}
+
+#[test]
+fn genius_quotes() {
+ chk(r#"EXE "" """#, &["EXE", "", ""]);
+ chk(r#"EXE "" """"#, &["EXE", "", r#"""#]);
+ chk(
+ r#"EXE "this is """all""" in the same argument""#,
+ &["EXE", r#"this is "all" in the same argument"#],
+ );
+ chk(r#"EXE "a"""#, &["EXE", r#"a""#]);
+ chk(r#"EXE "a"" a"#, &["EXE", r#"a" a"#]);
+ // quotes cannot be escaped in command names
+ chk(r#""EXE" check"#, &["EXE", "check"]);
+ chk(r#""EXE check""#, &["EXE check"]);
+ chk(r#""EXE """for""" check"#, &["EXE for check"]);
+ chk(r#""EXE \"for\" check"#, &[r"EXE \for\ check"]);
+ chk(r#""EXE \" for \" check"#, &[r"EXE \", "for", r#"""#, "check"]);
+ chk(r#"E"X"E test"#, &["EXE", "test"]);
+ chk(r#"EX""E test"#, &["EXE", "test"]);
+}
+
+// from https://daviddeley.com/autohotkey/parameters/parameters.htm#WINCRULESEX
+#[test]
+fn post_2008() {
+ chk("EXE CallMeIshmael", &["EXE", "CallMeIshmael"]);
+ chk(r#"EXE "Call Me Ishmael""#, &["EXE", "Call Me Ishmael"]);
+ chk(r#"EXE Cal"l Me I"shmael"#, &["EXE", "Call Me Ishmael"]);
+ chk(r#"EXE CallMe\"Ishmael"#, &["EXE", r#"CallMe"Ishmael"#]);
+ chk(r#"EXE "CallMe\"Ishmael""#, &["EXE", r#"CallMe"Ishmael"#]);
+ chk(r#"EXE "Call Me Ishmael\\""#, &["EXE", r"Call Me Ishmael\"]);
+ chk(r#"EXE "CallMe\\\"Ishmael""#, &["EXE", r#"CallMe\"Ishmael"#]);
+ chk(r#"EXE a\\\b"#, &["EXE", r"a\\\b"]);
+ chk(r#"EXE "a\\\b""#, &["EXE", r"a\\\b"]);
+ chk(r#"EXE "\"Call Me Ishmael\"""#, &["EXE", r#""Call Me Ishmael""#]);
+ chk(r#"EXE "C:\TEST A\\""#, &["EXE", r"C:\TEST A\"]);
+ chk(r#"EXE "\"C:\TEST A\\\"""#, &["EXE", r#""C:\TEST A\""#]);
+ chk(r#"EXE "a b c" d e"#, &["EXE", "a b c", "d", "e"]);
+ chk(r#"EXE "ab\"c" "\\" d"#, &["EXE", r#"ab"c"#, r"\", "d"]);
+ chk(r#"EXE a\\\b d"e f"g h"#, &["EXE", r"a\\\b", "de fg", "h"]);
+ chk(r#"EXE a\\\"b c d"#, &["EXE", r#"a\"b"#, "c", "d"]);
+ chk(r#"EXE a\\\\"b c" d e"#, &["EXE", r"a\\b c", "d", "e"]);
+ // Double Double Quotes
+ chk(r#"EXE "a b c"""#, &["EXE", r#"a b c""#]);
+ chk(r#"EXE """CallMeIshmael""" b c"#, &["EXE", r#""CallMeIshmael""#, "b", "c"]);
+ chk(r#"EXE """Call Me Ishmael""""#, &["EXE", r#""Call Me Ishmael""#]);
+ chk(r#"EXE """"Call Me Ishmael"" b c"#, &["EXE", r#""Call"#, "Me", "Ishmael", "b", "c"]);
+}
diff --git a/library/std/src/sys/windows/c.rs b/library/std/src/sys/windows/c.rs
new file mode 100644
index 000000000..478068c73
--- /dev/null
+++ b/library/std/src/sys/windows/c.rs
@@ -0,0 +1,1340 @@
+//! C definitions used by libnative that don't belong in liblibc
+
+#![allow(nonstandard_style)]
+#![cfg_attr(test, allow(dead_code))]
+#![unstable(issue = "none", feature = "windows_c")]
+
+use crate::ffi::CStr;
+use crate::mem;
+use crate::os::raw::{c_char, c_int, c_long, c_longlong, c_uint, c_ulong, c_ushort};
+use crate::os::windows::io::{BorrowedHandle, HandleOrInvalid, HandleOrNull};
+use crate::ptr;
+use core::ffi::NonZero_c_ulong;
+
+use libc::{c_void, size_t, wchar_t};
+
+#[path = "c/errors.rs"] // c.rs is included from two places so we need to specify this
+mod errors;
+pub use errors::*;
+
+pub use self::EXCEPTION_DISPOSITION::*;
+pub use self::FILE_INFO_BY_HANDLE_CLASS::*;
+
+pub type DWORD_PTR = ULONG_PTR;
+pub type DWORD = c_ulong;
+pub type NonZeroDWORD = NonZero_c_ulong;
+pub type HANDLE = LPVOID;
+pub type HINSTANCE = HANDLE;
+pub type HMODULE = HINSTANCE;
+pub type HRESULT = LONG;
+pub type BOOL = c_int;
+pub type BYTE = u8;
+pub type BOOLEAN = BYTE;
+pub type GROUP = c_uint;
+pub type LARGE_INTEGER = c_longlong;
+pub type LONG = c_long;
+pub type UINT = c_uint;
+pub type WCHAR = u16;
+pub type USHORT = c_ushort;
+pub type SIZE_T = usize;
+pub type WORD = u16;
+pub type CHAR = c_char;
+pub type CCHAR = c_char;
+pub type ULONG_PTR = usize;
+pub type ULONG = c_ulong;
+pub type NTSTATUS = LONG;
+pub type ACCESS_MASK = DWORD;
+
+pub type LPBOOL = *mut BOOL;
+pub type LPBYTE = *mut BYTE;
+pub type LPCSTR = *const CHAR;
+pub type LPCWSTR = *const WCHAR;
+pub type LPDWORD = *mut DWORD;
+pub type LPHANDLE = *mut HANDLE;
+pub type LPOVERLAPPED = *mut OVERLAPPED;
+pub type LPPROCESS_INFORMATION = *mut PROCESS_INFORMATION;
+pub type LPSECURITY_ATTRIBUTES = *mut SECURITY_ATTRIBUTES;
+pub type LPSTARTUPINFO = *mut STARTUPINFO;
+pub type LPVOID = *mut c_void;
+pub type LPWCH = *mut WCHAR;
+pub type LPWIN32_FIND_DATAW = *mut WIN32_FIND_DATAW;
+pub type LPWSADATA = *mut WSADATA;
+pub type LPWSAPROTOCOL_INFO = *mut WSAPROTOCOL_INFO;
+pub type LPWSTR = *mut WCHAR;
+pub type LPFILETIME = *mut FILETIME;
+pub type LPSYSTEM_INFO = *mut SYSTEM_INFO;
+pub type LPWSABUF = *mut WSABUF;
+pub type LPWSAOVERLAPPED = *mut c_void;
+pub type LPWSAOVERLAPPED_COMPLETION_ROUTINE = *mut c_void;
+
+pub type PCONDITION_VARIABLE = *mut CONDITION_VARIABLE;
+pub type PLARGE_INTEGER = *mut c_longlong;
+pub type PSRWLOCK = *mut SRWLOCK;
+
+pub type SOCKET = crate::os::windows::raw::SOCKET;
+pub type socklen_t = c_int;
+pub type ADDRESS_FAMILY = USHORT;
+
+pub const TRUE: BOOL = 1;
+pub const FALSE: BOOL = 0;
+
+pub const CSTR_LESS_THAN: c_int = 1;
+pub const CSTR_EQUAL: c_int = 2;
+pub const CSTR_GREATER_THAN: c_int = 3;
+
+pub const FILE_ATTRIBUTE_READONLY: DWORD = 0x1;
+pub const FILE_ATTRIBUTE_DIRECTORY: DWORD = 0x10;
+pub const FILE_ATTRIBUTE_REPARSE_POINT: DWORD = 0x400;
+pub const INVALID_FILE_ATTRIBUTES: DWORD = DWORD::MAX;
+
+pub const FILE_SHARE_DELETE: DWORD = 0x4;
+pub const FILE_SHARE_READ: DWORD = 0x1;
+pub const FILE_SHARE_WRITE: DWORD = 0x2;
+
+pub const FILE_OPEN: ULONG = 0x00000001;
+pub const FILE_OPEN_REPARSE_POINT: ULONG = 0x200000;
+pub const OBJ_DONT_REPARSE: ULONG = 0x1000;
+
+pub const CREATE_ALWAYS: DWORD = 2;
+pub const CREATE_NEW: DWORD = 1;
+pub const OPEN_ALWAYS: DWORD = 4;
+pub const OPEN_EXISTING: DWORD = 3;
+pub const TRUNCATE_EXISTING: DWORD = 5;
+
+pub const FILE_LIST_DIRECTORY: DWORD = 0x1;
+pub const FILE_WRITE_DATA: DWORD = 0x00000002;
+pub const FILE_APPEND_DATA: DWORD = 0x00000004;
+pub const FILE_WRITE_EA: DWORD = 0x00000010;
+pub const FILE_WRITE_ATTRIBUTES: DWORD = 0x00000100;
+pub const DELETE: DWORD = 0x10000;
+pub const READ_CONTROL: DWORD = 0x00020000;
+pub const SYNCHRONIZE: DWORD = 0x00100000;
+pub const GENERIC_READ: DWORD = 0x80000000;
+pub const GENERIC_WRITE: DWORD = 0x40000000;
+pub const STANDARD_RIGHTS_WRITE: DWORD = READ_CONTROL;
+pub const FILE_GENERIC_WRITE: DWORD = STANDARD_RIGHTS_WRITE
+ | FILE_WRITE_DATA
+ | FILE_WRITE_ATTRIBUTES
+ | FILE_WRITE_EA
+ | FILE_APPEND_DATA
+ | SYNCHRONIZE;
+
+pub const FILE_FLAG_OPEN_REPARSE_POINT: DWORD = 0x00200000;
+pub const FILE_FLAG_BACKUP_SEMANTICS: DWORD = 0x02000000;
+pub const SECURITY_SQOS_PRESENT: DWORD = 0x00100000;
+
+pub const FIONBIO: c_ulong = 0x8004667e;
+
+#[repr(C)]
+#[derive(Copy)]
+pub struct WIN32_FIND_DATAW {
+ pub dwFileAttributes: DWORD,
+ pub ftCreationTime: FILETIME,
+ pub ftLastAccessTime: FILETIME,
+ pub ftLastWriteTime: FILETIME,
+ pub nFileSizeHigh: DWORD,
+ pub nFileSizeLow: DWORD,
+ pub dwReserved0: DWORD,
+ pub dwReserved1: DWORD,
+ pub cFileName: [wchar_t; 260], // #define MAX_PATH 260
+ pub cAlternateFileName: [wchar_t; 14],
+}
+impl Clone for WIN32_FIND_DATAW {
+ fn clone(&self) -> Self {
+ *self
+ }
+}
+
+pub const WSA_FLAG_OVERLAPPED: DWORD = 0x01;
+pub const WSA_FLAG_NO_HANDLE_INHERIT: DWORD = 0x80;
+
+pub const WSADESCRIPTION_LEN: usize = 256;
+pub const WSASYS_STATUS_LEN: usize = 128;
+pub const WSAPROTOCOL_LEN: DWORD = 255;
+pub const INVALID_SOCKET: SOCKET = !0;
+
+pub const MAX_PROTOCOL_CHAIN: DWORD = 7;
+
+pub const MAXIMUM_REPARSE_DATA_BUFFER_SIZE: usize = 16 * 1024;
+pub const FSCTL_GET_REPARSE_POINT: DWORD = 0x900a8;
+pub const IO_REPARSE_TAG_SYMLINK: DWORD = 0xa000000c;
+pub const IO_REPARSE_TAG_MOUNT_POINT: DWORD = 0xa0000003;
+pub const SYMLINK_FLAG_RELATIVE: DWORD = 0x00000001;
+pub const FSCTL_SET_REPARSE_POINT: DWORD = 0x900a4;
+
+pub const SYMBOLIC_LINK_FLAG_DIRECTORY: DWORD = 0x1;
+pub const SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE: DWORD = 0x2;
+
+// Note that these are not actually HANDLEs, just values to pass to GetStdHandle
+pub const STD_INPUT_HANDLE: DWORD = -10i32 as DWORD;
+pub const STD_OUTPUT_HANDLE: DWORD = -11i32 as DWORD;
+pub const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD;
+
+pub const PROGRESS_CONTINUE: DWORD = 0;
+
+pub const E_NOTIMPL: HRESULT = 0x80004001u32 as HRESULT;
+
+pub const INVALID_HANDLE_VALUE: HANDLE = ptr::invalid_mut(!0);
+
+pub const FACILITY_NT_BIT: DWORD = 0x1000_0000;
+
+pub const FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000;
+pub const FORMAT_MESSAGE_FROM_HMODULE: DWORD = 0x00000800;
+pub const FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200;
+
+pub const TLS_OUT_OF_INDEXES: DWORD = 0xFFFFFFFF;
+
+pub const DLL_THREAD_DETACH: DWORD = 3;
+pub const DLL_PROCESS_DETACH: DWORD = 0;
+
+pub const INFINITE: DWORD = !0;
+
+pub const DUPLICATE_SAME_ACCESS: DWORD = 0x00000002;
+
+pub const CONDITION_VARIABLE_INIT: CONDITION_VARIABLE = CONDITION_VARIABLE { ptr: ptr::null_mut() };
+pub const SRWLOCK_INIT: SRWLOCK = SRWLOCK { ptr: ptr::null_mut() };
+
+pub const DETACHED_PROCESS: DWORD = 0x00000008;
+pub const CREATE_NEW_PROCESS_GROUP: DWORD = 0x00000200;
+pub const CREATE_UNICODE_ENVIRONMENT: DWORD = 0x00000400;
+pub const STARTF_USESTDHANDLES: DWORD = 0x00000100;
+
+pub const AF_INET: c_int = 2;
+pub const AF_INET6: c_int = 23;
+pub const SD_BOTH: c_int = 2;
+pub const SD_RECEIVE: c_int = 0;
+pub const SD_SEND: c_int = 1;
+pub const SOCK_DGRAM: c_int = 2;
+pub const SOCK_STREAM: c_int = 1;
+pub const SOCKET_ERROR: c_int = -1;
+pub const SOL_SOCKET: c_int = 0xffff;
+pub const SO_LINGER: c_int = 0x0080;
+pub const SO_RCVTIMEO: c_int = 0x1006;
+pub const SO_SNDTIMEO: c_int = 0x1005;
+pub const IPPROTO_IP: c_int = 0;
+pub const IPPROTO_TCP: c_int = 6;
+pub const IPPROTO_IPV6: c_int = 41;
+pub const TCP_NODELAY: c_int = 0x0001;
+pub const IP_TTL: c_int = 4;
+pub const IPV6_V6ONLY: c_int = 27;
+pub const SO_ERROR: c_int = 0x1007;
+pub const SO_BROADCAST: c_int = 0x0020;
+pub const IP_MULTICAST_LOOP: c_int = 11;
+pub const IPV6_MULTICAST_LOOP: c_int = 11;
+pub const IP_MULTICAST_TTL: c_int = 10;
+pub const IP_ADD_MEMBERSHIP: c_int = 12;
+pub const IP_DROP_MEMBERSHIP: c_int = 13;
+pub const IPV6_ADD_MEMBERSHIP: c_int = 12;
+pub const IPV6_DROP_MEMBERSHIP: c_int = 13;
+pub const MSG_PEEK: c_int = 0x2;
+
+#[repr(C)]
+#[derive(Copy, Clone)]
+pub struct linger {
+ pub l_onoff: c_ushort,
+ pub l_linger: c_ushort,
+}
+
+#[repr(C)]
+pub struct ip_mreq {
+ pub imr_multiaddr: in_addr,
+ pub imr_interface: in_addr,
+}
+
+#[repr(C)]
+pub struct ipv6_mreq {
+ pub ipv6mr_multiaddr: in6_addr,
+ pub ipv6mr_interface: c_uint,
+}
+
+pub const VOLUME_NAME_DOS: DWORD = 0x0;
+pub const MOVEFILE_REPLACE_EXISTING: DWORD = 1;
+
+pub const FILE_BEGIN: DWORD = 0;
+pub const FILE_CURRENT: DWORD = 1;
+pub const FILE_END: DWORD = 2;
+
+pub const WAIT_OBJECT_0: DWORD = 0x00000000;
+pub const WAIT_TIMEOUT: DWORD = 258;
+pub const WAIT_FAILED: DWORD = 0xFFFFFFFF;
+
+pub const PIPE_ACCESS_INBOUND: DWORD = 0x00000001;
+pub const PIPE_ACCESS_OUTBOUND: DWORD = 0x00000002;
+pub const FILE_FLAG_FIRST_PIPE_INSTANCE: DWORD = 0x00080000;
+pub const FILE_FLAG_OVERLAPPED: DWORD = 0x40000000;
+pub const PIPE_WAIT: DWORD = 0x00000000;
+pub const PIPE_TYPE_BYTE: DWORD = 0x00000000;
+pub const PIPE_REJECT_REMOTE_CLIENTS: DWORD = 0x00000008;
+pub const PIPE_READMODE_BYTE: DWORD = 0x00000000;
+
+pub const FD_SETSIZE: usize = 64;
+
+pub const STACK_SIZE_PARAM_IS_A_RESERVATION: DWORD = 0x00010000;
+
+pub const STATUS_SUCCESS: NTSTATUS = 0x00000000;
+pub const STATUS_DELETE_PENDING: NTSTATUS = 0xc0000056_u32 as _;
+pub const STATUS_INVALID_PARAMETER: NTSTATUS = 0xc000000d_u32 as _;
+
+pub const STATUS_PENDING: NTSTATUS = 0x103 as _;
+pub const STATUS_END_OF_FILE: NTSTATUS = 0xC0000011_u32 as _;
+pub const STATUS_NOT_IMPLEMENTED: NTSTATUS = 0xC0000002_u32 as _;
+
+// Equivalent to the `NT_SUCCESS` C preprocessor macro.
+// See: https://docs.microsoft.com/en-us/windows-hardware/drivers/kernel/using-ntstatus-values
+pub fn nt_success(status: NTSTATUS) -> bool {
+ status >= 0
+}
+
+pub const BCRYPT_USE_SYSTEM_PREFERRED_RNG: DWORD = 0x00000002;
+
+#[repr(C)]
+pub struct UNICODE_STRING {
+ pub Length: u16,
+ pub MaximumLength: u16,
+ pub Buffer: *mut u16,
+}
+impl UNICODE_STRING {
+ pub fn from_ref(slice: &[u16]) -> Self {
+ let len = slice.len() * mem::size_of::<u16>();
+ Self { Length: len as _, MaximumLength: len as _, Buffer: slice.as_ptr() as _ }
+ }
+}
+#[repr(C)]
+pub struct OBJECT_ATTRIBUTES {
+ pub Length: ULONG,
+ pub RootDirectory: HANDLE,
+ pub ObjectName: *const UNICODE_STRING,
+ pub Attributes: ULONG,
+ pub SecurityDescriptor: *mut c_void,
+ pub SecurityQualityOfService: *mut c_void,
+}
+impl Default for OBJECT_ATTRIBUTES {
+ fn default() -> Self {
+ Self {
+ Length: mem::size_of::<Self>() as _,
+ RootDirectory: ptr::null_mut(),
+ ObjectName: ptr::null_mut(),
+ Attributes: 0,
+ SecurityDescriptor: ptr::null_mut(),
+ SecurityQualityOfService: ptr::null_mut(),
+ }
+ }
+}
+#[repr(C)]
+union IO_STATUS_BLOCK_union {
+ Status: NTSTATUS,
+ Pointer: *mut c_void,
+}
+impl Default for IO_STATUS_BLOCK_union {
+ fn default() -> Self {
+ let mut this = Self { Pointer: ptr::null_mut() };
+ this.Status = STATUS_PENDING;
+ this
+ }
+}
+#[repr(C)]
+#[derive(Default)]
+pub struct IO_STATUS_BLOCK {
+ u: IO_STATUS_BLOCK_union,
+ pub Information: usize,
+}
+impl IO_STATUS_BLOCK {
+ pub fn status(&self) -> NTSTATUS {
+ // SAFETY: If `self.u.Status` was set then this is obviously safe.
+ // If `self.u.Pointer` was set then this is the equivalent to converting
+ // the pointer to an integer, which is also safe.
+ // Currently the only safe way to construct `IO_STATUS_BLOCK` outside of
+ // this module is to call the `default` method, which sets the `Status`.
+ unsafe { self.u.Status }
+ }
+}
+
+pub type LPOVERLAPPED_COMPLETION_ROUTINE = unsafe extern "system" fn(
+ dwErrorCode: DWORD,
+ dwNumberOfBytesTransfered: DWORD,
+ lpOverlapped: *mut OVERLAPPED,
+);
+
+type IO_APC_ROUTINE = unsafe extern "system" fn(
+ ApcContext: *mut c_void,
+ IoStatusBlock: *mut IO_STATUS_BLOCK,
+ Reserved: ULONG,
+);
+
+#[repr(C)]
+#[cfg(not(target_pointer_width = "64"))]
+pub struct WSADATA {
+ pub wVersion: WORD,
+ pub wHighVersion: WORD,
+ pub szDescription: [u8; WSADESCRIPTION_LEN + 1],
+ pub szSystemStatus: [u8; WSASYS_STATUS_LEN + 1],
+ pub iMaxSockets: u16,
+ pub iMaxUdpDg: u16,
+ pub lpVendorInfo: *mut u8,
+}
+#[repr(C)]
+#[cfg(target_pointer_width = "64")]
+pub struct WSADATA {
+ pub wVersion: WORD,
+ pub wHighVersion: WORD,
+ pub iMaxSockets: u16,
+ pub iMaxUdpDg: u16,
+ pub lpVendorInfo: *mut u8,
+ pub szDescription: [u8; WSADESCRIPTION_LEN + 1],
+ pub szSystemStatus: [u8; WSASYS_STATUS_LEN + 1],
+}
+
+#[derive(Copy, Clone)]
+#[repr(C)]
+pub struct WSABUF {
+ pub len: ULONG,
+ pub buf: *mut CHAR,
+}
+
+#[repr(C)]
+pub struct WSAPROTOCOL_INFO {
+ pub dwServiceFlags1: DWORD,
+ pub dwServiceFlags2: DWORD,
+ pub dwServiceFlags3: DWORD,
+ pub dwServiceFlags4: DWORD,
+ pub dwProviderFlags: DWORD,
+ pub ProviderId: GUID,
+ pub dwCatalogEntryId: DWORD,
+ pub ProtocolChain: WSAPROTOCOLCHAIN,
+ pub iVersion: c_int,
+ pub iAddressFamily: c_int,
+ pub iMaxSockAddr: c_int,
+ pub iMinSockAddr: c_int,
+ pub iSocketType: c_int,
+ pub iProtocol: c_int,
+ pub iProtocolMaxOffset: c_int,
+ pub iNetworkByteOrder: c_int,
+ pub iSecurityScheme: c_int,
+ pub dwMessageSize: DWORD,
+ pub dwProviderReserved: DWORD,
+ pub szProtocol: [u16; (WSAPROTOCOL_LEN as usize) + 1],
+}
+
+#[repr(C)]
+#[derive(Copy, Clone)]
+pub struct WIN32_FILE_ATTRIBUTE_DATA {
+ pub dwFileAttributes: DWORD,
+ pub ftCreationTime: FILETIME,
+ pub ftLastAccessTime: FILETIME,
+ pub ftLastWriteTime: FILETIME,
+ pub nFileSizeHigh: DWORD,
+ pub nFileSizeLow: DWORD,
+}
+
+#[repr(C)]
+#[allow(dead_code)] // we only use some variants
+pub enum FILE_INFO_BY_HANDLE_CLASS {
+ FileBasicInfo = 0,
+ FileStandardInfo = 1,
+ FileNameInfo = 2,
+ FileRenameInfo = 3,
+ FileDispositionInfo = 4,
+ FileAllocationInfo = 5,
+ FileEndOfFileInfo = 6,
+ FileStreamInfo = 7,
+ FileCompressionInfo = 8,
+ FileAttributeTagInfo = 9,
+ FileIdBothDirectoryInfo = 10, // 0xA
+ FileIdBothDirectoryRestartInfo = 11, // 0xB
+ FileIoPriorityHintInfo = 12, // 0xC
+ FileRemoteProtocolInfo = 13, // 0xD
+ FileFullDirectoryInfo = 14, // 0xE
+ FileFullDirectoryRestartInfo = 15, // 0xF
+ FileStorageInfo = 16, // 0x10
+ FileAlignmentInfo = 17, // 0x11
+ FileIdInfo = 18, // 0x12
+ FileIdExtdDirectoryInfo = 19, // 0x13
+ FileIdExtdDirectoryRestartInfo = 20, // 0x14
+ FileDispositionInfoEx = 21, // 0x15, Windows 10 version 1607
+ MaximumFileInfoByHandlesClass,
+}
+
+#[repr(C)]
+pub struct FILE_DISPOSITION_INFO {
+ pub DeleteFile: BOOLEAN,
+}
+
+pub const FILE_DISPOSITION_DELETE: DWORD = 0x1;
+pub const FILE_DISPOSITION_POSIX_SEMANTICS: DWORD = 0x2;
+pub const FILE_DISPOSITION_IGNORE_READONLY_ATTRIBUTE: DWORD = 0x10;
+
+#[repr(C)]
+pub struct FILE_DISPOSITION_INFO_EX {
+ pub Flags: DWORD,
+}
+
+#[repr(C)]
+#[derive(Default)]
+pub struct FILE_ID_BOTH_DIR_INFO {
+ pub NextEntryOffset: DWORD,
+ pub FileIndex: DWORD,
+ pub CreationTime: LARGE_INTEGER,
+ pub LastAccessTime: LARGE_INTEGER,
+ pub LastWriteTime: LARGE_INTEGER,
+ pub ChangeTime: LARGE_INTEGER,
+ pub EndOfFile: LARGE_INTEGER,
+ pub AllocationSize: LARGE_INTEGER,
+ pub FileAttributes: DWORD,
+ pub FileNameLength: DWORD,
+ pub EaSize: DWORD,
+ pub ShortNameLength: CCHAR,
+ pub ShortName: [WCHAR; 12],
+ pub FileId: LARGE_INTEGER,
+ pub FileName: [WCHAR; 1],
+}
+#[repr(C)]
+pub struct FILE_BASIC_INFO {
+ pub CreationTime: LARGE_INTEGER,
+ pub LastAccessTime: LARGE_INTEGER,
+ pub LastWriteTime: LARGE_INTEGER,
+ pub ChangeTime: LARGE_INTEGER,
+ pub FileAttributes: DWORD,
+}
+
+#[repr(C)]
+pub struct FILE_END_OF_FILE_INFO {
+ pub EndOfFile: LARGE_INTEGER,
+}
+
+#[repr(C)]
+pub struct REPARSE_DATA_BUFFER {
+ pub ReparseTag: c_uint,
+ pub ReparseDataLength: c_ushort,
+ pub Reserved: c_ushort,
+ pub rest: (),
+}
+
+#[repr(C)]
+pub struct SYMBOLIC_LINK_REPARSE_BUFFER {
+ pub SubstituteNameOffset: c_ushort,
+ pub SubstituteNameLength: c_ushort,
+ pub PrintNameOffset: c_ushort,
+ pub PrintNameLength: c_ushort,
+ pub Flags: c_ulong,
+ pub PathBuffer: WCHAR,
+}
+
+#[repr(C)]
+pub struct MOUNT_POINT_REPARSE_BUFFER {
+ pub SubstituteNameOffset: c_ushort,
+ pub SubstituteNameLength: c_ushort,
+ pub PrintNameOffset: c_ushort,
+ pub PrintNameLength: c_ushort,
+ pub PathBuffer: WCHAR,
+}
+
+pub type LPPROGRESS_ROUTINE = crate::option::Option<
+ unsafe extern "system" fn(
+ TotalFileSize: LARGE_INTEGER,
+ TotalBytesTransferred: LARGE_INTEGER,
+ StreamSize: LARGE_INTEGER,
+ StreamBytesTransferred: LARGE_INTEGER,
+ dwStreamNumber: DWORD,
+ dwCallbackReason: DWORD,
+ hSourceFile: HANDLE,
+ hDestinationFile: HANDLE,
+ lpData: LPVOID,
+ ) -> DWORD,
+>;
+
+#[repr(C)]
+pub struct CONDITION_VARIABLE {
+ pub ptr: LPVOID,
+}
+#[repr(C)]
+pub struct SRWLOCK {
+ pub ptr: LPVOID,
+}
+
+#[repr(C)]
+pub struct REPARSE_MOUNTPOINT_DATA_BUFFER {
+ pub ReparseTag: DWORD,
+ pub ReparseDataLength: DWORD,
+ pub Reserved: WORD,
+ pub ReparseTargetLength: WORD,
+ pub ReparseTargetMaximumLength: WORD,
+ pub Reserved1: WORD,
+ pub ReparseTarget: WCHAR,
+}
+
+#[repr(C)]
+pub struct GUID {
+ pub Data1: DWORD,
+ pub Data2: WORD,
+ pub Data3: WORD,
+ pub Data4: [BYTE; 8],
+}
+
+#[repr(C)]
+pub struct WSAPROTOCOLCHAIN {
+ pub ChainLen: c_int,
+ pub ChainEntries: [DWORD; MAX_PROTOCOL_CHAIN as usize],
+}
+
+#[repr(C)]
+pub struct SECURITY_ATTRIBUTES {
+ pub nLength: DWORD,
+ pub lpSecurityDescriptor: LPVOID,
+ pub bInheritHandle: BOOL,
+}
+
+#[repr(C)]
+pub struct PROCESS_INFORMATION {
+ pub hProcess: HANDLE,
+ pub hThread: HANDLE,
+ pub dwProcessId: DWORD,
+ pub dwThreadId: DWORD,
+}
+
+#[repr(C)]
+pub struct STARTUPINFO {
+ pub cb: DWORD,
+ pub lpReserved: LPWSTR,
+ pub lpDesktop: LPWSTR,
+ pub lpTitle: LPWSTR,
+ pub dwX: DWORD,
+ pub dwY: DWORD,
+ pub dwXSize: DWORD,
+ pub dwYSize: DWORD,
+ pub dwXCountChars: DWORD,
+ pub dwYCountCharts: DWORD,
+ pub dwFillAttribute: DWORD,
+ pub dwFlags: DWORD,
+ pub wShowWindow: WORD,
+ pub cbReserved2: WORD,
+ pub lpReserved2: LPBYTE,
+ pub hStdInput: HANDLE,
+ pub hStdOutput: HANDLE,
+ pub hStdError: HANDLE,
+}
+
+#[repr(C)]
+pub struct SOCKADDR {
+ pub sa_family: ADDRESS_FAMILY,
+ pub sa_data: [CHAR; 14],
+}
+
+#[repr(C)]
+#[derive(Copy, Clone, Debug, Default)]
+pub struct FILETIME {
+ pub dwLowDateTime: DWORD,
+ pub dwHighDateTime: DWORD,
+}
+
+#[repr(C)]
+pub struct SYSTEM_INFO {
+ pub wProcessorArchitecture: WORD,
+ pub wReserved: WORD,
+ pub dwPageSize: DWORD,
+ pub lpMinimumApplicationAddress: LPVOID,
+ pub lpMaximumApplicationAddress: LPVOID,
+ pub dwActiveProcessorMask: DWORD_PTR,
+ pub dwNumberOfProcessors: DWORD,
+ pub dwProcessorType: DWORD,
+ pub dwAllocationGranularity: DWORD,
+ pub wProcessorLevel: WORD,
+ pub wProcessorRevision: WORD,
+}
+
+#[repr(C)]
+pub struct OVERLAPPED {
+ pub Internal: *mut c_ulong,
+ pub InternalHigh: *mut c_ulong,
+ pub Offset: DWORD,
+ pub OffsetHigh: DWORD,
+ pub hEvent: HANDLE,
+}
+
+#[repr(C)]
+#[allow(dead_code)] // we only use some variants
+pub enum ADDRESS_MODE {
+ AddrMode1616,
+ AddrMode1632,
+ AddrModeReal,
+ AddrModeFlat,
+}
+
+#[repr(C)]
+pub struct SOCKADDR_STORAGE_LH {
+ pub ss_family: ADDRESS_FAMILY,
+ pub __ss_pad1: [CHAR; 6],
+ pub __ss_align: i64,
+ pub __ss_pad2: [CHAR; 112],
+}
+
+#[repr(C)]
+pub struct ADDRINFOA {
+ pub ai_flags: c_int,
+ pub ai_family: c_int,
+ pub ai_socktype: c_int,
+ pub ai_protocol: c_int,
+ pub ai_addrlen: size_t,
+ pub ai_canonname: *mut c_char,
+ pub ai_addr: *mut SOCKADDR,
+ pub ai_next: *mut ADDRINFOA,
+}
+
+#[repr(C)]
+#[derive(Copy, Clone)]
+pub struct sockaddr_in {
+ pub sin_family: ADDRESS_FAMILY,
+ pub sin_port: USHORT,
+ pub sin_addr: in_addr,
+ pub sin_zero: [CHAR; 8],
+}
+
+#[repr(C)]
+#[derive(Copy, Clone)]
+pub struct sockaddr_in6 {
+ pub sin6_family: ADDRESS_FAMILY,
+ pub sin6_port: USHORT,
+ pub sin6_flowinfo: c_ulong,
+ pub sin6_addr: in6_addr,
+ pub sin6_scope_id: c_ulong,
+}
+
+#[repr(C)]
+#[derive(Copy, Clone)]
+pub struct in_addr {
+ pub s_addr: u32,
+}
+
+#[repr(C)]
+#[derive(Copy, Clone)]
+pub struct in6_addr {
+ pub s6_addr: [u8; 16],
+}
+
+#[repr(C)]
+#[derive(Copy, Clone)]
+#[allow(dead_code)] // we only use some variants
+pub enum EXCEPTION_DISPOSITION {
+ ExceptionContinueExecution,
+ ExceptionContinueSearch,
+ ExceptionNestedException,
+ ExceptionCollidedUnwind,
+}
+
+#[repr(C)]
+#[derive(Copy)]
+pub struct fd_set {
+ pub fd_count: c_uint,
+ pub fd_array: [SOCKET; FD_SETSIZE],
+}
+
+impl Clone for fd_set {
+ fn clone(&self) -> fd_set {
+ *self
+ }
+}
+
+#[repr(C)]
+#[derive(Copy, Clone)]
+pub struct timeval {
+ pub tv_sec: c_long,
+ pub tv_usec: c_long,
+}
+
+// Desktop specific functions & types
+cfg_if::cfg_if! {
+if #[cfg(not(target_vendor = "uwp"))] {
+ pub const EXCEPTION_CONTINUE_SEARCH: LONG = 0;
+ pub const EXCEPTION_STACK_OVERFLOW: DWORD = 0xc00000fd;
+ pub const EXCEPTION_MAXIMUM_PARAMETERS: usize = 15;
+
+ #[repr(C)]
+ pub struct EXCEPTION_RECORD {
+ pub ExceptionCode: DWORD,
+ pub ExceptionFlags: DWORD,
+ pub ExceptionRecord: *mut EXCEPTION_RECORD,
+ pub ExceptionAddress: LPVOID,
+ pub NumberParameters: DWORD,
+ pub ExceptionInformation: [LPVOID; EXCEPTION_MAXIMUM_PARAMETERS],
+ }
+
+ pub enum CONTEXT {}
+
+ #[repr(C)]
+ pub struct EXCEPTION_POINTERS {
+ pub ExceptionRecord: *mut EXCEPTION_RECORD,
+ pub ContextRecord: *mut CONTEXT,
+ }
+
+ pub type PVECTORED_EXCEPTION_HANDLER =
+ extern "system" fn(ExceptionInfo: *mut EXCEPTION_POINTERS) -> LONG;
+
+ #[repr(C)]
+ #[derive(Copy, Clone)]
+ pub struct CONSOLE_READCONSOLE_CONTROL {
+ pub nLength: ULONG,
+ pub nInitialChars: ULONG,
+ pub dwCtrlWakeupMask: ULONG,
+ pub dwControlKeyState: ULONG,
+ }
+
+ pub type PCONSOLE_READCONSOLE_CONTROL = *mut CONSOLE_READCONSOLE_CONTROL;
+
+ #[repr(C)]
+ pub struct BY_HANDLE_FILE_INFORMATION {
+ pub dwFileAttributes: DWORD,
+ pub ftCreationTime: FILETIME,
+ pub ftLastAccessTime: FILETIME,
+ pub ftLastWriteTime: FILETIME,
+ pub dwVolumeSerialNumber: DWORD,
+ pub nFileSizeHigh: DWORD,
+ pub nFileSizeLow: DWORD,
+ pub nNumberOfLinks: DWORD,
+ pub nFileIndexHigh: DWORD,
+ pub nFileIndexLow: DWORD,
+ }
+
+ pub type LPBY_HANDLE_FILE_INFORMATION = *mut BY_HANDLE_FILE_INFORMATION;
+ pub type LPCVOID = *const c_void;
+
+ pub const HANDLE_FLAG_INHERIT: DWORD = 0x00000001;
+
+ pub const TOKEN_READ: DWORD = 0x20008;
+
+ #[link(name = "advapi32")]
+ extern "system" {
+ // Forbidden when targeting UWP
+ #[link_name = "SystemFunction036"]
+ pub fn RtlGenRandom(RandomBuffer: *mut u8, RandomBufferLength: ULONG) -> BOOLEAN;
+
+ // Allowed but unused by UWP
+ pub fn OpenProcessToken(
+ ProcessHandle: HANDLE,
+ DesiredAccess: DWORD,
+ TokenHandle: *mut HANDLE,
+ ) -> BOOL;
+ }
+
+ #[link(name = "userenv")]
+ extern "system" {
+ // Allowed but unused by UWP
+ pub fn GetUserProfileDirectoryW(
+ hToken: HANDLE,
+ lpProfileDir: LPWSTR,
+ lpcchSize: *mut DWORD,
+ ) -> BOOL;
+ }
+
+ #[link(name = "kernel32")]
+ extern "system" {
+ // Functions forbidden when targeting UWP
+ pub fn ReadConsoleW(
+ hConsoleInput: HANDLE,
+ lpBuffer: LPVOID,
+ nNumberOfCharsToRead: DWORD,
+ lpNumberOfCharsRead: LPDWORD,
+ pInputControl: PCONSOLE_READCONSOLE_CONTROL,
+ ) -> BOOL;
+
+ pub fn WriteConsoleW(
+ hConsoleOutput: HANDLE,
+ lpBuffer: LPCVOID,
+ nNumberOfCharsToWrite: DWORD,
+ lpNumberOfCharsWritten: LPDWORD,
+ lpReserved: LPVOID,
+ ) -> BOOL;
+
+ pub fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: LPDWORD) -> BOOL;
+ // Allowed but unused by UWP
+ pub fn GetFileInformationByHandle(
+ hFile: HANDLE,
+ lpFileInformation: LPBY_HANDLE_FILE_INFORMATION,
+ ) -> BOOL;
+ pub fn SetHandleInformation(hObject: HANDLE, dwMask: DWORD, dwFlags: DWORD) -> BOOL;
+ pub fn AddVectoredExceptionHandler(
+ FirstHandler: ULONG,
+ VectoredHandler: PVECTORED_EXCEPTION_HANDLER,
+ ) -> LPVOID;
+ pub fn CreateHardLinkW(
+ lpSymlinkFileName: LPCWSTR,
+ lpTargetFileName: LPCWSTR,
+ lpSecurityAttributes: LPSECURITY_ATTRIBUTES,
+ ) -> BOOL;
+ pub fn SetThreadStackGuarantee(_size: *mut c_ulong) -> BOOL;
+ pub fn GetWindowsDirectoryW(lpBuffer: LPWSTR, uSize: UINT) -> UINT;
+ }
+}
+}
+
+// UWP specific functions & types
+cfg_if::cfg_if! {
+if #[cfg(target_vendor = "uwp")] {
+ #[repr(C)]
+ pub struct FILE_STANDARD_INFO {
+ pub AllocationSize: LARGE_INTEGER,
+ pub EndOfFile: LARGE_INTEGER,
+ pub NumberOfLinks: DWORD,
+ pub DeletePending: BOOLEAN,
+ pub Directory: BOOLEAN,
+ }
+}
+}
+
+// Shared between Desktop & UWP
+
+#[link(name = "kernel32")]
+extern "system" {
+ pub fn GetCurrentProcessId() -> DWORD;
+
+ pub fn GetSystemDirectoryW(lpBuffer: LPWSTR, uSize: UINT) -> UINT;
+ pub fn RemoveDirectoryW(lpPathName: LPCWSTR) -> BOOL;
+ pub fn SetFileAttributesW(lpFileName: LPCWSTR, dwFileAttributes: DWORD) -> BOOL;
+ pub fn SetFileTime(
+ hFile: BorrowedHandle<'_>,
+ lpCreationTime: Option<&FILETIME>,
+ lpLastAccessTime: Option<&FILETIME>,
+ lpLastWriteTime: Option<&FILETIME>,
+ ) -> BOOL;
+ pub fn SetLastError(dwErrCode: DWORD);
+ pub fn GetCommandLineW() -> LPWSTR;
+ pub fn GetTempPathW(nBufferLength: DWORD, lpBuffer: LPCWSTR) -> DWORD;
+ pub fn GetCurrentProcess() -> HANDLE;
+ pub fn GetCurrentThread() -> HANDLE;
+ pub fn GetStdHandle(which: DWORD) -> HANDLE;
+ pub fn ExitProcess(uExitCode: c_uint) -> !;
+ pub fn DeviceIoControl(
+ hDevice: HANDLE,
+ dwIoControlCode: DWORD,
+ lpInBuffer: LPVOID,
+ nInBufferSize: DWORD,
+ lpOutBuffer: LPVOID,
+ nOutBufferSize: DWORD,
+ lpBytesReturned: LPDWORD,
+ lpOverlapped: LPOVERLAPPED,
+ ) -> BOOL;
+ pub fn CreateThread(
+ lpThreadAttributes: LPSECURITY_ATTRIBUTES,
+ dwStackSize: SIZE_T,
+ lpStartAddress: extern "system" fn(*mut c_void) -> DWORD,
+ lpParameter: LPVOID,
+ dwCreationFlags: DWORD,
+ lpThreadId: LPDWORD,
+ ) -> HandleOrNull;
+ pub fn WaitForSingleObject(hHandle: HANDLE, dwMilliseconds: DWORD) -> DWORD;
+ pub fn SwitchToThread() -> BOOL;
+ pub fn Sleep(dwMilliseconds: DWORD);
+ pub fn SleepEx(dwMilliseconds: DWORD, bAlertable: BOOL) -> DWORD;
+ pub fn GetProcessId(handle: HANDLE) -> DWORD;
+ pub fn CopyFileExW(
+ lpExistingFileName: LPCWSTR,
+ lpNewFileName: LPCWSTR,
+ lpProgressRoutine: LPPROGRESS_ROUTINE,
+ lpData: LPVOID,
+ pbCancel: LPBOOL,
+ dwCopyFlags: DWORD,
+ ) -> BOOL;
+ pub fn FormatMessageW(
+ flags: DWORD,
+ lpSrc: LPVOID,
+ msgId: DWORD,
+ langId: DWORD,
+ buf: LPWSTR,
+ nsize: DWORD,
+ args: *const c_void,
+ ) -> DWORD;
+ pub fn TlsAlloc() -> DWORD;
+ pub fn TlsGetValue(dwTlsIndex: DWORD) -> LPVOID;
+ pub fn TlsSetValue(dwTlsIndex: DWORD, lpTlsvalue: LPVOID) -> BOOL;
+ pub fn GetLastError() -> DWORD;
+ pub fn QueryPerformanceFrequency(lpFrequency: *mut LARGE_INTEGER) -> BOOL;
+ pub fn QueryPerformanceCounter(lpPerformanceCount: *mut LARGE_INTEGER) -> BOOL;
+ pub fn GetExitCodeProcess(hProcess: HANDLE, lpExitCode: LPDWORD) -> BOOL;
+ pub fn TerminateProcess(hProcess: HANDLE, uExitCode: UINT) -> BOOL;
+ pub fn CreateProcessW(
+ lpApplicationName: LPCWSTR,
+ lpCommandLine: LPWSTR,
+ lpProcessAttributes: LPSECURITY_ATTRIBUTES,
+ lpThreadAttributes: LPSECURITY_ATTRIBUTES,
+ bInheritHandles: BOOL,
+ dwCreationFlags: DWORD,
+ lpEnvironment: LPVOID,
+ lpCurrentDirectory: LPCWSTR,
+ lpStartupInfo: LPSTARTUPINFO,
+ lpProcessInformation: LPPROCESS_INFORMATION,
+ ) -> BOOL;
+ pub fn GetEnvironmentVariableW(n: LPCWSTR, v: LPWSTR, nsize: DWORD) -> DWORD;
+ pub fn SetEnvironmentVariableW(n: LPCWSTR, v: LPCWSTR) -> BOOL;
+ pub fn GetEnvironmentStringsW() -> LPWCH;
+ pub fn FreeEnvironmentStringsW(env_ptr: LPWCH) -> BOOL;
+ pub fn GetModuleFileNameW(hModule: HMODULE, lpFilename: LPWSTR, nSize: DWORD) -> DWORD;
+ pub fn CreateDirectoryW(
+ lpPathName: LPCWSTR,
+ lpSecurityAttributes: LPSECURITY_ATTRIBUTES,
+ ) -> BOOL;
+ pub fn DeleteFileW(lpPathName: LPCWSTR) -> BOOL;
+ pub fn GetCurrentDirectoryW(nBufferLength: DWORD, lpBuffer: LPWSTR) -> DWORD;
+ pub fn SetCurrentDirectoryW(lpPathName: LPCWSTR) -> BOOL;
+ pub fn DuplicateHandle(
+ hSourceProcessHandle: HANDLE,
+ hSourceHandle: HANDLE,
+ hTargetProcessHandle: HANDLE,
+ lpTargetHandle: LPHANDLE,
+ dwDesiredAccess: DWORD,
+ bInheritHandle: BOOL,
+ dwOptions: DWORD,
+ ) -> BOOL;
+ pub fn ReadFile(
+ hFile: BorrowedHandle<'_>,
+ lpBuffer: LPVOID,
+ nNumberOfBytesToRead: DWORD,
+ lpNumberOfBytesRead: LPDWORD,
+ lpOverlapped: LPOVERLAPPED,
+ ) -> BOOL;
+ pub fn ReadFileEx(
+ hFile: BorrowedHandle<'_>,
+ lpBuffer: LPVOID,
+ nNumberOfBytesToRead: DWORD,
+ lpOverlapped: LPOVERLAPPED,
+ lpCompletionRoutine: LPOVERLAPPED_COMPLETION_ROUTINE,
+ ) -> BOOL;
+ pub fn WriteFileEx(
+ hFile: BorrowedHandle<'_>,
+ lpBuffer: LPVOID,
+ nNumberOfBytesToWrite: DWORD,
+ lpOverlapped: LPOVERLAPPED,
+ lpCompletionRoutine: LPOVERLAPPED_COMPLETION_ROUTINE,
+ ) -> BOOL;
+ pub fn CloseHandle(hObject: HANDLE) -> BOOL;
+ pub fn MoveFileExW(lpExistingFileName: LPCWSTR, lpNewFileName: LPCWSTR, dwFlags: DWORD)
+ -> BOOL;
+ pub fn SetFilePointerEx(
+ hFile: HANDLE,
+ liDistanceToMove: LARGE_INTEGER,
+ lpNewFilePointer: PLARGE_INTEGER,
+ dwMoveMethod: DWORD,
+ ) -> BOOL;
+ pub fn FlushFileBuffers(hFile: HANDLE) -> BOOL;
+ pub fn CreateFileW(
+ lpFileName: LPCWSTR,
+ dwDesiredAccess: DWORD,
+ dwShareMode: DWORD,
+ lpSecurityAttributes: LPSECURITY_ATTRIBUTES,
+ dwCreationDisposition: DWORD,
+ dwFlagsAndAttributes: DWORD,
+ hTemplateFile: HANDLE,
+ ) -> HandleOrInvalid;
+
+ pub fn FindFirstFileW(fileName: LPCWSTR, findFileData: LPWIN32_FIND_DATAW) -> HANDLE;
+ pub fn FindNextFileW(findFile: HANDLE, findFileData: LPWIN32_FIND_DATAW) -> BOOL;
+ pub fn FindClose(findFile: HANDLE) -> BOOL;
+
+ pub fn GetProcAddress(handle: HMODULE, name: LPCSTR) -> *mut c_void;
+ pub fn GetModuleHandleA(lpModuleName: LPCSTR) -> HMODULE;
+ pub fn GetModuleHandleW(lpModuleName: LPCWSTR) -> HMODULE;
+
+ pub fn GetSystemTimeAsFileTime(lpSystemTimeAsFileTime: LPFILETIME);
+ pub fn GetSystemInfo(lpSystemInfo: LPSYSTEM_INFO);
+
+ pub fn CreateEventW(
+ lpEventAttributes: LPSECURITY_ATTRIBUTES,
+ bManualReset: BOOL,
+ bInitialState: BOOL,
+ lpName: LPCWSTR,
+ ) -> HANDLE;
+ pub fn WaitForMultipleObjects(
+ nCount: DWORD,
+ lpHandles: *const HANDLE,
+ bWaitAll: BOOL,
+ dwMilliseconds: DWORD,
+ ) -> DWORD;
+ pub fn CreateNamedPipeW(
+ lpName: LPCWSTR,
+ dwOpenMode: DWORD,
+ dwPipeMode: DWORD,
+ nMaxInstances: DWORD,
+ nOutBufferSize: DWORD,
+ nInBufferSize: DWORD,
+ nDefaultTimeOut: DWORD,
+ lpSecurityAttributes: LPSECURITY_ATTRIBUTES,
+ ) -> HANDLE;
+ pub fn CancelIo(handle: HANDLE) -> BOOL;
+ pub fn GetOverlappedResult(
+ hFile: HANDLE,
+ lpOverlapped: LPOVERLAPPED,
+ lpNumberOfBytesTransferred: LPDWORD,
+ bWait: BOOL,
+ ) -> BOOL;
+ pub fn CreateSymbolicLinkW(
+ lpSymlinkFileName: LPCWSTR,
+ lpTargetFileName: LPCWSTR,
+ dwFlags: DWORD,
+ ) -> BOOLEAN;
+ pub fn GetFinalPathNameByHandleW(
+ hFile: HANDLE,
+ lpszFilePath: LPCWSTR,
+ cchFilePath: DWORD,
+ dwFlags: DWORD,
+ ) -> DWORD;
+ pub fn GetFileInformationByHandleEx(
+ hFile: HANDLE,
+ fileInfoClass: FILE_INFO_BY_HANDLE_CLASS,
+ lpFileInformation: LPVOID,
+ dwBufferSize: DWORD,
+ ) -> BOOL;
+ pub fn SetFileInformationByHandle(
+ hFile: HANDLE,
+ FileInformationClass: FILE_INFO_BY_HANDLE_CLASS,
+ lpFileInformation: LPVOID,
+ dwBufferSize: DWORD,
+ ) -> BOOL;
+ pub fn SleepConditionVariableSRW(
+ ConditionVariable: PCONDITION_VARIABLE,
+ SRWLock: PSRWLOCK,
+ dwMilliseconds: DWORD,
+ Flags: ULONG,
+ ) -> BOOL;
+
+ pub fn WakeConditionVariable(ConditionVariable: PCONDITION_VARIABLE);
+ pub fn WakeAllConditionVariable(ConditionVariable: PCONDITION_VARIABLE);
+
+ pub fn AcquireSRWLockExclusive(SRWLock: PSRWLOCK);
+ pub fn AcquireSRWLockShared(SRWLock: PSRWLOCK);
+ pub fn ReleaseSRWLockExclusive(SRWLock: PSRWLOCK);
+ pub fn ReleaseSRWLockShared(SRWLock: PSRWLOCK);
+ pub fn TryAcquireSRWLockExclusive(SRWLock: PSRWLOCK) -> BOOLEAN;
+ pub fn TryAcquireSRWLockShared(SRWLock: PSRWLOCK) -> BOOLEAN;
+
+ pub fn CompareStringOrdinal(
+ lpString1: LPCWSTR,
+ cchCount1: c_int,
+ lpString2: LPCWSTR,
+ cchCount2: c_int,
+ bIgnoreCase: BOOL,
+ ) -> c_int;
+ pub fn GetFullPathNameW(
+ lpFileName: LPCWSTR,
+ nBufferLength: DWORD,
+ lpBuffer: LPWSTR,
+ lpFilePart: *mut LPWSTR,
+ ) -> DWORD;
+ pub fn GetFileAttributesW(lpFileName: LPCWSTR) -> DWORD;
+}
+
+#[link(name = "ws2_32")]
+extern "system" {
+ pub fn WSAStartup(wVersionRequested: WORD, lpWSAData: LPWSADATA) -> c_int;
+ pub fn WSACleanup() -> c_int;
+ pub fn WSAGetLastError() -> c_int;
+ pub fn WSADuplicateSocketW(
+ s: SOCKET,
+ dwProcessId: DWORD,
+ lpProtocolInfo: LPWSAPROTOCOL_INFO,
+ ) -> c_int;
+ pub fn WSASend(
+ s: SOCKET,
+ lpBuffers: LPWSABUF,
+ dwBufferCount: DWORD,
+ lpNumberOfBytesSent: LPDWORD,
+ dwFlags: DWORD,
+ lpOverlapped: LPWSAOVERLAPPED,
+ lpCompletionRoutine: LPWSAOVERLAPPED_COMPLETION_ROUTINE,
+ ) -> c_int;
+ pub fn WSARecv(
+ s: SOCKET,
+ lpBuffers: LPWSABUF,
+ dwBufferCount: DWORD,
+ lpNumberOfBytesRecvd: LPDWORD,
+ lpFlags: LPDWORD,
+ lpOverlapped: LPWSAOVERLAPPED,
+ lpCompletionRoutine: LPWSAOVERLAPPED_COMPLETION_ROUTINE,
+ ) -> c_int;
+ pub fn WSASocketW(
+ af: c_int,
+ kind: c_int,
+ protocol: c_int,
+ lpProtocolInfo: LPWSAPROTOCOL_INFO,
+ g: GROUP,
+ dwFlags: DWORD,
+ ) -> SOCKET;
+ pub fn ioctlsocket(s: SOCKET, cmd: c_long, argp: *mut c_ulong) -> c_int;
+ pub fn closesocket(socket: SOCKET) -> c_int;
+ pub fn recv(socket: SOCKET, buf: *mut c_void, len: c_int, flags: c_int) -> c_int;
+ pub fn send(socket: SOCKET, buf: *const c_void, len: c_int, flags: c_int) -> c_int;
+ pub fn recvfrom(
+ socket: SOCKET,
+ buf: *mut c_void,
+ len: c_int,
+ flags: c_int,
+ addr: *mut SOCKADDR,
+ addrlen: *mut c_int,
+ ) -> c_int;
+ pub fn sendto(
+ socket: SOCKET,
+ buf: *const c_void,
+ len: c_int,
+ flags: c_int,
+ addr: *const SOCKADDR,
+ addrlen: c_int,
+ ) -> c_int;
+ pub fn shutdown(socket: SOCKET, how: c_int) -> c_int;
+ pub fn accept(socket: SOCKET, address: *mut SOCKADDR, address_len: *mut c_int) -> SOCKET;
+ pub fn getsockopt(
+ s: SOCKET,
+ level: c_int,
+ optname: c_int,
+ optval: *mut c_char,
+ optlen: *mut c_int,
+ ) -> c_int;
+ pub fn setsockopt(
+ s: SOCKET,
+ level: c_int,
+ optname: c_int,
+ optval: *const c_void,
+ optlen: c_int,
+ ) -> c_int;
+ pub fn getsockname(socket: SOCKET, address: *mut SOCKADDR, address_len: *mut c_int) -> c_int;
+ pub fn getpeername(socket: SOCKET, address: *mut SOCKADDR, address_len: *mut c_int) -> c_int;
+ pub fn bind(socket: SOCKET, address: *const SOCKADDR, address_len: socklen_t) -> c_int;
+ pub fn listen(socket: SOCKET, backlog: c_int) -> c_int;
+ pub fn connect(socket: SOCKET, address: *const SOCKADDR, len: c_int) -> c_int;
+ pub fn getaddrinfo(
+ node: *const c_char,
+ service: *const c_char,
+ hints: *const ADDRINFOA,
+ res: *mut *mut ADDRINFOA,
+ ) -> c_int;
+ pub fn freeaddrinfo(res: *mut ADDRINFOA);
+ pub fn select(
+ nfds: c_int,
+ readfds: *mut fd_set,
+ writefds: *mut fd_set,
+ exceptfds: *mut fd_set,
+ timeout: *const timeval,
+ ) -> c_int;
+}
+
+#[link(name = "bcrypt")]
+extern "system" {
+ // >= Vista / Server 2008
+ // https://docs.microsoft.com/en-us/windows/win32/api/bcrypt/nf-bcrypt-bcryptgenrandom
+ pub fn BCryptGenRandom(
+ hAlgorithm: LPVOID,
+ pBuffer: *mut u8,
+ cbBuffer: ULONG,
+ dwFlags: ULONG,
+ ) -> NTSTATUS;
+}
+
+// Functions that aren't available on every version of Windows that we support,
+// but we still use them and just provide some form of a fallback implementation.
+compat_fn_with_fallback! {
+ pub static KERNEL32: &CStr = ansi_str!("kernel32");
+
+ // >= Win10 1607
+ // https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-setthreaddescription
+ pub fn SetThreadDescription(hThread: HANDLE,
+ lpThreadDescription: LPCWSTR) -> HRESULT {
+ SetLastError(ERROR_CALL_NOT_IMPLEMENTED as DWORD); E_NOTIMPL
+ }
+
+ // >= Win8 / Server 2012
+ // https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimepreciseasfiletime
+ pub fn GetSystemTimePreciseAsFileTime(lpSystemTimeAsFileTime: LPFILETIME)
+ -> () {
+ GetSystemTimeAsFileTime(lpSystemTimeAsFileTime)
+ }
+
+ // >= Win11 / Server 2022
+ // https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-gettemppath2a
+ pub fn GetTempPath2W(nBufferLength: DWORD, lpBuffer: LPCWSTR) -> DWORD {
+ GetTempPathW(nBufferLength, lpBuffer)
+ }
+}
+
+compat_fn_optional! {
+ pub static SYNCH_API: &CStr = ansi_str!("api-ms-win-core-synch-l1-2-0");
+
+ // >= Windows 8 / Server 2012
+ // https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-waitonaddress
+ pub fn WaitOnAddress(
+ Address: LPVOID,
+ CompareAddress: LPVOID,
+ AddressSize: SIZE_T,
+ dwMilliseconds: DWORD
+ ) -> BOOL;
+ pub fn WakeByAddressSingle(Address: LPVOID) -> ();
+}
+
+compat_fn_with_fallback! {
+ pub static NTDLL: &CStr = ansi_str!("ntdll");
+
+ pub fn NtCreateFile(
+ FileHandle: *mut HANDLE,
+ DesiredAccess: ACCESS_MASK,
+ ObjectAttributes: *const OBJECT_ATTRIBUTES,
+ IoStatusBlock: *mut IO_STATUS_BLOCK,
+ AllocationSize: *mut i64,
+ FileAttributes: ULONG,
+ ShareAccess: ULONG,
+ CreateDisposition: ULONG,
+ CreateOptions: ULONG,
+ EaBuffer: *mut c_void,
+ EaLength: ULONG
+ ) -> NTSTATUS {
+ STATUS_NOT_IMPLEMENTED
+ }
+ pub fn NtReadFile(
+ FileHandle: BorrowedHandle<'_>,
+ Event: HANDLE,
+ ApcRoutine: Option<IO_APC_ROUTINE>,
+ ApcContext: *mut c_void,
+ IoStatusBlock: &mut IO_STATUS_BLOCK,
+ Buffer: *mut crate::mem::MaybeUninit<u8>,
+ Length: ULONG,
+ ByteOffset: Option<&LARGE_INTEGER>,
+ Key: Option<&ULONG>
+ ) -> NTSTATUS {
+ STATUS_NOT_IMPLEMENTED
+ }
+ pub fn NtWriteFile(
+ FileHandle: BorrowedHandle<'_>,
+ Event: HANDLE,
+ ApcRoutine: Option<IO_APC_ROUTINE>,
+ ApcContext: *mut c_void,
+ IoStatusBlock: &mut IO_STATUS_BLOCK,
+ Buffer: *const u8,
+ Length: ULONG,
+ ByteOffset: Option<&LARGE_INTEGER>,
+ Key: Option<&ULONG>
+ ) -> NTSTATUS {
+ STATUS_NOT_IMPLEMENTED
+ }
+ pub fn RtlNtStatusToDosError(
+ Status: NTSTATUS
+ ) -> ULONG {
+ Status as ULONG
+ }
+ pub fn NtCreateKeyedEvent(
+ KeyedEventHandle: LPHANDLE,
+ DesiredAccess: ACCESS_MASK,
+ ObjectAttributes: LPVOID,
+ Flags: ULONG
+ ) -> NTSTATUS {
+ panic!("keyed events not available")
+ }
+ pub fn NtReleaseKeyedEvent(
+ EventHandle: HANDLE,
+ Key: LPVOID,
+ Alertable: BOOLEAN,
+ Timeout: PLARGE_INTEGER
+ ) -> NTSTATUS {
+ panic!("keyed events not available")
+ }
+ pub fn NtWaitForKeyedEvent(
+ EventHandle: HANDLE,
+ Key: LPVOID,
+ Alertable: BOOLEAN,
+ Timeout: PLARGE_INTEGER
+ ) -> NTSTATUS {
+ panic!("keyed events not available")
+ }
+}
diff --git a/library/std/src/sys/windows/c/errors.rs b/library/std/src/sys/windows/c/errors.rs
new file mode 100644
index 000000000..23dcc119d
--- /dev/null
+++ b/library/std/src/sys/windows/c/errors.rs
@@ -0,0 +1,1883 @@
+// List of Windows system error codes with descriptions:
+// https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes#system-error-codes
+
+#![allow(dead_code)]
+
+use super::{c_int, DWORD};
+
+pub const ERROR_DIRECTORY_NOT_SUPPORTED: DWORD = 336;
+pub const ERROR_DRIVER_CANCEL_TIMEOUT: DWORD = 594;
+pub const ERROR_DISK_QUOTA_EXCEEDED: DWORD = 1295;
+pub const ERROR_RESOURCE_CALL_TIMED_OUT: DWORD = 5910;
+pub const FRS_ERR_SYSVOL_POPULATE_TIMEOUT: DWORD = 8014;
+pub const DNS_ERROR_RECORD_TIMED_OUT: DWORD = 9705;
+
+// The followiung list was obtained from
+// `/usr/x86_64-w64-mingw32/include/winerror.h`
+// in the Debian package
+// mingw-w64_6.0.0-3_all.deb
+//
+// The header of that file says:
+// * This file has no copyright assigned and is placed in the Public Domain.
+// * This file is part of the mingw-w64 runtime package.
+// * No warranty is given; refer to the file DISCLAIMER.PD within this package.
+//
+// The text here is the result of the following rune:
+// grep -P '#define ERROR' /usr/x86_64-w64-mingw32/include/winerror.h >>library/std/src/sys/windows/c/errors.rs
+// grep -P '#define WSA' /usr/x86_64-w64-mingw32/include/winerror.h >>library/std/src/sys/windows/c/errors.rs
+// and then using some manually-invented but rather obvious editor search-and-replace
+// invocations, plus some straightforward manual fixups, to turn it into Rust syntax
+// and remove all the duplicates from the manual table above.
+
+pub const ERROR_SUCCESS: DWORD = 0;
+pub const ERROR_INVALID_FUNCTION: DWORD = 1;
+pub const ERROR_FILE_NOT_FOUND: DWORD = 2;
+pub const ERROR_PATH_NOT_FOUND: DWORD = 3;
+pub const ERROR_TOO_MANY_OPEN_FILES: DWORD = 4;
+pub const ERROR_ACCESS_DENIED: DWORD = 5;
+pub const ERROR_INVALID_HANDLE: DWORD = 6;
+pub const ERROR_ARENA_TRASHED: DWORD = 7;
+pub const ERROR_NOT_ENOUGH_MEMORY: DWORD = 8;
+pub const ERROR_INVALID_BLOCK: DWORD = 9;
+pub const ERROR_BAD_ENVIRONMENT: DWORD = 10;
+pub const ERROR_BAD_FORMAT: DWORD = 11;
+pub const ERROR_INVALID_ACCESS: DWORD = 12;
+pub const ERROR_INVALID_DATA: DWORD = 13;
+pub const ERROR_OUTOFMEMORY: DWORD = 14;
+pub const ERROR_INVALID_DRIVE: DWORD = 15;
+pub const ERROR_CURRENT_DIRECTORY: DWORD = 16;
+pub const ERROR_NOT_SAME_DEVICE: DWORD = 17;
+pub const ERROR_NO_MORE_FILES: DWORD = 18;
+pub const ERROR_WRITE_PROTECT: DWORD = 19;
+pub const ERROR_BAD_UNIT: DWORD = 20;
+pub const ERROR_NOT_READY: DWORD = 21;
+pub const ERROR_BAD_COMMAND: DWORD = 22;
+pub const ERROR_CRC: DWORD = 23;
+pub const ERROR_BAD_LENGTH: DWORD = 24;
+pub const ERROR_SEEK: DWORD = 25;
+pub const ERROR_NOT_DOS_DISK: DWORD = 26;
+pub const ERROR_SECTOR_NOT_FOUND: DWORD = 27;
+pub const ERROR_OUT_OF_PAPER: DWORD = 28;
+pub const ERROR_WRITE_FAULT: DWORD = 29;
+pub const ERROR_READ_FAULT: DWORD = 30;
+pub const ERROR_GEN_FAILURE: DWORD = 31;
+pub const ERROR_SHARING_VIOLATION: DWORD = 32;
+pub const ERROR_LOCK_VIOLATION: DWORD = 33;
+pub const ERROR_WRONG_DISK: DWORD = 34;
+pub const ERROR_SHARING_BUFFER_EXCEEDED: DWORD = 36;
+pub const ERROR_HANDLE_EOF: DWORD = 38;
+pub const ERROR_HANDLE_DISK_FULL: DWORD = 39;
+pub const ERROR_NOT_SUPPORTED: DWORD = 50;
+pub const ERROR_REM_NOT_LIST: DWORD = 51;
+pub const ERROR_DUP_NAME: DWORD = 52;
+pub const ERROR_BAD_NETPATH: DWORD = 53;
+pub const ERROR_NETWORK_BUSY: DWORD = 54;
+pub const ERROR_DEV_NOT_EXIST: DWORD = 55;
+pub const ERROR_TOO_MANY_CMDS: DWORD = 56;
+pub const ERROR_ADAP_HDW_ERR: DWORD = 57;
+pub const ERROR_BAD_NET_RESP: DWORD = 58;
+pub const ERROR_UNEXP_NET_ERR: DWORD = 59;
+pub const ERROR_BAD_REM_ADAP: DWORD = 60;
+pub const ERROR_PRINTQ_FULL: DWORD = 61;
+pub const ERROR_NO_SPOOL_SPACE: DWORD = 62;
+pub const ERROR_PRINT_CANCELLED: DWORD = 63;
+pub const ERROR_NETNAME_DELETED: DWORD = 64;
+pub const ERROR_NETWORK_ACCESS_DENIED: DWORD = 65;
+pub const ERROR_BAD_DEV_TYPE: DWORD = 66;
+pub const ERROR_BAD_NET_NAME: DWORD = 67;
+pub const ERROR_TOO_MANY_NAMES: DWORD = 68;
+pub const ERROR_TOO_MANY_SESS: DWORD = 69;
+pub const ERROR_SHARING_PAUSED: DWORD = 70;
+pub const ERROR_REQ_NOT_ACCEP: DWORD = 71;
+pub const ERROR_REDIR_PAUSED: DWORD = 72;
+pub const ERROR_FILE_EXISTS: DWORD = 80;
+pub const ERROR_CANNOT_MAKE: DWORD = 82;
+pub const ERROR_FAIL_I24: DWORD = 83;
+pub const ERROR_OUT_OF_STRUCTURES: DWORD = 84;
+pub const ERROR_ALREADY_ASSIGNED: DWORD = 85;
+pub const ERROR_INVALID_PASSWORD: DWORD = 86;
+pub const ERROR_INVALID_PARAMETER: DWORD = 87;
+pub const ERROR_NET_WRITE_FAULT: DWORD = 88;
+pub const ERROR_NO_PROC_SLOTS: DWORD = 89;
+pub const ERROR_TOO_MANY_SEMAPHORES: DWORD = 100;
+pub const ERROR_EXCL_SEM_ALREADY_OWNED: DWORD = 101;
+pub const ERROR_SEM_IS_SET: DWORD = 102;
+pub const ERROR_TOO_MANY_SEM_REQUESTS: DWORD = 103;
+pub const ERROR_INVALID_AT_INTERRUPT_TIME: DWORD = 104;
+pub const ERROR_SEM_OWNER_DIED: DWORD = 105;
+pub const ERROR_SEM_USER_LIMIT: DWORD = 106;
+pub const ERROR_DISK_CHANGE: DWORD = 107;
+pub const ERROR_DRIVE_LOCKED: DWORD = 108;
+pub const ERROR_BROKEN_PIPE: DWORD = 109;
+pub const ERROR_OPEN_FAILED: DWORD = 110;
+pub const ERROR_BUFFER_OVERFLOW: DWORD = 111;
+pub const ERROR_DISK_FULL: DWORD = 112;
+pub const ERROR_NO_MORE_SEARCH_HANDLES: DWORD = 113;
+pub const ERROR_INVALID_TARGET_HANDLE: DWORD = 114;
+pub const ERROR_INVALID_CATEGORY: DWORD = 117;
+pub const ERROR_INVALID_VERIFY_SWITCH: DWORD = 118;
+pub const ERROR_BAD_DRIVER_LEVEL: DWORD = 119;
+pub const ERROR_CALL_NOT_IMPLEMENTED: DWORD = 120;
+pub const ERROR_SEM_TIMEOUT: DWORD = 121;
+pub const ERROR_INSUFFICIENT_BUFFER: DWORD = 122;
+pub const ERROR_INVALID_NAME: DWORD = 123;
+pub const ERROR_INVALID_LEVEL: DWORD = 124;
+pub const ERROR_NO_VOLUME_LABEL: DWORD = 125;
+pub const ERROR_MOD_NOT_FOUND: DWORD = 126;
+pub const ERROR_PROC_NOT_FOUND: DWORD = 127;
+pub const ERROR_WAIT_NO_CHILDREN: DWORD = 128;
+pub const ERROR_CHILD_NOT_COMPLETE: DWORD = 129;
+pub const ERROR_DIRECT_ACCESS_HANDLE: DWORD = 130;
+pub const ERROR_NEGATIVE_SEEK: DWORD = 131;
+pub const ERROR_SEEK_ON_DEVICE: DWORD = 132;
+pub const ERROR_IS_JOIN_TARGET: DWORD = 133;
+pub const ERROR_IS_JOINED: DWORD = 134;
+pub const ERROR_IS_SUBSTED: DWORD = 135;
+pub const ERROR_NOT_JOINED: DWORD = 136;
+pub const ERROR_NOT_SUBSTED: DWORD = 137;
+pub const ERROR_JOIN_TO_JOIN: DWORD = 138;
+pub const ERROR_SUBST_TO_SUBST: DWORD = 139;
+pub const ERROR_JOIN_TO_SUBST: DWORD = 140;
+pub const ERROR_SUBST_TO_JOIN: DWORD = 141;
+pub const ERROR_BUSY_DRIVE: DWORD = 142;
+pub const ERROR_SAME_DRIVE: DWORD = 143;
+pub const ERROR_DIR_NOT_ROOT: DWORD = 144;
+pub const ERROR_DIR_NOT_EMPTY: DWORD = 145;
+pub const ERROR_IS_SUBST_PATH: DWORD = 146;
+pub const ERROR_IS_JOIN_PATH: DWORD = 147;
+pub const ERROR_PATH_BUSY: DWORD = 148;
+pub const ERROR_IS_SUBST_TARGET: DWORD = 149;
+pub const ERROR_SYSTEM_TRACE: DWORD = 150;
+pub const ERROR_INVALID_EVENT_COUNT: DWORD = 151;
+pub const ERROR_TOO_MANY_MUXWAITERS: DWORD = 152;
+pub const ERROR_INVALID_LIST_FORMAT: DWORD = 153;
+pub const ERROR_LABEL_TOO_LONG: DWORD = 154;
+pub const ERROR_TOO_MANY_TCBS: DWORD = 155;
+pub const ERROR_SIGNAL_REFUSED: DWORD = 156;
+pub const ERROR_DISCARDED: DWORD = 157;
+pub const ERROR_NOT_LOCKED: DWORD = 158;
+pub const ERROR_BAD_THREADID_ADDR: DWORD = 159;
+pub const ERROR_BAD_ARGUMENTS: DWORD = 160;
+pub const ERROR_BAD_PATHNAME: DWORD = 161;
+pub const ERROR_SIGNAL_PENDING: DWORD = 162;
+pub const ERROR_MAX_THRDS_REACHED: DWORD = 164;
+pub const ERROR_LOCK_FAILED: DWORD = 167;
+pub const ERROR_BUSY: DWORD = 170;
+pub const ERROR_CANCEL_VIOLATION: DWORD = 173;
+pub const ERROR_ATOMIC_LOCKS_NOT_SUPPORTED: DWORD = 174;
+pub const ERROR_INVALID_SEGMENT_NUMBER: DWORD = 180;
+pub const ERROR_INVALID_ORDINAL: DWORD = 182;
+pub const ERROR_ALREADY_EXISTS: DWORD = 183;
+pub const ERROR_INVALID_FLAG_NUMBER: DWORD = 186;
+pub const ERROR_SEM_NOT_FOUND: DWORD = 187;
+pub const ERROR_INVALID_STARTING_CODESEG: DWORD = 188;
+pub const ERROR_INVALID_STACKSEG: DWORD = 189;
+pub const ERROR_INVALID_MODULETYPE: DWORD = 190;
+pub const ERROR_INVALID_EXE_SIGNATURE: DWORD = 191;
+pub const ERROR_EXE_MARKED_INVALID: DWORD = 192;
+pub const ERROR_BAD_EXE_FORMAT: DWORD = 193;
+pub const ERROR_ITERATED_DATA_EXCEEDS_64k: DWORD = 194;
+pub const ERROR_INVALID_MINALLOCSIZE: DWORD = 195;
+pub const ERROR_DYNLINK_FROM_INVALID_RING: DWORD = 196;
+pub const ERROR_IOPL_NOT_ENABLED: DWORD = 197;
+pub const ERROR_INVALID_SEGDPL: DWORD = 198;
+pub const ERROR_AUTODATASEG_EXCEEDS_64k: DWORD = 199;
+pub const ERROR_RING2SEG_MUST_BE_MOVABLE: DWORD = 200;
+pub const ERROR_RELOC_CHAIN_XEEDS_SEGLIM: DWORD = 201;
+pub const ERROR_INFLOOP_IN_RELOC_CHAIN: DWORD = 202;
+pub const ERROR_ENVVAR_NOT_FOUND: DWORD = 203;
+pub const ERROR_NO_SIGNAL_SENT: DWORD = 205;
+pub const ERROR_FILENAME_EXCED_RANGE: DWORD = 206;
+pub const ERROR_RING2_STACK_IN_USE: DWORD = 207;
+pub const ERROR_META_EXPANSION_TOO_LONG: DWORD = 208;
+pub const ERROR_INVALID_SIGNAL_NUMBER: DWORD = 209;
+pub const ERROR_THREAD_1_INACTIVE: DWORD = 210;
+pub const ERROR_LOCKED: DWORD = 212;
+pub const ERROR_TOO_MANY_MODULES: DWORD = 214;
+pub const ERROR_NESTING_NOT_ALLOWED: DWORD = 215;
+pub const ERROR_EXE_MACHINE_TYPE_MISMATCH: DWORD = 216;
+pub const ERROR_EXE_CANNOT_MODIFY_SIGNED_BINARY: DWORD = 217;
+pub const ERROR_EXE_CANNOT_MODIFY_STRONG_SIGNED_BINARY: DWORD = 218;
+pub const ERROR_FILE_CHECKED_OUT: DWORD = 220;
+pub const ERROR_CHECKOUT_REQUIRED: DWORD = 221;
+pub const ERROR_BAD_FILE_TYPE: DWORD = 222;
+pub const ERROR_FILE_TOO_LARGE: DWORD = 223;
+pub const ERROR_FORMS_AUTH_REQUIRED: DWORD = 224;
+pub const ERROR_PIPE_LOCAL: DWORD = 229;
+pub const ERROR_BAD_PIPE: DWORD = 230;
+pub const ERROR_PIPE_BUSY: DWORD = 231;
+pub const ERROR_NO_DATA: DWORD = 232;
+pub const ERROR_PIPE_NOT_CONNECTED: DWORD = 233;
+pub const ERROR_MORE_DATA: DWORD = 234;
+pub const ERROR_VC_DISCONNECTED: DWORD = 240;
+pub const ERROR_INVALID_EA_NAME: DWORD = 254;
+pub const ERROR_EA_LIST_INCONSISTENT: DWORD = 255;
+pub const ERROR_NO_MORE_ITEMS: DWORD = 259;
+pub const ERROR_CANNOT_COPY: DWORD = 266;
+pub const ERROR_DIRECTORY: DWORD = 267;
+pub const ERROR_EAS_DIDNT_FIT: DWORD = 275;
+pub const ERROR_EA_FILE_CORRUPT: DWORD = 276;
+pub const ERROR_EA_TABLE_FULL: DWORD = 277;
+pub const ERROR_INVALID_EA_HANDLE: DWORD = 278;
+pub const ERROR_EAS_NOT_SUPPORTED: DWORD = 282;
+pub const ERROR_NOT_OWNER: DWORD = 288;
+pub const ERROR_TOO_MANY_POSTS: DWORD = 298;
+pub const ERROR_PARTIAL_COPY: DWORD = 299;
+pub const ERROR_OPLOCK_NOT_GRANTED: DWORD = 300;
+pub const ERROR_INVALID_OPLOCK_PROTOCOL: DWORD = 301;
+pub const ERROR_DISK_TOO_FRAGMENTED: DWORD = 302;
+pub const ERROR_DELETE_PENDING: DWORD = 303;
+pub const ERROR_INVALID_TOKEN: DWORD = 315;
+pub const ERROR_MR_MID_NOT_FOUND: DWORD = 317;
+pub const ERROR_SCOPE_NOT_FOUND: DWORD = 318;
+pub const ERROR_INVALID_ADDRESS: DWORD = 487;
+pub const ERROR_ARITHMETIC_OVERFLOW: DWORD = 534;
+pub const ERROR_PIPE_CONNECTED: DWORD = 535;
+pub const ERROR_PIPE_LISTENING: DWORD = 536;
+pub const ERROR_WAKE_SYSTEM: DWORD = 730;
+pub const ERROR_WAIT_1: DWORD = 731;
+pub const ERROR_WAIT_2: DWORD = 732;
+pub const ERROR_WAIT_3: DWORD = 733;
+pub const ERROR_WAIT_63: DWORD = 734;
+pub const ERROR_ABANDONED_WAIT_0: DWORD = 735;
+pub const ERROR_ABANDONED_WAIT_63: DWORD = 736;
+pub const ERROR_USER_APC: DWORD = 737;
+pub const ERROR_KERNEL_APC: DWORD = 738;
+pub const ERROR_ALERTED: DWORD = 739;
+pub const ERROR_EA_ACCESS_DENIED: DWORD = 994;
+pub const ERROR_OPERATION_ABORTED: DWORD = 995;
+pub const ERROR_IO_INCOMPLETE: DWORD = 996;
+pub const ERROR_IO_PENDING: DWORD = 997;
+pub const ERROR_NOACCESS: DWORD = 998;
+pub const ERROR_SWAPERROR: DWORD = 999;
+pub const ERROR_STACK_OVERFLOW: DWORD = 1001;
+pub const ERROR_INVALID_MESSAGE: DWORD = 1002;
+pub const ERROR_CAN_NOT_COMPLETE: DWORD = 1003;
+pub const ERROR_INVALID_FLAGS: DWORD = 1004;
+pub const ERROR_UNRECOGNIZED_VOLUME: DWORD = 1005;
+pub const ERROR_FILE_INVALID: DWORD = 1006;
+pub const ERROR_FULLSCREEN_MODE: DWORD = 1007;
+pub const ERROR_NO_TOKEN: DWORD = 1008;
+pub const ERROR_BADDB: DWORD = 1009;
+pub const ERROR_BADKEY: DWORD = 1010;
+pub const ERROR_CANTOPEN: DWORD = 1011;
+pub const ERROR_CANTREAD: DWORD = 1012;
+pub const ERROR_CANTWRITE: DWORD = 1013;
+pub const ERROR_REGISTRY_RECOVERED: DWORD = 1014;
+pub const ERROR_REGISTRY_CORRUPT: DWORD = 1015;
+pub const ERROR_REGISTRY_IO_FAILED: DWORD = 1016;
+pub const ERROR_NOT_REGISTRY_FILE: DWORD = 1017;
+pub const ERROR_KEY_DELETED: DWORD = 1018;
+pub const ERROR_NO_LOG_SPACE: DWORD = 1019;
+pub const ERROR_KEY_HAS_CHILDREN: DWORD = 1020;
+pub const ERROR_CHILD_MUST_BE_VOLATILE: DWORD = 1021;
+pub const ERROR_NOTIFY_ENUM_DIR: DWORD = 1022;
+pub const ERROR_DEPENDENT_SERVICES_RUNNING: DWORD = 1051;
+pub const ERROR_INVALID_SERVICE_CONTROL: DWORD = 1052;
+pub const ERROR_SERVICE_REQUEST_TIMEOUT: DWORD = 1053;
+pub const ERROR_SERVICE_NO_THREAD: DWORD = 1054;
+pub const ERROR_SERVICE_DATABASE_LOCKED: DWORD = 1055;
+pub const ERROR_SERVICE_ALREADY_RUNNING: DWORD = 1056;
+pub const ERROR_INVALID_SERVICE_ACCOUNT: DWORD = 1057;
+pub const ERROR_SERVICE_DISABLED: DWORD = 1058;
+pub const ERROR_CIRCULAR_DEPENDENCY: DWORD = 1059;
+pub const ERROR_SERVICE_DOES_NOT_EXIST: DWORD = 1060;
+pub const ERROR_SERVICE_CANNOT_ACCEPT_CTRL: DWORD = 1061;
+pub const ERROR_SERVICE_NOT_ACTIVE: DWORD = 1062;
+pub const ERROR_FAILED_SERVICE_CONTROLLER_CONNECT: DWORD = 1063;
+pub const ERROR_EXCEPTION_IN_SERVICE: DWORD = 1064;
+pub const ERROR_DATABASE_DOES_NOT_EXIST: DWORD = 1065;
+pub const ERROR_SERVICE_SPECIFIC_ERROR: DWORD = 1066;
+pub const ERROR_PROCESS_ABORTED: DWORD = 1067;
+pub const ERROR_SERVICE_DEPENDENCY_FAIL: DWORD = 1068;
+pub const ERROR_SERVICE_LOGON_FAILED: DWORD = 1069;
+pub const ERROR_SERVICE_START_HANG: DWORD = 1070;
+pub const ERROR_INVALID_SERVICE_LOCK: DWORD = 1071;
+pub const ERROR_SERVICE_MARKED_FOR_DELETE: DWORD = 1072;
+pub const ERROR_SERVICE_EXISTS: DWORD = 1073;
+pub const ERROR_ALREADY_RUNNING_LKG: DWORD = 1074;
+pub const ERROR_SERVICE_DEPENDENCY_DELETED: DWORD = 1075;
+pub const ERROR_BOOT_ALREADY_ACCEPTED: DWORD = 1076;
+pub const ERROR_SERVICE_NEVER_STARTED: DWORD = 1077;
+pub const ERROR_DUPLICATE_SERVICE_NAME: DWORD = 1078;
+pub const ERROR_DIFFERENT_SERVICE_ACCOUNT: DWORD = 1079;
+pub const ERROR_CANNOT_DETECT_DRIVER_FAILURE: DWORD = 1080;
+pub const ERROR_CANNOT_DETECT_PROCESS_ABORT: DWORD = 1081;
+pub const ERROR_NO_RECOVERY_PROGRAM: DWORD = 1082;
+pub const ERROR_SERVICE_NOT_IN_EXE: DWORD = 1083;
+pub const ERROR_NOT_SAFEBOOT_SERVICE: DWORD = 1084;
+pub const ERROR_END_OF_MEDIA: DWORD = 1100;
+pub const ERROR_FILEMARK_DETECTED: DWORD = 1101;
+pub const ERROR_BEGINNING_OF_MEDIA: DWORD = 1102;
+pub const ERROR_SETMARK_DETECTED: DWORD = 1103;
+pub const ERROR_NO_DATA_DETECTED: DWORD = 1104;
+pub const ERROR_PARTITION_FAILURE: DWORD = 1105;
+pub const ERROR_INVALID_BLOCK_LENGTH: DWORD = 1106;
+pub const ERROR_DEVICE_NOT_PARTITIONED: DWORD = 1107;
+pub const ERROR_UNABLE_TO_LOCK_MEDIA: DWORD = 1108;
+pub const ERROR_UNABLE_TO_UNLOAD_MEDIA: DWORD = 1109;
+pub const ERROR_MEDIA_CHANGED: DWORD = 1110;
+pub const ERROR_BUS_RESET: DWORD = 1111;
+pub const ERROR_NO_MEDIA_IN_DRIVE: DWORD = 1112;
+pub const ERROR_NO_UNICODE_TRANSLATION: DWORD = 1113;
+pub const ERROR_DLL_INIT_FAILED: DWORD = 1114;
+pub const ERROR_SHUTDOWN_IN_PROGRESS: DWORD = 1115;
+pub const ERROR_NO_SHUTDOWN_IN_PROGRESS: DWORD = 1116;
+pub const ERROR_IO_DEVICE: DWORD = 1117;
+pub const ERROR_SERIAL_NO_DEVICE: DWORD = 1118;
+pub const ERROR_IRQ_BUSY: DWORD = 1119;
+pub const ERROR_MORE_WRITES: DWORD = 1120;
+pub const ERROR_COUNTER_TIMEOUT: DWORD = 1121;
+pub const ERROR_FLOPPY_ID_MARK_NOT_FOUND: DWORD = 1122;
+pub const ERROR_FLOPPY_WRONG_CYLINDER: DWORD = 1123;
+pub const ERROR_FLOPPY_UNKNOWN_ERROR: DWORD = 1124;
+pub const ERROR_FLOPPY_BAD_REGISTERS: DWORD = 1125;
+pub const ERROR_DISK_RECALIBRATE_FAILED: DWORD = 1126;
+pub const ERROR_DISK_OPERATION_FAILED: DWORD = 1127;
+pub const ERROR_DISK_RESET_FAILED: DWORD = 1128;
+pub const ERROR_EOM_OVERFLOW: DWORD = 1129;
+pub const ERROR_NOT_ENOUGH_SERVER_MEMORY: DWORD = 1130;
+pub const ERROR_POSSIBLE_DEADLOCK: DWORD = 1131;
+pub const ERROR_MAPPED_ALIGNMENT: DWORD = 1132;
+pub const ERROR_SET_POWER_STATE_VETOED: DWORD = 1140;
+pub const ERROR_SET_POWER_STATE_FAILED: DWORD = 1141;
+pub const ERROR_TOO_MANY_LINKS: DWORD = 1142;
+pub const ERROR_OLD_WIN_VERSION: DWORD = 1150;
+pub const ERROR_APP_WRONG_OS: DWORD = 1151;
+pub const ERROR_SINGLE_INSTANCE_APP: DWORD = 1152;
+pub const ERROR_RMODE_APP: DWORD = 1153;
+pub const ERROR_INVALID_DLL: DWORD = 1154;
+pub const ERROR_NO_ASSOCIATION: DWORD = 1155;
+pub const ERROR_DDE_FAIL: DWORD = 1156;
+pub const ERROR_DLL_NOT_FOUND: DWORD = 1157;
+pub const ERROR_NO_MORE_USER_HANDLES: DWORD = 1158;
+pub const ERROR_MESSAGE_SYNC_ONLY: DWORD = 1159;
+pub const ERROR_SOURCE_ELEMENT_EMPTY: DWORD = 1160;
+pub const ERROR_DESTINATION_ELEMENT_FULL: DWORD = 1161;
+pub const ERROR_ILLEGAL_ELEMENT_ADDRESS: DWORD = 1162;
+pub const ERROR_MAGAZINE_NOT_PRESENT: DWORD = 1163;
+pub const ERROR_DEVICE_REINITIALIZATION_NEEDED: DWORD = 1164;
+pub const ERROR_DEVICE_REQUIRES_CLEANING: DWORD = 1165;
+pub const ERROR_DEVICE_DOOR_OPEN: DWORD = 1166;
+pub const ERROR_DEVICE_NOT_CONNECTED: DWORD = 1167;
+pub const ERROR_NOT_FOUND: DWORD = 1168;
+pub const ERROR_NO_MATCH: DWORD = 1169;
+pub const ERROR_SET_NOT_FOUND: DWORD = 1170;
+pub const ERROR_POINT_NOT_FOUND: DWORD = 1171;
+pub const ERROR_NO_TRACKING_SERVICE: DWORD = 1172;
+pub const ERROR_NO_VOLUME_ID: DWORD = 1173;
+pub const ERROR_UNABLE_TO_REMOVE_REPLACED: DWORD = 1175;
+pub const ERROR_UNABLE_TO_MOVE_REPLACEMENT: DWORD = 1176;
+pub const ERROR_UNABLE_TO_MOVE_REPLACEMENT_2: DWORD = 1177;
+pub const ERROR_JOURNAL_DELETE_IN_PROGRESS: DWORD = 1178;
+pub const ERROR_JOURNAL_NOT_ACTIVE: DWORD = 1179;
+pub const ERROR_POTENTIAL_FILE_FOUND: DWORD = 1180;
+pub const ERROR_JOURNAL_ENTRY_DELETED: DWORD = 1181;
+pub const ERROR_BAD_DEVICE: DWORD = 1200;
+pub const ERROR_CONNECTION_UNAVAIL: DWORD = 1201;
+pub const ERROR_DEVICE_ALREADY_REMEMBERED: DWORD = 1202;
+pub const ERROR_NO_NET_OR_BAD_PATH: DWORD = 1203;
+pub const ERROR_BAD_PROVIDER: DWORD = 1204;
+pub const ERROR_CANNOT_OPEN_PROFILE: DWORD = 1205;
+pub const ERROR_BAD_PROFILE: DWORD = 1206;
+pub const ERROR_NOT_CONTAINER: DWORD = 1207;
+pub const ERROR_EXTENDED_ERROR: DWORD = 1208;
+pub const ERROR_INVALID_GROUPNAME: DWORD = 1209;
+pub const ERROR_INVALID_COMPUTERNAME: DWORD = 1210;
+pub const ERROR_INVALID_EVENTNAME: DWORD = 1211;
+pub const ERROR_INVALID_DOMAINNAME: DWORD = 1212;
+pub const ERROR_INVALID_SERVICENAME: DWORD = 1213;
+pub const ERROR_INVALID_NETNAME: DWORD = 1214;
+pub const ERROR_INVALID_SHARENAME: DWORD = 1215;
+pub const ERROR_INVALID_PASSWORDNAME: DWORD = 1216;
+pub const ERROR_INVALID_MESSAGENAME: DWORD = 1217;
+pub const ERROR_INVALID_MESSAGEDEST: DWORD = 1218;
+pub const ERROR_SESSION_CREDENTIAL_CONFLICT: DWORD = 1219;
+pub const ERROR_REMOTE_SESSION_LIMIT_EXCEEDED: DWORD = 1220;
+pub const ERROR_DUP_DOMAINNAME: DWORD = 1221;
+pub const ERROR_NO_NETWORK: DWORD = 1222;
+pub const ERROR_CANCELLED: DWORD = 1223;
+pub const ERROR_USER_MAPPED_FILE: DWORD = 1224;
+pub const ERROR_CONNECTION_REFUSED: DWORD = 1225;
+pub const ERROR_GRACEFUL_DISCONNECT: DWORD = 1226;
+pub const ERROR_ADDRESS_ALREADY_ASSOCIATED: DWORD = 1227;
+pub const ERROR_ADDRESS_NOT_ASSOCIATED: DWORD = 1228;
+pub const ERROR_CONNECTION_INVALID: DWORD = 1229;
+pub const ERROR_CONNECTION_ACTIVE: DWORD = 1230;
+pub const ERROR_NETWORK_UNREACHABLE: DWORD = 1231;
+pub const ERROR_HOST_UNREACHABLE: DWORD = 1232;
+pub const ERROR_PROTOCOL_UNREACHABLE: DWORD = 1233;
+pub const ERROR_PORT_UNREACHABLE: DWORD = 1234;
+pub const ERROR_REQUEST_ABORTED: DWORD = 1235;
+pub const ERROR_CONNECTION_ABORTED: DWORD = 1236;
+pub const ERROR_RETRY: DWORD = 1237;
+pub const ERROR_CONNECTION_COUNT_LIMIT: DWORD = 1238;
+pub const ERROR_LOGIN_TIME_RESTRICTION: DWORD = 1239;
+pub const ERROR_LOGIN_WKSTA_RESTRICTION: DWORD = 1240;
+pub const ERROR_INCORRECT_ADDRESS: DWORD = 1241;
+pub const ERROR_ALREADY_REGISTERED: DWORD = 1242;
+pub const ERROR_SERVICE_NOT_FOUND: DWORD = 1243;
+pub const ERROR_NOT_AUTHENTICATED: DWORD = 1244;
+pub const ERROR_NOT_LOGGED_ON: DWORD = 1245;
+pub const ERROR_CONTINUE: DWORD = 1246;
+pub const ERROR_ALREADY_INITIALIZED: DWORD = 1247;
+pub const ERROR_NO_MORE_DEVICES: DWORD = 1248;
+pub const ERROR_NO_SUCH_SITE: DWORD = 1249;
+pub const ERROR_DOMAIN_CONTROLLER_EXISTS: DWORD = 1250;
+pub const ERROR_ONLY_IF_CONNECTED: DWORD = 1251;
+pub const ERROR_OVERRIDE_NOCHANGES: DWORD = 1252;
+pub const ERROR_BAD_USER_PROFILE: DWORD = 1253;
+pub const ERROR_NOT_SUPPORTED_ON_SBS: DWORD = 1254;
+pub const ERROR_SERVER_SHUTDOWN_IN_PROGRESS: DWORD = 1255;
+pub const ERROR_HOST_DOWN: DWORD = 1256;
+pub const ERROR_NON_ACCOUNT_SID: DWORD = 1257;
+pub const ERROR_NON_DOMAIN_SID: DWORD = 1258;
+pub const ERROR_APPHELP_BLOCK: DWORD = 1259;
+pub const ERROR_ACCESS_DISABLED_BY_POLICY: DWORD = 1260;
+pub const ERROR_REG_NAT_CONSUMPTION: DWORD = 1261;
+pub const ERROR_CSCSHARE_OFFLINE: DWORD = 1262;
+pub const ERROR_PKINIT_FAILURE: DWORD = 1263;
+pub const ERROR_SMARTCARD_SUBSYSTEM_FAILURE: DWORD = 1264;
+pub const ERROR_DOWNGRADE_DETECTED: DWORD = 1265;
+pub const ERROR_MACHINE_LOCKED: DWORD = 1271;
+pub const ERROR_CALLBACK_SUPPLIED_INVALID_DATA: DWORD = 1273;
+pub const ERROR_SYNC_FOREGROUND_REFRESH_REQUIRED: DWORD = 1274;
+pub const ERROR_DRIVER_BLOCKED: DWORD = 1275;
+pub const ERROR_INVALID_IMPORT_OF_NON_DLL: DWORD = 1276;
+pub const ERROR_ACCESS_DISABLED_WEBBLADE: DWORD = 1277;
+pub const ERROR_ACCESS_DISABLED_WEBBLADE_TAMPER: DWORD = 1278;
+pub const ERROR_RECOVERY_FAILURE: DWORD = 1279;
+pub const ERROR_ALREADY_FIBER: DWORD = 1280;
+pub const ERROR_ALREADY_THREAD: DWORD = 1281;
+pub const ERROR_STACK_BUFFER_OVERRUN: DWORD = 1282;
+pub const ERROR_PARAMETER_QUOTA_EXCEEDED: DWORD = 1283;
+pub const ERROR_DEBUGGER_INACTIVE: DWORD = 1284;
+pub const ERROR_DELAY_LOAD_FAILED: DWORD = 1285;
+pub const ERROR_VDM_DISALLOWED: DWORD = 1286;
+pub const ERROR_UNIDENTIFIED_ERROR: DWORD = 1287;
+pub const ERROR_NOT_ALL_ASSIGNED: DWORD = 1300;
+pub const ERROR_SOME_NOT_MAPPED: DWORD = 1301;
+pub const ERROR_NO_QUOTAS_FOR_ACCOUNT: DWORD = 1302;
+pub const ERROR_LOCAL_USER_SESSION_KEY: DWORD = 1303;
+pub const ERROR_NULL_LM_PASSWORD: DWORD = 1304;
+pub const ERROR_UNKNOWN_REVISION: DWORD = 1305;
+pub const ERROR_REVISION_MISMATCH: DWORD = 1306;
+pub const ERROR_INVALID_OWNER: DWORD = 1307;
+pub const ERROR_INVALID_PRIMARY_GROUP: DWORD = 1308;
+pub const ERROR_NO_IMPERSONATION_TOKEN: DWORD = 1309;
+pub const ERROR_CANT_DISABLE_MANDATORY: DWORD = 1310;
+pub const ERROR_NO_LOGON_SERVERS: DWORD = 1311;
+pub const ERROR_NO_SUCH_LOGON_SESSION: DWORD = 1312;
+pub const ERROR_NO_SUCH_PRIVILEGE: DWORD = 1313;
+pub const ERROR_PRIVILEGE_NOT_HELD: DWORD = 1314;
+pub const ERROR_INVALID_ACCOUNT_NAME: DWORD = 1315;
+pub const ERROR_USER_EXISTS: DWORD = 1316;
+pub const ERROR_NO_SUCH_USER: DWORD = 1317;
+pub const ERROR_GROUP_EXISTS: DWORD = 1318;
+pub const ERROR_NO_SUCH_GROUP: DWORD = 1319;
+pub const ERROR_MEMBER_IN_GROUP: DWORD = 1320;
+pub const ERROR_MEMBER_NOT_IN_GROUP: DWORD = 1321;
+pub const ERROR_LAST_ADMIN: DWORD = 1322;
+pub const ERROR_WRONG_PASSWORD: DWORD = 1323;
+pub const ERROR_ILL_FORMED_PASSWORD: DWORD = 1324;
+pub const ERROR_PASSWORD_RESTRICTION: DWORD = 1325;
+pub const ERROR_LOGON_FAILURE: DWORD = 1326;
+pub const ERROR_ACCOUNT_RESTRICTION: DWORD = 1327;
+pub const ERROR_INVALID_LOGON_HOURS: DWORD = 1328;
+pub const ERROR_INVALID_WORKSTATION: DWORD = 1329;
+pub const ERROR_PASSWORD_EXPIRED: DWORD = 1330;
+pub const ERROR_ACCOUNT_DISABLED: DWORD = 1331;
+pub const ERROR_NONE_MAPPED: DWORD = 1332;
+pub const ERROR_TOO_MANY_LUIDS_REQUESTED: DWORD = 1333;
+pub const ERROR_LUIDS_EXHAUSTED: DWORD = 1334;
+pub const ERROR_INVALID_SUB_AUTHORITY: DWORD = 1335;
+pub const ERROR_INVALID_ACL: DWORD = 1336;
+pub const ERROR_INVALID_SID: DWORD = 1337;
+pub const ERROR_INVALID_SECURITY_DESCR: DWORD = 1338;
+pub const ERROR_BAD_INHERITANCE_ACL: DWORD = 1340;
+pub const ERROR_SERVER_DISABLED: DWORD = 1341;
+pub const ERROR_SERVER_NOT_DISABLED: DWORD = 1342;
+pub const ERROR_INVALID_ID_AUTHORITY: DWORD = 1343;
+pub const ERROR_ALLOTTED_SPACE_EXCEEDED: DWORD = 1344;
+pub const ERROR_INVALID_GROUP_ATTRIBUTES: DWORD = 1345;
+pub const ERROR_BAD_IMPERSONATION_LEVEL: DWORD = 1346;
+pub const ERROR_CANT_OPEN_ANONYMOUS: DWORD = 1347;
+pub const ERROR_BAD_VALIDATION_CLASS: DWORD = 1348;
+pub const ERROR_BAD_TOKEN_TYPE: DWORD = 1349;
+pub const ERROR_NO_SECURITY_ON_OBJECT: DWORD = 1350;
+pub const ERROR_CANT_ACCESS_DOMAIN_INFO: DWORD = 1351;
+pub const ERROR_INVALID_SERVER_STATE: DWORD = 1352;
+pub const ERROR_INVALID_DOMAIN_STATE: DWORD = 1353;
+pub const ERROR_INVALID_DOMAIN_ROLE: DWORD = 1354;
+pub const ERROR_NO_SUCH_DOMAIN: DWORD = 1355;
+pub const ERROR_DOMAIN_EXISTS: DWORD = 1356;
+pub const ERROR_DOMAIN_LIMIT_EXCEEDED: DWORD = 1357;
+pub const ERROR_INTERNAL_DB_CORRUPTION: DWORD = 1358;
+pub const ERROR_INTERNAL_ERROR: DWORD = 1359;
+pub const ERROR_GENERIC_NOT_MAPPED: DWORD = 1360;
+pub const ERROR_BAD_DESCRIPTOR_FORMAT: DWORD = 1361;
+pub const ERROR_NOT_LOGON_PROCESS: DWORD = 1362;
+pub const ERROR_LOGON_SESSION_EXISTS: DWORD = 1363;
+pub const ERROR_NO_SUCH_PACKAGE: DWORD = 1364;
+pub const ERROR_BAD_LOGON_SESSION_STATE: DWORD = 1365;
+pub const ERROR_LOGON_SESSION_COLLISION: DWORD = 1366;
+pub const ERROR_INVALID_LOGON_TYPE: DWORD = 1367;
+pub const ERROR_CANNOT_IMPERSONATE: DWORD = 1368;
+pub const ERROR_RXACT_INVALID_STATE: DWORD = 1369;
+pub const ERROR_RXACT_COMMIT_FAILURE: DWORD = 1370;
+pub const ERROR_SPECIAL_ACCOUNT: DWORD = 1371;
+pub const ERROR_SPECIAL_GROUP: DWORD = 1372;
+pub const ERROR_SPECIAL_USER: DWORD = 1373;
+pub const ERROR_MEMBERS_PRIMARY_GROUP: DWORD = 1374;
+pub const ERROR_TOKEN_ALREADY_IN_USE: DWORD = 1375;
+pub const ERROR_NO_SUCH_ALIAS: DWORD = 1376;
+pub const ERROR_MEMBER_NOT_IN_ALIAS: DWORD = 1377;
+pub const ERROR_MEMBER_IN_ALIAS: DWORD = 1378;
+pub const ERROR_ALIAS_EXISTS: DWORD = 1379;
+pub const ERROR_LOGON_NOT_GRANTED: DWORD = 1380;
+pub const ERROR_TOO_MANY_SECRETS: DWORD = 1381;
+pub const ERROR_SECRET_TOO_LONG: DWORD = 1382;
+pub const ERROR_INTERNAL_DB_ERROR: DWORD = 1383;
+pub const ERROR_TOO_MANY_CONTEXT_IDS: DWORD = 1384;
+pub const ERROR_LOGON_TYPE_NOT_GRANTED: DWORD = 1385;
+pub const ERROR_NT_CROSS_ENCRYPTION_REQUIRED: DWORD = 1386;
+pub const ERROR_NO_SUCH_MEMBER: DWORD = 1387;
+pub const ERROR_INVALID_MEMBER: DWORD = 1388;
+pub const ERROR_TOO_MANY_SIDS: DWORD = 1389;
+pub const ERROR_LM_CROSS_ENCRYPTION_REQUIRED: DWORD = 1390;
+pub const ERROR_NO_INHERITANCE: DWORD = 1391;
+pub const ERROR_FILE_CORRUPT: DWORD = 1392;
+pub const ERROR_DISK_CORRUPT: DWORD = 1393;
+pub const ERROR_NO_USER_SESSION_KEY: DWORD = 1394;
+pub const ERROR_LICENSE_QUOTA_EXCEEDED: DWORD = 1395;
+pub const ERROR_WRONG_TARGET_NAME: DWORD = 1396;
+pub const ERROR_MUTUAL_AUTH_FAILED: DWORD = 1397;
+pub const ERROR_TIME_SKEW: DWORD = 1398;
+pub const ERROR_CURRENT_DOMAIN_NOT_ALLOWED: DWORD = 1399;
+pub const ERROR_INVALID_WINDOW_HANDLE: DWORD = 1400;
+pub const ERROR_INVALID_MENU_HANDLE: DWORD = 1401;
+pub const ERROR_INVALID_CURSOR_HANDLE: DWORD = 1402;
+pub const ERROR_INVALID_ACCEL_HANDLE: DWORD = 1403;
+pub const ERROR_INVALID_HOOK_HANDLE: DWORD = 1404;
+pub const ERROR_INVALID_DWP_HANDLE: DWORD = 1405;
+pub const ERROR_TLW_WITH_WSCHILD: DWORD = 1406;
+pub const ERROR_CANNOT_FIND_WND_CLASS: DWORD = 1407;
+pub const ERROR_WINDOW_OF_OTHER_THREAD: DWORD = 1408;
+pub const ERROR_HOTKEY_ALREADY_REGISTERED: DWORD = 1409;
+pub const ERROR_CLASS_ALREADY_EXISTS: DWORD = 1410;
+pub const ERROR_CLASS_DOES_NOT_EXIST: DWORD = 1411;
+pub const ERROR_CLASS_HAS_WINDOWS: DWORD = 1412;
+pub const ERROR_INVALID_INDEX: DWORD = 1413;
+pub const ERROR_INVALID_ICON_HANDLE: DWORD = 1414;
+pub const ERROR_PRIVATE_DIALOG_INDEX: DWORD = 1415;
+pub const ERROR_LISTBOX_ID_NOT_FOUND: DWORD = 1416;
+pub const ERROR_NO_WILDCARD_CHARACTERS: DWORD = 1417;
+pub const ERROR_CLIPBOARD_NOT_OPEN: DWORD = 1418;
+pub const ERROR_HOTKEY_NOT_REGISTERED: DWORD = 1419;
+pub const ERROR_WINDOW_NOT_DIALOG: DWORD = 1420;
+pub const ERROR_CONTROL_ID_NOT_FOUND: DWORD = 1421;
+pub const ERROR_INVALID_COMBOBOX_MESSAGE: DWORD = 1422;
+pub const ERROR_WINDOW_NOT_COMBOBOX: DWORD = 1423;
+pub const ERROR_INVALID_EDIT_HEIGHT: DWORD = 1424;
+pub const ERROR_DC_NOT_FOUND: DWORD = 1425;
+pub const ERROR_INVALID_HOOK_FILTER: DWORD = 1426;
+pub const ERROR_INVALID_FILTER_PROC: DWORD = 1427;
+pub const ERROR_HOOK_NEEDS_HMOD: DWORD = 1428;
+pub const ERROR_GLOBAL_ONLY_HOOK: DWORD = 1429;
+pub const ERROR_JOURNAL_HOOK_SET: DWORD = 1430;
+pub const ERROR_HOOK_NOT_INSTALLED: DWORD = 1431;
+pub const ERROR_INVALID_LB_MESSAGE: DWORD = 1432;
+pub const ERROR_SETCOUNT_ON_BAD_LB: DWORD = 1433;
+pub const ERROR_LB_WITHOUT_TABSTOPS: DWORD = 1434;
+pub const ERROR_DESTROY_OBJECT_OF_OTHER_THREAD: DWORD = 1435;
+pub const ERROR_CHILD_WINDOW_MENU: DWORD = 1436;
+pub const ERROR_NO_SYSTEM_MENU: DWORD = 1437;
+pub const ERROR_INVALID_MSGBOX_STYLE: DWORD = 1438;
+pub const ERROR_INVALID_SPI_VALUE: DWORD = 1439;
+pub const ERROR_SCREEN_ALREADY_LOCKED: DWORD = 1440;
+pub const ERROR_HWNDS_HAVE_DIFF_PARENT: DWORD = 1441;
+pub const ERROR_NOT_CHILD_WINDOW: DWORD = 1442;
+pub const ERROR_INVALID_GW_COMMAND: DWORD = 1443;
+pub const ERROR_INVALID_THREAD_ID: DWORD = 1444;
+pub const ERROR_NON_MDICHILD_WINDOW: DWORD = 1445;
+pub const ERROR_POPUP_ALREADY_ACTIVE: DWORD = 1446;
+pub const ERROR_NO_SCROLLBARS: DWORD = 1447;
+pub const ERROR_INVALID_SCROLLBAR_RANGE: DWORD = 1448;
+pub const ERROR_INVALID_SHOWWIN_COMMAND: DWORD = 1449;
+pub const ERROR_NO_SYSTEM_RESOURCES: DWORD = 1450;
+pub const ERROR_NONPAGED_SYSTEM_RESOURCES: DWORD = 1451;
+pub const ERROR_PAGED_SYSTEM_RESOURCES: DWORD = 1452;
+pub const ERROR_WORKING_SET_QUOTA: DWORD = 1453;
+pub const ERROR_PAGEFILE_QUOTA: DWORD = 1454;
+pub const ERROR_COMMITMENT_LIMIT: DWORD = 1455;
+pub const ERROR_MENU_ITEM_NOT_FOUND: DWORD = 1456;
+pub const ERROR_INVALID_KEYBOARD_HANDLE: DWORD = 1457;
+pub const ERROR_HOOK_TYPE_NOT_ALLOWED: DWORD = 1458;
+pub const ERROR_REQUIRES_INTERACTIVE_WINDOWSTATION: DWORD = 1459;
+pub const ERROR_TIMEOUT: DWORD = 1460;
+pub const ERROR_INVALID_MONITOR_HANDLE: DWORD = 1461;
+pub const ERROR_INCORRECT_SIZE: DWORD = 1462;
+pub const ERROR_SYMLINK_CLASS_DISABLED: DWORD = 1463;
+pub const ERROR_SYMLINK_NOT_SUPPORTED: DWORD = 1464;
+pub const ERROR_XML_PARSE_ERROR: DWORD = 1465;
+pub const ERROR_XMLDSIG_ERROR: DWORD = 1466;
+pub const ERROR_RESTART_APPLICATION: DWORD = 1467;
+pub const ERROR_WRONG_COMPARTMENT: DWORD = 1468;
+pub const ERROR_AUTHIP_FAILURE: DWORD = 1469;
+pub const ERROR_NO_NVRAM_RESOURCES: DWORD = 1470;
+pub const ERROR_NOT_GUI_PROCESS: DWORD = 1471;
+pub const ERROR_EVENTLOG_FILE_CORRUPT: DWORD = 1500;
+pub const ERROR_EVENTLOG_CANT_START: DWORD = 1501;
+pub const ERROR_LOG_FILE_FULL: DWORD = 1502;
+pub const ERROR_EVENTLOG_FILE_CHANGED: DWORD = 1503;
+pub const ERROR_INSTALL_SERVICE_FAILURE: DWORD = 1601;
+pub const ERROR_INSTALL_USEREXIT: DWORD = 1602;
+pub const ERROR_INSTALL_FAILURE: DWORD = 1603;
+pub const ERROR_INSTALL_SUSPEND: DWORD = 1604;
+pub const ERROR_UNKNOWN_PRODUCT: DWORD = 1605;
+pub const ERROR_UNKNOWN_FEATURE: DWORD = 1606;
+pub const ERROR_UNKNOWN_COMPONENT: DWORD = 1607;
+pub const ERROR_UNKNOWN_PROPERTY: DWORD = 1608;
+pub const ERROR_INVALID_HANDLE_STATE: DWORD = 1609;
+pub const ERROR_BAD_CONFIGURATION: DWORD = 1610;
+pub const ERROR_INDEX_ABSENT: DWORD = 1611;
+pub const ERROR_INSTALL_SOURCE_ABSENT: DWORD = 1612;
+pub const ERROR_INSTALL_PACKAGE_VERSION: DWORD = 1613;
+pub const ERROR_PRODUCT_UNINSTALLED: DWORD = 1614;
+pub const ERROR_BAD_QUERY_SYNTAX: DWORD = 1615;
+pub const ERROR_INVALID_FIELD: DWORD = 1616;
+pub const ERROR_DEVICE_REMOVED: DWORD = 1617;
+pub const ERROR_INSTALL_ALREADY_RUNNING: DWORD = 1618;
+pub const ERROR_INSTALL_PACKAGE_OPEN_FAILED: DWORD = 1619;
+pub const ERROR_INSTALL_PACKAGE_INVALID: DWORD = 1620;
+pub const ERROR_INSTALL_UI_FAILURE: DWORD = 1621;
+pub const ERROR_INSTALL_LOG_FAILURE: DWORD = 1622;
+pub const ERROR_INSTALL_LANGUAGE_UNSUPPORTED: DWORD = 1623;
+pub const ERROR_INSTALL_TRANSFORM_FAILURE: DWORD = 1624;
+pub const ERROR_INSTALL_PACKAGE_REJECTED: DWORD = 1625;
+pub const ERROR_FUNCTION_NOT_CALLED: DWORD = 1626;
+pub const ERROR_FUNCTION_FAILED: DWORD = 1627;
+pub const ERROR_INVALID_TABLE: DWORD = 1628;
+pub const ERROR_DATATYPE_MISMATCH: DWORD = 1629;
+pub const ERROR_UNSUPPORTED_TYPE: DWORD = 1630;
+pub const ERROR_CREATE_FAILED: DWORD = 1631;
+pub const ERROR_INSTALL_TEMP_UNWRITABLE: DWORD = 1632;
+pub const ERROR_INSTALL_PLATFORM_UNSUPPORTED: DWORD = 1633;
+pub const ERROR_INSTALL_NOTUSED: DWORD = 1634;
+pub const ERROR_PATCH_PACKAGE_OPEN_FAILED: DWORD = 1635;
+pub const ERROR_PATCH_PACKAGE_INVALID: DWORD = 1636;
+pub const ERROR_PATCH_PACKAGE_UNSUPPORTED: DWORD = 1637;
+pub const ERROR_PRODUCT_VERSION: DWORD = 1638;
+pub const ERROR_INVALID_COMMAND_LINE: DWORD = 1639;
+pub const ERROR_INSTALL_REMOTE_DISALLOWED: DWORD = 1640;
+pub const ERROR_SUCCESS_REBOOT_INITIATED: DWORD = 1641;
+pub const ERROR_PATCH_TARGET_NOT_FOUND: DWORD = 1642;
+pub const ERROR_PATCH_PACKAGE_REJECTED: DWORD = 1643;
+pub const ERROR_INSTALL_TRANSFORM_REJECTED: DWORD = 1644;
+pub const ERROR_INSTALL_REMOTE_PROHIBITED: DWORD = 1645;
+pub const ERROR_INVALID_USER_BUFFER: DWORD = 1784;
+pub const ERROR_UNRECOGNIZED_MEDIA: DWORD = 1785;
+pub const ERROR_NO_TRUST_LSA_SECRET: DWORD = 1786;
+pub const ERROR_NO_TRUST_SAM_ACCOUNT: DWORD = 1787;
+pub const ERROR_TRUSTED_DOMAIN_FAILURE: DWORD = 1788;
+pub const ERROR_TRUSTED_RELATIONSHIP_FAILURE: DWORD = 1789;
+pub const ERROR_TRUST_FAILURE: DWORD = 1790;
+pub const ERROR_NETLOGON_NOT_STARTED: DWORD = 1792;
+pub const ERROR_ACCOUNT_EXPIRED: DWORD = 1793;
+pub const ERROR_REDIRECTOR_HAS_OPEN_HANDLES: DWORD = 1794;
+pub const ERROR_PRINTER_DRIVER_ALREADY_INSTALLED: DWORD = 1795;
+pub const ERROR_UNKNOWN_PORT: DWORD = 1796;
+pub const ERROR_UNKNOWN_PRINTER_DRIVER: DWORD = 1797;
+pub const ERROR_UNKNOWN_PRINTPROCESSOR: DWORD = 1798;
+pub const ERROR_INVALID_SEPARATOR_FILE: DWORD = 1799;
+pub const ERROR_INVALID_PRIORITY: DWORD = 1800;
+pub const ERROR_INVALID_PRINTER_NAME: DWORD = 1801;
+pub const ERROR_PRINTER_ALREADY_EXISTS: DWORD = 1802;
+pub const ERROR_INVALID_PRINTER_COMMAND: DWORD = 1803;
+pub const ERROR_INVALID_DATATYPE: DWORD = 1804;
+pub const ERROR_INVALID_ENVIRONMENT: DWORD = 1805;
+pub const ERROR_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT: DWORD = 1807;
+pub const ERROR_NOLOGON_WORKSTATION_TRUST_ACCOUNT: DWORD = 1808;
+pub const ERROR_NOLOGON_SERVER_TRUST_ACCOUNT: DWORD = 1809;
+pub const ERROR_DOMAIN_TRUST_INCONSISTENT: DWORD = 1810;
+pub const ERROR_SERVER_HAS_OPEN_HANDLES: DWORD = 1811;
+pub const ERROR_RESOURCE_DATA_NOT_FOUND: DWORD = 1812;
+pub const ERROR_RESOURCE_TYPE_NOT_FOUND: DWORD = 1813;
+pub const ERROR_RESOURCE_NAME_NOT_FOUND: DWORD = 1814;
+pub const ERROR_RESOURCE_LANG_NOT_FOUND: DWORD = 1815;
+pub const ERROR_NOT_ENOUGH_QUOTA: DWORD = 1816;
+pub const ERROR_INVALID_TIME: DWORD = 1901;
+pub const ERROR_INVALID_FORM_NAME: DWORD = 1902;
+pub const ERROR_INVALID_FORM_SIZE: DWORD = 1903;
+pub const ERROR_ALREADY_WAITING: DWORD = 1904;
+pub const ERROR_PRINTER_DELETED: DWORD = 1905;
+pub const ERROR_INVALID_PRINTER_STATE: DWORD = 1906;
+pub const ERROR_PASSWORD_MUST_CHANGE: DWORD = 1907;
+pub const ERROR_DOMAIN_CONTROLLER_NOT_FOUND: DWORD = 1908;
+pub const ERROR_ACCOUNT_LOCKED_OUT: DWORD = 1909;
+pub const ERROR_NO_SITENAME: DWORD = 1919;
+pub const ERROR_CANT_ACCESS_FILE: DWORD = 1920;
+pub const ERROR_CANT_RESOLVE_FILENAME: DWORD = 1921;
+pub const ERROR_KM_DRIVER_BLOCKED: DWORD = 1930;
+pub const ERROR_CONTEXT_EXPIRED: DWORD = 1931;
+pub const ERROR_PER_USER_TRUST_QUOTA_EXCEEDED: DWORD = 1932;
+pub const ERROR_ALL_USER_TRUST_QUOTA_EXCEEDED: DWORD = 1933;
+pub const ERROR_USER_DELETE_TRUST_QUOTA_EXCEEDED: DWORD = 1934;
+pub const ERROR_AUTHENTICATION_FIREWALL_FAILED: DWORD = 1935;
+pub const ERROR_REMOTE_PRINT_CONNECTIONS_BLOCKED: DWORD = 1936;
+pub const ERROR_INVALID_PIXEL_FORMAT: DWORD = 2000;
+pub const ERROR_BAD_DRIVER: DWORD = 2001;
+pub const ERROR_INVALID_WINDOW_STYLE: DWORD = 2002;
+pub const ERROR_METAFILE_NOT_SUPPORTED: DWORD = 2003;
+pub const ERROR_TRANSFORM_NOT_SUPPORTED: DWORD = 2004;
+pub const ERROR_CLIPPING_NOT_SUPPORTED: DWORD = 2005;
+pub const ERROR_INVALID_CMM: DWORD = 2010;
+pub const ERROR_INVALID_PROFILE: DWORD = 2011;
+pub const ERROR_TAG_NOT_FOUND: DWORD = 2012;
+pub const ERROR_TAG_NOT_PRESENT: DWORD = 2013;
+pub const ERROR_DUPLICATE_TAG: DWORD = 2014;
+pub const ERROR_PROFILE_NOT_ASSOCIATED_WITH_DEVICE: DWORD = 2015;
+pub const ERROR_PROFILE_NOT_FOUND: DWORD = 2016;
+pub const ERROR_INVALID_COLORSPACE: DWORD = 2017;
+pub const ERROR_ICM_NOT_ENABLED: DWORD = 2018;
+pub const ERROR_DELETING_ICM_XFORM: DWORD = 2019;
+pub const ERROR_INVALID_TRANSFORM: DWORD = 2020;
+pub const ERROR_COLORSPACE_MISMATCH: DWORD = 2021;
+pub const ERROR_INVALID_COLORINDEX: DWORD = 2022;
+pub const ERROR_CONNECTED_OTHER_PASSWORD: DWORD = 2108;
+pub const ERROR_CONNECTED_OTHER_PASSWORD_DEFAULT: DWORD = 2109;
+pub const ERROR_BAD_USERNAME: DWORD = 2202;
+pub const ERROR_NOT_CONNECTED: DWORD = 2250;
+pub const ERROR_OPEN_FILES: DWORD = 2401;
+pub const ERROR_ACTIVE_CONNECTIONS: DWORD = 2402;
+pub const ERROR_DEVICE_IN_USE: DWORD = 2404;
+pub const ERROR_UNKNOWN_PRINT_MONITOR: DWORD = 3000;
+pub const ERROR_PRINTER_DRIVER_IN_USE: DWORD = 3001;
+pub const ERROR_SPOOL_FILE_NOT_FOUND: DWORD = 3002;
+pub const ERROR_SPL_NO_STARTDOC: DWORD = 3003;
+pub const ERROR_SPL_NO_ADDJOB: DWORD = 3004;
+pub const ERROR_PRINT_PROCESSOR_ALREADY_INSTALLED: DWORD = 3005;
+pub const ERROR_PRINT_MONITOR_ALREADY_INSTALLED: DWORD = 3006;
+pub const ERROR_INVALID_PRINT_MONITOR: DWORD = 3007;
+pub const ERROR_PRINT_MONITOR_IN_USE: DWORD = 3008;
+pub const ERROR_PRINTER_HAS_JOBS_QUEUED: DWORD = 3009;
+pub const ERROR_SUCCESS_REBOOT_REQUIRED: DWORD = 3010;
+pub const ERROR_SUCCESS_RESTART_REQUIRED: DWORD = 3011;
+pub const ERROR_PRINTER_NOT_FOUND: DWORD = 3012;
+pub const ERROR_PRINTER_DRIVER_WARNED: DWORD = 3013;
+pub const ERROR_PRINTER_DRIVER_BLOCKED: DWORD = 3014;
+pub const ERROR_WINS_INTERNAL: DWORD = 4000;
+pub const ERROR_CAN_NOT_DEL_LOCAL_WINS: DWORD = 4001;
+pub const ERROR_STATIC_INIT: DWORD = 4002;
+pub const ERROR_INC_BACKUP: DWORD = 4003;
+pub const ERROR_FULL_BACKUP: DWORD = 4004;
+pub const ERROR_REC_NON_EXISTENT: DWORD = 4005;
+pub const ERROR_RPL_NOT_ALLOWED: DWORD = 4006;
+pub const ERROR_DHCP_ADDRESS_CONFLICT: DWORD = 4100;
+pub const ERROR_WMI_GUID_NOT_FOUND: DWORD = 4200;
+pub const ERROR_WMI_INSTANCE_NOT_FOUND: DWORD = 4201;
+pub const ERROR_WMI_ITEMID_NOT_FOUND: DWORD = 4202;
+pub const ERROR_WMI_TRY_AGAIN: DWORD = 4203;
+pub const ERROR_WMI_DP_NOT_FOUND: DWORD = 4204;
+pub const ERROR_WMI_UNRESOLVED_INSTANCE_REF: DWORD = 4205;
+pub const ERROR_WMI_ALREADY_ENABLED: DWORD = 4206;
+pub const ERROR_WMI_GUID_DISCONNECTED: DWORD = 4207;
+pub const ERROR_WMI_SERVER_UNAVAILABLE: DWORD = 4208;
+pub const ERROR_WMI_DP_FAILED: DWORD = 4209;
+pub const ERROR_WMI_INVALID_MOF: DWORD = 4210;
+pub const ERROR_WMI_INVALID_REGINFO: DWORD = 4211;
+pub const ERROR_WMI_ALREADY_DISABLED: DWORD = 4212;
+pub const ERROR_WMI_READ_ONLY: DWORD = 4213;
+pub const ERROR_WMI_SET_FAILURE: DWORD = 4214;
+pub const ERROR_INVALID_MEDIA: DWORD = 4300;
+pub const ERROR_INVALID_LIBRARY: DWORD = 4301;
+pub const ERROR_INVALID_MEDIA_POOL: DWORD = 4302;
+pub const ERROR_DRIVE_MEDIA_MISMATCH: DWORD = 4303;
+pub const ERROR_MEDIA_OFFLINE: DWORD = 4304;
+pub const ERROR_LIBRARY_OFFLINE: DWORD = 4305;
+pub const ERROR_EMPTY: DWORD = 4306;
+pub const ERROR_NOT_EMPTY: DWORD = 4307;
+pub const ERROR_MEDIA_UNAVAILABLE: DWORD = 4308;
+pub const ERROR_RESOURCE_DISABLED: DWORD = 4309;
+pub const ERROR_INVALID_CLEANER: DWORD = 4310;
+pub const ERROR_UNABLE_TO_CLEAN: DWORD = 4311;
+pub const ERROR_OBJECT_NOT_FOUND: DWORD = 4312;
+pub const ERROR_DATABASE_FAILURE: DWORD = 4313;
+pub const ERROR_DATABASE_FULL: DWORD = 4314;
+pub const ERROR_MEDIA_INCOMPATIBLE: DWORD = 4315;
+pub const ERROR_RESOURCE_NOT_PRESENT: DWORD = 4316;
+pub const ERROR_INVALID_OPERATION: DWORD = 4317;
+pub const ERROR_MEDIA_NOT_AVAILABLE: DWORD = 4318;
+pub const ERROR_DEVICE_NOT_AVAILABLE: DWORD = 4319;
+pub const ERROR_REQUEST_REFUSED: DWORD = 4320;
+pub const ERROR_INVALID_DRIVE_OBJECT: DWORD = 4321;
+pub const ERROR_LIBRARY_FULL: DWORD = 4322;
+pub const ERROR_MEDIUM_NOT_ACCESSIBLE: DWORD = 4323;
+pub const ERROR_UNABLE_TO_LOAD_MEDIUM: DWORD = 4324;
+pub const ERROR_UNABLE_TO_INVENTORY_DRIVE: DWORD = 4325;
+pub const ERROR_UNABLE_TO_INVENTORY_SLOT: DWORD = 4326;
+pub const ERROR_UNABLE_TO_INVENTORY_TRANSPORT: DWORD = 4327;
+pub const ERROR_TRANSPORT_FULL: DWORD = 4328;
+pub const ERROR_CONTROLLING_IEPORT: DWORD = 4329;
+pub const ERROR_UNABLE_TO_EJECT_MOUNTED_MEDIA: DWORD = 4330;
+pub const ERROR_CLEANER_SLOT_SET: DWORD = 4331;
+pub const ERROR_CLEANER_SLOT_NOT_SET: DWORD = 4332;
+pub const ERROR_CLEANER_CARTRIDGE_SPENT: DWORD = 4333;
+pub const ERROR_UNEXPECTED_OMID: DWORD = 4334;
+pub const ERROR_CANT_DELETE_LAST_ITEM: DWORD = 4335;
+pub const ERROR_MESSAGE_EXCEEDS_MAX_SIZE: DWORD = 4336;
+pub const ERROR_VOLUME_CONTAINS_SYS_FILES: DWORD = 4337;
+pub const ERROR_INDIGENOUS_TYPE: DWORD = 4338;
+pub const ERROR_NO_SUPPORTING_DRIVES: DWORD = 4339;
+pub const ERROR_CLEANER_CARTRIDGE_INSTALLED: DWORD = 4340;
+pub const ERROR_IEPORT_FULL: DWORD = 4341;
+pub const ERROR_FILE_OFFLINE: DWORD = 4350;
+pub const ERROR_REMOTE_STORAGE_NOT_ACTIVE: DWORD = 4351;
+pub const ERROR_REMOTE_STORAGE_MEDIA_ERROR: DWORD = 4352;
+pub const ERROR_NOT_A_REPARSE_POINT: DWORD = 4390;
+pub const ERROR_REPARSE_ATTRIBUTE_CONFLICT: DWORD = 4391;
+pub const ERROR_INVALID_REPARSE_DATA: DWORD = 4392;
+pub const ERROR_REPARSE_TAG_INVALID: DWORD = 4393;
+pub const ERROR_REPARSE_TAG_MISMATCH: DWORD = 4394;
+pub const ERROR_VOLUME_NOT_SIS_ENABLED: DWORD = 4500;
+pub const ERROR_DEPENDENT_RESOURCE_EXISTS: DWORD = 5001;
+pub const ERROR_DEPENDENCY_NOT_FOUND: DWORD = 5002;
+pub const ERROR_DEPENDENCY_ALREADY_EXISTS: DWORD = 5003;
+pub const ERROR_RESOURCE_NOT_ONLINE: DWORD = 5004;
+pub const ERROR_HOST_NODE_NOT_AVAILABLE: DWORD = 5005;
+pub const ERROR_RESOURCE_NOT_AVAILABLE: DWORD = 5006;
+pub const ERROR_RESOURCE_NOT_FOUND: DWORD = 5007;
+pub const ERROR_SHUTDOWN_CLUSTER: DWORD = 5008;
+pub const ERROR_CANT_EVICT_ACTIVE_NODE: DWORD = 5009;
+pub const ERROR_OBJECT_ALREADY_EXISTS: DWORD = 5010;
+pub const ERROR_OBJECT_IN_LIST: DWORD = 5011;
+pub const ERROR_GROUP_NOT_AVAILABLE: DWORD = 5012;
+pub const ERROR_GROUP_NOT_FOUND: DWORD = 5013;
+pub const ERROR_GROUP_NOT_ONLINE: DWORD = 5014;
+pub const ERROR_HOST_NODE_NOT_RESOURCE_OWNER: DWORD = 5015;
+pub const ERROR_HOST_NODE_NOT_GROUP_OWNER: DWORD = 5016;
+pub const ERROR_RESMON_CREATE_FAILED: DWORD = 5017;
+pub const ERROR_RESMON_ONLINE_FAILED: DWORD = 5018;
+pub const ERROR_RESOURCE_ONLINE: DWORD = 5019;
+pub const ERROR_QUORUM_RESOURCE: DWORD = 5020;
+pub const ERROR_NOT_QUORUM_CAPABLE: DWORD = 5021;
+pub const ERROR_CLUSTER_SHUTTING_DOWN: DWORD = 5022;
+pub const ERROR_INVALID_STATE: DWORD = 5023;
+pub const ERROR_RESOURCE_PROPERTIES_STORED: DWORD = 5024;
+pub const ERROR_NOT_QUORUM_CLASS: DWORD = 5025;
+pub const ERROR_CORE_RESOURCE: DWORD = 5026;
+pub const ERROR_QUORUM_RESOURCE_ONLINE_FAILED: DWORD = 5027;
+pub const ERROR_QUORUMLOG_OPEN_FAILED: DWORD = 5028;
+pub const ERROR_CLUSTERLOG_CORRUPT: DWORD = 5029;
+pub const ERROR_CLUSTERLOG_RECORD_EXCEEDS_MAXSIZE: DWORD = 5030;
+pub const ERROR_CLUSTERLOG_EXCEEDS_MAXSIZE: DWORD = 5031;
+pub const ERROR_CLUSTERLOG_CHKPOINT_NOT_FOUND: DWORD = 5032;
+pub const ERROR_CLUSTERLOG_NOT_ENOUGH_SPACE: DWORD = 5033;
+pub const ERROR_QUORUM_OWNER_ALIVE: DWORD = 5034;
+pub const ERROR_NETWORK_NOT_AVAILABLE: DWORD = 5035;
+pub const ERROR_NODE_NOT_AVAILABLE: DWORD = 5036;
+pub const ERROR_ALL_NODES_NOT_AVAILABLE: DWORD = 5037;
+pub const ERROR_RESOURCE_FAILED: DWORD = 5038;
+pub const ERROR_CLUSTER_INVALID_NODE: DWORD = 5039;
+pub const ERROR_CLUSTER_NODE_EXISTS: DWORD = 5040;
+pub const ERROR_CLUSTER_JOIN_IN_PROGRESS: DWORD = 5041;
+pub const ERROR_CLUSTER_NODE_NOT_FOUND: DWORD = 5042;
+pub const ERROR_CLUSTER_LOCAL_NODE_NOT_FOUND: DWORD = 5043;
+pub const ERROR_CLUSTER_NETWORK_EXISTS: DWORD = 5044;
+pub const ERROR_CLUSTER_NETWORK_NOT_FOUND: DWORD = 5045;
+pub const ERROR_CLUSTER_NETINTERFACE_EXISTS: DWORD = 5046;
+pub const ERROR_CLUSTER_NETINTERFACE_NOT_FOUND: DWORD = 5047;
+pub const ERROR_CLUSTER_INVALID_REQUEST: DWORD = 5048;
+pub const ERROR_CLUSTER_INVALID_NETWORK_PROVIDER: DWORD = 5049;
+pub const ERROR_CLUSTER_NODE_DOWN: DWORD = 5050;
+pub const ERROR_CLUSTER_NODE_UNREACHABLE: DWORD = 5051;
+pub const ERROR_CLUSTER_NODE_NOT_MEMBER: DWORD = 5052;
+pub const ERROR_CLUSTER_JOIN_NOT_IN_PROGRESS: DWORD = 5053;
+pub const ERROR_CLUSTER_INVALID_NETWORK: DWORD = 5054;
+pub const ERROR_CLUSTER_NODE_UP: DWORD = 5056;
+pub const ERROR_CLUSTER_IPADDR_IN_USE: DWORD = 5057;
+pub const ERROR_CLUSTER_NODE_NOT_PAUSED: DWORD = 5058;
+pub const ERROR_CLUSTER_NO_SECURITY_CONTEXT: DWORD = 5059;
+pub const ERROR_CLUSTER_NETWORK_NOT_INTERNAL: DWORD = 5060;
+pub const ERROR_CLUSTER_NODE_ALREADY_UP: DWORD = 5061;
+pub const ERROR_CLUSTER_NODE_ALREADY_DOWN: DWORD = 5062;
+pub const ERROR_CLUSTER_NETWORK_ALREADY_ONLINE: DWORD = 5063;
+pub const ERROR_CLUSTER_NETWORK_ALREADY_OFFLINE: DWORD = 5064;
+pub const ERROR_CLUSTER_NODE_ALREADY_MEMBER: DWORD = 5065;
+pub const ERROR_CLUSTER_LAST_INTERNAL_NETWORK: DWORD = 5066;
+pub const ERROR_CLUSTER_NETWORK_HAS_DEPENDENTS: DWORD = 5067;
+pub const ERROR_INVALID_OPERATION_ON_QUORUM: DWORD = 5068;
+pub const ERROR_DEPENDENCY_NOT_ALLOWED: DWORD = 5069;
+pub const ERROR_CLUSTER_NODE_PAUSED: DWORD = 5070;
+pub const ERROR_NODE_CANT_HOST_RESOURCE: DWORD = 5071;
+pub const ERROR_CLUSTER_NODE_NOT_READY: DWORD = 5072;
+pub const ERROR_CLUSTER_NODE_SHUTTING_DOWN: DWORD = 5073;
+pub const ERROR_CLUSTER_JOIN_ABORTED: DWORD = 5074;
+pub const ERROR_CLUSTER_INCOMPATIBLE_VERSIONS: DWORD = 5075;
+pub const ERROR_CLUSTER_MAXNUM_OF_RESOURCES_EXCEEDED: DWORD = 5076;
+pub const ERROR_CLUSTER_SYSTEM_CONFIG_CHANGED: DWORD = 5077;
+pub const ERROR_CLUSTER_RESOURCE_TYPE_NOT_FOUND: DWORD = 5078;
+pub const ERROR_CLUSTER_RESTYPE_NOT_SUPPORTED: DWORD = 5079;
+pub const ERROR_CLUSTER_RESNAME_NOT_FOUND: DWORD = 5080;
+pub const ERROR_CLUSTER_NO_RPC_PACKAGES_REGISTERED: DWORD = 5081;
+pub const ERROR_CLUSTER_OWNER_NOT_IN_PREFLIST: DWORD = 5082;
+pub const ERROR_CLUSTER_DATABASE_SEQMISMATCH: DWORD = 5083;
+pub const ERROR_RESMON_INVALID_STATE: DWORD = 5084;
+pub const ERROR_CLUSTER_GUM_NOT_LOCKER: DWORD = 5085;
+pub const ERROR_QUORUM_DISK_NOT_FOUND: DWORD = 5086;
+pub const ERROR_DATABASE_BACKUP_CORRUPT: DWORD = 5087;
+pub const ERROR_CLUSTER_NODE_ALREADY_HAS_DFS_ROOT: DWORD = 5088;
+pub const ERROR_RESOURCE_PROPERTY_UNCHANGEABLE: DWORD = 5089;
+pub const ERROR_CLUSTER_MEMBERSHIP_INVALID_STATE: DWORD = 5890;
+pub const ERROR_CLUSTER_QUORUMLOG_NOT_FOUND: DWORD = 5891;
+pub const ERROR_CLUSTER_MEMBERSHIP_HALT: DWORD = 5892;
+pub const ERROR_CLUSTER_INSTANCE_ID_MISMATCH: DWORD = 5893;
+pub const ERROR_CLUSTER_NETWORK_NOT_FOUND_FOR_IP: DWORD = 5894;
+pub const ERROR_CLUSTER_PROPERTY_DATA_TYPE_MISMATCH: DWORD = 5895;
+pub const ERROR_CLUSTER_EVICT_WITHOUT_CLEANUP: DWORD = 5896;
+pub const ERROR_CLUSTER_PARAMETER_MISMATCH: DWORD = 5897;
+pub const ERROR_NODE_CANNOT_BE_CLUSTERED: DWORD = 5898;
+pub const ERROR_CLUSTER_WRONG_OS_VERSION: DWORD = 5899;
+pub const ERROR_CLUSTER_CANT_CREATE_DUP_CLUSTER_NAME: DWORD = 5900;
+pub const ERROR_CLUSCFG_ALREADY_COMMITTED: DWORD = 5901;
+pub const ERROR_CLUSCFG_ROLLBACK_FAILED: DWORD = 5902;
+pub const ERROR_CLUSCFG_SYSTEM_DISK_DRIVE_LETTER_CONFLICT: DWORD = 5903;
+pub const ERROR_CLUSTER_OLD_VERSION: DWORD = 5904;
+pub const ERROR_CLUSTER_MISMATCHED_COMPUTER_ACCT_NAME: DWORD = 5905;
+pub const ERROR_ENCRYPTION_FAILED: DWORD = 6000;
+pub const ERROR_DECRYPTION_FAILED: DWORD = 6001;
+pub const ERROR_FILE_ENCRYPTED: DWORD = 6002;
+pub const ERROR_NO_RECOVERY_POLICY: DWORD = 6003;
+pub const ERROR_NO_EFS: DWORD = 6004;
+pub const ERROR_WRONG_EFS: DWORD = 6005;
+pub const ERROR_NO_USER_KEYS: DWORD = 6006;
+pub const ERROR_FILE_NOT_ENCRYPTED: DWORD = 6007;
+pub const ERROR_NOT_EXPORT_FORMAT: DWORD = 6008;
+pub const ERROR_FILE_READ_ONLY: DWORD = 6009;
+pub const ERROR_DIR_EFS_DISALLOWED: DWORD = 6010;
+pub const ERROR_EFS_SERVER_NOT_TRUSTED: DWORD = 6011;
+pub const ERROR_BAD_RECOVERY_POLICY: DWORD = 6012;
+pub const ERROR_EFS_ALG_BLOB_TOO_BIG: DWORD = 6013;
+pub const ERROR_VOLUME_NOT_SUPPORT_EFS: DWORD = 6014;
+pub const ERROR_EFS_DISABLED: DWORD = 6015;
+pub const ERROR_EFS_VERSION_NOT_SUPPORT: DWORD = 6016;
+pub const ERROR_NO_BROWSER_SERVERS_FOUND: DWORD = 6118;
+pub const ERROR_CTX_WINSTATION_NAME_INVALID: DWORD = 7001;
+pub const ERROR_CTX_INVALID_PD: DWORD = 7002;
+pub const ERROR_CTX_PD_NOT_FOUND: DWORD = 7003;
+pub const ERROR_CTX_WD_NOT_FOUND: DWORD = 7004;
+pub const ERROR_CTX_CANNOT_MAKE_EVENTLOG_ENTRY: DWORD = 7005;
+pub const ERROR_CTX_SERVICE_NAME_COLLISION: DWORD = 7006;
+pub const ERROR_CTX_CLOSE_PENDING: DWORD = 7007;
+pub const ERROR_CTX_NO_OUTBUF: DWORD = 7008;
+pub const ERROR_CTX_MODEM_INF_NOT_FOUND: DWORD = 7009;
+pub const ERROR_CTX_INVALID_MODEMNAME: DWORD = 7010;
+pub const ERROR_CTX_MODEM_RESPONSE_ERROR: DWORD = 7011;
+pub const ERROR_CTX_MODEM_RESPONSE_TIMEOUT: DWORD = 7012;
+pub const ERROR_CTX_MODEM_RESPONSE_NO_CARRIER: DWORD = 7013;
+pub const ERROR_CTX_MODEM_RESPONSE_NO_DIALTONE: DWORD = 7014;
+pub const ERROR_CTX_MODEM_RESPONSE_BUSY: DWORD = 7015;
+pub const ERROR_CTX_MODEM_RESPONSE_VOICE: DWORD = 7016;
+pub const ERROR_CTX_TD_ERROR: DWORD = 7017;
+pub const ERROR_CTX_WINSTATION_NOT_FOUND: DWORD = 7022;
+pub const ERROR_CTX_WINSTATION_ALREADY_EXISTS: DWORD = 7023;
+pub const ERROR_CTX_WINSTATION_BUSY: DWORD = 7024;
+pub const ERROR_CTX_BAD_VIDEO_MODE: DWORD = 7025;
+pub const ERROR_CTX_GRAPHICS_INVALID: DWORD = 7035;
+pub const ERROR_CTX_LOGON_DISABLED: DWORD = 7037;
+pub const ERROR_CTX_NOT_CONSOLE: DWORD = 7038;
+pub const ERROR_CTX_CLIENT_QUERY_TIMEOUT: DWORD = 7040;
+pub const ERROR_CTX_CONSOLE_DISCONNECT: DWORD = 7041;
+pub const ERROR_CTX_CONSOLE_CONNECT: DWORD = 7042;
+pub const ERROR_CTX_SHADOW_DENIED: DWORD = 7044;
+pub const ERROR_CTX_WINSTATION_ACCESS_DENIED: DWORD = 7045;
+pub const ERROR_CTX_INVALID_WD: DWORD = 7049;
+pub const ERROR_CTX_SHADOW_INVALID: DWORD = 7050;
+pub const ERROR_CTX_SHADOW_DISABLED: DWORD = 7051;
+pub const ERROR_CTX_CLIENT_LICENSE_IN_USE: DWORD = 7052;
+pub const ERROR_CTX_CLIENT_LICENSE_NOT_SET: DWORD = 7053;
+pub const ERROR_CTX_LICENSE_NOT_AVAILABLE: DWORD = 7054;
+pub const ERROR_CTX_LICENSE_CLIENT_INVALID: DWORD = 7055;
+pub const ERROR_CTX_LICENSE_EXPIRED: DWORD = 7056;
+pub const ERROR_CTX_SHADOW_NOT_RUNNING: DWORD = 7057;
+pub const ERROR_CTX_SHADOW_ENDED_BY_MODE_CHANGE: DWORD = 7058;
+pub const ERROR_ACTIVATION_COUNT_EXCEEDED: DWORD = 7059;
+pub const ERROR_DS_NOT_INSTALLED: DWORD = 8200;
+pub const ERROR_DS_MEMBERSHIP_EVALUATED_LOCALLY: DWORD = 8201;
+pub const ERROR_DS_NO_ATTRIBUTE_OR_VALUE: DWORD = 8202;
+pub const ERROR_DS_INVALID_ATTRIBUTE_SYNTAX: DWORD = 8203;
+pub const ERROR_DS_ATTRIBUTE_TYPE_UNDEFINED: DWORD = 8204;
+pub const ERROR_DS_ATTRIBUTE_OR_VALUE_EXISTS: DWORD = 8205;
+pub const ERROR_DS_BUSY: DWORD = 8206;
+pub const ERROR_DS_UNAVAILABLE: DWORD = 8207;
+pub const ERROR_DS_NO_RIDS_ALLOCATED: DWORD = 8208;
+pub const ERROR_DS_NO_MORE_RIDS: DWORD = 8209;
+pub const ERROR_DS_INCORRECT_ROLE_OWNER: DWORD = 8210;
+pub const ERROR_DS_RIDMGR_INIT_ERROR: DWORD = 8211;
+pub const ERROR_DS_OBJ_CLASS_VIOLATION: DWORD = 8212;
+pub const ERROR_DS_CANT_ON_NON_LEAF: DWORD = 8213;
+pub const ERROR_DS_CANT_ON_RDN: DWORD = 8214;
+pub const ERROR_DS_CANT_MOD_OBJ_CLASS: DWORD = 8215;
+pub const ERROR_DS_CROSS_DOM_MOVE_ERROR: DWORD = 8216;
+pub const ERROR_DS_GC_NOT_AVAILABLE: DWORD = 8217;
+pub const ERROR_SHARED_POLICY: DWORD = 8218;
+pub const ERROR_POLICY_OBJECT_NOT_FOUND: DWORD = 8219;
+pub const ERROR_POLICY_ONLY_IN_DS: DWORD = 8220;
+pub const ERROR_PROMOTION_ACTIVE: DWORD = 8221;
+pub const ERROR_NO_PROMOTION_ACTIVE: DWORD = 8222;
+pub const ERROR_DS_OPERATIONS_ERROR: DWORD = 8224;
+pub const ERROR_DS_PROTOCOL_ERROR: DWORD = 8225;
+pub const ERROR_DS_TIMELIMIT_EXCEEDED: DWORD = 8226;
+pub const ERROR_DS_SIZELIMIT_EXCEEDED: DWORD = 8227;
+pub const ERROR_DS_ADMIN_LIMIT_EXCEEDED: DWORD = 8228;
+pub const ERROR_DS_COMPARE_FALSE: DWORD = 8229;
+pub const ERROR_DS_COMPARE_TRUE: DWORD = 8230;
+pub const ERROR_DS_AUTH_METHOD_NOT_SUPPORTED: DWORD = 8231;
+pub const ERROR_DS_STRONG_AUTH_REQUIRED: DWORD = 8232;
+pub const ERROR_DS_INAPPROPRIATE_AUTH: DWORD = 8233;
+pub const ERROR_DS_AUTH_UNKNOWN: DWORD = 8234;
+pub const ERROR_DS_REFERRAL: DWORD = 8235;
+pub const ERROR_DS_UNAVAILABLE_CRIT_EXTENSION: DWORD = 8236;
+pub const ERROR_DS_CONFIDENTIALITY_REQUIRED: DWORD = 8237;
+pub const ERROR_DS_INAPPROPRIATE_MATCHING: DWORD = 8238;
+pub const ERROR_DS_CONSTRAINT_VIOLATION: DWORD = 8239;
+pub const ERROR_DS_NO_SUCH_OBJECT: DWORD = 8240;
+pub const ERROR_DS_ALIAS_PROBLEM: DWORD = 8241;
+pub const ERROR_DS_INVALID_DN_SYNTAX: DWORD = 8242;
+pub const ERROR_DS_IS_LEAF: DWORD = 8243;
+pub const ERROR_DS_ALIAS_DEREF_PROBLEM: DWORD = 8244;
+pub const ERROR_DS_UNWILLING_TO_PERFORM: DWORD = 8245;
+pub const ERROR_DS_LOOP_DETECT: DWORD = 8246;
+pub const ERROR_DS_NAMING_VIOLATION: DWORD = 8247;
+pub const ERROR_DS_OBJECT_RESULTS_TOO_LARGE: DWORD = 8248;
+pub const ERROR_DS_AFFECTS_MULTIPLE_DSAS: DWORD = 8249;
+pub const ERROR_DS_SERVER_DOWN: DWORD = 8250;
+pub const ERROR_DS_LOCAL_ERROR: DWORD = 8251;
+pub const ERROR_DS_ENCODING_ERROR: DWORD = 8252;
+pub const ERROR_DS_DECODING_ERROR: DWORD = 8253;
+pub const ERROR_DS_FILTER_UNKNOWN: DWORD = 8254;
+pub const ERROR_DS_PARAM_ERROR: DWORD = 8255;
+pub const ERROR_DS_NOT_SUPPORTED: DWORD = 8256;
+pub const ERROR_DS_NO_RESULTS_RETURNED: DWORD = 8257;
+pub const ERROR_DS_CONTROL_NOT_FOUND: DWORD = 8258;
+pub const ERROR_DS_CLIENT_LOOP: DWORD = 8259;
+pub const ERROR_DS_REFERRAL_LIMIT_EXCEEDED: DWORD = 8260;
+pub const ERROR_DS_SORT_CONTROL_MISSING: DWORD = 8261;
+pub const ERROR_DS_OFFSET_RANGE_ERROR: DWORD = 8262;
+pub const ERROR_DS_ROOT_MUST_BE_NC: DWORD = 8301;
+pub const ERROR_DS_ADD_REPLICA_INHIBITED: DWORD = 8302;
+pub const ERROR_DS_ATT_NOT_DEF_IN_SCHEMA: DWORD = 8303;
+pub const ERROR_DS_MAX_OBJ_SIZE_EXCEEDED: DWORD = 8304;
+pub const ERROR_DS_OBJ_STRING_NAME_EXISTS: DWORD = 8305;
+pub const ERROR_DS_NO_RDN_DEFINED_IN_SCHEMA: DWORD = 8306;
+pub const ERROR_DS_RDN_DOESNT_MATCH_SCHEMA: DWORD = 8307;
+pub const ERROR_DS_NO_REQUESTED_ATTS_FOUND: DWORD = 8308;
+pub const ERROR_DS_USER_BUFFER_TO_SMALL: DWORD = 8309;
+pub const ERROR_DS_ATT_IS_NOT_ON_OBJ: DWORD = 8310;
+pub const ERROR_DS_ILLEGAL_MOD_OPERATION: DWORD = 8311;
+pub const ERROR_DS_OBJ_TOO_LARGE: DWORD = 8312;
+pub const ERROR_DS_BAD_INSTANCE_TYPE: DWORD = 8313;
+pub const ERROR_DS_MASTERDSA_REQUIRED: DWORD = 8314;
+pub const ERROR_DS_OBJECT_CLASS_REQUIRED: DWORD = 8315;
+pub const ERROR_DS_MISSING_REQUIRED_ATT: DWORD = 8316;
+pub const ERROR_DS_ATT_NOT_DEF_FOR_CLASS: DWORD = 8317;
+pub const ERROR_DS_ATT_ALREADY_EXISTS: DWORD = 8318;
+pub const ERROR_DS_CANT_ADD_ATT_VALUES: DWORD = 8320;
+pub const ERROR_DS_SINGLE_VALUE_CONSTRAINT: DWORD = 8321;
+pub const ERROR_DS_RANGE_CONSTRAINT: DWORD = 8322;
+pub const ERROR_DS_ATT_VAL_ALREADY_EXISTS: DWORD = 8323;
+pub const ERROR_DS_CANT_REM_MISSING_ATT: DWORD = 8324;
+pub const ERROR_DS_CANT_REM_MISSING_ATT_VAL: DWORD = 8325;
+pub const ERROR_DS_ROOT_CANT_BE_SUBREF: DWORD = 8326;
+pub const ERROR_DS_NO_CHAINING: DWORD = 8327;
+pub const ERROR_DS_NO_CHAINED_EVAL: DWORD = 8328;
+pub const ERROR_DS_NO_PARENT_OBJECT: DWORD = 8329;
+pub const ERROR_DS_PARENT_IS_AN_ALIAS: DWORD = 8330;
+pub const ERROR_DS_CANT_MIX_MASTER_AND_REPS: DWORD = 8331;
+pub const ERROR_DS_CHILDREN_EXIST: DWORD = 8332;
+pub const ERROR_DS_OBJ_NOT_FOUND: DWORD = 8333;
+pub const ERROR_DS_ALIASED_OBJ_MISSING: DWORD = 8334;
+pub const ERROR_DS_BAD_NAME_SYNTAX: DWORD = 8335;
+pub const ERROR_DS_ALIAS_POINTS_TO_ALIAS: DWORD = 8336;
+pub const ERROR_DS_CANT_DEREF_ALIAS: DWORD = 8337;
+pub const ERROR_DS_OUT_OF_SCOPE: DWORD = 8338;
+pub const ERROR_DS_OBJECT_BEING_REMOVED: DWORD = 8339;
+pub const ERROR_DS_CANT_DELETE_DSA_OBJ: DWORD = 8340;
+pub const ERROR_DS_GENERIC_ERROR: DWORD = 8341;
+pub const ERROR_DS_DSA_MUST_BE_INT_MASTER: DWORD = 8342;
+pub const ERROR_DS_CLASS_NOT_DSA: DWORD = 8343;
+pub const ERROR_DS_INSUFF_ACCESS_RIGHTS: DWORD = 8344;
+pub const ERROR_DS_ILLEGAL_SUPERIOR: DWORD = 8345;
+pub const ERROR_DS_ATTRIBUTE_OWNED_BY_SAM: DWORD = 8346;
+pub const ERROR_DS_NAME_TOO_MANY_PARTS: DWORD = 8347;
+pub const ERROR_DS_NAME_TOO_LONG: DWORD = 8348;
+pub const ERROR_DS_NAME_VALUE_TOO_LONG: DWORD = 8349;
+pub const ERROR_DS_NAME_UNPARSEABLE: DWORD = 8350;
+pub const ERROR_DS_NAME_TYPE_UNKNOWN: DWORD = 8351;
+pub const ERROR_DS_NOT_AN_OBJECT: DWORD = 8352;
+pub const ERROR_DS_SEC_DESC_TOO_SHORT: DWORD = 8353;
+pub const ERROR_DS_SEC_DESC_INVALID: DWORD = 8354;
+pub const ERROR_DS_NO_DELETED_NAME: DWORD = 8355;
+pub const ERROR_DS_SUBREF_MUST_HAVE_PARENT: DWORD = 8356;
+pub const ERROR_DS_NCNAME_MUST_BE_NC: DWORD = 8357;
+pub const ERROR_DS_CANT_ADD_SYSTEM_ONLY: DWORD = 8358;
+pub const ERROR_DS_CLASS_MUST_BE_CONCRETE: DWORD = 8359;
+pub const ERROR_DS_INVALID_DMD: DWORD = 8360;
+pub const ERROR_DS_OBJ_GUID_EXISTS: DWORD = 8361;
+pub const ERROR_DS_NOT_ON_BACKLINK: DWORD = 8362;
+pub const ERROR_DS_NO_CROSSREF_FOR_NC: DWORD = 8363;
+pub const ERROR_DS_SHUTTING_DOWN: DWORD = 8364;
+pub const ERROR_DS_UNKNOWN_OPERATION: DWORD = 8365;
+pub const ERROR_DS_INVALID_ROLE_OWNER: DWORD = 8366;
+pub const ERROR_DS_COULDNT_CONTACT_FSMO: DWORD = 8367;
+pub const ERROR_DS_CROSS_NC_DN_RENAME: DWORD = 8368;
+pub const ERROR_DS_CANT_MOD_SYSTEM_ONLY: DWORD = 8369;
+pub const ERROR_DS_REPLICATOR_ONLY: DWORD = 8370;
+pub const ERROR_DS_OBJ_CLASS_NOT_DEFINED: DWORD = 8371;
+pub const ERROR_DS_OBJ_CLASS_NOT_SUBCLASS: DWORD = 8372;
+pub const ERROR_DS_NAME_REFERENCE_INVALID: DWORD = 8373;
+pub const ERROR_DS_CROSS_REF_EXISTS: DWORD = 8374;
+pub const ERROR_DS_CANT_DEL_MASTER_CROSSREF: DWORD = 8375;
+pub const ERROR_DS_SUBTREE_NOTIFY_NOT_NC_HEAD: DWORD = 8376;
+pub const ERROR_DS_NOTIFY_FILTER_TOO_COMPLEX: DWORD = 8377;
+pub const ERROR_DS_DUP_RDN: DWORD = 8378;
+pub const ERROR_DS_DUP_OID: DWORD = 8379;
+pub const ERROR_DS_DUP_MAPI_ID: DWORD = 8380;
+pub const ERROR_DS_DUP_SCHEMA_ID_GUID: DWORD = 8381;
+pub const ERROR_DS_DUP_LDAP_DISPLAY_NAME: DWORD = 8382;
+pub const ERROR_DS_SEMANTIC_ATT_TEST: DWORD = 8383;
+pub const ERROR_DS_SYNTAX_MISMATCH: DWORD = 8384;
+pub const ERROR_DS_EXISTS_IN_MUST_HAVE: DWORD = 8385;
+pub const ERROR_DS_EXISTS_IN_MAY_HAVE: DWORD = 8386;
+pub const ERROR_DS_NONEXISTENT_MAY_HAVE: DWORD = 8387;
+pub const ERROR_DS_NONEXISTENT_MUST_HAVE: DWORD = 8388;
+pub const ERROR_DS_AUX_CLS_TEST_FAIL: DWORD = 8389;
+pub const ERROR_DS_NONEXISTENT_POSS_SUP: DWORD = 8390;
+pub const ERROR_DS_SUB_CLS_TEST_FAIL: DWORD = 8391;
+pub const ERROR_DS_BAD_RDN_ATT_ID_SYNTAX: DWORD = 8392;
+pub const ERROR_DS_EXISTS_IN_AUX_CLS: DWORD = 8393;
+pub const ERROR_DS_EXISTS_IN_SUB_CLS: DWORD = 8394;
+pub const ERROR_DS_EXISTS_IN_POSS_SUP: DWORD = 8395;
+pub const ERROR_DS_RECALCSCHEMA_FAILED: DWORD = 8396;
+pub const ERROR_DS_TREE_DELETE_NOT_FINISHED: DWORD = 8397;
+pub const ERROR_DS_CANT_DELETE: DWORD = 8398;
+pub const ERROR_DS_ATT_SCHEMA_REQ_ID: DWORD = 8399;
+pub const ERROR_DS_BAD_ATT_SCHEMA_SYNTAX: DWORD = 8400;
+pub const ERROR_DS_CANT_CACHE_ATT: DWORD = 8401;
+pub const ERROR_DS_CANT_CACHE_CLASS: DWORD = 8402;
+pub const ERROR_DS_CANT_REMOVE_ATT_CACHE: DWORD = 8403;
+pub const ERROR_DS_CANT_REMOVE_CLASS_CACHE: DWORD = 8404;
+pub const ERROR_DS_CANT_RETRIEVE_DN: DWORD = 8405;
+pub const ERROR_DS_MISSING_SUPREF: DWORD = 8406;
+pub const ERROR_DS_CANT_RETRIEVE_INSTANCE: DWORD = 8407;
+pub const ERROR_DS_CODE_INCONSISTENCY: DWORD = 8408;
+pub const ERROR_DS_DATABASE_ERROR: DWORD = 8409;
+pub const ERROR_DS_GOVERNSID_MISSING: DWORD = 8410;
+pub const ERROR_DS_MISSING_EXPECTED_ATT: DWORD = 8411;
+pub const ERROR_DS_NCNAME_MISSING_CR_REF: DWORD = 8412;
+pub const ERROR_DS_SECURITY_CHECKING_ERROR: DWORD = 8413;
+pub const ERROR_DS_SCHEMA_NOT_LOADED: DWORD = 8414;
+pub const ERROR_DS_SCHEMA_ALLOC_FAILED: DWORD = 8415;
+pub const ERROR_DS_ATT_SCHEMA_REQ_SYNTAX: DWORD = 8416;
+pub const ERROR_DS_GCVERIFY_ERROR: DWORD = 8417;
+pub const ERROR_DS_DRA_SCHEMA_MISMATCH: DWORD = 8418;
+pub const ERROR_DS_CANT_FIND_DSA_OBJ: DWORD = 8419;
+pub const ERROR_DS_CANT_FIND_EXPECTED_NC: DWORD = 8420;
+pub const ERROR_DS_CANT_FIND_NC_IN_CACHE: DWORD = 8421;
+pub const ERROR_DS_CANT_RETRIEVE_CHILD: DWORD = 8422;
+pub const ERROR_DS_SECURITY_ILLEGAL_MODIFY: DWORD = 8423;
+pub const ERROR_DS_CANT_REPLACE_HIDDEN_REC: DWORD = 8424;
+pub const ERROR_DS_BAD_HIERARCHY_FILE: DWORD = 8425;
+pub const ERROR_DS_BUILD_HIERARCHY_TABLE_FAILED: DWORD = 8426;
+pub const ERROR_DS_CONFIG_PARAM_MISSING: DWORD = 8427;
+pub const ERROR_DS_COUNTING_AB_INDICES_FAILED: DWORD = 8428;
+pub const ERROR_DS_HIERARCHY_TABLE_MALLOC_FAILED: DWORD = 8429;
+pub const ERROR_DS_INTERNAL_FAILURE: DWORD = 8430;
+pub const ERROR_DS_UNKNOWN_ERROR: DWORD = 8431;
+pub const ERROR_DS_ROOT_REQUIRES_CLASS_TOP: DWORD = 8432;
+pub const ERROR_DS_REFUSING_FSMO_ROLES: DWORD = 8433;
+pub const ERROR_DS_MISSING_FSMO_SETTINGS: DWORD = 8434;
+pub const ERROR_DS_UNABLE_TO_SURRENDER_ROLES: DWORD = 8435;
+pub const ERROR_DS_DRA_GENERIC: DWORD = 8436;
+pub const ERROR_DS_DRA_INVALID_PARAMETER: DWORD = 8437;
+pub const ERROR_DS_DRA_BUSY: DWORD = 8438;
+pub const ERROR_DS_DRA_BAD_DN: DWORD = 8439;
+pub const ERROR_DS_DRA_BAD_NC: DWORD = 8440;
+pub const ERROR_DS_DRA_DN_EXISTS: DWORD = 8441;
+pub const ERROR_DS_DRA_INTERNAL_ERROR: DWORD = 8442;
+pub const ERROR_DS_DRA_INCONSISTENT_DIT: DWORD = 8443;
+pub const ERROR_DS_DRA_CONNECTION_FAILED: DWORD = 8444;
+pub const ERROR_DS_DRA_BAD_INSTANCE_TYPE: DWORD = 8445;
+pub const ERROR_DS_DRA_OUT_OF_MEM: DWORD = 8446;
+pub const ERROR_DS_DRA_MAIL_PROBLEM: DWORD = 8447;
+pub const ERROR_DS_DRA_REF_ALREADY_EXISTS: DWORD = 8448;
+pub const ERROR_DS_DRA_REF_NOT_FOUND: DWORD = 8449;
+pub const ERROR_DS_DRA_OBJ_IS_REP_SOURCE: DWORD = 8450;
+pub const ERROR_DS_DRA_DB_ERROR: DWORD = 8451;
+pub const ERROR_DS_DRA_NO_REPLICA: DWORD = 8452;
+pub const ERROR_DS_DRA_ACCESS_DENIED: DWORD = 8453;
+pub const ERROR_DS_DRA_NOT_SUPPORTED: DWORD = 8454;
+pub const ERROR_DS_DRA_RPC_CANCELLED: DWORD = 8455;
+pub const ERROR_DS_DRA_SOURCE_DISABLED: DWORD = 8456;
+pub const ERROR_DS_DRA_SINK_DISABLED: DWORD = 8457;
+pub const ERROR_DS_DRA_NAME_COLLISION: DWORD = 8458;
+pub const ERROR_DS_DRA_SOURCE_REINSTALLED: DWORD = 8459;
+pub const ERROR_DS_DRA_MISSING_PARENT: DWORD = 8460;
+pub const ERROR_DS_DRA_PREEMPTED: DWORD = 8461;
+pub const ERROR_DS_DRA_ABANDON_SYNC: DWORD = 8462;
+pub const ERROR_DS_DRA_SHUTDOWN: DWORD = 8463;
+pub const ERROR_DS_DRA_INCOMPATIBLE_PARTIAL_SET: DWORD = 8464;
+pub const ERROR_DS_DRA_SOURCE_IS_PARTIAL_REPLICA: DWORD = 8465;
+pub const ERROR_DS_DRA_EXTN_CONNECTION_FAILED: DWORD = 8466;
+pub const ERROR_DS_INSTALL_SCHEMA_MISMATCH: DWORD = 8467;
+pub const ERROR_DS_DUP_LINK_ID: DWORD = 8468;
+pub const ERROR_DS_NAME_ERROR_RESOLVING: DWORD = 8469;
+pub const ERROR_DS_NAME_ERROR_NOT_FOUND: DWORD = 8470;
+pub const ERROR_DS_NAME_ERROR_NOT_UNIQUE: DWORD = 8471;
+pub const ERROR_DS_NAME_ERROR_NO_MAPPING: DWORD = 8472;
+pub const ERROR_DS_NAME_ERROR_DOMAIN_ONLY: DWORD = 8473;
+pub const ERROR_DS_NAME_ERROR_NO_SYNTACTICAL_MAPPING: DWORD = 8474;
+pub const ERROR_DS_CONSTRUCTED_ATT_MOD: DWORD = 8475;
+pub const ERROR_DS_WRONG_OM_OBJ_CLASS: DWORD = 8476;
+pub const ERROR_DS_DRA_REPL_PENDING: DWORD = 8477;
+pub const ERROR_DS_DS_REQUIRED: DWORD = 8478;
+pub const ERROR_DS_INVALID_LDAP_DISPLAY_NAME: DWORD = 8479;
+pub const ERROR_DS_NON_BASE_SEARCH: DWORD = 8480;
+pub const ERROR_DS_CANT_RETRIEVE_ATTS: DWORD = 8481;
+pub const ERROR_DS_BACKLINK_WITHOUT_LINK: DWORD = 8482;
+pub const ERROR_DS_EPOCH_MISMATCH: DWORD = 8483;
+pub const ERROR_DS_SRC_NAME_MISMATCH: DWORD = 8484;
+pub const ERROR_DS_SRC_AND_DST_NC_IDENTICAL: DWORD = 8485;
+pub const ERROR_DS_DST_NC_MISMATCH: DWORD = 8486;
+pub const ERROR_DS_NOT_AUTHORITIVE_FOR_DST_NC: DWORD = 8487;
+pub const ERROR_DS_SRC_GUID_MISMATCH: DWORD = 8488;
+pub const ERROR_DS_CANT_MOVE_DELETED_OBJECT: DWORD = 8489;
+pub const ERROR_DS_PDC_OPERATION_IN_PROGRESS: DWORD = 8490;
+pub const ERROR_DS_CROSS_DOMAIN_CLEANUP_REQD: DWORD = 8491;
+pub const ERROR_DS_ILLEGAL_XDOM_MOVE_OPERATION: DWORD = 8492;
+pub const ERROR_DS_CANT_WITH_ACCT_GROUP_MEMBERSHPS: DWORD = 8493;
+pub const ERROR_DS_NC_MUST_HAVE_NC_PARENT: DWORD = 8494;
+pub const ERROR_DS_CR_IMPOSSIBLE_TO_VALIDATE: DWORD = 8495;
+pub const ERROR_DS_DST_DOMAIN_NOT_NATIVE: DWORD = 8496;
+pub const ERROR_DS_MISSING_INFRASTRUCTURE_CONTAINER: DWORD = 8497;
+pub const ERROR_DS_CANT_MOVE_ACCOUNT_GROUP: DWORD = 8498;
+pub const ERROR_DS_CANT_MOVE_RESOURCE_GROUP: DWORD = 8499;
+pub const ERROR_DS_INVALID_SEARCH_FLAG: DWORD = 8500;
+pub const ERROR_DS_NO_TREE_DELETE_ABOVE_NC: DWORD = 8501;
+pub const ERROR_DS_COULDNT_LOCK_TREE_FOR_DELETE: DWORD = 8502;
+pub const ERROR_DS_COULDNT_IDENTIFY_OBJECTS_FOR_TREE_DELETE: DWORD = 8503;
+pub const ERROR_DS_SAM_INIT_FAILURE: DWORD = 8504;
+pub const ERROR_DS_SENSITIVE_GROUP_VIOLATION: DWORD = 8505;
+pub const ERROR_DS_CANT_MOD_PRIMARYGROUPID: DWORD = 8506;
+pub const ERROR_DS_ILLEGAL_BASE_SCHEMA_MOD: DWORD = 8507;
+pub const ERROR_DS_NONSAFE_SCHEMA_CHANGE: DWORD = 8508;
+pub const ERROR_DS_SCHEMA_UPDATE_DISALLOWED: DWORD = 8509;
+pub const ERROR_DS_CANT_CREATE_UNDER_SCHEMA: DWORD = 8510;
+pub const ERROR_DS_INSTALL_NO_SRC_SCH_VERSION: DWORD = 8511;
+pub const ERROR_DS_INSTALL_NO_SCH_VERSION_IN_INIFILE: DWORD = 8512;
+pub const ERROR_DS_INVALID_GROUP_TYPE: DWORD = 8513;
+pub const ERROR_DS_NO_NEST_GLOBALGROUP_IN_MIXEDDOMAIN: DWORD = 8514;
+pub const ERROR_DS_NO_NEST_LOCALGROUP_IN_MIXEDDOMAIN: DWORD = 8515;
+pub const ERROR_DS_GLOBAL_CANT_HAVE_LOCAL_MEMBER: DWORD = 8516;
+pub const ERROR_DS_GLOBAL_CANT_HAVE_UNIVERSAL_MEMBER: DWORD = 8517;
+pub const ERROR_DS_UNIVERSAL_CANT_HAVE_LOCAL_MEMBER: DWORD = 8518;
+pub const ERROR_DS_GLOBAL_CANT_HAVE_CROSSDOMAIN_MEMBER: DWORD = 8519;
+pub const ERROR_DS_LOCAL_CANT_HAVE_CROSSDOMAIN_LOCAL_MEMBER: DWORD = 8520;
+pub const ERROR_DS_HAVE_PRIMARY_MEMBERS: DWORD = 8521;
+pub const ERROR_DS_STRING_SD_CONVERSION_FAILED: DWORD = 8522;
+pub const ERROR_DS_NAMING_MASTER_GC: DWORD = 8523;
+pub const ERROR_DS_DNS_LOOKUP_FAILURE: DWORD = 8524;
+pub const ERROR_DS_COULDNT_UPDATE_SPNS: DWORD = 8525;
+pub const ERROR_DS_CANT_RETRIEVE_SD: DWORD = 8526;
+pub const ERROR_DS_KEY_NOT_UNIQUE: DWORD = 8527;
+pub const ERROR_DS_WRONG_LINKED_ATT_SYNTAX: DWORD = 8528;
+pub const ERROR_DS_SAM_NEED_BOOTKEY_PASSWORD: DWORD = 8529;
+pub const ERROR_DS_SAM_NEED_BOOTKEY_FLOPPY: DWORD = 8530;
+pub const ERROR_DS_CANT_START: DWORD = 8531;
+pub const ERROR_DS_INIT_FAILURE: DWORD = 8532;
+pub const ERROR_DS_NO_PKT_PRIVACY_ON_CONNECTION: DWORD = 8533;
+pub const ERROR_DS_SOURCE_DOMAIN_IN_FOREST: DWORD = 8534;
+pub const ERROR_DS_DESTINATION_DOMAIN_NOT_IN_FOREST: DWORD = 8535;
+pub const ERROR_DS_DESTINATION_AUDITING_NOT_ENABLED: DWORD = 8536;
+pub const ERROR_DS_CANT_FIND_DC_FOR_SRC_DOMAIN: DWORD = 8537;
+pub const ERROR_DS_SRC_OBJ_NOT_GROUP_OR_USER: DWORD = 8538;
+pub const ERROR_DS_SRC_SID_EXISTS_IN_FOREST: DWORD = 8539;
+pub const ERROR_DS_SRC_AND_DST_OBJECT_CLASS_MISMATCH: DWORD = 8540;
+pub const ERROR_SAM_INIT_FAILURE: DWORD = 8541;
+pub const ERROR_DS_DRA_SCHEMA_INFO_SHIP: DWORD = 8542;
+pub const ERROR_DS_DRA_SCHEMA_CONFLICT: DWORD = 8543;
+pub const ERROR_DS_DRA_EARLIER_SCHEMA_CONFLICT: DWORD = 8544;
+pub const ERROR_DS_DRA_OBJ_NC_MISMATCH: DWORD = 8545;
+pub const ERROR_DS_NC_STILL_HAS_DSAS: DWORD = 8546;
+pub const ERROR_DS_GC_REQUIRED: DWORD = 8547;
+pub const ERROR_DS_LOCAL_MEMBER_OF_LOCAL_ONLY: DWORD = 8548;
+pub const ERROR_DS_NO_FPO_IN_UNIVERSAL_GROUPS: DWORD = 8549;
+pub const ERROR_DS_CANT_ADD_TO_GC: DWORD = 8550;
+pub const ERROR_DS_NO_CHECKPOINT_WITH_PDC: DWORD = 8551;
+pub const ERROR_DS_SOURCE_AUDITING_NOT_ENABLED: DWORD = 8552;
+pub const ERROR_DS_CANT_CREATE_IN_NONDOMAIN_NC: DWORD = 8553;
+pub const ERROR_DS_INVALID_NAME_FOR_SPN: DWORD = 8554;
+pub const ERROR_DS_FILTER_USES_CONTRUCTED_ATTRS: DWORD = 8555;
+pub const ERROR_DS_UNICODEPWD_NOT_IN_QUOTES: DWORD = 8556;
+pub const ERROR_DS_MACHINE_ACCOUNT_QUOTA_EXCEEDED: DWORD = 8557;
+pub const ERROR_DS_MUST_BE_RUN_ON_DST_DC: DWORD = 8558;
+pub const ERROR_DS_SRC_DC_MUST_BE_SP4_OR_GREATER: DWORD = 8559;
+pub const ERROR_DS_CANT_TREE_DELETE_CRITICAL_OBJ: DWORD = 8560;
+pub const ERROR_DS_INIT_FAILURE_CONSOLE: DWORD = 8561;
+pub const ERROR_DS_SAM_INIT_FAILURE_CONSOLE: DWORD = 8562;
+pub const ERROR_DS_FOREST_VERSION_TOO_HIGH: DWORD = 8563;
+pub const ERROR_DS_DOMAIN_VERSION_TOO_HIGH: DWORD = 8564;
+pub const ERROR_DS_FOREST_VERSION_TOO_LOW: DWORD = 8565;
+pub const ERROR_DS_DOMAIN_VERSION_TOO_LOW: DWORD = 8566;
+pub const ERROR_DS_INCOMPATIBLE_VERSION: DWORD = 8567;
+pub const ERROR_DS_LOW_DSA_VERSION: DWORD = 8568;
+pub const ERROR_DS_NO_BEHAVIOR_VERSION_IN_MIXEDDOMAIN: DWORD = 8569;
+pub const ERROR_DS_NOT_SUPPORTED_SORT_ORDER: DWORD = 8570;
+pub const ERROR_DS_NAME_NOT_UNIQUE: DWORD = 8571;
+pub const ERROR_DS_MACHINE_ACCOUNT_CREATED_PRENT4: DWORD = 8572;
+pub const ERROR_DS_OUT_OF_VERSION_STORE: DWORD = 8573;
+pub const ERROR_DS_INCOMPATIBLE_CONTROLS_USED: DWORD = 8574;
+pub const ERROR_DS_NO_REF_DOMAIN: DWORD = 8575;
+pub const ERROR_DS_RESERVED_LINK_ID: DWORD = 8576;
+pub const ERROR_DS_LINK_ID_NOT_AVAILABLE: DWORD = 8577;
+pub const ERROR_DS_AG_CANT_HAVE_UNIVERSAL_MEMBER: DWORD = 8578;
+pub const ERROR_DS_MODIFYDN_DISALLOWED_BY_INSTANCE_TYPE: DWORD = 8579;
+pub const ERROR_DS_NO_OBJECT_MOVE_IN_SCHEMA_NC: DWORD = 8580;
+pub const ERROR_DS_MODIFYDN_DISALLOWED_BY_FLAG: DWORD = 8581;
+pub const ERROR_DS_MODIFYDN_WRONG_GRANDPARENT: DWORD = 8582;
+pub const ERROR_DS_NAME_ERROR_TRUST_REFERRAL: DWORD = 8583;
+pub const ERROR_NOT_SUPPORTED_ON_STANDARD_SERVER: DWORD = 8584;
+pub const ERROR_DS_CANT_ACCESS_REMOTE_PART_OF_AD: DWORD = 8585;
+pub const ERROR_DS_CR_IMPOSSIBLE_TO_VALIDATE_V2: DWORD = 8586;
+pub const ERROR_DS_THREAD_LIMIT_EXCEEDED: DWORD = 8587;
+pub const ERROR_DS_NOT_CLOSEST: DWORD = 8588;
+pub const ERROR_DS_CANT_DERIVE_SPN_WITHOUT_SERVER_REF: DWORD = 8589;
+pub const ERROR_DS_SINGLE_USER_MODE_FAILED: DWORD = 8590;
+pub const ERROR_DS_NTDSCRIPT_SYNTAX_ERROR: DWORD = 8591;
+pub const ERROR_DS_NTDSCRIPT_PROCESS_ERROR: DWORD = 8592;
+pub const ERROR_DS_DIFFERENT_REPL_EPOCHS: DWORD = 8593;
+pub const ERROR_DS_DRS_EXTENSIONS_CHANGED: DWORD = 8594;
+pub const ERROR_DS_REPLICA_SET_CHANGE_NOT_ALLOWED_ON_DISABLED_CR: DWORD = 8595;
+pub const ERROR_DS_NO_MSDS_INTID: DWORD = 8596;
+pub const ERROR_DS_DUP_MSDS_INTID: DWORD = 8597;
+pub const ERROR_DS_EXISTS_IN_RDNATTID: DWORD = 8598;
+pub const ERROR_DS_AUTHORIZATION_FAILED: DWORD = 8599;
+pub const ERROR_DS_INVALID_SCRIPT: DWORD = 8600;
+pub const ERROR_DS_REMOTE_CROSSREF_OP_FAILED: DWORD = 8601;
+pub const ERROR_DS_CROSS_REF_BUSY: DWORD = 8602;
+pub const ERROR_DS_CANT_DERIVE_SPN_FOR_DELETED_DOMAIN: DWORD = 8603;
+pub const ERROR_DS_CANT_DEMOTE_WITH_WRITEABLE_NC: DWORD = 8604;
+pub const ERROR_DS_DUPLICATE_ID_FOUND: DWORD = 8605;
+pub const ERROR_DS_INSUFFICIENT_ATTR_TO_CREATE_OBJECT: DWORD = 8606;
+pub const ERROR_DS_GROUP_CONVERSION_ERROR: DWORD = 8607;
+pub const ERROR_DS_CANT_MOVE_APP_BASIC_GROUP: DWORD = 8608;
+pub const ERROR_DS_CANT_MOVE_APP_QUERY_GROUP: DWORD = 8609;
+pub const ERROR_DS_ROLE_NOT_VERIFIED: DWORD = 8610;
+pub const ERROR_DS_WKO_CONTAINER_CANNOT_BE_SPECIAL: DWORD = 8611;
+pub const ERROR_DS_DOMAIN_RENAME_IN_PROGRESS: DWORD = 8612;
+pub const ERROR_DS_EXISTING_AD_CHILD_NC: DWORD = 8613;
+pub const ERROR_DS_REPL_LIFETIME_EXCEEDED: DWORD = 8614;
+pub const ERROR_DS_DISALLOWED_IN_SYSTEM_CONTAINER: DWORD = 8615;
+pub const ERROR_DS_LDAP_SEND_QUEUE_FULL: DWORD = 8616;
+pub const ERROR_DS_DRA_OUT_SCHEDULE_WINDOW: DWORD = 8617;
+pub const ERROR_SXS_SECTION_NOT_FOUND: DWORD = 14000;
+pub const ERROR_SXS_CANT_GEN_ACTCTX: DWORD = 14001;
+pub const ERROR_SXS_INVALID_ACTCTXDATA_FORMAT: DWORD = 14002;
+pub const ERROR_SXS_ASSEMBLY_NOT_FOUND: DWORD = 14003;
+pub const ERROR_SXS_MANIFEST_FORMAT_ERROR: DWORD = 14004;
+pub const ERROR_SXS_MANIFEST_PARSE_ERROR: DWORD = 14005;
+pub const ERROR_SXS_ACTIVATION_CONTEXT_DISABLED: DWORD = 14006;
+pub const ERROR_SXS_KEY_NOT_FOUND: DWORD = 14007;
+pub const ERROR_SXS_VERSION_CONFLICT: DWORD = 14008;
+pub const ERROR_SXS_WRONG_SECTION_TYPE: DWORD = 14009;
+pub const ERROR_SXS_THREAD_QUERIES_DISABLED: DWORD = 14010;
+pub const ERROR_SXS_PROCESS_DEFAULT_ALREADY_SET: DWORD = 14011;
+pub const ERROR_SXS_UNKNOWN_ENCODING_GROUP: DWORD = 14012;
+pub const ERROR_SXS_UNKNOWN_ENCODING: DWORD = 14013;
+pub const ERROR_SXS_INVALID_XML_NAMESPACE_URI: DWORD = 14014;
+pub const ERROR_SXS_ROOT_MANIFEST_DEPENDENCY_NOT_INSTALLED: DWORD = 14015;
+pub const ERROR_SXS_LEAF_MANIFEST_DEPENDENCY_NOT_INSTALLED: DWORD = 14016;
+pub const ERROR_SXS_INVALID_ASSEMBLY_IDENTITY_ATTRIBUTE: DWORD = 14017;
+pub const ERROR_SXS_MANIFEST_MISSING_REQUIRED_DEFAULT_NAMESPACE: DWORD = 14018;
+pub const ERROR_SXS_MANIFEST_INVALID_REQUIRED_DEFAULT_NAMESPACE: DWORD = 14019;
+pub const ERROR_SXS_PRIVATE_MANIFEST_CROSS_PATH_WITH_REPARSE_POINT: DWORD = 14020;
+pub const ERROR_SXS_DUPLICATE_DLL_NAME: DWORD = 14021;
+pub const ERROR_SXS_DUPLICATE_WINDOWCLASS_NAME: DWORD = 14022;
+pub const ERROR_SXS_DUPLICATE_CLSID: DWORD = 14023;
+pub const ERROR_SXS_DUPLICATE_IID: DWORD = 14024;
+pub const ERROR_SXS_DUPLICATE_TLBID: DWORD = 14025;
+pub const ERROR_SXS_DUPLICATE_PROGID: DWORD = 14026;
+pub const ERROR_SXS_DUPLICATE_ASSEMBLY_NAME: DWORD = 14027;
+pub const ERROR_SXS_FILE_HASH_MISMATCH: DWORD = 14028;
+pub const ERROR_SXS_POLICY_PARSE_ERROR: DWORD = 14029;
+pub const ERROR_SXS_XML_E_MISSINGQUOTE: DWORD = 14030;
+pub const ERROR_SXS_XML_E_COMMENTSYNTAX: DWORD = 14031;
+pub const ERROR_SXS_XML_E_BADSTARTNAMECHAR: DWORD = 14032;
+pub const ERROR_SXS_XML_E_BADNAMECHAR: DWORD = 14033;
+pub const ERROR_SXS_XML_E_BADCHARINSTRING: DWORD = 14034;
+pub const ERROR_SXS_XML_E_XMLDECLSYNTAX: DWORD = 14035;
+pub const ERROR_SXS_XML_E_BADCHARDATA: DWORD = 14036;
+pub const ERROR_SXS_XML_E_MISSINGWHITESPACE: DWORD = 14037;
+pub const ERROR_SXS_XML_E_EXPECTINGTAGEND: DWORD = 14038;
+pub const ERROR_SXS_XML_E_MISSINGSEMICOLON: DWORD = 14039;
+pub const ERROR_SXS_XML_E_UNBALANCEDPAREN: DWORD = 14040;
+pub const ERROR_SXS_XML_E_INTERNALERROR: DWORD = 14041;
+pub const ERROR_SXS_XML_E_UNEXPECTED_WHITESPACE: DWORD = 14042;
+pub const ERROR_SXS_XML_E_INCOMPLETE_ENCODING: DWORD = 14043;
+pub const ERROR_SXS_XML_E_MISSING_PAREN: DWORD = 14044;
+pub const ERROR_SXS_XML_E_EXPECTINGCLOSEQUOTE: DWORD = 14045;
+pub const ERROR_SXS_XML_E_MULTIPLE_COLONS: DWORD = 14046;
+pub const ERROR_SXS_XML_E_INVALID_DECIMAL: DWORD = 14047;
+pub const ERROR_SXS_XML_E_INVALID_HEXIDECIMAL: DWORD = 14048;
+pub const ERROR_SXS_XML_E_INVALID_UNICODE: DWORD = 14049;
+pub const ERROR_SXS_XML_E_WHITESPACEORQUESTIONMARK: DWORD = 14050;
+pub const ERROR_SXS_XML_E_UNEXPECTEDENDTAG: DWORD = 14051;
+pub const ERROR_SXS_XML_E_UNCLOSEDTAG: DWORD = 14052;
+pub const ERROR_SXS_XML_E_DUPLICATEATTRIBUTE: DWORD = 14053;
+pub const ERROR_SXS_XML_E_MULTIPLEROOTS: DWORD = 14054;
+pub const ERROR_SXS_XML_E_INVALIDATROOTLEVEL: DWORD = 14055;
+pub const ERROR_SXS_XML_E_BADXMLDECL: DWORD = 14056;
+pub const ERROR_SXS_XML_E_MISSINGROOT: DWORD = 14057;
+pub const ERROR_SXS_XML_E_UNEXPECTEDEOF: DWORD = 14058;
+pub const ERROR_SXS_XML_E_BADPEREFINSUBSET: DWORD = 14059;
+pub const ERROR_SXS_XML_E_UNCLOSEDSTARTTAG: DWORD = 14060;
+pub const ERROR_SXS_XML_E_UNCLOSEDENDTAG: DWORD = 14061;
+pub const ERROR_SXS_XML_E_UNCLOSEDSTRING: DWORD = 14062;
+pub const ERROR_SXS_XML_E_UNCLOSEDCOMMENT: DWORD = 14063;
+pub const ERROR_SXS_XML_E_UNCLOSEDDECL: DWORD = 14064;
+pub const ERROR_SXS_XML_E_UNCLOSEDCDATA: DWORD = 14065;
+pub const ERROR_SXS_XML_E_RESERVEDNAMESPACE: DWORD = 14066;
+pub const ERROR_SXS_XML_E_INVALIDENCODING: DWORD = 14067;
+pub const ERROR_SXS_XML_E_INVALIDSWITCH: DWORD = 14068;
+pub const ERROR_SXS_XML_E_BADXMLCASE: DWORD = 14069;
+pub const ERROR_SXS_XML_E_INVALID_STANDALONE: DWORD = 14070;
+pub const ERROR_SXS_XML_E_UNEXPECTED_STANDALONE: DWORD = 14071;
+pub const ERROR_SXS_XML_E_INVALID_VERSION: DWORD = 14072;
+pub const ERROR_SXS_XML_E_MISSINGEQUALS: DWORD = 14073;
+pub const ERROR_SXS_PROTECTION_RECOVERY_FAILED: DWORD = 14074;
+pub const ERROR_SXS_PROTECTION_PUBLIC_KEY_TOO_SHORT: DWORD = 14075;
+pub const ERROR_SXS_PROTECTION_CATALOG_NOT_VALID: DWORD = 14076;
+pub const ERROR_SXS_UNTRANSLATABLE_HRESULT: DWORD = 14077;
+pub const ERROR_SXS_PROTECTION_CATALOG_FILE_MISSING: DWORD = 14078;
+pub const ERROR_SXS_MISSING_ASSEMBLY_IDENTITY_ATTRIBUTE: DWORD = 14079;
+pub const ERROR_SXS_INVALID_ASSEMBLY_IDENTITY_ATTRIBUTE_NAME: DWORD = 14080;
+pub const ERROR_SXS_ASSEMBLY_MISSING: DWORD = 14081;
+pub const ERROR_SXS_CORRUPT_ACTIVATION_STACK: DWORD = 14082;
+pub const ERROR_SXS_CORRUPTION: DWORD = 14083;
+pub const ERROR_SXS_EARLY_DEACTIVATION: DWORD = 14084;
+pub const ERROR_SXS_INVALID_DEACTIVATION: DWORD = 14085;
+pub const ERROR_SXS_MULTIPLE_DEACTIVATION: DWORD = 14086;
+pub const ERROR_SXS_PROCESS_TERMINATION_REQUESTED: DWORD = 14087;
+pub const ERROR_SXS_RELEASE_ACTIVATION_CONTEXT: DWORD = 14088;
+pub const ERROR_SXS_SYSTEM_DEFAULT_ACTIVATION_CONTEXT_EMPTY: DWORD = 14089;
+pub const ERROR_SXS_INVALID_IDENTITY_ATTRIBUTE_VALUE: DWORD = 14090;
+pub const ERROR_SXS_INVALID_IDENTITY_ATTRIBUTE_NAME: DWORD = 14091;
+pub const ERROR_SXS_IDENTITY_DUPLICATE_ATTRIBUTE: DWORD = 14092;
+pub const ERROR_SXS_IDENTITY_PARSE_ERROR: DWORD = 14093;
+pub const ERROR_MALFORMED_SUBSTITUTION_STRING: DWORD = 14094;
+pub const ERROR_SXS_INCORRECT_PUBLIC_KEY_TOKEN: DWORD = 14095;
+pub const ERROR_UNMAPPED_SUBSTITUTION_STRING: DWORD = 14096;
+pub const ERROR_SXS_ASSEMBLY_NOT_LOCKED: DWORD = 14097;
+pub const ERROR_SXS_COMPONENT_STORE_CORRUPT: DWORD = 14098;
+pub const ERROR_ADVANCED_INSTALLER_FAILED: DWORD = 14099;
+pub const ERROR_XML_ENCODING_MISMATCH: DWORD = 14100;
+pub const ERROR_SXS_MANIFEST_IDENTITY_SAME_BUT_CONTENTS_DIFFERENT: DWORD = 14101;
+pub const ERROR_SXS_IDENTITIES_DIFFERENT: DWORD = 14102;
+pub const ERROR_SXS_ASSEMBLY_IS_NOT_A_DEPLOYMENT: DWORD = 14103;
+pub const ERROR_SXS_FILE_NOT_PART_OF_ASSEMBLY: DWORD = 14104;
+pub const ERROR_SXS_MANIFEST_TOO_BIG: DWORD = 14105;
+pub const ERROR_SXS_SETTING_NOT_REGISTERED: DWORD = 14106;
+pub const ERROR_SXS_TRANSACTION_CLOSURE_INCOMPLETE: DWORD = 14107;
+pub const ERROR_SMI_PRIMITIVE_INSTALLER_FAILED: DWORD = 14108;
+pub const ERROR_GENERIC_COMMAND_FAILED: DWORD = 14109;
+pub const ERROR_SXS_FILE_HASH_MISSING: DWORD = 14110;
+pub const ERROR_IPSEC_QM_POLICY_EXISTS: DWORD = 13000;
+pub const ERROR_IPSEC_QM_POLICY_NOT_FOUND: DWORD = 13001;
+pub const ERROR_IPSEC_QM_POLICY_IN_USE: DWORD = 13002;
+pub const ERROR_IPSEC_MM_POLICY_EXISTS: DWORD = 13003;
+pub const ERROR_IPSEC_MM_POLICY_NOT_FOUND: DWORD = 13004;
+pub const ERROR_IPSEC_MM_POLICY_IN_USE: DWORD = 13005;
+pub const ERROR_IPSEC_MM_FILTER_EXISTS: DWORD = 13006;
+pub const ERROR_IPSEC_MM_FILTER_NOT_FOUND: DWORD = 13007;
+pub const ERROR_IPSEC_TRANSPORT_FILTER_EXISTS: DWORD = 13008;
+pub const ERROR_IPSEC_TRANSPORT_FILTER_NOT_FOUND: DWORD = 13009;
+pub const ERROR_IPSEC_MM_AUTH_EXISTS: DWORD = 13010;
+pub const ERROR_IPSEC_MM_AUTH_NOT_FOUND: DWORD = 13011;
+pub const ERROR_IPSEC_MM_AUTH_IN_USE: DWORD = 13012;
+pub const ERROR_IPSEC_DEFAULT_MM_POLICY_NOT_FOUND: DWORD = 13013;
+pub const ERROR_IPSEC_DEFAULT_MM_AUTH_NOT_FOUND: DWORD = 13014;
+pub const ERROR_IPSEC_DEFAULT_QM_POLICY_NOT_FOUND: DWORD = 13015;
+pub const ERROR_IPSEC_TUNNEL_FILTER_EXISTS: DWORD = 13016;
+pub const ERROR_IPSEC_TUNNEL_FILTER_NOT_FOUND: DWORD = 13017;
+pub const ERROR_IPSEC_MM_FILTER_PENDING_DELETION: DWORD = 13018;
+pub const ERROR_IPSEC_TRANSPORT_FILTER_PENDING_DELETION: DWORD = 13019;
+pub const ERROR_IPSEC_TUNNEL_FILTER_PENDING_DELETION: DWORD = 13020;
+pub const ERROR_IPSEC_MM_POLICY_PENDING_DELETION: DWORD = 13021;
+pub const ERROR_IPSEC_MM_AUTH_PENDING_DELETION: DWORD = 13022;
+pub const ERROR_IPSEC_QM_POLICY_PENDING_DELETION: DWORD = 13023;
+pub const ERROR_IPSEC_IKE_NEG_STATUS_BEGIN: DWORD = 13800;
+pub const ERROR_IPSEC_IKE_AUTH_FAIL: DWORD = 13801;
+pub const ERROR_IPSEC_IKE_ATTRIB_FAIL: DWORD = 13802;
+pub const ERROR_IPSEC_IKE_NEGOTIATION_PENDING: DWORD = 13803;
+pub const ERROR_IPSEC_IKE_GENERAL_PROCESSING_ERROR: DWORD = 13804;
+pub const ERROR_IPSEC_IKE_TIMED_OUT: DWORD = 13805;
+pub const ERROR_IPSEC_IKE_NO_CERT: DWORD = 13806;
+pub const ERROR_IPSEC_IKE_SA_DELETED: DWORD = 13807;
+pub const ERROR_IPSEC_IKE_SA_REAPED: DWORD = 13808;
+pub const ERROR_IPSEC_IKE_MM_ACQUIRE_DROP: DWORD = 13809;
+pub const ERROR_IPSEC_IKE_QM_ACQUIRE_DROP: DWORD = 13810;
+pub const ERROR_IPSEC_IKE_QUEUE_DROP_MM: DWORD = 13811;
+pub const ERROR_IPSEC_IKE_QUEUE_DROP_NO_MM: DWORD = 13812;
+pub const ERROR_IPSEC_IKE_DROP_NO_RESPONSE: DWORD = 13813;
+pub const ERROR_IPSEC_IKE_MM_DELAY_DROP: DWORD = 13814;
+pub const ERROR_IPSEC_IKE_QM_DELAY_DROP: DWORD = 13815;
+pub const ERROR_IPSEC_IKE_ERROR: DWORD = 13816;
+pub const ERROR_IPSEC_IKE_CRL_FAILED: DWORD = 13817;
+pub const ERROR_IPSEC_IKE_INVALID_KEY_USAGE: DWORD = 13818;
+pub const ERROR_IPSEC_IKE_INVALID_CERT_TYPE: DWORD = 13819;
+pub const ERROR_IPSEC_IKE_NO_PRIVATE_KEY: DWORD = 13820;
+pub const ERROR_IPSEC_IKE_DH_FAIL: DWORD = 13822;
+pub const ERROR_IPSEC_IKE_INVALID_HEADER: DWORD = 13824;
+pub const ERROR_IPSEC_IKE_NO_POLICY: DWORD = 13825;
+pub const ERROR_IPSEC_IKE_INVALID_SIGNATURE: DWORD = 13826;
+pub const ERROR_IPSEC_IKE_KERBEROS_ERROR: DWORD = 13827;
+pub const ERROR_IPSEC_IKE_NO_PUBLIC_KEY: DWORD = 13828;
+pub const ERROR_IPSEC_IKE_PROCESS_ERR: DWORD = 13829;
+pub const ERROR_IPSEC_IKE_PROCESS_ERR_SA: DWORD = 13830;
+pub const ERROR_IPSEC_IKE_PROCESS_ERR_PROP: DWORD = 13831;
+pub const ERROR_IPSEC_IKE_PROCESS_ERR_TRANS: DWORD = 13832;
+pub const ERROR_IPSEC_IKE_PROCESS_ERR_KE: DWORD = 13833;
+pub const ERROR_IPSEC_IKE_PROCESS_ERR_ID: DWORD = 13834;
+pub const ERROR_IPSEC_IKE_PROCESS_ERR_CERT: DWORD = 13835;
+pub const ERROR_IPSEC_IKE_PROCESS_ERR_CERT_REQ: DWORD = 13836;
+pub const ERROR_IPSEC_IKE_PROCESS_ERR_HASH: DWORD = 13837;
+pub const ERROR_IPSEC_IKE_PROCESS_ERR_SIG: DWORD = 13838;
+pub const ERROR_IPSEC_IKE_PROCESS_ERR_NONCE: DWORD = 13839;
+pub const ERROR_IPSEC_IKE_PROCESS_ERR_NOTIFY: DWORD = 13840;
+pub const ERROR_IPSEC_IKE_PROCESS_ERR_DELETE: DWORD = 13841;
+pub const ERROR_IPSEC_IKE_PROCESS_ERR_VENDOR: DWORD = 13842;
+pub const ERROR_IPSEC_IKE_INVALID_PAYLOAD: DWORD = 13843;
+pub const ERROR_IPSEC_IKE_LOAD_SOFT_SA: DWORD = 13844;
+pub const ERROR_IPSEC_IKE_SOFT_SA_TORN_DOWN: DWORD = 13845;
+pub const ERROR_IPSEC_IKE_INVALID_COOKIE: DWORD = 13846;
+pub const ERROR_IPSEC_IKE_NO_PEER_CERT: DWORD = 13847;
+pub const ERROR_IPSEC_IKE_PEER_CRL_FAILED: DWORD = 13848;
+pub const ERROR_IPSEC_IKE_POLICY_CHANGE: DWORD = 13849;
+pub const ERROR_IPSEC_IKE_NO_MM_POLICY: DWORD = 13850;
+pub const ERROR_IPSEC_IKE_NOTCBPRIV: DWORD = 13851;
+pub const ERROR_IPSEC_IKE_SECLOADFAIL: DWORD = 13852;
+pub const ERROR_IPSEC_IKE_FAILSSPINIT: DWORD = 13853;
+pub const ERROR_IPSEC_IKE_FAILQUERYSSP: DWORD = 13854;
+pub const ERROR_IPSEC_IKE_SRVACQFAIL: DWORD = 13855;
+pub const ERROR_IPSEC_IKE_SRVQUERYCRED: DWORD = 13856;
+pub const ERROR_IPSEC_IKE_GETSPIFAIL: DWORD = 13857;
+pub const ERROR_IPSEC_IKE_INVALID_FILTER: DWORD = 13858;
+pub const ERROR_IPSEC_IKE_OUT_OF_MEMORY: DWORD = 13859;
+pub const ERROR_IPSEC_IKE_ADD_UPDATE_KEY_FAILED: DWORD = 13860;
+pub const ERROR_IPSEC_IKE_INVALID_POLICY: DWORD = 13861;
+pub const ERROR_IPSEC_IKE_UNKNOWN_DOI: DWORD = 13862;
+pub const ERROR_IPSEC_IKE_INVALID_SITUATION: DWORD = 13863;
+pub const ERROR_IPSEC_IKE_DH_FAILURE: DWORD = 13864;
+pub const ERROR_IPSEC_IKE_INVALID_GROUP: DWORD = 13865;
+pub const ERROR_IPSEC_IKE_ENCRYPT: DWORD = 13866;
+pub const ERROR_IPSEC_IKE_DECRYPT: DWORD = 13867;
+pub const ERROR_IPSEC_IKE_POLICY_MATCH: DWORD = 13868;
+pub const ERROR_IPSEC_IKE_UNSUPPORTED_ID: DWORD = 13869;
+pub const ERROR_IPSEC_IKE_INVALID_HASH: DWORD = 13870;
+pub const ERROR_IPSEC_IKE_INVALID_HASH_ALG: DWORD = 13871;
+pub const ERROR_IPSEC_IKE_INVALID_HASH_SIZE: DWORD = 13872;
+pub const ERROR_IPSEC_IKE_INVALID_ENCRYPT_ALG: DWORD = 13873;
+pub const ERROR_IPSEC_IKE_INVALID_AUTH_ALG: DWORD = 13874;
+pub const ERROR_IPSEC_IKE_INVALID_SIG: DWORD = 13875;
+pub const ERROR_IPSEC_IKE_LOAD_FAILED: DWORD = 13876;
+pub const ERROR_IPSEC_IKE_RPC_DELETE: DWORD = 13877;
+pub const ERROR_IPSEC_IKE_BENIGN_REINIT: DWORD = 13878;
+pub const ERROR_IPSEC_IKE_INVALID_RESPONDER_LIFETIME_NOTIFY: DWORD = 13879;
+pub const ERROR_IPSEC_IKE_INVALID_CERT_KEYLEN: DWORD = 13881;
+pub const ERROR_IPSEC_IKE_MM_LIMIT: DWORD = 13882;
+pub const ERROR_IPSEC_IKE_NEGOTIATION_DISABLED: DWORD = 13883;
+/*pub const ERROR_IPSEC_IKE_NEG_STATUS_END: DWORD = 13884)*/
+pub const ERROR_IPSEC_IKE_QM_LIMIT: DWORD = 13884;
+pub const ERROR_IPSEC_IKE_MM_EXPIRED: DWORD = 13885;
+pub const ERROR_IPSEC_IKE_PEER_MM_ASSUMED_INVALID: DWORD = 13886;
+pub const ERROR_IPSEC_IKE_CERT_CHAIN_POLICY_MISMATCH: DWORD = 13887;
+pub const ERROR_IPSEC_IKE_UNEXPECTED_MESSAGE_ID: DWORD = 13888;
+pub const ERROR_IPSEC_IKE_INVALID_AUTH_PAYLOAD: DWORD = 13889;
+pub const ERROR_IPSEC_IKE_DOS_COOKIE_SENT: DWORD = 13890;
+pub const ERROR_IPSEC_IKE_SHUTTING_DOWN: DWORD = 13891;
+pub const ERROR_IPSEC_IKE_CGA_AUTH_FAILED: DWORD = 13892;
+pub const ERROR_IPSEC_IKE_PROCESS_ERR_NATOA: DWORD = 13893;
+pub const ERROR_IPSEC_IKE_INVALID_MM_FOR_QM: DWORD = 13894;
+pub const ERROR_IPSEC_IKE_QM_EXPIRED: DWORD = 13895;
+pub const ERROR_IPSEC_IKE_TOO_MANY_FILTERS: DWORD = 13896;
+pub const ERROR_IPSEC_IKE_NEG_STATUS_END: DWORD = 13897;
+pub const ERROR_IPSEC_IKE_KILL_DUMMY_NAP_TUNNEL: DWORD = 13898;
+pub const ERROR_IPSEC_IKE_INNER_IP_ASSIGNMENT_FAILURE: DWORD = 13899;
+pub const ERROR_IPSEC_IKE_REQUIRE_CP_PAYLOAD_MISSING: DWORD = 13900;
+pub const ERROR_IPSEC_KEY_MODULE_IMPERSONATION_NEGOTIATION_PENDING: DWORD = 13901;
+pub const ERROR_IPSEC_IKE_COEXISTENCE_SUPPRESS: DWORD = 13902;
+pub const ERROR_IPSEC_IKE_RATELIMIT_DROP: DWORD = 13903;
+pub const ERROR_IPSEC_IKE_PEER_DOESNT_SUPPORT_MOBIKE: DWORD = 13904;
+pub const ERROR_IPSEC_IKE_AUTHORIZATION_FAILURE: DWORD = 13905;
+pub const ERROR_IPSEC_IKE_STRONG_CRED_AUTHORIZATION_FAILURE: DWORD = 13906;
+pub const ERROR_IPSEC_IKE_AUTHORIZATION_FAILURE_WITH_OPTIONAL_RETRY: DWORD = 13907;
+pub const ERROR_IPSEC_IKE_STRONG_CRED_AUTHORIZATION_AND_CERTMAP_FAILURE: DWORD = 13908;
+pub const ERROR_IPSEC_IKE_NEG_STATUS_EXTENDED_END: DWORD = 13909;
+pub const ERROR_IPSEC_BAD_SPI: DWORD = 13910;
+pub const ERROR_IPSEC_SA_LIFETIME_EXPIRED: DWORD = 13911;
+pub const ERROR_IPSEC_WRONG_SA: DWORD = 13912;
+pub const ERROR_IPSEC_REPLAY_CHECK_FAILED: DWORD = 13913;
+pub const ERROR_IPSEC_INVALID_PACKET: DWORD = 13914;
+pub const ERROR_IPSEC_INTEGRITY_CHECK_FAILED: DWORD = 13915;
+pub const ERROR_IPSEC_CLEAR_TEXT_DROP: DWORD = 13916;
+pub const ERROR_IPSEC_AUTH_FIREWALL_DROP: DWORD = 13917;
+pub const ERROR_IPSEC_THROTTLE_DROP: DWORD = 13918;
+pub const ERROR_IPSEC_DOSP_BLOCK: DWORD = 13925;
+pub const ERROR_IPSEC_DOSP_RECEIVED_MULTICAST: DWORD = 13926;
+pub const ERROR_IPSEC_DOSP_INVALID_PACKET: DWORD = 13927;
+pub const ERROR_IPSEC_DOSP_STATE_LOOKUP_FAILED: DWORD = 13928;
+pub const ERROR_IPSEC_DOSP_MAX_ENTRIES: DWORD = 13929;
+pub const ERROR_IPSEC_DOSP_KEYMOD_NOT_ALLOWED: DWORD = 13930;
+pub const ERROR_IPSEC_DOSP_NOT_INSTALLED: DWORD = 13931;
+pub const ERROR_IPSEC_DOSP_MAX_PER_IP_RATELIMIT_QUEUES: DWORD = 13932;
+pub const ERROR_EVT_INVALID_CHANNEL_PATH: DWORD = 15000;
+pub const ERROR_EVT_INVALID_QUERY: DWORD = 15001;
+pub const ERROR_EVT_PUBLISHER_METADATA_NOT_FOUND: DWORD = 15002;
+pub const ERROR_EVT_EVENT_TEMPLATE_NOT_FOUND: DWORD = 15003;
+pub const ERROR_EVT_INVALID_PUBLISHER_NAME: DWORD = 15004;
+pub const ERROR_EVT_INVALID_EVENT_DATA: DWORD = 15005;
+pub const ERROR_EVT_CHANNEL_NOT_FOUND: DWORD = 15007;
+pub const ERROR_EVT_MALFORMED_XML_TEXT: DWORD = 15008;
+pub const ERROR_EVT_SUBSCRIPTION_TO_DIRECT_CHANNEL: DWORD = 15009;
+pub const ERROR_EVT_CONFIGURATION_ERROR: DWORD = 15010;
+pub const ERROR_EVT_QUERY_RESULT_STALE: DWORD = 15011;
+pub const ERROR_EVT_QUERY_RESULT_INVALID_POSITION: DWORD = 15012;
+pub const ERROR_EVT_NON_VALIDATING_MSXML: DWORD = 15013;
+pub const ERROR_EVT_FILTER_ALREADYSCOPED: DWORD = 15014;
+pub const ERROR_EVT_FILTER_NOTELTSET: DWORD = 15015;
+pub const ERROR_EVT_FILTER_INVARG: DWORD = 15016;
+pub const ERROR_EVT_FILTER_INVTEST: DWORD = 15017;
+pub const ERROR_EVT_FILTER_INVTYPE: DWORD = 15018;
+pub const ERROR_EVT_FILTER_PARSEERR: DWORD = 15019;
+pub const ERROR_EVT_FILTER_UNSUPPORTEDOP: DWORD = 15020;
+pub const ERROR_EVT_FILTER_UNEXPECTEDTOKEN: DWORD = 15021;
+pub const ERROR_EVT_INVALID_OPERATION_OVER_ENABLED_DIRECT_CHANNEL: DWORD = 15022;
+pub const ERROR_EVT_INVALID_CHANNEL_PROPERTY_VALUE: DWORD = 15023;
+pub const ERROR_EVT_INVALID_PUBLISHER_PROPERTY_VALUE: DWORD = 15024;
+pub const ERROR_EVT_CHANNEL_CANNOT_ACTIVATE: DWORD = 15025;
+pub const ERROR_EVT_FILTER_TOO_COMPLEX: DWORD = 15026;
+pub const ERROR_EVT_MESSAGE_NOT_FOUND: DWORD = 15027;
+pub const ERROR_EVT_MESSAGE_ID_NOT_FOUND: DWORD = 15028;
+pub const ERROR_EVT_UNRESOLVED_VALUE_INSERT: DWORD = 15029;
+pub const ERROR_EVT_UNRESOLVED_PARAMETER_INSERT: DWORD = 15030;
+pub const ERROR_EVT_MAX_INSERTS_REACHED: DWORD = 15031;
+pub const ERROR_EVT_EVENT_DEFINITION_NOT_FOUND: DWORD = 15032;
+pub const ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND: DWORD = 15033;
+pub const ERROR_EVT_VERSION_TOO_OLD: DWORD = 15034;
+pub const ERROR_EVT_VERSION_TOO_NEW: DWORD = 15035;
+pub const ERROR_EVT_CANNOT_OPEN_CHANNEL_OF_QUERY: DWORD = 15036;
+pub const ERROR_EVT_PUBLISHER_DISABLED: DWORD = 15037;
+pub const ERROR_EVT_FILTER_OUT_OF_RANGE: DWORD = 15038;
+pub const ERROR_EC_SUBSCRIPTION_CANNOT_ACTIVATE: DWORD = 15080;
+pub const ERROR_EC_LOG_DISABLED: DWORD = 15081;
+pub const ERROR_EC_CIRCULAR_FORWARDING: DWORD = 15082;
+pub const ERROR_EC_CREDSTORE_FULL: DWORD = 15083;
+pub const ERROR_EC_CRED_NOT_FOUND: DWORD = 15084;
+pub const ERROR_EC_NO_ACTIVE_CHANNEL: DWORD = 15085;
+pub const ERROR_MUI_FILE_NOT_FOUND: DWORD = 15100;
+pub const ERROR_MUI_INVALID_FILE: DWORD = 15101;
+pub const ERROR_MUI_INVALID_RC_CONFIG: DWORD = 15102;
+pub const ERROR_MUI_INVALID_LOCALE_NAME: DWORD = 15103;
+pub const ERROR_MUI_INVALID_ULTIMATEFALLBACK_NAME: DWORD = 15104;
+pub const ERROR_MUI_FILE_NOT_LOADED: DWORD = 15105;
+pub const ERROR_RESOURCE_ENUM_USER_STOP: DWORD = 15106;
+pub const ERROR_MUI_INTLSETTINGS_UILANG_NOT_INSTALLED: DWORD = 15107;
+pub const ERROR_MUI_INTLSETTINGS_INVALID_LOCALE_NAME: DWORD = 15108;
+pub const ERROR_MRM_RUNTIME_NO_DEFAULT_OR_NEUTRAL_RESOURCE: DWORD = 15110;
+pub const ERROR_MRM_INVALID_PRICONFIG: DWORD = 15111;
+pub const ERROR_MRM_INVALID_FILE_TYPE: DWORD = 15112;
+pub const ERROR_MRM_UNKNOWN_QUALIFIER: DWORD = 15113;
+pub const ERROR_MRM_INVALID_QUALIFIER_VALUE: DWORD = 15114;
+pub const ERROR_MRM_NO_CANDIDATE: DWORD = 15115;
+pub const ERROR_MRM_NO_MATCH_OR_DEFAULT_CANDIDATE: DWORD = 15116;
+pub const ERROR_MRM_RESOURCE_TYPE_MISMATCH: DWORD = 15117;
+pub const ERROR_MRM_DUPLICATE_MAP_NAME: DWORD = 15118;
+pub const ERROR_MRM_DUPLICATE_ENTRY: DWORD = 15119;
+pub const ERROR_MRM_INVALID_RESOURCE_IDENTIFIER: DWORD = 15120;
+pub const ERROR_MRM_FILEPATH_TOO_LONG: DWORD = 15121;
+pub const ERROR_MRM_UNSUPPORTED_DIRECTORY_TYPE: DWORD = 15122;
+pub const ERROR_MRM_INVALID_PRI_FILE: DWORD = 15126;
+pub const ERROR_MRM_NAMED_RESOURCE_NOT_FOUND: DWORD = 15127;
+pub const ERROR_MRM_MAP_NOT_FOUND: DWORD = 15135;
+pub const ERROR_MRM_UNSUPPORTED_PROFILE_TYPE: DWORD = 15136;
+pub const ERROR_MRM_INVALID_QUALIFIER_OPERATOR: DWORD = 15137;
+pub const ERROR_MRM_INDETERMINATE_QUALIFIER_VALUE: DWORD = 15138;
+pub const ERROR_MRM_AUTOMERGE_ENABLED: DWORD = 15139;
+pub const ERROR_MRM_TOO_MANY_RESOURCES: DWORD = 15140;
+pub const ERROR_MCA_INVALID_CAPABILITIES_STRING: DWORD = 15200;
+pub const ERROR_MCA_INVALID_VCP_VERSION: DWORD = 15201;
+pub const ERROR_MCA_MONITOR_VIOLATES_MCCS_SPECIFICATION: DWORD = 15202;
+pub const ERROR_MCA_MCCS_VERSION_MISMATCH: DWORD = 15203;
+pub const ERROR_MCA_UNSUPPORTED_MCCS_VERSION: DWORD = 15204;
+pub const ERROR_MCA_INTERNAL_ERROR: DWORD = 15205;
+pub const ERROR_MCA_INVALID_TECHNOLOGY_TYPE_RETURNED: DWORD = 15206;
+pub const ERROR_MCA_UNSUPPORTED_COLOR_TEMPERATURE: DWORD = 15207;
+pub const ERROR_AMBIGUOUS_SYSTEM_DEVICE: DWORD = 15250;
+pub const ERROR_SYSTEM_DEVICE_NOT_FOUND: DWORD = 15299;
+pub const ERROR_HASH_NOT_SUPPORTED: DWORD = 15300;
+pub const ERROR_HASH_NOT_PRESENT: DWORD = 15301;
+pub const ERROR_SECONDARY_IC_PROVIDER_NOT_REGISTERED: DWORD = 15321;
+pub const ERROR_GPIO_CLIENT_INFORMATION_INVALID: DWORD = 15322;
+pub const ERROR_GPIO_VERSION_NOT_SUPPORTED: DWORD = 15323;
+pub const ERROR_GPIO_INVALID_REGISTRATION_PACKET: DWORD = 15324;
+pub const ERROR_GPIO_OPERATION_DENIED: DWORD = 15325;
+pub const ERROR_GPIO_INCOMPATIBLE_CONNECT_MODE: DWORD = 15326;
+pub const ERROR_GPIO_INTERRUPT_ALREADY_UNMASKED: DWORD = 15327;
+pub const ERROR_CANNOT_SWITCH_RUNLEVEL: DWORD = 15400;
+pub const ERROR_INVALID_RUNLEVEL_SETTING: DWORD = 15401;
+pub const ERROR_RUNLEVEL_SWITCH_TIMEOUT: DWORD = 15402;
+pub const ERROR_RUNLEVEL_SWITCH_AGENT_TIMEOUT: DWORD = 15403;
+pub const ERROR_RUNLEVEL_SWITCH_IN_PROGRESS: DWORD = 15404;
+pub const ERROR_SERVICES_FAILED_AUTOSTART: DWORD = 15405;
+pub const ERROR_COM_TASK_STOP_PENDING: DWORD = 15501;
+pub const ERROR_INSTALL_OPEN_PACKAGE_FAILED: DWORD = 15600;
+pub const ERROR_INSTALL_PACKAGE_NOT_FOUND: DWORD = 15601;
+pub const ERROR_INSTALL_INVALID_PACKAGE: DWORD = 15602;
+pub const ERROR_INSTALL_RESOLVE_DEPENDENCY_FAILED: DWORD = 15603;
+pub const ERROR_INSTALL_OUT_OF_DISK_SPACE: DWORD = 15604;
+pub const ERROR_INSTALL_NETWORK_FAILURE: DWORD = 15605;
+pub const ERROR_INSTALL_REGISTRATION_FAILURE: DWORD = 15606;
+pub const ERROR_INSTALL_DEREGISTRATION_FAILURE: DWORD = 15607;
+pub const ERROR_INSTALL_CANCEL: DWORD = 15608;
+pub const ERROR_INSTALL_FAILED: DWORD = 15609;
+pub const ERROR_REMOVE_FAILED: DWORD = 15610;
+pub const ERROR_PACKAGE_ALREADY_EXISTS: DWORD = 15611;
+pub const ERROR_NEEDS_REMEDIATION: DWORD = 15612;
+pub const ERROR_INSTALL_PREREQUISITE_FAILED: DWORD = 15613;
+pub const ERROR_PACKAGE_REPOSITORY_CORRUPTED: DWORD = 15614;
+pub const ERROR_INSTALL_POLICY_FAILURE: DWORD = 15615;
+pub const ERROR_PACKAGE_UPDATING: DWORD = 15616;
+pub const ERROR_DEPLOYMENT_BLOCKED_BY_POLICY: DWORD = 15617;
+pub const ERROR_PACKAGES_IN_USE: DWORD = 15618;
+pub const ERROR_RECOVERY_FILE_CORRUPT: DWORD = 15619;
+pub const ERROR_INVALID_STAGED_SIGNATURE: DWORD = 15620;
+pub const ERROR_DELETING_EXISTING_APPLICATIONDATA_STORE_FAILED: DWORD = 15621;
+pub const ERROR_INSTALL_PACKAGE_DOWNGRADE: DWORD = 15622;
+pub const ERROR_SYSTEM_NEEDS_REMEDIATION: DWORD = 15623;
+pub const ERROR_APPX_INTEGRITY_FAILURE_CLR_NGEN: DWORD = 15624;
+pub const ERROR_RESILIENCY_FILE_CORRUPT: DWORD = 15625;
+pub const ERROR_INSTALL_FIREWALL_SERVICE_NOT_RUNNING: DWORD = 15626;
+pub const ERROR_STATE_LOAD_STORE_FAILED: DWORD = 15800;
+pub const ERROR_STATE_GET_VERSION_FAILED: DWORD = 15801;
+pub const ERROR_STATE_SET_VERSION_FAILED: DWORD = 15802;
+pub const ERROR_STATE_STRUCTURED_RESET_FAILED: DWORD = 15803;
+pub const ERROR_STATE_OPEN_CONTAINER_FAILED: DWORD = 15804;
+pub const ERROR_STATE_CREATE_CONTAINER_FAILED: DWORD = 15805;
+pub const ERROR_STATE_DELETE_CONTAINER_FAILED: DWORD = 15806;
+pub const ERROR_STATE_READ_SETTING_FAILED: DWORD = 15807;
+pub const ERROR_STATE_WRITE_SETTING_FAILED: DWORD = 15808;
+pub const ERROR_STATE_DELETE_SETTING_FAILED: DWORD = 15809;
+pub const ERROR_STATE_QUERY_SETTING_FAILED: DWORD = 15810;
+pub const ERROR_STATE_READ_COMPOSITE_SETTING_FAILED: DWORD = 15811;
+pub const ERROR_STATE_WRITE_COMPOSITE_SETTING_FAILED: DWORD = 15812;
+pub const ERROR_STATE_ENUMERATE_CONTAINER_FAILED: DWORD = 15813;
+pub const ERROR_STATE_ENUMERATE_SETTINGS_FAILED: DWORD = 15814;
+pub const ERROR_STATE_COMPOSITE_SETTING_VALUE_SIZE_LIMIT_EXCEEDED: DWORD = 15815;
+pub const ERROR_STATE_SETTING_VALUE_SIZE_LIMIT_EXCEEDED: DWORD = 15816;
+pub const ERROR_STATE_SETTING_NAME_SIZE_LIMIT_EXCEEDED: DWORD = 15817;
+pub const ERROR_STATE_CONTAINER_NAME_SIZE_LIMIT_EXCEEDED: DWORD = 15818;
+pub const ERROR_API_UNAVAILABLE: DWORD = 15841;
+pub const ERROR_AUDITING_DISABLED: DWORD = 0xC0090001;
+pub const ERROR_ALL_SIDS_FILTERED: DWORD = 0xC0090002;
+
+pub const WSABASEERR: c_int = 10000;
+pub const WSAEINTR: c_int = WSABASEERR + 4;
+pub const WSAEBADF: c_int = WSABASEERR + 9;
+pub const WSAEACCES: c_int = WSABASEERR + 13;
+pub const WSAEFAULT: c_int = WSABASEERR + 14;
+pub const WSAEINVAL: c_int = WSABASEERR + 22;
+pub const WSAEMFILE: c_int = WSABASEERR + 24;
+pub const WSAEWOULDBLOCK: c_int = WSABASEERR + 35;
+pub const WSAEINPROGRESS: c_int = WSABASEERR + 36;
+pub const WSAEALREADY: c_int = WSABASEERR + 37;
+pub const WSAENOTSOCK: c_int = WSABASEERR + 38;
+pub const WSAEDESTADDRREQ: c_int = WSABASEERR + 39;
+pub const WSAEMSGSIZE: c_int = WSABASEERR + 40;
+pub const WSAEPROTOTYPE: c_int = WSABASEERR + 41;
+pub const WSAENOPROTOOPT: c_int = WSABASEERR + 42;
+pub const WSAEPROTONOSUPPORT: c_int = WSABASEERR + 43;
+pub const WSAESOCKTNOSUPPORT: c_int = WSABASEERR + 44;
+pub const WSAEOPNOTSUPP: c_int = WSABASEERR + 45;
+pub const WSAEPFNOSUPPORT: c_int = WSABASEERR + 46;
+pub const WSAEAFNOSUPPORT: c_int = WSABASEERR + 47;
+pub const WSAEADDRINUSE: c_int = WSABASEERR + 48;
+pub const WSAEADDRNOTAVAIL: c_int = WSABASEERR + 49;
+pub const WSAENETDOWN: c_int = WSABASEERR + 50;
+pub const WSAENETUNREACH: c_int = WSABASEERR + 51;
+pub const WSAENETRESET: c_int = WSABASEERR + 52;
+pub const WSAECONNABORTED: c_int = WSABASEERR + 53;
+pub const WSAECONNRESET: c_int = WSABASEERR + 54;
+pub const WSAENOBUFS: c_int = WSABASEERR + 55;
+pub const WSAEISCONN: c_int = WSABASEERR + 56;
+pub const WSAENOTCONN: c_int = WSABASEERR + 57;
+pub const WSAESHUTDOWN: c_int = WSABASEERR + 58;
+pub const WSAETOOMANYREFS: c_int = WSABASEERR + 59;
+pub const WSAETIMEDOUT: c_int = WSABASEERR + 60;
+pub const WSAECONNREFUSED: c_int = WSABASEERR + 61;
+pub const WSAELOOP: c_int = WSABASEERR + 62;
+pub const WSAENAMETOOLONG: c_int = WSABASEERR + 63;
+pub const WSAEHOSTDOWN: c_int = WSABASEERR + 64;
+pub const WSAEHOSTUNREACH: c_int = WSABASEERR + 65;
+pub const WSAENOTEMPTY: c_int = WSABASEERR + 66;
+pub const WSAEPROCLIM: c_int = WSABASEERR + 67;
+pub const WSAEUSERS: c_int = WSABASEERR + 68;
+pub const WSAEDQUOT: c_int = WSABASEERR + 69;
+pub const WSAESTALE: c_int = WSABASEERR + 70;
+pub const WSAEREMOTE: c_int = WSABASEERR + 71;
+pub const WSASYSNOTREADY: c_int = WSABASEERR + 91;
+pub const WSAVERNOTSUPPORTED: c_int = WSABASEERR + 92;
+pub const WSANOTINITIALISED: c_int = WSABASEERR + 93;
+pub const WSAEDISCON: c_int = WSABASEERR + 101;
+pub const WSAENOMORE: c_int = WSABASEERR + 102;
+pub const WSAECANCELLED: c_int = WSABASEERR + 103;
+pub const WSAEINVALIDPROCTABLE: c_int = WSABASEERR + 104;
+pub const WSAEINVALIDPROVIDER: c_int = WSABASEERR + 105;
+pub const WSAEPROVIDERFAILEDINIT: c_int = WSABASEERR + 106;
+pub const WSASYSCALLFAILURE: c_int = WSABASEERR + 107;
+pub const WSASERVICE_NOT_FOUND: c_int = WSABASEERR + 108;
+pub const WSATYPE_NOT_FOUND: c_int = WSABASEERR + 109;
+pub const WSA_E_NO_MORE: c_int = WSABASEERR + 110;
+pub const WSA_E_CANCELLED: c_int = WSABASEERR + 111;
+pub const WSAEREFUSED: c_int = WSABASEERR + 112;
+pub const WSAHOST_NOT_FOUND: c_int = WSABASEERR + 1001;
+pub const WSATRY_AGAIN: c_int = WSABASEERR + 1002;
+pub const WSANO_RECOVERY: c_int = WSABASEERR + 1003;
+pub const WSANO_DATA: c_int = WSABASEERR + 1004;
+pub const WSA_QOS_RECEIVERS: c_int = WSABASEERR + 1005;
+pub const WSA_QOS_SENDERS: c_int = WSABASEERR + 1006;
+pub const WSA_QOS_NO_SENDERS: c_int = WSABASEERR + 1007;
+pub const WSA_QOS_NO_RECEIVERS: c_int = WSABASEERR + 1008;
+pub const WSA_QOS_REQUEST_CONFIRMED: c_int = WSABASEERR + 1009;
+pub const WSA_QOS_ADMISSION_FAILURE: c_int = WSABASEERR + 1010;
+pub const WSA_QOS_POLICY_FAILURE: c_int = WSABASEERR + 1011;
+pub const WSA_QOS_BAD_STYLE: c_int = WSABASEERR + 1012;
+pub const WSA_QOS_BAD_OBJECT: c_int = WSABASEERR + 1013;
+pub const WSA_QOS_TRAFFIC_CTRL_ERROR: c_int = WSABASEERR + 1014;
+pub const WSA_QOS_GENERIC_ERROR: c_int = WSABASEERR + 1015;
+pub const WSA_QOS_ESERVICETYPE: c_int = WSABASEERR + 1016;
+pub const WSA_QOS_EFLOWSPEC: c_int = WSABASEERR + 1017;
+pub const WSA_QOS_EPROVSPECBUF: c_int = WSABASEERR + 1018;
+pub const WSA_QOS_EFILTERSTYLE: c_int = WSABASEERR + 1019;
+pub const WSA_QOS_EFILTERTYPE: c_int = WSABASEERR + 1020;
+pub const WSA_QOS_EFILTERCOUNT: c_int = WSABASEERR + 1021;
+pub const WSA_QOS_EOBJLENGTH: c_int = WSABASEERR + 1022;
+pub const WSA_QOS_EFLOWCOUNT: c_int = WSABASEERR + 1023;
+pub const WSA_QOS_EUNKNOWNPSOBJ: c_int = WSABASEERR + 1024;
+pub const WSA_QOS_EUNKOWNPSOBJ: c_int = WSA_QOS_EUNKNOWNPSOBJ;
+pub const WSA_QOS_EPOLICYOBJ: c_int = WSABASEERR + 1025;
+pub const WSA_QOS_EFLOWDESC: c_int = WSABASEERR + 1026;
+pub const WSA_QOS_EPSFLOWSPEC: c_int = WSABASEERR + 1027;
+pub const WSA_QOS_EPSFILTERSPEC: c_int = WSABASEERR + 1028;
+pub const WSA_QOS_ESDMODEOBJ: c_int = WSABASEERR + 1029;
+pub const WSA_QOS_ESHAPERATEOBJ: c_int = WSABASEERR + 1030;
+pub const WSA_QOS_RESERVED_PETYPE: c_int = WSABASEERR + 1031;
diff --git a/library/std/src/sys/windows/cmath.rs b/library/std/src/sys/windows/cmath.rs
new file mode 100644
index 000000000..1a5421fac
--- /dev/null
+++ b/library/std/src/sys/windows/cmath.rs
@@ -0,0 +1,92 @@
+#![cfg(not(test))]
+
+use libc::{c_double, c_float};
+
+extern "C" {
+ pub fn acos(n: c_double) -> c_double;
+ pub fn asin(n: c_double) -> c_double;
+ pub fn atan(n: c_double) -> c_double;
+ pub fn atan2(a: c_double, b: c_double) -> c_double;
+ pub fn cbrt(n: c_double) -> c_double;
+ pub fn cbrtf(n: c_float) -> c_float;
+ pub fn cosh(n: c_double) -> c_double;
+ pub fn expm1(n: c_double) -> c_double;
+ pub fn expm1f(n: c_float) -> c_float;
+ pub fn fdim(a: c_double, b: c_double) -> c_double;
+ pub fn fdimf(a: c_float, b: c_float) -> c_float;
+ #[cfg_attr(target_env = "msvc", link_name = "_hypot")]
+ pub fn hypot(x: c_double, y: c_double) -> c_double;
+ #[cfg_attr(target_env = "msvc", link_name = "_hypotf")]
+ pub fn hypotf(x: c_float, y: c_float) -> c_float;
+ pub fn log1p(n: c_double) -> c_double;
+ pub fn log1pf(n: c_float) -> c_float;
+ pub fn sinh(n: c_double) -> c_double;
+ pub fn tan(n: c_double) -> c_double;
+ pub fn tanh(n: c_double) -> c_double;
+}
+
+pub use self::shims::*;
+
+#[cfg(not(all(target_env = "msvc", target_arch = "x86")))]
+mod shims {
+ use libc::c_float;
+
+ extern "C" {
+ pub fn acosf(n: c_float) -> c_float;
+ pub fn asinf(n: c_float) -> c_float;
+ pub fn atan2f(a: c_float, b: c_float) -> c_float;
+ pub fn atanf(n: c_float) -> c_float;
+ pub fn coshf(n: c_float) -> c_float;
+ pub fn sinhf(n: c_float) -> c_float;
+ pub fn tanf(n: c_float) -> c_float;
+ pub fn tanhf(n: c_float) -> c_float;
+ }
+}
+
+// On 32-bit x86 MSVC these functions aren't defined, so we just define shims
+// which promote everything fo f64, perform the calculation, and then demote
+// back to f32. While not precisely correct should be "correct enough" for now.
+#[cfg(all(target_env = "msvc", target_arch = "x86"))]
+mod shims {
+ use libc::c_float;
+
+ #[inline]
+ pub unsafe fn acosf(n: c_float) -> c_float {
+ f64::acos(n as f64) as c_float
+ }
+
+ #[inline]
+ pub unsafe fn asinf(n: c_float) -> c_float {
+ f64::asin(n as f64) as c_float
+ }
+
+ #[inline]
+ pub unsafe fn atan2f(n: c_float, b: c_float) -> c_float {
+ f64::atan2(n as f64, b as f64) as c_float
+ }
+
+ #[inline]
+ pub unsafe fn atanf(n: c_float) -> c_float {
+ f64::atan(n as f64) as c_float
+ }
+
+ #[inline]
+ pub unsafe fn coshf(n: c_float) -> c_float {
+ f64::cosh(n as f64) as c_float
+ }
+
+ #[inline]
+ pub unsafe fn sinhf(n: c_float) -> c_float {
+ f64::sinh(n as f64) as c_float
+ }
+
+ #[inline]
+ pub unsafe fn tanf(n: c_float) -> c_float {
+ f64::tan(n as f64) as c_float
+ }
+
+ #[inline]
+ pub unsafe fn tanhf(n: c_float) -> c_float {
+ f64::tanh(n as f64) as c_float
+ }
+}
diff --git a/library/std/src/sys/windows/compat.rs b/library/std/src/sys/windows/compat.rs
new file mode 100644
index 000000000..ccc90177a
--- /dev/null
+++ b/library/std/src/sys/windows/compat.rs
@@ -0,0 +1,273 @@
+//! A "compatibility layer" for supporting older versions of Windows
+//!
+//! The standard library uses some Windows API functions that are not present
+//! on older versions of Windows. (Note that the oldest version of Windows
+//! that Rust supports is Windows 7 (client) and Windows Server 2008 (server).)
+//! This module implements a form of delayed DLL import binding, using
+//! `GetModuleHandle` and `GetProcAddress` to look up DLL entry points at
+//! runtime.
+//!
+//! This implementation uses a static initializer to look up the DLL entry
+//! points. The CRT (C runtime) executes static initializers before `main`
+//! is called (for binaries) and before `DllMain` is called (for DLLs).
+//! This is the ideal time to look up DLL imports, because we are guaranteed
+//! that no other threads will attempt to call these entry points. Thus,
+//! we can look up the imports and store them in `static mut` fields
+//! without any synchronization.
+//!
+//! This has an additional advantage: Because the DLL import lookup happens
+//! at module initialization, the cost of these lookups is deterministic,
+//! and is removed from the code paths that actually call the DLL imports.
+//! That is, there is no unpredictable "cache miss" that occurs when calling
+//! a DLL import. For applications that benefit from predictable delays,
+//! this is a benefit. This also eliminates the comparison-and-branch
+//! from the hot path.
+//!
+//! Currently, the standard library uses only a small number of dynamic
+//! DLL imports. If this number grows substantially, then the cost of
+//! performing all of the lookups at initialization time might become
+//! substantial.
+//!
+//! The mechanism of registering a static initializer with the CRT is
+//! documented in
+//! [CRT Initialization](https://docs.microsoft.com/en-us/cpp/c-runtime-library/crt-initialization?view=msvc-160).
+//! It works by contributing a global symbol to the `.CRT$XCU` section.
+//! The linker builds a table of all static initializer functions.
+//! The CRT startup code then iterates that table, calling each
+//! initializer function.
+//!
+//! # **WARNING!!*
+//! The environment that a static initializer function runs in is highly
+//! constrained. There are **many** restrictions on what static initializers
+//! can safely do. Static initializer functions **MUST NOT** do any of the
+//! following (this list is not comprehensive):
+//! * touch any other static field that is used by a different static
+//! initializer, because the order that static initializers run in
+//! is not defined.
+//! * call `LoadLibrary` or any other function that acquires the DLL
+//! loader lock.
+//! * call any Rust function or CRT function that touches any static
+//! (global) state.
+
+use crate::ffi::{c_void, CStr};
+use crate::ptr::NonNull;
+use crate::sys::c;
+
+/// Helper macro for creating CStrs from literals and symbol names.
+macro_rules! ansi_str {
+ (sym $ident:ident) => {{
+ #[allow(unused_unsafe)]
+ crate::sys::compat::const_cstr_from_bytes(concat!(stringify!($ident), "\0").as_bytes())
+ }};
+ ($lit:literal) => {{ crate::sys::compat::const_cstr_from_bytes(concat!($lit, "\0").as_bytes()) }};
+}
+
+/// Creates a C string wrapper from a byte slice, in a constant context.
+///
+/// This is a utility function used by the [`ansi_str`] macro.
+///
+/// # Panics
+///
+/// Panics if the slice is not null terminated or contains nulls, except as the last item
+pub(crate) const fn const_cstr_from_bytes(bytes: &'static [u8]) -> &'static CStr {
+ if !matches!(bytes.last(), Some(&0)) {
+ panic!("A CStr must be null terminated");
+ }
+ let mut i = 0;
+ // At this point `len()` is at least 1.
+ while i < bytes.len() - 1 {
+ if bytes[i] == 0 {
+ panic!("A CStr must not have interior nulls")
+ }
+ i += 1;
+ }
+ // SAFETY: The safety is ensured by the above checks.
+ unsafe { crate::ffi::CStr::from_bytes_with_nul_unchecked(bytes) }
+}
+
+#[used]
+#[link_section = ".CRT$XCU"]
+static INIT_TABLE_ENTRY: unsafe extern "C" fn() = init;
+
+/// This is where the magic preloading of symbols happens.
+///
+/// Note that any functions included here will be unconditionally included in
+/// the final binary, regardless of whether or not they're actually used.
+///
+/// Therefore, this is limited to `compat_fn_optional` functions which must be
+/// preloaded and any functions which may be more time sensitive, even for the first call.
+unsafe extern "C" fn init() {
+ // There is no locking here. This code is executed before main() is entered, and
+ // is guaranteed to be single-threaded.
+ //
+ // DO NOT do anything interesting or complicated in this function! DO NOT call
+ // any Rust functions or CRT functions if those functions touch any global state,
+ // because this function runs during global initialization. For example, DO NOT
+ // do any dynamic allocation, don't call LoadLibrary, etc.
+
+ if let Some(synch) = Module::new(c::SYNCH_API) {
+ // These are optional and so we must manually attempt to load them
+ // before they can be used.
+ c::WaitOnAddress::preload(synch);
+ c::WakeByAddressSingle::preload(synch);
+ }
+
+ if let Some(kernel32) = Module::new(c::KERNEL32) {
+ // Preloading this means getting a precise time will be as fast as possible.
+ c::GetSystemTimePreciseAsFileTime::preload(kernel32);
+ }
+}
+
+/// Represents a loaded module.
+///
+/// Note that the modules std depends on must not be unloaded.
+/// Therefore a `Module` is always valid for the lifetime of std.
+#[derive(Copy, Clone)]
+pub(in crate::sys) struct Module(NonNull<c_void>);
+impl Module {
+ /// Try to get a handle to a loaded module.
+ ///
+ /// # SAFETY
+ ///
+ /// This should only be use for modules that exist for the lifetime of std
+ /// (e.g. kernel32 and ntdll).
+ pub unsafe fn new(name: &CStr) -> Option<Self> {
+ // SAFETY: A CStr is always null terminated.
+ let module = c::GetModuleHandleA(name.as_ptr());
+ NonNull::new(module).map(Self)
+ }
+
+ // Try to get the address of a function.
+ pub fn proc_address(self, name: &CStr) -> Option<NonNull<c_void>> {
+ // SAFETY:
+ // `self.0` will always be a valid module.
+ // A CStr is always null terminated.
+ let proc = unsafe { c::GetProcAddress(self.0.as_ptr(), name.as_ptr()) };
+ NonNull::new(proc)
+ }
+}
+
+/// Load a function or use a fallback implementation if that fails.
+macro_rules! compat_fn_with_fallback {
+ (pub static $module:ident: &CStr = $name:expr; $(
+ $(#[$meta:meta])*
+ pub fn $symbol:ident($($argname:ident: $argtype:ty),*) -> $rettype:ty $fallback_body:block
+ )*) => (
+ pub static $module: &CStr = $name;
+ $(
+ $(#[$meta])*
+ pub mod $symbol {
+ #[allow(unused_imports)]
+ use super::*;
+ use crate::mem;
+ use crate::ffi::CStr;
+ use crate::sync::atomic::{AtomicPtr, Ordering};
+ use crate::sys::compat::Module;
+
+ type F = unsafe extern "system" fn($($argtype),*) -> $rettype;
+
+ /// `PTR` contains a function pointer to one of three functions.
+ /// It starts with the `load` function.
+ /// When that is called it attempts to load the requested symbol.
+ /// If it succeeds, `PTR` is set to the address of that symbol.
+ /// If it fails, then `PTR` is set to `fallback`.
+ static PTR: AtomicPtr<c_void> = AtomicPtr::new(load as *mut _);
+
+ unsafe extern "system" fn load($($argname: $argtype),*) -> $rettype {
+ let func = load_from_module(Module::new($module));
+ func($($argname),*)
+ }
+
+ fn load_from_module(module: Option<Module>) -> F {
+ unsafe {
+ static SYMBOL_NAME: &CStr = ansi_str!(sym $symbol);
+ if let Some(f) = module.and_then(|m| m.proc_address(SYMBOL_NAME)) {
+ PTR.store(f.as_ptr(), Ordering::Relaxed);
+ mem::transmute(f)
+ } else {
+ PTR.store(fallback as *mut _, Ordering::Relaxed);
+ fallback
+ }
+ }
+ }
+
+ #[allow(unused_variables)]
+ unsafe extern "system" fn fallback($($argname: $argtype),*) -> $rettype {
+ $fallback_body
+ }
+
+ #[allow(unused)]
+ pub(in crate::sys) fn preload(module: Module) {
+ load_from_module(Some(module));
+ }
+
+ #[inline(always)]
+ pub unsafe fn call($($argname: $argtype),*) -> $rettype {
+ let func: F = mem::transmute(PTR.load(Ordering::Relaxed));
+ func($($argname),*)
+ }
+ }
+ $(#[$meta])*
+ pub use $symbol::call as $symbol;
+ )*)
+}
+
+/// A function that either exists or doesn't.
+///
+/// NOTE: Optional functions must be preloaded in the `init` function above, or they will always be None.
+macro_rules! compat_fn_optional {
+ (pub static $module:ident: &CStr = $name:expr; $(
+ $(#[$meta:meta])*
+ pub fn $symbol:ident($($argname:ident: $argtype:ty),*) -> $rettype:ty;
+ )*) => (
+ pub static $module: &CStr = $name;
+ $(
+ $(#[$meta])*
+ pub mod $symbol {
+ #[allow(unused_imports)]
+ use super::*;
+ use crate::mem;
+ use crate::sync::atomic::{AtomicPtr, Ordering};
+ use crate::sys::compat::Module;
+ use crate::ptr::{self, NonNull};
+
+ type F = unsafe extern "system" fn($($argtype),*) -> $rettype;
+
+ /// `PTR` will either be `null()` or set to the loaded function.
+ static PTR: AtomicPtr<c_void> = AtomicPtr::new(ptr::null_mut());
+
+ /// Only allow access to the function if it has loaded successfully.
+ #[inline(always)]
+ #[cfg(not(miri))]
+ pub fn option() -> Option<F> {
+ unsafe {
+ NonNull::new(PTR.load(Ordering::Relaxed)).map(|f| mem::transmute(f))
+ }
+ }
+
+ // Miri does not understand the way we do preloading
+ // therefore load the function here instead.
+ #[cfg(miri)]
+ pub fn option() -> Option<F> {
+ let mut func = NonNull::new(PTR.load(Ordering::Relaxed));
+ if func.is_none() {
+ unsafe { Module::new($module).map(preload) };
+ func = NonNull::new(PTR.load(Ordering::Relaxed));
+ }
+ unsafe {
+ func.map(|f| mem::transmute(f))
+ }
+ }
+
+ #[allow(unused)]
+ pub(in crate::sys) fn preload(module: Module) {
+ unsafe {
+ static SYMBOL_NAME: &CStr = ansi_str!(sym $symbol);
+ if let Some(f) = module.proc_address(SYMBOL_NAME) {
+ PTR.store(f.as_ptr(), Ordering::Relaxed);
+ }
+ }
+ }
+ }
+ )*)
+}
diff --git a/library/std/src/sys/windows/env.rs b/library/std/src/sys/windows/env.rs
new file mode 100644
index 000000000..f0a99d620
--- /dev/null
+++ b/library/std/src/sys/windows/env.rs
@@ -0,0 +1,9 @@
+pub mod os {
+ pub const FAMILY: &str = "windows";
+ pub const OS: &str = "windows";
+ pub const DLL_PREFIX: &str = "";
+ pub const DLL_SUFFIX: &str = ".dll";
+ pub const DLL_EXTENSION: &str = "dll";
+ pub const EXE_SUFFIX: &str = ".exe";
+ pub const EXE_EXTENSION: &str = "exe";
+}
diff --git a/library/std/src/sys/windows/fs.rs b/library/std/src/sys/windows/fs.rs
new file mode 100644
index 000000000..aed082b3e
--- /dev/null
+++ b/library/std/src/sys/windows/fs.rs
@@ -0,0 +1,1399 @@
+use crate::os::windows::prelude::*;
+
+use crate::ffi::OsString;
+use crate::fmt;
+use crate::io::{self, Error, IoSlice, IoSliceMut, ReadBuf, SeekFrom};
+use crate::mem;
+use crate::os::windows::io::{AsHandle, BorrowedHandle};
+use crate::path::{Path, PathBuf};
+use crate::ptr;
+use crate::slice;
+use crate::sync::Arc;
+use crate::sys::handle::Handle;
+use crate::sys::time::SystemTime;
+use crate::sys::{c, cvt};
+use crate::sys_common::{AsInner, FromInner, IntoInner};
+use crate::thread;
+
+use super::path::maybe_verbatim;
+use super::to_u16s;
+
+pub struct File {
+ handle: Handle,
+}
+
+#[derive(Clone)]
+pub struct FileAttr {
+ attributes: c::DWORD,
+ creation_time: c::FILETIME,
+ last_access_time: c::FILETIME,
+ last_write_time: c::FILETIME,
+ file_size: u64,
+ reparse_tag: c::DWORD,
+ volume_serial_number: Option<u32>,
+ number_of_links: Option<u32>,
+ file_index: Option<u64>,
+}
+
+#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
+pub struct FileType {
+ attributes: c::DWORD,
+ reparse_tag: c::DWORD,
+}
+
+pub struct ReadDir {
+ handle: FindNextFileHandle,
+ root: Arc<PathBuf>,
+ first: Option<c::WIN32_FIND_DATAW>,
+}
+
+struct FindNextFileHandle(c::HANDLE);
+
+unsafe impl Send for FindNextFileHandle {}
+unsafe impl Sync for FindNextFileHandle {}
+
+pub struct DirEntry {
+ root: Arc<PathBuf>,
+ data: c::WIN32_FIND_DATAW,
+}
+
+unsafe impl Send for OpenOptions {}
+unsafe impl Sync for OpenOptions {}
+
+#[derive(Clone, Debug)]
+pub struct OpenOptions {
+ // generic
+ read: bool,
+ write: bool,
+ append: bool,
+ truncate: bool,
+ create: bool,
+ create_new: bool,
+ // system-specific
+ custom_flags: u32,
+ access_mode: Option<c::DWORD>,
+ attributes: c::DWORD,
+ share_mode: c::DWORD,
+ security_qos_flags: c::DWORD,
+ security_attributes: c::LPSECURITY_ATTRIBUTES,
+}
+
+#[derive(Clone, PartialEq, Eq, Debug)]
+pub struct FilePermissions {
+ attrs: c::DWORD,
+}
+
+#[derive(Copy, Clone, Debug, Default)]
+pub struct FileTimes {
+ accessed: Option<c::FILETIME>,
+ modified: Option<c::FILETIME>,
+}
+
+#[derive(Debug)]
+pub struct DirBuilder;
+
+impl fmt::Debug for ReadDir {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
+ // Thus the result will be e g 'ReadDir("C:\")'
+ fmt::Debug::fmt(&*self.root, f)
+ }
+}
+
+impl Iterator for ReadDir {
+ type Item = io::Result<DirEntry>;
+ fn next(&mut self) -> Option<io::Result<DirEntry>> {
+ if let Some(first) = self.first.take() {
+ if let Some(e) = DirEntry::new(&self.root, &first) {
+ return Some(Ok(e));
+ }
+ }
+ unsafe {
+ let mut wfd = mem::zeroed();
+ loop {
+ if c::FindNextFileW(self.handle.0, &mut wfd) == 0 {
+ if c::GetLastError() == c::ERROR_NO_MORE_FILES {
+ return None;
+ } else {
+ return Some(Err(Error::last_os_error()));
+ }
+ }
+ if let Some(e) = DirEntry::new(&self.root, &wfd) {
+ return Some(Ok(e));
+ }
+ }
+ }
+ }
+}
+
+impl Drop for FindNextFileHandle {
+ fn drop(&mut self) {
+ let r = unsafe { c::FindClose(self.0) };
+ debug_assert!(r != 0);
+ }
+}
+
+impl DirEntry {
+ fn new(root: &Arc<PathBuf>, wfd: &c::WIN32_FIND_DATAW) -> Option<DirEntry> {
+ match &wfd.cFileName[0..3] {
+ // check for '.' and '..'
+ &[46, 0, ..] | &[46, 46, 0, ..] => return None,
+ _ => {}
+ }
+
+ Some(DirEntry { root: root.clone(), data: *wfd })
+ }
+
+ pub fn path(&self) -> PathBuf {
+ self.root.join(&self.file_name())
+ }
+
+ pub fn file_name(&self) -> OsString {
+ let filename = super::truncate_utf16_at_nul(&self.data.cFileName);
+ OsString::from_wide(filename)
+ }
+
+ pub fn file_type(&self) -> io::Result<FileType> {
+ Ok(FileType::new(
+ self.data.dwFileAttributes,
+ /* reparse_tag = */ self.data.dwReserved0,
+ ))
+ }
+
+ pub fn metadata(&self) -> io::Result<FileAttr> {
+ Ok(self.data.into())
+ }
+}
+
+impl OpenOptions {
+ pub fn new() -> OpenOptions {
+ OpenOptions {
+ // generic
+ read: false,
+ write: false,
+ append: false,
+ truncate: false,
+ create: false,
+ create_new: false,
+ // system-specific
+ custom_flags: 0,
+ access_mode: None,
+ share_mode: c::FILE_SHARE_READ | c::FILE_SHARE_WRITE | c::FILE_SHARE_DELETE,
+ attributes: 0,
+ security_qos_flags: 0,
+ security_attributes: ptr::null_mut(),
+ }
+ }
+
+ pub fn read(&mut self, read: bool) {
+ self.read = read;
+ }
+ pub fn write(&mut self, write: bool) {
+ self.write = write;
+ }
+ pub fn append(&mut self, append: bool) {
+ self.append = append;
+ }
+ pub fn truncate(&mut self, truncate: bool) {
+ self.truncate = truncate;
+ }
+ pub fn create(&mut self, create: bool) {
+ self.create = create;
+ }
+ pub fn create_new(&mut self, create_new: bool) {
+ self.create_new = create_new;
+ }
+
+ pub fn custom_flags(&mut self, flags: u32) {
+ self.custom_flags = flags;
+ }
+ pub fn access_mode(&mut self, access_mode: u32) {
+ self.access_mode = Some(access_mode);
+ }
+ pub fn share_mode(&mut self, share_mode: u32) {
+ self.share_mode = share_mode;
+ }
+ pub fn attributes(&mut self, attrs: u32) {
+ self.attributes = attrs;
+ }
+ pub fn security_qos_flags(&mut self, flags: u32) {
+ // We have to set `SECURITY_SQOS_PRESENT` here, because one of the valid flags we can
+ // receive is `SECURITY_ANONYMOUS = 0x0`, which we can't check for later on.
+ self.security_qos_flags = flags | c::SECURITY_SQOS_PRESENT;
+ }
+ pub fn security_attributes(&mut self, attrs: c::LPSECURITY_ATTRIBUTES) {
+ self.security_attributes = attrs;
+ }
+
+ fn get_access_mode(&self) -> io::Result<c::DWORD> {
+ const ERROR_INVALID_PARAMETER: i32 = 87;
+
+ match (self.read, self.write, self.append, self.access_mode) {
+ (.., Some(mode)) => Ok(mode),
+ (true, false, false, None) => Ok(c::GENERIC_READ),
+ (false, true, false, None) => Ok(c::GENERIC_WRITE),
+ (true, true, false, None) => Ok(c::GENERIC_READ | c::GENERIC_WRITE),
+ (false, _, true, None) => Ok(c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA),
+ (true, _, true, None) => {
+ Ok(c::GENERIC_READ | (c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA))
+ }
+ (false, false, false, None) => Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER)),
+ }
+ }
+
+ fn get_creation_mode(&self) -> io::Result<c::DWORD> {
+ const ERROR_INVALID_PARAMETER: i32 = 87;
+
+ match (self.write, self.append) {
+ (true, false) => {}
+ (false, false) => {
+ if self.truncate || self.create || self.create_new {
+ return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
+ }
+ }
+ (_, true) => {
+ if self.truncate && !self.create_new {
+ return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
+ }
+ }
+ }
+
+ Ok(match (self.create, self.truncate, self.create_new) {
+ (false, false, false) => c::OPEN_EXISTING,
+ (true, false, false) => c::OPEN_ALWAYS,
+ (false, true, false) => c::TRUNCATE_EXISTING,
+ (true, true, false) => c::CREATE_ALWAYS,
+ (_, _, true) => c::CREATE_NEW,
+ })
+ }
+
+ fn get_flags_and_attributes(&self) -> c::DWORD {
+ self.custom_flags
+ | self.attributes
+ | self.security_qos_flags
+ | if self.create_new { c::FILE_FLAG_OPEN_REPARSE_POINT } else { 0 }
+ }
+}
+
+impl File {
+ pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
+ let path = maybe_verbatim(path)?;
+ let handle = unsafe {
+ c::CreateFileW(
+ path.as_ptr(),
+ opts.get_access_mode()?,
+ opts.share_mode,
+ opts.security_attributes,
+ opts.get_creation_mode()?,
+ opts.get_flags_and_attributes(),
+ ptr::null_mut(),
+ )
+ };
+ if let Ok(handle) = handle.try_into() {
+ Ok(File { handle: Handle::from_inner(handle) })
+ } else {
+ Err(Error::last_os_error())
+ }
+ }
+
+ pub fn fsync(&self) -> io::Result<()> {
+ cvt(unsafe { c::FlushFileBuffers(self.handle.as_raw_handle()) })?;
+ Ok(())
+ }
+
+ pub fn datasync(&self) -> io::Result<()> {
+ self.fsync()
+ }
+
+ pub fn truncate(&self, size: u64) -> io::Result<()> {
+ let mut info = c::FILE_END_OF_FILE_INFO { EndOfFile: size as c::LARGE_INTEGER };
+ let size = mem::size_of_val(&info);
+ cvt(unsafe {
+ c::SetFileInformationByHandle(
+ self.handle.as_raw_handle(),
+ c::FileEndOfFileInfo,
+ &mut info as *mut _ as *mut _,
+ size as c::DWORD,
+ )
+ })?;
+ Ok(())
+ }
+
+ #[cfg(not(target_vendor = "uwp"))]
+ pub fn file_attr(&self) -> io::Result<FileAttr> {
+ unsafe {
+ let mut info: c::BY_HANDLE_FILE_INFORMATION = mem::zeroed();
+ cvt(c::GetFileInformationByHandle(self.handle.as_raw_handle(), &mut info))?;
+ let mut reparse_tag = 0;
+ if info.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
+ let mut b = [0; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
+ if let Ok((_, buf)) = self.reparse_point(&mut b) {
+ reparse_tag = buf.ReparseTag;
+ }
+ }
+ Ok(FileAttr {
+ attributes: info.dwFileAttributes,
+ creation_time: info.ftCreationTime,
+ last_access_time: info.ftLastAccessTime,
+ last_write_time: info.ftLastWriteTime,
+ file_size: (info.nFileSizeLow as u64) | ((info.nFileSizeHigh as u64) << 32),
+ reparse_tag,
+ volume_serial_number: Some(info.dwVolumeSerialNumber),
+ number_of_links: Some(info.nNumberOfLinks),
+ file_index: Some(
+ (info.nFileIndexLow as u64) | ((info.nFileIndexHigh as u64) << 32),
+ ),
+ })
+ }
+ }
+
+ #[cfg(target_vendor = "uwp")]
+ pub fn file_attr(&self) -> io::Result<FileAttr> {
+ unsafe {
+ let mut info: c::FILE_BASIC_INFO = mem::zeroed();
+ let size = mem::size_of_val(&info);
+ cvt(c::GetFileInformationByHandleEx(
+ self.handle.as_raw_handle(),
+ c::FileBasicInfo,
+ &mut info as *mut _ as *mut libc::c_void,
+ size as c::DWORD,
+ ))?;
+ let mut attr = FileAttr {
+ attributes: info.FileAttributes,
+ creation_time: c::FILETIME {
+ dwLowDateTime: info.CreationTime as c::DWORD,
+ dwHighDateTime: (info.CreationTime >> 32) as c::DWORD,
+ },
+ last_access_time: c::FILETIME {
+ dwLowDateTime: info.LastAccessTime as c::DWORD,
+ dwHighDateTime: (info.LastAccessTime >> 32) as c::DWORD,
+ },
+ last_write_time: c::FILETIME {
+ dwLowDateTime: info.LastWriteTime as c::DWORD,
+ dwHighDateTime: (info.LastWriteTime >> 32) as c::DWORD,
+ },
+ file_size: 0,
+ reparse_tag: 0,
+ volume_serial_number: None,
+ number_of_links: None,
+ file_index: None,
+ };
+ let mut info: c::FILE_STANDARD_INFO = mem::zeroed();
+ let size = mem::size_of_val(&info);
+ cvt(c::GetFileInformationByHandleEx(
+ self.handle.as_raw_handle(),
+ c::FileStandardInfo,
+ &mut info as *mut _ as *mut libc::c_void,
+ size as c::DWORD,
+ ))?;
+ attr.file_size = info.AllocationSize as u64;
+ attr.number_of_links = Some(info.NumberOfLinks);
+ if attr.file_type().is_reparse_point() {
+ let mut b = [0; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
+ if let Ok((_, buf)) = self.reparse_point(&mut b) {
+ attr.reparse_tag = buf.ReparseTag;
+ }
+ }
+ Ok(attr)
+ }
+ }
+
+ pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
+ self.handle.read(buf)
+ }
+
+ pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
+ self.handle.read_vectored(bufs)
+ }
+
+ #[inline]
+ pub fn is_read_vectored(&self) -> bool {
+ self.handle.is_read_vectored()
+ }
+
+ pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
+ self.handle.read_at(buf, offset)
+ }
+
+ pub fn read_buf(&self, buf: &mut ReadBuf<'_>) -> io::Result<()> {
+ self.handle.read_buf(buf)
+ }
+
+ pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
+ self.handle.write(buf)
+ }
+
+ pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
+ self.handle.write_vectored(bufs)
+ }
+
+ #[inline]
+ pub fn is_write_vectored(&self) -> bool {
+ self.handle.is_write_vectored()
+ }
+
+ pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
+ self.handle.write_at(buf, offset)
+ }
+
+ pub fn flush(&self) -> io::Result<()> {
+ Ok(())
+ }
+
+ pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
+ let (whence, pos) = match pos {
+ // Casting to `i64` is fine, `SetFilePointerEx` reinterprets this
+ // integer as `u64`.
+ SeekFrom::Start(n) => (c::FILE_BEGIN, n as i64),
+ SeekFrom::End(n) => (c::FILE_END, n),
+ SeekFrom::Current(n) => (c::FILE_CURRENT, n),
+ };
+ let pos = pos as c::LARGE_INTEGER;
+ let mut newpos = 0;
+ cvt(unsafe { c::SetFilePointerEx(self.handle.as_raw_handle(), pos, &mut newpos, whence) })?;
+ Ok(newpos as u64)
+ }
+
+ pub fn duplicate(&self) -> io::Result<File> {
+ Ok(Self { handle: self.handle.try_clone()? })
+ }
+
+ fn reparse_point<'a>(
+ &self,
+ space: &'a mut [u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE],
+ ) -> io::Result<(c::DWORD, &'a c::REPARSE_DATA_BUFFER)> {
+ unsafe {
+ let mut bytes = 0;
+ cvt({
+ c::DeviceIoControl(
+ self.handle.as_raw_handle(),
+ c::FSCTL_GET_REPARSE_POINT,
+ ptr::null_mut(),
+ 0,
+ space.as_mut_ptr() as *mut _,
+ space.len() as c::DWORD,
+ &mut bytes,
+ ptr::null_mut(),
+ )
+ })?;
+ Ok((bytes, &*(space.as_ptr() as *const c::REPARSE_DATA_BUFFER)))
+ }
+ }
+
+ fn readlink(&self) -> io::Result<PathBuf> {
+ let mut space = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
+ let (_bytes, buf) = self.reparse_point(&mut space)?;
+ unsafe {
+ let (path_buffer, subst_off, subst_len, relative) = match buf.ReparseTag {
+ c::IO_REPARSE_TAG_SYMLINK => {
+ let info: *const c::SYMBOLIC_LINK_REPARSE_BUFFER =
+ &buf.rest as *const _ as *const _;
+ (
+ &(*info).PathBuffer as *const _ as *const u16,
+ (*info).SubstituteNameOffset / 2,
+ (*info).SubstituteNameLength / 2,
+ (*info).Flags & c::SYMLINK_FLAG_RELATIVE != 0,
+ )
+ }
+ c::IO_REPARSE_TAG_MOUNT_POINT => {
+ let info: *const c::MOUNT_POINT_REPARSE_BUFFER =
+ &buf.rest as *const _ as *const _;
+ (
+ &(*info).PathBuffer as *const _ as *const u16,
+ (*info).SubstituteNameOffset / 2,
+ (*info).SubstituteNameLength / 2,
+ false,
+ )
+ }
+ _ => {
+ return Err(io::const_io_error!(
+ io::ErrorKind::Uncategorized,
+ "Unsupported reparse point type",
+ ));
+ }
+ };
+ let subst_ptr = path_buffer.offset(subst_off as isize);
+ let mut subst = slice::from_raw_parts(subst_ptr, subst_len as usize);
+ // Absolute paths start with an NT internal namespace prefix `\??\`
+ // We should not let it leak through.
+ if !relative && subst.starts_with(&[92u16, 63u16, 63u16, 92u16]) {
+ subst = &subst[4..];
+ }
+ Ok(PathBuf::from(OsString::from_wide(subst)))
+ }
+ }
+
+ pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
+ let mut info = c::FILE_BASIC_INFO {
+ CreationTime: 0,
+ LastAccessTime: 0,
+ LastWriteTime: 0,
+ ChangeTime: 0,
+ FileAttributes: perm.attrs,
+ };
+ let size = mem::size_of_val(&info);
+ cvt(unsafe {
+ c::SetFileInformationByHandle(
+ self.handle.as_raw_handle(),
+ c::FileBasicInfo,
+ &mut info as *mut _ as *mut _,
+ size as c::DWORD,
+ )
+ })?;
+ Ok(())
+ }
+
+ pub fn set_times(&self, times: FileTimes) -> io::Result<()> {
+ let is_zero = |t: c::FILETIME| t.dwLowDateTime == 0 && t.dwHighDateTime == 0;
+ if times.accessed.map_or(false, is_zero) || times.modified.map_or(false, is_zero) {
+ return Err(io::const_io_error!(
+ io::ErrorKind::InvalidInput,
+ "Cannot set file timestamp to 0",
+ ));
+ }
+ cvt(unsafe {
+ c::SetFileTime(self.as_handle(), None, times.accessed.as_ref(), times.modified.as_ref())
+ })?;
+ Ok(())
+ }
+
+ /// Get only basic file information such as attributes and file times.
+ fn basic_info(&self) -> io::Result<c::FILE_BASIC_INFO> {
+ unsafe {
+ let mut info: c::FILE_BASIC_INFO = mem::zeroed();
+ let size = mem::size_of_val(&info);
+ cvt(c::GetFileInformationByHandleEx(
+ self.handle.as_raw_handle(),
+ c::FileBasicInfo,
+ &mut info as *mut _ as *mut libc::c_void,
+ size as c::DWORD,
+ ))?;
+ Ok(info)
+ }
+ }
+ /// Delete using POSIX semantics.
+ ///
+ /// Files will be deleted as soon as the handle is closed. This is supported
+ /// for Windows 10 1607 (aka RS1) and later. However some filesystem
+ /// drivers will not support it even then, e.g. FAT32.
+ ///
+ /// If the operation is not supported for this filesystem or OS version
+ /// then errors will be `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`.
+ fn posix_delete(&self) -> io::Result<()> {
+ let mut info = c::FILE_DISPOSITION_INFO_EX {
+ Flags: c::FILE_DISPOSITION_DELETE
+ | c::FILE_DISPOSITION_POSIX_SEMANTICS
+ | c::FILE_DISPOSITION_IGNORE_READONLY_ATTRIBUTE,
+ };
+ let size = mem::size_of_val(&info);
+ cvt(unsafe {
+ c::SetFileInformationByHandle(
+ self.handle.as_raw_handle(),
+ c::FileDispositionInfoEx,
+ &mut info as *mut _ as *mut _,
+ size as c::DWORD,
+ )
+ })?;
+ Ok(())
+ }
+
+ /// Delete a file using win32 semantics. The file won't actually be deleted
+ /// until all file handles are closed. However, marking a file for deletion
+ /// will prevent anyone from opening a new handle to the file.
+ fn win32_delete(&self) -> io::Result<()> {
+ let mut info = c::FILE_DISPOSITION_INFO { DeleteFile: c::TRUE as _ };
+ let size = mem::size_of_val(&info);
+ cvt(unsafe {
+ c::SetFileInformationByHandle(
+ self.handle.as_raw_handle(),
+ c::FileDispositionInfo,
+ &mut info as *mut _ as *mut _,
+ size as c::DWORD,
+ )
+ })?;
+ Ok(())
+ }
+
+ /// Fill the given buffer with as many directory entries as will fit.
+ /// This will remember its position and continue from the last call unless
+ /// `restart` is set to `true`.
+ ///
+ /// The returned bool indicates if there are more entries or not.
+ /// It is an error if `self` is not a directory.
+ ///
+ /// # Symlinks and other reparse points
+ ///
+ /// On Windows a file is either a directory or a non-directory.
+ /// A symlink directory is simply an empty directory with some "reparse" metadata attached.
+ /// So if you open a link (not its target) and iterate the directory,
+ /// you will always iterate an empty directory regardless of the target.
+ fn fill_dir_buff(&self, buffer: &mut DirBuff, restart: bool) -> io::Result<bool> {
+ let class =
+ if restart { c::FileIdBothDirectoryRestartInfo } else { c::FileIdBothDirectoryInfo };
+
+ unsafe {
+ let result = cvt(c::GetFileInformationByHandleEx(
+ self.handle.as_raw_handle(),
+ class,
+ buffer.as_mut_ptr().cast(),
+ buffer.capacity() as _,
+ ));
+ match result {
+ Ok(_) => Ok(true),
+ Err(e) if e.raw_os_error() == Some(c::ERROR_NO_MORE_FILES as _) => Ok(false),
+ Err(e) => Err(e),
+ }
+ }
+ }
+}
+
+/// A buffer for holding directory entries.
+struct DirBuff {
+ buffer: Vec<u8>,
+}
+impl DirBuff {
+ fn new() -> Self {
+ const BUFFER_SIZE: usize = 1024;
+ Self { buffer: vec![0_u8; BUFFER_SIZE] }
+ }
+ fn capacity(&self) -> usize {
+ self.buffer.len()
+ }
+ fn as_mut_ptr(&mut self) -> *mut u8 {
+ self.buffer.as_mut_ptr().cast()
+ }
+ /// Returns a `DirBuffIter`.
+ fn iter(&self) -> DirBuffIter<'_> {
+ DirBuffIter::new(self)
+ }
+}
+impl AsRef<[u8]> for DirBuff {
+ fn as_ref(&self) -> &[u8] {
+ &self.buffer
+ }
+}
+
+/// An iterator over entries stored in a `DirBuff`.
+///
+/// Currently only returns file names (UTF-16 encoded).
+struct DirBuffIter<'a> {
+ buffer: Option<&'a [u8]>,
+ cursor: usize,
+}
+impl<'a> DirBuffIter<'a> {
+ fn new(buffer: &'a DirBuff) -> Self {
+ Self { buffer: Some(buffer.as_ref()), cursor: 0 }
+ }
+}
+impl<'a> Iterator for DirBuffIter<'a> {
+ type Item = (&'a [u16], bool);
+ fn next(&mut self) -> Option<Self::Item> {
+ use crate::mem::size_of;
+ let buffer = &self.buffer?[self.cursor..];
+
+ // Get the name and next entry from the buffer.
+ // SAFETY: The buffer contains a `FILE_ID_BOTH_DIR_INFO` struct but the
+ // last field (the file name) is unsized. So an offset has to be
+ // used to get the file name slice.
+ let (name, is_directory, next_entry) = unsafe {
+ let info = buffer.as_ptr().cast::<c::FILE_ID_BOTH_DIR_INFO>();
+ let next_entry = (*info).NextEntryOffset as usize;
+ let name = crate::slice::from_raw_parts(
+ (*info).FileName.as_ptr().cast::<u16>(),
+ (*info).FileNameLength as usize / size_of::<u16>(),
+ );
+ let is_directory = ((*info).FileAttributes & c::FILE_ATTRIBUTE_DIRECTORY) != 0;
+
+ (name, is_directory, next_entry)
+ };
+
+ if next_entry == 0 {
+ self.buffer = None
+ } else {
+ self.cursor += next_entry
+ }
+
+ // Skip `.` and `..` pseudo entries.
+ const DOT: u16 = b'.' as u16;
+ match name {
+ [DOT] | [DOT, DOT] => self.next(),
+ _ => Some((name, is_directory)),
+ }
+ }
+}
+
+/// Open a link relative to the parent directory, ensure no symlinks are followed.
+fn open_link_no_reparse(parent: &File, name: &[u16], access: u32) -> io::Result<File> {
+ // This is implemented using the lower level `NtCreateFile` function as
+ // unfortunately opening a file relative to a parent is not supported by
+ // win32 functions. It is however a fundamental feature of the NT kernel.
+ //
+ // See https://docs.microsoft.com/en-us/windows/win32/api/winternl/nf-winternl-ntcreatefile
+ unsafe {
+ let mut handle = ptr::null_mut();
+ let mut io_status = c::IO_STATUS_BLOCK::default();
+ let name_str = c::UNICODE_STRING::from_ref(name);
+ use crate::sync::atomic::{AtomicU32, Ordering};
+ // The `OBJ_DONT_REPARSE` attribute ensures that we haven't been
+ // tricked into following a symlink. However, it may not be available in
+ // earlier versions of Windows.
+ static ATTRIBUTES: AtomicU32 = AtomicU32::new(c::OBJ_DONT_REPARSE);
+ let object = c::OBJECT_ATTRIBUTES {
+ ObjectName: &name_str,
+ RootDirectory: parent.as_raw_handle(),
+ Attributes: ATTRIBUTES.load(Ordering::Relaxed),
+ ..c::OBJECT_ATTRIBUTES::default()
+ };
+ let status = c::NtCreateFile(
+ &mut handle,
+ access,
+ &object,
+ &mut io_status,
+ crate::ptr::null_mut(),
+ 0,
+ c::FILE_SHARE_DELETE | c::FILE_SHARE_READ | c::FILE_SHARE_WRITE,
+ c::FILE_OPEN,
+ // If `name` is a symlink then open the link rather than the target.
+ c::FILE_OPEN_REPARSE_POINT,
+ crate::ptr::null_mut(),
+ 0,
+ );
+ // Convert an NTSTATUS to the more familiar Win32 error codes (aka "DosError")
+ if c::nt_success(status) {
+ Ok(File::from_raw_handle(handle))
+ } else if status == c::STATUS_DELETE_PENDING {
+ // We make a special exception for `STATUS_DELETE_PENDING` because
+ // otherwise this will be mapped to `ERROR_ACCESS_DENIED` which is
+ // very unhelpful.
+ Err(io::Error::from_raw_os_error(c::ERROR_DELETE_PENDING as _))
+ } else if status == c::STATUS_INVALID_PARAMETER
+ && ATTRIBUTES.load(Ordering::Relaxed) == c::OBJ_DONT_REPARSE
+ {
+ // Try without `OBJ_DONT_REPARSE`. See above.
+ ATTRIBUTES.store(0, Ordering::Relaxed);
+ open_link_no_reparse(parent, name, access)
+ } else {
+ Err(io::Error::from_raw_os_error(c::RtlNtStatusToDosError(status) as _))
+ }
+ }
+}
+
+impl AsInner<Handle> for File {
+ fn as_inner(&self) -> &Handle {
+ &self.handle
+ }
+}
+
+impl IntoInner<Handle> for File {
+ fn into_inner(self) -> Handle {
+ self.handle
+ }
+}
+
+impl FromInner<Handle> for File {
+ fn from_inner(handle: Handle) -> File {
+ File { handle }
+ }
+}
+
+impl AsHandle for File {
+ fn as_handle(&self) -> BorrowedHandle<'_> {
+ self.as_inner().as_handle()
+ }
+}
+
+impl AsRawHandle for File {
+ fn as_raw_handle(&self) -> RawHandle {
+ self.as_inner().as_raw_handle()
+ }
+}
+
+impl IntoRawHandle for File {
+ fn into_raw_handle(self) -> RawHandle {
+ self.into_inner().into_raw_handle()
+ }
+}
+
+impl FromRawHandle for File {
+ unsafe fn from_raw_handle(raw_handle: RawHandle) -> Self {
+ Self { handle: FromInner::from_inner(FromRawHandle::from_raw_handle(raw_handle)) }
+ }
+}
+
+impl fmt::Debug for File {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ // FIXME(#24570): add more info here (e.g., mode)
+ let mut b = f.debug_struct("File");
+ b.field("handle", &self.handle.as_raw_handle());
+ if let Ok(path) = get_path(&self) {
+ b.field("path", &path);
+ }
+ b.finish()
+ }
+}
+
+impl FileAttr {
+ pub fn size(&self) -> u64 {
+ self.file_size
+ }
+
+ pub fn perm(&self) -> FilePermissions {
+ FilePermissions { attrs: self.attributes }
+ }
+
+ pub fn attrs(&self) -> u32 {
+ self.attributes
+ }
+
+ pub fn file_type(&self) -> FileType {
+ FileType::new(self.attributes, self.reparse_tag)
+ }
+
+ pub fn modified(&self) -> io::Result<SystemTime> {
+ Ok(SystemTime::from(self.last_write_time))
+ }
+
+ pub fn accessed(&self) -> io::Result<SystemTime> {
+ Ok(SystemTime::from(self.last_access_time))
+ }
+
+ pub fn created(&self) -> io::Result<SystemTime> {
+ Ok(SystemTime::from(self.creation_time))
+ }
+
+ pub fn modified_u64(&self) -> u64 {
+ to_u64(&self.last_write_time)
+ }
+
+ pub fn accessed_u64(&self) -> u64 {
+ to_u64(&self.last_access_time)
+ }
+
+ pub fn created_u64(&self) -> u64 {
+ to_u64(&self.creation_time)
+ }
+
+ pub fn volume_serial_number(&self) -> Option<u32> {
+ self.volume_serial_number
+ }
+
+ pub fn number_of_links(&self) -> Option<u32> {
+ self.number_of_links
+ }
+
+ pub fn file_index(&self) -> Option<u64> {
+ self.file_index
+ }
+}
+impl From<c::WIN32_FIND_DATAW> for FileAttr {
+ fn from(wfd: c::WIN32_FIND_DATAW) -> Self {
+ FileAttr {
+ attributes: wfd.dwFileAttributes,
+ creation_time: wfd.ftCreationTime,
+ last_access_time: wfd.ftLastAccessTime,
+ last_write_time: wfd.ftLastWriteTime,
+ file_size: ((wfd.nFileSizeHigh as u64) << 32) | (wfd.nFileSizeLow as u64),
+ reparse_tag: if wfd.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
+ // reserved unless this is a reparse point
+ wfd.dwReserved0
+ } else {
+ 0
+ },
+ volume_serial_number: None,
+ number_of_links: None,
+ file_index: None,
+ }
+ }
+}
+
+fn to_u64(ft: &c::FILETIME) -> u64 {
+ (ft.dwLowDateTime as u64) | ((ft.dwHighDateTime as u64) << 32)
+}
+
+impl FilePermissions {
+ pub fn readonly(&self) -> bool {
+ self.attrs & c::FILE_ATTRIBUTE_READONLY != 0
+ }
+
+ pub fn set_readonly(&mut self, readonly: bool) {
+ if readonly {
+ self.attrs |= c::FILE_ATTRIBUTE_READONLY;
+ } else {
+ self.attrs &= !c::FILE_ATTRIBUTE_READONLY;
+ }
+ }
+}
+
+impl FileTimes {
+ pub fn set_accessed(&mut self, t: SystemTime) {
+ self.accessed = Some(t.into_inner());
+ }
+
+ pub fn set_modified(&mut self, t: SystemTime) {
+ self.modified = Some(t.into_inner());
+ }
+}
+
+impl FileType {
+ fn new(attrs: c::DWORD, reparse_tag: c::DWORD) -> FileType {
+ FileType { attributes: attrs, reparse_tag }
+ }
+ pub fn is_dir(&self) -> bool {
+ !self.is_symlink() && self.is_directory()
+ }
+ pub fn is_file(&self) -> bool {
+ !self.is_symlink() && !self.is_directory()
+ }
+ pub fn is_symlink(&self) -> bool {
+ self.is_reparse_point() && self.is_reparse_tag_name_surrogate()
+ }
+ pub fn is_symlink_dir(&self) -> bool {
+ self.is_symlink() && self.is_directory()
+ }
+ pub fn is_symlink_file(&self) -> bool {
+ self.is_symlink() && !self.is_directory()
+ }
+ fn is_directory(&self) -> bool {
+ self.attributes & c::FILE_ATTRIBUTE_DIRECTORY != 0
+ }
+ fn is_reparse_point(&self) -> bool {
+ self.attributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0
+ }
+ fn is_reparse_tag_name_surrogate(&self) -> bool {
+ self.reparse_tag & 0x20000000 != 0
+ }
+}
+
+impl DirBuilder {
+ pub fn new() -> DirBuilder {
+ DirBuilder
+ }
+
+ pub fn mkdir(&self, p: &Path) -> io::Result<()> {
+ let p = maybe_verbatim(p)?;
+ cvt(unsafe { c::CreateDirectoryW(p.as_ptr(), ptr::null_mut()) })?;
+ Ok(())
+ }
+}
+
+pub fn readdir(p: &Path) -> io::Result<ReadDir> {
+ let root = p.to_path_buf();
+ let star = p.join("*");
+ let path = maybe_verbatim(&star)?;
+
+ unsafe {
+ let mut wfd = mem::zeroed();
+ let find_handle = c::FindFirstFileW(path.as_ptr(), &mut wfd);
+ if find_handle != c::INVALID_HANDLE_VALUE {
+ Ok(ReadDir {
+ handle: FindNextFileHandle(find_handle),
+ root: Arc::new(root),
+ first: Some(wfd),
+ })
+ } else {
+ Err(Error::last_os_error())
+ }
+ }
+}
+
+pub fn unlink(p: &Path) -> io::Result<()> {
+ let p_u16s = maybe_verbatim(p)?;
+ cvt(unsafe { c::DeleteFileW(p_u16s.as_ptr()) })?;
+ Ok(())
+}
+
+pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
+ let old = maybe_verbatim(old)?;
+ let new = maybe_verbatim(new)?;
+ cvt(unsafe { c::MoveFileExW(old.as_ptr(), new.as_ptr(), c::MOVEFILE_REPLACE_EXISTING) })?;
+ Ok(())
+}
+
+pub fn rmdir(p: &Path) -> io::Result<()> {
+ let p = maybe_verbatim(p)?;
+ cvt(unsafe { c::RemoveDirectoryW(p.as_ptr()) })?;
+ Ok(())
+}
+
+/// Open a file or directory without following symlinks.
+fn open_link(path: &Path, access_mode: u32) -> io::Result<File> {
+ let mut opts = OpenOptions::new();
+ opts.access_mode(access_mode);
+ // `FILE_FLAG_BACKUP_SEMANTICS` allows opening directories.
+ // `FILE_FLAG_OPEN_REPARSE_POINT` opens a link instead of its target.
+ opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS | c::FILE_FLAG_OPEN_REPARSE_POINT);
+ File::open(path, &opts)
+}
+
+pub fn remove_dir_all(path: &Path) -> io::Result<()> {
+ let file = open_link(path, c::DELETE | c::FILE_LIST_DIRECTORY)?;
+
+ // Test if the file is not a directory or a symlink to a directory.
+ if (file.basic_info()?.FileAttributes & c::FILE_ATTRIBUTE_DIRECTORY) == 0 {
+ return Err(io::Error::from_raw_os_error(c::ERROR_DIRECTORY as _));
+ }
+
+ match remove_dir_all_iterative(&file, File::posix_delete) {
+ Err(e) => {
+ if let Some(code) = e.raw_os_error() {
+ match code as u32 {
+ // If POSIX delete is not supported for this filesystem then fallback to win32 delete.
+ c::ERROR_NOT_SUPPORTED
+ | c::ERROR_INVALID_FUNCTION
+ | c::ERROR_INVALID_PARAMETER => {
+ remove_dir_all_iterative(&file, File::win32_delete)
+ }
+ _ => Err(e),
+ }
+ } else {
+ Err(e)
+ }
+ }
+ ok => ok,
+ }
+}
+
+fn remove_dir_all_iterative(f: &File, delete: fn(&File) -> io::Result<()>) -> io::Result<()> {
+ // When deleting files we may loop this many times when certain error conditions occur.
+ // This allows remove_dir_all to succeed when the error is temporary.
+ const MAX_RETRIES: u32 = 10;
+
+ let mut buffer = DirBuff::new();
+ let mut dirlist = vec![f.duplicate()?];
+
+ // FIXME: This is a hack so we can push to the dirlist vec after borrowing from it.
+ fn copy_handle(f: &File) -> mem::ManuallyDrop<File> {
+ unsafe { mem::ManuallyDrop::new(File::from_raw_handle(f.as_raw_handle())) }
+ }
+
+ let mut restart = true;
+ while let Some(dir) = dirlist.last() {
+ let dir = copy_handle(dir);
+
+ // Fill the buffer and iterate the entries.
+ let more_data = dir.fill_dir_buff(&mut buffer, restart)?;
+ restart = false;
+ for (name, is_directory) in buffer.iter() {
+ if is_directory {
+ let child_dir = open_link_no_reparse(
+ &dir,
+ name,
+ c::SYNCHRONIZE | c::DELETE | c::FILE_LIST_DIRECTORY,
+ )?;
+ dirlist.push(child_dir);
+ } else {
+ for i in 1..=MAX_RETRIES {
+ let result = open_link_no_reparse(&dir, name, c::SYNCHRONIZE | c::DELETE);
+ match result {
+ Ok(f) => delete(&f)?,
+ // Already deleted, so skip.
+ Err(e) if e.kind() == io::ErrorKind::NotFound => break,
+ // Retry a few times if the file is locked or a delete is already in progress.
+ Err(e)
+ if i < MAX_RETRIES
+ && (e.raw_os_error() == Some(c::ERROR_DELETE_PENDING as _)
+ || e.raw_os_error()
+ == Some(c::ERROR_SHARING_VIOLATION as _)) => {}
+ // Otherwise return the error.
+ Err(e) => return Err(e),
+ }
+ thread::yield_now();
+ }
+ }
+ }
+ // If there were no more files then delete the directory.
+ if !more_data {
+ if let Some(dir) = dirlist.pop() {
+ // Retry deleting a few times in case we need to wait for a file to be deleted.
+ for i in 1..=MAX_RETRIES {
+ let result = delete(&dir);
+ if let Err(e) = result {
+ if i == MAX_RETRIES || e.kind() != io::ErrorKind::DirectoryNotEmpty {
+ return Err(e);
+ }
+ thread::yield_now();
+ } else {
+ break;
+ }
+ }
+ }
+ }
+ }
+ Ok(())
+}
+
+pub fn readlink(path: &Path) -> io::Result<PathBuf> {
+ // Open the link with no access mode, instead of generic read.
+ // By default FILE_LIST_DIRECTORY is denied for the junction "C:\Documents and Settings", so
+ // this is needed for a common case.
+ let mut opts = OpenOptions::new();
+ opts.access_mode(0);
+ opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS);
+ let file = File::open(&path, &opts)?;
+ file.readlink()
+}
+
+pub fn symlink(original: &Path, link: &Path) -> io::Result<()> {
+ symlink_inner(original, link, false)
+}
+
+pub fn symlink_inner(original: &Path, link: &Path, dir: bool) -> io::Result<()> {
+ let original = to_u16s(original)?;
+ let link = maybe_verbatim(link)?;
+ let flags = if dir { c::SYMBOLIC_LINK_FLAG_DIRECTORY } else { 0 };
+ // Formerly, symlink creation required the SeCreateSymbolicLink privilege. For the Windows 10
+ // Creators Update, Microsoft loosened this to allow unprivileged symlink creation if the
+ // computer is in Developer Mode, but SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE must be
+ // added to dwFlags to opt into this behaviour.
+ let result = cvt(unsafe {
+ c::CreateSymbolicLinkW(
+ link.as_ptr(),
+ original.as_ptr(),
+ flags | c::SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE,
+ ) as c::BOOL
+ });
+ if let Err(err) = result {
+ if err.raw_os_error() == Some(c::ERROR_INVALID_PARAMETER as i32) {
+ // Older Windows objects to SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE,
+ // so if we encounter ERROR_INVALID_PARAMETER, retry without that flag.
+ cvt(unsafe {
+ c::CreateSymbolicLinkW(link.as_ptr(), original.as_ptr(), flags) as c::BOOL
+ })?;
+ } else {
+ return Err(err);
+ }
+ }
+ Ok(())
+}
+
+#[cfg(not(target_vendor = "uwp"))]
+pub fn link(original: &Path, link: &Path) -> io::Result<()> {
+ let original = maybe_verbatim(original)?;
+ let link = maybe_verbatim(link)?;
+ cvt(unsafe { c::CreateHardLinkW(link.as_ptr(), original.as_ptr(), ptr::null_mut()) })?;
+ Ok(())
+}
+
+#[cfg(target_vendor = "uwp")]
+pub fn link(_original: &Path, _link: &Path) -> io::Result<()> {
+ return Err(io::const_io_error!(
+ io::ErrorKind::Unsupported,
+ "hard link are not supported on UWP",
+ ));
+}
+
+pub fn stat(path: &Path) -> io::Result<FileAttr> {
+ metadata(path, ReparsePoint::Follow)
+}
+
+pub fn lstat(path: &Path) -> io::Result<FileAttr> {
+ metadata(path, ReparsePoint::Open)
+}
+
+#[repr(u32)]
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum ReparsePoint {
+ Follow = 0,
+ Open = c::FILE_FLAG_OPEN_REPARSE_POINT,
+}
+impl ReparsePoint {
+ fn as_flag(self) -> u32 {
+ self as u32
+ }
+}
+
+fn metadata(path: &Path, reparse: ReparsePoint) -> io::Result<FileAttr> {
+ let mut opts = OpenOptions::new();
+ // No read or write permissions are necessary
+ opts.access_mode(0);
+ opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS | reparse.as_flag());
+
+ // Attempt to open the file normally.
+ // If that fails with `ERROR_SHARING_VIOLATION` then retry using `FindFirstFileW`.
+ // If the fallback fails for any reason we return the original error.
+ match File::open(path, &opts) {
+ Ok(file) => file.file_attr(),
+ Err(e) if e.raw_os_error() == Some(c::ERROR_SHARING_VIOLATION as _) => {
+ // `ERROR_SHARING_VIOLATION` will almost never be returned.
+ // Usually if a file is locked you can still read some metadata.
+ // However, there are special system files, such as
+ // `C:\hiberfil.sys`, that are locked in a way that denies even that.
+ unsafe {
+ let path = maybe_verbatim(path)?;
+
+ // `FindFirstFileW` accepts wildcard file names.
+ // Fortunately wildcards are not valid file names and
+ // `ERROR_SHARING_VIOLATION` means the file exists (but is locked)
+ // therefore it's safe to assume the file name given does not
+ // include wildcards.
+ let mut wfd = mem::zeroed();
+ let handle = c::FindFirstFileW(path.as_ptr(), &mut wfd);
+
+ if handle == c::INVALID_HANDLE_VALUE {
+ // This can fail if the user does not have read access to the
+ // directory.
+ Err(e)
+ } else {
+ // We no longer need the find handle.
+ c::FindClose(handle);
+
+ // `FindFirstFileW` reads the cached file information from the
+ // directory. The downside is that this metadata may be outdated.
+ let attrs = FileAttr::from(wfd);
+ if reparse == ReparsePoint::Follow && attrs.file_type().is_symlink() {
+ Err(e)
+ } else {
+ Ok(attrs)
+ }
+ }
+ }
+ }
+ Err(e) => Err(e),
+ }
+}
+
+pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
+ let p = maybe_verbatim(p)?;
+ unsafe {
+ cvt(c::SetFileAttributesW(p.as_ptr(), perm.attrs))?;
+ Ok(())
+ }
+}
+
+fn get_path(f: &File) -> io::Result<PathBuf> {
+ super::fill_utf16_buf(
+ |buf, sz| unsafe {
+ c::GetFinalPathNameByHandleW(f.handle.as_raw_handle(), buf, sz, c::VOLUME_NAME_DOS)
+ },
+ |buf| PathBuf::from(OsString::from_wide(buf)),
+ )
+}
+
+pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
+ let mut opts = OpenOptions::new();
+ // No read or write permissions are necessary
+ opts.access_mode(0);
+ // This flag is so we can open directories too
+ opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
+ let f = File::open(p, &opts)?;
+ get_path(&f)
+}
+
+pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
+ unsafe extern "system" fn callback(
+ _TotalFileSize: c::LARGE_INTEGER,
+ _TotalBytesTransferred: c::LARGE_INTEGER,
+ _StreamSize: c::LARGE_INTEGER,
+ StreamBytesTransferred: c::LARGE_INTEGER,
+ dwStreamNumber: c::DWORD,
+ _dwCallbackReason: c::DWORD,
+ _hSourceFile: c::HANDLE,
+ _hDestinationFile: c::HANDLE,
+ lpData: c::LPVOID,
+ ) -> c::DWORD {
+ if dwStreamNumber == 1 {
+ *(lpData as *mut i64) = StreamBytesTransferred;
+ }
+ c::PROGRESS_CONTINUE
+ }
+ let pfrom = maybe_verbatim(from)?;
+ let pto = maybe_verbatim(to)?;
+ let mut size = 0i64;
+ cvt(unsafe {
+ c::CopyFileExW(
+ pfrom.as_ptr(),
+ pto.as_ptr(),
+ Some(callback),
+ &mut size as *mut _ as *mut _,
+ ptr::null_mut(),
+ 0,
+ )
+ })?;
+ Ok(size as u64)
+}
+
+#[allow(dead_code)]
+pub fn symlink_junction<P: AsRef<Path>, Q: AsRef<Path>>(
+ original: P,
+ junction: Q,
+) -> io::Result<()> {
+ symlink_junction_inner(original.as_ref(), junction.as_ref())
+}
+
+// Creating a directory junction on windows involves dealing with reparse
+// points and the DeviceIoControl function, and this code is a skeleton of
+// what can be found here:
+//
+// http://www.flexhex.com/docs/articles/hard-links.phtml
+#[allow(dead_code)]
+fn symlink_junction_inner(original: &Path, junction: &Path) -> io::Result<()> {
+ let d = DirBuilder::new();
+ d.mkdir(&junction)?;
+
+ let mut opts = OpenOptions::new();
+ opts.write(true);
+ opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS);
+ let f = File::open(junction, &opts)?;
+ let h = f.as_inner().as_raw_handle();
+
+ unsafe {
+ let mut data = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
+ let db = data.as_mut_ptr() as *mut c::REPARSE_MOUNTPOINT_DATA_BUFFER;
+ let buf = &mut (*db).ReparseTarget as *mut c::WCHAR;
+ let mut i = 0;
+ // FIXME: this conversion is very hacky
+ let v = br"\??\";
+ let v = v.iter().map(|x| *x as u16);
+ for c in v.chain(original.as_os_str().encode_wide()) {
+ *buf.offset(i) = c;
+ i += 1;
+ }
+ *buf.offset(i) = 0;
+ i += 1;
+ (*db).ReparseTag = c::IO_REPARSE_TAG_MOUNT_POINT;
+ (*db).ReparseTargetMaximumLength = (i * 2) as c::WORD;
+ (*db).ReparseTargetLength = ((i - 1) * 2) as c::WORD;
+ (*db).ReparseDataLength = (*db).ReparseTargetLength as c::DWORD + 12;
+
+ let mut ret = 0;
+ cvt(c::DeviceIoControl(
+ h as *mut _,
+ c::FSCTL_SET_REPARSE_POINT,
+ data.as_ptr() as *mut _,
+ (*db).ReparseDataLength + 8,
+ ptr::null_mut(),
+ 0,
+ &mut ret,
+ ptr::null_mut(),
+ ))
+ .map(drop)
+ }
+}
+
+// Try to see if a file exists but, unlike `exists`, report I/O errors.
+pub fn try_exists(path: &Path) -> io::Result<bool> {
+ // Open the file to ensure any symlinks are followed to their target.
+ let mut opts = OpenOptions::new();
+ // No read, write, etc access rights are needed.
+ opts.access_mode(0);
+ // Backup semantics enables opening directories as well as files.
+ opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
+ match File::open(path, &opts) {
+ Err(e) => match e.kind() {
+ // The file definitely does not exist
+ io::ErrorKind::NotFound => Ok(false),
+
+ // `ERROR_SHARING_VIOLATION` means that the file has been locked by
+ // another process. This is often temporary so we simply report it
+ // as the file existing.
+ _ if e.raw_os_error() == Some(c::ERROR_SHARING_VIOLATION as i32) => Ok(true),
+
+ // Other errors such as `ERROR_ACCESS_DENIED` may indicate that the
+ // file exists. However, these types of errors are usually more
+ // permanent so we report them here.
+ _ => Err(e),
+ },
+ // The file was opened successfully therefore it must exist,
+ Ok(_) => Ok(true),
+ }
+}
diff --git a/library/std/src/sys/windows/handle.rs b/library/std/src/sys/windows/handle.rs
new file mode 100644
index 000000000..e24b09cc9
--- /dev/null
+++ b/library/std/src/sys/windows/handle.rs
@@ -0,0 +1,335 @@
+#![unstable(issue = "none", feature = "windows_handle")]
+
+#[cfg(test)]
+mod tests;
+
+use crate::cmp;
+use crate::io::{self, ErrorKind, IoSlice, IoSliceMut, Read, ReadBuf};
+use crate::mem;
+use crate::os::windows::io::{
+ AsHandle, AsRawHandle, BorrowedHandle, FromRawHandle, IntoRawHandle, OwnedHandle, RawHandle,
+};
+use crate::ptr;
+use crate::sys::c;
+use crate::sys::cvt;
+use crate::sys_common::{AsInner, FromInner, IntoInner};
+
+/// An owned container for `HANDLE` object, closing them on Drop.
+///
+/// All methods are inherited through a `Deref` impl to `RawHandle`
+pub struct Handle(OwnedHandle);
+
+impl Handle {
+ pub fn new_event(manual: bool, init: bool) -> io::Result<Handle> {
+ unsafe {
+ let event =
+ c::CreateEventW(ptr::null_mut(), manual as c::BOOL, init as c::BOOL, ptr::null());
+ if event.is_null() {
+ Err(io::Error::last_os_error())
+ } else {
+ Ok(Handle::from_raw_handle(event))
+ }
+ }
+ }
+}
+
+impl AsInner<OwnedHandle> for Handle {
+ fn as_inner(&self) -> &OwnedHandle {
+ &self.0
+ }
+}
+
+impl IntoInner<OwnedHandle> for Handle {
+ fn into_inner(self) -> OwnedHandle {
+ self.0
+ }
+}
+
+impl FromInner<OwnedHandle> for Handle {
+ fn from_inner(file_desc: OwnedHandle) -> Self {
+ Self(file_desc)
+ }
+}
+
+impl AsHandle for Handle {
+ fn as_handle(&self) -> BorrowedHandle<'_> {
+ self.0.as_handle()
+ }
+}
+
+impl AsRawHandle for Handle {
+ fn as_raw_handle(&self) -> RawHandle {
+ self.0.as_raw_handle()
+ }
+}
+
+impl IntoRawHandle for Handle {
+ fn into_raw_handle(self) -> RawHandle {
+ self.0.into_raw_handle()
+ }
+}
+
+impl FromRawHandle for Handle {
+ unsafe fn from_raw_handle(raw_handle: RawHandle) -> Self {
+ Self(FromRawHandle::from_raw_handle(raw_handle))
+ }
+}
+
+impl Handle {
+ pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
+ let res = unsafe { self.synchronous_read(buf.as_mut_ptr().cast(), buf.len(), None) };
+
+ match res {
+ Ok(read) => Ok(read as usize),
+
+ // The special treatment of BrokenPipe is to deal with Windows
+ // pipe semantics, which yields this error when *reading* from
+ // a pipe after the other end has closed; we interpret that as
+ // EOF on the pipe.
+ Err(ref e) if e.kind() == ErrorKind::BrokenPipe => Ok(0),
+
+ Err(e) => Err(e),
+ }
+ }
+
+ pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
+ crate::io::default_read_vectored(|buf| self.read(buf), bufs)
+ }
+
+ #[inline]
+ pub fn is_read_vectored(&self) -> bool {
+ false
+ }
+
+ pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
+ let res =
+ unsafe { self.synchronous_read(buf.as_mut_ptr().cast(), buf.len(), Some(offset)) };
+
+ match res {
+ Ok(read) => Ok(read as usize),
+ Err(ref e) if e.raw_os_error() == Some(c::ERROR_HANDLE_EOF as i32) => Ok(0),
+ Err(e) => Err(e),
+ }
+ }
+
+ pub fn read_buf(&self, buf: &mut ReadBuf<'_>) -> io::Result<()> {
+ let res = unsafe {
+ self.synchronous_read(buf.unfilled_mut().as_mut_ptr(), buf.remaining(), None)
+ };
+
+ match res {
+ Ok(read) => {
+ // Safety: `read` bytes were written to the initialized portion of the buffer
+ unsafe {
+ buf.assume_init(read as usize);
+ }
+ buf.add_filled(read as usize);
+ Ok(())
+ }
+
+ // The special treatment of BrokenPipe is to deal with Windows
+ // pipe semantics, which yields this error when *reading* from
+ // a pipe after the other end has closed; we interpret that as
+ // EOF on the pipe.
+ Err(ref e) if e.kind() == ErrorKind::BrokenPipe => Ok(()),
+
+ Err(e) => Err(e),
+ }
+ }
+
+ pub unsafe fn read_overlapped(
+ &self,
+ buf: &mut [u8],
+ overlapped: *mut c::OVERLAPPED,
+ ) -> io::Result<Option<usize>> {
+ let len = cmp::min(buf.len(), <c::DWORD>::MAX as usize) as c::DWORD;
+ let mut amt = 0;
+ let res = cvt(c::ReadFile(
+ self.as_handle(),
+ buf.as_ptr() as c::LPVOID,
+ len,
+ &mut amt,
+ overlapped,
+ ));
+ match res {
+ Ok(_) => Ok(Some(amt as usize)),
+ Err(e) => {
+ if e.raw_os_error() == Some(c::ERROR_IO_PENDING as i32) {
+ Ok(None)
+ } else if e.raw_os_error() == Some(c::ERROR_BROKEN_PIPE as i32) {
+ Ok(Some(0))
+ } else {
+ Err(e)
+ }
+ }
+ }
+ }
+
+ pub fn overlapped_result(
+ &self,
+ overlapped: *mut c::OVERLAPPED,
+ wait: bool,
+ ) -> io::Result<usize> {
+ unsafe {
+ let mut bytes = 0;
+ let wait = if wait { c::TRUE } else { c::FALSE };
+ let res =
+ cvt(c::GetOverlappedResult(self.as_raw_handle(), overlapped, &mut bytes, wait));
+ match res {
+ Ok(_) => Ok(bytes as usize),
+ Err(e) => {
+ if e.raw_os_error() == Some(c::ERROR_HANDLE_EOF as i32)
+ || e.raw_os_error() == Some(c::ERROR_BROKEN_PIPE as i32)
+ {
+ Ok(0)
+ } else {
+ Err(e)
+ }
+ }
+ }
+ }
+ }
+
+ pub fn cancel_io(&self) -> io::Result<()> {
+ unsafe { cvt(c::CancelIo(self.as_raw_handle())).map(drop) }
+ }
+
+ pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
+ self.synchronous_write(&buf, None)
+ }
+
+ pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
+ crate::io::default_write_vectored(|buf| self.write(buf), bufs)
+ }
+
+ #[inline]
+ pub fn is_write_vectored(&self) -> bool {
+ false
+ }
+
+ pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
+ self.synchronous_write(&buf, Some(offset))
+ }
+
+ pub fn try_clone(&self) -> io::Result<Self> {
+ Ok(Self(self.0.try_clone()?))
+ }
+
+ pub fn duplicate(
+ &self,
+ access: c::DWORD,
+ inherit: bool,
+ options: c::DWORD,
+ ) -> io::Result<Self> {
+ Ok(Self(self.0.as_handle().duplicate(access, inherit, options)?))
+ }
+
+ /// Performs a synchronous read.
+ ///
+ /// If the handle is opened for asynchronous I/O then this abort the process.
+ /// See #81357.
+ ///
+ /// If `offset` is `None` then the current file position is used.
+ unsafe fn synchronous_read(
+ &self,
+ buf: *mut mem::MaybeUninit<u8>,
+ len: usize,
+ offset: Option<u64>,
+ ) -> io::Result<usize> {
+ let mut io_status = c::IO_STATUS_BLOCK::default();
+
+ // The length is clamped at u32::MAX.
+ let len = cmp::min(len, c::DWORD::MAX as usize) as c::DWORD;
+ let status = c::NtReadFile(
+ self.as_handle(),
+ ptr::null_mut(),
+ None,
+ ptr::null_mut(),
+ &mut io_status,
+ buf,
+ len,
+ offset.map(|n| n as _).as_ref(),
+ None,
+ );
+
+ let status = if status == c::STATUS_PENDING {
+ c::WaitForSingleObject(self.as_raw_handle(), c::INFINITE);
+ io_status.status()
+ } else {
+ status
+ };
+ match status {
+ // If the operation has not completed then abort the process.
+ // Doing otherwise means that the buffer and stack may be written to
+ // after this function returns.
+ c::STATUS_PENDING => rtabort!("I/O error: operation failed to complete synchronously"),
+
+ // Return `Ok(0)` when there's nothing more to read.
+ c::STATUS_END_OF_FILE => Ok(0),
+
+ // Success!
+ status if c::nt_success(status) => Ok(io_status.Information),
+
+ status => {
+ let error = c::RtlNtStatusToDosError(status);
+ Err(io::Error::from_raw_os_error(error as _))
+ }
+ }
+ }
+
+ /// Performs a synchronous write.
+ ///
+ /// If the handle is opened for asynchronous I/O then this abort the process.
+ /// See #81357.
+ ///
+ /// If `offset` is `None` then the current file position is used.
+ fn synchronous_write(&self, buf: &[u8], offset: Option<u64>) -> io::Result<usize> {
+ let mut io_status = c::IO_STATUS_BLOCK::default();
+
+ // The length is clamped at u32::MAX.
+ let len = cmp::min(buf.len(), c::DWORD::MAX as usize) as c::DWORD;
+ let status = unsafe {
+ c::NtWriteFile(
+ self.as_handle(),
+ ptr::null_mut(),
+ None,
+ ptr::null_mut(),
+ &mut io_status,
+ buf.as_ptr(),
+ len,
+ offset.map(|n| n as _).as_ref(),
+ None,
+ )
+ };
+ let status = if status == c::STATUS_PENDING {
+ unsafe { c::WaitForSingleObject(self.as_raw_handle(), c::INFINITE) };
+ io_status.status()
+ } else {
+ status
+ };
+ match status {
+ // If the operation has not completed then abort the process.
+ // Doing otherwise means that the buffer may be read and the stack
+ // written to after this function returns.
+ c::STATUS_PENDING => rtabort!("I/O error: operation failed to complete synchronously"),
+
+ // Success!
+ status if c::nt_success(status) => Ok(io_status.Information),
+
+ status => {
+ let error = unsafe { c::RtlNtStatusToDosError(status) };
+ Err(io::Error::from_raw_os_error(error as _))
+ }
+ }
+ }
+}
+
+impl<'a> Read for &'a Handle {
+ fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
+ (**self).read(buf)
+ }
+
+ fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
+ (**self).read_vectored(bufs)
+ }
+}
diff --git a/library/std/src/sys/windows/handle/tests.rs b/library/std/src/sys/windows/handle/tests.rs
new file mode 100644
index 000000000..d836dae4c
--- /dev/null
+++ b/library/std/src/sys/windows/handle/tests.rs
@@ -0,0 +1,22 @@
+use crate::sys::pipe::{anon_pipe, Pipes};
+use crate::{thread, time};
+
+/// Test the synchronous fallback for overlapped I/O.
+#[test]
+fn overlapped_handle_fallback() {
+ // Create some pipes. `ours` will be asynchronous.
+ let Pipes { ours, theirs } = anon_pipe(true, false).unwrap();
+
+ let async_readable = ours.into_handle();
+ let sync_writeable = theirs.into_handle();
+
+ thread::scope(|_| {
+ thread::sleep(time::Duration::from_millis(100));
+ sync_writeable.write(b"hello world!").unwrap();
+ });
+
+ // The pipe buffer starts empty so reading won't complete synchronously unless
+ // our fallback path works.
+ let mut buffer = [0u8; 1024];
+ async_readable.read(&mut buffer).unwrap();
+}
diff --git a/library/std/src/sys/windows/io.rs b/library/std/src/sys/windows/io.rs
new file mode 100644
index 000000000..fb06df1f8
--- /dev/null
+++ b/library/std/src/sys/windows/io.rs
@@ -0,0 +1,80 @@
+use crate::marker::PhantomData;
+use crate::slice;
+use crate::sys::c;
+
+#[derive(Copy, Clone)]
+#[repr(transparent)]
+pub struct IoSlice<'a> {
+ vec: c::WSABUF,
+ _p: PhantomData<&'a [u8]>,
+}
+
+impl<'a> IoSlice<'a> {
+ #[inline]
+ pub fn new(buf: &'a [u8]) -> IoSlice<'a> {
+ assert!(buf.len() <= c::ULONG::MAX as usize);
+ IoSlice {
+ vec: c::WSABUF {
+ len: buf.len() as c::ULONG,
+ buf: buf.as_ptr() as *mut u8 as *mut c::CHAR,
+ },
+ _p: PhantomData,
+ }
+ }
+
+ #[inline]
+ pub fn advance(&mut self, n: usize) {
+ if (self.vec.len as usize) < n {
+ panic!("advancing IoSlice beyond its length");
+ }
+
+ unsafe {
+ self.vec.len -= n as c::ULONG;
+ self.vec.buf = self.vec.buf.add(n);
+ }
+ }
+
+ #[inline]
+ pub fn as_slice(&self) -> &[u8] {
+ unsafe { slice::from_raw_parts(self.vec.buf as *mut u8, self.vec.len as usize) }
+ }
+}
+
+#[repr(transparent)]
+pub struct IoSliceMut<'a> {
+ vec: c::WSABUF,
+ _p: PhantomData<&'a mut [u8]>,
+}
+
+impl<'a> IoSliceMut<'a> {
+ #[inline]
+ pub fn new(buf: &'a mut [u8]) -> IoSliceMut<'a> {
+ assert!(buf.len() <= c::ULONG::MAX as usize);
+ IoSliceMut {
+ vec: c::WSABUF { len: buf.len() as c::ULONG, buf: buf.as_mut_ptr() as *mut c::CHAR },
+ _p: PhantomData,
+ }
+ }
+
+ #[inline]
+ pub fn advance(&mut self, n: usize) {
+ if (self.vec.len as usize) < n {
+ panic!("advancing IoSliceMut beyond its length");
+ }
+
+ unsafe {
+ self.vec.len -= n as c::ULONG;
+ self.vec.buf = self.vec.buf.add(n);
+ }
+ }
+
+ #[inline]
+ pub fn as_slice(&self) -> &[u8] {
+ unsafe { slice::from_raw_parts(self.vec.buf as *mut u8, self.vec.len as usize) }
+ }
+
+ #[inline]
+ pub fn as_mut_slice(&mut self) -> &mut [u8] {
+ unsafe { slice::from_raw_parts_mut(self.vec.buf as *mut u8, self.vec.len as usize) }
+ }
+}
diff --git a/library/std/src/sys/windows/locks/condvar.rs b/library/std/src/sys/windows/locks/condvar.rs
new file mode 100644
index 000000000..be9a2abbe
--- /dev/null
+++ b/library/std/src/sys/windows/locks/condvar.rs
@@ -0,0 +1,52 @@
+use crate::cell::UnsafeCell;
+use crate::sys::c;
+use crate::sys::locks::{mutex, Mutex};
+use crate::sys::os;
+use crate::time::Duration;
+
+pub struct Condvar {
+ inner: UnsafeCell<c::CONDITION_VARIABLE>,
+}
+
+pub type MovableCondvar = Condvar;
+
+unsafe impl Send for Condvar {}
+unsafe impl Sync for Condvar {}
+
+impl Condvar {
+ #[inline]
+ pub const fn new() -> Condvar {
+ Condvar { inner: UnsafeCell::new(c::CONDITION_VARIABLE_INIT) }
+ }
+
+ #[inline]
+ pub unsafe fn wait(&self, mutex: &Mutex) {
+ let r = c::SleepConditionVariableSRW(self.inner.get(), mutex::raw(mutex), c::INFINITE, 0);
+ debug_assert!(r != 0);
+ }
+
+ pub unsafe fn wait_timeout(&self, mutex: &Mutex, dur: Duration) -> bool {
+ let r = c::SleepConditionVariableSRW(
+ self.inner.get(),
+ mutex::raw(mutex),
+ crate::sys::windows::dur2timeout(dur),
+ 0,
+ );
+ if r == 0 {
+ debug_assert_eq!(os::errno() as usize, c::ERROR_TIMEOUT as usize);
+ false
+ } else {
+ true
+ }
+ }
+
+ #[inline]
+ pub unsafe fn notify_one(&self) {
+ c::WakeConditionVariable(self.inner.get())
+ }
+
+ #[inline]
+ pub unsafe fn notify_all(&self) {
+ c::WakeAllConditionVariable(self.inner.get())
+ }
+}
diff --git a/library/std/src/sys/windows/locks/mod.rs b/library/std/src/sys/windows/locks/mod.rs
new file mode 100644
index 000000000..d412ff152
--- /dev/null
+++ b/library/std/src/sys/windows/locks/mod.rs
@@ -0,0 +1,6 @@
+mod condvar;
+mod mutex;
+mod rwlock;
+pub use condvar::{Condvar, MovableCondvar};
+pub use mutex::{MovableMutex, Mutex};
+pub use rwlock::{MovableRwLock, RwLock};
diff --git a/library/std/src/sys/windows/locks/mutex.rs b/library/std/src/sys/windows/locks/mutex.rs
new file mode 100644
index 000000000..f91e8f9f5
--- /dev/null
+++ b/library/std/src/sys/windows/locks/mutex.rs
@@ -0,0 +1,57 @@
+//! System Mutexes
+//!
+//! The Windows implementation of mutexes is a little odd and it might not be
+//! immediately obvious what's going on. The primary oddness is that SRWLock is
+//! used instead of CriticalSection, and this is done because:
+//!
+//! 1. SRWLock is several times faster than CriticalSection according to
+//! benchmarks performed on both Windows 8 and Windows 7.
+//!
+//! 2. CriticalSection allows recursive locking while SRWLock deadlocks. The
+//! Unix implementation deadlocks so consistency is preferred. See #19962 for
+//! more details.
+//!
+//! 3. While CriticalSection is fair and SRWLock is not, the current Rust policy
+//! is that there are no guarantees of fairness.
+
+use crate::cell::UnsafeCell;
+use crate::sys::c;
+
+pub struct Mutex {
+ srwlock: UnsafeCell<c::SRWLOCK>,
+}
+
+// Windows SRW Locks are movable (while not borrowed).
+pub type MovableMutex = Mutex;
+
+unsafe impl Send for Mutex {}
+unsafe impl Sync for Mutex {}
+
+#[inline]
+pub unsafe fn raw(m: &Mutex) -> c::PSRWLOCK {
+ m.srwlock.get()
+}
+
+impl Mutex {
+ #[inline]
+ pub const fn new() -> Mutex {
+ Mutex { srwlock: UnsafeCell::new(c::SRWLOCK_INIT) }
+ }
+ #[inline]
+ pub unsafe fn init(&mut self) {}
+
+ #[inline]
+ pub unsafe fn lock(&self) {
+ c::AcquireSRWLockExclusive(raw(self));
+ }
+
+ #[inline]
+ pub unsafe fn try_lock(&self) -> bool {
+ c::TryAcquireSRWLockExclusive(raw(self)) != 0
+ }
+
+ #[inline]
+ pub unsafe fn unlock(&self) {
+ c::ReleaseSRWLockExclusive(raw(self));
+ }
+}
diff --git a/library/std/src/sys/windows/locks/rwlock.rs b/library/std/src/sys/windows/locks/rwlock.rs
new file mode 100644
index 000000000..fa5ffe574
--- /dev/null
+++ b/library/std/src/sys/windows/locks/rwlock.rs
@@ -0,0 +1,42 @@
+use crate::cell::UnsafeCell;
+use crate::sys::c;
+
+pub struct RwLock {
+ inner: UnsafeCell<c::SRWLOCK>,
+}
+
+pub type MovableRwLock = RwLock;
+
+unsafe impl Send for RwLock {}
+unsafe impl Sync for RwLock {}
+
+impl RwLock {
+ #[inline]
+ pub const fn new() -> RwLock {
+ RwLock { inner: UnsafeCell::new(c::SRWLOCK_INIT) }
+ }
+ #[inline]
+ pub unsafe fn read(&self) {
+ c::AcquireSRWLockShared(self.inner.get())
+ }
+ #[inline]
+ pub unsafe fn try_read(&self) -> bool {
+ c::TryAcquireSRWLockShared(self.inner.get()) != 0
+ }
+ #[inline]
+ pub unsafe fn write(&self) {
+ c::AcquireSRWLockExclusive(self.inner.get())
+ }
+ #[inline]
+ pub unsafe fn try_write(&self) -> bool {
+ c::TryAcquireSRWLockExclusive(self.inner.get()) != 0
+ }
+ #[inline]
+ pub unsafe fn read_unlock(&self) {
+ c::ReleaseSRWLockShared(self.inner.get())
+ }
+ #[inline]
+ pub unsafe fn write_unlock(&self) {
+ c::ReleaseSRWLockExclusive(self.inner.get())
+ }
+}
diff --git a/library/std/src/sys/windows/memchr.rs b/library/std/src/sys/windows/memchr.rs
new file mode 100644
index 000000000..b9e5bcc1b
--- /dev/null
+++ b/library/std/src/sys/windows/memchr.rs
@@ -0,0 +1,5 @@
+// Original implementation taken from rust-memchr.
+// Copyright 2015 Andrew Gallant, bluss and Nicolas Koch
+
+// Fallback memchr is fastest on Windows.
+pub use core::slice::memchr::{memchr, memrchr};
diff --git a/library/std/src/sys/windows/mod.rs b/library/std/src/sys/windows/mod.rs
new file mode 100644
index 000000000..b3f6d2d0a
--- /dev/null
+++ b/library/std/src/sys/windows/mod.rs
@@ -0,0 +1,323 @@
+#![allow(missing_docs, nonstandard_style)]
+
+use crate::ffi::{CStr, OsStr, OsString};
+use crate::io::ErrorKind;
+use crate::os::windows::ffi::{OsStrExt, OsStringExt};
+use crate::path::PathBuf;
+use crate::time::Duration;
+
+pub use self::rand::hashmap_random_keys;
+
+#[macro_use]
+pub mod compat;
+
+pub mod alloc;
+pub mod args;
+pub mod c;
+pub mod cmath;
+pub mod env;
+pub mod fs;
+pub mod handle;
+pub mod io;
+pub mod locks;
+pub mod memchr;
+pub mod net;
+pub mod os;
+pub mod os_str;
+pub mod path;
+pub mod pipe;
+pub mod process;
+pub mod rand;
+pub mod thread;
+pub mod thread_local_dtor;
+pub mod thread_local_key;
+pub mod thread_parker;
+pub mod time;
+cfg_if::cfg_if! {
+ if #[cfg(not(target_vendor = "uwp"))] {
+ pub mod stdio;
+ pub mod stack_overflow;
+ } else {
+ pub mod stdio_uwp;
+ pub mod stack_overflow_uwp;
+ pub use self::stdio_uwp as stdio;
+ pub use self::stack_overflow_uwp as stack_overflow;
+ }
+}
+
+// SAFETY: must be called only once during runtime initialization.
+// NOTE: this is not guaranteed to run, for example when Rust code is called externally.
+pub unsafe fn init(_argc: isize, _argv: *const *const u8) {
+ stack_overflow::init();
+
+ // Normally, `thread::spawn` will call `Thread::set_name` but since this thread already
+ // exists, we have to call it ourselves.
+ thread::Thread::set_name(&CStr::from_bytes_with_nul_unchecked(b"main\0"));
+}
+
+// SAFETY: must be called only once during runtime cleanup.
+// NOTE: this is not guaranteed to run, for example when the program aborts.
+pub unsafe fn cleanup() {
+ net::cleanup();
+}
+
+pub fn decode_error_kind(errno: i32) -> ErrorKind {
+ use ErrorKind::*;
+
+ match errno as c::DWORD {
+ c::ERROR_ACCESS_DENIED => return PermissionDenied,
+ c::ERROR_ALREADY_EXISTS => return AlreadyExists,
+ c::ERROR_FILE_EXISTS => return AlreadyExists,
+ c::ERROR_BROKEN_PIPE => return BrokenPipe,
+ c::ERROR_FILE_NOT_FOUND => return NotFound,
+ c::ERROR_PATH_NOT_FOUND => return NotFound,
+ c::ERROR_NO_DATA => return BrokenPipe,
+ c::ERROR_INVALID_NAME => return InvalidFilename,
+ c::ERROR_INVALID_PARAMETER => return InvalidInput,
+ c::ERROR_NOT_ENOUGH_MEMORY | c::ERROR_OUTOFMEMORY => return OutOfMemory,
+ c::ERROR_SEM_TIMEOUT
+ | c::WAIT_TIMEOUT
+ | c::ERROR_DRIVER_CANCEL_TIMEOUT
+ | c::ERROR_OPERATION_ABORTED
+ | c::ERROR_SERVICE_REQUEST_TIMEOUT
+ | c::ERROR_COUNTER_TIMEOUT
+ | c::ERROR_TIMEOUT
+ | c::ERROR_RESOURCE_CALL_TIMED_OUT
+ | c::ERROR_CTX_MODEM_RESPONSE_TIMEOUT
+ | c::ERROR_CTX_CLIENT_QUERY_TIMEOUT
+ | c::FRS_ERR_SYSVOL_POPULATE_TIMEOUT
+ | c::ERROR_DS_TIMELIMIT_EXCEEDED
+ | c::DNS_ERROR_RECORD_TIMED_OUT
+ | c::ERROR_IPSEC_IKE_TIMED_OUT
+ | c::ERROR_RUNLEVEL_SWITCH_TIMEOUT
+ | c::ERROR_RUNLEVEL_SWITCH_AGENT_TIMEOUT => return TimedOut,
+ c::ERROR_CALL_NOT_IMPLEMENTED => return Unsupported,
+ c::ERROR_HOST_UNREACHABLE => return HostUnreachable,
+ c::ERROR_NETWORK_UNREACHABLE => return NetworkUnreachable,
+ c::ERROR_DIRECTORY => return NotADirectory,
+ c::ERROR_DIRECTORY_NOT_SUPPORTED => return IsADirectory,
+ c::ERROR_DIR_NOT_EMPTY => return DirectoryNotEmpty,
+ c::ERROR_WRITE_PROTECT => return ReadOnlyFilesystem,
+ c::ERROR_DISK_FULL | c::ERROR_HANDLE_DISK_FULL => return StorageFull,
+ c::ERROR_SEEK_ON_DEVICE => return NotSeekable,
+ c::ERROR_DISK_QUOTA_EXCEEDED => return FilesystemQuotaExceeded,
+ c::ERROR_FILE_TOO_LARGE => return FileTooLarge,
+ c::ERROR_BUSY => return ResourceBusy,
+ c::ERROR_POSSIBLE_DEADLOCK => return Deadlock,
+ c::ERROR_NOT_SAME_DEVICE => return CrossesDevices,
+ c::ERROR_TOO_MANY_LINKS => return TooManyLinks,
+ c::ERROR_FILENAME_EXCED_RANGE => return InvalidFilename,
+ _ => {}
+ }
+
+ match errno {
+ c::WSAEACCES => PermissionDenied,
+ c::WSAEADDRINUSE => AddrInUse,
+ c::WSAEADDRNOTAVAIL => AddrNotAvailable,
+ c::WSAECONNABORTED => ConnectionAborted,
+ c::WSAECONNREFUSED => ConnectionRefused,
+ c::WSAECONNRESET => ConnectionReset,
+ c::WSAEINVAL => InvalidInput,
+ c::WSAENOTCONN => NotConnected,
+ c::WSAEWOULDBLOCK => WouldBlock,
+ c::WSAETIMEDOUT => TimedOut,
+ c::WSAEHOSTUNREACH => HostUnreachable,
+ c::WSAENETDOWN => NetworkDown,
+ c::WSAENETUNREACH => NetworkUnreachable,
+
+ _ => Uncategorized,
+ }
+}
+
+pub fn unrolled_find_u16s(needle: u16, haystack: &[u16]) -> Option<usize> {
+ let ptr = haystack.as_ptr();
+ let mut start = &haystack[..];
+
+ // For performance reasons unfold the loop eight times.
+ while start.len() >= 8 {
+ macro_rules! if_return {
+ ($($n:literal,)+) => {
+ $(
+ if start[$n] == needle {
+ return Some(((&start[$n] as *const u16).addr() - ptr.addr()) / 2);
+ }
+ )+
+ }
+ }
+
+ if_return!(0, 1, 2, 3, 4, 5, 6, 7,);
+
+ start = &start[8..];
+ }
+
+ for c in start {
+ if *c == needle {
+ return Some(((c as *const u16).addr() - ptr.addr()) / 2);
+ }
+ }
+ None
+}
+
+pub fn to_u16s<S: AsRef<OsStr>>(s: S) -> crate::io::Result<Vec<u16>> {
+ fn inner(s: &OsStr) -> crate::io::Result<Vec<u16>> {
+ // Most paths are ASCII, so reserve capacity for as much as there are bytes
+ // in the OsStr plus one for the null-terminating character. We are not
+ // wasting bytes here as paths created by this function are primarily used
+ // in an ephemeral fashion.
+ let mut maybe_result = Vec::with_capacity(s.len() + 1);
+ maybe_result.extend(s.encode_wide());
+
+ if unrolled_find_u16s(0, &maybe_result).is_some() {
+ return Err(crate::io::const_io_error!(
+ ErrorKind::InvalidInput,
+ "strings passed to WinAPI cannot contain NULs",
+ ));
+ }
+ maybe_result.push(0);
+ Ok(maybe_result)
+ }
+ inner(s.as_ref())
+}
+
+// Many Windows APIs follow a pattern of where we hand a buffer and then they
+// will report back to us how large the buffer should be or how many bytes
+// currently reside in the buffer. This function is an abstraction over these
+// functions by making them easier to call.
+//
+// The first callback, `f1`, is yielded a (pointer, len) pair which can be
+// passed to a syscall. The `ptr` is valid for `len` items (u16 in this case).
+// The closure is expected to return what the syscall returns which will be
+// interpreted by this function to determine if the syscall needs to be invoked
+// again (with more buffer space).
+//
+// Once the syscall has completed (errors bail out early) the second closure is
+// yielded the data which has been read from the syscall. The return value
+// from this closure is then the return value of the function.
+fn fill_utf16_buf<F1, F2, T>(mut f1: F1, f2: F2) -> crate::io::Result<T>
+where
+ F1: FnMut(*mut u16, c::DWORD) -> c::DWORD,
+ F2: FnOnce(&[u16]) -> T,
+{
+ // Start off with a stack buf but then spill over to the heap if we end up
+ // needing more space.
+ //
+ // This initial size also works around `GetFullPathNameW` returning
+ // incorrect size hints for some short paths:
+ // https://github.com/dylni/normpath/issues/5
+ let mut stack_buf = [0u16; 512];
+ let mut heap_buf = Vec::new();
+ unsafe {
+ let mut n = stack_buf.len();
+ loop {
+ let buf = if n <= stack_buf.len() {
+ &mut stack_buf[..]
+ } else {
+ let extra = n - heap_buf.len();
+ heap_buf.reserve(extra);
+ heap_buf.set_len(n);
+ &mut heap_buf[..]
+ };
+
+ // This function is typically called on windows API functions which
+ // will return the correct length of the string, but these functions
+ // also return the `0` on error. In some cases, however, the
+ // returned "correct length" may actually be 0!
+ //
+ // To handle this case we call `SetLastError` to reset it to 0 and
+ // then check it again if we get the "0 error value". If the "last
+ // error" is still 0 then we interpret it as a 0 length buffer and
+ // not an actual error.
+ c::SetLastError(0);
+ let k = match f1(buf.as_mut_ptr(), n as c::DWORD) {
+ 0 if c::GetLastError() == 0 => 0,
+ 0 => return Err(crate::io::Error::last_os_error()),
+ n => n,
+ } as usize;
+ if k == n && c::GetLastError() == c::ERROR_INSUFFICIENT_BUFFER {
+ n *= 2;
+ } else if k > n {
+ n = k;
+ } else if k == n {
+ // It is impossible to reach this point.
+ // On success, k is the returned string length excluding the null.
+ // On failure, k is the required buffer length including the null.
+ // Therefore k never equals n.
+ unreachable!();
+ } else {
+ return Ok(f2(&buf[..k]));
+ }
+ }
+ }
+}
+
+fn os2path(s: &[u16]) -> PathBuf {
+ PathBuf::from(OsString::from_wide(s))
+}
+
+pub fn truncate_utf16_at_nul(v: &[u16]) -> &[u16] {
+ match unrolled_find_u16s(0, v) {
+ // don't include the 0
+ Some(i) => &v[..i],
+ None => v,
+ }
+}
+
+pub trait IsZero {
+ fn is_zero(&self) -> bool;
+}
+
+macro_rules! impl_is_zero {
+ ($($t:ident)*) => ($(impl IsZero for $t {
+ fn is_zero(&self) -> bool {
+ *self == 0
+ }
+ })*)
+}
+
+impl_is_zero! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
+
+pub fn cvt<I: IsZero>(i: I) -> crate::io::Result<I> {
+ if i.is_zero() { Err(crate::io::Error::last_os_error()) } else { Ok(i) }
+}
+
+pub fn dur2timeout(dur: Duration) -> c::DWORD {
+ // Note that a duration is a (u64, u32) (seconds, nanoseconds) pair, and the
+ // timeouts in windows APIs are typically u32 milliseconds. To translate, we
+ // have two pieces to take care of:
+ //
+ // * Nanosecond precision is rounded up
+ // * Greater than u32::MAX milliseconds (50 days) is rounded up to INFINITE
+ // (never time out).
+ dur.as_secs()
+ .checked_mul(1000)
+ .and_then(|ms| ms.checked_add((dur.subsec_nanos() as u64) / 1_000_000))
+ .and_then(|ms| ms.checked_add(if dur.subsec_nanos() % 1_000_000 > 0 { 1 } else { 0 }))
+ .map(|ms| if ms > <c::DWORD>::MAX as u64 { c::INFINITE } else { ms as c::DWORD })
+ .unwrap_or(c::INFINITE)
+}
+
+/// Use `__fastfail` to abort the process
+///
+/// This is the same implementation as in libpanic_abort's `__rust_start_panic`. See
+/// that function for more information on `__fastfail`
+#[allow(unreachable_code)]
+pub fn abort_internal() -> ! {
+ #[allow(unused)]
+ const FAST_FAIL_FATAL_APP_EXIT: usize = 7;
+ #[cfg(not(miri))] // inline assembly does not work in Miri
+ unsafe {
+ cfg_if::cfg_if! {
+ if #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] {
+ core::arch::asm!("int $$0x29", in("ecx") FAST_FAIL_FATAL_APP_EXIT);
+ crate::intrinsics::unreachable();
+ } else if #[cfg(all(target_arch = "arm", target_feature = "thumb-mode"))] {
+ core::arch::asm!(".inst 0xDEFB", in("r0") FAST_FAIL_FATAL_APP_EXIT);
+ crate::intrinsics::unreachable();
+ } else if #[cfg(target_arch = "aarch64")] {
+ core::arch::asm!("brk 0xF003", in("x0") FAST_FAIL_FATAL_APP_EXIT);
+ crate::intrinsics::unreachable();
+ }
+ }
+ }
+ crate::intrinsics::abort();
+}
diff --git a/library/std/src/sys/windows/net.rs b/library/std/src/sys/windows/net.rs
new file mode 100644
index 000000000..e0701a498
--- /dev/null
+++ b/library/std/src/sys/windows/net.rs
@@ -0,0 +1,476 @@
+#![unstable(issue = "none", feature = "windows_net")]
+
+use crate::cmp;
+use crate::io::{self, IoSlice, IoSliceMut, Read};
+use crate::mem;
+use crate::net::{Shutdown, SocketAddr};
+use crate::os::windows::io::{
+ AsRawSocket, AsSocket, BorrowedSocket, FromRawSocket, IntoRawSocket, OwnedSocket, RawSocket,
+};
+use crate::ptr;
+use crate::sync::OnceLock;
+use crate::sys;
+use crate::sys::c;
+use crate::sys_common::net;
+use crate::sys_common::{AsInner, FromInner, IntoInner};
+use crate::time::Duration;
+
+use libc::{c_int, c_long, c_ulong, c_ushort};
+
+pub type wrlen_t = i32;
+
+pub mod netc {
+ pub use crate::sys::c::ADDRESS_FAMILY as sa_family_t;
+ pub use crate::sys::c::ADDRINFOA as addrinfo;
+ pub use crate::sys::c::SOCKADDR as sockaddr;
+ pub use crate::sys::c::SOCKADDR_STORAGE_LH as sockaddr_storage;
+ pub use crate::sys::c::*;
+}
+
+pub struct Socket(OwnedSocket);
+
+static WSA_CLEANUP: OnceLock<unsafe extern "system" fn() -> i32> = OnceLock::new();
+
+/// Checks whether the Windows socket interface has been started already, and
+/// if not, starts it.
+pub fn init() {
+ let _ = WSA_CLEANUP.get_or_init(|| unsafe {
+ let mut data: c::WSADATA = mem::zeroed();
+ let ret = c::WSAStartup(
+ 0x202, // version 2.2
+ &mut data,
+ );
+ assert_eq!(ret, 0);
+
+ // Only register `WSACleanup` if `WSAStartup` is actually ever called.
+ // Workaround to prevent linking to `WS2_32.dll` when no network functionality is used.
+ // See issue #85441.
+ c::WSACleanup
+ });
+}
+
+pub fn cleanup() {
+ // only perform cleanup if network functionality was actually initialized
+ if let Some(cleanup) = WSA_CLEANUP.get() {
+ unsafe {
+ cleanup();
+ }
+ }
+}
+
+/// Returns the last error from the Windows socket interface.
+fn last_error() -> io::Error {
+ io::Error::from_raw_os_error(unsafe { c::WSAGetLastError() })
+}
+
+#[doc(hidden)]
+pub trait IsMinusOne {
+ fn is_minus_one(&self) -> bool;
+}
+
+macro_rules! impl_is_minus_one {
+ ($($t:ident)*) => ($(impl IsMinusOne for $t {
+ fn is_minus_one(&self) -> bool {
+ *self == -1
+ }
+ })*)
+}
+
+impl_is_minus_one! { i8 i16 i32 i64 isize }
+
+/// Checks if the signed integer is the Windows constant `SOCKET_ERROR` (-1)
+/// and if so, returns the last error from the Windows socket interface. This
+/// function must be called before another call to the socket API is made.
+pub fn cvt<T: IsMinusOne>(t: T) -> io::Result<T> {
+ if t.is_minus_one() { Err(last_error()) } else { Ok(t) }
+}
+
+/// A variant of `cvt` for `getaddrinfo` which return 0 for a success.
+pub fn cvt_gai(err: c_int) -> io::Result<()> {
+ if err == 0 { Ok(()) } else { Err(last_error()) }
+}
+
+/// Just to provide the same interface as sys/unix/net.rs
+pub fn cvt_r<T, F>(mut f: F) -> io::Result<T>
+where
+ T: IsMinusOne,
+ F: FnMut() -> T,
+{
+ cvt(f())
+}
+
+impl Socket {
+ pub fn new(addr: &SocketAddr, ty: c_int) -> io::Result<Socket> {
+ let family = match *addr {
+ SocketAddr::V4(..) => c::AF_INET,
+ SocketAddr::V6(..) => c::AF_INET6,
+ };
+ let socket = unsafe {
+ c::WSASocketW(
+ family,
+ ty,
+ 0,
+ ptr::null_mut(),
+ 0,
+ c::WSA_FLAG_OVERLAPPED | c::WSA_FLAG_NO_HANDLE_INHERIT,
+ )
+ };
+
+ if socket != c::INVALID_SOCKET {
+ unsafe { Ok(Self::from_raw_socket(socket)) }
+ } else {
+ let error = unsafe { c::WSAGetLastError() };
+
+ if error != c::WSAEPROTOTYPE && error != c::WSAEINVAL {
+ return Err(io::Error::from_raw_os_error(error));
+ }
+
+ let socket =
+ unsafe { c::WSASocketW(family, ty, 0, ptr::null_mut(), 0, c::WSA_FLAG_OVERLAPPED) };
+
+ if socket == c::INVALID_SOCKET {
+ return Err(last_error());
+ }
+
+ unsafe {
+ let socket = Self::from_raw_socket(socket);
+ socket.0.set_no_inherit()?;
+ Ok(socket)
+ }
+ }
+ }
+
+ pub fn connect_timeout(&self, addr: &SocketAddr, timeout: Duration) -> io::Result<()> {
+ self.set_nonblocking(true)?;
+ let result = {
+ let (addr, len) = addr.into_inner();
+ let result = unsafe { c::connect(self.as_raw_socket(), addr.as_ptr(), len) };
+ cvt(result).map(drop)
+ };
+ self.set_nonblocking(false)?;
+
+ match result {
+ Err(ref error) if error.kind() == io::ErrorKind::WouldBlock => {
+ if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 {
+ return Err(io::const_io_error!(
+ io::ErrorKind::InvalidInput,
+ "cannot set a 0 duration timeout",
+ ));
+ }
+
+ let mut timeout = c::timeval {
+ tv_sec: timeout.as_secs() as c_long,
+ tv_usec: (timeout.subsec_nanos() / 1000) as c_long,
+ };
+
+ if timeout.tv_sec == 0 && timeout.tv_usec == 0 {
+ timeout.tv_usec = 1;
+ }
+
+ let fds = {
+ let mut fds = unsafe { mem::zeroed::<c::fd_set>() };
+ fds.fd_count = 1;
+ fds.fd_array[0] = self.as_raw_socket();
+ fds
+ };
+
+ let mut writefds = fds;
+ let mut errorfds = fds;
+
+ let count = {
+ let result = unsafe {
+ c::select(1, ptr::null_mut(), &mut writefds, &mut errorfds, &timeout)
+ };
+ cvt(result)?
+ };
+
+ match count {
+ 0 => Err(io::const_io_error!(io::ErrorKind::TimedOut, "connection timed out")),
+ _ => {
+ if writefds.fd_count != 1 {
+ if let Some(e) = self.take_error()? {
+ return Err(e);
+ }
+ }
+
+ Ok(())
+ }
+ }
+ }
+ _ => result,
+ }
+ }
+
+ pub fn accept(&self, storage: *mut c::SOCKADDR, len: *mut c_int) -> io::Result<Socket> {
+ let socket = unsafe { c::accept(self.as_raw_socket(), storage, len) };
+
+ match socket {
+ c::INVALID_SOCKET => Err(last_error()),
+ _ => unsafe { Ok(Self::from_raw_socket(socket)) },
+ }
+ }
+
+ pub fn duplicate(&self) -> io::Result<Socket> {
+ Ok(Self(self.0.try_clone()?))
+ }
+
+ fn recv_with_flags(&self, buf: &mut [u8], flags: c_int) -> io::Result<usize> {
+ // On unix when a socket is shut down all further reads return 0, so we
+ // do the same on windows to map a shut down socket to returning EOF.
+ let length = cmp::min(buf.len(), i32::MAX as usize) as i32;
+ let result =
+ unsafe { c::recv(self.as_raw_socket(), buf.as_mut_ptr() as *mut _, length, flags) };
+
+ match result {
+ c::SOCKET_ERROR => {
+ let error = unsafe { c::WSAGetLastError() };
+
+ if error == c::WSAESHUTDOWN {
+ Ok(0)
+ } else {
+ Err(io::Error::from_raw_os_error(error))
+ }
+ }
+ _ => Ok(result as usize),
+ }
+ }
+
+ pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
+ self.recv_with_flags(buf, 0)
+ }
+
+ pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
+ // On unix when a socket is shut down all further reads return 0, so we
+ // do the same on windows to map a shut down socket to returning EOF.
+ let length = cmp::min(bufs.len(), c::DWORD::MAX as usize) as c::DWORD;
+ let mut nread = 0;
+ let mut flags = 0;
+ let result = unsafe {
+ c::WSARecv(
+ self.as_raw_socket(),
+ bufs.as_mut_ptr() as *mut c::WSABUF,
+ length,
+ &mut nread,
+ &mut flags,
+ ptr::null_mut(),
+ ptr::null_mut(),
+ )
+ };
+
+ match result {
+ 0 => Ok(nread as usize),
+ _ => {
+ let error = unsafe { c::WSAGetLastError() };
+
+ if error == c::WSAESHUTDOWN {
+ Ok(0)
+ } else {
+ Err(io::Error::from_raw_os_error(error))
+ }
+ }
+ }
+ }
+
+ #[inline]
+ pub fn is_read_vectored(&self) -> bool {
+ true
+ }
+
+ pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
+ self.recv_with_flags(buf, c::MSG_PEEK)
+ }
+
+ fn recv_from_with_flags(
+ &self,
+ buf: &mut [u8],
+ flags: c_int,
+ ) -> io::Result<(usize, SocketAddr)> {
+ let mut storage = unsafe { mem::zeroed::<c::SOCKADDR_STORAGE_LH>() };
+ let mut addrlen = mem::size_of_val(&storage) as c::socklen_t;
+ let length = cmp::min(buf.len(), <wrlen_t>::MAX as usize) as wrlen_t;
+
+ // On unix when a socket is shut down all further reads return 0, so we
+ // do the same on windows to map a shut down socket to returning EOF.
+ let result = unsafe {
+ c::recvfrom(
+ self.as_raw_socket(),
+ buf.as_mut_ptr() as *mut _,
+ length,
+ flags,
+ &mut storage as *mut _ as *mut _,
+ &mut addrlen,
+ )
+ };
+
+ match result {
+ c::SOCKET_ERROR => {
+ let error = unsafe { c::WSAGetLastError() };
+
+ if error == c::WSAESHUTDOWN {
+ Ok((0, net::sockaddr_to_addr(&storage, addrlen as usize)?))
+ } else {
+ Err(io::Error::from_raw_os_error(error))
+ }
+ }
+ _ => Ok((result as usize, net::sockaddr_to_addr(&storage, addrlen as usize)?)),
+ }
+ }
+
+ pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
+ self.recv_from_with_flags(buf, 0)
+ }
+
+ pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
+ self.recv_from_with_flags(buf, c::MSG_PEEK)
+ }
+
+ pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
+ let length = cmp::min(bufs.len(), c::DWORD::MAX as usize) as c::DWORD;
+ let mut nwritten = 0;
+ let result = unsafe {
+ c::WSASend(
+ self.as_raw_socket(),
+ bufs.as_ptr() as *const c::WSABUF as *mut _,
+ length,
+ &mut nwritten,
+ 0,
+ ptr::null_mut(),
+ ptr::null_mut(),
+ )
+ };
+ cvt(result).map(|_| nwritten as usize)
+ }
+
+ #[inline]
+ pub fn is_write_vectored(&self) -> bool {
+ true
+ }
+
+ pub fn set_timeout(&self, dur: Option<Duration>, kind: c_int) -> io::Result<()> {
+ let timeout = match dur {
+ Some(dur) => {
+ let timeout = sys::dur2timeout(dur);
+ if timeout == 0 {
+ return Err(io::const_io_error!(
+ io::ErrorKind::InvalidInput,
+ "cannot set a 0 duration timeout",
+ ));
+ }
+ timeout
+ }
+ None => 0,
+ };
+ net::setsockopt(self, c::SOL_SOCKET, kind, timeout)
+ }
+
+ pub fn timeout(&self, kind: c_int) -> io::Result<Option<Duration>> {
+ let raw: c::DWORD = net::getsockopt(self, c::SOL_SOCKET, kind)?;
+ if raw == 0 {
+ Ok(None)
+ } else {
+ let secs = raw / 1000;
+ let nsec = (raw % 1000) * 1000000;
+ Ok(Some(Duration::new(secs as u64, nsec as u32)))
+ }
+ }
+
+ pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
+ let how = match how {
+ Shutdown::Write => c::SD_SEND,
+ Shutdown::Read => c::SD_RECEIVE,
+ Shutdown::Both => c::SD_BOTH,
+ };
+ let result = unsafe { c::shutdown(self.as_raw_socket(), how) };
+ cvt(result).map(drop)
+ }
+
+ pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
+ let mut nonblocking = nonblocking as c_ulong;
+ let result =
+ unsafe { c::ioctlsocket(self.as_raw_socket(), c::FIONBIO as c_int, &mut nonblocking) };
+ cvt(result).map(drop)
+ }
+
+ pub fn set_linger(&self, linger: Option<Duration>) -> io::Result<()> {
+ let linger = c::linger {
+ l_onoff: linger.is_some() as c_ushort,
+ l_linger: linger.unwrap_or_default().as_secs() as c_ushort,
+ };
+
+ net::setsockopt(self, c::SOL_SOCKET, c::SO_LINGER, linger)
+ }
+
+ pub fn linger(&self) -> io::Result<Option<Duration>> {
+ let val: c::linger = net::getsockopt(self, c::SOL_SOCKET, c::SO_LINGER)?;
+
+ Ok((val.l_onoff != 0).then(|| Duration::from_secs(val.l_linger as u64)))
+ }
+
+ pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
+ net::setsockopt(self, c::IPPROTO_TCP, c::TCP_NODELAY, nodelay as c::BOOL)
+ }
+
+ pub fn nodelay(&self) -> io::Result<bool> {
+ let raw: c::BOOL = net::getsockopt(self, c::IPPROTO_TCP, c::TCP_NODELAY)?;
+ Ok(raw != 0)
+ }
+
+ pub fn take_error(&self) -> io::Result<Option<io::Error>> {
+ let raw: c_int = net::getsockopt(self, c::SOL_SOCKET, c::SO_ERROR)?;
+ if raw == 0 { Ok(None) } else { Ok(Some(io::Error::from_raw_os_error(raw as i32))) }
+ }
+
+ // This is used by sys_common code to abstract over Windows and Unix.
+ pub fn as_raw(&self) -> RawSocket {
+ self.as_inner().as_raw_socket()
+ }
+}
+
+#[unstable(reason = "not public", issue = "none", feature = "fd_read")]
+impl<'a> Read for &'a Socket {
+ fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
+ (**self).read(buf)
+ }
+}
+
+impl AsInner<OwnedSocket> for Socket {
+ fn as_inner(&self) -> &OwnedSocket {
+ &self.0
+ }
+}
+
+impl FromInner<OwnedSocket> for Socket {
+ fn from_inner(sock: OwnedSocket) -> Socket {
+ Socket(sock)
+ }
+}
+
+impl IntoInner<OwnedSocket> for Socket {
+ fn into_inner(self) -> OwnedSocket {
+ self.0
+ }
+}
+
+impl AsSocket for Socket {
+ fn as_socket(&self) -> BorrowedSocket<'_> {
+ self.0.as_socket()
+ }
+}
+
+impl AsRawSocket for Socket {
+ fn as_raw_socket(&self) -> RawSocket {
+ self.0.as_raw_socket()
+ }
+}
+
+impl IntoRawSocket for Socket {
+ fn into_raw_socket(self) -> RawSocket {
+ self.0.into_raw_socket()
+ }
+}
+
+impl FromRawSocket for Socket {
+ unsafe fn from_raw_socket(raw_socket: RawSocket) -> Self {
+ Self(FromRawSocket::from_raw_socket(raw_socket))
+ }
+}
diff --git a/library/std/src/sys/windows/os.rs b/library/std/src/sys/windows/os.rs
new file mode 100644
index 000000000..bcac996c0
--- /dev/null
+++ b/library/std/src/sys/windows/os.rs
@@ -0,0 +1,328 @@
+//! Implementation of `std::os` functionality for Windows.
+
+#![allow(nonstandard_style)]
+
+#[cfg(test)]
+mod tests;
+
+use crate::os::windows::prelude::*;
+
+use crate::error::Error as StdError;
+use crate::ffi::{OsStr, OsString};
+use crate::fmt;
+use crate::io;
+use crate::os::windows::ffi::EncodeWide;
+use crate::path::{self, PathBuf};
+use crate::ptr;
+use crate::slice;
+use crate::sys::{c, cvt};
+
+use super::to_u16s;
+
+pub fn errno() -> i32 {
+ unsafe { c::GetLastError() as i32 }
+}
+
+/// Gets a detailed string description for the given error number.
+pub fn error_string(mut errnum: i32) -> String {
+ // This value is calculated from the macro
+ // MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
+ let langId = 0x0800 as c::DWORD;
+
+ let mut buf = [0 as c::WCHAR; 2048];
+
+ unsafe {
+ let mut module = ptr::null_mut();
+ let mut flags = 0;
+
+ // NTSTATUS errors may be encoded as HRESULT, which may returned from
+ // GetLastError. For more information about Windows error codes, see
+ // `[MS-ERREF]`: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-erref/0642cb2f-2075-4469-918c-4441e69c548a
+ if (errnum & c::FACILITY_NT_BIT as i32) != 0 {
+ // format according to https://support.microsoft.com/en-us/help/259693
+ const NTDLL_DLL: &[u16] = &[
+ 'N' as _, 'T' as _, 'D' as _, 'L' as _, 'L' as _, '.' as _, 'D' as _, 'L' as _,
+ 'L' as _, 0,
+ ];
+ module = c::GetModuleHandleW(NTDLL_DLL.as_ptr());
+
+ if !module.is_null() {
+ errnum ^= c::FACILITY_NT_BIT as i32;
+ flags = c::FORMAT_MESSAGE_FROM_HMODULE;
+ }
+ }
+
+ let res = c::FormatMessageW(
+ flags | c::FORMAT_MESSAGE_FROM_SYSTEM | c::FORMAT_MESSAGE_IGNORE_INSERTS,
+ module,
+ errnum as c::DWORD,
+ langId,
+ buf.as_mut_ptr(),
+ buf.len() as c::DWORD,
+ ptr::null(),
+ ) as usize;
+ if res == 0 {
+ // Sometimes FormatMessageW can fail e.g., system doesn't like langId,
+ let fm_err = errno();
+ return format!("OS Error {errnum} (FormatMessageW() returned error {fm_err})");
+ }
+
+ match String::from_utf16(&buf[..res]) {
+ Ok(mut msg) => {
+ // Trim trailing CRLF inserted by FormatMessageW
+ let len = msg.trim_end().len();
+ msg.truncate(len);
+ msg
+ }
+ Err(..) => format!(
+ "OS Error {} (FormatMessageW() returned \
+ invalid UTF-16)",
+ errnum
+ ),
+ }
+ }
+}
+
+pub struct Env {
+ base: c::LPWCH,
+ cur: c::LPWCH,
+}
+
+impl Iterator for Env {
+ type Item = (OsString, OsString);
+
+ fn next(&mut self) -> Option<(OsString, OsString)> {
+ loop {
+ unsafe {
+ if *self.cur == 0 {
+ return None;
+ }
+ let p = self.cur as *const u16;
+ let mut len = 0;
+ while *p.offset(len) != 0 {
+ len += 1;
+ }
+ let s = slice::from_raw_parts(p, len as usize);
+ self.cur = self.cur.offset(len + 1);
+
+ // Windows allows environment variables to start with an equals
+ // symbol (in any other position, this is the separator between
+ // variable name and value). Since`s` has at least length 1 at
+ // this point (because the empty string terminates the array of
+ // environment variables), we can safely slice.
+ let pos = match s[1..].iter().position(|&u| u == b'=' as u16).map(|p| p + 1) {
+ Some(p) => p,
+ None => continue,
+ };
+ return Some((
+ OsStringExt::from_wide(&s[..pos]),
+ OsStringExt::from_wide(&s[pos + 1..]),
+ ));
+ }
+ }
+ }
+}
+
+impl Drop for Env {
+ fn drop(&mut self) {
+ unsafe {
+ c::FreeEnvironmentStringsW(self.base);
+ }
+ }
+}
+
+pub fn env() -> Env {
+ unsafe {
+ let ch = c::GetEnvironmentStringsW();
+ if ch.is_null() {
+ panic!("failure getting env string from OS: {}", io::Error::last_os_error());
+ }
+ Env { base: ch, cur: ch }
+ }
+}
+
+pub struct SplitPaths<'a> {
+ data: EncodeWide<'a>,
+ must_yield: bool,
+}
+
+pub fn split_paths(unparsed: &OsStr) -> SplitPaths<'_> {
+ SplitPaths { data: unparsed.encode_wide(), must_yield: true }
+}
+
+impl<'a> Iterator for SplitPaths<'a> {
+ type Item = PathBuf;
+ fn next(&mut self) -> Option<PathBuf> {
+ // On Windows, the PATH environment variable is semicolon separated.
+ // Double quotes are used as a way of introducing literal semicolons
+ // (since c:\some;dir is a valid Windows path). Double quotes are not
+ // themselves permitted in path names, so there is no way to escape a
+ // double quote. Quoted regions can appear in arbitrary locations, so
+ //
+ // c:\foo;c:\som"e;di"r;c:\bar
+ //
+ // Should parse as [c:\foo, c:\some;dir, c:\bar].
+ //
+ // (The above is based on testing; there is no clear reference available
+ // for the grammar.)
+
+ let must_yield = self.must_yield;
+ self.must_yield = false;
+
+ let mut in_progress = Vec::new();
+ let mut in_quote = false;
+ for b in self.data.by_ref() {
+ if b == '"' as u16 {
+ in_quote = !in_quote;
+ } else if b == ';' as u16 && !in_quote {
+ self.must_yield = true;
+ break;
+ } else {
+ in_progress.push(b)
+ }
+ }
+
+ if !must_yield && in_progress.is_empty() {
+ None
+ } else {
+ Some(super::os2path(&in_progress))
+ }
+ }
+}
+
+#[derive(Debug)]
+pub struct JoinPathsError;
+
+pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
+where
+ I: Iterator<Item = T>,
+ T: AsRef<OsStr>,
+{
+ let mut joined = Vec::new();
+ let sep = b';' as u16;
+
+ for (i, path) in paths.enumerate() {
+ let path = path.as_ref();
+ if i > 0 {
+ joined.push(sep)
+ }
+ let v = path.encode_wide().collect::<Vec<u16>>();
+ if v.contains(&(b'"' as u16)) {
+ return Err(JoinPathsError);
+ } else if v.contains(&sep) {
+ joined.push(b'"' as u16);
+ joined.extend_from_slice(&v[..]);
+ joined.push(b'"' as u16);
+ } else {
+ joined.extend_from_slice(&v[..]);
+ }
+ }
+
+ Ok(OsStringExt::from_wide(&joined[..]))
+}
+
+impl fmt::Display for JoinPathsError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ "path segment contains `\"`".fmt(f)
+ }
+}
+
+impl StdError for JoinPathsError {
+ #[allow(deprecated)]
+ fn description(&self) -> &str {
+ "failed to join paths"
+ }
+}
+
+pub fn current_exe() -> io::Result<PathBuf> {
+ super::fill_utf16_buf(
+ |buf, sz| unsafe { c::GetModuleFileNameW(ptr::null_mut(), buf, sz) },
+ super::os2path,
+ )
+}
+
+pub fn getcwd() -> io::Result<PathBuf> {
+ super::fill_utf16_buf(|buf, sz| unsafe { c::GetCurrentDirectoryW(sz, buf) }, super::os2path)
+}
+
+pub fn chdir(p: &path::Path) -> io::Result<()> {
+ let p: &OsStr = p.as_ref();
+ let mut p = p.encode_wide().collect::<Vec<_>>();
+ p.push(0);
+
+ cvt(unsafe { c::SetCurrentDirectoryW(p.as_ptr()) }).map(drop)
+}
+
+pub fn getenv(k: &OsStr) -> Option<OsString> {
+ let k = to_u16s(k).ok()?;
+ super::fill_utf16_buf(
+ |buf, sz| unsafe { c::GetEnvironmentVariableW(k.as_ptr(), buf, sz) },
+ |buf| OsStringExt::from_wide(buf),
+ )
+ .ok()
+}
+
+pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
+ let k = to_u16s(k)?;
+ let v = to_u16s(v)?;
+
+ cvt(unsafe { c::SetEnvironmentVariableW(k.as_ptr(), v.as_ptr()) }).map(drop)
+}
+
+pub fn unsetenv(n: &OsStr) -> io::Result<()> {
+ let v = to_u16s(n)?;
+ cvt(unsafe { c::SetEnvironmentVariableW(v.as_ptr(), ptr::null()) }).map(drop)
+}
+
+pub fn temp_dir() -> PathBuf {
+ super::fill_utf16_buf(|buf, sz| unsafe { c::GetTempPath2W(sz, buf) }, super::os2path).unwrap()
+}
+
+#[cfg(not(target_vendor = "uwp"))]
+fn home_dir_crt() -> Option<PathBuf> {
+ unsafe {
+ // The magic constant -4 can be used as the token passed to GetUserProfileDirectoryW below
+ // instead of us having to go through these multiple steps to get a token. However this is
+ // not implemented on Windows 7, only Windows 8 and up. When we drop support for Windows 7
+ // we can simplify this code. See #90144 for details.
+ use crate::sys::handle::Handle;
+
+ let me = c::GetCurrentProcess();
+ let mut token = ptr::null_mut();
+ if c::OpenProcessToken(me, c::TOKEN_READ, &mut token) == 0 {
+ return None;
+ }
+ let _handle = Handle::from_raw_handle(token);
+ super::fill_utf16_buf(
+ |buf, mut sz| {
+ match c::GetUserProfileDirectoryW(token, buf, &mut sz) {
+ 0 if c::GetLastError() != c::ERROR_INSUFFICIENT_BUFFER => 0,
+ 0 => sz,
+ _ => sz - 1, // sz includes the null terminator
+ }
+ },
+ super::os2path,
+ )
+ .ok()
+ }
+}
+
+#[cfg(target_vendor = "uwp")]
+fn home_dir_crt() -> Option<PathBuf> {
+ None
+}
+
+pub fn home_dir() -> Option<PathBuf> {
+ crate::env::var_os("HOME")
+ .or_else(|| crate::env::var_os("USERPROFILE"))
+ .map(PathBuf::from)
+ .or_else(|| home_dir_crt())
+}
+
+pub fn exit(code: i32) -> ! {
+ unsafe { c::ExitProcess(code as c::UINT) }
+}
+
+pub fn getpid() -> u32 {
+ unsafe { c::GetCurrentProcessId() as u32 }
+}
diff --git a/library/std/src/sys/windows/os/tests.rs b/library/std/src/sys/windows/os/tests.rs
new file mode 100644
index 000000000..458d6e11c
--- /dev/null
+++ b/library/std/src/sys/windows/os/tests.rs
@@ -0,0 +1,13 @@
+use crate::io::Error;
+use crate::sys::c;
+
+// tests `error_string` above
+#[test]
+fn ntstatus_error() {
+ const STATUS_UNSUCCESSFUL: u32 = 0xc000_0001;
+ assert!(
+ !Error::from_raw_os_error((STATUS_UNSUCCESSFUL | c::FACILITY_NT_BIT) as _)
+ .to_string()
+ .contains("FormatMessageW() returned error")
+ );
+}
diff --git a/library/std/src/sys/windows/os_str.rs b/library/std/src/sys/windows/os_str.rs
new file mode 100644
index 000000000..11883f150
--- /dev/null
+++ b/library/std/src/sys/windows/os_str.rs
@@ -0,0 +1,226 @@
+/// The underlying OsString/OsStr implementation on Windows is a
+/// wrapper around the "WTF-8" encoding; see the `wtf8` module for more.
+use crate::borrow::Cow;
+use crate::collections::TryReserveError;
+use crate::fmt;
+use crate::mem;
+use crate::rc::Rc;
+use crate::sync::Arc;
+use crate::sys_common::wtf8::{Wtf8, Wtf8Buf};
+use crate::sys_common::{AsInner, FromInner, IntoInner};
+
+#[derive(Clone, Hash)]
+pub struct Buf {
+ pub inner: Wtf8Buf,
+}
+
+impl IntoInner<Wtf8Buf> for Buf {
+ fn into_inner(self) -> Wtf8Buf {
+ self.inner
+ }
+}
+
+impl FromInner<Wtf8Buf> for Buf {
+ fn from_inner(inner: Wtf8Buf) -> Self {
+ Buf { inner }
+ }
+}
+
+impl AsInner<Wtf8> for Buf {
+ fn as_inner(&self) -> &Wtf8 {
+ &self.inner
+ }
+}
+
+impl fmt::Debug for Buf {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ fmt::Debug::fmt(self.as_slice(), formatter)
+ }
+}
+
+impl fmt::Display for Buf {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ fmt::Display::fmt(self.as_slice(), formatter)
+ }
+}
+
+#[repr(transparent)]
+pub struct Slice {
+ pub inner: Wtf8,
+}
+
+impl fmt::Debug for Slice {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ fmt::Debug::fmt(&self.inner, formatter)
+ }
+}
+
+impl fmt::Display for Slice {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ fmt::Display::fmt(&self.inner, formatter)
+ }
+}
+
+impl Buf {
+ pub fn with_capacity(capacity: usize) -> Buf {
+ Buf { inner: Wtf8Buf::with_capacity(capacity) }
+ }
+
+ pub fn clear(&mut self) {
+ self.inner.clear()
+ }
+
+ pub fn capacity(&self) -> usize {
+ self.inner.capacity()
+ }
+
+ pub fn from_string(s: String) -> Buf {
+ Buf { inner: Wtf8Buf::from_string(s) }
+ }
+
+ pub fn as_slice(&self) -> &Slice {
+ // SAFETY: Slice is just a wrapper for Wtf8,
+ // and self.inner.as_slice() returns &Wtf8.
+ // Therefore, transmuting &Wtf8 to &Slice is safe.
+ unsafe { mem::transmute(self.inner.as_slice()) }
+ }
+
+ pub fn as_mut_slice(&mut self) -> &mut Slice {
+ // SAFETY: Slice is just a wrapper for Wtf8,
+ // and self.inner.as_mut_slice() returns &mut Wtf8.
+ // Therefore, transmuting &mut Wtf8 to &mut Slice is safe.
+ // Additionally, care should be taken to ensure the slice
+ // is always valid Wtf8.
+ unsafe { mem::transmute(self.inner.as_mut_slice()) }
+ }
+
+ pub fn into_string(self) -> Result<String, Buf> {
+ self.inner.into_string().map_err(|buf| Buf { inner: buf })
+ }
+
+ pub fn push_slice(&mut self, s: &Slice) {
+ self.inner.push_wtf8(&s.inner)
+ }
+
+ pub fn reserve(&mut self, additional: usize) {
+ self.inner.reserve(additional)
+ }
+
+ pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
+ self.inner.try_reserve(additional)
+ }
+
+ pub fn reserve_exact(&mut self, additional: usize) {
+ self.inner.reserve_exact(additional)
+ }
+
+ pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
+ self.inner.try_reserve_exact(additional)
+ }
+
+ pub fn shrink_to_fit(&mut self) {
+ self.inner.shrink_to_fit()
+ }
+
+ #[inline]
+ pub fn shrink_to(&mut self, min_capacity: usize) {
+ self.inner.shrink_to(min_capacity)
+ }
+
+ #[inline]
+ pub fn into_box(self) -> Box<Slice> {
+ unsafe { mem::transmute(self.inner.into_box()) }
+ }
+
+ #[inline]
+ pub fn from_box(boxed: Box<Slice>) -> Buf {
+ let inner: Box<Wtf8> = unsafe { mem::transmute(boxed) };
+ Buf { inner: Wtf8Buf::from_box(inner) }
+ }
+
+ #[inline]
+ pub fn into_arc(&self) -> Arc<Slice> {
+ self.as_slice().into_arc()
+ }
+
+ #[inline]
+ pub fn into_rc(&self) -> Rc<Slice> {
+ self.as_slice().into_rc()
+ }
+}
+
+impl Slice {
+ #[inline]
+ pub fn from_str(s: &str) -> &Slice {
+ unsafe { mem::transmute(Wtf8::from_str(s)) }
+ }
+
+ pub fn to_str(&self) -> Option<&str> {
+ self.inner.as_str()
+ }
+
+ pub fn to_string_lossy(&self) -> Cow<'_, str> {
+ self.inner.to_string_lossy()
+ }
+
+ pub fn to_owned(&self) -> Buf {
+ let mut buf = Wtf8Buf::with_capacity(self.inner.len());
+ buf.push_wtf8(&self.inner);
+ Buf { inner: buf }
+ }
+
+ pub fn clone_into(&self, buf: &mut Buf) {
+ self.inner.clone_into(&mut buf.inner)
+ }
+
+ #[inline]
+ pub fn into_box(&self) -> Box<Slice> {
+ unsafe { mem::transmute(self.inner.into_box()) }
+ }
+
+ pub fn empty_box() -> Box<Slice> {
+ unsafe { mem::transmute(Wtf8::empty_box()) }
+ }
+
+ #[inline]
+ pub fn into_arc(&self) -> Arc<Slice> {
+ let arc = self.inner.into_arc();
+ unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Slice) }
+ }
+
+ #[inline]
+ pub fn into_rc(&self) -> Rc<Slice> {
+ let rc = self.inner.into_rc();
+ unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Slice) }
+ }
+
+ #[inline]
+ pub fn make_ascii_lowercase(&mut self) {
+ self.inner.make_ascii_lowercase()
+ }
+
+ #[inline]
+ pub fn make_ascii_uppercase(&mut self) {
+ self.inner.make_ascii_uppercase()
+ }
+
+ #[inline]
+ pub fn to_ascii_lowercase(&self) -> Buf {
+ Buf { inner: self.inner.to_ascii_lowercase() }
+ }
+
+ #[inline]
+ pub fn to_ascii_uppercase(&self) -> Buf {
+ Buf { inner: self.inner.to_ascii_uppercase() }
+ }
+
+ #[inline]
+ pub fn is_ascii(&self) -> bool {
+ self.inner.is_ascii()
+ }
+
+ #[inline]
+ pub fn eq_ignore_ascii_case(&self, other: &Self) -> bool {
+ self.inner.eq_ignore_ascii_case(&other.inner)
+ }
+}
diff --git a/library/std/src/sys/windows/path.rs b/library/std/src/sys/windows/path.rs
new file mode 100644
index 000000000..beeca1917
--- /dev/null
+++ b/library/std/src/sys/windows/path.rs
@@ -0,0 +1,333 @@
+use super::{c, fill_utf16_buf, to_u16s};
+use crate::ffi::{OsStr, OsString};
+use crate::io;
+use crate::mem;
+use crate::path::{Path, PathBuf, Prefix};
+use crate::ptr;
+
+#[cfg(test)]
+mod tests;
+
+pub const MAIN_SEP_STR: &str = "\\";
+pub const MAIN_SEP: char = '\\';
+
+/// # Safety
+///
+/// `bytes` must be a valid wtf8 encoded slice
+#[inline]
+unsafe fn bytes_as_os_str(bytes: &[u8]) -> &OsStr {
+ // &OsStr is layout compatible with &Slice, which is compatible with &Wtf8,
+ // which is compatible with &[u8].
+ mem::transmute(bytes)
+}
+
+#[inline]
+pub fn is_sep_byte(b: u8) -> bool {
+ b == b'/' || b == b'\\'
+}
+
+#[inline]
+pub fn is_verbatim_sep(b: u8) -> bool {
+ b == b'\\'
+}
+
+/// Returns true if `path` looks like a lone filename.
+pub(crate) fn is_file_name(path: &OsStr) -> bool {
+ !path.bytes().iter().copied().any(is_sep_byte)
+}
+pub(crate) fn has_trailing_slash(path: &OsStr) -> bool {
+ let is_verbatim = path.bytes().starts_with(br"\\?\");
+ let is_separator = if is_verbatim { is_verbatim_sep } else { is_sep_byte };
+ if let Some(&c) = path.bytes().last() { is_separator(c) } else { false }
+}
+
+/// Appends a suffix to a path.
+///
+/// Can be used to append an extension without removing an existing extension.
+pub(crate) fn append_suffix(path: PathBuf, suffix: &OsStr) -> PathBuf {
+ let mut path = OsString::from(path);
+ path.push(suffix);
+ path.into()
+}
+
+struct PrefixParser<'a, const LEN: usize> {
+ path: &'a OsStr,
+ prefix: [u8; LEN],
+}
+
+impl<'a, const LEN: usize> PrefixParser<'a, LEN> {
+ #[inline]
+ fn get_prefix(path: &OsStr) -> [u8; LEN] {
+ let mut prefix = [0; LEN];
+ // SAFETY: Only ASCII characters are modified.
+ for (i, &ch) in path.bytes().iter().take(LEN).enumerate() {
+ prefix[i] = if ch == b'/' { b'\\' } else { ch };
+ }
+ prefix
+ }
+
+ fn new(path: &'a OsStr) -> Self {
+ Self { path, prefix: Self::get_prefix(path) }
+ }
+
+ fn as_slice(&self) -> PrefixParserSlice<'a, '_> {
+ PrefixParserSlice {
+ path: self.path,
+ prefix: &self.prefix[..LEN.min(self.path.len())],
+ index: 0,
+ }
+ }
+}
+
+struct PrefixParserSlice<'a, 'b> {
+ path: &'a OsStr,
+ prefix: &'b [u8],
+ index: usize,
+}
+
+impl<'a> PrefixParserSlice<'a, '_> {
+ fn strip_prefix(&self, prefix: &str) -> Option<Self> {
+ self.prefix[self.index..]
+ .starts_with(prefix.as_bytes())
+ .then(|| Self { index: self.index + prefix.len(), ..*self })
+ }
+
+ fn prefix_bytes(&self) -> &'a [u8] {
+ &self.path.bytes()[..self.index]
+ }
+
+ fn finish(self) -> &'a OsStr {
+ // SAFETY: The unsafety here stems from converting between &OsStr and
+ // &[u8] and back. This is safe to do because (1) we only look at ASCII
+ // contents of the encoding and (2) new &OsStr values are produced only
+ // from ASCII-bounded slices of existing &OsStr values.
+ unsafe { bytes_as_os_str(&self.path.bytes()[self.index..]) }
+ }
+}
+
+pub fn parse_prefix(path: &OsStr) -> Option<Prefix<'_>> {
+ use Prefix::{DeviceNS, Disk, Verbatim, VerbatimDisk, VerbatimUNC, UNC};
+
+ let parser = PrefixParser::<8>::new(path);
+ let parser = parser.as_slice();
+ if let Some(parser) = parser.strip_prefix(r"\\") {
+ // \\
+
+ // The meaning of verbatim paths can change when they use a different
+ // separator.
+ if let Some(parser) = parser.strip_prefix(r"?\") && !parser.prefix_bytes().iter().any(|&x| x == b'/') {
+ // \\?\
+ if let Some(parser) = parser.strip_prefix(r"UNC\") {
+ // \\?\UNC\server\share
+
+ let path = parser.finish();
+ let (server, path) = parse_next_component(path, true);
+ let (share, _) = parse_next_component(path, true);
+
+ Some(VerbatimUNC(server, share))
+ } else {
+ let path = parser.finish();
+
+ // in verbatim paths only recognize an exact drive prefix
+ if let Some(drive) = parse_drive_exact(path) {
+ // \\?\C:
+ Some(VerbatimDisk(drive))
+ } else {
+ // \\?\prefix
+ let (prefix, _) = parse_next_component(path, true);
+ Some(Verbatim(prefix))
+ }
+ }
+ } else if let Some(parser) = parser.strip_prefix(r".\") {
+ // \\.\COM42
+ let path = parser.finish();
+ let (prefix, _) = parse_next_component(path, false);
+ Some(DeviceNS(prefix))
+ } else {
+ let path = parser.finish();
+ let (server, path) = parse_next_component(path, false);
+ let (share, _) = parse_next_component(path, false);
+
+ if !server.is_empty() && !share.is_empty() {
+ // \\server\share
+ Some(UNC(server, share))
+ } else {
+ // no valid prefix beginning with "\\" recognized
+ None
+ }
+ }
+ } else if let Some(drive) = parse_drive(path) {
+ // C:
+ Some(Disk(drive))
+ } else {
+ // no prefix
+ None
+ }
+}
+
+// Parses a drive prefix, e.g. "C:" and "C:\whatever"
+fn parse_drive(path: &OsStr) -> Option<u8> {
+ // In most DOS systems, it is not possible to have more than 26 drive letters.
+ // See <https://en.wikipedia.org/wiki/Drive_letter_assignment#Common_assignments>.
+ fn is_valid_drive_letter(drive: &u8) -> bool {
+ drive.is_ascii_alphabetic()
+ }
+
+ match path.bytes() {
+ [drive, b':', ..] if is_valid_drive_letter(drive) => Some(drive.to_ascii_uppercase()),
+ _ => None,
+ }
+}
+
+// Parses a drive prefix exactly, e.g. "C:"
+fn parse_drive_exact(path: &OsStr) -> Option<u8> {
+ // only parse two bytes: the drive letter and the drive separator
+ if path.bytes().get(2).map(|&x| is_sep_byte(x)).unwrap_or(true) {
+ parse_drive(path)
+ } else {
+ None
+ }
+}
+
+// Parse the next path component.
+//
+// Returns the next component and the rest of the path excluding the component and separator.
+// Does not recognize `/` as a separator character if `verbatim` is true.
+fn parse_next_component(path: &OsStr, verbatim: bool) -> (&OsStr, &OsStr) {
+ let separator = if verbatim { is_verbatim_sep } else { is_sep_byte };
+
+ match path.bytes().iter().position(|&x| separator(x)) {
+ Some(separator_start) => {
+ let separator_end = separator_start + 1;
+
+ let component = &path.bytes()[..separator_start];
+
+ // Panic safe
+ // The max `separator_end` is `bytes.len()` and `bytes[bytes.len()..]` is a valid index.
+ let path = &path.bytes()[separator_end..];
+
+ // SAFETY: `path` is a valid wtf8 encoded slice and each of the separators ('/', '\')
+ // is encoded in a single byte, therefore `bytes[separator_start]` and
+ // `bytes[separator_end]` must be code point boundaries and thus
+ // `bytes[..separator_start]` and `bytes[separator_end..]` are valid wtf8 slices.
+ unsafe { (bytes_as_os_str(component), bytes_as_os_str(path)) }
+ }
+ None => (path, OsStr::new("")),
+ }
+}
+
+/// Returns a UTF-16 encoded path capable of bypassing the legacy `MAX_PATH` limits.
+///
+/// This path may or may not have a verbatim prefix.
+pub(crate) fn maybe_verbatim(path: &Path) -> io::Result<Vec<u16>> {
+ // Normally the MAX_PATH is 260 UTF-16 code units (including the NULL).
+ // However, for APIs such as CreateDirectory[1], the limit is 248.
+ //
+ // [1]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createdirectorya#parameters
+ const LEGACY_MAX_PATH: usize = 248;
+ // UTF-16 encoded code points, used in parsing and building UTF-16 paths.
+ // All of these are in the ASCII range so they can be cast directly to `u16`.
+ const SEP: u16 = b'\\' as _;
+ const ALT_SEP: u16 = b'/' as _;
+ const QUERY: u16 = b'?' as _;
+ const COLON: u16 = b':' as _;
+ const DOT: u16 = b'.' as _;
+ const U: u16 = b'U' as _;
+ const N: u16 = b'N' as _;
+ const C: u16 = b'C' as _;
+
+ // \\?\
+ const VERBATIM_PREFIX: &[u16] = &[SEP, SEP, QUERY, SEP];
+ // \??\
+ const NT_PREFIX: &[u16] = &[SEP, QUERY, QUERY, SEP];
+ // \\?\UNC\
+ const UNC_PREFIX: &[u16] = &[SEP, SEP, QUERY, SEP, U, N, C, SEP];
+
+ let mut path = to_u16s(path)?;
+ if path.starts_with(VERBATIM_PREFIX) || path.starts_with(NT_PREFIX) || path == &[0] {
+ // Early return for paths that are already verbatim or empty.
+ return Ok(path);
+ } else if path.len() < LEGACY_MAX_PATH {
+ // Early return if an absolute path is less < 260 UTF-16 code units.
+ // This is an optimization to avoid calling `GetFullPathNameW` unnecessarily.
+ match path.as_slice() {
+ // Starts with `D:`, `D:\`, `D:/`, etc.
+ // Does not match if the path starts with a `\` or `/`.
+ [drive, COLON, 0] | [drive, COLON, SEP | ALT_SEP, ..]
+ if *drive != SEP && *drive != ALT_SEP =>
+ {
+ return Ok(path);
+ }
+ // Starts with `\\`, `//`, etc
+ [SEP | ALT_SEP, SEP | ALT_SEP, ..] => return Ok(path),
+ _ => {}
+ }
+ }
+
+ // Firstly, get the absolute path using `GetFullPathNameW`.
+ // https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfullpathnamew
+ let lpfilename = path.as_ptr();
+ fill_utf16_buf(
+ // SAFETY: `fill_utf16_buf` ensures the `buffer` and `size` are valid.
+ // `lpfilename` is a pointer to a null terminated string that is not
+ // invalidated until after `GetFullPathNameW` returns successfully.
+ |buffer, size| unsafe { c::GetFullPathNameW(lpfilename, size, buffer, ptr::null_mut()) },
+ |mut absolute| {
+ path.clear();
+
+ // Secondly, add the verbatim prefix. This is easier here because we know the
+ // path is now absolute and fully normalized (e.g. `/` has been changed to `\`).
+ let prefix = match absolute {
+ // C:\ => \\?\C:\
+ [_, COLON, SEP, ..] => VERBATIM_PREFIX,
+ // \\.\ => \\?\
+ [SEP, SEP, DOT, SEP, ..] => {
+ absolute = &absolute[4..];
+ VERBATIM_PREFIX
+ }
+ // Leave \\?\ and \??\ as-is.
+ [SEP, SEP, QUERY, SEP, ..] | [SEP, QUERY, QUERY, SEP, ..] => &[],
+ // \\ => \\?\UNC\
+ [SEP, SEP, ..] => {
+ absolute = &absolute[2..];
+ UNC_PREFIX
+ }
+ // Anything else we leave alone.
+ _ => &[],
+ };
+
+ path.reserve_exact(prefix.len() + absolute.len() + 1);
+ path.extend_from_slice(prefix);
+ path.extend_from_slice(absolute);
+ path.push(0);
+ },
+ )?;
+ Ok(path)
+}
+
+/// Make a Windows path absolute.
+pub(crate) fn absolute(path: &Path) -> io::Result<PathBuf> {
+ let path = path.as_os_str();
+ let prefix = parse_prefix(path);
+ // Verbatim paths should not be modified.
+ if prefix.map(|x| x.is_verbatim()).unwrap_or(false) {
+ // NULs in verbatim paths are rejected for consistency.
+ if path.bytes().contains(&0) {
+ return Err(io::const_io_error!(
+ io::ErrorKind::InvalidInput,
+ "strings passed to WinAPI cannot contain NULs",
+ ));
+ }
+ return Ok(path.to_owned().into());
+ }
+
+ let path = to_u16s(path)?;
+ let lpfilename = path.as_ptr();
+ fill_utf16_buf(
+ // SAFETY: `fill_utf16_buf` ensures the `buffer` and `size` are valid.
+ // `lpfilename` is a pointer to a null terminated string that is not
+ // invalidated until after `GetFullPathNameW` returns successfully.
+ |buffer, size| unsafe { c::GetFullPathNameW(lpfilename, size, buffer, ptr::null_mut()) },
+ super::os2path,
+ )
+}
diff --git a/library/std/src/sys/windows/path/tests.rs b/library/std/src/sys/windows/path/tests.rs
new file mode 100644
index 000000000..6eab38cab
--- /dev/null
+++ b/library/std/src/sys/windows/path/tests.rs
@@ -0,0 +1,137 @@
+use super::*;
+
+#[test]
+fn test_parse_next_component() {
+ assert_eq!(
+ parse_next_component(OsStr::new(r"server\share"), true),
+ (OsStr::new(r"server"), OsStr::new(r"share"))
+ );
+
+ assert_eq!(
+ parse_next_component(OsStr::new(r"server/share"), true),
+ (OsStr::new(r"server/share"), OsStr::new(r""))
+ );
+
+ assert_eq!(
+ parse_next_component(OsStr::new(r"server/share"), false),
+ (OsStr::new(r"server"), OsStr::new(r"share"))
+ );
+
+ assert_eq!(
+ parse_next_component(OsStr::new(r"server\"), false),
+ (OsStr::new(r"server"), OsStr::new(r""))
+ );
+
+ assert_eq!(
+ parse_next_component(OsStr::new(r"\server\"), false),
+ (OsStr::new(r""), OsStr::new(r"server\"))
+ );
+
+ assert_eq!(
+ parse_next_component(OsStr::new(r"servershare"), false),
+ (OsStr::new(r"servershare"), OsStr::new(""))
+ );
+}
+
+#[test]
+fn verbatim() {
+ use crate::path::Path;
+ fn check(path: &str, expected: &str) {
+ let verbatim = maybe_verbatim(Path::new(path)).unwrap();
+ let verbatim = String::from_utf16_lossy(verbatim.strip_suffix(&[0]).unwrap());
+ assert_eq!(&verbatim, expected, "{}", path);
+ }
+
+ // Ensure long paths are correctly prefixed.
+ check(
+ r"C:\Program Files\Rust\aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\foo.txt",
+ r"\\?\C:\Program Files\Rust\aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\foo.txt",
+ );
+ check(
+ r"\\server\share\aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\foo.txt",
+ r"\\?\UNC\server\share\aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\foo.txt",
+ );
+ check(
+ r"\\.\PIPE\aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\foo.txt",
+ r"\\?\PIPE\aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\foo.txt",
+ );
+ // `\\?\` prefixed paths are left unchanged...
+ check(
+ r"\\?\verbatim.\aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\foo.txt",
+ r"\\?\verbatim.\aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\foo.txt",
+ );
+ // But `//?/` is not a verbatim prefix so it will be normalized.
+ check(
+ r"//?/E:/verbatim.\aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\foo.txt",
+ r"\\?\E:\verbatim\aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\foo.txt",
+ );
+
+ // For performance, short absolute paths are left unchanged.
+ check(r"C:\Program Files\Rust", r"C:\Program Files\Rust");
+ check(r"\\server\share", r"\\server\share");
+ check(r"\\.\COM1", r"\\.\COM1");
+
+ // Check that paths of length 247 are converted to verbatim.
+ // This is necessary for `CreateDirectory`.
+ check(
+ r"C:\aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ r"\\?\C:\aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ );
+
+ // Make sure opening a drive will work.
+ check("Z:", "Z:");
+
+ // A path that contains null is not a valid path.
+ assert!(maybe_verbatim(Path::new("\0")).is_err());
+}
+
+fn parse_prefix(path: &str) -> Option<Prefix<'_>> {
+ super::parse_prefix(OsStr::new(path))
+}
+
+#[test]
+fn test_parse_prefix_verbatim() {
+ let prefix = Some(Prefix::VerbatimDisk(b'C'));
+ assert_eq!(prefix, parse_prefix(r"\\?\C:/windows/system32/notepad.exe"));
+ assert_eq!(prefix, parse_prefix(r"\\?\C:\windows\system32\notepad.exe"));
+}
+
+#[test]
+fn test_parse_prefix_verbatim_device() {
+ let prefix = Some(Prefix::UNC(OsStr::new("?"), OsStr::new("C:")));
+ assert_eq!(prefix, parse_prefix(r"//?/C:/windows/system32/notepad.exe"));
+ assert_eq!(prefix, parse_prefix(r"//?/C:\windows\system32\notepad.exe"));
+ assert_eq!(prefix, parse_prefix(r"/\?\C:\windows\system32\notepad.exe"));
+ assert_eq!(prefix, parse_prefix(r"\\?/C:\windows\system32\notepad.exe"));
+}
+
+// See #93586 for more infomation.
+#[test]
+fn test_windows_prefix_components() {
+ use crate::path::Path;
+
+ let path = Path::new("C:");
+ let mut components = path.components();
+ let drive = components.next().expect("drive is expected here");
+ assert_eq!(drive.as_os_str(), OsStr::new("C:"));
+ assert_eq!(components.as_path(), Path::new(""));
+}
+
+/// See #101358.
+///
+/// Note that the exact behaviour here may change in the future.
+/// In which case this test will need to adjusted.
+#[test]
+fn broken_unc_path() {
+ use crate::path::Component;
+
+ let mut components = Path::new(r"\\foo\\bar\\").components();
+ assert_eq!(components.next(), Some(Component::RootDir));
+ assert_eq!(components.next(), Some(Component::Normal("foo".as_ref())));
+ assert_eq!(components.next(), Some(Component::Normal("bar".as_ref())));
+
+ let mut components = Path::new("//foo//bar//").components();
+ assert_eq!(components.next(), Some(Component::RootDir));
+ assert_eq!(components.next(), Some(Component::Normal("foo".as_ref())));
+ assert_eq!(components.next(), Some(Component::Normal("bar".as_ref())));
+}
diff --git a/library/std/src/sys/windows/pipe.rs b/library/std/src/sys/windows/pipe.rs
new file mode 100644
index 000000000..013c776c4
--- /dev/null
+++ b/library/std/src/sys/windows/pipe.rs
@@ -0,0 +1,538 @@
+use crate::os::windows::prelude::*;
+
+use crate::ffi::OsStr;
+use crate::io::{self, IoSlice, IoSliceMut};
+use crate::mem;
+use crate::path::Path;
+use crate::ptr;
+use crate::slice;
+use crate::sync::atomic::AtomicUsize;
+use crate::sync::atomic::Ordering::SeqCst;
+use crate::sys::c;
+use crate::sys::fs::{File, OpenOptions};
+use crate::sys::handle::Handle;
+use crate::sys::hashmap_random_keys;
+use crate::sys_common::IntoInner;
+
+////////////////////////////////////////////////////////////////////////////////
+// Anonymous pipes
+////////////////////////////////////////////////////////////////////////////////
+
+pub struct AnonPipe {
+ inner: Handle,
+}
+
+impl IntoInner<Handle> for AnonPipe {
+ fn into_inner(self) -> Handle {
+ self.inner
+ }
+}
+
+pub struct Pipes {
+ pub ours: AnonPipe,
+ pub theirs: AnonPipe,
+}
+
+/// Although this looks similar to `anon_pipe` in the Unix module it's actually
+/// subtly different. Here we'll return two pipes in the `Pipes` return value,
+/// but one is intended for "us" where as the other is intended for "someone
+/// else".
+///
+/// Currently the only use case for this function is pipes for stdio on
+/// processes in the standard library, so "ours" is the one that'll stay in our
+/// process whereas "theirs" will be inherited to a child.
+///
+/// The ours/theirs pipes are *not* specifically readable or writable. Each
+/// one only supports a read or a write, but which is which depends on the
+/// boolean flag given. If `ours_readable` is `true`, then `ours` is readable and
+/// `theirs` is writable. Conversely, if `ours_readable` is `false`, then `ours`
+/// is writable and `theirs` is readable.
+///
+/// Also note that the `ours` pipe is always a handle opened up in overlapped
+/// mode. This means that technically speaking it should only ever be used
+/// with `OVERLAPPED` instances, but also works out ok if it's only ever used
+/// once at a time (which we do indeed guarantee).
+pub fn anon_pipe(ours_readable: bool, their_handle_inheritable: bool) -> io::Result<Pipes> {
+ // A 64kb pipe capacity is the same as a typical Linux default.
+ const PIPE_BUFFER_CAPACITY: u32 = 64 * 1024;
+
+ // Note that we specifically do *not* use `CreatePipe` here because
+ // unfortunately the anonymous pipes returned do not support overlapped
+ // operations. Instead, we create a "hopefully unique" name and create a
+ // named pipe which has overlapped operations enabled.
+ //
+ // Once we do this, we connect do it as usual via `CreateFileW`, and then
+ // we return those reader/writer halves. Note that the `ours` pipe return
+ // value is always the named pipe, whereas `theirs` is just the normal file.
+ // This should hopefully shield us from child processes which assume their
+ // stdout is a named pipe, which would indeed be odd!
+ unsafe {
+ let ours;
+ let mut name;
+ let mut tries = 0;
+ let mut reject_remote_clients_flag = c::PIPE_REJECT_REMOTE_CLIENTS;
+ loop {
+ tries += 1;
+ name = format!(
+ r"\\.\pipe\__rust_anonymous_pipe1__.{}.{}",
+ c::GetCurrentProcessId(),
+ random_number()
+ );
+ let wide_name = OsStr::new(&name).encode_wide().chain(Some(0)).collect::<Vec<_>>();
+ let mut flags = c::FILE_FLAG_FIRST_PIPE_INSTANCE | c::FILE_FLAG_OVERLAPPED;
+ if ours_readable {
+ flags |= c::PIPE_ACCESS_INBOUND;
+ } else {
+ flags |= c::PIPE_ACCESS_OUTBOUND;
+ }
+
+ let handle = c::CreateNamedPipeW(
+ wide_name.as_ptr(),
+ flags,
+ c::PIPE_TYPE_BYTE
+ | c::PIPE_READMODE_BYTE
+ | c::PIPE_WAIT
+ | reject_remote_clients_flag,
+ 1,
+ PIPE_BUFFER_CAPACITY,
+ PIPE_BUFFER_CAPACITY,
+ 0,
+ ptr::null_mut(),
+ );
+
+ // We pass the `FILE_FLAG_FIRST_PIPE_INSTANCE` flag above, and we're
+ // also just doing a best effort at selecting a unique name. If
+ // `ERROR_ACCESS_DENIED` is returned then it could mean that we
+ // accidentally conflicted with an already existing pipe, so we try
+ // again.
+ //
+ // Don't try again too much though as this could also perhaps be a
+ // legit error.
+ // If `ERROR_INVALID_PARAMETER` is returned, this probably means we're
+ // running on pre-Vista version where `PIPE_REJECT_REMOTE_CLIENTS` is
+ // not supported, so we continue retrying without it. This implies
+ // reduced security on Windows versions older than Vista by allowing
+ // connections to this pipe from remote machines.
+ // Proper fix would increase the number of FFI imports and introduce
+ // significant amount of Windows XP specific code with no clean
+ // testing strategy
+ // For more info, see https://github.com/rust-lang/rust/pull/37677.
+ if handle == c::INVALID_HANDLE_VALUE {
+ let err = io::Error::last_os_error();
+ let raw_os_err = err.raw_os_error();
+ if tries < 10 {
+ if raw_os_err == Some(c::ERROR_ACCESS_DENIED as i32) {
+ continue;
+ } else if reject_remote_clients_flag != 0
+ && raw_os_err == Some(c::ERROR_INVALID_PARAMETER as i32)
+ {
+ reject_remote_clients_flag = 0;
+ tries -= 1;
+ continue;
+ }
+ }
+ return Err(err);
+ }
+ ours = Handle::from_raw_handle(handle);
+ break;
+ }
+
+ // Connect to the named pipe we just created. This handle is going to be
+ // returned in `theirs`, so if `ours` is readable we want this to be
+ // writable, otherwise if `ours` is writable we want this to be
+ // readable.
+ //
+ // Additionally we don't enable overlapped mode on this because most
+ // client processes aren't enabled to work with that.
+ let mut opts = OpenOptions::new();
+ opts.write(ours_readable);
+ opts.read(!ours_readable);
+ opts.share_mode(0);
+ let size = mem::size_of::<c::SECURITY_ATTRIBUTES>();
+ let mut sa = c::SECURITY_ATTRIBUTES {
+ nLength: size as c::DWORD,
+ lpSecurityDescriptor: ptr::null_mut(),
+ bInheritHandle: their_handle_inheritable as i32,
+ };
+ opts.security_attributes(&mut sa);
+ let theirs = File::open(Path::new(&name), &opts)?;
+ let theirs = AnonPipe { inner: theirs.into_inner() };
+
+ Ok(Pipes {
+ ours: AnonPipe { inner: ours },
+ theirs: AnonPipe { inner: theirs.into_inner() },
+ })
+ }
+}
+
+/// Takes an asynchronous source pipe and returns a synchronous pipe suitable
+/// for sending to a child process.
+///
+/// This is achieved by creating a new set of pipes and spawning a thread that
+/// relays messages between the source and the synchronous pipe.
+pub fn spawn_pipe_relay(
+ source: &AnonPipe,
+ ours_readable: bool,
+ their_handle_inheritable: bool,
+) -> io::Result<AnonPipe> {
+ // We need this handle to live for the lifetime of the thread spawned below.
+ let source = source.duplicate()?;
+
+ // create a new pair of anon pipes.
+ let Pipes { theirs, ours } = anon_pipe(ours_readable, their_handle_inheritable)?;
+
+ // Spawn a thread that passes messages from one pipe to the other.
+ // Any errors will simply cause the thread to exit.
+ let (reader, writer) = if ours_readable { (ours, source) } else { (source, ours) };
+ crate::thread::spawn(move || {
+ let mut buf = [0_u8; 4096];
+ 'reader: while let Ok(len) = reader.read(&mut buf) {
+ if len == 0 {
+ break;
+ }
+ let mut start = 0;
+ while let Ok(written) = writer.write(&buf[start..len]) {
+ start += written;
+ if start == len {
+ continue 'reader;
+ }
+ }
+ break;
+ }
+ });
+
+ // Return the pipe that should be sent to the child process.
+ Ok(theirs)
+}
+
+fn random_number() -> usize {
+ static N: AtomicUsize = AtomicUsize::new(0);
+ loop {
+ if N.load(SeqCst) != 0 {
+ return N.fetch_add(1, SeqCst);
+ }
+
+ N.store(hashmap_random_keys().0 as usize, SeqCst);
+ }
+}
+
+// Abstracts over `ReadFileEx` and `WriteFileEx`
+type AlertableIoFn = unsafe extern "system" fn(
+ BorrowedHandle<'_>,
+ c::LPVOID,
+ c::DWORD,
+ c::LPOVERLAPPED,
+ c::LPOVERLAPPED_COMPLETION_ROUTINE,
+) -> c::BOOL;
+
+impl AnonPipe {
+ pub fn handle(&self) -> &Handle {
+ &self.inner
+ }
+ pub fn into_handle(self) -> Handle {
+ self.inner
+ }
+ fn duplicate(&self) -> io::Result<Self> {
+ self.inner.duplicate(0, false, c::DUPLICATE_SAME_ACCESS).map(|inner| AnonPipe { inner })
+ }
+
+ pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
+ let result = unsafe {
+ let len = crate::cmp::min(buf.len(), c::DWORD::MAX as usize) as c::DWORD;
+ self.alertable_io_internal(c::ReadFileEx, buf.as_mut_ptr() as _, len)
+ };
+
+ match result {
+ // The special treatment of BrokenPipe is to deal with Windows
+ // pipe semantics, which yields this error when *reading* from
+ // a pipe after the other end has closed; we interpret that as
+ // EOF on the pipe.
+ Err(ref e) if e.kind() == io::ErrorKind::BrokenPipe => Ok(0),
+ _ => result,
+ }
+ }
+
+ pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
+ self.inner.read_vectored(bufs)
+ }
+
+ #[inline]
+ pub fn is_read_vectored(&self) -> bool {
+ self.inner.is_read_vectored()
+ }
+
+ pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
+ unsafe {
+ let len = crate::cmp::min(buf.len(), c::DWORD::MAX as usize) as c::DWORD;
+ self.alertable_io_internal(c::WriteFileEx, buf.as_ptr() as _, len)
+ }
+ }
+
+ pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
+ self.inner.write_vectored(bufs)
+ }
+
+ #[inline]
+ pub fn is_write_vectored(&self) -> bool {
+ self.inner.is_write_vectored()
+ }
+
+ /// Synchronizes asynchronous reads or writes using our anonymous pipe.
+ ///
+ /// This is a wrapper around [`ReadFileEx`] or [`WriteFileEx`] that uses
+ /// [Asynchronous Procedure Call] (APC) to synchronize reads or writes.
+ ///
+ /// Note: This should not be used for handles we don't create.
+ ///
+ /// # Safety
+ ///
+ /// `buf` must be a pointer to a buffer that's valid for reads or writes
+ /// up to `len` bytes. The `AlertableIoFn` must be either `ReadFileEx` or `WriteFileEx`
+ ///
+ /// [`ReadFileEx`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-readfileex
+ /// [`WriteFileEx`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-writefileex
+ /// [Asynchronous Procedure Call]: https://docs.microsoft.com/en-us/windows/win32/sync/asynchronous-procedure-calls
+ unsafe fn alertable_io_internal(
+ &self,
+ io: AlertableIoFn,
+ buf: c::LPVOID,
+ len: c::DWORD,
+ ) -> io::Result<usize> {
+ // Use "alertable I/O" to synchronize the pipe I/O.
+ // This has four steps.
+ //
+ // STEP 1: Start the asynchronous I/O operation.
+ // This simply calls either `ReadFileEx` or `WriteFileEx`,
+ // giving it a pointer to the buffer and callback function.
+ //
+ // STEP 2: Enter an alertable state.
+ // The callback set in step 1 will not be called until the thread
+ // enters an "alertable" state. This can be done using `SleepEx`.
+ //
+ // STEP 3: The callback
+ // Once the I/O is complete and the thread is in an alertable state,
+ // the callback will be run on the same thread as the call to
+ // `ReadFileEx` or `WriteFileEx` done in step 1.
+ // In the callback we simply set the result of the async operation.
+ //
+ // STEP 4: Return the result.
+ // At this point we'll have a result from the callback function
+ // and can simply return it. Note that we must not return earlier,
+ // while the I/O is still in progress.
+
+ // The result that will be set from the asynchronous callback.
+ let mut async_result: Option<AsyncResult> = None;
+ struct AsyncResult {
+ error: u32,
+ transfered: u32,
+ }
+
+ // STEP 3: The callback.
+ unsafe extern "system" fn callback(
+ dwErrorCode: u32,
+ dwNumberOfBytesTransfered: u32,
+ lpOverlapped: *mut c::OVERLAPPED,
+ ) {
+ // Set `async_result` using a pointer smuggled through `hEvent`.
+ let result = AsyncResult { error: dwErrorCode, transfered: dwNumberOfBytesTransfered };
+ *(*lpOverlapped).hEvent.cast::<Option<AsyncResult>>() = Some(result);
+ }
+
+ // STEP 1: Start the I/O operation.
+ let mut overlapped: c::OVERLAPPED = crate::mem::zeroed();
+ // `hEvent` is unused by `ReadFileEx` and `WriteFileEx`.
+ // Therefore the documentation suggests using it to smuggle a pointer to the callback.
+ overlapped.hEvent = &mut async_result as *mut _ as *mut _;
+
+ // Asynchronous read of the pipe.
+ // If successful, `callback` will be called once it completes.
+ let result = io(self.inner.as_handle(), buf, len, &mut overlapped, callback);
+ if result == c::FALSE {
+ // We can return here because the call failed.
+ // After this we must not return until the I/O completes.
+ return Err(io::Error::last_os_error());
+ }
+
+ // Wait indefinitely for the result.
+ let result = loop {
+ // STEP 2: Enter an alertable state.
+ // The second parameter of `SleepEx` is used to make this sleep alertable.
+ c::SleepEx(c::INFINITE, c::TRUE);
+ if let Some(result) = async_result {
+ break result;
+ }
+ };
+ // STEP 4: Return the result.
+ // `async_result` is always `Some` at this point
+ match result.error {
+ c::ERROR_SUCCESS => Ok(result.transfered as usize),
+ error => Err(io::Error::from_raw_os_error(error as _)),
+ }
+ }
+}
+
+pub fn read2(p1: AnonPipe, v1: &mut Vec<u8>, p2: AnonPipe, v2: &mut Vec<u8>) -> io::Result<()> {
+ let p1 = p1.into_handle();
+ let p2 = p2.into_handle();
+
+ let mut p1 = AsyncPipe::new(p1, v1)?;
+ let mut p2 = AsyncPipe::new(p2, v2)?;
+ let objs = [p1.event.as_raw_handle(), p2.event.as_raw_handle()];
+
+ // In a loop we wait for either pipe's scheduled read operation to complete.
+ // If the operation completes with 0 bytes, that means EOF was reached, in
+ // which case we just finish out the other pipe entirely.
+ //
+ // Note that overlapped I/O is in general super unsafe because we have to
+ // be careful to ensure that all pointers in play are valid for the entire
+ // duration of the I/O operation (where tons of operations can also fail).
+ // The destructor for `AsyncPipe` ends up taking care of most of this.
+ loop {
+ let res = unsafe { c::WaitForMultipleObjects(2, objs.as_ptr(), c::FALSE, c::INFINITE) };
+ if res == c::WAIT_OBJECT_0 {
+ if !p1.result()? || !p1.schedule_read()? {
+ return p2.finish();
+ }
+ } else if res == c::WAIT_OBJECT_0 + 1 {
+ if !p2.result()? || !p2.schedule_read()? {
+ return p1.finish();
+ }
+ } else {
+ return Err(io::Error::last_os_error());
+ }
+ }
+}
+
+struct AsyncPipe<'a> {
+ pipe: Handle,
+ event: Handle,
+ overlapped: Box<c::OVERLAPPED>, // needs a stable address
+ dst: &'a mut Vec<u8>,
+ state: State,
+}
+
+#[derive(PartialEq, Debug)]
+enum State {
+ NotReading,
+ Reading,
+ Read(usize),
+}
+
+impl<'a> AsyncPipe<'a> {
+ fn new(pipe: Handle, dst: &'a mut Vec<u8>) -> io::Result<AsyncPipe<'a>> {
+ // Create an event which we'll use to coordinate our overlapped
+ // operations, this event will be used in WaitForMultipleObjects
+ // and passed as part of the OVERLAPPED handle.
+ //
+ // Note that we do a somewhat clever thing here by flagging the
+ // event as being manually reset and setting it initially to the
+ // signaled state. This means that we'll naturally fall through the
+ // WaitForMultipleObjects call above for pipes created initially,
+ // and the only time an even will go back to "unset" will be once an
+ // I/O operation is successfully scheduled (what we want).
+ let event = Handle::new_event(true, true)?;
+ let mut overlapped: Box<c::OVERLAPPED> = unsafe { Box::new(mem::zeroed()) };
+ overlapped.hEvent = event.as_raw_handle();
+ Ok(AsyncPipe { pipe, overlapped, event, dst, state: State::NotReading })
+ }
+
+ /// Executes an overlapped read operation.
+ ///
+ /// Must not currently be reading, and returns whether the pipe is currently
+ /// at EOF or not. If the pipe is not at EOF then `result()` must be called
+ /// to complete the read later on (may block), but if the pipe is at EOF
+ /// then `result()` should not be called as it will just block forever.
+ fn schedule_read(&mut self) -> io::Result<bool> {
+ assert_eq!(self.state, State::NotReading);
+ let amt = unsafe {
+ let slice = slice_to_end(self.dst);
+ self.pipe.read_overlapped(slice, &mut *self.overlapped)?
+ };
+
+ // If this read finished immediately then our overlapped event will
+ // remain signaled (it was signaled coming in here) and we'll progress
+ // down to the method below.
+ //
+ // Otherwise the I/O operation is scheduled and the system set our event
+ // to not signaled, so we flag ourselves into the reading state and move
+ // on.
+ self.state = match amt {
+ Some(0) => return Ok(false),
+ Some(amt) => State::Read(amt),
+ None => State::Reading,
+ };
+ Ok(true)
+ }
+
+ /// Wait for the result of the overlapped operation previously executed.
+ ///
+ /// Takes a parameter `wait` which indicates if this pipe is currently being
+ /// read whether the function should block waiting for the read to complete.
+ ///
+ /// Returns values:
+ ///
+ /// * `true` - finished any pending read and the pipe is not at EOF (keep
+ /// going)
+ /// * `false` - finished any pending read and pipe is at EOF (stop issuing
+ /// reads)
+ fn result(&mut self) -> io::Result<bool> {
+ let amt = match self.state {
+ State::NotReading => return Ok(true),
+ State::Reading => self.pipe.overlapped_result(&mut *self.overlapped, true)?,
+ State::Read(amt) => amt,
+ };
+ self.state = State::NotReading;
+ unsafe {
+ let len = self.dst.len();
+ self.dst.set_len(len + amt);
+ }
+ Ok(amt != 0)
+ }
+
+ /// Finishes out reading this pipe entirely.
+ ///
+ /// Waits for any pending and schedule read, and then calls `read_to_end`
+ /// if necessary to read all the remaining information.
+ fn finish(&mut self) -> io::Result<()> {
+ while self.result()? && self.schedule_read()? {
+ // ...
+ }
+ Ok(())
+ }
+}
+
+impl<'a> Drop for AsyncPipe<'a> {
+ fn drop(&mut self) {
+ match self.state {
+ State::Reading => {}
+ _ => return,
+ }
+
+ // If we have a pending read operation, then we have to make sure that
+ // it's *done* before we actually drop this type. The kernel requires
+ // that the `OVERLAPPED` and buffer pointers are valid for the entire
+ // I/O operation.
+ //
+ // To do that, we call `CancelIo` to cancel any pending operation, and
+ // if that succeeds we wait for the overlapped result.
+ //
+ // If anything here fails, there's not really much we can do, so we leak
+ // the buffer/OVERLAPPED pointers to ensure we're at least memory safe.
+ if self.pipe.cancel_io().is_err() || self.result().is_err() {
+ let buf = mem::take(self.dst);
+ let overlapped = Box::new(unsafe { mem::zeroed() });
+ let overlapped = mem::replace(&mut self.overlapped, overlapped);
+ mem::forget((buf, overlapped));
+ }
+ }
+}
+
+unsafe fn slice_to_end(v: &mut Vec<u8>) -> &mut [u8] {
+ if v.capacity() == 0 {
+ v.reserve(16);
+ }
+ if v.capacity() == v.len() {
+ v.reserve(1);
+ }
+ slice::from_raw_parts_mut(v.as_mut_ptr().add(v.len()), v.capacity() - v.len())
+}
diff --git a/library/std/src/sys/windows/process.rs b/library/std/src/sys/windows/process.rs
new file mode 100644
index 000000000..02d5af471
--- /dev/null
+++ b/library/std/src/sys/windows/process.rs
@@ -0,0 +1,847 @@
+#![unstable(feature = "process_internals", issue = "none")]
+
+#[cfg(test)]
+mod tests;
+
+use crate::cmp;
+use crate::collections::BTreeMap;
+use crate::env;
+use crate::env::consts::{EXE_EXTENSION, EXE_SUFFIX};
+use crate::ffi::{OsStr, OsString};
+use crate::fmt;
+use crate::io::{self, Error, ErrorKind};
+use crate::mem;
+use crate::num::NonZeroI32;
+use crate::os::windows::ffi::{OsStrExt, OsStringExt};
+use crate::os::windows::io::{AsHandle, AsRawHandle, BorrowedHandle, FromRawHandle, IntoRawHandle};
+use crate::path::{Path, PathBuf};
+use crate::ptr;
+use crate::sys::args::{self, Arg};
+use crate::sys::c;
+use crate::sys::c::NonZeroDWORD;
+use crate::sys::cvt;
+use crate::sys::fs::{File, OpenOptions};
+use crate::sys::handle::Handle;
+use crate::sys::path;
+use crate::sys::pipe::{self, AnonPipe};
+use crate::sys::stdio;
+use crate::sys_common::mutex::StaticMutex;
+use crate::sys_common::process::{CommandEnv, CommandEnvs};
+use crate::sys_common::IntoInner;
+
+use libc::{c_void, EXIT_FAILURE, EXIT_SUCCESS};
+
+////////////////////////////////////////////////////////////////////////////////
+// Command
+////////////////////////////////////////////////////////////////////////////////
+
+#[derive(Clone, Debug, Eq)]
+#[doc(hidden)]
+pub struct EnvKey {
+ os_string: OsString,
+ // This stores a UTF-16 encoded string to workaround the mismatch between
+ // Rust's OsString (WTF-8) and the Windows API string type (UTF-16).
+ // Normally converting on every API call is acceptable but here
+ // `c::CompareStringOrdinal` will be called for every use of `==`.
+ utf16: Vec<u16>,
+}
+
+impl EnvKey {
+ fn new<T: Into<OsString>>(key: T) -> Self {
+ EnvKey::from(key.into())
+ }
+}
+
+// Comparing Windows environment variable keys[1] are behaviourally the
+// composition of two operations[2]:
+//
+// 1. Case-fold both strings. This is done using a language-independent
+// uppercase mapping that's unique to Windows (albeit based on data from an
+// older Unicode spec). It only operates on individual UTF-16 code units so
+// surrogates are left unchanged. This uppercase mapping can potentially change
+// between Windows versions.
+//
+// 2. Perform an ordinal comparison of the strings. A comparison using ordinal
+// is just a comparison based on the numerical value of each UTF-16 code unit[3].
+//
+// Because the case-folding mapping is unique to Windows and not guaranteed to
+// be stable, we ask the OS to compare the strings for us. This is done by
+// calling `CompareStringOrdinal`[4] with `bIgnoreCase` set to `TRUE`.
+//
+// [1] https://docs.microsoft.com/en-us/dotnet/standard/base-types/best-practices-strings#choosing-a-stringcomparison-member-for-your-method-call
+// [2] https://docs.microsoft.com/en-us/dotnet/standard/base-types/best-practices-strings#stringtoupper-and-stringtolower
+// [3] https://docs.microsoft.com/en-us/dotnet/api/system.stringcomparison?view=net-5.0#System_StringComparison_Ordinal
+// [4] https://docs.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-comparestringordinal
+impl Ord for EnvKey {
+ fn cmp(&self, other: &Self) -> cmp::Ordering {
+ unsafe {
+ let result = c::CompareStringOrdinal(
+ self.utf16.as_ptr(),
+ self.utf16.len() as _,
+ other.utf16.as_ptr(),
+ other.utf16.len() as _,
+ c::TRUE,
+ );
+ match result {
+ c::CSTR_LESS_THAN => cmp::Ordering::Less,
+ c::CSTR_EQUAL => cmp::Ordering::Equal,
+ c::CSTR_GREATER_THAN => cmp::Ordering::Greater,
+ // `CompareStringOrdinal` should never fail so long as the parameters are correct.
+ _ => panic!("comparing environment keys failed: {}", Error::last_os_error()),
+ }
+ }
+ }
+}
+impl PartialOrd for EnvKey {
+ fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
+ Some(self.cmp(other))
+ }
+}
+impl PartialEq for EnvKey {
+ fn eq(&self, other: &Self) -> bool {
+ if self.utf16.len() != other.utf16.len() {
+ false
+ } else {
+ self.cmp(other) == cmp::Ordering::Equal
+ }
+ }
+}
+impl PartialOrd<str> for EnvKey {
+ fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
+ Some(self.cmp(&EnvKey::new(other)))
+ }
+}
+impl PartialEq<str> for EnvKey {
+ fn eq(&self, other: &str) -> bool {
+ if self.os_string.len() != other.len() {
+ false
+ } else {
+ self.cmp(&EnvKey::new(other)) == cmp::Ordering::Equal
+ }
+ }
+}
+
+// Environment variable keys should preserve their original case even though
+// they are compared using a caseless string mapping.
+impl From<OsString> for EnvKey {
+ fn from(k: OsString) -> Self {
+ EnvKey { utf16: k.encode_wide().collect(), os_string: k }
+ }
+}
+
+impl From<EnvKey> for OsString {
+ fn from(k: EnvKey) -> Self {
+ k.os_string
+ }
+}
+
+impl From<&OsStr> for EnvKey {
+ fn from(k: &OsStr) -> Self {
+ Self::from(k.to_os_string())
+ }
+}
+
+impl AsRef<OsStr> for EnvKey {
+ fn as_ref(&self) -> &OsStr {
+ &self.os_string
+ }
+}
+
+pub(crate) fn ensure_no_nuls<T: AsRef<OsStr>>(str: T) -> io::Result<T> {
+ if str.as_ref().encode_wide().any(|b| b == 0) {
+ Err(io::const_io_error!(ErrorKind::InvalidInput, "nul byte found in provided data"))
+ } else {
+ Ok(str)
+ }
+}
+
+pub struct Command {
+ program: OsString,
+ args: Vec<Arg>,
+ env: CommandEnv,
+ cwd: Option<OsString>,
+ flags: u32,
+ detach: bool, // not currently exposed in std::process
+ stdin: Option<Stdio>,
+ stdout: Option<Stdio>,
+ stderr: Option<Stdio>,
+ force_quotes_enabled: bool,
+}
+
+pub enum Stdio {
+ Inherit,
+ Null,
+ MakePipe,
+ Pipe(AnonPipe),
+ Handle(Handle),
+}
+
+pub struct StdioPipes {
+ pub stdin: Option<AnonPipe>,
+ pub stdout: Option<AnonPipe>,
+ pub stderr: Option<AnonPipe>,
+}
+
+impl Command {
+ pub fn new(program: &OsStr) -> Command {
+ Command {
+ program: program.to_os_string(),
+ args: Vec::new(),
+ env: Default::default(),
+ cwd: None,
+ flags: 0,
+ detach: false,
+ stdin: None,
+ stdout: None,
+ stderr: None,
+ force_quotes_enabled: false,
+ }
+ }
+
+ pub fn arg(&mut self, arg: &OsStr) {
+ self.args.push(Arg::Regular(arg.to_os_string()))
+ }
+ pub fn env_mut(&mut self) -> &mut CommandEnv {
+ &mut self.env
+ }
+ pub fn cwd(&mut self, dir: &OsStr) {
+ self.cwd = Some(dir.to_os_string())
+ }
+ pub fn stdin(&mut self, stdin: Stdio) {
+ self.stdin = Some(stdin);
+ }
+ pub fn stdout(&mut self, stdout: Stdio) {
+ self.stdout = Some(stdout);
+ }
+ pub fn stderr(&mut self, stderr: Stdio) {
+ self.stderr = Some(stderr);
+ }
+ pub fn creation_flags(&mut self, flags: u32) {
+ self.flags = flags;
+ }
+
+ pub fn force_quotes(&mut self, enabled: bool) {
+ self.force_quotes_enabled = enabled;
+ }
+
+ pub fn raw_arg(&mut self, command_str_to_append: &OsStr) {
+ self.args.push(Arg::Raw(command_str_to_append.to_os_string()))
+ }
+
+ pub fn get_program(&self) -> &OsStr {
+ &self.program
+ }
+
+ pub fn get_args(&self) -> CommandArgs<'_> {
+ let iter = self.args.iter();
+ CommandArgs { iter }
+ }
+
+ pub fn get_envs(&self) -> CommandEnvs<'_> {
+ self.env.iter()
+ }
+
+ pub fn get_current_dir(&self) -> Option<&Path> {
+ self.cwd.as_ref().map(|cwd| Path::new(cwd))
+ }
+
+ pub fn spawn(
+ &mut self,
+ default: Stdio,
+ needs_stdin: bool,
+ ) -> io::Result<(Process, StdioPipes)> {
+ let maybe_env = self.env.capture_if_changed();
+
+ let mut si = zeroed_startupinfo();
+ si.cb = mem::size_of::<c::STARTUPINFO>() as c::DWORD;
+ si.dwFlags = c::STARTF_USESTDHANDLES;
+
+ let child_paths = if let Some(env) = maybe_env.as_ref() {
+ env.get(&EnvKey::new("PATH")).map(|s| s.as_os_str())
+ } else {
+ None
+ };
+ let program = resolve_exe(&self.program, || env::var_os("PATH"), child_paths)?;
+ // Case insensitive "ends_with" of UTF-16 encoded ".bat" or ".cmd"
+ let is_batch_file = matches!(
+ program.len().checked_sub(5).and_then(|i| program.get(i..)),
+ Some([46, 98 | 66, 97 | 65, 116 | 84, 0] | [46, 99 | 67, 109 | 77, 100 | 68, 0])
+ );
+ let (program, mut cmd_str) = if is_batch_file {
+ (
+ command_prompt()?,
+ args::make_bat_command_line(
+ &args::to_user_path(program)?,
+ &self.args,
+ self.force_quotes_enabled,
+ )?,
+ )
+ } else {
+ let cmd_str = make_command_line(&self.program, &self.args, self.force_quotes_enabled)?;
+ (program, cmd_str)
+ };
+ cmd_str.push(0); // add null terminator
+
+ // stolen from the libuv code.
+ let mut flags = self.flags | c::CREATE_UNICODE_ENVIRONMENT;
+ if self.detach {
+ flags |= c::DETACHED_PROCESS | c::CREATE_NEW_PROCESS_GROUP;
+ }
+
+ let (envp, _data) = make_envp(maybe_env)?;
+ let (dirp, _data) = make_dirp(self.cwd.as_ref())?;
+ let mut pi = zeroed_process_information();
+
+ // Prepare all stdio handles to be inherited by the child. This
+ // currently involves duplicating any existing ones with the ability to
+ // be inherited by child processes. Note, however, that once an
+ // inheritable handle is created, *any* spawned child will inherit that
+ // handle. We only want our own child to inherit this handle, so we wrap
+ // the remaining portion of this spawn in a mutex.
+ //
+ // For more information, msdn also has an article about this race:
+ // https://support.microsoft.com/kb/315939
+ static CREATE_PROCESS_LOCK: StaticMutex = StaticMutex::new();
+
+ let _guard = unsafe { CREATE_PROCESS_LOCK.lock() };
+
+ let mut pipes = StdioPipes { stdin: None, stdout: None, stderr: None };
+ let null = Stdio::Null;
+ let default_stdin = if needs_stdin { &default } else { &null };
+ let stdin = self.stdin.as_ref().unwrap_or(default_stdin);
+ let stdout = self.stdout.as_ref().unwrap_or(&default);
+ let stderr = self.stderr.as_ref().unwrap_or(&default);
+ let stdin = stdin.to_handle(c::STD_INPUT_HANDLE, &mut pipes.stdin)?;
+ let stdout = stdout.to_handle(c::STD_OUTPUT_HANDLE, &mut pipes.stdout)?;
+ let stderr = stderr.to_handle(c::STD_ERROR_HANDLE, &mut pipes.stderr)?;
+ si.hStdInput = stdin.as_raw_handle();
+ si.hStdOutput = stdout.as_raw_handle();
+ si.hStdError = stderr.as_raw_handle();
+
+ unsafe {
+ cvt(c::CreateProcessW(
+ program.as_ptr(),
+ cmd_str.as_mut_ptr(),
+ ptr::null_mut(),
+ ptr::null_mut(),
+ c::TRUE,
+ flags,
+ envp,
+ dirp,
+ &mut si,
+ &mut pi,
+ ))
+ }?;
+
+ unsafe {
+ Ok((
+ Process {
+ handle: Handle::from_raw_handle(pi.hProcess),
+ main_thread_handle: Handle::from_raw_handle(pi.hThread),
+ },
+ pipes,
+ ))
+ }
+ }
+}
+
+impl fmt::Debug for Command {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ self.program.fmt(f)?;
+ for arg in &self.args {
+ f.write_str(" ")?;
+ match arg {
+ Arg::Regular(s) => s.fmt(f),
+ Arg::Raw(s) => f.write_str(&s.to_string_lossy()),
+ }?;
+ }
+ Ok(())
+ }
+}
+
+// Resolve `exe_path` to the executable name.
+//
+// * If the path is simply a file name then use the paths given by `search_paths` to find the executable.
+// * Otherwise use the `exe_path` as given.
+//
+// This function may also append `.exe` to the name. The rationale for doing so is as follows:
+//
+// It is a very strong convention that Windows executables have the `exe` extension.
+// In Rust, it is common to omit this extension.
+// Therefore this functions first assumes `.exe` was intended.
+// It falls back to the plain file name if a full path is given and the extension is omitted
+// or if only a file name is given and it already contains an extension.
+fn resolve_exe<'a>(
+ exe_path: &'a OsStr,
+ parent_paths: impl FnOnce() -> Option<OsString>,
+ child_paths: Option<&OsStr>,
+) -> io::Result<Vec<u16>> {
+ // Early return if there is no filename.
+ if exe_path.is_empty() || path::has_trailing_slash(exe_path) {
+ return Err(io::const_io_error!(
+ io::ErrorKind::InvalidInput,
+ "program path has no file name",
+ ));
+ }
+ // Test if the file name has the `exe` extension.
+ // This does a case-insensitive `ends_with`.
+ let has_exe_suffix = if exe_path.len() >= EXE_SUFFIX.len() {
+ exe_path.bytes()[exe_path.len() - EXE_SUFFIX.len()..]
+ .eq_ignore_ascii_case(EXE_SUFFIX.as_bytes())
+ } else {
+ false
+ };
+
+ // If `exe_path` is an absolute path or a sub-path then don't search `PATH` for it.
+ if !path::is_file_name(exe_path) {
+ if has_exe_suffix {
+ // The application name is a path to a `.exe` file.
+ // Let `CreateProcessW` figure out if it exists or not.
+ return path::maybe_verbatim(Path::new(exe_path));
+ }
+ let mut path = PathBuf::from(exe_path);
+
+ // Append `.exe` if not already there.
+ path = path::append_suffix(path, EXE_SUFFIX.as_ref());
+ if let Some(path) = program_exists(&path) {
+ return Ok(path);
+ } else {
+ // It's ok to use `set_extension` here because the intent is to
+ // remove the extension that was just added.
+ path.set_extension("");
+ return path::maybe_verbatim(&path);
+ }
+ } else {
+ ensure_no_nuls(exe_path)?;
+ // From the `CreateProcessW` docs:
+ // > If the file name does not contain an extension, .exe is appended.
+ // Note that this rule only applies when searching paths.
+ let has_extension = exe_path.bytes().contains(&b'.');
+
+ // Search the directories given by `search_paths`.
+ let result = search_paths(parent_paths, child_paths, |mut path| {
+ path.push(&exe_path);
+ if !has_extension {
+ path.set_extension(EXE_EXTENSION);
+ }
+ program_exists(&path)
+ });
+ if let Some(path) = result {
+ return Ok(path);
+ }
+ }
+ // If we get here then the executable cannot be found.
+ Err(io::const_io_error!(io::ErrorKind::NotFound, "program not found"))
+}
+
+// Calls `f` for every path that should be used to find an executable.
+// Returns once `f` returns the path to an executable or all paths have been searched.
+fn search_paths<Paths, Exists>(
+ parent_paths: Paths,
+ child_paths: Option<&OsStr>,
+ mut exists: Exists,
+) -> Option<Vec<u16>>
+where
+ Paths: FnOnce() -> Option<OsString>,
+ Exists: FnMut(PathBuf) -> Option<Vec<u16>>,
+{
+ // 1. Child paths
+ // This is for consistency with Rust's historic behaviour.
+ if let Some(paths) = child_paths {
+ for path in env::split_paths(paths).filter(|p| !p.as_os_str().is_empty()) {
+ if let Some(path) = exists(path) {
+ return Some(path);
+ }
+ }
+ }
+
+ // 2. Application path
+ if let Ok(mut app_path) = env::current_exe() {
+ app_path.pop();
+ if let Some(path) = exists(app_path) {
+ return Some(path);
+ }
+ }
+
+ // 3 & 4. System paths
+ // SAFETY: This uses `fill_utf16_buf` to safely call the OS functions.
+ unsafe {
+ if let Ok(Some(path)) = super::fill_utf16_buf(
+ |buf, size| c::GetSystemDirectoryW(buf, size),
+ |buf| exists(PathBuf::from(OsString::from_wide(buf))),
+ ) {
+ return Some(path);
+ }
+ #[cfg(not(target_vendor = "uwp"))]
+ {
+ if let Ok(Some(path)) = super::fill_utf16_buf(
+ |buf, size| c::GetWindowsDirectoryW(buf, size),
+ |buf| exists(PathBuf::from(OsString::from_wide(buf))),
+ ) {
+ return Some(path);
+ }
+ }
+ }
+
+ // 5. Parent paths
+ if let Some(parent_paths) = parent_paths() {
+ for path in env::split_paths(&parent_paths).filter(|p| !p.as_os_str().is_empty()) {
+ if let Some(path) = exists(path) {
+ return Some(path);
+ }
+ }
+ }
+ None
+}
+
+/// Check if a file exists without following symlinks.
+fn program_exists(path: &Path) -> Option<Vec<u16>> {
+ unsafe {
+ let path = path::maybe_verbatim(path).ok()?;
+ // Getting attributes using `GetFileAttributesW` does not follow symlinks
+ // and it will almost always be successful if the link exists.
+ // There are some exceptions for special system files (e.g. the pagefile)
+ // but these are not executable.
+ if c::GetFileAttributesW(path.as_ptr()) == c::INVALID_FILE_ATTRIBUTES {
+ None
+ } else {
+ Some(path)
+ }
+ }
+}
+
+impl Stdio {
+ fn to_handle(&self, stdio_id: c::DWORD, pipe: &mut Option<AnonPipe>) -> io::Result<Handle> {
+ match *self {
+ // If no stdio handle is available, then inherit means that it
+ // should still be unavailable so propagate the
+ // INVALID_HANDLE_VALUE.
+ Stdio::Inherit => match stdio::get_handle(stdio_id) {
+ Ok(io) => unsafe {
+ let io = Handle::from_raw_handle(io);
+ let ret = io.duplicate(0, true, c::DUPLICATE_SAME_ACCESS);
+ io.into_raw_handle();
+ ret
+ },
+ Err(..) => unsafe { Ok(Handle::from_raw_handle(c::INVALID_HANDLE_VALUE)) },
+ },
+
+ Stdio::MakePipe => {
+ let ours_readable = stdio_id != c::STD_INPUT_HANDLE;
+ let pipes = pipe::anon_pipe(ours_readable, true)?;
+ *pipe = Some(pipes.ours);
+ Ok(pipes.theirs.into_handle())
+ }
+
+ Stdio::Pipe(ref source) => {
+ let ours_readable = stdio_id != c::STD_INPUT_HANDLE;
+ pipe::spawn_pipe_relay(source, ours_readable, true).map(AnonPipe::into_handle)
+ }
+
+ Stdio::Handle(ref handle) => handle.duplicate(0, true, c::DUPLICATE_SAME_ACCESS),
+
+ // Open up a reference to NUL with appropriate read/write
+ // permissions as well as the ability to be inherited to child
+ // processes (as this is about to be inherited).
+ Stdio::Null => {
+ let size = mem::size_of::<c::SECURITY_ATTRIBUTES>();
+ let mut sa = c::SECURITY_ATTRIBUTES {
+ nLength: size as c::DWORD,
+ lpSecurityDescriptor: ptr::null_mut(),
+ bInheritHandle: 1,
+ };
+ let mut opts = OpenOptions::new();
+ opts.read(stdio_id == c::STD_INPUT_HANDLE);
+ opts.write(stdio_id != c::STD_INPUT_HANDLE);
+ opts.security_attributes(&mut sa);
+ File::open(Path::new("NUL"), &opts).map(|file| file.into_inner())
+ }
+ }
+ }
+}
+
+impl From<AnonPipe> for Stdio {
+ fn from(pipe: AnonPipe) -> Stdio {
+ Stdio::Pipe(pipe)
+ }
+}
+
+impl From<File> for Stdio {
+ fn from(file: File) -> Stdio {
+ Stdio::Handle(file.into_inner())
+ }
+}
+
+////////////////////////////////////////////////////////////////////////////////
+// Processes
+////////////////////////////////////////////////////////////////////////////////
+
+/// A value representing a child process.
+///
+/// The lifetime of this value is linked to the lifetime of the actual
+/// process - the Process destructor calls self.finish() which waits
+/// for the process to terminate.
+pub struct Process {
+ handle: Handle,
+ main_thread_handle: Handle,
+}
+
+impl Process {
+ pub fn kill(&mut self) -> io::Result<()> {
+ cvt(unsafe { c::TerminateProcess(self.handle.as_raw_handle(), 1) })?;
+ Ok(())
+ }
+
+ pub fn id(&self) -> u32 {
+ unsafe { c::GetProcessId(self.handle.as_raw_handle()) as u32 }
+ }
+
+ pub fn main_thread_handle(&self) -> BorrowedHandle<'_> {
+ self.main_thread_handle.as_handle()
+ }
+
+ pub fn wait(&mut self) -> io::Result<ExitStatus> {
+ unsafe {
+ let res = c::WaitForSingleObject(self.handle.as_raw_handle(), c::INFINITE);
+ if res != c::WAIT_OBJECT_0 {
+ return Err(Error::last_os_error());
+ }
+ let mut status = 0;
+ cvt(c::GetExitCodeProcess(self.handle.as_raw_handle(), &mut status))?;
+ Ok(ExitStatus(status))
+ }
+ }
+
+ pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
+ unsafe {
+ match c::WaitForSingleObject(self.handle.as_raw_handle(), 0) {
+ c::WAIT_OBJECT_0 => {}
+ c::WAIT_TIMEOUT => {
+ return Ok(None);
+ }
+ _ => return Err(io::Error::last_os_error()),
+ }
+ let mut status = 0;
+ cvt(c::GetExitCodeProcess(self.handle.as_raw_handle(), &mut status))?;
+ Ok(Some(ExitStatus(status)))
+ }
+ }
+
+ pub fn handle(&self) -> &Handle {
+ &self.handle
+ }
+
+ pub fn into_handle(self) -> Handle {
+ self.handle
+ }
+}
+
+#[derive(PartialEq, Eq, Clone, Copy, Debug)]
+pub struct ExitStatus(c::DWORD);
+
+impl ExitStatus {
+ pub fn exit_ok(&self) -> Result<(), ExitStatusError> {
+ match NonZeroDWORD::try_from(self.0) {
+ /* was nonzero */ Ok(failure) => Err(ExitStatusError(failure)),
+ /* was zero, couldn't convert */ Err(_) => Ok(()),
+ }
+ }
+ pub fn code(&self) -> Option<i32> {
+ Some(self.0 as i32)
+ }
+}
+
+/// Converts a raw `c::DWORD` to a type-safe `ExitStatus` by wrapping it without copying.
+impl From<c::DWORD> for ExitStatus {
+ fn from(u: c::DWORD) -> ExitStatus {
+ ExitStatus(u)
+ }
+}
+
+impl fmt::Display for ExitStatus {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ // Windows exit codes with the high bit set typically mean some form of
+ // unhandled exception or warning. In this scenario printing the exit
+ // code in decimal doesn't always make sense because it's a very large
+ // and somewhat gibberish number. The hex code is a bit more
+ // recognizable and easier to search for, so print that.
+ if self.0 & 0x80000000 != 0 {
+ write!(f, "exit code: {:#x}", self.0)
+ } else {
+ write!(f, "exit code: {}", self.0)
+ }
+ }
+}
+
+#[derive(PartialEq, Eq, Clone, Copy, Debug)]
+pub struct ExitStatusError(c::NonZeroDWORD);
+
+impl Into<ExitStatus> for ExitStatusError {
+ fn into(self) -> ExitStatus {
+ ExitStatus(self.0.into())
+ }
+}
+
+impl ExitStatusError {
+ pub fn code(self) -> Option<NonZeroI32> {
+ Some((u32::from(self.0) as i32).try_into().unwrap())
+ }
+}
+
+#[derive(PartialEq, Eq, Clone, Copy, Debug)]
+pub struct ExitCode(c::DWORD);
+
+impl ExitCode {
+ pub const SUCCESS: ExitCode = ExitCode(EXIT_SUCCESS as _);
+ pub const FAILURE: ExitCode = ExitCode(EXIT_FAILURE as _);
+
+ #[inline]
+ pub fn as_i32(&self) -> i32 {
+ self.0 as i32
+ }
+}
+
+impl From<u8> for ExitCode {
+ fn from(code: u8) -> Self {
+ ExitCode(c::DWORD::from(code))
+ }
+}
+
+impl From<u32> for ExitCode {
+ fn from(code: u32) -> Self {
+ ExitCode(c::DWORD::from(code))
+ }
+}
+
+fn zeroed_startupinfo() -> c::STARTUPINFO {
+ c::STARTUPINFO {
+ cb: 0,
+ lpReserved: ptr::null_mut(),
+ lpDesktop: ptr::null_mut(),
+ lpTitle: ptr::null_mut(),
+ dwX: 0,
+ dwY: 0,
+ dwXSize: 0,
+ dwYSize: 0,
+ dwXCountChars: 0,
+ dwYCountCharts: 0,
+ dwFillAttribute: 0,
+ dwFlags: 0,
+ wShowWindow: 0,
+ cbReserved2: 0,
+ lpReserved2: ptr::null_mut(),
+ hStdInput: c::INVALID_HANDLE_VALUE,
+ hStdOutput: c::INVALID_HANDLE_VALUE,
+ hStdError: c::INVALID_HANDLE_VALUE,
+ }
+}
+
+fn zeroed_process_information() -> c::PROCESS_INFORMATION {
+ c::PROCESS_INFORMATION {
+ hProcess: ptr::null_mut(),
+ hThread: ptr::null_mut(),
+ dwProcessId: 0,
+ dwThreadId: 0,
+ }
+}
+
+// Produces a wide string *without terminating null*; returns an error if
+// `prog` or any of the `args` contain a nul.
+fn make_command_line(argv0: &OsStr, args: &[Arg], force_quotes: bool) -> io::Result<Vec<u16>> {
+ // Encode the command and arguments in a command line string such
+ // that the spawned process may recover them using CommandLineToArgvW.
+ let mut cmd: Vec<u16> = Vec::new();
+
+ // Always quote the program name so CreateProcess to avoid ambiguity when
+ // the child process parses its arguments.
+ // Note that quotes aren't escaped here because they can't be used in arg0.
+ // But that's ok because file paths can't contain quotes.
+ cmd.push(b'"' as u16);
+ cmd.extend(argv0.encode_wide());
+ cmd.push(b'"' as u16);
+
+ for arg in args {
+ cmd.push(' ' as u16);
+ args::append_arg(&mut cmd, arg, force_quotes)?;
+ }
+ Ok(cmd)
+}
+
+// Get `cmd.exe` for use with bat scripts, encoded as a UTF-16 string.
+fn command_prompt() -> io::Result<Vec<u16>> {
+ let mut system: Vec<u16> = super::fill_utf16_buf(
+ |buf, size| unsafe { c::GetSystemDirectoryW(buf, size) },
+ |buf| buf.into(),
+ )?;
+ system.extend("\\cmd.exe".encode_utf16().chain([0]));
+ Ok(system)
+}
+
+fn make_envp(maybe_env: Option<BTreeMap<EnvKey, OsString>>) -> io::Result<(*mut c_void, Vec<u16>)> {
+ // On Windows we pass an "environment block" which is not a char**, but
+ // rather a concatenation of null-terminated k=v\0 sequences, with a final
+ // \0 to terminate.
+ if let Some(env) = maybe_env {
+ let mut blk = Vec::new();
+
+ // If there are no environment variables to set then signal this by
+ // pushing a null.
+ if env.is_empty() {
+ blk.push(0);
+ }
+
+ for (k, v) in env {
+ ensure_no_nuls(k.os_string)?;
+ blk.extend(k.utf16);
+ blk.push('=' as u16);
+ blk.extend(ensure_no_nuls(v)?.encode_wide());
+ blk.push(0);
+ }
+ blk.push(0);
+ Ok((blk.as_mut_ptr() as *mut c_void, blk))
+ } else {
+ Ok((ptr::null_mut(), Vec::new()))
+ }
+}
+
+fn make_dirp(d: Option<&OsString>) -> io::Result<(*const u16, Vec<u16>)> {
+ match d {
+ Some(dir) => {
+ let mut dir_str: Vec<u16> = ensure_no_nuls(dir)?.encode_wide().collect();
+ dir_str.push(0);
+ Ok((dir_str.as_ptr(), dir_str))
+ }
+ None => Ok((ptr::null(), Vec::new())),
+ }
+}
+
+pub struct CommandArgs<'a> {
+ iter: crate::slice::Iter<'a, Arg>,
+}
+
+impl<'a> Iterator for CommandArgs<'a> {
+ type Item = &'a OsStr;
+ fn next(&mut self) -> Option<&'a OsStr> {
+ self.iter.next().map(|arg| match arg {
+ Arg::Regular(s) | Arg::Raw(s) => s.as_ref(),
+ })
+ }
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ self.iter.size_hint()
+ }
+}
+
+impl<'a> ExactSizeIterator for CommandArgs<'a> {
+ fn len(&self) -> usize {
+ self.iter.len()
+ }
+ fn is_empty(&self) -> bool {
+ self.iter.is_empty()
+ }
+}
+
+impl<'a> fmt::Debug for CommandArgs<'a> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_list().entries(self.iter.clone()).finish()
+ }
+}
diff --git a/library/std/src/sys/windows/process/tests.rs b/library/std/src/sys/windows/process/tests.rs
new file mode 100644
index 000000000..3fc0c7524
--- /dev/null
+++ b/library/std/src/sys/windows/process/tests.rs
@@ -0,0 +1,222 @@
+use super::make_command_line;
+use super::Arg;
+use crate::env;
+use crate::ffi::{OsStr, OsString};
+use crate::process::Command;
+
+#[test]
+fn test_raw_args() {
+ let command_line = &make_command_line(
+ OsStr::new("quoted exe"),
+ &[
+ Arg::Regular(OsString::from("quote me")),
+ Arg::Raw(OsString::from("quote me *not*")),
+ Arg::Raw(OsString::from("\t\\")),
+ Arg::Raw(OsString::from("internal \\\"backslash-\"quote")),
+ Arg::Regular(OsString::from("optional-quotes")),
+ ],
+ false,
+ )
+ .unwrap();
+ assert_eq!(
+ String::from_utf16(command_line).unwrap(),
+ "\"quoted exe\" \"quote me\" quote me *not* \t\\ internal \\\"backslash-\"quote optional-quotes"
+ );
+}
+
+#[test]
+fn test_thread_handle() {
+ use crate::os::windows::io::BorrowedHandle;
+ use crate::os::windows::process::{ChildExt, CommandExt};
+ const CREATE_SUSPENDED: u32 = 0x00000004;
+
+ let p = Command::new("cmd").args(&["/C", "exit 0"]).creation_flags(CREATE_SUSPENDED).spawn();
+ assert!(p.is_ok());
+ let mut p = p.unwrap();
+
+ extern "system" {
+ fn ResumeThread(_: BorrowedHandle<'_>) -> u32;
+ }
+ unsafe {
+ ResumeThread(p.main_thread_handle());
+ }
+
+ crate::thread::sleep(crate::time::Duration::from_millis(100));
+
+ let res = p.try_wait();
+ assert!(res.is_ok());
+ assert!(res.unwrap().is_some());
+ assert!(p.try_wait().unwrap().unwrap().success());
+}
+
+#[test]
+fn test_make_command_line() {
+ fn test_wrapper(prog: &str, args: &[&str], force_quotes: bool) -> String {
+ let command_line = &make_command_line(
+ OsStr::new(prog),
+ &args.iter().map(|a| Arg::Regular(OsString::from(a))).collect::<Vec<_>>(),
+ force_quotes,
+ )
+ .unwrap();
+ String::from_utf16(command_line).unwrap()
+ }
+
+ assert_eq!(test_wrapper("prog", &["aaa", "bbb", "ccc"], false), "\"prog\" aaa bbb ccc");
+
+ assert_eq!(test_wrapper("prog", &[r"C:\"], false), r#""prog" C:\"#);
+ assert_eq!(test_wrapper("prog", &[r"2slashes\\"], false), r#""prog" 2slashes\\"#);
+ assert_eq!(test_wrapper("prog", &[r" C:\"], false), r#""prog" " C:\\""#);
+ assert_eq!(test_wrapper("prog", &[r" 2slashes\\"], false), r#""prog" " 2slashes\\\\""#);
+
+ assert_eq!(
+ test_wrapper("C:\\Program Files\\blah\\blah.exe", &["aaa"], false),
+ "\"C:\\Program Files\\blah\\blah.exe\" aaa"
+ );
+ assert_eq!(
+ test_wrapper("C:\\Program Files\\blah\\blah.exe", &["aaa", "v*"], false),
+ "\"C:\\Program Files\\blah\\blah.exe\" aaa v*"
+ );
+ assert_eq!(
+ test_wrapper("C:\\Program Files\\blah\\blah.exe", &["aaa", "v*"], true),
+ "\"C:\\Program Files\\blah\\blah.exe\" \"aaa\" \"v*\""
+ );
+ assert_eq!(
+ test_wrapper("C:\\Program Files\\test", &["aa\"bb"], false),
+ "\"C:\\Program Files\\test\" aa\\\"bb"
+ );
+ assert_eq!(test_wrapper("echo", &["a b c"], false), "\"echo\" \"a b c\"");
+ assert_eq!(
+ test_wrapper("echo", &["\" \\\" \\", "\\"], false),
+ "\"echo\" \"\\\" \\\\\\\" \\\\\" \\"
+ );
+ assert_eq!(
+ test_wrapper("\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}", &[], false),
+ "\"\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}\""
+ );
+}
+
+// On Windows, environment args are case preserving but comparisons are case-insensitive.
+// See: #85242
+#[test]
+fn windows_env_unicode_case() {
+ let test_cases = [
+ ("ä", "Ä"),
+ ("ß", "SS"),
+ ("Ä", "Ö"),
+ ("Ä", "Ö"),
+ ("I", "İ"),
+ ("I", "i"),
+ ("I", "ı"),
+ ("i", "I"),
+ ("i", "İ"),
+ ("i", "ı"),
+ ("İ", "I"),
+ ("İ", "i"),
+ ("İ", "ı"),
+ ("ı", "I"),
+ ("ı", "i"),
+ ("ı", "İ"),
+ ("ä", "Ä"),
+ ("ß", "SS"),
+ ("Ä", "Ö"),
+ ("Ä", "Ö"),
+ ("I", "İ"),
+ ("I", "i"),
+ ("I", "ı"),
+ ("i", "I"),
+ ("i", "İ"),
+ ("i", "ı"),
+ ("İ", "I"),
+ ("İ", "i"),
+ ("İ", "ı"),
+ ("ı", "I"),
+ ("ı", "i"),
+ ("ı", "İ"),
+ ];
+ // Test that `cmd.env` matches `env::set_var` when setting two strings that
+ // may (or may not) be case-folded when compared.
+ for (a, b) in test_cases.iter() {
+ let mut cmd = Command::new("cmd");
+ cmd.env(a, "1");
+ cmd.env(b, "2");
+ env::set_var(a, "1");
+ env::set_var(b, "2");
+
+ for (key, value) in cmd.get_envs() {
+ assert_eq!(
+ env::var(key).ok(),
+ value.map(|s| s.to_string_lossy().into_owned()),
+ "command environment mismatch: {a} {b}",
+ );
+ }
+ }
+}
+
+// UWP applications run in a restricted environment which means this test may not work.
+#[cfg(not(target_vendor = "uwp"))]
+#[test]
+fn windows_exe_resolver() {
+ use super::resolve_exe;
+ use crate::io;
+ use crate::sys::fs::symlink;
+ use crate::sys_common::io::test::tmpdir;
+
+ let env_paths = || env::var_os("PATH");
+
+ // Test a full path, with and without the `exe` extension.
+ let mut current_exe = env::current_exe().unwrap();
+ assert!(resolve_exe(current_exe.as_ref(), env_paths, None).is_ok());
+ current_exe.set_extension("");
+ assert!(resolve_exe(current_exe.as_ref(), env_paths, None).is_ok());
+
+ // Test lone file names.
+ assert!(resolve_exe(OsStr::new("cmd"), env_paths, None).is_ok());
+ assert!(resolve_exe(OsStr::new("cmd.exe"), env_paths, None).is_ok());
+ assert!(resolve_exe(OsStr::new("cmd.EXE"), env_paths, None).is_ok());
+ assert!(resolve_exe(OsStr::new("fc"), env_paths, None).is_ok());
+
+ // Invalid file names should return InvalidInput.
+ assert_eq!(
+ resolve_exe(OsStr::new(""), env_paths, None).unwrap_err().kind(),
+ io::ErrorKind::InvalidInput
+ );
+ assert_eq!(
+ resolve_exe(OsStr::new("\0"), env_paths, None).unwrap_err().kind(),
+ io::ErrorKind::InvalidInput
+ );
+ // Trailing slash, therefore there's no file name component.
+ assert_eq!(
+ resolve_exe(OsStr::new(r"C:\Path\to\"), env_paths, None).unwrap_err().kind(),
+ io::ErrorKind::InvalidInput
+ );
+
+ /*
+ Some of the following tests may need to be changed if you are deliberately
+ changing the behaviour of `resolve_exe`.
+ */
+
+ let empty_paths = || None;
+
+ // The resolver looks in system directories even when `PATH` is empty.
+ assert!(resolve_exe(OsStr::new("cmd.exe"), empty_paths, None).is_ok());
+
+ // The application's directory is also searched.
+ let current_exe = env::current_exe().unwrap();
+ assert!(resolve_exe(current_exe.file_name().unwrap().as_ref(), empty_paths, None).is_ok());
+
+ // Create a temporary path and add a broken symlink.
+ let temp = tmpdir();
+ let mut exe_path = temp.path().to_owned();
+ exe_path.push("exists.exe");
+
+ // A broken symlink should still be resolved.
+ // Skip this check if not in CI and creating symlinks isn't possible.
+ let is_ci = env::var("CI").is_ok();
+ let result = symlink("<DOES NOT EXIST>".as_ref(), &exe_path);
+ if is_ci || result.is_ok() {
+ result.unwrap();
+ assert!(
+ resolve_exe(OsStr::new("exists.exe"), empty_paths, Some(temp.path().as_ref())).is_ok()
+ );
+ }
+}
diff --git a/library/std/src/sys/windows/rand.rs b/library/std/src/sys/windows/rand.rs
new file mode 100644
index 000000000..f8fd93a73
--- /dev/null
+++ b/library/std/src/sys/windows/rand.rs
@@ -0,0 +1,35 @@
+use crate::io;
+use crate::mem;
+use crate::ptr;
+use crate::sys::c;
+
+pub fn hashmap_random_keys() -> (u64, u64) {
+ let mut v = (0, 0);
+ let ret = unsafe {
+ c::BCryptGenRandom(
+ ptr::null_mut(),
+ &mut v as *mut _ as *mut u8,
+ mem::size_of_val(&v) as c::ULONG,
+ c::BCRYPT_USE_SYSTEM_PREFERRED_RNG,
+ )
+ };
+ if ret != 0 { fallback_rng() } else { v }
+}
+
+/// Generate random numbers using the fallback RNG function (RtlGenRandom)
+#[cfg(not(target_vendor = "uwp"))]
+#[inline(never)]
+fn fallback_rng() -> (u64, u64) {
+ let mut v = (0, 0);
+ let ret =
+ unsafe { c::RtlGenRandom(&mut v as *mut _ as *mut u8, mem::size_of_val(&v) as c::ULONG) };
+
+ if ret != 0 { v } else { panic!("fallback RNG broken: {}", io::Error::last_os_error()) }
+}
+
+/// We can't use RtlGenRandom with UWP, so there is no fallback
+#[cfg(target_vendor = "uwp")]
+#[inline(never)]
+fn fallback_rng() -> (u64, u64) {
+ panic!("fallback RNG broken: RtlGenRandom() not supported on UWP");
+}
diff --git a/library/std/src/sys/windows/stack_overflow.rs b/library/std/src/sys/windows/stack_overflow.rs
new file mode 100644
index 000000000..18a2a36ad
--- /dev/null
+++ b/library/std/src/sys/windows/stack_overflow.rs
@@ -0,0 +1,42 @@
+#![cfg_attr(test, allow(dead_code))]
+
+use crate::sys::c;
+use crate::thread;
+
+pub struct Handler;
+
+impl Handler {
+ pub unsafe fn new() -> Handler {
+ // This API isn't available on XP, so don't panic in that case and just
+ // pray it works out ok.
+ if c::SetThreadStackGuarantee(&mut 0x5000) == 0
+ && c::GetLastError() as u32 != c::ERROR_CALL_NOT_IMPLEMENTED as u32
+ {
+ panic!("failed to reserve stack space for exception handling");
+ }
+ Handler
+ }
+}
+
+extern "system" fn vectored_handler(ExceptionInfo: *mut c::EXCEPTION_POINTERS) -> c::LONG {
+ unsafe {
+ let rec = &(*(*ExceptionInfo).ExceptionRecord);
+ let code = rec.ExceptionCode;
+
+ if code == c::EXCEPTION_STACK_OVERFLOW {
+ rtprintpanic!(
+ "\nthread '{}' has overflowed its stack\n",
+ thread::current().name().unwrap_or("<unknown>")
+ );
+ }
+ c::EXCEPTION_CONTINUE_SEARCH
+ }
+}
+
+pub unsafe fn init() {
+ if c::AddVectoredExceptionHandler(0, vectored_handler).is_null() {
+ panic!("failed to install exception handler");
+ }
+ // Set the thread stack guarantee for the main thread.
+ let _h = Handler::new();
+}
diff --git a/library/std/src/sys/windows/stack_overflow_uwp.rs b/library/std/src/sys/windows/stack_overflow_uwp.rs
new file mode 100644
index 000000000..afdf7f566
--- /dev/null
+++ b/library/std/src/sys/windows/stack_overflow_uwp.rs
@@ -0,0 +1,11 @@
+#![cfg_attr(test, allow(dead_code))]
+
+pub struct Handler;
+
+impl Handler {
+ pub fn new() -> Handler {
+ Handler
+ }
+}
+
+pub unsafe fn init() {}
diff --git a/library/std/src/sys/windows/stdio.rs b/library/std/src/sys/windows/stdio.rs
new file mode 100644
index 000000000..a001d6b98
--- /dev/null
+++ b/library/std/src/sys/windows/stdio.rs
@@ -0,0 +1,422 @@
+#![unstable(issue = "none", feature = "windows_stdio")]
+
+use crate::char::decode_utf16;
+use crate::cmp;
+use crate::io;
+use crate::os::windows::io::{FromRawHandle, IntoRawHandle};
+use crate::ptr;
+use crate::str;
+use crate::sys::c;
+use crate::sys::cvt;
+use crate::sys::handle::Handle;
+use core::str::utf8_char_width;
+
+// Don't cache handles but get them fresh for every read/write. This allows us to track changes to
+// the value over time (such as if a process calls `SetStdHandle` while it's running). See #40490.
+pub struct Stdin {
+ surrogate: u16,
+ incomplete_utf8: IncompleteUtf8,
+}
+
+pub struct Stdout {
+ incomplete_utf8: IncompleteUtf8,
+}
+
+pub struct Stderr {
+ incomplete_utf8: IncompleteUtf8,
+}
+
+struct IncompleteUtf8 {
+ bytes: [u8; 4],
+ len: u8,
+}
+
+impl IncompleteUtf8 {
+ // Implemented for use in Stdin::read.
+ fn read(&mut self, buf: &mut [u8]) -> usize {
+ // Write to buffer until the buffer is full or we run out of bytes.
+ let to_write = cmp::min(buf.len(), self.len as usize);
+ buf[..to_write].copy_from_slice(&self.bytes[..to_write]);
+
+ // Rotate the remaining bytes if not enough remaining space in buffer.
+ if usize::from(self.len) > buf.len() {
+ self.bytes.copy_within(to_write.., 0);
+ self.len -= to_write as u8;
+ } else {
+ self.len = 0;
+ }
+
+ to_write
+ }
+}
+
+// Apparently Windows doesn't handle large reads on stdin or writes to stdout/stderr well (see
+// #13304 for details).
+//
+// From MSDN (2011): "The storage for this buffer is allocated from a shared heap for the
+// process that is 64 KB in size. The maximum size of the buffer will depend on heap usage."
+//
+// We choose the cap at 8 KiB because libuv does the same, and it seems to be acceptable so far.
+const MAX_BUFFER_SIZE: usize = 8192;
+
+// The standard buffer size of BufReader for Stdin should be able to hold 3x more bytes than there
+// are `u16`'s in MAX_BUFFER_SIZE. This ensures the read data can always be completely decoded from
+// UTF-16 to UTF-8.
+pub const STDIN_BUF_SIZE: usize = MAX_BUFFER_SIZE / 2 * 3;
+
+pub fn get_handle(handle_id: c::DWORD) -> io::Result<c::HANDLE> {
+ let handle = unsafe { c::GetStdHandle(handle_id) };
+ if handle == c::INVALID_HANDLE_VALUE {
+ Err(io::Error::last_os_error())
+ } else if handle.is_null() {
+ Err(io::Error::from_raw_os_error(c::ERROR_INVALID_HANDLE as i32))
+ } else {
+ Ok(handle)
+ }
+}
+
+fn is_console(handle: c::HANDLE) -> bool {
+ // `GetConsoleMode` will return false (0) if this is a pipe (we don't care about the reported
+ // mode). This will only detect Windows Console, not other terminals connected to a pipe like
+ // MSYS. Which is exactly what we need, as only Windows Console needs a conversion to UTF-16.
+ let mut mode = 0;
+ unsafe { c::GetConsoleMode(handle, &mut mode) != 0 }
+}
+
+fn write(
+ handle_id: c::DWORD,
+ data: &[u8],
+ incomplete_utf8: &mut IncompleteUtf8,
+) -> io::Result<usize> {
+ if data.is_empty() {
+ return Ok(0);
+ }
+
+ let handle = get_handle(handle_id)?;
+ if !is_console(handle) {
+ unsafe {
+ let handle = Handle::from_raw_handle(handle);
+ let ret = handle.write(data);
+ handle.into_raw_handle(); // Don't close the handle
+ return ret;
+ }
+ }
+
+ if incomplete_utf8.len > 0 {
+ assert!(
+ incomplete_utf8.len < 4,
+ "Unexpected number of bytes for incomplete UTF-8 codepoint."
+ );
+ if data[0] >> 6 != 0b10 {
+ // not a continuation byte - reject
+ incomplete_utf8.len = 0;
+ return Err(io::const_io_error!(
+ io::ErrorKind::InvalidData,
+ "Windows stdio in console mode does not support writing non-UTF-8 byte sequences",
+ ));
+ }
+ incomplete_utf8.bytes[incomplete_utf8.len as usize] = data[0];
+ incomplete_utf8.len += 1;
+ let char_width = utf8_char_width(incomplete_utf8.bytes[0]);
+ if (incomplete_utf8.len as usize) < char_width {
+ // more bytes needed
+ return Ok(1);
+ }
+ let s = str::from_utf8(&incomplete_utf8.bytes[0..incomplete_utf8.len as usize]);
+ incomplete_utf8.len = 0;
+ match s {
+ Ok(s) => {
+ assert_eq!(char_width, s.len());
+ let written = write_valid_utf8_to_console(handle, s)?;
+ assert_eq!(written, s.len()); // guaranteed by write_valid_utf8_to_console() for single codepoint writes
+ return Ok(1);
+ }
+ Err(_) => {
+ return Err(io::const_io_error!(
+ io::ErrorKind::InvalidData,
+ "Windows stdio in console mode does not support writing non-UTF-8 byte sequences",
+ ));
+ }
+ }
+ }
+
+ // As the console is meant for presenting text, we assume bytes of `data` are encoded as UTF-8,
+ // which needs to be encoded as UTF-16.
+ //
+ // If the data is not valid UTF-8 we write out as many bytes as are valid.
+ // If the first byte is invalid it is either first byte of a multi-byte sequence but the
+ // provided byte slice is too short or it is the first byte of an invalid multi-byte sequence.
+ let len = cmp::min(data.len(), MAX_BUFFER_SIZE / 2);
+ let utf8 = match str::from_utf8(&data[..len]) {
+ Ok(s) => s,
+ Err(ref e) if e.valid_up_to() == 0 => {
+ let first_byte_char_width = utf8_char_width(data[0]);
+ if first_byte_char_width > 1 && data.len() < first_byte_char_width {
+ incomplete_utf8.bytes[0] = data[0];
+ incomplete_utf8.len = 1;
+ return Ok(1);
+ } else {
+ return Err(io::const_io_error!(
+ io::ErrorKind::InvalidData,
+ "Windows stdio in console mode does not support writing non-UTF-8 byte sequences",
+ ));
+ }
+ }
+ Err(e) => str::from_utf8(&data[..e.valid_up_to()]).unwrap(),
+ };
+
+ write_valid_utf8_to_console(handle, utf8)
+}
+
+fn write_valid_utf8_to_console(handle: c::HANDLE, utf8: &str) -> io::Result<usize> {
+ let mut utf16 = [0u16; MAX_BUFFER_SIZE / 2];
+ let mut len_utf16 = 0;
+ for (chr, dest) in utf8.encode_utf16().zip(utf16.iter_mut()) {
+ *dest = chr;
+ len_utf16 += 1;
+ }
+ let utf16 = &utf16[..len_utf16];
+
+ let mut written = write_u16s(handle, &utf16)?;
+
+ // Figure out how many bytes of as UTF-8 were written away as UTF-16.
+ if written == utf16.len() {
+ Ok(utf8.len())
+ } else {
+ // Make sure we didn't end up writing only half of a surrogate pair (even though the chance
+ // is tiny). Because it is not possible for user code to re-slice `data` in such a way that
+ // a missing surrogate can be produced (and also because of the UTF-8 validation above),
+ // write the missing surrogate out now.
+ // Buffering it would mean we have to lie about the number of bytes written.
+ let first_char_remaining = utf16[written];
+ if first_char_remaining >= 0xDCEE && first_char_remaining <= 0xDFFF {
+ // low surrogate
+ // We just hope this works, and give up otherwise
+ let _ = write_u16s(handle, &utf16[written..written + 1]);
+ written += 1;
+ }
+ // Calculate the number of bytes of `utf8` that were actually written.
+ let mut count = 0;
+ for ch in utf16[..written].iter() {
+ count += match ch {
+ 0x0000..=0x007F => 1,
+ 0x0080..=0x07FF => 2,
+ 0xDCEE..=0xDFFF => 1, // Low surrogate. We already counted 3 bytes for the other.
+ _ => 3,
+ };
+ }
+ debug_assert!(String::from_utf16(&utf16[..written]).unwrap() == utf8[..count]);
+ Ok(count)
+ }
+}
+
+fn write_u16s(handle: c::HANDLE, data: &[u16]) -> io::Result<usize> {
+ let mut written = 0;
+ cvt(unsafe {
+ c::WriteConsoleW(
+ handle,
+ data.as_ptr() as c::LPCVOID,
+ data.len() as u32,
+ &mut written,
+ ptr::null_mut(),
+ )
+ })?;
+ Ok(written as usize)
+}
+
+impl Stdin {
+ pub const fn new() -> Stdin {
+ Stdin { surrogate: 0, incomplete_utf8: IncompleteUtf8::new() }
+ }
+}
+
+impl io::Read for Stdin {
+ fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
+ let handle = get_handle(c::STD_INPUT_HANDLE)?;
+ if !is_console(handle) {
+ unsafe {
+ let handle = Handle::from_raw_handle(handle);
+ let ret = handle.read(buf);
+ handle.into_raw_handle(); // Don't close the handle
+ return ret;
+ }
+ }
+
+ // If there are bytes in the incomplete utf-8, start with those.
+ // (No-op if there is nothing in the buffer.)
+ let mut bytes_copied = self.incomplete_utf8.read(buf);
+
+ if bytes_copied == buf.len() {
+ return Ok(bytes_copied);
+ } else if buf.len() - bytes_copied < 4 {
+ // Not enough space to get a UTF-8 byte. We will use the incomplete UTF8.
+ let mut utf16_buf = [0u16; 1];
+ // Read one u16 character.
+ let read = read_u16s_fixup_surrogates(handle, &mut utf16_buf, 1, &mut self.surrogate)?;
+ // Read bytes, using the (now-empty) self.incomplete_utf8 as extra space.
+ let read_bytes = utf16_to_utf8(&utf16_buf[..read], &mut self.incomplete_utf8.bytes)?;
+
+ // Read in the bytes from incomplete_utf8 until the buffer is full.
+ self.incomplete_utf8.len = read_bytes as u8;
+ // No-op if no bytes.
+ bytes_copied += self.incomplete_utf8.read(&mut buf[bytes_copied..]);
+ Ok(bytes_copied)
+ } else {
+ let mut utf16_buf = [0u16; MAX_BUFFER_SIZE / 2];
+ // In the worst case, a UTF-8 string can take 3 bytes for every `u16` of a UTF-16. So
+ // we can read at most a third of `buf.len()` chars and uphold the guarantee no data gets
+ // lost.
+ let amount = cmp::min(buf.len() / 3, utf16_buf.len());
+ let read =
+ read_u16s_fixup_surrogates(handle, &mut utf16_buf, amount, &mut self.surrogate)?;
+
+ match utf16_to_utf8(&utf16_buf[..read], buf) {
+ Ok(value) => return Ok(bytes_copied + value),
+ Err(e) => return Err(e),
+ }
+ }
+ }
+}
+
+// We assume that if the last `u16` is an unpaired surrogate they got sliced apart by our
+// buffer size, and keep it around for the next read hoping to put them together.
+// This is a best effort, and might not work if we are not the only reader on Stdin.
+fn read_u16s_fixup_surrogates(
+ handle: c::HANDLE,
+ buf: &mut [u16],
+ mut amount: usize,
+ surrogate: &mut u16,
+) -> io::Result<usize> {
+ // Insert possibly remaining unpaired surrogate from last read.
+ let mut start = 0;
+ if *surrogate != 0 {
+ buf[0] = *surrogate;
+ *surrogate = 0;
+ start = 1;
+ if amount == 1 {
+ // Special case: `Stdin::read` guarantees we can always read at least one new `u16`
+ // and combine it with an unpaired surrogate, because the UTF-8 buffer is at least
+ // 4 bytes.
+ amount = 2;
+ }
+ }
+ let mut amount = read_u16s(handle, &mut buf[start..amount])? + start;
+
+ if amount > 0 {
+ let last_char = buf[amount - 1];
+ if last_char >= 0xD800 && last_char <= 0xDBFF {
+ // high surrogate
+ *surrogate = last_char;
+ amount -= 1;
+ }
+ }
+ Ok(amount)
+}
+
+fn read_u16s(handle: c::HANDLE, buf: &mut [u16]) -> io::Result<usize> {
+ // Configure the `pInputControl` parameter to not only return on `\r\n` but also Ctrl-Z, the
+ // traditional DOS method to indicate end of character stream / user input (SUB).
+ // See #38274 and https://stackoverflow.com/questions/43836040/win-api-readconsole.
+ const CTRL_Z: u16 = 0x1A;
+ const CTRL_Z_MASK: c::ULONG = 1 << CTRL_Z;
+ let mut input_control = c::CONSOLE_READCONSOLE_CONTROL {
+ nLength: crate::mem::size_of::<c::CONSOLE_READCONSOLE_CONTROL>() as c::ULONG,
+ nInitialChars: 0,
+ dwCtrlWakeupMask: CTRL_Z_MASK,
+ dwControlKeyState: 0,
+ };
+
+ let mut amount = 0;
+ loop {
+ cvt(unsafe {
+ c::SetLastError(0);
+ c::ReadConsoleW(
+ handle,
+ buf.as_mut_ptr() as c::LPVOID,
+ buf.len() as u32,
+ &mut amount,
+ &mut input_control as c::PCONSOLE_READCONSOLE_CONTROL,
+ )
+ })?;
+
+ // ReadConsoleW returns success with ERROR_OPERATION_ABORTED for Ctrl-C or Ctrl-Break.
+ // Explicitly check for that case here and try again.
+ if amount == 0 && unsafe { c::GetLastError() } == c::ERROR_OPERATION_ABORTED {
+ continue;
+ }
+ break;
+ }
+
+ if amount > 0 && buf[amount as usize - 1] == CTRL_Z {
+ amount -= 1;
+ }
+ Ok(amount as usize)
+}
+
+#[allow(unused)]
+fn utf16_to_utf8(utf16: &[u16], utf8: &mut [u8]) -> io::Result<usize> {
+ let mut written = 0;
+ for chr in decode_utf16(utf16.iter().cloned()) {
+ match chr {
+ Ok(chr) => {
+ chr.encode_utf8(&mut utf8[written..]);
+ written += chr.len_utf8();
+ }
+ Err(_) => {
+ // We can't really do any better than forget all data and return an error.
+ return Err(io::const_io_error!(
+ io::ErrorKind::InvalidData,
+ "Windows stdin in console mode does not support non-UTF-16 input; \
+ encountered unpaired surrogate",
+ ));
+ }
+ }
+ }
+ Ok(written)
+}
+
+impl IncompleteUtf8 {
+ pub const fn new() -> IncompleteUtf8 {
+ IncompleteUtf8 { bytes: [0; 4], len: 0 }
+ }
+}
+
+impl Stdout {
+ pub const fn new() -> Stdout {
+ Stdout { incomplete_utf8: IncompleteUtf8::new() }
+ }
+}
+
+impl io::Write for Stdout {
+ fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+ write(c::STD_OUTPUT_HANDLE, buf, &mut self.incomplete_utf8)
+ }
+
+ fn flush(&mut self) -> io::Result<()> {
+ Ok(())
+ }
+}
+
+impl Stderr {
+ pub const fn new() -> Stderr {
+ Stderr { incomplete_utf8: IncompleteUtf8::new() }
+ }
+}
+
+impl io::Write for Stderr {
+ fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+ write(c::STD_ERROR_HANDLE, buf, &mut self.incomplete_utf8)
+ }
+
+ fn flush(&mut self) -> io::Result<()> {
+ Ok(())
+ }
+}
+
+pub fn is_ebadf(err: &io::Error) -> bool {
+ err.raw_os_error() == Some(c::ERROR_INVALID_HANDLE as i32)
+}
+
+pub fn panic_output() -> Option<impl io::Write> {
+ Some(Stderr::new())
+}
diff --git a/library/std/src/sys/windows/stdio_uwp.rs b/library/std/src/sys/windows/stdio_uwp.rs
new file mode 100644
index 000000000..32550f796
--- /dev/null
+++ b/library/std/src/sys/windows/stdio_uwp.rs
@@ -0,0 +1,87 @@
+#![unstable(issue = "none", feature = "windows_stdio")]
+
+use crate::io;
+use crate::mem::ManuallyDrop;
+use crate::os::windows::io::FromRawHandle;
+use crate::sys::c;
+use crate::sys::handle::Handle;
+
+pub struct Stdin {}
+pub struct Stdout;
+pub struct Stderr;
+
+const MAX_BUFFER_SIZE: usize = 8192;
+pub const STDIN_BUF_SIZE: usize = MAX_BUFFER_SIZE / 2 * 3;
+
+pub fn get_handle(handle_id: c::DWORD) -> io::Result<c::HANDLE> {
+ let handle = unsafe { c::GetStdHandle(handle_id) };
+ if handle == c::INVALID_HANDLE_VALUE {
+ Err(io::Error::last_os_error())
+ } else if handle.is_null() {
+ Err(io::Error::from_raw_os_error(c::ERROR_INVALID_HANDLE as i32))
+ } else {
+ Ok(handle)
+ }
+}
+
+fn write(handle_id: c::DWORD, data: &[u8]) -> io::Result<usize> {
+ let handle = get_handle(handle_id)?;
+ // SAFETY: The handle returned from `get_handle` must be valid and non-null.
+ let handle = unsafe { Handle::from_raw_handle(handle) };
+ ManuallyDrop::new(handle).write(data)
+}
+
+impl Stdin {
+ pub const fn new() -> Stdin {
+ Stdin {}
+ }
+}
+
+impl io::Read for Stdin {
+ fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
+ let handle = get_handle(c::STD_INPUT_HANDLE)?;
+ // SAFETY: The handle returned from `get_handle` must be valid and non-null.
+ let handle = unsafe { Handle::from_raw_handle(handle) };
+ ManuallyDrop::new(handle).read(buf)
+ }
+}
+
+impl Stdout {
+ pub const fn new() -> Stdout {
+ Stdout
+ }
+}
+
+impl io::Write for Stdout {
+ fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+ write(c::STD_OUTPUT_HANDLE, buf)
+ }
+
+ fn flush(&mut self) -> io::Result<()> {
+ Ok(())
+ }
+}
+
+impl Stderr {
+ pub const fn new() -> Stderr {
+ Stderr
+ }
+}
+
+impl io::Write for Stderr {
+ fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+ write(c::STD_ERROR_HANDLE, buf)
+ }
+
+ fn flush(&mut self) -> io::Result<()> {
+ Ok(())
+ }
+}
+
+pub fn is_ebadf(err: &io::Error) -> bool {
+ err.raw_os_error() == Some(c::ERROR_INVALID_HANDLE as i32)
+}
+
+pub fn panic_output() -> Option<impl io::Write> {
+ Some(Stderr::new())
+}
diff --git a/library/std/src/sys/windows/thread.rs b/library/std/src/sys/windows/thread.rs
new file mode 100644
index 000000000..c5c9e97e6
--- /dev/null
+++ b/library/std/src/sys/windows/thread.rs
@@ -0,0 +1,125 @@
+use crate::ffi::CStr;
+use crate::io;
+use crate::num::NonZeroUsize;
+use crate::os::windows::io::AsRawHandle;
+use crate::ptr;
+use crate::sys::c;
+use crate::sys::handle::Handle;
+use crate::sys::stack_overflow;
+use crate::sys_common::FromInner;
+use crate::time::Duration;
+
+use libc::c_void;
+
+use super::to_u16s;
+
+pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024;
+
+pub struct Thread {
+ handle: Handle,
+}
+
+impl Thread {
+ // unsafe: see thread::Builder::spawn_unchecked for safety requirements
+ pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
+ let p = Box::into_raw(box p);
+
+ // FIXME On UNIX, we guard against stack sizes that are too small but
+ // that's because pthreads enforces that stacks are at least
+ // PTHREAD_STACK_MIN bytes big. Windows has no such lower limit, it's
+ // just that below a certain threshold you can't do anything useful.
+ // That threshold is application and architecture-specific, however.
+ let ret = c::CreateThread(
+ ptr::null_mut(),
+ stack,
+ thread_start,
+ p as *mut _,
+ c::STACK_SIZE_PARAM_IS_A_RESERVATION,
+ ptr::null_mut(),
+ );
+
+ return if let Ok(handle) = ret.try_into() {
+ Ok(Thread { handle: Handle::from_inner(handle) })
+ } else {
+ // The thread failed to start and as a result p was not consumed. Therefore, it is
+ // safe to reconstruct the box so that it gets deallocated.
+ drop(Box::from_raw(p));
+ Err(io::Error::last_os_error())
+ };
+
+ extern "system" fn thread_start(main: *mut c_void) -> c::DWORD {
+ unsafe {
+ // Next, set up our stack overflow handler which may get triggered if we run
+ // out of stack.
+ let _handler = stack_overflow::Handler::new();
+ // Finally, let's run some code.
+ Box::from_raw(main as *mut Box<dyn FnOnce()>)();
+ }
+ 0
+ }
+ }
+
+ pub fn set_name(name: &CStr) {
+ if let Ok(utf8) = name.to_str() {
+ if let Ok(utf16) = to_u16s(utf8) {
+ unsafe {
+ c::SetThreadDescription(c::GetCurrentThread(), utf16.as_ptr());
+ };
+ };
+ };
+ }
+
+ pub fn join(self) {
+ let rc = unsafe { c::WaitForSingleObject(self.handle.as_raw_handle(), c::INFINITE) };
+ if rc == c::WAIT_FAILED {
+ panic!("failed to join on thread: {}", io::Error::last_os_error());
+ }
+ }
+
+ pub fn yield_now() {
+ // This function will return 0 if there are no other threads to execute,
+ // but this also means that the yield was useless so this isn't really a
+ // case that needs to be worried about.
+ unsafe {
+ c::SwitchToThread();
+ }
+ }
+
+ pub fn sleep(dur: Duration) {
+ unsafe { c::Sleep(super::dur2timeout(dur)) }
+ }
+
+ pub fn handle(&self) -> &Handle {
+ &self.handle
+ }
+
+ pub fn into_handle(self) -> Handle {
+ self.handle
+ }
+}
+
+pub fn available_parallelism() -> io::Result<NonZeroUsize> {
+ let res = unsafe {
+ let mut sysinfo: c::SYSTEM_INFO = crate::mem::zeroed();
+ c::GetSystemInfo(&mut sysinfo);
+ sysinfo.dwNumberOfProcessors as usize
+ };
+ match res {
+ 0 => Err(io::const_io_error!(
+ io::ErrorKind::NotFound,
+ "The number of hardware threads is not known for the target platform",
+ )),
+ cpus => Ok(unsafe { NonZeroUsize::new_unchecked(cpus) }),
+ }
+}
+
+#[cfg_attr(test, allow(dead_code))]
+pub mod guard {
+ pub type Guard = !;
+ pub unsafe fn current() -> Option<Guard> {
+ None
+ }
+ pub unsafe fn init() -> Option<Guard> {
+ None
+ }
+}
diff --git a/library/std/src/sys/windows/thread_local_dtor.rs b/library/std/src/sys/windows/thread_local_dtor.rs
new file mode 100644
index 000000000..25d1c6e8e
--- /dev/null
+++ b/library/std/src/sys/windows/thread_local_dtor.rs
@@ -0,0 +1,28 @@
+//! Implements thread-local destructors that are not associated with any
+//! particular data.
+
+#![unstable(feature = "thread_local_internals", issue = "none")]
+#![cfg(target_thread_local)]
+
+// Using a per-thread list avoids the problems in synchronizing global state.
+#[thread_local]
+static mut DESTRUCTORS: Vec<(*mut u8, unsafe extern "C" fn(*mut u8))> = Vec::new();
+
+pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern "C" fn(*mut u8)) {
+ DESTRUCTORS.push((t, dtor));
+}
+
+/// Runs destructors. This should not be called until thread exit.
+pub unsafe fn run_keyless_dtors() {
+ // Drop all the destructors.
+ //
+ // Note: While this is potentially an infinite loop, it *should* be
+ // the case that this loop always terminates because we provide the
+ // guarantee that a TLS key cannot be set after it is flagged for
+ // destruction.
+ while let Some((ptr, dtor)) = DESTRUCTORS.pop() {
+ (dtor)(ptr);
+ }
+ // We're done so free the memory.
+ DESTRUCTORS = Vec::new();
+}
diff --git a/library/std/src/sys/windows/thread_local_key.rs b/library/std/src/sys/windows/thread_local_key.rs
new file mode 100644
index 000000000..ec670238e
--- /dev/null
+++ b/library/std/src/sys/windows/thread_local_key.rs
@@ -0,0 +1,238 @@
+use crate::mem::ManuallyDrop;
+use crate::ptr;
+use crate::sync::atomic::AtomicPtr;
+use crate::sync::atomic::Ordering::SeqCst;
+use crate::sys::c;
+
+pub type Key = c::DWORD;
+pub type Dtor = unsafe extern "C" fn(*mut u8);
+
+// Turns out, like pretty much everything, Windows is pretty close the
+// functionality that Unix provides, but slightly different! In the case of
+// TLS, Windows does not provide an API to provide a destructor for a TLS
+// variable. This ends up being pretty crucial to this implementation, so we
+// need a way around this.
+//
+// The solution here ended up being a little obscure, but fear not, the
+// internet has informed me [1][2] that this solution is not unique (no way
+// I could have thought of it as well!). The key idea is to insert some hook
+// somewhere to run arbitrary code on thread termination. With this in place
+// we'll be able to run anything we like, including all TLS destructors!
+//
+// To accomplish this feat, we perform a number of threads, all contained
+// within this module:
+//
+// * All TLS destructors are tracked by *us*, not the windows runtime. This
+// means that we have a global list of destructors for each TLS key that
+// we know about.
+// * When a thread exits, we run over the entire list and run dtors for all
+// non-null keys. This attempts to match Unix semantics in this regard.
+//
+// This ends up having the overhead of using a global list, having some
+// locks here and there, and in general just adding some more code bloat. We
+// attempt to optimize runtime by forgetting keys that don't have
+// destructors, but this only gets us so far.
+//
+// For more details and nitty-gritty, see the code sections below!
+//
+// [1]: https://www.codeproject.com/Articles/8113/Thread-Local-Storage-The-C-Way
+// [2]: https://github.com/ChromiumWebApps/chromium/blob/master/base
+// /threading/thread_local_storage_win.cc#L42
+
+// -------------------------------------------------------------------------
+// Native bindings
+//
+// This section is just raw bindings to the native functions that Windows
+// provides, There's a few extra calls to deal with destructors.
+
+#[inline]
+pub unsafe fn create(dtor: Option<Dtor>) -> Key {
+ let key = c::TlsAlloc();
+ assert!(key != c::TLS_OUT_OF_INDEXES);
+ if let Some(f) = dtor {
+ register_dtor(key, f);
+ }
+ key
+}
+
+#[inline]
+pub unsafe fn set(key: Key, value: *mut u8) {
+ let r = c::TlsSetValue(key, value as c::LPVOID);
+ debug_assert!(r != 0);
+}
+
+#[inline]
+pub unsafe fn get(key: Key) -> *mut u8 {
+ c::TlsGetValue(key) as *mut u8
+}
+
+#[inline]
+pub unsafe fn destroy(_key: Key) {
+ rtabort!("can't destroy tls keys on windows")
+}
+
+#[inline]
+pub fn requires_synchronized_create() -> bool {
+ true
+}
+
+// -------------------------------------------------------------------------
+// Dtor registration
+//
+// Windows has no native support for running destructors so we manage our own
+// list of destructors to keep track of how to destroy keys. We then install a
+// callback later to get invoked whenever a thread exits, running all
+// appropriate destructors.
+//
+// Currently unregistration from this list is not supported. A destructor can be
+// registered but cannot be unregistered. There's various simplifying reasons
+// for doing this, the big ones being:
+//
+// 1. Currently we don't even support deallocating TLS keys, so normal operation
+// doesn't need to deallocate a destructor.
+// 2. There is no point in time where we know we can unregister a destructor
+// because it could always be getting run by some remote thread.
+//
+// Typically processes have a statically known set of TLS keys which is pretty
+// small, and we'd want to keep this memory alive for the whole process anyway
+// really.
+//
+// Perhaps one day we can fold the `Box` here into a static allocation,
+// expanding the `StaticKey` structure to contain not only a slot for the TLS
+// key but also a slot for the destructor queue on windows. An optimization for
+// another day!
+
+static DTORS: AtomicPtr<Node> = AtomicPtr::new(ptr::null_mut());
+
+struct Node {
+ dtor: Dtor,
+ key: Key,
+ next: *mut Node,
+}
+
+unsafe fn register_dtor(key: Key, dtor: Dtor) {
+ let mut node = ManuallyDrop::new(Box::new(Node { key, dtor, next: ptr::null_mut() }));
+
+ let mut head = DTORS.load(SeqCst);
+ loop {
+ node.next = head;
+ match DTORS.compare_exchange(head, &mut **node, SeqCst, SeqCst) {
+ Ok(_) => return, // nothing to drop, we successfully added the node to the list
+ Err(cur) => head = cur,
+ }
+ }
+}
+
+// -------------------------------------------------------------------------
+// Where the Magic (TM) Happens
+//
+// If you're looking at this code, and wondering "what is this doing?",
+// you're not alone! I'll try to break this down step by step:
+//
+// # What's up with CRT$XLB?
+//
+// For anything about TLS destructors to work on Windows, we have to be able
+// to run *something* when a thread exits. To do so, we place a very special
+// static in a very special location. If this is encoded in just the right
+// way, the kernel's loader is apparently nice enough to run some function
+// of ours whenever a thread exits! How nice of the kernel!
+//
+// Lots of detailed information can be found in source [1] above, but the
+// gist of it is that this is leveraging a feature of Microsoft's PE format
+// (executable format) which is not actually used by any compilers today.
+// This apparently translates to any callbacks in the ".CRT$XLB" section
+// being run on certain events.
+//
+// So after all that, we use the compiler's #[link_section] feature to place
+// a callback pointer into the magic section so it ends up being called.
+//
+// # What's up with this callback?
+//
+// The callback specified receives a number of parameters from... someone!
+// (the kernel? the runtime? I'm not quite sure!) There are a few events that
+// this gets invoked for, but we're currently only interested on when a
+// thread or a process "detaches" (exits). The process part happens for the
+// last thread and the thread part happens for any normal thread.
+//
+// # Ok, what's up with running all these destructors?
+//
+// This will likely need to be improved over time, but this function
+// attempts a "poor man's" destructor callback system. Once we've got a list
+// of what to run, we iterate over all keys, check their values, and then run
+// destructors if the values turn out to be non null (setting them to null just
+// beforehand). We do this a few times in a loop to basically match Unix
+// semantics. If we don't reach a fixed point after a short while then we just
+// inevitably leak something most likely.
+//
+// # The article mentions weird stuff about "/INCLUDE"?
+//
+// It sure does! Specifically we're talking about this quote:
+//
+// The Microsoft run-time library facilitates this process by defining a
+// memory image of the TLS Directory and giving it the special name
+// “__tls_used” (Intel x86 platforms) or “_tls_used” (other platforms). The
+// linker looks for this memory image and uses the data there to create the
+// TLS Directory. Other compilers that support TLS and work with the
+// Microsoft linker must use this same technique.
+//
+// Basically what this means is that if we want support for our TLS
+// destructors/our hook being called then we need to make sure the linker does
+// not omit this symbol. Otherwise it will omit it and our callback won't be
+// wired up.
+//
+// We don't actually use the `/INCLUDE` linker flag here like the article
+// mentions because the Rust compiler doesn't propagate linker flags, but
+// instead we use a shim function which performs a volatile 1-byte load from
+// the address of the symbol to ensure it sticks around.
+
+#[link_section = ".CRT$XLB"]
+#[allow(dead_code, unused_variables)]
+#[used] // we don't want LLVM eliminating this symbol for any reason, and
+// when the symbol makes it to the linker the linker will take over
+pub static p_thread_callback: unsafe extern "system" fn(c::LPVOID, c::DWORD, c::LPVOID) =
+ on_tls_callback;
+
+#[allow(dead_code, unused_variables)]
+unsafe extern "system" fn on_tls_callback(h: c::LPVOID, dwReason: c::DWORD, pv: c::LPVOID) {
+ if dwReason == c::DLL_THREAD_DETACH || dwReason == c::DLL_PROCESS_DETACH {
+ run_dtors();
+ #[cfg(target_thread_local)]
+ super::thread_local_dtor::run_keyless_dtors();
+ }
+
+ // See comments above for what this is doing. Note that we don't need this
+ // trickery on GNU windows, just on MSVC.
+ reference_tls_used();
+ #[cfg(target_env = "msvc")]
+ unsafe fn reference_tls_used() {
+ extern "C" {
+ static _tls_used: u8;
+ }
+ crate::intrinsics::volatile_load(&_tls_used);
+ }
+ #[cfg(not(target_env = "msvc"))]
+ unsafe fn reference_tls_used() {}
+}
+
+#[allow(dead_code)] // actually called above
+unsafe fn run_dtors() {
+ let mut any_run = true;
+ for _ in 0..5 {
+ if !any_run {
+ break;
+ }
+ any_run = false;
+ let mut cur = DTORS.load(SeqCst);
+ while !cur.is_null() {
+ let ptr = c::TlsGetValue((*cur).key);
+
+ if !ptr.is_null() {
+ c::TlsSetValue((*cur).key, ptr::null_mut());
+ ((*cur).dtor)(ptr as *mut _);
+ any_run = true;
+ }
+
+ cur = (*cur).next;
+ }
+ }
+}
diff --git a/library/std/src/sys/windows/thread_parker.rs b/library/std/src/sys/windows/thread_parker.rs
new file mode 100644
index 000000000..d876e0f6f
--- /dev/null
+++ b/library/std/src/sys/windows/thread_parker.rs
@@ -0,0 +1,255 @@
+// Thread parker implementation for Windows.
+//
+// This uses WaitOnAddress and WakeByAddressSingle if available (Windows 8+).
+// This modern API is exactly the same as the futex syscalls the Linux thread
+// parker uses. When These APIs are available, the implementation of this
+// thread parker matches the Linux thread parker exactly.
+//
+// However, when the modern API is not available, this implementation falls
+// back to NT Keyed Events, which are similar, but have some important
+// differences. These are available since Windows XP.
+//
+// WaitOnAddress first checks the state of the thread parker to make sure it no
+// WakeByAddressSingle calls can be missed between updating the parker state
+// and calling the function.
+//
+// NtWaitForKeyedEvent does not have this option, and unconditionally blocks
+// without checking the parker state first. Instead, NtReleaseKeyedEvent
+// (unlike WakeByAddressSingle) *blocks* until it woke up a thread waiting for
+// it by NtWaitForKeyedEvent. This way, we can be sure no events are missed,
+// but we need to be careful not to block unpark() if park_timeout() was woken
+// up by a timeout instead of unpark().
+//
+// Unlike WaitOnAddress, NtWaitForKeyedEvent/NtReleaseKeyedEvent operate on a
+// HANDLE (created with NtCreateKeyedEvent). This means that we can be sure
+// a successfully awoken park() was awoken by unpark() and not a
+// NtReleaseKeyedEvent call from some other code, as these events are not only
+// matched by the key (address of the parker (state)), but also by this HANDLE.
+// We lazily allocate this handle the first time it is needed.
+//
+// The fast path (calling park() after unpark() was already called) and the
+// possible states are the same for both implementations. This is used here to
+// make sure the fast path does not even check which API to use, but can return
+// right away, independent of the used API. Only the slow paths (which will
+// actually block/wake a thread) check which API is available and have
+// different implementations.
+//
+// Unfortunately, NT Keyed Events are an undocumented Windows API. However:
+// - This API is relatively simple with obvious behaviour, and there are
+// several (unofficial) articles documenting the details. [1]
+// - `parking_lot` has been using this API for years (on Windows versions
+// before Windows 8). [2] Many big projects extensively use parking_lot,
+// such as servo and the Rust compiler itself.
+// - It is the underlying API used by Windows SRW locks and Windows critical
+// sections. [3] [4]
+// - The source code of the implementations of Wine, ReactOs, and Windows XP
+// are available and match the expected behaviour.
+// - The main risk with an undocumented API is that it might change in the
+// future. But since we only use it for older versions of Windows, that's not
+// a problem.
+// - Even if these functions do not block or wake as we expect (which is
+// unlikely, see all previous points), this implementation would still be
+// memory safe. The NT Keyed Events API is only used to sleep/block in the
+// right place.
+//
+// [1]: http://www.locklessinc.com/articles/keyed_events/
+// [2]: https://github.com/Amanieu/parking_lot/commit/43abbc964e
+// [3]: https://docs.microsoft.com/en-us/archive/msdn-magazine/2012/november/windows-with-c-the-evolution-of-synchronization-in-windows-and-c
+// [4]: Windows Internals, Part 1, ISBN 9780735671300
+
+use crate::pin::Pin;
+use crate::ptr;
+use crate::sync::atomic::{
+ AtomicI8, AtomicPtr,
+ Ordering::{Acquire, Relaxed, Release},
+};
+use crate::sys::{c, dur2timeout};
+use crate::time::Duration;
+
+pub struct Parker {
+ state: AtomicI8,
+}
+
+const PARKED: i8 = -1;
+const EMPTY: i8 = 0;
+const NOTIFIED: i8 = 1;
+
+// Notes about memory ordering:
+//
+// Memory ordering is only relevant for the relative ordering of operations
+// between different variables. Even Ordering::Relaxed guarantees a
+// monotonic/consistent order when looking at just a single atomic variable.
+//
+// So, since this parker is just a single atomic variable, we only need to look
+// at the ordering guarantees we need to provide to the 'outside world'.
+//
+// The only memory ordering guarantee that parking and unparking provide, is
+// that things which happened before unpark() are visible on the thread
+// returning from park() afterwards. Otherwise, it was effectively unparked
+// before unpark() was called while still consuming the 'token'.
+//
+// In other words, unpark() needs to synchronize with the part of park() that
+// consumes the token and returns.
+//
+// This is done with a release-acquire synchronization, by using
+// Ordering::Release when writing NOTIFIED (the 'token') in unpark(), and using
+// Ordering::Acquire when reading this state in park() after waking up.
+impl Parker {
+ /// Construct the Windows parker. The UNIX parker implementation
+ /// requires this to happen in-place.
+ pub unsafe fn new(parker: *mut Parker) {
+ parker.write(Self { state: AtomicI8::new(EMPTY) });
+ }
+
+ // Assumes this is only called by the thread that owns the Parker,
+ // which means that `self.state != PARKED`. This implementation doesn't require `Pin`,
+ // but other implementations do.
+ pub unsafe fn park(self: Pin<&Self>) {
+ // Change NOTIFIED=>EMPTY or EMPTY=>PARKED, and directly return in the
+ // first case.
+ if self.state.fetch_sub(1, Acquire) == NOTIFIED {
+ return;
+ }
+
+ if let Some(wait_on_address) = c::WaitOnAddress::option() {
+ loop {
+ // Wait for something to happen, assuming it's still set to PARKED.
+ wait_on_address(self.ptr(), &PARKED as *const _ as c::LPVOID, 1, c::INFINITE);
+ // Change NOTIFIED=>EMPTY but leave PARKED alone.
+ if self.state.compare_exchange(NOTIFIED, EMPTY, Acquire, Acquire).is_ok() {
+ // Actually woken up by unpark().
+ return;
+ } else {
+ // Spurious wake up. We loop to try again.
+ }
+ }
+ } else {
+ // Wait for unpark() to produce this event.
+ c::NtWaitForKeyedEvent(keyed_event_handle(), self.ptr(), 0, ptr::null_mut());
+ // Set the state back to EMPTY (from either PARKED or NOTIFIED).
+ // Note that we don't just write EMPTY, but use swap() to also
+ // include an acquire-ordered read to synchronize with unpark()'s
+ // release-ordered write.
+ self.state.swap(EMPTY, Acquire);
+ }
+ }
+
+ // Assumes this is only called by the thread that owns the Parker,
+ // which means that `self.state != PARKED`. This implementation doesn't require `Pin`,
+ // but other implementations do.
+ pub unsafe fn park_timeout(self: Pin<&Self>, timeout: Duration) {
+ // Change NOTIFIED=>EMPTY or EMPTY=>PARKED, and directly return in the
+ // first case.
+ if self.state.fetch_sub(1, Acquire) == NOTIFIED {
+ return;
+ }
+
+ if let Some(wait_on_address) = c::WaitOnAddress::option() {
+ // Wait for something to happen, assuming it's still set to PARKED.
+ wait_on_address(self.ptr(), &PARKED as *const _ as c::LPVOID, 1, dur2timeout(timeout));
+ // Set the state back to EMPTY (from either PARKED or NOTIFIED).
+ // Note that we don't just write EMPTY, but use swap() to also
+ // include an acquire-ordered read to synchronize with unpark()'s
+ // release-ordered write.
+ if self.state.swap(EMPTY, Acquire) == NOTIFIED {
+ // Actually woken up by unpark().
+ } else {
+ // Timeout or spurious wake up.
+ // We return either way, because we can't easily tell if it was the
+ // timeout or not.
+ }
+ } else {
+ // Need to wait for unpark() using NtWaitForKeyedEvent.
+ let handle = keyed_event_handle();
+
+ // NtWaitForKeyedEvent uses a unit of 100ns, and uses negative
+ // values to indicate a relative time on the monotonic clock.
+ // This is documented here for the underlying KeWaitForSingleObject function:
+ // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-kewaitforsingleobject
+ let mut timeout = match i64::try_from((timeout.as_nanos() + 99) / 100) {
+ Ok(t) => -t,
+ Err(_) => i64::MIN,
+ };
+
+ // Wait for unpark() to produce this event.
+ let unparked =
+ c::NtWaitForKeyedEvent(handle, self.ptr(), 0, &mut timeout) == c::STATUS_SUCCESS;
+
+ // Set the state back to EMPTY (from either PARKED or NOTIFIED).
+ let prev_state = self.state.swap(EMPTY, Acquire);
+
+ if !unparked && prev_state == NOTIFIED {
+ // We were awoken by a timeout, not by unpark(), but the state
+ // was set to NOTIFIED, which means we *just* missed an
+ // unpark(), which is now blocked on us to wait for it.
+ // Wait for it to consume the event and unblock that thread.
+ c::NtWaitForKeyedEvent(handle, self.ptr(), 0, ptr::null_mut());
+ }
+ }
+ }
+
+ // This implementation doesn't require `Pin`, but other implementations do.
+ pub fn unpark(self: Pin<&Self>) {
+ // Change PARKED=>NOTIFIED, EMPTY=>NOTIFIED, or NOTIFIED=>NOTIFIED, and
+ // wake the thread in the first case.
+ //
+ // Note that even NOTIFIED=>NOTIFIED results in a write. This is on
+ // purpose, to make sure every unpark() has a release-acquire ordering
+ // with park().
+ if self.state.swap(NOTIFIED, Release) == PARKED {
+ if let Some(wake_by_address_single) = c::WakeByAddressSingle::option() {
+ unsafe {
+ wake_by_address_single(self.ptr());
+ }
+ } else {
+ // If we run NtReleaseKeyedEvent before the waiting thread runs
+ // NtWaitForKeyedEvent, this (shortly) blocks until we can wake it up.
+ // If the waiting thread wakes up before we run NtReleaseKeyedEvent
+ // (e.g. due to a timeout), this blocks until we do wake up a thread.
+ // To prevent this thread from blocking indefinitely in that case,
+ // park_impl() will, after seeing the state set to NOTIFIED after
+ // waking up, call NtWaitForKeyedEvent again to unblock us.
+ unsafe {
+ c::NtReleaseKeyedEvent(keyed_event_handle(), self.ptr(), 0, ptr::null_mut());
+ }
+ }
+ }
+ }
+
+ fn ptr(&self) -> c::LPVOID {
+ &self.state as *const _ as c::LPVOID
+ }
+}
+
+fn keyed_event_handle() -> c::HANDLE {
+ const INVALID: c::HANDLE = ptr::invalid_mut(!0);
+ static HANDLE: AtomicPtr<libc::c_void> = AtomicPtr::new(INVALID);
+ match HANDLE.load(Relaxed) {
+ INVALID => {
+ let mut handle = c::INVALID_HANDLE_VALUE;
+ unsafe {
+ match c::NtCreateKeyedEvent(
+ &mut handle,
+ c::GENERIC_READ | c::GENERIC_WRITE,
+ ptr::null_mut(),
+ 0,
+ ) {
+ c::STATUS_SUCCESS => {}
+ r => panic!("Unable to create keyed event handle: error {r}"),
+ }
+ }
+ match HANDLE.compare_exchange(INVALID, handle, Relaxed, Relaxed) {
+ Ok(_) => handle,
+ Err(h) => {
+ // Lost the race to another thread initializing HANDLE before we did.
+ // Closing our handle and using theirs instead.
+ unsafe {
+ c::CloseHandle(handle);
+ }
+ h
+ }
+ }
+ }
+ handle => handle,
+ }
+}
diff --git a/library/std/src/sys/windows/time.rs b/library/std/src/sys/windows/time.rs
new file mode 100644
index 000000000..b8209a854
--- /dev/null
+++ b/library/std/src/sys/windows/time.rs
@@ -0,0 +1,224 @@
+use crate::cmp::Ordering;
+use crate::fmt;
+use crate::mem;
+use crate::sys::c;
+use crate::sys_common::IntoInner;
+use crate::time::Duration;
+
+use core::hash::{Hash, Hasher};
+
+const NANOS_PER_SEC: u64 = 1_000_000_000;
+const INTERVALS_PER_SEC: u64 = NANOS_PER_SEC / 100;
+
+#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Hash)]
+pub struct Instant {
+ // This duration is relative to an arbitrary microsecond epoch
+ // from the winapi QueryPerformanceCounter function.
+ t: Duration,
+}
+
+#[derive(Copy, Clone)]
+pub struct SystemTime {
+ t: c::FILETIME,
+}
+
+const INTERVALS_TO_UNIX_EPOCH: u64 = 11_644_473_600 * INTERVALS_PER_SEC;
+
+pub const UNIX_EPOCH: SystemTime = SystemTime {
+ t: c::FILETIME {
+ dwLowDateTime: INTERVALS_TO_UNIX_EPOCH as u32,
+ dwHighDateTime: (INTERVALS_TO_UNIX_EPOCH >> 32) as u32,
+ },
+};
+
+impl Instant {
+ pub fn now() -> Instant {
+ // High precision timing on windows operates in "Performance Counter"
+ // units, as returned by the WINAPI QueryPerformanceCounter function.
+ // These relate to seconds by a factor of QueryPerformanceFrequency.
+ // In order to keep unit conversions out of normal interval math, we
+ // measure in QPC units and immediately convert to nanoseconds.
+ perf_counter::PerformanceCounterInstant::now().into()
+ }
+
+ pub fn checked_sub_instant(&self, other: &Instant) -> Option<Duration> {
+ // On windows there's a threshold below which we consider two timestamps
+ // equivalent due to measurement error. For more details + doc link,
+ // check the docs on epsilon.
+ let epsilon = perf_counter::PerformanceCounterInstant::epsilon();
+ if other.t > self.t && other.t - self.t <= epsilon {
+ Some(Duration::new(0, 0))
+ } else {
+ self.t.checked_sub(other.t)
+ }
+ }
+
+ pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> {
+ Some(Instant { t: self.t.checked_add(*other)? })
+ }
+
+ pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
+ Some(Instant { t: self.t.checked_sub(*other)? })
+ }
+}
+
+impl SystemTime {
+ pub fn now() -> SystemTime {
+ unsafe {
+ let mut t: SystemTime = mem::zeroed();
+ c::GetSystemTimePreciseAsFileTime(&mut t.t);
+ t
+ }
+ }
+
+ fn from_intervals(intervals: i64) -> SystemTime {
+ SystemTime {
+ t: c::FILETIME {
+ dwLowDateTime: intervals as c::DWORD,
+ dwHighDateTime: (intervals >> 32) as c::DWORD,
+ },
+ }
+ }
+
+ fn intervals(&self) -> i64 {
+ (self.t.dwLowDateTime as i64) | ((self.t.dwHighDateTime as i64) << 32)
+ }
+
+ pub fn sub_time(&self, other: &SystemTime) -> Result<Duration, Duration> {
+ let me = self.intervals();
+ let other = other.intervals();
+ if me >= other {
+ Ok(intervals2dur((me - other) as u64))
+ } else {
+ Err(intervals2dur((other - me) as u64))
+ }
+ }
+
+ pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
+ let intervals = self.intervals().checked_add(checked_dur2intervals(other)?)?;
+ Some(SystemTime::from_intervals(intervals))
+ }
+
+ pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
+ let intervals = self.intervals().checked_sub(checked_dur2intervals(other)?)?;
+ Some(SystemTime::from_intervals(intervals))
+ }
+}
+
+impl PartialEq for SystemTime {
+ fn eq(&self, other: &SystemTime) -> bool {
+ self.intervals() == other.intervals()
+ }
+}
+
+impl Eq for SystemTime {}
+
+impl PartialOrd for SystemTime {
+ fn partial_cmp(&self, other: &SystemTime) -> Option<Ordering> {
+ Some(self.cmp(other))
+ }
+}
+
+impl Ord for SystemTime {
+ fn cmp(&self, other: &SystemTime) -> Ordering {
+ self.intervals().cmp(&other.intervals())
+ }
+}
+
+impl fmt::Debug for SystemTime {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("SystemTime").field("intervals", &self.intervals()).finish()
+ }
+}
+
+impl From<c::FILETIME> for SystemTime {
+ fn from(t: c::FILETIME) -> SystemTime {
+ SystemTime { t }
+ }
+}
+
+impl IntoInner<c::FILETIME> for SystemTime {
+ fn into_inner(self) -> c::FILETIME {
+ self.t
+ }
+}
+
+impl Hash for SystemTime {
+ fn hash<H: Hasher>(&self, state: &mut H) {
+ self.intervals().hash(state)
+ }
+}
+
+fn checked_dur2intervals(dur: &Duration) -> Option<i64> {
+ dur.as_secs()
+ .checked_mul(INTERVALS_PER_SEC)?
+ .checked_add(dur.subsec_nanos() as u64 / 100)?
+ .try_into()
+ .ok()
+}
+
+fn intervals2dur(intervals: u64) -> Duration {
+ Duration::new(intervals / INTERVALS_PER_SEC, ((intervals % INTERVALS_PER_SEC) * 100) as u32)
+}
+
+mod perf_counter {
+ use super::NANOS_PER_SEC;
+ use crate::sync::atomic::{AtomicU64, Ordering};
+ use crate::sys::c;
+ use crate::sys::cvt;
+ use crate::sys_common::mul_div_u64;
+ use crate::time::Duration;
+
+ pub struct PerformanceCounterInstant {
+ ts: c::LARGE_INTEGER,
+ }
+ impl PerformanceCounterInstant {
+ pub fn now() -> Self {
+ Self { ts: query() }
+ }
+
+ // Per microsoft docs, the margin of error for cross-thread time comparisons
+ // using QueryPerformanceCounter is 1 "tick" -- defined as 1/frequency().
+ // Reference: https://docs.microsoft.com/en-us/windows/desktop/SysInfo
+ // /acquiring-high-resolution-time-stamps
+ pub fn epsilon() -> Duration {
+ let epsilon = NANOS_PER_SEC / (frequency() as u64);
+ Duration::from_nanos(epsilon)
+ }
+ }
+ impl From<PerformanceCounterInstant> for super::Instant {
+ fn from(other: PerformanceCounterInstant) -> Self {
+ let freq = frequency() as u64;
+ let instant_nsec = mul_div_u64(other.ts as u64, NANOS_PER_SEC, freq);
+ Self { t: Duration::from_nanos(instant_nsec) }
+ }
+ }
+
+ fn frequency() -> c::LARGE_INTEGER {
+ // Either the cached result of `QueryPerformanceFrequency` or `0` for
+ // uninitialized. Storing this as a single `AtomicU64` allows us to use
+ // `Relaxed` operations, as we are only interested in the effects on a
+ // single memory location.
+ static FREQUENCY: AtomicU64 = AtomicU64::new(0);
+
+ let cached = FREQUENCY.load(Ordering::Relaxed);
+ // If a previous thread has filled in this global state, use that.
+ if cached != 0 {
+ return cached as c::LARGE_INTEGER;
+ }
+ // ... otherwise learn for ourselves ...
+ let mut frequency = 0;
+ unsafe {
+ cvt(c::QueryPerformanceFrequency(&mut frequency)).unwrap();
+ }
+
+ FREQUENCY.store(frequency as u64, Ordering::Relaxed);
+ frequency
+ }
+
+ fn query() -> c::LARGE_INTEGER {
+ let mut qpc_value: c::LARGE_INTEGER = 0;
+ cvt(unsafe { c::QueryPerformanceCounter(&mut qpc_value) }).unwrap();
+ qpc_value
+ }
+}