Debian Codegraph @

debian/rust-vendor/cc/src/command_helpers.rs

raw
1 //! Miscellaneous helpers for running commands
2
3 use std::{
4 borrow::Cow,
5 collections::hash_map,
6 ffi::{OsStr, OsString},
7 fmt::Display,
8 fs,
9 hash::Hasher,
10 io::{self, Read, Write},
11 path::Path,
12 process::{Child, ChildStderr, Command, Output, Stdio},
13 sync::{
14 atomic::{AtomicBool, Ordering},
15 Arc,
16 },
17 };
18
19 use crate::{utilities::cargo_env_var_os, Error, ErrorKind, Object};
20
21 #[derive(Clone, Debug)]
22 pub(crate) struct CargoOutput {
23 pub(crate) metadata: bool,
24 pub(crate) warnings: bool,
25 pub(crate) debug: bool,
26 pub(crate) output: OutputKind,
27 checked_dbg_var: Arc<AtomicBool>,
28 }
29
30 /// Different strategies for handling compiler output (to stdout)
31 #[derive(Clone, Debug)]
32 pub(crate) enum OutputKind {
33 /// Forward the output to this process' stdout ([`Stdio::inherit()`])
34 Forward,
35 /// Discard the output ([`Stdio::null()`])
36 Discard,
37 /// Capture the result ([`Stdio::piped()`])
38 Capture,
39 }
40
41 impl CargoOutput {
42 pub(crate) fn new() -> Self {
43 #[allow(clippy::disallowed_methods)]
44 Self {
45 metadata: true,
46 warnings: true,
47 output: OutputKind::Forward,
48 debug: match std::env::var_os("CC_ENABLE_DEBUG_OUTPUT") {
49 Some(v) => v != "0" && v != "false" && !v.is_empty(),
50 None => false,
51 },
52 checked_dbg_var: Arc::new(AtomicBool::new(false)),
53 }
54 }
55
56 pub(crate) fn print_metadata(&self, s: &dyn Display) {
57 if self.metadata {
58 println!("{s}");
59 }
60 }
61
62 pub(crate) fn print_warning(&self, arg: &dyn Display) {
63 if self.warnings {
64 println!("cargo:warning={arg}");
65 }
66 }
67
68 pub(crate) fn print_debug(&self, arg: &dyn Display) {
69 if self.metadata
70 && self
71 .checked_dbg_var
72 .compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed)
73 .is_ok()
74 {
75 println!("cargo:rerun-if-env-changed=CC_ENABLE_DEBUG_OUTPUT");
76 }
77 if self.debug {
78 println!("{arg}");
79 }
80 }
81
82 fn stdio_for_warnings(&self) -> Stdio {
83 if self.warnings {
84 Stdio::piped()
85 } else {
86 Stdio::null()
87 }
88 }
89
90 fn stdio_for_output(&self) -> Stdio {
91 match self.output {
92 OutputKind::Capture => Stdio::piped(),
93 OutputKind::Forward => Stdio::inherit(),
94 OutputKind::Discard => Stdio::null(),
95 }
96 }
97 }
98
99 pub(crate) struct StderrForwarder {
100 inner: Option<(ChildStderr, Vec<u8>)>,
101 #[cfg(feature = "parallel")]
102 is_non_blocking: bool,
103 #[cfg(feature = "parallel")]
104 bytes_available_failed: bool,
105 /// number of bytes buffered in inner
106 bytes_buffered: usize,
107 }
108
109 const MIN_BUFFER_CAPACITY: usize = 100;
110
111 impl StderrForwarder {
112 pub(crate) fn new(child: &mut Child) -> Self {
113 Self {
114 inner: child
115 .stderr
116 .take()
117 .map(|stderr| (stderr, Vec::with_capacity(MIN_BUFFER_CAPACITY))),
118 bytes_buffered: 0,
119 #[cfg(feature = "parallel")]
120 is_non_blocking: false,
121 #[cfg(feature = "parallel")]
122 bytes_available_failed: false,
123 }
124 }
125
126 pub(crate) fn forward_available(&mut self) -> bool {
127 if let Some((stderr, buffer)) = self.inner.as_mut() {
128 loop {
129 // For non-blocking we check to see if there is data available, so we should try to
130 // read at least that much. For blocking, always read at least the minimum amount.
131 #[cfg(not(feature = "parallel"))]
132 let to_reserve = MIN_BUFFER_CAPACITY;
133 #[cfg(feature = "parallel")]
134 let to_reserve = if self.is_non_blocking && !self.bytes_available_failed {
135 match crate::parallel::stderr::bytes_available(stderr) {
136 #[cfg(windows)]
137 Ok(0) => break false,
138 #[cfg(unix)]
139 Ok(0) => {
140 // On Unix, depending on the implementation, we may sometimes get 0 in a
141 // loop (either there is data available or the pipe is broken), so
142 // continue with the non-blocking read anyway.
143 MIN_BUFFER_CAPACITY
144 }
145 #[cfg(windows)]
146 Err(_) => {
147 // On Windows, if we get an error then the pipe is broken, so flush
148 // the buffer and bail.
149 if !buffer.is_empty() {
150 write_warning(&buffer[..]);
151 }
152 self.inner = None;
153 break true;
154 }
155 #[cfg(unix)]
156 Err(_) => {
157 // On Unix, depending on the implementation, we may get spurious
158 // errors so make a note not to use bytes_available again and try
159 // the non-blocking read anyway.
160 self.bytes_available_failed = true;
161 MIN_BUFFER_CAPACITY
162 }
163 #[cfg(target_family = "wasm")]
164 Err(_) => panic!("bytes_available should always succeed on wasm"),
165 Ok(bytes_available) => MIN_BUFFER_CAPACITY.max(bytes_available),
166 }
167 } else {
168 MIN_BUFFER_CAPACITY
169 };
170 if self.bytes_buffered + to_reserve > buffer.len() {
171 buffer.resize(self.bytes_buffered + to_reserve, 0);
172 }
173
174 match stderr.read(&mut buffer[self.bytes_buffered..]) {
175 Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {
176 // No data currently, yield back.
177 break false;
178 }
179 Err(err) if err.kind() == std::io::ErrorKind::Interrupted => {
180 // Interrupted, try again.
181 continue;
182 }
183 Ok(bytes_read) if bytes_read != 0 => {
184 self.bytes_buffered += bytes_read;
185 let mut consumed = 0;
186 for line in buffer[..self.bytes_buffered].split_inclusive(|&b| b == b'\n') {
187 // Only forward complete lines, leave the rest in the buffer.
188 if let Some((b'\n', line)) = line.split_last() {
189 consumed += line.len() + 1;
190 write_warning(line);
191 }
192 }
193 if consumed > 0 && consumed < self.bytes_buffered {
194 // Remove the consumed bytes from buffer
195 buffer.copy_within(consumed.., 0);
196 }
197 self.bytes_buffered -= consumed;
198 }
199 res => {
200 // End of stream: flush remaining data and bail.
201 if self.bytes_buffered > 0 {
202 write_warning(&buffer[..self.bytes_buffered]);
203 }
204 if let Err(err) = res {
205 write_warning(
206 format!("Failed to read from child stderr: {err}").as_bytes(),
207 );
208 }
209 self.inner.take();
210 break true;
211 }
212 }
213 }
214 } else {
215 true
216 }
217 }
218
219 #[cfg(feature = "parallel")]
220 pub(crate) fn set_non_blocking(&mut self) -> Result<(), Error> {
221 assert!(!self.is_non_blocking);
222
223 #[cfg(unix)]
224 if let Some((stderr, _)) = self.inner.as_ref() {
225 crate::parallel::stderr::set_non_blocking(stderr)?;
226 }
227
228 self.is_non_blocking = true;
229 Ok(())
230 }
231
232 #[cfg(feature = "parallel")]
233 pub(crate) fn forward_all(&mut self) {
234 while !self.forward_available() {}
235 }
236
237 #[cfg(not(feature = "parallel"))]
238 fn forward_all(&mut self) {
239 let forward_result = self.forward_available();
240 assert!(forward_result, "Should have consumed all data");
241 }
242 }
243
244 fn write_warning(line: &[u8]) {
245 let stdout = io::stdout();
246 let mut stdout = stdout.lock();
247 stdout.write_all(b"cargo:warning=").unwrap();
248 stdout.write_all(line).unwrap();
249 stdout.write_all(b"\n").unwrap();
250 }
251
252 fn wait_on_child(
253 cmd: &Command,
254 child: &mut Child,
255 cargo_output: &CargoOutput,
256 ) -> Result<(), Error> {
257 StderrForwarder::new(child).forward_all();
258
259 let status = match child.wait() {
260 Ok(s) => s,
261 Err(e) => {
262 return Err(Error::new(
263 ErrorKind::ToolExecError,
264 format!("failed to wait on spawned child process `{cmd:?}`: {e}"),
265 ));
266 }
267 };
268
269 cargo_output.print_debug(&status);
270
271 if status.success() {
272 Ok(())
273 } else {
274 Err(Error::new(
275 ErrorKind::ToolExecError,
276 format!("command did not execute successfully (status code {status}): {cmd:?}"),
277 ))
278 }
279 }
280
281 /// Find the destination object path for each file in the input source files,
282 /// and store them in the output Object.
283 pub(crate) fn objects_from_files(files: &[Arc<Path>], dst: &Path) -> Result<Vec<Object>, Error> {
284 let mut objects = Vec::with_capacity(files.len());
285 for file in files {
286 let basename = file
287 .file_name()
288 .ok_or_else(|| {
289 Error::new(
290 ErrorKind::InvalidArgument,
291 "No file_name for object file path!",
292 )
293 })?
294 .to_string_lossy();
295 let dirname = file
296 .parent()
297 .ok_or_else(|| {
298 Error::new(
299 ErrorKind::InvalidArgument,
300 "No parent for object file path!",
301 )
302 })?
303 .to_string_lossy();
304
305 // Hash the dirname. This should prevent conflicts if we have multiple
306 // object files with the same filename in different subfolders.
307 let mut hasher = hash_map::DefaultHasher::new();
308
309 // Make the dirname relative (if possible) to avoid full system paths influencing the sha
310 // and making the output system-dependent
311 let dirname = if let Some(root) = cargo_env_var_os("CARGO_MANIFEST_DIR") {
312 let root = root.to_string_lossy();
313 Cow::Borrowed(dirname.strip_prefix(&*root).unwrap_or(&dirname))
314 } else {
315 dirname
316 };
317
318 hasher.write(dirname.as_bytes());
319 if let Some(extension) = file.extension() {
320 hasher.write(extension.to_string_lossy().as_bytes());
321 }
322
323 let obj = dst
324 .join(format!("{:016x}-{}", hasher.finish(), basename))
325 .with_extension("o");
326
327 match obj.parent() {
328 Some(s) => fs::create_dir_all(s)?,
329 None => {
330 return Err(Error::new(
331 ErrorKind::InvalidArgument,
332 "dst is an invalid path with no parent",
333 ));
334 }
335 };
336
337 objects.push(Object::new(file.to_path_buf(), obj));
338 }
339
340 Ok(objects)
341 }
342
343 /// Which of cc's own probing invocations a [`Command`] is being set up for.
344 ///
345 /// A probe is not a command the caller asked cc to run: it is how cc works out
346 /// what the compiler it was handed can do. Which probes run, and how many of
347 /// them, depends on the compiler, the target and cc's internal caching, so the
348 /// test shim records one only when a test names its class. See
349 /// [`set_probe_env`] and `src/bin/cc-shim.rs`.
350 #[derive(Clone, Copy, Debug)]
351 enum ProbeKind {
352 /// Working out a compiler's [`ToolFamily`](crate::ToolFamily).
353 FamilyDetection,
354 /// Checking whether a compiler accepts a flag.
355 FlagSupportCheck,
356 /// Working out whether an Android NDK ships `llvm-ar` under that name.
357 ArDetection,
358 }
359
360 impl ProbeKind {
361 /// The test-only variable naming where the shim should record this class.
362 const fn out_files_var(self) -> &'static str {
363 match self {
364 Self::FamilyDetection => "CC_SHIM_OUT_FILES_FOR_FAMILY_DETECTION",
365 Self::FlagSupportCheck => "CC_SHIM_OUT_FILES_FOR_FLAG_SUPPORT_CHECK",
366 Self::ArDetection => "CC_SHIM_OUT_FILES_FOR_AR_DETECTION",
367 }
368 }
369 }
370
371 /// Apply [`Build::env`](crate::Build::env) to one of cc's own probing
372 /// invocations.
373 ///
374 /// A probe is a child process like any other, so it gets the environment the
375 /// caller configured - `PATH` above all, without which a probe resolves a bare
376 /// compiler name such as `cc` against the ambient environment rather than the
377 /// one the compile commands run in, and answers a question about a different
378 /// compiler than the one being built with (rust-lang/cc-rs#1859).
379 ///
380 /// The `CC_SHIM_OUT_FILES_FOR_*` variables are the exception, and a third
381 /// category beside the two that [`Build::env`](crate::Build::env) already
382 /// distinguishes: they are set through `Build::env` but read by cc itself, and
383 /// rewritten for exactly one child. cc renames the one matching `kind` to
384 /// `CC_SHIM_OUT_FILES` and otherwise clears it, and clears `CC_SHIM_OUT_DIR`
385 /// either way, instead of copying `Build::env` over blindly. A probe a test did
386 /// not ask about then records nothing at all, rather than taking an `out{i}`
387 /// slot and shifting the invocations the test is asserting on. They are
388 /// test-only, like `CC_SHIM_OUT_DIR`, and so are documented in
389 /// `src/bin/cc-shim.rs` rather than in the table of public variables in
390 /// `src/lib.rs`.
391 fn set_probe_env<K, V>(cmd: &mut Command, env: &[(K, V)], kind: ProbeKind)
392 where
393 K: AsRef<OsStr>,
394 V: AsRef<OsStr>,
395 {
396 for (key, value) in env {
397 cmd.env(key.as_ref(), value.as_ref());
398 }
399
400 cmd.env_remove("CC_SHIM_OUT_DIR");
401 match env
402 .iter()
403 .find(|(key, _)| key.as_ref() == OsStr::new(kind.out_files_var()))
404 {
405 Some((_, value)) => cmd.env("CC_SHIM_OUT_FILES", value.as_ref()),
406 None => cmd.env_remove("CC_SHIM_OUT_FILES"),
407 };
408 }
409
410 pub(crate) fn run(cmd: &mut Command, cargo_output: &CargoOutput) -> Result<(), Error> {
411 let mut child = spawn(cmd, cargo_output)?;
412 wait_on_child(cmd, &mut child, cargo_output)
413 }
414
415 /// Like [`run`], but stderr is only forwarded as `cargo:warning=` when the
416 /// command succeeds. On failure, stderr is silently discarded.
417 ///
418 /// Useful for probe commands where failure is expected and the error
419 /// message is not actionable.
420 pub(crate) fn run_silent_on_error(
421 cmd: &mut Command,
422 cargo_output: &CargoOutput,
423 ) -> Result<(), Error> {
424 let Output {
425 status,
426 stdout: _,
427 stderr,
428 } = spawn_and_wait_for_output(cmd, cargo_output)?;
429
430 cargo_output.print_debug(&status);
431
432 if status.success() {
433 if cargo_output.warnings {
434 stderr
435 .split(|&b| b == b'\n')
436 .map(|line| line.strip_suffix(b"\r").unwrap_or(line))
437 .filter(|line| !line.is_empty())
438 .for_each(write_warning);
439 }
440 Ok(())
441 } else {
442 Err(Error::new(
443 ErrorKind::ToolExecError,
444 format!("command did not execute successfully (status code {status}): {cmd:?}"),
445 ))
446 }
447 }
448
449 pub(crate) fn spawn_and_wait_for_output(
450 cmd: &mut Command,
451 cargo_output: &CargoOutput,
452 ) -> Result<Output, Error> {
453 // We specifically need the output to be captured, so override default
454 let mut captured_cargo_output = cargo_output.clone();
455 captured_cargo_output.output = OutputKind::Capture;
456 spawn(cmd, &captured_cargo_output)?
457 .wait_with_output()
458 .map_err(|e| {
459 Error::new(
460 ErrorKind::ToolExecError,
461 format!("failed to wait on spawned child process `{cmd:?}`: {e}"),
462 )
463 })
464 }
465
466 pub(crate) fn run_output(cmd: &mut Command, cargo_output: &CargoOutput) -> Result<Vec<u8>, Error> {
467 let Output {
468 status,
469 stdout,
470 stderr,
471 } = spawn_and_wait_for_output(cmd, cargo_output)?;
472
473 stderr
474 .split(|&b| b == b'\n')
475 .filter(|part| !part.is_empty())
476 .for_each(write_warning);
477
478 cargo_output.print_debug(&status);
479
480 if status.success() {
481 Ok(stdout)
482 } else {
483 Err(Error::new(
484 ErrorKind::ToolExecError,
485 format!("command did not execute successfully (status code {status}): {cmd:?}"),
486 ))
487 }
488 }
489
490 pub(crate) fn spawn(cmd: &mut Command, cargo_output: &CargoOutput) -> Result<Child, Error> {
491 struct ResetStderr<'cmd>(&'cmd mut Command);
492
493 impl Drop for ResetStderr<'_> {
494 fn drop(&mut self) {
495 // Reset stderr to default to release pipe_writer so that print thread will
496 // not block forever.
497 self.0.stderr(Stdio::inherit());
498 }
499 }
500
501 cargo_output.print_debug(&format_args!("running: {cmd:?}"));
502
503 let cmd = ResetStderr(cmd);
504 let child = cmd
505 .0
506 .stderr(cargo_output.stdio_for_warnings())
507 .stdout(cargo_output.stdio_for_output())
508 .spawn();
509 match child {
510 Ok(child) => Ok(child),
511 Err(ref e) if e.kind() == io::ErrorKind::NotFound => {
512 let extra = if cfg!(windows) {
513 " (see https://docs.rs/cc/latest/cc/#compile-time-requirements for help)"
514 } else {
515 ""
516 };
517 Err(Error::new(
518 ErrorKind::ToolNotFound,
519 format!("failed to find tool {:?}: {e}{extra}", cmd.0.get_program()),
520 ))
521 }
522 Err(e) => Err(Error::new(
523 ErrorKind::ToolExecError,
524 format!("command `{:?}` failed to start: {e}", cmd.0),
525 )),
526 }
527 }
528
529 pub(crate) struct CmdAddOutputFileArgs {
530 pub(crate) cuda: bool,
531 pub(crate) is_assembler_msvc: bool,
532 pub(crate) msvc: bool,
533 pub(crate) clang: bool,
534 pub(crate) gnu: bool,
535 pub(crate) is_asm: bool,
536 pub(crate) is_arm: bool,
537 }
538
539 pub(crate) fn command_add_output_file(cmd: &mut Command, dst: &Path, args: CmdAddOutputFileArgs) {
540 if args.is_assembler_msvc
541 || !(!args.msvc || args.clang || args.gnu || args.cuda || (args.is_asm && args.is_arm))
542 {
543 let mut s = OsString::from("-Fo");
544 s.push(dst);
545 cmd.arg(s);
546 } else {
547 cmd.arg("-o").arg(dst);
548 }
549 }
550
551 /// Naming the two probe classes at the call site, so a caller does not have
552 /// to reach for [`ProbeKind`] to say which one it means.
553 pub(crate) trait CommandExt {
554 /// Apply `Build::env` to a compiler family detection probe.
555 fn set_family_detection_env<K, V>(&mut self, env: &[(K, V)]) -> &mut Self
556 where
557 K: AsRef<OsStr>,
558 V: AsRef<OsStr>;
559
560 /// Apply `Build::env` to an `is_flag_supported` probe.
561 fn set_flag_supported_env<K, V>(&mut self, env: &[(K, V)]) -> &mut Self
562 where
563 K: AsRef<OsStr>,
564 V: AsRef<OsStr>;
565
566 /// Apply `Build::env` to the Android `llvm-ar` probe.
567 fn set_ar_detection_env<K, V>(&mut self, env: &[(K, V)]) -> &mut Self
568 where
569 K: AsRef<OsStr>,
570 V: AsRef<OsStr>;
571 }
572
573 impl CommandExt for Command {
574 fn set_family_detection_env<K, V>(&mut self, env: &[(K, V)]) -> &mut Self
575 where
576 K: AsRef<OsStr>,
577 V: AsRef<OsStr>,
578 {
579 set_probe_env(self, env, ProbeKind::FamilyDetection);
580 self
581 }
582
583 fn set_flag_supported_env<K, V>(&mut self, env: &[(K, V)]) -> &mut Self
584 where
585 K: AsRef<OsStr>,
586 V: AsRef<OsStr>,
587 {
588 set_probe_env(self, env, ProbeKind::FlagSupportCheck);
589 self
590 }
591
592 fn set_ar_detection_env<K, V>(&mut self, env: &[(K, V)]) -> &mut Self
593 where
594 K: AsRef<OsStr>,
595 V: AsRef<OsStr>,
596 {
597 set_probe_env(self, env, ProbeKind::ArDetection);
598 self
599 }
600 }