diff --git a/rust/Cargo.toml b/rust/Cargo.toml index 2a03e5acfb..f186ec8930 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -2,7 +2,7 @@ name = "binaryninja" version = "0.1.0" authors = ["Ryan Snyder ", "Kyle Martin "] -edition = "2021" +edition = "2024" rust-version = "1.91.1" license = "Apache-2.0" diff --git a/rust/binaryninjacore-sys/Cargo.toml b/rust/binaryninjacore-sys/Cargo.toml index 296d3d68de..1754f70ae0 100644 --- a/rust/binaryninjacore-sys/Cargo.toml +++ b/rust/binaryninjacore-sys/Cargo.toml @@ -3,7 +3,7 @@ name = "binaryninjacore-sys" version = "0.1.0" authors = ["Ryan Snyder ", "Kyle Martin "] build = "build.rs" -edition = "2021" +edition = "2024" links = "binaryninjacore" license = "Apache-2.0" diff --git a/rust/binaryninjacore-sys/rustfmt.toml b/rust/binaryninjacore-sys/rustfmt.toml new file mode 100644 index 0000000000..8153a3d0b7 --- /dev/null +++ b/rust/binaryninjacore-sys/rustfmt.toml @@ -0,0 +1 @@ +style_edition = "2021" diff --git a/rust/rustfmt.toml b/rust/rustfmt.toml new file mode 100644 index 0000000000..8153a3d0b7 --- /dev/null +++ b/rust/rustfmt.toml @@ -0,0 +1 @@ +style_edition = "2021" diff --git a/rust/src/architecture.rs b/rust/src/architecture.rs index d96dc34b5f..4f76c18d61 100644 --- a/rust/src/architecture.rs +++ b/rust/src/architecture.rs @@ -621,7 +621,7 @@ impl FunctionLifterContext { function: *mut BNLowLevelILFunction, handle: *mut BNFunctionLifterContext, ) -> Self { - Self::from_raw_with_arch(function, handle, None) + unsafe { Self::from_raw_with_arch(function, handle, None) } } pub(crate) unsafe fn from_raw_with_arch( @@ -629,105 +629,107 @@ impl FunctionLifterContext { handle: *mut BNFunctionLifterContext, arch: Option, ) -> Self { - debug_assert!(!function.is_null()); - debug_assert!(!handle.is_null()); - let flc_ref = &*handle; - let platform = unsafe { Platform::ref_from_raw(BNNewPlatformReference(flc_ref.platform)) }; - let logger = unsafe { Logger::ref_from_raw(BNNewLoggerReference(flc_ref.logger)) }; - - let mut blocks = Vec::new(); - for i in 0..flc_ref.basicBlockCount { - let block = unsafe { - Some(BasicBlock::ref_from_raw( - BNNewBasicBlockReference(*flc_ref.basicBlocks.add(i)), - NativeBlock::new(), - )) - }; + unsafe { + debug_assert!(!function.is_null()); + debug_assert!(!handle.is_null()); + let flc_ref = &*handle; + let platform = { Platform::ref_from_raw(BNNewPlatformReference(flc_ref.platform)) }; + let logger = { Logger::ref_from_raw(BNNewLoggerReference(flc_ref.logger)) }; + + let mut blocks = Vec::new(); + for i in 0..flc_ref.basicBlockCount { + let block = { + Some(BasicBlock::ref_from_raw( + BNNewBasicBlockReference(*flc_ref.basicBlocks.add(i)), + NativeBlock::new(), + )) + }; - blocks.push(block.unwrap()); - } + blocks.push(block.unwrap()); + } - let raw_no_return_calls: &[BNArchitectureAndAddress] = - lifter_context_slice(flc_ref.noReturnCalls, flc_ref.noReturnCallsCount); - let no_return_calls: HashSet = - raw_no_return_calls.iter().map(Location::from).collect(); + let raw_no_return_calls: &[BNArchitectureAndAddress] = + lifter_context_slice(flc_ref.noReturnCalls, flc_ref.noReturnCallsCount); + let no_return_calls: HashSet = + raw_no_return_calls.iter().map(Location::from).collect(); - let raw_contextual_return_locs: &[BNArchitectureAndAddress] = unsafe { - lifter_context_slice( - flc_ref.contextualFunctionReturnLocations, - flc_ref.contextualFunctionReturnCount, - ) - }; - let raw_contextual_return_vals: &[bool] = unsafe { - lifter_context_slice( - flc_ref.contextualFunctionReturnValues, - flc_ref.contextualFunctionReturnCount, - ) - }; - let contextual_returns: HashMap = raw_contextual_return_locs - .iter() - .map(Location::from) - .zip(raw_contextual_return_vals.iter().copied()) - .collect(); + let raw_contextual_return_locs: &[BNArchitectureAndAddress] = { + lifter_context_slice( + flc_ref.contextualFunctionReturnLocations, + flc_ref.contextualFunctionReturnCount, + ) + }; + let raw_contextual_return_vals: &[bool] = { + lifter_context_slice( + flc_ref.contextualFunctionReturnValues, + flc_ref.contextualFunctionReturnCount, + ) + }; + let contextual_returns: HashMap = raw_contextual_return_locs + .iter() + .map(Location::from) + .zip(raw_contextual_return_vals.iter().copied()) + .collect(); - let inlined_remapping: HashMap = { - let raw_inline_remap_locs: &[BNArchitectureAndAddress] = lifter_context_slice( - flc_ref.inlinedRemappingKeys, - flc_ref.inlinedRemappingEntryCount, - ); + let inlined_remapping: HashMap = { + let raw_inline_remap_locs: &[BNArchitectureAndAddress] = lifter_context_slice( + flc_ref.inlinedRemappingKeys, + flc_ref.inlinedRemappingEntryCount, + ); - let raw_inline_remap_dests: &[BNArchitectureAndAddress] = lifter_context_slice( - flc_ref.inlinedRemappingValues, - flc_ref.inlinedRemappingEntryCount, - ); + let raw_inline_remap_dests: &[BNArchitectureAndAddress] = lifter_context_slice( + flc_ref.inlinedRemappingValues, + flc_ref.inlinedRemappingEntryCount, + ); - raw_inline_remap_locs - .iter() - .map(Location::from) - .zip(raw_inline_remap_dests.iter().map(Location::from)) - .collect() - }; + raw_inline_remap_locs + .iter() + .map(Location::from) + .zip(raw_inline_remap_dests.iter().map(Location::from)) + .collect() + }; - let mut user_indirect_branches: HashMap> = HashMap::new(); - let mut auto_indirect_branches: HashMap> = HashMap::new(); - for i in 0..flc_ref.indirectBranchesCount { - let entry = unsafe { *flc_ref.indirectBranches.add(i) }; - let src = Location::new( - Some(CoreArchitecture::from_raw(entry.sourceArch)), - entry.sourceAddr, - ); - let dest = Location::new( - Some(CoreArchitecture::from_raw(entry.destArch)), - entry.destAddr, - ); - if entry.autoDefined { - auto_indirect_branches.entry(src).or_default().insert(dest); - } else { - user_indirect_branches.entry(src).or_default().insert(dest); + let mut user_indirect_branches: HashMap> = HashMap::new(); + let mut auto_indirect_branches: HashMap> = HashMap::new(); + for i in 0..flc_ref.indirectBranchesCount { + let entry = { *flc_ref.indirectBranches.add(i) }; + let src = Location::new( + Some(CoreArchitecture::from_raw(entry.sourceArch)), + entry.sourceAddr, + ); + let dest = Location::new( + Some(CoreArchitecture::from_raw(entry.destArch)), + entry.destAddr, + ); + if entry.autoDefined { + auto_indirect_branches.entry(src).or_default().insert(dest); + } else { + user_indirect_branches.entry(src).or_default().insert(dest); + } } - } - let inlined_calls: HashSet = - lifter_context_slice(flc_ref.inlinedCalls, flc_ref.inlinedCallsCount) - .iter() - .copied() - .collect(); + let inlined_calls: HashSet = + lifter_context_slice(flc_ref.inlinedCalls, flc_ref.inlinedCallsCount) + .iter() + .copied() + .collect(); - FunctionLifterContext { - handle, - function: LowLevelILMutableFunction::ref_from_raw_with_arch( - BNNewLowLevelILFunctionReference(function), - arch, - ), - platform, - logger, - blocks, - no_return_calls, - contextual_returns, - inlined_remapping, - user_indirect_branches, - auto_indirect_branches, - inlined_calls, + FunctionLifterContext { + handle, + function: LowLevelILMutableFunction::ref_from_raw_with_arch( + BNNewLowLevelILFunctionReference(function), + arch, + ), + platform, + logger, + blocks, + no_return_calls, + contextual_returns, + inlined_remapping, + user_indirect_branches, + auto_indirect_branches, + inlined_calls, + } } } diff --git a/rust/src/architecture/basic_block.rs b/rust/src/architecture/basic_block.rs index ac5ce774b8..1f7b6758b5 100644 --- a/rust/src/architecture/basic_block.rs +++ b/rust/src/architecture/basic_block.rs @@ -33,119 +33,124 @@ pub struct BasicBlockAnalysisContext { impl BasicBlockAnalysisContext { pub unsafe fn from_raw(handle: *mut BNBasicBlockAnalysisContext) -> Self { - debug_assert!(!handle.is_null()); + unsafe { + debug_assert!(!handle.is_null()); - let ctx_ref = &*handle; + let ctx_ref = &*handle; - let raw_indirect_branches: &[BNIndirectBranchInfo] = - std::slice::from_raw_parts(ctx_ref.indirectBranches, ctx_ref.indirectBranchesCount); - let indirect_branches: Vec = raw_indirect_branches - .iter() - .map(IndirectBranchInfo::from) - .collect(); - - let raw_indirect_no_return_calls: &[BNArchitectureAndAddress] = std::slice::from_raw_parts( - ctx_ref.indirectNoReturnCalls, - ctx_ref.indirectNoReturnCallsCount, - ); - let indirect_no_return_calls: HashSet = raw_indirect_no_return_calls - .iter() - .map(Location::from) - .collect(); - - let raw_contextual_return_locs: &[BNArchitectureAndAddress] = unsafe { - std::slice::from_raw_parts( - ctx_ref.contextualFunctionReturnLocations, - ctx_ref.contextualFunctionReturnCount, - ) - }; - let raw_contextual_return_vals: &[bool] = unsafe { - std::slice::from_raw_parts( - ctx_ref.contextualFunctionReturnValues, - ctx_ref.contextualFunctionReturnCount, - ) - }; - let contextual_returns: HashMap = raw_contextual_return_locs - .iter() - .map(Location::from) - .zip(raw_contextual_return_vals.iter().copied()) - .collect(); + let raw_indirect_branches: &[BNIndirectBranchInfo] = + std::slice::from_raw_parts(ctx_ref.indirectBranches, ctx_ref.indirectBranchesCount); + let indirect_branches: Vec = raw_indirect_branches + .iter() + .map(IndirectBranchInfo::from) + .collect(); - // The lists below this are out params and are possibly not initialized. - let raw_direct_ref_sources: &[BNArchitectureAndAddress] = match ctx_ref - .directRefSources - .is_null() - { - true => &[], - false => std::slice::from_raw_parts(ctx_ref.directRefSources, ctx_ref.directRefCount), - }; - let raw_direct_ref_targets: &[u64] = match ctx_ref.directRefTargets.is_null() { - true => &[], - false => std::slice::from_raw_parts(ctx_ref.directRefTargets, ctx_ref.directRefCount), - }; - let direct_code_references: HashMap = raw_direct_ref_targets - .iter() - .copied() - .zip(raw_direct_ref_sources.iter().map(Location::from)) - .collect(); + let raw_indirect_no_return_calls: &[BNArchitectureAndAddress] = + std::slice::from_raw_parts( + ctx_ref.indirectNoReturnCalls, + ctx_ref.indirectNoReturnCallsCount, + ); + let indirect_no_return_calls: HashSet = raw_indirect_no_return_calls + .iter() + .map(Location::from) + .collect(); - let raw_direct_no_return_calls: &[BNArchitectureAndAddress] = - match ctx_ref.directNoReturnCalls.is_null() { - true => &[], - false => std::slice::from_raw_parts( - ctx_ref.directNoReturnCalls, - ctx_ref.directNoReturnCallsCount, - ), + let raw_contextual_return_locs: &[BNArchitectureAndAddress] = { + std::slice::from_raw_parts( + ctx_ref.contextualFunctionReturnLocations, + ctx_ref.contextualFunctionReturnCount, + ) }; - let direct_no_return_calls: HashSet = raw_direct_no_return_calls - .iter() - .map(Location::from) - .collect(); - - let raw_halted_disassembly_address: &[BNArchitectureAndAddress] = - match ctx_ref.haltedDisassemblyAddresses.is_null() { - true => &[], - false => std::slice::from_raw_parts( - ctx_ref.haltedDisassemblyAddresses, - ctx_ref.haltedDisassemblyAddressesCount, - ), + let raw_contextual_return_vals: &[bool] = { + std::slice::from_raw_parts( + ctx_ref.contextualFunctionReturnValues, + ctx_ref.contextualFunctionReturnCount, + ) }; - let halted_disassembly_addresses: HashSet = raw_halted_disassembly_address - .iter() - .map(Location::from) - .collect(); + let contextual_returns: HashMap = raw_contextual_return_locs + .iter() + .map(Location::from) + .zip(raw_contextual_return_vals.iter().copied()) + .collect(); - let raw_inlined_unresolved_indirect_branches: &[BNArchitectureAndAddress] = - match ctx_ref.inlinedUnresolvedIndirectBranches.is_null() { + // The lists below this are out params and are possibly not initialized. + let raw_direct_ref_sources: &[BNArchitectureAndAddress] = + match ctx_ref.directRefSources.is_null() { + true => &[], + false => { + std::slice::from_raw_parts(ctx_ref.directRefSources, ctx_ref.directRefCount) + } + }; + let raw_direct_ref_targets: &[u64] = match ctx_ref.directRefTargets.is_null() { true => &[], - false => std::slice::from_raw_parts( - ctx_ref.inlinedUnresolvedIndirectBranches, - ctx_ref.inlinedUnresolvedIndirectBranchCount, - ), + false => { + std::slice::from_raw_parts(ctx_ref.directRefTargets, ctx_ref.directRefCount) + } }; - let inlined_unresolved_indirect_branches: HashSet = - raw_inlined_unresolved_indirect_branches + let direct_code_references: HashMap = raw_direct_ref_targets + .iter() + .copied() + .zip(raw_direct_ref_sources.iter().map(Location::from)) + .collect(); + + let raw_direct_no_return_calls: &[BNArchitectureAndAddress] = + match ctx_ref.directNoReturnCalls.is_null() { + true => &[], + false => std::slice::from_raw_parts( + ctx_ref.directNoReturnCalls, + ctx_ref.directNoReturnCallsCount, + ), + }; + let direct_no_return_calls: HashSet = raw_direct_no_return_calls .iter() .map(Location::from) .collect(); - BasicBlockAnalysisContext { - handle, - contextual_returns_dirty: false, - indirect_branches, - indirect_no_return_calls, - analysis_skip_override: ctx_ref.analysisSkipOverride, - guided_analysis_mode: ctx_ref.guidedAnalysisMode, - trigger_guided_on_invalid_instruction: ctx_ref.triggerGuidedOnInvalidInstruction, - translate_tail_calls: ctx_ref.translateTailCalls, - disallow_branch_to_string: ctx_ref.disallowBranchToString, - max_function_size: ctx_ref.maxFunctionSize, - max_size_reached: ctx_ref.maxSizeReached, - contextual_returns, - direct_code_references, - direct_no_return_calls, - halted_disassembly_addresses, - inlined_unresolved_indirect_branches, + let raw_halted_disassembly_address: &[BNArchitectureAndAddress] = + match ctx_ref.haltedDisassemblyAddresses.is_null() { + true => &[], + false => std::slice::from_raw_parts( + ctx_ref.haltedDisassemblyAddresses, + ctx_ref.haltedDisassemblyAddressesCount, + ), + }; + let halted_disassembly_addresses: HashSet = raw_halted_disassembly_address + .iter() + .map(Location::from) + .collect(); + + let raw_inlined_unresolved_indirect_branches: &[BNArchitectureAndAddress] = + match ctx_ref.inlinedUnresolvedIndirectBranches.is_null() { + true => &[], + false => std::slice::from_raw_parts( + ctx_ref.inlinedUnresolvedIndirectBranches, + ctx_ref.inlinedUnresolvedIndirectBranchCount, + ), + }; + let inlined_unresolved_indirect_branches: HashSet = + raw_inlined_unresolved_indirect_branches + .iter() + .map(Location::from) + .collect(); + + BasicBlockAnalysisContext { + handle, + contextual_returns_dirty: false, + indirect_branches, + indirect_no_return_calls, + analysis_skip_override: ctx_ref.analysisSkipOverride, + guided_analysis_mode: ctx_ref.guidedAnalysisMode, + trigger_guided_on_invalid_instruction: ctx_ref.triggerGuidedOnInvalidInstruction, + translate_tail_calls: ctx_ref.translateTailCalls, + disallow_branch_to_string: ctx_ref.disallowBranchToString, + max_function_size: ctx_ref.maxFunctionSize, + max_size_reached: ctx_ref.maxSizeReached, + contextual_returns, + direct_code_references, + direct_no_return_calls, + halted_disassembly_addresses, + inlined_unresolved_indirect_branches, + } } } diff --git a/rust/src/architecture/branches.rs b/rust/src/architecture/branches.rs index a6810b345b..271fde961f 100644 --- a/rust/src/architecture/branches.rs +++ b/rust/src/architecture/branches.rs @@ -150,7 +150,7 @@ impl CoreArrayProvider for IndirectBranchInfo { unsafe impl CoreArrayProviderInner for IndirectBranchInfo { unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { - BNFreeIndirectBranchList(raw) + unsafe { BNFreeIndirectBranchList(raw) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { diff --git a/rust/src/architecture/register.rs b/rust/src/architecture/register.rs index 0f76084422..8314437e6b 100644 --- a/rust/src/architecture/register.rs +++ b/rust/src/architecture/register.rs @@ -311,7 +311,7 @@ impl CoreArrayProvider for CoreRegister { unsafe impl CoreArrayProviderInner for CoreRegister { unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { - BNFreeRegisterList(raw) + unsafe { BNFreeRegisterList(raw) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { diff --git a/rust/src/background_task.rs b/rust/src/background_task.rs index 1d902c3ad4..bca6c62250 100644 --- a/rust/src/background_task.rs +++ b/rust/src/background_task.rs @@ -141,13 +141,17 @@ impl Debug for BackgroundTask { unsafe impl RefCountable for BackgroundTask { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: BNNewBackgroundTaskReference(handle.handle), - }) + unsafe { + Ref::new(Self { + handle: BNNewBackgroundTaskReference(handle.handle), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeBackgroundTask(handle.handle); + unsafe { + BNFreeBackgroundTask(handle.handle); + } } } @@ -159,10 +163,12 @@ impl CoreArrayProvider for BackgroundTask { unsafe impl CoreArrayProviderInner for BackgroundTask { unsafe fn free(raw: *mut *mut BNBackgroundTask, count: usize, _context: &()) { - BNFreeBackgroundTaskList(raw, count); + unsafe { + BNFreeBackgroundTaskList(raw, count); + } } unsafe fn wrap_raw<'a>(raw: &'a *mut BNBackgroundTask, context: &'a ()) -> Self::Wrapped<'a> { - Guard::new(BackgroundTask::from_raw(*raw), context) + unsafe { Guard::new(BackgroundTask::from_raw(*raw), context) } } } diff --git a/rust/src/base_detection.rs b/rust/src/base_detection.rs index ceeb6737fc..056d1ebc3d 100644 --- a/rust/src/base_detection.rs +++ b/rust/src/base_detection.rs @@ -61,13 +61,15 @@ impl CoreArrayProvider for BaseAddressDetectionReason { unsafe impl CoreArrayProviderInner for BaseAddressDetectionReason { unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { - BNFreeBaseAddressDetectionReasons(raw) + unsafe { BNFreeBaseAddressDetectionReasons(raw) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { - // SAFETY BNBaseAddressDetectionReason and BaseAddressDetectionReason - // are transparent - std::mem::transmute::<&BNBaseAddressDetectionReason, &BaseAddressDetectionReason>(raw) + unsafe { + // SAFETY BNBaseAddressDetectionReason and BaseAddressDetectionReason + // are transparent + std::mem::transmute::<&BNBaseAddressDetectionReason, &BaseAddressDetectionReason>(raw) + } } } @@ -82,7 +84,7 @@ impl BaseAddressDetection { #[allow(clippy::mut_from_ref)] pub(crate) unsafe fn as_raw(&self) -> &mut BNBaseAddressDetection { - &mut *self.handle.as_ptr() + unsafe { &mut *self.handle.as_ptr() } } /// Indicates whether base address detection analysis was aborted early diff --git a/rust/src/basic_block.rs b/rust/src/basic_block.rs index 60ce2416be..2d3b320292 100644 --- a/rust/src/basic_block.rs +++ b/rust/src/basic_block.rs @@ -58,32 +58,36 @@ impl<'a, C: 'a + BlockContext> CoreArrayProvider for Edge<'a, C> { unsafe impl<'a, C: 'a + BlockContext> CoreArrayProviderInner for Edge<'a, C> { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeBasicBlockEdgeList(raw, count); + unsafe { + BNFreeBasicBlockEdgeList(raw, count); + } } unsafe fn wrap_raw<'b>(raw: &'b Self::Raw, context: &'b Self::Context) -> Self::Wrapped<'b> { - let edge_target = Guard::new( - BasicBlock::from_raw(raw.target, context.orig_block.context.clone()), - raw, - ); - let orig_block = Guard::new( - BasicBlock::from_raw( - context.orig_block.handle, - context.orig_block.context.clone(), - ), - raw, - ); - - let (source, target) = match context.dir { - EdgeDirection::Incoming => (edge_target, orig_block), - EdgeDirection::Outgoing => (orig_block, edge_target), - }; - - Edge { - branch: raw.type_, - back_edge: raw.backEdge, - source, - target, + unsafe { + let edge_target = Guard::new( + BasicBlock::from_raw(raw.target, context.orig_block.context.clone()), + raw, + ); + let orig_block = Guard::new( + BasicBlock::from_raw( + context.orig_block.handle, + context.orig_block.context.clone(), + ), + raw, + ); + + let (source, target) = match context.dir { + EdgeDirection::Incoming => (edge_target, orig_block), + EdgeDirection::Outgoing => (orig_block, edge_target), + }; + + Edge { + branch: raw.type_, + back_edge: raw.backEdge, + source, + target, + } } } } @@ -134,7 +138,9 @@ impl CoreArrayProvider for PendingBasicBlockEdge { unsafe impl CoreArrayProviderInner for PendingBasicBlockEdge { unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { - BNFreePendingBasicBlockEdgeList(raw); + unsafe { + BNFreePendingBasicBlockEdgeList(raw); + } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { @@ -170,7 +176,7 @@ impl BasicBlock { } pub(crate) unsafe fn ref_from_raw(handle: *mut BNBasicBlock, context: C) -> Ref { - Ref::new(Self::from_raw(handle, context)) + unsafe { Ref::new(Self::from_raw(handle, context)) } } // TODO native bb vs il bbs @@ -459,14 +465,18 @@ impl ToOwned for BasicBlock { unsafe impl RefCountable for BasicBlock { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: BNNewBasicBlockReference(handle.handle), - context: handle.context.clone(), - }) + unsafe { + Ref::new(Self { + handle: BNNewBasicBlockReference(handle.handle), + context: handle.context.clone(), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeBasicBlock(handle.handle); + unsafe { + BNFreeBasicBlock(handle.handle); + } } } @@ -481,11 +491,13 @@ impl CoreArrayProvider for BasicBlock { unsafe impl CoreArrayProviderInner for BasicBlock { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeBasicBlockList(raw, count); + unsafe { + BNFreeBasicBlockList(raw, count); + } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - Guard::new(BasicBlock::from_raw(*raw, context.clone()), context) + unsafe { Guard::new(BasicBlock::from_raw(*raw, context.clone()), context) } } } diff --git a/rust/src/binary_view.rs b/rust/src/binary_view.rs index 3d1c243d57..c26a8c67eb 100644 --- a/rust/src/binary_view.rs +++ b/rust/src/binary_view.rs @@ -410,11 +410,13 @@ impl CoreArrayProvider for BinaryViewType { unsafe impl CoreArrayProviderInner for BinaryViewType { unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { - BNFreeBinaryViewTypeList(raw); + unsafe { + BNFreeBinaryViewTypeList(raw); + } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { - Guard::new(BinaryViewType::from_raw(*raw), &()) + unsafe { Guard::new(BinaryViewType::from_raw(*raw), &()) } } } @@ -648,8 +650,10 @@ impl BinaryView { } pub(crate) unsafe fn ref_from_raw(handle: *mut BNBinaryView) -> Ref { - debug_assert!(!handle.is_null()); - Ref::new(Self { handle }) + unsafe { + debug_assert!(!handle.is_null()); + Ref::new(Self { handle }) + } } /// Create a core instance of the [`CustomBinaryView`]. @@ -874,9 +878,11 @@ impl BinaryView { offset: u64, data: *mut BNDataBuffer, ) -> bool { - let f = ctx as *mut C; - let buffer = DataBuffer::from_raw(data); - (*f)(offset, &buffer) + unsafe { + let f = ctx as *mut C; + let buffer = DataBuffer::from_raw(data); + (*f)(offset, &buffer) + } } let query = query.to_json().to_cstr(); @@ -3089,13 +3095,17 @@ impl BinaryViewBase for BinaryView { unsafe impl RefCountable for BinaryView { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: BNNewViewReference(handle.handle), - }) + unsafe { + Ref::new(Self { + handle: BNNewViewReference(handle.handle), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeBinaryView(handle.handle); + unsafe { + BNFreeBinaryView(handle.handle); + } } } @@ -3187,10 +3197,12 @@ where ctx: *mut c_void, view: *mut BNBinaryView, ) { - ffi_wrap!("EventHandler::on_event", { - let context = unsafe { &*(ctx as *const Handler) }; - context.on_event(&BinaryView::ref_from_raw(BNNewViewReference(view))); - }) + unsafe { + ffi_wrap!("EventHandler::on_event", { + let context = { &*(ctx as *const Handler) }; + context.on_event(&BinaryView::ref_from_raw(BNNewViewReference(view))); + }) + } } let boxed = Box::new(handler); @@ -3220,7 +3232,7 @@ impl CoreArrayProvider for CommentReference { unsafe impl CoreArrayProviderInner for CommentReference { unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { - BNFreeAddressList(raw) + unsafe { BNFreeAddressList(raw) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { @@ -3263,7 +3275,7 @@ impl CoreArrayProvider for StringReference { unsafe impl CoreArrayProviderInner for StringReference { unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { - BNFreeStringReferenceList(raw) + unsafe { BNFreeStringReferenceList(raw) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { @@ -3303,7 +3315,9 @@ impl CoreArrayProvider for AddressRange { unsafe impl CoreArrayProviderInner for AddressRange { unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { - BNFreeAddressRanges(raw); + unsafe { + BNFreeAddressRanges(raw); + } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { diff --git a/rust/src/calling_convention.rs b/rust/src/calling_convention.rs index 04ff345275..4327139c0b 100644 --- a/rust/src/calling_convention.rs +++ b/rust/src/calling_convention.rs @@ -342,15 +342,19 @@ where } unsafe fn from_ctxt<'a, C: CallingConvention>(ctxt: *mut c_void) -> &'a C { - (*(ctxt as *mut CustomCallingConventionContext)) - .cc - .assume_init_ref() + unsafe { + (*(ctxt as *mut CustomCallingConventionContext)) + .cc + .assume_init_ref() + } } unsafe fn register_list(regs: Vec, count: *mut usize) -> *mut u32 { - let regs: Box<[u32]> = regs.iter().map(|r| r.0).collect(); - *count = regs.len(); - Box::leak(regs).as_mut_ptr() + unsafe { + let regs: Box<[u32]> = regs.iter().map(|r| r.0).collect(); + *count = regs.len(); + Box::leak(regs).as_mut_ptr() + } } unsafe fn permitted_registers( @@ -1101,10 +1105,12 @@ impl CoreCallingConvention { handle: *mut BNCallingConvention, arch: CoreArchitecture, ) -> Ref { - Ref::new(CoreCallingConvention { - handle, - arch_handle: arch, - }) + unsafe { + Ref::new(CoreCallingConvention { + handle, + arch_handle: arch, + }) + } } pub fn name(&self) -> String { @@ -1957,14 +1963,18 @@ impl ToOwned for CoreCallingConvention { unsafe impl RefCountable for CoreCallingConvention { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: BNNewCallingConventionReference(handle.handle), - arch_handle: handle.arch_handle, - }) + unsafe { + Ref::new(Self { + handle: BNNewCallingConventionReference(handle.handle), + arch_handle: handle.arch_handle, + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeCallingConvention(handle.handle); + unsafe { + BNFreeCallingConvention(handle.handle); + } } } @@ -1976,17 +1986,21 @@ impl CoreArrayProvider for CoreCallingConvention { unsafe impl CoreArrayProviderInner for CoreCallingConvention { unsafe fn free(raw: *mut *mut BNCallingConvention, count: usize, _content: &Self::Context) { - BNFreeCallingConventionList(raw, count); + unsafe { + BNFreeCallingConventionList(raw, count); + } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - Guard::new( - CoreCallingConvention { - handle: *raw, - arch_handle: *context, - }, - context, - ) + unsafe { + Guard::new( + CoreCallingConvention { + handle: *raw, + arch_handle: *context, + }, + context, + ) + } } } diff --git a/rust/src/collaboration/changeset.rs b/rust/src/collaboration/changeset.rs index cce750e6e0..383b791cbf 100644 --- a/rust/src/collaboration/changeset.rs +++ b/rust/src/collaboration/changeset.rs @@ -21,7 +21,7 @@ impl Changeset { #[allow(unused)] pub(crate) unsafe fn ref_from_raw(handle: NonNull) -> Ref { - Ref::new(Self { handle }) + unsafe { Ref::new(Self { handle }) } } /// Owning database for snapshots @@ -81,14 +81,18 @@ impl ToOwned for Changeset { unsafe impl RefCountable for Changeset { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: NonNull::new(BNNewCollaborationChangesetReference(handle.handle.as_ptr())) - .unwrap(), - }) + unsafe { + Ref::new(Self { + handle: NonNull::new(BNNewCollaborationChangesetReference(handle.handle.as_ptr())) + .unwrap(), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeCollaborationChangeset(handle.handle.as_ptr()); + unsafe { + BNFreeCollaborationChangeset(handle.handle.as_ptr()); + } } } @@ -100,11 +104,13 @@ impl CoreArrayProvider for Changeset { unsafe impl CoreArrayProviderInner for Changeset { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeCollaborationChangesetList(raw, count) + unsafe { BNFreeCollaborationChangesetList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - let raw_ptr = NonNull::new(*raw).unwrap(); - Guard::new(Self::from_raw(raw_ptr), context) + unsafe { + let raw_ptr = NonNull::new(*raw).unwrap(); + Guard::new(Self::from_raw(raw_ptr), context) + } } } diff --git a/rust/src/collaboration/file.rs b/rust/src/collaboration/file.rs index 84860dd828..416344dd84 100644 --- a/rust/src/collaboration/file.rs +++ b/rust/src/collaboration/file.rs @@ -33,7 +33,7 @@ impl RemoteFile { } pub(crate) unsafe fn ref_from_raw(handle: NonNull) -> Ref { - Ref::new(Self { handle }) + unsafe { Ref::new(Self { handle }) } } /// Look up the remote File for a local database, or None if there is no matching @@ -600,13 +600,17 @@ unsafe impl Sync for RemoteFile {} unsafe impl RefCountable for RemoteFile { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: NonNull::new(BNNewRemoteFileReference(handle.handle.as_ptr())).unwrap(), - }) + unsafe { + Ref::new(Self { + handle: NonNull::new(BNNewRemoteFileReference(handle.handle.as_ptr())).unwrap(), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeRemoteFile(handle.handle.as_ptr()); + unsafe { + BNFreeRemoteFile(handle.handle.as_ptr()); + } } } @@ -618,11 +622,13 @@ impl CoreArrayProvider for RemoteFile { unsafe impl CoreArrayProviderInner for RemoteFile { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeRemoteFileList(raw, count) + unsafe { BNFreeRemoteFileList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - let raw_ptr = NonNull::new(*raw).unwrap(); - Guard::new(Self::from_raw(raw_ptr), context) + unsafe { + let raw_ptr = NonNull::new(*raw).unwrap(); + Guard::new(Self::from_raw(raw_ptr), context) + } } } diff --git a/rust/src/collaboration/folder.rs b/rust/src/collaboration/folder.rs index 3ae84b6424..df26567dda 100644 --- a/rust/src/collaboration/folder.rs +++ b/rust/src/collaboration/folder.rs @@ -18,7 +18,7 @@ impl RemoteFolder { } pub(crate) unsafe fn ref_from_raw(handle: NonNull) -> Ref { - Ref::new(Self { handle }) + unsafe { Ref::new(Self { handle }) } } // TODO: Rename to local folder? @@ -157,13 +157,17 @@ unsafe impl Sync for RemoteFolder {} unsafe impl RefCountable for RemoteFolder { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: NonNull::new(BNNewRemoteFolderReference(handle.handle.as_ptr())).unwrap(), - }) + unsafe { + Ref::new(Self { + handle: NonNull::new(BNNewRemoteFolderReference(handle.handle.as_ptr())).unwrap(), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeRemoteFolder(handle.handle.as_ptr()); + unsafe { + BNFreeRemoteFolder(handle.handle.as_ptr()); + } } } @@ -175,11 +179,13 @@ impl CoreArrayProvider for RemoteFolder { unsafe impl CoreArrayProviderInner for RemoteFolder { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeRemoteFolderList(raw, count) + unsafe { BNFreeRemoteFolderList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - let raw_ptr = NonNull::new(*raw).unwrap(); - Guard::new(Self::from_raw(raw_ptr), context) + unsafe { + let raw_ptr = NonNull::new(*raw).unwrap(); + Guard::new(Self::from_raw(raw_ptr), context) + } } } diff --git a/rust/src/collaboration/group.rs b/rust/src/collaboration/group.rs index e3ee82d023..55ce3b0395 100644 --- a/rust/src/collaboration/group.rs +++ b/rust/src/collaboration/group.rs @@ -18,7 +18,7 @@ impl RemoteGroup { } pub(crate) unsafe fn ref_from_raw(handle: NonNull) -> Ref { - Ref::new(Self { handle }) + unsafe { Ref::new(Self { handle }) } } /// Owning Remote @@ -110,13 +110,18 @@ impl ToOwned for RemoteGroup { unsafe impl RefCountable for RemoteGroup { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: NonNull::new(BNNewCollaborationGroupReference(handle.handle.as_ptr())).unwrap(), - }) + unsafe { + Ref::new(Self { + handle: NonNull::new(BNNewCollaborationGroupReference(handle.handle.as_ptr())) + .unwrap(), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeCollaborationGroup(handle.handle.as_ptr()); + unsafe { + BNFreeCollaborationGroup(handle.handle.as_ptr()); + } } } @@ -128,12 +133,14 @@ impl CoreArrayProvider for RemoteGroup { unsafe impl CoreArrayProviderInner for RemoteGroup { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeCollaborationGroupList(raw, count) + unsafe { BNFreeCollaborationGroupList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - let raw_ptr = NonNull::new(*raw).unwrap(); - Guard::new(Self::from_raw(raw_ptr), context) + unsafe { + let raw_ptr = NonNull::new(*raw).unwrap(); + Guard::new(Self::from_raw(raw_ptr), context) + } } } @@ -155,7 +162,7 @@ impl CoreArrayProvider for GroupId { unsafe impl CoreArrayProviderInner for GroupId { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNCollaborationFreeIdList(raw, count) + unsafe { BNCollaborationFreeIdList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { diff --git a/rust/src/collaboration/merge.rs b/rust/src/collaboration/merge.rs index aea117015d..e698ac586e 100644 --- a/rust/src/collaboration/merge.rs +++ b/rust/src/collaboration/merge.rs @@ -21,7 +21,7 @@ impl MergeConflict { #[allow(unused)] pub(crate) unsafe fn ref_from_raw(handle: NonNull) -> Ref { - Ref::new(Self { handle }) + unsafe { Ref::new(Self { handle }) } } /// Database backing all snapshots in the merge conflict @@ -160,14 +160,18 @@ impl ToOwned for MergeConflict { unsafe impl RefCountable for MergeConflict { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: NonNull::new(BNNewAnalysisMergeConflictReference(handle.handle.as_ptr())) - .unwrap(), - }) + unsafe { + Ref::new(Self { + handle: NonNull::new(BNNewAnalysisMergeConflictReference(handle.handle.as_ptr())) + .unwrap(), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeAnalysisMergeConflict(handle.handle.as_ptr()); + unsafe { + BNFreeAnalysisMergeConflict(handle.handle.as_ptr()); + } } } @@ -179,11 +183,13 @@ impl CoreArrayProvider for MergeConflict { unsafe impl CoreArrayProviderInner for MergeConflict { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeAnalysisMergeConflictList(raw, count) + unsafe { BNFreeAnalysisMergeConflictList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - let raw_ptr = NonNull::new(*raw).unwrap(); - Guard::new(Self::from_raw(raw_ptr), context) + unsafe { + let raw_ptr = NonNull::new(*raw).unwrap(); + Guard::new(Self::from_raw(raw_ptr), context) + } } } diff --git a/rust/src/collaboration/permission.rs b/rust/src/collaboration/permission.rs index 76b1eba3ca..75d4897c63 100644 --- a/rust/src/collaboration/permission.rs +++ b/rust/src/collaboration/permission.rs @@ -19,7 +19,7 @@ impl Permission { } pub(crate) unsafe fn ref_from_raw(handle: NonNull) -> Ref { - Ref::new(Self { handle }) + unsafe { Ref::new(Self { handle }) } } pub fn remote(&self) -> Result, ()> { @@ -128,16 +128,20 @@ impl ToOwned for Permission { unsafe impl RefCountable for Permission { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: NonNull::new(BNNewCollaborationPermissionReference( - handle.handle.as_ptr(), - )) - .unwrap(), - }) + unsafe { + Ref::new(Self { + handle: NonNull::new(BNNewCollaborationPermissionReference( + handle.handle.as_ptr(), + )) + .unwrap(), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeCollaborationPermission(handle.handle.as_ptr()); + unsafe { + BNFreeCollaborationPermission(handle.handle.as_ptr()); + } } } @@ -149,11 +153,13 @@ impl CoreArrayProvider for Permission { unsafe impl CoreArrayProviderInner for Permission { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeCollaborationPermissionList(raw, count) + unsafe { BNFreeCollaborationPermissionList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - let raw_ptr = NonNull::new(*raw).unwrap(); - Guard::new(Self::from_raw(raw_ptr), context) + unsafe { + let raw_ptr = NonNull::new(*raw).unwrap(); + Guard::new(Self::from_raw(raw_ptr), context) + } } } diff --git a/rust/src/collaboration/project.rs b/rust/src/collaboration/project.rs index 8ea7c028b5..a44c68f18e 100644 --- a/rust/src/collaboration/project.rs +++ b/rust/src/collaboration/project.rs @@ -30,7 +30,7 @@ impl RemoteProject { } pub(crate) unsafe fn ref_from_raw(handle: NonNull) -> Ref { - Ref::new(Self { handle }) + unsafe { Ref::new(Self { handle }) } } /// Determine if the project is open (it needs to be opened before you can access its files) @@ -900,13 +900,17 @@ unsafe impl Sync for RemoteProject {} unsafe impl RefCountable for RemoteProject { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: NonNull::new(BNNewRemoteProjectReference(handle.handle.as_ptr())).unwrap(), - }) + unsafe { + Ref::new(Self { + handle: NonNull::new(BNNewRemoteProjectReference(handle.handle.as_ptr())).unwrap(), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeRemoteProject(handle.handle.as_ptr()); + unsafe { + BNFreeRemoteProject(handle.handle.as_ptr()); + } } } @@ -918,11 +922,13 @@ impl CoreArrayProvider for RemoteProject { unsafe impl CoreArrayProviderInner for RemoteProject { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeRemoteProjectList(raw, count) + unsafe { BNFreeRemoteProjectList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - let raw_ptr = NonNull::new(*raw).unwrap(); - Guard::new(Self::from_raw(raw_ptr), context) + unsafe { + let raw_ptr = NonNull::new(*raw).unwrap(); + Guard::new(Self::from_raw(raw_ptr), context) + } } } diff --git a/rust/src/collaboration/remote.rs b/rust/src/collaboration/remote.rs index 247ab36876..f4dfe67b15 100644 --- a/rust/src/collaboration/remote.rs +++ b/rust/src/collaboration/remote.rs @@ -25,7 +25,7 @@ impl Remote { } pub(crate) unsafe fn ref_from_raw(handle: NonNull) -> Ref { - Ref::new(Self { handle }) + unsafe { Ref::new(Self { handle }) } } /// Create a Remote and add it to the list of known remotes (saved to Settings) @@ -784,11 +784,14 @@ impl PartialEq for Remote { // don't pull metadata if we hand't yet if !self.has_loaded_metadata() || other.has_loaded_metadata() { self.address() == other.address() - } else if let Some((slf, oth)) = self.unique_id().ok().zip(other.unique_id().ok()) { - slf == oth } else { - // falback to comparing address - self.address() == other.address() + match self.unique_id().ok().zip(other.unique_id().ok()) { + Some((slf, oth)) => slf == oth, + _ => { + // falback to comparing address + self.address() == other.address() + } + } } } } @@ -804,13 +807,17 @@ impl ToOwned for Remote { unsafe impl RefCountable for Remote { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: NonNull::new(BNNewRemoteReference(handle.handle.as_ptr())).unwrap(), - }) + unsafe { + Ref::new(Self { + handle: NonNull::new(BNNewRemoteReference(handle.handle.as_ptr())).unwrap(), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeRemote(handle.handle.as_ptr()); + unsafe { + BNFreeRemote(handle.handle.as_ptr()); + } } } @@ -822,12 +829,14 @@ impl CoreArrayProvider for Remote { unsafe impl CoreArrayProviderInner for Remote { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeRemoteList(raw, count) + unsafe { BNFreeRemoteList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - let raw_ptr = NonNull::new(*raw).unwrap(); - Guard::new(Self::from_raw(raw_ptr), context) + unsafe { + let raw_ptr = NonNull::new(*raw).unwrap(); + Guard::new(Self::from_raw(raw_ptr), context) + } } } diff --git a/rust/src/collaboration/snapshot.rs b/rust/src/collaboration/snapshot.rs index 3e99805d09..3d0b9628fb 100644 --- a/rust/src/collaboration/snapshot.rs +++ b/rust/src/collaboration/snapshot.rs @@ -24,7 +24,7 @@ impl RemoteSnapshot { } pub(crate) unsafe fn ref_from_raw(handle: NonNull) -> Ref { - Ref::new(Self { handle }) + unsafe { Ref::new(Self { handle }) } } /// Get the remote snapshot associated with a local snapshot (if it exists) @@ -339,14 +339,18 @@ impl ToOwned for RemoteSnapshot { unsafe impl RefCountable for RemoteSnapshot { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: NonNull::new(BNNewCollaborationSnapshotReference(handle.handle.as_ptr())) - .unwrap(), - }) + unsafe { + Ref::new(Self { + handle: NonNull::new(BNNewCollaborationSnapshotReference(handle.handle.as_ptr())) + .unwrap(), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeCollaborationSnapshot(handle.handle.as_ptr()); + unsafe { + BNFreeCollaborationSnapshot(handle.handle.as_ptr()); + } } } @@ -358,11 +362,13 @@ impl CoreArrayProvider for RemoteSnapshot { unsafe impl CoreArrayProviderInner for RemoteSnapshot { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeCollaborationSnapshotList(raw, count) + unsafe { BNFreeCollaborationSnapshotList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - let raw_ptr = NonNull::new(*raw).unwrap(); - Guard::new(Self::from_raw(raw_ptr), context) + unsafe { + let raw_ptr = NonNull::new(*raw).unwrap(); + Guard::new(Self::from_raw(raw_ptr), context) + } } } diff --git a/rust/src/collaboration/sync.rs b/rust/src/collaboration/sync.rs index 1bf9c010bb..879eda388f 100644 --- a/rust/src/collaboration/sync.rs +++ b/rust/src/collaboration/sync.rs @@ -794,11 +794,13 @@ pub trait NameChangeset: Sized { ctxt: *mut ::std::os::raw::c_void, changeset: *mut BNCollaborationChangeset, ) -> bool { - let ctxt: &mut Self = &mut *(ctxt as *mut Self); - let raw_changeset_ptr = NonNull::new(changeset).unwrap(); - // TODO: Do we take ownership with a ref here or not? - let changeset = Changeset::from_raw(raw_changeset_ptr); - ctxt.name_changeset(&changeset) + unsafe { + let ctxt: &mut Self = &mut *(ctxt as *mut Self); + let raw_changeset_ptr = NonNull::new(changeset).unwrap(); + // TODO: Do we take ownership with a ref here or not? + let changeset = Changeset::from_raw(raw_changeset_ptr); + ctxt.name_changeset(&changeset) + } } } @@ -841,16 +843,18 @@ pub trait DatabaseConflictHandler: Sized { conflicts: *mut *mut BNAnalysisMergeConflict, conflict_count: usize, ) -> bool { - let ctxt: &mut Self = &mut *(ctxt as *mut Self); - let keys = core::slice::from_raw_parts(keys, conflict_count); - let conflicts = core::slice::from_raw_parts(conflicts, conflict_count); - keys.iter().zip(conflicts.iter()).all(|(key, conflict)| { - let key = raw_to_string(*key).unwrap(); - // TODO I guess dont drop here? - let raw_ptr = NonNull::new(*conflict).unwrap(); - let conflict = MergeConflict::from_raw(raw_ptr); - ctxt.handle_conflict(&key, &conflict) - }) + unsafe { + let ctxt: &mut Self = &mut *(ctxt as *mut Self); + let keys = core::slice::from_raw_parts(keys, conflict_count); + let conflicts = core::slice::from_raw_parts(conflicts, conflict_count); + keys.iter().zip(conflicts.iter()).all(|(key, conflict)| { + let key = raw_to_string(*key).unwrap(); + // TODO I guess dont drop here? + let raw_ptr = NonNull::new(*conflict).unwrap(); + let conflict = MergeConflict::from_raw(raw_ptr); + ctxt.handle_conflict(&key, &conflict) + }) + } } } @@ -887,14 +891,16 @@ pub trait TypeArchiveConflictHandler: Sized { conflicts: *mut *mut BNTypeArchiveMergeConflict, conflict_count: usize, ) -> bool { - let ctx: &mut Self = &mut *(ctxt as *mut Self); - // TODO: Verify that we dont own the merge conflict, or this list passed to us. - let conflicts_raw = core::slice::from_raw_parts(conflicts, conflict_count); - conflicts_raw - .iter() - .map(|t| NonNull::new_unchecked(*t)) - .map(|t| TypeArchiveMergeConflict::from_raw(t)) - .all(|conflict| ctx.handle_conflict(&conflict)) + unsafe { + let ctx: &mut Self = &mut *(ctxt as *mut Self); + // TODO: Verify that we dont own the merge conflict, or this list passed to us. + let conflicts_raw = core::slice::from_raw_parts(conflicts, conflict_count); + conflicts_raw + .iter() + .map(|t| NonNull::new_unchecked(*t)) + .map(|t| TypeArchiveMergeConflict::from_raw(t)) + .all(|conflict| ctx.handle_conflict(&conflict)) + } } } diff --git a/rust/src/collaboration/undo.rs b/rust/src/collaboration/undo.rs index 0dde860fde..56bcb51150 100644 --- a/rust/src/collaboration/undo.rs +++ b/rust/src/collaboration/undo.rs @@ -25,7 +25,7 @@ impl RemoteUndoEntry { } pub(crate) unsafe fn ref_from_raw(handle: NonNull) -> Ref { - Ref::new(Self { handle }) + unsafe { Ref::new(Self { handle }) } } /// Owning Snapshot @@ -111,14 +111,18 @@ impl ToOwned for RemoteUndoEntry { unsafe impl RefCountable for RemoteUndoEntry { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: NonNull::new(BNNewCollaborationUndoEntryReference(handle.handle.as_ptr())) - .unwrap(), - }) + unsafe { + Ref::new(Self { + handle: NonNull::new(BNNewCollaborationUndoEntryReference(handle.handle.as_ptr())) + .unwrap(), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeCollaborationUndoEntry(handle.handle.as_ptr()); + unsafe { + BNFreeCollaborationUndoEntry(handle.handle.as_ptr()); + } } } @@ -130,12 +134,14 @@ impl CoreArrayProvider for RemoteUndoEntry { unsafe impl CoreArrayProviderInner for RemoteUndoEntry { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeCollaborationUndoEntryList(raw, count) + unsafe { BNFreeCollaborationUndoEntryList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - let raw_ptr = NonNull::new(*raw).unwrap(); - Guard::new(Self::from_raw(raw_ptr), context) + unsafe { + let raw_ptr = NonNull::new(*raw).unwrap(); + Guard::new(Self::from_raw(raw_ptr), context) + } } } @@ -157,7 +163,7 @@ impl CoreArrayProvider for RemoteUndoEntryId { unsafe impl CoreArrayProviderInner for RemoteUndoEntryId { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNCollaborationFreeIdList(raw, count) + unsafe { BNCollaborationFreeIdList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { diff --git a/rust/src/collaboration/user.rs b/rust/src/collaboration/user.rs index 51bdebb54a..6b96fd7bc1 100644 --- a/rust/src/collaboration/user.rs +++ b/rust/src/collaboration/user.rs @@ -16,7 +16,7 @@ impl RemoteUser { } pub(crate) unsafe fn ref_from_raw(handle: NonNull) -> Ref { - Ref::new(Self { handle }) + unsafe { Ref::new(Self { handle }) } } /// Owning Remote @@ -117,13 +117,18 @@ impl ToOwned for RemoteUser { unsafe impl RefCountable for RemoteUser { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: NonNull::new(BNNewCollaborationUserReference(handle.handle.as_ptr())).unwrap(), - }) + unsafe { + Ref::new(Self { + handle: NonNull::new(BNNewCollaborationUserReference(handle.handle.as_ptr())) + .unwrap(), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeCollaborationUser(handle.handle.as_ptr()); + unsafe { + BNFreeCollaborationUser(handle.handle.as_ptr()); + } } } @@ -135,11 +140,13 @@ impl CoreArrayProvider for RemoteUser { unsafe impl CoreArrayProviderInner for RemoteUser { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeCollaborationUserList(raw, count) + unsafe { BNFreeCollaborationUserList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - let raw_ptr = NonNull::new(*raw).unwrap(); - Guard::new(Self::from_raw(raw_ptr), context) + unsafe { + let raw_ptr = NonNull::new(*raw).unwrap(); + Guard::new(Self::from_raw(raw_ptr), context) + } } } diff --git a/rust/src/component.rs b/rust/src/component.rs index c99081fad2..38286a50c1 100644 --- a/rust/src/component.rs +++ b/rust/src/component.rs @@ -83,7 +83,7 @@ impl Component { } pub(crate) unsafe fn ref_from_raw(handle: NonNull) -> Ref { - Ref::new(Self { handle }) + unsafe { Ref::new(Self { handle }) } } pub fn guid(&self) -> String { @@ -278,13 +278,17 @@ impl ToOwned for Component { unsafe impl RefCountable for Component { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: NonNull::new(BNNewComponentReference(handle.handle.as_ptr())).unwrap(), - }) + unsafe { + Ref::new(Self { + handle: NonNull::new(BNNewComponentReference(handle.handle.as_ptr())).unwrap(), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeComponent(handle.handle.as_ptr()); + unsafe { + BNFreeComponent(handle.handle.as_ptr()); + } } } @@ -296,12 +300,14 @@ impl CoreArrayProvider for Component { unsafe impl CoreArrayProviderInner for Component { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeComponents(raw, count) + unsafe { BNFreeComponents(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - let raw_ptr = NonNull::new(*raw).unwrap(); - Guard::new(Self::from_raw(raw_ptr), context) + unsafe { + let raw_ptr = NonNull::new(*raw).unwrap(); + Guard::new(Self::from_raw(raw_ptr), context) + } } } @@ -317,11 +323,13 @@ impl CoreArrayProvider for ComponentReferencedType { unsafe impl CoreArrayProviderInner for ComponentReferencedType { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNComponentFreeReferencedTypes(raw, count) + unsafe { BNComponentFreeReferencedTypes(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { - // SAFETY: &*mut BNType == &Type (*mut BNType == Type) - std::mem::transmute(raw) + unsafe { + // SAFETY: &*mut BNType == &Type (*mut BNType == Type) + std::mem::transmute(raw) + } } } diff --git a/rust/src/data_notification.rs b/rust/src/data_notification.rs index d01a5ed32a..99cce27d85 100644 --- a/rust/src/data_notification.rs +++ b/rust/src/data_notification.rs @@ -26,7 +26,7 @@ macro_rules! trait_handler { $arg_name:ident: $raw_arg_type:ty: $arg_type:ty = - $value_calculated:expr + $value_calculated:expr_2021 ),* $(,)? ) $(-> $ret_type:ty)? ),* $(,)? @@ -70,10 +70,10 @@ macro_rules! trait_handler { unsafe extern "C" fn $fun_name( ctxt: *mut ::std::os::raw::c_void, $($arg_name: $raw_arg_type),* - ) $(-> $ret_type)* { + ) $(-> $ret_type)* { unsafe { let handle: &mut H = &mut *(ctxt as *mut H); handle.$fun_name($($value_calculated),*) - } + }} )* fn register_data_notification<'a, H: CustomDataNotification + 'a>( @@ -422,11 +422,11 @@ where impl DataNotificationHandle<'_, T> { unsafe fn unregister_bv(&mut self) { - BNUnregisterDataNotification(self.bv.handle, self.handle.as_mut()) + unsafe { BNUnregisterDataNotification(self.bv.handle, self.handle.as_mut()) } } unsafe fn extract_context(&mut self) -> Box { - Box::from_raw(self.handle.context as *mut T) + unsafe { Box::from_raw(self.handle.context as *mut T) } } pub fn unregister(self) -> T { diff --git a/rust/src/data_renderer.rs b/rust/src/data_renderer.rs index d6b0734320..e957ee4c4f 100644 --- a/rust/src/data_renderer.rs +++ b/rust/src/data_renderer.rs @@ -173,7 +173,9 @@ impl Debug for TypeContext { } unsafe extern "C" fn cb_free_object(ctxt: *mut c_void) { - let _ = Box::from_raw(ctxt as *mut C); + unsafe { + let _ = Box::from_raw(ctxt as *mut C); + } } unsafe extern "C" fn cb_is_valid_for_data( @@ -184,15 +186,17 @@ unsafe extern "C" fn cb_is_valid_for_data( type_ctx: *mut BNTypeContext, ctx_count: usize, ) -> bool { - let ctxt = ctxt as *mut C; - // SAFETY BNTypeContext and TypeContext are transparent - let types = core::slice::from_raw_parts(type_ctx as *mut TypeContext, ctx_count); - (*ctxt).is_valid_for_data( - &BinaryView::from_raw(view), - addr, - &Type::from_raw(type_), - types, - ) + unsafe { + let ctxt = ctxt as *mut C; + // SAFETY BNTypeContext and TypeContext are transparent + let types = core::slice::from_raw_parts(type_ctx as *mut TypeContext, ctx_count); + (*ctxt).is_valid_for_data( + &BinaryView::from_raw(view), + addr, + &Type::from_raw(type_), + types, + ) + } } unsafe extern "C" fn cb_get_lines_for_data( @@ -208,28 +212,30 @@ unsafe extern "C" fn cb_get_lines_for_data( ctx_count: usize, language: *const ffi::c_char, ) -> *mut BNDisassemblyTextLine { - let ctxt = ctxt as *mut C; - // SAFETY BNTypeContext and TypeContext are transparent - let types = core::slice::from_raw_parts(type_ctx as *mut TypeContext, ctx_count); - let prefix = core::slice::from_raw_parts(prefix, prefix_count) - .iter() - .map(InstructionTextToken::from_raw) - .collect::>(); - let result = (*ctxt).lines_for_data( - &BinaryView::from_raw(view), - addr, - &Type::from_raw(type_), - prefix, - width, - types, - ffi::CStr::from_ptr(language).to_str().unwrap(), - ); - let result: Box<[BNDisassemblyTextLine]> = result - .into_iter() - .map(DisassemblyTextLine::into_raw) - .collect(); - *count = result.len(); - Box::leak(result).as_mut_ptr() + unsafe { + let ctxt = ctxt as *mut C; + // SAFETY BNTypeContext and TypeContext are transparent + let types = core::slice::from_raw_parts(type_ctx as *mut TypeContext, ctx_count); + let prefix = core::slice::from_raw_parts(prefix, prefix_count) + .iter() + .map(InstructionTextToken::from_raw) + .collect::>(); + let result = (*ctxt).lines_for_data( + &BinaryView::from_raw(view), + addr, + &Type::from_raw(type_), + prefix, + width, + types, + ffi::CStr::from_ptr(language).to_str().unwrap(), + ); + let result: Box<[BNDisassemblyTextLine]> = result + .into_iter() + .map(DisassemblyTextLine::into_raw) + .collect(); + *count = result.len(); + Box::leak(result).as_mut_ptr() + } } unsafe extern "C" fn cb_free_lines( @@ -237,8 +243,10 @@ unsafe extern "C" fn cb_free_lines( lines: *mut BNDisassemblyTextLine, count: usize, ) { - let lines = Box::from_raw(std::ptr::slice_from_raw_parts_mut(lines, count)); - for line in lines { - let _ = DisassemblyTextLine::from_raw(&line); + unsafe { + let lines = Box::from_raw(std::ptr::slice_from_raw_parts_mut(lines, count)); + for line in lines { + let _ = DisassemblyTextLine::from_raw(&line); + } } } diff --git a/rust/src/database.rs b/rust/src/database.rs index f0627306e6..6005e14d72 100644 --- a/rust/src/database.rs +++ b/rust/src/database.rs @@ -27,7 +27,7 @@ impl Database { } pub(crate) unsafe fn ref_from_raw(handle: NonNull) -> Ref { - Ref::new(Self { handle }) + unsafe { Ref::new(Self { handle }) } } /// Get a [`Snapshot`] by its `id`, or `None` if no snapshot with that `id` exists. @@ -233,12 +233,16 @@ impl ToOwned for Database { unsafe impl RefCountable for Database { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: NonNull::new(BNNewDatabaseReference(handle.handle.as_ptr())).unwrap(), - }) + unsafe { + Ref::new(Self { + handle: NonNull::new(BNNewDatabaseReference(handle.handle.as_ptr())).unwrap(), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeDatabase(handle.handle.as_ptr()); + unsafe { + BNFreeDatabase(handle.handle.as_ptr()); + } } } diff --git a/rust/src/database/kvs.rs b/rust/src/database/kvs.rs index 13b1796218..b62696c823 100644 --- a/rust/src/database/kvs.rs +++ b/rust/src/database/kvs.rs @@ -19,7 +19,7 @@ pub struct KeyValueStore { impl KeyValueStore { pub(crate) unsafe fn ref_from_raw(handle: NonNull) -> Ref { - Ref::new(Self { handle }) + unsafe { Ref::new(Self { handle }) } } pub fn to_hashmap(&self) -> HashMap { @@ -110,13 +110,17 @@ impl ToOwned for KeyValueStore { unsafe impl RefCountable for KeyValueStore { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: NonNull::new(BNNewKeyValueStoreReference(handle.handle.as_ptr())).unwrap(), - }) + unsafe { + Ref::new(Self { + handle: NonNull::new(BNNewKeyValueStoreReference(handle.handle.as_ptr())).unwrap(), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeKeyValueStore(handle.handle.as_ptr()); + unsafe { + BNFreeKeyValueStore(handle.handle.as_ptr()); + } } } diff --git a/rust/src/database/snapshot.rs b/rust/src/database/snapshot.rs index 85c57f4ea0..ce1f720d73 100644 --- a/rust/src/database/snapshot.rs +++ b/rust/src/database/snapshot.rs @@ -29,7 +29,7 @@ impl Snapshot { } pub(crate) unsafe fn ref_from_raw(handle: NonNull) -> Ref { - Ref::new(Self { handle }) + unsafe { Ref::new(Self { handle }) } } /// Get the owning database @@ -223,13 +223,17 @@ impl ToOwned for Snapshot { unsafe impl RefCountable for Snapshot { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: NonNull::new(BNNewSnapshotReference(handle.handle.as_ptr())).unwrap(), - }) + unsafe { + Ref::new(Self { + handle: NonNull::new(BNNewSnapshotReference(handle.handle.as_ptr())).unwrap(), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeSnapshot(handle.handle.as_ptr()); + unsafe { + BNFreeSnapshot(handle.handle.as_ptr()); + } } } @@ -241,12 +245,16 @@ impl CoreArrayProvider for Snapshot { unsafe impl CoreArrayProviderInner for Snapshot { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeSnapshotList(raw, count); + unsafe { + BNFreeSnapshotList(raw, count); + } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - let raw_ptr = NonNull::new(*raw).unwrap(); - Guard::new(Self::from_raw(raw_ptr), context) + unsafe { + let raw_ptr = NonNull::new(*raw).unwrap(); + Guard::new(Self::from_raw(raw_ptr), context) + } } } @@ -268,7 +276,7 @@ impl CoreArrayProvider for SnapshotId { unsafe impl CoreArrayProviderInner for SnapshotId { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNCollaborationFreeSnapshotIdList(raw, count) + unsafe { BNCollaborationFreeSnapshotIdList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { diff --git a/rust/src/database/undo.rs b/rust/src/database/undo.rs index a2001b7218..351e0586f7 100644 --- a/rust/src/database/undo.rs +++ b/rust/src/database/undo.rs @@ -23,7 +23,7 @@ impl UndoEntry { #[allow(dead_code)] pub(crate) unsafe fn ref_from_raw(handle: NonNull) -> Ref { - Ref::new(Self { handle }) + unsafe { Ref::new(Self { handle }) } } pub fn id(&self) -> String { @@ -65,13 +65,17 @@ impl ToOwned for UndoEntry { unsafe impl RefCountable for UndoEntry { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: NonNull::new(BNNewUndoEntryReference(handle.handle.as_ptr())).unwrap(), - }) + unsafe { + Ref::new(Self { + handle: NonNull::new(BNNewUndoEntryReference(handle.handle.as_ptr())).unwrap(), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeUndoEntry(handle.handle.as_ptr()); + unsafe { + BNFreeUndoEntry(handle.handle.as_ptr()); + } } } @@ -83,12 +87,16 @@ impl CoreArrayProvider for UndoEntry { unsafe impl CoreArrayProviderInner for UndoEntry { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeUndoEntryList(raw, count); + unsafe { + BNFreeUndoEntryList(raw, count); + } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - let raw_ptr = NonNull::new(*raw).unwrap(); - Guard::new(Self::from_raw(raw_ptr), context) + unsafe { + let raw_ptr = NonNull::new(*raw).unwrap(); + Guard::new(Self::from_raw(raw_ptr), context) + } } } @@ -104,7 +112,7 @@ impl UndoAction { #[allow(dead_code)] pub(crate) unsafe fn ref_from_raw(handle: NonNull) -> Ref { - Ref::new(Self { handle }) + unsafe { Ref::new(Self { handle }) } } pub fn summary(&self) -> Array { @@ -140,13 +148,17 @@ impl ToOwned for UndoAction { unsafe impl RefCountable for UndoAction { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: NonNull::new(BNNewUndoActionReference(handle.handle.as_ptr())).unwrap(), - }) + unsafe { + Ref::new(Self { + handle: NonNull::new(BNNewUndoActionReference(handle.handle.as_ptr())).unwrap(), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeUndoAction(handle.handle.as_ptr()); + unsafe { + BNFreeUndoAction(handle.handle.as_ptr()); + } } } @@ -158,11 +170,15 @@ impl CoreArrayProvider for UndoAction { unsafe impl CoreArrayProviderInner for UndoAction { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeUndoActionList(raw, count); + unsafe { + BNFreeUndoActionList(raw, count); + } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - let raw_ptr = NonNull::new(*raw).unwrap(); - Guard::new(Self::from_raw(raw_ptr), context) + unsafe { + let raw_ptr = NonNull::new(*raw).unwrap(); + Guard::new(Self::from_raw(raw_ptr), context) + } } } diff --git a/rust/src/debuginfo.rs b/rust/src/debuginfo.rs index 2710537f42..361db6608c 100644 --- a/rust/src/debuginfo.rs +++ b/rust/src/debuginfo.rs @@ -109,9 +109,11 @@ pub struct DebugInfoParser { impl DebugInfoParser { pub(crate) unsafe fn from_raw(handle: *mut BNDebugInfoParser) -> Ref { - debug_assert!(!handle.is_null()); + unsafe { + debug_assert!(!handle.is_null()); - Ref::new(Self { handle }) + Ref::new(Self { handle }) + } } /// Returns debug info parser of the given name, if it exists @@ -272,13 +274,17 @@ impl DebugInfoParser { unsafe impl RefCountable for DebugInfoParser { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: BNNewDebugInfoParserReference(handle.handle), - }) + unsafe { + Ref::new(Self { + handle: BNNewDebugInfoParserReference(handle.handle), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeDebugInfoParserReference(handle.handle); + unsafe { + BNFreeDebugInfoParserReference(handle.handle); + } } } @@ -298,11 +304,13 @@ impl CoreArrayProvider for DebugInfoParser { unsafe impl CoreArrayProviderInner for DebugInfoParser { unsafe fn free(raw: *mut Self::Raw, count: usize, _: &Self::Context) { - BNFreeDebugInfoParserList(raw, count); + unsafe { + BNFreeDebugInfoParserList(raw, count); + } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - Guard::new(Self { handle: *raw }, context) + unsafe { Guard::new(Self { handle: *raw }, context) } } } @@ -409,8 +417,10 @@ pub struct DebugInfo { impl DebugInfo { pub(crate) unsafe fn ref_from_raw(handle: *mut BNDebugInfo) -> Ref { - debug_assert!(!handle.is_null()); - Ref::new(Self { handle }) + unsafe { + debug_assert!(!handle.is_null()); + Ref::new(Self { handle }) + } } /// Returns all types within the parser @@ -752,13 +762,17 @@ impl DebugInfo { unsafe impl RefCountable for DebugInfo { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: BNNewDebugInfoReference(handle.handle), - }) + unsafe { + Ref::new(Self { + handle: BNNewDebugInfoReference(handle.handle), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeDebugInfoReference(handle.handle); + unsafe { + BNFreeDebugInfoReference(handle.handle); + } } } diff --git a/rust/src/demangle.rs b/rust/src/demangle.rs index d6aad25cee..a5bf56433b 100644 --- a/rust/src/demangle.rs +++ b/rust/src/demangle.rs @@ -377,11 +377,13 @@ impl CoreArrayProvider for Demangler { unsafe impl CoreArrayProviderInner for Demangler { unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { - BNFreeDemanglerList(raw); + unsafe { + BNFreeDemanglerList(raw); + } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { - Demangler::from_raw(*raw) + unsafe { Demangler::from_raw(*raw) } } } diff --git a/rust/src/disassembly.rs b/rust/src/disassembly.rs index 9aa790cd87..db807fa6c0 100644 --- a/rust/src/disassembly.rs +++ b/rust/src/disassembly.rs @@ -187,7 +187,7 @@ impl CoreArrayProvider for DisassemblyTextLine { unsafe impl CoreArrayProviderInner for DisassemblyTextLine { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeDisassemblyTextLines(raw, count) + unsafe { BNFreeDisassemblyTextLines(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { @@ -363,8 +363,10 @@ impl CoreArrayProvider for InstructionTextToken { unsafe impl CoreArrayProviderInner for InstructionTextToken { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - // SAFETY: The Array MUST have been allocated on the core side. This will `delete[] raw`. - BNFreeInstructionText(raw, count) + unsafe { + // SAFETY: The Array MUST have been allocated on the core side. This will `delete[] raw`. + BNFreeInstructionText(raw, count) + } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { @@ -380,13 +382,17 @@ impl CoreArrayProvider for Array { unsafe impl CoreArrayProviderInner for Array { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - // SAFETY: The Array MUST have been allocated on the core side. This will `delete[] raw`. - BNFreeInstructionTextLines(raw, count) + unsafe { + // SAFETY: The Array MUST have been allocated on the core side. This will `delete[] raw`. + BNFreeInstructionTextLines(raw, count) + } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { - // TODO: This is insane. - std::mem::ManuallyDrop::new(Self::new(raw.tokens, raw.count, ())) + unsafe { + // TODO: This is insane. + std::mem::ManuallyDrop::new(Self::new(raw.tokens, raw.count, ())) + } } } @@ -1091,7 +1097,7 @@ pub struct DisassemblyTextRenderer { impl DisassemblyTextRenderer { pub unsafe fn ref_from_raw(handle: NonNull) -> Ref { - Ref::new(Self { handle }) + unsafe { Ref::new(Self { handle }) } } pub fn from_function(func: &Function, settings: Option<&DisassemblySettings>) -> Ref { @@ -1362,16 +1368,20 @@ impl ToOwned for DisassemblyTextRenderer { unsafe impl RefCountable for DisassemblyTextRenderer { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: NonNull::new(BNNewDisassemblyTextRendererReference( - handle.handle.as_ptr(), - )) - .unwrap(), - }) + unsafe { + Ref::new(Self { + handle: NonNull::new(BNNewDisassemblyTextRendererReference( + handle.handle.as_ptr(), + )) + .unwrap(), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeDisassemblyTextRenderer(handle.handle.as_ptr()); + unsafe { + BNFreeDisassemblyTextRenderer(handle.handle.as_ptr()); + } } } @@ -1411,12 +1421,16 @@ impl ToOwned for DisassemblySettings { unsafe impl RefCountable for DisassemblySettings { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: BNNewDisassemblySettingsReference(handle.handle), - }) + unsafe { + Ref::new(Self { + handle: BNNewDisassemblySettingsReference(handle.handle), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeDisassemblySettings(handle.handle); + unsafe { + BNFreeDisassemblySettings(handle.handle); + } } } diff --git a/rust/src/download/instance.rs b/rust/src/download/instance.rs index 7f43dc0f4c..2346899c1f 100644 --- a/rust/src/download/instance.rs +++ b/rust/src/download/instance.rs @@ -193,7 +193,7 @@ impl DownloadInstance { } pub(crate) unsafe fn ref_from_raw(handle: *mut BNDownloadInstance) -> Ref { - Ref::new(Self::from_raw(handle)) + unsafe { Ref::new(Self::from_raw(handle)) } } fn get_error(&self) -> String { @@ -452,94 +452,112 @@ impl ToOwned for DownloadInstance { unsafe impl RefCountable for DownloadInstance { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: BNNewDownloadInstanceReference(handle.handle), - }) + unsafe { + Ref::new(Self { + handle: BNNewDownloadInstanceReference(handle.handle), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeDownloadInstance(handle.handle); + unsafe { + BNFreeDownloadInstance(handle.handle); + } } } unsafe extern "C" fn cb_read_input(data: *mut u8, len: u64, ctxt: *mut c_void) -> i64 { - let callbacks = ctxt as *mut DownloadInstanceInputOutputCallbacks; - if let Some(func) = &mut (*callbacks).read { - let slice = slice::from_raw_parts_mut(data, len as usize); - let result = (func)(slice); - if let Some(count) = result { - count as i64 + unsafe { + let callbacks = ctxt as *mut DownloadInstanceInputOutputCallbacks; + if let Some(func) = &mut (*callbacks).read { + let slice = slice::from_raw_parts_mut(data, len as usize); + let result = (func)(slice); + if let Some(count) = result { + count as i64 + } else { + -1 + } } else { - -1 + 0 } - } else { - 0 } } unsafe extern "C" fn cb_write_input(data: *mut u8, len: u64, ctxt: *mut c_void) -> u64 { - let callbacks = ctxt as *mut DownloadInstanceInputOutputCallbacks; - if let Some(func) = &mut (*callbacks).write { - let slice = slice::from_raw_parts(data, len as usize); - let result = (func)(slice); - result as u64 - } else { - 0 + unsafe { + let callbacks = ctxt as *mut DownloadInstanceInputOutputCallbacks; + if let Some(func) = &mut (*callbacks).write { + let slice = slice::from_raw_parts(data, len as usize); + let result = (func)(slice); + result as u64 + } else { + 0 + } } } unsafe extern "C" fn cb_progress_input(ctxt: *mut c_void, progress: usize, total: usize) -> bool { - let callbacks = ctxt as *mut DownloadInstanceInputOutputCallbacks; - if let Some(func) = &mut (*callbacks).progress { - (func)(progress, total) - } else { - true + unsafe { + let callbacks = ctxt as *mut DownloadInstanceInputOutputCallbacks; + if let Some(func) = &mut (*callbacks).progress { + (func)(progress, total) + } else { + true + } } } unsafe extern "C" fn cb_write_output(data: *mut u8, len: u64, ctxt: *mut c_void) -> u64 { - let callbacks = ctxt as *mut DownloadInstanceOutputCallbacks; - if let Some(func) = &mut (*callbacks).write { - let slice = slice::from_raw_parts(data, len as usize); - let result = (func)(slice); - result as u64 - } else { - 0u64 + unsafe { + let callbacks = ctxt as *mut DownloadInstanceOutputCallbacks; + if let Some(func) = &mut (*callbacks).write { + let slice = slice::from_raw_parts(data, len as usize); + let result = (func)(slice); + result as u64 + } else { + 0u64 + } } } unsafe extern "C" fn cb_progress_output(ctxt: *mut c_void, progress: usize, total: usize) -> bool { - let callbacks = ctxt as *mut DownloadInstanceOutputCallbacks; - if let Some(func) = &mut (*callbacks).progress { - (func)(progress, total) - } else { - true + unsafe { + let callbacks = ctxt as *mut DownloadInstanceOutputCallbacks; + if let Some(func) = &mut (*callbacks).progress { + (func)(progress, total) + } else { + true + } } } pub unsafe extern "C" fn cb_destroy_instance(ctxt: *mut c_void) { - let _ = Box::from_raw(ctxt as *mut C); + unsafe { + let _ = Box::from_raw(ctxt as *mut C); + } } pub unsafe extern "C" fn cb_perform_request( ctxt: *mut c_void, url: *const c_char, ) -> i32 { - let c = ManuallyDrop::new(Box::from_raw(ctxt as *mut C)); - - let url = match CStr::from_ptr(url).to_str() { - Ok(url) => url, - Err(e) => { - c.handle().set_error(&format!("Invalid URL: {}", e)); - return -1; - } - }; + unsafe { + let c = ManuallyDrop::new(Box::from_raw(ctxt as *mut C)); + + let url = match CStr::from_ptr(url).to_str() { + Ok(url) => url, + Err(e) => { + c.handle().set_error(&format!("Invalid URL: {}", e)); + return -1; + } + }; - match c.perform_request(url) { - Ok(()) => 0, - Err(e) => { - c.handle().set_error(&e); - -1 + match c.perform_request(url) { + Ok(()) => 0, + Err(e) => { + c.handle().set_error(&e); + -1 + } } } } @@ -553,51 +571,55 @@ pub unsafe extern "C" fn cb_perform_custom_request( header_values: *const *const c_char, response: *mut *mut BNDownloadInstanceResponse, ) -> i32 { - let c = ManuallyDrop::new(Box::from_raw(ctxt as *mut C)); + unsafe { + let c = ManuallyDrop::new(Box::from_raw(ctxt as *mut C)); + + let method = match CStr::from_ptr(method).to_str() { + Ok(method) => method, + Err(e) => { + c.handle().set_error(&format!("Invalid Method: {}", e)); + return -1; + } + }; - let method = match CStr::from_ptr(method).to_str() { - Ok(method) => method, - Err(e) => { - c.handle().set_error(&format!("Invalid Method: {}", e)); - return -1; - } - }; + let url = match CStr::from_ptr(url).to_str() { + Ok(url) => url, + Err(e) => { + c.handle().set_error(&format!("Invalid URL: {}", e)); + return -1; + } + }; - let url = match CStr::from_ptr(url).to_str() { - Ok(url) => url, - Err(e) => { - c.handle().set_error(&format!("Invalid URL: {}", e)); - return -1; - } - }; - - // SAFETY BnString and *mut c_char are transparent - let header_count = usize::try_from(header_count).unwrap(); - let header_keys = slice::from_raw_parts(header_keys as *const BnString, header_count); - let header_values = slice::from_raw_parts(header_values as *const BnString, header_count); - let header_keys_str = header_keys.iter().map(|s| s.to_string_lossy().to_string()); - let header_values_str = header_values - .iter() - .map(|s| s.to_string_lossy().to_string()); - let headers = header_keys_str.zip(header_values_str); - - match c.perform_custom_request(method, url, headers) { - Ok(res) => { - let res_header_keys_ptr = strings_to_string_list(res.headers.keys()); - let res_header_values_ptr = strings_to_string_list(res.headers.values()); - let raw_response = BNDownloadInstanceResponse { - statusCode: res.status_code, - headerCount: res.headers.len() as u64, - headerKeys: res_header_keys_ptr, - headerValues: res_header_values_ptr, - }; - // Leak the response and free it with cb_free_response - unsafe { *response = Box::leak(Box::new(raw_response)) }; - 0 - } - Err(e) => { - c.handle().set_error(&e); - -1 + // SAFETY BnString and *mut c_char are transparent + let header_count = usize::try_from(header_count).unwrap(); + let header_keys = slice::from_raw_parts(header_keys as *const BnString, header_count); + let header_values = slice::from_raw_parts(header_values as *const BnString, header_count); + let header_keys_str = header_keys.iter().map(|s| s.to_string_lossy().to_string()); + let header_values_str = header_values + .iter() + .map(|s| s.to_string_lossy().to_string()); + let headers = header_keys_str.zip(header_values_str); + + match c.perform_custom_request(method, url, headers) { + Ok(res) => { + let res_header_keys_ptr = strings_to_string_list(res.headers.keys()); + let res_header_values_ptr = strings_to_string_list(res.headers.values()); + let raw_response = BNDownloadInstanceResponse { + statusCode: res.status_code, + headerCount: res.headers.len() as u64, + headerKeys: res_header_keys_ptr, + headerValues: res_header_values_ptr, + }; + // Leak the response and free it with cb_free_response + { + *response = Box::leak(Box::new(raw_response)) + }; + 0 + } + Err(e) => { + c.handle().set_error(&e); + -1 + } } } } @@ -606,5 +628,7 @@ unsafe extern "C" fn cb_free_response( _ctxt: *mut c_void, response: *mut BNDownloadInstanceResponse, ) { - let _ = Box::from_raw(response); + unsafe { + let _ = Box::from_raw(response); + } } diff --git a/rust/src/download/provider.rs b/rust/src/download/provider.rs index 391c550ae2..cb77f1f1f2 100644 --- a/rust/src/download/provider.rs +++ b/rust/src/download/provider.rs @@ -113,11 +113,13 @@ impl CoreArrayProvider for DownloadProvider { unsafe impl CoreArrayProviderInner for DownloadProvider { unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { - BNFreeDownloadProviderList(raw); + unsafe { + BNFreeDownloadProviderList(raw); + } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { - Guard::new(DownloadProvider::from_raw(*raw), &()) + unsafe { Guard::new(DownloadProvider::from_raw(*raw), &()) } } } diff --git a/rust/src/enterprise.rs b/rust/src/enterprise.rs index 2e13245408..ca2f55b33f 100644 --- a/rust/src/enterprise.rs +++ b/rust/src/enterprise.rs @@ -302,8 +302,10 @@ pub fn register_license_changed_callback<'a, F: FnMut(bool) + 'a>( ctxt: *mut c_void, still_valid: bool, ) { - let ctxt: &mut F = &mut *(ctxt as *mut F); - ctxt(still_valid) + unsafe { + let ctxt: &mut F = &mut *(ctxt as *mut F); + ctxt(still_valid) + } } let mut handle = binaryninjacore_sys::BNEnterpriseServerCallbacks { context: Box::leak(Box::new(callback)) as *mut F as *mut c_void, diff --git a/rust/src/external_library.rs b/rust/src/external_library.rs index 148fd030f6..707106ea2e 100644 --- a/rust/src/external_library.rs +++ b/rust/src/external_library.rs @@ -19,7 +19,7 @@ impl ExternalLibrary { } pub(crate) unsafe fn ref_from_raw(handle: NonNull) -> Ref { - Ref::new(Self { handle }) + unsafe { Ref::new(Self { handle }) } } /// Get the name of this external library @@ -55,13 +55,18 @@ impl ToOwned for ExternalLibrary { unsafe impl RefCountable for ExternalLibrary { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: NonNull::new(BNNewExternalLibraryReference(handle.handle.as_ptr())).unwrap(), - }) + unsafe { + Ref::new(Self { + handle: NonNull::new(BNNewExternalLibraryReference(handle.handle.as_ptr())) + .unwrap(), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeExternalLibrary(handle.handle.as_ptr()); + unsafe { + BNFreeExternalLibrary(handle.handle.as_ptr()); + } } } @@ -82,12 +87,14 @@ impl CoreArrayProvider for ExternalLibrary { unsafe impl CoreArrayProviderInner for ExternalLibrary { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeExternalLibraryList(raw, count) + unsafe { BNFreeExternalLibraryList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - let raw_ptr = NonNull::new(*raw).unwrap(); - Guard::new(Self::from_raw(raw_ptr), context) + unsafe { + let raw_ptr = NonNull::new(*raw).unwrap(); + Guard::new(Self::from_raw(raw_ptr), context) + } } } @@ -104,7 +111,7 @@ impl ExternalLocation { } pub(crate) unsafe fn ref_from_raw(handle: NonNull) -> Ref { - Ref::new(Self { handle }) + unsafe { Ref::new(Self { handle }) } } /// Get the source symbol for this ExternalLocation @@ -200,13 +207,18 @@ impl ToOwned for ExternalLocation { unsafe impl RefCountable for ExternalLocation { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: NonNull::new(BNNewExternalLocationReference(handle.handle.as_ptr())).unwrap(), - }) + unsafe { + Ref::new(Self { + handle: NonNull::new(BNNewExternalLocationReference(handle.handle.as_ptr())) + .unwrap(), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeExternalLocation(handle.handle.as_ptr()); + unsafe { + BNFreeExternalLocation(handle.handle.as_ptr()); + } } } @@ -218,11 +230,13 @@ impl CoreArrayProvider for ExternalLocation { unsafe impl CoreArrayProviderInner for ExternalLocation { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeExternalLocationList(raw, count) + unsafe { BNFreeExternalLocationList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - let raw_ptr = NonNull::new(*raw).unwrap(); - Guard::new(Self::from_raw(raw_ptr), context) + unsafe { + let raw_ptr = NonNull::new(*raw).unwrap(); + Guard::new(Self::from_raw(raw_ptr), context) + } } } diff --git a/rust/src/ffi.rs b/rust/src/ffi.rs index 66e5f70f18..7bfc93f344 100644 --- a/rust/src/ffi.rs +++ b/rust/src/ffi.rs @@ -17,7 +17,7 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH}; pub(crate) const INVALID_REGISTER: u32 = 0xffff_ffff; macro_rules! ffi_wrap { - ($n:expr, $b:expr) => {{ + ($n:expr_2021, $b:expr_2021) => {{ use std::panic; use std::process; @@ -48,12 +48,12 @@ pub(crate) unsafe fn slice_from_raw_parts<'a, T>(data: *const T, len: usize) -> #[macro_export] macro_rules! ffi_span { - ($name:expr, $bv:expr) => {{ + ($name:expr_2021, $bv:expr_2021) => {{ #[allow(unused_imports)] use $crate::file_metadata::FileMetadata; ::tracing::info_span!($name, session_id = $bv.file().session_id().0).entered() }}; - ($name:expr) => { + ($name:expr_2021) => { ::tracing::info_span!($name).entered() }; } diff --git a/rust/src/file_metadata.rs b/rust/src/file_metadata.rs index 064d1fe93d..8592bf22f9 100644 --- a/rust/src/file_metadata.rs +++ b/rust/src/file_metadata.rs @@ -90,13 +90,17 @@ impl ToOwned for SaveSettings { unsafe impl RefCountable for SaveSettings { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: BNNewSaveSettingsReference(handle.handle), - }) + unsafe { + Ref::new(Self { + handle: BNNewSaveSettingsReference(handle.handle), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeSaveSettings(handle.handle); + unsafe { + BNFreeSaveSettings(handle.handle); + } } } @@ -658,12 +662,16 @@ impl ToOwned for FileMetadata { unsafe impl RefCountable for FileMetadata { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: BNNewFileReference(handle.handle), - }) + unsafe { + Ref::new(Self { + handle: BNNewFileReference(handle.handle), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeFileMetadata(handle.handle); + unsafe { + BNFreeFileMetadata(handle.handle); + } } } diff --git a/rust/src/flowgraph.rs b/rust/src/flowgraph.rs index cac4e91f4e..6760b61f32 100644 --- a/rust/src/flowgraph.rs +++ b/rust/src/flowgraph.rs @@ -52,7 +52,7 @@ impl FlowGraph { } pub(crate) unsafe fn ref_from_raw(raw: *mut BNFlowGraph) -> Ref { - Ref::new(Self { handle: raw }) + unsafe { Ref::new(Self { handle: raw }) } } /// Create an empty flowgraph. @@ -322,13 +322,17 @@ impl FlowGraph { unsafe impl RefCountable for FlowGraph { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: BNNewFlowGraphReference(handle.handle), - }) + unsafe { + Ref::new(Self { + handle: BNNewFlowGraphReference(handle.handle), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeFlowGraph(handle.handle); + unsafe { + BNFreeFlowGraph(handle.handle); + } } } diff --git a/rust/src/flowgraph/edge.rs b/rust/src/flowgraph/edge.rs index a891026718..db2f24aac0 100644 --- a/rust/src/flowgraph/edge.rs +++ b/rust/src/flowgraph/edge.rs @@ -37,7 +37,9 @@ impl CoreArrayProvider for FlowGraphEdge { unsafe impl CoreArrayProviderInner for FlowGraphEdge { unsafe fn free(raw: *mut Self::Raw, count: usize, _: &Self::Context) { - BNFreeFlowGraphNodeEdgeList(raw, count); + unsafe { + BNFreeFlowGraphNodeEdgeList(raw, count); + } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { diff --git a/rust/src/flowgraph/layout.rs b/rust/src/flowgraph/layout.rs index 92d6295abe..62e784e70c 100644 --- a/rust/src/flowgraph/layout.rs +++ b/rust/src/flowgraph/layout.rs @@ -84,13 +84,15 @@ impl CoreArrayProvider for CoreFlowGraphLayout { unsafe impl CoreArrayProviderInner for CoreFlowGraphLayout { unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { - BNFreeFlowGraphLayoutList(raw) + unsafe { BNFreeFlowGraphLayoutList(raw) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { - // TODO: Because handle is a NonNull we should prob make Self::Raw that as well... - let handle = NonNull::new(*raw).unwrap(); - CoreFlowGraphLayout::from_raw(handle) + unsafe { + // TODO: Because handle is a NonNull we should prob make Self::Raw that as well... + let handle = NonNull::new(*raw).unwrap(); + CoreFlowGraphLayout::from_raw(handle) + } } } @@ -106,7 +108,7 @@ impl FlowGraphLayoutRequest { pub(crate) unsafe fn ref_from_raw( handle: NonNull, ) -> Ref { - Ref::new(Self { handle }) + unsafe { Ref::new(Self { handle }) } } /// The flow graph that this request is for. @@ -137,14 +139,18 @@ impl ToOwned for FlowGraphLayoutRequest { unsafe impl RefCountable for FlowGraphLayoutRequest { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: NonNull::new(BNNewFlowGraphLayoutRequestReference(handle.handle.as_ptr())) - .unwrap(), - }) + unsafe { + Ref::new(Self { + handle: NonNull::new(BNNewFlowGraphLayoutRequestReference(handle.handle.as_ptr())) + .unwrap(), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeFlowGraphLayoutRequest(handle.handle.as_ptr()); + unsafe { + BNFreeFlowGraphLayoutRequest(handle.handle.as_ptr()); + } } } @@ -154,11 +160,13 @@ unsafe extern "C" fn cb_layout( nodes: *mut *mut BNFlowGraphNode, node_count: usize, ) -> bool { - let ctxt = ctxt as *mut C; - let nodes_slice = core::slice::from_raw_parts(nodes, node_count); - let nodes: Vec<_> = nodes_slice - .iter() - .map(|ptr| unsafe { FlowGraphNode::from_raw(*ptr) }) - .collect(); - (*ctxt).layout(&FlowGraph::from_raw(graph), &nodes) + unsafe { + let ctxt = ctxt as *mut C; + let nodes_slice = core::slice::from_raw_parts(nodes, node_count); + let nodes: Vec<_> = nodes_slice + .iter() + .map(|ptr| FlowGraphNode::from_raw(*ptr)) + .collect(); + (*ctxt).layout(&FlowGraph::from_raw(graph), &nodes) + } } diff --git a/rust/src/flowgraph/node.rs b/rust/src/flowgraph/node.rs index f6da618ffd..fb5d2f28be 100644 --- a/rust/src/flowgraph/node.rs +++ b/rust/src/flowgraph/node.rs @@ -32,7 +32,7 @@ impl FlowGraphNode { } pub(crate) unsafe fn ref_from_raw(raw: *mut BNFlowGraphNode) -> Ref { - Ref::new(Self { handle: raw }) + unsafe { Ref::new(Self { handle: raw }) } } pub fn new(graph: &FlowGraph) -> Ref { @@ -173,13 +173,17 @@ impl Debug for FlowGraphNode { unsafe impl RefCountable for FlowGraphNode { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: BNNewFlowGraphNodeReference(handle.handle), - }) + unsafe { + Ref::new(Self { + handle: BNNewFlowGraphNodeReference(handle.handle), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeFlowGraphNode(handle.handle); + unsafe { + BNFreeFlowGraphNode(handle.handle); + } } } @@ -199,10 +203,12 @@ impl CoreArrayProvider for FlowGraphNode { unsafe impl CoreArrayProviderInner for FlowGraphNode { unsafe fn free(raw: *mut Self::Raw, count: usize, _: &Self::Context) { - BNFreeFlowGraphNodeList(raw, count); + unsafe { + BNFreeFlowGraphNodeList(raw, count); + } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { - Self::from_raw(*raw) + unsafe { Self::from_raw(*raw) } } } diff --git a/rust/src/function.rs b/rust/src/function.rs index fb0aec6d16..8782880d64 100644 --- a/rust/src/function.rs +++ b/rust/src/function.rs @@ -126,8 +126,10 @@ impl CoreArrayProvider for Location { unsafe impl CoreArrayProviderInner for Location { unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { - // NOTE: Does not use _count because freeing does not require iterating the list. - BNFreeArchitectureAndAddressList(raw) + unsafe { + // NOTE: Does not use _count because freeing does not require iterating the list. + BNFreeArchitectureAndAddressList(raw) + } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { @@ -345,8 +347,10 @@ impl Function { } pub unsafe fn ref_from_raw(handle: *mut BNFunction) -> Ref { - debug_assert!(!handle.is_null()); - Ref::new(Self { handle }) + unsafe { + debug_assert!(!handle.is_null()); + Ref::new(Self { handle }) + } } pub fn arch(&self) -> CoreArchitecture { @@ -2770,13 +2774,17 @@ impl ToOwned for Function { unsafe impl RefCountable for Function { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: BNNewFunctionReference(handle.handle), - }) + unsafe { + Ref::new(Self { + handle: BNNewFunctionReference(handle.handle), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeFunction(handle.handle); + unsafe { + BNFreeFunction(handle.handle); + } } } @@ -2788,11 +2796,13 @@ impl CoreArrayProvider for Function { unsafe impl CoreArrayProviderInner for Function { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeFunctionList(raw, count); + unsafe { + BNFreeFunctionList(raw, count); + } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - Guard::new(Self::from_raw(*raw), context) + unsafe { Guard::new(Self::from_raw(*raw), context) } } } @@ -2865,7 +2875,9 @@ impl CoreArrayProvider for PerformanceInfo { unsafe impl CoreArrayProviderInner for PerformanceInfo { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeAnalysisPerformanceInfo(raw, count); + unsafe { + BNFreeAnalysisPerformanceInfo(raw, count); + } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { @@ -2890,7 +2902,7 @@ impl CoreArrayProvider for UnresolvedIndirectBranches { unsafe impl CoreArrayProviderInner for UnresolvedIndirectBranches { unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { - BNFreeAddressList(raw) + unsafe { BNFreeAddressList(raw) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { @@ -2936,7 +2948,7 @@ impl CoreArrayProvider for ConstantReference { unsafe impl CoreArrayProviderInner for ConstantReference { unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { - BNFreeConstantReferenceList(raw) + unsafe { BNFreeConstantReferenceList(raw) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { @@ -2986,7 +2998,7 @@ impl CoreArrayProvider for RegisterStackAdjustment { unsafe impl CoreArrayProviderInner for RegisterStackAdjustment { unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { - BNFreeRegisterStackAdjustments(raw) + unsafe { BNFreeRegisterStackAdjustments(raw) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { @@ -3096,7 +3108,9 @@ impl CoreArrayProvider for Comment { unsafe impl CoreArrayProviderInner for Comment { unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { - BNFreeAddressList(raw); + unsafe { + BNFreeAddressList(raw); + } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, function: &'a Self::Context) -> Self::Wrapped<'a> { diff --git a/rust/src/high_level_il/function.rs b/rust/src/high_level_il/function.rs index 0a55470ee3..c5bebe1194 100644 --- a/rust/src/high_level_il/function.rs +++ b/rust/src/high_level_il/function.rs @@ -26,8 +26,10 @@ impl HighLevelILFunction { handle: *mut BNHighLevelILFunction, full_ast: bool, ) -> Ref { - debug_assert!(!handle.is_null()); - Ref::new(Self { handle, full_ast }) + unsafe { + debug_assert!(!handle.is_null()); + Ref::new(Self { handle, full_ast }) + } } pub fn instruction_from_index( @@ -288,13 +290,17 @@ impl ToOwned for HighLevelILFunction { unsafe impl RefCountable for HighLevelILFunction { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: BNNewHighLevelILFunctionReference(handle.handle), - full_ast: handle.full_ast, - }) + unsafe { + Ref::new(Self { + handle: BNNewHighLevelILFunctionReference(handle.handle), + full_ast: handle.full_ast, + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeHighLevelILFunction(handle.handle); + unsafe { + BNFreeHighLevelILFunction(handle.handle); + } } } diff --git a/rust/src/high_level_il/token_emitter.rs b/rust/src/high_level_il/token_emitter.rs index 864ee50dd0..09131fa715 100644 --- a/rust/src/high_level_il/token_emitter.rs +++ b/rust/src/high_level_il/token_emitter.rs @@ -352,13 +352,15 @@ unsafe impl Sync for HighLevelILTokenEmitter {} unsafe impl RefCountable for HighLevelILTokenEmitter { unsafe fn inc_ref(handle: &Self) -> Ref { - let handle = BNNewHighLevelILTokenEmitterReference(handle.handle.as_ptr()); - let handle = NonNull::new(handle).unwrap(); - Ref::new(HighLevelILTokenEmitter { handle }) + unsafe { + let handle = BNNewHighLevelILTokenEmitterReference(handle.handle.as_ptr()); + let handle = NonNull::new(handle).unwrap(); + Ref::new(HighLevelILTokenEmitter { handle }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeHighLevelILTokenEmitter(handle.handle.as_ptr()) + unsafe { BNFreeHighLevelILTokenEmitter(handle.handle.as_ptr()) } } } diff --git a/rust/src/interaction.rs b/rust/src/interaction.rs index 5fbb91f984..77eb4590c1 100644 --- a/rust/src/interaction.rs +++ b/rust/src/interaction.rs @@ -205,22 +205,24 @@ pub fn run_progress_dialog Result<(), ()>>)>( progress: Option bool>, progress_ctxt: *mut c_void, ) { - ffi_wrap!("run_progress_dialog", { - let context = ctxt as *mut TaskContext; - let progress_fn = Box::new(move |cur: usize, max: usize| -> Result<(), ()> { - match progress { - Some(func) => { - if (func)(progress_ctxt, cur, max) { - Ok(()) - } else { - Err(()) + unsafe { + ffi_wrap!("run_progress_dialog", { + let context = ctxt as *mut TaskContext; + let progress_fn = Box::new(move |cur: usize, max: usize| -> Result<(), ()> { + match progress { + Some(func) => { + if (func)(progress_ctxt, cur, max) { + Ok(()) + } else { + Err(()) + } } + None => Ok(()), } - None => Ok(()), - } - }); - ((*context).0)(progress_fn); - }) + }); + ((*context).0)(progress_fn); + }) + } } let title = title.to_cstr(); diff --git a/rust/src/interaction/handler.rs b/rust/src/interaction/handler.rs index d4734d3444..770eb3b5b7 100644 --- a/rust/src/interaction/handler.rs +++ b/rust/src/interaction/handler.rs @@ -300,8 +300,10 @@ unsafe extern "C" fn cb_custom_interaction_handler_task bool { - let ctxt = ctxt as *mut P; - (*ctxt)(cur, max) + unsafe { + let ctxt = ctxt as *mut P; + (*ctxt)(cur, max) + } } unsafe extern "C" fn cb_show_plain_text_report( @@ -310,14 +312,16 @@ unsafe extern "C" fn cb_show_plain_text_report( title: *const c_char, contents: *const c_char, ) { - let ctxt = ctxt as *mut R; - let title = raw_to_string(title).unwrap(); - let contents = raw_to_string(contents).unwrap(); - let view = match !view.is_null() { - true => Some(BinaryView::from_raw(view)), - false => None, - }; - (*ctxt).show_plain_text_report(view.as_ref(), &title, &contents) + unsafe { + let ctxt = ctxt as *mut R; + let title = raw_to_string(title).unwrap(); + let contents = raw_to_string(contents).unwrap(); + let view = match !view.is_null() { + true => Some(BinaryView::from_raw(view)), + false => None, + }; + (*ctxt).show_plain_text_report(view.as_ref(), &title, &contents) + } } unsafe extern "C" fn cb_show_markdown_report( @@ -327,15 +331,17 @@ unsafe extern "C" fn cb_show_markdown_report( contents: *const c_char, plaintext: *const c_char, ) { - let ctxt = ctxt as *mut R; - let title = raw_to_string(title).unwrap(); - let contents = raw_to_string(contents).unwrap(); - let plaintext = raw_to_string(plaintext).unwrap(); - let view = match !view.is_null() { - true => Some(BinaryView::from_raw(view)), - false => None, - }; - (*ctxt).show_markdown_report(view.as_ref(), &title, &contents, &plaintext) + unsafe { + let ctxt = ctxt as *mut R; + let title = raw_to_string(title).unwrap(); + let contents = raw_to_string(contents).unwrap(); + let plaintext = raw_to_string(plaintext).unwrap(); + let view = match !view.is_null() { + true => Some(BinaryView::from_raw(view)), + false => None, + }; + (*ctxt).show_markdown_report(view.as_ref(), &title, &contents, &plaintext) + } } unsafe extern "C" fn cb_show_html_report( @@ -345,15 +351,17 @@ unsafe extern "C" fn cb_show_html_report( contents: *const c_char, plaintext: *const c_char, ) { - let ctxt = ctxt as *mut R; - let title = raw_to_string(title).unwrap(); - let contents = raw_to_string(contents).unwrap(); - let plaintext = raw_to_string(plaintext).unwrap(); - let view = match !view.is_null() { - true => Some(BinaryView::from_raw(view)), - false => None, - }; - (*ctxt).show_html_report(view.as_ref(), &title, &contents, &plaintext) + unsafe { + let ctxt = ctxt as *mut R; + let title = raw_to_string(title).unwrap(); + let contents = raw_to_string(contents).unwrap(); + let plaintext = raw_to_string(plaintext).unwrap(); + let view = match !view.is_null() { + true => Some(BinaryView::from_raw(view)), + false => None, + }; + (*ctxt).show_html_report(view.as_ref(), &title, &contents, &plaintext) + } } unsafe extern "C" fn cb_show_graph_report( @@ -362,13 +370,15 @@ unsafe extern "C" fn cb_show_graph_report( title: *const c_char, graph: *mut BNFlowGraph, ) { - let ctxt = ctxt as *mut R; - let title = raw_to_string(title).unwrap(); - let view = match !view.is_null() { - true => Some(BinaryView::from_raw(view)), - false => None, - }; - (*ctxt).show_graph_report(view.as_ref(), &title, &FlowGraph::from_raw(graph)) + unsafe { + let ctxt = ctxt as *mut R; + let title = raw_to_string(title).unwrap(); + let view = match !view.is_null() { + true => Some(BinaryView::from_raw(view)), + false => None, + }; + (*ctxt).show_graph_report(view.as_ref(), &title, &FlowGraph::from_raw(graph)) + } } unsafe extern "C" fn cb_show_report_collection( @@ -376,12 +386,14 @@ unsafe extern "C" fn cb_show_report_collection( title: *const c_char, report: *mut BNReportCollection, ) { - let ctxt = ctxt as *mut R; - let title = raw_to_string(title).unwrap(); - (*ctxt).show_report_collection( - &title, - &ReportCollection::from_raw(ptr::NonNull::new(report).unwrap()), - ) + unsafe { + let ctxt = ctxt as *mut R; + let title = raw_to_string(title).unwrap(); + (*ctxt).show_report_collection( + &title, + &ReportCollection::from_raw(ptr::NonNull::new(report).unwrap()), + ) + } } unsafe extern "C" fn cb_get_text_line_input( @@ -390,16 +402,22 @@ unsafe extern "C" fn cb_get_text_line_input( prompt: *const c_char, title: *const c_char, ) -> bool { - let ctxt = ctxt as *mut R; - let prompt = raw_to_string(prompt).unwrap(); - let title = raw_to_string(title).unwrap(); - let result = (*ctxt).get_text_line_input(&prompt, &title); - if let Some(result) = result { - unsafe { *result_ffi = BnString::into_raw(BnString::new(result)) }; - true - } else { - unsafe { *result_ffi = ptr::null_mut() }; - false + unsafe { + let ctxt = ctxt as *mut R; + let prompt = raw_to_string(prompt).unwrap(); + let title = raw_to_string(title).unwrap(); + let result = (*ctxt).get_text_line_input(&prompt, &title); + if let Some(result) = result { + { + *result_ffi = BnString::into_raw(BnString::new(result)) + }; + true + } else { + { + *result_ffi = ptr::null_mut() + }; + false + } } } @@ -409,16 +427,22 @@ unsafe extern "C" fn cb_get_integer_input( prompt: *const c_char, title: *const c_char, ) -> bool { - let ctxt = ctxt as *mut R; - let prompt = raw_to_string(prompt).unwrap(); - let title = raw_to_string(title).unwrap(); - let result = (*ctxt).get_integer_input(&prompt, &title); - if let Some(result) = result { - unsafe { *result_ffi = result }; - true - } else { - unsafe { *result_ffi = 0 }; - false + unsafe { + let ctxt = ctxt as *mut R; + let prompt = raw_to_string(prompt).unwrap(); + let title = raw_to_string(title).unwrap(); + let result = (*ctxt).get_integer_input(&prompt, &title); + if let Some(result) = result { + { + *result_ffi = result + }; + true + } else { + { + *result_ffi = 0 + }; + false + } } } @@ -430,17 +454,23 @@ unsafe extern "C" fn cb_get_address_input( view: *mut BNBinaryView, current_addr: u64, ) -> bool { - let ctxt = ctxt as *mut R; - let prompt = raw_to_string(prompt).unwrap(); - let title = raw_to_string(title).unwrap(); - let view = (!view.is_null()).then(|| BinaryView::from_raw(view)); - let result = (*ctxt).get_address_input(&prompt, &title, view.as_ref(), current_addr); - if let Some(result) = result { - unsafe { *result_ffi = result }; - true - } else { - unsafe { *result_ffi = 0 }; - false + unsafe { + let ctxt = ctxt as *mut R; + let prompt = raw_to_string(prompt).unwrap(); + let title = raw_to_string(title).unwrap(); + let view = (!view.is_null()).then(|| BinaryView::from_raw(view)); + let result = (*ctxt).get_address_input(&prompt, &title, view.as_ref(), current_addr); + if let Some(result) = result { + { + *result_ffi = result + }; + true + } else { + { + *result_ffi = 0 + }; + false + } } } @@ -452,23 +482,29 @@ unsafe extern "C" fn cb_get_choice_input( choices: *mut *const c_char, count: usize, ) -> bool { - let ctxt = ctxt as *mut R; - let prompt = raw_to_string(prompt).unwrap(); - let title = raw_to_string(title).unwrap(); - let choices = unsafe { core::slice::from_raw_parts(choices, count) }; - // SAFETY: BnString and *const c_char are transparent - let choices = unsafe { core::mem::transmute::<&[*const c_char], &[BnString]>(choices) }; - let choices: Vec = choices - .iter() - .map(|x| x.to_string_lossy().to_string()) - .collect(); - let result = (*ctxt).get_choice_input(&prompt, &title, choices); - if let Some(result) = result { - unsafe { *result_ffi = result }; - true - } else { - unsafe { *result_ffi = 0 }; - false + unsafe { + let ctxt = ctxt as *mut R; + let prompt = raw_to_string(prompt).unwrap(); + let title = raw_to_string(title).unwrap(); + let choices = { core::slice::from_raw_parts(choices, count) }; + // SAFETY: BnString and *const c_char are transparent + let choices = { core::mem::transmute::<&[*const c_char], &[BnString]>(choices) }; + let choices: Vec = choices + .iter() + .map(|x| x.to_string_lossy().to_string()) + .collect(); + let result = (*ctxt).get_choice_input(&prompt, &title, choices); + if let Some(result) = result { + { + *result_ffi = result + }; + true + } else { + { + *result_ffi = 0 + }; + false + } } } @@ -480,23 +516,29 @@ unsafe extern "C" fn cb_get_large_choice_input( choices: *mut *const c_char, count: usize, ) -> bool { - let ctxt = ctxt as *mut R; - let prompt = raw_to_string(prompt).unwrap(); - let title = raw_to_string(title).unwrap(); - let choices = unsafe { core::slice::from_raw_parts(choices, count) }; - // SAFETY: BnString and *const c_char are transparent - let choices = unsafe { core::mem::transmute::<&[*const c_char], &[BnString]>(choices) }; - let choices: Vec = choices - .iter() - .map(|x| x.to_string_lossy().to_string()) - .collect(); - let result = (*ctxt).get_large_choice_input(&prompt, &title, choices); - if let Some(result) = result { - unsafe { *result_ffi = result }; - true - } else { - unsafe { *result_ffi = 0 }; - false + unsafe { + let ctxt = ctxt as *mut R; + let prompt = raw_to_string(prompt).unwrap(); + let title = raw_to_string(title).unwrap(); + let choices = { core::slice::from_raw_parts(choices, count) }; + // SAFETY: BnString and *const c_char are transparent + let choices = { core::mem::transmute::<&[*const c_char], &[BnString]>(choices) }; + let choices: Vec = choices + .iter() + .map(|x| x.to_string_lossy().to_string()) + .collect(); + let result = (*ctxt).get_large_choice_input(&prompt, &title, choices); + if let Some(result) = result { + { + *result_ffi = result + }; + true + } else { + { + *result_ffi = 0 + }; + false + } } } @@ -506,17 +548,23 @@ unsafe extern "C" fn cb_get_open_file_name_input( prompt: *const c_char, ext: *const c_char, ) -> bool { - let ctxt = ctxt as *mut R; - let prompt = raw_to_string(prompt).unwrap(); - let ext = (!ext.is_null()).then(|| unsafe { CStr::from_ptr(ext) }); - let result = - (*ctxt).get_open_file_name_input(&prompt, ext.map(|x| x.to_string_lossy().to_string())); - if let Some(result) = result { - unsafe { *result_ffi = BnString::into_raw(BnString::new(result)) }; - true - } else { - unsafe { *result_ffi = ptr::null_mut() }; - false + unsafe { + let ctxt = ctxt as *mut R; + let prompt = raw_to_string(prompt).unwrap(); + let ext = (!ext.is_null()).then(|| CStr::from_ptr(ext)); + let result = + (*ctxt).get_open_file_name_input(&prompt, ext.map(|x| x.to_string_lossy().to_string())); + if let Some(result) = result { + { + *result_ffi = BnString::into_raw(BnString::new(result)) + }; + true + } else { + { + *result_ffi = ptr::null_mut() + }; + false + } } } @@ -527,17 +575,23 @@ unsafe extern "C" fn cb_get_save_file_name_input( ext: *const c_char, default_name: *const c_char, ) -> bool { - let ctxt = ctxt as *mut R; - let prompt = raw_to_string(prompt).unwrap(); - let ext = raw_to_string(ext); - let default_name = raw_to_string(default_name); - let result = (*ctxt).get_save_file_name_input(&prompt, ext, default_name); - if let Some(result) = result { - unsafe { *result_ffi = BnString::into_raw(BnString::new(result)) }; - true - } else { - unsafe { *result_ffi = ptr::null_mut() }; - false + unsafe { + let ctxt = ctxt as *mut R; + let prompt = raw_to_string(prompt).unwrap(); + let ext = raw_to_string(ext); + let default_name = raw_to_string(default_name); + let result = (*ctxt).get_save_file_name_input(&prompt, ext, default_name); + if let Some(result) = result { + { + *result_ffi = BnString::into_raw(BnString::new(result)) + }; + true + } else { + { + *result_ffi = ptr::null_mut() + }; + false + } } } @@ -547,16 +601,22 @@ unsafe extern "C" fn cb_get_directory_name_input( prompt: *const c_char, default_name: *const c_char, ) -> bool { - let ctxt = ctxt as *mut R; - let prompt = raw_to_string(prompt).unwrap(); - let default_name = raw_to_string(default_name); - let result = (*ctxt).get_directory_name_input(&prompt, default_name); - if let Some(result) = result { - unsafe { *result_ffi = BnString::into_raw(BnString::new(result)) }; - true - } else { - unsafe { *result_ffi = ptr::null_mut() }; - false + unsafe { + let ctxt = ctxt as *mut R; + let prompt = raw_to_string(prompt).unwrap(); + let default_name = raw_to_string(default_name); + let result = (*ctxt).get_directory_name_input(&prompt, default_name); + if let Some(result) = result { + { + *result_ffi = BnString::into_raw(BnString::new(result)) + }; + true + } else { + { + *result_ffi = ptr::null_mut() + }; + false + } } } @@ -567,17 +627,23 @@ unsafe extern "C" fn cb_get_checkbox_input( title: *const c_char, default_choice: *const i64, ) -> bool { - let ctxt = ctxt as *mut R; - let prompt = raw_to_string(prompt).unwrap(); - let title = raw_to_string(title).unwrap(); - let default = (!default_choice.is_null()).then(|| *default_choice); - let result = (*ctxt).get_checkbox_input(&prompt, &title, default); - if let Some(result) = result { - unsafe { *result_ffi = result }; - true - } else { - unsafe { *result_ffi = 0 }; - false + unsafe { + let ctxt = ctxt as *mut R; + let prompt = raw_to_string(prompt).unwrap(); + let title = raw_to_string(title).unwrap(); + let default = (!default_choice.is_null()).then(|| *default_choice); + let result = (*ctxt).get_checkbox_input(&prompt, &title, default); + if let Some(result) = result { + { + *result_ffi = result + }; + true + } else { + { + *result_ffi = 0 + }; + false + } } } @@ -587,24 +653,26 @@ unsafe extern "C" fn cb_get_form_input( count: usize, title: *const c_char, ) -> bool { - let ctxt = ctxt as *mut R; - let raw_fields = unsafe { core::slice::from_raw_parts_mut(fields, count) }; - let fields: Vec<_> = raw_fields - .iter_mut() - .map(|x| FormInputField::from_raw(x)) - .collect(); - let title = raw_to_string(title).unwrap(); - let mut form = Form::new_with_fields(title, fields); - let results = (*ctxt).get_form_input(&mut form); - // Update the fields with the new values. Freeing the old ones. - raw_fields - .iter_mut() - .enumerate() - .for_each(|(idx, raw_field)| { - FormInputField::free_raw(*raw_field); - *raw_field = form.fields[idx].into_raw(); - }); - results + unsafe { + let ctxt = ctxt as *mut R; + let raw_fields = { core::slice::from_raw_parts_mut(fields, count) }; + let fields: Vec<_> = raw_fields + .iter_mut() + .map(|x| FormInputField::from_raw(x)) + .collect(); + let title = raw_to_string(title).unwrap(); + let mut form = Form::new_with_fields(title, fields); + let results = (*ctxt).get_form_input(&mut form); + // Update the fields with the new values. Freeing the old ones. + raw_fields + .iter_mut() + .enumerate() + .for_each(|(idx, raw_field)| { + FormInputField::free_raw(*raw_field); + *raw_field = form.fields[idx].into_raw(); + }); + results + } } unsafe extern "C" fn cb_show_message_box( @@ -614,19 +682,23 @@ unsafe extern "C" fn cb_show_message_box( buttons: BNMessageBoxButtonSet, icon: BNMessageBoxIcon, ) -> BNMessageBoxButtonResult { - let ctxt = ctxt as *mut R; - let title = raw_to_string(title).unwrap(); - let text = raw_to_string(text).unwrap(); - (*ctxt).show_message_box(&title, &text, buttons, icon) + unsafe { + let ctxt = ctxt as *mut R; + let title = raw_to_string(title).unwrap(); + let text = raw_to_string(text).unwrap(); + (*ctxt).show_message_box(&title, &text, buttons, icon) + } } unsafe extern "C" fn cb_open_url( ctxt: *mut c_void, url: *const c_char, ) -> bool { - let ctxt = ctxt as *mut R; - let url = raw_to_string(url).unwrap(); - (*ctxt).open_url(&url) + unsafe { + let ctxt = ctxt as *mut R; + let url = raw_to_string(url).unwrap(); + (*ctxt).open_url(&url) + } } unsafe extern "C" fn cb_run_progress_dialog( @@ -642,11 +714,13 @@ unsafe extern "C" fn cb_run_progress_dialog( >, task_ctxt: *mut c_void, ) -> bool { - let ctxt = ctxt as *mut R; - let title = raw_to_string(title).unwrap(); - let task = InteractionHandlerTask { - ctxt: task_ctxt, - task, - }; - (*ctxt).run_progress_dialog(&title, can_cancel, &task) + unsafe { + let ctxt = ctxt as *mut R; + let title = raw_to_string(title).unwrap(); + let task = InteractionHandlerTask { + ctxt: task_ctxt, + task, + }; + (*ctxt).run_progress_dialog(&title, can_cancel, &task) + } } diff --git a/rust/src/language_representation.rs b/rust/src/language_representation.rs index 470d67b069..c732ebcf8e 100644 --- a/rust/src/language_representation.rs +++ b/rust/src/language_representation.rs @@ -221,16 +221,18 @@ impl CoreArrayProvider for CoreLanguageRepresentationFunctionType { unsafe impl CoreArrayProviderInner for CoreLanguageRepresentationFunctionType { unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { - BNFreeLanguageRepresentationFunctionTypeList(raw) + unsafe { BNFreeLanguageRepresentationFunctionTypeList(raw) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { - // SAFETY: CoreLanguageRepresentationFunctionType and BNCoreLanguageRepresentationFunctionType - // transparent - std::mem::transmute::< - &*mut BNLanguageRepresentationFunctionType, - &CoreLanguageRepresentationFunctionType, - >(raw) + unsafe { + // SAFETY: CoreLanguageRepresentationFunctionType and BNCoreLanguageRepresentationFunctionType + // transparent + std::mem::transmute::< + &*mut BNLanguageRepresentationFunctionType, + &CoreLanguageRepresentationFunctionType, + >(raw) + } } } @@ -407,16 +409,18 @@ impl CoreLanguageRepresentationFunction { unsafe impl RefCountable for CoreLanguageRepresentationFunction { unsafe fn inc_ref(handle: &Self) -> Ref { - Self::ref_from_raw( - NonNull::new(BNNewLanguageRepresentationFunctionReference( - handle.handle.as_ptr(), - )) - .unwrap(), - ) + unsafe { + Self::ref_from_raw( + NonNull::new(BNNewLanguageRepresentationFunctionReference( + handle.handle.as_ptr(), + )) + .unwrap(), + ) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeLanguageRepresentationFunction(handle.handle.as_ptr()) + unsafe { BNFreeLanguageRepresentationFunction(handle.handle.as_ptr()) } } } @@ -434,53 +438,63 @@ unsafe extern "C" fn cb_create( owner: *mut BNFunction, high_level_il: *mut BNHighLevelILFunction, ) -> *mut BNLanguageRepresentationFunction { - let ctxt = ctxt as *mut C; - let arch = CoreArchitecture::from_raw(arch); - let owner = Function::from_raw(owner); - let high_level_il = HighLevelILFunction { - full_ast: false, - handle: high_level_il, - }; - let result = (*ctxt).create(&arch, &owner, &high_level_il); - Ref::into_raw(result).handle.as_ptr() + unsafe { + let ctxt = ctxt as *mut C; + let arch = CoreArchitecture::from_raw(arch); + let owner = Function::from_raw(owner); + let high_level_il = HighLevelILFunction { + full_ast: false, + handle: high_level_il, + }; + let result = (*ctxt).create(&arch, &owner, &high_level_il); + Ref::into_raw(result).handle.as_ptr() + } } unsafe extern "C" fn cb_is_valid( ctxt: *mut c_void, view: *mut BNBinaryView, ) -> bool { - let ctxt = ctxt as *mut C; - let view = BinaryView::from_raw(view); - (*ctxt).is_valid(&view) + unsafe { + let ctxt = ctxt as *mut C; + let view = BinaryView::from_raw(view); + (*ctxt).is_valid(&view) + } } unsafe extern "C" fn cb_get_type_printer( ctxt: *mut c_void, ) -> *mut BNTypePrinter { - let ctxt = ctxt as *mut C; - match (*ctxt).type_printer() { - None => std::ptr::null_mut(), - Some(printer) => printer.handle.as_ptr(), + unsafe { + let ctxt = ctxt as *mut C; + match (*ctxt).type_printer() { + None => std::ptr::null_mut(), + Some(printer) => printer.handle.as_ptr(), + } } } unsafe extern "C" fn cb_get_type_parser( ctxt: *mut c_void, ) -> *mut BNTypeParser { - let ctxt = ctxt as *mut C; - match (*ctxt).type_parser() { - None => std::ptr::null_mut(), - Some(parser) => parser.handle.as_ptr(), + unsafe { + let ctxt = ctxt as *mut C; + match (*ctxt).type_parser() { + None => std::ptr::null_mut(), + Some(parser) => parser.handle.as_ptr(), + } } } unsafe extern "C" fn cb_get_line_formatter( ctxt: *mut c_void, ) -> *mut BNLineFormatter { - let ctxt = ctxt as *mut C; - match (*ctxt).line_formatter() { - None => std::ptr::null_mut(), - Some(formatter) => formatter.handle.as_ptr(), + unsafe { + let ctxt = ctxt as *mut C; + match (*ctxt).line_formatter() { + None => std::ptr::null_mut(), + Some(formatter) => formatter.handle.as_ptr(), + } } } @@ -490,17 +504,19 @@ unsafe extern "C" fn cb_get_function_type_tokens *mut BNDisassemblyTextLine { - let ctxt = ctxt as *mut C; - let func = Function::from_raw(func); - let settings = DisassemblySettings { handle: settings }; - let result = (*ctxt).function_type_tokens(&func, &settings); - *count = result.len(); - let result: Box<[BNDisassemblyTextLine]> = result - .into_iter() - .map(DisassemblyTextLine::into_raw) - .collect(); - // NOTE freed by function_type_free_lines_ffi - Box::leak(result).as_mut_ptr() + unsafe { + let ctxt = ctxt as *mut C; + let func = Function::from_raw(func); + let settings = DisassemblySettings { handle: settings }; + let result = (*ctxt).function_type_tokens(&func, &settings); + *count = result.len(); + let result: Box<[BNDisassemblyTextLine]> = result + .into_iter() + .map(DisassemblyTextLine::into_raw) + .collect(); + // NOTE freed by function_type_free_lines_ffi + Box::leak(result).as_mut_ptr() + } } unsafe extern "C" fn cb_free_lines( @@ -508,16 +524,20 @@ unsafe extern "C" fn cb_free_lines( lines: *mut BNDisassemblyTextLine, count: usize, ) { - let lines: Box<[BNDisassemblyTextLine]> = - Box::from_raw(std::ptr::slice_from_raw_parts_mut(lines, count)); - for line in lines { - DisassemblyTextLine::free_raw(line); + unsafe { + let lines: Box<[BNDisassemblyTextLine]> = + Box::from_raw(std::ptr::slice_from_raw_parts_mut(lines, count)); + for line in lines { + DisassemblyTextLine::free_raw(line); + } } } unsafe extern "C" fn cb_free_object(ctxt: *mut c_void) { - let ctxt = ctxt as *mut C; - drop(Box::from_raw(ctxt)) + unsafe { + let ctxt = ctxt as *mut C; + drop(Box::from_raw(ctxt)) + } } unsafe extern "C" fn cb_external_ref_taken(_ctxt: *mut c_void) { @@ -534,9 +554,11 @@ unsafe extern "C" fn cb_init_token_emitter( ctxt: *mut c_void, tokens: *mut BNHighLevelILTokenEmitter, ) { - let ctxt = ctxt as *mut C; - let tokens = HighLevelILTokenEmitter::from_raw(NonNull::new(tokens).unwrap()); - (*ctxt).on_token_emitter_init(&tokens) + unsafe { + let ctxt = ctxt as *mut C; + let tokens = HighLevelILTokenEmitter::from_raw(NonNull::new(tokens).unwrap()); + (*ctxt).on_token_emitter_init(&tokens) + } } unsafe extern "C" fn cb_get_expr_text( @@ -549,22 +571,24 @@ unsafe extern "C" fn cb_get_expr_text( precedence: BNOperatorPrecedence, statement: bool, ) { - let ctxt = ctxt as *mut C; - let il = HighLevelILFunction { - full_ast: as_full_ast, - handle: il, - }; - let tokens = HighLevelILTokenEmitter::from_raw(NonNull::new(tokens).unwrap()); - let settings = DisassemblySettings { handle: settings }; - (*ctxt).expr_text( - &il, - expr_index.into(), - &tokens, - &settings, - as_full_ast, - precedence, - statement, - ); + unsafe { + let ctxt = ctxt as *mut C; + let il = HighLevelILFunction { + full_ast: as_full_ast, + handle: il, + }; + let tokens = HighLevelILTokenEmitter::from_raw(NonNull::new(tokens).unwrap()); + let settings = DisassemblySettings { handle: settings }; + (*ctxt).expr_text( + &il, + expr_index.into(), + &tokens, + &settings, + as_full_ast, + precedence, + statement, + ); + } } unsafe extern "C" fn cb_begin_lines( @@ -573,13 +597,15 @@ unsafe extern "C" fn cb_begin_lines( expr_index: usize, tokens: *mut BNHighLevelILTokenEmitter, ) { - let ctxt = ctxt as *mut C; - let il = HighLevelILFunction { - full_ast: false, - handle: il, - }; - let tokens = HighLevelILTokenEmitter::from_raw(NonNull::new(tokens).unwrap()); - (*ctxt).begin_lines(&il, expr_index.into(), &tokens) + unsafe { + let ctxt = ctxt as *mut C; + let il = HighLevelILFunction { + full_ast: false, + handle: il, + }; + let tokens = HighLevelILTokenEmitter::from_raw(NonNull::new(tokens).unwrap()); + (*ctxt).begin_lines(&il, expr_index.into(), &tokens) + } } unsafe extern "C" fn cb_end_lines( @@ -588,43 +614,53 @@ unsafe extern "C" fn cb_end_lines( expr_index: usize, tokens: *mut BNHighLevelILTokenEmitter, ) { - let ctxt = ctxt as *mut C; - let il = HighLevelILFunction { - full_ast: false, - handle: il, - }; - let tokens = HighLevelILTokenEmitter::from_raw(NonNull::new(tokens).unwrap()); - (*ctxt).end_lines(&il, expr_index.into(), &tokens) + unsafe { + let ctxt = ctxt as *mut C; + let il = HighLevelILFunction { + full_ast: false, + handle: il, + }; + let tokens = HighLevelILTokenEmitter::from_raw(NonNull::new(tokens).unwrap()); + (*ctxt).end_lines(&il, expr_index.into(), &tokens) + } } unsafe extern "C" fn cb_get_comment_start_string( ctxt: *mut c_void, ) -> *mut c_char { - let ctxt = ctxt as *mut C; - let result = (*ctxt).comment_start_string(); - BnString::into_raw(BnString::new(result)) + unsafe { + let ctxt = ctxt as *mut C; + let result = (*ctxt).comment_start_string(); + BnString::into_raw(BnString::new(result)) + } } unsafe extern "C" fn cb_get_comment_end_string( ctxt: *mut c_void, ) -> *mut c_char { - let ctxt = ctxt as *mut C; - let result = (*ctxt).comment_end_string(); - BnString::into_raw(BnString::new(result)) + unsafe { + let ctxt = ctxt as *mut C; + let result = (*ctxt).comment_end_string(); + BnString::into_raw(BnString::new(result)) + } } unsafe extern "C" fn cb_get_annotation_start_string( ctxt: *mut c_void, ) -> *mut c_char { - let ctxt = ctxt as *mut C; - let result = (*ctxt).annotation_start_string(); - BnString::into_raw(BnString::new(result)) + unsafe { + let ctxt = ctxt as *mut C; + let result = (*ctxt).annotation_start_string(); + BnString::into_raw(BnString::new(result)) + } } unsafe extern "C" fn cb_get_annotation_end_string( ctxt: *mut c_void, ) -> *mut c_char { - let ctxt = ctxt as *mut C; - let result = (*ctxt).annotation_end_string(); - BnString::into_raw(BnString::new(result)) + unsafe { + let ctxt = ctxt as *mut C; + let result = (*ctxt).annotation_end_string(); + BnString::into_raw(BnString::new(result)) + } } diff --git a/rust/src/lib.rs b/rust/src/lib.rs index 854bbbcb1f..f79bb14125 100644 --- a/rust/src/lib.rs +++ b/rust/src/lib.rs @@ -613,7 +613,7 @@ pub fn add_optional_plugin_dependency(name: &str) { /// Exported function to tell the core what core ABI version this plugin was compiled against. #[cfg(not(feature = "no_exports"))] -#[no_mangle] +#[unsafe(no_mangle)] #[allow(non_snake_case)] pub extern "C" fn CorePluginABIVersion() -> u32 { plugin_abi_version() @@ -621,7 +621,7 @@ pub extern "C" fn CorePluginABIVersion() -> u32 { /// Exported function to tell the core what UI ABI version this plugin was compiled against. #[cfg(not(feature = "no_exports"))] -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn UIPluginABIVersion() -> u32 { plugin_ui_abi_version() } diff --git a/rust/src/line_formatter.rs b/rust/src/line_formatter.rs index 9e6460c7e2..1c347fa0af 100644 --- a/rust/src/line_formatter.rs +++ b/rust/src/line_formatter.rs @@ -69,7 +69,7 @@ impl CoreArrayProvider for CoreLineFormatter { unsafe impl CoreArrayProviderInner for CoreLineFormatter { unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { - BNFreeLineFormatterList(raw) + unsafe { BNFreeLineFormatterList(raw) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { @@ -137,21 +137,23 @@ unsafe extern "C" fn cb_format_lines( raw_settings: *const BNLineFormatterSettings, out_count: *mut usize, ) -> *mut BNDisassemblyTextLine { - // NOTE dropped by line_formatter_free_lines_ffi - let ctxt = ctxt as *mut C; - let lines_slice = core::slice::from_raw_parts(in_lines, in_count); - let lines: Vec<_> = lines_slice - .iter() - .map(DisassemblyTextLine::from_raw) - .collect(); - let settings = LineFormatterSettings::from_raw(&*raw_settings); - let result = (*ctxt).format_lines(&lines, &settings); - *out_count = result.len(); - let result: Box<[BNDisassemblyTextLine]> = result - .into_iter() - .map(DisassemblyTextLine::into_raw) - .collect(); - Box::leak(result).as_mut_ptr() + unsafe { + // NOTE dropped by line_formatter_free_lines_ffi + let ctxt = ctxt as *mut C; + let lines_slice = core::slice::from_raw_parts(in_lines, in_count); + let lines: Vec<_> = lines_slice + .iter() + .map(DisassemblyTextLine::from_raw) + .collect(); + let settings = LineFormatterSettings::from_raw(&*raw_settings); + let result = (*ctxt).format_lines(&lines, &settings); + *out_count = result.len(); + let result: Box<[BNDisassemblyTextLine]> = result + .into_iter() + .map(DisassemblyTextLine::into_raw) + .collect(); + Box::leak(result).as_mut_ptr() + } } unsafe extern "C" fn cb_free_lines( @@ -159,9 +161,11 @@ unsafe extern "C" fn cb_free_lines( raw_lines: *mut BNDisassemblyTextLine, count: usize, ) { - let lines: Box<[BNDisassemblyTextLine]> = - Box::from_raw(std::ptr::slice_from_raw_parts_mut(raw_lines, count)); - for line in lines { - DisassemblyTextLine::free_raw(line); + unsafe { + let lines: Box<[BNDisassemblyTextLine]> = + Box::from_raw(std::ptr::slice_from_raw_parts_mut(raw_lines, count)); + for line in lines { + DisassemblyTextLine::free_raw(line); + } } } diff --git a/rust/src/linear_view.rs b/rust/src/linear_view.rs index 7f518bd259..eb677aa6d0 100644 --- a/rust/src/linear_view.rs +++ b/rust/src/linear_view.rs @@ -40,8 +40,10 @@ impl LinearViewObject { } pub(crate) unsafe fn ref_from_raw(handle: *mut BNLinearViewObject) -> Ref { - debug_assert!(!handle.is_null()); - Ref::new(Self { handle }) + unsafe { + debug_assert!(!handle.is_null()); + Ref::new(Self { handle }) + } } pub fn identifier(&self) -> LinearViewObjectIdentifier { @@ -211,13 +213,17 @@ impl LinearViewObject { unsafe impl RefCountable for LinearViewObject { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: BNNewLinearViewObjectReference(handle.handle), - }) + unsafe { + Ref::new(Self { + handle: BNNewLinearViewObjectReference(handle.handle), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeLinearViewObject(handle.handle); + unsafe { + BNFreeLinearViewObject(handle.handle); + } } } @@ -279,8 +285,10 @@ pub struct LinearViewCursor { impl LinearViewCursor { pub(crate) unsafe fn ref_from_raw(handle: *mut BNLinearViewCursor) -> Ref { - debug_assert!(!handle.is_null()); - Ref::new(Self { handle }) + unsafe { + debug_assert!(!handle.is_null()); + Ref::new(Self { handle }) + } } /// Gets the current [`LinearViewObject`] associated with this cursor. @@ -402,13 +410,17 @@ impl Ord for LinearViewCursor { unsafe impl RefCountable for LinearViewCursor { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: BNNewLinearViewCursorReference(handle.handle), - }) + unsafe { + Ref::new(Self { + handle: BNNewLinearViewCursorReference(handle.handle), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeLinearViewCursor(handle.handle); + unsafe { + BNFreeLinearViewCursor(handle.handle); + } } } @@ -460,9 +472,11 @@ impl LinearDisassemblyLine { #[allow(unused)] pub(crate) unsafe fn from_owned_raw(value: BNLinearDisassemblyLine) -> Self { - let owned = Self::from_raw(&value); - Self::free_raw(value); - owned + unsafe { + let owned = Self::from_raw(&value); + Self::free_raw(value); + owned + } } pub(crate) fn into_raw(value: Self) -> BNLinearDisassemblyLine { @@ -522,10 +536,12 @@ impl CoreArrayProvider for LinearDisassemblyLine { unsafe impl CoreArrayProviderInner for LinearDisassemblyLine { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeLinearDisassemblyLines(raw, count); + unsafe { + BNFreeLinearDisassemblyLines(raw, count); + } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { - Self::from_raw(raw) + unsafe { Self::from_raw(raw) } } } diff --git a/rust/src/logger.rs b/rust/src/logger.rs index d2903a5a46..7d591df185 100644 --- a/rust/src/logger.rs +++ b/rust/src/logger.rs @@ -130,13 +130,17 @@ impl ToOwned for Logger { unsafe impl RefCountable for Logger { unsafe fn inc_ref(logger: &Self) -> Ref { - Ref::new(Self { - handle: NonNull::new(BNNewLoggerReference(logger.handle.as_ptr())).unwrap(), - }) + unsafe { + Ref::new(Self { + handle: NonNull::new(BNNewLoggerReference(logger.handle.as_ptr())).unwrap(), + }) + } } unsafe fn dec_ref(logger: &Self) { - BNFreeLogger(logger.handle.as_ptr()); + unsafe { + BNFreeLogger(logger.handle.as_ptr()); + } } } diff --git a/rust/src/low_level_il/expression.rs b/rust/src/low_level_il/expression.rs index 233b06a55f..ac4fff393e 100644 --- a/rust/src/low_level_il/expression.rs +++ b/rust/src/low_level_il/expression.rs @@ -664,7 +664,7 @@ where use LowLevelILExpressionKind::*; macro_rules! visit { - ($expr:expr) => { + ($expr:expr_2021) => { if let VisitorAction::Halt = visitor($expr) { return VisitorAction::Halt; } @@ -672,50 +672,46 @@ where } match self { - CmpE(ref op) | CmpNe(ref op) | CmpSlt(ref op) | CmpUlt(ref op) | CmpSle(ref op) - | CmpUle(ref op) | CmpSge(ref op) | CmpUge(ref op) | CmpSgt(ref op) - | CmpUgt(ref op) | FcmpE(ref op) | FcmpNE(ref op) | FcmpLT(ref op) | FcmpLE(ref op) - | FcmpGE(ref op) | FcmpGT(ref op) | FcmpO(ref op) | FcmpUO(ref op) => { + CmpE(op) | CmpNe(op) | CmpSlt(op) | CmpUlt(op) | CmpSle(op) | CmpUle(op) + | CmpSge(op) | CmpUge(op) | CmpSgt(op) | CmpUgt(op) | FcmpE(op) | FcmpNE(op) + | FcmpLT(op) | FcmpLE(op) | FcmpGE(op) | FcmpGT(op) | FcmpO(op) | FcmpUO(op) => { visit!(op.left()); visit!(op.right()); } - Adc(ref op) | Sbb(ref op) | Rlc(ref op) | Rrc(ref op) => { + Adc(op) | Sbb(op) | Rlc(op) | Rrc(op) => { visit!(op.left()); visit!(op.right()); visit!(op.carry()); } - Add(ref op) | AddOverflow(ref op) | Sub(ref op) | And(ref op) | Or(ref op) - | Xor(ref op) | Lsl(ref op) | Lsr(ref op) | Asr(ref op) | Rol(ref op) | Ror(ref op) - | Mul(ref op) | MulsDp(ref op) | MuluDp(ref op) | Divu(ref op) | Divs(ref op) - | Modu(ref op) | Mods(ref op) | Fadd(ref op) | Fsub(ref op) | Fmul(ref op) - | DivuDp(ref op) | DivsDp(ref op) | ModuDp(ref op) | ModsDp(ref op) | Fdiv(ref op) - | MinSigned(ref op) | MaxSigned(ref op) | MinUnsigned(ref op) | MaxUnsigned(ref op) - | TestBit(ref op) => { + Add(op) | AddOverflow(op) | Sub(op) | And(op) | Or(op) | Xor(op) | Lsl(op) + | Lsr(op) | Asr(op) | Rol(op) | Ror(op) | Mul(op) | MulsDp(op) | MuluDp(op) + | Divu(op) | Divs(op) | Modu(op) | Mods(op) | Fadd(op) | Fsub(op) | Fmul(op) + | DivuDp(op) | DivsDp(op) | ModuDp(op) | ModsDp(op) | Fdiv(op) | MinSigned(op) + | MaxSigned(op) | MinUnsigned(op) | MaxUnsigned(op) | TestBit(op) => { visit!(op.left()); visit!(op.right()); } - Neg(ref op) | Not(ref op) | Bswap(ref op) | Popcnt(ref op) | Clz(ref op) - | Ctz(ref op) | Rbit(ref op) | Cls(ref op) | Abs(ref op) | Sx(ref op) | Zx(ref op) - | LowPart(ref op) | BoolToInt(ref op) | Fsqrt(ref op) | Fneg(ref op) | Fabs(ref op) - | FloatToInt(ref op) | IntToFloat(ref op) | FloatConv(ref op) | RoundToInt(ref op) - | Floor(ref op) | Ceil(ref op) | Ftrunc(ref op) => { + Neg(op) | Not(op) | Bswap(op) | Popcnt(op) | Clz(op) | Ctz(op) | Rbit(op) | Cls(op) + | Abs(op) | Sx(op) | Zx(op) | LowPart(op) | BoolToInt(op) | Fsqrt(op) | Fneg(op) + | Fabs(op) | FloatToInt(op) | IntToFloat(op) | FloatConv(op) | RoundToInt(op) + | Floor(op) | Ceil(op) | Ftrunc(op) => { visit!(op.operand()); } - UnimplMem(ref op) => { + UnimplMem(op) => { visit!(op.mem_expr()); } - Load(ref op) => { + Load(op) => { visit!(op.source_expr()); } - LoadSsa(ref op) => { + LoadSsa(op) => { visit!(op.source_expr()); } - CallParamSsa(ref op) => { + CallParamSsa(op) => { for param_expr in op.param_exprs() { visit!(param_expr); } } - SeparateParamListSsa(ref op) => { + SeparateParamListSsa(op) => { for param_expr in op.param_exprs() { visit!(param_expr); } diff --git a/rust/src/low_level_il/function.rs b/rust/src/low_level_il/function.rs index a0db838b8a..896c1edde5 100644 --- a/rust/src/low_level_il/function.rs +++ b/rust/src/low_level_il/function.rs @@ -72,19 +72,21 @@ where } pub unsafe fn from_raw(handle: *mut BNLowLevelILFunction) -> Self { - Self::from_raw_with_arch(handle, None) + unsafe { Self::from_raw_with_arch(handle, None) } } pub(crate) unsafe fn ref_from_raw_with_arch( handle: *mut BNLowLevelILFunction, arch: Option, ) -> Ref { - debug_assert!(!handle.is_null()); - Ref::new(Self::from_raw_with_arch(handle, arch)) + unsafe { + debug_assert!(!handle.is_null()); + Ref::new(Self::from_raw_with_arch(handle, arch)) + } } pub(crate) unsafe fn ref_from_raw(handle: *mut BNLowLevelILFunction) -> Ref { - Self::ref_from_raw_with_arch(handle, None) + unsafe { Self::ref_from_raw_with_arch(handle, None) } } pub(crate) fn arch(&self) -> CoreArchitecture { @@ -395,16 +397,20 @@ where F: FunctionForm, { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: BNNewLowLevelILFunctionReference(handle.handle), - arch: handle.arch, - _mutability: PhantomData, - _form: PhantomData, - }) + unsafe { + Ref::new(Self { + handle: BNNewLowLevelILFunctionReference(handle.handle), + arch: handle.arch, + _mutability: PhantomData, + _form: PhantomData, + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeLowLevelILFunction(handle.handle); + unsafe { + BNFreeLowLevelILFunction(handle.handle); + } } } diff --git a/rust/src/low_level_il/instruction.rs b/rust/src/low_level_il/instruction.rs index 720117fbb5..51512dca00 100644 --- a/rust/src/low_level_il/instruction.rs +++ b/rust/src/low_level_il/instruction.rs @@ -61,7 +61,7 @@ impl CoreArrayProvider for LowLevelInstructionIndex { unsafe impl CoreArrayProviderInner for LowLevelInstructionIndex { unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { - BNFreeILInstructionList(raw) + unsafe { BNFreeILInstructionList(raw) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { @@ -398,7 +398,7 @@ where use LowLevelILInstructionKind::*; macro_rules! visit { - ($expr:expr) => { + ($expr:expr_2021) => { if let VisitorAction::Halt = visitor($expr) { return VisitorAction::Halt; } @@ -406,35 +406,35 @@ where } match self { - SetReg(ref op) => visit!(&op.source_expr()), - SetRegSsa(ref op) => visit!(&op.source_expr()), - SetRegPartialSsa(ref op) => visit!(&op.source_expr()), - SetRegSplit(ref op) => visit!(&op.source_expr()), - SetRegSplitSsa(ref op) => visit!(&op.source_expr()), - SetFlag(ref op) => visit!(&op.source_expr()), - SetFlagSsa(ref op) => visit!(&op.source_expr()), - Store(ref op) => { + SetReg(op) => visit!(&op.source_expr()), + SetRegSsa(op) => visit!(&op.source_expr()), + SetRegPartialSsa(op) => visit!(&op.source_expr()), + SetRegSplit(op) => visit!(&op.source_expr()), + SetRegSplitSsa(op) => visit!(&op.source_expr()), + SetFlag(op) => visit!(&op.source_expr()), + SetFlagSsa(op) => visit!(&op.source_expr()), + Store(op) => { visit!(&op.dest_expr()); visit!(&op.source_expr()); } - StoreSsa(ref op) => { + StoreSsa(op) => { visit!(&op.dest_expr()); visit!(&op.source_expr()); } - Push(ref op) => visit!(&op.operand()), - RegStackPush(ref op) => visit!(&op.source_expr()), - Jump(ref op) => visit!(&op.target()), - JumpTo(ref op) => visit!(&op.target()), - SyscallSsa(ref op) => { + Push(op) => visit!(&op.operand()), + RegStackPush(op) => visit!(&op.source_expr()), + Jump(op) => visit!(&op.target()), + JumpTo(op) => visit!(&op.target()), + SyscallSsa(op) => { visit!(&op.output_expr()); visit!(&op.param_expr()); visit!(&op.stack_expr()); } - Call(ref op) | TailCall(ref op) => visit!(&op.target()), - CallSsa(ref op) | TailCallSsa(ref op) => visit!(&op.target()), - Ret(ref op) => visit!(&op.target()), - If(ref op) => visit!(&op.condition()), - Intrinsic(ref _op) => { + Call(op) | TailCall(op) => visit!(&op.target()), + CallSsa(op) | TailCallSsa(op) => visit!(&op.target()), + Ret(op) => visit!(&op.target()), + If(op) => visit!(&op.condition()), + Intrinsic(_op) => { // TODO: Visit when we support expression lists } Value(e) => visit!(e), diff --git a/rust/src/low_level_il/lifting.rs b/rust/src/low_level_il/lifting.rs index e2fb84e425..e3e8987862 100644 --- a/rust/src/low_level_il/lifting.rs +++ b/rust/src/low_level_il/lifting.rs @@ -303,7 +303,7 @@ impl LowLevelILFlagWriteOp { } macro_rules! op { - ($x:ident, $($ops:expr),*) => { + ($x:ident, $($ops:expr_2021),*) => { ( $x(size, $( build_op(arch, size, &operands[$ops]), )* ) ) }; } @@ -1059,14 +1059,16 @@ impl LowLevelILMutableFunction { replaced_expr_index: LowLevelExpressionIndex, replacement: E, ) -> bool { - use binaryninjacore_sys::BNReplaceLowLevelILExpr; - if replaced_expr_index.0 >= self.expression_count() { - // Invalid expression index, cant replace expression. - return false; + unsafe { + use binaryninjacore_sys::BNReplaceLowLevelILExpr; + if replaced_expr_index.0 >= self.expression_count() { + // Invalid expression index, cant replace expression. + return false; + } + let expr = self.expression(replacement); + BNReplaceLowLevelILExpr(self.handle, replaced_expr_index.0, expr.index.0); + true } - let expr = self.expression(replacement); - BNReplaceLowLevelILExpr(self.handle, replaced_expr_index.0, expr.index.0); - true } pub fn const_int(&self, size: usize, val: u64) -> LowLevelILMutableExpression<'_, ValueExpr> { diff --git a/rust/src/main_thread.rs b/rust/src/main_thread.rs index cf4c37f199..6c74e50a46 100644 --- a/rust/src/main_thread.rs +++ b/rust/src/main_thread.rs @@ -12,8 +12,10 @@ pub struct MainThreadActionExecutor { impl MainThreadActionExecutor { unsafe extern "C" fn cb_execute(ctx: *mut c_void) { - let f: Box = Box::from_raw(ctx as *mut Self); - f.execute(); + unsafe { + let f: Box = Box::from_raw(ctx as *mut Self); + f.execute(); + } } pub fn execute(&self) { @@ -58,11 +60,13 @@ pub trait MainThreadHandler: Sized { fn add_action(&self, _view: Ref); unsafe extern "C" fn cb_add_action(ctxt: *mut c_void, action: *mut BNMainThreadAction) { - ffi_wrap!("MainThread::add_action", { - let main_thread = &*(ctxt as *mut Self); - let action = MainThreadAction::ref_from_raw(action); - main_thread.add_action(action); - }) + unsafe { + ffi_wrap!("MainThread::add_action", { + let main_thread = &*(ctxt as *mut Self); + let action = MainThreadAction::ref_from_raw(action); + main_thread.add_action(action); + }) + } } /// Register the main thread handler. Leaking [`Self`] in the process. @@ -116,13 +120,17 @@ impl ToOwned for MainThreadAction { unsafe impl RefCountable for MainThreadAction { unsafe fn inc_ref(action: &Self) -> Ref { - Ref::new(Self { - handle: BNNewMainThreadActionReference(action.handle), - }) + unsafe { + Ref::new(Self { + handle: BNNewMainThreadActionReference(action.handle), + }) + } } unsafe fn dec_ref(action: &Self) { - BNFreeMainThreadAction(action.handle); + unsafe { + BNFreeMainThreadAction(action.handle); + } } } diff --git a/rust/src/medium_level_il/function.rs b/rust/src/medium_level_il/function.rs index d437adde6f..5fb22aa2fe 100644 --- a/rust/src/medium_level_il/function.rs +++ b/rust/src/medium_level_il/function.rs @@ -28,8 +28,10 @@ impl MediumLevelILFunction { } pub(crate) unsafe fn ref_from_raw(handle: *mut BNMediumLevelILFunction) -> Ref { - debug_assert!(!handle.is_null()); - Ref::new(Self::from_raw(handle)) + unsafe { + debug_assert!(!handle.is_null()); + Ref::new(Self::from_raw(handle)) + } } pub fn instruction_at>(&self, loc: L) -> Option { @@ -485,13 +487,17 @@ impl ToOwned for MediumLevelILFunction { unsafe impl RefCountable for MediumLevelILFunction { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: BNNewMediumLevelILFunctionReference(handle.handle), - }) + unsafe { + Ref::new(Self { + handle: BNNewMediumLevelILFunctionReference(handle.handle), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeMediumLevelILFunction(handle.handle); + unsafe { + BNFreeMediumLevelILFunction(handle.handle); + } } } @@ -560,7 +566,7 @@ impl CoreArrayProvider for ILReferenceSource { unsafe impl CoreArrayProviderInner for ILReferenceSource { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeILReferences(raw, count) + unsafe { BNFreeILReferences(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { @@ -601,7 +607,7 @@ impl CoreArrayProvider for VariableReferenceSource { unsafe impl CoreArrayProviderInner for VariableReferenceSource { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeVariableReferenceSourceList(raw, count) + unsafe { BNFreeVariableReferenceSourceList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { diff --git a/rust/src/medium_level_il/instruction.rs b/rust/src/medium_level_il/instruction.rs index 69936e6038..36ed2aaf8c 100644 --- a/rust/src/medium_level_il/instruction.rs +++ b/rust/src/medium_level_il/instruction.rs @@ -1800,7 +1800,7 @@ impl CoreArrayProvider for MediumLevelILInstruction { unsafe impl CoreArrayProviderInner for MediumLevelILInstruction { unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { - BNFreeILInstructionList(raw) + unsafe { BNFreeILInstructionList(raw) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { diff --git a/rust/src/metadata.rs b/rust/src/metadata.rs index b6a88eef4f..2006dfd2b5 100644 --- a/rust/src/metadata.rs +++ b/rust/src/metadata.rs @@ -20,7 +20,7 @@ impl Metadata { } pub(crate) unsafe fn ref_from_raw(handle: *mut BNMetadata) -> Ref { - Ref::new(Self::from_raw(handle)) + unsafe { Ref::new(Self::from_raw(handle)) } } pub fn new_of_type(metadata_type: MetadataType) -> Ref { @@ -394,13 +394,17 @@ unsafe impl Send for Metadata {} unsafe impl RefCountable for Metadata { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: BNNewMetadataReference(handle.handle), - }) + unsafe { + Ref::new(Self { + handle: BNNewMetadataReference(handle.handle), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeMetadata(handle.handle); + unsafe { + BNFreeMetadata(handle.handle); + } } } @@ -412,12 +416,14 @@ impl CoreArrayProvider for Metadata { unsafe impl CoreArrayProviderInner for Metadata { unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { - // TODO: `count` is not passed into the core here... - BNFreeMetadataArray(raw); + unsafe { + // TODO: `count` is not passed into the core here... + BNFreeMetadataArray(raw); + } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - Guard::new(Self::from_raw(*raw), context) + unsafe { Guard::new(Self::from_raw(*raw), context) } } } diff --git a/rust/src/object_destructor.rs b/rust/src/object_destructor.rs index aff5e4f0d0..c78400d1c7 100644 --- a/rust/src/object_destructor.rs +++ b/rust/src/object_destructor.rs @@ -63,31 +63,37 @@ unsafe extern "C" fn cb_destruct_binary_view( ctxt: *mut c_void, view: *mut BNBinaryView, ) { - ffi_wrap!("ObjectDestructor::destruct_view", { - let destructor = &*(ctxt as *mut D); - let view = BinaryView { handle: view }; - destructor.destruct_view(&view); - }) + unsafe { + ffi_wrap!("ObjectDestructor::destruct_view", { + let destructor = &*(ctxt as *mut D); + let view = BinaryView { handle: view }; + destructor.destruct_view(&view); + }) + } } unsafe extern "C" fn cb_destruct_file_metadata( ctxt: *mut c_void, file: *mut BNFileMetadata, ) { - ffi_wrap!("ObjectDestructor::destruct_file_metadata", { - let destructor = &*(ctxt as *mut D); - let file = FileMetadata::from_raw(file); - destructor.destruct_file_metadata(&file); - }) + unsafe { + ffi_wrap!("ObjectDestructor::destruct_file_metadata", { + let destructor = &*(ctxt as *mut D); + let file = FileMetadata::from_raw(file); + destructor.destruct_file_metadata(&file); + }) + } } unsafe extern "C" fn cb_destruct_function( ctxt: *mut c_void, func: *mut BNFunction, ) { - ffi_wrap!("ObjectDestructor::destruct_function", { - let destructor = &*(ctxt as *mut D); - let func = Function { handle: func }; - destructor.destruct_function(&func); - }) + unsafe { + ffi_wrap!("ObjectDestructor::destruct_function", { + let destructor = &*(ctxt as *mut D); + let func = Function { handle: func }; + destructor.destruct_function(&func); + }) + } } diff --git a/rust/src/platform.rs b/rust/src/platform.rs index 9de125a1c3..27f63cbc5d 100644 --- a/rust/src/platform.rs +++ b/rust/src/platform.rs @@ -80,8 +80,10 @@ impl Platform { } pub(crate) unsafe fn ref_from_raw(handle: *mut BNPlatform) -> Ref { - debug_assert!(!handle.is_null()); - Ref::new(Self { handle }) + unsafe { + debug_assert!(!handle.is_null()); + Ref::new(Self { handle }) + } } pub fn by_name(name: &str) -> Option> { @@ -441,13 +443,17 @@ impl ToOwned for Platform { unsafe impl RefCountable for Platform { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: BNNewPlatformReference(handle.handle), - }) + unsafe { + Ref::new(Self { + handle: BNNewPlatformReference(handle.handle), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreePlatform(handle.handle); + unsafe { + BNFreePlatform(handle.handle); + } } } @@ -459,11 +465,15 @@ impl CoreArrayProvider for Platform { unsafe impl CoreArrayProviderInner for Platform { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreePlatformList(raw, count); + unsafe { + BNFreePlatformList(raw, count); + } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - debug_assert!(!raw.is_null()); - Guard::new(Self::from_raw(*raw), context) + unsafe { + debug_assert!(!raw.is_null()); + Guard::new(Self::from_raw(*raw), context) + } } } diff --git a/rust/src/progress.rs b/rust/src/progress.rs index 6280a7b66d..79d5e71b6f 100644 --- a/rust/src/progress.rs +++ b/rust/src/progress.rs @@ -13,8 +13,10 @@ pub trait ProgressCallback: Sized { progress: usize, total: usize, ) -> bool { - let ctxt: &mut Self = &mut *(ctxt as *mut Self); - ctxt.progress(progress, total) + unsafe { + let ctxt: &mut Self = &mut *(ctxt as *mut Self); + ctxt.progress(progress, total) + } } #[allow(clippy::wrong_self_convention)] diff --git a/rust/src/project.rs b/rust/src/project.rs index 7188ed59d6..5a568f7ab2 100644 --- a/rust/src/project.rs +++ b/rust/src/project.rs @@ -29,7 +29,7 @@ impl Project { } pub unsafe fn ref_from_raw(handle: NonNull) -> Ref { - Ref::new(Self { handle }) + unsafe { Ref::new(Self { handle }) } } /// All of the open [`Project`]s @@ -374,15 +374,17 @@ impl Project { id: &str, creation_time: SystemTime, ) -> Result, ()> { - self.create_file_from_path_unsafe_with_progress( - path, - folder, - name, - description, - id, - creation_time, - NoProgressCallback, - ) + unsafe { + self.create_file_from_path_unsafe_with_progress( + path, + folder, + name, + description, + id, + creation_time, + NoProgressCallback, + ) + } } /// Create a file in the project from a path on disk @@ -500,15 +502,17 @@ impl Project { id: &str, creation_time: SystemTime, ) -> Result, ()> { - self.create_file_unsafe_with_progress( - contents, - folder, - name, - description, - id, - creation_time, - NoProgressCallback, - ) + unsafe { + self.create_file_unsafe_with_progress( + contents, + folder, + name, + description, + id, + creation_time, + NoProgressCallback, + ) + } } /// Create a file in the project @@ -666,13 +670,17 @@ impl ToOwned for Project { unsafe impl RefCountable for Project { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: NonNull::new(BNNewProjectReference(handle.handle.as_ptr())).unwrap(), - }) + unsafe { + Ref::new(Self { + handle: NonNull::new(BNNewProjectReference(handle.handle.as_ptr())).unwrap(), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeProject(handle.handle.as_ptr()); + unsafe { + BNFreeProject(handle.handle.as_ptr()); + } } } @@ -687,12 +695,14 @@ impl CoreArrayProvider for Project { unsafe impl CoreArrayProviderInner for Project { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeProjectList(raw, count) + unsafe { BNFreeProjectList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - let raw_ptr = NonNull::new(*raw).unwrap(); - Guard::new(Self::from_raw(raw_ptr), context) + unsafe { + let raw_ptr = NonNull::new(*raw).unwrap(); + Guard::new(Self::from_raw(raw_ptr), context) + } } } diff --git a/rust/src/project/file.rs b/rust/src/project/file.rs index d016d377d4..ba0e4e8eef 100644 --- a/rust/src/project/file.rs +++ b/rust/src/project/file.rs @@ -27,7 +27,7 @@ impl ProjectFile { } pub(crate) unsafe fn ref_from_raw(handle: NonNull) -> Ref { - Ref::new(Self { handle }) + unsafe { Ref::new(Self { handle }) } } /// Get the project that owns this file @@ -180,13 +180,17 @@ impl ToOwned for ProjectFile { unsafe impl RefCountable for ProjectFile { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: NonNull::new(BNNewProjectFileReference(handle.handle.as_ptr())).unwrap(), - }) + unsafe { + Ref::new(Self { + handle: NonNull::new(BNNewProjectFileReference(handle.handle.as_ptr())).unwrap(), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeProjectFile(handle.handle.as_ptr()); + unsafe { + BNFreeProjectFile(handle.handle.as_ptr()); + } } } @@ -198,11 +202,13 @@ impl CoreArrayProvider for ProjectFile { unsafe impl CoreArrayProviderInner for ProjectFile { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeProjectFileList(raw, count) + unsafe { BNFreeProjectFileList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - let raw_ptr = NonNull::new(*raw).unwrap(); - Guard::new(Self::from_raw(raw_ptr), context) + unsafe { + let raw_ptr = NonNull::new(*raw).unwrap(); + Guard::new(Self::from_raw(raw_ptr), context) + } } } diff --git a/rust/src/project/folder.rs b/rust/src/project/folder.rs index e14b84a804..d6dc442020 100644 --- a/rust/src/project/folder.rs +++ b/rust/src/project/folder.rs @@ -26,7 +26,7 @@ impl ProjectFolder { } pub(crate) unsafe fn ref_from_raw(handle: NonNull) -> Ref { - Ref::new(Self { handle }) + unsafe { Ref::new(Self { handle }) } } /// Get the project that owns this folder @@ -140,13 +140,17 @@ impl ToOwned for ProjectFolder { unsafe impl RefCountable for ProjectFolder { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: NonNull::new(BNNewProjectFolderReference(handle.handle.as_ptr())).unwrap(), - }) + unsafe { + Ref::new(Self { + handle: NonNull::new(BNNewProjectFolderReference(handle.handle.as_ptr())).unwrap(), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeProjectFolder(handle.handle.as_ptr()); + unsafe { + BNFreeProjectFolder(handle.handle.as_ptr()); + } } } @@ -158,11 +162,13 @@ impl CoreArrayProvider for ProjectFolder { unsafe impl CoreArrayProviderInner for ProjectFolder { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeProjectFolderList(raw, count) + unsafe { BNFreeProjectFolderList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - let raw_ptr = NonNull::new(*raw).unwrap(); - Guard::new(Self::from_raw(raw_ptr), context) + unsafe { + let raw_ptr = NonNull::new(*raw).unwrap(); + Guard::new(Self::from_raw(raw_ptr), context) + } } } diff --git a/rust/src/qualified_name.rs b/rust/src/qualified_name.rs index aed045a06c..e46866d470 100644 --- a/rust/src/qualified_name.rs +++ b/rust/src/qualified_name.rs @@ -270,7 +270,9 @@ impl CoreArrayProvider for QualifiedName { unsafe impl CoreArrayProviderInner for QualifiedName { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeTypeNameList(raw, count); + unsafe { + BNFreeTypeNameList(raw, count); + } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { diff --git a/rust/src/rc.rs b/rust/src/rc.rs index 7635455ac4..046cad4f54 100644 --- a/rust/src/rc.rs +++ b/rust/src/rc.rs @@ -56,9 +56,11 @@ impl Ref { } pub unsafe fn into_raw(obj: Self) -> T { - let res = ptr::read(&obj.contents); - mem::forget(obj); - res + unsafe { + let res = ptr::read(&obj.contents); + mem::forget(obj); + res + } } } diff --git a/rust/src/references.rs b/rust/src/references.rs index 52fb671368..19e7511475 100644 --- a/rust/src/references.rs +++ b/rust/src/references.rs @@ -78,7 +78,7 @@ impl CoreArrayProvider for CodeReference { unsafe impl CoreArrayProviderInner for CodeReference { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeCodeReferences(raw, count) + unsafe { BNFreeCodeReferences(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { @@ -103,7 +103,7 @@ impl CoreArrayProvider for DataReference { unsafe impl CoreArrayProviderInner for DataReference { unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { - BNFreeDataReferences(raw) + unsafe { BNFreeDataReferences(raw) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { diff --git a/rust/src/relocation.rs b/rust/src/relocation.rs index a2c3822115..28d705a57f 100644 --- a/rust/src/relocation.rs +++ b/rust/src/relocation.rs @@ -192,7 +192,8 @@ impl Relocation { } pub fn info(&self) -> RelocationInfo { - RelocationInfo::from_raw(unsafe { &BNRelocationGetInfo(self.0) }) + let info = unsafe { BNRelocationGetInfo(self.0) }; + RelocationInfo::from_raw(&info) } pub fn architecture(&self) -> Option { @@ -230,11 +231,13 @@ impl CoreArrayProvider for Relocation { unsafe impl CoreArrayProviderInner for Relocation { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeRelocationList(raw, count); + unsafe { + BNFreeRelocationList(raw, count); + } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { - Guard::new(Relocation(*raw), &()) + unsafe { Guard::new(Relocation(*raw), &()) } } } @@ -394,11 +397,13 @@ impl ToOwned for CoreRelocationHandler { unsafe impl RefCountable for CoreRelocationHandler { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self(BNNewRelocationHandlerReference(handle.0))) + unsafe { Ref::new(Self(BNNewRelocationHandlerReference(handle.0))) } } unsafe fn dec_ref(handle: &Self) { - BNFreeRelocationHandler(handle.0); + unsafe { + BNFreeRelocationHandler(handle.0); + } } } diff --git a/rust/src/render_layer.rs b/rust/src/render_layer.rs index 59430b3d68..dc7a0b3452 100644 --- a/rust/src/render_layer.rs +++ b/rust/src/render_layer.rs @@ -365,7 +365,7 @@ impl CoreArrayProvider for CoreRenderLayer { unsafe impl CoreArrayProviderInner for CoreRenderLayer { unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { - BNFreeRenderLayerList(raw) + unsafe { BNFreeRenderLayerList(raw) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { @@ -379,10 +379,12 @@ unsafe extern "C" fn cb_apply_to_flow_graph( ctxt: *mut c_void, graph: *mut BNFlowGraph, ) { - let ctxt: &mut T = &mut *(ctxt as *mut T); - // SAFETY: We do not own the flowgraph, do not take it as Ref. - let mut flow_graph = FlowGraph::from_raw(graph); - ctxt.apply_to_flow_graph(&mut flow_graph); + unsafe { + let ctxt: &mut T = &mut *(ctxt as *mut T); + // SAFETY: We do not own the flowgraph, do not take it as Ref. + let mut flow_graph = FlowGraph::from_raw(graph); + ctxt.apply_to_flow_graph(&mut flow_graph); + } } unsafe extern "C" fn cb_apply_to_linear_view_object( @@ -395,43 +397,45 @@ unsafe extern "C" fn cb_apply_to_linear_view_object( out_lines: *mut *mut BNLinearDisassemblyLine, out_line_count: *mut usize, ) { - let ctxt: &mut T = &mut *(ctxt as *mut T); - // SAFETY: We do not own the flowgraph, do not take it as Ref. - let mut object = LinearViewObject::from_raw(object); - let mut prev_object = if !prev.is_null() { - Some(LinearViewObject::from_raw(prev)) - } else { - None - }; - let mut next_object = if !next.is_null() { - Some(LinearViewObject::from_raw(next)) - } else { - None - }; + unsafe { + let ctxt: &mut T = &mut *(ctxt as *mut T); + // SAFETY: We do not own the flowgraph, do not take it as Ref. + let mut object = LinearViewObject::from_raw(object); + let mut prev_object = if !prev.is_null() { + Some(LinearViewObject::from_raw(prev)) + } else { + None + }; + let mut next_object = if !next.is_null() { + Some(LinearViewObject::from_raw(next)) + } else { + None + }; - let raw_lines = std::slice::from_raw_parts(in_lines, in_line_count); - // NOTE: The caller is owned of the inLines. - let lines: Vec<_> = raw_lines - .iter() - .map(|line| LinearDisassemblyLine::from_raw(line)) - .collect(); + let raw_lines = std::slice::from_raw_parts(in_lines, in_line_count); + // NOTE: The caller is owned of the inLines. + let lines: Vec<_> = raw_lines + .iter() + .map(|line| LinearDisassemblyLine::from_raw(line)) + .collect(); - let new_lines = ctxt.apply_to_linear_object( - &mut object, - prev_object.as_mut(), - next_object.as_mut(), - lines, - ); + let new_lines = ctxt.apply_to_linear_object( + &mut object, + prev_object.as_mut(), + next_object.as_mut(), + lines, + ); - unsafe { - *out_line_count = new_lines.len(); - let boxed_new_lines: Box<[_]> = new_lines - .into_iter() - // NOTE: Freed by cb_free_lines - .map(LinearDisassemblyLine::into_raw) - .collect(); - // NOTE: Dropped by cb_free_lines - *out_lines = Box::leak(boxed_new_lines).as_mut_ptr(); + { + *out_line_count = new_lines.len(); + let boxed_new_lines: Box<[_]> = new_lines + .into_iter() + // NOTE: Freed by cb_free_lines + .map(LinearDisassemblyLine::into_raw) + .collect(); + // NOTE: Dropped by cb_free_lines + *out_lines = Box::leak(boxed_new_lines).as_mut_ptr(); + } } } @@ -440,9 +444,11 @@ unsafe extern "C" fn cb_free_lines( lines: *mut BNLinearDisassemblyLine, line_count: usize, ) { - let lines_ptr = std::ptr::slice_from_raw_parts_mut(lines, line_count); - let boxed_lines = Box::from_raw(lines_ptr); - for line in boxed_lines { - LinearDisassemblyLine::free_raw(line); + unsafe { + let lines_ptr = std::ptr::slice_from_raw_parts_mut(lines, line_count); + let boxed_lines = Box::from_raw(lines_ptr); + for line in boxed_lines { + LinearDisassemblyLine::free_raw(line); + } } } diff --git a/rust/src/repository.rs b/rust/src/repository.rs index 18946eac2f..2da1068891 100644 --- a/rust/src/repository.rs +++ b/rust/src/repository.rs @@ -30,7 +30,7 @@ impl Repository { } pub(crate) unsafe fn ref_from_raw(handle: NonNull) -> Ref { - Ref::new(Self { handle }) + unsafe { Ref::new(Self { handle }) } } /// String URL of the git repository where the plugin repository's are stored @@ -92,11 +92,15 @@ impl ToOwned for Repository { unsafe impl RefCountable for Repository { unsafe fn inc_ref(handle: &Self) -> Ref { - Self::ref_from_raw(NonNull::new(BNNewRepositoryReference(handle.handle.as_ptr())).unwrap()) + unsafe { + Self::ref_from_raw( + NonNull::new(BNNewRepositoryReference(handle.handle.as_ptr())).unwrap(), + ) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeRepository(handle.handle.as_ptr()) + unsafe { BNFreeRepository(handle.handle.as_ptr()) } } } @@ -108,11 +112,11 @@ impl CoreArrayProvider for Repository { unsafe impl CoreArrayProviderInner for Repository { unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { - BNFreeRepositoryManagerRepositoriesList(raw) + unsafe { BNFreeRepositoryManagerRepositoriesList(raw) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - Guard::new(Self::from_raw(NonNull::new(*raw).unwrap()), context) + unsafe { Guard::new(Self::from_raw(NonNull::new(*raw).unwrap()), context) } } } @@ -124,7 +128,7 @@ impl CoreArrayProvider for PluginType { unsafe impl CoreArrayProviderInner for PluginType { unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { - BNFreePluginTypes(raw) + unsafe { BNFreePluginTypes(raw) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { diff --git a/rust/src/repository/plugin.rs b/rust/src/repository/plugin.rs index f715c58f3f..d4fd3602fa 100644 --- a/rust/src/repository/plugin.rs +++ b/rust/src/repository/plugin.rs @@ -78,7 +78,7 @@ impl Extension { } pub(crate) unsafe fn ref_from_raw(handle: NonNull) -> Ref { - Ref::new(Self { handle }) + unsafe { Ref::new(Self { handle }) } } /// String indicating the API used by the plugin @@ -343,11 +343,13 @@ impl ToOwned for Extension { unsafe impl RefCountable for Extension { unsafe fn inc_ref(handle: &Self) -> Ref { - Self::ref_from_raw(NonNull::new(BNNewPluginReference(handle.handle.as_ptr())).unwrap()) + unsafe { + Self::ref_from_raw(NonNull::new(BNNewPluginReference(handle.handle.as_ptr())).unwrap()) + } } unsafe fn dec_ref(handle: &Self) { - BNFreePlugin(handle.handle.as_ptr()) + unsafe { BNFreePlugin(handle.handle.as_ptr()) } } } @@ -359,11 +361,11 @@ impl CoreArrayProvider for Extension { unsafe impl CoreArrayProviderInner for Extension { unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { - BNFreeRepositoryPluginList(raw) + unsafe { BNFreeRepositoryPluginList(raw) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - Guard::new(Self::from_raw(NonNull::new(*raw).unwrap()), context) + unsafe { Guard::new(Self::from_raw(NonNull::new(*raw).unwrap()), context) } } } @@ -375,7 +377,7 @@ impl CoreArrayProvider for ExtensionVersion { unsafe impl CoreArrayProviderInner for ExtensionVersion { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreePluginVersions(raw, count) + unsafe { BNFreePluginVersions(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { diff --git a/rust/src/secrets_provider.rs b/rust/src/secrets_provider.rs index da7bdecef1..f5fcfd3355 100644 --- a/rust/src/secrets_provider.rs +++ b/rust/src/secrets_provider.rs @@ -104,12 +104,14 @@ impl CoreArrayProvider for CoreSecretsProvider { unsafe impl CoreArrayProviderInner for CoreSecretsProvider { unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { - BNFreeSecretsProviderList(raw) + unsafe { BNFreeSecretsProviderList(raw) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { - let raw_ptr = NonNull::new(*raw).unwrap(); - Self::from_raw(raw_ptr) + unsafe { + let raw_ptr = NonNull::new(*raw).unwrap(); + Self::from_raw(raw_ptr) + } } } @@ -117,18 +119,22 @@ unsafe extern "C" fn cb_has_data( ctxt: *mut c_void, key: *const c_char, ) -> bool { - let ctxt: &mut C = &mut *(ctxt as *mut C); - ctxt.has_data(&CStr::from_ptr(key).to_string_lossy()) + unsafe { + let ctxt: &mut C = &mut *(ctxt as *mut C); + ctxt.has_data(&CStr::from_ptr(key).to_string_lossy()) + } } unsafe extern "C" fn cb_get_data( ctxt: *mut c_void, key: *const c_char, ) -> *mut c_char { - let ctxt: &mut C = &mut *(ctxt as *mut C); - match ctxt.get_data(&CStr::from_ptr(key).to_string_lossy()) { - Some(result) => BnString::into_raw(BnString::new(result)), - None => std::ptr::null_mut(), + unsafe { + let ctxt: &mut C = &mut *(ctxt as *mut C); + match ctxt.get_data(&CStr::from_ptr(key).to_string_lossy()) { + Some(result) => BnString::into_raw(BnString::new(result)), + None => std::ptr::null_mut(), + } } } @@ -137,16 +143,20 @@ unsafe extern "C" fn cb_store_data( key: *const c_char, data: *const c_char, ) -> bool { - let ctxt: &mut C = &mut *(ctxt as *mut C); - let key = CStr::from_ptr(key).to_string_lossy(); - let data = CStr::from_ptr(data).to_string_lossy(); - ctxt.store_data(&key, &data) + unsafe { + let ctxt: &mut C = &mut *(ctxt as *mut C); + let key = CStr::from_ptr(key).to_string_lossy(); + let data = CStr::from_ptr(data).to_string_lossy(); + ctxt.store_data(&key, &data) + } } unsafe extern "C" fn cb_delete_data( ctxt: *mut c_void, key: *const c_char, ) -> bool { - let ctxt: &mut C = &mut *(ctxt as *mut C); - ctxt.delete_data(&CStr::from_ptr(key).to_string_lossy()) + unsafe { + let ctxt: &mut C = &mut *(ctxt as *mut C); + ctxt.delete_data(&CStr::from_ptr(key).to_string_lossy()) + } } diff --git a/rust/src/section.rs b/rust/src/section.rs index ee7e0ec7a7..da7fb40440 100644 --- a/rust/src/section.rs +++ b/rust/src/section.rs @@ -73,8 +73,10 @@ impl Section { } pub(crate) unsafe fn ref_from_raw(handle: *mut BNSection) -> Ref { - debug_assert!(!handle.is_null()); - Ref::new(Self { handle }) + unsafe { + debug_assert!(!handle.is_null()); + Ref::new(Self { handle }) + } } /// You need to create a section builder, customize that section, then add it to a binary view: @@ -194,13 +196,17 @@ impl ToOwned for Section { unsafe impl RefCountable for Section { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: BNNewSectionReference(handle.handle), - }) + unsafe { + Ref::new(Self { + handle: BNNewSectionReference(handle.handle), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeSection(handle.handle); + unsafe { + BNFreeSection(handle.handle); + } } } @@ -212,11 +218,13 @@ impl CoreArrayProvider for Section { unsafe impl CoreArrayProviderInner for Section { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeSectionList(raw, count); + unsafe { + BNFreeSectionList(raw, count); + } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - Guard::new(Section::from_raw(*raw), context) + unsafe { Guard::new(Section::from_raw(*raw), context) } } } diff --git a/rust/src/segment.rs b/rust/src/segment.rs index a042d1fdb7..6144b82437 100644 --- a/rust/src/segment.rs +++ b/rust/src/segment.rs @@ -102,8 +102,10 @@ impl Segment { } pub(crate) unsafe fn ref_from_raw(handle: *mut BNSegment) -> Ref { - assert!(!handle.is_null()); - Ref::new(Self { handle }) + unsafe { + assert!(!handle.is_null()); + Ref::new(Self { handle }) + } } /// You need to create a segment builder, customize that segment, then add it to a binary view: @@ -194,13 +196,17 @@ impl ToOwned for Segment { unsafe impl RefCountable for Segment { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: BNNewSegmentReference(handle.handle), - }) + unsafe { + Ref::new(Self { + handle: BNNewSegmentReference(handle.handle), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeSegment(handle.handle); + unsafe { + BNFreeSegment(handle.handle); + } } } @@ -212,11 +218,13 @@ impl CoreArrayProvider for Segment { unsafe impl CoreArrayProviderInner for Segment { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeSegmentList(raw, count); + unsafe { + BNFreeSegmentList(raw, count); + } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - Guard::new(Segment::from_raw(*raw), context) + unsafe { Guard::new(Segment::from_raw(*raw), context) } } } diff --git a/rust/src/settings.rs b/rust/src/settings.rs index 4e35f20f6e..d2ab6d0fc1 100644 --- a/rust/src/settings.rs +++ b/rust/src/settings.rs @@ -36,8 +36,10 @@ pub struct Settings { impl Settings { pub(crate) unsafe fn ref_from_raw(handle: *mut BNSettings) -> Ref { - debug_assert!(!handle.is_null()); - Ref::new(Self { handle }) + unsafe { + debug_assert!(!handle.is_null()); + Ref::new(Self { handle }) + } } /// Retrieve the global settings instance, this will be populated by both the core and plugins. @@ -546,13 +548,17 @@ impl ToOwned for Settings { unsafe impl RefCountable for Settings { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: BNNewSettingsReference(handle.handle), - }) + unsafe { + Ref::new(Self { + handle: BNNewSettingsReference(handle.handle), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeSettings(handle.handle); + unsafe { + BNFreeSettings(handle.handle); + } } } diff --git a/rust/src/string.rs b/rust/src/string.rs index 001fc3e3a5..67a7b548b4 100644 --- a/rust/src/string.rs +++ b/rust/src/string.rs @@ -76,7 +76,7 @@ impl BnString { /// /// This expects the passed raw string to be owned, as in, freed by us. pub unsafe fn into_string(raw: *mut c_char) -> String { - Self::from_raw(raw).to_string_lossy().to_string() + unsafe { Self::from_raw(raw).to_string_lossy().to_string() } } /// Construct a BnString from an owned const char* allocated by [`BNAllocString`]. @@ -86,8 +86,10 @@ impl BnString { /// Free a raw string allocated by [`BNAllocString`]. pub unsafe fn free_raw(raw: *mut c_char) { - if !raw.is_null() { - BNFreeString(raw); + unsafe { + if !raw.is_null() { + BNFreeString(raw); + } } } @@ -176,11 +178,13 @@ impl CoreArrayProvider for BnString { unsafe impl CoreArrayProviderInner for BnString { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeStringList(raw, count); + unsafe { + BNFreeStringList(raw, count); + } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { - CStr::from_ptr(*raw).to_str().unwrap() + unsafe { CStr::from_ptr(*raw).to_str().unwrap() } } } diff --git a/rust/src/symbol.rs b/rust/src/symbol.rs index 6c368f7c5f..8bc8f8a84b 100644 --- a/rust/src/symbol.rs +++ b/rust/src/symbol.rs @@ -222,7 +222,7 @@ pub struct Symbol { impl Symbol { pub(crate) unsafe fn ref_from_raw(raw: *mut BNSymbol) -> Ref { - Ref::new(Self { handle: raw }) + unsafe { Ref::new(Self { handle: raw }) } } pub(crate) unsafe fn from_raw(raw: *mut BNSymbol) -> Self { @@ -322,13 +322,17 @@ impl ToOwned for Symbol { unsafe impl RefCountable for Symbol { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: BNNewSymbolReference(handle.handle), - }) + unsafe { + Ref::new(Self { + handle: BNNewSymbolReference(handle.handle), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeSymbol(handle.handle); + unsafe { + BNFreeSymbol(handle.handle); + } } } @@ -340,11 +344,13 @@ impl CoreArrayProvider for Symbol { unsafe impl CoreArrayProviderInner for Symbol { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeSymbolList(raw, count); + unsafe { + BNFreeSymbolList(raw, count); + } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - Guard::new(Symbol::from_raw(*raw), context) + unsafe { Guard::new(Symbol::from_raw(*raw), context) } } } diff --git a/rust/src/tags.rs b/rust/src/tags.rs index bb0de9574f..13d7e1ea1c 100644 --- a/rust/src/tags.rs +++ b/rust/src/tags.rs @@ -39,8 +39,10 @@ impl Tag { } pub(crate) unsafe fn ref_from_raw(handle: *mut BNTag) -> Ref { - debug_assert!(!handle.is_null()); - Ref::new(Self { handle }) + unsafe { + debug_assert!(!handle.is_null()); + Ref::new(Self { handle }) + } } pub fn new(t: &TagType, data: &str) -> Ref { @@ -88,13 +90,17 @@ impl Eq for Tag {} unsafe impl RefCountable for Tag { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: BNNewTagReference(handle.handle), - }) + unsafe { + Ref::new(Self { + handle: BNNewTagReference(handle.handle), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeTag(handle.handle); + unsafe { + BNFreeTag(handle.handle); + } } } @@ -114,11 +120,11 @@ impl CoreArrayProvider for Tag { unsafe impl CoreArrayProviderInner for Tag { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeTagList(raw, count) + unsafe { BNFreeTagList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - Guard::new(Self { handle: *raw }, &context) + unsafe { Guard::new(Self { handle: *raw }, &context) } } } @@ -137,11 +143,11 @@ impl CoreArrayProvider for TagType { unsafe impl CoreArrayProviderInner for TagType { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeTagTypeList(raw, count) + unsafe { BNFreeTagTypeList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - Guard::new(Self::from_raw(*raw), context) + unsafe { Guard::new(Self::from_raw(*raw), context) } } } @@ -152,8 +158,10 @@ impl TagType { } pub(crate) unsafe fn ref_from_raw(handle: *mut BNTagType) -> Ref { - debug_assert!(!handle.is_null()); - Ref::new(Self { handle }) + unsafe { + debug_assert!(!handle.is_null()); + Ref::new(Self { handle }) + } } pub fn create(view: &BinaryView, name: &str, icon: &str) -> Ref { @@ -235,13 +243,17 @@ impl Eq for TagType {} unsafe impl RefCountable for TagType { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: BNNewTagTypeReference(handle.handle), - }) + unsafe { + Ref::new(Self { + handle: BNNewTagTypeReference(handle.handle), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeTagType(handle.handle); + unsafe { + BNFreeTagType(handle.handle); + } } } @@ -300,7 +312,7 @@ impl CoreArrayProvider for TagReference { unsafe impl CoreArrayProviderInner for TagReference { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeTagReferences(raw, count) + unsafe { BNFreeTagReferences(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { diff --git a/rust/src/tracing.rs b/rust/src/tracing.rs index cacf382f5a..e09c141848 100644 --- a/rust/src/tracing.rs +++ b/rust/src/tracing.rs @@ -57,7 +57,7 @@ macro_rules! tracing_init { let layer = $crate::tracing::BinaryNinjaLayer::default(); $crate::tracing::init_with_layer(layer); }; - ($name:expr) => { + ($name:expr_2021) => { let layer = $crate::tracing::BinaryNinjaLayer::default() .with_target_mapping(env!("CARGO_CRATE_NAME"), $name); $crate::tracing::init_with_layer(layer); diff --git a/rust/src/types.rs b/rust/src/types.rs index 7ca6f33b22..67b04c10f1 100644 --- a/rust/src/types.rs +++ b/rust/src/types.rs @@ -653,8 +653,10 @@ impl Type { } pub unsafe fn ref_from_raw(handle: *mut BNType) -> Ref { - debug_assert!(!handle.is_null()); - Ref::new(Self { handle }) + unsafe { + debug_assert!(!handle.is_null()); + Ref::new(Self { handle }) + } } pub fn to_builder(&self) -> TypeBuilder { @@ -1143,11 +1145,13 @@ unsafe impl Sync for Type {} unsafe impl RefCountable for Type { unsafe fn inc_ref(handle: &Self) -> Ref { - Self::ref_from_raw(BNNewTypeReference(handle.handle)) + unsafe { Self::ref_from_raw(BNNewTypeReference(handle.handle)) } } unsafe fn dec_ref(handle: &Self) { - BNFreeType(handle.handle); + unsafe { + BNFreeType(handle.handle); + } } } @@ -1167,12 +1171,14 @@ impl CoreArrayProvider for Type { unsafe impl CoreArrayProviderInner for Type { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeTypeList(raw, count) + unsafe { BNFreeTypeList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { - // TODO: This is assuming &'a Type is &*mut BNType - std::mem::transmute(raw) + unsafe { + // TODO: This is assuming &'a Type is &*mut BNType + std::mem::transmute(raw) + } } } @@ -1554,8 +1560,10 @@ impl NamedTypeReference { } pub(crate) unsafe fn ref_from_raw(handle: *mut BNNamedTypeReference) -> Ref { - debug_assert!(!handle.is_null()); - Ref::new(Self { handle }) + unsafe { + debug_assert!(!handle.is_null()); + Ref::new(Self { handle }) + } } /// Create an NTR to a type that did not come directly from a BinaryView's types list. @@ -1649,11 +1657,11 @@ impl ToOwned for NamedTypeReference { unsafe impl RefCountable for NamedTypeReference { unsafe fn inc_ref(handle: &Self) -> Ref { - Self::ref_from_raw(BNNewNamedTypeReference(handle.handle)) + unsafe { Self::ref_from_raw(BNNewNamedTypeReference(handle.handle)) } } unsafe fn dec_ref(handle: &Self) { - BNFreeNamedTypeReference(handle.handle) + unsafe { BNFreeNamedTypeReference(handle.handle) } } } @@ -1733,7 +1741,9 @@ impl CoreArrayProvider for QualifiedNameAndType { unsafe impl CoreArrayProviderInner for QualifiedNameAndType { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeTypeAndNameList(raw, count); + unsafe { + BNFreeTypeAndNameList(raw, count); + } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { @@ -1788,7 +1798,9 @@ impl CoreArrayProvider for QualifiedNameTypeAndId { unsafe impl CoreArrayProviderInner for QualifiedNameTypeAndId { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeTypeIdList(raw, count); + unsafe { + BNFreeTypeIdList(raw, count); + } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { @@ -1855,7 +1867,9 @@ impl CoreArrayProvider for NameAndType { unsafe impl CoreArrayProviderInner for NameAndType { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeNameAndTypeList(raw, count); + unsafe { + BNFreeNameAndTypeList(raw, count); + } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { diff --git a/rust/src/types/archive.rs b/rust/src/types/archive.rs index 15f4cbfeb4..a40f509220 100644 --- a/rust/src/types/archive.rs +++ b/rust/src/types/archive.rs @@ -49,12 +49,14 @@ impl CoreArrayProvider for TypeArchiveSnapshotId { unsafe impl CoreArrayProviderInner for TypeArchiveSnapshotId { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeStringList(raw, count) + unsafe { BNFreeStringList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { - let str = CStr::from_ptr(*raw).to_str().unwrap().to_string(); - TypeArchiveSnapshotId(str) + unsafe { + let str = CStr::from_ptr(*raw).to_str().unwrap().to_string(); + TypeArchiveSnapshotId(str) + } } } @@ -79,7 +81,7 @@ impl TypeArchive { } pub(crate) unsafe fn ref_from_raw(handle: NonNull) -> Ref { - Ref::new(Self { handle }) + unsafe { Ref::new(Self { handle }) } } /// Open the Type Archive at the given path, if it exists. @@ -698,9 +700,11 @@ impl TypeArchive { ctxt: *mut c_void, id: *const c_char, ) -> bool { - let fun: &mut F = &mut *(ctxt as *mut F); - let id_str = raw_to_string(id).unwrap(); - fun(&TypeArchiveSnapshotId(id_str)) + unsafe { + let fun: &mut F = &mut *(ctxt as *mut F); + let id_str = raw_to_string(id).unwrap(); + fun(&TypeArchiveSnapshotId(id_str)) + } } let parents_cstr: Vec<_> = parents.iter().map(|p| p.clone().to_cstr()).collect(); @@ -823,13 +827,17 @@ impl ToOwned for TypeArchive { unsafe impl RefCountable for TypeArchive { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: NonNull::new(BNNewTypeArchiveReference(handle.handle.as_ptr())).unwrap(), - }) + unsafe { + Ref::new(Self { + handle: NonNull::new(BNNewTypeArchiveReference(handle.handle.as_ptr())).unwrap(), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeTypeArchiveReference(handle.handle.as_ptr()); + unsafe { + BNFreeTypeArchiveReference(handle.handle.as_ptr()); + } } } @@ -865,12 +873,14 @@ impl CoreArrayProvider for TypeArchive { unsafe impl CoreArrayProviderInner for TypeArchive { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeTypeArchiveList(raw, count) + unsafe { BNFreeTypeArchiveList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - let raw_ptr = NonNull::new(*raw).unwrap(); - Guard::new(Self::from_raw(raw_ptr), context) + unsafe { + let raw_ptr = NonNull::new(*raw).unwrap(); + Guard::new(Self::from_raw(raw_ptr), context) + } } } @@ -1001,14 +1011,13 @@ unsafe extern "C" fn cb_type_added( id: *const ::std::os::raw::c_char, definition: *mut BNType, ) { - let ctxt: &mut T = &mut *(ctxt as *mut T); - // `archive` is owned by the caller. - let archive = unsafe { TypeArchive::from_raw(NonNull::new(archive).unwrap()) }; - ctxt.type_added( - &archive, - unsafe { CStr::from_ptr(id).to_string_lossy().as_ref() }, - &Type { handle: definition }, - ) + unsafe { + let ctxt: &mut T = &mut *(ctxt as *mut T); + // `archive` is owned by the caller. + let archive = { TypeArchive::from_raw(NonNull::new(archive).unwrap()) }; + let id = CStr::from_ptr(id).to_string_lossy(); + ctxt.type_added(&archive, id.as_ref(), &Type { handle: definition }) + } } unsafe extern "C" fn cb_type_updated( ctxt: *mut ::std::os::raw::c_void, @@ -1017,19 +1026,22 @@ unsafe extern "C" fn cb_type_updated( old_definition: *mut BNType, new_definition: *mut BNType, ) { - let ctxt: &mut T = &mut *(ctxt as *mut T); - // `archive` is owned by the caller. - let archive = unsafe { TypeArchive::from_raw(NonNull::new(archive).unwrap()) }; - ctxt.type_updated( - &archive, - unsafe { CStr::from_ptr(id).to_string_lossy().as_ref() }, - &Type { - handle: old_definition, - }, - &Type { - handle: new_definition, - }, - ) + unsafe { + let ctxt: &mut T = &mut *(ctxt as *mut T); + // `archive` is owned by the caller. + let archive = { TypeArchive::from_raw(NonNull::new(archive).unwrap()) }; + let id = CStr::from_ptr(id).to_string_lossy(); + ctxt.type_updated( + &archive, + id.as_ref(), + &Type { + handle: old_definition, + }, + &Type { + handle: new_definition, + }, + ) + } } unsafe extern "C" fn cb_type_renamed( ctxt: *mut ::std::os::raw::c_void, @@ -1038,19 +1050,17 @@ unsafe extern "C" fn cb_type_renamed( old_name: *const BNQualifiedName, new_name: *const BNQualifiedName, ) { - let ctxt: &mut T = &mut *(ctxt as *mut T); - // `old_name` is freed by the caller - let old_name = QualifiedName::from_raw(&*old_name); - // `new_name` is freed by the caller - let new_name = QualifiedName::from_raw(&*new_name); - // `archive` is owned by the caller. - let archive = unsafe { TypeArchive::from_raw(NonNull::new(archive).unwrap()) }; - ctxt.type_renamed( - &archive, - unsafe { CStr::from_ptr(id).to_string_lossy().as_ref() }, - &old_name, - &new_name, - ) + unsafe { + let ctxt: &mut T = &mut *(ctxt as *mut T); + // `old_name` is freed by the caller + let old_name = QualifiedName::from_raw(&*old_name); + // `new_name` is freed by the caller + let new_name = QualifiedName::from_raw(&*new_name); + // `archive` is owned by the caller. + let archive = { TypeArchive::from_raw(NonNull::new(archive).unwrap()) }; + let id = CStr::from_ptr(id).to_string_lossy(); + ctxt.type_renamed(&archive, id.as_ref(), &old_name, &new_name) + } } unsafe extern "C" fn cb_type_deleted( ctxt: *mut ::std::os::raw::c_void, @@ -1058,14 +1068,13 @@ unsafe extern "C" fn cb_type_deleted( id: *const ::std::os::raw::c_char, definition: *mut BNType, ) { - let ctxt: &mut T = &mut *(ctxt as *mut T); - // `archive` is owned by the caller. - let archive = unsafe { TypeArchive::from_raw(NonNull::new(archive).unwrap()) }; - ctxt.type_deleted( - &archive, - unsafe { CStr::from_ptr(id).to_string_lossy().as_ref() }, - &Type { handle: definition }, - ) + unsafe { + let ctxt: &mut T = &mut *(ctxt as *mut T); + // `archive` is owned by the caller. + let archive = { TypeArchive::from_raw(NonNull::new(archive).unwrap()) }; + let id = CStr::from_ptr(id).to_string_lossy(); + ctxt.type_deleted(&archive, id.as_ref(), &Type { handle: definition }) + } } #[repr(transparent)] @@ -1080,7 +1089,7 @@ impl TypeArchiveMergeConflict { #[allow(unused)] pub(crate) unsafe fn ref_from_raw(handle: NonNull) -> Ref { - Ref::new(Self { handle }) + unsafe { Ref::new(Self { handle }) } } pub fn get_type_archive(&self) -> Option> { @@ -1143,16 +1152,20 @@ impl ToOwned for TypeArchiveMergeConflict { unsafe impl RefCountable for TypeArchiveMergeConflict { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: NonNull::new(BNNewTypeArchiveMergeConflictReference( - handle.handle.as_ptr(), - )) - .unwrap(), - }) + unsafe { + Ref::new(Self { + handle: NonNull::new(BNNewTypeArchiveMergeConflictReference( + handle.handle.as_ptr(), + )) + .unwrap(), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeTypeArchiveMergeConflict(handle.handle.as_ptr()); + unsafe { + BNFreeTypeArchiveMergeConflict(handle.handle.as_ptr()); + } } } @@ -1164,11 +1177,13 @@ impl CoreArrayProvider for TypeArchiveMergeConflict { unsafe impl CoreArrayProviderInner for TypeArchiveMergeConflict { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeTypeArchiveMergeConflictList(raw, count) + unsafe { BNFreeTypeArchiveMergeConflictList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - let raw_ptr = NonNull::new(*raw).unwrap(); - Guard::new(Self::from_raw(raw_ptr), context) + unsafe { + let raw_ptr = NonNull::new(*raw).unwrap(); + Guard::new(Self::from_raw(raw_ptr), context) + } } } diff --git a/rust/src/types/container.rs b/rust/src/types/container.rs index 5096ac78c0..53377f5866 100644 --- a/rust/src/types/container.rs +++ b/rust/src/types/container.rs @@ -30,14 +30,16 @@ pub struct TypeContainer { impl TypeContainer { pub(crate) unsafe fn from_raw(handle: NonNull) -> Self { - // NOTE: There does not seem to be any shared ref counting for type containers, it seems if the - // NOTE: binary view is freed the type container will be freed and cause this to become invalid - // NOTE: but this is how the C++ and Python bindings operate so i guess its fine? - // TODO: I really dont get how some of the usage of the TypeContainer doesnt free the underlying container. - // TODO: So for now we always duplicate the type container - let cloned_ptr = NonNull::new(BNDuplicateTypeContainer(handle.as_ptr())); - Self { - handle: cloned_ptr.unwrap(), + unsafe { + // NOTE: There does not seem to be any shared ref counting for type containers, it seems if the + // NOTE: binary view is freed the type container will be freed and cause this to become invalid + // NOTE: but this is how the C++ and Python bindings operate so i guess its fine? + // TODO: I really dont get how some of the usage of the TypeContainer doesnt free the underlying container. + // TODO: So for now we always duplicate the type container + let cloned_ptr = NonNull::new(BNDuplicateTypeContainer(handle.as_ptr())); + Self { + handle: cloned_ptr.unwrap(), + } } } diff --git a/rust/src/types/enumeration.rs b/rust/src/types/enumeration.rs index 70c266e1f7..3229ab0456 100644 --- a/rust/src/types/enumeration.rs +++ b/rust/src/types/enumeration.rs @@ -100,8 +100,10 @@ pub struct Enumeration { impl Enumeration { pub(crate) unsafe fn ref_from_raw(handle: *mut BNEnumeration) -> Ref { - debug_assert!(!handle.is_null()); - Ref::new(Self { handle }) + unsafe { + debug_assert!(!handle.is_null()); + Ref::new(Self { handle }) + } } pub fn builder() -> EnumerationBuilder { @@ -135,11 +137,13 @@ impl Debug for Enumeration { unsafe impl RefCountable for Enumeration { unsafe fn inc_ref(handle: &Self) -> Ref { - Self::ref_from_raw(BNNewEnumerationReference(handle.handle)) + unsafe { Self::ref_from_raw(BNNewEnumerationReference(handle.handle)) } } unsafe fn dec_ref(handle: &Self) { - BNFreeEnumeration(handle.handle); + unsafe { + BNFreeEnumeration(handle.handle); + } } } diff --git a/rust/src/types/library.rs b/rust/src/types/library.rs index 9b543362ab..9b9838f3a6 100644 --- a/rust/src/types/library.rs +++ b/rust/src/types/library.rs @@ -39,12 +39,12 @@ impl TypeLibrary { } pub(crate) unsafe fn ref_from_raw(handle: NonNull) -> Ref { - Ref::new(Self { handle }) + unsafe { Ref::new(Self { handle }) } } #[allow(clippy::mut_from_ref)] pub(crate) unsafe fn as_raw(&self) -> &mut BNTypeLibrary { - &mut *self.handle.as_ptr() + unsafe { &mut *self.handle.as_ptr() } } /// Duplicate the type library. This creates a new, non-finalized type library object that shares @@ -386,13 +386,17 @@ impl Hash for TypeLibrary { unsafe impl RefCountable for TypeLibrary { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: NonNull::new(BNNewTypeLibraryReference(handle.handle.as_ptr())).unwrap(), - }) + unsafe { + Ref::new(Self { + handle: NonNull::new(BNNewTypeLibraryReference(handle.handle.as_ptr())).unwrap(), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeTypeLibrary(handle.handle.as_ptr()); + unsafe { + BNFreeTypeLibrary(handle.handle.as_ptr()); + } } } @@ -412,11 +416,11 @@ impl CoreArrayProvider for TypeLibrary { unsafe impl CoreArrayProviderInner for TypeLibrary { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeTypeLibraryList(raw, count) + unsafe { BNFreeTypeLibraryList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - Guard::new(Self::from_raw(NonNull::new(*raw).unwrap()), context) + unsafe { Guard::new(Self::from_raw(NonNull::new(*raw).unwrap()), context) } } } diff --git a/rust/src/types/parser.rs b/rust/src/types/parser.rs index 9bcdf41aa9..7cfe2f937b 100644 --- a/rust/src/types/parser.rs +++ b/rust/src/types/parser.rs @@ -283,13 +283,15 @@ impl CoreArrayProvider for CoreTypeParser { unsafe impl CoreArrayProviderInner for CoreTypeParser { unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { - BNFreeTypeParserList(raw) + unsafe { BNFreeTypeParserList(raw) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { - // TODO: Because handle is a NonNull we should prob make Self::Raw that as well... - let handle = NonNull::new(*raw).unwrap(); - CoreTypeParser::from_raw(handle) + unsafe { + // TODO: Because handle is a NonNull we should prob make Self::Raw that as well... + let handle = NonNull::new(*raw).unwrap(); + CoreTypeParser::from_raw(handle) + } } } @@ -519,15 +521,17 @@ unsafe extern "C" fn cb_get_option_text( value: *const c_char, result: *mut *mut c_char, ) -> bool { - let ctxt: &mut T = &mut *(ctxt as *mut T); - if let Some(inner_result) = ctxt.get_option_text(option, &raw_to_string(value).unwrap()) { - let bn_inner_result = BnString::new(inner_result); - // NOTE: Dropped by `cb_free_string` - *result = BnString::into_raw(bn_inner_result); - true - } else { - *result = std::ptr::null_mut(); - false + unsafe { + let ctxt: &mut T = &mut *(ctxt as *mut T); + if let Some(inner_result) = ctxt.get_option_text(option, &raw_to_string(value).unwrap()) { + let bn_inner_result = BnString::new(inner_result); + // NOTE: Dropped by `cb_free_string` + *result = BnString::into_raw(bn_inner_result); + true + } else { + *result = std::ptr::null_mut(); + false + } } } @@ -545,47 +549,49 @@ unsafe extern "C" fn cb_preprocess_source( errors: *mut *mut BNTypeParserError, error_count: *mut usize, ) -> bool { - let ctxt: &mut T = &mut *(ctxt as *mut T); - let platform = Platform { handle: platform }; - let existing_types_ptr = NonNull::new(existing_types).unwrap(); - let existing_types = TypeContainer::from_raw(existing_types_ptr); - let options_raw = unsafe { std::slice::from_raw_parts(options, option_count) }; - let options: Vec<_> = options_raw - .iter() - .filter_map(|&r| raw_to_string(r)) - .collect(); - let includes_raw = unsafe { std::slice::from_raw_parts(include_dirs, include_dir_count) }; - let includes: Vec<_> = includes_raw - .iter() - .filter_map(|&r| Some(PathBuf::from(raw_to_string(r)?))) - .collect(); - match ctxt.preprocess_source( - &raw_to_string(source).unwrap(), - &raw_to_string(file_name).unwrap(), - &platform, - &existing_types, - &options, - &includes, - ) { - Ok(inner_result) => { - let bn_inner_result = BnString::new(inner_result); - // NOTE: Dropped by `cb_free_string` - *result = BnString::into_raw(bn_inner_result); - *errors = std::ptr::null_mut(); - *error_count = 0; - true - } - Err(inner_errors) => { - *result = std::ptr::null_mut(); - *error_count = inner_errors.len(); - // NOTE: Leaking errors here, dropped by `cb_free_error_list`. - let inner_errors: Box<[_]> = inner_errors - .into_iter() - .map(TypeParserError::into_raw) - .collect(); - // NOTE: Dropped by `cb_free_error_list` - *errors = Box::leak(inner_errors).as_mut_ptr(); - false + unsafe { + let ctxt: &mut T = &mut *(ctxt as *mut T); + let platform = Platform { handle: platform }; + let existing_types_ptr = NonNull::new(existing_types).unwrap(); + let existing_types = TypeContainer::from_raw(existing_types_ptr); + let options_raw = unsafe { std::slice::from_raw_parts(options, option_count) }; + let options: Vec<_> = options_raw + .iter() + .filter_map(|&r| raw_to_string(r)) + .collect(); + let includes_raw = unsafe { std::slice::from_raw_parts(include_dirs, include_dir_count) }; + let includes: Vec<_> = includes_raw + .iter() + .filter_map(|&r| Some(PathBuf::from(raw_to_string(r)?))) + .collect(); + match ctxt.preprocess_source( + &raw_to_string(source).unwrap(), + &raw_to_string(file_name).unwrap(), + &platform, + &existing_types, + &options, + &includes, + ) { + Ok(inner_result) => { + let bn_inner_result = BnString::new(inner_result); + // NOTE: Dropped by `cb_free_string` + *result = BnString::into_raw(bn_inner_result); + *errors = std::ptr::null_mut(); + *error_count = 0; + true + } + Err(inner_errors) => { + *result = std::ptr::null_mut(); + *error_count = inner_errors.len(); + // NOTE: Leaking errors here, dropped by `cb_free_error_list`. + let inner_errors: Box<[_]> = inner_errors + .into_iter() + .map(TypeParserError::into_raw) + .collect(); + // NOTE: Dropped by `cb_free_error_list` + *errors = Box::leak(inner_errors).as_mut_ptr(); + false + } } } } @@ -605,45 +611,47 @@ unsafe extern "C" fn cb_parse_types_from_source( errors: *mut *mut BNTypeParserError, error_count: *mut usize, ) -> bool { - let ctxt: &mut T = &mut *(ctxt as *mut T); - let platform = Platform { handle: platform }; - let existing_types_ptr = NonNull::new(existing_types).unwrap(); - let existing_types = TypeContainer::from_raw(existing_types_ptr); - let options_raw = unsafe { std::slice::from_raw_parts(options, option_count) }; - let options: Vec<_> = options_raw - .iter() - .filter_map(|&r| raw_to_string(r)) - .collect(); - let includes_raw = unsafe { std::slice::from_raw_parts(include_dirs, include_dir_count) }; - let includes: Vec<_> = includes_raw - .iter() - .filter_map(|&r| Some(PathBuf::from(raw_to_string(r)?))) - .collect(); - match ctxt.parse_types_from_source( - &raw_to_string(source).unwrap(), - &raw_to_string(file_name).unwrap(), - &platform, - &existing_types, - &options, - &includes, - &raw_to_string(auto_type_source).unwrap(), - ) { - Ok(type_parser_result) => { - *result = TypeParserResult::into_raw(type_parser_result); - *errors = std::ptr::null_mut(); - *error_count = 0; - true - } - Err(inner_errors) => { - *error_count = inner_errors.len(); - let inner_errors: Box<[_]> = inner_errors - .into_iter() - .map(TypeParserError::into_raw) - .collect(); - *result = Default::default(); - // NOTE: Dropped by cb_free_error_list - *errors = Box::leak(inner_errors).as_mut_ptr(); - false + unsafe { + let ctxt: &mut T = &mut *(ctxt as *mut T); + let platform = Platform { handle: platform }; + let existing_types_ptr = NonNull::new(existing_types).unwrap(); + let existing_types = TypeContainer::from_raw(existing_types_ptr); + let options_raw = unsafe { std::slice::from_raw_parts(options, option_count) }; + let options: Vec<_> = options_raw + .iter() + .filter_map(|&r| raw_to_string(r)) + .collect(); + let includes_raw = unsafe { std::slice::from_raw_parts(include_dirs, include_dir_count) }; + let includes: Vec<_> = includes_raw + .iter() + .filter_map(|&r| Some(PathBuf::from(raw_to_string(r)?))) + .collect(); + match ctxt.parse_types_from_source( + &raw_to_string(source).unwrap(), + &raw_to_string(file_name).unwrap(), + &platform, + &existing_types, + &options, + &includes, + &raw_to_string(auto_type_source).unwrap(), + ) { + Ok(type_parser_result) => { + *result = TypeParserResult::into_raw(type_parser_result); + *errors = std::ptr::null_mut(); + *error_count = 0; + true + } + Err(inner_errors) => { + *error_count = inner_errors.len(); + let inner_errors: Box<[_]> = inner_errors + .into_iter() + .map(TypeParserError::into_raw) + .collect(); + *result = Default::default(); + // NOTE: Dropped by cb_free_error_list + *errors = Box::leak(inner_errors).as_mut_ptr(); + false + } } } } @@ -657,38 +665,44 @@ unsafe extern "C" fn cb_parse_type_string( errors: *mut *mut BNTypeParserError, error_count: *mut usize, ) -> bool { - let ctxt: &mut T = &mut *(ctxt as *mut T); - let platform = Platform { handle: platform }; - let existing_types_ptr = NonNull::new(existing_types).unwrap(); - let existing_types = TypeContainer::from_raw(existing_types_ptr); - match ctxt.parse_type_string(&raw_to_string(source).unwrap(), &platform, &existing_types) { - Ok(inner_result) => { - *result = QualifiedNameAndType::into_raw(inner_result); - *errors = std::ptr::null_mut(); - *error_count = 0; - true - } - Err(inner_errors) => { - *error_count = inner_errors.len(); - let inner_errors: Box<[_]> = inner_errors - .into_iter() - .map(TypeParserError::into_raw) - .collect(); - *result = Default::default(); - // NOTE: Dropped by cb_free_error_list - *errors = Box::leak(inner_errors).as_mut_ptr(); - false + unsafe { + let ctxt: &mut T = &mut *(ctxt as *mut T); + let platform = Platform { handle: platform }; + let existing_types_ptr = NonNull::new(existing_types).unwrap(); + let existing_types = TypeContainer::from_raw(existing_types_ptr); + match ctxt.parse_type_string(&raw_to_string(source).unwrap(), &platform, &existing_types) { + Ok(inner_result) => { + *result = QualifiedNameAndType::into_raw(inner_result); + *errors = std::ptr::null_mut(); + *error_count = 0; + true + } + Err(inner_errors) => { + *error_count = inner_errors.len(); + let inner_errors: Box<[_]> = inner_errors + .into_iter() + .map(TypeParserError::into_raw) + .collect(); + *result = Default::default(); + // NOTE: Dropped by cb_free_error_list + *errors = Box::leak(inner_errors).as_mut_ptr(); + false + } } } } unsafe extern "C" fn cb_free_string(_ctxt: *mut c_void, string: *mut c_char) { - // SAFETY: The returned string is just BnString - BnString::free_raw(string); + unsafe { + // SAFETY: The returned string is just BnString + BnString::free_raw(string); + } } unsafe extern "C" fn cb_free_result(_ctxt: *mut c_void, result: *mut BNTypeParserResult) { - TypeParserResult::free_owned_raw(*result); + unsafe { + TypeParserResult::free_owned_raw(*result); + } } unsafe extern "C" fn cb_free_error_list( @@ -696,9 +710,11 @@ unsafe extern "C" fn cb_free_error_list( errors: *mut BNTypeParserError, error_count: usize, ) { - let errors = std::ptr::slice_from_raw_parts_mut(errors, error_count); - let boxed_errors = Box::from_raw(errors); - for error in boxed_errors { - TypeParserError::free_raw(error); + unsafe { + let errors = std::ptr::slice_from_raw_parts_mut(errors, error_count); + let boxed_errors = Box::from_raw(errors); + for error in boxed_errors { + TypeParserError::free_raw(error); + } } } diff --git a/rust/src/types/printer.rs b/rust/src/types/printer.rs index aa3b4873d9..1078b645d9 100644 --- a/rust/src/types/printer.rs +++ b/rust/src/types/printer.rs @@ -375,13 +375,15 @@ impl CoreArrayProvider for CoreTypePrinter { unsafe impl CoreArrayProviderInner for CoreTypePrinter { unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { - BNFreeTypePrinterList(raw) + unsafe { BNFreeTypePrinterList(raw) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { - // TODO: Because handle is a NonNull we should prob make Self::Raw that as well... - let handle = NonNull::new(*raw).unwrap(); - CoreTypePrinter::from_raw(handle) + unsafe { + // TODO: Because handle is a NonNull we should prob make Self::Raw that as well... + let handle = NonNull::new(*raw).unwrap(); + CoreTypePrinter::from_raw(handle) + } } } @@ -676,32 +678,34 @@ unsafe extern "C" fn cb_get_type_tokens( result: *mut *mut BNInstructionTextToken, result_count: *mut usize, ) -> bool { - let ctxt: &mut T = &mut *(ctxt as *mut T); - // NOTE: The caller is responsible for freeing name. - let qualified_name = QualifiedName::from_raw(&*name); - let inner_result = ctxt.get_type_tokens( - unsafe { Type::ref_from_raw(type_) }, - match platform.is_null() { - false => Some(Platform::ref_from_raw(platform)), - true => None, - }, - qualified_name, - base_confidence, - escaping, - ); - if let Some(inner_result) = inner_result { - let raw_text_tokens: Box<[BNInstructionTextToken]> = inner_result - .into_iter() - .map(InstructionTextToken::into_raw) - .collect(); - *result_count = raw_text_tokens.len(); - // NOTE: Dropped by the cb_free_tokens - *result = Box::leak(raw_text_tokens).as_mut_ptr(); - true - } else { - *result = std::ptr::null_mut(); - *result_count = 0; - false + unsafe { + let ctxt: &mut T = &mut *(ctxt as *mut T); + // NOTE: The caller is responsible for freeing name. + let qualified_name = QualifiedName::from_raw(&*name); + let inner_result = ctxt.get_type_tokens( + unsafe { Type::ref_from_raw(type_) }, + match platform.is_null() { + false => Some(Platform::ref_from_raw(platform)), + true => None, + }, + qualified_name, + base_confidence, + escaping, + ); + if let Some(inner_result) = inner_result { + let raw_text_tokens: Box<[BNInstructionTextToken]> = inner_result + .into_iter() + .map(InstructionTextToken::into_raw) + .collect(); + *result_count = raw_text_tokens.len(); + // NOTE: Dropped by the cb_free_tokens + *result = Box::leak(raw_text_tokens).as_mut_ptr(); + true + } else { + *result = std::ptr::null_mut(); + *result_count = 0; + false + } } } @@ -715,33 +719,35 @@ unsafe extern "C" fn cb_get_type_tokens_before_name( result: *mut *mut BNInstructionTextToken, result_count: *mut usize, ) -> bool { - let ctxt: &mut T = &mut *(ctxt as *mut T); - let inner_result = ctxt.get_type_tokens_before_name( - Type::ref_from_raw(type_), - match platform.is_null() { - false => Some(Platform::ref_from_raw(platform)), - true => None, - }, - base_confidence, - match parent_type.is_null() { - false => Some(Type::ref_from_raw(parent_type)), - true => None, - }, - escaping, - ); - if let Some(inner_result) = inner_result { - let raw_text_tokens: Box<[BNInstructionTextToken]> = inner_result - .into_iter() - .map(InstructionTextToken::into_raw) - .collect(); - *result_count = raw_text_tokens.len(); - // NOTE: Dropped by the cb_free_tokens - *result = Box::leak(raw_text_tokens).as_mut_ptr(); - true - } else { - *result = std::ptr::null_mut(); - *result_count = 0; - false + unsafe { + let ctxt: &mut T = &mut *(ctxt as *mut T); + let inner_result = ctxt.get_type_tokens_before_name( + Type::ref_from_raw(type_), + match platform.is_null() { + false => Some(Platform::ref_from_raw(platform)), + true => None, + }, + base_confidence, + match parent_type.is_null() { + false => Some(Type::ref_from_raw(parent_type)), + true => None, + }, + escaping, + ); + if let Some(inner_result) = inner_result { + let raw_text_tokens: Box<[BNInstructionTextToken]> = inner_result + .into_iter() + .map(InstructionTextToken::into_raw) + .collect(); + *result_count = raw_text_tokens.len(); + // NOTE: Dropped by the cb_free_tokens + *result = Box::leak(raw_text_tokens).as_mut_ptr(); + true + } else { + *result = std::ptr::null_mut(); + *result_count = 0; + false + } } } @@ -755,33 +761,35 @@ unsafe extern "C" fn cb_get_type_tokens_after_name( result: *mut *mut BNInstructionTextToken, result_count: *mut usize, ) -> bool { - let ctxt: &mut T = &mut *(ctxt as *mut T); - let inner_result = ctxt.get_type_tokens_after_name( - Type::ref_from_raw(type_), - match platform.is_null() { - false => Some(Platform::ref_from_raw(platform)), - true => None, - }, - base_confidence, - match parent_type.is_null() { - false => Some(Type::ref_from_raw(parent_type)), - true => None, - }, - escaping, - ); - if let Some(inner_result) = inner_result { - let raw_text_tokens: Box<[BNInstructionTextToken]> = inner_result - .into_iter() - .map(InstructionTextToken::into_raw) - .collect(); - *result_count = raw_text_tokens.len(); - // NOTE: Dropped by the cb_free_tokens - *result = Box::leak(raw_text_tokens).as_mut_ptr(); - true - } else { - *result = std::ptr::null_mut(); - *result_count = 0; - false + unsafe { + let ctxt: &mut T = &mut *(ctxt as *mut T); + let inner_result = ctxt.get_type_tokens_after_name( + Type::ref_from_raw(type_), + match platform.is_null() { + false => Some(Platform::ref_from_raw(platform)), + true => None, + }, + base_confidence, + match parent_type.is_null() { + false => Some(Type::ref_from_raw(parent_type)), + true => None, + }, + escaping, + ); + if let Some(inner_result) = inner_result { + let raw_text_tokens: Box<[BNInstructionTextToken]> = inner_result + .into_iter() + .map(InstructionTextToken::into_raw) + .collect(); + *result_count = raw_text_tokens.len(); + // NOTE: Dropped by the cb_free_tokens + *result = Box::leak(raw_text_tokens).as_mut_ptr(); + true + } else { + *result = std::ptr::null_mut(); + *result_count = 0; + false + } } } @@ -793,26 +801,28 @@ unsafe extern "C" fn cb_get_type_string( escaping: BNTokenEscapingType, result: *mut *mut ::std::os::raw::c_char, ) -> bool { - let ctxt: &mut T = &mut *(ctxt as *mut T); - // NOTE: The caller is responsible for freeing name. - let qualified_name = QualifiedName::from_raw(&*name); - let inner_result = ctxt.get_type_string( - Type::ref_from_raw(type_), - match platform.is_null() { - false => Some(Platform::ref_from_raw(platform)), - true => None, - }, - qualified_name, - escaping, - ); - if let Some(inner_result) = inner_result { - let raw_string = BnString::new(inner_result); - // NOTE: Dropped by `cb_free_string` - *result = BnString::into_raw(raw_string); - true - } else { - *result = std::ptr::null_mut(); - false + unsafe { + let ctxt: &mut T = &mut *(ctxt as *mut T); + // NOTE: The caller is responsible for freeing name. + let qualified_name = QualifiedName::from_raw(&*name); + let inner_result = ctxt.get_type_string( + Type::ref_from_raw(type_), + match platform.is_null() { + false => Some(Platform::ref_from_raw(platform)), + true => None, + }, + qualified_name, + escaping, + ); + if let Some(inner_result) = inner_result { + let raw_string = BnString::new(inner_result); + // NOTE: Dropped by `cb_free_string` + *result = BnString::into_raw(raw_string); + true + } else { + *result = std::ptr::null_mut(); + false + } } } @@ -823,23 +833,25 @@ unsafe extern "C" fn cb_get_type_string_before_name( escaping: BNTokenEscapingType, result: *mut *mut ::std::os::raw::c_char, ) -> bool { - let ctxt: &mut T = &mut *(ctxt as *mut T); - let inner_result = ctxt.get_type_string_before_name( - Type::ref_from_raw(type_), - match platform.is_null() { - false => Some(Platform::ref_from_raw(platform)), - true => None, - }, - escaping, - ); - if let Some(inner_result) = inner_result { - // NOTE: Dropped by `cb_free_string` - let raw_string = BnString::new(inner_result); - *result = BnString::into_raw(raw_string); - true - } else { - *result = std::ptr::null_mut(); - false + unsafe { + let ctxt: &mut T = &mut *(ctxt as *mut T); + let inner_result = ctxt.get_type_string_before_name( + Type::ref_from_raw(type_), + match platform.is_null() { + false => Some(Platform::ref_from_raw(platform)), + true => None, + }, + escaping, + ); + if let Some(inner_result) = inner_result { + // NOTE: Dropped by `cb_free_string` + let raw_string = BnString::new(inner_result); + *result = BnString::into_raw(raw_string); + true + } else { + *result = std::ptr::null_mut(); + false + } } } @@ -850,23 +862,25 @@ unsafe extern "C" fn cb_get_type_string_after_name( escaping: BNTokenEscapingType, result: *mut *mut ::std::os::raw::c_char, ) -> bool { - let ctxt: &mut T = &mut *(ctxt as *mut T); - let inner_result = ctxt.get_type_string_after_name( - Type::ref_from_raw(type_), - match platform.is_null() { - false => Some(Platform::ref_from_raw(platform)), - true => None, - }, - escaping, - ); - if let Some(inner_result) = inner_result { - let raw_string = BnString::new(inner_result); - // NOTE: Dropped by `cb_free_string` - *result = BnString::into_raw(raw_string); - true - } else { - *result = std::ptr::null_mut(); - false + unsafe { + let ctxt: &mut T = &mut *(ctxt as *mut T); + let inner_result = ctxt.get_type_string_after_name( + Type::ref_from_raw(type_), + match platform.is_null() { + false => Some(Platform::ref_from_raw(platform)), + true => None, + }, + escaping, + ); + if let Some(inner_result) = inner_result { + let raw_string = BnString::new(inner_result); + // NOTE: Dropped by `cb_free_string` + *result = BnString::into_raw(raw_string); + true + } else { + *result = std::ptr::null_mut(); + false + } } } @@ -881,32 +895,34 @@ unsafe extern "C" fn cb_get_type_lines( result: *mut *mut BNTypeDefinitionLine, result_count: *mut usize, ) -> bool { - let ctxt: &mut T = &mut *(ctxt as *mut T); - // NOTE: The caller is responsible for freeing name. - let qualified_name = QualifiedName::from_raw(&*name); - let types_ptr = NonNull::new(types).unwrap(); - let types = TypeContainer::from_raw(types_ptr); - let inner_result = ctxt.get_type_lines( - Type::ref_from_raw(type_), - &types, - qualified_name, - padding_cols as isize, - collapsed, - escaping, - ); - if let Some(inner_result) = inner_result { - let boxed_raw_lines: Box<[_]> = inner_result - .into_iter() - .map(TypeDefinitionLine::into_raw) - .collect(); - *result_count = boxed_raw_lines.len(); - // NOTE: Dropped by `cb_free_lines` - *result = Box::leak(boxed_raw_lines).as_mut_ptr(); - true - } else { - *result = std::ptr::null_mut(); - *result_count = 0; - false + unsafe { + let ctxt: &mut T = &mut *(ctxt as *mut T); + // NOTE: The caller is responsible for freeing name. + let qualified_name = QualifiedName::from_raw(&*name); + let types_ptr = NonNull::new(types).unwrap(); + let types = TypeContainer::from_raw(types_ptr); + let inner_result = ctxt.get_type_lines( + Type::ref_from_raw(type_), + &types, + qualified_name, + padding_cols as isize, + collapsed, + escaping, + ); + if let Some(inner_result) = inner_result { + let boxed_raw_lines: Box<[_]> = inner_result + .into_iter() + .map(TypeDefinitionLine::into_raw) + .collect(); + *result_count = boxed_raw_lines.len(); + // NOTE: Dropped by `cb_free_lines` + *result = Box::leak(boxed_raw_lines).as_mut_ptr(); + true + } else { + *result = std::ptr::null_mut(); + *result_count = 0; + false + } } } @@ -920,34 +936,38 @@ unsafe extern "C" fn cb_print_all_types( escaping: BNTokenEscapingType, result: *mut *mut ::std::os::raw::c_char, ) -> bool { - let ctxt: &mut T = &mut *(ctxt as *mut T); - let raw_names = std::slice::from_raw_parts(names, type_count); - // NOTE: The caller is responsible for freeing raw_names. - let names: Vec<_> = raw_names.iter().map(QualifiedName::from_raw).collect(); - let raw_types = std::slice::from_raw_parts(types, type_count); - // NOTE: The caller is responsible for freeing raw_types. - let types: Vec<_> = raw_types.iter().map(|&t| Type::ref_from_raw(t)).collect(); - let inner_result = ctxt.print_all_types( - names, - types, - BinaryView::ref_from_raw(data), - padding_cols as isize, - escaping, - ); - if let Some(inner_result) = inner_result { - let raw_string = BnString::new(inner_result); - // NOTE: Dropped by `cb_free_string` - *result = BnString::into_raw(raw_string); - true - } else { - *result = std::ptr::null_mut(); - false + unsafe { + let ctxt: &mut T = &mut *(ctxt as *mut T); + let raw_names = std::slice::from_raw_parts(names, type_count); + // NOTE: The caller is responsible for freeing raw_names. + let names: Vec<_> = raw_names.iter().map(QualifiedName::from_raw).collect(); + let raw_types = std::slice::from_raw_parts(types, type_count); + // NOTE: The caller is responsible for freeing raw_types. + let types: Vec<_> = raw_types.iter().map(|&t| Type::ref_from_raw(t)).collect(); + let inner_result = ctxt.print_all_types( + names, + types, + BinaryView::ref_from_raw(data), + padding_cols as isize, + escaping, + ); + if let Some(inner_result) = inner_result { + let raw_string = BnString::new(inner_result); + // NOTE: Dropped by `cb_free_string` + *result = BnString::into_raw(raw_string); + true + } else { + *result = std::ptr::null_mut(); + false + } } } unsafe extern "C" fn cb_free_string(_ctxt: *mut c_void, string: *mut c_char) { - // SAFETY: The returned string is just BnString - BnString::free_raw(string); + unsafe { + // SAFETY: The returned string is just BnString + BnString::free_raw(string); + } } unsafe extern "C" fn cb_free_tokens( @@ -955,11 +975,13 @@ unsafe extern "C" fn cb_free_tokens( tokens: *mut BNInstructionTextToken, count: usize, ) { - let tokens = std::ptr::slice_from_raw_parts_mut(tokens, count); - // SAFETY: tokens must have been allocated by rust. - let boxed_tokens = Box::from_raw(tokens); - for token in boxed_tokens { - InstructionTextToken::free_raw(token); + unsafe { + let tokens = std::ptr::slice_from_raw_parts_mut(tokens, count); + // SAFETY: tokens must have been allocated by rust. + let boxed_tokens = Box::from_raw(tokens); + for token in boxed_tokens { + InstructionTextToken::free_raw(token); + } } } @@ -968,10 +990,12 @@ unsafe extern "C" fn cb_free_lines( lines: *mut BNTypeDefinitionLine, count: usize, ) { - let lines = std::ptr::slice_from_raw_parts_mut(lines, count); - // SAFETY: lines must have been allocated by rust. - let boxes_lines = Box::from_raw(lines); - for line in boxes_lines { - TypeDefinitionLine::free_owned_raw(line); + unsafe { + let lines = std::ptr::slice_from_raw_parts_mut(lines, count); + // SAFETY: lines must have been allocated by rust. + let boxes_lines = Box::from_raw(lines); + for line in boxes_lines { + TypeDefinitionLine::free_owned_raw(line); + } } } diff --git a/rust/src/types/structure.rs b/rust/src/types/structure.rs index 6dd8048a6f..ef26208468 100644 --- a/rust/src/types/structure.rs +++ b/rust/src/types/structure.rs @@ -322,8 +322,10 @@ pub struct Structure { impl Structure { pub(crate) unsafe fn ref_from_raw(handle: *mut BNStructure) -> Ref { - debug_assert!(!handle.is_null()); - Ref::new(Self { handle }) + unsafe { + debug_assert!(!handle.is_null()); + Ref::new(Self { handle }) + } } pub fn builder() -> StructureBuilder { @@ -442,11 +444,13 @@ impl Debug for Structure { unsafe impl RefCountable for Structure { unsafe fn inc_ref(handle: &Self) -> Ref { - Self::ref_from_raw(BNNewStructureReference(handle.handle)) + unsafe { Self::ref_from_raw(BNNewStructureReference(handle.handle)) } } unsafe fn dec_ref(handle: &Self) { - BNFreeStructure(handle.handle); + unsafe { + BNFreeStructure(handle.handle); + } } } @@ -590,7 +594,7 @@ impl CoreArrayProvider for StructureMember { unsafe impl CoreArrayProviderInner for StructureMember { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeStructureMemberList(raw, count) + unsafe { BNFreeStructureMemberList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { diff --git a/rust/src/update.rs b/rust/src/update.rs index 48d841fb99..2dcea7f70a 100644 --- a/rust/src/update.rs +++ b/rust/src/update.rs @@ -203,7 +203,7 @@ impl CoreArrayProvider for UpdateChannel { unsafe impl CoreArrayProviderInner for UpdateChannel { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeUpdateChannelList(raw, count) + unsafe { BNFreeUpdateChannelList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { @@ -258,7 +258,7 @@ impl CoreArrayProvider for UpdateVersion { unsafe impl CoreArrayProviderInner for UpdateVersion { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeUpdateChannelVersionList(raw, count) + unsafe { BNFreeUpdateChannelVersionList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { diff --git a/rust/src/variable.rs b/rust/src/variable.rs index 1eefc9a82c..0c8bce33ac 100644 --- a/rust/src/variable.rs +++ b/rust/src/variable.rs @@ -90,7 +90,9 @@ impl CoreArrayProvider for DataVariable { unsafe impl CoreArrayProviderInner for DataVariable { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeDataVariables(raw, count); + unsafe { + BNFreeDataVariables(raw, count); + } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { @@ -160,7 +162,7 @@ impl CoreArrayProvider for NamedDataVariableWithType { unsafe impl CoreArrayProviderInner for NamedDataVariableWithType { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeDataVariablesAndName(raw, count) + unsafe { BNFreeDataVariablesAndName(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { @@ -230,7 +232,7 @@ impl CoreArrayProvider for NamedVariableWithType { unsafe impl CoreArrayProviderInner for NamedVariableWithType { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeVariableNameAndTypeList(raw, count) + unsafe { BNFreeVariableNameAndTypeList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { @@ -276,7 +278,7 @@ impl CoreArrayProvider for UserVariableValue { unsafe impl CoreArrayProviderInner for UserVariableValue { unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { - BNFreeUserVariableValues(raw) + unsafe { BNFreeUserVariableValues(raw) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { @@ -344,7 +346,7 @@ impl CoreArrayProvider for StackVariableReference { unsafe impl CoreArrayProviderInner for StackVariableReference { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeStackVariableReferenceList(raw, count) + unsafe { BNFreeStackVariableReferenceList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { @@ -372,7 +374,7 @@ impl CoreArrayProvider for SSAVariable { unsafe impl CoreArrayProviderInner for SSAVariable { unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { - BNFreeILInstructionList(raw) + unsafe { BNFreeILInstructionList(raw) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { @@ -487,7 +489,7 @@ impl CoreArrayProvider for Variable { unsafe impl CoreArrayProviderInner for Variable { unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { - BNFreeVariableList(raw) + unsafe { BNFreeVariableList(raw) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { @@ -521,7 +523,7 @@ impl CoreArrayProvider for MergedVariable { unsafe impl CoreArrayProviderInner for MergedVariable { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeMergedVariableList(raw, count) + unsafe { BNFreeMergedVariableList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { diff --git a/rust/src/websocket/client.rs b/rust/src/websocket/client.rs index 8095fc934c..3b63b4c363 100644 --- a/rust/src/websocket/client.rs +++ b/rust/src/websocket/client.rs @@ -75,12 +75,12 @@ pub struct CoreWebsocketClient { impl CoreWebsocketClient { pub(crate) unsafe fn ref_from_raw(handle: NonNull) -> Ref { - Ref::new(Self { handle }) + unsafe { Ref::new(Self { handle }) } } #[allow(clippy::mut_from_ref)] pub(crate) unsafe fn as_raw(&self) -> &mut BNWebsocketClient { - &mut *self.handle.as_ptr() + unsafe { &mut *self.handle.as_ptr() } } /// Call the connect callback function, forward the callback returned value @@ -208,17 +208,21 @@ impl ToOwned for CoreWebsocketClient { unsafe impl RefCountable for CoreWebsocketClient { unsafe fn inc_ref(handle: &Self) -> Ref { - let result = BNNewWebsocketClientReference(handle.as_raw()); - unsafe { Self::ref_from_raw(NonNull::new(result).unwrap()) } + unsafe { + let result = BNNewWebsocketClientReference(handle.as_raw()); + Self::ref_from_raw(NonNull::new(result).unwrap()) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeWebsocketClient(handle.as_raw()) + unsafe { BNFreeWebsocketClient(handle.as_raw()) } } } pub(crate) unsafe extern "C" fn cb_destroy_client(ctxt: *mut c_void) { - let _ = Box::from_raw(ctxt as *mut W); + unsafe { + let _ = Box::from_raw(ctxt as *mut W); + } } pub(crate) unsafe extern "C" fn cb_connect( @@ -228,18 +232,21 @@ pub(crate) unsafe extern "C" fn cb_connect( header_keys: *const *const c_char, header_values: *const *const c_char, ) -> bool { - let ctxt: &mut W = &mut *(ctxt as *mut W); - let host = CStr::from_ptr(host); - // SAFETY BnString and *mut c_char are transparent - let header_count = usize::try_from(header_count).unwrap(); - let header_keys = core::slice::from_raw_parts(header_keys as *const BnString, header_count); - let header_values = core::slice::from_raw_parts(header_values as *const BnString, header_count); - let header_keys_str = header_keys.iter().map(|s| s.to_string_lossy().to_string()); - let header_values_str = header_values - .iter() - .map(|s| s.to_string_lossy().to_string()); - let header = header_keys_str.zip(header_values_str); - ctxt.connect(&host.to_string_lossy(), header) + unsafe { + let ctxt: &mut W = &mut *(ctxt as *mut W); + let host = CStr::from_ptr(host); + // SAFETY BnString and *mut c_char are transparent + let header_count = usize::try_from(header_count).unwrap(); + let header_keys = core::slice::from_raw_parts(header_keys as *const BnString, header_count); + let header_values = + core::slice::from_raw_parts(header_values as *const BnString, header_count); + let header_keys_str = header_keys.iter().map(|s| s.to_string_lossy().to_string()); + let header_values_str = header_values + .iter() + .map(|s| s.to_string_lossy().to_string()); + let header = header_keys_str.zip(header_values_str); + ctxt.connect(&host.to_string_lossy(), header) + } } pub(crate) unsafe extern "C" fn cb_write( @@ -247,31 +254,41 @@ pub(crate) unsafe extern "C" fn cb_write( len: u64, ctxt: *mut c_void, ) -> bool { - let ctxt: &mut W = &mut *(ctxt as *mut W); - let len = usize::try_from(len).unwrap(); - let data = core::slice::from_raw_parts(data, len); - ctxt.write(data) + unsafe { + let ctxt: &mut W = &mut *(ctxt as *mut W); + let len = usize::try_from(len).unwrap(); + let data = core::slice::from_raw_parts(data, len); + ctxt.write(data) + } } pub(crate) unsafe extern "C" fn cb_disconnect(ctxt: *mut c_void) -> bool { - let ctxt: &mut W = &mut *(ctxt as *mut W); - ctxt.disconnect() + unsafe { + let ctxt: &mut W = &mut *(ctxt as *mut W); + ctxt.disconnect() + } } unsafe extern "C" fn cb_connected(ctxt: *mut c_void) -> bool { - let ctxt: &mut W = &mut *(ctxt as *mut W); - ctxt.connected() + unsafe { + let ctxt: &mut W = &mut *(ctxt as *mut W); + ctxt.connected() + } } unsafe extern "C" fn cb_disconnected(ctxt: *mut c_void) { - let ctxt: &mut W = &mut *(ctxt as *mut W); - ctxt.disconnected() + unsafe { + let ctxt: &mut W = &mut *(ctxt as *mut W); + ctxt.disconnected() + } } unsafe extern "C" fn cb_error(msg: *const c_char, ctxt: *mut c_void) { - let ctxt: &mut W = &mut *(ctxt as *mut W); - let msg = CStr::from_ptr(msg); - ctxt.error(&msg.to_string_lossy()) + unsafe { + let ctxt: &mut W = &mut *(ctxt as *mut W); + let msg = CStr::from_ptr(msg); + ctxt.error(&msg.to_string_lossy()) + } } unsafe extern "C" fn cb_read( @@ -279,8 +296,10 @@ unsafe extern "C" fn cb_read( len: u64, ctxt: *mut c_void, ) -> bool { - let ctxt: &mut W = &mut *(ctxt as *mut W); - let len = usize::try_from(len).unwrap(); - let data = core::slice::from_raw_parts_mut(data, len); - ctxt.read(data) + unsafe { + let ctxt: &mut W = &mut *(ctxt as *mut W); + let len = usize::try_from(len).unwrap(); + let data = core::slice::from_raw_parts_mut(data, len); + ctxt.read(data) + } } diff --git a/rust/src/websocket/provider.rs b/rust/src/websocket/provider.rs index 914a3f165c..e6b3f0013a 100644 --- a/rust/src/websocket/provider.rs +++ b/rust/src/websocket/provider.rs @@ -104,24 +104,28 @@ impl CoreArrayProvider for CoreWebsocketProvider { unsafe impl CoreArrayProviderInner for CoreWebsocketProvider { unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { - BNFreeWebsocketProviderList(raw) + unsafe { BNFreeWebsocketProviderList(raw) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { - let handle = NonNull::new(*raw).unwrap(); - Self::from_raw(handle) + unsafe { + let handle = NonNull::new(*raw).unwrap(); + Self::from_raw(handle) + } } } unsafe extern "C" fn cb_create_client( ctxt: *mut c_void, ) -> *mut BNWebsocketClient { - let ctxt: &mut W = &mut *(ctxt as *mut W); - match ctxt.create_client() { - Ok(owned_client) => { - // SAFETY: The caller is assumed to have picked up this ref. - Ref::into_raw(owned_client).handle.as_ptr() + unsafe { + let ctxt: &mut W = &mut *(ctxt as *mut W); + match ctxt.create_client() { + Ok(owned_client) => { + // SAFETY: The caller is assumed to have picked up this ref. + Ref::into_raw(owned_client).handle.as_ptr() + } + Err(_) => std::ptr::null_mut(), } - Err(_) => std::ptr::null_mut(), } } diff --git a/rust/src/worker_thread.rs b/rust/src/worker_thread.rs index 113a7d0b01..98c4ac2ac6 100644 --- a/rust/src/worker_thread.rs +++ b/rust/src/worker_thread.rs @@ -8,8 +8,10 @@ pub struct WorkerThreadActionExecutor { impl WorkerThreadActionExecutor { unsafe extern "C" fn cb_execute(ctx: *mut c_void) { - let f: Box = Box::from_raw(ctx as *mut Self); - f.execute(); + unsafe { + let f: Box = Box::from_raw(ctx as *mut Self); + f.execute(); + } } pub fn execute(&self) { diff --git a/rust/src/workflow.rs b/rust/src/workflow.rs index 72d0223799..e99d8241de 100644 --- a/rust/src/workflow.rs +++ b/rust/src/workflow.rs @@ -35,7 +35,7 @@ impl AnalysisContext { #[allow(unused)] pub(crate) unsafe fn ref_from_raw(handle: NonNull) -> Ref { - Ref::new(Self { handle }) + unsafe { Ref::new(Self { handle }) } } /// BinaryView for the current AnalysisContext @@ -141,14 +141,18 @@ impl ToOwned for AnalysisContext { unsafe impl RefCountable for AnalysisContext { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: NonNull::new(BNNewAnalysisContextReference(handle.handle.as_ptr())) - .expect("valid handle"), - }) + unsafe { + Ref::new(Self { + handle: NonNull::new(BNNewAnalysisContextReference(handle.handle.as_ptr())) + .expect("valid handle"), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeAnalysisContext(handle.handle.as_ptr()); + unsafe { + BNFreeAnalysisContext(handle.handle.as_ptr()); + } } } @@ -163,7 +167,7 @@ impl Workflow { } pub(crate) unsafe fn ref_from_raw(handle: NonNull) -> Ref { - Ref::new(Self { handle }) + unsafe { Ref::new(Self { handle }) } } /// Create a new unregistered [Workflow] with no activities. @@ -346,14 +350,18 @@ impl ToOwned for Workflow { unsafe impl RefCountable for Workflow { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: NonNull::new(BNNewWorkflowReference(handle.handle.as_ptr())) - .expect("valid handle"), - }) + unsafe { + Ref::new(Self { + handle: NonNull::new(BNNewWorkflowReference(handle.handle.as_ptr())) + .expect("valid handle"), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeWorkflow(handle.handle.as_ptr()); + unsafe { + BNFreeWorkflow(handle.handle.as_ptr()); + } } } @@ -365,14 +373,16 @@ impl CoreArrayProvider for Workflow { unsafe impl CoreArrayProviderInner for Workflow { unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { - BNFreeWorkflowList(raw, count) + unsafe { BNFreeWorkflowList(raw, count) } } unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> { - Guard::new( - Workflow::from_raw(NonNull::new(*raw).expect("valid handle")), - context, - ) + unsafe { + Guard::new( + Workflow::from_raw(NonNull::new(*raw).expect("valid handle")), + context, + ) + } } } diff --git a/rust/src/workflow/activity.rs b/rust/src/workflow/activity.rs index 71ff6c6060..5d776bba70 100644 --- a/rust/src/workflow/activity.rs +++ b/rust/src/workflow/activity.rs @@ -48,7 +48,7 @@ impl Activity { } pub(crate) unsafe fn ref_from_raw(handle: NonNull) -> Ref { - Ref::new(Self { handle }) + unsafe { Ref::new(Self { handle }) } } pub fn new(config: impl AsConfig) -> Ref { @@ -67,11 +67,13 @@ impl Activity { ctxt: *mut c_void, analysis: *mut BNAnalysisContext, ) { - let ctxt = &mut *(ctxt as *mut F); - if let Some(analysis) = NonNull::new(analysis) { - let analysis = AnalysisContext::from_raw(analysis); - let _span = ffi_span!("Activity::action", analysis.view()); - ctxt(&analysis) + unsafe { + let ctxt = &mut *(ctxt as *mut F); + if let Some(analysis) = NonNull::new(analysis) { + let analysis = AnalysisContext::from_raw(analysis); + let _span = ffi_span!("Activity::action", analysis.view()); + ctxt(&analysis) + } } } let config = config.as_config(); @@ -102,14 +104,18 @@ impl ToOwned for Activity { unsafe impl RefCountable for Activity { unsafe fn inc_ref(handle: &Self) -> Ref { - Ref::new(Self { - handle: NonNull::new(BNNewActivityReference(handle.handle.as_ptr())) - .expect("valid handle"), - }) + unsafe { + Ref::new(Self { + handle: NonNull::new(BNNewActivityReference(handle.handle.as_ptr())) + .expect("valid handle"), + }) + } } unsafe fn dec_ref(handle: &Self) { - BNFreeActivity(handle.handle.as_ptr()); + unsafe { + BNFreeActivity(handle.handle.as_ptr()); + } } } diff --git a/rust/tests/interaction.rs b/rust/tests/interaction.rs index 2f38241cd8..ccc9880971 100644 --- a/rust/tests/interaction.rs +++ b/rust/tests/interaction.rs @@ -79,23 +79,15 @@ impl InteractionHandler for MyInteractionHandler { } match &mut form.fields[0] { - FormInputField::Integer { ref mut value, .. } => { + FormInputField::Integer { value, .. } => { *value = 1337; true } - FormInputField::Address { - ref mut value, - default, - .. - } => { + FormInputField::Address { value, default, .. } => { *value = default.unwrap_or(0) + 0x10; true } - FormInputField::DirectoryName { - ref mut value, - default, - .. - } => { + FormInputField::DirectoryName { value, default, .. } => { let new_value = format!("example{}", default.clone().unwrap_or_default(),); *value = Some(new_value); true