rustrip 0.1.1

Make stripped Rust binaries readable again: recover slice-string boundaries, demangle symbols, and reconstruct panic source locations from release/stripped ELF/PE binaries.
Documentation
//! Generate a self-contained Binary Ninja Python script that re-applies
//! annotations on whichever binary view the user opens it in.
//!
//! Strategy mirrors `ghidra.rs`: emit static Python that the user pastes
//! into the Binary Ninja Python console (no plugin SDK required, works
//! across all editions).

use crate::analyzers::{Annotation, AnnotationKind};
use crate::output::OutputBackend;
use std::io::Write;

/// Binary Ninja Python script output backend.
pub struct Binja;

impl OutputBackend for Binja {
    fn render(&self, anns: &[Annotation], w: &mut dyn Write) -> std::io::Result<()> {
        writeln!(
            w,
            "# auto-generated by rustrip — paste this into Binary Ninja's Python console"
        )?;
        writeln!(
            w,
            "# applies {} annotations to the current binary view",
            anns.len()
        )?;
        writeln!(w)?;
        writeln!(w, "import binaryninja as bn")?;
        writeln!(w)?;
        writeln!(w, "_labels = {{}}")?;
        writeln!(w, "_comments = {{}}")?;
        writeln!(w)?;
        for a in anns {
            if matches!(a.kind, AnnotationKind::String) {
                continue;
            }
            writeln!(
                w,
                "_labels[0x{:x}] = {}",
                a.vaddr,
                py_str_with_escape(&a.label)
            )?;
        }
        for a in anns {
            if let Some(c) = &a.comment {
                writeln!(w, "_comments[0x{:x}] = {}", a.vaddr, py_str_with_escape(c))?;
            }
        }
        writeln!(w)?;
        writeln!(w, "_bv = bn.BinaryView")?;
        writeln!(w, "# The user must rebind _bv to their open BinaryView:")?;
        writeln!(w, "# _bv = current_view  # noqa")?;
        writeln!(w)?;
        writeln!(w, "_applied_l = 0")?;
        writeln!(w, "_applied_c = 0")?;
        writeln!(w, "for addr, name in _labels.items():")?;
        writeln!(w, "    try:")?;
        writeln!(
            w,
            "        sym = bn.Symbol(bn.SymbolType.DataSymbol, name, addr)"
        )?;
        writeln!(w, "        _bv.define_user_symbol(sym)")?;
        writeln!(w, "        _applied_l += 1")?;
        writeln!(w, "    except Exception as _e:")?;
        writeln!(w, "        pass")?;
        writeln!(w, "for addr, text in _comments.items():")?;
        writeln!(w, "    _bv.set_comment_at(addr, text)")?;
        writeln!(w, "    _applied_c += 1")?;
        writeln!(w)?;
        writeln!(
            w,
            "print(\"rustrip: applied\", _applied_l, \"labels,\", _applied_c, \"comments\")"
        )?;
        Ok(())
    }
}

fn py_str_with_escape(s: &str) -> String {
    // Emit a normal (non-raw) double-quoted Python string literal with every
    // metacharacter escaped. Raw literals (`r"..."`) were unsafe: Python raw
    // strings cannot end in a backslash — a recovered `&str` ending in `\`
    // (common in Windows paths, and trivially crafted in an adversarial
    // binary) escapes the closing quote and desyncs the whole generated
    // script. A fully-escaped literal is valid Python for any input,
    // including trailing `\`, embedded `"`, and quote-injection attempts.
    use std::fmt::Write as _;
    let mut out = String::with_capacity(s.len() + 2);
    out.push('"');
    for ch in s.chars() {
        match ch {
            '\\' => out.push_str("\\\\"),
            '"' => out.push_str("\\\""),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if u32::from(c) < 0x20 => {
                let _ = write!(out, "\\x{:02x}", u32::from(c));
            }
            c => out.push(c),
        }
    }
    out.push('"');
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn paths_escape_backslashes() {
        let s = py_str_with_escape(r"C:\Users\foo\bar.rs");
        assert_eq!(s, r#""C:\\Users\\foo\\bar.rs""#);
    }

    #[test]
    fn double_quote_is_escaped() {
        let s = py_str_with_escape("a\"b");
        assert_eq!(s, "\"a\\\"b\"");
    }

    #[test]
    fn trailing_backslash_is_safe() {
        // Regression: raw literal `r"foo\"` is a Python SyntaxError. The
        // escaped form `"foo\\"` parses cleanly.
        let s = py_str_with_escape("foo\\");
        assert_eq!(s, "\"foo\\\\\"");
    }

    // ─────────────────────────────────────────────────────────────────────
    // Byte-exact snapshot. Production order:
    //   1. header / import
    //   2. `_labels = {}`, `_comments = {}` initial lines
    //   3. ALL symbol/panic labels appended
    //   4. ALL string comments appended
    //   5. apply loop (`_bv = bn.BinaryView` etc.)
    //   6. final `print(...)`
    // Mutations that reorder, drop, or duplicate any of these lines get
    // caught by the byte-exact comparison.
    // ─────────────────────────────────────────────────────────────────────

    fn render_reference(anns: &[Annotation]) -> String {
        use std::fmt::Write as _;
        let mut s = String::new();
        let _ = writeln!(
            s,
            "# auto-generated by rustrip — paste this into Binary Ninja's Python console"
        );
        let _ = writeln!(
            s,
            "# applies {} annotations to the current binary view",
            anns.len()
        );
        s.push('\n');
        let _ = writeln!(s, "import binaryninja as bn");
        s.push('\n');
        let _ = writeln!(s, "_labels = {{}}");
        let _ = writeln!(s, "_comments = {{}}");
        s.push('\n');
        for a in anns {
            if matches!(a.kind, AnnotationKind::String) {
                continue;
            }
            let _ = writeln!(
                s,
                "_labels[0x{:x}] = {}",
                a.vaddr,
                py_str_with_escape(&a.label)
            );
        }
        for a in anns {
            if let Some(c) = &a.comment {
                let _ = writeln!(s, "_comments[0x{:x}] = {}", a.vaddr, py_str_with_escape(c));
            }
        }
        s.push('\n');
        let _ = writeln!(s, "_bv = bn.BinaryView");
        let _ = writeln!(s, "# The user must rebind _bv to their open BinaryView:");
        let _ = writeln!(s, "# _bv = current_view  # noqa");
        s.push('\n');
        let _ = writeln!(s, "_applied_l = 0");
        let _ = writeln!(s, "_applied_c = 0");
        let _ = writeln!(s, "for addr, name in _labels.items():");
        let _ = writeln!(s, "    try:");
        let _ = writeln!(
            s,
            "        sym = bn.Symbol(bn.SymbolType.DataSymbol, name, addr)"
        );
        let _ = writeln!(s, "        _bv.define_user_symbol(sym)");
        let _ = writeln!(s, "        _applied_l += 1");
        let _ = writeln!(s, "    except Exception as _e:");
        let _ = writeln!(s, "        pass");
        let _ = writeln!(s, "for addr, text in _comments.items():");
        let _ = writeln!(s, "    _bv.set_comment_at(addr, text)");
        let _ = writeln!(s, "    _applied_c += 1");
        s.push('\n');
        let _ = writeln!(
            s,
            "print(\"rustrip: applied\", _applied_l, \"labels,\", _applied_c, \"comments\")"
        );
        s
    }

    fn render_actual(anns: &[Annotation]) -> String {
        let mut buf = Vec::new();
        // nosemgrep: rustrip-no-unwrapping-trust-bytes (test code)
        Binja.render(anns, &mut buf).unwrap();
        // nosemgrep: rustrip-no-unwrapping-trust-bytes (test code)
        String::from_utf8(buf).unwrap()
    }

    #[test]
    fn byte_exact_empty() {
        let anns: Vec<Annotation> = vec![];
        assert_eq!(render_actual(&anns), render_reference(&anns));
    }

    #[test]
    fn byte_exact_labels_before_comments() {
        // The unconditional ordering of `for a in anns` blocks matters:
        // labels (symbols + panic) come first, then comments. This pins
        // that ordering so a cargo-mutants mutation that reorders the
        // two loops can never silently change which annotation ends up
        // first.
        let anns = vec![
            Annotation {
                vaddr: 0x0040_0000,
                kind: AnnotationKind::String,
                label: "s".into(),
                comment: Some("comment-A".into()),
            },
            Annotation {
                vaddr: 0x0040_0010,
                kind: AnnotationKind::Symbol,
                label: "core::fmt::write".into(),
                comment: None,
            },
            Annotation {
                vaddr: 0x0040_0020,
                kind: AnnotationKind::PanicSite,
                label: "src/main.rs:1".into(),
                comment: Some("comment-B".into()),
            },
            Annotation {
                vaddr: 0x0040_0030,
                kind: AnnotationKind::String,
                label: "t".into(),
                comment: Some("comment-C".into()),
            },
        ];
        assert_eq!(render_actual(&anns), render_reference(&anns));
    }

    #[test]
    fn byte_exact_only_strings_no_labels() {
        let anns = vec![Annotation {
            vaddr: 0x0040_4000,
            kind: AnnotationKind::String,
            label: "ignored".into(),
            comment: Some("only comment, no label".into()),
        }];
        assert_eq!(render_actual(&anns), render_reference(&anns));
    }

    #[test]
    fn byte_exact_inner_double_quote_escaped() {
        // Verifies py_str_with_escape is plumbed into the actual rendered
        // script by producing a comment that contains a literal `"`.
        let anns = vec![Annotation {
            vaddr: 0x0040_5000,
            kind: AnnotationKind::String,
            label: "ignored".into(),
            comment: Some(r#"he said "hi""#.into()),
        }];
        assert_eq!(render_actual(&anns), render_reference(&anns));
    }
}