rustrip 0.1.13

Make stripped Rust binaries readable again: recover slice-string boundaries, demangle symbols, and reconstruct panic source locations from release/stripped ELF, PE, and Mach-O binaries.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
//! 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))
                .then_with(|| x.comment.cmp(&y.comment))
        });
        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,
    /// Inclusive maximum line number accepted as a panic location.
    pub max_line: u32,
    /// Inclusive maximum column number accepted as a panic location.
    pub max_col: u32,
}

/// Hard cap on annotations produced by either pointer-walking recovery pass.
///
/// This is deliberately independent of [`Limits`] so existing public struct
/// literals remain source-compatible.
pub(super) const MAX_RECOVERED_ANNOTATIONS: usize = 65_536;
/// Hard cap on aggregate owned label/comment bytes from one recovery pass.
pub(super) const MAX_RECOVERED_TEXT_BYTES: usize = 16 * 1024 * 1024;
/// Recovered text may be at most this multiple of classified backing bytes.
const RECOVERED_TEXT_BACKING_MULTIPLIER: usize = 2;

/// Bounds annotations and owned text created while walking untrusted pointer
/// tables. The dynamic portions are tied to the byte-backed classified
/// sections, rather than to their untrusted declared virtual sizes.
#[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
    }

    /// Returns whether one more annotation can fit when its owned text is at
    /// least `minimum_text_bytes`. Callers use this before reading untrusted
    /// candidate text, so the value must be a conservative lower bound.
    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
    }

    /// Returns whether no further annotation with the supplied minimum owned
    /// text size can fit. This lets walkers stop before examining more headers.
    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"
        );
    }
}