diff options
| author | Mason Reed <mason@vector35.com> | 2024-12-22 01:21:02 -0500 |
|---|---|---|
| committer | Mason Reed <mason@vector35.com> | 2025-01-25 00:52:29 -0500 |
| commit | 6a63c17853009ce7a0071458e39c140a09440230 (patch) | |
| tree | ad59ab3b356b0a2c60423e55f62c996891788788 /rust/src/custom_binary_view.rs | |
| parent | bfa1d409b2d5e734804a5fdb4c68c90a93712f1f (diff) | |
Rust refactor
Moves a bunch of stuff out of src/types.rs that did not belong:
- Confidence
- Variable
- Function specific stuff
- Refactored InstructionInfo, see the msp430 and riscv examples.
- Renamed Function::from_raw to Function::ref_from_raw and fixed places where the ref was incremented twice
- Fixed FunctionRecognizer leaking functions (see above)
- Fixed some apis incorrectly returning Result where Option is clearer
- Started to move destructured types to the From trait for converting to an from ffi types, see Location for an example
- Started to remove bad module level imports (importing std modules like mem all over the place)
- Moved some wrapper handle types to named handle field (this improves readability), see CoreArchitecture for an example
- Removed some unintuitive getters, this is bad practice for Rust code, just access the field directly, see DataVariable for an example
- General code cleanup, purposely did not run rustfmt, that will be a single seperate commit
More rust cleanup
- Fixed invalid views being able to invoke UB when dealing with databases
- Cleaned up some helper code in dwarf_import
- Fixed inverted is_null checks causing crashes! Oops!
More rust cleanup
Still a WIP, I think branch info is still invalid, need to figure out the issue there.
- Fixed some invalid Ref lifetimes when constructing indirectly, see Array<DataVariable> for example
- Added some more comments
- Removed some "magic" functions like MLIL Function::ssa_variables
There are still a bunch of invalid lifetimes that aren't crashing us due to the usage of those API's not living long enough. But they ARE an issue.
More rust cleanup
Trying to comment more TODO's as I go along.
- Renamed llil::Function to llil::LowLevelILFunction for clarity and consistency
- Take base structures by ref in StructureBuilder::set_base_structures to prevent premature drops
- Added more raw to wrapper conversions
- Removed UB prone apis
- Getting rid of more core module references, use std!
- Removed improper Guard usage in array impls for wrapper types with no context
- Untangling the UB of the Label api, still only half done :/
More rust cleanup
- Misc formatting
- Made Logger ref counted
- Fixed leaking name of logger every time something was logged
- Fixed the last (hopefully) of the unresolved labels
- Simplified some code
Fix leak in DebugInfo::AddType
componentArray was never freed
Add more HLIL related functions to rust
More rust cleanup
improve the CustomBinaryView init process
Canonicalize path in `create_delete_empty` test
Link core in rust
When linking you must depend on the -sys crate.
This is because linker arguments (what says where to find binaryninjacore) are NOT transitive. The top level application crate MUST provide it.
For more information see:
- https://github.com/rust-lang/cargo/issues/9554#issuecomment-857882964
- https://github.com/oxidecomputer/omicron/pull/225
Remove vendored pdb crate
Use cargo to manage the git repo ref instead
Fix misc rustdoc warnings
Move actual plugins out of `rust/examples` and into `plugins`
This is where all shipped public plugins that are not arch/view/platform/lang will be at from now on
Originally they were in the rust workspace, meaning they all shared a Cargo.lock which is ill-advised.
More rust cleanup
- More clarification on plugin/executable requirements
- Made examples actually rust examples
- Add Display impl for InstructionTextToken
- Renamed feature "noexports" to "no_exports"
Move under_construction.png to assets directory
This really did bother me
Remove unneeded `extern crate bindgen`
Replace nop'd log::info with println
We don't register a compatible log sink so they will just get sent into the void
Move inline tests into tests directory
This is being done in the hopes of curbing the multi-thousand line files that will occur once we flesh out the tests
Format rust code
Update rust ci
Still need to add support for running tests in ci
More rust cleanup
- Architecture id's are now typed accordingly
- Fix some clippy lints
- Make instruction index public in LLIL
- Removed useless helper functions
- LLIL expressions and instruction indexes are now typed accordingly
Generate binaryninjacore-sys documentation
This should show binaryninjacore-sys alongside binaryninja crate
More rust cleanup
- Remove lazy_static dependency
- Remove hacky impl Debug for Type and just use the display impl
- Add more debug impls
- Reorder some top level namespace items
- Add first type test
Remove unneeded script helper in rust api
More rust cleanup
- Added main thread handler api
- Register a headless main thread handler by default in initialization
- Refactor QualifiedName to be properly owned
- Loosened some type constraints on some apis involving QualifiedName
- Fixed some apis that were crashing due to incorrect param types
- Removed extern crate cruft for log crate
- Simplified headless initialization using more wrapper apis
- Fixed segments leaking because of no ref wrapper, see BinaryViewExt::segment_at
- Added rstest to manage headless init in unit tests
- Added some more unit tests
- Refactored demangler api to be more ergonomic
- Fixed minidump plugin not building
More rust cleanup
- Fixup usage of QualifiedName in plugins
- Make QualifiedName more usable
Implement rust TypeParser
fix Platform TypeParser related functions
separate User and System implementations of TypeParserResult
Implement rust TypeContainer
More rust cleanup
- Hopefully fixed the rust.yml CI
- Added TypePrinter API (this is still WIP and will crash)
- Added TypeParser API
- Added TypeContainer API
- More work around QualifiedName apis
Oh your suppose to do this
Add workflow_dispatch trigger to rust.yml
More rust fixes
- Swapped some usage of raw 255 to MAX_CONFIDENCE, no one likes magic numbers
- New InstructionTextToken API, complete with owned data, this still needs a lot of testing.
- InstructionTextTokenKind describes a destructured InstructionTextToken, this should make token usage much clearer, some docs pending
- Added some misc Default and Debug impls
- Updated TypePrinter and architectures to use new InstructionTextToken API
Misc formatting changes
More rust cleanup
- Fixed MANY memory leaks (most due to QualifiedName)
- Made StructureBuilder more builder and less structure
- Fixed CMakeLists.txt that were globbing entire api, resulting in 100 second slowdown on cmake generation
- Added more Debug impl's
- Added some more tests
- Fixed TypeParserResult UB
- Moved the From impls to blank impl for clarity, we have multiple different variants of core to rust for some structures, it should be explicit which one you are choosing.
- PossibleValueSet should now be able to allocate so we can go from rust to core with those variants that require allocation
- Misc doc code formatting
Misc clippy lints and clippy CI
Co-authored-by: Michael Krasnitski <michael.krasnitski@gmail.com>
Fix typo in rust CI
Misc rust formatting
Fix misc typos and add typos to rust CI
Add cargo workspace
This will help tooling and external contributors get a map of the rust crates within binaryninja-api
More rust cleanup
- Format all rust plugins
- Fix some tests that were out of date
- Simplify WARP tests to only binaries, building object files from source is a pain
- Link to core in all rust plugins
- Fix some memory leaks
- Update warp insta snapshots
- Fix some misc clippy lints
Run rust tests in CI
This commit also coincides with the creation of the "testing" environment which exposes a BN_SERIAL secret for pulling a headless Binary Ninja
Install missing wayland dependency in github CI
Apparently its needed for linux file picker for the WARP integration
Set the BINARYNINJADIR so rust can find binaryninjacore in CI
The chances of this working are low
Misc remove unused dependency
Rust misc formatting fixes
Improve initialization in rust headless scripts
Provide sensible errors and validation to rust headless scripts, solves https://github.com/Vector35/binaryninja-api/issues/5796
Add BN_LICENSE environment variable to rust CI
We pass the serial to download binary ninja, but we never provided the license for core initialization
Fix typo
More rust cleanup
- Improved binary view initialization (see init_with_opts)
- Allow floating license to free itself before initialization
- Add initialization unit test
- Add better Debug impls for some common types
- Use Path api for opening binary views, this is not breaking as it uses the AsRef impl
- Bump rayon dependency and constrain dependencies to x.x
Update readme and include that directly in the rustdocs
More rust documentation changes
Add format comment to InitializationOptions::with_license
Misc formatting and clippy lint allow
More rust cleanup
- Remove under_construction.png from the build.rs it has been removed
- Use InstructionIndex in more places
- Add missing PartialOrd and Ord impls for id types
More rust cleanup
- Make workflow cloning explicit
- Add workflow tests
- Add missing property string list getting for settings
- Remove IntoActivityName (see https://github.com/Vector35/binaryninja-api/pull/6257)
More rust cleanup
This commit is half done
Misc rust formatting
More rust cleanup
- Renamed common name conflictions (I will put my justification in the PR)
- Fixed invalid instruction retrieval for LLIL
- Added common aliases for llil function, instruction and expression types (see my comment in the PR)
- Refactored the instruction retrieval for LLIL, MLIL and HLIL
- Added instruction index types to MLIL and HLIL
- Moved llil module to lowlevelil module (mlil and hlil will be moved as well)
- Added preliminary LLIL unit testing
Fix typos
Misc clippy fixes
More rust cleanup
- Normalized modules
- Split some code out into own files
- Fixed some UB in type archive and projects
- Improved API around type archives and projects substantially
- Added ProgressExecutor abstraction for functions which have a progress callback
- Improved background task documentation and added unit tests
- Added worker thread api and unit tests
- Moved some owned types to ref types, this is still not complete, but this is the path forward.
- Add external location/library accessors to the binary view
- Added some misc documentation
- Replaced mod.rs with the module name source file
Still need to normalize some paths and also update some documentation surrounding that change.
Update some tests and examples
Fix background task tests colliding
We were creating multiple background tasks with the same progress text on multiple threads
More rust cleanup
- Fixed progress executor freeing itself after one iteration
- Updated the last of the doc imports
- Moved mainthread to main_thread
- Made project creation and opening failable
We could probably AsRef<ProgressExecutor> to get around the allocation and free inside the function bodies, not high priority as those functions are long running anyways.
Move binary view initialization into function body for LLIL test
Normalize test file names
More rust cleanup
- Updated README to clarify offline documentation
- Refactored settings api
- Added settings example to show dumping settings value and specific properties
- Use the workspace to depend on binaryninja and binaryninjacore-sys
- Remove binaryninjacore-sys as a workspace member (its not really required)
Update workflow test to new settings api
More rust cleanup
- Rename Label to LowLevelILLabel
- Update the functions label map automatically
This fixed a major api blunder where the label map is returned as a reference and originally resulted in UB prone lifetime semantics. It was temporarily "fixed" with explicit label updates in the architecture implementation code. But that was less than ideal and was easy to mess up. Now the label map will be updated automatically as the location of labels is now tracked.
Misc clippy lints
More rust cleanup
- Get rid of RawFunctionViewType
- Add better Debug impl for Function
More rust cleanup
- Fixed the documentation icon using local files (thank you @mkrasnitski)
- Fixed labels being updated and overwriting the label location used to update the label map
More rust cleanup
- Added unit tests for MLIL and HLIL
- "Fixed" MLIL, LLIL, and HLIL having issues regarding Instruction vs Expression indexes
- Renamed CallingConvention to CoreCallingConvention and removed architecture generic
- Renamed CallingConventionBase to CallingConvention
- Simplified calling convention code and fixed some bugs with implicit registers
- Added impl Debug to MLIL and HLIL instructions
Still need to at some point add an Expression to MLIL and HLIL. We also might want to look into having the Instruction kind just return the expression kind.
Misc clippy lint
More rust cleanup
- Allow calling conventions to be registered for multiple architectures
- Swapped a unreachable statement to an unimplemented statement
More rust cleanup
- Fixed the issue with PDB types, this has caused me an insane amount of grief
- Fixed LLIL visit_tree missing LLIL_LOAD expressions
- Added LLIL visitor test
- Made all WARP file pickers use the rfd crate
Use the dev branch of Binary Ninja in rust CI
Misc rust fmt
More rust cleanup
- Refactored BinaryReader and BinaryWriter
- Added some warnings to high_level_il and medium_level_il modules that they are unstable
- Add BinaryReader and BinaryWriter tests
- Changed BinaryView len to return u64 (that is what the core returns)
- Misc formatting changes
- Remove extern uses in lib.rs
Add impl Debug for BinaryReader and BinaryWriter
Turn off broken tests
Add more info to the rust README.md
More rust cleanup
- Make EdgeStyle type not wrap raw
- Regression tests for WARP will run on all bins in the out dir now
impl rust Collaboration and Remote API
Fix typo
Update collaboration API
Makes collaboration more in line with the refactor. Still a lot of work to do.
Namely still need:
- Proper errors
- _with_opts functions
- More ergonomic api
- Better connection procedure
- Updated documentation
- A LOT of unit tests
- An example
- Typed id's for everything (i dont want BnString as the id!!!)
- NEED to refactor the progress callbacks into the new progress api, but we should pull in some of the stuff the collab progress has
- Elimination of apis that are dumb helpers
Separate out the rust testing and use pull_request_target
pull_request_target allows PR's to access the headless license, for this to be safe we need to prevent people from running the job.
To prevent the job from being ran we add an environment requirement on testing that a reviewer must review the code and then manually approve it to run.
More rust cleanup
- Use GroupId instead of u64
- Use ProgressCallback in place of ProgressExecutor
- Misc cleanup of FileMetadata
- Add `save_to_path` and `save_to_accessor` to save modified binaries
- Added binary_view unit tests
- Added collaboration unit tests
- Fixed a few issues with the collaboration apis
- Renamed Command registration functions so that there is no import ambiguity
- Split out RemoteUndoEntry
- Collaboration apis now have a explicit `_with_progress` set of apis
- Misc clippy lint fixes
Fix some typos
More rust cleanup
- Add extra info to README.md
- Refactor components api
- Add components unit test
Add testing and documentation to contributing section in README.md
Fix misc doc comments
Diffstat (limited to 'rust/src/custom_binary_view.rs')
| -rw-r--r-- | rust/src/custom_binary_view.rs | 852 |
1 files changed, 852 insertions, 0 deletions
diff --git a/rust/src/custom_binary_view.rs b/rust/src/custom_binary_view.rs new file mode 100644 index 00000000..d3258a2b --- /dev/null +++ b/rust/src/custom_binary_view.rs @@ -0,0 +1,852 @@ +// Copyright 2021-2024 Vector 35 Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! An interface for providing your own [BinaryView]s to Binary Ninja. + +use binaryninjacore_sys::*; + +pub use binaryninjacore_sys::BNModificationStatus as ModificationStatus; + +use std::marker::PhantomData; +use std::mem::MaybeUninit; +use std::os::raw::c_void; +use std::ptr; +use std::slice; + +use crate::architecture::Architecture; +use crate::binary_view::{BinaryView, BinaryViewBase, BinaryViewExt, Result}; +use crate::platform::Platform; +use crate::settings::Settings; +use crate::Endianness; + +use crate::rc::*; +use crate::string::*; + +/// Registers a custom `BinaryViewType` with the core. +/// +/// The `constructor` argument is called immediately after successful registration of the type with +/// the core. The `BinaryViewType` argument passed to `constructor` is the object that the +/// `AsRef<BinaryViewType>` +/// implementation of the `CustomBinaryViewType` must return. +pub fn register_view_type<S, T, F>(name: S, long_name: S, constructor: F) -> &'static T +where + S: BnStrCompatible, + T: CustomBinaryViewType, + F: FnOnce(BinaryViewType) -> T, +{ + extern "C" fn cb_valid<T>(ctxt: *mut c_void, data: *mut BNBinaryView) -> bool + where + T: CustomBinaryViewType, + { + ffi_wrap!("BinaryViewTypeBase::is_valid_for", unsafe { + let view_type = &*(ctxt as *mut T); + let data = BinaryView::ref_from_raw(BNNewViewReference(data)); + + view_type.is_valid_for(&data) + }) + } + + extern "C" fn cb_deprecated<T>(ctxt: *mut c_void) -> bool + where + T: CustomBinaryViewType, + { + ffi_wrap!("BinaryViewTypeBase::is_deprecated", unsafe { + let view_type = &*(ctxt as *mut T); + view_type.is_deprecated() + }) + } + + extern "C" fn cb_force_loadable<T>(ctxt: *mut c_void) -> bool + where + T: CustomBinaryViewType, + { + ffi_wrap!("BinaryViewTypeBase::is_force_loadable", unsafe { + let view_type = &*(ctxt as *mut T); + view_type.is_force_loadable() + }) + } + + extern "C" fn cb_create<T>(ctxt: *mut c_void, data: *mut BNBinaryView) -> *mut BNBinaryView + where + T: CustomBinaryViewType, + { + ffi_wrap!("BinaryViewTypeBase::create", unsafe { + let view_type = &*(ctxt as *mut T); + let data = BinaryView::ref_from_raw(BNNewViewReference(data)); + + let builder = CustomViewBuilder { + view_type, + actual_parent: &data, + }; + + match view_type.create_custom_view(&data, builder) { + Ok(bv) => { + // force a leak of the Ref; failure to do this would result + // in the refcount going to 0 in the process of returning it + // to the core -- we're transferring ownership of the Ref here + Ref::into_raw(bv.handle).handle + } + Err(_) => { + log::error!("CustomBinaryViewType::create_custom_view returned Err"); + ptr::null_mut() + } + } + }) + } + + extern "C" fn cb_parse<T>(ctxt: *mut c_void, data: *mut BNBinaryView) -> *mut BNBinaryView + where + T: CustomBinaryViewType, + { + ffi_wrap!("BinaryViewTypeBase::parse", unsafe { + let view_type = &*(ctxt as *mut T); + let data = BinaryView::ref_from_raw(BNNewViewReference(data)); + + let builder = CustomViewBuilder { + view_type, + actual_parent: &data, + }; + + match view_type.parse_custom_view(&data, builder) { + Ok(bv) => { + // force a leak of the Ref; failure to do this would result + // in the refcount going to 0 in the process of returning it + // to the core -- we're transferring ownership of the Ref here + Ref::into_raw(bv.handle).handle + } + Err(_) => { + log::error!("CustomBinaryViewType::parse returned Err"); + ptr::null_mut() + } + } + }) + } + + extern "C" fn cb_load_settings<T>(ctxt: *mut c_void, data: *mut BNBinaryView) -> *mut BNSettings + where + T: CustomBinaryViewType, + { + ffi_wrap!("BinaryViewTypeBase::load_settings", unsafe { + let view_type = &*(ctxt as *mut T); + let data = BinaryView::ref_from_raw(BNNewViewReference(data)); + + match view_type.load_settings_for_data(&data) { + Some(settings) => Ref::into_raw(settings).handle, + None => ptr::null_mut() as *mut _, + } + }) + } + + let name = name.into_bytes_with_nul(); + let name_ptr = name.as_ref().as_ptr() as *mut _; + + let long_name = long_name.into_bytes_with_nul(); + let long_name_ptr = long_name.as_ref().as_ptr() as *mut _; + + let ctxt = Box::leak(Box::new(MaybeUninit::zeroed())); + + let mut bn_obj = BNCustomBinaryViewType { + context: ctxt.as_mut_ptr() as *mut _, + create: Some(cb_create::<T>), + parse: Some(cb_parse::<T>), + isValidForData: Some(cb_valid::<T>), + isDeprecated: Some(cb_deprecated::<T>), + isForceLoadable: Some(cb_force_loadable::<T>), + getLoadSettingsForData: Some(cb_load_settings::<T>), + }; + + unsafe { + let handle = BNRegisterBinaryViewType(name_ptr, long_name_ptr, &mut bn_obj as *mut _); + if handle.is_null() { + // avoid leaking the space allocated for the type, but also + // avoid running its Drop impl (if any -- not that there should + // be one since view types live for the life of the process) as + // MaybeUninit suppress the Drop implementation of it's inner type + drop(Box::from_raw(ctxt)); + + panic!("bvt registration failed"); + } + + ctxt.write(constructor(BinaryViewType { handle })); + ctxt.assume_init_mut() + } +} + +pub trait BinaryViewTypeBase: AsRef<BinaryViewType> { + fn is_valid_for(&self, data: &BinaryView) -> bool; + + fn is_deprecated(&self) -> bool { + false + } + + fn is_force_loadable(&self) -> bool { + false + } + + fn default_load_settings_for_data(&self, data: &BinaryView) -> Option<Ref<Settings>> { + let settings_handle = + unsafe { BNGetBinaryViewDefaultLoadSettingsForData(self.as_ref().handle, data.handle) }; + + if settings_handle.is_null() { + None + } else { + unsafe { Some(Settings::from_raw(settings_handle)) } + } + } + + fn load_settings_for_data(&self, _data: &BinaryView) -> Option<Ref<Settings>> { + None + } +} + +pub trait BinaryViewTypeExt: BinaryViewTypeBase { + fn name(&self) -> BnString { + unsafe { BnString::from_raw(BNGetBinaryViewTypeName(self.as_ref().handle)) } + } + + fn long_name(&self) -> BnString { + unsafe { BnString::from_raw(BNGetBinaryViewTypeLongName(self.as_ref().handle)) } + } + + fn register_arch<A: Architecture>(&self, id: u32, endianness: Endianness, arch: &A) { + unsafe { + BNRegisterArchitectureForViewType( + self.as_ref().handle, + id, + endianness, + arch.as_ref().handle, + ); + } + } + + fn register_platform(&self, id: u32, plat: &Platform) { + let arch = plat.arch(); + + unsafe { + BNRegisterPlatformForViewType(self.as_ref().handle, id, arch.handle, plat.handle); + } + } + + fn open(&self, data: &BinaryView) -> Result<Ref<BinaryView>> { + let handle = unsafe { BNCreateBinaryViewOfType(self.as_ref().handle, data.handle) }; + + if handle.is_null() { + log::error!( + "failed to create BinaryView of BinaryViewType '{}'", + self.name() + ); + return Err(()); + } + + unsafe { Ok(BinaryView::ref_from_raw(handle)) } + } + + fn parse(&self, data: &BinaryView) -> Result<Ref<BinaryView>> { + let handle = unsafe { BNParseBinaryViewOfType(self.as_ref().handle, data.handle) }; + + if handle.is_null() { + log::error!( + "failed to parse BinaryView of BinaryViewType '{}'", + self.name() + ); + return Err(()); + } + + unsafe { Ok(BinaryView::ref_from_raw(handle)) } + } +} + +impl<T: BinaryViewTypeBase> BinaryViewTypeExt for T {} + +#[derive(Copy, Clone, PartialEq, Eq, Hash)] +pub struct BinaryViewType { + pub handle: *mut BNBinaryViewType, +} + +impl BinaryViewType { + pub(crate) unsafe fn from_raw(handle: *mut BNBinaryViewType) -> Self { + debug_assert!(!handle.is_null()); + Self { handle } + } + + pub fn list_all() -> Array<BinaryViewType> { + unsafe { + let mut count: usize = 0; + let types = BNGetBinaryViewTypes(&mut count as *mut _); + Array::new(types, count, ()) + } + } + + pub fn list_valid_types_for(data: &BinaryView) -> Array<BinaryViewType> { + unsafe { + let mut count: usize = 0; + let types = BNGetBinaryViewTypesForData(data.handle, &mut count as *mut _); + Array::new(types, count, ()) + } + } + + /// Looks up a BinaryViewType by its short name + pub fn by_name<N: BnStrCompatible>(name: N) -> Result<Self> { + let bytes = name.into_bytes_with_nul(); + let handle = unsafe { BNGetBinaryViewTypeByName(bytes.as_ref().as_ptr() as *const _) }; + match handle.is_null() { + false => Ok(unsafe { BinaryViewType::from_raw(handle) }), + true => Err(()), + } + } +} + +impl BinaryViewTypeBase for BinaryViewType { + fn is_valid_for(&self, data: &BinaryView) -> bool { + unsafe { BNIsBinaryViewTypeValidForData(self.handle, data.handle) } + } + + fn is_deprecated(&self) -> bool { + unsafe { BNIsBinaryViewTypeDeprecated(self.handle) } + } + + fn is_force_loadable(&self) -> bool { + unsafe { BNIsBinaryViewTypeForceLoadable(self.handle) } + } + + fn load_settings_for_data(&self, data: &BinaryView) -> Option<Ref<Settings>> { + let settings_handle = + unsafe { BNGetBinaryViewLoadSettingsForData(self.handle, data.handle) }; + + if settings_handle.is_null() { + None + } else { + unsafe { Some(Settings::from_raw(settings_handle)) } + } + } +} + +impl CoreArrayProvider for BinaryViewType { + type Raw = *mut BNBinaryViewType; + type Context = (); + type Wrapped<'a> = Guard<'a, BinaryViewType>; +} + +unsafe impl CoreArrayProviderInner for BinaryViewType { + unsafe fn free(raw: *mut Self::Raw, _count: usize, _context: &Self::Context) { + BNFreeBinaryViewTypeList(raw); + } + + unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { + Guard::new(BinaryViewType::from_raw(*raw), &()) + } +} + +impl AsRef<BinaryViewType> for BinaryViewType { + fn as_ref(&self) -> &Self { + self + } +} + +unsafe impl Send for BinaryViewType {} +unsafe impl Sync for BinaryViewType {} + +pub trait CustomBinaryViewType: 'static + BinaryViewTypeBase + Sync { + fn create_custom_view<'builder>( + &self, + data: &BinaryView, + builder: CustomViewBuilder<'builder, Self>, + ) -> Result<CustomView<'builder>>; + + fn parse_custom_view<'builder>( + &self, + data: &BinaryView, + builder: CustomViewBuilder<'builder, Self>, + ) -> Result<CustomView<'builder>> { + // TODO: Check to make sure data.type_name is not Self::type_name ? + self.create_custom_view(data, builder) + } +} + +/// Represents a request from the core to instantiate a custom BinaryView +pub struct CustomViewBuilder<'a, T: CustomBinaryViewType + ?Sized> { + view_type: &'a T, + actual_parent: &'a BinaryView, +} + +pub unsafe trait CustomBinaryView: 'static + BinaryViewBase + Sync + Sized { + type Args: Send; + + fn new(handle: &BinaryView, args: &Self::Args) -> Result<Self>; + fn init(&mut self, args: Self::Args) -> Result<()>; +} + +/// Represents a partially initialized custom `BinaryView` that should be returned to the core +/// from the `create_custom_view` method of a `CustomBinaryViewType`. +#[must_use] +pub struct CustomView<'builder> { + // this object can't actually be treated like a real + // BinaryView as it isn't fully initialized until the + // core receives it from the BNCustomBinaryViewType::create + // callback. + handle: Ref<BinaryView>, + _builder: PhantomData<&'builder ()>, +} + +impl<'a, T: CustomBinaryViewType> CustomViewBuilder<'a, T> { + /// Begins creating a custom BinaryView. + /// + /// This function may only be called from the `create_custom_view` function of a + /// `CustomBinaryViewType`. + /// + /// `parent` specifies the view that the core will treat as the parent view, that + /// Segments created against the created view will be backed by `parent`. It will + /// usually be (but is not required to be) the `data` argument of the `create_custom_view` + /// callback. + /// + /// `constructor` will not be called until well after the value returned by this function + /// has been returned by `create_custom_view` callback to the core, and may not ever + /// be called if the value returned by this function is dropped or leaked. + /// + /// # Errors + /// + /// This function will fail if the `FileMetadata` object associated with the *expected* parent + /// (i.e., the `data` argument passed to the `create_custom_view` function) already has an + /// associated `BinaryView` of the same `CustomBinaryViewType`. Multiple `BinaryView` objects + /// of the same `BinaryViewType` belonging to the same `FileMetadata` object is prohibited and + /// can cause strange, delayed segmentation faults. + /// + /// # Safety + /// + /// `constructor` should avoid doing anything with the object it returns, especially anything + /// that would cause the core to invoke any of the `BinaryViewBase` methods. The core isn't + /// going to consider the object fully initialized until after that callback has run. + /// + /// The `BinaryView` argument passed to the constructor function is the object that is expected + /// to be returned by the `AsRef<BinaryView>` implementation required by the `BinaryViewBase` trait. + /// TODO FIXME whelp this is broke going to need 2 init callbacks + pub fn create<V>(self, parent: &BinaryView, view_args: V::Args) -> Result<CustomView<'a>> + where + V: CustomBinaryView, + { + let file = self.actual_parent.file(); + let view_type = self.view_type; + + let view_name = view_type.name(); + + if let Some(bv) = file.view_of_type(view_name.as_str()) { + // while it seems to work most of the time, you can get really unlucky + // if the a free of the existing view of the same type kicks off while + // BNCreateBinaryViewOfType is still running. the freeObject callback + // will run for the new view before we've even finished initializing, + // and that's all she wrote. + // + // even if we deal with it gracefully in cb_free_object, + // BNCreateBinaryViewOfType is still going to crash, so we're just + // going to try and stop this from happening in the first place. + log::error!( + "attempt to create duplicate view of type '{}' (existing: {:?})", + view_name.as_str(), + bv.handle + ); + + return Err(()); + } + + // struct representing the context of a BNCustomBinaryView. Can be safely + // dropped at any moment. + struct CustomViewContext<V> + where + V: CustomBinaryView, + { + raw_handle: *mut BNBinaryView, + state: CustomViewContextState<V>, + } + + enum CustomViewContextState<V> + where + V: CustomBinaryView, + { + Uninitialized { args: V::Args }, + Initialized { view: V }, + // dummy state, used as a helper to change states, only happen if the + // `new` or `init` function fails. + None, + } + + impl<V: CustomBinaryView> CustomViewContext<V> { + fn assume_init_ref(&self) -> &V { + let CustomViewContextState::Initialized { view } = &self.state else { + panic!("CustomViewContextState in invalid state"); + }; + view + } + } + + extern "C" fn cb_init<V>(ctxt: *mut c_void) -> bool + where + V: CustomBinaryView, + { + ffi_wrap!("BinaryViewBase::init", unsafe { + let context = &mut *(ctxt as *mut CustomViewContext<V>); + let handle = BinaryView::ref_from_raw(context.raw_handle); + + // take the uninitialized state and use the args to call init + let mut state = CustomViewContextState::None; + core::mem::swap(&mut context.state, &mut state); + let CustomViewContextState::Uninitialized { args } = state else { + panic!("CustomViewContextState in invalid state"); + }; + match V::new(handle.as_ref(), &args) { + Ok(mut view) => match view.init(args) { + Ok(_) => { + // put the initialized state + context.state = CustomViewContextState::Initialized { view }; + true + } + Err(_) => { + log::error!("CustomBinaryView::init failed; custom view returned Err"); + false + } + }, + Err(_) => { + log::error!("CustomBinaryView::new failed; custom view returned Err"); + false + } + } + }) + } + + extern "C" fn cb_free_object<V>(ctxt: *mut c_void) + where + V: CustomBinaryView, + { + ffi_wrap!("BinaryViewBase::freeObject", unsafe { + let context = ctxt as *mut CustomViewContext<V>; + let context = Box::from_raw(context); + + if context.raw_handle.is_null() { + // being called here is essentially a guarantee that BNCreateBinaryViewOfType + // is above above us on the call stack somewhere -- no matter what we do, a crash + // is pretty much certain at this point. + // + // this has been observed when two views of the same BinaryViewType are created + // against the same BNFileMetaData object, and one of the views gets freed while + // the second one is being initialized -- somehow the partially initialized one + // gets freed before BNCreateBinaryViewOfType returns. + // + // multiples views of the same BinaryViewType in a BNFileMetaData object are + // prohibited, so an API contract was violated in order to get here. + // + // if we're here, it's too late to do anything about it, though we can at least not + // run the destructor on the custom view since that memory is uninitialized. + log::error!( + "BinaryViewBase::freeObject called on partially initialized object! crash imminent!" + ); + } else if matches!( + &context.state, + CustomViewContextState::None | CustomViewContextState::Uninitialized { .. } + ) { + // making it here means somebody went out of their way to leak a BinaryView + // after calling BNCreateCustomView and never gave the BNBinaryView handle + // to the core (which would have called cb_init) + // + // the result is a half-initialized BinaryView that the core will happily hand out + // references to via BNGetFileViewofType even though it was never initialized + // all the way. + // + // TODO update when this corner case gets fixed in the core? + // + // we can't do anything to prevent this, but we can at least have the crash + // not be our fault. + log::error!("BinaryViewBase::freeObject called on leaked/never initialized custom view!"); + } + }) + } + + extern "C" fn cb_read<V>( + ctxt: *mut c_void, + dest: *mut c_void, + offset: u64, + len: usize, + ) -> usize + where + V: CustomBinaryView, + { + ffi_wrap!("BinaryViewBase::read", unsafe { + let context = &*(ctxt as *mut CustomViewContext<V>); + let dest = slice::from_raw_parts_mut(dest as *mut u8, len); + context.assume_init_ref().read(dest, offset) + }) + } + + extern "C" fn cb_write<V>( + ctxt: *mut c_void, + offset: u64, + src: *const c_void, + len: usize, + ) -> usize + where + V: CustomBinaryView, + { + ffi_wrap!("BinaryViewBase::write", unsafe { + let context = &*(ctxt as *mut CustomViewContext<V>); + let src = slice::from_raw_parts(src as *const u8, len); + context.assume_init_ref().write(offset, src) + }) + } + + extern "C" fn cb_insert<V>( + ctxt: *mut c_void, + offset: u64, + src: *const c_void, + len: usize, + ) -> usize + where + V: CustomBinaryView, + { + ffi_wrap!("BinaryViewBase::insert", unsafe { + let context = &*(ctxt as *mut CustomViewContext<V>); + let src = slice::from_raw_parts(src as *const u8, len); + context.assume_init_ref().insert(offset, src) + }) + } + + extern "C" fn cb_remove<V>(ctxt: *mut c_void, offset: u64, len: u64) -> usize + where + V: CustomBinaryView, + { + ffi_wrap!("BinaryViewBase::remove", unsafe { + let context = &*(ctxt as *mut CustomViewContext<V>); + context.assume_init_ref().remove(offset, len as usize) + }) + } + + extern "C" fn cb_modification<V>(ctxt: *mut c_void, offset: u64) -> ModificationStatus + where + V: CustomBinaryView, + { + ffi_wrap!("BinaryViewBase::modification_status", unsafe { + let context = &*(ctxt as *mut CustomViewContext<V>); + context.assume_init_ref().modification_status(offset) + }) + } + + extern "C" fn cb_offset_valid<V>(ctxt: *mut c_void, offset: u64) -> bool + where + V: CustomBinaryView, + { + ffi_wrap!("BinaryViewBase::offset_valid", unsafe { + let context = &*(ctxt as *mut CustomViewContext<V>); + context.assume_init_ref().offset_valid(offset) + }) + } + + extern "C" fn cb_offset_readable<V>(ctxt: *mut c_void, offset: u64) -> bool + where + V: CustomBinaryView, + { + ffi_wrap!("BinaryViewBase::readable", unsafe { + let context = &*(ctxt as *mut CustomViewContext<V>); + context.assume_init_ref().offset_readable(offset) + }) + } + + extern "C" fn cb_offset_writable<V>(ctxt: *mut c_void, offset: u64) -> bool + where + V: CustomBinaryView, + { + ffi_wrap!("BinaryViewBase::writable", unsafe { + let context = &*(ctxt as *mut CustomViewContext<V>); + context.assume_init_ref().offset_writable(offset) + }) + } + + extern "C" fn cb_offset_executable<V>(ctxt: *mut c_void, offset: u64) -> bool + where + V: CustomBinaryView, + { + ffi_wrap!("BinaryViewBase::offset_executable", unsafe { + let context = &*(ctxt as *mut CustomViewContext<V>); + context.assume_init_ref().offset_executable(offset) + }) + } + + extern "C" fn cb_offset_backed_by_file<V>(ctxt: *mut c_void, offset: u64) -> bool + where + V: CustomBinaryView, + { + ffi_wrap!("BinaryViewBase::offset_backed_by_file", unsafe { + let context = &*(ctxt as *mut CustomViewContext<V>); + context.assume_init_ref().offset_backed_by_file(offset) + }) + } + + extern "C" fn cb_next_valid_offset<V>(ctxt: *mut c_void, offset: u64) -> u64 + where + V: CustomBinaryView, + { + ffi_wrap!("BinaryViewBase::next_valid_offset_after", unsafe { + let context = &*(ctxt as *mut CustomViewContext<V>); + context.assume_init_ref().next_valid_offset_after(offset) + }) + } + + extern "C" fn cb_start<V>(ctxt: *mut c_void) -> u64 + where + V: CustomBinaryView, + { + ffi_wrap!("BinaryViewBase::start", unsafe { + let context = &*(ctxt as *mut CustomViewContext<V>); + context.assume_init_ref().start() + }) + } + + extern "C" fn cb_length<V>(ctxt: *mut c_void) -> u64 + where + V: CustomBinaryView, + { + ffi_wrap!("BinaryViewBase::len", unsafe { + let context = &*(ctxt as *mut CustomViewContext<V>); + context.assume_init_ref().len() + }) + } + + extern "C" fn cb_entry_point<V>(ctxt: *mut c_void) -> u64 + where + V: CustomBinaryView, + { + ffi_wrap!("BinaryViewBase::entry_point", unsafe { + let context = &*(ctxt as *mut CustomViewContext<V>); + context.assume_init_ref().entry_point() + }) + } + + extern "C" fn cb_executable<V>(ctxt: *mut c_void) -> bool + where + V: CustomBinaryView, + { + ffi_wrap!("BinaryViewBase::executable", unsafe { + let context = &*(ctxt as *mut CustomViewContext<V>); + context.assume_init_ref().executable() + }) + } + + extern "C" fn cb_endianness<V>(ctxt: *mut c_void) -> Endianness + where + V: CustomBinaryView, + { + ffi_wrap!("BinaryViewBase::default_endianness", unsafe { + let context = &*(ctxt as *mut CustomViewContext<V>); + + context.assume_init_ref().default_endianness() + }) + } + + extern "C" fn cb_relocatable<V>(ctxt: *mut c_void) -> bool + where + V: CustomBinaryView, + { + ffi_wrap!("BinaryViewBase::relocatable", unsafe { + let context = &*(ctxt as *mut CustomViewContext<V>); + + context.assume_init_ref().relocatable() + }) + } + + extern "C" fn cb_address_size<V>(ctxt: *mut c_void) -> usize + where + V: CustomBinaryView, + { + ffi_wrap!("BinaryViewBase::address_size", unsafe { + let context = &*(ctxt as *mut CustomViewContext<V>); + + context.assume_init_ref().address_size() + }) + } + + extern "C" fn cb_save<V>(ctxt: *mut c_void, _fa: *mut BNFileAccessor) -> bool + where + V: CustomBinaryView, + { + ffi_wrap!("BinaryViewBase::save", unsafe { + let _context = &*(ctxt as *mut CustomViewContext<V>); + false + }) + } + + let ctxt = Box::new(CustomViewContext::<V> { + raw_handle: ptr::null_mut(), + state: CustomViewContextState::Uninitialized { args: view_args }, + }); + + let ctxt = Box::into_raw(ctxt); + + let mut bn_obj = BNCustomBinaryView { + context: ctxt as *mut _, + init: Some(cb_init::<V>), + freeObject: Some(cb_free_object::<V>), + externalRefTaken: None, + externalRefReleased: None, + read: Some(cb_read::<V>), + write: Some(cb_write::<V>), + insert: Some(cb_insert::<V>), + remove: Some(cb_remove::<V>), + getModification: Some(cb_modification::<V>), + isValidOffset: Some(cb_offset_valid::<V>), + isOffsetReadable: Some(cb_offset_readable::<V>), + isOffsetWritable: Some(cb_offset_writable::<V>), + isOffsetExecutable: Some(cb_offset_executable::<V>), + isOffsetBackedByFile: Some(cb_offset_backed_by_file::<V>), + getNextValidOffset: Some(cb_next_valid_offset::<V>), + getStart: Some(cb_start::<V>), + getLength: Some(cb_length::<V>), + getEntryPoint: Some(cb_entry_point::<V>), + isExecutable: Some(cb_executable::<V>), + getDefaultEndianness: Some(cb_endianness::<V>), + isRelocatable: Some(cb_relocatable::<V>), + getAddressSize: Some(cb_address_size::<V>), + save: Some(cb_save::<V>), + }; + + unsafe { + let res = BNCreateCustomBinaryView( + view_name.as_ptr(), + file.handle, + parent.handle, + &mut bn_obj, + ); + + if res.is_null() { + // TODO not sure when this can even happen, let alone what we're supposed to do about + // it. cb_init isn't normally called until later, and cb_free_object definitely won't + // have been called, so we'd at least be on the hook for freeing that stuff... + // probably. + // + // no idea how to force this to fail so I can test this, so just going to do the + // reasonable thing and panic. + panic!("failed to create custom binary view!"); + } + + (*ctxt).raw_handle = res; + + Ok(CustomView { + handle: BinaryView::ref_from_raw(res), + _builder: PhantomData, + }) + } + } + + pub fn wrap_existing(self, wrapped_view: Ref<BinaryView>) -> Result<CustomView<'a>> { + Ok(CustomView { + handle: wrapped_view, + _builder: PhantomData, + }) + } +} |
