Skip to main content

xtask/coverage/
wrapper.rs

1//! The `RUSTC_WRAPPER` of the instrumented build.
2//!
3//! Only workspace crates are instrumented: instrumenting wasmtime and
4//! cranelift made every wasm compile in the suite several times slower, and
5//! their records were thrown away anyway. `RUSTFLAGS` cannot say "workspace
6//! only", so cargo runs this executable in front of every rustc. A crate whose
7//! manifest lives under the workspace root gets `-Cinstrument-coverage` appended
8//! and still goes through the wrapper the environment had before: the flag is
9//! then part of sccache's argv, hence of its cache key, so an instrumented
10//! artifact is never stored under a key that lacks it. Everything else goes
11//! through that wrapper unchanged.
12//!
13//! A compilation with an explicit `--target` is left alone as well: the suite
14//! starts wasm32 builds, and that target has no profiler runtime.
15//!
16//! `RUSTC_WORKSPACE_WRAPPER` would not do: cargo nests it inside
17//! `RUSTC_WRAPPER`, so sccache would sit outside it.
18
19use 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
26/// Presence switches `main` into wrapper mode; the value is the wrapper that
27/// was set before, possibly empty.
28const PREVIOUS_VAR: &str = "NOMISYNC_COVERAGE_WRAPPER";
29const ROOT_VAR: &str = "NOMISYNC_COVERAGE_ROOT";
30const COVERAGE_FLAG: &str = "-Cinstrument-coverage";
31
32/// The program and arguments to run in place of the wrapper itself.
33#[derive(Debug, PartialEq, Eq)]
34struct Invocation {
35    program: OsString,
36    args: Vec<OsString>,
37}
38
39/// The environment that makes cargo route every rustc through this executable.
40pub(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
52/// Runs as the wrapper when the marker is set and cargo's call shape matches.
53/// `None` means this is a normal xtask invocation, including one a test spawned
54/// under the marker it inherited; `Some` is only ever the failure to start rustc, because
55/// success replaces this process.
56pub 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
77/// Cargo runs `$RUSTC_WRAPPER <rustc> <args…>`, the rustc being a path or a bare
78/// name; an xtask invocation starts with a subcommand instead.
79fn 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
84/// `argv` is what cargo passed: the rustc to run, then its arguments.
85fn 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;