xtask/coverage/
wrapper.rs1use std::ffi::{OsStr, OsString};
20use std::os::unix::process::CommandExt;
21use std::path::{Path, PathBuf};
22use std::process::Command;
23
24use anyhow::{Context, Error, Result, bail};
25
26const PREVIOUS_VAR: &str = "NOMISYNC_COVERAGE_WRAPPER";
29const ROOT_VAR: &str = "NOMISYNC_COVERAGE_ROOT";
30const COVERAGE_FLAG: &str = "-Cinstrument-coverage";
31
32#[derive(Debug, PartialEq, Eq)]
34struct Invocation {
35 program: OsString,
36 args: Vec<OsString>,
37}
38
39pub(super) fn wrapper_env(
41 exe: &Path,
42 previous: &OsStr,
43 root: &Path,
44) -> [(&'static str, OsString); 3] {
45 [
46 ("RUSTC_WRAPPER", exe.as_os_str().to_owned()),
47 (PREVIOUS_VAR, previous.to_owned()),
48 (ROOT_VAR, root.as_os_str().to_owned()),
49 ]
50}
51
52pub fn intercept() -> Option<Error> {
57 let previous = std::env::var_os(PREVIOUS_VAR)?;
58 let manifest_dir = std::env::var_os("CARGO_MANIFEST_DIR").map(PathBuf::from);
59 let argv: Vec<OsString> = std::env::args_os().skip(1).collect();
60 if !is_rustc_call(&argv) {
61 return None;
62 }
63 let root = match std::env::var_os(ROOT_VAR).context("the coverage workspace root is not set") {
64 Ok(root) => PathBuf::from(root),
65 Err(err) => return Some(err),
66 };
67 let invocation = match plan(&previous, &root, manifest_dir.as_deref(), argv) {
68 Ok(invocation) => invocation,
69 Err(err) => return Some(err),
70 };
71 let failure = Command::new(&invocation.program)
72 .args(&invocation.args)
73 .exec();
74 Some(Error::new(failure).context(format!("cannot run {:?}", invocation.program)))
75}
76
77fn is_rustc_call(argv: &[OsString]) -> bool {
80 argv.first()
81 .is_some_and(|program| Path::new(program).file_name() == Some(OsStr::new("rustc")))
82}
83
84fn plan(
86 previous: &OsStr,
87 root: &Path,
88 manifest_dir: Option<&Path>,
89 mut argv: Vec<OsString>,
90) -> Result<Invocation> {
91 if argv.is_empty() {
92 bail!("the coverage wrapper was given no rustc to run");
93 }
94 if manifest_dir.is_some_and(|dir| dir.starts_with(root)) && !cross_compiles(&argv) {
95 argv.push(COVERAGE_FLAG.into());
96 }
97 if !previous.is_empty() {
98 argv.insert(0, previous.to_owned());
99 }
100 Ok(split(argv))
101}
102
103fn cross_compiles(argv: &[OsString]) -> bool {
104 argv.iter()
105 .any(|arg| arg == "--target" || arg.as_encoded_bytes().starts_with(b"--target="))
106}
107
108fn split(mut argv: Vec<OsString>) -> Invocation {
109 let program = argv.remove(0);
110 Invocation {
111 program,
112 args: argv,
113 }
114}
115
116#[cfg(test)]
117mod tests;