1mod 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";
39const 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];
51const DEBUG_LEVEL: &str = "line-tables-only";
54
55pub 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 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 crate::watchdog::run_watched("cargo", NEXTEST_ARGS, &env, Some(database_url))?;
141
142 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
156fn 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 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 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;