Skip to content

Commit

Permalink
Fix clippy warnings and run rustfmt
Browse files Browse the repository at this point in the history
  • Loading branch information
mkrasnitski committed Apr 16, 2024
1 parent f408eb3 commit 1129010
Show file tree
Hide file tree
Showing 19 changed files with 74 additions and 119 deletions.
2 changes: 1 addition & 1 deletion rust/examples/decompile/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ fn decompile_to_c(view: &BinaryView, func: &Function) {
let last = view.get_next_linear_disassembly_lines(&mut cursor.duplicate());
let first = view.get_previous_linear_disassembly_lines(&mut cursor);

let lines = first.into_iter().chain(last.into_iter());
let lines = first.into_iter().chain(&last);

for line in lines {
println!("{}", line.as_ref());
Expand Down
12 changes: 5 additions & 7 deletions rust/examples/dwarf/dwarf_export/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -522,13 +522,11 @@ fn export_data_vars(

for data_variable in &bv.data_variables() {
if let Some(symbol) = data_variable.symbol(bv) {
if symbol.sym_type() == SymbolType::External {
continue;
} else if symbol.sym_type() == SymbolType::Function {
continue;
} else if symbol.sym_type() == SymbolType::ImportedFunction {
continue;
} else if symbol.sym_type() == SymbolType::LibraryFunction {
if let SymbolType::External
| SymbolType::Function
| SymbolType::ImportedFunction
| SymbolType::LibraryFunction = symbol.sym_type()
{
continue;
}
}
Expand Down
22 changes: 9 additions & 13 deletions rust/examples/dwarf/dwarf_import/src/dwarfdebuginfo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ use gimli::{DebuggingInformationEntry, Dwarf, Reader, Unit};

use log::{error, warn};
use std::{
cmp::Ordering,
collections::{hash_map::Values, HashMap},
hash::Hash,
};
Expand Down Expand Up @@ -222,13 +223,7 @@ impl DebugInfoBuilder {
self.types.values()
}

pub(crate) fn add_type(
&mut self,
type_uid: TypeUID,
name: String,
t: Ref<Type>,
commit: bool,
) {
pub(crate) fn add_type(&mut self, type_uid: TypeUID, name: String, t: Ref<Type>, commit: bool) {
if let Some(DebugType {
name: existing_name,
t: existing_type,
Expand Down Expand Up @@ -379,19 +374,20 @@ impl DebugInfoBuilder {
if simplify_str_to_fqn(func_full_name, true).len()
< simplify_str_to_fqn(symbol_full_name.clone(), true).len()
{
func.full_name =
Some(symbol_full_name.to_string());
func.full_name = Some(symbol_full_name.to_string());
}
}
}
}

if let Some(address) = func.address {
let existing_functions = bv.functions_at(address);
if existing_functions.len() > 1 {
warn!("Multiple existing functions at address {address:08x}. One or more functions at this address may have the wrong platform information. Please report this binary.");
} else if existing_functions.len() == 1 {
func.platform = Some(existing_functions.get(0).platform());
match existing_functions.len().cmp(&1) {
Ordering::Greater => {
warn!("Multiple existing functions at address {address:08x}. One or more functions at this address may have the wrong platform information. Please report this binary.");
}
Ordering::Equal => func.platform = Some(existing_functions.get(0).platform()),
Ordering::Less => {}
}
}
}
Expand Down
45 changes: 22 additions & 23 deletions rust/examples/dwarf/dwarf_import/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,7 @@ fn recover_names<R: Reader<Offset = usize>>(
}
}
} else {
namespace_qualifiers
.push((depth, "anonymous_namespace".to_string()));
namespace_qualifiers.push((depth, "anonymous_namespace".to_string()));
}
}

Expand All @@ -129,22 +128,24 @@ fn recover_names<R: Reader<Offset = usize>>(
depth,
match entry.tag() {
constants::DW_TAG_class_type => "anonymous_class".to_string(),
constants::DW_TAG_structure_type => "anonymous_structure".to_string(),
constants::DW_TAG_structure_type => {
"anonymous_structure".to_string()
}
constants::DW_TAG_union_type => "anonymous_union".to_string(),
_ => unreachable!(),
}
},
))
}
debug_info_builder_context.set_name(
get_uid(&unit, entry),
simplify_str_to_str(
namespace_qualifiers
.iter()
.map(|(_, namespace)| namespace.to_owned())
.collect::<Vec<String>>()
.join("::"),
)
.to_string(),
simplify_str_to_str(
namespace_qualifiers
.iter()
.map(|(_, namespace)| namespace.to_owned())
.collect::<Vec<String>>()
.join("::"),
)
.to_string(),
);
}
constants::DW_TAG_typedef
Expand All @@ -153,17 +154,15 @@ fn recover_names<R: Reader<Offset = usize>>(
if let Some(name) = get_name(&unit, entry, debug_info_builder_context) {
debug_info_builder_context.set_name(
get_uid(&unit, entry),
simplify_str_to_str(
namespace_qualifiers
.iter()
.chain(vec![&(-1, name)].into_iter())
.map(|(_, namespace)| {
namespace.to_owned()
})
.collect::<Vec<String>>()
.join("::"),
)
.to_string(),
simplify_str_to_str(
namespace_qualifiers
.iter()
.chain(vec![&(-1, name)].into_iter())
.map(|(_, namespace)| namespace.to_owned())
.collect::<Vec<String>>()
.join("::"),
)
.to_string(),
);
}
}
Expand Down
4 changes: 2 additions & 2 deletions rust/examples/dwarf/dwarfdump/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ use gimli::{
UnitSectionOffset,
};

static PADDING: [&'static str; 23] = [
static PADDING: [&str; 23] = [
"",
" ",
" ",
Expand Down Expand Up @@ -189,7 +189,7 @@ fn get_info_string<R: Reader>(
let value_string = format!("{}", value);
attr_line.push(InstructionTextToken::new(
&value_string,
InstructionTextTokenContents::Integer(value.into()),
InstructionTextTokenContents::Integer(value),
));
} else if let Some(value) = attr.sdata_value() {
let value_string = format!("{}", value);
Expand Down
2 changes: 1 addition & 1 deletion rust/examples/hlil_visitor/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ fn print_variable(func: &HighLevelILFunction, var: &Variable) {
fn print_il_expr(instr: &HighLevelILLiftedInstruction, mut indent: usize) {
print_indent(indent);
print_operation(instr);
println!("");
println!();

indent += 1;

Expand Down
5 changes: 1 addition & 4 deletions rust/examples/minidump/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,11 @@ use minidump::{Minidump, MinidumpMemoryInfoList};

use binaryninja::binaryview::{BinaryView, BinaryViewBase, BinaryViewExt};

use crate::view::DataBufferWrapper;

pub fn print_memory_information(bv: &BinaryView) {
debug!("Printing memory information");
if let Ok(minidump_bv) = bv.parent_view() {
if let Ok(read_buffer) = minidump_bv.read_buffer(0, minidump_bv.len()) {
let read_buffer = DataBufferWrapper::new(read_buffer);
if let Ok(minidump_obj) = Minidump::read(read_buffer) {
if let Ok(minidump_obj) = Minidump::read(read_buffer.get_data()) {
if let Ok(memory_info_list) = minidump_obj.get_stream::<MinidumpMemoryInfoList>() {
let mut memory_info_list_writer = Vec::new();
match memory_info_list.print(&mut memory_info_list_writer) {
Expand Down
32 changes: 2 additions & 30 deletions rust/examples/minidump/src/view.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use std::collections::HashMap;
use std::ops::{Deref, Range};
use std::sync::Arc;
use std::ops::Range;

use binaryninja::section::Section;
use binaryninja::segment::Segment;
Expand All @@ -16,37 +15,11 @@ use binaryninja::custombinaryview::{
BinaryViewType, BinaryViewTypeBase, CustomBinaryView, CustomBinaryViewType, CustomView,
CustomViewBuilder,
};
use binaryninja::databuffer::DataBuffer;
use binaryninja::platform::Platform;
use binaryninja::Endianness;

type BinaryViewResult<R> = binaryninja::binaryview::Result<R>;

/// A wrapper around a `binaryninja::databuffer::DataBuffer`, from which a `[u8]` buffer can be obtained
/// to pass to `minidump::Minidump::read`.
///
/// This code is taken from [`dwarfdump`](https://github.com/Vector35/binaryninja-api/blob/9d8bc846bd213407fb1a7a19af2a96f17501ac3b/rust/examples/dwarfdump/src/lib.rs#L81)
/// in the Rust API examples.
#[derive(Clone)]
pub struct DataBufferWrapper {
inner: Arc<DataBuffer>,
}

impl DataBufferWrapper {
pub fn new(buf: DataBuffer) -> Self {
DataBufferWrapper {
inner: Arc::new(buf),
}
}
}

impl Deref for DataBufferWrapper {
type Target = [u8];
fn deref(&self) -> &Self::Target {
self.inner.get_data()
}
}

/// The _Minidump_ binary view type, which the Rust plugin registers with the Binary Ninja core
/// (via `binaryninja::custombinaryview::register_view_type`) as a possible binary view
/// that can be applied to opened binaries.
Expand Down Expand Up @@ -141,9 +114,8 @@ impl MinidumpBinaryView {
fn init(&self) -> BinaryViewResult<()> {
let parent_view = self.parent_view()?;
let read_buffer = parent_view.read_buffer(0, parent_view.len())?;
let read_buffer = DataBufferWrapper::new(read_buffer);

if let Ok(minidump_obj) = Minidump::read(read_buffer) {
if let Ok(minidump_obj) = Minidump::read(read_buffer.get_data()) {
// Architecture, platform information
if let Ok(minidump_system_info) = minidump_obj.get_stream::<MinidumpSystemInfo>() {
if let Some(platform) = MinidumpBinaryView::translate_minidump_platform(
Expand Down
2 changes: 1 addition & 1 deletion rust/examples/mlil_visitor/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ fn print_variable(func: &MediumLevelILFunction, var: &Variable) {
fn print_il_expr(instr: &MediumLevelILLiftedInstruction, mut indent: usize) {
print_indent(indent);
print_operation(instr);
println!("");
println!();

indent += 1;

Expand Down
2 changes: 1 addition & 1 deletion rust/src/architecture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1172,7 +1172,7 @@ impl Architecture for CoreArchitecture {
}
}
}

fn instruction_llil(
&self,
data: &[u8],
Expand Down
8 changes: 3 additions & 5 deletions rust/src/binaryview.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1576,11 +1576,9 @@ where
ctx: *mut ::std::os::raw::c_void,
view: *mut BNBinaryView,
) {
ffi_wrap!("EventHandler::on_event", unsafe {
let mut context = &mut *(ctx as *mut Handler);

let handle = BinaryView::from_raw(BNNewViewReference(view));
Handler::on_event(&mut context, handle.as_ref());
ffi_wrap!("EventHandler::on_event", {
let context = unsafe { &*(ctx as *const Handler) };
context.on_event(&BinaryView::from_raw(BNNewViewReference(view)));
})
}

Expand Down
17 changes: 4 additions & 13 deletions rust/src/debuginfo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -414,10 +414,7 @@ impl DebugInfo {
}

/// Returns a generator of all functions provided by a named DebugInfoParser
pub fn functions_by_name<S: BnStrCompatible>(
&self,
parser_name: S,
) -> Vec<DebugFunctionInfo> {
pub fn functions_by_name<S: BnStrCompatible>(&self, parser_name: S) -> Vec<DebugFunctionInfo> {
let parser_name = parser_name.into_bytes_with_nul();

let mut count: usize = 0;
Expand Down Expand Up @@ -758,21 +755,15 @@ impl DebugInfo {
let short_name_bytes = new_func.short_name.map(|name| name.into_bytes_with_nul());
let short_name = short_name_bytes
.as_ref()
.map_or(ptr::null_mut() as *mut _, |name| {
name.as_ptr() as _
});
.map_or(ptr::null_mut() as *mut _, |name| name.as_ptr() as _);
let full_name_bytes = new_func.full_name.map(|name| name.into_bytes_with_nul());
let full_name = full_name_bytes
.as_ref()
.map_or(ptr::null_mut() as *mut _, |name| {
name.as_ptr() as _
});
.map_or(ptr::null_mut() as *mut _, |name| name.as_ptr() as _);
let raw_name_bytes = new_func.raw_name.map(|name| name.into_bytes_with_nul());
let raw_name = raw_name_bytes
.as_ref()
.map_or(ptr::null_mut() as *mut _, |name| {
name.as_ptr() as _
});
.map_or(ptr::null_mut() as *mut _, |name| name.as_ptr() as _);

let mut components_array: Vec<*const ::std::os::raw::c_char> =
Vec::with_capacity(new_func.components.len());
Expand Down
4 changes: 2 additions & 2 deletions rust/src/flowgraph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ impl<'a> FlowGraphNode<'a> {
unsafe { FlowGraphNode::from_raw(BNCreateFlowGraphNode(graph.handle)) }
}

pub fn set_disassembly_lines(&self, lines: &'a Vec<DisassemblyTextLine>) {
pub fn set_disassembly_lines(&self, lines: &'a [DisassemblyTextLine]) {
unsafe {
BNSetFlowGraphNodeLines(self.handle, lines.as_ptr() as *mut _, lines.len());
// BNFreeDisassemblyTextLines(lines.as_ptr() as *mut _, lines.len()); // Shouldn't need...would be a double free?
Expand All @@ -79,7 +79,7 @@ impl<'a> FlowGraphNode<'a> {
let lines = lines
.iter()
.map(|&line| DisassemblyTextLine::from(&vec![line]))
.collect();
.collect::<Vec<_>>();
self.set_disassembly_lines(&lines);
}

Expand Down
1 change: 0 additions & 1 deletion rust/src/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ pub use binaryninjacore_sys::BNAnalysisSkipReason as AnalysisSkipReason;
pub use binaryninjacore_sys::BNFunctionAnalysisSkipOverride as FunctionAnalysisSkipOverride;
pub use binaryninjacore_sys::BNFunctionUpdateType as FunctionUpdateType;


use std::hash::Hash;
use std::{fmt, mem};

Expand Down
14 changes: 5 additions & 9 deletions rust/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,16 +74,12 @@
//! ### `main.rs`
//! Standalone binaries need to initialize Binary Ninja before they can work. You can do this through [`headless::Session`], [`headless::script_helper`], or [`headless::init()`] at start and [`headless::shutdown()`] at shutdown.
//! ```rust
//! fn main() {
//! // This loads all the core architecture, platform, etc plugins
//! // Standalone executables need to call this, but plugins do not
//! let headless_session = binaryninja::headless::Session::new();
//! // This loads all the core architecture, platform, etc plugins
//! // Standalone executables need to call this, but plugins do not
//! let headless_session = binaryninja::headless::Session::new();
//!
//! println!("Loading binary...");
//! let bv = headless_session.load("/bin/cat").expect("Couldn't open `/bin/cat`");
//!
//! // Your code here...
//! }
//! println!("Loading binary...");
//! let bv = headless_session.load("/bin/cat").expect("Couldn't open `/bin/cat`");
//! ```
//!
//! ### `Cargo.toml`
Expand Down
2 changes: 1 addition & 1 deletion rust/src/llil/instruction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ where
let expr_idx =
unsafe { BNGetLowLevelILIndexForInstruction(self.function.handle, self.instr_idx) };
let op = unsafe { BNGetLowLevelILByIndex(self.function.handle, expr_idx) };
return op.address;
op.address
}

pub fn info(&self) -> InstrInfo<'func, A, M, NonSSA<V>> {
Expand Down
8 changes: 4 additions & 4 deletions rust/src/llil/operation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,10 +89,10 @@ pub struct Syscall;
pub struct Intrinsic;

impl<'func, A, M, V> Operation<'func, A, M, NonSSA<V>, Intrinsic>
where
A: 'func + Architecture,
M: FunctionMutability,
V: NonSSAVariant,
where
A: 'func + Architecture,
M: FunctionMutability,
V: NonSSAVariant,
{
// TODO: Support register and expression lists
pub fn intrinsic(&self) -> Option<A::Intrinsic> {
Expand Down
Loading

0 comments on commit 1129010

Please sign in to comment.