Skip to content

Commit d42c1e5

Browse files
committed
Remove dependency on pipe, unless parallel
1 parent 2b52daf commit d42c1e5

File tree

10 files changed

+278
-321
lines changed

10 files changed

+278
-321
lines changed

Cargo.toml

+2-2
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,10 @@ rust-version = "1.53"
2222
[target.'cfg(unix)'.dependencies]
2323
# Don't turn on the feature "std" for this, see https://github.com/rust-lang/cargo/issues/4866
2424
# which is still an issue with `resolver = "1"`.
25-
libc = { version = "0.2.62", default-features = false }
25+
libc = { version = "0.2.62", default-features = false, optional = true }
2626

2727
[features]
28-
parallel = []
28+
parallel = ["libc"]
2929

3030
[dev-dependencies]
3131
tempfile = "3"

dev-tools/gen-windows-sys-binding/windows_sys.list

+1-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
Windows.Win32.Foundation.FILETIME
2-
Windows.Win32.Foundation.INVALID_HANDLE_VALUE
32
Windows.Win32.Foundation.ERROR_NO_MORE_ITEMS
43
Windows.Win32.Foundation.ERROR_SUCCESS
54
Windows.Win32.Foundation.SysFreeString
@@ -20,7 +19,7 @@ Windows.Win32.System.Com.COINIT_MULTITHREADED
2019
Windows.Win32.System.Com.CoCreateInstance
2120
Windows.Win32.System.Com.CoInitializeEx
2221

23-
Windows.Win32.System.Pipes.CreatePipe
22+
Windows.Win32.System.Pipes.PeekNamedPipe
2423

2524
Windows.Win32.System.Registry.RegCloseKey
2625
Windows.Win32.System.Registry.RegEnumKeyExW

src/command_helpers.rs

+163-90
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,12 @@ use std::{
44
collections::hash_map,
55
ffi::OsString,
66
fmt::Display,
7-
fs::{self, File},
7+
fs,
88
hash::Hasher,
9-
io::{self, BufRead, BufReader, Read, Write},
9+
io::{self, Read, Write},
1010
path::Path,
11-
process::{Child, Command, Stdio},
11+
process::{Child, ChildStderr, Command, Stdio},
1212
sync::Arc,
13-
thread::{self, JoinHandle},
1413
};
1514

1615
use crate::{Error, ErrorKind, Object};
@@ -41,83 +40,164 @@ impl CargoOutput {
4140
}
4241
}
4342

44-
pub(crate) fn print_thread(&self) -> Result<Option<PrintThread>, Error> {
45-
self.warnings.then(PrintThread::new).transpose()
43+
fn stdio_for_warnings(&self) -> Stdio {
44+
if self.warnings {
45+
Stdio::piped()
46+
} else {
47+
Stdio::null()
48+
}
4649
}
4750
}
4851

49-
pub(crate) struct PrintThread {
50-
handle: Option<JoinHandle<()>>,
51-
pipe_writer: Option<File>,
52+
pub(crate) struct StderrForwarder {
53+
inner: Option<(ChildStderr, Vec<u8>)>,
54+
#[cfg(feature = "parallel")]
55+
is_non_blocking: bool,
56+
#[cfg(feature = "parallel")]
57+
bytes_available_failed: bool,
5258
}
5359

54-
impl PrintThread {
55-
pub(crate) fn new() -> Result<Self, Error> {
56-
let (pipe_reader, pipe_writer) = crate::os_pipe::pipe()?;
57-
58-
// Capture the standard error coming from compilation, and write it out
59-
// with cargo:warning= prefixes. Note that this is a bit wonky to avoid
60-
// requiring the output to be UTF-8, we instead just ship bytes from one
61-
// location to another.
62-
let print = thread::spawn(move || {
63-
let mut stderr = BufReader::with_capacity(4096, pipe_reader);
64-
let mut line = Vec::with_capacity(20);
65-
let stdout = io::stdout();
66-
67-
// read_until returns 0 on Eof
68-
while stderr.read_until(b'\n', &mut line).unwrap() != 0 {
69-
{
70-
let mut stdout = stdout.lock();
71-
72-
stdout.write_all(b"cargo:warning=").unwrap();
73-
stdout.write_all(&line).unwrap();
74-
stdout.write_all(b"\n").unwrap();
75-
}
60+
const MIN_BUFFER_CAPACITY: usize = 100;
7661

77-
// read_until does not clear the buffer
78-
line.clear();
79-
}
80-
});
62+
impl StderrForwarder {
63+
pub(crate) fn new(child: &mut Child) -> Self {
64+
Self {
65+
inner: child
66+
.stderr
67+
.take()
68+
.map(|stderr| (stderr, Vec::with_capacity(MIN_BUFFER_CAPACITY))),
69+
#[cfg(feature = "parallel")]
70+
is_non_blocking: false,
71+
#[cfg(feature = "parallel")]
72+
bytes_available_failed: false,
73+
}
74+
}
8175

82-
Ok(Self {
83-
handle: Some(print),
84-
pipe_writer: Some(pipe_writer),
85-
})
76+
#[allow(clippy::uninit_vec)]
77+
fn forward_available(&mut self) -> bool {
78+
if let Some((stderr, buffer)) = self.inner.as_mut() {
79+
loop {
80+
let old_data_end = buffer.len();
81+
82+
// For non-blocking we check to see if there is data available, so we should try to
83+
// read at least that much. For blocking, always read at least the minimum amount.
84+
#[cfg(not(feature = "parallel"))]
85+
let to_reserve = MIN_BUFFER_CAPACITY;
86+
#[cfg(feature = "parallel")]
87+
let to_reserve = if self.is_non_blocking && !self.bytes_available_failed {
88+
match crate::parallel::stderr::bytes_available(stderr) {
89+
#[cfg(windows)]
90+
Ok(0) => return false,
91+
#[cfg(unix)]
92+
Ok(0) => {
93+
// On Unix, depending on the implementation, we may sometimes get 0 in a
94+
// loop (either there is data available or the pipe is broken), so
95+
// continue with the non-blocking read anyway.
96+
MIN_BUFFER_CAPACITY
97+
}
98+
#[cfg(windows)]
99+
Err(_) => {
100+
// On Windows, if we get an error then the pipe is broken, so flush
101+
// the buffer and bail.
102+
if !buffer.is_empty() {
103+
write_warning(&buffer[..]);
104+
}
105+
self.inner = None;
106+
return true;
107+
}
108+
#[cfg(unix)]
109+
Err(_) => {
110+
// On Unix, depending on the implementation, we may get spurious
111+
// errors so make a note not to use bytes_available again and try
112+
// the non-blocking read anyway.
113+
self.bytes_available_failed = true;
114+
MIN_BUFFER_CAPACITY
115+
}
116+
Ok(bytes_available) => MIN_BUFFER_CAPACITY.max(bytes_available),
117+
}
118+
} else {
119+
MIN_BUFFER_CAPACITY
120+
};
121+
buffer.reserve(to_reserve);
122+
123+
// SAFETY: 1) the length is set to the capacity, so we are never using memory beyond
124+
// the underlying buffer and 2) we always call `truncate` below to set the len back
125+
// to the intitialized data.
126+
unsafe {
127+
buffer.set_len(buffer.capacity());
128+
}
129+
match stderr.read(&mut buffer[old_data_end..]) {
130+
Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {
131+
// No data currently, yield back.
132+
buffer.truncate(old_data_end);
133+
return false;
134+
}
135+
Err(err) if err.kind() == std::io::ErrorKind::Interrupted => {
136+
// Interrupted, try again.
137+
buffer.truncate(old_data_end);
138+
}
139+
Ok(0) | Err(_) => {
140+
// End of stream: flush remaining data and bail.
141+
if old_data_end > 0 {
142+
write_warning(&buffer[..old_data_end]);
143+
}
144+
self.inner = None;
145+
return true;
146+
}
147+
Ok(bytes_read) => {
148+
buffer.truncate(old_data_end + bytes_read);
149+
let mut consumed = 0;
150+
for line in buffer.split_inclusive(|&b| b == b'\n') {
151+
// Only forward complete lines, leave the rest in the buffer.
152+
if let Some((b'\n', line)) = line.split_last() {
153+
consumed += line.len() + 1;
154+
write_warning(line);
155+
}
156+
}
157+
buffer.drain(..consumed);
158+
}
159+
}
160+
}
161+
} else {
162+
true
163+
}
86164
}
87165

88-
/// # Panics
89-
///
90-
/// Will panic if the pipe writer has already been taken.
91-
pub(crate) fn take_pipe_writer(&mut self) -> File {
92-
self.pipe_writer.take().unwrap()
166+
#[cfg(feature = "parallel")]
167+
pub(crate) fn set_non_blocking(&mut self) -> Result<(), Error> {
168+
assert!(!self.is_non_blocking);
169+
170+
if let Some((stderr, _)) = self.inner.as_mut() {
171+
crate::parallel::stderr::set_non_blocking(stderr)?;
172+
}
173+
174+
self.is_non_blocking = true;
175+
Ok(())
93176
}
94177

95-
/// # Panics
96-
///
97-
/// Will panic if the pipe writer has already been taken.
98-
pub(crate) fn clone_pipe_writer(&self) -> Result<File, Error> {
99-
self.try_clone_pipe_writer().map(Option::unwrap)
178+
#[cfg(feature = "parallel")]
179+
fn forward_all(&mut self) {
180+
while !self.forward_available() {}
100181
}
101182

102-
pub(crate) fn try_clone_pipe_writer(&self) -> Result<Option<File>, Error> {
103-
self.pipe_writer
104-
.as_ref()
105-
.map(File::try_clone)
106-
.transpose()
107-
.map_err(From::from)
183+
#[cfg(not(feature = "parallel"))]
184+
fn forward_all(&mut self) {
185+
let forward_result = self.forward_available();
186+
assert!(forward_result, "Should have consumed all data");
108187
}
109188
}
110189

111-
impl Drop for PrintThread {
112-
fn drop(&mut self) {
113-
// Drop pipe_writer first to avoid deadlock
114-
self.pipe_writer.take();
115-
116-
self.handle.take().unwrap().join().unwrap();
117-
}
190+
fn write_warning(line: &[u8]) {
191+
let stdout = io::stdout();
192+
let mut stdout = stdout.lock();
193+
stdout.write_all(b"cargo:warning=").unwrap();
194+
stdout.write_all(line).unwrap();
195+
stdout.write_all(b"\n").unwrap();
118196
}
119197

120198
fn wait_on_child(cmd: &Command, program: &str, child: &mut Child) -> Result<(), Error> {
199+
StderrForwarder::new(child).forward_all();
200+
121201
let status = match child.wait() {
122202
Ok(s) => s,
123203
Err(e) => {
@@ -193,20 +273,13 @@ pub(crate) fn objects_from_files(files: &[Arc<Path>], dst: &Path) -> Result<Vec<
193273
Ok(objects)
194274
}
195275

196-
fn run_inner(cmd: &mut Command, program: &str, pipe_writer: Option<File>) -> Result<(), Error> {
197-
let mut child = spawn(cmd, program, pipe_writer)?;
198-
wait_on_child(cmd, program, &mut child)
199-
}
200-
201276
pub(crate) fn run(
202277
cmd: &mut Command,
203278
program: &str,
204-
print: Option<&PrintThread>,
279+
cargo_output: &CargoOutput,
205280
) -> Result<(), Error> {
206-
let pipe_writer = print.map(PrintThread::clone_pipe_writer).transpose()?;
207-
run_inner(cmd, program, pipe_writer)?;
208-
209-
Ok(())
281+
let mut child = spawn(cmd, program, cargo_output)?;
282+
wait_on_child(cmd, program, &mut child)
210283
}
211284

212285
pub(crate) fn run_output(
@@ -216,12 +289,7 @@ pub(crate) fn run_output(
216289
) -> Result<Vec<u8>, Error> {
217290
cmd.stdout(Stdio::piped());
218291

219-
let mut print = cargo_output.print_thread()?;
220-
let mut child = spawn(
221-
cmd,
222-
program,
223-
print.as_mut().map(PrintThread::take_pipe_writer),
224-
)?;
292+
let mut child = spawn(cmd, program, cargo_output)?;
225293

226294
let mut stdout = vec![];
227295
child
@@ -239,7 +307,7 @@ pub(crate) fn run_output(
239307
pub(crate) fn spawn(
240308
cmd: &mut Command,
241309
program: &str,
242-
pipe_writer: Option<File>,
310+
cargo_output: &CargoOutput,
243311
) -> Result<Child, Error> {
244312
struct ResetStderr<'cmd>(&'cmd mut Command);
245313

@@ -254,10 +322,7 @@ pub(crate) fn spawn(
254322
println!("running: {:?}", cmd);
255323

256324
let cmd = ResetStderr(cmd);
257-
let child = cmd
258-
.0
259-
.stderr(pipe_writer.map_or_else(Stdio::null, Stdio::from))
260-
.spawn();
325+
let child = cmd.0.stderr(cargo_output.stdio_for_warnings()).spawn();
261326
match child {
262327
Ok(child) => Ok(child),
263328
Err(ref e) if e.kind() == io::ErrorKind::NotFound => {
@@ -307,9 +372,14 @@ pub(crate) fn try_wait_on_child(
307372
program: &str,
308373
child: &mut Child,
309374
stdout: &mut dyn io::Write,
375+
stderr_forwarder: &mut StderrForwarder,
310376
) -> Result<Option<()>, Error> {
377+
stderr_forwarder.forward_available();
378+
311379
match child.try_wait() {
312380
Ok(Some(status)) => {
381+
stderr_forwarder.forward_all();
382+
313383
let _ = writeln!(stdout, "{}", status);
314384

315385
if status.success() {
@@ -325,12 +395,15 @@ pub(crate) fn try_wait_on_child(
325395
}
326396
}
327397
Ok(None) => Ok(None),
328-
Err(e) => Err(Error::new(
329-
ErrorKind::ToolExecError,
330-
format!(
331-
"Failed to wait on spawned child process, command {:?} with args {:?}: {}.",
332-
cmd, program, e
333-
),
334-
)),
398+
Err(e) => {
399+
stderr_forwarder.forward_all();
400+
Err(Error::new(
401+
ErrorKind::ToolExecError,
402+
format!(
403+
"Failed to wait on spawned child process, command {:?} with args {:?}: {}.",
404+
cmd, program, e
405+
),
406+
))
407+
}
335408
}
336409
}

0 commit comments

Comments
 (0)