use crate::analyzers::{Annotation, AnnotationKind};
use crate::output::OutputBackend;
use std::io::Write;
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 {
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() {
let s = py_str_with_escape("foo\\");
assert_eq!(s, "\"foo\\\\\"");
}
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();
Binja.render(anns, &mut buf).unwrap();
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() {
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() {
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));
}
}