use anyhow::{bail, Context};
use elf::{endian::AnyEndian, ElfBytes};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
const PROVIDER: &str = "ddheap";
pub fn check_usdt_probes_in(path: &Path, expected_probes: &[&str]) -> anyhow::Result<()> {
let data = std::fs::read(path).with_context(|| format!("failed to read {}", path.display()))?;
let elf = ElfBytes::<AnyEndian>::minimal_parse(&data)
.with_context(|| format!("failed to parse ELF at {}", path.display()))?;
check_one_note_per_probe(&elf, expected_probes)?;
Ok(())
}
pub fn sanity_check() -> anyhow::Result<()> {
let mut expected = vec!["alloc"];
if cfg!(feature = "live-heap") {
expected.push("free");
}
check_usdt_probes_in(&own_elf_path()?, &expected)
}
fn own_elf_path() -> anyhow::Result<PathBuf> {
let addr = sanity_check as *const () as usize;
let maps =
std::fs::read_to_string("/proc/self/maps").context("failed to read /proc/self/maps")?;
for line in maps.lines() {
let mut rest = line;
for _ in 0..5 {
rest = rest.trim_start_matches(|c: char| c.is_ascii_whitespace());
rest = rest.trim_start_matches(|c: char| !c.is_ascii_whitespace());
}
let path = rest.trim_start_matches(|c: char| c.is_ascii_whitespace());
if !path.starts_with('/') {
continue;
}
if let Some((start_str, end_str)) = line
.split_whitespace()
.next()
.and_then(|f| f.split_once('-'))
{
let start = usize::from_str_radix(start_str, 16).unwrap_or(0);
let end = usize::from_str_radix(end_str, 16).unwrap_or(0);
if addr >= start && addr < end {
return Ok(PathBuf::from(path));
}
}
}
bail!("could not find our own object file in /proc/self/maps")
}
fn check_one_note_per_probe(
elf: &ElfBytes<'_, AnyEndian>,
expected_probes: &[&str],
) -> anyhow::Result<()> {
let shdr = elf
.section_header_by_name(".note.stapsdt")
.context("failed to read section headers")?
.context("no .note.stapsdt section: USDT probes are missing from this object")?;
let notes = elf
.section_data_as_notes(&shdr)
.context("failed to parse .note.stapsdt")?;
let word = if elf.ehdr.class == elf::file::Class::ELF64 {
8
} else {
4
};
let mut counts: BTreeMap<String, usize> = BTreeMap::new();
for note in notes {
let elf::note::Note::Unknown(any) = note else {
continue;
};
if any.name != "stapsdt" {
continue;
}
let strings = any.desc.get(3 * word..).unwrap_or(&[]);
let mut parts = strings.split(|&b| b == 0);
let provider = parts.next().unwrap_or(&[]);
let probe = parts.next().unwrap_or(&[]);
if provider == PROVIDER.as_bytes() {
if let Ok(name) = std::str::from_utf8(probe) {
*counts.entry(name.to_string()).or_default() += 1;
}
}
}
for &probe in expected_probes {
match counts.get(probe).copied().unwrap_or(0) {
1 => {}
0 => bail!("USDT probe '{PROVIDER}:{probe}' has no .note.stapsdt entry"),
n => bail!(
"USDT probe '{PROVIDER}:{probe}' has {n} .note.stapsdt entries, expected 1 \
(duplicate entries make an attached consumer fire twice)"
),
}
}
Ok(())
}