rustrip 0.1.14

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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! 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). String annotations are rendered
        // as comments below; a String *without* a comment would otherwise
        // vanish entirely, so it falls back to a label.
        writeln!(w, "_labels = [")?;
        for (index, a) in anns.iter().enumerate() {
            if matches!(a.kind, AnnotationKind::String) && a.comment.is_some() {
                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 string_without_comment_falls_back_to_label() {
        // A String annotation with no comment is invisible in the comments
        // list; it must survive as a label instead of being dropped.
        let anns = vec![Annotation {
            vaddr: 0x0040_1000,
            kind: AnnotationKind::String,
            label: "orphan".into(),
            comment: None,
        }];
        let script = render_actual(&anns);
        assert!(script.contains("    (0x401000, u\"orphan_401000_0\"),"));
        assert!(!script.contains("_comments = [\n    "));
    }

    #[test]
    fn string_with_comment_is_not_duplicated_as_label() {
        let anns = vec![Annotation {
            vaddr: 0x0040_1000,
            kind: AnnotationKind::String,
            label: "text".into(),
            comment: Some("payload".into()),
        }];
        let script = render_actual(&anns);
        assert!(script.contains("u\"payload\""));
        assert!(!script.contains("u\"text\""));
    }

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