Skip to main content

xtask/coverage/
export.rs

1//! Exporting each instrumented object to lcov, several at a time, keeping only
2//! the workspace's own source records.
3
4use std::fs::File;
5use std::io::{BufRead, BufReader, BufWriter, Read, Write};
6use std::path::Path;
7use std::process::{Command, Stdio};
8use std::thread;
9
10use anyhow::{Context, Result, anyhow, bail};
11
12use super::objects::instrumented_objects;
13use crate::clean::remove_dir_if_present;
14
15/// Also the thread count of the profile merge: one bound for the whole phase.
16pub(super) const WORKERS: usize = 4;
17/// Sources llvm-cov need not even read: the registry, the toolchain's own
18/// sources and the system. The workspace filter below stays authoritative.
19const IGNORED_SOURCES: &str = "/registry/src/|/rustc/|/toolchains/|^/usr/";
20
21pub(super) fn export_objects(
22    tool: &Path,
23    profdata: &Path,
24    target_dir: &Path,
25    lcov_dir: &Path,
26    root: &str,
27) -> Result<usize> {
28    let objects = instrumented_objects(target_dir)?;
29    if objects.is_empty() {
30        bail!("no instrumented objects under {}", target_dir.display());
31    }
32    remove_dir_if_present(lcov_dir)?;
33    std::fs::create_dir_all(lcov_dir).context("cannot make the lcov dir")?;
34
35    let workspace_sources = thread::scope(|scope| {
36        let workers: Vec<_> = partition(&objects, WORKERS)
37            .into_iter()
38            .map(|share| {
39                scope.spawn(move || {
40                    share
41                        .into_iter()
42                        .try_fold(0usize, |total, (index, object)| {
43                            let info = lcov_dir.join(format!("{index}.info"));
44                            export_object(tool, profdata, object, &info, root)
45                                .map(|kept| total.saturating_add(kept))
46                        })
47                })
48            })
49            .collect();
50        workers
51            .into_iter()
52            .map(|worker| {
53                worker
54                    .join()
55                    .map_err(|_| anyhow!("an export worker panicked"))?
56            })
57            .try_fold(0usize, |total, kept| {
58                Ok::<_, anyhow::Error>(total.saturating_add(kept?))
59            })
60    })?;
61    // grcov still writes an index and badges when every source was ignored, so
62    // a checkout path llvm-cov does not report would otherwise publish a green,
63    // empty report.
64    if workspace_sources == 0 {
65        bail!("no lcov source path starts with {root}; the report would have no workspace files");
66    }
67    Ok(objects.len())
68}
69
70/// Deals the items out round-robin, each with its index in `items`.
71fn partition<T>(items: &[T], workers: usize) -> Vec<Vec<(usize, &T)>> {
72    let workers = workers.max(1);
73    let mut shares: Vec<Vec<(usize, &T)>> = (0..workers).map(|_| Vec::new()).collect();
74    for (index, item) in items.iter().enumerate() {
75        if let Some(share) = shares.get_mut(index % workers) {
76            share.push((index, item));
77        }
78    }
79    shares.retain(|share| !share.is_empty());
80    shares
81}
82
83/// Returns how many workspace source records were kept.
84pub(super) fn export_object(
85    tool: &Path,
86    profdata: &Path,
87    object: &Path,
88    info: &Path,
89    root: &str,
90) -> Result<usize> {
91    let mut child = Command::new(tool)
92        .args([
93            "export",
94            "-format=lcov",
95            "-ignore-filename-regex",
96            IGNORED_SOURCES,
97            "-instr-profile",
98        ])
99        .arg(profdata)
100        .arg(object)
101        .stdout(Stdio::piped())
102        .spawn()
103        .with_context(|| format!("failed to run {}", tool.display()))?;
104    let stdout = child
105        .stdout
106        .take()
107        .context("llvm-cov stdout was not captured")?;
108    // The reader is dropped before the wait, so a failed copy closes the pipe
109    // and llvm-cov exits instead of blocking on a full pipe.
110    let copied = copy_workspace_records(stdout, info, root);
111    let status = child
112        .wait()
113        .with_context(|| format!("llvm-cov export {} did not finish", object.display()))?;
114    let kept = copied?;
115    if !status.success() {
116        bail!("llvm-cov export {} exited with {status}", object.display());
117    }
118    Ok(kept)
119}
120
121/// Copies only the records of sources under `root`, with their paths made
122/// relative. The report ignores every absolute path anyway, and dropping the
123/// registry and toolchain records here keeps gigabytes of lcov off the disk.
124/// Returns how many records were kept.
125fn copy_workspace_records(lcov: impl Read, info: &Path, root: &str) -> Result<usize> {
126    let file = File::create(info).with_context(|| format!("cannot create {}", info.display()))?;
127    let mut writer = BufWriter::new(file);
128    let mut kept = 0usize;
129    let mut keep = false;
130    for line in BufReader::new(lcov).lines() {
131        let line = line?;
132        match line
133            .strip_prefix("SF:")
134            .map(|source| source.strip_prefix(root))
135        {
136            Some(Some(relative)) => {
137                keep = true;
138                kept = kept.saturating_add(1);
139                writeln!(writer, "SF:{relative}")?;
140            }
141            Some(None) => keep = false,
142            None if keep => writeln!(writer, "{line}")?,
143            None => {}
144        }
145    }
146    writer
147        .flush()
148        .with_context(|| format!("cannot write {}", info.display()))?;
149    Ok(kept)
150}
151
152#[cfg(test)]
153mod tests;