std\sys\pal\windows/pipe.rs
1use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut};
2use crate::ops::Neg;
3use crate::os::windows::prelude::*;
4use crate::sys::api::wide_str;
5use crate::sys::c;
6use crate::sys::handle::Handle;
7use crate::sys_common::{FromInner, IntoInner};
8use crate::{mem, ptr};
9
10////////////////////////////////////////////////////////////////////////////////
11// Anonymous pipes
12////////////////////////////////////////////////////////////////////////////////
13
14pub struct AnonPipe {
15 inner: Handle,
16}
17
18impl IntoInner<Handle> for AnonPipe {
19 fn into_inner(self) -> Handle {
20 self.inner
21 }
22}
23
24impl FromInner<Handle> for AnonPipe {
25 fn from_inner(inner: Handle) -> AnonPipe {
26 Self { inner }
27 }
28}
29
30pub struct Pipes {
31 pub ours: AnonPipe,
32 pub theirs: AnonPipe,
33}
34
35/// Although this looks similar to `anon_pipe` in the Unix module it's actually
36/// subtly different. Here we'll return two pipes in the `Pipes` return value,
37/// but one is intended for "us" where as the other is intended for "someone
38/// else".
39///
40/// Currently the only use case for this function is pipes for stdio on
41/// processes in the standard library, so "ours" is the one that'll stay in our
42/// process whereas "theirs" will be inherited to a child.
43///
44/// The ours/theirs pipes are *not* specifically readable or writable. Each
45/// one only supports a read or a write, but which is which depends on the
46/// boolean flag given. If `ours_readable` is `true`, then `ours` is readable and
47/// `theirs` is writable. Conversely, if `ours_readable` is `false`, then `ours`
48/// is writable and `theirs` is readable.
49///
50/// Also note that the `ours` pipe is always a handle opened up in overlapped
51/// mode. This means that technically speaking it should only ever be used
52/// with `OVERLAPPED` instances, but also works out ok if it's only ever used
53/// once at a time (which we do indeed guarantee).
54pub fn anon_pipe(ours_readable: bool, their_handle_inheritable: bool) -> io::Result<Pipes> {
55 // A 64kb pipe capacity is the same as a typical Linux default.
56 const PIPE_BUFFER_CAPACITY: u32 = 64 * 1024;
57
58 // Note that we specifically do *not* use `CreatePipe` here because
59 // unfortunately the anonymous pipes returned do not support overlapped
60 // operations. Instead, we use `NtCreateNamedPipeFile` to create the
61 // anonymous pipe with overlapped support.
62 //
63 // Once we do this, we connect to it via `NtOpenFile`, and then
64 // we return those reader/writer halves. Note that the `ours` pipe return
65 // value is always the named pipe, whereas `theirs` is just the normal file.
66 // This should hopefully shield us from child processes which assume their
67 // stdout is a named pipe, which would indeed be odd!
68 unsafe {
69 let mut io_status = c::IO_STATUS_BLOCK::default();
70 let mut object_attributes = c::OBJECT_ATTRIBUTES::default();
71 object_attributes.Length = size_of::<c::OBJECT_ATTRIBUTES>() as u32;
72
73 // Open a handle to the pipe filesystem (`\??\PIPE\`).
74 // This will be used when creating a new annon pipe.
75 let pipe_fs = {
76 static PIPE_PATH: [u16; 10] = *wide_str!(r"\??\PIPE\");
77 let path = c::UNICODE_STRING::from_ref(&PIPE_PATH[..PIPE_PATH.len() - 1]);
78 object_attributes.ObjectName = &path;
79 let mut pipe_fs = ptr::null_mut();
80 let status = c::NtOpenFile(
81 &mut pipe_fs,
82 c::SYNCHRONIZE | c::GENERIC_READ,
83 &object_attributes,
84 &mut io_status,
85 c::FILE_SHARE_READ | c::FILE_SHARE_WRITE,
86 c::FILE_SYNCHRONOUS_IO_NONALERT, // synchronous access
87 );
88 if c::nt_success(status) {
89 Handle::from_raw_handle(pipe_fs)
90 } else {
91 return Err(io::Error::from_raw_os_error(c::RtlNtStatusToDosError(status) as i32));
92 }
93 };
94
95 // From now on we're using handles instead of paths to create and open pipes.
96 // So set the `ObjectName` to a zero length string.
97 let empty = c::UNICODE_STRING::default();
98 object_attributes.ObjectName = ∅
99
100 // Create our side of the pipe for async access.
101 let ours = {
102 // Use the pipe filesystem as the root directory.
103 // With no name provided, an anonymous pipe will be created.
104 object_attributes.RootDirectory = pipe_fs.as_raw_handle();
105
106 // A negative timeout value is a relative time (rather than an absolute time).
107 // The time is given in 100's of nanoseconds so this is 50 milliseconds.
108 // This value was chosen to be consistent with the default timeout set by `CreateNamedPipeW`
109 // See: https://learn.microsoft.com/en-us/windows/win32/api/namedpipeapi/nf-namedpipeapi-createnamedpipew
110 let timeout = (50_i64 * 10000).neg() as u64;
111
112 let mut ours = ptr::null_mut();
113 let status = c::NtCreateNamedPipeFile(
114 &mut ours,
115 c::SYNCHRONIZE | if ours_readable { c::GENERIC_READ } else { c::GENERIC_WRITE },
116 &object_attributes,
117 &mut io_status,
118 if ours_readable { c::FILE_SHARE_WRITE } else { c::FILE_SHARE_READ },
119 c::FILE_CREATE,
120 0,
121 c::FILE_PIPE_BYTE_STREAM_TYPE,
122 c::FILE_PIPE_BYTE_STREAM_MODE,
123 c::FILE_PIPE_QUEUE_OPERATION,
124 // only allow one client pipe
125 1,
126 PIPE_BUFFER_CAPACITY,
127 PIPE_BUFFER_CAPACITY,
128 &timeout,
129 );
130 if c::nt_success(status) {
131 Handle::from_raw_handle(ours)
132 } else {
133 return Err(io::Error::from_raw_os_error(c::RtlNtStatusToDosError(status) as i32));
134 }
135 };
136
137 // Open their side of the pipe for synchronous access.
138 let theirs = {
139 // We can reopen the anonymous pipe without a name by setting
140 // RootDirectory to the pipe handle and not setting a path name,
141 object_attributes.RootDirectory = ours.as_raw_handle();
142
143 if their_handle_inheritable {
144 object_attributes.Attributes |= c::OBJ_INHERIT;
145 }
146 let mut theirs = ptr::null_mut();
147 let status = c::NtOpenFile(
148 &mut theirs,
149 c::SYNCHRONIZE
150 | if ours_readable {
151 c::GENERIC_WRITE | c::FILE_READ_ATTRIBUTES
152 } else {
153 c::GENERIC_READ
154 },
155 &object_attributes,
156 &mut io_status,
157 0,
158 c::FILE_NON_DIRECTORY_FILE | c::FILE_SYNCHRONOUS_IO_NONALERT,
159 );
160 if c::nt_success(status) {
161 Handle::from_raw_handle(theirs)
162 } else {
163 return Err(io::Error::from_raw_os_error(c::RtlNtStatusToDosError(status) as i32));
164 }
165 };
166
167 Ok(Pipes { ours: AnonPipe { inner: ours }, theirs: AnonPipe { inner: theirs } })
168 }
169}
170
171/// Takes an asynchronous source pipe and returns a synchronous pipe suitable
172/// for sending to a child process.
173///
174/// This is achieved by creating a new set of pipes and spawning a thread that
175/// relays messages between the source and the synchronous pipe.
176pub fn spawn_pipe_relay(
177 source: &AnonPipe,
178 ours_readable: bool,
179 their_handle_inheritable: bool,
180) -> io::Result<AnonPipe> {
181 // We need this handle to live for the lifetime of the thread spawned below.
182 let source = source.try_clone()?;
183
184 // create a new pair of anon pipes.
185 let Pipes { theirs, ours } = anon_pipe(ours_readable, their_handle_inheritable)?;
186
187 // Spawn a thread that passes messages from one pipe to the other.
188 // Any errors will simply cause the thread to exit.
189 let (reader, writer) = if ours_readable { (ours, source) } else { (source, ours) };
190 crate::thread::spawn(move || {
191 let mut buf = [0_u8; 4096];
192 'reader: while let Ok(len) = reader.read(&mut buf) {
193 if len == 0 {
194 break;
195 }
196 let mut start = 0;
197 while let Ok(written) = writer.write(&buf[start..len]) {
198 start += written;
199 if start == len {
200 continue 'reader;
201 }
202 }
203 break;
204 }
205 });
206
207 // Return the pipe that should be sent to the child process.
208 Ok(theirs)
209}
210
211impl AnonPipe {
212 pub fn handle(&self) -> &Handle {
213 &self.inner
214 }
215 pub fn into_handle(self) -> Handle {
216 self.inner
217 }
218
219 pub fn try_clone(&self) -> io::Result<Self> {
220 self.inner.duplicate(0, false, c::DUPLICATE_SAME_ACCESS).map(|inner| AnonPipe { inner })
221 }
222
223 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
224 let result = unsafe {
225 let len = crate::cmp::min(buf.len(), u32::MAX as usize) as u32;
226 let ptr = buf.as_mut_ptr();
227 self.alertable_io_internal(|overlapped, callback| {
228 c::ReadFileEx(self.inner.as_raw_handle(), ptr, len, overlapped, callback)
229 })
230 };
231
232 match result {
233 // The special treatment of BrokenPipe is to deal with Windows
234 // pipe semantics, which yields this error when *reading* from
235 // a pipe after the other end has closed; we interpret that as
236 // EOF on the pipe.
237 Err(ref e) if e.kind() == io::ErrorKind::BrokenPipe => Ok(0),
238 _ => result,
239 }
240 }
241
242 pub fn read_buf(&self, mut buf: BorrowedCursor<'_>) -> io::Result<()> {
243 let result = unsafe {
244 let len = crate::cmp::min(buf.capacity(), u32::MAX as usize) as u32;
245 let ptr = buf.as_mut().as_mut_ptr().cast::<u8>();
246 self.alertable_io_internal(|overlapped, callback| {
247 c::ReadFileEx(self.inner.as_raw_handle(), ptr, len, overlapped, callback)
248 })
249 };
250
251 match result {
252 // The special treatment of BrokenPipe is to deal with Windows
253 // pipe semantics, which yields this error when *reading* from
254 // a pipe after the other end has closed; we interpret that as
255 // EOF on the pipe.
256 Err(ref e) if e.kind() == io::ErrorKind::BrokenPipe => Ok(()),
257 Err(e) => Err(e),
258 Ok(n) => {
259 unsafe {
260 buf.advance_unchecked(n);
261 }
262 Ok(())
263 }
264 }
265 }
266
267 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
268 self.inner.read_vectored(bufs)
269 }
270
271 #[inline]
272 pub fn is_read_vectored(&self) -> bool {
273 self.inner.is_read_vectored()
274 }
275
276 pub fn read_to_end(&self, buf: &mut Vec<u8>) -> io::Result<usize> {
277 self.handle().read_to_end(buf)
278 }
279
280 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
281 unsafe {
282 let len = crate::cmp::min(buf.len(), u32::MAX as usize) as u32;
283 self.alertable_io_internal(|overlapped, callback| {
284 c::WriteFileEx(self.inner.as_raw_handle(), buf.as_ptr(), len, overlapped, callback)
285 })
286 }
287 }
288
289 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
290 self.inner.write_vectored(bufs)
291 }
292
293 #[inline]
294 pub fn is_write_vectored(&self) -> bool {
295 self.inner.is_write_vectored()
296 }
297
298 /// Synchronizes asynchronous reads or writes using our anonymous pipe.
299 ///
300 /// This is a wrapper around [`ReadFileEx`] or [`WriteFileEx`] that uses
301 /// [Asynchronous Procedure Call] (APC) to synchronize reads or writes.
302 ///
303 /// Note: This should not be used for handles we don't create.
304 ///
305 /// # Safety
306 ///
307 /// `buf` must be a pointer to a buffer that's valid for reads or writes
308 /// up to `len` bytes. The `AlertableIoFn` must be either `ReadFileEx` or `WriteFileEx`
309 ///
310 /// [`ReadFileEx`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-readfileex
311 /// [`WriteFileEx`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-writefileex
312 /// [Asynchronous Procedure Call]: https://docs.microsoft.com/en-us/windows/win32/sync/asynchronous-procedure-calls
313 unsafe fn alertable_io_internal(
314 &self,
315 io: impl FnOnce(&mut c::OVERLAPPED, c::LPOVERLAPPED_COMPLETION_ROUTINE) -> c::BOOL,
316 ) -> io::Result<usize> {
317 // Use "alertable I/O" to synchronize the pipe I/O.
318 // This has four steps.
319 //
320 // STEP 1: Start the asynchronous I/O operation.
321 // This simply calls either `ReadFileEx` or `WriteFileEx`,
322 // giving it a pointer to the buffer and callback function.
323 //
324 // STEP 2: Enter an alertable state.
325 // The callback set in step 1 will not be called until the thread
326 // enters an "alertable" state. This can be done using `SleepEx`.
327 //
328 // STEP 3: The callback
329 // Once the I/O is complete and the thread is in an alertable state,
330 // the callback will be run on the same thread as the call to
331 // `ReadFileEx` or `WriteFileEx` done in step 1.
332 // In the callback we simply set the result of the async operation.
333 //
334 // STEP 4: Return the result.
335 // At this point we'll have a result from the callback function
336 // and can simply return it. Note that we must not return earlier,
337 // while the I/O is still in progress.
338
339 // The result that will be set from the asynchronous callback.
340 let mut async_result: Option<AsyncResult> = None;
341 struct AsyncResult {
342 error: u32,
343 transferred: u32,
344 }
345
346 // STEP 3: The callback.
347 unsafe extern "system" fn callback(
348 dwErrorCode: u32,
349 dwNumberOfBytesTransferred: u32,
350 lpOverlapped: *mut c::OVERLAPPED,
351 ) {
352 // Set `async_result` using a pointer smuggled through `hEvent`.
353 // SAFETY:
354 // At this point, the OVERLAPPED struct will have been written to by the OS,
355 // except for our `hEvent` field which we set to a valid AsyncResult pointer (see below)
356 unsafe {
357 let result =
358 AsyncResult { error: dwErrorCode, transferred: dwNumberOfBytesTransferred };
359 *(*lpOverlapped).hEvent.cast::<Option<AsyncResult>>() = Some(result);
360 }
361 }
362
363 // STEP 1: Start the I/O operation.
364 let mut overlapped: c::OVERLAPPED = unsafe { crate::mem::zeroed() };
365 // `hEvent` is unused by `ReadFileEx` and `WriteFileEx`.
366 // Therefore the documentation suggests using it to smuggle a pointer to the callback.
367 overlapped.hEvent = (&raw mut async_result) as *mut _;
368
369 // Asynchronous read of the pipe.
370 // If successful, `callback` will be called once it completes.
371 let result = io(&mut overlapped, Some(callback));
372 if result == c::FALSE {
373 // We can return here because the call failed.
374 // After this we must not return until the I/O completes.
375 return Err(io::Error::last_os_error());
376 }
377
378 // Wait indefinitely for the result.
379 let result = loop {
380 // STEP 2: Enter an alertable state.
381 // The second parameter of `SleepEx` is used to make this sleep alertable.
382 unsafe { c::SleepEx(c::INFINITE, c::TRUE) };
383 if let Some(result) = async_result {
384 break result;
385 }
386 };
387 // STEP 4: Return the result.
388 // `async_result` is always `Some` at this point
389 match result.error {
390 c::ERROR_SUCCESS => Ok(result.transferred as usize),
391 error => Err(io::Error::from_raw_os_error(error as _)),
392 }
393 }
394}
395
396pub fn read2(p1: AnonPipe, v1: &mut Vec<u8>, p2: AnonPipe, v2: &mut Vec<u8>) -> io::Result<()> {
397 let p1 = p1.into_handle();
398 let p2 = p2.into_handle();
399
400 let mut p1 = AsyncPipe::new(p1, v1)?;
401 let mut p2 = AsyncPipe::new(p2, v2)?;
402 let objs = [p1.event.as_raw_handle(), p2.event.as_raw_handle()];
403
404 // In a loop we wait for either pipe's scheduled read operation to complete.
405 // If the operation completes with 0 bytes, that means EOF was reached, in
406 // which case we just finish out the other pipe entirely.
407 //
408 // Note that overlapped I/O is in general super unsafe because we have to
409 // be careful to ensure that all pointers in play are valid for the entire
410 // duration of the I/O operation (where tons of operations can also fail).
411 // The destructor for `AsyncPipe` ends up taking care of most of this.
412 loop {
413 let res = unsafe { c::WaitForMultipleObjects(2, objs.as_ptr(), c::FALSE, c::INFINITE) };
414 if res == c::WAIT_OBJECT_0 {
415 if !p1.result()? || !p1.schedule_read()? {
416 return p2.finish();
417 }
418 } else if res == c::WAIT_OBJECT_0 + 1 {
419 if !p2.result()? || !p2.schedule_read()? {
420 return p1.finish();
421 }
422 } else {
423 return Err(io::Error::last_os_error());
424 }
425 }
426}
427
428struct AsyncPipe<'a> {
429 pipe: Handle,
430 event: Handle,
431 overlapped: Box<c::OVERLAPPED>, // needs a stable address
432 dst: &'a mut Vec<u8>,
433 state: State,
434}
435
436#[derive(PartialEq, Debug)]
437enum State {
438 NotReading,
439 Reading,
440 Read(usize),
441}
442
443impl<'a> AsyncPipe<'a> {
444 fn new(pipe: Handle, dst: &'a mut Vec<u8>) -> io::Result<AsyncPipe<'a>> {
445 // Create an event which we'll use to coordinate our overlapped
446 // operations, this event will be used in WaitForMultipleObjects
447 // and passed as part of the OVERLAPPED handle.
448 //
449 // Note that we do a somewhat clever thing here by flagging the
450 // event as being manually reset and setting it initially to the
451 // signaled state. This means that we'll naturally fall through the
452 // WaitForMultipleObjects call above for pipes created initially,
453 // and the only time an even will go back to "unset" will be once an
454 // I/O operation is successfully scheduled (what we want).
455 let event = Handle::new_event(true, true)?;
456 let mut overlapped: Box<c::OVERLAPPED> = unsafe { Box::new(mem::zeroed()) };
457 overlapped.hEvent = event.as_raw_handle();
458 Ok(AsyncPipe { pipe, overlapped, event, dst, state: State::NotReading })
459 }
460
461 /// Executes an overlapped read operation.
462 ///
463 /// Must not currently be reading, and returns whether the pipe is currently
464 /// at EOF or not. If the pipe is not at EOF then `result()` must be called
465 /// to complete the read later on (may block), but if the pipe is at EOF
466 /// then `result()` should not be called as it will just block forever.
467 fn schedule_read(&mut self) -> io::Result<bool> {
468 assert_eq!(self.state, State::NotReading);
469 let amt = unsafe {
470 if self.dst.capacity() == self.dst.len() {
471 let additional = if self.dst.capacity() == 0 { 16 } else { 1 };
472 self.dst.reserve(additional);
473 }
474 self.pipe.read_overlapped(self.dst.spare_capacity_mut(), &mut *self.overlapped)?
475 };
476
477 // If this read finished immediately then our overlapped event will
478 // remain signaled (it was signaled coming in here) and we'll progress
479 // down to the method below.
480 //
481 // Otherwise the I/O operation is scheduled and the system set our event
482 // to not signaled, so we flag ourselves into the reading state and move
483 // on.
484 self.state = match amt {
485 Some(0) => return Ok(false),
486 Some(amt) => State::Read(amt),
487 None => State::Reading,
488 };
489 Ok(true)
490 }
491
492 /// Wait for the result of the overlapped operation previously executed.
493 ///
494 /// Takes a parameter `wait` which indicates if this pipe is currently being
495 /// read whether the function should block waiting for the read to complete.
496 ///
497 /// Returns values:
498 ///
499 /// * `true` - finished any pending read and the pipe is not at EOF (keep
500 /// going)
501 /// * `false` - finished any pending read and pipe is at EOF (stop issuing
502 /// reads)
503 fn result(&mut self) -> io::Result<bool> {
504 let amt = match self.state {
505 State::NotReading => return Ok(true),
506 State::Reading => self.pipe.overlapped_result(&mut *self.overlapped, true)?,
507 State::Read(amt) => amt,
508 };
509 self.state = State::NotReading;
510 unsafe {
511 let len = self.dst.len();
512 self.dst.set_len(len + amt);
513 }
514 Ok(amt != 0)
515 }
516
517 /// Finishes out reading this pipe entirely.
518 ///
519 /// Waits for any pending and schedule read, and then calls `read_to_end`
520 /// if necessary to read all the remaining information.
521 fn finish(&mut self) -> io::Result<()> {
522 while self.result()? && self.schedule_read()? {
523 // ...
524 }
525 Ok(())
526 }
527}
528
529impl<'a> Drop for AsyncPipe<'a> {
530 fn drop(&mut self) {
531 match self.state {
532 State::Reading => {}
533 _ => return,
534 }
535
536 // If we have a pending read operation, then we have to make sure that
537 // it's *done* before we actually drop this type. The kernel requires
538 // that the `OVERLAPPED` and buffer pointers are valid for the entire
539 // I/O operation.
540 //
541 // To do that, we call `CancelIo` to cancel any pending operation, and
542 // if that succeeds we wait for the overlapped result.
543 //
544 // If anything here fails, there's not really much we can do, so we leak
545 // the buffer/OVERLAPPED pointers to ensure we're at least memory safe.
546 if self.pipe.cancel_io().is_err() || self.result().is_err() {
547 let buf = mem::take(self.dst);
548 let overlapped = Box::new(unsafe { mem::zeroed() });
549 let overlapped = mem::replace(&mut self.overlapped, overlapped);
550 mem::forget((buf, overlapped));
551 }
552 }
553}