]> git.lizzy.rs Git - rust.git/blob - src/tools/compiletest/src/read2.rs
Merge commit '3c7e7dbc1583a0b06df5bd7623dd354a4debd23d' into clippyup
[rust.git] / src / tools / compiletest / src / read2.rs
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.
3
4 #[cfg(test)]
5 mod tests;
6
7 pub use self::imp::read2;
8 use std::io::{self, Write};
9 use std::mem::replace;
10 use std::process::{Child, Output};
11
12 pub fn read2_abbreviated(mut child: Child, filter_paths_from_len: &[String]) -> io::Result<Output> {
13     let mut stdout = ProcOutput::new();
14     let mut stderr = ProcOutput::new();
15
16     drop(child.stdin.take());
17     read2(
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, filter_paths_from_len);
22             data.clear();
23         },
24     )?;
25     let status = child.wait()?;
26
27     Ok(Output { status, stdout: stdout.into_bytes(), stderr: stderr.into_bytes() })
28 }
29
30 const HEAD_LEN: usize = 160 * 1024;
31 const TAIL_LEN: usize = 256 * 1024;
32
33 // Whenever a path is filtered when counting the length of the output, we need to add some
34 // placeholder length to ensure a compiler emitting only filtered paths doesn't cause a OOM.
35 //
36 // 32 was chosen semi-arbitrarily: it was the highest power of two that still allowed the test
37 // suite to pass at the moment of implementing path filtering.
38 const FILTERED_PATHS_PLACEHOLDER_LEN: usize = 32;
39
40 enum ProcOutput {
41     Full { bytes: Vec<u8>, filtered_len: usize },
42     Abbreviated { head: Vec<u8>, skipped: usize, tail: Box<[u8]> },
43 }
44
45 impl ProcOutput {
46     fn new() -> Self {
47         ProcOutput::Full { bytes: Vec::new(), filtered_len: 0 }
48     }
49
50     fn extend(&mut self, data: &[u8], filter_paths_from_len: &[String]) {
51         let new_self = match *self {
52             ProcOutput::Full { ref mut bytes, ref mut filtered_len } => {
53                 let old_len = bytes.len();
54                 bytes.extend_from_slice(data);
55                 *filtered_len += data.len();
56
57                 // We had problems in the past with tests failing only in some environments,
58                 // due to the length of the base path pushing the output size over the limit.
59                 //
60                 // To make those failures deterministic across all environments we ignore known
61                 // paths when calculating the string length, while still including the full
62                 // path in the output. This could result in some output being larger than the
63                 // threshold, but it's better than having nondeterministic failures.
64                 //
65                 // The compiler emitting only excluded strings is addressed by adding a
66                 // placeholder size for each excluded segment, which will eventually reach
67                 // the configured threshold.
68                 for path in filter_paths_from_len {
69                     let path_bytes = path.as_bytes();
70                     // We start matching `path_bytes - 1` into the previously loaded data,
71                     // to account for the fact a path_bytes might be included across multiple
72                     // `extend` calls. Starting from `- 1` avoids double-counting paths.
73                     let matches = (&bytes[(old_len.saturating_sub(path_bytes.len() - 1))..])
74                         .windows(path_bytes.len())
75                         .filter(|window| window == &path_bytes)
76                         .count();
77                     *filtered_len -= matches * path_bytes.len();
78
79                     // We can't just remove the length of the filtered path from the output lenght,
80                     // otherwise a compiler emitting only filtered paths would OOM compiletest. Add
81                     // a fixed placeholder length for each path to prevent that.
82                     *filtered_len += matches * FILTERED_PATHS_PLACEHOLDER_LEN;
83                 }
84
85                 let new_len = bytes.len();
86                 if *filtered_len <= HEAD_LEN + TAIL_LEN {
87                     return;
88                 }
89
90                 let mut head = replace(bytes, Vec::new());
91                 let mut middle = head.split_off(HEAD_LEN);
92                 let tail = middle.split_off(middle.len() - TAIL_LEN).into_boxed_slice();
93                 let skipped = new_len - HEAD_LEN - TAIL_LEN;
94                 ProcOutput::Abbreviated { head, skipped, tail }
95             }
96             ProcOutput::Abbreviated { ref mut skipped, ref mut tail, .. } => {
97                 *skipped += data.len();
98                 if data.len() <= TAIL_LEN {
99                     tail[..data.len()].copy_from_slice(data);
100                     tail.rotate_left(data.len());
101                 } else {
102                     tail.copy_from_slice(&data[(data.len() - TAIL_LEN)..]);
103                 }
104                 return;
105             }
106         };
107         *self = new_self;
108     }
109
110     fn into_bytes(self) -> Vec<u8> {
111         match self {
112             ProcOutput::Full { bytes, .. } => bytes,
113             ProcOutput::Abbreviated { mut head, skipped, tail } => {
114                 write!(&mut head, "\n\n<<<<<< SKIPPED {} BYTES >>>>>>\n\n", skipped).unwrap();
115                 head.extend_from_slice(&tail);
116                 head
117             }
118         }
119     }
120 }
121
122 #[cfg(not(any(unix, windows)))]
123 mod imp {
124     use std::io::{self, Read};
125     use std::process::{ChildStderr, ChildStdout};
126
127     pub fn read2(
128         out_pipe: ChildStdout,
129         err_pipe: ChildStderr,
130         data: &mut dyn FnMut(bool, &mut Vec<u8>, bool),
131     ) -> io::Result<()> {
132         let mut buffer = Vec::new();
133         out_pipe.read_to_end(&mut buffer)?;
134         data(true, &mut buffer, true);
135         buffer.clear();
136         err_pipe.read_to_end(&mut buffer)?;
137         data(false, &mut buffer, true);
138         Ok(())
139     }
140 }
141
142 #[cfg(unix)]
143 mod imp {
144     use std::io;
145     use std::io::prelude::*;
146     use std::mem;
147     use std::os::unix::prelude::*;
148     use std::process::{ChildStderr, ChildStdout};
149
150     pub fn read2(
151         mut out_pipe: ChildStdout,
152         mut err_pipe: ChildStderr,
153         data: &mut dyn FnMut(bool, &mut Vec<u8>, bool),
154     ) -> io::Result<()> {
155         unsafe {
156             libc::fcntl(out_pipe.as_raw_fd(), libc::F_SETFL, libc::O_NONBLOCK);
157             libc::fcntl(err_pipe.as_raw_fd(), libc::F_SETFL, libc::O_NONBLOCK);
158         }
159
160         let mut out_done = false;
161         let mut err_done = false;
162         let mut out = Vec::new();
163         let mut err = Vec::new();
164
165         let mut fds: [libc::pollfd; 2] = unsafe { mem::zeroed() };
166         fds[0].fd = out_pipe.as_raw_fd();
167         fds[0].events = libc::POLLIN;
168         fds[1].fd = err_pipe.as_raw_fd();
169         fds[1].events = libc::POLLIN;
170         let mut nfds = 2;
171         let mut errfd = 1;
172
173         while nfds > 0 {
174             // wait for either pipe to become readable using `select`
175             let r = unsafe { libc::poll(fds.as_mut_ptr(), nfds, -1) };
176             if r == -1 {
177                 let err = io::Error::last_os_error();
178                 if err.kind() == io::ErrorKind::Interrupted {
179                     continue;
180                 }
181                 return Err(err);
182             }
183
184             // Read as much as we can from each pipe, ignoring EWOULDBLOCK or
185             // EAGAIN. If we hit EOF, then this will happen because the underlying
186             // reader will return Ok(0), in which case we'll see `Ok` ourselves. In
187             // this case we flip the other fd back into blocking mode and read
188             // whatever's leftover on that file descriptor.
189             let handle = |res: io::Result<_>| match res {
190                 Ok(_) => Ok(true),
191                 Err(e) => {
192                     if e.kind() == io::ErrorKind::WouldBlock {
193                         Ok(false)
194                     } else {
195                         Err(e)
196                     }
197                 }
198             };
199             if !err_done && fds[errfd].revents != 0 && handle(err_pipe.read_to_end(&mut err))? {
200                 err_done = true;
201                 nfds -= 1;
202             }
203             data(false, &mut err, err_done);
204             if !out_done && fds[0].revents != 0 && handle(out_pipe.read_to_end(&mut out))? {
205                 out_done = true;
206                 fds[0].fd = err_pipe.as_raw_fd();
207                 errfd = 0;
208                 nfds -= 1;
209             }
210             data(true, &mut out, out_done);
211         }
212         Ok(())
213     }
214 }
215
216 #[cfg(windows)]
217 mod imp {
218     use std::io;
219     use std::os::windows::prelude::*;
220     use std::process::{ChildStderr, ChildStdout};
221     use std::slice;
222
223     use miow::iocp::{CompletionPort, CompletionStatus};
224     use miow::pipe::NamedPipe;
225     use miow::Overlapped;
226     use winapi::shared::winerror::ERROR_BROKEN_PIPE;
227
228     struct Pipe<'a> {
229         dst: &'a mut Vec<u8>,
230         overlapped: Overlapped,
231         pipe: NamedPipe,
232         done: bool,
233     }
234
235     pub fn read2(
236         out_pipe: ChildStdout,
237         err_pipe: ChildStderr,
238         data: &mut dyn FnMut(bool, &mut Vec<u8>, bool),
239     ) -> io::Result<()> {
240         let mut out = Vec::new();
241         let mut err = Vec::new();
242
243         let port = CompletionPort::new(1)?;
244         port.add_handle(0, &out_pipe)?;
245         port.add_handle(1, &err_pipe)?;
246
247         unsafe {
248             let mut out_pipe = Pipe::new(out_pipe, &mut out);
249             let mut err_pipe = Pipe::new(err_pipe, &mut err);
250
251             out_pipe.read()?;
252             err_pipe.read()?;
253
254             let mut status = [CompletionStatus::zero(), CompletionStatus::zero()];
255
256             while !out_pipe.done || !err_pipe.done {
257                 for status in port.get_many(&mut status, None)? {
258                     if status.token() == 0 {
259                         out_pipe.complete(status);
260                         data(true, out_pipe.dst, out_pipe.done);
261                         out_pipe.read()?;
262                     } else {
263                         err_pipe.complete(status);
264                         data(false, err_pipe.dst, err_pipe.done);
265                         err_pipe.read()?;
266                     }
267                 }
268             }
269
270             Ok(())
271         }
272     }
273
274     impl<'a> Pipe<'a> {
275         unsafe fn new<P: IntoRawHandle>(p: P, dst: &'a mut Vec<u8>) -> Pipe<'a> {
276             Pipe {
277                 dst: dst,
278                 pipe: NamedPipe::from_raw_handle(p.into_raw_handle()),
279                 overlapped: Overlapped::zero(),
280                 done: false,
281             }
282         }
283
284         unsafe fn read(&mut self) -> io::Result<()> {
285             let dst = slice_to_end(self.dst);
286             match self.pipe.read_overlapped(dst, self.overlapped.raw()) {
287                 Ok(_) => Ok(()),
288                 Err(e) => {
289                     if e.raw_os_error() == Some(ERROR_BROKEN_PIPE as i32) {
290                         self.done = true;
291                         Ok(())
292                     } else {
293                         Err(e)
294                     }
295                 }
296             }
297         }
298
299         unsafe fn complete(&mut self, status: &CompletionStatus) {
300             let prev = self.dst.len();
301             self.dst.set_len(prev + status.bytes_transferred() as usize);
302             if status.bytes_transferred() == 0 {
303                 self.done = true;
304             }
305         }
306     }
307
308     unsafe fn slice_to_end(v: &mut Vec<u8>) -> &mut [u8] {
309         if v.capacity() == 0 {
310             v.reserve(16);
311         }
312         if v.capacity() == v.len() {
313             v.reserve(1);
314         }
315         slice::from_raw_parts_mut(v.as_mut_ptr().offset(v.len() as isize), v.capacity() - v.len())
316     }
317 }