use crate::binary::Binary;
pub mod panics;
pub mod strings;
pub mod symbols;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AnnotationKind {
String,
Symbol,
PanicSite,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Annotation {
pub vaddr: u64,
pub kind: AnnotationKind,
pub label: String,
pub comment: Option<String>,
}
pub trait Analyzer: Sync {
fn name(&self) -> &'static str;
fn analyze(&self, bin: &Binary) -> Vec<Annotation>;
}
#[must_use = "Registry::run produces annotations; discard it and you'll regress the pipeline"]
pub struct Registry {
analyzers: Vec<Box<dyn Analyzer>>,
}
impl Registry {
pub fn new() -> Self {
Self {
analyzers: Vec::new(),
}
}
#[must_use = "appends an analyzer to the pipeline; discarding the returned Registry drops the analyzer from the chain"]
pub fn with(mut self, a: Box<dyn Analyzer>) -> Self {
self.analyzers.push(a);
self
}
#[must_use]
pub fn run(&self, bin: &Binary) -> Vec<Annotation> {
let mut out = Vec::new();
for a in &self.analyzers {
out.extend(a.analyze(bin));
}
out.sort_by(|x, y| {
x.vaddr
.cmp(&y.vaddr)
.then_with(|| kind_debug_rank(&x.kind).cmp(&kind_debug_rank(&y.kind)))
.then_with(|| x.label.cmp(&y.label))
.then_with(|| x.comment.cmp(&y.comment))
});
dedup(&mut out);
out
}
}
impl Default for Registry {
fn default() -> Self {
Self::new()
}
}
fn dedup(out: &mut Vec<Annotation>) {
out.dedup_by(|a, b| {
a.vaddr == b.vaddr && a.kind == b.kind && a.label == b.label && a.comment == b.comment
});
}
const fn kind_debug_rank(kind: &AnnotationKind) -> u8 {
use AnnotationKind::{PanicSite, String as KString, Symbol};
match kind {
PanicSite => 0,
KString => 1,
Symbol => 2,
}
}
#[derive(Debug, Clone)]
pub struct Limits {
pub max_string_len: usize,
pub max_line: u32,
pub max_col: u32,
}
pub(super) const MAX_RECOVERED_ANNOTATIONS: usize = 65_536;
pub(super) const MAX_RECOVERED_TEXT_BYTES: usize = 16 * 1024 * 1024;
const RECOVERED_TEXT_BACKING_MULTIPLIER: usize = 2;
#[derive(Debug)]
pub(super) struct RecoveredAnnotationBudget {
max_annotations: usize,
annotations: usize,
remaining_text_bytes: usize,
}
impl RecoveredAnnotationBudget {
pub(super) fn for_string_sections(bin: &Binary, word_size: usize) -> Self {
let backing_bytes = bin
.sections()
.iter()
.enumerate()
.filter(|(index, _)| bin.is_string_section_index(*index))
.map(|(_, section)| section)
.fold(0usize, |total, section| {
total.saturating_add(section.data.len())
});
let max_annotations = backing_bytes
.checked_div(word_size.max(1))
.unwrap_or(0)
.min(MAX_RECOVERED_ANNOTATIONS);
let remaining_text_bytes = backing_bytes
.saturating_mul(RECOVERED_TEXT_BACKING_MULTIPLIER)
.min(MAX_RECOVERED_TEXT_BYTES);
Self {
max_annotations,
annotations: 0,
remaining_text_bytes,
}
}
pub(super) const fn annotation_limit_reached(&self) -> bool {
self.annotations >= self.max_annotations
}
pub(super) const fn can_fit_annotation_with_minimum_text(
&self,
minimum_text_bytes: usize,
) -> bool {
!self.annotation_limit_reached() && minimum_text_bytes <= self.remaining_text_bytes
}
pub(super) const fn cannot_fit_any_annotation(&self, minimum_text_bytes: usize) -> bool {
!self.can_fit_annotation_with_minimum_text(minimum_text_bytes)
}
pub(super) const fn try_consume(&mut self, text_bytes: usize) -> bool {
if !self.can_fit_annotation_with_minimum_text(text_bytes) {
return false;
}
self.annotations += 1;
self.remaining_text_bytes -= text_bytes;
true
}
}
impl Default for Limits {
fn default() -> Self {
Self {
max_string_len: 4096,
max_line: 1_000_000,
max_col: 10_000,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::binary::Binary;
struct MockAnalyzer {
anns: Vec<Annotation>,
}
impl Analyzer for MockAnalyzer {
fn name(&self) -> &'static str {
"mock"
}
fn analyze(&self, _bin: &Binary) -> Vec<Annotation> {
self.anns.clone()
}
}
fn mock_bin() -> Binary {
Binary::from_test_parts(
crate::binary::BinaryFormat::Elf,
true,
true,
vec![],
vec![],
vec![],
)
}
fn ann(vaddr: u64, kind: AnnotationKind, label: &str) -> Annotation {
Annotation {
vaddr,
kind,
label: label.into(),
comment: None,
}
}
#[test]
fn constants_distinct() {
let lim = Limits::default();
assert!(lim.max_line >= 100_000);
assert!(lim.max_col >= 100);
}
#[test]
fn recovered_annotation_budget_blocks_count_and_text_amplification() {
let bin = Binary::from_test_parts(
crate::binary::BinaryFormat::Elf,
true,
true,
vec![crate::binary::Section {
name: ".rodata".into(),
vaddr: 0x1000,
size: 16,
data: vec![0; 16],
}],
vec![],
vec![0],
);
let mut text_budget = RecoveredAnnotationBudget::for_string_sections(&bin, 8);
assert_eq!(text_budget.remaining_text_bytes, 32);
assert!(text_budget.try_consume(31));
assert!(!text_budget.try_consume(2));
let mut count_budget = RecoveredAnnotationBudget::for_string_sections(&bin, 8);
assert!(count_budget.try_consume(0));
assert!(count_budget.try_consume(0));
assert!(count_budget.annotation_limit_reached());
assert!(!count_budget.try_consume(0));
}
#[test]
fn recovered_annotation_budget_stops_at_hard_limits() {
let mut text_budget = RecoveredAnnotationBudget {
max_annotations: MAX_RECOVERED_ANNOTATIONS,
annotations: 0,
remaining_text_bytes: MAX_RECOVERED_TEXT_BYTES,
};
assert!(text_budget.try_consume(MAX_RECOVERED_TEXT_BYTES - 1));
assert!(!text_budget.try_consume(2));
let mut count_budget = RecoveredAnnotationBudget {
max_annotations: MAX_RECOVERED_ANNOTATIONS,
annotations: MAX_RECOVERED_ANNOTATIONS - 1,
remaining_text_bytes: MAX_RECOVERED_TEXT_BYTES,
};
assert!(count_budget.try_consume(1));
assert!(!count_budget.try_consume(1));
}
#[test]
fn recovered_annotation_budget_queries_respect_text_and_count_capacity() {
let mut budget = RecoveredAnnotationBudget {
max_annotations: 2,
annotations: 0,
remaining_text_bytes: 8,
};
assert!(budget.can_fit_annotation_with_minimum_text(8));
assert!(!budget.cannot_fit_any_annotation(8));
assert!(!budget.can_fit_annotation_with_minimum_text(9));
assert!(budget.cannot_fit_any_annotation(9));
assert!(budget.try_consume(4));
assert!(budget.can_fit_annotation_with_minimum_text(4));
assert!(budget.try_consume(4));
assert!(budget.cannot_fit_any_annotation(0));
}
#[test]
fn registry_dedup_removes_identical() {
let a = ann(0x1000, AnnotationKind::String, "hello");
let bin = mock_bin();
let r = Registry::new().with(Box::new(MockAnalyzer {
anns: vec![a.clone(), a.clone(), a],
}));
assert_eq!(r.run(&bin).len(), 1);
}
#[test]
fn registry_dedup_preserves_distinct() {
let bin = mock_bin();
let r = Registry::new().with(Box::new(MockAnalyzer {
anns: vec![
ann(0x1000, AnnotationKind::String, "a"),
ann(0x2000, AnnotationKind::Symbol, "b"),
ann(0x3000, AnnotationKind::PanicSite, "c"),
],
}));
assert_eq!(r.run(&bin).len(), 3);
}
#[test]
fn registry_dedup_preserves_different_kind() {
let bin = mock_bin();
let r = Registry::new().with(Box::new(MockAnalyzer {
anns: vec![
ann(0x1000, AnnotationKind::String, "x"),
ann(0x1000, AnnotationKind::Symbol, "x"),
],
}));
assert_eq!(r.run(&bin).len(), 2);
}
#[test]
fn registry_dedup_preserves_different_label() {
let bin = mock_bin();
let r = Registry::new().with(Box::new(MockAnalyzer {
anns: vec![
ann(0x1000, AnnotationKind::String, "foo"),
ann(0x1000, AnnotationKind::String, "bar"),
],
}));
assert_eq!(r.run(&bin).len(), 2);
}
#[test]
fn registry_dedup_preserves_different_comment() {
let bin = mock_bin();
let r = Registry::new().with(Box::new(MockAnalyzer {
anns: vec![
Annotation {
vaddr: 0x1000,
kind: AnnotationKind::String,
label: "x".into(),
comment: Some("c1".into()),
},
Annotation {
vaddr: 0x1000,
kind: AnnotationKind::String,
label: "x".into(),
comment: Some("c2".into()),
},
],
}));
assert_eq!(r.run(&bin).len(), 2);
}
#[test]
fn registry_dedup_removes_exact_duplicates_when_comments_interleave() {
let bin = mock_bin();
let duplicate = Annotation {
vaddr: 0x1000,
kind: AnnotationKind::String,
label: "x".into(),
comment: Some("c1".into()),
};
let r = Registry::new().with(Box::new(MockAnalyzer {
anns: vec![
duplicate.clone(),
Annotation {
comment: Some("c2".into()),
..duplicate.clone()
},
duplicate,
],
}));
assert_eq!(r.run(&bin).len(), 2);
}
#[test]
fn registry_dedup_preserves_none_vs_some_comment() {
let bin = mock_bin();
let r = Registry::new().with(Box::new(MockAnalyzer {
anns: vec![
Annotation {
vaddr: 0x1000,
kind: AnnotationKind::String,
label: "x".into(),
comment: None,
},
Annotation {
vaddr: 0x1000,
kind: AnnotationKind::String,
label: "x".into(),
comment: Some("c".into()),
},
],
}));
assert_eq!(r.run(&bin).len(), 2);
}
#[test]
fn registry_dedup_removes_after_sort() {
let a = ann(0x1000, AnnotationKind::String, "hello");
let b = ann(0x2000, AnnotationKind::Symbol, "world");
let bin = mock_bin();
let r = Registry::new().with(Box::new(MockAnalyzer {
anns: vec![a.clone(), b, a],
}));
assert_eq!(r.run(&bin).len(), 2);
}
#[test]
fn registry_dedup_preserves_different_vaddr_same_rest() {
let bin = mock_bin();
let r = Registry::new().with(Box::new(MockAnalyzer {
anns: vec![
ann(0x1000, AnnotationKind::String, "hello"),
ann(0x2000, AnnotationKind::String, "hello"),
],
}));
assert_eq!(
r.run(&bin).len(),
2,
"different vaddr + same kind/label/comment must NOT dedup"
);
}
#[test]
fn kind_debug_rank_matches_debug_string_order() {
let kinds = [
AnnotationKind::PanicSite,
AnnotationKind::String,
AnnotationKind::Symbol,
];
let mut by_rank: Vec<&AnnotationKind> = kinds.iter().collect();
by_rank.sort_by_key(|kind| kind_debug_rank(kind));
let mut by_debug: Vec<&AnnotationKind> = kinds.iter().collect();
by_debug.sort_by_key(|kind| format!("{kind:?}"));
assert_eq!(by_rank, by_debug);
}
#[test]
fn registry_run_orders_same_vaddr_kinds_by_debug_string() {
let bin = mock_bin();
let r = Registry::new().with(Box::new(MockAnalyzer {
anns: vec![
ann(0x1000, AnnotationKind::Symbol, "x"),
ann(0x1000, AnnotationKind::String, "x"),
ann(0x1000, AnnotationKind::PanicSite, "x"),
],
}));
let kinds: Vec<AnnotationKind> = r.run(&bin).into_iter().map(|a| a.kind).collect();
assert_eq!(
kinds,
vec![
AnnotationKind::PanicSite,
AnnotationKind::String,
AnnotationKind::Symbol
],
"same-vaddr kinds must stay ordered by their debug-string names"
);
}
}