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/lib.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/lib.rs')
| -rw-r--r-- | rust/src/lib.rs | 660 |
1 files changed, 212 insertions, 448 deletions
diff --git a/rust/src/lib.rs b/rust/src/lib.rs index eff9518d..08e31c00 100644 --- a/rust/src/lib.rs +++ b/rust/src/lib.rs @@ -12,149 +12,58 @@ // See the License for the specific language governing permissions and // limitations under the License. -// TODO : These clippy-allow are bad and needs to be removed +// TODO: These clippy-allow are bad and needs to be removed #![allow(clippy::missing_safety_doc)] #![allow(clippy::result_unit_err)] #![allow(clippy::type_complexity)] -#![doc(html_root_url = "https://dev-rust.binary.ninja/binaryninja/")] -#![doc(html_favicon_url = "/favicon.ico")] -#![doc(html_logo_url = "/logo.png")] +#![allow(clippy::too_many_arguments)] +#![allow(clippy::needless_doctest_main)] +#![doc(html_root_url = "https://dev-rust.binary.ninja/")] +#![doc(html_favicon_url = "https://binary.ninja/icons/favicon-32x32.png")] +#![doc(html_logo_url = "https://binary.ninja/icons/android-chrome-512x512.png")] #![doc(issue_tracker_base_url = "https://github.com/Vector35/binaryninja-api/issues/")] - -//! This crate is the official [Binary Ninja] API wrapper for Rust. -//! -//! [Binary Ninja] is an interactive disassembler, decompiler, and binary analysis platform for reverse engineers, malware analysts, vulnerability researchers, and software developers that runs on Windows, macOS, and Linux. Our extensive API can be used to create and customize loaders, add or augment architectures, customize the UI, or automate any workflow (types, patches, decompilation...anything!). -//! -//! If you're just getting started with [Binary Ninja], you may wish to check out the [Getting Started Guide] -//! -//! If you have questions, we'd love to answer them in [our public Slack], and if you find any issues, please [file an issue] or [submit a PR]. -//! -//! --- -//! # Warning -//! <img align="right" src="../under_construction.png" width="175" height="175"> -//! -//! > ⚠️ **These bindings are in a very early beta, only have partial support for the core APIs and are still actively under development. Compatibility _will_ break and conventions _will_ change! They are being used for core Binary Ninja features however, so we expect much of what is already there to be reliable enough to build on, just don't be surprised if your plugins/scripts need to hit a moving target.** -//! -//! > ⚠️ This project runs on Rust version `1.83.0` -//! -//! --- -//! -//! # Examples -//! -//! There are two distinct ways to use this crate: -//! 1. [Writing a Plugin](#writing-a-plugin) -//! 2. [Writing a Script](#writing-a-script) -//! -//! ## Writing a Plugin -//! -//! Create a new library (`cargo new --lib <plugin-name>`) and include the following in your `Cargo.toml`: -//! -//! ```toml -//! [lib] -//! crate-type = ["cdylib"] -//! -//! [dependencies] -//! binaryninja = {git = "https://github.com/Vector35/binaryninja-api.git", branch = "dev"} -//! ``` -//! -//! In `lib.rs` you'll need to provide a `CorePluginInit` or `UIPluginInit` function for Binary Ninja to call. -//! -//! See [`command`] for the different actions you can provide and how to register your plugin with [Binary Ninja]. -//! -//! ## Writing a Script: -//! -//! "Scripts" are binaries (`cargo new --bin <script-name>`), and have some specific requirements: -//! -//! ### build.rs -//! -//! Because [the only official method of providing linker arguments to a crate is through that crate's `build.rs`], all scripts need to provide their own `build.rs` so they can probably link with Binary Ninja. -//! -//! The most up-to-date version of the suggested [`build.rs` is here]. -//! -//! ### `main.rs` -//! Standalone binaries need to initialize Binary Ninja before they can work. You can do this through [`headless::Session`], [`headless::script_helper`], or [`headless::init()`] at start and [`headless::shutdown()`] at shutdown. -//! ```no_run -//! // This loads all the core architecture, platform, etc plugins -//! // Standalone executables need to call this, but plugins do not -//! let headless_session = binaryninja::headless::Session::new(); -//! -//! println!("Loading binary..."); -//! let bv = headless_session.load("/bin/cat").expect("Couldn't open `/bin/cat`"); -//! -//! // Your code here... -//! ``` -//! -//! ### `Cargo.toml` -//! ```toml -//! [dependencies] -//! binaryninja = { git = "https://github.com/Vector35/binaryninja-api.git", branch = "dev"} -//! ``` -//! -//! See the [examples] on GitHub for more comprehensive examples. -//! -//! [Binary Ninja]: https://binary.ninja/ -//! [Getting Started Guide]: https://docs.binary.ninja/ -//! [our public Slack]: https://join.slack.com/t/binaryninja/shared_invite/zt-3u4vu3ja-IGUF4ZWNlD7ER2ulvICvuQ -//! [file an issue]: https://github.com/Vector35/binaryninja-api/issues -//! [submit a PR]: https://github.com/Vector35/binaryninja-api/pulls -//! [the only official method of providing linker arguments to a crate is through that crate's `build.rs`]: https://github.com/rust-lang/cargo/issues/9554 -//! [`build.rs` is here]: https://github.com/Vector35/binaryninja-api/blob/dev/rust/examples/template/build.rs -//! [examples]: https://github.com/Vector35/binaryninja-api/tree/dev/rust/examples -//! - -#[macro_use] -extern crate log; -#[doc(hidden)] -pub extern crate binaryninjacore_sys; -#[cfg(feature = "rayon")] -extern crate rayon; - -// TODO -// move some options to results -// replace `fn handle` with `AsRef` bounds -// possible values -// arch rework -// cc possible values -// bv reorg -// core fileaccessor (for bv saving) -// platform cc +#![doc = include_str!("../README.md")] #[macro_use] mod ffi; mod operand_iter; pub mod architecture; -pub mod backgroundtask; -pub mod basicblock; -pub mod binaryreader; -pub mod binaryview; -pub mod binarywriter; -pub mod callingconvention; +pub mod background_task; +pub mod basic_block; +pub mod binary_reader; +pub mod binary_view; +pub mod binary_writer; +pub mod calling_convention; +pub mod collaboration; pub mod command; -pub mod custombinaryview; +pub mod component; +pub mod confidence; +pub mod custom_binary_view; +pub mod data_buffer; pub mod database; -pub mod databuffer; pub mod debuginfo; pub mod demangle; pub mod disassembly; +pub mod download_provider; pub mod enterprise; -pub mod component; -pub mod downloadprovider; -pub mod externallibrary; -pub mod fileaccessor; -pub mod filemetadata; +pub mod external_library; +pub mod file_accessor; +pub mod file_metadata; pub mod flowgraph; pub mod function; -pub mod functionrecognizer; +pub mod function_recognizer; pub mod headless; -pub mod hlil; +pub mod high_level_il; pub mod interaction; -pub mod linearview; -pub mod llil; +pub mod linear_view; pub mod logger; +pub mod low_level_il; +pub mod main_thread; +pub mod medium_level_il; pub mod metadata; -pub mod mlil; pub mod platform; +pub mod progress; pub mod project; pub mod rc; pub mod references; @@ -165,124 +74,66 @@ pub mod settings; pub mod string; pub mod symbol; pub mod tags; -pub mod templatesimplifier; -pub mod typelibrary; -pub mod typearchive; +pub mod template_simplifier; +pub mod type_archive; +pub mod type_container; +pub mod type_library; +pub mod type_parser; +pub mod type_printer; pub mod types; pub mod update; +pub mod variable; +pub mod worker_thread; pub mod workflow; -use std::collections::HashMap; -use std::ffi::{c_void, CStr}; -use std::path::PathBuf; -use std::ptr; -use binaryninjacore_sys::{BNBinaryView, BNFileMetadata, BNFunction, BNObjectDestructionCallbacks, BNRegisterObjectDestructionCallbacks, BNUnregisterObjectDestructionCallbacks}; -pub use binaryninjacore_sys::BNBranchType as BranchType; -pub use binaryninjacore_sys::BNEndianness as Endianness; -use binaryview::BinaryView; +use crate::file_metadata::FileMetadata; +use crate::function::Function; +use binary_view::BinaryView; +use binaryninjacore_sys::*; use metadata::Metadata; use metadata::MetadataType; +use rc::Ref; +use std::collections::HashMap; +use std::ffi::{c_char, c_void, CStr}; +use std::path::{Path, PathBuf}; use string::BnStrCompatible; +use string::BnString; use string::IntoJson; -use crate::filemetadata::FileMetadata; -use crate::function::Function; -// Commented out to suppress unused warnings -// const BN_MAX_INSTRUCTION_LENGTH: u64 = 256; -// const BN_DEFAULT_INSTRUCTION_LENGTH: u64 = 16; -// const BN_DEFAULT_OPCODE_DISPLAY: u64 = 8; -// const BN_MAX_INSTRUCTION_BRANCHES: u64 = 3; -// const BN_MAX_STORED_DATA_LENGTH: u64 = 0x3fffffff; -// const BN_NULL_ID: i64 = -1; -// const BN_INVALID_REGISTER: usize = 0xffffffff; -// const BN_AUTOCOERCE_EXTERN_PTR: u64 = 0xfffffffd; -// const BN_NOCOERCE_EXTERN_PTR: u64 = 0xfffffffe; -// const BN_INVALID_OPERAND: u64 = 0xffffffff; -// const BN_MAX_STRING_LENGTH: u64 = 128; -// const BN_MAX_VARIABLE_OFFSET: u64 = 0x7fffffffff; -// const BN_MAX_VARIABLE_INDEX: u64 = 0xfffff; -// const BN_MINIMUM_CONFIDENCE: u8 = 1; -// const BN_HEURISTIC_CONFIDENCE: u8 = 192; - -const BN_FULL_CONFIDENCE: u8 = 255; -const BN_INVALID_EXPR: usize = usize::MAX; - -unsafe extern "C" fn cb_progress_func<F: FnMut(usize, usize) -> bool>( - ctxt: *mut std::ffi::c_void, - progress: usize, - total: usize, -) -> bool { - if ctxt.is_null() { - return true; - } - let closure: &mut F = std::mem::transmute(ctxt); - closure(progress, total) -} - -unsafe extern "C" fn cb_progress_nop( - _ctxt: *mut std::ffi::c_void, - _arg1: usize, - _arg2: usize -) -> bool { - true -} +use crate::progress::{NoProgressCallback, ProgressCallback}; +pub use binaryninjacore_sys::BNBranchType as BranchType; +pub use binaryninjacore_sys::BNDataFlowQueryOption as DataFlowQueryOption; +pub use binaryninjacore_sys::BNEndianness as Endianness; +pub use binaryninjacore_sys::BNILBranchDependence as ILBranchDependence; +pub const BN_FULL_CONFIDENCE: u8 = u8::MAX; +pub const BN_INVALID_EXPR: usize = usize::MAX; /// The main way to open and load files into Binary Ninja. Make sure you've properly initialized the core before calling this function. See [`crate::headless::init()`] -pub fn load<S>( - filename: S, -) -> Option<rc::Ref<binaryview::BinaryView>> -where - S: BnStrCompatible, -{ - let filename = filename.into_bytes_with_nul(); - let options = "\x00"; - - - let handle = unsafe { - binaryninjacore_sys::BNLoadFilename( - filename.as_ref().as_ptr() as *mut _, - true, - options.as_ptr() as *mut core::ffi::c_char, - Some(cb_progress_nop), - ptr::null_mut(), - ) - }; - - if handle.is_null() { - None - } else { - Some(unsafe { BinaryView::from_raw(handle) }) - } +pub fn load(file_path: impl AsRef<Path>) -> Option<Ref<BinaryView>> { + load_with_progress(file_path, NoProgressCallback) } -pub fn load_with_progress<S, F>( - filename: S, - mut progress: F, -) -> Option<rc::Ref<binaryview::BinaryView>> -where - S: BnStrCompatible, - F: FnMut(usize, usize) -> bool, -{ - let filename = filename.into_bytes_with_nul(); - let options = "\x00"; - - let progress_ctx = &mut progress as *mut F as *mut std::ffi::c_void; - +pub fn load_with_progress<P: ProgressCallback>( + file_path: impl AsRef<Path>, + mut progress: P, +) -> Option<Ref<BinaryView>> { + let file_path = file_path.as_ref().into_bytes_with_nul(); + let options = c""; let handle = unsafe { - binaryninjacore_sys::BNLoadFilename( - filename.as_ref().as_ptr() as *mut _, + BNLoadFilename( + file_path.as_ptr() as *mut _, true, - options.as_ptr() as *mut core::ffi::c_char, - Some(cb_progress_func::<F>), - progress_ctx, + options.as_ptr() as *mut c_char, + Some(P::cb_progress_callback), + &mut progress as *mut P as *mut c_void, ) }; if handle.is_null() { None } else { - Some(unsafe { BinaryView::from_raw(handle) }) + Some(unsafe { BinaryView::ref_from_raw(handle) }) } } @@ -303,61 +154,33 @@ where /// let bv = binaryninja::load_with_options("/bin/cat", true, Some(json!("analysis.linearSweep.autorun": false).to_string())) /// .expect("Couldn't open `/bin/cat`"); /// ``` -pub fn load_with_options<S, O>( - filename: S, +pub fn load_with_options<O>( + file_path: impl AsRef<Path>, update_analysis_and_wait: bool, options: Option<O>, -) -> Option<rc::Ref<binaryview::BinaryView>> +) -> Option<Ref<BinaryView>> where - S: BnStrCompatible, O: IntoJson, { - let filename = filename.into_bytes_with_nul(); - - let options_or_default = if let Some(opt) = options { - opt.get_json_string() - .ok()? - .into_bytes_with_nul() - .as_ref() - .to_vec() - } else { - Metadata::new_of_type(MetadataType::KeyValueDataType) - .get_json_string() - .ok()? - .as_ref() - .to_vec() - }; - - let handle = unsafe { - binaryninjacore_sys::BNLoadFilename( - filename.as_ref().as_ptr() as *mut _, - update_analysis_and_wait, - options_or_default.as_ptr() as *mut core::ffi::c_char, - Some(cb_progress_nop), - core::ptr::null_mut(), - ) - }; - - if handle.is_null() { - None - } else { - Some(unsafe { BinaryView::from_raw(handle) }) - } + load_with_options_and_progress( + file_path, + update_analysis_and_wait, + options, + NoProgressCallback, + ) } -pub fn load_with_options_and_progress<S, O, F>( - filename: S, +pub fn load_with_options_and_progress<O, P>( + file_path: impl AsRef<Path>, update_analysis_and_wait: bool, options: Option<O>, - progress: Option<F>, -) -> Option<rc::Ref<binaryview::BinaryView>> + mut progress: P, +) -> Option<Ref<BinaryView>> where - S: BnStrCompatible, O: IntoJson, - F: FnMut(usize, usize) -> bool, + P: ProgressCallback, { - let filename = filename.into_bytes_with_nul(); - + let file_path = file_path.as_ref().into_bytes_with_nul(); let options_or_default = if let Some(opt) = options { opt.get_json_string() .ok()? @@ -371,26 +194,20 @@ where .as_ref() .to_vec() }; - - let progress_ctx = match progress { - Some(mut x) => &mut x as *mut F as *mut std::ffi::c_void, - None => core::ptr::null_mut() - }; - let handle = unsafe { - binaryninjacore_sys::BNLoadFilename( - filename.as_ref().as_ptr() as *mut _, + BNLoadFilename( + file_path.as_ptr() as *mut _, update_analysis_and_wait, - options_or_default.as_ptr() as *mut core::ffi::c_char, - Some(cb_progress_func::<F>), - progress_ctx, + options_or_default.as_ptr() as *mut c_char, + Some(P::cb_progress_callback), + &mut progress as *mut P as *mut c_void, ) }; if handle.is_null() { None } else { - Some(unsafe { BinaryView::from_raw(handle) }) + Some(unsafe { BinaryView::ref_from_raw(handle) }) } } @@ -398,50 +215,22 @@ pub fn load_view<O>( bv: &BinaryView, update_analysis_and_wait: bool, options: Option<O>, -) -> Option<rc::Ref<binaryview::BinaryView>> +) -> Option<Ref<BinaryView>> where O: IntoJson, { - let options_or_default = if let Some(opt) = options { - opt.get_json_string() - .ok()? - .into_bytes_with_nul() - .as_ref() - .to_vec() - } else { - Metadata::new_of_type(MetadataType::KeyValueDataType) - .get_json_string() - .ok()? - .as_ref() - .to_vec() - }; - - let handle = unsafe { - binaryninjacore_sys::BNLoadBinaryView( - bv.handle as *mut _, - update_analysis_and_wait, - options_or_default.as_ptr() as *mut core::ffi::c_char, - Some(cb_progress_nop), - core::ptr::null_mut(), - ) - }; - - if handle.is_null() { - None - } else { - Some(unsafe { BinaryView::from_raw(handle) }) - } + load_view_with_progress(bv, update_analysis_and_wait, options, NoProgressCallback) } -pub fn load_view_with_progress<O, F>( +pub fn load_view_with_progress<O, P>( bv: &BinaryView, update_analysis_and_wait: bool, options: Option<O>, - progress: Option<F>, -) -> Option<rc::Ref<binaryview::BinaryView>> + mut progress: P, +) -> Option<Ref<BinaryView>> where O: IntoJson, - F: FnMut(usize, usize) -> bool, + P: ProgressCallback, { let options_or_default = if let Some(opt) = options { opt.get_json_string() @@ -456,159 +245,128 @@ where .as_ref() .to_vec() }; - - let progress_ctx = match progress { - Some(mut x) => &mut x as *mut F as *mut std::ffi::c_void, - None => core::ptr::null_mut() - }; - let handle = unsafe { - binaryninjacore_sys::BNLoadBinaryView( + BNLoadBinaryView( bv.handle as *mut _, update_analysis_and_wait, - options_or_default.as_ptr() as *mut core::ffi::c_char, - Some(cb_progress_func::<F>), - progress_ctx, + options_or_default.as_ptr() as *mut c_char, + Some(P::cb_progress_callback), + &mut progress as *mut P as *mut c_void, ) }; if handle.is_null() { None } else { - Some(unsafe { BinaryView::from_raw(handle) }) + Some(unsafe { BinaryView::ref_from_raw(handle) }) } } -pub fn install_directory() -> Result<PathBuf, ()> { - let s: *mut std::os::raw::c_char = unsafe { binaryninjacore_sys::BNGetInstallDirectory() }; - if s.is_null() { - return Err(()); - } - Ok(PathBuf::from( - unsafe { string::BnString::from_raw(s) }.to_string(), - )) +pub fn install_directory() -> PathBuf { + let install_dir_ptr: *mut c_char = unsafe { BNGetInstallDirectory() }; + assert!(!install_dir_ptr.is_null()); + let bn_install_dir = unsafe { BnString::from_raw(install_dir_ptr) }; + PathBuf::from(bn_install_dir.to_string()) } pub fn bundled_plugin_directory() -> Result<PathBuf, ()> { - let s: *mut std::os::raw::c_char = - unsafe { binaryninjacore_sys::BNGetBundledPluginDirectory() }; + let s: *mut c_char = unsafe { BNGetBundledPluginDirectory() }; if s.is_null() { return Err(()); } - Ok(PathBuf::from( - unsafe { string::BnString::from_raw(s) }.to_string(), - )) + Ok(PathBuf::from(unsafe { BnString::from_raw(s) }.to_string())) } -pub fn set_bundled_plugin_directory<S: string::BnStrCompatible>(new_dir: S) { - unsafe { - binaryninjacore_sys::BNSetBundledPluginDirectory( - new_dir.into_bytes_with_nul().as_ref().as_ptr() as *const std::os::raw::c_char, - ) - }; +pub fn set_bundled_plugin_directory(new_dir: impl AsRef<Path>) { + let new_dir = new_dir.as_ref().into_bytes_with_nul(); + unsafe { BNSetBundledPluginDirectory(new_dir.as_ptr() as *const c_char) }; } -pub fn user_directory() -> Result<PathBuf, ()> { - let s: *mut std::os::raw::c_char = unsafe { binaryninjacore_sys::BNGetUserDirectory() }; - if s.is_null() { - return Err(()); - } - Ok(PathBuf::from( - unsafe { string::BnString::from_raw(s) }.to_string(), - )) +pub fn user_directory() -> PathBuf { + let user_dir_ptr: *mut c_char = unsafe { BNGetUserDirectory() }; + assert!(!user_dir_ptr.is_null()); + let bn_user_dir = unsafe { BnString::from_raw(user_dir_ptr) }; + PathBuf::from(bn_user_dir.to_string()) } pub fn user_plugin_directory() -> Result<PathBuf, ()> { - let s: *mut std::os::raw::c_char = unsafe { binaryninjacore_sys::BNGetUserPluginDirectory() }; + let s: *mut c_char = unsafe { BNGetUserPluginDirectory() }; if s.is_null() { return Err(()); } - Ok(PathBuf::from( - unsafe { string::BnString::from_raw(s) }.to_string(), - )) + Ok(PathBuf::from(unsafe { BnString::from_raw(s) }.to_string())) } pub fn repositories_directory() -> Result<PathBuf, ()> { - let s: *mut std::os::raw::c_char = unsafe { binaryninjacore_sys::BNGetRepositoriesDirectory() }; + let s: *mut c_char = unsafe { BNGetRepositoriesDirectory() }; if s.is_null() { return Err(()); } - Ok(PathBuf::from( - unsafe { string::BnString::from_raw(s) }.to_string(), - )) + Ok(PathBuf::from(unsafe { BnString::from_raw(s) }.to_string())) } -pub fn settings_file_name() -> Result<PathBuf, ()> { - let s: *mut std::os::raw::c_char = unsafe { binaryninjacore_sys::BNGetSettingsFileName() }; - if s.is_null() { - return Err(()); - } - Ok(PathBuf::from( - unsafe { string::BnString::from_raw(s) }.to_string(), - )) +pub fn settings_file_name() -> PathBuf { + let settings_file_name_ptr: *mut c_char = unsafe { BNGetSettingsFileName() }; + assert!(!settings_file_name_ptr.is_null()); + let bn_settings_file_name = unsafe { BnString::from_raw(settings_file_name_ptr) }; + PathBuf::from(bn_settings_file_name.to_string()) } +/// Write the installation directory of the currently running core instance to disk. +/// +/// This is used to select the most recent installation for running scripts. pub fn save_last_run() { - unsafe { binaryninjacore_sys::BNSaveLastRun() }; + unsafe { BNSaveLastRun() }; } -pub fn path_relative_to_bundled_plugin_directory<S: string::BnStrCompatible>( - path: S, -) -> Result<PathBuf, ()> { - let s: *mut std::os::raw::c_char = unsafe { - binaryninjacore_sys::BNGetPathRelativeToBundledPluginDirectory( - path.into_bytes_with_nul().as_ref().as_ptr() as *const std::os::raw::c_char, - ) - }; +pub fn path_relative_to_bundled_plugin_directory(path: impl AsRef<Path>) -> Result<PathBuf, ()> { + let path_raw = path.as_ref().into_bytes_with_nul(); + let s: *mut c_char = + unsafe { BNGetPathRelativeToBundledPluginDirectory(path_raw.as_ptr() as *const c_char) }; if s.is_null() { return Err(()); } - Ok(PathBuf::from( - unsafe { string::BnString::from_raw(s) }.to_string(), - )) + Ok(PathBuf::from(unsafe { BnString::from_raw(s) }.to_string())) } -pub fn path_relative_to_user_plugin_directory<S: string::BnStrCompatible>( - path: S, -) -> Result<PathBuf, ()> { - let s: *mut std::os::raw::c_char = unsafe { - binaryninjacore_sys::BNGetPathRelativeToUserPluginDirectory( - path.into_bytes_with_nul().as_ref().as_ptr() as *const std::os::raw::c_char, - ) - }; +pub fn path_relative_to_user_plugin_directory(path: impl AsRef<Path>) -> Result<PathBuf, ()> { + let path_raw = path.as_ref().into_bytes_with_nul(); + let s: *mut c_char = + unsafe { BNGetPathRelativeToUserPluginDirectory(path_raw.as_ptr() as *const c_char) }; if s.is_null() { return Err(()); } - Ok(PathBuf::from( - unsafe { string::BnString::from_raw(s) }.to_string(), - )) + Ok(PathBuf::from(unsafe { BnString::from_raw(s) }.to_string())) } -pub fn path_relative_to_user_directory<S: string::BnStrCompatible>(path: S) -> Result<PathBuf, ()> { - let s: *mut std::os::raw::c_char = unsafe { - binaryninjacore_sys::BNGetPathRelativeToUserDirectory( - path.into_bytes_with_nul().as_ref().as_ptr() as *const std::os::raw::c_char, - ) - }; +pub fn path_relative_to_user_directory(path: impl AsRef<Path>) -> Result<PathBuf, ()> { + let path_raw = path.as_ref().into_bytes_with_nul(); + let s: *mut c_char = + unsafe { BNGetPathRelativeToUserDirectory(path_raw.as_ptr() as *const c_char) }; if s.is_null() { return Err(()); } - Ok(PathBuf::from( - unsafe { string::BnString::from_raw(s) }.to_string(), - )) + Ok(PathBuf::from(unsafe { BnString::from_raw(s) }.to_string())) +} + +/// Returns if the running thread is the "main thread" +/// +/// If there is no registered main thread than this will always return true. +pub fn is_main_thread() -> bool { + unsafe { BNIsMainThread() } } pub fn memory_info() -> HashMap<String, u64> { let mut count = 0; let mut usage = HashMap::new(); unsafe { - let info_ptr = binaryninjacore_sys::BNGetMemoryUsageInfo(&mut count); + let info_ptr = BNGetMemoryUsageInfo(&mut count); let info_list = std::slice::from_raw_parts(info_ptr, count); for info in info_list { let info_name = CStr::from_ptr(info.name).to_str().unwrap().to_string(); usage.insert(info_name, info.value); } - binaryninjacore_sys::BNFreeMemoryUsageInfo(info_ptr, count); + BNFreeMemoryUsageInfo(info_ptr, count); } usage } @@ -619,8 +377,7 @@ pub trait ObjectDestructor: 'static + Sync + Sized { fn destruct_file_metadata(&self, _metadata: &FileMetadata) {} fn destruct_function(&self, _func: &Function) {} - unsafe extern "C" fn cb_destruct_binary_view(ctxt: *mut c_void, view: *mut BNBinaryView) - { + unsafe extern "C" fn cb_destruct_binary_view(ctxt: *mut c_void, view: *mut BNBinaryView) { ffi_wrap!("ObjectDestructor::destruct_view", { let view_type = &*(ctxt as *mut Self); let view = BinaryView { handle: view }; @@ -628,8 +385,7 @@ pub trait ObjectDestructor: 'static + Sync + Sized { }) } - unsafe extern "C" fn cb_destruct_file_metadata(ctxt: *mut c_void, file: *mut BNFileMetadata) - { + unsafe extern "C" fn cb_destruct_file_metadata(ctxt: *mut c_void, file: *mut BNFileMetadata) { ffi_wrap!("ObjectDestructor::destruct_file_metadata", { let view_type = &*(ctxt as *mut Self); let file = FileMetadata::from_raw(file); @@ -637,15 +393,14 @@ pub trait ObjectDestructor: 'static + Sync + Sized { }) } - unsafe extern "C" fn cb_destruct_function(ctxt: *mut c_void, func: *mut BNFunction) - { + unsafe extern "C" fn cb_destruct_function(ctxt: *mut c_void, func: *mut BNFunction) { ffi_wrap!("ObjectDestructor::destruct_function", { let view_type = &*(ctxt as *mut Self); let func = Function { handle: func }; view_type.destruct_function(&func); }) } - + unsafe fn as_callbacks(&'static mut self) -> BNObjectDestructionCallbacks { BNObjectDestructionCallbacks { context: std::mem::transmute(&self), @@ -654,22 +409,22 @@ pub trait ObjectDestructor: 'static + Sync + Sized { destructFunction: Some(Self::cb_destruct_function), } } - + fn register(&'static mut self) { unsafe { BNRegisterObjectDestructionCallbacks(&mut self.as_callbacks()) }; } - + fn unregister(&'static mut self) { unsafe { BNUnregisterObjectDestructionCallbacks(&mut self.as_callbacks()) }; } } -pub fn version() -> string::BnString { - unsafe { string::BnString::from_raw(binaryninjacore_sys::BNGetVersionString()) } +pub fn version() -> BnString { + unsafe { BnString::from_raw(BNGetVersionString()) } } pub fn build_id() -> u32 { - unsafe { binaryninjacore_sys::BNGetBuildId() } + unsafe { BNGetBuildId() } } #[derive(Clone, PartialEq, Eq, Hash)] @@ -677,115 +432,124 @@ pub struct VersionInfo { pub major: u32, pub minor: u32, pub build: u32, - pub channel: string::BnString, + pub channel: String, } -pub fn version_info() -> VersionInfo { - let info_raw = unsafe { binaryninjacore_sys::BNGetVersionInfo() }; - VersionInfo { - major: info_raw.major, - minor: info_raw.minor, - build: info_raw.build, - channel: unsafe { string::BnString::from_raw(info_raw.channel) }, +impl VersionInfo { + pub(crate) fn from_owned_raw(value: BNVersionInfo) -> Self { + Self { + major: value.major, + minor: value.minor, + build: value.build, + channel: unsafe { BnString::from_raw(value.channel) }.to_string(), + } } } -pub fn serial_number() -> string::BnString { - unsafe { string::BnString::from_raw(binaryninjacore_sys::BNGetSerialNumber()) } +pub fn version_info() -> VersionInfo { + let info_raw = unsafe { BNGetVersionInfo() }; + VersionInfo::from_owned_raw(info_raw) +} + +pub fn serial_number() -> BnString { + unsafe { BnString::from_raw(BNGetSerialNumber()) } } pub fn is_license_validated() -> bool { - unsafe { binaryninjacore_sys::BNIsLicenseValidated() } + unsafe { BNIsLicenseValidated() } +} + +pub fn licensed_user_email() -> BnString { + unsafe { BnString::from_raw(BNGetLicensedUserEmail()) } } -pub fn licensed_user_email() -> string::BnString { - unsafe { string::BnString::from_raw(binaryninjacore_sys::BNGetLicensedUserEmail()) } +pub fn license_path() -> PathBuf { + user_directory().join("license.dat") } pub fn license_count() -> i32 { - unsafe { binaryninjacore_sys::BNGetLicenseCount() } + unsafe { BNGetLicenseCount() } } -pub fn set_license<S: string::BnStrCompatible>(license: S) { - let license = license.into_bytes_with_nul(); +/// Set the license that will be used once the core initializes. You can reset the license by passing `None`. +/// +/// If not set the normal license retrieval will occur: +/// 1. Check the BN_LICENSE environment variable +/// 2. Check the Binary Ninja user directory for license.dat +pub fn set_license<S: BnStrCompatible + Default>(license: Option<S>) { + let license = license.unwrap_or_default().into_bytes_with_nul(); let license_slice = license.as_ref(); - unsafe { binaryninjacore_sys::BNSetLicense(license_slice.as_ptr() as *const std::os::raw::c_char) } + unsafe { BNSetLicense(license_slice.as_ptr() as *const c_char) } } -pub fn product() -> string::BnString { - unsafe { string::BnString::from_raw(binaryninjacore_sys::BNGetProduct()) } +pub fn product() -> BnString { + unsafe { BnString::from_raw(BNGetProduct()) } } -pub fn product_type() -> string::BnString { - unsafe { string::BnString::from_raw(binaryninjacore_sys::BNGetProductType()) } +pub fn product_type() -> BnString { + unsafe { BnString::from_raw(BNGetProductType()) } } pub fn license_expiration_time() -> std::time::SystemTime { - let m = std::time::Duration::from_secs(unsafe { - binaryninjacore_sys::BNGetLicenseExpirationTime() - }); + let m = std::time::Duration::from_secs(unsafe { BNGetLicenseExpirationTime() }); std::time::UNIX_EPOCH + m } pub fn is_ui_enabled() -> bool { - unsafe { binaryninjacore_sys::BNIsUIEnabled() } + unsafe { BNIsUIEnabled() } } -pub fn is_database<S: string::BnStrCompatible>(filename: S) -> bool { +pub fn is_database<S: BnStrCompatible>(filename: S) -> bool { let filename = filename.into_bytes_with_nul(); let filename_slice = filename.as_ref(); - unsafe { binaryninjacore_sys::BNIsDatabase(filename_slice.as_ptr() as *const std::os::raw::c_char) } + unsafe { BNIsDatabase(filename_slice.as_ptr() as *const c_char) } } pub fn plugin_abi_version() -> u32 { - binaryninjacore_sys::BN_CURRENT_CORE_ABI_VERSION + BN_CURRENT_CORE_ABI_VERSION } pub fn plugin_abi_minimum_version() -> u32 { - binaryninjacore_sys::BN_MINIMUM_CORE_ABI_VERSION + BN_MINIMUM_CORE_ABI_VERSION } pub fn core_abi_version() -> u32 { - unsafe { binaryninjacore_sys::BNGetCurrentCoreABIVersion() } + unsafe { BNGetCurrentCoreABIVersion() } } pub fn core_abi_minimum_version() -> u32 { - unsafe { binaryninjacore_sys::BNGetMinimumCoreABIVersion() } + unsafe { BNGetMinimumCoreABIVersion() } } pub fn plugin_ui_abi_version() -> u32 { - binaryninjacore_sys::BN_CURRENT_UI_ABI_VERSION + BN_CURRENT_UI_ABI_VERSION } pub fn plugin_ui_abi_minimum_version() -> u32 { - binaryninjacore_sys::BN_MINIMUM_UI_ABI_VERSION + BN_MINIMUM_UI_ABI_VERSION } -pub fn add_required_plugin_dependency<S: string::BnStrCompatible>(name: S) { +pub fn add_required_plugin_dependency<S: BnStrCompatible>(name: S) { unsafe { - binaryninjacore_sys::BNAddRequiredPluginDependency( - name.into_bytes_with_nul().as_ref().as_ptr() as *const std::os::raw::c_char, - ) + BNAddRequiredPluginDependency(name.into_bytes_with_nul().as_ref().as_ptr() as *const c_char) }; } -pub fn add_optional_plugin_dependency<S: string::BnStrCompatible>(name: S) { +pub fn add_optional_plugin_dependency<S: BnStrCompatible>(name: S) { unsafe { - binaryninjacore_sys::BNAddOptionalPluginDependency( - name.into_bytes_with_nul().as_ref().as_ptr() as *const std::os::raw::c_char, - ) + BNAddOptionalPluginDependency(name.into_bytes_with_nul().as_ref().as_ptr() as *const c_char) }; } // Provide ABI version automatically so that the core can verify binary compatibility -#[cfg(not(feature = "noexports"))] +#[cfg(not(feature = "no_exports"))] #[no_mangle] #[allow(non_snake_case)] pub extern "C" fn CorePluginABIVersion() -> u32 { plugin_abi_version() } -#[cfg(not(feature = "noexports"))] +#[cfg(not(feature = "no_exports"))] #[no_mangle] pub extern "C" fn UIPluginABIVersion() -> u32 { plugin_ui_abi_version() |
