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 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;

const MAX_GHIDRA_LABEL_LEN: usize = 240;

/// 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, "# -*- coding: utf-8 -*-")?;
        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.symbol import SourceType")?;
        writeln!(w)?;
        writeln!(w, "_af = currentProgram.getAddressFactory()")?;
        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 (index, a) in anns.iter().enumerate() {
            if matches!(a.kind, AnnotationKind::String) {
                continue;
            }
            writeln!(
                w,
                "    (0x{:x}, {}),",
                a.vaddr,
                py_str(&ghidra_label(a, index))
            )?;
        }
        writeln!(w, "]")?;
        writeln!(w)?;
        writeln!(w, "_applied_c = 0")?;
        writeln!(w, "_applied_l = 0")?;
        writeln!(w, "_failed = 0")?;
        writeln!(w, "_comment_groups = {{}}")?;
        writeln!(w, "for vaddr, text in _comments:")?;
        writeln!(w, "    _comment_groups.setdefault(vaddr, []).append(text)")?;
        writeln!(w, "for vaddr, texts in _comment_groups.items():")?;
        // 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, "    try:")?;
        writeln!(
            w,
            "        addr = _af.getAddress(\"0x{{:x}}\".format(vaddr))"
        )?;
        writeln!(w, "        if addr is None:")?;
        writeln!(w, "            raise ValueError(\"address is not mapped\")")?;
        writeln!(w, "        setEOLComment(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(vaddr, _e))"
        )?;
        writeln!(w)?;
        writeln!(w, "_sym_tbl = currentProgram.getSymbolTable()")?;
        writeln!(w, "for vaddr, name in _labels:")?;
        #[allow(clippy::literal_string_with_formatting_args)]
        writeln!(w, "    try:")?;
        writeln!(
            w,
            "        addr = _af.getAddress(\"0x{{:x}}\".format(vaddr))"
        )?;
        writeln!(w, "        if addr is None:")?;
        writeln!(w, "            raise ValueError(\"address is not mapped\")")?;
        writeln!(
            w,
            "        _sym_tbl.createLabel(addr, name, SourceType.USER_DEFINED)"
        )?;
        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(vaddr, _e))"
        )?;
        writeln!(w)?;
        writeln!(
            w,
            "print(\"rustrip: applied {{}} comments, {{}} labels; {{}} failures\".format(_applied_c, _applied_l, _failed))"
        )?;
        Ok(())
    }
}

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

fn ghidra_label(annotation: &Annotation, index: usize) -> String {
    let prefix = label_prefix(&annotation.kind);
    let suffix = format!("_{:x}_{index}", annotation.vaddr);
    let base_limit = MAX_GHIDRA_LABEL_LEN.saturating_sub(suffix.len());
    let mut name = String::with_capacity(MAX_GHIDRA_LABEL_LEN);
    if !prefix.is_empty() {
        name.push_str(prefix);
        name.push('_');
    }
    for ch in annotation.label.chars() {
        if name.len() >= base_limit {
            break;
        }
        name.push(if ch.is_ascii_alphanumeric() || ch == '_' {
            ch
        } else {
            '_'
        });
    }
    if name.is_empty() {
        name.push_str("rustrip");
    }
    name.push_str(&suffix);
    name
}

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() + 3);
    out.push_str("u\"");
    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 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),
        }
    }
}

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 py_str_apostrophe_and_double_quote() {
        let s = py_str("can't say \"hi\"");
        assert_eq!(s, r#"u"can't say \"hi\"""#);
    }

    #[test]
    fn py_str_triple_single_quotes_need_no_escaping() {
        let s = py_str("abc'''xyz");
        assert_eq!(s, "u\"abc'''xyz\"");
    }

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

    #[test]
    fn py_str_trailing_backslash_is_safe() {
        let s = py_str("foo\\");
        assert_eq!(s, "u\"foo\\\\\"");
    }

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

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

    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 coding_declaration_is_first_line() {
        let script = render_actual(&[]);
        assert_eq!(script.lines().next(), Some("# -*- coding: utf-8 -*-"));
    }

    #[test]
    fn uses_documented_comment_and_label_apis_with_failure_reporting() {
        let anns = vec![Annotation {
            vaddr: 0x0040_1000,
            kind: AnnotationKind::String,
            label: "ignored".into(),
            comment: Some("hello world".into()),
        }];
        let script = render_actual(&anns);
        assert!(script.contains("setEOLComment(addr, \"\\n\".join(texts))"));
        assert!(script.contains("_sym_tbl.createLabel(addr, name, SourceType.USER_DEFINED)"));
        assert!(script.contains("except Exception as _e:"));
        assert!(script.contains("comment failed at 0x{:x}: {}"));
        assert!(script.contains("label failed at 0x{:x}: {}"));
        assert!(!script.contains("createLabel(addr, name, True)"));
        assert!(!script.contains("getCodeUnitAt(addr)"));
    }

    #[test]
    fn sanitizes_bounds_and_uniquifies_labels() {
        let annotation = Annotation {
            vaddr: 0x0040_2000,
            kind: AnnotationKind::PanicSite,
            label: format!("src/main.rs:42:5 {}", "x".repeat(1000)),
            comment: None,
        };
        let first = ghidra_label(&annotation, 1);
        let second = ghidra_label(&annotation, 2);
        assert!(first.len() <= MAX_GHIDRA_LABEL_LEN);
        assert!(first
            .chars()
            .all(|ch| ch.is_ascii_alphanumeric() || ch == '_'));
        assert!(first.starts_with("rustrip_panic_"));
        assert_ne!(first, second);
    }

    #[test]
    fn ghidra_label_stops_before_suffix_at_exact_max_length() {
        let annotation = Annotation {
            vaddr: 0x1234,
            kind: AnnotationKind::Symbol,
            label: "A".repeat(MAX_GHIDRA_LABEL_LEN),
            comment: None,
        };
        let label = ghidra_label(&annotation, 5);
        let suffix = "_1234_5";
        let base_len = MAX_GHIDRA_LABEL_LEN - suffix.len();

        assert_eq!(label.len(), MAX_GHIDRA_LABEL_LEN);
        assert_eq!(&label[..base_len], &"A".repeat(base_len));
        assert!(label.ends_with(suffix));
    }

    #[test]
    fn ghidra_label_preserves_allowed_ascii_and_replaces_disallowed_chars() {
        let annotation = Annotation {
            vaddr: 0xab,
            kind: AnnotationKind::Symbol,
            label: "Az09_-. :".into(),
            comment: None,
        };

        assert_eq!(ghidra_label(&annotation, 3), "Az09______ab_3");
    }

    #[test]
    fn preserves_distinct_same_address_labels() {
        let anns = vec![
            Annotation {
                vaddr: 0x0040_0010,
                kind: AnnotationKind::Symbol,
                label: "one".into(),
                comment: None,
            },
            Annotation {
                vaddr: 0x0040_0010,
                kind: AnnotationKind::PanicSite,
                label: "two".into(),
                comment: None,
            },
        ];
        let script = render_actual(&anns);
        assert_eq!(script.matches("    (0x400010, u\"").count(), 2);
    }

    #[test]
    fn groups_distinct_comments_at_one_address_and_counts_each() {
        let anns = vec![
            Annotation {
                vaddr: 0x0040_0010,
                kind: AnnotationKind::String,
                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, u\"comment-A\"),"));
        assert!(script.contains("    (0x400010, u\"comment-B\"),"));
        assert!(script.contains("_comment_groups.setdefault(vaddr, []).append(text)"));
        assert!(script.contains("setEOLComment(addr, \"\\n\".join(texts))"));
        assert!(script.contains("_applied_c += len(texts)"));
        assert!(script.contains("_failed += len(texts)"));
    }
}