Skip to content

Commit 1fa9906

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

File tree

10 files changed

+202
-326
lines changed

10 files changed

+202
-326
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

+116-95
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,112 @@ 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>)>,
5254
}
5355

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-
}
76-
77-
// read_until does not clear the buffer
78-
line.clear();
79-
}
80-
});
56+
const MIN_BUFFER_CAPACITY: usize = 100;
8157

82-
Ok(Self {
83-
handle: Some(print),
84-
pipe_writer: Some(pipe_writer),
85-
})
86-
}
87-
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()
93-
}
94-
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)
58+
impl StderrForwarder {
59+
pub(crate) fn new(child: &mut Child) -> Self {
60+
Self {
61+
inner: child
62+
.stderr
63+
.take()
64+
.map(|stderr| (stderr, Vec::with_capacity(MIN_BUFFER_CAPACITY))),
65+
}
10066
}
10167

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)
68+
fn forward(&mut self, non_blocking: bool) -> bool {
69+
if let Some((stderr, buffer)) = self.inner.as_mut() {
70+
loop {
71+
let old_data_end = buffer.len();
72+
73+
// For blocking, we always try to read as much as possible, but for non-blocking we
74+
// want to check if there is any data available, then only read that much.
75+
let write_until = if non_blocking {
76+
#[cfg(feature = "parallel")]
77+
match crate::parallel::stderr::bytes_available(stderr) {
78+
Ok(0) => return false,
79+
Ok(bytes_available) => {
80+
buffer.reserve(bytes_available);
81+
old_data_end + bytes_available
82+
}
83+
Err(_) => {
84+
// Error: flush remaining data and bail.
85+
if !buffer.is_empty() {
86+
write_warning(&buffer[..]);
87+
}
88+
self.inner = None;
89+
return true;
90+
}
91+
}
92+
#[cfg(not(feature = "parallel"))]
93+
panic!("Non-blocking mode is only available with the parallel feature");
94+
} else {
95+
buffer.reserve(MIN_BUFFER_CAPACITY);
96+
buffer.capacity()
97+
};
98+
99+
// SAFETY: 1) write_until is either reserved or the capacity, so we are never using
100+
// memory beyond the underlying buffer and 2) we always call `truncate` below to set
101+
// the len back to the intitialized data.
102+
unsafe {
103+
buffer.set_len(write_until);
104+
}
105+
match stderr.read(&mut buffer[old_data_end..write_until]) {
106+
Err(err) if err.kind() == std::io::ErrorKind::Interrupted => {
107+
// Interrupted, try again.
108+
buffer.truncate(old_data_end);
109+
}
110+
Ok(0) | Err(_) => {
111+
// End of stream: flush remaining data and bail.
112+
if old_data_end > 0 {
113+
write_warning(&buffer[..old_data_end]);
114+
}
115+
self.inner = None;
116+
return true;
117+
}
118+
Ok(bytes_read) => {
119+
buffer.truncate(old_data_end + bytes_read);
120+
let mut consumed = 0;
121+
for line in buffer.split_inclusive(|&b| b == b'\n') {
122+
// Only forward complete lines, leave the rest in the buffer.
123+
if let Some((b'\n', line)) = line.split_last() {
124+
consumed += line.len() + 1;
125+
write_warning(line);
126+
}
127+
}
128+
buffer.drain(..consumed);
129+
}
130+
}
131+
}
132+
} else {
133+
true
134+
}
108135
}
109136
}
110137

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-
}
138+
fn write_warning(line: &[u8]) {
139+
let stdout = io::stdout();
140+
let mut stdout = stdout.lock();
141+
stdout.write_all(b"cargo:warning=").unwrap();
142+
stdout.write_all(line).unwrap();
143+
stdout.write_all(b"\n").unwrap();
118144
}
119145

120146
fn wait_on_child(cmd: &Command, program: &str, child: &mut Child) -> Result<(), Error> {
147+
StderrForwarder::new(child).forward(false);
148+
121149
let status = match child.wait() {
122150
Ok(s) => s,
123151
Err(e) => {
@@ -193,20 +221,13 @@ pub(crate) fn objects_from_files(files: &[Arc<Path>], dst: &Path) -> Result<Vec<
193221
Ok(objects)
194222
}
195223

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-
201224
pub(crate) fn run(
202225
cmd: &mut Command,
203226
program: &str,
204-
print: Option<&PrintThread>,
227+
cargo_output: &CargoOutput,
205228
) -> Result<(), Error> {
206-
let pipe_writer = print.map(PrintThread::clone_pipe_writer).transpose()?;
207-
run_inner(cmd, program, pipe_writer)?;
208-
209-
Ok(())
229+
let mut child = spawn(cmd, program, cargo_output)?;
230+
wait_on_child(cmd, program, &mut child)
210231
}
211232

212233
pub(crate) fn run_output(
@@ -216,12 +237,7 @@ pub(crate) fn run_output(
216237
) -> Result<Vec<u8>, Error> {
217238
cmd.stdout(Stdio::piped());
218239

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-
)?;
240+
let mut child = spawn(cmd, program, cargo_output)?;
225241

226242
let mut stdout = vec![];
227243
child
@@ -239,7 +255,7 @@ pub(crate) fn run_output(
239255
pub(crate) fn spawn(
240256
cmd: &mut Command,
241257
program: &str,
242-
pipe_writer: Option<File>,
258+
cargo_output: &CargoOutput,
243259
) -> Result<Child, Error> {
244260
struct ResetStderr<'cmd>(&'cmd mut Command);
245261

@@ -254,10 +270,7 @@ pub(crate) fn spawn(
254270
println!("running: {:?}", cmd);
255271

256272
let cmd = ResetStderr(cmd);
257-
let child = cmd
258-
.0
259-
.stderr(pipe_writer.map_or_else(Stdio::null, Stdio::from))
260-
.spawn();
273+
let child = cmd.0.stderr(cargo_output.stdio_for_warnings()).spawn();
261274
match child {
262275
Ok(child) => Ok(child),
263276
Err(ref e) if e.kind() == io::ErrorKind::NotFound => {
@@ -307,9 +320,14 @@ pub(crate) fn try_wait_on_child(
307320
program: &str,
308321
child: &mut Child,
309322
stdout: &mut dyn io::Write,
323+
stderr_forwarder: &mut StderrForwarder,
310324
) -> Result<Option<()>, Error> {
325+
stderr_forwarder.forward(true);
326+
311327
match child.try_wait() {
312328
Ok(Some(status)) => {
329+
stderr_forwarder.forward(false);
330+
313331
let _ = writeln!(stdout, "{}", status);
314332

315333
if status.success() {
@@ -325,12 +343,15 @@ pub(crate) fn try_wait_on_child(
325343
}
326344
}
327345
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-
)),
346+
Err(e) => {
347+
stderr_forwarder.forward(false);
348+
Err(Error::new(
349+
ErrorKind::ToolExecError,
350+
format!(
351+
"Failed to wait on spawned child process, command {:?} with args {:?}: {}.",
352+
cmd, program, e
353+
),
354+
))
355+
}
335356
}
336357
}

0 commit comments

Comments
 (0)