1 use crate::os::windows::prelude::*;
4 use crate::io::{self, IoSlice, IoSliceMut, Read};
9 use crate::sync::atomic::AtomicUsize;
10 use crate::sync::atomic::Ordering::SeqCst;
12 use crate::sys::fs::{File, OpenOptions};
13 use crate::sys::handle::Handle;
14 use crate::sys::hashmap_random_keys;
15 use crate::sys_common::IntoInner;
17 ////////////////////////////////////////////////////////////////////////////////
19 ////////////////////////////////////////////////////////////////////////////////
25 impl IntoInner<Handle> for AnonPipe {
26 fn into_inner(self) -> Handle {
36 /// Although this looks similar to `anon_pipe` in the Unix module it's actually
37 /// subtly different. Here we'll return two pipes in the `Pipes` return value,
38 /// but one is intended for "us" where as the other is intended for "someone
41 /// Currently the only use case for this function is pipes for stdio on
42 /// processes in the standard library, so "ours" is the one that'll stay in our
43 /// process whereas "theirs" will be inherited to a child.
45 /// The ours/theirs pipes are *not* specifically readable or writable. Each
46 /// one only supports a read or a write, but which is which depends on the
47 /// boolean flag given. If `ours_readable` is `true`, then `ours` is readable and
48 /// `theirs` is writable. Conversely, if `ours_readable` is `false`, then `ours`
49 /// is writable and `theirs` is readable.
51 /// Also note that the `ours` pipe is always a handle opened up in overlapped
52 /// mode. This means that technically speaking it should only ever be used
53 /// with `OVERLAPPED` instances, but also works out ok if it's only ever used
54 /// once at a time (which we do indeed guarantee).
55 pub fn anon_pipe(ours_readable: bool, their_handle_inheritable: bool) -> io::Result<Pipes> {
56 // A 64kb pipe capacity is the same as a typical Linux default.
57 const PIPE_BUFFER_CAPACITY: u32 = 64 * 1024;
59 // Note that we specifically do *not* use `CreatePipe` here because
60 // unfortunately the anonymous pipes returned do not support overlapped
61 // operations. Instead, we create a "hopefully unique" name and create a
62 // named pipe which has overlapped operations enabled.
64 // Once we do this, we connect do it as usual via `CreateFileW`, and then
65 // we return those reader/writer halves. Note that the `ours` pipe return
66 // value is always the named pipe, whereas `theirs` is just the normal file.
67 // This should hopefully shield us from child processes which assume their
68 // stdout is a named pipe, which would indeed be odd!
73 let mut reject_remote_clients_flag = c::PIPE_REJECT_REMOTE_CLIENTS;
77 r"\\.\pipe\__rust_anonymous_pipe1__.{}.{}",
78 c::GetCurrentProcessId(),
81 let wide_name = OsStr::new(&name).encode_wide().chain(Some(0)).collect::<Vec<_>>();
82 let mut flags = c::FILE_FLAG_FIRST_PIPE_INSTANCE | c::FILE_FLAG_OVERLAPPED;
84 flags |= c::PIPE_ACCESS_INBOUND;
86 flags |= c::PIPE_ACCESS_OUTBOUND;
89 let handle = c::CreateNamedPipeW(
93 | c::PIPE_READMODE_BYTE
95 | reject_remote_clients_flag,
103 // We pass the `FILE_FLAG_FIRST_PIPE_INSTANCE` flag above, and we're
104 // also just doing a best effort at selecting a unique name. If
105 // `ERROR_ACCESS_DENIED` is returned then it could mean that we
106 // accidentally conflicted with an already existing pipe, so we try
109 // Don't try again too much though as this could also perhaps be a
111 // If `ERROR_INVALID_PARAMETER` is returned, this probably means we're
112 // running on pre-Vista version where `PIPE_REJECT_REMOTE_CLIENTS` is
113 // not supported, so we continue retrying without it. This implies
114 // reduced security on Windows versions older than Vista by allowing
115 // connections to this pipe from remote machines.
116 // Proper fix would increase the number of FFI imports and introduce
117 // significant amount of Windows XP specific code with no clean
119 // For more info, see https://github.com/rust-lang/rust/pull/37677.
120 if handle == c::INVALID_HANDLE_VALUE {
121 let err = io::Error::last_os_error();
122 let raw_os_err = err.raw_os_error();
124 if raw_os_err == Some(c::ERROR_ACCESS_DENIED as i32) {
126 } else if reject_remote_clients_flag != 0
127 && raw_os_err == Some(c::ERROR_INVALID_PARAMETER as i32)
129 reject_remote_clients_flag = 0;
136 ours = Handle::from_raw_handle(handle);
140 // Connect to the named pipe we just created. This handle is going to be
141 // returned in `theirs`, so if `ours` is readable we want this to be
142 // writable, otherwise if `ours` is writable we want this to be
145 // Additionally we don't enable overlapped mode on this because most
146 // client processes aren't enabled to work with that.
147 let mut opts = OpenOptions::new();
148 opts.write(ours_readable);
149 opts.read(!ours_readable);
151 let size = mem::size_of::<c::SECURITY_ATTRIBUTES>();
152 let mut sa = c::SECURITY_ATTRIBUTES {
153 nLength: size as c::DWORD,
154 lpSecurityDescriptor: ptr::null_mut(),
155 bInheritHandle: their_handle_inheritable as i32,
157 opts.security_attributes(&mut sa);
158 let theirs = File::open(Path::new(&name), &opts)?;
159 let theirs = AnonPipe { inner: theirs.into_inner() };
162 ours: AnonPipe { inner: ours },
163 theirs: AnonPipe { inner: theirs.into_inner() },
168 /// Takes an asynchronous source pipe and returns a synchronous pipe suitable
169 /// for sending to a child process.
171 /// This is achieved by creating a new set of pipes and spawning a thread that
172 /// relays messages between the source and the synchronous pipe.
173 pub fn spawn_pipe_relay(
176 their_handle_inheritable: bool,
177 ) -> io::Result<AnonPipe> {
178 // We need this handle to live for the lifetime of the thread spawned below.
179 let source = source.duplicate()?;
181 // create a new pair of anon pipes.
182 let Pipes { theirs, ours } = anon_pipe(ours_readable, their_handle_inheritable)?;
184 // Spawn a thread that passes messages from one pipe to the other.
185 // Any errors will simply cause the thread to exit.
186 let (reader, writer) = if ours_readable { (ours, source) } else { (source, ours) };
187 crate::thread::spawn(move || {
188 let mut buf = [0_u8; 4096];
189 'reader: while let Ok(len) = reader.read(&mut buf) {
194 while let Ok(written) = writer.write(&buf[start..len]) {
204 // Return the pipe that should be sent to the child process.
208 fn random_number() -> usize {
209 static N: AtomicUsize = AtomicUsize::new(0);
211 if N.load(SeqCst) != 0 {
212 return N.fetch_add(1, SeqCst);
215 N.store(hashmap_random_keys().0 as usize, SeqCst);
219 // Abstracts over `ReadFileEx` and `WriteFileEx`
220 type AlertableIoFn = unsafe extern "system" fn(
225 c::LPOVERLAPPED_COMPLETION_ROUTINE,
229 pub fn handle(&self) -> &Handle {
232 pub fn into_handle(self) -> Handle {
235 fn duplicate(&self) -> io::Result<Self> {
236 self.inner.duplicate(0, false, c::DUPLICATE_SAME_ACCESS).map(|inner| AnonPipe { inner })
239 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
240 let result = unsafe {
241 let len = crate::cmp::min(buf.len(), c::DWORD::MAX as usize) as c::DWORD;
242 self.alertable_io_internal(c::ReadFileEx, buf.as_mut_ptr() as _, len)
246 // The special treatment of BrokenPipe is to deal with Windows
247 // pipe semantics, which yields this error when *reading* from
248 // a pipe after the other end has closed; we interpret that as
250 Err(ref e) if e.kind() == io::ErrorKind::BrokenPipe => Ok(0),
255 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
256 self.inner.read_vectored(bufs)
260 pub fn is_read_vectored(&self) -> bool {
261 self.inner.is_read_vectored()
264 pub fn read_to_end(&self, buf: &mut Vec<u8>) -> io::Result<usize> {
265 self.handle().read_to_end(buf)
268 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
270 let len = crate::cmp::min(buf.len(), c::DWORD::MAX as usize) as c::DWORD;
271 self.alertable_io_internal(c::WriteFileEx, buf.as_ptr() as _, len)
275 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
276 self.inner.write_vectored(bufs)
280 pub fn is_write_vectored(&self) -> bool {
281 self.inner.is_write_vectored()
284 /// Synchronizes asynchronous reads or writes using our anonymous pipe.
286 /// This is a wrapper around [`ReadFileEx`] or [`WriteFileEx`] that uses
287 /// [Asynchronous Procedure Call] (APC) to synchronize reads or writes.
289 /// Note: This should not be used for handles we don't create.
293 /// `buf` must be a pointer to a buffer that's valid for reads or writes
294 /// up to `len` bytes. The `AlertableIoFn` must be either `ReadFileEx` or `WriteFileEx`
296 /// [`ReadFileEx`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-readfileex
297 /// [`WriteFileEx`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-writefileex
298 /// [Asynchronous Procedure Call]: https://docs.microsoft.com/en-us/windows/win32/sync/asynchronous-procedure-calls
299 unsafe fn alertable_io_internal(
304 ) -> io::Result<usize> {
305 // Use "alertable I/O" to synchronize the pipe I/O.
306 // This has four steps.
308 // STEP 1: Start the asynchronous I/O operation.
309 // This simply calls either `ReadFileEx` or `WriteFileEx`,
310 // giving it a pointer to the buffer and callback function.
312 // STEP 2: Enter an alertable state.
313 // The callback set in step 1 will not be called until the thread
314 // enters an "alertable" state. This can be done using `SleepEx`.
316 // STEP 3: The callback
317 // Once the I/O is complete and the thread is in an alertable state,
318 // the callback will be run on the same thread as the call to
319 // `ReadFileEx` or `WriteFileEx` done in step 1.
320 // In the callback we simply set the result of the async operation.
322 // STEP 4: Return the result.
323 // At this point we'll have a result from the callback function
324 // and can simply return it. Note that we must not return earlier,
325 // while the I/O is still in progress.
327 // The result that will be set from the asynchronous callback.
328 let mut async_result: Option<AsyncResult> = None;
334 // STEP 3: The callback.
335 unsafe extern "system" fn callback(
337 dwNumberOfBytesTransferred: u32,
338 lpOverlapped: *mut c::OVERLAPPED,
340 // Set `async_result` using a pointer smuggled through `hEvent`.
342 AsyncResult { error: dwErrorCode, transferred: dwNumberOfBytesTransferred };
343 *(*lpOverlapped).hEvent.cast::<Option<AsyncResult>>() = Some(result);
346 // STEP 1: Start the I/O operation.
347 let mut overlapped: c::OVERLAPPED = crate::mem::zeroed();
348 // `hEvent` is unused by `ReadFileEx` and `WriteFileEx`.
349 // Therefore the documentation suggests using it to smuggle a pointer to the callback.
350 overlapped.hEvent = &mut async_result as *mut _ as *mut _;
352 // Asynchronous read of the pipe.
353 // If successful, `callback` will be called once it completes.
354 let result = io(self.inner.as_handle(), buf, len, &mut overlapped, callback);
355 if result == c::FALSE {
356 // We can return here because the call failed.
357 // After this we must not return until the I/O completes.
358 return Err(io::Error::last_os_error());
361 // Wait indefinitely for the result.
363 // STEP 2: Enter an alertable state.
364 // The second parameter of `SleepEx` is used to make this sleep alertable.
365 c::SleepEx(c::INFINITE, c::TRUE);
366 if let Some(result) = async_result {
370 // STEP 4: Return the result.
371 // `async_result` is always `Some` at this point
373 c::ERROR_SUCCESS => Ok(result.transferred as usize),
374 error => Err(io::Error::from_raw_os_error(error as _)),
379 pub fn read2(p1: AnonPipe, v1: &mut Vec<u8>, p2: AnonPipe, v2: &mut Vec<u8>) -> io::Result<()> {
380 let p1 = p1.into_handle();
381 let p2 = p2.into_handle();
383 let mut p1 = AsyncPipe::new(p1, v1)?;
384 let mut p2 = AsyncPipe::new(p2, v2)?;
385 let objs = [p1.event.as_raw_handle(), p2.event.as_raw_handle()];
387 // In a loop we wait for either pipe's scheduled read operation to complete.
388 // If the operation completes with 0 bytes, that means EOF was reached, in
389 // which case we just finish out the other pipe entirely.
391 // Note that overlapped I/O is in general super unsafe because we have to
392 // be careful to ensure that all pointers in play are valid for the entire
393 // duration of the I/O operation (where tons of operations can also fail).
394 // The destructor for `AsyncPipe` ends up taking care of most of this.
396 let res = unsafe { c::WaitForMultipleObjects(2, objs.as_ptr(), c::FALSE, c::INFINITE) };
397 if res == c::WAIT_OBJECT_0 {
398 if !p1.result()? || !p1.schedule_read()? {
401 } else if res == c::WAIT_OBJECT_0 + 1 {
402 if !p2.result()? || !p2.schedule_read()? {
406 return Err(io::Error::last_os_error());
411 struct AsyncPipe<'a> {
414 overlapped: Box<c::OVERLAPPED>, // needs a stable address
415 dst: &'a mut Vec<u8>,
419 #[derive(PartialEq, Debug)]
426 impl<'a> AsyncPipe<'a> {
427 fn new(pipe: Handle, dst: &'a mut Vec<u8>) -> io::Result<AsyncPipe<'a>> {
428 // Create an event which we'll use to coordinate our overlapped
429 // operations, this event will be used in WaitForMultipleObjects
430 // and passed as part of the OVERLAPPED handle.
432 // Note that we do a somewhat clever thing here by flagging the
433 // event as being manually reset and setting it initially to the
434 // signaled state. This means that we'll naturally fall through the
435 // WaitForMultipleObjects call above for pipes created initially,
436 // and the only time an even will go back to "unset" will be once an
437 // I/O operation is successfully scheduled (what we want).
438 let event = Handle::new_event(true, true)?;
439 let mut overlapped: Box<c::OVERLAPPED> = unsafe { Box::new(mem::zeroed()) };
440 overlapped.hEvent = event.as_raw_handle();
441 Ok(AsyncPipe { pipe, overlapped, event, dst, state: State::NotReading })
444 /// Executes an overlapped read operation.
446 /// Must not currently be reading, and returns whether the pipe is currently
447 /// at EOF or not. If the pipe is not at EOF then `result()` must be called
448 /// to complete the read later on (may block), but if the pipe is at EOF
449 /// then `result()` should not be called as it will just block forever.
450 fn schedule_read(&mut self) -> io::Result<bool> {
451 assert_eq!(self.state, State::NotReading);
453 let slice = slice_to_end(self.dst);
454 self.pipe.read_overlapped(slice, &mut *self.overlapped)?
457 // If this read finished immediately then our overlapped event will
458 // remain signaled (it was signaled coming in here) and we'll progress
459 // down to the method below.
461 // Otherwise the I/O operation is scheduled and the system set our event
462 // to not signaled, so we flag ourselves into the reading state and move
464 self.state = match amt {
465 Some(0) => return Ok(false),
466 Some(amt) => State::Read(amt),
467 None => State::Reading,
472 /// Wait for the result of the overlapped operation previously executed.
474 /// Takes a parameter `wait` which indicates if this pipe is currently being
475 /// read whether the function should block waiting for the read to complete.
479 /// * `true` - finished any pending read and the pipe is not at EOF (keep
481 /// * `false` - finished any pending read and pipe is at EOF (stop issuing
483 fn result(&mut self) -> io::Result<bool> {
484 let amt = match self.state {
485 State::NotReading => return Ok(true),
486 State::Reading => self.pipe.overlapped_result(&mut *self.overlapped, true)?,
487 State::Read(amt) => amt,
489 self.state = State::NotReading;
491 let len = self.dst.len();
492 self.dst.set_len(len + amt);
497 /// Finishes out reading this pipe entirely.
499 /// Waits for any pending and schedule read, and then calls `read_to_end`
500 /// if necessary to read all the remaining information.
501 fn finish(&mut self) -> io::Result<()> {
502 while self.result()? && self.schedule_read()? {
509 impl<'a> Drop for AsyncPipe<'a> {
516 // If we have a pending read operation, then we have to make sure that
517 // it's *done* before we actually drop this type. The kernel requires
518 // that the `OVERLAPPED` and buffer pointers are valid for the entire
521 // To do that, we call `CancelIo` to cancel any pending operation, and
522 // if that succeeds we wait for the overlapped result.
524 // If anything here fails, there's not really much we can do, so we leak
525 // the buffer/OVERLAPPED pointers to ensure we're at least memory safe.
526 if self.pipe.cancel_io().is_err() || self.result().is_err() {
527 let buf = mem::take(self.dst);
528 let overlapped = Box::new(unsafe { mem::zeroed() });
529 let overlapped = mem::replace(&mut self.overlapped, overlapped);
530 mem::forget((buf, overlapped));
535 unsafe fn slice_to_end(v: &mut Vec<u8>) -> &mut [u8] {
536 if v.capacity() == 0 {
539 if v.capacity() == v.len() {
542 slice::from_raw_parts_mut(v.as_mut_ptr().add(v.len()), v.capacity() - v.len())