Skip to main content

xtask/
coverage.rs

1//! The coverage phase: an instrumented test run rendered into
2//! `web/static/doc/coverage`.
3//!
4//! Only the workspace's crates are instrumented (see [`wrapper`]), so wasmtime
5//! and cranelift run at full speed and leave no profiles to merge or export.
6//!
7//! grcov can read the raw profiles itself, but it then holds every binary's
8//! results at once and runs one `llvm-cov` per CPU — about 13 GiB for this
9//! workspace, enough to OOM-kill the job on an 8 GiB CI node. So the profiles
10//! are merged here, each test executable and binary is exported to lcov on its
11//! own, a few at a time, and grcov only renders. Exporting per object keeps
12//! grcov's numbers: one export over every object discards the counters of
13//! functions compiled differently in different binaries.
14//!
15//! Unlike grcov, which skips an object llvm-cov cannot export, a failed export
16//! fails the phase: every exported object carries a real coverage map, so a
17//! failure means a broken build, and a quietly lower percentage would hide it.
18
19mod elf;
20mod export;
21mod objects;
22pub mod wrapper;
23
24use std::ffi::OsString;
25use std::path::{Path, PathBuf};
26use std::process::Command;
27
28use anyhow::{Context, Result, bail};
29
30use crate::clean::remove_dir_if_present;
31use crate::heartbeat::Heartbeat;
32use crate::release::{DOC_DIR, run};
33use export::{WORKERS, export_objects};
34
35const PROFRAW_DIR: &str = "target/coverage";
36const PROFDATA: &str = "target/coverage.profdata";
37const LCOV_DIR: &str = "target/coverage-lcov";
38const TARGET_DIR: &str = "target/debug";
39/// Runtime checks of every anodized `#[spec]`; the macros read it when they
40/// compile, so it must reach every crate, not just the instrumented ones.
41const INSTRUMENTED_RUSTFLAGS: &str = "--cfg anodized_panic";
42const NEXTEST_ARGS: &[&str] = &[
43    "nextest",
44    "run",
45    "--no-fail-fast",
46    "--all-features",
47    "--workspace",
48    "--test-threads",
49    "4",
50];
51/// Coverage mapping needs only line tables, and full debuginfo made the
52/// instrumented build and its test binaries much larger.
53const DEBUG_LEVEL: &str = "line-tables-only";
54
55/// Instrumented test run, then the HTML report.
56pub fn run_coverage(heartbeat: &Heartbeat, database_url: &str) -> Result<()> {
57    let cwd = std::env::current_dir()?;
58    let profraw_dir = cwd.join(PROFRAW_DIR);
59    instrumented_test_run(heartbeat, &cwd, &profraw_dir, database_url)?;
60
61    let llvm_bin = llvm_bin()?;
62    let profdata = Path::new(PROFDATA);
63    heartbeat.phase("merge profiles");
64    merge_profiles(&llvm_bin.join("llvm-profdata"), &profraw_dir, profdata)?;
65
66    heartbeat.phase("llvm-cov export");
67    let exported = export_objects(
68        &llvm_bin.join("llvm-cov"),
69        profdata,
70        Path::new(TARGET_DIR),
71        Path::new(LCOV_DIR),
72        &format!("{}/", cwd.display()),
73    )?;
74    println!(">> exported {exported} instrumented objects");
75
76    heartbeat.phase("grcov");
77    render_html(
78        "grcov",
79        Path::new(LCOV_DIR),
80        &PathBuf::from(DOC_DIR).join("coverage"),
81    )
82}
83
84fn instrumented_env(
85    pattern: &str,
86    database_url: &str,
87    wrapper_env: [(&'static str, OsString); 3],
88) -> Vec<(&'static str, OsString)> {
89    let mut env = vec![
90        ("RUSTFLAGS", INSTRUMENTED_RUSTFLAGS.into()),
91        ("CARGO_INCREMENTAL", "0".into()),
92        ("CARGO_PROFILE_DEV_DEBUG", DEBUG_LEVEL.into()),
93        ("CARGO_PROFILE_TEST_DEBUG", DEBUG_LEVEL.into()),
94        ("LLVM_PROFILE_FILE", pattern.into()),
95        ("DATABASE_URL", database_url.into()),
96    ];
97    env.extend(wrapper_env);
98    env
99}
100
101fn profile_pattern(profraw_dir: &Path) -> String {
102    profraw_dir
103        .join("nomisync-%4m.profraw")
104        .to_string_lossy()
105        .into_owned()
106}
107
108fn instrumented_test_run(
109    heartbeat: &Heartbeat,
110    root: &Path,
111    profraw_dir: &Path,
112    database_url: &str,
113) -> Result<()> {
114    // `%4m` merges online into at most four files per binary signature, so the
115    // pool stays small however many processes the suite starts.
116    remove_dir_if_present(profraw_dir)?;
117    std::fs::create_dir_all(profraw_dir).context("cannot make the profraw dir")?;
118    let profile_pattern = profile_pattern(profraw_dir);
119
120    let previous = std::env::var_os("RUSTC_WRAPPER").unwrap_or_default();
121    let exe = std::env::current_exe().context("cannot find the xtask executable")?;
122    let env = instrumented_env(
123        &profile_pattern,
124        database_url,
125        wrapper::wrapper_env(&exe, &previous, root),
126    );
127    let env: Vec<(&str, &str)> = env
128        .iter()
129        .map(|(key, value)| Ok((*key, value.to_str().context("non-UTF-8 environment")?)))
130        .collect::<Result<_>>()?;
131
132    heartbeat.phase("instrumented test run");
133    // Watched, unlike every other phase here: this one prints a line per test,
134    // so silence means something is stuck rather than merely slow. A hang here
135    // once cost an hour and told us nothing about which test caused it.
136    // Nextest runs every test in its own process and every binary at once, so
137    // a 4-vCPU node stays busy. Doctests are not run: their binaries are
138    // temporary and never reach the coverage export.
139    // `--no-fail-fast`: one red test must not hide the others in the report.
140    crate::watchdog::run_watched("cargo", NEXTEST_ARGS, &env, Some(database_url))?;
141
142    // A coverage run that produced no profiles yields an empty-but-valid grcov
143    // report: green CI, blank coverage page. Assert instead.
144    let profraw_count = std::fs::read_dir(profraw_dir)
145        .context("cannot read the profraw dir")?
146        .filter_map(Result::ok)
147        .filter(|entry| entry.path().extension().is_some_and(|ext| ext == "profraw"))
148        .count();
149    if profraw_count == 0 {
150        bail!("no .profraw produced — coverage instrumentation did not run");
151    }
152    println!(">> {profraw_count} profraw files");
153    Ok(())
154}
155
156/// `llvm-tools` installs its binaries beside the host target's libdir.
157fn llvm_bin() -> Result<PathBuf> {
158    let output = Command::new("rustc")
159        .args(["--print", "target-libdir"])
160        .output()
161        .context("failed to run rustc")?;
162    if !output.status.success() {
163        bail!("rustc --print target-libdir exited with {}", output.status);
164    }
165    let libdir = String::from_utf8(output.stdout).context("rustc printed a non-UTF-8 libdir")?;
166    let bin =
167        llvm_bin_for(Path::new(libdir.trim())).context("rustc's target libdir has no parent")?;
168    require_llvm_tools(bin)
169}
170
171fn llvm_bin_for(libdir: &Path) -> Option<PathBuf> {
172    libdir.parent().map(|host| host.join("bin"))
173}
174
175fn require_llvm_tools(bin: PathBuf) -> Result<PathBuf> {
176    if !bin.join("llvm-profdata").is_file() {
177        bail!(
178            "no llvm-profdata in {} — install it with `rustup component add llvm-tools`",
179            bin.display()
180        );
181    }
182    Ok(bin)
183}
184
185fn merge_profiles(tool: &Path, profraw_dir: &Path, profdata: &Path) -> Result<()> {
186    run(
187        &tool.to_string_lossy(),
188        &[
189            "merge",
190            "-sparse",
191            &format!("--num-threads={WORKERS}"),
192            "-o",
193            &profdata.to_string_lossy(),
194            &profraw_dir.to_string_lossy(),
195        ],
196        &[],
197    )
198}
199
200fn render_html(grcov: &str, lcov_dir: &Path, coverage_dir: &Path) -> Result<()> {
201    // Stale trees must go first: `mv target/doc <existing>` nests the new tree
202    // inside the old one, silently pinning published pages to a snapshot.
203    remove_dir_if_present(coverage_dir)?;
204    run(
205        grcov,
206        &[
207            &lcov_dir.to_string_lossy(),
208            "-s",
209            ".",
210            "-t",
211            "html",
212            "--branch",
213            "--ignore-not-existing",
214            "--ignore",
215            "/*",
216            "--ignore",
217            "*cranelift*",
218            "--ignore",
219            "*lexicon*",
220            "--ignore",
221            "*incremental*",
222            "-o",
223            &coverage_dir.to_string_lossy(),
224        ],
225        &[],
226    )?;
227
228    // grcov exits zero on an empty profile set, so the tree existing is not the
229    // same as the tree having content. This job is the only place that can tell,
230    // and it is the artifact deploy will overlay.
231    let pages = std::fs::read_dir(coverage_dir)
232        .with_context(|| format!("grcov produced no {}", coverage_dir.display()))?
233        .count();
234    if pages == 0 {
235        bail!(
236            "{} is empty — the coverage report has no pages",
237            coverage_dir.display()
238        );
239    }
240    println!(">> coverage report: {pages} entries");
241    Ok(())
242}
243
244#[cfg(test)]
245mod test_fixtures;
246#[cfg(test)]
247mod tests;
248#[cfg(test)]
249mod tool_tests;