xtask/coverage/
objects.rs1use std::collections::HashSet;
5use std::fs::File;
6use std::os::unix::fs::{MetadataExt, PermissionsExt};
7use std::path::{Path, PathBuf};
8
9use anyhow::{Context, Result};
10
11use super::elf::{COVMAP_SECTION, elf_has_section};
12
13type FileId = (u64, u64);
15
16pub(super) fn instrumented_objects(dir: &Path) -> Result<Vec<PathBuf>> {
17 let mut found = Vec::new();
18 collect_objects(dir, &mut found)?;
19 found.sort();
20 Ok(dedupe_hardlinks(found))
21}
22
23fn collect_objects(dir: &Path, found: &mut Vec<(PathBuf, FileId)>) -> Result<()> {
24 let entries =
25 std::fs::read_dir(dir).with_context(|| format!("cannot read {}", dir.display()))?;
26 for entry in entries {
27 let entry = entry?;
28 let path = entry.path();
29 let file_type = entry.file_type()?;
30 if file_type.is_dir() {
31 collect_objects(&path, found)?;
32 continue;
33 }
34 let metadata = entry.metadata()?;
35 if file_type.is_file()
36 && is_candidate(&path, metadata.permissions().mode())
37 && has_coverage_map(&path)?
38 {
39 found.push((path, (metadata.dev(), metadata.ino())));
40 }
41 }
42 Ok(())
43}
44
45fn dedupe_hardlinks(entries: Vec<(PathBuf, FileId)>) -> Vec<PathBuf> {
47 let mut seen = HashSet::new();
48 entries
49 .into_iter()
50 .filter(|(_, id)| seen.insert(*id))
51 .map(|(path, _)| path)
52 .collect()
53}
54
55fn is_candidate(path: &Path, mode: u32) -> bool {
58 let name = path.file_name().and_then(|name| name.to_str());
59 if name
60 .is_some_and(|name| name.starts_with("build_script_") || name.starts_with("build-script-"))
61 {
62 return false;
63 }
64 match path.extension().and_then(|ext| ext.to_str()) {
65 Some("so" | "d") => false,
66 _ => mode & 0o111 != 0,
67 }
68}
69
70fn has_coverage_map(path: &Path) -> Result<bool> {
71 let mut file = File::open(path).with_context(|| format!("cannot open {}", path.display()))?;
72 elf_has_section(&mut file, COVMAP_SECTION)
73 .with_context(|| format!("cannot read {}", path.display()))
74}
75
76#[cfg(test)]
77mod tests;