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
//! CLI integration tests.
//!
//! These tests exercise `rustrip` as a subprocess so they cover the
//! `main.rs` paths that unit tests under `#[cfg(test)] mod tests`
//! cannot reach: clap parsing, file I/O, and per-flag combos.
//!
//! Strategy: spawn the freshly-built `rustrip` binary (`CARGO_BIN_EXE`)
//! via `std::process::Command`, capture stdout/stderr, and assert on
//! behaviour. The `CARGO_BIN_EXE_rustrip` env var is set automatically
//! by `cargo test` to the just-built binary path.

use std::io::Write;
use std::path::PathBuf;
use std::process::Command;

fn rustrip_bin() -> PathBuf {
    PathBuf::from(env!("CARGO_BIN_EXE_rustrip"))
}

#[test]
fn cli_version_prints_pkg_version() {
    let out = Command::new(rustrip_bin())
        .arg("--version")
        .output()
        .expect("run rustrip --version");
    assert!(
        out.status.success(),
        "{:?}",
        String::from_utf8_lossy(&out.stderr)
    );
    let s = String::from_utf8_lossy(&out.stdout);
    assert!(
        s.contains(env!("CARGO_PKG_VERSION")),
        "version output {s:?} does not contain pkg version"
    );
}

#[test]
fn cli_help_contains_killer_tagline() {
    let out = Command::new(rustrip_bin())
        .arg("--help")
        .output()
        .expect("run rustrip --help");
    assert!(
        out.status.success(),
        "stderr: {:?}",
        String::from_utf8_lossy(&out.stderr)
    );
    let combined =
        String::from_utf8_lossy(&out.stdout).into_owned() + &String::from_utf8_lossy(&out.stderr);
    assert!(
        combined.contains("Make stripped Rust binaries readable again"),
        "tagline missing from --help"
    );
}

#[test]
fn cli_on_self_binary_produces_table_output() {
    let exe = rustrip_bin();
    let out = Command::new(&exe)
        .arg(&exe)
        .arg("-f")
        .arg("table")
        .output()
        .expect("run rustrip self-analysis table");
    assert!(
        out.status.success(),
        "stderr: {:?}",
        String::from_utf8_lossy(&out.stderr)
    );
    let s = String::from_utf8_lossy(&out.stdout);
    assert!(s.contains("vaddr"), "no vaddr header: {s:?}");
    assert!(
        s.lines().nth(2).is_some(),
        "self-analysis table must contain at least one annotation: {s:?}"
    );
}

#[test]
fn cli_selective_flags_all_combinatorial() {
    let exe = rustrip_bin();
    let cases: &[&[&str]] = &[
        &["--no-strings"],
        &["--no-symbols"],
        &["--no-panics"],
        &["--no-strings", "--no-symbols"],
        &["--no-strings", "--no-panics"],
        &["--no-symbols", "--no-panics"],
        &["--no-strings", "--no-symbols", "--no-panics"],
    ];
    let run_json = |flags: &[&str]| {
        let mut cmd = Command::new(&exe);
        cmd.arg(&exe).arg("-f").arg("json");
        for flag in flags {
            cmd.arg(flag);
        }
        let out = cmd.output().expect("run rustrip selective");
        assert!(
            out.status.success(),
            "flag combination {flags:?} failed. stderr: {:?}",
            String::from_utf8_lossy(&out.stderr)
        );
        out.stdout
    };
    let baseline = run_json(&[]);
    let baseline: serde_json::Value = serde_json::from_slice(&baseline).expect("baseline JSON");
    let baseline = baseline.as_array().expect("baseline JSON array");

    for flags in cases {
        let stdout = run_json(flags);
        if flags.len() == 3 {
            assert_eq!(
                stdout, b"[]\n",
                "all analyzers disabled must produce exactly an empty JSON array"
            );
        }
        let annotations: serde_json::Value =
            serde_json::from_slice(&stdout).expect("selective JSON");
        let annotations = annotations.as_array().expect("selective JSON array");
        for (flag, kind) in [
            ("--no-strings", "string"),
            ("--no-symbols", "symbol"),
            ("--no-panics", "panic"),
        ] {
            let disabled = flags.contains(&flag);
            let baseline_has_kind = baseline.iter().any(|annotation| {
                annotation.get("kind").and_then(serde_json::Value::as_str) == Some(kind)
            });
            if disabled && baseline_has_kind {
                assert!(
                    annotations.iter().all(|annotation| {
                        annotation.get("kind").and_then(serde_json::Value::as_str) != Some(kind)
                    }),
                    "{flag} must remove externally observable {kind} annotations: {annotations:?}"
                );
            }
        }
    }
}

#[test]
fn cli_format_aliases_all_accepted() {
    let exe = rustrip_bin();
    let aliases = [
        "text",
        "json",
        "cli",
        "ghidra",
        "ghidra-py",
        "py-ghidra",
        "binja",
        "binary-ninja",
        "bn",
        "py-binja",
    ];
    for alias in aliases {
        let mut cmd = Command::new(&exe);
        cmd.arg(&exe).arg("-f").arg(alias);
        let out = cmd.output().expect("run rustrip with alias");
        assert!(
            out.status.success(),
            "alias {alias} failed: stderr: {:?}",
            String::from_utf8_lossy(&out.stderr)
        );
    }
}

#[test]
fn cli_format_unknown_non_zero_exit() {
    let exe = rustrip_bin();
    let out = Command::new(&exe)
        .arg(&exe)
        .arg("-f")
        .arg("garbage-format")
        .output()
        .expect("run rustrip with bad format");
    assert!(
        !out.status.success(),
        "garbage --format should fail; stderr: {:?}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stderr = String::from_utf8_lossy(&out.stderr).to_lowercase();
    assert!(
        stderr.contains("invalid value") && stderr.contains("--format"),
        "unknown format must be rejected as an argument: {stderr:?}"
    );
}

#[test]
fn cli_missing_path_non_zero_exit() {
    let exe = rustrip_bin();
    let dir = tempfile::tempdir().expect("tempdir");
    let missing = dir.path().join("does-not-exist.bin");
    let out = Command::new(&exe)
        .arg(&missing)
        .output()
        .expect("run rustrip with missing path");
    assert!(
        !out.status.success(),
        "missing path should error; stderr: {:?}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.to_lowercase().contains("opening") || stderr.to_lowercase().contains("path"),
        "stderr should mention the path/IO: {stderr:?}"
    );
}

#[test]
fn cli_reads_from_stdin_via_dash() {
    let mut child = Command::new(rustrip_bin())
        .arg("-")
        .arg("-f")
        .arg("text")
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .expect("spawn rustrip with stdin");
    let mut stdin = child.stdin.take().expect("stdin handle");
    stdin
        .write_all(&std::fs::read(rustrip_bin()).expect("read self binary"))
        .expect("stdin write");
    drop(stdin);
    let out = child.wait_with_output().expect("wait rustrip");
    // Reading from stdin must not fail; succeeded produces a normal
    // annotation stream.
    assert!(
        out.status.success(),
        "stdin self-analysis failed; stderr: {:?}",
        String::from_utf8_lossy(&out.stderr)
    );
}

#[test]
fn cli_max_string_len_zero_disables_string_backed_recovery() {
    let exe = rustrip_bin();
    let out = Command::new(&exe)
        .arg(&exe)
        .arg("-f")
        .arg("json")
        .arg("--max-string-len")
        .arg("0")
        .output()
        .expect("run rustrip max-string-len=0");
    assert!(
        out.status.success(),
        "max-string-len=0 should run cleanly; stderr: {:?}",
        String::from_utf8_lossy(&out.stderr)
    );
    let annotations: serde_json::Value =
        serde_json::from_slice(&out.stdout).expect("max-string-len=0 JSON parses");
    let annotations = annotations.as_array().expect("top-level JSON array");
    assert!(
        annotations.iter().all(|annotation| {
            !matches!(
                annotation.get("kind").and_then(serde_json::Value::as_str),
                Some("string" | "panic")
            )
        }),
        "max-string-len=0 must suppress string and panic recovery: {annotations:?}"
    );
}

// ─────────────────────────────────────────────────────────────────────
// File-output path: exercises the `Some(p)` branch in `main.rs`, which creates
// an output file without overwriting existing paths.
// ─────────────────────────────────────────────────────────────────────

#[test]
fn cli_output_file_writes_table_to_disk_without_stdout() {
    let dir = tempfile::tempdir().expect("tempdir");
    let out_path = dir.path().join("rustrip-table.txt");
    let exe = rustrip_bin();
    let out = Command::new(&exe)
        .arg(&exe)
        .arg("-f")
        .arg("table")
        .arg("-o")
        .arg(&out_path)
        .output()
        .expect("run rustrip -o table");
    assert!(
        out.status.success(),
        "stderr: {:?}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        out.stdout.is_empty(),
        "-o must suppress rendered stdout: {:?}",
        String::from_utf8_lossy(&out.stdout)
    );
    let on_disk = std::fs::read_to_string(&out_path).expect("read output");
    assert!(
        on_disk.contains("vaddr"),
        "no vaddr header on disk: {on_disk:?}"
    );
}

#[test]
fn cli_invalid_input_does_not_create_output_file() {
    let dir = tempfile::tempdir().expect("tempdir");
    let invalid = dir.path().join("truncated-elf.bin");
    let output = dir.path().join("report.json");
    std::fs::write(&invalid, b"\x7fELF").expect("write truncated ELF magic");

    let out = Command::new(rustrip_bin())
        .arg(&invalid)
        .arg("-f")
        .arg("json")
        .arg("-o")
        .arg(&output)
        .output()
        .expect("run rustrip with invalid input and output path");
    assert!(
        !out.status.success(),
        "invalid input must fail before rendering; stderr: {:?}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        !output.exists(),
        "invalid input must not create an output file: {}",
        output.display()
    );
}

#[test]
fn cli_output_file_writes_json_to_disk() {
    let dir = tempfile::tempdir().expect("tempdir");
    let out_path = dir.path().join("rustrip-report.json");
    let exe = rustrip_bin();
    let out = Command::new(&exe)
        .arg(&exe)
        .arg("-f")
        .arg("json")
        .arg("-o")
        .arg(&out_path)
        .output()
        .expect("run rustrip -o json");
    assert!(
        out.status.success(),
        "stderr: {:?}",
        String::from_utf8_lossy(&out.stderr)
    );
    let on_disk = std::fs::read_to_string(&out_path).expect("read json");
    let parsed: serde_json::Value = serde_json::from_str(&on_disk).expect("json parses");
    assert!(parsed.is_array(), "top-level must be array");
}

#[test]
fn cli_output_file_writes_ghidra_python_to_disk() {
    let dir = tempfile::tempdir().expect("tempdir");
    let out_path = dir.path().join("rustrip-report_ghidra.py");
    let exe = rustrip_bin();
    let out = Command::new(&exe)
        .arg(&exe)
        .arg("-f")
        .arg("ghidra")
        .arg("-o")
        .arg(&out_path)
        .output()
        .expect("run rustrip -o ghidra");
    assert!(
        out.status.success(),
        "stderr: {:?}",
        String::from_utf8_lossy(&out.stderr)
    );
    let on_disk = std::fs::read_to_string(&out_path).expect("read ghidra py");
    assert!(on_disk.contains("currentProgram"));
    assert!(on_disk.contains("_comments"));
}

#[test]
fn cli_output_file_writes_binja_python_to_disk() {
    let dir = tempfile::tempdir().expect("tempdir");
    let out_path = dir.path().join("rustrip-report_binja.py");
    let exe = rustrip_bin();
    let out = Command::new(&exe)
        .arg(&exe)
        .arg("-f")
        .arg("binja")
        .arg("-o")
        .arg(&out_path)
        .output()
        .expect("run rustrip -o binja");
    assert!(
        out.status.success(),
        "stderr: {:?}",
        String::from_utf8_lossy(&out.stderr)
    );
    let on_disk = std::fs::read_to_string(&out_path).expect("read binja py");
    assert!(on_disk.contains("binaryninja"));
    assert!(on_disk.contains("_labels"));
}

#[test]
fn cli_output_same_path_is_rejected_without_modifying_input() {
    let dir = tempfile::tempdir().expect("tempdir");
    let input = dir.path().join("input-binary");
    let original = std::fs::read(rustrip_bin()).expect("read self binary");
    std::fs::write(&input, &original).expect("write input copy");

    let out = Command::new(rustrip_bin())
        .arg(&input)
        .arg("-f")
        .arg("json")
        .arg("-o")
        .arg(&input)
        .output()
        .expect("run rustrip with identical output");
    assert!(!out.status.success(), "same-path output must be rejected");
    assert_eq!(std::fs::read(&input).expect("read input"), original);
}

#[cfg(unix)]
#[test]
fn cli_output_symlink_to_input_is_rejected_without_modifying_input() {
    use std::os::unix::fs::symlink;

    let dir = tempfile::tempdir().expect("tempdir");
    let input = dir.path().join("input-binary");
    let output = dir.path().join("output-link");
    let original = std::fs::read(rustrip_bin()).expect("read self binary");
    std::fs::write(&input, &original).expect("write input copy");
    symlink(&input, &output).expect("create output symlink");

    let out = Command::new(rustrip_bin())
        .arg(&input)
        .arg("-f")
        .arg("json")
        .arg("-o")
        .arg(&output)
        .output()
        .expect("run rustrip with symlink output");
    assert!(!out.status.success(), "symlink alias must be rejected");
    assert_eq!(std::fs::read(&input).expect("read input"), original);
}

#[test]
fn cli_output_hardlink_to_input_is_rejected_without_modifying_input() {
    let dir = tempfile::tempdir().expect("tempdir");
    let input = dir.path().join("input-binary");
    let output = dir.path().join("output-hardlink");
    let original = std::fs::read(rustrip_bin()).expect("read self binary");
    std::fs::write(&input, &original).expect("write input copy");
    std::fs::hard_link(&input, &output).expect("create output hardlink");

    let out = Command::new(rustrip_bin())
        .arg(&input)
        .arg("-f")
        .arg("json")
        .arg("-o")
        .arg(&output)
        .output()
        .expect("run rustrip with hardlink output");
    assert!(!out.status.success(), "hardlink alias must be rejected");
    assert_eq!(std::fs::read(&input).expect("read input"), original);
    assert_eq!(std::fs::read(&output).expect("read hardlink"), original);
}

#[test]
fn cli_existing_output_is_rejected_without_modifying_contents() {
    let dir = tempfile::tempdir().expect("tempdir");
    let output = dir.path().join("existing-output.json");
    let original = b"old contents";
    std::fs::write(&output, original).expect("write existing output");

    let out = Command::new(rustrip_bin())
        .arg(rustrip_bin())
        .arg("-f")
        .arg("json")
        .arg("-o")
        .arg(&output)
        .output()
        .expect("run rustrip with existing output");
    assert!(!out.status.success(), "existing output must be rejected");
    assert_eq!(std::fs::read(&output).expect("read output"), original);
}

// ─────────────────────────────────────────────────────────────────────
// Tiny-binary guard. `read_bytes` returns `Err` when the file is less
// than 4 bytes — covers cargo-mutants deletions of the `anyhow::bail!`
// arm + the surrounding `if buf.len() < 4` (mutation `<` → `<=` is
// killed by the boundary tests below).
// ─────────────────────────────────────────────────────────────────────

#[test]
fn cli_tiny_binary_bails_with_friendly_message() {
    let dir = tempfile::tempdir().expect("tempdir");
    let tiny = dir.path().join("tiny.bin");
    std::fs::write(&tiny, [0u8, 0, 0]).expect("write tiny");
    let exe = rustrip_bin();
    let out = Command::new(&exe)
        .arg(&tiny)
        .arg("-f")
        .arg("text")
        .output()
        .expect("run rustrip tiny");
    assert!(
        !out.status.success(),
        "tiny input should fail; stderr: {:?}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stderr = String::from_utf8_lossy(&out.stderr).to_lowercase();
    assert!(
        stderr.contains("too small") || stderr.contains("small"),
        "stderr should mention 'too small': {stderr:?}"
    );
}

/// 4-byte boundary. cargo-mutants mutates `buf.len() < 4` to `<=`; the
/// mutated version bails on exactly-4-byte input. This test feeds an
/// ELF magic-header file (4 bytes) just at the threshold and asserts
/// the rustrip binary does NOT trip its own tiny-file guard. (The
/// underlying goblin parser will fail with *its* error message about a
/// malformed object, NOT rustrip's "binary too small" message.)
#[test]
fn cli_four_byte_or_larger_does_not_bail_tiny() {
    let dir = tempfile::tempdir().expect("tempdir");
    let tiny = dir.path().join("four.bin");
    std::fs::write(&tiny, [0x7f, b'E', b'L', b'F']).expect("write ELF magic");
    let exe = rustrip_bin();
    let out = Command::new(&exe)
        .arg(&tiny)
        .arg("-f")
        .arg("text")
        .output()
        .expect("run rustrip 4-byte ELF magic");
    // Must not be rustrip's tiny-file guard: that message is "binary
    // too small". goblin's own error phrasings (e.g. "object is too
    // small", "malformed entity") are fine — they're the mutated
    // mutation-target guard's actual error from the deeper loader.
    let stderr = String::from_utf8_lossy(&out.stderr).to_lowercase();
    assert!(
        !stderr.contains("binary too small"),
        "4-byte ELF magic should not hit rustrip's tiny-file bail: {stderr:?}"
    );
}

/// End-to-end coverage for accepting a non-default `--max-string-len` value.
/// Deterministic propagation into analyzers is covered by `src/main.rs` unit
/// tests; this CLI test must not rely on linker-dependent self-binary strings.
#[test]
fn cli_max_string_len_accepts_non_default_limit() {
    let exe = rustrip_bin();
    let out = Command::new(&exe)
        .arg(&exe)
        .arg("-f")
        .arg("json")
        .arg("--max-string-len")
        .arg("8")
        .output()
        .expect("run rustrip --max-string-len");
    assert!(
        out.status.success(),
        "non-default --max-string-len failed: {:?}",
        String::from_utf8_lossy(&out.stderr)
    );
    let parsed: serde_json::Value = serde_json::from_slice(&out.stdout).expect("json parses");
    assert!(parsed.is_array());
}