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
//! 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, "_bv = bv")?;
        writeln!(w)?;
        writeln!(w, "_labels = [")?;
        for a in anns {
            if matches!(a.kind, AnnotationKind::String) {
                continue;
            }
            writeln!(
                w,
                "    (0x{:x}, {}),",
                a.vaddr,
                py_str_with_escape(&a.label)
            )?;
        }
        writeln!(w, "]")?;
        writeln!(w, "_comments = [")?;
        for a in anns {
            if let Some(c) = &a.comment {
                writeln!(w, "    (0x{:x}, {}),", a.vaddr, py_str_with_escape(c))?;
            }
        }
        writeln!(w, "]")?;
        writeln!(w)?;
        writeln!(w, "_applied_l = 0")?;
        writeln!(w, "_applied_c = 0")?;
        writeln!(w, "_failed = 0")?;
        writeln!(w, "for addr, name in _labels:")?;
        writeln!(w, "    try:")?;
        writeln!(
            w,
            "        sym = bn.Symbol(bn.SymbolType.DataSymbol, addr, name)"
        )?;
        writeln!(w, "        _bv.define_user_symbol(sym)")?;
        writeln!(w, "        _applied_l += 1")?;
        writeln!(w, "    except Exception as _e:")?;
        writeln!(w, "        _failed += 1")?;
        writeln!(
            w,
            "        print(\"rustrip: label failed at 0x{{:x}}: {{}}\".format(addr, _e))"
        )?;
        writeln!(w, "_comment_groups = {{}}")?;
        writeln!(w, "for addr, text in _comments:")?;
        writeln!(w, "    _comment_groups.setdefault(addr, []).append(text)")?;
        writeln!(w, "for addr, texts in _comment_groups.items():")?;
        writeln!(w, "    try:")?;
        writeln!(w, "        _bv.set_comment_at(addr, \"\\n\".join(texts))")?;
        writeln!(w, "        _applied_c += len(texts)")?;
        writeln!(w, "    except Exception as _e:")?;
        writeln!(w, "        _failed += len(texts)")?;
        writeln!(
            w,
            "        print(\"rustrip: comment failed at 0x{{:x}}: {{}}\".format(addr, _e))"
        )?;
        writeln!(w)?;
        writeln!(
            w,
            "print(\"rustrip: applied {{}} labels, {{}} comments; {{}} failures\".format(_applied_l, _applied_c, _failed))"
        )?;
        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 matches!(u32::from(c), 0x00..=0x1f | 0x7f..=0x9f) => {
                let _ = write!(out, "\\x{:02x}", u32::from(c));
            }
            c if is_script_format_control(c) => {
                let _ = write!(out, "\\u{:04x}", u32::from(c));
            }
            c => out.push(c),
        }
    }
    out.push('"');
    out
}

const fn is_script_format_control(ch: char) -> bool {
    matches!(
        ch,
        '\u{061c}'
            | '\u{200e}'
            | '\u{200f}'
            | '\u{202a}'..='\u{202e}'
            | '\u{2066}'..='\u{2069}'
            | '\u{feff}'
    )
}

#[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\\\\\"");
    }

    #[test]
    fn string_literals_escape_c0_c1_del_and_format_controls() {
        assert_eq!(
            py_str_with_escape("\0\u{0007}\u{001b}\u{007f}\u{0085}\u{009f}"),
            r#""\x00\x07\x1b\x7f\x85\x9f""#
        );
        assert_eq!(
            py_str_with_escape("\u{061c}\u{200e}\u{200f}\u{202a}\u{202e}\u{2066}\u{2069}\u{feff}"),
            r#""\u061c\u200e\u200f\u202a\u202e\u2066\u2069\ufeff""#
        );
    }

    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 uses_documented_current_view_and_symbol_signature() {
        let script = render_actual(&[Annotation {
            vaddr: 0x0040_1000,
            kind: AnnotationKind::Symbol,
            label: "name".into(),
            comment: None,
        }]);
        assert!(script.contains("bn.Symbol(bn.SymbolType.DataSymbol, addr, name)"));
        assert!(script.contains("_bv = bv"));
        assert!(script.contains("_bv.define_user_symbol(sym)"));
        assert!(script.contains("_bv.set_comment_at(addr, \"\\n\".join(texts))"));
        assert!(!script.contains("_bv = bn.BinaryView"));
        assert!(!script.contains("DataSymbol, name, addr"));
    }

    #[test]
    fn preserves_distinct_same_address_annotations() {
        let anns = vec![
            Annotation {
                vaddr: 0x0040_0010,
                kind: AnnotationKind::Symbol,
                label: "one".into(),
                comment: Some("comment-A".into()),
            },
            Annotation {
                vaddr: 0x0040_0010,
                kind: AnnotationKind::PanicSite,
                label: "two".into(),
                comment: Some("comment-B".into()),
            },
        ];
        let script = render_actual(&anns);
        assert!(script.contains("    (0x400010, \"one\"),"));
        assert!(script.contains("    (0x400010, \"two\"),"));
        assert!(script.contains("    (0x400010, \"comment-A\"),"));
        assert!(script.contains("    (0x400010, \"comment-B\"),"));
        assert!(script.contains("_comment_groups.setdefault(addr, []).append(text)"));
    }

    #[test]
    fn reports_label_and_comment_failures() {
        let script = render_actual(&[]);
        assert_eq!(script.matches("except Exception as _e:").count(), 2);
        assert!(script.contains("label failed at 0x{:x}: {}"));
        assert!(script.contains("comment failed at 0x{:x}: {}"));
        assert!(!script.contains("        pass"));
    }
}