rustrip 0.1.1

Make stripped Rust binaries readable again: recover slice-string boundaries, demangle symbols, and reconstruct panic source locations from release/stripped ELF/PE binaries.
Documentation
//! Pluggable analyzer framework.
//!
//! An analyzer takes a parsed [`Binary`] and produces a `Vec<Annotation>`.
//! The pipeline is simple: every analyzer is independent, the registry
//! aggregates, and a single output backend renders the merged set.

use crate::binary::Binary;

pub mod panics;
pub mod strings;
pub mod symbols;

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AnnotationKind {
    /// Recovered `&str` slice (Rust fat pointer). The `vaddr` is the *string*
    /// location, not the slice-header location.
    String,
    /// Demangled symbol name.
    Symbol,
    /// Panic/Unwrap/Expect site with `file:line:col`.
    PanicSite,
}

/// A single recovered artifact from the binary (string, symbol, or panic site).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Annotation {
    /// Virtual address of the artifact.
    pub vaddr: u64,
    /// What kind of artifact this is.
    pub kind: AnnotationKind,
    /// Human-readable label (string content, demangled name, or `file:line:col`).
    pub label: String,
    /// Optional comment (e.g. recovered source path for a string).
    pub comment: Option<String>,
}

/// Trait for a single analysis pass over a [`Binary`].
///
/// Implementations must be `Sync` so the registry can be shared across threads.
pub trait Analyzer: Sync {
    /// Short identifier for this analyzer (e.g. `"strings"`, `"panics"`).
    fn name(&self) -> &'static str;
    /// Run the analysis pass and return all annotations found.
    fn analyze(&self, bin: &Binary) -> Vec<Annotation>;
}

/// Aggregates multiple analyzers and runs them in order.
#[must_use = "Registry::run produces annotations; discard it and you'll regress the pipeline"]
pub struct Registry {
    analyzers: Vec<Box<dyn Analyzer>>,
}

impl Registry {
    /// Create an empty registry.
    pub fn new() -> Self {
        Self {
            analyzers: Vec::new(),
        }
    }

    /// Builder-style construction. Cheap; returns `self` for chaining.
    #[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
    }

    /// Apply every registered analyzer to `bin` and return a sorted,
    /// de-duplicated annotation list.
    #[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));
        }
        // Stable order — helps determinism for snapshot tests & JSON output.
        out.sort_by(|x, y| {
            x.vaddr
                .cmp(&y.vaddr)
                .then_with(|| format!("{:?}", x.kind).cmp(&format!("{:?}", y.kind)))
                .then_with(|| x.label.cmp(&y.label))
        });
        dedup(&mut out);
        out
    }
}

impl Default for Registry {
    fn default() -> Self {
        Self::new()
    }
}

/// Drop identical annotations (same `vaddr + kind + label + comment`) so
/// duplicate slice references don't bloat the output. Panic sites with the
/// same vaddr but wildly different line numbers would be suspicious — but
/// identical entries are common because multiple code paths reference the
/// same `&'static str`.
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
    });
}

/// Tunables shared by analyzers that walk pointer-sized data structures.
#[derive(Debug, Clone)]
pub struct Limits {
    /// Maximum bytes consumed by any single recovered string.
    pub max_string_len: usize,
    /// Maximum line number accepted as a panic location.
    pub max_line: u32,
    /// Maximum column number accepted as a panic location.
    pub max_col: u32,
}

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 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_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"
        );
    }
}