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

            
19
mod elf;
20
mod export;
21
mod objects;
22
pub mod wrapper;
23

            
24
use std::ffi::OsString;
25
use std::path::{Path, PathBuf};
26
use std::process::Command;
27

            
28
use anyhow::{Context, Result, bail};
29

            
30
use crate::clean::remove_dir_if_present;
31
use crate::heartbeat::Heartbeat;
32
use crate::release::{DOC_DIR, run};
33
use export::{WORKERS, export_objects};
34

            
35
const PROFRAW_DIR: &str = "target/coverage";
36
const PROFDATA: &str = "target/coverage.profdata";
37
const LCOV_DIR: &str = "target/coverage-lcov";
38
const 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.
41
const INSTRUMENTED_RUSTFLAGS: &str = "--cfg anodized_panic";
42
const 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.
53
const DEBUG_LEVEL: &str = "line-tables-only";
54

            
55
/// Instrumented test run, then the HTML report.
56
pub 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

            
84
4
fn instrumented_env(
85
4
    pattern: &str,
86
4
    database_url: &str,
87
4
    wrapper_env: [(&'static str, OsString); 3],
88
4
) -> Vec<(&'static str, OsString)> {
89
4
    let mut env = vec![
90
4
        ("RUSTFLAGS", INSTRUMENTED_RUSTFLAGS.into()),
91
4
        ("CARGO_INCREMENTAL", "0".into()),
92
4
        ("CARGO_PROFILE_DEV_DEBUG", DEBUG_LEVEL.into()),
93
4
        ("CARGO_PROFILE_TEST_DEBUG", DEBUG_LEVEL.into()),
94
4
        ("LLVM_PROFILE_FILE", pattern.into()),
95
4
        ("DATABASE_URL", database_url.into()),
96
    ];
97
4
    env.extend(wrapper_env);
98
4
    env
99
4
}
100

            
101
1
fn profile_pattern(profraw_dir: &Path) -> String {
102
1
    profraw_dir
103
1
        .join("nomisync-%4m.profraw")
104
1
        .to_string_lossy()
105
1
        .into_owned()
106
1
}
107

            
108
fn 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.
157
1
fn llvm_bin() -> Result<PathBuf> {
158
1
    let output = Command::new("rustc")
159
1
        .args(["--print", "target-libdir"])
160
1
        .output()
161
1
        .context("failed to run rustc")?;
162
1
    if !output.status.success() {
163
        bail!("rustc --print target-libdir exited with {}", output.status);
164
1
    }
165
1
    let libdir = String::from_utf8(output.stdout).context("rustc printed a non-UTF-8 libdir")?;
166
    let bin =
167
1
        llvm_bin_for(Path::new(libdir.trim())).context("rustc's target libdir has no parent")?;
168
1
    require_llvm_tools(bin)
169
1
}
170

            
171
3
fn llvm_bin_for(libdir: &Path) -> Option<PathBuf> {
172
3
    libdir.parent().map(|host| host.join("bin"))
173
3
}
174

            
175
3
fn require_llvm_tools(bin: PathBuf) -> Result<PathBuf> {
176
3
    if !bin.join("llvm-profdata").is_file() {
177
1
        bail!(
178
            "no llvm-profdata in {} — install it with `rustup component add llvm-tools`",
179
1
            bin.display()
180
        );
181
2
    }
182
2
    Ok(bin)
183
3
}
184

            
185
2
fn merge_profiles(tool: &Path, profraw_dir: &Path, profdata: &Path) -> Result<()> {
186
2
    run(
187
2
        &tool.to_string_lossy(),
188
2
        &[
189
2
            "merge",
190
2
            "-sparse",
191
2
            &format!("--num-threads={WORKERS}"),
192
2
            "-o",
193
2
            &profdata.to_string_lossy(),
194
2
            &profraw_dir.to_string_lossy(),
195
2
        ],
196
2
        &[],
197
2
    )
198
2
}
199

            
200
3
fn 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
3
    remove_dir_if_present(coverage_dir)?;
204
3
    run(
205
3
        grcov,
206
3
        &[
207
3
            &lcov_dir.to_string_lossy(),
208
3
            "-s",
209
3
            ".",
210
3
            "-t",
211
3
            "html",
212
3
            "--branch",
213
3
            "--ignore-not-existing",
214
3
            "--ignore",
215
3
            "/*",
216
3
            "--ignore",
217
3
            "*cranelift*",
218
3
            "--ignore",
219
3
            "*lexicon*",
220
3
            "--ignore",
221
3
            "*incremental*",
222
3
            "-o",
223
3
            &coverage_dir.to_string_lossy(),
224
3
        ],
225
3
        &[],
226
3
    )?;
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
2
    let pages = std::fs::read_dir(coverage_dir)
232
        .with_context(|| format!("grcov produced no {}", coverage_dir.display()))?
233
        .count();
234
2
    if pages == 0 {
235
1
        bail!(
236
            "{} is empty — the coverage report has no pages",
237
1
            coverage_dir.display()
238
        );
239
1
    }
240
1
    println!(">> coverage report: {pages} entries");
241
1
    Ok(())
242
3
}
243

            
244
#[cfg(test)]
245
mod test_fixtures;
246
#[cfg(test)]
247
mod tests;
248
#[cfg(test)]
249
mod tool_tests;