rustrip 0.1.14

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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
//! Recover `&str` slices from read-only data sections.
//!
//! Rust string literals are stored as `(ptr, len)` fat-pointer pairs in
//! read-only data sections (ELF: `.rodata`, `.data.rel.ro`; PE: `.rdata`;
//! Mach-O: `__TEXT.__cstring` / `__DATA_CONST.__const`). Disassemblers see
//! these tables as one giant blob of bytes with no internal structure. We
//! walk the tables at pointer-aligned offsets, dereference each `(ptr, len)`
//! pair, validate
//! that the slice lies entirely inside a string-hosting section, and
//! require valid UTF-8 with at least one alphanumeric character.
//!
//! Tuples that fail *any* of those checks are rejected. The combination
//! of UTF-8 validity, length bounds, and alphanumeric content is
//! conservative on real binaries and rejects more than 95% of random
//! pair collisions on stripped ELF/PE artifacts.

use crate::analyzers::{Analyzer, Annotation, AnnotationKind, Limits, RecoveredAnnotationBudget};
use crate::binary::Binary;
use std::collections::HashSet;

// Every emitted string keeps its complete text as a comment and has a
// non-empty label, even when truncation makes the label much shorter.
const MIN_STRING_LABEL_BYTES: usize = 1;
const MIN_STRING_OWNED_TEXT_BYTES: usize = 1 + MIN_STRING_LABEL_BYTES;

#[cfg(test)]
thread_local! {
    static CANDIDATE_CONTENT_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

#[cfg(test)]
fn reset_candidate_content_reads() {
    CANDIDATE_CONTENT_READS.with(|reads| reads.set(0));
}

#[cfg(test)]
fn candidate_content_reads() -> usize {
    CANDIDATE_CONTENT_READS.with(std::cell::Cell::get)
}

#[cfg(test)]
fn record_candidate_content_read() {
    CANDIDATE_CONTENT_READS.with(|reads| reads.set(reads.get().saturating_add(1)));
}

/// Analyzer that recovers `&str` slice boundaries from read-only data sections.
#[derive(Debug, Clone)]
pub struct StringsAnalyzer {
    pub limits: Limits,
}

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

impl StringsAnalyzer {
    /// Create with default limits.
    #[must_use]
    pub fn new() -> Self {
        Self {
            limits: Limits::default(),
        }
    }

    /// Create with custom limits.
    #[must_use]
    pub const fn with_limits(limits: Limits) -> Self {
        Self { limits }
    }
}

impl Analyzer for StringsAnalyzer {
    fn name(&self) -> &'static str {
        "strings"
    }

    fn analyze(&self, bin: &Binary) -> Vec<Annotation> {
        let mut out = Vec::new();
        let ws = if bin.is_64 { 8usize } else { 4 };
        let max = self.limits.max_string_len;
        let mut budget = RecoveredAnnotationBudget::for_string_sections(bin, ws);
        let mut seen_slices = HashSet::new();

        for (section_index, sec) in bin.sections().iter().enumerate() {
            if !bin.is_string_section_index(section_index) {
                continue;
            }
            scan_section(bin, sec, ws, max, &mut budget, &mut seen_slices, &mut out);
            if budget.cannot_fit_any_annotation(MIN_STRING_OWNED_TEXT_BYTES) {
                break;
            }
        }
        out
    }
}

fn scan_section(
    bin: &Binary,
    sec: &crate::binary::Section,
    ws: usize,
    max: usize,
    budget: &mut RecoveredAnnotationBudget,
    seen_slices: &mut HashSet<(u64, u64)>,
    out: &mut Vec<Annotation>,
) {
    let data = sec.data.as_slice();
    if data.len() < ws.saturating_mul(2) {
        return;
    }
    // Step by `ws` bytes: many slice-headers can sit at offset 0, 8, 16...
    // but random table rows interleaved with relocations are also plausible.
    // We rely on the validity checks to reject near-misses.
    let mut off = 0usize;
    while off.checked_add(ws * 2).is_some_and(|e| e <= data.len()) {
        if budget.cannot_fit_any_annotation(MIN_STRING_OWNED_TEXT_BYTES) {
            break;
        }
        // Wraparound-protected walker:
        //   `sec.vaddr.checked_add(off as u64)` returns None if the section
        //   vaddr is so large that adding the dataset offset overflows
        //   u64. Stop the walk in that case — malicious binaries padding
        //   u64::MAX shouldn't be able to overflow our pointer arithmetic.
        //   The length-field address is also checked so a header at the end
        //   of the address space cannot wrap into a low mapped section.
        let Some(lookup) = sec.vaddr.checked_add(off as u64) else {
            break;
        };
        let Some(ptr) = bin.read_ptr(lookup) else {
            off = off.saturating_add(ws);
            continue;
        };
        let Some(len_vaddr) = lookup.checked_add(ws as u64) else {
            off = off.saturating_add(ws);
            continue;
        };
        let Some(len) = bin.read_ptr(len_vaddr) else {
            off = off.saturating_add(ws);
            continue;
        };

        let Ok(text_bytes) = usize::try_from(len) else {
            off = off.saturating_add(ws);
            continue;
        };
        if text_bytes == 0 || text_bytes > max {
            off = off.saturating_add(ws);
            continue;
        }
        // `comment` owns the complete slice. A valid string also emits at
        // least one label byte, so this lower bound cannot reject a fit.
        if !budget.can_fit_annotation_with_minimum_text(minimum_owned_text_bytes(text_bytes)) {
            off = off.saturating_add(ws);
            continue;
        }
        if !bin.vaddr_in_string_section(ptr, len) {
            off = off.saturating_add(ws);
            continue;
        }
        if seen_slices.contains(&(ptr, len)) {
            off = off.saturating_add(ws);
            continue;
        }
        #[cfg(test)]
        record_candidate_content_read();
        let Some(bytes) = bin.read_at_vaddr(ptr, text_bytes) else {
            off = off.saturating_add(ws);
            continue;
        };
        if !is_reasonable_string(bytes) {
            off = off.saturating_add(ws);
            continue;
        }

        let Ok(text) = std::str::from_utf8(bytes) else {
            off = off.saturating_add(ws);
            continue;
        };
        let text_bytes = text.len();
        let label_len = text
            .char_indices()
            .nth(80)
            .map_or(text_bytes, |(offset, _)| {
                offset.saturating_add('…'.len_utf8())
            });
        let owned_text_bytes = text_bytes.saturating_add(label_len);
        if !budget.try_consume(owned_text_bytes) {
            off = off.saturating_add(ws);
            continue;
        }
        // Store only emitted slices, keeping dedup storage within the same
        // annotation budget while avoiding owned text for repeats.
        seen_slices.insert((ptr, len));
        let label = truncate(text, 80);
        out.push(Annotation {
            vaddr: ptr,
            kind: AnnotationKind::String,
            label,
            comment: Some(text.to_owned()),
        });
        off = off.saturating_add(ws);
    }
}

const fn minimum_owned_text_bytes(comment_bytes: usize) -> usize {
    comment_bytes.saturating_add(MIN_STRING_LABEL_BYTES)
}

/// A candidate slice must be valid UTF-8, contain no control characters,
/// and contain at least one alphanumeric character. Punctuation-only
/// runs (e.g. `--`, `::`) are rejected because (a) they almost always
/// coincide with random `(ptr, len)` alignments inside relocation tables
/// and (b) real Rust string literals virtually always include at least one
/// letter or digit.
fn is_reasonable_string(b: &[u8]) -> bool {
    let Ok(s) = std::str::from_utf8(b) else {
        return false;
    };
    if s.is_empty() {
        return false;
    }
    !s.chars().any(char::is_control) && s.chars().any(char::is_alphanumeric)
}

fn truncate(s: &str, n: usize) -> String {
    if s.chars().count() <= n {
        s.to_string()
    } else {
        let mut out: String = s.chars().take(n).collect();
        out.push('\u{2026}');
        out
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::binary::{Binary, BinaryFormat as Bf, Section};

    #[test]
    fn empty_string_rejected() {
        assert!(!is_reasonable_string(b""));
        assert!(!is_reasonable_string(b"\x00\x00\x00"));
    }

    #[test]
    fn control_chars_rejected() {
        assert!(!is_reasonable_string(b"hello\x00world"));
        assert!(!is_reasonable_string(b"hello\nworld"));
    }

    #[test]
    fn alphanumeric_required() {
        assert!(is_reasonable_string(b"hello world"));
        assert!(is_reasonable_string(b"src/foo.rs:42"));
        assert!(is_reasonable_string(b"v1.2.3-rc1"));
        assert!(is_reasonable_string(b"~/path/to/{x}"));
    }

    #[test]
    fn punctuation_only_rejected() {
        assert!(!is_reasonable_string(b"--"));
        assert!(!is_reasonable_string(b"::"));
        assert!(!is_reasonable_string(b"..."));
        assert!(!is_reasonable_string(b"()"));
    }

    #[test]
    fn truncate_keeps_ellipsis() {
        let t = truncate(&"a".repeat(120), 10);
        assert!(t.chars().count() <= 11);
        assert!(t.ends_with('\u{2026}'));
    }

    #[test]
    fn analyzer_name_returns_strings() {
        assert_eq!(StringsAnalyzer::new().name(), "strings");
    }

    #[test]
    fn scan_accepts_data_exactly_ws2() {
        // ws*2 = 16 bytes. Section with exactly 16 bytes must be accepted.
        // If ws*2 → ws/2 = 4: sections with 4-15 bytes would be accepted
        // (too many). If ws*2 → ws+2 = 10: sections with 10-15 bytes
        // would be rejected (too few). A section with exactly 16 bytes
        // kills ws+2 (16 >= 10 → passes, but 16 < 16 → fails with ws+2
        // if the check is <). Wait, the check is `data.len() < ws*2`.
        // With ws*2=16: 16 < 16 = false → accepted.
        // With ws/2=4: 16 < 4 = false → accepted (same).
        // With ws+2=10: 16 < 10 = false → accepted (same).
        // Need a section with 15 bytes: 15 < 16 = true → rejected (correct).
        // 15 < 4 = false → accepted (mutation ws/2 → WRONG, finds garbage).
        // 15 < 10 = false → accepted (mutation ws+2 → WRONG, finds garbage).
        let sv = 0x4000u64;
        let text = b"hello";
        // Build 15 bytes of data (less than ws*2=16)
        let mut rd = ptr_len(sv, text.len() as u64);
        rd.pop(); // 15 bytes
        let bin = string_bin(rd, sv, text.to_vec());
        assert!(
            StringsAnalyzer::new().analyze(&bin).is_empty(),
            "section with 15 bytes (< ws*2=16) must be rejected"
        );
    }

    fn string_bin(rodata_data: Vec<u8>, str_vaddr: u64, str_data: Vec<u8>) -> Binary {
        Binary::from_test_parts(
            Bf::Elf,
            true,
            true,
            vec![
                Section {
                    name: ".rodata".into(),
                    vaddr: 0x1000,
                    size: rodata_data.len() as u64,
                    data: rodata_data,
                },
                Section {
                    name: ".rodata.str".into(),
                    vaddr: str_vaddr,
                    size: str_data.len() as u64,
                    data: str_data,
                },
            ],
            vec![],
            vec![0, 1],
        )
    }

    fn ptr_len(ptr: u64, len: u64) -> Vec<u8> {
        let mut b = Vec::with_capacity(16);
        b.extend_from_slice(&ptr.to_le_bytes());
        b.extend_from_slice(&len.to_le_bytes());
        b
    }

    #[test]
    fn scan_finds_string_at_exact_min_section_size() {
        let sv = 0x4000u64;
        let text = b"hello";
        let rd = ptr_len(sv, text.len() as u64);
        assert_eq!(rd.len(), 16);
        let bin = string_bin(rd, sv, text.to_vec());
        let anns = StringsAnalyzer::new().analyze(&bin);
        assert_eq!(anns.len(), 1);
        assert_eq!(anns[0].label, "hello");
    }

    #[test]
    fn scan_rejects_section_smaller_than_min() {
        let sv = 0x4000u64;
        let mut rd = ptr_len(sv, 5);
        rd.pop();
        let bin = string_bin(rd, sv, b"hello".to_vec());
        assert!(StringsAnalyzer::new().analyze(&bin).is_empty());
    }

    #[test]
    fn scan_rejects_zero_length_string() {
        let sv = 0x4000u64;
        let rd = ptr_len(sv, 0);
        let bin = string_bin(rd, sv, b"hello".to_vec());
        assert!(StringsAnalyzer::new().analyze(&bin).is_empty());
    }

    #[test]
    fn scan_accepts_len_at_max_boundary() {
        let lim = Limits {
            max_string_len: 5,
            ..Limits::default()
        };
        let sv = 0x4000u64;
        let text = b"hello";
        let rd = ptr_len(sv, text.len() as u64);
        let bin = string_bin(rd, sv, text.to_vec());
        assert_eq!(StringsAnalyzer::with_limits(lim).analyze(&bin).len(), 1);
    }

    #[test]
    fn scan_rejects_len_above_max() {
        let lim = Limits {
            max_string_len: 3,
            ..Limits::default()
        };
        let sv = 0x4000u64;
        let text = b"hello";
        let rd = ptr_len(sv, text.len() as u64);
        let bin = string_bin(rd, sv, text.to_vec());
        assert!(StringsAnalyzer::with_limits(lim).analyze(&bin).is_empty());
    }

    #[test]
    fn scan_accepts_len_one() {
        let sv = 0x4000u64;
        let text = b"x";
        let rd = ptr_len(sv, 1);
        let bin = string_bin(rd, sv, text.to_vec());
        let anns = StringsAnalyzer::new().analyze(&bin);
        assert_eq!(anns.len(), 1, "len=1 with alphanumeric must be accepted");
    }

    #[test]
    fn scan_finds_string_in_comma_qualified_mach_sections() {
        let sv = 0x4000u64;
        let text = b"hello";
        let bin = Binary::from_test_parts(
            Bf::MachO,
            true,
            true,
            vec![
                Section {
                    name: "__DATA_CONST.__const,regular".into(),
                    vaddr: 0x1000,
                    size: 16,
                    data: ptr_len(sv, text.len() as u64),
                },
                Section {
                    name: "__TEXT.__cstring,cstring_literals".into(),
                    vaddr: sv,
                    size: text.len() as u64,
                    data: text.to_vec(),
                },
            ],
            vec![],
            vec![0, 1],
        );
        let anns = StringsAnalyzer::new().analyze(&bin);
        assert_eq!(anns.len(), 1);
        assert_eq!(anns[0].label, "hello");
    }

    #[test]
    fn scan_finds_string_in_exact_rodata1() {
        let vaddr = 0x1000u64;
        let string_vaddr = vaddr + 16;
        let mut data = ptr_len(string_vaddr, 5);
        data.extend_from_slice(b"hello");
        let bin = Binary::from_test_parts(
            Bf::Elf,
            true,
            true,
            vec![Section {
                name: ".rodata1".into(),
                vaddr,
                size: data.len() as u64,
                data,
            }],
            vec![],
            vec![0],
        );
        let anns = StringsAnalyzer::new().analyze(&bin);
        assert_eq!(anns.len(), 1);
        assert_eq!(anns[0].label, "hello");
    }

    #[test]
    fn scan_honors_forced_string_section_classification() {
        let sv = 0x4000u64;
        let text = b"hello";
        let bin = Binary::from_test_parts(
            Bf::Elf,
            true,
            true,
            vec![
                Section {
                    name: ".custom_headers".into(),
                    vaddr: 0x1000,
                    size: 16,
                    data: ptr_len(sv, text.len() as u64),
                },
                Section {
                    name: ".custom_strings".into(),
                    vaddr: sv,
                    size: text.len() as u64,
                    data: text.to_vec(),
                },
            ],
            vec![],
            vec![0, 1],
        );
        assert_eq!(StringsAnalyzer::new().analyze(&bin).len(), 1);
    }

    #[test]
    fn scan_does_not_override_an_empty_forced_classification() {
        let sv = 0x4000u64;
        let text = b"hello";
        let bin = Binary::from_test_parts(
            Bf::Elf,
            true,
            true,
            vec![
                Section {
                    name: ".rodata".into(),
                    vaddr: 0x1000,
                    size: 16,
                    data: ptr_len(sv, text.len() as u64),
                },
                Section {
                    name: ".rodata.str".into(),
                    vaddr: sv,
                    size: text.len() as u64,
                    data: text.to_vec(),
                },
            ],
            vec![],
            vec![],
        );
        assert!(StringsAnalyzer::new().analyze(&bin).is_empty());
    }

    #[test]
    fn scan_deduplicates_repeated_slice_before_allocating_text() {
        let sv = 0x4000u64;
        let text = b"hello";
        let mut headers = ptr_len(sv, text.len() as u64);
        headers.extend_from_slice(&ptr_len(sv, text.len() as u64));
        let bin = string_bin(headers, sv, text.to_vec());
        let anns = StringsAnalyzer::new().analyze(&bin);
        assert_eq!(anns.len(), 1);
        assert_eq!(anns[0].comment.as_deref(), Some("hello"));
    }

    #[test]
    fn scan_caps_aggregate_owned_text_against_backing_bytes() {
        let sv = 0x4000u64;
        let text = vec![b'a'; 4096];
        let mut headers = Vec::new();
        for offset in 0..3u64 {
            headers.extend_from_slice(&ptr_len(sv + offset, 4000));
        }
        let backing_bytes = headers.len() + text.len();
        let bin = string_bin(headers, sv, text);
        let anns = StringsAnalyzer::new().analyze(&bin);
        let emitted_text = anns.iter().fold(0usize, |total, annotation| {
            total
                .saturating_add(annotation.label.len())
                .saturating_add(annotation.comment.as_deref().map_or(0, str::len))
        });
        assert_eq!(anns.len(), 2);
        assert!(emitted_text <= backing_bytes.saturating_mul(2));
    }

    #[test]
    fn scan_skips_over_budget_strings_before_content_read() {
        let sv = 0x4000u64;
        let text = vec![b'a'; 4096];
        let mut headers = Vec::new();
        for offset in 0..4u64 {
            headers.extend_from_slice(&ptr_len(sv + offset, 4000));
        }
        let bin = string_bin(headers, sv, text);

        reset_candidate_content_reads();
        let anns = StringsAnalyzer::new().analyze(&bin);

        // Two annotations consume all but 154 bytes. The remaining two
        // candidates need at least their 4,000-byte comments plus one label
        // byte, so they must not reach the content reader.
        assert_eq!(anns.len(), 2);
        assert_eq!(candidate_content_reads(), 2);
        assert!(anns.iter().all(|annotation| annotation
            .comment
            .as_deref()
            .is_some_and(|text| text.len() == 4000)));
    }

    #[test]
    fn scan_checked_add_len_address_overflow_does_not_wrap() {
        let vaddr = u64::MAX - 7;
        let mut data = ptr_len(0x4000, 0);
        data[8..].fill(0xff);
        let bin = Binary {
            path: None,
            format: Bf::Elf,
            arch: "x86_64".into(),
            is_64: true,
            little_endian: true,
            bytes: vec![],
            sections: vec![
                Section {
                    name: ".rodata".into(),
                    vaddr,
                    size: 16,
                    data,
                },
                Section {
                    name: ".data".into(),
                    vaddr: 0,
                    size: 8,
                    data: 5u64.to_le_bytes().to_vec(),
                },
                Section {
                    name: ".rodata.str".into(),
                    vaddr: 0x4000,
                    size: 5,
                    data: b"hello".to_vec(),
                },
            ],
            symbols: vec![],
            sec_by_vaddr: vec![(0, 8, 1), (0x4000, 0x4005, 2), (vaddr, u64::MAX, 0)],
            string_sections: vec![0, 2],
        };
        assert!(StringsAnalyzer::new().analyze(&bin).is_empty());
    }
}