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
//! `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(|| {
            format!(
                "creating {}; --output refuses to overwrite an existing file",
                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"
        );
    }
}