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 detcore_model::happens_before::syscall_never_reaches_tracer;
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)
}
#[derive(Debug, Clone, Copy)]
pub struct HbLaunch<'a> {
pub backend: &'a str,
pub ptrace: bool,
pub namespace_only: bool,
pub passthru_opt: bool,
pub preemption: bool,
pub replay_schedule: bool,
}
pub fn refuse_unenforceable_anchors(
program: &HappensBeforeProgram,
path: &Path,
launch: HbLaunch<'_>,
) -> anyhow::Result<()> {
for anchor in program.anchors.values() {
let refusal = match &anchor.position {
Position::Syscall { .. } if !anchor.is_syscall_occurrence() => {
"names the polling phase, which is not enforced; syscall anchors fire at the \
prehook or, with \"phase\": \"posthook\", when the syscall completes"
.to_owned()
}
Position::Syscall { .. } if anchor.fires_at_posthook() && launch.replay_schedule => {
"fires at the posthook, which is not supported with --replay-schedule-from: \
its gate adds a scheduler turn the recorded schedule does not have"
.to_owned()
}
Position::Syscall { sysno, .. } if syscall_never_reaches_tracer(*sysno) => format!(
"names {}, which never reaches Hermit's tracer: it runs untraced so the \
signal frame is restored safely",
sysno.name()
),
Position::Syscall { .. } | Position::SyscallCount(_) => {
let kind = if anchor.is_syscall_occurrence() {
"syscall-occurrence anchor"
} else {
"count anchor"
};
if launch.namespace_only {
format!(
"is a {kind}, but --namespace-only runs the guest without interception \
or a scheduler"
)
} else if !launch.ptrace {
format!(
"is a {kind}, which is enforced only on the ptrace backend; this run \
selected the {} backend",
launch.backend
)
} else if launch.passthru_opt && anchor.is_syscall_occurrence() {
format!(
"is a {kind}, which needs every syscall intercepted; --passthru-opt \
leaves some unintercepted"
)
} else {
continue;
}
}
_ => continue,
};
anyhow::bail!(
"happens-before spec {}: anchor '{}' ({}) {}",
path.display(),
anchor.name,
anchor.position,
refusal
);
}
if !launch.preemption {
refuse_hold_without_preemption(
program,
path,
"--max-timeslice disabled turns the preemption timer off",
)?;
}
Ok(())
}
pub fn refuse_hold_without_preemption(
program: &HappensBeforeProgram,
path: &Path,
reason: &str,
) -> anyhow::Result<()> {
if !program.is_version_2() {
return Ok(());
}
anyhow::bail!(
"HERMIT_HB_HOLD_WITHOUT_PREEMPTION: happens-before spec {} is version {}, which bounds \
every hold by max_hold_ns and needs the preemption timer to charge it, but {}",
path.display(),
program.version,
reason
)
}
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());
}
#[test]
fn launch_refuses_every_anchor_it_cannot_enforce() {
let dir = tempfile::tempdir().unwrap();
let spec = dir.path().join("spec.json");
let ptrace = HbLaunch {
backend: "Ptrace",
ptrace: true,
namespace_only: false,
passthru_opt: false,
preemption: true,
replay_schedule: false,
};
let check = |json: &str, launch: HbLaunch<'_>| -> Result<(), String> {
std::fs::write(&spec, json).unwrap();
let program = load_program(&spec).expect("every spec here loads for preview");
refuse_unenforceable_anchors(&program, &spec, launch).map_err(|e| e.to_string())
};
let fd_anchor = r#"{"version": 1,
"events": {"w": {"thread": "3", "syscall": "write", "fd": 1}}}"#;
let err = check(
r#"{"version": 1,
"events": {"closed": {"thread": "3", "syscall": "close", "fd": 4, "phase": "polling"}}}"#,
ptrace,
)
.unwrap_err();
assert!(
err.contains("anchor 'closed'")
&& err.contains("names the polling phase, which is not enforced"),
"{err}"
);
let err = check(
r#"{"version": 1, "events": {"ret": {"thread": "3", "syscall": "rt_sigreturn"}}}"#,
ptrace,
)
.unwrap_err();
assert!(
err.contains("anchor 'ret'") && err.contains("never reaches Hermit's tracer"),
"{err}"
);
let err = check(
fd_anchor,
HbLaunch {
namespace_only: true,
..ptrace
},
)
.unwrap_err();
assert!(
err.contains("anchor 'w'") && err.contains("--namespace-only"),
"{err}"
);
let err = check(
fd_anchor,
HbLaunch {
backend: "Kvm",
ptrace: false,
..ptrace
},
)
.unwrap_err();
assert!(
err.contains("anchor 'w'") && err.contains("the Kvm backend"),
"{err}"
);
let err = check(
fd_anchor,
HbLaunch {
passthru_opt: true,
..ptrace
},
)
.unwrap_err();
assert!(
err.contains("anchor 'w'") && err.contains("--passthru-opt"),
"{err}"
);
assert!(check(fd_anchor, ptrace).is_ok());
let posthook = r#"{"version": 1,
"events": {"p": {"thread": "3", "syscall": "write", "fd": 1, "phase": "posthook"}}}"#;
assert!(check(posthook, ptrace).is_ok());
let replay = HbLaunch {
replay_schedule: true,
..ptrace
};
let err = check(posthook, replay).unwrap_err();
assert!(
err.contains("anchor 'p'") && err.contains("not supported with --replay-schedule-from"),
"{err}"
);
assert!(check(fd_anchor, replay).is_ok());
assert!(
check(
r#"{"version": 1,
"events": {"closed": {"thread": "3", "syscall": "close", "fd": 4, "phase": "pre"}}}"#,
ptrace
)
.is_ok()
);
let count_only = r#"{"version": 1, "events": {"c": {"thread": "3", "syscalls": 5}}}"#;
let err = check(
count_only,
HbLaunch {
namespace_only: true,
..ptrace
},
)
.unwrap_err();
assert!(
err.contains("anchor 'c' (after 5 syscalls) is a count anchor, but --namespace-only"),
"{err}"
);
let err = check(
count_only,
HbLaunch {
backend: "Sabre",
ptrace: false,
..ptrace
},
)
.unwrap_err();
assert!(
err.contains("is a count anchor, which is enforced only on the ptrace backend")
&& err.contains("the Sabre backend"),
"{err}"
);
assert!(
check(
count_only,
HbLaunch {
passthru_opt: true,
..ptrace
}
)
.is_ok()
);
assert!(check(count_only, ptrace).is_ok());
let v2 = r#"{"version": 2, "events": {"w": {"thread": "3", "syscall": "write", "fd": 1}}}"#;
let no_timer = HbLaunch {
preemption: false,
..ptrace
};
let err = check(v2, no_timer).unwrap_err();
assert!(
err.starts_with("HERMIT_HB_HOLD_WITHOUT_PREEMPTION: happens-before spec ")
&& err.contains("is version 2")
&& err.ends_with("but --max-timeslice disabled turns the preemption timer off"),
"{err}"
);
assert!(check(v2, ptrace).is_ok());
assert!(check(fd_anchor, no_timer).is_ok());
}
}