1 #![allow(missing_docs, nonstandard_style)]
4 use crate::ffi::{OsStr, OsString};
5 use crate::io::ErrorKind;
6 use crate::os::windows::ffi::{OsStrExt, OsStringExt};
7 use crate::path::PathBuf;
8 use crate::time::Duration;
11 pub use self::rand::hashmap_random_keys;
13 #[macro_use] pub mod compat;
17 #[cfg(feature = "backtrace")]
22 #[cfg(feature = "backtrace")]
26 pub mod fast_thread_local;
40 pub mod stack_overflow;
50 pub fn decode_error_kind(errno: i32) -> ErrorKind {
51 match errno as c::DWORD {
52 c::ERROR_ACCESS_DENIED => return ErrorKind::PermissionDenied,
53 c::ERROR_ALREADY_EXISTS => return ErrorKind::AlreadyExists,
54 c::ERROR_FILE_EXISTS => return ErrorKind::AlreadyExists,
55 c::ERROR_BROKEN_PIPE => return ErrorKind::BrokenPipe,
56 c::ERROR_FILE_NOT_FOUND => return ErrorKind::NotFound,
57 c::ERROR_PATH_NOT_FOUND => return ErrorKind::NotFound,
58 c::ERROR_NO_DATA => return ErrorKind::BrokenPipe,
59 c::ERROR_OPERATION_ABORTED => return ErrorKind::TimedOut,
64 c::WSAEACCES => ErrorKind::PermissionDenied,
65 c::WSAEADDRINUSE => ErrorKind::AddrInUse,
66 c::WSAEADDRNOTAVAIL => ErrorKind::AddrNotAvailable,
67 c::WSAECONNABORTED => ErrorKind::ConnectionAborted,
68 c::WSAECONNREFUSED => ErrorKind::ConnectionRefused,
69 c::WSAECONNRESET => ErrorKind::ConnectionReset,
70 c::WSAEINVAL => ErrorKind::InvalidInput,
71 c::WSAENOTCONN => ErrorKind::NotConnected,
72 c::WSAEWOULDBLOCK => ErrorKind::WouldBlock,
73 c::WSAETIMEDOUT => ErrorKind::TimedOut,
75 _ => ErrorKind::Other,
79 pub fn to_u16s<S: AsRef<OsStr>>(s: S) -> crate::io::Result<Vec<u16>> {
80 fn inner(s: &OsStr) -> crate::io::Result<Vec<u16>> {
81 let mut maybe_result: Vec<u16> = s.encode_wide().collect();
82 if maybe_result.iter().any(|&u| u == 0) {
83 return Err(crate::io::Error::new(ErrorKind::InvalidInput,
84 "strings passed to WinAPI cannot contain NULs"));
92 // Many Windows APIs follow a pattern of where we hand a buffer and then they
93 // will report back to us how large the buffer should be or how many bytes
94 // currently reside in the buffer. This function is an abstraction over these
95 // functions by making them easier to call.
97 // The first callback, `f1`, is yielded a (pointer, len) pair which can be
98 // passed to a syscall. The `ptr` is valid for `len` items (u16 in this case).
99 // The closure is expected to return what the syscall returns which will be
100 // interpreted by this function to determine if the syscall needs to be invoked
101 // again (with more buffer space).
103 // Once the syscall has completed (errors bail out early) the second closure is
104 // yielded the data which has been read from the syscall. The return value
105 // from this closure is then the return value of the function.
106 fn fill_utf16_buf<F1, F2, T>(mut f1: F1, f2: F2) -> crate::io::Result<T>
107 where F1: FnMut(*mut u16, c::DWORD) -> c::DWORD,
108 F2: FnOnce(&[u16]) -> T
110 // Start off with a stack buf but then spill over to the heap if we end up
111 // needing more space.
112 let mut stack_buf = [0u16; 512];
113 let mut heap_buf = Vec::new();
115 let mut n = stack_buf.len();
117 let buf = if n <= stack_buf.len() {
120 let extra = n - heap_buf.len();
121 heap_buf.reserve(extra);
126 // This function is typically called on windows API functions which
127 // will return the correct length of the string, but these functions
128 // also return the `0` on error. In some cases, however, the
129 // returned "correct length" may actually be 0!
131 // To handle this case we call `SetLastError` to reset it to 0 and
132 // then check it again if we get the "0 error value". If the "last
133 // error" is still 0 then we interpret it as a 0 length buffer and
134 // not an actual error.
136 let k = match f1(buf.as_mut_ptr(), n as c::DWORD) {
137 0 if c::GetLastError() == 0 => 0,
138 0 => return Err(crate::io::Error::last_os_error()),
141 if k == n && c::GetLastError() == c::ERROR_INSUFFICIENT_BUFFER {
146 return Ok(f2(&buf[..k]))
152 fn os2path(s: &[u16]) -> PathBuf {
153 PathBuf::from(OsString::from_wide(s))
156 #[allow(dead_code)] // Only used in backtrace::gnu::get_executable_filename()
157 fn wide_char_to_multi_byte(code_page: u32,
160 no_default_char: bool)
161 -> crate::io::Result<Vec<i8>> {
163 let mut size = c::WideCharToMultiByte(code_page,
172 return Err(crate::io::Error::last_os_error());
175 let mut buf = Vec::with_capacity(size as usize);
176 buf.set_len(size as usize);
178 let mut used_default_char = c::FALSE;
179 size = c::WideCharToMultiByte(code_page,
186 if no_default_char { &mut used_default_char }
187 else { ptr::null_mut() });
189 return Err(crate::io::Error::last_os_error());
191 if no_default_char && used_default_char == c::TRUE {
192 return Err(crate::io::Error::new(crate::io::ErrorKind::InvalidData,
193 "string cannot be converted to requested code page"));
196 buf.set_len(size as usize);
202 pub fn truncate_utf16_at_nul<'a>(v: &'a [u16]) -> &'a [u16] {
203 match v.iter().position(|c| *c == 0) {
204 // don't include the 0
211 fn is_zero(&self) -> bool;
214 macro_rules! impl_is_zero {
215 ($($t:ident)*) => ($(impl IsZero for $t {
216 fn is_zero(&self) -> bool {
222 impl_is_zero! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
224 pub fn cvt<I: IsZero>(i: I) -> crate::io::Result<I> {
226 Err(crate::io::Error::last_os_error())
232 pub fn dur2timeout(dur: Duration) -> c::DWORD {
233 // Note that a duration is a (u64, u32) (seconds, nanoseconds) pair, and the
234 // timeouts in windows APIs are typically u32 milliseconds. To translate, we
235 // have two pieces to take care of:
237 // * Nanosecond precision is rounded up
238 // * Greater than u32::MAX milliseconds (50 days) is rounded up to INFINITE
240 dur.as_secs().checked_mul(1000).and_then(|ms| {
241 ms.checked_add((dur.subsec_nanos() as u64) / 1_000_000)
243 ms.checked_add(if dur.subsec_nanos() % 1_000_000 > 0 {1} else {0})
245 if ms > <c::DWORD>::max_value() as u64 {
250 }).unwrap_or(c::INFINITE)
253 // On Windows, use the processor-specific __fastfail mechanism. In Windows 8
254 // and later, this will terminate the process immediately without running any
255 // in-process exception handlers. In earlier versions of Windows, this
256 // sequence of instructions will be treated as an access violation,
257 // terminating the process but without necessarily bypassing all exception
260 // https://msdn.microsoft.com/en-us/library/dn774154.aspx
261 #[allow(unreachable_code)]
262 pub unsafe fn abort_internal() -> ! {
263 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
265 asm!("int $$0x29" :: "{ecx}"(7) ::: volatile); // 7 is FAST_FAIL_FATAL_APP_EXIT
266 crate::intrinsics::unreachable();
268 crate::intrinsics::abort();