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/medium_level_il/function.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/medium_level_il/function.rs')
| -rw-r--r-- | rust/src/medium_level_il/function.rs | 718 |
1 files changed, 718 insertions, 0 deletions
diff --git a/rust/src/medium_level_il/function.rs b/rust/src/medium_level_il/function.rs new file mode 100644 index 00000000..a9802005 --- /dev/null +++ b/rust/src/medium_level_il/function.rs @@ -0,0 +1,718 @@ +use binaryninjacore_sys::*; +use std::ffi::c_char; +use std::fmt::{Debug, Formatter}; +use std::hash::{Hash, Hasher}; + +use super::{MediumLevelILBlock, MediumLevelILInstruction, MediumLevelInstructionIndex}; +use crate::architecture::CoreArchitecture; +use crate::basic_block::BasicBlock; +use crate::confidence::Conf; +use crate::disassembly::DisassemblySettings; +use crate::flowgraph::FlowGraph; +use crate::function::{Function, Location}; +use crate::rc::{Array, CoreArrayProvider, CoreArrayProviderInner, Ref, RefCountable}; +use crate::string::BnStrCompatible; +use crate::types::Type; +use crate::variable::{PossibleValueSet, RegisterValue, SSAVariable, UserVariableValue, Variable}; + +// TODO: Does this belong here? +pub use binaryninjacore_sys::BNFunctionGraphType as FunctionGraphType; + +pub struct MediumLevelILFunction { + pub(crate) handle: *mut BNMediumLevelILFunction, +} + +impl MediumLevelILFunction { + pub(crate) unsafe fn from_raw(handle: *mut BNMediumLevelILFunction) -> Self { + debug_assert!(!handle.is_null()); + Self { handle } + } + + pub(crate) unsafe fn ref_from_raw(handle: *mut BNMediumLevelILFunction) -> Ref<Self> { + debug_assert!(!handle.is_null()); + Ref::new(Self::from_raw(handle)) + } + + pub fn instruction_at<L: Into<Location>>(&self, loc: L) -> Option<MediumLevelILInstruction> { + Some(MediumLevelILInstruction::new( + self.to_owned(), + self.instruction_index_at(loc)?, + )) + } + + pub fn instruction_index_at<L: Into<Location>>( + &self, + loc: L, + ) -> Option<MediumLevelInstructionIndex> { + let loc: Location = loc.into(); + let arch = loc + .arch + .map(|a| a.handle) + .unwrap_or_else(std::ptr::null_mut); + let instr_idx = unsafe { BNMediumLevelILGetInstructionStart(self.handle, arch, loc.addr) }; + // `instr_idx` will equal self.instruction_count() if the instruction is not valid. + if instr_idx >= self.instruction_count() { + None + } else { + Some(MediumLevelInstructionIndex(instr_idx)) + } + } + + pub fn instruction_from_index( + &self, + index: MediumLevelInstructionIndex, + ) -> Option<MediumLevelILInstruction> { + if index.0 >= self.instruction_count() { + None + } else { + Some(MediumLevelILInstruction::new(self.to_owned(), index)) + } + } + + pub fn instruction_from_expr_index( + &self, + expr_index: MediumLevelInstructionIndex, + ) -> Option<MediumLevelILInstruction> { + if expr_index.0 >= self.expression_count() { + None + } else { + Some(MediumLevelILInstruction::new_expr( + self.to_owned(), + expr_index, + )) + } + } + + pub fn instruction_count(&self) -> usize { + unsafe { BNGetMediumLevelILInstructionCount(self.handle) } + } + + pub fn expression_count(&self) -> usize { + unsafe { BNGetMediumLevelILExprCount(self.handle) } + } + + pub fn ssa_form(&self) -> MediumLevelILFunction { + let ssa = unsafe { BNGetMediumLevelILSSAForm(self.handle) }; + assert!(!ssa.is_null()); + MediumLevelILFunction { handle: ssa } + } + + pub fn function(&self) -> Ref<Function> { + unsafe { + let func = BNGetMediumLevelILOwnerFunction(self.handle); + Function::ref_from_raw(func) + } + } + + pub fn basic_blocks(&self) -> Array<BasicBlock<MediumLevelILBlock>> { + let mut count = 0; + let blocks = unsafe { BNGetMediumLevelILBasicBlockList(self.handle, &mut count) }; + let context = MediumLevelILBlock { + function: self.to_owned(), + }; + unsafe { Array::new(blocks, count, context) } + } + + pub fn var_definitions(&self, var: &Variable) -> Array<MediumLevelILInstruction> { + let mut count = 0; + let raw_var = BNVariable::from(var); + let raw_instr_idxs = + unsafe { BNGetMediumLevelILVariableDefinitions(self.handle, &raw_var, &mut count) }; + assert!(!raw_instr_idxs.is_null()); + unsafe { Array::new(raw_instr_idxs, count, self.to_owned()) } + } + + pub fn create_user_stack_var<'a, S: BnStrCompatible, C: Into<Conf<&'a Type>>>( + self, + offset: i64, + var_type: C, + name: S, + ) { + let mut owned_raw_var_ty = Conf::<&Type>::into_raw(var_type.into()); + let name = name.into_bytes_with_nul(); + unsafe { + BNCreateUserStackVariable( + self.function().handle, + offset, + &mut owned_raw_var_ty, + name.as_ref().as_ptr() as *const c_char, + ) + } + } + + pub fn delete_user_stack_var(self, offset: i64) { + unsafe { BNDeleteUserStackVariable(self.function().handle, offset) } + } + + pub fn create_user_var<'a, S: BnStrCompatible, C: Into<Conf<&'a Type>>>( + &self, + var: &Variable, + var_type: C, + name: S, + ignore_disjoint_uses: bool, + ) { + let raw_var = BNVariable::from(var); + let mut owned_raw_var_ty = Conf::<&Type>::into_raw(var_type.into()); + let name = name.into_bytes_with_nul(); + unsafe { + BNCreateUserVariable( + self.function().handle, + &raw_var, + &mut owned_raw_var_ty, + name.as_ref().as_ptr() as *const _, + ignore_disjoint_uses, + ) + } + } + + pub fn delete_user_var(&self, var: &Variable) { + let raw_var = BNVariable::from(var); + unsafe { BNDeleteUserVariable(self.function().handle, &raw_var) } + } + + pub fn is_var_user_defined(&self, var: &Variable) -> bool { + let raw_var = BNVariable::from(var); + unsafe { BNIsVariableUserDefined(self.function().handle, &raw_var) } + } + + /// Allows the user to specify a PossibleValueSet value for an MLIL + /// variable at its definition site. + /// + /// .. warning:: Setting the variable value, triggers a reanalysis of the + /// function and allows the dataflow to compute and propagate values which + /// depend on the current variable. This implies that branch conditions + /// whose values can be determined statically will be computed, leading to + /// potential branch elimination at the HLIL layer. + /// + /// * `var` - Variable for which the value is to be set + /// * `addr` - Address of the definition site of the variable + /// * `value` - Informed value of the variable + /// + /// # Example + /// ```no_run + /// # use binaryninja::medium_level_il::MediumLevelILFunction; + /// # use binaryninja::variable::PossibleValueSet; + /// # let mlil_fun: MediumLevelILFunction = todo!(); + /// let user_var_val = mlil_fun.user_var_values().iter().next().unwrap(); + /// let def_address = user_var_val.def_site.addr; + /// let var_value = PossibleValueSet::ConstantValue { value: 5 }; + /// mlil_fun + /// .set_user_var_value(&user_var_val.variable, def_address, var_value) + /// .unwrap(); + /// ``` + pub fn set_user_var_value( + &self, + var: &Variable, + addr: u64, + value: PossibleValueSet, + ) -> Result<(), ()> { + let Some(_def_site) = self + .var_definitions(var) + .iter() + .find(|def| def.address == addr) + else { + // Error "No definition for Variable found at given address" + return Err(()); + }; + let function = self.function(); + let def_site = BNArchitectureAndAddress { + arch: function.arch().handle, + address: addr, + }; + let raw_var = BNVariable::from(var); + let raw_value = PossibleValueSet::into_raw(value); + unsafe { BNSetUserVariableValue(function.handle, &raw_var, &def_site, &raw_value) } + PossibleValueSet::free_owned_raw(raw_value); + Ok(()) + } + + /// Clears a previously defined user variable value. + /// + /// * `var` - Variable for which the value was informed + /// * `def_addr` - Address of the definition site of the variable + pub fn clear_user_var_value(&self, var: &Variable, addr: u64) -> Result<(), ()> { + let Some(_var_def) = self + .var_definitions(var) + .iter() + .find(|site| site.address == addr) + else { + //error "Could not get definition for Variable" + return Err(()); + }; + + let function = self.function(); + let raw_var = BNVariable::from(var); + let def_site = BNArchitectureAndAddress { + arch: function.arch().handle, + address: addr, + }; + + unsafe { BNClearUserVariableValue(function.handle, &raw_var, &def_site) }; + Ok(()) + } + + /// Returns a map of current defined user variable values. + /// Returns a Map of user current defined user variable values and their definition sites. + pub fn user_var_values(&self) -> Array<UserVariableValue> { + let mut count = 0; + let function = self.function(); + let var_values = unsafe { BNGetAllUserVariableValues(function.handle, &mut count) }; + assert!(!var_values.is_null()); + unsafe { Array::new(var_values, count, ()) } + } + + /// Clear all user defined variable values. + pub fn clear_user_var_values(&self) -> Result<(), ()> { + for user_var_val in &self.user_var_values() { + self.clear_user_var_value(&user_var_val.variable, user_var_val.def_site.addr)?; + } + Ok(()) + } + + pub fn create_auto_stack_var<'a, T: Into<Conf<&'a Type>>, S: BnStrCompatible>( + &self, + offset: i64, + var_type: T, + name: S, + ) { + let mut owned_raw_var_ty = Conf::<&Type>::into_raw(var_type.into()); + let name = name.into_bytes_with_nul(); + let name_c_str = name.as_ref(); + unsafe { + BNCreateAutoStackVariable( + self.function().handle, + offset, + &mut owned_raw_var_ty, + name_c_str.as_ptr() as *const c_char, + ) + } + } + + pub fn delete_auto_stack_var(&self, offset: i64) { + unsafe { BNDeleteAutoStackVariable(self.function().handle, offset) } + } + + pub fn create_auto_var<'a, S: BnStrCompatible, C: Into<Conf<&'a Type>>>( + &self, + var: &Variable, + var_type: C, + name: S, + ignore_disjoint_uses: bool, + ) { + let raw_var = BNVariable::from(var); + let mut owned_raw_var_ty = Conf::<&Type>::into_raw(var_type.into()); + let name = name.into_bytes_with_nul(); + let name_c_str = name.as_ref(); + unsafe { + BNCreateAutoVariable( + self.function().handle, + &raw_var, + &mut owned_raw_var_ty, + name_c_str.as_ptr() as *const c_char, + ignore_disjoint_uses, + ) + } + } + + /// Returns a list of ILReferenceSource objects (IL xrefs or cross-references) + /// that reference the given variable. The variable is a local variable that can be either on the stack, + /// in a register, or in a flag. + /// This function is related to get_hlil_var_refs(), which returns variable references collected + /// from HLIL. The two can be different in several cases, e.g., multiple variables in MLIL can be merged + /// into a single variable in HLIL. + /// + /// * `var` - Variable for which to query the xref + /// + /// # Example + /// ```no_run + /// # use binaryninja::medium_level_il::MediumLevelILFunction; + /// # use binaryninja::variable::Variable; + /// # let mlil_fun: MediumLevelILFunction = todo!(); + /// # let mlil_var: Variable = todo!(); + /// let instr_idx = mlil_fun.var_refs(&mlil_var).get(0).expr_idx; + /// ``` + pub fn var_refs(&self, var: &Variable) -> Array<ILReferenceSource> { + let mut count = 0; + let mut raw_var = BNVariable::from(var); + let refs = unsafe { + BNGetMediumLevelILVariableReferences(self.function().handle, &mut raw_var, &mut count) + }; + assert!(!refs.is_null()); + unsafe { Array::new(refs, count, ()) } + } + + /// Retrieves variable references from a specified location or range within a medium-level IL function. + /// + /// Passing in a `length` will query a range for variable references, instead of just the address + /// specified in `location`. + pub fn var_refs_from( + &self, + location: impl Into<Location>, + length: Option<u64>, + ) -> Array<VariableReferenceSource> { + let location = location.into(); + let raw_arch = location + .arch + .map(|a| a.handle) + .unwrap_or(std::ptr::null_mut()); + let function = self.function(); + let mut count = 0; + + let refs = if let Some(length) = length { + unsafe { + BNGetMediumLevelILVariableReferencesInRange( + function.handle, + raw_arch, + location.addr, + length, + &mut count, + ) + } + } else { + unsafe { + BNGetMediumLevelILVariableReferencesFrom( + function.handle, + raw_arch, + location.addr, + &mut count, + ) + } + }; + assert!(!refs.is_null()); + unsafe { Array::new(refs, count, ()) } + } + + // TODO: Rename to `current_location`? + /// Current IL Address + pub fn current_address(&self) -> Location { + let addr = unsafe { BNMediumLevelILGetCurrentAddress(self.handle) }; + Location::from(addr) + } + + // TODO: Rename to `set_current_location`? + /// Set the current IL Address + pub fn set_current_address(&self, location: impl Into<Location>) { + let location = location.into(); + let arch = location + .arch + .map(|a| a.handle) + .unwrap_or(std::ptr::null_mut()); + unsafe { BNMediumLevelILSetCurrentAddress(self.handle, arch, location.addr) } + } + + /// Returns the [`BasicBlock`] at the given instruction `index`. + /// + /// You can also retrieve this using [`MediumLevelILInstruction::basic_block`]. + pub fn basic_block_containing_index( + &self, + index: MediumLevelInstructionIndex, + ) -> Option<Ref<BasicBlock<MediumLevelILBlock>>> { + let context = MediumLevelILBlock { + function: self.to_owned(), + }; + // TODO: If we can guarantee self.index is valid we can omit the wrapped Option. + let basic_block_ptr = + unsafe { BNGetMediumLevelILBasicBlockForInstruction(self.handle, index.0) }; + match basic_block_ptr.is_null() { + false => Some(unsafe { BasicBlock::ref_from_raw(basic_block_ptr, context) }), + true => None, + } + } + + /// Ends the function and computes the list of basic blocks. + /// + /// NOTE: This should be called after updating MLIL. + pub fn finalize(&self) { + unsafe { BNFinalizeMediumLevelILFunction(self.handle) } + } + + /// Generate SSA form given the current MLIL. + /// + /// NOTE: This should be called after updating MLIL. + /// + /// * `analyze_conditionals` - whether to analyze conditionals + /// * `handle_aliases` - whether to handle aliases + /// * `non_aliased_vars` - optional list of variables known to be not aliased + /// * `aliased_vars` - optional list of variables known to be aliased + pub fn generate_ssa_form( + &self, + analyze_conditionals: bool, + handle_aliases: bool, + non_aliased_vars: impl IntoIterator<Item = Variable>, + aliased_vars: impl IntoIterator<Item = Variable>, + ) { + let raw_non_aliased_vars: Vec<BNVariable> = + non_aliased_vars.into_iter().map(Into::into).collect(); + let raw_aliased_vars: Vec<BNVariable> = aliased_vars.into_iter().map(Into::into).collect(); + unsafe { + BNGenerateMediumLevelILSSAForm( + self.handle, + analyze_conditionals, + handle_aliases, + raw_non_aliased_vars.as_ptr() as *mut _, + raw_non_aliased_vars.len(), + raw_aliased_vars.as_ptr() as *mut _, + raw_aliased_vars.len(), + ) + } + } + + /// Gets the instruction that contains the given SSA variable's definition. + /// + /// Since SSA variables can only be defined once, this will return the single instruction where that occurs. + /// For SSA variable version 0s, which don't have definitions, this will return `None` instead. + pub fn ssa_variable_definition( + &self, + ssa_variable: &SSAVariable, + ) -> Option<MediumLevelILInstruction> { + let raw_var = BNVariable::from(ssa_variable.variable); + let result = unsafe { + BNGetMediumLevelILSSAVarDefinition(self.handle, &raw_var, ssa_variable.version) + }; + // TODO: Does this return the expression or instruction index? Also we dont diff and this prob doesnt work. + self.instruction_from_index(MediumLevelInstructionIndex(result)) + } + + pub fn ssa_memory_definition(&self, version: usize) -> Option<MediumLevelILInstruction> { + let result = unsafe { BNGetMediumLevelILSSAMemoryDefinition(self.handle, version) }; + // TODO: Does this return the expression or instruction index? Also we dont diff and this prob doesnt work. + self.instruction_from_index(MediumLevelInstructionIndex(result)) + } + + /// Gets all the instructions that use the given SSA variable. + pub fn ssa_variable_uses(&self, ssa_variable: &SSAVariable) -> Array<MediumLevelILInstruction> { + let mut count = 0; + let raw_var = BNVariable::from(ssa_variable.variable); + let uses = unsafe { + BNGetMediumLevelILSSAVarUses(self.handle, &raw_var, ssa_variable.version, &mut count) + }; + assert!(!uses.is_null()); + unsafe { Array::new(uses, count, self.to_owned()) } + } + + pub fn ssa_memory_uses(&self, version: usize) -> Array<MediumLevelILInstruction> { + let mut count = 0; + let uses = unsafe { BNGetMediumLevelILSSAMemoryUses(self.handle, version, &mut count) }; + assert!(!uses.is_null()); + unsafe { Array::new(uses, count, self.to_owned()) } + } + + /// Determines if `variable` is live at any point in the function + pub fn is_ssa_variable_live(&self, ssa_variable: &SSAVariable) -> bool { + let raw_var = BNVariable::from(ssa_variable.variable); + unsafe { BNIsMediumLevelILSSAVarLive(self.handle, &raw_var, ssa_variable.version) } + } + + pub fn variable_definitions(&self, variable: &Variable) -> Array<MediumLevelILInstruction> { + let mut count = 0; + let raw_var = BNVariable::from(variable); + let defs = + unsafe { BNGetMediumLevelILVariableDefinitions(self.handle, &raw_var, &mut count) }; + unsafe { Array::new(defs, count, self.to_owned()) } + } + + pub fn variable_uses(&self, variable: &Variable) -> Array<MediumLevelILInstruction> { + let mut count = 0; + let raw_var = BNVariable::from(variable); + let uses = unsafe { BNGetMediumLevelILVariableUses(self.handle, &raw_var, &mut count) }; + unsafe { Array::new(uses, count, self.to_owned()) } + } + + /// Computes the list of instructions for which `var` is live. + /// If `include_last_use` is false, the last use of the variable will not be included in the + /// list (this allows for easier computation of overlaps in liveness between two variables). + /// If the variable is never used, this function will return an empty list. + /// + /// `var` - the variable to query + /// `include_last_use` - whether to include the last use of the variable in the list of instructions + pub fn live_instruction_for_variable( + &self, + variable: &Variable, + include_last_user: bool, + ) -> Array<MediumLevelILInstruction> { + let mut count = 0; + let raw_var = BNVariable::from(variable); + let uses = unsafe { + BNGetMediumLevelILLiveInstructionsForVariable( + self.handle, + &raw_var, + include_last_user, + &mut count, + ) + }; + unsafe { Array::new(uses, count, self.to_owned()) } + } + + pub fn ssa_variable_value(&self, ssa_variable: &SSAVariable) -> RegisterValue { + let raw_var = BNVariable::from(ssa_variable.variable); + unsafe { BNGetMediumLevelILSSAVarValue(self.handle, &raw_var, ssa_variable.version) }.into() + } + + pub fn create_graph(&self, settings: Option<DisassemblySettings>) -> FlowGraph { + let settings = settings.map(|x| x.handle).unwrap_or(std::ptr::null_mut()); + let graph = unsafe { BNCreateMediumLevelILFunctionGraph(self.handle, settings) }; + unsafe { FlowGraph::from_raw(graph) } + } + + /// This gets just the MLIL variables - you may be interested in the union + /// of [`MediumLevelILFunction::aliased_variables`] and [`Function::parameter_variables`] for + /// all the variables used in the function + pub fn variables(&self) -> Array<Variable> { + let mut count = 0; + let uses = unsafe { BNGetMediumLevelILVariables(self.handle, &mut count) }; + unsafe { Array::new(uses, count, ()) } + } + + /// This returns a list of Variables that are taken reference to and used + /// elsewhere. You may also wish to consider [`MediumLevelILFunction::variables`] + /// and [`Function::parameter_variables`] + pub fn aliased_variables(&self) -> Array<Variable> { + let mut count = 0; + let uses = unsafe { BNGetMediumLevelILAliasedVariables(self.handle, &mut count) }; + unsafe { Array::new(uses, count, ()) } + } + + /// This gets the MLIL SSA variables for a given [`Variable`]. + pub fn ssa_variables(&self, variable: &Variable) -> Array<SSAVariable> { + let mut count = 0; + let raw_variable = BNVariable::from(variable); + let versions = unsafe { + BNGetMediumLevelILVariableSSAVersions(self.handle, &raw_variable, &mut count) + }; + unsafe { Array::new(versions, count, *variable) } + } +} + +impl ToOwned for MediumLevelILFunction { + type Owned = Ref<Self>; + + fn to_owned(&self) -> Self::Owned { + unsafe { RefCountable::inc_ref(self) } + } +} + +unsafe impl RefCountable for MediumLevelILFunction { + unsafe fn inc_ref(handle: &Self) -> Ref<Self> { + Ref::new(Self { + handle: BNNewMediumLevelILFunctionReference(handle.handle), + }) + } + + unsafe fn dec_ref(handle: &Self) { + BNFreeMediumLevelILFunction(handle.handle); + } +} + +impl Debug for MediumLevelILFunction { + fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { + f.debug_struct("MediumLevelILFunction") + .field("arch", &self.function().arch()) + .field("instruction_count", &self.instruction_count()) + .finish() + } +} + +unsafe impl Send for MediumLevelILFunction {} +unsafe impl Sync for MediumLevelILFunction {} + +impl Eq for MediumLevelILFunction {} +impl PartialEq for MediumLevelILFunction { + fn eq(&self, rhs: &Self) -> bool { + self.function().eq(&rhs.function()) + } +} + +impl Hash for MediumLevelILFunction { + fn hash<H: Hasher>(&self, state: &mut H) { + self.function().hash(state) + } +} + +pub struct ILReferenceSource { + pub function: Ref<Function>, + pub arch: CoreArchitecture, + pub addr: u64, + pub graph_type: FunctionGraphType, + pub expr_idx: usize, +} + +impl From<BNILReferenceSource> for ILReferenceSource { + fn from(value: BNILReferenceSource) -> Self { + Self { + function: unsafe { Function::ref_from_raw(value.func) }, + arch: unsafe { CoreArchitecture::from_raw(value.arch) }, + addr: value.addr, + graph_type: value.type_, + expr_idx: value.exprId, + } + } +} + +impl From<&BNILReferenceSource> for ILReferenceSource { + fn from(value: &BNILReferenceSource) -> Self { + Self { + function: unsafe { Function::from_raw(value.func).to_owned() }, + arch: unsafe { CoreArchitecture::from_raw(value.arch) }, + addr: value.addr, + graph_type: value.type_, + expr_idx: value.exprId, + } + } +} + +impl CoreArrayProvider for ILReferenceSource { + type Raw = BNILReferenceSource; + type Context = (); + type Wrapped<'a> = Self; +} + +unsafe impl CoreArrayProviderInner for ILReferenceSource { + unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { + BNFreeILReferences(raw, count) + } + + unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { + raw.into() + } +} + +pub struct VariableReferenceSource { + pub variable: Variable, + pub source: ILReferenceSource, +} + +impl From<BNVariableReferenceSource> for VariableReferenceSource { + fn from(value: BNVariableReferenceSource) -> Self { + Self { + variable: Variable::from(value.var), + source: value.source.into(), + } + } +} + +impl From<&BNVariableReferenceSource> for VariableReferenceSource { + fn from(value: &BNVariableReferenceSource) -> Self { + Self { + variable: Variable::from(value.var), + // TODO: We really need to document this better, or have some other facility for this. + // NOTE: We take this as a ref to increment the function ref. + source: ILReferenceSource::from(&value.source), + } + } +} + +impl CoreArrayProvider for VariableReferenceSource { + type Raw = BNVariableReferenceSource; + type Context = (); + type Wrapped<'a> = Self; +} + +unsafe impl CoreArrayProviderInner for VariableReferenceSource { + unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) { + BNFreeVariableReferenceSourceList(raw, count) + } + + unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> { + raw.into() + } +} |
