summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--rust/binaryninjacore-sys/build.rs8
-rw-r--r--rust/binaryninjacore-sys/src/lib.rs2
-rw-r--r--rust/examples/basic_script/src/main.rs13
-rw-r--r--rust/examples/dwarfdump/src/lib.rs38
-rw-r--r--rust/examples/template/src/main.rs13
-rw-r--r--rust/src/architecture.rs11
-rw-r--r--rust/src/basicblock.rs8
-rw-r--r--rust/src/binaryview.rs10
-rw-r--r--rust/src/callingconvention.rs18
-rw-r--r--rust/src/custombinaryview.rs8
-rw-r--r--rust/src/databuffer.rs8
-rw-r--r--rust/src/debuginfo.rs24
-rw-r--r--rust/src/disassembly.rs8
-rw-r--r--rust/src/downloadprovider.rs8
-rw-r--r--rust/src/fileaccessor.rs27
-rw-r--r--rust/src/flowgraph.rs20
-rw-r--r--rust/src/function.rs2
-rw-r--r--rust/src/headless.rs14
-rw-r--r--rust/src/lib.rs101
-rw-r--r--rust/src/llil/function.rs6
-rw-r--r--rust/src/llil/instruction.rs4
-rw-r--r--rust/src/llil/lifting.rs58
-rw-r--r--rust/src/llil/operation.rs12
-rw-r--r--rust/src/metadata.rs5
-rw-r--r--rust/src/rc.rs15
-rw-r--r--rust/src/section.rs38
-rw-r--r--rust/src/segment.rs22
-rw-r--r--rust/src/symbol.rs35
-rw-r--r--rust/src/types.rs66
29 files changed, 339 insertions, 263 deletions
diff --git a/rust/binaryninjacore-sys/build.rs b/rust/binaryninjacore-sys/build.rs
index d666c53f..451a70e6 100644
--- a/rust/binaryninjacore-sys/build.rs
+++ b/rust/binaryninjacore-sys/build.rs
@@ -82,10 +82,10 @@ fn main() {
let file = File::open("../../ui/uitypes.h").expect("Couldn't open uitypes.h");
for line in BufReader::new(file).lines() {
let line = line.unwrap();
- if line.starts_with(current_line) {
- current_version = (&line[current_line.len()..]).to_owned();
- } else if line.starts_with(minimum_line) {
- minimum_version = (&line[minimum_line.len()..]).to_owned();
+ if let Some(version) = line.strip_prefix(current_line) {
+ current_version = version.to_owned();
+ } else if let Some(version) = line.strip_prefix(minimum_line) {
+ minimum_version = version.to_owned();
}
}
diff --git a/rust/binaryninjacore-sys/src/lib.rs b/rust/binaryninjacore-sys/src/lib.rs
index 04d76a43..effc9340 100644
--- a/rust/binaryninjacore-sys/src/lib.rs
+++ b/rust/binaryninjacore-sys/src/lib.rs
@@ -3,4 +3,6 @@
#![allow(non_snake_case)]
#![allow(unused)]
+#![allow(clippy::type_complexity)]
+
include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
diff --git a/rust/examples/basic_script/src/main.rs b/rust/examples/basic_script/src/main.rs
index ae4554e8..e535f15f 100644
--- a/rust/examples/basic_script/src/main.rs
+++ b/rust/examples/basic_script/src/main.rs
@@ -18,19 +18,16 @@ fn main() {
// TODO : This is intended to be refactored to be more nice to work with soon(TM)
for addr in basic_block.as_ref() {
print!(" {} ", addr);
- match func.arch().instruction_text(
+ if let Some((_, tokens)) = func.arch().instruction_text(
bv.read_buffer(addr, func.arch().max_instr_len())
.unwrap()
.get_data(),
addr,
) {
- Some((_, tokens)) => {
- tokens
- .iter()
- .for_each(|token| print!("{}", token.text().as_str()));
- println!("")
- }
- _ => (),
+ tokens
+ .iter()
+ .for_each(|token| print!("{}", token.text().as_str()));
+ println!();
}
}
}
diff --git a/rust/examples/dwarfdump/src/lib.rs b/rust/examples/dwarfdump/src/lib.rs
index 7860c5bf..9b3cb376 100644
--- a/rust/examples/dwarfdump/src/lib.rs
+++ b/rust/examples/dwarfdump/src/lib.rs
@@ -38,7 +38,7 @@ use gimli::{
use std::{fmt, ops::Deref, sync::Arc};
-static PADDING: [&'static str; 23] = [
+static PADDING: [&str; 23] = [
"",
" ",
" ",
@@ -170,13 +170,13 @@ fn get_info_string<R: Reader>(
InstructionTextTokenContents::Text,
));
- if let Ok(Some(addr)) = dwarf.attr_address(&unit, attr.value()) {
+ if let Ok(Some(addr)) = dwarf.attr_address(unit, attr.value()) {
let addr_string = format!("0x{:08x}", addr);
attr_line.push(InstructionTextToken::new(
BnString::new(addr_string),
InstructionTextTokenContents::Integer(addr),
));
- } else if let Ok(attr_reader) = dwarf.attr_string(&unit, attr.value()) {
+ } else if let Ok(attr_reader) = dwarf.attr_string(unit, attr.value()) {
if let Ok(attr_string) = attr_reader.to_string() {
attr_line.push(InstructionTextToken::new(
BnString::new(attr_string.as_ref()),
@@ -236,7 +236,7 @@ fn get_info_string<R: Reader>(
let value_string = format!("{}", value);
attr_line.push(InstructionTextToken::new(
BnString::new(value_string),
- InstructionTextTokenContents::Integer(value.into()),
+ InstructionTextTokenContents::Integer(value),
));
} else if let Some(value) = attr.sdata_value() {
let value_string = format!("{}", value);
@@ -271,7 +271,7 @@ fn process_tree<R: Reader>(
// || (die_node.entry().tag() == constants::DW_TAG_compile_unit)
// || (die_node.entry().tag() == constants::DW_TAG_subprogram)
// {
- let new_node = FlowGraphNode::new(&graph);
+ let new_node = FlowGraphNode::new(graph);
let attr_string = get_info_string(view, dwarf, unit, die_node.entry());
new_node.set_disassembly_lines(&attr_string);
@@ -291,12 +291,11 @@ fn process_tree<R: Reader>(
}
fn dump_dwarf(bv: &BinaryView) {
- let view;
- if bv.section_by_name(".debug_info").is_ok() {
- view = bv.to_owned();
+ let view = if bv.section_by_name(".debug_info").is_ok() {
+ bv.to_owned()
} else {
- view = bv.parent_view().unwrap();
- }
+ bv.parent_view().unwrap()
+ };
// TODO : Accommodate Endianity
let get_section_data_little =
@@ -305,24 +304,23 @@ fn dump_dwarf(bv: &BinaryView) {
let offset = section.start();
let len = section.len();
if len == 0 {
- return Ok(CustomReader::new(
+ Ok(CustomReader::new(
DataBufferWrapper::new(DataBuffer::default()),
LittleEndian,
- ));
- }
-
- if let Ok(read_buffer) = view.read_buffer(offset, len as usize) {
- return Ok(CustomReader::new(
+ ))
+ } else if let Ok(read_buffer) = view.read_buffer(offset, len) {
+ Ok(CustomReader::new(
DataBufferWrapper::new(read_buffer),
LittleEndian,
- ));
+ ))
+ } else {
+ Err(Error::Io)
}
- return Err(Error::Io);
} else {
- return Ok(CustomReader::new(
+ Ok(CustomReader::new(
DataBufferWrapper::new(DataBuffer::default()),
LittleEndian,
- ));
+ ))
}
};
diff --git a/rust/examples/template/src/main.rs b/rust/examples/template/src/main.rs
index 1fbe3c83..0c27b6d2 100644
--- a/rust/examples/template/src/main.rs
+++ b/rust/examples/template/src/main.rs
@@ -23,19 +23,16 @@ fn main() {
// TODO : This is intended to be refactored to be more nice to work with soon(TM)
for addr in basic_block.as_ref() {
print!(" {} ", addr);
- match func.arch().instruction_text(
+ if let Some((_, tokens)) = func.arch().instruction_text(
bv.read_buffer(addr, func.arch().max_instr_len())
.unwrap()
.get_data(),
addr,
) {
- Some((_, tokens)) => {
- tokens
- .iter()
- .for_each(|token| print!("{}", token.text().as_str()));
- println!("")
- }
- _ => (),
+ tokens
+ .iter()
+ .for_each(|token| print!("{}", token.text().as_str()));
+ println!();
}
}
}
diff --git a/rust/src/architecture.rs b/rust/src/architecture.rs
index d5e1685f..348e8e06 100644
--- a/rust/src/architecture.rs
+++ b/rust/src/architecture.rs
@@ -108,12 +108,19 @@ impl InstructionInfo {
pub fn len(&self) -> usize {
self.0.length
}
+
+ pub fn is_empty(&self) -> bool {
+ self.0.length == 0
+ }
+
pub fn branch_count(&self) -> usize {
self.0.branchCount
}
+
pub fn branch_delay(&self) -> bool {
self.0.branchDelay
}
+
pub fn branches(&self) -> BranchIter {
BranchIter(self, 0..self.branch_count())
}
@@ -1363,7 +1370,7 @@ where
res.push(len as u32);
for i in items {
- res.push(i.clone().into());
+ res.push(i);
}
assert!(res.len() == len + 1);
@@ -1910,7 +1917,7 @@ where
let uninit_arch = ArchitectureBuilder {
arch: unsafe { zeroed() },
- func: func,
+ func,
};
let raw = Box::into_raw(Box::new(uninit_arch));
diff --git a/rust/src/basicblock.rs b/rust/src/basicblock.rs
index c59e8d22..cdd7186e 100644
--- a/rust/src/basicblock.rs
+++ b/rust/src/basicblock.rs
@@ -42,11 +42,11 @@ impl<'a, C: 'a + BlockContext> Edge<'a, C> {
}
pub fn source(&self) -> &BasicBlock<C> {
- &*self.source
+ &self.source
}
pub fn target(&self) -> &BasicBlock<C> {
- &*self.target
+ &self.target
}
}
@@ -100,8 +100,8 @@ unsafe impl<'a, C: 'a + BlockContext> CoreArrayWrapper<'a> for Edge<'a, C> {
Edge {
branch: raw.type_,
back_edge: raw.backEdge,
- source: source,
- target: target,
+ source,
+ target,
}
}
}
diff --git a/rust/src/binaryview.rs b/rust/src/binaryview.rs
index ad9a0fc9..2c9c5cc2 100644
--- a/rust/src/binaryview.rs
+++ b/rust/src/binaryview.rs
@@ -54,16 +54,20 @@ use crate::string::*;
pub type Result<R> = result::Result<R, ()>;
+#[allow(clippy::len_without_is_empty)]
pub trait BinaryViewBase: AsRef<BinaryView> {
fn read(&self, _buf: &mut [u8], _offset: u64) -> usize {
0
}
+
fn write(&self, _offset: u64, _data: &[u8]) -> usize {
0
}
+
fn insert(&self, _offset: u64, _data: &[u8]) -> usize {
0
}
+
fn remove(&self, _offset: u64, _len: usize) -> usize {
0
}
@@ -110,6 +114,7 @@ pub trait BinaryViewBase: AsRef<BinaryView> {
fn start(&self) -> u64 {
0
}
+
fn len(&self) -> usize {
0
}
@@ -117,6 +122,7 @@ pub trait BinaryViewBase: AsRef<BinaryView> {
fn executable(&self) -> bool {
true
}
+
fn relocatable(&self) -> bool {
true
}
@@ -890,7 +896,7 @@ pub trait BinaryViewExt: BinaryViewBase {
) -> Array<LinearDisassemblyLine> {
let mut result = unsafe { Array::new(std::ptr::null_mut(), 0, ()) };
- while result.len() == 0 {
+ while result.is_empty() {
result = pos.lines();
if !pos.next() {
return result;
@@ -913,7 +919,7 @@ pub trait BinaryViewExt: BinaryViewBase {
pos: &mut LinearViewCursor,
) -> Array<LinearDisassemblyLine> {
let mut result = unsafe { Array::new(std::ptr::null_mut(), 0, ()) };
- while result.len() == 0 {
+ while result.is_empty() {
if !pos.previous() {
return result;
}
diff --git a/rust/src/callingconvention.rs b/rust/src/callingconvention.rs
index d6a1efe4..99b6c654 100644
--- a/rust/src/callingconvention.rs
+++ b/rust/src/callingconvention.rs
@@ -96,7 +96,7 @@ where
res.push(len as u32);
for i in items {
- res.push(i.clone().into());
+ res.push(i);
}
assert!(res.len() == len + 1);
@@ -371,7 +371,7 @@ where
let name = name.into_bytes_with_nul();
let raw = Box::into_raw(Box::new(CustomCallingConventionContext {
raw_handle: ptr::null_mut(),
- cc: cc,
+ cc,
}));
let mut cc = BNCustomCallingConvention {
context: raw as *mut _,
@@ -436,7 +436,7 @@ impl<A: Architecture> CallingConvention<A> {
arch: A::Handle,
) -> Ref<Self> {
Ref::new(CallingConvention {
- handle: handle,
+ handle,
arch_handle: arch,
_arch: PhantomData,
})
@@ -448,7 +448,7 @@ impl<A: Architecture> CallingConvention<A> {
pub fn variables_for_parameters<S: Clone + BnStrCompatible>(
&self,
- params: &Vec<FunctionParameter<S>>,
+ params: &[FunctionParameter<S>],
int_arg_registers: Option<Vec<A::Register>>,
) -> Vec<Variable> {
let mut bn_params: Vec<BNFunctionParameter> = vec![];
@@ -459,7 +459,7 @@ impl<A: Architecture> CallingConvention<A> {
}
for (parameter, raw_name) in params.iter().zip(name_strings.iter_mut()) {
let location = match &parameter.location {
- Some(location) => location.into_raw(),
+ Some(location) => location.raw(),
None => unsafe { mem::zeroed() },
};
bn_params.push(BNFunctionParameter {
@@ -845,19 +845,19 @@ impl<A: Architecture> CallingConventionBase for ConventionBuilder<A> {
}
fn return_int_reg(&self) -> Option<A::Register> {
- self.return_int_reg.clone()
+ self.return_int_reg
}
fn return_hi_int_reg(&self) -> Option<A::Register> {
- self.return_hi_int_reg.clone()
+ self.return_hi_int_reg
}
fn return_float_reg(&self) -> Option<A::Register> {
- self.return_float_reg.clone()
+ self.return_float_reg
}
fn global_pointer_reg(&self) -> Option<A::Register> {
- self.global_pointer_reg.clone()
+ self.global_pointer_reg
}
fn implicitly_defined_registers(&self) -> Vec<A::Register> {
diff --git a/rust/src/custombinaryview.rs b/rust/src/custombinaryview.rs
index a50e956f..aa4e9e2f 100644
--- a/rust/src/custombinaryview.rs
+++ b/rust/src/custombinaryview.rs
@@ -76,7 +76,7 @@ where
let data = BinaryView::from_raw(BNNewViewReference(data));
let builder = CustomViewBuilder {
- view_type: view_type,
+ view_type,
actual_parent: &data,
};
@@ -254,7 +254,7 @@ impl BinaryViewTypeBase for BinaryViewType {
fn load_settings_for_data(&self, data: &BinaryView) -> Result<Ref<Settings>> {
let settings_handle =
- unsafe { BNGetBinaryViewDefaultLoadSettingsForData(self.as_ref().0, data.handle) };
+ unsafe { BNGetBinaryViewDefaultLoadSettingsForData(self.0, data.handle) };
if settings_handle.is_null() {
Err(())
@@ -441,10 +441,10 @@ impl<'a, T: CustomBinaryViewType> CustomViewBuilder<'a, T> {
if context.initialized {
mem::forget(context.args); // already consumed
- mem::drop(context.view); // cb_init was called
+ // mem::drop(context.view); // cb_init was called
} else {
mem::drop(context.args); // never consumed
- mem::forget(context.view); // cb_init was not called, is uninit
+ // mem::forget(context.view); // cb_init was not called, is uninit
if context.raw_handle.is_null() {
// being called here is essentially a guarantee that BNCreateBinaryViewOfType
diff --git a/rust/src/databuffer.rs b/rust/src/databuffer.rs
index 65003711..e8bf32c9 100644
--- a/rust/src/databuffer.rs
+++ b/rust/src/databuffer.rs
@@ -27,7 +27,7 @@ impl DataBuffer {
}
pub fn get_data(&self) -> &[u8] {
- if self.0 == ptr::null_mut() {
+ if self.0.is_null() {
// TODO : Change the default value and remove this
return &[];
}
@@ -43,6 +43,10 @@ impl DataBuffer {
unsafe { BNGetDataBufferLength(self.0) }
}
+ pub fn is_empty(&self) -> bool {
+ unsafe { BNGetDataBufferLength(self.0) == 0 }
+ }
+
// pub fn new(data: ?, len: usize) -> Result<Self> {
// let read_buffer = unsafe { BNCreateDataBuffer(data, len) };
// if read_buffer.is_null() {
@@ -62,7 +66,7 @@ impl Default for DataBuffer {
impl Drop for DataBuffer {
fn drop(&mut self) {
- if self.0 != ptr::null_mut() {
+ if !self.0.is_null() {
unsafe {
BNFreeDataBuffer(self.0);
}
diff --git a/rust/src/debuginfo.rs b/rust/src/debuginfo.rs
index 766ed026..32b478fb 100644
--- a/rust/src/debuginfo.rs
+++ b/rust/src/debuginfo.rs
@@ -172,7 +172,7 @@ impl DebugInfoParser {
if info.is_null() {
return None;
}
- return Some(unsafe { DebugInfo::from_raw(info) });
+ Some(unsafe { DebugInfo::from_raw(info) })
}
// Registers a DebugInfoParser. See `binaryninja::debuginfo::DebugInfoParser` for more details.
@@ -576,11 +576,11 @@ impl DebugInfo {
unsafe { slice::from_raw_parts(raw_names_and_types as *mut _, count) };
let mut result = Vec::with_capacity(count);
- for i in 0..count {
+ for name_and_type in names_and_types.iter().take(count) {
unsafe {
result.push((
- raw_to_string((*names_and_types[i]).name).unwrap(),
- Type::ref_from_raw(BNNewTypeReference((*names_and_types[i]).type_)),
+ raw_to_string((**name_and_type).name).unwrap(),
+ Type::ref_from_raw(BNNewTypeReference((**name_and_type).type_)),
))
};
}
@@ -605,12 +605,12 @@ impl DebugInfo {
unsafe { slice::from_raw_parts(raw_variables_and_names as *mut _, count) };
let mut result = Vec::with_capacity(count);
- for i in 0..count {
+ for variable_and_name in variables_and_names.iter().take(count) {
unsafe {
result.push((
- raw_to_string((*variables_and_names[i]).name).unwrap(),
- (*variables_and_names[i]).address,
- Type::ref_from_raw(BNNewTypeReference((*variables_and_names[i]).type_)),
+ raw_to_string((**variable_and_name).name).unwrap(),
+ (**variable_and_name).address,
+ Type::ref_from_raw(BNNewTypeReference((**variable_and_name).type_)),
))
};
}
@@ -629,12 +629,12 @@ impl DebugInfo {
unsafe { slice::from_raw_parts(raw_variables_and_names as *mut _, count) };
let mut result = Vec::with_capacity(count);
- for i in 0..count {
+ for variable_and_name in variables_and_names.iter().take(count) {
unsafe {
result.push((
- raw_to_string((*variables_and_names[i]).parser).unwrap(),
- raw_to_string((*variables_and_names[i]).name).unwrap(),
- Type::ref_from_raw(BNNewTypeReference((*variables_and_names[i]).type_)),
+ raw_to_string((**variable_and_name).parser).unwrap(),
+ raw_to_string((**variable_and_name).name).unwrap(),
+ Type::ref_from_raw(BNNewTypeReference((**variable_and_name).type_)),
))
};
}
diff --git a/rust/src/disassembly.rs b/rust/src/disassembly.rs
index 22706f4b..ff33e3dd 100644
--- a/rust/src/disassembly.rs
+++ b/rust/src/disassembly.rs
@@ -98,7 +98,7 @@ pub enum InstructionTextTokenContents {
impl InstructionTextToken {
pub(crate) unsafe fn from_raw(raw: &BNInstructionTextToken) -> Self {
- Self(raw.clone())
+ Self(*raw)
}
pub fn new(text: BnString, contents: InstructionTextTokenContents) -> Self {
@@ -289,11 +289,7 @@ impl DisassemblyTextLine {
impl std::fmt::Display for DisassemblyTextLine {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for token in self.tokens() {
- let result = write!(f, "{}", token.text());
-
- if result.is_err() {
- return result;
- }
+ write!(f, "{}", token.text())?
}
Ok(())
diff --git a/rust/src/downloadprovider.rs b/rust/src/downloadprovider.rs
index 65a11dd0..dfc8b5e2 100644
--- a/rust/src/downloadprovider.rs
+++ b/rust/src/downloadprovider.rs
@@ -38,6 +38,8 @@ impl DownloadProvider {
Ok(unsafe { Array::new(list, count, ()) })
}
+ /// TODO : Clippy isn't happy...says we should `impl Default`....excessive error checking might be preventing us from doing so
+ #[allow(clippy::should_implement_trait)]
pub fn default() -> Result<DownloadProvider, ()> {
let s = Settings::new("");
let dp_name = s.get_string("network.downloadProviderName", None, None);
@@ -164,10 +166,10 @@ impl DownloadInstance {
// Drop it
unsafe { Box::from_raw(callbacks) };
if result < 0 {
- return Err(self.get_error());
+ Err(self.get_error())
+ } else {
+ Ok(())
}
-
- return Ok(());
}
unsafe extern "C" fn i_read_callback(data: *mut u8, len: u64, ctxt: *mut c_void) -> i64 {
diff --git a/rust/src/fileaccessor.rs b/rust/src/fileaccessor.rs
index 68b9cf14..874e348d 100644
--- a/rust/src/fileaccessor.rs
+++ b/rust/src/fileaccessor.rs
@@ -35,10 +35,7 @@ impl<'a> FileAccessor<'a> {
{
let f = unsafe { &mut *(ctxt as *mut F) };
- match f.seek(SeekFrom::End(0)) {
- Ok(len) => len,
- Err(_) => 0,
- }
+ f.seek(SeekFrom::End(0)).unwrap_or(0)
}
extern "C" fn cb_read<F>(
@@ -53,14 +50,11 @@ impl<'a> FileAccessor<'a> {
let f = unsafe { &mut *(ctxt as *mut F) };
let dest = unsafe { slice::from_raw_parts_mut(dest as *mut u8, len) };
- if !f.seek(SeekFrom::Start(offset)).is_ok() {
+ if f.seek(SeekFrom::Start(offset)).is_err() {
debug!("Failed to seek to offset {:x}", offset);
- return 0;
- }
-
- match f.read(dest) {
- Ok(len) => len,
- Err(_) => 0,
+ 0
+ } else {
+ f.read(dest).unwrap_or(0)
}
}
@@ -76,13 +70,10 @@ impl<'a> FileAccessor<'a> {
let f = unsafe { &mut *(ctxt as *mut F) };
let src = unsafe { slice::from_raw_parts(src as *const u8, len) };
- if !f.seek(SeekFrom::Start(offset)).is_ok() {
- return 0;
- }
-
- match f.write(src) {
- Ok(len) => len,
- Err(_) => 0,
+ if f.seek(SeekFrom::Start(offset)).is_err() {
+ 0
+ } else {
+ f.write(src).unwrap_or(0)
}
}
diff --git a/rust/src/flowgraph.rs b/rust/src/flowgraph.rs
index c4bf5340..92b098cd 100644
--- a/rust/src/flowgraph.rs
+++ b/rust/src/flowgraph.rs
@@ -33,9 +33,9 @@ pub struct EdgeStyle(pub(crate) BNEdgeStyle);
impl EdgeStyle {
pub fn new(style: EdgePenStyle, width: usize, color: ThemeColor) -> Self {
EdgeStyle(BNEdgeStyle {
- style: style,
- width: width,
- color: color,
+ style,
+ width,
+ color,
})
}
}
@@ -65,12 +65,12 @@ impl<'a> FlowGraphNode<'a> {
}
pub fn new(graph: &FlowGraph) -> Self {
- unsafe { FlowGraphNode::from_raw(BNCreateFlowGraphNode(graph.as_ref().handle)) }
+ unsafe { FlowGraphNode::from_raw(BNCreateFlowGraphNode(graph.handle)) }
}
pub fn set_disassembly_lines(&self, lines: &'a Vec<DisassemblyTextLine>) {
unsafe {
- BNSetFlowGraphNodeLines(self.as_ref().handle, lines.as_ptr() as *mut _, lines.len());
+ 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?
}
}
@@ -91,9 +91,9 @@ impl<'a> FlowGraphNode<'a> {
) {
unsafe {
BNAddFlowGraphNodeOutgoingEdge(
- self.as_ref().handle,
+ self.handle,
type_,
- target.as_ref().handle,
+ target.handle,
edge_style.0,
)
}
@@ -144,15 +144,15 @@ impl FlowGraph {
}
pub fn append(&self, node: &FlowGraphNode) -> usize {
- unsafe { BNAddFlowGraphNode(self.as_ref().handle, node.handle) }
+ unsafe { BNAddFlowGraphNode(self.handle, node.handle) }
}
pub fn set_option(&self, option: FlowGraphOption, value: bool) {
- unsafe { BNSetFlowGraphOption(self.as_ref().handle, option, value) }
+ unsafe { BNSetFlowGraphOption(self.handle, option, value) }
}
pub fn is_option_set(&self, option: FlowGraphOption) -> bool {
- unsafe { BNIsFlowGraphOptionSet(self.as_ref().handle, option) }
+ unsafe { BNIsFlowGraphOptionSet(self.handle, option) }
}
}
diff --git a/rust/src/function.rs b/rust/src/function.rs
index 186671d9..f56f0d64 100644
--- a/rust/src/function.rs
+++ b/rust/src/function.rs
@@ -37,7 +37,7 @@ impl From<u64> for Location {
fn from(addr: u64) -> Self {
Location {
arch: None,
- addr: addr,
+ addr,
}
}
}
diff --git a/rust/src/headless.rs b/rust/src/headless.rs
index cca8863b..c54e3ec9 100644
--- a/rust/src/headless.rs
+++ b/rust/src/headless.rs
@@ -89,14 +89,12 @@ pub fn shutdown() {
/// Prelued-postlued helper function (calls [`init`] and [`shutdown`] for you)
/// ```rust
-/// fn main() {
-/// binaryninja::headless::script_helper(|| {
-/// binaryninja::open_view("/bin/cat")
-/// .expect("Couldn't open `/bin/cat`")
-/// .iter()
-/// .for_each(|func| println!(" `{}`", func.symbol().full_name()));
-/// });
-/// }
+/// binaryninja::headless::script_helper(|| {
+/// binaryninja::open_view("/bin/cat")
+/// .expect("Couldn't open `/bin/cat`")
+/// .iter()
+/// .for_each(|func| println!(" `{}`", func.symbol().full_name()));
+/// });
/// ```
pub fn script_helper(func: fn()) {
init();
diff --git a/rust/src/lib.rs b/rust/src/lib.rs
index 19414a22..db550b49 100644
--- a/rust/src/lib.rs
+++ b/rust/src/lib.rs
@@ -12,6 +12,12 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+// TODO : If I commit this I've fucked up
+#![allow(clippy::missing_safety_doc)]
+#![allow(clippy::type_complexity)]
+#![allow(clippy::from_over_into)]
+// TODO : This is bad and needs to be removed
+#![allow(clippy::result_unit_err)]
#![doc(html_no_source)]
#![doc(html_favicon_url = "/favicon.ico")]
#![doc(html_logo_url = "/logo.png")]
@@ -342,8 +348,7 @@ pub fn open_view<F: AsRef<Path>>(filename: F) -> Result<rc::Ref<binaryview::Bina
let mut file = File::open(filename).or(Err("Could not open file".to_string()))?;
let mut buf = [0; 15];
- file.read_exact(&mut buf)
- .or(Err("Not a valid BNDB (too small)".to_string()))?;
+ file.read_exact(&mut buf).map_err(|_| "Not a valid BNDB (too small)".to_string())?;
let sqlite_string = "SQLite format 3";
if buf != sqlite_string.as_bytes() {
return Err("Not a valid BNDB (invalid magic)".to_string());
@@ -361,14 +366,13 @@ pub fn open_view<F: AsRef<Path>>(filename: F) -> Result<rc::Ref<binaryview::Bina
.iter()
.filter_map(|available_view| {
if **available_view.name() == *"Raw" {
- return None;
- }
- if is_bndb {
- return Some(view.file().get_view_of_type(available_view.name()).unwrap());
+ None
+ } else if is_bndb {
+ Some(view.file().get_view_of_type(available_view.name()).unwrap())
} else {
// TODO : add log prints
println!("Opening view of type: `{}`", available_view.name());
- return Some(available_view.open(&view).unwrap());
+ Some(available_view.open(&view).unwrap())
}
})
.next()
@@ -471,38 +475,38 @@ pub fn open_view_with_options<F: AsRef<Path>>(
if load_settings.is_none() {
// TODO : The Python version has a "fixme" here but I have no idea why
- if universal_view_type.is_some()
- && options.is_some()
- && options
- .as_ref()
- .unwrap()
- .contains_key("files.universal.architecturePreference")
- {
- load_settings = match universal_view_type
- .unwrap()
- .load_settings_for_data(view.as_ref())
- {
- Ok(settings) => Some(settings),
- _ => return Err("Could not load settings for universal view data".to_string()),
- };
- // let arch_list = load_settings.as_ref().unwrap().get_string(
- // "loader.universal.architectures",
- // None,
- // None,
- // );
+ if let (Some(universal_view_type), Some(options)) = (universal_view_type, &options) {
+ if options.contains_key("files.universal.architecturePreference") {
+ if let Ok(settings) = universal_view_type.load_settings_for_data(view.as_ref()) {
+ load_settings = Some(settings);
+ } else {
+ return Err("Could not load settings for universal view data".to_string());
+ };
+
+ // let arch_list = load_settings.as_ref().unwrap().get_string(
+ // "loader.universal.architectures",
+ // None,
+ // None,
+ // );
- // TODO : Need json support
- // let arch_list = arch_list.as_str();
- // let arch_list = arch_list[1..arch_list.len()].split("'");
- // arch_entry = [entry for entry in arch_list if entry['architecture'] == options['files.universal.architecturePreference'][0]]
- // if not arch_entry:
- // log.log_error(f"Could not load {options['files.universal.architecturePreference'][0]} from Universal image. Entry not found!")
- // return None
+ // TODO : Need json support
+ // let arch_list = arch_list.as_str();
+ // let arch_list = arch_list[1..arch_list.len()].split("'");
+ // arch_entry = [entry for entry in arch_list if entry['architecture'] == options['files.universal.architecturePreference'][0]]
+ // if not arch_entry:
+ // log.log_error(f"Could not load {options['files.universal.architecturePreference'][0]} from Universal image. Entry not found!")
+ // return None
- // let tmp_load_settings = settings::Settings::new(BNGetUniqueIdentifierString());
- // tmp_load_settings.deserialize_schema(arch_entry[0]['loadSchema']);
- // load_settings = Some(tmp_load_settings);
+ // let tmp_load_settings = settings::Settings::new(BNGetUniqueIdentifierString());
+ // tmp_load_settings.deserialize_schema(arch_entry[0]['loadSchema']);
+ // load_settings = Some(tmp_load_settings);
+ } else {
+ load_settings = match view_type.load_settings_for_data(view.as_ref()) {
+ Ok(settings) => Some(settings),
+ _ => None,
+ };
+ }
} else {
load_settings = match view_type.load_settings_for_data(view.as_ref()) {
Ok(settings) => Some(settings),
@@ -518,23 +522,20 @@ pub fn open_view_with_options<F: AsRef<Path>>(
load_settings.set_resource_id(view_type.name());
view.set_load_settings(view_type.name(), load_settings.as_ref());
- match options {
- Some(options) => {
- for (setting, value) in options {
- if load_settings.contains(setting) {
- if !load_settings.set_json(setting, value, Some(view.as_ref()), None) {
- return Err(format!("Setting: {} set operation failed!", setting));
- }
- } else if default_settings.contains(setting) {
- if !default_settings.set_json(setting, value, Some(view.as_ref()), None) {
- return Err(format!("Setting: {} set operation failed!", setting));
- }
- } else {
- return Err(format!("Setting: {} not available!", setting));
+ if let Some(options) = options {
+ for (setting, value) in options {
+ if load_settings.contains(setting) {
+ if !load_settings.set_json(setting, value, Some(view.as_ref()), None) {
+ return Err(format!("Setting: {} set operation failed!", setting));
+ }
+ } else if default_settings.contains(setting) {
+ if !default_settings.set_json(setting, value, Some(view.as_ref()), None) {
+ return Err(format!("Setting: {} set operation failed!", setting));
}
+ } else {
+ return Err(format!("Setting: {} not available!", setting));
}
}
- None => (),
}
if is_bndb {
diff --git a/rust/src/llil/function.rs b/rust/src/llil/function.rs
index 1c2b7df0..20d2cb04 100644
--- a/rust/src/llil/function.rs
+++ b/rust/src/llil/function.rs
@@ -103,7 +103,7 @@ where
use binaryninjacore_sys::BNLowLevelILGetInstructionStart;
let loc: Location = loc.into();
- let arch_handle = loc.arch.unwrap_or_else(|| *self.arch().as_ref());
+ let arch_handle = loc.arch.unwrap_or(*self.arch().as_ref());
unsafe {
let instr_idx = BNLowLevelILGetInstructionStart(self.handle, arch_handle.0, loc.addr);
@@ -113,7 +113,7 @@ where
} else {
Some(Instruction {
function: self,
- instr_idx: instr_idx,
+ instr_idx,
})
}
}
@@ -128,7 +128,7 @@ where
Instruction {
function: self,
- instr_idx: instr_idx,
+ instr_idx,
}
}
}
diff --git a/rust/src/llil/instruction.rs b/rust/src/llil/instruction.rs
index ad7ce274..20cc545b 100644
--- a/rust/src/llil/instruction.rs
+++ b/rust/src/llil/instruction.rs
@@ -115,13 +115,13 @@ where
}
LLIL_SYSCALL => InstrInfo::Syscall(Operation::new(self.function, op)),
_ => {
- common_info(self.function, op).unwrap_or_else(|| {
+ common_info(self.function, op).unwrap_or({
// Hopefully this is a bare value. If it isn't (expression
// from wrong function form or similar) it won't really cause
// any problems as it'll come back as undefined when queried.
let expr = Expression {
function: self.function,
- expr_idx: expr_idx,
+ expr_idx,
_ty: PhantomData,
};
diff --git a/rust/src/llil/lifting.rs b/rust/src/llil/lifting.rs
index 216b3bbd..bd87b9bc 100644
--- a/rust/src/llil/lifting.rs
+++ b/rust/src/llil/lifting.rs
@@ -59,7 +59,7 @@ impl<R: ArchReg> RegisterOrConstant<R> {
RegisterOrConstant::Constant(_, value) => BNRegisterOrConstant {
constant: true,
reg: 0,
- value: value,
+ value,
},
}
}
@@ -385,7 +385,7 @@ where
Expression {
function: il,
- expr_idx: expr_idx,
+ expr_idx,
_ty: PhantomData,
}
}
@@ -410,7 +410,7 @@ where
Expression {
function: il,
- expr_idx: expr_idx,
+ expr_idx,
_ty: PhantomData,
}
}
@@ -663,7 +663,7 @@ where
Expression {
function: self.function,
- expr_idx: expr_idx,
+ expr_idx,
_ty: PhantomData,
}
}
@@ -723,7 +723,7 @@ macro_rules! no_arg_lifter {
Expression {
function: self,
- expr_idx: expr_idx,
+ expr_idx,
_ty: PhantomData,
}
}
@@ -738,7 +738,7 @@ macro_rules! sized_no_arg_lifter {
ExpressionBuilder {
function: self,
op: $op,
- size: size,
+ size,
flags: 0,
op1: 0,
op2: 0,
@@ -770,7 +770,7 @@ macro_rules! unsized_unary_op_lifter {
Expression {
function: self,
- expr_idx: expr_idx,
+ expr_idx,
_ty: PhantomData,
}
}
@@ -790,7 +790,7 @@ macro_rules! sized_unary_op_lifter {
ExpressionBuilder {
function: self,
op: $op,
- size: size,
+ size,
flags: 0,
op1: expr.expr_idx as u64,
op2: 0,
@@ -815,7 +815,7 @@ macro_rules! size_changing_unary_op_lifter {
ExpressionBuilder {
function: self,
op: $op,
- size: size,
+ size,
flags: 0,
op1: expr.expr_idx as u64,
op2: 0,
@@ -847,7 +847,7 @@ macro_rules! binary_op_lifter {
ExpressionBuilder {
function: self,
op: $op,
- size: size,
+ size,
flags: 0,
op1: left.expr_idx as u64,
op2: right.expr_idx as u64,
@@ -882,7 +882,7 @@ macro_rules! binary_op_carry_lifter {
ExpressionBuilder {
function: self,
op: $op,
- size: size,
+ size,
flags: 0,
op1: left.expr_idx as u64,
op2: right.expr_idx as u64,
@@ -946,7 +946,7 @@ where
Expression {
function: self,
- expr_idx: expr_idx,
+ expr_idx,
_ty: PhantomData,
}
}
@@ -964,7 +964,7 @@ where
Expression {
function: self,
- expr_idx: expr_idx,
+ expr_idx,
_ty: PhantomData,
}
}
@@ -981,7 +981,7 @@ where
Expression {
function: self,
- expr_idx: expr_idx,
+ expr_idx,
_ty: PhantomData,
}
}
@@ -1023,7 +1023,7 @@ where
Expression {
function: self,
- expr_idx: expr_idx,
+ expr_idx,
_ty: PhantomData,
}
}
@@ -1038,7 +1038,7 @@ where
Expression {
function: self,
- expr_idx: expr_idx,
+ expr_idx,
_ty: PhantomData,
}
}
@@ -1062,7 +1062,7 @@ where
Expression {
function: self,
- expr_idx: expr_idx,
+ expr_idx,
_ty: PhantomData,
}
}
@@ -1090,7 +1090,7 @@ where
ExpressionBuilder {
function: self,
op: LLIL_SET_REG,
- size: size,
+ size,
flags: 0,
op1: dest_reg as u64,
op2: expr.expr_idx as u64,
@@ -1131,7 +1131,7 @@ where
ExpressionBuilder {
function: self,
op: LLIL_SET_REG_SPLIT,
- size: size,
+ size,
flags: 0,
op1: hi_reg as u64,
op2: lo_reg as u64,
@@ -1151,7 +1151,7 @@ where
Expression {
function: self,
- expr_idx: expr_idx,
+ expr_idx,
_ty: PhantomData,
}
}
@@ -1169,7 +1169,7 @@ where
Expression {
function: self,
- expr_idx: expr_idx,
+ expr_idx,
_ty: PhantomData,
}
}
@@ -1197,7 +1197,7 @@ where
Expression {
function: self,
- expr_idx: expr_idx,
+ expr_idx,
_ty: PhantomData,
}
}
@@ -1245,7 +1245,7 @@ where
ExpressionBuilder {
function: self,
op: LLIL_LOAD,
- size: size,
+ size,
flags: 0,
op1: expr.expr_idx as u64,
op2: 0,
@@ -1273,7 +1273,7 @@ where
ExpressionBuilder {
function: self,
op: LLIL_STORE,
- size: size,
+ size,
flags: 0,
op1: dest_mem.expr_idx as u64,
op2: value.expr_idx as u64,
@@ -1353,7 +1353,7 @@ where
use binaryninjacore_sys::BNLowLevelILSetCurrentAddress;
let loc: Location = loc.into();
- let arch = loc.arch.unwrap_or_else(|| *self.arch().as_ref());
+ let arch = loc.arch.unwrap_or(*self.arch().as_ref());
unsafe {
BNLowLevelILSetCurrentAddress(self.handle, arch.0, loc.addr);
@@ -1364,7 +1364,7 @@ where
use binaryninjacore_sys::BNGetLowLevelILLabelForAddress;
let loc: Location = loc.into();
- let arch = loc.arch.unwrap_or_else(|| *self.arch().as_ref());
+ let arch = loc.arch.unwrap_or(*self.arch().as_ref());
let res = unsafe { BNGetLowLevelILLabelForAddress(self.handle, arch.0, loc.addr) };
@@ -1400,3 +1400,9 @@ impl Label {
}
}
}
+
+impl Default for Label {
+ fn default() -> Self {
+ Label::new()
+ }
+}
diff --git a/rust/src/llil/operation.rs b/rust/src/llil/operation.rs
index f7d59ef6..296a45db 100644
--- a/rust/src/llil/operation.rs
+++ b/rust/src/llil/operation.rs
@@ -40,8 +40,8 @@ where
{
pub(crate) fn new(function: &'func Function<A, M, F>, op: BNLowLevelILInstruction) -> Self {
Self {
- function: function,
- op: op,
+ function,
+ op,
_args: PhantomData,
}
}
@@ -108,7 +108,7 @@ where
.arch()
.register_from_id(raw_id)
.map(Register::ArchReg)
- .unwrap_or_else(|| {
+ .unwrap_or({
error!(
"got garbage register from LLIL_SET_REG @ 0x{:x}",
self.op.address
@@ -151,7 +151,7 @@ where
.arch()
.register_from_id(raw_id)
.map(Register::ArchReg)
- .unwrap_or_else(|| {
+ .unwrap_or({
error!(
"got garbage register from LLIL_SET_REG_SPLIT @ 0x{:x}",
self.op.address
@@ -172,7 +172,7 @@ where
.arch()
.register_from_id(raw_id)
.map(Register::ArchReg)
- .unwrap_or_else(|| {
+ .unwrap_or({
error!(
"got garbage register from LLIL_SET_REG_SPLIT @ 0x{:x}",
self.op.address
@@ -285,7 +285,7 @@ where
.arch()
.register_from_id(raw_id)
.map(Register::ArchReg)
- .unwrap_or_else(|| {
+ .unwrap_or({
error!(
"got garbage register from LLIL_REG @ 0x{:x}",
self.op.address
diff --git a/rust/src/metadata.rs b/rust/src/metadata.rs
index 120a08b7..b17ba41c 100644
--- a/rust/src/metadata.rs
+++ b/rust/src/metadata.rs
@@ -1,4 +1,3 @@
-#[allow(non_snake_case)]
use crate::rc::{
Array, CoreArrayProvider, CoreArrayWrapper, CoreOwnedArrayProvider, Guard, Ref, RefCountable,
};
@@ -236,6 +235,10 @@ impl Metadata {
unsafe { BNMetadataSize(self.handle) }
}
+ pub fn is_empty(&self) -> bool {
+ unsafe { BNMetadataSize(self.handle) == 0 }
+ }
+
pub fn index(&self, index: usize) -> Result<Option<Ref<Metadata>>, ()> {
if self.get_type() != MetadataType::ArrayDataType {
return Err(());
diff --git a/rust/src/rc.rs b/rust/src/rc.rs
index 1c7de9da..57deddc3 100644
--- a/rust/src/rc.rs
+++ b/rust/src/rc.rs
@@ -147,6 +147,7 @@ impl<'a, T> Guard<'a, T>
where
T: RefCountable,
{
+ #[allow(clippy::should_implement_trait)] // This _is_ out own (lite) version of that trait
pub fn clone(&self) -> Ref<T> {
unsafe { <T as RefCountable>::inc_ref(&self.contents) }
}
@@ -230,6 +231,11 @@ impl<P: CoreOwnedArrayProvider> Array<P> {
self.count
}
+ #[inline]
+ pub fn is_empty(&self) -> bool {
+ self.count == 0
+ }
+
pub fn into_raw_parts(self) -> (*mut P::Raw, usize) {
let me = mem::ManuallyDrop::new(self);
(me.contents, me.count)
@@ -302,6 +308,11 @@ impl<P: CoreArrayProvider> ArrayGuard<P> {
pub fn len(&self) -> usize {
self.count
}
+
+ #[inline]
+ pub fn is_empty(&self) -> bool {
+ self.count == 0
+ }
}
impl<'a, P: 'a + CoreArrayWrapper<'a> + CoreArrayProvider> ArrayGuard<P> {
@@ -355,7 +366,7 @@ where
fn next(&mut self) -> Option<P::Wrapped> {
self.it
.next()
- .map(|r| unsafe { P::wrap_raw(r, &self.context) })
+ .map(|r| unsafe { P::wrap_raw(r, self.context) })
}
#[inline]
@@ -382,7 +393,7 @@ where
fn next_back(&mut self) -> Option<P::Wrapped> {
self.it
.next_back()
- .map(|r| unsafe { P::wrap_raw(r, &self.context) })
+ .map(|r| unsafe { P::wrap_raw(r, self.context) })
}
}
diff --git a/rust/src/section.rs b/rust/src/section.rs
index 4eb49e69..b73809c0 100644
--- a/rust/src/section.rs
+++ b/rust/src/section.rs
@@ -70,19 +70,14 @@ impl Section {
Self { handle: raw }
}
+ #[allow(clippy::new_ret_no_self)]
+ /// You need to create a section builder, customize that section, then add it to a binary view:
+ ///
+ /// ```
+ /// bv.add_section(Section::new().align(4).entry_size(4))
+ /// ```
pub fn new<S: BnStrCompatible>(name: S, range: Range<u64>) -> SectionBuilder<S> {
- SectionBuilder {
- is_auto: false,
- name: name,
- range: range,
- semantics: Semantics::DefaultSection,
- _ty: None,
- align: 1,
- entry_size: 1,
- linked_section: None,
- info_section: None,
- info_data: 0,
- }
+ SectionBuilder::new(name, range)
}
pub fn name(&self) -> BnString {
@@ -105,6 +100,10 @@ impl Section {
unsafe { BNSectionGetLength(self.handle) as usize }
}
+ pub fn is_empty(&self) -> bool {
+ unsafe { BNSectionGetLength(self.handle) as usize == 0 }
+ }
+
pub fn address_range(&self) -> Range<u64> {
self.start()..self.end()
}
@@ -204,6 +203,21 @@ pub struct SectionBuilder<S: BnStrCompatible> {
}
impl<S: BnStrCompatible> SectionBuilder<S> {
+ pub fn new(name: S, range: Range<u64>) -> Self {
+ SectionBuilder {
+ is_auto: false,
+ name,
+ range,
+ semantics: Semantics::DefaultSection,
+ _ty: None,
+ align: 1,
+ entry_size: 1,
+ linked_section: None,
+ info_section: None,
+ info_data: 0,
+ }
+ }
+
pub fn semantics(mut self, semantics: Semantics) -> Self {
self.semantics = semantics;
self
diff --git a/rust/src/segment.rs b/rust/src/segment.rs
index 88cf9356..285aa8a8 100644
--- a/rust/src/segment.rs
+++ b/rust/src/segment.rs
@@ -34,6 +34,15 @@ pub struct SegmentBuilder {
}
impl SegmentBuilder {
+ pub fn new(ea: Range<u64>) -> Self {
+ SegmentBuilder {
+ ea,
+ parent_backing: None,
+ flags: 0,
+ is_auto: false,
+ }
+ }
+
pub fn parent_backing(mut self, parent_backing: Range<u64>) -> Self {
self.parent_backing = Some(parent_backing);
self
@@ -106,13 +115,14 @@ impl Segment {
Self { handle: raw }
}
+ #[allow(clippy::new_ret_no_self)]
+ /// You need to create a segment builder, customize that segment, then add it to a binary view:
+ ///
+ /// ```
+ /// bv.add_segment(Segment::new().align(4).entry_size(4))
+ /// ```
pub fn new(ea_range: Range<u64>) -> SegmentBuilder {
- SegmentBuilder {
- ea: ea_range,
- parent_backing: None,
- flags: 0,
- is_auto: false,
- }
+ SegmentBuilder::new(ea_range)
}
pub fn address_range(&self) -> Range<u64> {
diff --git a/rust/src/symbol.rs b/rust/src/symbol.rs
index 5b1d62a1..0b3ef224 100644
--- a/rust/src/symbol.rs
+++ b/rust/src/symbol.rs
@@ -113,6 +113,18 @@ pub struct SymbolBuilder<S: BnStrCompatible> {
}
impl<S: BnStrCompatible> SymbolBuilder<S> {
+ pub fn new(ty: SymbolType, raw_name: S, addr: u64) -> Self {
+ Self {
+ ty,
+ binding: Binding::None,
+ addr,
+ raw_name,
+ short_name: None,
+ full_name: None,
+ ordinal: 0,
+ }
+ }
+
pub fn binding(mut self, binding: Binding) -> Self {
self.binding = binding;
self
@@ -163,7 +175,6 @@ impl<S: BnStrCompatible> SymbolBuilder<S> {
}
}
-#[derive(Hash)]
pub struct Symbol {
pub(crate) handle: *mut BNSymbol,
}
@@ -173,16 +184,14 @@ impl Symbol {
Self { handle: raw }
}
+ #[allow(clippy::new_ret_no_self)]
+ /// To create a new symbol, you need to create a symbol builder, customize that symbol, then add `SymbolBuilder::create` it into a `Ref<Symbol>`:
+ ///
+ /// ```
+ /// Symbol::new().short_name("hello").full_name("hello").create();
+ /// ```
pub fn new<S: BnStrCompatible>(ty: SymbolType, raw_name: S, addr: u64) -> SymbolBuilder<S> {
- SymbolBuilder {
- ty: ty,
- binding: Binding::None,
- addr: addr,
- raw_name: raw_name,
- short_name: None,
- full_name: None,
- ordinal: 0,
- }
+ SymbolBuilder::new(ty, raw_name, addr)
}
pub fn sym_type(&self) -> SymbolType {
@@ -278,6 +287,12 @@ unsafe impl<'a> CoreArrayWrapper<'a> for Symbol {
}
}
+impl Hash for Symbol {
+ fn hash<H: Hasher>(&self, state: &mut H) {
+ self.handle.hash(state);
+ }
+}
+
impl PartialEq for Symbol {
fn eq(&self, other: &Self) -> bool {
self.handle == other.handle
diff --git a/rust/src/types.rs b/rust/src/types.rs
index c7f55b8f..a8f023ad 100644
--- a/rust/src/types.rs
+++ b/rust/src/types.rs
@@ -310,13 +310,13 @@ impl TypeBuilder {
// Settable properties
- pub fn set_const<'a, T: Into<Conf<bool>>>(&'a mut self, value: T) -> &'a mut Self {
+ pub fn set_const<T: Into<Conf<bool>>>(&mut self, value: T) -> &mut Self {
let mut bool_with_confidence = value.into().into();
unsafe { BNTypeBuilderSetConst(self.handle, &mut bool_with_confidence) };
self
}
- pub fn set_volatile<'a, T: Into<Conf<bool>>>(&'a mut self, value: T) -> &'a mut Self {
+ pub fn set_volatile<T: Into<Conf<bool>>>(&mut self, value: T) -> &mut Self {
let mut bool_with_confidence = value.into().into();
unsafe { BNTypeBuilderSetVolatile(self.handle, &mut bool_with_confidence) };
self
@@ -621,7 +621,7 @@ impl TypeBuilder {
&t.into().into(),
&mut is_const,
&mut is_volatile,
- ref_type.unwrap_or_else(|| ReferenceType::PointerReferenceType),
+ ref_type.unwrap_or(ReferenceType::PointerReferenceType),
))
}
}
@@ -641,7 +641,7 @@ impl TypeBuilder {
&t.into().into(),
&mut is_const,
&mut is_volatile,
- ref_type.unwrap_or_else(|| ReferenceType::PointerReferenceType),
+ ref_type.unwrap_or(ReferenceType::PointerReferenceType),
))
}
}
@@ -664,7 +664,7 @@ impl Drop for TypeBuilder {
//////////
// Type
-#[derive(Eq, Hash)]
+#[derive(Eq)]
pub struct Type {
pub(crate) handle: *mut BNType,
}
@@ -978,7 +978,7 @@ impl Type {
for parameter in parameters {
let raw_name = parameter.name.clone().into_bytes_with_nul();
let location = match &parameter.location {
- Some(location) => location.into_raw(),
+ Some(location) => location.raw(),
None => unsafe { mem::zeroed() },
};
@@ -1048,7 +1048,7 @@ impl Type {
for (name, parameter) in zip(name_ptrs, parameters) {
let raw_name = name.into_bytes_with_nul();
let location = match &parameter.location {
- Some(location) => location.into_raw(),
+ Some(location) => location.raw(),
None => unsafe { mem::zeroed() },
};
@@ -1136,7 +1136,7 @@ impl Type {
&t.into().into(),
&mut is_const,
&mut is_volatile,
- ref_type.unwrap_or_else(|| ReferenceType::PointerReferenceType),
+ ref_type.unwrap_or(ReferenceType::PointerReferenceType),
))
}
}
@@ -1156,7 +1156,7 @@ impl Type {
&t.into().into(),
&mut is_const,
&mut is_volatile,
- ref_type.unwrap_or_else(|| ReferenceType::PointerReferenceType),
+ ref_type.unwrap_or(ReferenceType::PointerReferenceType),
))
}
}
@@ -1216,7 +1216,7 @@ impl fmt::Debug for Type {
for (i, line) in line_slice.iter().enumerate() {
if i > 0 {
- write!(f, "\n")?;
+ writeln!(f)?;
}
let tokens: &[BNInstructionTextToken] =
@@ -1245,6 +1245,12 @@ impl PartialEq for Type {
}
}
+impl Hash for Type {
+ fn hash<H: Hasher>(&self, state: &mut H) {
+ self.handle.hash(state);
+ }
+}
+
unsafe impl Send for Type {}
unsafe impl Sync for Type {}
@@ -1276,7 +1282,7 @@ pub struct FunctionParameter<S: BnStrCompatible> {
pub location: Option<Variable>,
}
-impl<'a, S: BnStrCompatible> FunctionParameter<S> {
+impl<S: BnStrCompatible> FunctionParameter<S> {
pub fn new<T: Into<Conf<Ref<Type>>>>(t: T, name: S, location: Option<Variable>) -> Self {
Self {
t: t.into(),
@@ -1305,7 +1311,7 @@ impl FunctionParameter<BnString> {
unsafe { Type::ref_from_raw(BNNewTypeReference(handle.type_)) },
handle.typeConfidence,
),
- name: name,
+ name,
location: if handle.defaultLocation {
None
} else {
@@ -1338,7 +1344,7 @@ impl Variable {
}
}
- pub(crate) fn into_raw(&self) -> BNVariable {
+ pub(crate) fn raw(&self) -> BNVariable {
BNVariable {
type_: self.t,
index: self.index,
@@ -1395,7 +1401,7 @@ impl EnumerationBuilder {
Enumeration::new(self)
}
- pub fn append<'a, S: BnStrCompatible>(&'a mut self, name: S) -> &'a mut Self {
+ pub fn append<S: BnStrCompatible>(&mut self, name: S) -> &mut Self {
let name = name.into_bytes_with_nul();
unsafe {
BNAddEnumerationBuilderMember(self.handle, name.as_ref().as_ptr() as _);
@@ -1403,7 +1409,7 @@ impl EnumerationBuilder {
self
}
- pub fn insert<'a, S: BnStrCompatible>(&'a mut self, name: S, value: u64) -> &'a mut Self {
+ pub fn insert<S: BnStrCompatible>(&mut self, name: S, value: u64) -> &mut Self {
let name = name.into_bytes_with_nul();
unsafe {
BNAddEnumerationBuilderMemberWithValue(self.handle, name.as_ref().as_ptr() as _, value);
@@ -1411,12 +1417,12 @@ impl EnumerationBuilder {
self
}
- pub fn replace<'a, S: BnStrCompatible>(
- &'a mut self,
+ pub fn replace<S: BnStrCompatible>(
+ &mut self,
id: usize,
name: S,
value: u64,
- ) -> &'a mut Self {
+ ) -> &mut Self {
let name = name.into_bytes_with_nul();
unsafe {
BNReplaceEnumerationBuilderMember(self.handle, id, name.as_ref().as_ptr() as _, value);
@@ -1424,7 +1430,7 @@ impl EnumerationBuilder {
self
}
- pub fn remove<'a>(&'a mut self, id: usize) -> &'a mut Self {
+ pub fn remove(&mut self, id: usize) -> &mut Self {
unsafe {
BNRemoveEnumerationBuilderMember(self.handle, id);
}
@@ -1450,6 +1456,12 @@ impl EnumerationBuilder {
}
}
+impl Default for EnumerationBuilder {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl From<&Enumeration> for EnumerationBuilder {
fn from(enumeration: &Enumeration) -> Self {
unsafe {
@@ -1586,7 +1598,7 @@ impl StructureBuilder {
// Chainable builders/setters
- pub fn set_width<'a>(&'a mut self, width: u64) -> &'a mut Self {
+ pub fn set_width(&mut self, width: u64) -> &mut Self {
unsafe {
BNSetStructureBuilderWidth(self.handle, width);
}
@@ -1594,7 +1606,7 @@ impl StructureBuilder {
self
}
- pub fn set_alignment<'a>(&'a mut self, alignment: usize) -> &'a mut Self {
+ pub fn set_alignment(&mut self, alignment: usize) -> &mut Self {
unsafe {
BNSetStructureBuilderAlignment(self.handle, alignment);
}
@@ -1602,7 +1614,7 @@ impl StructureBuilder {
self
}
- pub fn set_packed<'a>(&'a mut self, packed: bool) -> &'a mut Self {
+ pub fn set_packed(&mut self, packed: bool) -> &mut Self {
unsafe {
BNSetStructureBuilderPacked(self.handle, packed);
}
@@ -1673,7 +1685,7 @@ impl StructureBuilder {
self
}
- pub fn set_structure_type<'a>(&'a mut self, t: StructureType) -> &'a Self {
+ pub fn set_structure_type(&mut self, t: StructureType) -> &Self {
unsafe { BNSetStructureBuilderType(self.handle, t) };
self
}
@@ -1727,6 +1739,12 @@ impl Drop for StructureBuilder {
}
}
+impl Default for StructureBuilder {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
///////////////
// Structure
@@ -2103,7 +2121,7 @@ impl NameAndType<String> {
impl<S: BnStrCompatible> NameAndType<S> {
pub fn new(name: S, t: &Ref<Type>, confidence: u8) -> Self {
Self {
- name: name,
+ name,
t: Conf::new(t.clone(), confidence),
}
}