1 #![unstable(issue = "none", feature = "windows_stdio")]
3 use crate::char::decode_utf16;
6 use crate::os::windows::io::{FromRawHandle, IntoRawHandle};
11 use crate::sys::handle::Handle;
12 use core::str::utf8_char_width;
14 // Don't cache handles but get them fresh for every read/write. This allows us to track changes to
15 // the value over time (such as if a process calls `SetStdHandle` while it's running). See #40490.
20 incomplete_utf8: IncompleteUtf8,
24 incomplete_utf8: IncompleteUtf8,
27 struct IncompleteUtf8 {
32 // Apparently Windows doesn't handle large reads on stdin or writes to stdout/stderr well (see
33 // #13304 for details).
35 // From MSDN (2011): "The storage for this buffer is allocated from a shared heap for the
36 // process that is 64 KB in size. The maximum size of the buffer will depend on heap usage."
38 // We choose the cap at 8 KiB because libuv does the same, and it seems to be acceptable so far.
39 const MAX_BUFFER_SIZE: usize = 8192;
41 // The standard buffer size of BufReader for Stdin should be able to hold 3x more bytes than there
42 // are `u16`'s in MAX_BUFFER_SIZE. This ensures the read data can always be completely decoded from
44 pub const STDIN_BUF_SIZE: usize = MAX_BUFFER_SIZE / 2 * 3;
46 pub fn get_handle(handle_id: c::DWORD) -> io::Result<c::HANDLE> {
47 let handle = unsafe { c::GetStdHandle(handle_id) };
48 if handle == c::INVALID_HANDLE_VALUE {
49 Err(io::Error::last_os_error())
50 } else if handle.is_null() {
51 Err(io::Error::from_raw_os_error(c::ERROR_INVALID_HANDLE as i32))
57 fn is_console(handle: c::HANDLE) -> bool {
58 // `GetConsoleMode` will return false (0) if this is a pipe (we don't care about the reported
59 // mode). This will only detect Windows Console, not other terminals connected to a pipe like
60 // MSYS. Which is exactly what we need, as only Windows Console needs a conversion to UTF-16.
62 unsafe { c::GetConsoleMode(handle, &mut mode) != 0 }
68 incomplete_utf8: &mut IncompleteUtf8,
69 ) -> io::Result<usize> {
74 let handle = get_handle(handle_id)?;
75 if !is_console(handle) {
77 let handle = Handle::from_raw_handle(handle);
78 let ret = handle.write(data);
79 handle.into_raw_handle(); // Don't close the handle
84 if incomplete_utf8.len > 0 {
86 incomplete_utf8.len < 4,
87 "Unexpected number of bytes for incomplete UTF-8 codepoint."
89 if data[0] >> 6 != 0b10 {
90 // not a continuation byte - reject
91 incomplete_utf8.len = 0;
92 return Err(io::Error::new_const(
93 io::ErrorKind::InvalidData,
94 &"Windows stdio in console mode does not support writing non-UTF-8 byte sequences",
97 incomplete_utf8.bytes[incomplete_utf8.len as usize] = data[0];
98 incomplete_utf8.len += 1;
99 let char_width = utf8_char_width(incomplete_utf8.bytes[0]);
100 if (incomplete_utf8.len as usize) < char_width {
104 let s = str::from_utf8(&incomplete_utf8.bytes[0..incomplete_utf8.len as usize]);
105 incomplete_utf8.len = 0;
108 assert_eq!(char_width, s.len());
109 let written = write_valid_utf8_to_console(handle, s)?;
110 assert_eq!(written, s.len()); // guaranteed by write_valid_utf8_to_console() for single codepoint writes
114 return Err(io::Error::new_const(
115 io::ErrorKind::InvalidData,
116 &"Windows stdio in console mode does not support writing non-UTF-8 byte sequences",
122 // As the console is meant for presenting text, we assume bytes of `data` are encoded as UTF-8,
123 // which needs to be encoded as UTF-16.
125 // If the data is not valid UTF-8 we write out as many bytes as are valid.
126 // If the first byte is invalid it is either first byte of a multi-byte sequence but the
127 // provided byte slice is too short or it is the first byte of an invalid multi-byte sequence.
128 let len = cmp::min(data.len(), MAX_BUFFER_SIZE / 2);
129 let utf8 = match str::from_utf8(&data[..len]) {
131 Err(ref e) if e.valid_up_to() == 0 => {
132 let first_byte_char_width = utf8_char_width(data[0]);
133 if first_byte_char_width > 1 && data.len() < first_byte_char_width {
134 incomplete_utf8.bytes[0] = data[0];
135 incomplete_utf8.len = 1;
138 return Err(io::Error::new_const(
139 io::ErrorKind::InvalidData,
140 &"Windows stdio in console mode does not support writing non-UTF-8 byte sequences",
144 Err(e) => str::from_utf8(&data[..e.valid_up_to()]).unwrap(),
147 write_valid_utf8_to_console(handle, utf8)
150 fn write_valid_utf8_to_console(handle: c::HANDLE, utf8: &str) -> io::Result<usize> {
151 let mut utf16 = [0u16; MAX_BUFFER_SIZE / 2];
152 let mut len_utf16 = 0;
153 for (chr, dest) in utf8.encode_utf16().zip(utf16.iter_mut()) {
157 let utf16 = &utf16[..len_utf16];
159 let mut written = write_u16s(handle, &utf16)?;
161 // Figure out how many bytes of as UTF-8 were written away as UTF-16.
162 if written == utf16.len() {
165 // Make sure we didn't end up writing only half of a surrogate pair (even though the chance
166 // is tiny). Because it is not possible for user code to re-slice `data` in such a way that
167 // a missing surrogate can be produced (and also because of the UTF-8 validation above),
168 // write the missing surrogate out now.
169 // Buffering it would mean we have to lie about the number of bytes written.
170 let first_char_remaining = utf16[written];
171 if first_char_remaining >= 0xDCEE && first_char_remaining <= 0xDFFF {
173 // We just hope this works, and give up otherwise
174 let _ = write_u16s(handle, &utf16[written..written + 1]);
177 // Calculate the number of bytes of `utf8` that were actually written.
179 for ch in utf16[..written].iter() {
181 0x0000..=0x007F => 1,
182 0x0080..=0x07FF => 2,
183 0xDCEE..=0xDFFF => 1, // Low surrogate. We already counted 3 bytes for the other.
187 debug_assert!(String::from_utf16(&utf16[..written]).unwrap() == utf8[..count]);
192 fn write_u16s(handle: c::HANDLE, data: &[u16]) -> io::Result<usize> {
197 data.as_ptr() as c::LPCVOID,
207 pub const fn new() -> Stdin {
208 Stdin { surrogate: 0 }
212 impl io::Read for Stdin {
213 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
214 let handle = get_handle(c::STD_INPUT_HANDLE)?;
215 if !is_console(handle) {
217 let handle = Handle::from_raw_handle(handle);
218 let ret = handle.read(buf);
219 handle.into_raw_handle(); // Don't close the handle
226 } else if buf.len() < 4 {
227 return Err(io::Error::new_const(
228 io::ErrorKind::InvalidInput,
229 &"Windows stdin in console mode does not support a buffer too small to \
230 guarantee holding one arbitrary UTF-8 character (4 bytes)",
234 let mut utf16_buf = [0u16; MAX_BUFFER_SIZE / 2];
235 // In the worst case, a UTF-8 string can take 3 bytes for every `u16` of a UTF-16. So
236 // we can read at most a third of `buf.len()` chars and uphold the guarantee no data gets
238 let amount = cmp::min(buf.len() / 3, utf16_buf.len());
239 let read = read_u16s_fixup_surrogates(handle, &mut utf16_buf, amount, &mut self.surrogate)?;
241 utf16_to_utf8(&utf16_buf[..read], buf)
245 // We assume that if the last `u16` is an unpaired surrogate they got sliced apart by our
246 // buffer size, and keep it around for the next read hoping to put them together.
247 // This is a best effort, and might not work if we are not the only reader on Stdin.
248 fn read_u16s_fixup_surrogates(
253 ) -> io::Result<usize> {
254 // Insert possibly remaining unpaired surrogate from last read.
261 // Special case: `Stdin::read` guarantees we can always read at least one new `u16`
262 // and combine it with an unpaired surrogate, because the UTF-8 buffer is at least
267 let mut amount = read_u16s(handle, &mut buf[start..amount])? + start;
270 let last_char = buf[amount - 1];
271 if last_char >= 0xD800 && last_char <= 0xDBFF {
273 *surrogate = last_char;
280 fn read_u16s(handle: c::HANDLE, buf: &mut [u16]) -> io::Result<usize> {
281 // Configure the `pInputControl` parameter to not only return on `\r\n` but also Ctrl-Z, the
282 // traditional DOS method to indicate end of character stream / user input (SUB).
283 // See #38274 and https://stackoverflow.com/questions/43836040/win-api-readconsole.
284 const CTRL_Z: u16 = 0x1A;
285 const CTRL_Z_MASK: c::ULONG = 1 << CTRL_Z;
286 let mut input_control = c::CONSOLE_READCONSOLE_CONTROL {
287 nLength: crate::mem::size_of::<c::CONSOLE_READCONSOLE_CONTROL>() as c::ULONG,
289 dwCtrlWakeupMask: CTRL_Z_MASK,
290 dwControlKeyState: 0,
299 buf.as_mut_ptr() as c::LPVOID,
302 &mut input_control as c::PCONSOLE_READCONSOLE_CONTROL,
306 // ReadConsoleW returns success with ERROR_OPERATION_ABORTED for Ctrl-C or Ctrl-Break.
307 // Explicitly check for that case here and try again.
308 if amount == 0 && unsafe { c::GetLastError() } == c::ERROR_OPERATION_ABORTED {
314 if amount > 0 && buf[amount as usize - 1] == CTRL_Z {
321 fn utf16_to_utf8(utf16: &[u16], utf8: &mut [u8]) -> io::Result<usize> {
323 for chr in decode_utf16(utf16.iter().cloned()) {
326 chr.encode_utf8(&mut utf8[written..]);
327 written += chr.len_utf8();
330 // We can't really do any better than forget all data and return an error.
331 return Err(io::Error::new_const(
332 io::ErrorKind::InvalidData,
333 &"Windows stdin in console mode does not support non-UTF-16 input; \
334 encountered unpaired surrogate",
342 impl IncompleteUtf8 {
343 pub const fn new() -> IncompleteUtf8 {
344 IncompleteUtf8 { bytes: [0; 4], len: 0 }
349 pub const fn new() -> Stdout {
350 Stdout { incomplete_utf8: IncompleteUtf8::new() }
354 impl io::Write for Stdout {
355 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
356 write(c::STD_OUTPUT_HANDLE, buf, &mut self.incomplete_utf8)
359 fn flush(&mut self) -> io::Result<()> {
365 pub const fn new() -> Stderr {
366 Stderr { incomplete_utf8: IncompleteUtf8::new() }
370 impl io::Write for Stderr {
371 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
372 write(c::STD_ERROR_HANDLE, buf, &mut self.incomplete_utf8)
375 fn flush(&mut self) -> io::Result<()> {
380 pub fn is_ebadf(err: &io::Error) -> bool {
381 err.raw_os_error() == Some(c::ERROR_INVALID_HANDLE as i32)
384 pub fn panic_output() -> Option<impl io::Write> {