Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
239 changes: 237 additions & 2 deletions rust/src/binary_view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ use crate::component::Component;
use crate::confidence::Conf;
use crate::data_buffer::DataBuffer;
use crate::debuginfo::DebugInfo;
use crate::disassembly::DisassemblySettings;
use crate::disassembly::{DisassemblyOption, DisassemblySettings};
use crate::external_library::{ExternalLibrary, ExternalLocation};
use crate::file_accessor::{
raw_mut as raw_file_accessor, Accessor, BorrowedFileAccessor, FileAccessor, FileAccessorHandle,
Expand Down Expand Up @@ -61,7 +61,7 @@ use crate::variable::DataVariable;
use crate::workflow::Workflow;
use crate::{Endianness, BN_FULL_CONFIDENCE};
use std::collections::{BTreeMap, HashMap};
use std::ffi::{c_char, c_void, CString};
use std::ffi::{c_char, c_void, CStr, CString};
use std::fmt::{Debug, Display, Formatter};
use std::mem::MaybeUninit;
use std::ops::Range;
Expand Down Expand Up @@ -1049,6 +1049,144 @@ impl BinaryView {
}
}

/// Find every occurrence of `data` between `start` and `end`.
///
/// In the `on_match` callback return `false` to stop searching.
pub fn find_all_data<C: FnMut(u64, &DataBuffer) -> bool>(
&self,
start: u64,
end: u64,
data: &DataBuffer,
on_match: C,
) -> bool {
self.find_all_data_with_opts(
start,
end,
data,
FindFlag::FindCaseInsensitive,
NoProgressCallback,
on_match,
)
}

/// Find every occurrence of `data` between `start` and `end`.
///
/// In the `on_match` callback return `false` to stop searching.
///
/// # Warning
///
/// This function is likely to be changed to take in a "query" structure. Or deprecated entirely.
pub fn find_all_data_with_opts<P: ProgressCallback, C: FnMut(u64, &DataBuffer) -> bool>(
&self,
start: u64,
end: u64,
data: &DataBuffer,
flag: FindFlag,
mut progress: P,
mut on_match: C,
) -> bool {
unsafe extern "C" fn cb_on_match<C: FnMut(u64, &DataBuffer) -> bool>(
ctx: *mut c_void,
addr: u64,
data: *mut BNDataBuffer,
) -> bool {
let f = ctx as *mut C;
let buffer = DataBuffer::from_raw(data);
(*f)(addr, &buffer)
}

unsafe {
BNFindAllDataWithProgress(
self.handle,
start,
end,
data.as_raw(),
flag,
&mut progress as *mut P as *mut c_void,
Some(P::cb_progress_callback),
&mut on_match as *mut C as *mut c_void,
Some(cb_on_match::<C>),
)
}
}

/// Find every line of `view_type` that shows `constant` between `start` and `end`.
///
/// In the `on_match` callback return `false` to stop searching.
///
/// Uses the same disassembly settings as the Python API's default, which
/// waits for IL to be generated so IL-level searches are complete.
pub fn find_all_constant<C: FnMut(u64, &LinearDisassemblyLine) -> bool>(
&self,
start: u64,
end: u64,
constant: u64,
view_type: FunctionViewType,
on_match: C,
) -> bool {
let settings = find_all_default_settings();
self.find_all_constant_with_opts(
start,
end,
constant,
&settings,
view_type,
NoProgressCallback,
on_match,
)
}

/// Find every line of `view_type` that shows `constant` between `start` and `end`.
///
/// In the `on_match` callback return `false` to stop searching.
///
/// # Warning
///
/// This function is likely to be changed to take in a "query" structure.
pub fn find_all_constant_with_opts<
P: ProgressCallback,
C: FnMut(u64, &LinearDisassemblyLine) -> bool,
>(
&self,
start: u64,
end: u64,
constant: u64,
disasm_settings: &DisassemblySettings,
view_type: FunctionViewType,
mut progress: P,
mut on_match: C,
) -> bool {
unsafe extern "C" fn cb_on_match<C: FnMut(u64, &LinearDisassemblyLine) -> bool>(
ctx: *mut c_void,
addr: u64,
line: *mut BNLinearDisassemblyLine,
) -> bool {
let f = ctx as *mut C;
let owned_line = LinearDisassemblyLine::from_raw(&*line);
// The core hands us ownership of the line.
BNFreeLinearDisassemblyLines(line, 1);
(*f)(addr, &owned_line)
}

let raw_view_type = FunctionViewType::into_raw(view_type);
let result = unsafe {
BNFindAllConstantWithProgress(
self.handle,
start,
end,
constant,
disasm_settings.handle,
raw_view_type,
&mut progress as *mut P as *mut c_void,
Some(P::cb_progress_callback),
&mut on_match as *mut C as *mut c_void,
Some(cb_on_match::<C>),
)
};
FunctionViewType::free_raw(raw_view_type);
result
}

pub fn find_next_text(
&self,
start: u64,
Expand Down Expand Up @@ -1108,6 +1246,92 @@ impl BinaryView {
}
}

/// Find every line of `view_type` containing `text` between `start` and `end`.
///
/// In the `on_match` callback return `false` to stop searching. It is
/// given the matching text and the line it was found on.
///
/// Uses the same disassembly settings as the Python API's default, which
/// waits for IL to be generated so IL-level searches are complete.
pub fn find_all_text<C: FnMut(u64, &str, &LinearDisassemblyLine) -> bool>(
&self,
start: u64,
end: u64,
text: &str,
view_type: FunctionViewType,
on_match: C,
) -> bool {
let settings = find_all_default_settings();
self.find_all_text_with_opts(
start,
end,
text,
&settings,
FindFlag::FindCaseInsensitive,
view_type,
NoProgressCallback,
on_match,
)
}

/// Find every line of `view_type` containing `text` between `start` and `end`.
///
/// In the `on_match` callback return `false` to stop searching. It is
/// given the matching text and the line it was found on.
///
/// # Warning
///
/// This function is likely to be changed to take in a "query" structure.
#[allow(clippy::too_many_arguments)]
pub fn find_all_text_with_opts<
P: ProgressCallback,
C: FnMut(u64, &str, &LinearDisassemblyLine) -> bool,
>(
&self,
start: u64,
end: u64,
text: &str,
disasm_settings: &DisassemblySettings,
flag: FindFlag,
view_type: FunctionViewType,
mut progress: P,
mut on_match: C,
) -> bool {
unsafe extern "C" fn cb_on_match<C: FnMut(u64, &str, &LinearDisassemblyLine) -> bool>(
ctx: *mut c_void,
addr: u64,
text: *const c_char,
line: *mut BNLinearDisassemblyLine,
) -> bool {
let f = ctx as *mut C;
let text = CStr::from_ptr(text).to_string_lossy();
let owned_line = LinearDisassemblyLine::from_raw(&*line);
// The core hands us ownership of the line.
BNFreeLinearDisassemblyLines(line, 1);
(*f)(addr, &text, &owned_line)
}

let text = text.to_cstr();
let raw_view_type = FunctionViewType::into_raw(view_type);
let result = unsafe {
BNFindAllTextWithProgress(
self.handle,
start,
end,
text.as_ptr(),
disasm_settings.handle,
flag,
raw_view_type,
&mut progress as *mut P as *mut c_void,
Some(P::cb_progress_callback),
&mut on_match as *mut C as *mut c_void,
Some(cb_on_match::<C>),
)
};
FunctionViewType::free_raw(raw_view_type);
result
}

pub fn notify_data_written(&self, offset: u64, len: usize) {
unsafe {
BNNotifyDataWritten(self.handle, offset, len);
Expand Down Expand Up @@ -3778,3 +4002,14 @@ where
.save(context.core_view.assume_init_ref(), &mut file)
})
}

/// The disassembly settings `find_all_constant` and `find_all_text` use by
/// default, matching the Python API.
fn find_all_default_settings() -> Ref<DisassemblySettings> {
let settings = DisassemblySettings::new();
settings.set_option(DisassemblyOption::ShowAddress, false);
settings.set_option(DisassemblyOption::ShowOpcode, false);
settings.set_option(DisassemblyOption::ShowVariableTypesWhenAssigned, true);
settings.set_option(DisassemblyOption::WaitForIL, true);
settings
}
45 changes: 45 additions & 0 deletions rust/src/linear_view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,25 @@ impl LinearViewObject {
}
}

pub fn single_function_llil(function: &Function, settings: &DisassemblySettings) -> Ref<Self> {
unsafe {
let handle =
BNCreateLinearViewSingleFunctionLowLevelIL(function.handle, settings.handle);
Self::ref_from_raw(handle)
}
}

pub fn single_function_llil_ssa(
function: &Function,
settings: &DisassemblySettings,
) -> Ref<Self> {
unsafe {
let handle =
BNCreateLinearViewSingleFunctionLowLevelILSSAForm(function.handle, settings.handle);
Self::ref_from_raw(handle)
}
}

pub fn single_function_mlil(function: &Function, settings: &DisassemblySettings) -> Ref<Self> {
unsafe {
let handle =
Expand All @@ -164,6 +183,32 @@ impl LinearViewObject {
}
}

pub fn single_function_mapped_mlil(
function: &Function,
settings: &DisassemblySettings,
) -> Ref<Self> {
unsafe {
let handle = BNCreateLinearViewSingleFunctionMappedMediumLevelIL(
function.handle,
settings.handle,
);
Self::ref_from_raw(handle)
}
}

pub fn single_function_mapped_mlil_ssa(
function: &Function,
settings: &DisassemblySettings,
) -> Ref<Self> {
unsafe {
let handle = BNCreateLinearViewSingleFunctionMappedMediumLevelILSSAForm(
function.handle,
settings.handle,
);
Self::ref_from_raw(handle)
}
}

pub fn single_function_hlil(function: &Function, settings: &DisassemblySettings) -> Ref<Self> {
unsafe {
let handle =
Expand Down
53 changes: 53 additions & 0 deletions rust/tests/binary_view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,59 @@ fn test_binary_view_search() {
assert_eq!(found.contains(&(&image_base + 0x63)), true);
}

#[test]
fn test_binary_view_find_all() {
let _session = Session::new().expect("Failed to initialize session");
let out_dir = env!("OUT_DIR").parse::<PathBuf>().unwrap();
let view = binaryninja::load(out_dir.join("atox.obj")).expect("Failed to create view");
let image_base = view.original_image_base();

// Test text search, keeping the matched lines past the callback.
let mut text_matches = Vec::new();
view.find_all_text(
0,
view.end(),
"minkernel",
FunctionViewType::MediumLevelIL,
|addr, text, line| {
text_matches.push((addr, text.to_string(), line.clone()));
true
},
);
assert!(text_matches
.iter()
.any(|(addr, _, _)| *addr == image_base + 0x1580));
assert!(text_matches
.iter()
.all(|(_, text, line)| !text.is_empty() && !line.to_string().is_empty()));

// Test data search.
let data = DataBuffer::new(b"minkernel");
let mut data_matches = Vec::new();
view.find_all_data(0, view.end(), &data, |addr, buffer| {
assert_eq!(buffer.get_data(), b"minkernel");
data_matches.push(addr);
true
});
assert!(data_matches.contains(&(image_base + 0x1582)));

// Test constant search, and that returning false stops the search.
let constant = 0x80000000;
let mut constant_matches = Vec::new();
view.find_all_constant(
0,
view.end(),
constant,
FunctionViewType::MediumLevelIL,
|addr, line| {
constant_matches.push((addr, line.clone()));
false
},
);
assert_eq!(constant_matches.len(), 1);
assert_eq!(constant_matches[0].0, image_base + 0x26080);
}

#[test]
fn test_binary_tags() {
let _session = Session::new().expect("Failed to initialize session");
Expand Down
Loading