]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/windows/mod.rs
Rollup merge of #60429 - estebank:pub-path, r=michaelwoerister
[rust.git] / src / libstd / sys / windows / mod.rs
1 #![allow(missing_docs, nonstandard_style)]
2
3 use crate::ptr;
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;
9
10 pub use libc::strlen;
11 pub use self::rand::hashmap_random_keys;
12
13 #[macro_use] pub mod compat;
14
15 pub mod alloc;
16 pub mod args;
17 #[cfg(feature = "backtrace")]
18 pub mod backtrace;
19 pub mod c;
20 pub mod cmath;
21 pub mod condvar;
22 #[cfg(feature = "backtrace")]
23 pub mod dynamic_lib;
24 pub mod env;
25 pub mod ext;
26 pub mod fast_thread_local;
27 pub mod fs;
28 pub mod handle;
29 pub mod io;
30 pub mod memchr;
31 pub mod mutex;
32 pub mod net;
33 pub mod os;
34 pub mod os_str;
35 pub mod path;
36 pub mod pipe;
37 pub mod process;
38 pub mod rand;
39 pub mod rwlock;
40 pub mod stack_overflow;
41 pub mod thread;
42 pub mod thread_local;
43 pub mod time;
44 pub mod stdio;
45
46 #[cfg(not(test))]
47 pub fn init() {
48 }
49
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,
60         _ => {}
61     }
62
63     match errno {
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,
74
75         _ => ErrorKind::Other,
76     }
77 }
78
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"));
85         }
86         maybe_result.push(0);
87         Ok(maybe_result)
88     }
89     inner(s.as_ref())
90 }
91
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.
96 //
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).
102 //
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
109 {
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();
114     unsafe {
115         let mut n = stack_buf.len();
116         loop {
117             let buf = if n <= stack_buf.len() {
118                 &mut stack_buf[..]
119             } else {
120                 let extra = n - heap_buf.len();
121                 heap_buf.reserve(extra);
122                 heap_buf.set_len(n);
123                 &mut heap_buf[..]
124             };
125
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!
130             //
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.
135             c::SetLastError(0);
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()),
139                 n => n,
140             } as usize;
141             if k == n && c::GetLastError() == c::ERROR_INSUFFICIENT_BUFFER {
142                 n *= 2;
143             } else if k >= n {
144                 n = k;
145             } else {
146                 return Ok(f2(&buf[..k]))
147             }
148         }
149     }
150 }
151
152 fn os2path(s: &[u16]) -> PathBuf {
153     PathBuf::from(OsString::from_wide(s))
154 }
155
156 #[allow(dead_code)] // Only used in backtrace::gnu::get_executable_filename()
157 fn wide_char_to_multi_byte(code_page: u32,
158                            flags: u32,
159                            s: &[u16],
160                            no_default_char: bool)
161                            -> crate::io::Result<Vec<i8>> {
162     unsafe {
163         let mut size = c::WideCharToMultiByte(code_page,
164                                               flags,
165                                               s.as_ptr(),
166                                               s.len() as i32,
167                                               ptr::null_mut(),
168                                               0,
169                                               ptr::null(),
170                                               ptr::null_mut());
171         if size == 0 {
172             return Err(crate::io::Error::last_os_error());
173         }
174
175         let mut buf = Vec::with_capacity(size as usize);
176         buf.set_len(size as usize);
177
178         let mut used_default_char = c::FALSE;
179         size = c::WideCharToMultiByte(code_page,
180                                       flags,
181                                       s.as_ptr(),
182                                       s.len() as i32,
183                                       buf.as_mut_ptr(),
184                                       buf.len() as i32,
185                                       ptr::null(),
186                                       if no_default_char { &mut used_default_char }
187                                       else { ptr::null_mut() });
188         if size == 0 {
189             return Err(crate::io::Error::last_os_error());
190         }
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"));
194         }
195
196         buf.set_len(size as usize);
197
198         Ok(buf)
199     }
200 }
201
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
205         Some(i) => &v[..i],
206         None => v
207     }
208 }
209
210 pub trait IsZero {
211     fn is_zero(&self) -> bool;
212 }
213
214 macro_rules! impl_is_zero {
215     ($($t:ident)*) => ($(impl IsZero for $t {
216         fn is_zero(&self) -> bool {
217             *self == 0
218         }
219     })*)
220 }
221
222 impl_is_zero! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
223
224 pub fn cvt<I: IsZero>(i: I) -> crate::io::Result<I> {
225     if i.is_zero() {
226         Err(crate::io::Error::last_os_error())
227     } else {
228         Ok(i)
229     }
230 }
231
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:
236     //
237     // * Nanosecond precision is rounded up
238     // * Greater than u32::MAX milliseconds (50 days) is rounded up to INFINITE
239     //   (never time out).
240     dur.as_secs().checked_mul(1000).and_then(|ms| {
241         ms.checked_add((dur.subsec_nanos() as u64) / 1_000_000)
242     }).and_then(|ms| {
243         ms.checked_add(if dur.subsec_nanos() % 1_000_000 > 0 {1} else {0})
244     }).map(|ms| {
245         if ms > <c::DWORD>::max_value() as u64 {
246             c::INFINITE
247         } else {
248             ms as c::DWORD
249         }
250     }).unwrap_or(c::INFINITE)
251 }
252
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
258 // handlers.
259 //
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"))]
264     {
265         asm!("int $$0x29" :: "{ecx}"(7) ::: volatile); // 7 is FAST_FAIL_FATAL_APP_EXIT
266         crate::intrinsics::unreachable();
267     }
268     crate::intrinsics::abort();
269 }