Skip to main content

std/os/windows/io/
mod.rs

1//! Windows-specific extensions to general I/O primitives.
2//!
3//! Just like raw pointers, raw Windows handles and sockets point to resources
4//! with dynamic lifetimes, and they can dangle if they outlive their resources
5//! or be forged if they're created from invalid values.
6//!
7//! This module provides three types for representing raw handles and sockets
8//! with different ownership properties: raw, borrowed, and owned, which are
9//! analogous to types used for representing pointers. These types reflect concepts of [I/O
10//! safety][io-safety] on Windows.
11//!
12//! | Type                   | Analogous to |
13//! | ---------------------- | ------------ |
14//! | [`RawHandle`]          | `*const _`   |
15//! | [`RawSocket`]          | `*const _`   |
16//! |                        |              |
17//! | [`BorrowedHandle<'a>`] | `&'a _`      |
18//! | [`BorrowedSocket<'a>`] | `&'a _`      |
19//! |                        |              |
20//! | [`OwnedHandle`]        | `Box<_>`     |
21//! | [`OwnedSocket`]        | `Box<_>`     |
22//!
23//! Like raw pointers, `RawHandle` and `RawSocket` values are primitive values.
24//! And in new code, they should be considered unsafe to do I/O on (analogous
25//! to dereferencing them). Rust did not always provide this guidance, so
26//! existing code in the Rust ecosystem often doesn't mark `RawHandle` and
27//! `RawSocket` usage as unsafe.
28//! Libraries are encouraged to migrate, either by adding `unsafe` to APIs
29//! that dereference `RawHandle` and `RawSocket` values, or by using to
30//! `BorrowedHandle`, `BorrowedSocket`, `OwnedHandle`, or `OwnedSocket`.
31//!
32//! Like references, `BorrowedHandle` and `BorrowedSocket` values are tied to a
33//! lifetime, to ensure that they don't outlive the resource they point to.
34//! These are safe to use. `BorrowedHandle` and `BorrowedSocket` values may be
35//! used in APIs which provide safe access to any system call except for
36//! `CloseHandle`, `closesocket`, or any other call that would end the
37//! dynamic lifetime of the resource without ending the lifetime of the
38//! handle or socket.
39//!
40//! `BorrowedHandle` and `BorrowedSocket` values may be used in APIs which
41//! provide safe access to `DuplicateHandle` and `WSADuplicateSocketW` and
42//! related functions, so types implementing `AsHandle`, `AsSocket`,
43//! `From<OwnedHandle>`, or `From<OwnedSocket>` should not assume they always
44//! have exclusive access to the underlying object.
45//!
46//! Like boxes, `OwnedHandle` and `OwnedSocket` values conceptually own the
47//! resource they point to, and free (close) it when they are dropped.
48//!
49//! See the [`io` module docs][io-safety] for a general explanation of I/O safety.
50//!
51//! [`BorrowedHandle<'a>`]: crate::os::windows::io::BorrowedHandle
52//! [`BorrowedSocket<'a>`]: crate::os::windows::io::BorrowedSocket
53//! [io-safety]: crate::io#io-safety
54
55#![stable(feature = "rust1", since = "1.0.0")]
56
57mod handle;
58mod raw;
59mod socket;
60
61#[stable(feature = "io_safety", since = "1.63.0")]
62pub use handle::*;
63#[stable(feature = "rust1", since = "1.0.0")]
64pub use raw::*;
65#[stable(feature = "io_safety", since = "1.63.0")]
66pub use socket::*;
67
68use crate::io::{self, Stderr, StderrLock, Stdin, StdinLock, Stdout, StdoutLock, Write};
69use crate::ptr;
70#[cfg(not(doc))]
71use crate::sys::c;
72
73#[cfg(test)]
74mod tests;
75
76#[unstable(feature = "stdio_swap", issue = "150667", reason = "recently added")]
77pub impl(self) trait StdioExt {
78    /// Sets the stdio console handle to `handle`, or `NULL` if it is `None`.
79    /// The old handle, if any, will not be closed, i.e. it is leaked because
80    /// console handles are shared global resources.
81    ///
82    /// Rust std::io write buffers (if any) are flushed, but other runtimes
83    /// (e.g. C stdio) or libraries that acquire a clone of the file handle
84    /// will not be aware of this change.
85    ///
86    #[cfg_attr(windows, doc = "```no_run")]
87    #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
88    /// #![feature(stdio_swap)]
89    /// use std::io::{self, Read, Write};
90    /// use std::os::windows::io::StdioExt;
91    ///
92    /// fn main() -> io::Result<()> {
93    ///    let (reader, mut writer) = io::pipe()?;
94    ///    let mut stdin = io::stdin();
95    ///    stdin.set_handle(Some(reader))?;
96    ///    writer.write_all(b"Hello, world!")?;
97    ///    let mut buffer = vec![0; 13];
98    ///    assert_eq!(stdin.read(&mut buffer)?, 13);
99    ///    assert_eq!(&buffer, b"Hello, world!");
100    ///    Ok(())
101    /// }
102    /// ```
103    fn set_handle<T: Into<OwnedHandle>>(&mut self, handle: Option<T>) -> io::Result<()>;
104
105    /// Sets the stdio console handle to `replace_with`. The previous handle is returned, or
106    /// `None` if it was `NULL`.
107    ///
108    /// The returned handle is a `BorrowedHandle<'static>` because console handles are shared global resources
109    /// and may have been obtained by other functions or threads.
110    /// Only if you have ensured that no other part of the program has borrowed this handle you can convert it into
111    /// an `OwnedHandle` and drop that to close it.
112    ///
113    /// Like `set_handle()`, Rust std::io write buffers (if any) are flushed.
114    fn replace_handle<T: Into<OwnedHandle>>(
115        &mut self,
116        replace_with: T,
117    ) -> io::Result<Option<BorrowedHandle<'static>>>;
118
119    /// Sets the stdio console handle to `NULL` and returns the old one
120    ///
121    /// See [`set_handle()`] for additional details.
122    ///
123    /// [`set_handle()`]: StdioExt::set_handle
124    fn take_handle(&mut self) -> io::Result<Option<BorrowedHandle<'static>>>;
125}
126
127macro io_ext_impl($stdio_ty:ty, $stdio_lock_ty:ty, $handle:path, $writer:literal) {
128    #[unstable(feature = "stdio_swap", issue = "150667", reason = "recently added")]
129    impl StdioExt for $stdio_ty {
130        fn set_handle<T: Into<OwnedHandle>>(&mut self, handle: Option<T>) -> io::Result<()> {
131            self.lock().set_handle(handle)
132        }
133
134        fn replace_handle<T: Into<OwnedHandle>>(
135            &mut self,
136            replace_with: T,
137        ) -> io::Result<Option<BorrowedHandle<'static>>> {
138            self.lock().replace_handle(replace_with)
139        }
140
141        fn take_handle(&mut self) -> io::Result<Option<BorrowedHandle<'static>>> {
142            self.lock().take_handle()
143        }
144    }
145
146    #[unstable(feature = "stdio_swap", issue = "150667", reason = "recently added")]
147    impl StdioExt for $stdio_lock_ty {
148        fn set_handle<T: Into<OwnedHandle>>(&mut self, handle: Option<T>) -> io::Result<()> {
149            #[cfg($writer)]
150            self.flush()?;
151            let raw = handle.map(|h| h.into().into_raw_handle()).unwrap_or(ptr::null_mut());
152            unsafe { c::SetStdHandle($handle, raw) };
153            Ok(())
154        }
155
156        fn replace_handle<T: Into<OwnedHandle>>(
157            &mut self,
158            replace_with: T,
159        ) -> io::Result<Option<BorrowedHandle<'static>>> {
160            let old = unsafe { BorrowedHandle::borrow_raw(self.as_raw_handle()) };
161            self.set_handle(Some(replace_with))?;
162            let handle = if old.as_raw_handle().is_null() { None } else { Some(old) };
163            Ok(handle)
164        }
165
166        fn take_handle(&mut self) -> io::Result<Option<BorrowedHandle<'static>>> {
167            let old = unsafe { BorrowedHandle::borrow_raw(self.as_raw_handle()) };
168            #[cfg($writer)]
169            self.flush()?;
170            unsafe { c::SetStdHandle($handle, ptr::null_mut()) };
171            let handle = if old.as_raw_handle().is_null() { None } else { Some(old) };
172            Ok(handle)
173        }
174    }
175}
176
177io_ext_impl!(Stdout, StdoutLock<'_>, c::STD_OUTPUT_HANDLE, true);
178io_ext_impl!(Stdin, StdinLock<'_>, c::STD_INPUT_HANDLE, false);
179io_ext_impl!(Stderr, StderrLock<'_>, c::STD_ERROR_HANDLE, true);