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.
7 pub use self::imp::read2;
8 use std::io::{self, Write};
10 use std::process::{Child, Output};
12 pub fn read2_abbreviated(mut child: Child, exclude_from_len: &[String]) -> io::Result<Output> {
13 let mut stdout = ProcOutput::new();
14 let mut stderr = ProcOutput::new();
16 drop(child.stdin.take());
18 child.stdout.take().unwrap(),
19 child.stderr.take().unwrap(),
20 &mut |is_stdout, data, _| {
21 if is_stdout { &mut stdout } else { &mut stderr }.extend(data, exclude_from_len);
25 let status = child.wait()?;
27 Ok(Output { status, stdout: stdout.into_bytes(), stderr: stderr.into_bytes() })
30 const HEAD_LEN: usize = 160 * 1024;
31 const TAIL_LEN: usize = 256 * 1024;
32 const EXCLUDED_PLACEHOLDER_LEN: isize = 32;
35 Full { bytes: Vec<u8>, excluded_len: isize },
36 Abbreviated { head: Vec<u8>, skipped: usize, tail: Box<[u8]> },
41 ProcOutput::Full { bytes: Vec::new(), excluded_len: 0 }
44 fn extend(&mut self, data: &[u8], exclude_from_len: &[String]) {
45 let new_self = match *self {
46 ProcOutput::Full { ref mut bytes, ref mut excluded_len } => {
47 let old_len = bytes.len();
48 bytes.extend_from_slice(data);
50 // We had problems in the past with tests failing only in some environments,
51 // due to the length of the base path pushing the output size over the limit.
53 // To make those failures deterministic across all environments we ignore known
54 // paths when calculating the string length, while still including the full
55 // path in the output. This could result in some output being larger than the
56 // threshold, but it's better than having nondeterministic failures.
58 // The compiler emitting only excluded strings is addressed by adding a
59 // placeholder size for each excluded segment, which will eventually reach
60 // the configured threshold.
61 for pattern in exclude_from_len {
62 let pattern_bytes = pattern.as_bytes();
63 // We start matching `pattern_bytes - 1` into the previously loaded data,
64 // to account for the fact a pattern might be included across multiple
65 // `extend` calls. Starting from `- 1` avoids double-counting patterns.
66 let matches = (&bytes[(old_len.saturating_sub(pattern_bytes.len() - 1))..])
67 .windows(pattern_bytes.len())
68 .filter(|window| window == &pattern_bytes)
70 *excluded_len += matches as isize
71 * (EXCLUDED_PLACEHOLDER_LEN - pattern_bytes.len() as isize);
74 let new_len = bytes.len();
75 if (new_len as isize + *excluded_len) as usize <= HEAD_LEN + TAIL_LEN {
79 let mut head = replace(bytes, Vec::new());
80 let mut middle = head.split_off(HEAD_LEN);
81 let tail = middle.split_off(middle.len() - TAIL_LEN).into_boxed_slice();
82 let skipped = new_len - HEAD_LEN - TAIL_LEN;
83 ProcOutput::Abbreviated { head, skipped, tail }
85 ProcOutput::Abbreviated { ref mut skipped, ref mut tail, .. } => {
86 *skipped += data.len();
87 if data.len() <= TAIL_LEN {
88 tail[..data.len()].copy_from_slice(data);
89 tail.rotate_left(data.len());
91 tail.copy_from_slice(&data[(data.len() - TAIL_LEN)..]);
99 fn into_bytes(self) -> Vec<u8> {
101 ProcOutput::Full { bytes, .. } => bytes,
102 ProcOutput::Abbreviated { mut head, skipped, tail } => {
103 write!(&mut head, "\n\n<<<<<< SKIPPED {} BYTES >>>>>>\n\n", skipped).unwrap();
104 head.extend_from_slice(&tail);
111 #[cfg(not(any(unix, windows)))]
113 use std::io::{self, Read};
114 use std::process::{ChildStderr, ChildStdout};
117 out_pipe: ChildStdout,
118 err_pipe: ChildStderr,
119 data: &mut dyn FnMut(bool, &mut Vec<u8>, bool),
120 ) -> io::Result<()> {
121 let mut buffer = Vec::new();
122 out_pipe.read_to_end(&mut buffer)?;
123 data(true, &mut buffer, true);
125 err_pipe.read_to_end(&mut buffer)?;
126 data(false, &mut buffer, true);
134 use std::io::prelude::*;
136 use std::os::unix::prelude::*;
137 use std::process::{ChildStderr, ChildStdout};
140 mut out_pipe: ChildStdout,
141 mut err_pipe: ChildStderr,
142 data: &mut dyn FnMut(bool, &mut Vec<u8>, bool),
143 ) -> io::Result<()> {
145 libc::fcntl(out_pipe.as_raw_fd(), libc::F_SETFL, libc::O_NONBLOCK);
146 libc::fcntl(err_pipe.as_raw_fd(), libc::F_SETFL, libc::O_NONBLOCK);
149 let mut out_done = false;
150 let mut err_done = false;
151 let mut out = Vec::new();
152 let mut err = Vec::new();
154 let mut fds: [libc::pollfd; 2] = unsafe { mem::zeroed() };
155 fds[0].fd = out_pipe.as_raw_fd();
156 fds[0].events = libc::POLLIN;
157 fds[1].fd = err_pipe.as_raw_fd();
158 fds[1].events = libc::POLLIN;
163 // wait for either pipe to become readable using `select`
164 let r = unsafe { libc::poll(fds.as_mut_ptr(), nfds, -1) };
166 let err = io::Error::last_os_error();
167 if err.kind() == io::ErrorKind::Interrupted {
173 // Read as much as we can from each pipe, ignoring EWOULDBLOCK or
174 // EAGAIN. If we hit EOF, then this will happen because the underlying
175 // reader will return Ok(0), in which case we'll see `Ok` ourselves. In
176 // this case we flip the other fd back into blocking mode and read
177 // whatever's leftover on that file descriptor.
178 let handle = |res: io::Result<_>| match res {
181 if e.kind() == io::ErrorKind::WouldBlock {
188 if !err_done && fds[errfd].revents != 0 && handle(err_pipe.read_to_end(&mut err))? {
192 data(false, &mut err, err_done);
193 if !out_done && fds[0].revents != 0 && handle(out_pipe.read_to_end(&mut out))? {
195 fds[0].fd = err_pipe.as_raw_fd();
199 data(true, &mut out, out_done);
208 use std::os::windows::prelude::*;
209 use std::process::{ChildStderr, ChildStdout};
212 use miow::iocp::{CompletionPort, CompletionStatus};
213 use miow::pipe::NamedPipe;
214 use miow::Overlapped;
215 use winapi::shared::winerror::ERROR_BROKEN_PIPE;
218 dst: &'a mut Vec<u8>,
219 overlapped: Overlapped,
225 out_pipe: ChildStdout,
226 err_pipe: ChildStderr,
227 data: &mut dyn FnMut(bool, &mut Vec<u8>, bool),
228 ) -> io::Result<()> {
229 let mut out = Vec::new();
230 let mut err = Vec::new();
232 let port = CompletionPort::new(1)?;
233 port.add_handle(0, &out_pipe)?;
234 port.add_handle(1, &err_pipe)?;
237 let mut out_pipe = Pipe::new(out_pipe, &mut out);
238 let mut err_pipe = Pipe::new(err_pipe, &mut err);
243 let mut status = [CompletionStatus::zero(), CompletionStatus::zero()];
245 while !out_pipe.done || !err_pipe.done {
246 for status in port.get_many(&mut status, None)? {
247 if status.token() == 0 {
248 out_pipe.complete(status);
249 data(true, out_pipe.dst, out_pipe.done);
252 err_pipe.complete(status);
253 data(false, err_pipe.dst, err_pipe.done);
264 unsafe fn new<P: IntoRawHandle>(p: P, dst: &'a mut Vec<u8>) -> Pipe<'a> {
267 pipe: NamedPipe::from_raw_handle(p.into_raw_handle()),
268 overlapped: Overlapped::zero(),
273 unsafe fn read(&mut self) -> io::Result<()> {
274 let dst = slice_to_end(self.dst);
275 match self.pipe.read_overlapped(dst, self.overlapped.raw()) {
278 if e.raw_os_error() == Some(ERROR_BROKEN_PIPE as i32) {
288 unsafe fn complete(&mut self, status: &CompletionStatus) {
289 let prev = self.dst.len();
290 self.dst.set_len(prev + status.bytes_transferred() as usize);
291 if status.bytes_transferred() == 0 {
297 unsafe fn slice_to_end(v: &mut Vec<u8>) -> &mut [u8] {
298 if v.capacity() == 0 {
301 if v.capacity() == v.len() {
304 slice::from_raw_parts_mut(v.as_mut_ptr().offset(v.len() as isize), v.capacity() - v.len())