]> git.lizzy.rs Git - rust.git/blob - src/tools/compiletest/src/read2.rs
add tests
[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, exclude_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, exclude_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 const EXCLUDED_PLACEHOLDER_LEN: isize = 32;
33
34 enum ProcOutput {
35     Full { bytes: Vec<u8>, excluded_len: isize },
36     Abbreviated { head: Vec<u8>, skipped: usize, tail: Box<[u8]> },
37 }
38
39 impl ProcOutput {
40     fn new() -> Self {
41         ProcOutput::Full { bytes: Vec::new(), excluded_len: 0 }
42     }
43
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);
49
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.
52                 //
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.
57                 //
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)
69                         .count();
70                     *excluded_len += matches as isize
71                         * (EXCLUDED_PLACEHOLDER_LEN - pattern_bytes.len() as isize);
72                 }
73
74                 let new_len = bytes.len();
75                 if (new_len as isize + *excluded_len) as usize <= HEAD_LEN + TAIL_LEN {
76                     return;
77                 }
78
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 }
84             }
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());
90                 } else {
91                     tail.copy_from_slice(&data[(data.len() - TAIL_LEN)..]);
92                 }
93                 return;
94             }
95         };
96         *self = new_self;
97     }
98
99     fn into_bytes(self) -> Vec<u8> {
100         match self {
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);
105                 head
106             }
107         }
108     }
109 }
110
111 #[cfg(not(any(unix, windows)))]
112 mod imp {
113     use std::io::{self, Read};
114     use std::process::{ChildStderr, ChildStdout};
115
116     pub fn read2(
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);
124         buffer.clear();
125         err_pipe.read_to_end(&mut buffer)?;
126         data(false, &mut buffer, true);
127         Ok(())
128     }
129 }
130
131 #[cfg(unix)]
132 mod imp {
133     use std::io;
134     use std::io::prelude::*;
135     use std::mem;
136     use std::os::unix::prelude::*;
137     use std::process::{ChildStderr, ChildStdout};
138
139     pub fn read2(
140         mut out_pipe: ChildStdout,
141         mut err_pipe: ChildStderr,
142         data: &mut dyn FnMut(bool, &mut Vec<u8>, bool),
143     ) -> io::Result<()> {
144         unsafe {
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);
147         }
148
149         let mut out_done = false;
150         let mut err_done = false;
151         let mut out = Vec::new();
152         let mut err = Vec::new();
153
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;
159         let mut nfds = 2;
160         let mut errfd = 1;
161
162         while nfds > 0 {
163             // wait for either pipe to become readable using `select`
164             let r = unsafe { libc::poll(fds.as_mut_ptr(), nfds, -1) };
165             if r == -1 {
166                 let err = io::Error::last_os_error();
167                 if err.kind() == io::ErrorKind::Interrupted {
168                     continue;
169                 }
170                 return Err(err);
171             }
172
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 {
179                 Ok(_) => Ok(true),
180                 Err(e) => {
181                     if e.kind() == io::ErrorKind::WouldBlock {
182                         Ok(false)
183                     } else {
184                         Err(e)
185                     }
186                 }
187             };
188             if !err_done && fds[errfd].revents != 0 && handle(err_pipe.read_to_end(&mut err))? {
189                 err_done = true;
190                 nfds -= 1;
191             }
192             data(false, &mut err, err_done);
193             if !out_done && fds[0].revents != 0 && handle(out_pipe.read_to_end(&mut out))? {
194                 out_done = true;
195                 fds[0].fd = err_pipe.as_raw_fd();
196                 errfd = 0;
197                 nfds -= 1;
198             }
199             data(true, &mut out, out_done);
200         }
201         Ok(())
202     }
203 }
204
205 #[cfg(windows)]
206 mod imp {
207     use std::io;
208     use std::os::windows::prelude::*;
209     use std::process::{ChildStderr, ChildStdout};
210     use std::slice;
211
212     use miow::iocp::{CompletionPort, CompletionStatus};
213     use miow::pipe::NamedPipe;
214     use miow::Overlapped;
215     use winapi::shared::winerror::ERROR_BROKEN_PIPE;
216
217     struct Pipe<'a> {
218         dst: &'a mut Vec<u8>,
219         overlapped: Overlapped,
220         pipe: NamedPipe,
221         done: bool,
222     }
223
224     pub fn read2(
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();
231
232         let port = CompletionPort::new(1)?;
233         port.add_handle(0, &out_pipe)?;
234         port.add_handle(1, &err_pipe)?;
235
236         unsafe {
237             let mut out_pipe = Pipe::new(out_pipe, &mut out);
238             let mut err_pipe = Pipe::new(err_pipe, &mut err);
239
240             out_pipe.read()?;
241             err_pipe.read()?;
242
243             let mut status = [CompletionStatus::zero(), CompletionStatus::zero()];
244
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);
250                         out_pipe.read()?;
251                     } else {
252                         err_pipe.complete(status);
253                         data(false, err_pipe.dst, err_pipe.done);
254                         err_pipe.read()?;
255                     }
256                 }
257             }
258
259             Ok(())
260         }
261     }
262
263     impl<'a> Pipe<'a> {
264         unsafe fn new<P: IntoRawHandle>(p: P, dst: &'a mut Vec<u8>) -> Pipe<'a> {
265             Pipe {
266                 dst: dst,
267                 pipe: NamedPipe::from_raw_handle(p.into_raw_handle()),
268                 overlapped: Overlapped::zero(),
269                 done: false,
270             }
271         }
272
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()) {
276                 Ok(_) => Ok(()),
277                 Err(e) => {
278                     if e.raw_os_error() == Some(ERROR_BROKEN_PIPE as i32) {
279                         self.done = true;
280                         Ok(())
281                     } else {
282                         Err(e)
283                     }
284                 }
285             }
286         }
287
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 {
292                 self.done = true;
293             }
294         }
295     }
296
297     unsafe fn slice_to_end(v: &mut Vec<u8>) -> &mut [u8] {
298         if v.capacity() == 0 {
299             v.reserve(16);
300         }
301         if v.capacity() == v.len() {
302             v.reserve(1);
303         }
304         slice::from_raw_parts_mut(v.as_mut_ptr().offset(v.len() as isize), v.capacity() - v.len())
305     }
306 }