use std::borrow::Cow;
use std::collections::BTreeMap;
use std::path::Path;
use addr2line::gimli;
use anyhow::Context as _;
use detcore_model::happens_before::Anchor;
use detcore_model::happens_before::CodeLocation;
use detcore_model::happens_before::HappensBeforeProgram;
use detcore_model::happens_before::HappensBeforeSpec;
use detcore_model::happens_before::Position;
use object::Object;
use object::ObjectSection;
use object::ObjectSymbol;
use object::SymbolKind;
#[derive(Clone, Copy, Debug)]
struct FuncExtent {
addr: u64,
size: u64,
}
impl FuncExtent {
fn contains(&self, addr: u64) -> bool {
if self.size == 0 {
addr == self.addr
} else {
addr >= self.addr && addr < self.addr + self.size
}
}
}
#[derive(Clone, Debug)]
struct LineRow {
addr: u64,
file: Option<String>,
line: u32,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ResolvedLocation {
pub function: Option<String>,
pub file: Option<String>,
pub line: Option<u32>,
}
pub struct DebugInfoResolver {
functions: BTreeMap<String, FuncExtent>,
lines: Vec<LineRow>,
}
impl DebugInfoResolver {
pub fn open(path: &Path) -> anyhow::Result<Self> {
let data = std::fs::read(path)
.with_context(|| format!("reading binary for debug info: {}", path.display()))?;
Self::from_bytes(&data)
.with_context(|| format!("parsing debug info from {}", path.display()))
}
pub fn from_bytes(data: &[u8]) -> anyhow::Result<Self> {
let object = object::File::parse(data)?;
let mut functions: BTreeMap<String, FuncExtent> = BTreeMap::new();
for sym in object.symbols() {
if sym.kind() != SymbolKind::Text {
continue;
}
let addr = sym.address();
if addr == 0 {
continue;
}
if let Ok(name) = sym.name() {
if name.is_empty() {
continue;
}
functions
.entry(name.to_string())
.and_modify(|e| {
if e.size == 0 && sym.size() > 0 {
*e = FuncExtent {
addr,
size: sym.size(),
};
}
})
.or_insert(FuncExtent {
addr,
size: sym.size(),
});
}
}
let lines = Self::load_line_rows(&object).unwrap_or_default();
Ok(Self { functions, lines })
}
fn load_line_rows(object: &object::File<'_>) -> anyhow::Result<Vec<LineRow>> {
let endian = if object.is_little_endian() {
gimli::RunTimeEndian::Little
} else {
gimli::RunTimeEndian::Big
};
let load_section = |id: gimli::SectionId| -> Result<Cow<'_, [u8]>, gimli::Error> {
match object.section_by_name(id.name()) {
Some(section) => Ok(section
.uncompressed_data()
.unwrap_or(Cow::Borrowed(&[][..]))),
None => Ok(Cow::Borrowed(&[][..])),
}
};
let dwarf_sections = gimli::DwarfSections::load(load_section)?;
let dwarf = dwarf_sections.borrow(|section| gimli::EndianSlice::new(section, endian));
let mut rows: Vec<LineRow> = Vec::new();
let mut units = dwarf.units();
while let Some(header) = units.next()? {
let unit = dwarf.unit(header)?;
let Some(program) = unit.line_program.clone() else {
continue;
};
let mut state = program.rows();
while let Some((header, row)) = state.next_row()? {
if row.end_sequence() {
continue;
}
let Some(line) = row.line() else {
continue;
};
let file = row.file(header).and_then(|file_entry| {
dwarf
.attr_string(&unit, file_entry.path_name())
.ok()
.and_then(|r| r.to_string().ok().map(basename))
});
rows.push(LineRow {
addr: row.address(),
file,
line: line.get() as u32,
});
}
}
rows.sort_by_key(|r| r.addr);
Ok(rows)
}
pub fn is_empty(&self) -> bool {
self.functions.is_empty() && self.lines.is_empty()
}
pub fn function_addr(&self, name: &str) -> Option<u64> {
self.functions.get(name).map(|e| e.addr)
}
pub fn line_addr(
&self,
file: Option<&str>,
line: u32,
within: Option<(u64, u64)>,
) -> Option<u64> {
let file_base = file.map(basename);
let extent = within.map(|(addr, size)| FuncExtent { addr, size });
self.lines
.iter()
.filter(|r| r.line == line)
.filter(|r| match (&file_base, &r.file) {
(Some(want), Some(have)) => want == have,
(Some(_), None) => false,
(None, _) => true,
})
.filter(|r| extent.map(|f| f.contains(r.addr)).unwrap_or(true))
.map(|r| r.addr)
.min()
}
pub fn resolve_location(&self, loc: &CodeLocation) -> Option<u64> {
match (&loc.function, loc.line) {
(Some(func), Some(line)) => {
let extent = self.functions.get(func).copied();
self.line_addr(loc.file.as_deref(), line, extent.map(|e| (e.addr, e.size)))
.or(extent.map(|e| e.addr))
}
(Some(func), None) => self.function_addr(func),
(None, Some(line)) => self.line_addr(loc.file.as_deref(), line, None),
(None, None) => None,
}
}
pub fn describe(&self, addr: u64) -> ResolvedLocation {
let function = self
.functions
.iter()
.filter(|(_, e)| e.contains(addr) || e.addr <= addr)
.max_by_key(|(_, e)| e.addr)
.map(|(name, _)| name.clone());
let idx = self.lines.partition_point(|r| r.addr <= addr);
let line_row = if idx > 0 {
self.lines.get(idx - 1)
} else {
None
};
ResolvedLocation {
function,
file: line_row.and_then(|r| r.file.clone()),
line: line_row.map(|r| r.line),
}
}
}
pub fn resolve_program(
program: &mut HappensBeforeProgram,
resolver: &DebugInfoResolver,
) -> Vec<String> {
let mut unresolved = Vec::new();
for (name, anchor) in program.anchors.iter_mut() {
if let Position::Rip { addr: None, nth } = &anchor.position {
let nth = *nth;
if let Some(resolved) = resolver.resolve_location(&anchor.location) {
anchor.position = Position::Rip {
addr: Some(resolved),
nth,
};
} else {
unresolved.push(name.clone());
}
}
}
unresolved
}
pub fn load_program(path: &Path) -> anyhow::Result<HappensBeforeProgram> {
let json = std::fs::read_to_string(path)
.with_context(|| format!("reading happens-before spec: {}", path.display()))?;
let spec = HappensBeforeSpec::from_json(&json)
.with_context(|| format!("parsing happens-before spec: {}", path.display()))?;
let program = spec
.normalize()
.with_context(|| format!("normalizing happens-before spec: {}", path.display()))?;
Ok(program)
}
pub fn describe_anchor(anchor: &Anchor, resolver: Option<&DebugInfoResolver>) -> String {
let mut out = format!("{}", anchor);
if let (Position::Rip { addr: Some(a), .. }, Some(r)) = (&anchor.position, resolver) {
let d = r.describe(*a);
let where_ = match (&d.function, &d.file, d.line) {
(Some(f), _, Some(l)) => format!(" -> {:#x} ({}:{})", a, f, l),
(Some(f), _, None) => format!(" -> {:#x} ({})", a, f),
_ => format!(" -> {:#x}", a),
};
out.push_str(&where_);
}
out
}
fn basename(s: &str) -> String {
match s.rsplit_once('/') {
Some((_, base)) => base.to_string(),
None => s.to_string(),
}
}
#[cfg(test)]
mod tests {
use std::process::Command;
use detcore_model::happens_before::HappensBeforeSpec;
use super::*;
fn compile_fixture() -> Option<std::path::PathBuf> {
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
static COUNTER: AtomicUsize = AtomicUsize::new(0);
let cc = ["cc", "gcc", "clang"]
.into_iter()
.find(|c| Command::new(c).arg("--version").output().is_ok())?;
let uniq = COUNTER.fetch_add(1, Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!("hb_fixture_{}_{}", std::process::id(), uniq));
std::fs::create_dir_all(&dir).ok()?;
let src = dir.join("fixture.c");
let bin = dir.join("fixture");
std::fs::write(
&src,
"int free_buffer(int x) { return x + 1; }\n\
int read_buffer(int x) { return x * 2; }\n\
int main(void) { return free_buffer(read_buffer(3)); }\n",
)
.ok()?;
let status = Command::new(cc)
.args(["-g", "-O0", "-o"])
.arg(&bin)
.arg(&src)
.status()
.ok()?;
if status.success() { Some(bin) } else { None }
}
#[test]
fn resolves_function_and_line_from_dwarf() {
let Some(bin) = compile_fixture() else {
eprintln!("skipping: no C compiler available");
return;
};
let resolver = DebugInfoResolver::open(&bin).unwrap();
assert!(!resolver.is_empty(), "expected symbols/lines in -g binary");
let free_addr = resolver.function_addr("free_buffer");
assert!(free_addr.is_some(), "free_buffer should resolve");
assert_ne!(free_addr.unwrap(), 0);
let loc = CodeLocation {
function: Some("free_buffer".to_string()),
file: None,
line: Some(1),
};
let addr = resolver.resolve_location(&loc);
assert!(addr.is_some(), "func+line should resolve");
let d = resolver.describe(free_addr.unwrap());
assert_eq!(d.function.as_deref(), Some("free_buffer"));
let _ = std::fs::remove_dir_all(bin.parent().unwrap());
}
#[test]
fn resolve_program_fills_rips() {
let Some(bin) = compile_fixture() else {
eprintln!("skipping: no C compiler available");
return;
};
let resolver = DebugInfoResolver::open(&bin).unwrap();
let json = r#"{
"version": 1,
"threads": { "t": {"label": "t"} },
"events": {
"A": {"thread": "t", "func": "free_buffer"},
"B": {"thread": "t", "func": "read_buffer", "line": 2}
},
"edges": [ {"before": "A", "after": "B"} ]
}"#;
let mut prog = HappensBeforeSpec::from_json(json)
.unwrap()
.normalize()
.unwrap();
assert_eq!(prog.unresolved_locations().count(), 2);
let missing = resolve_program(&mut prog, &resolver);
assert!(
missing.is_empty(),
"all locations should resolve: {:?}",
missing
);
assert_eq!(prog.unresolved_locations().count(), 0);
for anchor in prog.anchors.values() {
match &anchor.position {
Position::Rip { addr: Some(a), .. } => assert_ne!(*a, 0),
other => panic!("expected resolved RIP, got {:?}", other),
}
}
let _ = std::fs::remove_dir_all(bin.parent().unwrap());
}
#[test]
fn missing_function_reported() {
let Some(bin) = compile_fixture() else {
eprintln!("skipping: no C compiler available");
return;
};
let resolver = DebugInfoResolver::open(&bin).unwrap();
let json = r#"{
"version": 1,
"events": { "A": {"thread": "1", "func": "no_such_function"} },
"edges": []
}"#;
let mut prog = HappensBeforeSpec::from_json(json)
.unwrap()
.normalize()
.unwrap();
let missing = resolve_program(&mut prog, &resolver);
assert_eq!(missing, vec!["A".to_string()]);
let _ = std::fs::remove_dir_all(bin.parent().unwrap());
}
}