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 Ghidra Python script that re-applies the
//! annotations on whichever program the user opens it in.
//!
//! We generate code rather than talking to Ghidra's RPC because:
//!
//! - works for any Ghidra version with the Python API (>= 10.x);
//! - works offline; no Ghidra or Java runtime required at `rustrip` runtime;
//! - debuggable — the script is plain text the user can read & edit.
//!
//! The output script uses `setEOLComment` for annotations with a comment
//! (typically strings) and `createLabel` for symbol names. Panic sites
//! show up as labels — those are useful jump targets when debugging a
//! crash report.

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

/// Ghidra Python script output backend.
pub struct Ghidra;

impl OutputBackend for Ghidra {
    fn render(&self, anns: &[Annotation], w: &mut dyn Write) -> std::io::Result<()> {
        writeln!(
            w,
            "# auto-generated by rustrip — run inside Ghidra: Window > Script Manager > New > Python > paste this"
        )?;
        writeln!(
            w,
            "# applies {} annotations to the currently open program",
            anns.len()
        )?;
        writeln!(w)?;
        writeln!(w, "from ghidra.program.model.address import Address")?;
        writeln!(w)?;
        writeln!(w, "_af = currentProgram.getAddressFactory()")?;
        writeln!(w, "_listing = currentProgram.getListing()")?;
        writeln!(w)?;
        // Comment list (data) — strings live here.
        writeln!(w, "_comments = [")?;
        for a in anns {
            if let Some(c) = &a.comment {
                writeln!(w, "    (0x{:x}, {}),", a.vaddr, py_str(c))?;
            }
        }
        writeln!(w, "]")?;
        writeln!(w)?;
        // Label list (symbols & panic sites).
        writeln!(w, "_labels = [")?;
        for a in anns {
            if matches!(a.kind, AnnotationKind::String) {
                continue;
            }
            let prefix = label_prefix(&a.kind);
            if prefix.is_empty() {
                writeln!(w, "    (0x{:x}, {}, \"\"),", a.vaddr, py_str(&a.label))?;
            } else {
                writeln!(
                    w,
                    "    (0x{:x}, \"{}_{{}}\".format({}), \"\"),",
                    a.vaddr,
                    prefix,
                    py_str(&a.label)
                )?;
            }
        }
        writeln!(w, "]")?;
        writeln!(w)?;
        writeln!(w, "_applied_c = 0")?;
        writeln!(w, "_applied_l = 0")?;
        writeln!(w, "for vaddr, text in _comments:")?;
        // The `0x{{:x}}.format(...)` text intentionally contains Python's
        // format-spec syntax; clippy's literal-string-with-formatting-args
        // lint cannot tell that our outer `writeln!` is emitting Python
        // code, not consuming Rust format args.
        #[allow(clippy::literal_string_with_formatting_args)]
        writeln!(w, "    addr = _af.getAddress(\"0x{{:x}}\".format(vaddr))")?;
        writeln!(w, "    if addr is None:")?;
        writeln!(w, "        continue")?;
        writeln!(w, "    code_unit = _listing.getCodeUnitAt(addr)")?;
        writeln!(w, "    if code_unit is not None:")?;
        writeln!(
            w,
            "        code_unit.setComment(code_unit.EOL_COMMENT, text)"
        )?;
        writeln!(w, "        _applied_c += 1")?;
        writeln!(w)?;
        writeln!(w, "_sym_tbl = currentProgram.getSymbolTable()")?;
        writeln!(w, "for vaddr, name, unused_ns in _labels:")?;
        #[allow(clippy::literal_string_with_formatting_args)]
        writeln!(w, "    addr = _af.getAddress(\"0x{{:x}}\".format(vaddr))")?;
        writeln!(w, "    if addr is None:")?;
        writeln!(w, "        continue")?;
        writeln!(w, "    _sym_tbl.createLabel(addr, name, True)")?;
        writeln!(w, "    _applied_l += 1")?;
        writeln!(w)?;
        writeln!(
            w,
            "print(\"rustrip: applied {{}} comments, {{}} labels\".format(_applied_c, _applied_l))"
        )?;
        Ok(())
    }
}

const fn label_prefix(k: &AnnotationKind) -> &'static str {
    use AnnotationKind::{PanicSite, String as KString, Symbol};
    match k {
        PanicSite => "rustrip_panic",
        Symbol | KString => "",
    }
}

fn py_str(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 *entire* generated
    // script (SyntaxError, all annotations lost). A fully-escaped literal is
    // valid Python for any input byte sequence, including trailing `\`,
    // embedded `'''`, and quote-injection attempts.
    let mut out = String::with_capacity(s.len() + 2);
    out.push('"');
    push_escaped(&mut out, s);
    out.push('"');
    out
}

/// Append `s` to `out` with Python string-literal escaping (no surrounding
/// quotes). Shared by the comment and label emitters.
fn push_escaped(out: &mut String, s: &str) {
    use std::fmt::Write as _;
    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),
        }
    }
}

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

    #[test]
    fn py_str_apostrophe_and_double_quote() {
        // Apostrophes need no escaping in a double-quoted literal; double
        // quotes are backslash-escaped.
        let s = py_str("can't say \"hi\"");
        assert_eq!(s, r#""can't say \"hi\"""#);
    }

    #[test]
    fn py_str_triple_single_quotes_need_no_escaping() {
        // In a double-quoted literal a run of `'` is literal — no run
        // breaking, and no unterminated-string risk.
        let s = py_str("abc'''xyz");
        assert_eq!(s, "\"abc'''xyz\"");
    }

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

    #[test]
    fn py_str_trailing_backslash_is_safe() {
        // Regression: raw literal `r'''foo\'''` is a Python SyntaxError.
        // The escaped form `"foo\\"` parses cleanly (verified against
        // CPython 3.12: ast.literal_eval roundtrips to the input).
        let s = py_str("foo\\");
        assert_eq!(s, "\"foo\\\\\"");
    }

    #[test]
    fn renders_script_header() {
        let anns: Vec<Annotation> = vec![];
        let mut buf = Vec::new();
        // nosemgrep: rustrip-no-unwrapping-trust-bytes (test code)
        Ghidra.render(&anns, &mut buf).unwrap();
        // nosemgrep: rustrip-no-unwrapping-trust-bytes (test code)
        let s = String::from_utf8(buf).unwrap();
        assert!(s.contains("currentProgram"));
        assert!(s.contains("_comments"));
        assert!(s.contains("applied {} comments, {} labels"));
    }

    #[test]
    fn label_prefix_distinguishes_panic() {
        assert_eq!(label_prefix(&AnnotationKind::Symbol), "");
        assert_eq!(label_prefix(&AnnotationKind::PanicSite), "rustrip_panic");
        assert_eq!(label_prefix(&AnnotationKind::String), "");
    }

    // ─────────────────────────────────────────────────────────────────────
    // Byte-exact snapshot. The reference script is built using the same
    // helper functions and same constant Python source fragments as the
    // production renderer. Any literal-ordering mutation in production —
    // e.g. swapping the order of `_comments = [` vs `_labels = [`, or
    // moving the `print(...)` line above the for-loop — desyncs actual
    // vs. expected and is caught here.
    // ─────────────────────────────────────────────────────────────────────

    // The `"0x{{:x}}"` Python format fragment is intentionally emitted
    // verbatim — clippy's literal-string-with-formatting-args lint
    // cannot tell our `writeln!` is writing Python source, not
    // consuming Rust format args. Mirror production's `#[allow]`.
    #[allow(clippy::literal_string_with_formatting_args)]
    fn render_reference(anns: &[Annotation]) -> String {
        use std::fmt::Write as _;
        let mut s = String::new();
        let _ = writeln!(
            s,
            "# auto-generated by rustrip — run inside Ghidra: Window > Script Manager > New > Python > paste this"
        );
        let _ = writeln!(
            s,
            "# applies {} annotations to the currently open program",
            anns.len()
        );
        s.push('\n');
        let _ = writeln!(s, "from ghidra.program.model.address import Address");
        s.push('\n');
        let _ = writeln!(s, "_af = currentProgram.getAddressFactory()");
        let _ = writeln!(s, "_listing = currentProgram.getListing()");
        s.push('\n');
        let _ = writeln!(s, "_comments = [");
        for a in anns {
            if let Some(c) = &a.comment {
                let _ = writeln!(s, "    (0x{:x}, {}),", a.vaddr, py_str(c));
            }
        }
        let _ = writeln!(s, "]");
        s.push('\n');
        let _ = writeln!(s, "_labels = [");
        for a in anns {
            if matches!(a.kind, AnnotationKind::String) {
                continue;
            }
            let prefix = label_prefix(&a.kind);
            if prefix.is_empty() {
                let _ = writeln!(s, "    (0x{:x}, {}, \"\"),", a.vaddr, py_str(&a.label));
            } else {
                let _ = writeln!(
                    s,
                    "    (0x{:x}, \"{}_{{}}\".format({}), \"\"),",
                    a.vaddr,
                    prefix,
                    py_str(&a.label)
                );
            }
        }
        let _ = writeln!(s, "]");
        s.push('\n');
        let _ = writeln!(s, "_applied_c = 0");
        let _ = writeln!(s, "_applied_l = 0");
        let _ = writeln!(s, "for vaddr, text in _comments:");
        let _ = writeln!(s, "    addr = _af.getAddress(\"0x{{:x}}\".format(vaddr))");
        let _ = writeln!(s, "    if addr is None:");
        let _ = writeln!(s, "        continue");
        let _ = writeln!(s, "    code_unit = _listing.getCodeUnitAt(addr)");
        let _ = writeln!(s, "    if code_unit is not None:");
        let _ = writeln!(
            s,
            "        code_unit.setComment(code_unit.EOL_COMMENT, text)"
        );
        let _ = writeln!(s, "        _applied_c += 1");
        s.push('\n');
        let _ = writeln!(s, "_sym_tbl = currentProgram.getSymbolTable()");
        let _ = writeln!(s, "for vaddr, name, unused_ns in _labels:");
        let _ = writeln!(s, "    addr = _af.getAddress(\"0x{{:x}}\".format(vaddr))");
        let _ = writeln!(s, "    if addr is None:");
        let _ = writeln!(s, "        continue");
        let _ = writeln!(s, "    _sym_tbl.createLabel(addr, name, True)");
        let _ = writeln!(s, "    _applied_l += 1");
        s.push('\n');
        let _ = writeln!(
            s,
            "print(\"rustrip: applied {{}} comments, {{}} labels\".format(_applied_c, _applied_l))"
        );
        s
    }

    fn render_actual(anns: &[Annotation]) -> String {
        let mut buf = Vec::new();
        // nosemgrep: rustrip-no-unwrapping-trust-bytes (test code)
        Ghidra.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_only_string_with_comment() {
        // Strings get a `_comments` tuple but no `_labels` entry. The
        // `anns.len()` header reflects the total, even though labels
        // can be a subset.
        let anns = vec![Annotation {
            vaddr: 0x0040_1000,
            kind: AnnotationKind::String,
            label: "ignored-string-label".into(),
            comment: Some("hello world".into()),
        }];
        assert_eq!(render_actual(&anns), render_reference(&anns));
    }

    #[test]
    fn byte_exact_panic_site_uses_rustrip_panic_prefix() {
        const PANIC_LINE: &str = r#""rustrip_panic_{}".format("src/main.rs:42:5")"#;
        let anns = vec![
            Annotation {
                vaddr: 0x0040_2000,
                kind: AnnotationKind::PanicSite,
                label: "src/main.rs:42:5".into(),
                comment: None,
            },
            Annotation {
                vaddr: 0x0040_2010,
                kind: AnnotationKind::Symbol,
                label: "_ZN3std2io5Write9write_fmt17h".into(),
                comment: None,
            },
        ];
        assert_eq!(render_actual(&anns), render_reference(&anns));
        // Belt-and-suspenders: panic prefix is interpolated as the
        // Python format string ``"rustrip_panic_{}".format(r'''…''')``.
        let out_string = render_actual(&anns);
        assert!(
            out_string.contains(PANIC_LINE),
            "panic prefix line missing: {out_string}"
        );
    }

    #[test]
    fn byte_exact_mixed_kinds_with_and_without_comments() {
        let anns = vec![
            Annotation {
                vaddr: 0x0040_0000,
                kind: AnnotationKind::String,
                label: "s".into(),
                comment: Some("c-string-data".into()),
            },
            Annotation {
                vaddr: 0x0040_0010,
                kind: AnnotationKind::Symbol,
                label: "core::fmt::write".into(),
                comment: None,
            },
            Annotation {
                vaddr: 0x0040_0020,
                kind: AnnotationKind::PanicSite,
                label: "src/lib.rs:99".into(),
                comment: Some("user panic message".into()),
            },
        ];
        assert_eq!(render_actual(&anns), render_reference(&anns));
    }
}