diff options
| author | Mason Reed <mason@vector35.com> | 2025-12-17 21:23:46 -0500 |
|---|---|---|
| committer | Mason Reed <35282038+emesare@users.noreply.github.com> | 2026-01-11 10:36:01 -0800 |
| commit | 168a3fd34824adc9c6a606cd144219701f15cccf (patch) | |
| tree | 9bbac31ece5ea6ab6627998d995a77f7f7e2f8e6 /plugins | |
| parent | ca91bc1933976c62d24248f0f7c35af38451ff11 (diff) | |
[Rust] Replace `log` with `tracing`
- Added more documentation
- Replaced global named logger for plugins, fixing the issue when the CU has multiple (e.g. statically linked demo)
- Simplified some misc code
This is a breaking change, but I believe there is no better time to make it, we cannot continue to use the `log` crate, it is too limited for our needs.
Diffstat (limited to 'plugins')
48 files changed, 320 insertions, 307 deletions
diff --git a/plugins/dwarf/dwarf_export/Cargo.toml b/plugins/dwarf/dwarf_export/Cargo.toml index 570626f6..81c8a017 100644 --- a/plugins/dwarf/dwarf_export/Cargo.toml +++ b/plugins/dwarf/dwarf_export/Cargo.toml @@ -11,5 +11,4 @@ crate-type = ["cdylib"] binaryninja.workspace = true binaryninjacore-sys.workspace = true gimli = "^0.31" -log = "0.4" object = { version = "0.32.1", features = ["write"] } diff --git a/plugins/dwarf/dwarf_export/src/lib.rs b/plugins/dwarf/dwarf_export/src/lib.rs index 333ce83b..bc7d3c27 100644 --- a/plugins/dwarf/dwarf_export/src/lib.rs +++ b/plugins/dwarf/dwarf_export/src/lib.rs @@ -1,13 +1,13 @@ mod edit_distance; use binaryninja::interaction::form::{Form, FormInputField}; -use binaryninja::logger::Logger; use binaryninja::{ binary_view::{BinaryView, BinaryViewBase, BinaryViewExt}, command::{register_command, Command}, confidence::Conf, rc::Ref, symbol::SymbolType, + tracing, types::{MemberAccess, StructureType, Type, TypeClass}, }; use gimli::{ @@ -17,7 +17,6 @@ use gimli::{ UnitEntryId, }, }; -use log::{error, info, warn, LevelFilter}; use object::{write, Architecture, BinaryFormat, SectionKind}; use std::fs; use std::path::{Path, PathBuf}; @@ -148,7 +147,10 @@ fn export_type( ); } None => { - log::warn!("Could not export base struct `{}`", base_struct.ty.name()); + tracing::warn!( + "Could not export base struct `{}`", + base_struct.ty.name() + ); } } } @@ -374,7 +376,7 @@ fn export_type( Some(typedef_die_uid) } } else { - warn!("Could not get target of typedef `{}`", ntr.name()); + tracing::warn!("Could not get target of typedef `{}`", ntr.name()); None } } @@ -703,12 +705,12 @@ fn write_dwarf<T: gimli::Endianity>( if let Ok(out_data) = out_object.write() { if let Err(err) = fs::write(file_path, out_data) { - error!("Failed to write DWARF file: {}", err); + tracing::error!("Failed to write DWARF file: {}", err); } else { - info!("Successfully saved as DWARF to `{:?}`", file_path); + tracing::info!("Successfully saved as DWARF to `{:?}`", file_path); } } else { - error!("Failed to write DWARF with requested settings"); + tracing::error!("Failed to write DWARF with requested settings"); } Ok(()) @@ -785,7 +787,7 @@ fn export_dwarf(bv: &BinaryView) { }; if let Err(e) = write_dwarf(&save_loc_path, arch, endianness, &mut dwarf) { - error!("Error writing DWARF: {}", e); + tracing::error!("Error writing DWARF: {}", e); } } @@ -802,9 +804,7 @@ impl Command for MyCommand { #[no_mangle] pub extern "C" fn CorePluginInit() -> bool { - Logger::new("DWARF Export") - .with_level(LevelFilter::Debug) - .init(); + binaryninja::tracing_init!("DWARF Export"); register_command( "Export as DWARF", diff --git a/plugins/dwarf/dwarf_import/Cargo.toml b/plugins/dwarf/dwarf_import/Cargo.toml index 15f3fda8..f71d4cf4 100644 --- a/plugins/dwarf/dwarf_import/Cargo.toml +++ b/plugins/dwarf/dwarf_import/Cargo.toml @@ -15,7 +15,6 @@ dwarfreader = { path = "../shared/" } binaryninja.workspace = true binaryninjacore-sys.workspace = true gimli = "0.31" -log = "0.4" iset = "0.2.2" cpp_demangle = "0.4.3" regex = "1" diff --git a/plugins/dwarf/dwarf_import/demo/Cargo.toml b/plugins/dwarf/dwarf_import/demo/Cargo.toml index e088fb68..3a5ad601 100644 --- a/plugins/dwarf/dwarf_import/demo/Cargo.toml +++ b/plugins/dwarf/dwarf_import/demo/Cargo.toml @@ -16,7 +16,6 @@ dwarfreader = { path = "../../shared/" } binaryninja = { workspace = true, features = ["demo"]} binaryninjacore-sys.workspace = true gimli = "0.31" -log = "0.4" iset = "0.2.2" cpp_demangle = "0.4.3" regex = "1" diff --git a/plugins/dwarf/dwarf_import/src/die_handlers.rs b/plugins/dwarf/dwarf_import/src/die_handlers.rs index fed3a1da..b4b526a0 100644 --- a/plugins/dwarf/dwarf_import/src/die_handlers.rs +++ b/plugins/dwarf/dwarf_import/src/die_handlers.rs @@ -18,6 +18,7 @@ use crate::{helpers::*, ReaderType}; use binaryninja::{ rc::*, + tracing, types::{EnumerationBuilder, FunctionParameter, ReferenceType, Type, TypeBuilder}, }; @@ -109,7 +110,7 @@ pub(crate) fn handle_enum<R: ReaderType>( let mut tree = match unit.entries_tree(Some(entry.offset())) { Ok(x) => x, Err(e) => { - log::error!("Failed to get enum entry tree: {}", e); + tracing::error!("Failed to get enum entry tree: {}", e); return None; } }; @@ -117,7 +118,7 @@ pub(crate) fn handle_enum<R: ReaderType>( let tree_root = match tree.root() { Ok(x) => x, Err(e) => { - log::error!("Failed to get enum entry tree root: {}", e); + tracing::error!("Failed to get enum entry tree root: {}", e); return None; } }; @@ -132,15 +133,15 @@ pub(crate) fn handle_enum<R: ReaderType>( enumeration_builder.insert(&name, value); } else { // Somehow the child entry is not a const value. - log::error!("Unhandled enum member value type for `{}`", name); + tracing::error!("Unhandled enum member value type for `{}`", name); } } Ok(None) => { // Somehow the child entry does not have a const value. - log::error!("Enum member `{}` has no constant value attribute", name); + tracing::error!("Enum member `{}` has no constant value attribute", name); } Err(e) => { - log::error!("Error parsing next attribute entry for `{}`: {}", name, e); + tracing::error!("Error parsing next attribute entry for `{}`: {}", name, e); return None; } } @@ -208,7 +209,7 @@ pub(crate) fn handle_pointer<R: ReaderType>( Some(entry_type_offset) => { let debug_target_type = debug_info_builder.get_type(entry_type_offset).or_else(|| { - log::error!( + tracing::error!( "Failed to get pointer target type at entry offset {}", entry_type_offset ); @@ -255,7 +256,7 @@ pub(crate) fn handle_array<R: ReaderType>( let parent_type = debug_info_builder .get_type(entry_type_offset) .or_else(|| { - log::error!( + tracing::error!( "Failed to get array member type at entry offset {}", entry_type_offset ); @@ -266,14 +267,14 @@ pub(crate) fn handle_array<R: ReaderType>( let mut tree = match unit.entries_tree(Some(entry.offset())) { Ok(x) => x, Err(e) => { - log::error!("Failed to get array entry tree: {}", e); + tracing::error!("Failed to get array entry tree: {}", e); return None; } }; let tree_root = match tree.root() { Ok(x) => x, Err(e) => { - log::error!("Failed to get array entry tree root: {}", e); + tracing::error!("Failed to get array entry tree root: {}", e); return None; } }; @@ -351,7 +352,7 @@ pub(crate) fn handle_function<R: ReaderType>( let mut tree = match unit.entries_tree(Some(entry.offset())) { Ok(x) => x, Err(e) => { - log::error!("Failed to get function entry tree: {}", e); + tracing::error!("Failed to get function entry tree: {}", e); return None; } }; @@ -359,7 +360,7 @@ pub(crate) fn handle_function<R: ReaderType>( let tree_root = match tree.root() { Ok(x) => x, Err(e) => { - log::error!("Failed to get function entry tree root: {}", e); + tracing::error!("Failed to get function entry tree root: {}", e); return None; } }; @@ -374,7 +375,7 @@ pub(crate) fn handle_function<R: ReaderType>( debug_info_builder_context, debug_info_builder, ) else { - log::error!( + tracing::error!( "Failed to get function parameter child type in unit {:?} at offset {:x}", unit.header.offset(), child.entry().offset().0, @@ -384,7 +385,7 @@ pub(crate) fn handle_function<R: ReaderType>( let name = debug_info_builder_context.get_name(dwarf, unit, child.entry()); let child_debug_type = debug_info_builder.get_type(child_uid).or_else(|| { - log::error!( + tracing::error!( "Failed to get function parameter type with uid {}", child_uid ); @@ -439,7 +440,7 @@ pub(crate) fn handle_const( Some(entry_type_offset) => debug_info_builder .get_type(entry_type_offset) .or_else(|| { - log::error!( + tracing::error!( "Failed to get const type with entry offset {}", entry_type_offset ); @@ -469,7 +470,7 @@ pub(crate) fn handle_volatile( Some(entry_type_offset) => debug_info_builder .get_type(entry_type_offset) .or_else(|| { - log::error!( + tracing::error!( "Failed to get volatile type with entry offset {}", entry_type_offset ); diff --git a/plugins/dwarf/dwarf_import/src/dwarfdebuginfo.rs b/plugins/dwarf/dwarf_import/src/dwarfdebuginfo.rs index 497e6c9c..397e07a3 100644 --- a/plugins/dwarf/dwarf_import/src/dwarfdebuginfo.rs +++ b/plugins/dwarf/dwarf_import/src/dwarfdebuginfo.rs @@ -25,6 +25,7 @@ use binaryninja::{ rc::*, symbol::SymbolType, template_simplifier::simplify_str_to_fqn, + tracing, types::{FunctionParameter, Type}, variable::NamedVariableWithType, }; @@ -34,7 +35,6 @@ use gimli::{DebuggingInformationEntry, Dwarf, Unit}; use binaryninja::confidence::Conf; use binaryninja::variable::{Variable, VariableSourceType}; use indexmap::{map::Values, IndexMap}; -use log::{debug, error, warn}; use std::{cmp::Ordering, collections::HashMap, hash::Hash}; pub(crate) type TypeUID = usize; @@ -133,7 +133,7 @@ impl<R: ReaderType> DebugInfoBuilderContext<R> { if let Ok(unit) = dwarf.unit(header) { units.push(unit); } else { - error!("Unable to read DWARF information. File may be malformed or corrupted. Not applying debug info."); + tracing::error!("Unable to read DWARF information. File may be malformed or corrupted. Not applying debug info."); return None; } } @@ -145,7 +145,7 @@ impl<R: ReaderType> DebugInfoBuilderContext<R> { if let Ok(unit) = sup_dwarf.unit(header) { sup_units.push(unit); } else { - error!("Unable to read supplementary DWARF information. File may be malformed or corrupted. Not applying debug info."); + tracing::error!("Unable to read supplementary DWARF information. File may be malformed or corrupted. Not applying debug info."); return None; } } @@ -193,7 +193,7 @@ impl<R: ReaderType> DebugInfoBuilderContext<R> { match &entry_unit.entry(entry_offset) { Ok(x) => x, Err(e) => { - log::error!( + tracing::error!( "Failed to get entry {:?} in unit {:?}: {}", entry_offset, entry_unit.header.offset(), @@ -265,7 +265,7 @@ impl DebugInfoBuilder { // if the full name exists, update the stored index for the full name if let Some(idx) = self.raw_function_name_indices.get(ident) { let function = self.functions.get_mut(*idx).or_else(|| { - log::error!("Failed to get function with index {}", idx); + tracing::error!("Failed to get function with index {}", idx); None })?; @@ -298,7 +298,7 @@ impl DebugInfoBuilder { // if the raw name exists, update the stored index for the raw name if let Some(idx) = self.full_function_name_indices.get(ident) { let function = self.functions.get_mut(*idx).or_else(|| { - log::error!("Failed to get function with index {}", idx); + tracing::error!("Failed to get function with index {}", idx); None })?; @@ -325,7 +325,7 @@ impl DebugInfoBuilder { return Some(*idx); } } else { - debug!("Function entry in DWARF without full or raw name."); + tracing::debug!("Function entry in DWARF without full or raw name."); return None; } @@ -387,7 +387,7 @@ impl DebugInfoBuilder { }, ) { if existing_type != t && commit { - warn!("DWARF info contains duplicate type definition. Overwriting type `{}` (named `{:?}`) with `{}` (named `{:?}`)", + tracing::warn!("DWARF info contains duplicate type definition. Overwriting type `{}` (named `{:?}`) with `{}` (named `{:?}`)", existing_type, existing_name, t, @@ -434,7 +434,7 @@ impl DebugInfoBuilder { let Some(function_index) = fn_idx else { // If we somehow lost track of what subprogram we're in or we're not actually in a subprogram - error!( + tracing::error!( "Trying to add a local variable outside of a subprogram. Please report this issue." ); return; @@ -452,12 +452,12 @@ impl DebugInfoBuilder { let Some(func_addr) = function.address else { // If we somehow are processing a function's variables before the function is created - error!("Trying to add a local variable without a known function start. Please report this issue."); + tracing::error!("Trying to add a local variable without a known function start. Please report this issue."); return; }; let Some(frame_base) = &function.frame_base else { - error!("Trying to add a local variable ({}) to a function ({:#x}) without a frame base. Please report this issue.", name, func_addr); + tracing::error!("Trying to add a local variable ({}) to a function ({:#x}) without a frame base. Please report this issue.", name, func_addr); return; }; @@ -480,7 +480,7 @@ impl DebugInfoBuilder { .cloned() else { // Unknown why, but this is happening with MachO + external dSYM - debug!("Refusing to add a local variable ({}@{}) to function at {} without a known CFA adjustment.", name, offset, func_addr); + tracing::debug!("Refusing to add a local variable ({}@{}) to function at {} without a known CFA adjustment.", name, offset, func_addr); return; }; @@ -510,7 +510,7 @@ impl DebugInfoBuilder { if adjusted_offset > 0 { // If we somehow end up with a positive sp offset - error!("Trying to add a local variable \"{}\" in function at {:#x} at positive storage offset {}. Please report this issue.", name, func_addr, adjusted_offset); + tracing::error!("Trying to add a local variable \"{}\" in function at {:#x} at positive storage offset {}. Please report this issue.", name, func_addr, adjusted_offset); return; } @@ -536,7 +536,7 @@ impl DebugInfoBuilder { let existing_type = match self.get_type(existing_type_uid) { Some(x) => x.ty.as_ref(), None => { - log::error!( + tracing::error!( "Failed to find existing type with uid {} for data variable at {:#x}", existing_type_uid, address @@ -548,7 +548,7 @@ impl DebugInfoBuilder { let new_type = match self.get_type(type_uid) { Some(x) => x.ty.as_ref(), None => { - log::error!( + tracing::error!( "Failed to find new type with uid {} for data variable at {:#x}", type_uid, address @@ -558,7 +558,7 @@ impl DebugInfoBuilder { }; if existing_type_uid != type_uid || existing_type != new_type { - warn!("DWARF info contains duplicate data variable definition. Overwriting data variable at {:#08x} (`{}`) with `{}`", + tracing::warn!("DWARF info contains duplicate data variable definition. Overwriting data variable at {:#08x} (`{}`) with `{}`", address, existing_type, new_type @@ -580,7 +580,7 @@ impl DebugInfoBuilder { // Prevent storing two types with the same name and differing definitions if let Some(stored_uid) = type_uids_by_name.get(&debug_type_name) { let Some(stored_debug_type) = self.types.get(stored_uid) else { - error!("Stored type name without storing a type! Please report this error. UID: {}, name: {}", stored_uid, debug_type_name); + tracing::error!("Stored type name without storing a type! Please report this error. UID: {}, name: {}", stored_uid, debug_type_name); continue; }; @@ -624,14 +624,14 @@ impl DebugInfoBuilder { if let Some(target_type) = self.get_type(target_uid) { debug_info.add_type(&debug_type_name, &target_type.get_type(), &[]); } else { - error!( + tracing::error!( "Failed to find typedef {} target for uid {}", debug_type_name, ntr.name() ); } } else { - error!( + tracing::error!( "Failed to find typedef {} target uid for {}", debug_type_name, ntr.name() @@ -650,7 +650,7 @@ impl DebugInfoBuilder { let data_var_type = match self.get_type(*type_uid) { Some(x) => &x.ty, None => { - log::error!("Failed to find type for data variable at {:#x}", address); + tracing::error!("Failed to find type for data variable at {:#x}", address); continue; } }; @@ -752,7 +752,7 @@ impl DebugInfoBuilder { let existing_functions = bv.functions_at(*address); 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."); + tracing::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()) diff --git a/plugins/dwarf/dwarf_import/src/functions.rs b/plugins/dwarf/dwarf_import/src/functions.rs index adc74c41..709cea62 100644 --- a/plugins/dwarf/dwarf_import/src/functions.rs +++ b/plugins/dwarf/dwarf_import/src/functions.rs @@ -19,9 +19,9 @@ use crate::types::get_type; use crate::{helpers::*, ReaderType}; use binaryninja::template_simplifier::simplify_str_to_str; +use binaryninja::tracing; use cpp_demangle::DemangleOptions; use gimli::{constants, AttributeValue, DebuggingInformationEntry, Dwarf, Operation, Unit}; -use log::{debug, error}; use regex::Regex; #[derive(PartialEq, Eq, Hash)] @@ -45,14 +45,14 @@ fn get_parameters<R: ReaderType>( let mut sub_die_tree = match unit.entries_tree(Some(entry.offset())) { Ok(x) => x, Err(e) => { - log::error!("Failed to get function parameter entry tree: {}", e); + tracing::error!("Failed to get function parameter entry tree: {}", e); return (vec![], false); } }; let root = match sub_die_tree.root() { Ok(x) => x, Err(e) => { - log::error!("Failed to get function parameter entry tree root: {}", e); + tracing::error!("Failed to get function parameter entry tree root: {}", e); return (vec![], false); } }; @@ -148,7 +148,7 @@ pub(crate) fn parse_function_entry<R: ReaderType>( } if raw_name.is_none() && full_name.is_none() { - debug!( + tracing::debug!( "Function entry in DWARF without full or raw name: .debug_info offset {:?}", entry.offset().to_debug_info_offset(&unit.header) ); @@ -203,13 +203,13 @@ pub(crate) fn parse_lexical_block<R: ReaderType>( let unit_base = match unit.header.offset().as_debug_info_offset() { Some(x) => x.0, None => { - log::warn!("Unable to get unit offset in debug info: {:?}. This may be an indicator of parsing issues.", unit.header.offset()); + tracing::warn!("Unable to get unit offset in debug info: {:?}. This may be an indicator of parsing issues.", unit.header.offset()); 0 } }; let Ok(Some(low_pc)) = dwarf.attr_address(unit, low_pc_value.clone()) else { - error!( + tracing::error!( "Failed to read lexical block low_pc for entry {:#x}, please report this bug.", unit_base + entry.offset().0 ); @@ -217,7 +217,7 @@ pub(crate) fn parse_lexical_block<R: ReaderType>( }; let Ok(Some(high_pc_value)) = entry.attr_value(constants::DW_AT_high_pc) else { - error!("Failed to read lexical block high_pc attribute for entry {:#x}, please report this bug.", unit_base + entry.offset().0); + tracing::error!("Failed to read lexical block high_pc attribute for entry {:#x}, please report this bug.", unit_base + entry.offset().0); return None; }; @@ -226,7 +226,7 @@ pub(crate) fn parse_lexical_block<R: ReaderType>( .and_then(|x| Some(low_pc + x)) .or_else(|| dwarf.attr_address(unit, high_pc_value).unwrap_or(None)) else { - error!( + tracing::error!( "Failed to read lexical block high_pc for entry {:#x}, please report this bug.", unit_base + entry.offset().0 ); @@ -244,9 +244,10 @@ pub(crate) fn parse_lexical_block<R: ReaderType>( // Ranges where start == end may be ignored (DWARFv5 spec, 2.17.3 line 17) return None; } else { - error!( + tracing::error!( "Invalid lexical block range: {:#x} -> {:#x}", - low_pc, high_pc + low_pc, + high_pc ); } } else { diff --git a/plugins/dwarf/dwarf_import/src/helpers.rs b/plugins/dwarf/dwarf_import/src/helpers.rs index aca614ab..d2654d98 100644 --- a/plugins/dwarf/dwarf_import/src/helpers.rs +++ b/plugins/dwarf/dwarf_import/src/helpers.rs @@ -18,12 +18,12 @@ use std::{str::FromStr, sync::mpsc}; use crate::{DebugInfoBuilderContext, ReaderType}; use binaryninja::binary_view::BinaryViewBase; -use binaryninja::Endianness; use binaryninja::{ binary_view::{BinaryView, BinaryViewExt}, download::{DownloadInstanceInputOutputCallbacks, DownloadProvider}, settings::Settings, }; +use binaryninja::{tracing, Endianness}; use gimli::Dwarf; use gimli::{ constants, Attribute, AttributeValue, @@ -32,7 +32,6 @@ use gimli::{ }; use binaryninja::settings::QueryOptions; -use log::warn; pub(crate) fn get_uid<R: ReaderType>( dwarf: &Dwarf<R>, @@ -111,14 +110,16 @@ pub(crate) fn get_attr_die<'a, R: ReaderType>( let sup: &Dwarf<R> = match dwarf.sup() { Some(x) => x, None => { - log::error!("Trying to get offset in supplmentary dwarf info, but none is present"); + tracing::error!("Trying to get offset in supplmentary dwarf info, but none is present"); return None; } }; return Some(DieReference::UnitAndOffset((sup, source_unit, new_offset))); } } - warn!("Failed to fetch DIE. Supplementary debug information may be incomplete."); + tracing::warn!( + "Failed to fetch DIE. Supplementary debug information may be incomplete." + ); None } _ => None, @@ -143,7 +144,7 @@ pub(crate) fn resolve_specification<'a, R: ReaderType>( if let Ok(entry) = entry_unit.entry(entry_offset) { resolve_specification(dwarf, entry_unit, &entry, debug_info_builder_context) } else { - warn!("Failed to fetch DIE for attr DW_AT_specification. Debug information may be incomplete."); + tracing::warn!("Failed to fetch DIE for attr DW_AT_specification. Debug information may be incomplete."); DieReference::Err } } @@ -161,12 +162,12 @@ pub(crate) fn resolve_specification<'a, R: ReaderType>( if entry_offset == entry.offset() && unit.header.offset() == entry_unit.header.offset() { - warn!("DWARF information is invalid (infinite abstract origin reference cycle). Debug information may be incomplete."); + tracing::warn!("DWARF information is invalid (infinite abstract origin reference cycle). Debug information may be incomplete."); DieReference::Err } else if let Ok(new_entry) = entry_unit.entry(entry_offset) { resolve_specification(dwarf, entry_unit, &new_entry, debug_info_builder_context) } else { - warn!("Failed to fetch DIE for attr DW_AT_abstract_origin. Debug information may be incomplete."); + tracing::warn!("Failed to fetch DIE for attr DW_AT_abstract_origin. Debug information may be incomplete."); DieReference::Err } } @@ -189,7 +190,7 @@ pub(crate) fn get_name<R: ReaderType>( let resolved_entry = match entry_unit.entry(entry_offset) { Ok(x) => x, Err(_) => { - log::error!( + tracing::error!( "Failed to get entry in unit at {:?} at offset {:#x} (get_name)", entry_unit.header.offset(), entry_offset.0 @@ -236,7 +237,7 @@ pub(crate) fn get_raw_name<R: ReaderType>( let resolved_entry = match entry_unit.entry(entry_offset) { Ok(x) => x, Err(_) => { - log::error!( + tracing::error!( "Failed to get entry in unit at {:?} at offset {:#x} (get_raw_name)", entry_unit.header.offset(), entry_offset.0 diff --git a/plugins/dwarf/dwarf_import/src/lib.rs b/plugins/dwarf/dwarf_import/src/lib.rs index f192f9d1..e227a459 100644 --- a/plugins/dwarf/dwarf_import/src/lib.rs +++ b/plugins/dwarf/dwarf_import/src/lib.rs @@ -34,6 +34,7 @@ use binaryninja::{ debuginfo::{CustomDebugInfoParser, DebugInfo, DebugInfoParser}, settings::Settings, template_simplifier::simplify_str_to_str, + tracing, }; use dwarfreader::create_section_reader_object; @@ -43,10 +44,8 @@ use gimli::{ SectionId, Unit, UnwindContext, UnwindSection, }; -use binaryninja::logger::Logger; use helpers::{get_build_id, load_debug_info_for_build_id}; use iset::IntervalMap; -use log::{debug, error, warn}; use object::read::macho::FatArch; use object::{Object, ObjectSection}; @@ -126,7 +125,7 @@ fn recover_names_internal<R: ReaderType>( while let Ok(Some(header)) = iter.next() { let unit_offset = header.offset().as_debug_info_offset().map_or_else( || { - log::warn!("Failed to get debug info offset for {:?}", header.offset()); + tracing::warn!("Failed to get debug info offset for {:?}", header.offset()); 0 }, |x| x.0, @@ -134,7 +133,7 @@ fn recover_names_internal<R: ReaderType>( let unit = match dwarf.unit(header) { Ok(x) => x, Err(e) => { - log::error!("Failed to get unit at {:#x}: {}", unit_offset, e); + tracing::error!("Failed to get unit at {:#x}: {}", unit_offset, e); continue; } }; @@ -163,7 +162,7 @@ fn recover_names_internal<R: ReaderType>( depth += delta_depth; if depth < 0 { - error!("DWARF information is seriously malformed. Aborting parsing."); + tracing::error!("DWARF information is seriously malformed. Aborting parsing."); return false; } @@ -196,7 +195,7 @@ fn recover_names_internal<R: ReaderType>( let resolved_entry = match entry_unit.entry(entry_offset) { Ok(x) => x, Err(e) => { - log::error!("Failed to resolve entry in unit {:?} at offset {:#x} (resolve_namespace_name): {}", entry_unit.header.offset(), entry_offset.0, e); + tracing::error!("Failed to resolve entry in unit {:?} at offset {:#x} (resolve_namespace_name): {}", entry_unit.header.offset(), entry_offset.0, e); return; } }; @@ -210,7 +209,7 @@ fn recover_names_internal<R: ReaderType>( ) } DieReference::Err => { - warn!( + tracing::warn!( "Failed to fetch DIE when resolving namespace. Debug information may be incomplete." ); } @@ -436,7 +435,7 @@ where }) { Ok(fde) => fde, Err(e) => { - error!("Failed to parse FDE: {}", e); + tracing::error!("Failed to parse FDE: {}", e); continue; } }; @@ -447,7 +446,7 @@ where } if fde.initial_address().overflowing_add(fde.len()).1 { - warn!( + tracing::warn!( "FDE at offset {:?} exceeds bounds of memory space! {:#x} + length {:#x}", fde.offset(), fde.initial_address(), @@ -481,7 +480,7 @@ where cfa_offsets .insert(row.start_address()..row.end_address(), *offset); } else { - debug!( + tracing::debug!( "Invalid FDE table row addresses: {:#x}..{:#x}", row.start_address(), row.end_address() @@ -489,7 +488,7 @@ where } } CfaRule::Expression(_) => { - debug!("Unhandled CFA expression when determining offset"); + tracing::debug!("Unhandled CFA expression when determining offset"); } }; } @@ -548,7 +547,7 @@ fn parse_dwarf( progress: Box<dyn Fn(usize, usize) -> Result<(), ()>>, ) -> Result<DebugInfoBuilder, String> { if debug_file.section_by_name(".gnu_debugaltlink").is_some() && supplementary_data.is_none() { - log::warn!(".gnu_debugaltlink section present but no supplementary data provided. DWARF parsing may fail.") + tracing::warn!(".gnu_debugaltlink section present but no supplementary data provided. DWARF parsing may fail.") } let address_size = match debug_file.architecture().address_size() { @@ -588,7 +587,7 @@ fn parse_dwarf( create_section_reader_object(section_id, &sup_file, sup_endian, sup_dwo_file) }; if let Err(e) = dwarf.load_sup(sup_section_reader) { - error!("Failed to load supplementary file: {}", e); + tracing::error!("Failed to load supplementary file: {}", e); } } @@ -620,7 +619,7 @@ fn parse_dwarf( let sup = match dwarf.sup() { Some(x) => x, None => { - log::error!( + tracing::error!( "Supplemental units found but no supplementary DWARF info available" ); break; @@ -743,7 +742,7 @@ impl CustomDebugInfoParser for DWARFParser { match helpers::load_sibling_debug_file(bv) { Ok(x) => x, Err(e) => { - log::error!("Failed loading sibling debug file: {}", e); + tracing::error!("Failed loading sibling debug file: {}", e); None } } @@ -754,7 +753,7 @@ impl CustomDebugInfoParser for DWARFParser { match load_debug_info_for_build_id(&build_id, bv) { Ok(x) => x, Err(e) => { - log::error!("Failed loading debug info from build id: {}", e); + tracing::error!("Failed loading debug info from build id: {}", e); None } } @@ -771,7 +770,7 @@ impl CustomDebugInfoParser for DWARFParser { let debug_file = match parse_data_to_object(debug_data_vec.as_slice(), bv) { Ok(x) => x, Err(e) => { - log::error!("Failed to parse debug data: {}", e); + tracing::error!("Failed to parse debug data: {}", e); return false; } }; @@ -784,7 +783,7 @@ impl CustomDebugInfoParser for DWARFParser { let sup_data = match load_debug_info_for_build_id(sup_build_id, bv) { Ok(x) => x, Err(e) => { - log::error!("Failed to load supplementary debug file: {}", e); + tracing::error!("Failed to load supplementary debug file: {}", e); None } }; @@ -795,13 +794,13 @@ impl CustomDebugInfoParser for DWARFParser { |sup_file_path| match std::fs::read(sup_file_path) { Ok(sup_data) => Some(sup_data), Err(e) => { - log::error!("Failed reading supplementary file {}: {}", x, e); + tracing::error!("Failed reading supplementary file {}: {}", x, e); None } }, ), Err(e) => { - log::error!("Supplementary file path is invalid utf8: {}", e); + tracing::error!("Supplementary file path is invalid utf8: {}", e); None } }) @@ -812,7 +811,7 @@ impl CustomDebugInfoParser for DWARFParser { match parse_data_to_object(data.as_slice(), bv) { Ok(x) => Some(x), Err(e) => { - log::error!("Failed to parse supplementary debug data: {}", e); + tracing::error!("Failed to parse supplementary debug data: {}", e); None } } @@ -823,7 +822,7 @@ impl CustomDebugInfoParser for DWARFParser { if let Ok(Some((_, expected_build_id))) = debug_file.gnu_debugaltlink() { if let Ok(Some(loaded_sup_build_id)) = sup_file.build_id() { if loaded_sup_build_id != expected_build_id { - log::warn!( + tracing::warn!( "Supplementary debug info build id ({}) does not match expected ({})", loaded_sup_build_id .iter() @@ -845,7 +844,7 @@ impl CustomDebugInfoParser for DWARFParser { true } Err(e) => { - log::error!("Failed to parse DWARF: {}", e); + tracing::error!("Failed to parse DWARF: {}", e); false } }; @@ -855,7 +854,7 @@ impl CustomDebugInfoParser for DWARFParser { } fn plugin_init() { - Logger::new("DWARF").init(); + binaryninja::tracing_init!("DWARF Import"); let settings = Settings::new(); diff --git a/plugins/dwarf/dwarf_import/src/types.rs b/plugins/dwarf/dwarf_import/src/types.rs index 7f9e4e5d..45ccf74e 100644 --- a/plugins/dwarf/dwarf_import/src/types.rs +++ b/plugins/dwarf/dwarf_import/src/types.rs @@ -18,6 +18,7 @@ use crate::{die_handlers::*, ReaderType}; use binaryninja::{ rc::*, + tracing, types::{ BaseStructure, MemberAccess, MemberScope, ReferenceType, StructureBuilder, StructureType, Type, TypeClass, @@ -26,8 +27,6 @@ use binaryninja::{ use gimli::{constants, AttributeValue, DebuggingInformationEntry, DwAt, Dwarf, Operation, Unit}; -use log::{debug, error, warn}; - pub(crate) fn parse_variable<R: ReaderType>( dwarf: &Dwarf<R>, unit: &Unit<R>, @@ -79,7 +78,7 @@ pub(crate) fn parse_variable<R: ReaderType>( if let Ok(address) = dwarf.address(unit, index) { debug_info_builder.add_data_variable(address, full_name, uid) } else { - warn!("Invalid index into IAT: {}", index.0); + tracing::warn!("Invalid index into IAT: {}", index.0); } } } @@ -96,11 +95,12 @@ pub(crate) fn parse_variable<R: ReaderType>( ); } Ok(op) => { - debug!("Unhandled operation type for variable: {:?}", op); + tracing::debug!("Unhandled operation type for variable: {:?}", op); } - Err(e) => error!( + Err(e) => tracing::error!( "Error parsing operation type for variable {:?}: {}", - full_name, e + full_name, + e ), } } @@ -191,14 +191,14 @@ fn do_structure_parse<R: ReaderType>( let mut tree = match unit.entries_tree(Some(entry.offset())) { Ok(x) => x, Err(e) => { - log::error!("Failed to get structure entry tree: {}", e); + tracing::error!("Failed to get structure entry tree: {}", e); return None; } }; let tree_root = match tree.root() { Ok(x) => x, Err(e) => { - log::error!("Failed to get structure entry tree root: {}", e); + tracing::error!("Failed to get structure entry tree root: {}", e); return None; } }; @@ -238,7 +238,7 @@ fn do_structure_parse<R: ReaderType>( let Some(struct_offset_bytes) = get_attr_as_u64(&raw_struct_offset) .or_else(|| get_expr_value(unit, raw_struct_offset)) else { - log::warn!( + tracing::warn!( "Failed to get DW_AT_data_member_location for offset {:#x} in unit {:?}", child_entry.offset().0, unit.header.offset() @@ -323,7 +323,7 @@ fn do_structure_parse<R: ReaderType>( debug_info_builder_context, debug_info_builder, ) else { - warn!("Failed to get base type for inheritance"); + tracing::warn!("Failed to get base type for inheritance"); continue; }; let Some(base_dbg_ty) = debug_info_builder.get_type(base_type_id) else { @@ -334,7 +334,7 @@ fn do_structure_parse<R: ReaderType>( let Ok(Some(raw_data_member_location)) = child_entry.attr(constants::DW_AT_data_member_location) else { - warn!("Failed to get DW_AT_data_member_location for inheritance"); + tracing::warn!("Failed to get DW_AT_data_member_location for inheritance"); continue; }; @@ -405,7 +405,7 @@ pub(crate) fn get_type<R: ReaderType>( let resolved_entry = match entry_unit.entry(entry_offset) { Ok(x) => x, Err(e) => { - log::error!( + tracing::error!( "Failed to resolve entry in unit {:?} at offset {:#x}: {}", entry_unit.header.offset(), entry_offset.0, @@ -423,7 +423,7 @@ pub(crate) fn get_type<R: ReaderType>( ) } DieReference::Err => { - warn!("Failed to fetch DIE when getting type through DW_AT_type. Debug information may be incomplete."); + tracing::warn!("Failed to fetch DIE when getting type through DW_AT_type. Debug information may be incomplete."); None } } @@ -440,7 +440,7 @@ pub(crate) fn get_type<R: ReaderType>( let resolved_entry = match entry_unit.entry(entry_offset) { Ok(x) => x, Err(e) => { - log::error!( + tracing::error!( "Failed to resolve entry in unit {:?} at offset {:#x}: {}", entry_unit.header.offset(), entry_offset.0, @@ -458,7 +458,7 @@ pub(crate) fn get_type<R: ReaderType>( ) } DieReference::Err => { - warn!("Failed to fetch DIE when getting type through DW_AT_abstract_origin. Debug information may be incomplete."); + tracing::warn!("Failed to fetch DIE when getting type through DW_AT_abstract_origin. Debug information may be incomplete."); None } } @@ -472,7 +472,7 @@ pub(crate) fn get_type<R: ReaderType>( let resolved_entry = match entry_unit.entry(entry_offset) { Ok(x) => x, Err(e) => { - log::error!( + tracing::error!( "Failed to resolve entry in unit {:?} at offset {:#x}: {}", entry_unit.header.offset(), entry_offset.0, @@ -491,7 +491,7 @@ pub(crate) fn get_type<R: ReaderType>( } DieReference::UnitAndOffset(_) => None, DieReference::Err => { - warn!( + tracing::warn!( "Failed to fetch DIE when getting type. Debug information may be incomplete." ); None diff --git a/plugins/idb_import/Cargo.toml b/plugins/idb_import/Cargo.toml index cad56142..4a958106 100644 --- a/plugins/idb_import/Cargo.toml +++ b/plugins/idb_import/Cargo.toml @@ -13,4 +13,3 @@ anyhow = { version = "1.0.86", features = ["backtrace"] } binaryninja.workspace = true binaryninjacore-sys.workspace = true idb-rs = { git = "https://github.com/Vector35/idb-rs", tag = "0.1.12" } -log = "0.4" diff --git a/plugins/idb_import/src/lib.rs b/plugins/idb_import/src/lib.rs index b1643ea3..3564df11 100644 --- a/plugins/idb_import/src/lib.rs +++ b/plugins/idb_import/src/lib.rs @@ -18,10 +18,8 @@ use idb_rs::id0::{ID0Section, ID0SectionVariants}; use idb_rs::til::section::TILSection; use idb_rs::til::TypeVariant as TILTypeVariant; -use log::{error, trace, warn, LevelFilter}; - use anyhow::{anyhow, Result}; -use binaryninja::logger::Logger; +use binaryninja::tracing; struct IDBDebugInfoParser; impl CustomDebugInfoParser for IDBDebugInfoParser { @@ -45,7 +43,7 @@ impl CustomDebugInfoParser for IDBDebugInfoParser { match parse_idb_info(debug_info, bv, debug_file, progress) { Ok(()) => true, Err(error) => { - error!("Unable to parse IDB file: {error}"); + tracing::error!("Unable to parse IDB file: {error}"); false } } @@ -72,7 +70,7 @@ impl CustomDebugInfoParser for TILDebugInfoParser { match parse_til_info(debug_info, debug_file, progress) { Ok(()) => true, Err(error) => { - error!("Unable to parse TIL file: {error}"); + tracing::error!("Unable to parse TIL file: {error}"); false } } @@ -126,12 +124,12 @@ fn parse_idb_info( debug_file: &BinaryView, progress: Box<dyn Fn(usize, usize) -> Result<(), ()>>, ) -> Result<()> { - trace!("Opening a IDB file"); + tracing::trace!("Opening a IDB file"); let file = BinaryViewReader { bv: debug_file, offset: 0, }; - trace!("Parsing a IDB file"); + tracing::trace!("Parsing a IDB file"); let mut file = std::io::BufReader::new(file); let idb_kind = idb_rs::identify_idb_file(&mut file)?; match idb_kind { @@ -173,7 +171,7 @@ fn parse_idb_info_format( let id2_idx = format.id2_location(); if let Some(til_idx) = format.til_location() { - trace!("Parsing the TIL section"); + tracing::trace!("Parsing the TIL section"); let til = format.read_til(&mut idb_data, til_idx)?; // progress 0%-50% import_til_section(debug_info, debug_file, &til, progress)?; @@ -209,13 +207,13 @@ fn parse_til_info( debug_file: &BinaryView, progress: Box<dyn Fn(usize, usize) -> Result<(), ()>>, ) -> Result<()> { - trace!("Opening a TIL file"); + tracing::trace!("Opening a TIL file"); let file = BinaryViewReader { bv: debug_file, offset: 0, }; let mut file = std::io::BufReader::new(file); - trace!("Parsing the TIL section"); + tracing::trace!("Parsing the TIL section"); let til = TILSection::read(&mut file)?; import_til_section(debug_info, debug_file, &til, progress) } @@ -239,19 +237,19 @@ pub fn import_til_section( ); } TranslateTypeResult::Error(error) => { - error!( + tracing::error!( "Unable to parse type `{}`: {error}", ty.name.as_utf8_lossy(), ); } TranslateTypeResult::PartiallyTranslated(_, error) => { if let Some(error) = error { - error!( + tracing::error!( "Unable to parse type `{}` correctly: {error}", ty.name.as_utf8_lossy(), ); } else { - warn!( + tracing::warn!( "Type `{}` maybe not be fully translated", ty.name.as_utf8_lossy(), ); @@ -267,7 +265,7 @@ pub fn import_til_section( | TranslateTypeResult::PartiallyTranslated(bn_ty, _) = &ty.ty { if !debug_info.add_type(&ty.name.as_utf8_lossy(), bn_ty, &[/* TODO */]) { - error!("Unable to add type `{}`", ty.name.as_utf8_lossy()) + tracing::error!("Unable to add type `{}`", ty.name.as_utf8_lossy()) } } } @@ -278,7 +276,7 @@ pub fn import_til_section( | TranslateTypeResult::PartiallyTranslated(bn_ty, _) = &ty.ty { if !debug_info.add_type(&ty.name.as_utf8_lossy(), bn_ty, &[/* TODO */]) { - error!("Unable to fix type `{}`", ty.name.as_utf8_lossy()) + tracing::error!("Unable to fix type `{}`", ty.name.as_utf8_lossy()) } } } @@ -322,16 +320,16 @@ fn parse_id0_section_info<K: IDAKind>( .and_then(|ty| match translate_ephemeral_type(debug_file, ty) { TranslateTypeResult::Translated(result) => Some(result), TranslateTypeResult::PartiallyTranslated(result, None) => { - warn!("Unable to fully translate the type at {addr:#x}"); + tracing::warn!("Unable to fully translate the type at {addr:#x}"); Some(result) } TranslateTypeResult::NotYet => { - error!("Unable to translate the type at {addr:#x}"); + tracing::error!("Unable to translate the type at {addr:#x}"); None } TranslateTypeResult::PartiallyTranslated(_, Some(bn_type_error)) | TranslateTypeResult::Error(bn_type_error) => { - error!("Unable to translate the type at {addr:#x}: {bn_type_error}",); + tracing::error!("Unable to translate the type at {addr:#x}: {bn_type_error}",); None } }); @@ -341,7 +339,7 @@ fn parse_id0_section_info<K: IDAKind>( match (label, &ty, bnty) { (label, Some(ty), bnty) if matches!(&ty.type_variant, TILTypeVariant::Function(_)) => { if bnty.is_none() { - error!("Unable to convert the function type at {addr:#x}",) + tracing::error!("Unable to convert the function type at {addr:#x}",) } if !debug_info.add_function(&DebugFunctionInfo::new( None, @@ -353,18 +351,18 @@ fn parse_id0_section_info<K: IDAKind>( vec![], vec![], )) { - error!("Unable to add the function at {addr:#x}") + tracing::error!("Unable to add the function at {addr:#x}") } } (label, Some(_ty), Some(bnty)) => { if !debug_info.add_data_variable(addr, &bnty, label.as_ref().map(Cow::as_ref), &[]) { - error!("Unable to add the type at {addr:#x}") + tracing::error!("Unable to add the type at {addr:#x}") } } (label, Some(_ty), None) => { // TODO types come from the TIL sections, can we make all types be just NamedTypes? - error!("Unable to convert type {addr:#x}"); + tracing::error!("Unable to convert type {addr:#x}"); // TODO how to add a label without a type associated with it? if let Some(name) = label { if !debug_info.add_data_variable( @@ -373,7 +371,7 @@ fn parse_id0_section_info<K: IDAKind>( Some(&name), &[], ) { - error!("Unable to add the label at {addr:#x}") + tracing::error!("Unable to add the label at {addr:#x}") } } } @@ -385,7 +383,7 @@ fn parse_id0_section_info<K: IDAKind>( Some(&name), &[], ) { - error!("Unable to add the label at {addr:#x}") + tracing::error!("Unable to add the label at {addr:#x}") } } @@ -402,9 +400,7 @@ fn parse_id0_section_info<K: IDAKind>( #[allow(non_snake_case)] #[no_mangle] pub extern "C" fn CorePluginInit() -> bool { - Logger::new("IDB Import") - .with_level(LevelFilter::Error) - .init(); + binaryninja::tracing_init!("IDB Import"); DebugInfoParser::register("IDB Parser", IDBDebugInfoParser); DebugInfoParser::register("TIL Parser", TILDebugInfoParser); true diff --git a/plugins/pdb-ng/Cargo.toml b/plugins/pdb-ng/Cargo.toml index 3a9017d5..e77dac5b 100644 --- a/plugins/pdb-ng/Cargo.toml +++ b/plugins/pdb-ng/Cargo.toml @@ -12,7 +12,6 @@ anyhow = "^1.0" binaryninja.workspace = true binaryninjacore-sys.workspace = true itertools = "0.14" -log = "0.4" pdb = { git = "https://github.com/Vector35/pdb-rs", rev = "6016177" } regex = "1" diff --git a/plugins/pdb-ng/demo/Cargo.toml b/plugins/pdb-ng/demo/Cargo.toml index ddde9b94..bde9b28c 100644 --- a/plugins/pdb-ng/demo/Cargo.toml +++ b/plugins/pdb-ng/demo/Cargo.toml @@ -13,7 +13,6 @@ anyhow = "^1.0" binaryninja = { workspace = true, features = ["demo"]} binaryninjacore-sys.workspace = true itertools = "0.14" -log = "0.4" pdb = { git = "https://github.com/Vector35/pdb-rs", rev = "6016177" } regex = "1" diff --git a/plugins/pdb-ng/src/lib.rs b/plugins/pdb-ng/src/lib.rs index d7eb2524..5bbbb53e 100644 --- a/plugins/pdb-ng/src/lib.rs +++ b/plugins/pdb-ng/src/lib.rs @@ -21,15 +21,14 @@ use std::sync::mpsc; use std::{env, fs}; use anyhow::{anyhow, Result}; -use log::{debug, error, info}; use pdb::PDB; use binaryninja::binary_view::{BinaryView, BinaryViewBase, BinaryViewExt}; use binaryninja::debuginfo::{CustomDebugInfoParser, DebugInfo, DebugInfoParser}; use binaryninja::download::{DownloadInstanceInputOutputCallbacks, DownloadProvider}; use binaryninja::interaction::{MessageBoxButtonResult, MessageBoxButtonSet}; -use binaryninja::logger::Logger; use binaryninja::settings::{QueryOptions, Settings}; +use binaryninja::tracing::{debug, error, info}; use binaryninja::{interaction, user_directory}; use parser::PDBParserInstance; @@ -436,7 +435,9 @@ impl PDBParser { Ok(_) => { info!("Downloaded to: {}", cab_path.to_string_lossy()); } - Err(e) => error!("Could not write PDB to cache: {}", e), + Err(e) => { + error!("Could not write PDB to cache: {}", e) + } } } @@ -471,7 +472,9 @@ impl PDBParser { Ok(_) => { info!("Downloaded to: {}", cab_path.to_string_lossy()); } - Err(e) => error!("Could not write PDB to cache: {}", e), + Err(e) => { + error!("Could not write PDB to cache: {}", e) + } } } } @@ -588,7 +591,9 @@ impl CustomDebugInfoParser for PDBParser { } } Ok(None) => {} - e => error!("Error searching symbol store {}: {:?}", store, e), + e => { + error!("Error searching symbol store {}: {:?}", store, e) + } } } } @@ -649,7 +654,9 @@ impl CustomDebugInfoParser for PDBParser { Err(e) => debug!("Skipping, {}", e.to_string()), }, Err(e) if e.to_string() == "Cancelled" => return false, - Err(e) => debug!("Could not read pdb: {}", e.to_string()), + Err(e) => { + debug!("Could not read pdb: {}", e.to_string()) + } } } } @@ -690,7 +697,9 @@ impl CustomDebugInfoParser for PDBParser { } } Ok(None) => {} - e => error!("Error searching remote symbol server {}: {:?}", server, e), + e => { + error!("Error searching remote symbol server {}: {:?}", server, e) + } } } } @@ -718,7 +727,7 @@ pub extern "C" fn PDBPluginInit() -> bool { } fn init_plugin() -> bool { - Logger::new("PDB").init(); + binaryninja::tracing_init!("PDB Import"); DebugInfoParser::register("PDB", PDBParser {}); let settings = Settings::new(); diff --git a/plugins/pdb-ng/src/parser.rs b/plugins/pdb-ng/src/parser.rs index 96a9554e..708bc34a 100644 --- a/plugins/pdb-ng/src/parser.rs +++ b/plugins/pdb-ng/src/parser.rs @@ -18,7 +18,6 @@ use std::fmt::Display; use std::sync::OnceLock; use anyhow::{anyhow, Result}; -use log::{debug, info}; use pdb::*; use crate::symbol_parser::{ParsedDataSymbol, ParsedProcedure, ParsedSymbol}; @@ -31,6 +30,7 @@ use binaryninja::debuginfo::{DebugFunctionInfo, DebugInfo}; use binaryninja::platform::Platform; use binaryninja::rc::Ref; use binaryninja::settings::{QueryOptions, Settings}; +use binaryninja::tracing::{debug, info}; use binaryninja::types::{ EnumerationBuilder, NamedTypeReference, NamedTypeReferenceClass, StructureBuilder, StructureType, Type, TypeClass, diff --git a/plugins/pdb-ng/src/struct_grouper.rs b/plugins/pdb-ng/src/struct_grouper.rs index 902cea08..8143ff42 100644 --- a/plugins/pdb-ng/src/struct_grouper.rs +++ b/plugins/pdb-ng/src/struct_grouper.rs @@ -12,16 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. +use crate::type_parser::ParsedMember; use anyhow::{anyhow, Result}; use binaryninja::confidence::{Conf, MAX_CONFIDENCE}; +use binaryninja::tracing::{debug, warn}; use binaryninja::types::{MemberAccess, MemberScope, StructureBuilder, StructureType, Type}; -use log::{debug, warn}; use std::cmp::Ordering; use std::env; use std::fmt::{Debug, Display, Formatter}; -use crate::type_parser::ParsedMember; - #[derive(Debug, Clone, Copy, PartialEq, Eq)] struct MemberSize { index: usize, diff --git a/plugins/pdb-ng/src/type_parser.rs b/plugins/pdb-ng/src/type_parser.rs index 2ea404c2..e22489a9 100644 --- a/plugins/pdb-ng/src/type_parser.rs +++ b/plugins/pdb-ng/src/type_parser.rs @@ -24,12 +24,12 @@ use binaryninja::calling_convention::CoreCallingConvention; use binaryninja::confidence::{Conf, MAX_CONFIDENCE}; use binaryninja::platform::Platform; use binaryninja::rc::Ref; +use binaryninja::tracing::warn; use binaryninja::types::{ BaseStructure, EnumerationBuilder, EnumerationMember, FunctionParameter, MemberAccess, MemberScope, NamedTypeReference, NamedTypeReferenceClass, StructureBuilder, StructureMember, StructureType, Type, TypeBuilder, TypeClass, }; -use log::warn; use pdb::Error::UnimplementedTypeKind; use pdb::{ ArgumentList, ArrayType, BaseClassType, BitfieldType, ClassKind, ClassType, EnumerateType, diff --git a/plugins/svd/Cargo.toml b/plugins/svd/Cargo.toml index e25c410b..cd368585 100644 --- a/plugins/svd/Cargo.toml +++ b/plugins/svd/Cargo.toml @@ -11,7 +11,6 @@ crate-type = ["cdylib", "lib"] binaryninja.workspace = true binaryninjacore-sys.workspace = true svd-parser = { version = "0.14.8", features = ["expand"] } -log = "0.4" serde_json = "1.0" [dev-dependencies] diff --git a/plugins/svd/demo/Cargo.toml b/plugins/svd/demo/Cargo.toml index 0dffba6e..811f7d08 100644 --- a/plugins/svd/demo/Cargo.toml +++ b/plugins/svd/demo/Cargo.toml @@ -12,7 +12,6 @@ path = "../src/lib.rs" binaryninja = { workspace = true, features = ["demo"]} binaryninjacore-sys.workspace = true svd-parser = { version = "0.14.8", features = ["expand"] } -log = "0.4" serde_json = "1.0" [dev-dependencies] diff --git a/plugins/svd/src/lib.rs b/plugins/svd/src/lib.rs index 3a069056..396a9447 100644 --- a/plugins/svd/src/lib.rs +++ b/plugins/svd/src/lib.rs @@ -6,9 +6,8 @@ use crate::settings::LoadSettings; use binaryninja::binary_view::{BinaryView, BinaryViewBase, BinaryViewExt}; use binaryninja::command::Command; use binaryninja::interaction::{Form, FormInputField}; -use binaryninja::logger::Logger; +use binaryninja::tracing; use binaryninja::workflow::{activity, Activity, AnalysisContext, Workflow}; -use log::LevelFilter; use std::path::PathBuf; use svd_parser::ValidateLevel; @@ -120,7 +119,7 @@ impl Command for LoadSVDFile { let file_content = match std::fs::read_to_string(&file_path) { Ok(content) => content, Err(e) => { - log::error!("Failed to read file: {:?}", e); + tracing::error!("Failed to read file: {:?}", e); return; } }; @@ -137,7 +136,7 @@ impl Command for LoadSVDFile { view.update_analysis(); } Err(e) => { - log::error!("Failed to parse SVD file: {:?}", e); + tracing::error!("Failed to parse SVD file: {:?}", e); } } } @@ -152,7 +151,7 @@ impl Command for LoadSVDFile { #[cfg(not(feature = "demo"))] pub extern "C" fn CorePluginInit() -> bool { if plugin_init().is_err() { - log::error!("Failed to initialize SVD plug-in"); + tracing::error!("Failed to initialize SVD plug-in"); return false; } true @@ -163,14 +162,14 @@ pub extern "C" fn CorePluginInit() -> bool { #[cfg(feature = "demo")] pub extern "C" fn SVDPluginInit() -> bool { if plugin_init().is_err() { - log::error!("Failed to initialize SVD plug-in"); + tracing::error!("Failed to initialize SVD plug-in"); return false; } true } fn plugin_init() -> Result<(), ()> { - Logger::new("SVD").with_level(LevelFilter::Debug).init(); + binaryninja::tracing_init!("SVD"); binaryninja::command::register_command( "Load SVD File", @@ -185,13 +184,13 @@ fn plugin_init() -> Result<(), ()> { let view = ctx.view(); let load_settings = LoadSettings::from_view_settings(&view); let Some(file) = &load_settings.auto_load_file else { - log::debug!("No SVD file specified, skipping..."); + tracing::debug!("No SVD file specified, skipping..."); return; }; let file_content = match std::fs::read_to_string(file) { Ok(content) => content, Err(e) => { - log::error!("Failed to read file: {}", e); + tracing::error!("Failed to read file: {}", e); return; } }; @@ -204,7 +203,7 @@ fn plugin_init() -> Result<(), ()> { mapper.map_to_view(&view); } Err(e) => { - log::error!("Failed to parse SVD file: {:?}", e); + tracing::error!("Failed to parse SVD file: {:?}", e); } } }; diff --git a/plugins/svd/src/mapper.rs b/plugins/svd/src/mapper.rs index 4c49145b..2c09eb95 100644 --- a/plugins/svd/src/mapper.rs +++ b/plugins/svd/src/mapper.rs @@ -6,6 +6,7 @@ use binaryninja::rc::Ref; use binaryninja::section::{SectionBuilder, Semantics}; use binaryninja::segment::{SegmentBuilder, SegmentFlags}; use binaryninja::symbol::{SymbolBuilder, SymbolType}; +use binaryninja::tracing; use binaryninja::types::{ BaseStructure, EnumerationBuilder, MemberAccess, MemberScope, NamedTypeReference, NamedTypeReferenceClass, StructureBuilder, StructureMember, Type, TypeBuilder, @@ -78,7 +79,7 @@ impl DeviceMapper { } pub fn map_to_view(&self, view: &BinaryView) { - log::info!("Mapping device... {}", self.device.name); + tracing::info!("Mapping device... {}", self.device.name); for peripheral in &self.device.peripherals { match peripheral { Peripheral::Single(info) => { @@ -143,7 +144,7 @@ impl DeviceMapper { address_block: &AddressBlock, ) { let block_addr = peripheral.base_address + address_block.offset as u64; - log::info!( + tracing::info!( "Mapping peripheral block @ 0x{:x} for {}", block_addr, peripheral.name @@ -176,7 +177,7 @@ impl DeviceMapper { ); if !added_memory { - log::error!( + tracing::error!( "Failed to add memory for peripheral block! {} @ 0x{:x}", block_name, block_addr diff --git a/plugins/warp/Cargo.toml b/plugins/warp/Cargo.toml index 59f1e607..79f7632f 100644 --- a/plugins/warp/Cargo.toml +++ b/plugins/warp/Cargo.toml @@ -14,7 +14,6 @@ demo = [] binaryninja = { workspace = true, features = ["rayon"] } binaryninjacore-sys.workspace = true warp = { git = "https://github.com/Vector35/warp/", tag = "1.0.1" } -log = "0.4" itertools = "0.14.0" dashmap = { version = "6.1", features = ["rayon"]} rayon = "1.10" diff --git a/plugins/warp/demo/Cargo.toml b/plugins/warp/demo/Cargo.toml index 8e1070e3..50664483 100644 --- a/plugins/warp/demo/Cargo.toml +++ b/plugins/warp/demo/Cargo.toml @@ -15,7 +15,6 @@ demo = [] binaryninja = { workspace = true, features = ["rayon", "demo"] } binaryninjacore-sys.workspace = true warp = { git = "https://github.com/Vector35/warp/", tag = "1.0.0" } -log = "0.4" itertools = "0.14.0" dashmap = { version = "6.1", features = ["rayon"]} rayon = "1.10" diff --git a/plugins/warp/src/cache.rs b/plugins/warp/src/cache.rs index 09ad1444..30c7487c 100644 --- a/plugins/warp/src/cache.rs +++ b/plugins/warp/src/cache.rs @@ -11,7 +11,7 @@ use binaryninja::binary_view::{BinaryView, BinaryViewExt}; use binaryninja::function::Function as BNFunction; use binaryninja::rc::Guard; use binaryninja::rc::Ref as BNRef; -use binaryninja::ObjectDestructor; +use binaryninja::{tracing, ObjectDestructor}; use std::hash::{DefaultHasher, Hash, Hasher}; pub fn register_cache_destructor() { @@ -31,7 +31,7 @@ impl From<&BinaryView> for ViewID { fn from(value: &BinaryView) -> Self { let mut hasher = DefaultHasher::new(); hasher.write_u64(value.original_image_base()); - hasher.write_usize(value.file().session_id()); + hasher.write_usize(value.file().session_id().0); Self(hasher.finish()) } } @@ -79,6 +79,6 @@ pub struct CacheDestructor; impl ObjectDestructor for CacheDestructor { fn destruct_view(&self, view: &BinaryView) { clear_type_ref_cache(view); - log::debug!("Removed WARP caches for {:?}", view.file().filename()); + tracing::debug!("Removed WARP caches for {:?}", view.file().filename()); } } diff --git a/plugins/warp/src/container/disk.rs b/plugins/warp/src/container/disk.rs index a0400f9d..5e4a5613 100644 --- a/plugins/warp/src/container/disk.rs +++ b/plugins/warp/src/container/disk.rs @@ -1,6 +1,7 @@ use crate::container::{ Container, ContainerError, ContainerResult, SourceId, SourcePath, SourceTag, }; +use binaryninja::tracing; use std::collections::{HashMap, HashSet}; use std::fmt::{Debug, Display, Formatter}; use std::hash::{Hash, Hasher}; @@ -42,7 +43,7 @@ impl DiskContainer { match (DiskContainerSource::new_from_path(path.clone()), path_ext) { (Ok(source), _) => Some((source_id, source)), (Err(err), Some("warp")) => { - log::error!("Failed to load source '{}' from disk: {}", path, err); + tracing::error!("Failed to load source '{}' from disk: {}", path, err); None } // We don't care to show errors loading for non-warp files. diff --git a/plugins/warp/src/container/network.rs b/plugins/warp/src/container/network.rs index d0ccd3ea..0908b103 100644 --- a/plugins/warp/src/container/network.rs +++ b/plugins/warp/src/container/network.rs @@ -3,6 +3,7 @@ use crate::container::{ Container, ContainerError, ContainerResult, ContainerSearchQuery, ContainerSearchResponse, SourceId, SourcePath, SourceTag, }; +use binaryninja::tracing; use directories::ProjectDirs; use std::collections::{HashMap, HashSet}; use std::fmt::{Debug, Display, Formatter}; @@ -102,7 +103,7 @@ impl NetworkContainer { guids: &[FunctionGUID], ) -> HashMap<SourceId, Vec<FunctionGUID>> { let Some(target_id) = target.and_then(|t| self.get_target_id(t)) else { - log::debug!("Cannot query functions source without a target, skipping..."); + tracing::debug!("Cannot query functions source without a target, skipping..."); return HashMap::new(); }; @@ -122,7 +123,7 @@ impl NetworkContainer { { Ok(queried_results) => queried_results, Err(e) => { - log::error!("Failed to query functions source: {}", e); + tracing::error!("Failed to query functions source: {}", e); return result; } }; @@ -170,12 +171,12 @@ impl NetworkContainer { { Ok(file) => file, Err(e) => { - log::error!("Failed to query functions: {}", e); + tracing::error!("Failed to query functions: {}", e); return; } }; - log::debug!("Got {} chunks from server", file.chunks.len()); + tracing::debug!("Got {} chunks from server", file.chunks.len()); for chunk in &file.chunks { match &chunk.kind { ChunkKind::Signature(sc) => { @@ -183,12 +184,12 @@ impl NetworkContainer { // Probe the source before attempting to access it, as it might not exist locally. self.probe_source(*source); match self.cache.add_functions(target, source, &functions) { - Ok(_) => log::debug!( + Ok(_) => tracing::debug!( "Added {} functions into cached source '{}'", functions.len(), source ), - Err(err) => log::error!( + Err(err) => tracing::error!( "Failed to add {} function into cached source '{}': {}", functions.len(), source, @@ -227,7 +228,7 @@ impl NetworkContainer { let _ = self.cache.insert_source(source_id, SourcePath(source_path)); } Err(e) => { - log::error!("Failed to probe source '{}': {}", source_id, e); + tracing::error!("Failed to probe source '{}': {}", source_id, e); } } } diff --git a/plugins/warp/src/container/network/client.rs b/plugins/warp/src/container/network/client.rs index 9f68180b..d3c94d1a 100644 --- a/plugins/warp/src/container/network/client.rs +++ b/plugins/warp/src/container/network/client.rs @@ -5,6 +5,7 @@ use crate::container::{ }; use base64::Engine; use binaryninja::download::DownloadProvider; +use binaryninja::tracing; use serde::Deserialize; use serde_json::json; use std::collections::HashMap; @@ -496,14 +497,14 @@ impl NetworkClient { let kind = match item.kind.as_str() { "function" => { let Some(data) = &item.data else { - log::warn!( + tracing::warn!( "Function item {} has no data from network, skipping...", item.id ); continue; }; let Some(func) = Function::from_bytes(&data) else { - log::warn!( + tracing::warn!( "Function item {} has invalid data from network, skipping...", item.id ); @@ -514,7 +515,7 @@ impl NetworkClient { "source" => ContainerSearchItemKind::Source { path: match item.name { None => { - log::warn!("Source item {} has no name", item.id); + tracing::warn!("Source item {} has no name", item.id); continue; } Some(name) => SourcePath(format!("{}/{}", self.server_url, name).into()), @@ -523,14 +524,14 @@ impl NetworkClient { }, "type" => { let Some(data) = &item.data else { - log::warn!( + tracing::warn!( "Type item {} has no data from network, skipping...", item.id ); continue; }; let Some(ty) = Type::from_bytes(&data) else { - log::warn!( + tracing::warn!( "Type item {} has invalid data from network, skipping...", item.id ); diff --git a/plugins/warp/src/convert/types.rs b/plugins/warp/src/convert/types.rs index f8ead6af..227df2ea 100644 --- a/plugins/warp/src/convert/types.rs +++ b/plugins/warp/src/convert/types.rs @@ -6,6 +6,7 @@ use binaryninja::calling_convention::CoreCallingConvention as BNCallingConventio use binaryninja::confidence::Conf as BNConf; use binaryninja::confidence::MAX_CONFIDENCE; use binaryninja::rc::Ref as BNRef; +use binaryninja::tracing; use binaryninja::types::BaseStructure as BNBaseStructure; use binaryninja::types::EnumerationBuilder as BNEnumerationBuilder; use binaryninja::types::FunctionParameter as BNFunctionParameter; @@ -361,7 +362,7 @@ pub fn to_bn_type<A: BNArchitecture + Copy>(arch: Option<A>, ty: &Type) -> BNRef )) } _ => { - log::error!( + tracing::error!( "Adding base {:?} with invalid ty: {:?}", ty.name, member.ty @@ -470,7 +471,7 @@ pub fn to_bn_type<A: BNArchitecture + Copy>(arch: Option<A>, ty: &Type) -> BNRef ntr_name, ), None => { - log::error!("Referrer with no reference! {:?}", c); + tracing::error!("Referrer with no reference! {:?}", c); NamedTypeReference::new( NamedTypeReferenceClass::UnknownNamedTypeClass, "AHHHHHH", diff --git a/plugins/warp/src/plugin.rs b/plugins/warp/src/plugin.rs index 9fe6cd3f..dec62c2f 100644 --- a/plugins/warp/src/plugin.rs +++ b/plugins/warp/src/plugin.rs @@ -12,10 +12,8 @@ use binaryninja::background_task::BackgroundTask; use binaryninja::command::{ register_command, register_command_for_function, register_command_for_project, }; -use binaryninja::is_ui_enabled; -use binaryninja::logger::Logger; use binaryninja::settings::{QueryOptions, Settings}; -use log::LevelFilter; +use binaryninja::{is_ui_enabled, tracing}; mod commit; mod create; @@ -42,16 +40,16 @@ fn load_bundled_signatures() { let mut core_disk_container = DiskContainer::new_from_dir(core_signature_dir()); core_disk_container.name = "Bundled".to_string(); core_disk_container.writable = false; - log::debug!("{:#?}", core_disk_container); + tracing::debug!("{:#?}", core_disk_container); add_cached_container(core_disk_container); } if plugin_settings.load_user_files { let mut user_disk_container = DiskContainer::new_from_dir(user_signature_dir()); user_disk_container.name = "User".to_string(); - log::debug!("{:#?}", user_disk_container); + tracing::debug!("{:#?}", user_disk_container); add_cached_container(user_disk_container); } - log::info!("Loading files took {:?}", start.elapsed()); + tracing::info!("Loading files took {:?}", start.elapsed()); background_task.finish(); } @@ -62,7 +60,7 @@ fn load_network_container() { let network_client = NetworkClient::new(url.clone(), api_key.clone()); // Before constructing the container, let's make sure that the server is OK. if let Err(e) = network_client.status() { - log::warn!("Server '{}' failed to connect: {}", url, e); + tracing::warn!("Server '{}' failed to connect: {}", url, e); return; } @@ -70,7 +68,7 @@ fn load_network_container() { let mut writable_sources = Vec::new(); match network_client.current_user() { Ok((id, username)) => { - log::info!( + tracing::info!( "Server '{}' connected, logged in as user '{}'", url, username @@ -80,19 +78,19 @@ fn load_network_container() { writable_sources = sources; } Err(e) => { - log::error!("Server '{}' failed to get sources for user: {}", url, e); + tracing::error!("Server '{}' failed to get sources for user: {}", url, e); } } } Err(e) if api_key.is_some() => { - log::error!( + tracing::error!( "Server '{}' failed to authenticate with provided API key: {}", url, e ); } Err(_) => { - log::info!("Server '{}' connected, logged in as guest", url); + tracing::info!("Server '{}' connected, logged in as guest", url); } } @@ -100,7 +98,7 @@ fn load_network_container() { let main_cache_path = NetworkContainer::root_cache_location().join("main"); let network_container = NetworkContainer::new(network_client, main_cache_path, &writable_sources); - log::debug!("{:#?}", network_container); + tracing::debug!("{:#?}", network_container); add_cached_container(network_container); }; @@ -114,17 +112,17 @@ fn load_network_container() { add_network_container(second_server_url, plugin_settings.second_server_api_key); } } - log::debug!("Initializing warp server took {:?}", start.elapsed()); + tracing::debug!("Initializing warp server took {:?}", start.elapsed()); background_task.finish(); } fn plugin_init() -> bool { - Logger::new("WARP").with_level(LevelFilter::Debug).init(); + binaryninja::tracing_init!("WARP"); // Create the user signature directory if it does not exist, otherwise we will not be able to write to it. if !user_signature_dir().exists() { if let Err(e) = std::fs::create_dir_all(&user_signature_dir()) { - log::error!("Failed to create user signature directory: {}", e); + tracing::error!("Failed to create user signature directory: {}", e); } } @@ -141,7 +139,7 @@ fn plugin_init() -> bool { HighlightRenderLayer::register(); if workflow::insert_workflow().is_err() { - log::error!("Failed to register WARP workflow"); + tracing::error!("Failed to register WARP workflow"); return false; } diff --git a/plugins/warp/src/plugin/commit.rs b/plugins/warp/src/plugin/commit.rs index 2af5fc3e..56a78f9a 100644 --- a/plugins/warp/src/plugin/commit.rs +++ b/plugins/warp/src/plugin/commit.rs @@ -6,6 +6,7 @@ use crate::plugin::create::OpenFileField; use binaryninja::binary_view::BinaryView; use binaryninja::command::Command; use binaryninja::interaction::{Form, FormInputField}; +use binaryninja::tracing; use warp::chunk::ChunkKind; use warp::WarpFile; @@ -84,11 +85,11 @@ impl CommitFile { let open_file_path = OpenFileField::from_form(&form)?; let source_id = source_field.from_form(&form)?; - log::info!("Committing file to source: {}", source_id); + tracing::info!("Committing file to source: {}", source_id); let bytes = std::fs::read(open_file_path).ok()?; let Some(warp_file) = WarpFile::from_bytes(&bytes) else { - log::error!("Failed to parse warp file!"); + tracing::error!("Failed to parse warp file!"); return None; }; @@ -103,7 +104,7 @@ impl CommitFile { match &chunk.kind { ChunkKind::Signature(sc) => { let functions: Vec<_> = sc.functions().collect(); - log::info!( + tracing::info!( "Adding {} functions to source: {}", functions.len(), source_id @@ -113,22 +114,22 @@ impl CommitFile { &source_id, &functions, ) { - log::error!("Failed to add functions to source: {}", e); + tracing::error!("Failed to add functions to source: {}", e); } } ChunkKind::Type(sc) => { let types: Vec<_> = sc.types().collect(); - log::info!("Adding {} types to source: {}", types.len(), source_id); + tracing::info!("Adding {} types to source: {}", types.len(), source_id); if let Err(e) = container.add_computed_types(&source_id, &types) { - log::error!("Failed to add types to source: {}", e); + tracing::error!("Failed to add types to source: {}", e); } } } } if let Err(e) = container.commit_source(&source_id) { - log::error!("Failed to commit source: {}", e); + tracing::error!("Failed to commit source: {}", e); } - log::info!("Committed file to source: {}", source_id); + tracing::info!("Committed file to source: {}", source_id); return Some(()); } } diff --git a/plugins/warp/src/plugin/create.rs b/plugins/warp/src/plugin/create.rs index d6839ce6..04a3e9b6 100644 --- a/plugins/warp/src/plugin/create.rs +++ b/plugins/warp/src/plugin/create.rs @@ -10,6 +10,7 @@ use binaryninja::command::Command; use binaryninja::interaction::form::{Form, FormInputField}; use binaryninja::interaction::{MessageBoxButtonResult, MessageBoxButtonSet, MessageBoxIcon}; use binaryninja::rc::Ref; +use binaryninja::tracing; use std::path::PathBuf; use std::thread; use warp::chunk::Chunk; @@ -131,7 +132,7 @@ impl CreateFromCurrentView { existing_chunks.extend(existing_file.chunks); } MessageBoxButtonResult::CancelButton => { - log::info!( + tracing::info!( "User cancelled signature file creation, no operations were performed." ); return None; @@ -168,7 +169,7 @@ impl CreateFromCurrentView { MessageBoxButtonSet::OKButtonSet, MessageBoxIcon::ErrorIcon, ); - log::error!("Failed to create signature file: {}", err); + tracing::error!("Failed to create signature file: {}", err); return None; } @@ -184,7 +185,9 @@ impl CreateFromCurrentView { // After merging, we should have at least one chunk. If not, merging actually removed data. if file.chunks.len() < 1 { - log::error!("Failed to merge chunks! Please report this, it should not happen."); + tracing::error!( + "Failed to merge chunks! Please report this, it should not happen." + ); return None; } } @@ -192,9 +195,9 @@ impl CreateFromCurrentView { let file_bytes = file.to_bytes(); let file_size = file_bytes.len(); if std::fs::write(&file_path, file_bytes).is_err() { - log::error!("Failed to write data to signature file!"); + tracing::error!("Failed to write data to signature file!"); } - log::info!("Saved signature file to: '{}'", file_path.display()); + tracing::info!("Saved signature file to: '{}'", file_path.display()); background_task.finish(); // Show a report of the generate signatures, if desired. @@ -210,7 +213,7 @@ impl CreateFromCurrentView { // The ReportWidget uses a QTextBrowser, which cannot render large files very well. if file_size > 10000000 { - log::warn!("WARP report file is too large to show in the UI. Please see the report file on disk."); + tracing::warn!("WARP report file is too large to show in the UI. Please see the report file on disk."); } else { match report_kind { ReportKindField::None => {} diff --git a/plugins/warp/src/plugin/debug.rs b/plugins/warp/src/plugin/debug.rs index 399dba50..6db491e2 100644 --- a/plugins/warp/src/plugin/debug.rs +++ b/plugins/warp/src/plugin/debug.rs @@ -3,13 +3,13 @@ use crate::{build_function, cache}; use binaryninja::binary_view::BinaryView; use binaryninja::command::{Command, FunctionCommand}; use binaryninja::function::Function; -use binaryninja::ObjectDestructor; +use binaryninja::{tracing, ObjectDestructor}; pub struct DebugFunction; impl FunctionCommand for DebugFunction { fn action(&self, _view: &BinaryView, func: &Function) { - log::info!( + tracing::info!( "{:#?}", build_function(func, || func.lifted_il().ok(), false) ); @@ -25,7 +25,7 @@ pub struct DebugCache; impl Command for DebugCache { fn action(&self, _view: &BinaryView) { for_cached_containers(|c| { - log::info!("Container: {:#?}", c); + tracing::info!("Container: {:#?}", c); }); } @@ -40,7 +40,7 @@ impl Command for DebugInvalidateCache { fn action(&self, view: &BinaryView) { let destructor = cache::CacheDestructor {}; destructor.destruct_view(view); - log::info!("Invalidated all WARP caches..."); + tracing::info!("Invalidated all WARP caches..."); } fn valid(&self, _view: &BinaryView) -> bool { diff --git a/plugins/warp/src/plugin/ffi/container.rs b/plugins/warp/src/plugin/ffi/container.rs index 72c85366..6c2551c1 100644 --- a/plugins/warp/src/plugin/ffi/container.rs +++ b/plugins/warp/src/plugin/ffi/container.rs @@ -10,6 +10,7 @@ use binaryninja::architecture::CoreArchitecture; use binaryninja::binary_view::BinaryView; use binaryninja::rc::Ref; use binaryninja::string::BnString; +use binaryninja::tracing; use binaryninja::types::Type; use binaryninjacore_sys::{BNArchitecture, BNBinaryView, BNType}; use std::ffi::{c_char, CStr}; @@ -219,7 +220,7 @@ pub unsafe extern "C" fn BNWARPContainerFetchFunctions( let guids = unsafe { std::slice::from_raw_parts(guids, count) }; if let Err(e) = container.fetch_functions(&target, &source_tags, guids) { - log::error!("Failed to fetch functions: {}", e); + tracing::error!("Failed to fetch functions: {}", e); } } @@ -586,7 +587,7 @@ pub unsafe extern "C" fn BNWARPContainerSearch( let result = match container.search(&query) { Ok(result) => result, Err(err) => { - log::error!("Failed to search container {:?}: {}", query.deref(), err); + tracing::error!("Failed to search container {:?}: {}", query.deref(), err); return std::ptr::null_mut(); } }; diff --git a/plugins/warp/src/plugin/file.rs b/plugins/warp/src/plugin/file.rs index ec61bd78..899e3f46 100644 --- a/plugins/warp/src/plugin/file.rs +++ b/plugins/warp/src/plugin/file.rs @@ -1,6 +1,7 @@ use crate::report::ReportGenerator; use binaryninja::binary_view::{BinaryView, BinaryViewExt}; use binaryninja::command::Command; +use binaryninja::tracing; pub struct ShowFileReport; @@ -15,12 +16,12 @@ impl Command for ShowFileReport { }; let Ok(bytes) = std::fs::read(&path) else { - log::error!("Failed to read file: {:?}", path); + tracing::error!("Failed to read file: {:?}", path); return; }; let Some(file) = warp::WarpFile::from_bytes(&bytes) else { - log::error!("Failed to parse file: {:?}", path); + tracing::error!("Failed to parse file: {:?}", path); return; }; diff --git a/plugins/warp/src/plugin/function.rs b/plugins/warp/src/plugin/function.rs index 6202f9d7..3c0dc06c 100644 --- a/plugins/warp/src/plugin/function.rs +++ b/plugins/warp/src/plugin/function.rs @@ -10,6 +10,7 @@ use binaryninja::binary_view::{BinaryView, BinaryViewExt}; use binaryninja::command::{Command, FunctionCommand}; use binaryninja::function::{Function, FunctionUpdateType}; use binaryninja::rc::Guard; +use binaryninja::tracing; use rayon::iter::ParallelIterator; use std::thread; use warp::signature::function::FunctionGUID; @@ -24,7 +25,7 @@ impl FunctionCommand for IncludeFunction { let insert_tag_type = get_warp_include_tag_type(view); match should_add_tag { true => { - log::info!( + tracing::info!( "Including selected function '{}' at 0x{:x}", sym_name_str, func.start() @@ -32,7 +33,7 @@ impl FunctionCommand for IncludeFunction { func.add_tag(&insert_tag_type, "", None, false, None); } false => { - log::info!( + tracing::info!( "Removing included function '{}' at 0x{:x}", sym_name_str, func.start() @@ -58,7 +59,7 @@ impl FunctionCommand for IgnoreFunction { let ignore_tag_type = get_warp_ignore_tag_type(view); match should_add_tag { true => { - log::info!( + tracing::info!( "Ignoring function for matching '{}' at 0x{:x}", sym_name_str, func.start() @@ -66,7 +67,7 @@ impl FunctionCommand for IgnoreFunction { func.add_tag(&ignore_tag_type, "", None, false, None); } false => { - log::info!( + tracing::info!( "Including function for matching '{}' at 0x{:x}", sym_name_str, func.start() @@ -87,7 +88,7 @@ impl FunctionCommand for RemoveFunction { fn action(&self, _view: &BinaryView, func: &Function) { let sym_name = func.symbol().short_name(); let sym_name_str = sym_name.to_string_lossy(); - log::info!( + tracing::info!( "Removing matched function '{}' at 0x{:x}", sym_name_str, func.start() @@ -107,10 +108,10 @@ pub struct CopyFunctionGUID; impl FunctionCommand for CopyFunctionGUID { fn action(&self, _view: &BinaryView, func: &Function) { let Some(guid) = cached_function_guid(func, || func.lifted_il().ok()) else { - log::error!("Could not get guid for copied function"); + tracing::error!("Could not get guid for copied function"); return; }; - log::info!( + tracing::info!( "Function GUID for {:?}... {}", func.symbol().short_name(), guid @@ -137,11 +138,11 @@ impl Command for FindFunctionFromGUID { }; let Ok(searched_guid) = guid_str.parse::<FunctionGUID>() else { - log::error!("Failed to parse function guid... {}", guid_str); + tracing::error!("Failed to parse function guid... {}", guid_str); return; }; - log::info!("Searching functions for GUID... {}", searched_guid); + tracing::info!("Searching functions for GUID... {}", searched_guid); let funcs = view.functions(); let view = view.to_owned(); thread::spawn(move || { @@ -159,7 +160,7 @@ impl Command for FindFunctionFromGUID { .collect(); if matched.is_empty() { - log::info!("No matches found for GUID... {}", searched_guid); + tracing::info!("No matches found for GUID... {}", searched_guid); } else { for func in &matched { // Also navigate the user, as that is probably what they want. @@ -170,14 +171,14 @@ impl Command for FindFunctionFromGUID { .navigate_to(¤t_view, func.start()) .is_err() { - log::error!( + tracing::error!( "Failed to navigate to found function 0x{:0x} in view {}", func.start(), current_view ); } } - log::info!("Match found at function... 0x{:0x}", func.start()); + tracing::info!("Match found at function... 0x{:0x}", func.start()); } } diff --git a/plugins/warp/src/plugin/load.rs b/plugins/warp/src/plugin/load.rs index 0b8d1672..bd0e4838 100644 --- a/plugins/warp/src/plugin/load.rs +++ b/plugins/warp/src/plugin/load.rs @@ -10,6 +10,7 @@ use binaryninja::interaction::{ MessageBoxIcon, }; use binaryninja::rc::Ref; +use binaryninja::tracing; use std::collections::HashMap; use std::path::PathBuf; use std::sync::atomic::AtomicBool; @@ -130,7 +131,7 @@ impl LoadSignatureFile { let file = match LoadSignatureFile::read_file(&view, source_file_path.clone()) { Ok(file) => file, Err(e) => { - log::error!("Failed to read signature file: {}", e); + tracing::error!("Failed to read signature file: {}", e); return; } }; @@ -156,7 +157,7 @@ impl LoadSignatureFile { } let container_source = DiskContainerSource::new(source_file_path.clone(), file); - log::info!("Loading container source: '{}'", container_source.path); + tracing::info!("Loading container source: '{}'", container_source.path); let mut map = HashMap::new(); map.insert(source_file_path.to_source_id(), container_source); let container = DiskContainer::new("Loaded signatures".to_string(), map); diff --git a/plugins/warp/src/plugin/project.rs b/plugins/warp/src/plugin/project.rs index 725d164c..8862c00a 100644 --- a/plugins/warp/src/plugin/project.rs +++ b/plugins/warp/src/plugin/project.rs @@ -9,6 +9,7 @@ use binaryninja::interaction::{Form, FormInputField}; use binaryninja::project::folder::ProjectFolder; use binaryninja::project::Project; use binaryninja::rc::Ref; +use binaryninja::tracing; use binaryninja::worker_thread::{set_worker_thread_count, worker_thread_count}; use rayon::ThreadPoolBuilder; use regex::Regex; @@ -157,7 +158,7 @@ impl CreateSignatures { .create_file(&warp_file.to_bytes(), folder, name, "") .is_err() { - log::error!("Failed to create project file!"); + tracing::error!("Failed to create project file!"); } let report = ReportGenerator::new(); @@ -168,7 +169,7 @@ impl CreateSignatures { .create_file(&generated.into_bytes(), folder, &file_name, "Warp file") .is_err() { - log::error!("Failed to create project file!"); + tracing::error!("Failed to create project file!"); } } }; @@ -177,12 +178,12 @@ impl CreateSignatures { let callback_project = project.clone(); let save_individual_files_cb = move |path: &Path, file: &WarpFile| { if file.chunks.is_empty() { - log::debug!("Skipping empty file: {}", path.display()); + tracing::debug!("Skipping empty file: {}", path.display()); return; } // The path returned will be the one on disk, so we will go and grab the project for it. let Some(project_file) = callback_project.file_by_path(path) else { - log::error!("Failed to find project file for path: {}", path.display()); + tracing::error!("Failed to find project file for path: {}", path.display()); return; }; let project_file = project_file.to_owned(); @@ -214,8 +215,8 @@ impl CreateSignatures { processor = processor.with_file_filter(f); } Err(err) => { - log::error!("Failed to parse file filter: {}", err); - log::error!( + tracing::error!("Failed to parse file filter: {}", err); + tracing::error!( "Consider using a substring instead of a glob pattern, e.g. *.exe => exe" ); return; @@ -231,7 +232,7 @@ impl CreateSignatures { .num_threads(processing_thread_count) .build() else { - log::error!("Failed to create processing thread pool!"); + tracing::error!("Failed to create processing thread pool!"); return; }; @@ -240,7 +241,7 @@ impl CreateSignatures { let previous_worker_thread_count = worker_thread_count(); let upgraded_thread_count = previous_worker_thread_count * 3; if upgraded_thread_count > previous_worker_thread_count { - log::info!( + tracing::info!( "Setting worker thread count to {} for the duration of processing...", upgraded_thread_count ); @@ -253,14 +254,14 @@ impl CreateSignatures { save_warp_file(&project, None, "generated.warp", &warp_file); } Err(e) => { - log::error!("Failed to process project: {}", e); + tracing::error!("Failed to process project: {}", e); } }); let processed_file_count = processor .state() .files_with_state(ProcessingFileState::Processed); - log::info!( + tracing::info!( "Processing {} project files took: {:?}", processed_file_count, start.elapsed() diff --git a/plugins/warp/src/plugin/workflow.rs b/plugins/warp/src/plugin/workflow.rs index e5ce9b76..a51c7399 100644 --- a/plugins/warp/src/plugin/workflow.rs +++ b/plugins/warp/src/plugin/workflow.rs @@ -15,6 +15,7 @@ use binaryninja::command::Command; use binaryninja::function::Function as BNFunction; use binaryninja::rc::Ref as BNRef; use binaryninja::settings::{QueryOptions, Settings}; +use binaryninja::tracing; use binaryninja::workflow::{activity, Activity, AnalysisContext, Workflow, WorkflowBuilder}; use dashmap::DashSet; use itertools::Itertools; @@ -39,7 +40,7 @@ impl Command for RunMatcher { // Alert the user if we have no actual regions (+1 comes from the synthetic section). let regions = relocatable_regions(&view); if regions.len() <= 1 && view.memory_map().is_activated() { - log::warn!( + tracing::warn!( "No relocatable regions found, for best results please define sections for the binary!" ); } @@ -90,13 +91,15 @@ impl FunctionSet { .workflow() .expect("Function has no workflow"); if function_workflow.contains(GUID_ACTIVITY_NAME) { - log::error!("No function guids in database, please reanalyze the database."); + tracing::error!( + "No function guids in database, please reanalyze the database." + ); } else { - log::error!( - "Activity '{}' is not in workflow '{}', create function guids manually to run matcher...", - GUID_ACTIVITY_NAME, - function_workflow.name() - ) + tracing::error!( + "Activity '{}' is not in workflow '{}', create function guids manually to run matcher...", + GUID_ACTIVITY_NAME, + function_workflow.name() + ) } } return None; @@ -169,7 +172,7 @@ pub fn run_matcher(view: &BinaryView) { .maximum_possible_functions .is_some_and(|max| max < matched_functions.len() as u64) { - log::warn!( + tracing::warn!( "Skipping {}, too many possible functions: {}", guid, matched_functions.len() @@ -244,10 +247,10 @@ pub fn run_matcher(view: &BinaryView) { } if background_task.is_cancelled() { - log::info!("Matcher was cancelled by user, you may run it again by running the 'Run Matcher' command."); + tracing::info!("Matcher was cancelled by user, you may run it again by running the 'Run Matcher' command."); } - log::info!( + tracing::info!( "Function matching took {:.3} seconds and matched {} functions after {} rounds", start.elapsed().as_secs_f64(), matcher_results.len(), @@ -290,12 +293,12 @@ pub fn run_fetcher(view: &BinaryView) { }); if background_task.is_cancelled() { - log::info!( + tracing::info!( "Fetcher was cancelled by user, you may run it again by running the 'Fetch' command." ); } - log::info!("Fetching took {:?}", start.elapsed()); + tracing::info!("Fetching took {:?}", start.elapsed()); background_task.finish(); } diff --git a/plugins/warp/src/processor.rs b/plugins/warp/src/processor.rs index 693f0852..3076ddca 100644 --- a/plugins/warp/src/processor.rs +++ b/plugins/warp/src/processor.rs @@ -26,6 +26,10 @@ use binaryninja::project::file::ProjectFile; use binaryninja::project::Project; use binaryninja::rc::{Guard, Ref}; +use crate::cache::cached_type_references; +use crate::convert::platform_to_target; +use crate::{build_function, INCLUDE_TAG_ICON, INCLUDE_TAG_NAME}; +use binaryninja::tracing; use warp::chunk::{Chunk, ChunkKind, CompressionType}; use warp::r#type::chunk::TypeChunk; use warp::signature::chunk::SignatureChunk; @@ -33,10 +37,6 @@ use warp::signature::function::Function; use warp::target::Target; use warp::{WarpFile, WarpFileHeader}; -use crate::cache::cached_type_references; -use crate::convert::platform_to_target; -use crate::{build_function, INCLUDE_TAG_ICON, INCLUDE_TAG_NAME}; - /// Ensure we never exceed these many functions per signature chunk. /// /// This was added to fix running into the max table limit on certain files. @@ -538,15 +538,15 @@ impl WarpFileProcessor { Ok(result) => Some(Ok(result)), Err(ProcessingError::Cancelled) => Some(Err(ProcessingError::Cancelled)), Err(ProcessingError::NoPathToProjectFile(path)) => { - log::debug!("Skipping non-pulled project file: {:?}", path); + tracing::debug!("Skipping non-pulled project file: {:?}", path); None } Err(ProcessingError::SkippedFile(path)) => { - log::debug!("Skipping project file: {:?}", path); + tracing::debug!("Skipping project file: {:?}", path); None } Err(e) => { - log::error!("Project file processing error: {:?}", e); + tracing::error!("Project file processing error: {:?}", e); None } }) @@ -615,14 +615,14 @@ impl WarpFileProcessor { .with_extension("bndb"); if file_cache_path.exists() { // TODO: Update analysis and wait option - log::debug!("Analysis database found in cache: {:?}", file_cache_path); + tracing::debug!("Analysis database found in cache: {:?}", file_cache_path); binaryninja::load_with_options( &file_cache_path, self.request_analysis, Some(settings_str), ) } else { - log::debug!("No database found in cache: {:?}", file_cache_path); + tracing::debug!("No database found in cache: {:?}", file_cache_path); binaryninja::load_with_options(&path, self.request_analysis, Some(settings_str)) } } @@ -645,13 +645,13 @@ impl WarpFileProcessor { // TODO: We should also update the cache if analysis has changed! if !view.file().is_database_backed() { // Update the cache. - log::debug!("Saving analysis database to {:?}", file_cache_path); + tracing::debug!("Saving analysis database to {:?}", file_cache_path); if !view.file().create_database(&file_cache_path) { // TODO: We might want to error here... - log::warn!("Failed to save analysis database to {:?}", file_cache_path); + tracing::warn!("Failed to save analysis database to {:?}", file_cache_path); } } else { - log::debug!( + tracing::debug!( "Analysis database unchanged, skipping save to {:?}", file_cache_path ); @@ -699,7 +699,7 @@ impl WarpFileProcessor { // Process all the files. let unmerged_files: Result<Vec<_>, _> = files .into_par_iter() - .inspect(|path| log::debug!("Processing file: {:?}", path)) + .inspect(|path| tracing::debug!("Processing file: {:?}", path)) .map(|path| { self.check_cancelled()?; self.process(path) @@ -707,12 +707,12 @@ impl WarpFileProcessor { .filter_map(|res| match res { Ok(result) => Some(Ok(result)), Err(ProcessingError::SkippedFile(path)) => { - log::debug!("Skipping directory file: {:?}", path); + tracing::debug!("Skipping directory file: {:?}", path); None } Err(ProcessingError::Cancelled) => Some(Err(ProcessingError::Cancelled)), Err(e) => { - log::error!("Directory file processing error: {:?}", e); + tracing::error!("Directory file processing error: {:?}", e); None } }) @@ -752,7 +752,7 @@ impl WarpFileProcessor { std::io::copy(&mut entry, &mut output_file).map_err(ProcessingError::FileRead)?; entry_files.insert(output_path); } else { - log::debug!("Skipping already inserted entry: {}", normalized_name); + tracing::debug!("Skipping already inserted entry: {}", normalized_name); } } @@ -765,7 +765,7 @@ impl WarpFileProcessor { // Process all the entries. let unmerged_files: Result<Vec<_>, _> = entry_files .into_par_iter() - .inspect(|path| log::debug!("Processing entry: {:?}", path)) + .inspect(|path| tracing::debug!("Processing entry: {:?}", path)) .map(|path| { self.check_cancelled()?; self.process_file(path) @@ -773,12 +773,12 @@ impl WarpFileProcessor { .filter_map(|res| match res { Ok(result) => Some(Ok(result)), Err(ProcessingError::SkippedFile(path)) => { - log::debug!("Skipping archive file: {:?}", path); + tracing::debug!("Skipping archive file: {:?}", path); None } Err(ProcessingError::Cancelled) => Some(Err(ProcessingError::Cancelled)), Err(e) => { - log::error!("Archive file processing error: {:?}", e); + tracing::error!("Archive file processing error: {:?}", e); None } }) diff --git a/plugins/workflow_objc/Cargo.toml b/plugins/workflow_objc/Cargo.toml index 024d9d9a..da8ae2c6 100644 --- a/plugins/workflow_objc/Cargo.toml +++ b/plugins/workflow_objc/Cargo.toml @@ -13,7 +13,6 @@ demo = [] [dependencies] binaryninja = { workspace = true } binaryninjacore-sys.workspace = true -log = "0.4" dashmap = { version = "6.1", features = ["rayon"]} once_cell = "1.20" thiserror = "2.0" diff --git a/plugins/workflow_objc/src/activities/objc_msg_send_calls.rs b/plugins/workflow_objc/src/activities/objc_msg_send_calls.rs index b39c843c..86024047 100644 --- a/plugins/workflow_objc/src/activities/objc_msg_send_calls.rs +++ b/plugins/workflow_objc/src/activities/objc_msg_send_calls.rs @@ -7,6 +7,7 @@ use binaryninja::{ instruction::{InstructionHandler as _, LowLevelILInstruction, LowLevelILInstructionKind}, operation::{CallSsa, Operation}, }, + tracing, variable::PossibleValueSet, workflow::AnalysisContext, }; @@ -53,7 +54,7 @@ pub fn process(ac: &AnalysisContext) -> Result<(), Error> { Ok(true) => function_changed = true, Ok(_) => {} Err(err) => { - log::error!( + tracing::error!( "Error processing instruction at {:#x}: {}", insn.address(), err diff --git a/plugins/workflow_objc/src/activities/objc_msg_send_calls/rewrite_to_direct_call.rs b/plugins/workflow_objc/src/activities/objc_msg_send_calls/rewrite_to_direct_call.rs index 0ddf2945..56c2aa52 100644 --- a/plugins/workflow_objc/src/activities/objc_msg_send_calls/rewrite_to_direct_call.rs +++ b/plugins/workflow_objc/src/activities/objc_msg_send_calls/rewrite_to_direct_call.rs @@ -4,6 +4,7 @@ use binaryninja::{ function::{LowLevelILFunction, Mutable, NonSSA, SSA}, instruction::{InstructionHandler as _, LowLevelILInstruction, LowLevelILInstructionKind}, }, + tracing, }; use super::MessageSendType; @@ -48,7 +49,7 @@ pub fn process_call( Ok(()) } _ => { - log::error!( + tracing::error!( "Unexpected LLIL operation for objc_msgSend call at {:#x}", insn.address() ); diff --git a/plugins/workflow_objc/src/activities/remove_memory_management.rs b/plugins/workflow_objc/src/activities/remove_memory_management.rs index 3990f010..fdd76650 100644 --- a/plugins/workflow_objc/src/activities/remove_memory_management.rs +++ b/plugins/workflow_objc/src/activities/remove_memory_management.rs @@ -11,6 +11,7 @@ use binaryninja::{ lifting::LowLevelILLabel, LowLevelILRegisterKind, }, + tracing, variable::PossibleValueSet, workflow::AnalysisContext, }; @@ -176,7 +177,7 @@ pub fn process(ac: &AnalysisContext) -> Result<(), Error> { Ok(true) => function_changed = true, Ok(_) => {} Err(err) => { - log::error!( + tracing::error!( "Error processing instruction at {:#x}: {}", insn.address(), err diff --git a/plugins/workflow_objc/src/activities/super_init.rs b/plugins/workflow_objc/src/activities/super_init.rs index cfd3ecdc..1cdf8825 100644 --- a/plugins/workflow_objc/src/activities/super_init.rs +++ b/plugins/workflow_objc/src/activities/super_init.rs @@ -10,6 +10,7 @@ use binaryninja::{ MediumLevelILFunction, MediumLevelILLiftedInstruction, MediumLevelILLiftedInstructionKind, }, rc::Ref, + tracing, types::Type, variable::{RegisterValueType, SSAVariable}, workflow::AnalysisContext, @@ -148,7 +149,7 @@ fn return_type_for_super_init(call: &Call, view: &BinaryView) -> Option<Ref<Type src: super_param_var, }) = super_param.kind else { - log::debug!( + tracing::debug!( "Unhandled super paramater format at {:#0x} {:?}", super_param.address, super_param @@ -163,7 +164,7 @@ fn return_type_for_super_init(call: &Call, view: &BinaryView) -> Option<Ref<Type .function .ssa_variable_definition(&super_param_var) else { - log::debug!(" could not find definition of variable?"); + tracing::debug!(" could not find definition of variable?"); return None; }; @@ -171,7 +172,7 @@ fn return_type_for_super_init(call: &Call, view: &BinaryView) -> Option<Ref<Type MediumLevelILLiftedInstructionKind::SetVarSsa(LiftedSetVarSsa { src, .. }) => src, _ => { // The Swift compiler generates code that conditionally assigns to the receiver field of `objc_super`. - log::debug!( + tracing::debug!( "Unexpected variable definition kind at {:#0x} {:#x?}", super_param_def.address, super_param_def @@ -184,7 +185,7 @@ fn return_type_for_super_init(call: &Call, view: &BinaryView) -> Option<Ref<Type MediumLevelILLiftedInstructionKind::AddressOf(Var { src: src_var }) => src_var, _ => { // The Swift compiler generates code that initializes the `objc_super` variable in more varied ways. - log::debug!( + tracing::debug!( " found non-address-of variable definition of `objc_super` variable at {:#0x} {:?}", super_param_def.address, super_param_def @@ -223,7 +224,7 @@ fn return_type_for_super_init(call: &Call, view: &BinaryView) -> Option<Ref<Type // If there are zero, that likely means the assigned value was not a constant. Handling // that is above my pay grade. let &[super_class_ptr] = &super_class_constants[..] else { - log::debug!( + tracing::debug!( "Unexpected number of assignments to super class found for {:#0x}: {:#0x?}", src.address, super_class_constants @@ -232,7 +233,7 @@ fn return_type_for_super_init(call: &Call, view: &BinaryView) -> Option<Ref<Type }; let Some(super_class_symbol) = view.symbol_by_address(super_class_ptr) else { - log::debug!("No symbol found for super class at {super_class_ptr:#0x}"); + tracing::debug!("No symbol found for super class at {super_class_ptr:#0x}"); return None; }; @@ -240,12 +241,14 @@ fn return_type_for_super_init(call: &Call, view: &BinaryView) -> Option<Ref<Type let Some(class_name) = class_name_from_symbol_name(super_class_symbol_name.to_bytes().as_bstr()) else { - log::debug!("Unable to extract class name from symbol name: {super_class_symbol_name:?}"); + tracing::debug!( + "Unable to extract class name from symbol name: {super_class_symbol_name:?}" + ); return None; }; let Some(class_type) = view.type_by_name(class_name.to_str_lossy()) else { - log::debug!("No type found for class named {class_name:?}"); + tracing::debug!("No type found for class named {class_name:?}"); return None; }; diff --git a/plugins/workflow_objc/src/lib.rs b/plugins/workflow_objc/src/lib.rs index 8c859c6b..5b41b6d0 100644 --- a/plugins/workflow_objc/src/lib.rs +++ b/plugins/workflow_objc/src/lib.rs @@ -1,4 +1,4 @@ -use binaryninja::{add_optional_plugin_dependency, logger::Logger, settings::Settings}; +use binaryninja::{add_optional_plugin_dependency, settings::Settings, tracing}; mod activities; mod error; @@ -8,15 +8,11 @@ mod workflow; pub use error::Error; use metadata::GlobalState; -use log::LevelFilter; - fn plugin_init() -> bool { - Logger::new("Plugin.Objective-C") - .with_level(LevelFilter::Debug) - .init(); + binaryninja::tracing_init!("Plugin.Objective-C"); if workflow::register_activities().is_err() { - log::warn!("Failed to register Objective-C workflow"); + tracing::warn!("Failed to register Objective-C workflow"); return false; }; diff --git a/plugins/workflow_objc/src/metadata/global_state.rs b/plugins/workflow_objc/src/metadata/global_state.rs index 61104451..c6682a5f 100644 --- a/plugins/workflow_objc/src/metadata/global_state.rs +++ b/plugins/workflow_objc/src/metadata/global_state.rs @@ -1,10 +1,11 @@ +use binaryninja::file_metadata::SessionId; use binaryninja::{ binary_view::{BinaryView, BinaryViewBase, BinaryViewExt}, file_metadata::FileMetadata, metadata::Metadata, rc::Ref, settings::{QueryOptions, Settings}, - ObjectDestructor, + tracing, ObjectDestructor, }; use dashmap::DashMap; use once_cell::sync::Lazy; @@ -31,8 +32,8 @@ struct SelectorImplementations { sel_to_impl: HashMap<u64, Vec<u64>>, } -static VIEW_INFOS: Lazy<DashMap<usize, Arc<AnalysisInfo>>> = Lazy::new(DashMap::new); -static IGNORED_VIEWS: Lazy<DashMap<usize, bool>> = Lazy::new(DashMap::new); +static VIEW_INFOS: Lazy<DashMap<SessionId, Arc<AnalysisInfo>>> = Lazy::new(DashMap::new); +static IGNORED_VIEWS: Lazy<DashMap<SessionId, bool>> = Lazy::new(DashMap::new); struct ObjectLifetimeObserver; @@ -69,7 +70,7 @@ impl GlobalState { observer.register(); } - fn id(bv: &BinaryView) -> usize { + fn id(bv: &BinaryView) -> SessionId { bv.file().session_id() } @@ -159,7 +160,7 @@ impl AnalysisInfo { }; let version_meta = meta.get("version")?; if version_meta.get_unsigned_integer()? != 1 { - log::error!( + tracing::error!( "workflow_objc: Unexpected Objective-C metadata version. Expected 1, got {}.", version_meta.get_unsigned_integer()? ); @@ -192,7 +193,7 @@ impl AnalysisInfo { for item in &array { let item = item.get_array()?; if item.len() != 2 { - log::warn!( + tracing::warn!( "Expected selector implementation metadata to have 2 items, found {}", item.len() ); diff --git a/plugins/workflow_objc/src/workflow.rs b/plugins/workflow_objc/src/workflow.rs index 08a39042..13e3a71e 100644 --- a/plugins/workflow_objc/src/workflow.rs +++ b/plugins/workflow_objc/src/workflow.rs @@ -1,3 +1,4 @@ +use binaryninja::tracing; use binaryninja::workflow::{activity, Activity, AnalysisContext, Workflow}; use crate::{activities, error::WorkflowRegistrationError}; @@ -15,7 +16,7 @@ fn run<E: std::fmt::Debug>( ) -> impl Fn(&AnalysisContext) { move |ac| { if let Err(err) = func(ac) { - log::debug!("Error occurred while running activity: {err:#x?}"); + tracing::debug!("Error occurred while running activity: {err:#x?}"); } } } |
