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
//! `rustrip` CLI: parse a (possibly stripped + format-stripped) binary,
//! run the analyzer pipeline, and render annotations in a chosen format.

use anyhow::{Context, Result};
use clap::Parser;
use std::fs::{File, OpenOptions};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};

use rustrip::analyzers::{
    panics::PanicsAnalyzer, strings::StringsAnalyzer, symbols::SymbolsAnalyzer, Limits, Registry,
};
use rustrip::output::{
    binja::Binja, ghidra::Ghidra, json::Json, table::Table, Format, OutputBackend,
};

/// Maximum bytes accepted from a CLI file or stdin stream.
///
/// This is intentionally stricter than the library's 512 MiB parser ceiling:
/// command-line and stdin callers should not allocate an arbitrarily large
/// process-local buffer before analysis starts.
const MAX_INPUT_BYTES: usize = 64 * 1024 * 1024;

fn parse_format(value: &str) -> std::result::Result<String, String> {
    Format::parse(value)
        .map(|_| value.to_owned())
        .ok_or_else(|| format!("unknown output format '{value}'"))
}

#[derive(Parser, Debug)]
#[command(
    name = "rustrip",
    version,
    about = "Make stripped Rust binaries readable again",
    long_about = "Make stripped Rust binaries readable again.\n\n\
                  rustrip recovers `&str` slice boundaries, demangles Rust symbols, \
                  and reconstructs panic site source locations from release/stripped \
                  ELF, PE, and Mach-O binaries. Outputs to a table, JSON, or a Ghidra/\
                  Binary Ninja Python script that re-applies annotations."
)]
struct Cli {
    /// Path to the binary to analyze. Use `-` to read from stdin.
    path: PathBuf,

    /// Output format: table (default), json, ghidra, binja.
    #[arg(long, short = 'f', default_value = "table", value_parser = parse_format)]
    format: String,

    /// Create a new output file instead of writing to stdout. Scripts
    /// (`ghidra`, `binja`) almost always want this.
    #[arg(long, short = 'o')]
    output: Option<PathBuf>,

    /// Skip the string-slice analyzer.
    #[arg(long)]
    no_strings: bool,

    /// Skip the symbol-demangling analyzer.
    #[arg(long)]
    no_symbols: bool,

    /// Skip the panic-location analyzer.
    #[arg(long)]
    no_panics: bool,

    /// Maximum length of a recovered &str. Default: 4096 bytes.
    #[arg(long, default_value_t = 4096)]
    max_string_len: usize,
}

fn main() -> Result<()> {
    let cli = Cli::parse();

    let bytes = read_bytes(&cli.path)?;

    let bin = rustrip::binary::Binary::parse(cli.path.to_str(), bytes).context("loading binary")?;

    let registry = build_registry(&cli);
    let anns = registry.run(&bin);

    let fmt =
        Format::parse(&cli.format).with_context(|| format!("unknown --format '{}'", cli.format))?;

    let backend: Box<dyn OutputBackend> = match fmt {
        Format::Table => Box::new(Table),
        Format::Json => Box::new(Json),
        Format::GhidraScript => Box::new(Ghidra),
        Format::BinjaScript => Box::new(Binja),
    };

    if let Some(output) = cli.output.as_ref() {
        render_to_new_output(output, |sink| backend.render(&anns, sink))?;
    } else {
        backend.render(&anns, &mut std::io::stdout().lock())?;
    }
    Ok(())
}

fn build_registry(cli: &Cli) -> Registry {
    let mut registry = Registry::new();
    let limits = Limits {
        max_string_len: cli.max_string_len,
        ..Limits::default()
    };
    if !cli.no_strings {
        registry = registry.with(Box::new(StringsAnalyzer::with_limits(limits.clone())));
    }
    if !cli.no_symbols {
        registry = registry.with(Box::new(SymbolsAnalyzer::new()));
    }
    if !cli.no_panics {
        registry = registry.with(Box::new(PanicsAnalyzer::with_limits(limits)));
    }
    registry
}

fn read_bytes(path: &Path) -> Result<Vec<u8>> {
    let bytes = if path.to_str() == Some("-") {
        read_bounded(&mut std::io::stdin().lock(), "stdin")?
    } else {
        let mut file = File::open(path).with_context(|| format!("opening {}", path.display()))?;
        if file
            .metadata()
            .is_ok_and(|metadata| metadata.len() > MAX_INPUT_BYTES as u64)
        {
            anyhow::bail!(
                "input {} exceeds the maximum supported size of {} bytes",
                path.display(),
                MAX_INPUT_BYTES
            );
        }
        read_bounded(&mut file, &path.display().to_string())?
    };

    if bytes.len() < 4 {
        anyhow::bail!("binary too small: {} bytes", bytes.len());
    }
    Ok(bytes)
}

fn read_bounded(reader: &mut impl Read, source: &str) -> Result<Vec<u8>> {
    read_bounded_with_limit(reader, source, MAX_INPUT_BYTES)
}

fn read_bounded_with_limit(reader: &mut impl Read, source: &str, limit: usize) -> Result<Vec<u8>> {
    let mut bytes = Vec::new();
    let mut chunk = [0u8; 8192];

    loop {
        let remaining = limit.saturating_sub(bytes.len());
        if remaining == 0 {
            // Probe one byte after a full buffer so exactly-limit input is
            // accepted while larger streams are rejected without growing it.
            let mut extra = [0u8; 1];
            if reader.read(&mut extra)? != 0 {
                anyhow::bail!("input {source} exceeds the maximum supported size of {limit} bytes");
            }
            return Ok(bytes);
        }

        let read_len = chunk.len().min(remaining);
        let count = reader.read(&mut chunk[..read_len])?;
        if count == 0 {
            return Ok(bytes);
        }
        bytes.extend_from_slice(&chunk[..count]);
    }
}

fn render_to_new_output(
    output_path: &Path,
    render: impl FnOnce(&mut dyn Write) -> std::io::Result<()>,
) -> Result<()> {
    let mut sink = open_output(output_path)?;
    if let Err(error) = render(&mut sink).and_then(|()| sink.flush()) {
        // Removing by pathname after `create_new` would create a TOCTOU race.
        // Retain the new file and name it precisely so callers can inspect or
        // delete only the partial file they created.
        anyhow::bail!(
            "writing {} failed; partial output was retained at {}: {error}",
            output_path.display(),
            output_path.display()
        );
    }
    Ok(())
}

fn open_output(output_path: &Path) -> Result<File> {
    OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(output_path)
        .with_context(|| {
            // The overwrite-refusal only applies when the path already exists;
            // other create failures (missing parent dir, permissions) would
            // make that hint misleading.
            let overwrite_note = match output_path.try_exists() {
                Ok(true) => "; --output refuses to overwrite an existing file",
                Ok(false) | Err(_) => "",
            };
            format!("creating {}{overwrite_note}", output_path.display())
        })
}

#[cfg(test)]
mod tests {
    use super::*;
    use rustrip::analyzers::AnnotationKind;
    use rustrip::binary::{Binary, BinaryFormat, Section, Symbol};
    use std::io::Cursor;

    fn panic_fixture() -> Binary {
        let file = b"src/foo.rs";
        let file_vaddr = 0x5000u64;
        let mut header = Vec::with_capacity(24);
        header.extend_from_slice(&file_vaddr.to_le_bytes());
        header.extend_from_slice(
            &u64::try_from(file.len())
                .expect("filename length fits u64")
                .to_le_bytes(),
        );
        header.extend_from_slice(&42u32.to_le_bytes());
        header.extend_from_slice(&9u32.to_le_bytes());
        Binary::from_test_parts(
            BinaryFormat::Elf,
            true,
            true,
            vec![
                Section {
                    name: ".rodata".into(),
                    vaddr: 0x4000,
                    size: u64::try_from(header.len()).expect("header length fits u64"),
                    data: header,
                },
                Section {
                    name: ".rodata.str".into(),
                    vaddr: file_vaddr,
                    size: u64::try_from(file.len()).expect("filename length fits u64"),
                    data: file.to_vec(),
                },
            ],
            vec![],
            vec![0, 1],
        )
    }

    fn all_analyzer_fixture() -> Binary {
        let mut string_header = Vec::with_capacity(16);
        string_header.extend_from_slice(&0x5000u64.to_le_bytes());
        string_header.extend_from_slice(&5u64.to_le_bytes());

        let file = b"src/fixed.rs";
        let mut panic_header = Vec::with_capacity(24);
        panic_header.extend_from_slice(&0x7000u64.to_le_bytes());
        panic_header.extend_from_slice(
            &u64::try_from(file.len())
                .expect("filename length fits u64")
                .to_le_bytes(),
        );
        panic_header.extend_from_slice(&7u32.to_le_bytes());
        panic_header.extend_from_slice(&3u32.to_le_bytes());

        Binary::from_test_parts(
            BinaryFormat::Elf,
            true,
            true,
            vec![
                Section {
                    name: ".rodata".into(),
                    vaddr: 0x4000,
                    size: u64::try_from(string_header.len()).expect("header length fits u64"),
                    data: string_header,
                },
                Section {
                    name: ".rodata.str".into(),
                    vaddr: 0x5000,
                    size: 5,
                    data: b"hello".to_vec(),
                },
                Section {
                    name: ".rodata.panic".into(),
                    vaddr: 0x6000,
                    size: u64::try_from(panic_header.len()).expect("header length fits u64"),
                    data: panic_header,
                },
                Section {
                    name: ".rodata.file".into(),
                    vaddr: 0x7000,
                    size: u64::try_from(file.len()).expect("filename length fits u64"),
                    data: file.to_vec(),
                },
            ],
            vec![Symbol {
                vaddr: 0x8000,
                name: "_ZN7fixture4mainE".into(),
                size: 0,
            }],
            vec![0, 1, 2, 3],
        )
    }

    fn analyzer_kinds(no_strings: bool, no_symbols: bool, no_panics: bool) -> Vec<AnnotationKind> {
        let cli = Cli {
            path: PathBuf::from("fixture"),
            format: "json".into(),
            output: None,
            no_strings,
            no_symbols,
            no_panics,
            max_string_len: Limits::default().max_string_len,
        };
        build_registry(&cli)
            .run(&all_analyzer_fixture())
            .into_iter()
            .map(|annotation| annotation.kind)
            .collect()
    }

    fn panic_count(max_string_len: usize) -> usize {
        let cli = Cli {
            path: PathBuf::from("fixture"),
            format: "json".into(),
            output: None,
            no_strings: true,
            no_symbols: true,
            no_panics: false,
            max_string_len,
        };
        build_registry(&cli)
            .run(&panic_fixture())
            .into_iter()
            .filter(|annotation| annotation.kind == AnnotationKind::PanicSite)
            .count()
    }

    #[test]
    fn max_string_len_is_shared_with_panics_analyzer() {
        assert_eq!(panic_count(10), 1);
        assert_eq!(panic_count(9), 0);
    }

    #[test]
    fn analyzer_flags_disable_only_the_selected_analyzer() {
        let all = analyzer_kinds(false, false, false);
        assert!(all.contains(&AnnotationKind::String));
        assert!(all.contains(&AnnotationKind::Symbol));
        assert!(all.contains(&AnnotationKind::PanicSite));
        assert!(!analyzer_kinds(true, false, false).contains(&AnnotationKind::String));
        assert!(!analyzer_kinds(false, true, false).contains(&AnnotationKind::Symbol));
        assert!(!analyzer_kinds(false, false, true).contains(&AnnotationKind::PanicSite));
    }

    #[test]
    fn bounded_reader_accepts_limit_and_rejects_next_byte() {
        let mut exact = Cursor::new(b"1234");
        assert_eq!(
            read_bounded_with_limit(&mut exact, "fixture", 4).expect("exact limit accepted"),
            b"1234"
        );

        let mut oversized = Cursor::new(b"12345");
        let error = read_bounded_with_limit(&mut oversized, "fixture", 4)
            .expect_err("byte beyond limit rejected");
        assert!(error.to_string().contains("fixture"));
        assert!(error.to_string().contains("4 bytes"));
    }

    #[test]
    fn failed_output_render_retains_partial_file_and_reports_its_path() {
        let dir = tempfile::tempdir().expect("tempdir");
        let output = dir.path().join("partial.json");
        let error = render_to_new_output(&output, |sink| {
            sink.write_all(b"partial")?;
            Err(std::io::Error::other("simulated render failure"))
        })
        .expect_err("render failure is returned");

        assert!(error.to_string().contains(&output.display().to_string()));
        assert!(error.to_string().contains("partial output was retained"));
        assert_eq!(
            std::fs::read(&output).expect("read retained partial"),
            b"partial"
        );
    }

    #[test]
    fn open_output_names_overwrite_refusal_only_for_existing_paths() {
        let dir = tempfile::tempdir().expect("tempdir");

        let existing = dir.path().join("exists.json");
        std::fs::write(&existing, b"old").expect("seed existing output");
        let error = open_output(&existing).expect_err("existing path must be refused");
        assert!(
            error.to_string().contains("refuses to overwrite"),
            "existing-path error must mention overwrite refusal: {error:#}"
        );

        let missing_parent = dir.path().join("no-such-dir").join("out.json");
        let error = open_output(&missing_parent).expect_err("missing parent must fail");
        assert!(
            !error.to_string().contains("refuses to overwrite"),
            "missing-parent error must not claim an overwrite refusal: {error:#}"
        );
    }
}