1 // FIXME: This is a complete copy of `cargo/src/cargo/util/read2.rs`
2 // Consider unify the read2() in libstd, cargo and this to prevent further code duplication.
4 pub use self::imp::read2;
6 use std::process::{Child, Output};
8 pub fn read2_abbreviated(mut child: Child, exclude_from_len: &[String]) -> io::Result<Output> {
10 use std::mem::replace;
12 const HEAD_LEN: usize = 160 * 1024;
13 const TAIL_LEN: usize = 256 * 1024;
16 Full { bytes: Vec<u8>, excluded_len: usize },
17 Abbreviated { head: Vec<u8>, skipped: usize, tail: Box<[u8]> },
21 fn extend(&mut self, data: &[u8], exclude_from_len: &[String]) {
22 let new_self = match *self {
23 ProcOutput::Full { ref mut bytes, ref mut excluded_len } => {
24 bytes.extend_from_slice(data);
26 // We had problems in the past with tests failing only in some environments,
27 // due to the length of the base path pushing the output size over the limit.
29 // To make those failures deterministic across all environments we ignore known
30 // paths when calculating the string length, while still including the full
31 // path in the output. This could result in some output being larger than the
32 // threshold, but it's better than having nondeterministic failures.
33 for pattern in exclude_from_len {
34 let pattern_bytes = pattern.as_bytes();
36 .windows(pattern_bytes.len())
37 .filter(|window| window == &pattern_bytes)
39 *excluded_len += matches * pattern_bytes.len();
42 let new_len = bytes.len();
43 if new_len.saturating_sub(*excluded_len) <= HEAD_LEN + TAIL_LEN {
47 let mut head = replace(bytes, Vec::new());
48 let tail = head.split_off(new_len - TAIL_LEN).into_boxed_slice();
49 let skipped = new_len - HEAD_LEN - TAIL_LEN;
50 ProcOutput::Abbreviated { head, skipped, tail }
52 ProcOutput::Abbreviated { ref mut skipped, ref mut tail, .. } => {
53 *skipped += data.len();
54 if data.len() <= TAIL_LEN {
55 tail[..data.len()].copy_from_slice(data);
56 tail.rotate_left(data.len());
58 tail.copy_from_slice(&data[(data.len() - TAIL_LEN)..]);
66 fn into_bytes(self) -> Vec<u8> {
68 ProcOutput::Full { bytes, .. } => bytes,
69 ProcOutput::Abbreviated { mut head, skipped, tail } => {
70 write!(&mut head, "\n\n<<<<<< SKIPPED {} BYTES >>>>>>\n\n", skipped).unwrap();
71 head.extend_from_slice(&tail);
78 let mut stdout = ProcOutput::Full { bytes: Vec::new(), excluded_len: 0 };
79 let mut stderr = ProcOutput::Full { bytes: Vec::new(), excluded_len: 0 };
81 drop(child.stdin.take());
83 child.stdout.take().unwrap(),
84 child.stderr.take().unwrap(),
85 &mut |is_stdout, data, _| {
86 if is_stdout { &mut stdout } else { &mut stderr }.extend(data, exclude_from_len);
90 let status = child.wait()?;
92 Ok(Output { status, stdout: stdout.into_bytes(), stderr: stderr.into_bytes() })
95 #[cfg(not(any(unix, windows)))]
97 use std::io::{self, Read};
98 use std::process::{ChildStderr, ChildStdout};
101 out_pipe: ChildStdout,
102 err_pipe: ChildStderr,
103 data: &mut dyn FnMut(bool, &mut Vec<u8>, bool),
104 ) -> io::Result<()> {
105 let mut buffer = Vec::new();
106 out_pipe.read_to_end(&mut buffer)?;
107 data(true, &mut buffer, true);
109 err_pipe.read_to_end(&mut buffer)?;
110 data(false, &mut buffer, true);
118 use std::io::prelude::*;
120 use std::os::unix::prelude::*;
121 use std::process::{ChildStderr, ChildStdout};
124 mut out_pipe: ChildStdout,
125 mut err_pipe: ChildStderr,
126 data: &mut dyn FnMut(bool, &mut Vec<u8>, bool),
127 ) -> io::Result<()> {
129 libc::fcntl(out_pipe.as_raw_fd(), libc::F_SETFL, libc::O_NONBLOCK);
130 libc::fcntl(err_pipe.as_raw_fd(), libc::F_SETFL, libc::O_NONBLOCK);
133 let mut out_done = false;
134 let mut err_done = false;
135 let mut out = Vec::new();
136 let mut err = Vec::new();
138 let mut fds: [libc::pollfd; 2] = unsafe { mem::zeroed() };
139 fds[0].fd = out_pipe.as_raw_fd();
140 fds[0].events = libc::POLLIN;
141 fds[1].fd = err_pipe.as_raw_fd();
142 fds[1].events = libc::POLLIN;
147 // wait for either pipe to become readable using `select`
148 let r = unsafe { libc::poll(fds.as_mut_ptr(), nfds, -1) };
150 let err = io::Error::last_os_error();
151 if err.kind() == io::ErrorKind::Interrupted {
157 // Read as much as we can from each pipe, ignoring EWOULDBLOCK or
158 // EAGAIN. If we hit EOF, then this will happen because the underlying
159 // reader will return Ok(0), in which case we'll see `Ok` ourselves. In
160 // this case we flip the other fd back into blocking mode and read
161 // whatever's leftover on that file descriptor.
162 let handle = |res: io::Result<_>| match res {
165 if e.kind() == io::ErrorKind::WouldBlock {
172 if !err_done && fds[errfd].revents != 0 && handle(err_pipe.read_to_end(&mut err))? {
176 data(false, &mut err, err_done);
177 if !out_done && fds[0].revents != 0 && handle(out_pipe.read_to_end(&mut out))? {
179 fds[0].fd = err_pipe.as_raw_fd();
183 data(true, &mut out, out_done);
192 use std::os::windows::prelude::*;
193 use std::process::{ChildStderr, ChildStdout};
196 use miow::iocp::{CompletionPort, CompletionStatus};
197 use miow::pipe::NamedPipe;
198 use miow::Overlapped;
199 use winapi::shared::winerror::ERROR_BROKEN_PIPE;
202 dst: &'a mut Vec<u8>,
203 overlapped: Overlapped,
209 out_pipe: ChildStdout,
210 err_pipe: ChildStderr,
211 data: &mut dyn FnMut(bool, &mut Vec<u8>, bool),
212 ) -> io::Result<()> {
213 let mut out = Vec::new();
214 let mut err = Vec::new();
216 let port = CompletionPort::new(1)?;
217 port.add_handle(0, &out_pipe)?;
218 port.add_handle(1, &err_pipe)?;
221 let mut out_pipe = Pipe::new(out_pipe, &mut out);
222 let mut err_pipe = Pipe::new(err_pipe, &mut err);
227 let mut status = [CompletionStatus::zero(), CompletionStatus::zero()];
229 while !out_pipe.done || !err_pipe.done {
230 for status in port.get_many(&mut status, None)? {
231 if status.token() == 0 {
232 out_pipe.complete(status);
233 data(true, out_pipe.dst, out_pipe.done);
236 err_pipe.complete(status);
237 data(false, err_pipe.dst, err_pipe.done);
248 unsafe fn new<P: IntoRawHandle>(p: P, dst: &'a mut Vec<u8>) -> Pipe<'a> {
251 pipe: NamedPipe::from_raw_handle(p.into_raw_handle()),
252 overlapped: Overlapped::zero(),
257 unsafe fn read(&mut self) -> io::Result<()> {
258 let dst = slice_to_end(self.dst);
259 match self.pipe.read_overlapped(dst, self.overlapped.raw()) {
262 if e.raw_os_error() == Some(ERROR_BROKEN_PIPE as i32) {
272 unsafe fn complete(&mut self, status: &CompletionStatus) {
273 let prev = self.dst.len();
274 self.dst.set_len(prev + status.bytes_transferred() as usize);
275 if status.bytes_transferred() == 0 {
281 unsafe fn slice_to_end(v: &mut Vec<u8>) -> &mut [u8] {
282 if v.capacity() == 0 {
285 if v.capacity() == v.len() {
288 slice::from_raw_parts_mut(v.as_mut_ptr().offset(v.len() as isize), v.capacity() - v.len())