binaryview module¶
Class |
Description |
|---|---|
The purpose of this class is to generate IL functions IL function in the background |
|
The |
|
|
|
|
|
|
|
The |
|
The |
|
|
|
CoreDataVariable(_address: int, _type: ‘_types.Type’, _auto_discovered: bool) |
|
CoreDataVariable(_address: int, _type: ‘_types.Type’, _auto_discovered: bool) |
|
The MemoryMap object is used to describe a system level MemoryMap for which a BinaryView is… |
|
The |
|
Built-in mutable sequence. |
|
The |
|
Built-in mutable sequence. |
|
SymbolMapping object is used to improve performance of the bv.symbols API. |
|
The |
|
The |
|
TypeMapping object is used to improve performance of the bv.types API. |
|
TypedDataAccessor(type: ‘_types.Type’, address: int, view: ‘BinaryView’, endian: binaryninja.enum… |
- class ActiveAnalysisInfo[source]
Bases:
objectActiveAnalysisInfo(func: ‘_function.Function’, analysis_time: int, update_count: int, submit_count: int)
- analysis_time: int
- func: Function
- submit_count: int
- update_count: int
- class AdvancedILFunctionList[source]
Bases:
objectThe purpose of this class is to generate IL functions IL function in the background improving the performance of iterating MediumLevelIL and HighLevelILFunctions.
Using this class or the associated helper methods BinaryView.mlil_functions / BinaryView.hlil_functions can improve the performance of ILFunction iteration significantly
The prefetch_limit property is configurable and should be modified based upon your machines hardware and RAM limitations.
Warning
Setting the prefetch_limit excessively high can result in high memory utilization.
- Example:
>>> import timeit >>> len(bv.functions) 4817 >>> # Calculate the average time to generate hlil for all functions withing 'bv': >>> timeit.timeit(lambda:[f.hlil for f in bv.functions], number=1) 21.761621682000168 >>> t1 = _ >>> # Now try again with the advanced analysis iterator >>> timeit.timeit(lambda:[f for f in bv.hlil_functions(128)], number=1) 6.3147709989998475 >>> t1/_ 3.4461458199270947 >>> # This particular binary can iterate hlil functions 3.4x faster >>> # If you don't need IL then its still much faster to just use `bv.functions` >>> timeit.timeit(lambda:[f for f in bv.functions], number=1) 0.02230275600004461
- __init__(view: BinaryView, preload_limit: int = 19, functions: Iterable | None = None)[source]
- Parameters:
view (BinaryView) –
preload_limit (int) –
functions (Iterable | None) –
- class AnalysisCompletionEvent[source]
Bases:
objectThe
AnalysisCompletionEventobject provides an asynchronous mechanism for receiving callbacks when analysis is complete. The callback runs once. A completion event must be added for each new analysis in order to be notified of each analysis completion. The AnalysisCompletionEvent class takes responsibility for keeping track of the object’s lifetime.- Example:
>>> def on_complete(self): ... print("Analysis Complete", self._view) ... >>> evt = AnalysisCompletionEvent(bv, on_complete) >>>
- __init__(view: BinaryView, callback: Callable[[AnalysisCompletionEvent], None] | Callable[[], None])[source]
- Parameters:
view (BinaryView) –
callback (Callable[[AnalysisCompletionEvent], None] | Callable[[], None]) –
- cancel() None[source]
The
cancelmethod will cancel analysis for anAnalysisCompletionEvent.Warning
This method should only be used when the system is being shut down and no further analysis should be done afterward.
- Return type:
None
- property view: BinaryView
- class AnalysisInfo[source]
Bases:
objectAnalysisInfo(state: binaryninja.enums.AnalysisState, analysis_time: int, active_info: List[binaryninja.binaryview.ActiveAnalysisInfo])
- __init__(state: AnalysisState, analysis_time: int, active_info: List[ActiveAnalysisInfo]) None
- Parameters:
state (AnalysisState) –
analysis_time (int) –
active_info (List[ActiveAnalysisInfo]) –
- Return type:
None
- active_info: List[ActiveAnalysisInfo]
- analysis_time: int
- state: AnalysisState
- class AnalysisProgress[source]
Bases:
objectAnalysisProgress(state: binaryninja.enums.AnalysisState, count: int, total: int)
- __init__(state: AnalysisState, count: int, total: int) None
- Parameters:
state (AnalysisState) –
count (int) –
total (int) –
- Return type:
None
- count: int
- state: AnalysisState
- total: int
- class BinaryDataNotification[source]
Bases:
objectclass BinaryDataNotificationprovides an interface for receiving event notifications. Usage requires inheriting from this interface, overriding the relevant event handlers, and registering the BinaryDataNotification instance with a BinaryView using the register_notification method.By default, a BinaryDataNotification instance receives notifications for all available notification types. It is recommended for users of this interface to initialize the BinaryDataNotification base class with specific callbacks of interest by passing the appropriate NotificationType flags into the __init__ constructor.
Handlers provided by the user should aim to limit the amount of processing within the callback. The callback context holds a global lock, preventing other threads from making progress during the callback phase. While most of the API can be used safely during this time, care must be taken when issuing a call that can block, as waiting for a thread requiring the global lock can result in deadlock.
The NotificationBarrier is a special NotificationType that is disabled by default. To enable it, the NotificationBarrier flag must be passed to __init__. This notification is designed to facilitate efficient batch processing of other notification types. The idea is to collect other notifications of interest into a cache, which can be very efficient as it doesn’t require additional locks. After some time, the core generates a NotificationBarrier event, providing a safe context to move the cache for processing by a different thread.
To control the time of the next NotificationBarrier event, return the desired number of milliseconds until the next event from the NotificationBarrier callback. Returning zero quiesces future NotificationBarrier events. If the NotificationBarrier is quiesced, the reception of a new callback of interest automatically generates a new NotificationBarrier call after that notification is delivered. This mechanism effectively allows throttling and quiescing when necessary.
Note
Note that the core generates a NotificationBarrier as part of the BinaryDataNotification registration process. Registering the same BinaryDataNotification instance again results in a gratuitous NotificationBarrier event, which can be useful in situations requiring a safe context for processing due to some other asynchronous event (e.g., user interaction).
- Example:
>>> class NotifyTest(binaryninja.BinaryDataNotification): ... def __init__(self): ... super(NotifyTest, self).__init__(binaryninja.NotificationType.NotificationBarrier | binaryninja.NotificationType.FunctionLifetime | binaryninja.NotificationType.FunctionUpdated) ... self.received_event = False ... def notification_barrier(self, view: 'BinaryView') -> int: ... has_events = self.received_event ... self.received_event = False ... log_info("notification_barrier") ... if has_events: ... return 250 ... else: ... return 0 ... def function_added(self, view: 'BinaryView', func: '_function.Function') -> None: ... self.received_event = True ... log_info("function_added") ... def function_removed(self, view: 'BinaryView', func: '_function.Function') -> None: ... self.received_event = True ... log_info("function_removed") ... def function_updated(self, view: 'BinaryView', func: '_function.Function') -> None: ... self.received_event = True ... log_info("function_updated") ... >>> >>> bv.register_notification(NotifyTest()) >>>
- __init__(notifications: NotificationType | None = None)[source]
- Parameters:
notifications (NotificationType | None) –
- component_added(view: BinaryView, _component: Component) None[source]
- Parameters:
view (BinaryView) –
_component (Component) –
- Return type:
None
- component_data_var_added(view: BinaryView, _component: Component, var: DataVariable)[source]
- Parameters:
view (BinaryView) –
_component (Component) –
var (DataVariable) –
- component_data_var_removed(view: BinaryView, _component: Component, var: DataVariable)[source]
- Parameters:
view (BinaryView) –
_component (Component) –
var (DataVariable) –
- component_function_added(view: BinaryView, _component: Component, func: Function)[source]
- Parameters:
view (BinaryView) –
_component (Component) –
func (Function) –
- component_function_removed(view: BinaryView, _component: Component, func: Function)[source]
- Parameters:
view (BinaryView) –
_component (Component) –
func (Function) –
- component_moved(view: BinaryView, formerParent: Component, newParent: Component, _component: Component) None[source]
- Parameters:
view (BinaryView) –
formerParent (Component) –
newParent (Component) –
_component (Component) –
- Return type:
None
- component_name_updated(view: BinaryView, previous_name: str, _component: Component) None[source]
- Parameters:
view (BinaryView) –
previous_name (str) –
_component (Component) –
- Return type:
None
- component_removed(view: BinaryView, formerParent: Component, _component: Component) None[source]
- Parameters:
view (BinaryView) –
formerParent (Component) –
_component (Component) –
- Return type:
None
- data_inserted(view: BinaryView, offset: int, length: int) None[source]
- Parameters:
view (BinaryView) –
offset (int) –
length (int) –
- Return type:
None
- data_metadata_updated(view: BinaryView, offset: int) None[source]
- Parameters:
view (BinaryView) –
offset (int) –
- Return type:
None
- data_removed(view: BinaryView, offset: int, length: int) None[source]
- Parameters:
view (BinaryView) –
offset (int) –
length (int) –
- Return type:
None
- data_var_added(view: BinaryView, var: DataVariable) None[source]
Note
data_var_updated will be triggered instead when a user data variable is added over an auto data variable.
- Parameters:
view (BinaryView) –
var (DataVariable) –
- Return type:
None
- data_var_removed(view: BinaryView, var: DataVariable) None[source]
Note
data_var_updated will be triggered instead when a user data variable is removed over an auto data variable.
- Parameters:
view (BinaryView) –
var (DataVariable) –
- Return type:
None
- data_var_updated(view: BinaryView, var: DataVariable) None[source]
- Parameters:
view (BinaryView) –
var (DataVariable) –
- Return type:
None
- data_written(view: BinaryView, offset: int, length: int) None[source]
- Parameters:
view (BinaryView) –
offset (int) –
length (int) –
- Return type:
None
- function_added(view: BinaryView, func: Function) None[source]
Note
function_updated will be triggered instead when a user function is added over an auto function.
- Parameters:
view (BinaryView) –
func (Function) –
- Return type:
None
- function_removed(view: BinaryView, func: Function) None[source]
Note
function_updated will be triggered instead when a user function is removed over an auto function.
- Parameters:
view (BinaryView) –
func (Function) –
- Return type:
None
- function_update_requested(view: BinaryView, func: Function) None[source]
- Parameters:
view (BinaryView) –
func (Function) –
- Return type:
None
- function_updated(view: BinaryView, func: Function) None[source]
- Parameters:
view (BinaryView) –
func (Function) –
- Return type:
None
- notification_barrier(view: BinaryView) int[source]
- Parameters:
view (BinaryView) –
- Return type:
- redo_entry_taken(view: BinaryView, entry: UndoEntry)[source]
- Parameters:
view (BinaryView) –
entry (UndoEntry) –
- section_added(view: BinaryView, section: Section) None[source]
- Parameters:
view (BinaryView) –
section (Section) –
- Return type:
None
- section_removed(view: BinaryView, section: Section) None[source]
- Parameters:
view (BinaryView) –
section (Section) –
- Return type:
None
- section_updated(view: BinaryView, section: Section) None[source]
- Parameters:
view (BinaryView) –
section (Section) –
- Return type:
None
- segment_added(view: BinaryView, segment: Segment) None[source]
- Parameters:
view (BinaryView) –
segment (Segment) –
- Return type:
None
- segment_removed(view: BinaryView, segment: Segment) None[source]
- Parameters:
view (BinaryView) –
segment (Segment) –
- Return type:
None
- segment_updated(view: BinaryView, segment: Segment) None[source]
- Parameters:
view (BinaryView) –
segment (Segment) –
- Return type:
None
- string_found(view: BinaryView, string_type: StringType, offset: int, length: int) None[source]
- Parameters:
view (BinaryView) –
string_type (StringType) –
offset (int) –
length (int) –
- Return type:
None
- string_removed(view: BinaryView, string_type: StringType, offset: int, length: int) None[source]
- Parameters:
view (BinaryView) –
string_type (StringType) –
offset (int) –
length (int) –
- Return type:
None
- symbol_added(view: BinaryView, sym: CoreSymbol) None[source]
- Parameters:
view (BinaryView) –
sym (CoreSymbol) –
- Return type:
None
- symbol_removed(view: BinaryView, sym: CoreSymbol) None[source]
- Parameters:
view (BinaryView) –
sym (CoreSymbol) –
- Return type:
None
- symbol_updated(view: BinaryView, sym: CoreSymbol) None[source]
- Parameters:
view (BinaryView) –
sym (CoreSymbol) –
- Return type:
None
- tag_added(view: BinaryView, tag: Tag, ref_type: TagReferenceType, auto_defined: bool, arch: Architecture | None, func: Function | None, addr: int) None[source]
- Parameters:
view (BinaryView) –
tag (Tag) –
ref_type (TagReferenceType) –
auto_defined (bool) –
arch (Architecture | None) –
func (Function | None) –
addr (int) –
- Return type:
None
- tag_removed(view: BinaryView, tag: Tag, ref_type: TagReferenceType, auto_defined: bool, arch: Architecture | None, func: Function | None, addr: int) None[source]
- Parameters:
view (BinaryView) –
tag (Tag) –
ref_type (TagReferenceType) –
auto_defined (bool) –
arch (Architecture | None) –
func (Function | None) –
addr (int) –
- Return type:
None
- tag_type_updated(view: BinaryView, tag_type) None[source]
- Parameters:
view (BinaryView) –
- Return type:
None
- tag_updated(view: BinaryView, tag: Tag, ref_type: TagReferenceType, auto_defined: bool, arch: Architecture | None, func: Function | None, addr: int) None[source]
- Parameters:
view (BinaryView) –
tag (Tag) –
ref_type (TagReferenceType) –
auto_defined (bool) –
arch (Architecture | None) –
func (Function | None) –
addr (int) –
- Return type:
None
- type_archive_attached(view: BinaryView, id: str, path: str)[source]
- Parameters:
view (BinaryView) –
id (str) –
path (str) –
- type_archive_connected(view: BinaryView, archive: TypeArchive)[source]
- Parameters:
view (BinaryView) –
archive (TypeArchive) –
- type_archive_detached(view: BinaryView, id: str, path: str)[source]
- Parameters:
view (BinaryView) –
id (str) –
path (str) –
- type_archive_disconnected(view: BinaryView, archive: TypeArchive)[source]
- Parameters:
view (BinaryView) –
archive (TypeArchive) –
- type_defined(view: BinaryView, name: QualifiedName, type: Type) None[source]
- Parameters:
view (BinaryView) –
name (QualifiedName) –
type (Type) –
- Return type:
None
- type_field_ref_changed(view: BinaryView, name: QualifiedName, offset: int) None[source]
- Parameters:
view (BinaryView) –
name (QualifiedName) –
offset (int) –
- Return type:
None
- type_ref_changed(view: BinaryView, name: QualifiedName, type: Type) None[source]
- Parameters:
view (BinaryView) –
name (QualifiedName) –
type (Type) –
- Return type:
None
- type_undefined(view: BinaryView, name: QualifiedName, type: Type) None[source]
- Parameters:
view (BinaryView) –
name (QualifiedName) –
type (Type) –
- Return type:
None
- undo_entry_added(view: BinaryView, entry: UndoEntry)[source]
- Parameters:
view (BinaryView) –
entry (UndoEntry) –
- undo_entry_taken(view: BinaryView, entry: UndoEntry)[source]
- Parameters:
view (BinaryView) –
entry (UndoEntry) –
- class BinaryDataNotificationCallbacks[source]
Bases:
object- __init__(view: BinaryView, notify: BinaryDataNotification)[source]
- Parameters:
view (BinaryView) –
notify (BinaryDataNotification) –
- property notify: BinaryDataNotification
- property view: BinaryView
- class BinaryReader[source]
Bases:
objectclass BinaryReaderis a convenience class for reading binary data.BinaryReader can be instantiated as follows and the rest of the document will start from this context
>>> from binaryninja import * >>> bv = load("/bin/ls") >>> br = BinaryReader(bv) >>> hex(br.read32()) '0xfeedfacfL' >>>
Or using the optional endian parameter
>>> from binaryninja import * >>> br = BinaryReader(bv, Endianness.BigEndian) >>> hex(br.read32()) '0xcffaedfeL' >>>
- __init__(view: BinaryView, endian: Endianness | None = None, address: int | None = None)[source]
- Parameters:
view (BinaryView) –
endian (Endianness | None) –
address (int | None) –
- read(length: int, address: int | None = None) bytes | None[source]
readreturnslengthbytes read from the current offset, addinglengthto offset.
- read16(address: int | None = None) int | None[source]
read16returns a two byte integer from offset incrementing the offset by two, using specified endianness.
- read16be(address: int | None = None) int | None[source]
read16bereturns a two byte big endian integer from offset incrementing the offset by two.
- read16le(address: int | None = None) int | None[source]
read16lereturns a two byte little endian integer from offset incrementing the offset by two.
- read32(address: int | None = None) int | None[source]
read32returns a four byte integer from offset incrementing the offset by four, using specified endianness.
- read32be(address: int | None = None) int | None[source]
read32bereturns a four byte big endian integer from offset incrementing the offset by four.
- read32le(address: int | None = None) int | None[source]
read32lereturns a four byte little endian integer from offset incrementing the offset by four.
- read64(address: int | None = None) int | None[source]
read64returns an eight byte integer from offset incrementing the offset by eight, using specified endianness.
- read64be(address: int | None = None) int | None[source]
read64bereturns an eight byte big endian integer from offset incrementing the offset by eight.
- read64le(address: int | None = None) int | None[source]
read64lereturns an eight byte little endian integer from offset incrementing the offset by eight.
- read8(address: int | None = None) int | None[source]
read8returns a one byte integer from offset incrementing the offset.
- seek_relative(offset: int) None[source]
seek_relativeupdates the internal offset byoffset.- Parameters:
offset (int) – offset to add to the internal offset
- Return type:
None
- Example:
>>> hex(br.offset) '0x100000008L' >>> br.seek_relative(-8) >>> hex(br.offset) '0x100000000L' >>>
- property endianness: Endianness
The Endianness to read data. (read/write)
- Getter:
returns the endianness of the reader
- Setter:
sets the endianness of the reader (BigEndian or LittleEndian)
- Type:
- property eof: bool
Is end of file (read-only)
- Getter:
returns boolean, true if end of file, false otherwise
- Type:
- property offset: int
The current read offset (read/write).
- Getter:
returns the current internal offset
- Setter:
sets the internal offset
- Type:
- class BinaryView[source]
Bases:
objectclass BinaryViewimplements a view on binary data, and presents a queryable interface of a binary file. One key job of BinaryView is file format parsing which allows Binary Ninja to read, write, insert, remove portions of the file given a virtual address. For the purposes of this documentation we define a virtual address as the memory address that the various pieces of the physical file will be loaded at.A binary file does not have to have just one BinaryView, thus much of the interface to manipulate disassembly exists within or is accessed through a BinaryView. All files are guaranteed to have at least the
RawBinaryView. TheRawBinaryView is simply a hex editor, but is helpful for manipulating binary files via their absolute addresses.BinaryViews are plugins and thus registered with Binary Ninja at startup, and thus should never be instantiated directly as this is already done. The list of available BinaryViews can be seen in the BinaryViewType class which provides an iterator and map of the various installed BinaryViews:
>>> list(BinaryViewType) [<view type: 'Raw'>, <view type: 'ELF'>, <view type: 'Mach-O'>, <view type: 'PE'>] >>> BinaryViewType['ELF'] <view type: 'ELF'>
To open a file with a given BinaryView the following code is recommended:
>>> with load("/bin/ls") as bv: ... bv <BinaryView: '/bin/ls', start 0x100000000, len 0x142c8>
By convention in the rest of this document we will use bv to mean an open and, analyzed, BinaryView of an executable file. When a BinaryView is open on an executable view analysis is automatically run unless specific named parameters are used to disable updates. If such a parameter is used, updates can be triggered using the
update_analysis_and_waitmethod which disassembles the executable and returns when all disassembly and analysis is complete:>>> bv.update_analysis_and_wait() >>>
Since BinaryNinja’s analysis is multi-threaded (depending on version) this can also be done in the background by using the
update_analysismethod instead.By standard python convention methods which start with ‘_’ should be considered private and should not be called externally. Additionally, methods which begin with
perform_should not be called directly either and are used explicitly for subclassing a BinaryView.Note
An important note on the
*_user_*()methods. Binary Ninja makes a distinction between edits performed by the user and actions performed by auto analysis. Auto analysis actions that can quickly be recalculated are not saved to the database. Auto analysis actions that take a long time and all user edits are stored in the database (e.g.remove_user_functionrather thanremove_function). Thus use_user_methods if saving to the database is desired.- __init__(file_metadata: FileMetadata | None = None, parent_view: BinaryView | None = None, handle: LP_BNBinaryView | None = None)[source]
- Parameters:
file_metadata (FileMetadata | None) –
parent_view (BinaryView | None) –
handle (LP_BNBinaryView | None) –
- static __new__(cls, file_metadata=None, parent_view=None, handle=None)[source]
- abort_analysis() None[source]
abort_analysisaborts analysis and suspends the workflow machine. This operation is recoverable, and the workflow machine can be re-enabled via theenableAPI on WorkflowMachine.- Return type:
None
- add_analysis_completion_event(callback: Callable[[], None]) AnalysisCompletionEvent[source]
add_analysis_completion_eventsets up a call back function to be called when analysis has been completed. This is helpful when usingupdate_analysiswhich does not wait for analysis completion before returning.The callee of this function is not responsible for maintaining the lifetime of the returned AnalysisCompletionEvent object.
Note
The lock held by the callback thread on the BinaryView instance ensures that other BinaryView actions can be safely performed in the callback thread.
Warning
The built-in python console automatically updates analysis after every command is run, which means this call back may not behave as expected if entered interactively.
- Parameters:
callback (callback) – A function to be called with no parameters when analysis has completed.
- Returns:
An initialized AnalysisCompletionEvent object
- Return type:
- Example:
>>> def completionEvent(): ... print("done") ... >>> bv.add_analysis_completion_event(completionEvent) <binaryninja.AnalysisCompletionEvent object at 0x10a2c9f10> >>> bv.update_analysis() done >>>
- add_analysis_option(name: str) None[source]
add_analysis_optionadds an analysis option. Analysis options elaborate the analysis phase. The user must start analysis by calling eitherupdate_analysisorupdate_analysis_and_wait.- Parameters:
name (str) – name of the analysis option. Available options are: “linearsweep”, and “signaturematcher”.
- Return type:
None
- Example:
>>> bv.add_analysis_option("linearsweep") >>> bv.update_analysis_and_wait()
- add_auto_section(name: str, start: int, length: int, semantics: SectionSemantics = SectionSemantics.DefaultSectionSemantics, type: str = '', align: int = 1, entry_size: int = 1, linked_section: str = '', info_section: str = '', info_data: int = 0) None[source]
- add_auto_segment(start: int, length: int, data_offset: int, data_length: int, flags: SegmentFlag) None[source]
add_auto_segmentAdds an analysis segment that specifies how data from the raw file is mapped into a virtual address spaceNote that the segments added may have different size attributes than requested
- Parameters:
start (int) –
length (int) –
data_offset (int) –
data_length (int) –
flags (SegmentFlag) –
- Return type:
None
- add_auto_segments(segments: List[BNSegmentInfo]) None[source]
add_auto_segmentsAdds analysis segments that specify how data from the raw file is mapped into a virtual address space- Parameters:
segments (List[core.BNSegmentInfo]) – list of segments to add
- Return type:
None
- add_data_ref(from_addr: int, to_addr: int) None[source]
add_data_refadds an auto data cross-reference (xref) from the addressfrom_addrto the addressto_addr.- Parameters:
- Return type:
None
Note
It is intended to be used from within workflows or binary view initialization.
- add_entry_point(addr: int, plat: Platform | None = None) None[source]
add_entry_pointadds a virtual address to start analysis from for a given plat.
- add_expression_parser_magic_value(name: str, value: int) None[source]
Add a magic value to the expression parser.
If the magic value already exists, its value gets updated. The magic value can be used in the expression by a $ followed by its name, e.g., $foobar. It is optional to include the $ when calling this function, i.e., calling with foobar and $foobar has the same effect.
- add_expression_parser_magic_values(names: List[str], values: List[int]) None[source]
Add a list of magic value to the expression parser.
The list names and values must have the same size. The ith name in the names will correspond to the ith value in the values.
If a magic value already exists, its value gets updated. The magic value can be used in the expression by a $ followed by its name, e.g., $foobar. It is optional to include the $ when calling this function, i.e., calling with foobar and $foobar has the same effect.
- add_external_library(name: str, backing_file: ProjectFile | None = None, auto: bool = False) ExternalLibrary[source]
Add an ExternalLibrary to this BinaryView
- Parameters:
name (str) – Name of the external library
backing_file (ProjectFile | None) – Optional ProjectFile that backs the external library
auto (bool) – Whether or not this action is the result of automated analysis
- Returns:
The created ExternalLibrary
- Return type:
- add_external_location(source_symbol: CoreSymbol, library: ExternalLibrary | None, target_symbol: str | None, target_address: int | None, auto: bool = False) ExternalLocation[source]
Add an ExternalLocation with its source in this BinaryView. ExternalLocations must have a target address and/or symbol.
- Parameters:
source_symbol (CoreSymbol) – Symbol that the association is from
library (ExternalLibrary | None) – Library that the ExternalLocation belongs to
target_symbol (str | None) – Symbol that the ExternalLocation points to
target_address (int | None) – Address that the ExternalLocation points to
auto (bool) – Whether or not this action is the result of automated analysis
- Returns:
The created ExternalLocation
- Return type:
- add_function(addr: int, plat: Platform | None = None, auto_discovered: bool = False, func_type: Function | None = None) Function | None[source]
add_functionadd a new function of the givenplatat the virtual addressaddrWarning
This function is used to create auto functions, often used when writing loaders, etc. Most users will want to use
create_user_functionin their scripts.- Parameters:
- Return type:
None
- Example:
>>> bv.add_function(1) >>> bv.functions [<func: x86_64@0x1>]
- add_tag(addr: int, tag_type_name: str, data: str, user: bool = True)[source]
add_tagcreates and adds aTagobject at a data address.This API is appropriate for generic data tags. For functions, consider using
add_tag.
- add_to_entry_functions(func: Function) None[source]
add_to_entry_functionsadds a function to the entry_functions list.- Parameters:
func (Function) – a Function object
- Return type:
None
- Example:
>>> bv.entry_functions [<func: x86@0x4014c8>, <func: x86@0x401618>] >>> bv.add_to_entry_functions(bv.get_function_at(0x4014da)) >>> bv.entry_functions [<func: x86@0x4014c8>, <func: x86@0x401618>, <func: x86@0x4014da>]
- add_type_library(lib: TypeLibrary) None[source]
add_type_librarymake the contents of a type library available for type/import resolution- Parameters:
lib (TypeLibrary) – library to register with the view
- Return type:
None
- add_user_data_ref(from_addr: int, to_addr: int) None[source]
add_user_data_refadds a user-specified data cross-reference (xref) from the addressfrom_addrto the addressto_addr. If the reference already exists, no action is performed. To remove the reference, useremove_user_data_ref.
- add_user_section(name: str, start: int, length: int, semantics: SectionSemantics = SectionSemantics.DefaultSectionSemantics, type: str = '', align: int = 1, entry_size: int = 1, linked_section: str = '', info_section: str = '', info_data: int = 0) None[source]
add_user_sectioncreates a user-defined section that can help inform analysis by clarifying what types of data exist in what ranges. Note that all data specified must already be mapped by an existing segment.- Parameters:
name (str) – name of the section
start (int) – virtual address of the start of the section
length (int) – length of the section
semantics (SectionSemantics) – SectionSemantics of the section
type (str) – optional type
align (int) – optional byte alignment
entry_size (int) – optional entry size
linked_section (str) – optional name of a linked section
info_section (str) – optional name of an associated informational section
info_data (int) – optional info data
- Return type:
None
- add_user_segment(start: int, length: int, data_offset: int, data_length: int, flags: SegmentFlag) None[source]
add_user_segmentcreates a user-defined segment that specifies how data from the raw file is mapped into a virtual address space.- Parameters:
start (int) – virtual address of the start of the segment
length (int) – length of the segment (may be larger than the source data)
data_offset (int) – offset from the parent view
data_length (int) – length of the data from the parent view
flags (SegmentFlag) – SegmentFlags
- Return type:
None
- add_user_segments(segments: List[BNSegmentInfo]) None[source]
add_user_segmentsAdds user-defined segments that specify how data from the raw file is mapped into a virtual address space- Parameters:
segments (List[core.BNSegmentInfo]) – list of segments to add
- Return type:
None
- always_branch(addr: int, arch: Architecture | None = None) bool[source]
always_branchconvert the instruction of architecturearchat the virtual addressaddrto an unconditional branch.Note
This API performs a binary patch, analysis may need to be updated afterward. Additionally the binary file must be saved in order to preserve the changes made.
- Parameters:
addr (int) – virtual address of the instruction to be modified
arch (Architecture) – (optional) the architecture of the instructions if different from the default
- Returns:
True on success, False on failure.
- Return type:
- Example:
>>> bv.get_disassembly(0x100012ef) 'jg 0x100012f5' >>> bv.always_branch(0x100012ef) True >>> bv.get_disassembly(0x100012ef) 'jmp 0x100012f5' >>>
- apply_debug_info(value: DebugInfo) None[source]
Sets the debug info and applies its contents to the current binary view
- Parameters:
value (DebugInfo) –
- Return type:
None
- attach_type_archive(archive: TypeArchive)[source]
Attach a given type archive to the analysis and try to connect to it. If attaching was successful, names from that archive will become available to pull, but no types will actually be associated by calling this.
- Parameters:
archive (TypeArchive) – New archive
- attach_type_archive_by_id(id: str, path: str) TypeArchive | None[source]
Attach a type archive to the owned analysis and try to connect to it. If attaching was successful, names from that archive will become available to pull, but no types will actually be associated by calling this.
The behavior of this function is rather complicated, in an attempt to enable the ability to have attached, but disconnected Type Archives.
Normal operation:
If there was no previously connected Type Archive whose id matches id, and the file at path contains a Type Archive whose id matches id, it will be attached and connected.
Edge-cases:
If there was a previously connected Type Archive whose id matches id, nothing will happen, and it will simply be returned. If the file at path does not exist, nothing will happen and None will be returned. If the file at path exists but does not contain a Type Archive whose id matches id, nothing will happen and None will be returned. If there was a previously attached but disconnected Type Archive whose id matches id, and the file at path contains a Type Archive whose id matches id, the previously attached Type Archive will have its saved path updated to point to path. The Type Archive at path will be connected and returned.
- Parameters:
- Returns:
Attached archive object, if it could be connected.
- Return type:
TypeArchive | None
- begin_bulk_add_segments() None[source]
begin_bulk_add_segmentsBegins a bulk segment addition operation.This function prepares the BinaryView for bulk addition of both auto and user-defined segments. During the bulk operation, segments can be added using add_auto_segment or similar functions without immediately triggering the MemoryMap update process. The queued segments will not take effect until end_bulk_add_segments is called.
- Return type:
None
- begin_undo_actions(anonymous_allowed: bool = True) str[source]
begin_undo_actionsstarts recording actions taken so they can be undone at some point.- Parameters:
anonymous_allowed (bool) – Legacy interop: prevent empty calls to
commit_undo_actions`from affecting this undo state. Specifically forundoable_transaction`- Returns:
Id of undo state, for passing to
commit_undo_actions`orrevert_undo_actions.- Return type:
- Example:
>>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>> state = bv.begin_undo_actions() >>> bv.convert_to_nop(0x100012f1) True >>> bv.commit_undo_actions(state) >>> bv.get_disassembly(0x100012f1) 'nop' >>> bv.undo() >>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>>
- bulk_modify_symbols()[source]
bulk_modify_symbolsreturns a context manager that improves performance when adding or removing a large number of symbols. Symbols added within the Python with keyword will defer processing until the end of the block. Many symbol getter APIs will return stale results inside the with block, so this function should only be used when symbol queries are not needed at the same time as the modifications.
- can_assemble(arch: Architecture | None = None) bool[source]
can_assemblequeries the architecture plugin to determine if the architecture can assemble instructions.- Returns:
True if the architecture can assemble, False otherwise
- Return type:
- Example:
>>> bv.can_assemble() True >>>
- Parameters:
arch (Architecture | None) –
- cancel_bulk_add_segments() None[source]
cancel_bulk_add_segmentsCancels a bulk segment addition operation.This function discards all auto and user segments that were queued since the last call to begin_bulk_add_segments without applying them. It allows you to abandon the changes in case they are no longer needed.
Note: If no bulk operation is in progress, calling this function has no effect.
- Return type:
None
- check_for_string_annotation_type(addr: int, allow_short_strings: bool = False, allow_large_strings: bool = False, child_width: int = 0) Tuple[str, StringType] | None[source]
Check for string annotation at a given address. This returns the string (and type of the string) as annotated in the UI at a given address. If there’s no annotation, this function returns None.
- Parameters:
addr (int) – address at which to check for string annotation
allow_short_strings (bool) – Allow string shorter than the analysis.limits.minStringLength setting
allow_large_strings (bool) – Allow strings longer than the rendering.strings.maxAnnotationLength setting (up to analysis.limits.maxStringLength)
child_width (int) – What width of strings to look for, 1 for ASCII/UTF8, 2 for UTF16, 4 for UTF32, 0 to check for all
- Return type:
None
- clear_user_global_pointer_value()[source]
Clear a previously set user global pointer value, so the auto-analysis can calculate a new value
- commit_undo_actions(id: str | None = None) None[source]
commit_undo_actionscommits the actions taken since a call tobegin_undo_actionsPass as id the value returned bybegin_undo_actions. Empty values of id will commit all changes since the last call tobegin_undo_actions.- Parameters:
id (Optional[str]) – id of undo state, from
begin_undo_actions- Return type:
None
- Example:
>>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>> state = bv.begin_undo_actions() >>> bv.convert_to_nop(0x100012f1) True >>> bv.commit_undo_actions(state) >>> bv.get_disassembly(0x100012f1) 'nop' >>> bv.undo() >>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>>
- convert_to_nop(addr: int, arch: Architecture | None = None) bool[source]
convert_to_nopconverts the instruction at virtual addressaddrto a nop of the provided architecture.Note
This API performs a binary patch, analysis may need to be updated afterward. Additionally the binary file must be saved in order to preserve the changes made.
- Parameters:
addr (int) – virtual address of the instruction to convert to nops
arch (Architecture) – (optional) the architecture of the instructions if different from the default
- Returns:
True on success, False on failure.
- Return type:
- Example:
>>> bv.get_disassembly(0x100012fb) 'call 0x10001629' >>> bv.convert_to_nop(0x100012fb) True >>> #The above 'call' instruction is 5 bytes, a nop in x86 is 1 byte, >>> # thus 5 nops are used: >>> bv.get_disassembly(0x100012fb) 'nop' >>> bv.get_disassembly(0x100012fb + 1) 'nop' >>> bv.get_disassembly(0x100012fb + 2) 'nop' >>> bv.get_disassembly(0x100012fb + 3) 'nop' >>> bv.get_disassembly(0x100012fb + 4) 'nop' >>> bv.get_disassembly(0x100012fb + 5) 'mov byte [ebp-0x1c], al'
- create_component(name: str | None = None, parent: Component | str | None = None) Component[source]
Create a new component with an optional name and parent.
- The parent argument can be either a Component or the Guid of a component that the created component will be
added as a child of
- create_database(filename: str, progress_func: Callable[[int, int], bool] | None = None, settings: SaveSettings | None = None) bool[source]
create_databasewrites the current database (.bndb) out to the specified file.Warning
This API will only save a database, NOT the original file from a view. To save the original file, use
save. To update a database, usesave_auto_snapshot- Parameters:
filename (str) – path and filename to write the bndb to, this string should have “.bndb” appended to it.
progress_func (callback) – optional function to be called with the current progress and total count.
settings (SaveSettings) – optional argument for special save options.
- Returns:
True on success, False on failure
- Return type:
Warning
The calling thread must not hold a lock on the BinaryView instance as this action is run on the main thread which requires the lock.
- create_structure_from_offset_access(name: QualifiedName) StructureType[source]
- Parameters:
name (QualifiedName) –
- Return type:
- create_structure_member_from_access(name: QualifiedName, offset: int) Type[source]
- Parameters:
name (QualifiedName) –
offset (int) –
- Return type:
- create_tag_type(name: str, icon: str) TagType[source]
create_tag_typecreates a newTagTypeand adds it to the view
- create_user_function(addr: int, plat: Platform | None = None) Function | None[source]
create_user_functionadd a new user function of the givenplatat the virtual addressaddr
- define_auto_symbol(sym: CoreSymbol) None[source]
define_auto_symboladds a symbol to the internal list of automatically discovered Symbol objects in a given namespace.Warning
If multiple symbols for the same address are defined, only the most recent symbol will ever be used.
- Parameters:
sym (CoreSymbol) – the symbol to define
- Return type:
None
- define_auto_symbol_and_var_or_function(sym: CoreSymbol, type: Type | None = None, plat: Platform | None = None, type_confidence: int | None = 0) CoreSymbol | None[source]
define_auto_symbol_and_var_or_functionDefines an “Auto” symbol, and a Variable/Function alongside it.Warning
If multiple symbols for the same address are defined, only the most recent symbol will ever be used.
- Parameters:
sym (CoreSymbol) – Symbol to define
type (Type | None) – Type for the function/variable being defined (can be None)
plat (Platform | None) – Platform (optional)
type_confidence (int | None) – Optional confidence value for the type
- Return type:
Optional[CoreSymbol]
- define_data_var(addr: int, var_type: str | Type | TypeBuilder, name: str | CoreSymbol | None = None) None[source]
define_data_vardefines a non-user data variablevar_typeat the virtual addressaddr.- Parameters:
addr (int) – virtual address to define the given data variable
var_type (StringOrType) – type to be defined at the given virtual address
name (str | CoreSymbol | None) – Optionally additionally define a symbol at this location
name –
- Return type:
None
- Example:
>>> t = bv.parse_type_string("int foo") >>> t (<type: int32_t>, 'foo') >>> bv.define_data_var(bv.entry_point, t[0]) >>> bv.define_data_var(bv.entry_point + 4, "int", "foo") >>> bv.get_symbol_at(bv.entry_point + 4) <DataSymbol: "foo" @ 0x23950> >>> bv.get_data_var_at(bv.entry_point + 4) <var 0x23950: int32_t>
- define_imported_function(import_addr_sym: CoreSymbol, func: Function, type: Type | None = None) None[source]
define_imported_functiondefines an imported Functionfuncwith a ImportedFunctionSymbol type.- Parameters:
import_addr_sym (CoreSymbol) – A Symbol object with type ImportedFunctionSymbol
func (Function) – A Function object to define as an imported function
type (Type | None) – Optional type for the function
- Return type:
None
- define_type(type_id: str, default_name: _types.QualifiedNameType | None, type_obj: str | _types.Type | _types.TypeBuilder) _types.QualifiedName[source]
define_typeregisters aTypetype_objof the givennamein the global list of types for the currentBinaryView. This method should only be used for automatically generated types.- Parameters:
type_id (str) – Unique identifier for the automatically generated type
default_name (QualifiedName) – Name of the type to be registered
type_obj (StringOrType) – Type object to be registered
- Returns:
Registered name of the type. May not be the same as the requested name if the user has renamed types.
- Return type:
- Example:
>>> type, name = bv.parse_type_string("int foo") >>> registered_name = bv.define_type(Type.generate_auto_type_id("source", name), name, type) >>> bv.get_type_by_name(registered_name) <type: int32_t> >>> registered_name = bv.define_type("mytypeid", None, "int bar") >>> bv.get_type_by_name(registered_name) <type: int32_t>
- define_types(types: List[Tuple[str, _types.QualifiedNameType | None, str | _types.Type | _types.TypeBuilder]], progress_func: Callable[[int, int], bool] | None) Mapping[str, _types.QualifiedName][source]
define_typesregisters multiple types as though callingdefine_typemultiple times. The difference with this plural version is that it is optimized for adding many types at the same time, using knowledge of all types at add-time to improve runtime. There is an optionalprogress_funccallback function in case you want updates for a long-running call.Warning
This method should only be used for automatically generated types, see
define_user_typesfor interactive plugin uses.The return values of this function provide a map of each type id and which name was chosen for that type (which may be different from the requested name).
- Parameters:
- Returns:
A map of all the chosen names for the defined types with their ids.
- Return type:
- define_user_data_var(addr: int, var_type: str | Type | TypeBuilder, name: str | CoreSymbol | None = None) DataVariable | None[source]
define_user_data_vardefines a user data variablevar_typeat the virtual addressaddr.- Parameters:
addr (int) – virtual address to define the given data variable
var_type (binaryninja.Type) – type to be defined at the given virtual address
name (str | CoreSymbol | None) – Optionally, additionally define a symbol at this same address
name –
- Return type:
Optional[DataVariable]
- Example:
>>> t = bv.parse_type_string("int foo") >>> t (<type: int32_t>, 'foo') >>> bv.define_user_data_var(bv.entry_point, t[0]) <var 0x2394c: int32_t> >>> bv.define_user_data_var(bv.entry_point + 4, "int", "foo") <var 0x23950: int32_t> >>> bv.get_symbol_at(bv.entry_point + 4) <DataSymbol: "foo" @ 0x23950> >>> bv.get_data_var_at(bv.entry_point + 4) <var 0x23950: int32_t>
- define_user_symbol(sym: CoreSymbol) None[source]
define_user_symboladds a symbol to the internal list of user added Symbol objects.Warning
If multiple symbols for the same address are defined, only the most recent symbol will ever be used.
- Parameters:
sym (Symbol) – the symbol to define
- Return type:
None
- define_user_type(name: _types.QualifiedNameType | None, type_obj: str | _types.Type | _types.TypeBuilder) None[source]
define_user_typeregisters aTypetype_objof the givennamein the global list of user types for the currentBinaryView.- Parameters:
name (QualifiedName) – Name of the user type to be registered
type_obj (StringOrType) – Type object to be registered
- Return type:
None
- Example:
>>> type, name = bv.parse_type_string("int foo") >>> bv.define_user_type(name, type) >>> bv.get_type_by_name(name) <type: int32_t> >>> bv.define_user_type(None, "int bas") >>> bv.get_type_by_name("bas") <type: int32_t>
- define_user_types(types: List[Tuple[_types.QualifiedNameType | None, str | _types.Type | _types.TypeBuilder]], progress_func: Callable[[int, int], bool] | None)[source]
define_user_typesregisters multiple types as though callingdefine_user_typemultiple times. The difference with this plural version is that it is optimized for adding many types at the same time, using knowledge of all types at add-time to improve runtime. There is an optionalprogress_funccallback function in case you want updates for a long-running call.
- detach_type_archive(archive: TypeArchive)[source]
Detach from a type archive, breaking all associations to types within the archive
- Parameters:
archive (TypeArchive) – Type archive to detach
- detach_type_archive_by_id(id: str)[source]
Detach from a type archive, breaking all associations to types within the archive
- Parameters:
id (str) – Id of archive to detach
- disassembly_text(addr: int, arch: Architecture | None = None) Generator[Tuple[str, int], None, None][source]
disassembly_texthelper function for getting disassembly of a given address- Parameters:
addr (int) – virtual address of instruction
arch (Architecture) – optional Architecture,
self.archis used if this parameter is None
- Returns:
a str representation of the instruction at virtual address
addror None- Return type:
str or None
- Example:
>>> next(bv.disassembly_text(bv.entry_point)) 'push ebp', 1 >>>
- disassembly_tokens(addr: int, arch: Architecture | None = None) Generator[Tuple[List[InstructionTextToken], int], None, None][source]
- Parameters:
addr (int) –
arch (Architecture | None) –
- Return type:
Generator[Tuple[List[InstructionTextToken], int], None, None]
- disassociate_type_archive_type(type: _types.QualifiedNameType) bool[source]
Disassociate an associated type, so that it will no longer receive updates from its connected type archive
- Parameters:
type (_types.QualifiedNameType) – Name of type in analysis
- Returns:
True if successful
- Return type:
- disassociate_type_archive_type_by_id(type_id: str) bool[source]
Disassociate an associated type id, so that it will no longer receive updates from its connected type archive
- end_bulk_add_segments() None[source]
end_bulk_add_segmentsFinalizes and applies all queued segments (auto and user) added during a bulk segment addition operation.This function commits all segments that were queued since the last call to begin_bulk_add_segments. The MemoryMap update process is executed at this point, applying all changes in one batch for improved performance.
Note: This function must be called after begin_bulk_add_segments to apply the queued segments.
- Return type:
None
- eval(expression: str, here: int = 0) int[source]
Evaluates a string expression to an integer value. This is a more concise alias for the
parse_expressionAPI
- export_object_to_library(lib: TypeLibrary, name: str | None, type_obj: str | Type | TypeBuilder) None[source]
Recursively exports
type_objintolibas an object with aname.This should be used to store definitions for functions, variables, and other things that are named symbols. For example, MessageBoxA might be the name of a function with the type int ()(HWND, LPCSTR, LPCSTR, UINT). If you just want to store a type definition, you probably want
export_type_to_library.As other referenced types are encountered, they are either copied into the destination type library or else the type library that provided the referenced type is added as a dependency for the destination library.
- Parameters:
lib (TypeLibrary) –
name (QualifiedName) –
type_obj (StringOrType) –
- Return type:
None
- export_type_to_library(lib: TypeLibrary, name: str | None, type_obj: str | Type | TypeBuilder) None[source]
Recursively exports
type_objintolibas a type with aname.This should be used to store type definitions with no symbol information. For example, color might be a type of enum {RED=0, ORANGE=1, YELLOW=2, …} used by this library. If you have a function, variable, or other object that is exported, you probably want
export_object_to_libraryinstead.As other referenced types are encountered, they are either copied into the destination type library or else the type library that provided the referenced type is added as a dependency for the destination library.
- Parameters:
lib (TypeLibrary) –
name (QualifiedName) –
type_obj (StringOrType) –
- Return type:
None
- static external_namespace() NameSpace[source]
External namespace for the current BinaryView
- Return type:
- finalize_new_segments() bool[source]
Performs “finalization” on segments added after initial Finalization (performed after an Init() has completed).
- Finalizing a segment involves optimizing the relocation info stored in that segment, so if a segment is added
and relocations are defined for that segment by some automated process, this function should be called afterwards.
- An example of this can be seen in the KernelCache plugin, in KernelCache::LoadImageWithInstallName.
After we load an image, map new segments, and define relocations for all of them, we call this function to let core know it is now safe to finalize the new segments
- Returns:
Whether finalization was successful
- Return type:
- find_all_constant(start: int, end: int, constant: int, settings: DisassemblySettings | None = None, graph_type: FunctionViewType | FunctionGraphType | str = FunctionGraphType.NormalFunctionGraph, progress_func: Callable[[int, int], bool] | None = None, match_callback: Callable[[int, LinearDisassemblyLine], bool] | None = None) QueueGenerator[source]
find_all_constantsearches for the integer constantconstantstarting at the virtual addressstartuntil the virtual addressend. Once a match is found, thematch_callbackis called.Note
A
constantis considered used if a line in the linear view expansion of the given function graph type contains a token with a value that matches that constant. This does not search for raw bytes/data in the binary, for that you want to usefind_all_data.- Parameters:
start (int) – virtual address to start searching from.
end (int) – virtual address to end the search.
constant (int) – constant to search for
settings (DisassemblySettings) – DisassemblySettings object used to render the text to be searched
graph_type (FunctionViewType) – the IL to search within
progress_func (callback) – optional function to be called with the current progress and total count. This function should return a boolean value that decides whether the search should continue or stop
match_callback (callback) – function that gets called when a match is found. The callback takes two parameters, i.e., the address of the match, and the LinearDisassemblyLine that contains the matching line. If this parameter is None, this function becomes a generator and yields the matching address and the matching LinearDisassemblyLine. This function can return a boolean value that decides whether the search should continue or stop
- Rtype QueueGenerator:
A generator object that will yield all the found results
- find_all_data(start: int, end: int, data: bytes, flags: FindFlag = FindFlag.FindCaseSensitive, progress_func: Callable[[int, int], bool] | None = None, match_callback: Callable[[int, DataBuffer], bool] | None = None) QueueGenerator[source]
find_all_datasearches for the bytesdatastarting at the virtual addressstartuntil the virtual addressend. Once a match is found, thematch_callbackis called.- Parameters:
start (int) – virtual address to start searching from.
end (int) – virtual address to end the search.
data (bytes) – data to search for
flags (FindFlag) –
(optional) defaults to case-insensitive data search
FindFlag
Description
FindCaseSensitive
Case-sensitive search
FindCaseInsensitive
Case-insensitive search
progress_func (callback) – optional function to be called with the current progress and total count. This function should return a boolean value that decides whether the search should continue or stop
match_callback (callback) – function that gets called when a match is found. The callback takes two parameters, i.e., the address of the match, and the actual DataBuffer that satisfies the search. If this parameter is None, this function becomes a generator and yields a tuple of the matching address and the matched DataBuffer. This function can return a boolean value that decides whether the search should continue or stop.
data –
- Rtype QueueGenerator:
A generator object that will yield all the found results
- find_all_text(start: int, end: int, text: str, settings: DisassemblySettings | None = None, flags=FindFlag.FindCaseSensitive, graph_type: FunctionViewType | FunctionGraphType | str = FunctionGraphType.NormalFunctionGraph, progress_func=None, match_callback=None) QueueGenerator[source]
find_all_textsearches for stringtextoccurring in the linear view output starting at the virtual addressstartuntil the virtual addressend. Once a match is found, thematch_callbackis called.- Parameters:
start (int) – virtual address to start searching from.
end (int) – virtual address to end the search.
text (str) – text to search for
settings (DisassemblySettings) – DisassemblySettings object used to render the text to be searched
flags (FindFlag) –
(optional) bit-flags list of options, defaults to case-insensitive data search
FindFlag
Description
FindCaseSensitive
Case-sensitive search
FindCaseInsensitive
Case-insensitive search
FindIgnoreWhitespace
Ignore whitespace characters
graph_type (FunctionViewType) – the IL to search within
progress_func (callback) – optional function to be called with the current progress and total count. This function should return a boolean value that decides whether the search should continue or stop
match_callback (callback) – function that gets called when a match is found. The callback takes three parameters, i.e., the address of the match, and the actual string that satisfies the search, and the LinearDisassemblyLine that contains the matching line. If this parameter is None, this function becomes a generator and yields a tuple of the matching address, the matched string, and the matching LinearDisassemblyLine. This function can return a boolean value that decides whether the search should continue or stop
- Rtype QueueGenerator:
A generator object that will yield all the found results
- find_next_constant(start: int, constant: int, settings: DisassemblySettings | None = None, graph_type: FunctionViewType | FunctionGraphType | str = FunctionGraphType.NormalFunctionGraph) int | None[source]
find_next_constantsearches for integer constantconstantoccurring in the linear view output starting at the virtual addressstartuntil the end of the BinaryView.- Parameters:
start (int) – virtual address to start searching from.
constant (int) – constant to search for
settings (DisassemblySettings) – disassembly settings
graph_type (FunctionViewType) – the IL to search within
- Return type:
int | None
- find_next_data(start: int, data: bytes, flags: FindFlag = FindFlag.FindCaseSensitive) int | None[source]
find_next_datasearches for the bytesdatastarting at the virtual addressstartuntil the end of the BinaryView.- Parameters:
- Return type:
int | None
- find_next_text(start: int, text: str, settings: DisassemblySettings | None = None, flags: int = FindFlag.FindCaseSensitive, graph_type: FunctionViewType | FunctionGraphType | str = FunctionGraphType.NormalFunctionGraph) int | None[source]
find_next_textsearches for stringtextoccurring in the linear view output starting at the virtual addressstartuntil the end of the BinaryView.- Parameters:
start (int) – virtual address to start searching from.
text (str) – text to search for
settings (DisassemblySettings) – disassembly settings
flags (FindFlag) –
(optional) bit-flags list of options, defaults to case-insensitive data search
FindFlag
Description
FindCaseSensitive
Case-sensitive search
FindCaseInsensitive
Case-insensitive search
FindIgnoreWhitespace
Ignore whitespace characters
graph_type (FunctionViewType) – the IL to search within
- Return type:
int | None
- forget_undo_actions(id: str | None = None) None[source]
forget_undo_actionsremoves the actions taken since a call tobegin_undo_actionsPass as id the value returned bybegin_undo_actions. Empty values of id will remove all changes since the last call tobegin_undo_actions.- Parameters:
id (Optional[str]) – id of undo state, from
begin_undo_actions- Return type:
None
- Example:
>>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>> state = bv.begin_undo_actions() >>> bv.convert_to_nop(0x100012f1) True >>> bv.forget_undo_actions(state) >>> bv.get_disassembly(0x100012f1) 'nop' >>> bv.undo() >>> bv.get_disassembly(0x100012f1) 'nop' >>>
- get_address_for_data_offset(offset: int) int | None[source]
get_address_for_data_offsetreturns the virtual address that maps to the specific file offset.- Parameters:
offset (int) – file offset
- Returns:
the virtual address of the first segment that contains that file location
- Return type:
Int
- get_address_input(prompt: str, title: str, current_address: int | None = None) int | None[source]
get_address_inputGets a virtual address via a prompt displayed to the user
- get_all_fields_referenced(name: _types.QualifiedNameType) List[int][source]
get_all_fields_referencedreturns a list of offsets in the QualifiedName specified by name, which are referenced by code.- Parameters:
name (QualifiedName) – name of type to query for references
- Returns:
List of offsets
- Return type:
list(integer)
- Example:
>>> bv.get_all_fields_referenced('A') [0, 8, 16, 24, 32, 40] >>>
- get_all_sizes_referenced(name: _types.QualifiedNameType) Mapping[int, List[int]][source]
get_all_sizes_referencedreturns a map from field offset to a list of sizes of the accesses to it.- Parameters:
name (QualifiedName) – name of type to query for references
- Returns:
A map from field offset to the size of the code accesses to it
- Return type:
map
- Example:
>>> bv.get_all_sizes_referenced('B') {0: [1, 8], 8: [8], 16: [1, 8]} >>>
- get_all_types_referenced(name: _types.QualifiedNameType) Mapping[int, List[_types.Type]][source]
get_all_types_referencedreturns a map from field offset to a list of incoming types written to the specified type.- Parameters:
name (QualifiedName) – name of type to query for references
- Returns:
A map from field offset to a list of incoming types written to it
- Return type:
map
- Example:
>>> bv.get_all_types_referenced('B') {0: [<type: char, 0% confidence>], 8: [<type: int64_t, 0% confidence>], 16: [<type: char, 0% confidence>, <type: bool>]} >>>
- get_ascii_string_at(addr: int, min_length: int = 4, max_length: int | None = None, require_cstring: bool = True) StringReference | None[source]
get_ascii_string_atreturns an ascii string found ataddr.Note
This returns an ascii string irrespective of whether the core analysis identified a string at that location. For an alternative API that uses existing identified strings, use
get_string_at.- Parameters:
- Returns:
the string found at
addror None if a string does not exist- Return type:
StringReference or None
- Example:
>>> s1 = bv.get_ascii_string_at(0x70d0) >>> s1 <AsciiString: 0x70d0, len 0xb> >>> s1.value 'AWAVAUATUSH' >>> s2 = bv.get_ascii_string_at(0x70d1) >>> s2 <AsciiString: 0x70d1, len 0xa> >>> s2.value 'WAVAUATUSH'
- get_associated_type_archive_type_source(archive: TypeArchive, archive_type: _types.QualifiedNameType) _types.QualifiedName | None[source]
Determine the local source type name for a given archive type
- Parameters:
archive (TypeArchive) – Target type archive
archive_type (_types.QualifiedNameType) – Name of target archive type
- Returns:
Name of source analysis type, if this type is associated. None otherwise.
- Return type:
_types.QualifiedName | None
- get_associated_type_archive_type_source_by_id(archive_id: str, archive_type_id: str) str | None[source]
Determine the local source type id for a given archive type
- get_associated_type_archive_type_target(name: _types.QualifiedNameType) Tuple[TypeArchive | None, str] | None[source]
Determine the target archive / type id of a given analysis type
- Parameters:
name (_types.QualifiedNameType) – Analysis type
- Returns:
(archive, archive type id) if the type is associated. None otherwise.
- Return type:
Tuple[TypeArchive | None, str] | None
- get_associated_type_archive_type_target_by_id(type_id: str) Tuple[str, str] | None[source]
Determine the target archive / type id of a given analysis type
- get_associated_types_from_archive(archive: TypeArchive) Mapping[QualifiedName, str][source]
Get a list of all types in the analysis that are associated with a specific type archive
- Returns:
Map of all analysis types to their corresponding archive id
- Parameters:
archive (TypeArchive) –
- Return type:
- get_associated_types_from_archive_by_id(archive_id: str) Mapping[str, str][source]
Get a list of all types in the analysis that are associated with a specific type archive :return: Map of all analysis types to their corresponding archive id
- get_basic_blocks_at(addr: int) List[BasicBlock][source]
get_basic_blocks_atget a list ofBasicBlockobjects which exist at the provided virtual address.- Parameters:
addr (int) – virtual address of BasicBlock desired
- Returns:
a list of
BasicBlockobjects- Return type:
- get_basic_blocks_starting_at(addr: int) List[BasicBlock][source]
get_basic_blocks_starting_atget a list ofBasicBlockobjects which start at the provided virtual address.- Parameters:
addr (int) – virtual address of BasicBlock desired
- Returns:
a list of
BasicBlockobjects- Return type:
- get_callees(addr: int, func: Function | None = None, arch: Architecture | None = None) List[int][source]
get_calleesreturns a list of virtual addresses called by the call site in the functionfunc, of the architecturearch, and at the addressaddr. If no function is specified, call sites from all functions and containing the address will be considered. If no architecture is specified, the architecture of the function will be used.- Parameters:
addr (int) – virtual address of the call site to query for callees
func (Architecture) – (optional) the function that the call site belongs to
func – (optional) the architecture of the call site
arch (Architecture | None) –
- Returns:
list of integers
- Return type:
list(integer)
- get_callers(addr: int) Generator[ReferenceSource, None, None][source]
get_callersreturns a list of ReferenceSource objects (xrefs or cross-references) that call the provided virtual address. In this case, tail calls, jumps, and ordinary calls are considered.- Parameters:
addr (int) – virtual address of callee to query for callers
- Returns:
List of References that call the given virtual address
- Return type:
- Example:
>>> bv.get_callers(here) [<ref: x86@0x4165ff>] >>>
- get_code_refs(addr: int, length: int | None = None, max_items: int | None = None) Generator[ReferenceSource, None, None][source]
get_code_refsreturns a generator ofReferenceSourceobjects (xrefs or cross-references) that point to the provided virtual address. This function returns both autoanalysis (“auto”) and user-specified (“user”) xrefs. To add a user-specified reference, seeadd_user_code_ref.The related
get_data_refsis used to find data references to an address unlike this API which returns references that exist in code.Note
Note that get_code_refs returns xrefs to code that references the address being queried. get_data_refs on the other hand returns references that exist in data (pointers in global variables for example). The related
get_code_refs_fromlooks for references that are outgoing from the queried address to other locations.- Parameters:
- Returns:
A generator of References for the given virtual address
- Return type:
Generator[ReferenceSource, None, None]
- Example:
>>> bv.get_code_refs(here) [<ref: x86@0x4165ff>] >>>
- get_code_refs_for_type(name: str, max_items: int | None = None) Generator[ReferenceSource, None, None][source]
get_code_refs_for_typereturns a Generator[ReferenceSource] objects (xrefs or cross-references) that reference the provided QualifiedName.- Parameters:
name (QualifiedName) – name of type to query for references
max_items (int) – optional maximum number of references to fetch
- Returns:
List of References for the given type
- Return type:
- Example:
>>> bv.get_code_refs_for_type('A') [<ref: x86@0x4165ff>] >>>
- get_code_refs_for_type_field(name: str, offset: int, max_items: int | None = None) Generator[TypeFieldReference, None, None][source]
get_code_refs_for_typereturns a Generator[TypeFieldReference] objects (xrefs or cross-references) that reference the provided type field.- Parameters:
name (QualifiedName) – name of type to query for references
offset (int) – offset of the field, relative to the type
max_items (int) – optional maximum number of references to fetch
- Returns:
Generator of References for the given type
- Return type:
Generator[TypeFieldReference]
- Example:
>>> bv.get_code_refs_for_type_field('A', 0x8) [<ref: x86@0x4165ff>] >>>
- get_code_refs_for_type_fields_from(addr: int, func: Function | None = None, arch: Architecture | None = None, length: int | None = None) List[TypeReferenceSource][source]
get_code_refs_for_type_fields_fromreturns a list of type fields referenced by code in the functionfunc, of the architecturearch, and at the addressaddr. If no function is specified, references from all functions and containing the address will be returned. If no architecture is specified, the architecture of the function will be used.- Parameters:
addr (int) – virtual address to query for references
length (int) – optional length of query
func (Function | None) –
arch (Architecture | None) –
- Returns:
list of references
- Return type:
- get_code_refs_for_type_from(addr: int, func: Function | None = None, arch: Architecture | None = None, length: int | None = None) List[TypeReferenceSource][source]
get_code_refs_for_type_fromreturns a list of types referenced by code in the functionfunc, of the architecturearch, and at the addressaddr. If no function is specified, references from all functions and containing the address will be returned. If no architecture is specified, the architecture of the function will be used.- Parameters:
addr (int) – virtual address to query for references
length (int) – optional length of query
func (Function | None) –
arch (Architecture | None) –
- Returns:
list of references
- Return type:
- get_code_refs_from(addr: int, func: Function | None = None, arch: Architecture | None = None, length: int | None = None) List[int][source]
get_code_refs_fromreturns a list of virtual addresses referenced by code in the functionfunc, of the architecturearch, and at the addressaddr. If no function is specified, references from all functions and containing the address will be returned. If no architecture is specified, the architecture of the function will be used. This function returns both autoanalysis (“auto”) and user-specified (“user”) xrefs. To add a user-specified reference, seeadd_user_code_ref.- Parameters:
addr (int) – virtual address to query for references
length (int) – optional length of query
arch (Architecture) – optional architecture of query
func (Function | None) –
- Returns:
list of integers
- Return type:
list(integer)
- get_comment_at(addr: int) str[source]
get_comment_atreturns the address-based comment attached to the given address in this BinaryView Note that address-based comments are different from function-level comments which are specific to eachFunction. For more information, seeaddress_comments.
- get_component_by_path(path: str) Component | None[source]
Lookup a Component by its pathname
- Note:
This is a convenience method, and for performance-sensitive lookups, GetComponentByGuid is very highly recommended.
- Parameters:
path (str) –
- Return type:
Component | None
Lookups are done based on the .display_name of the Component.
All lookups are absolute from the root component, and are case-sensitive. Pathnames are delimited with “/”
- Parameters:
path (str) – Pathname of the desired Component
- Returns:
The Component at that pathname
- Example:
>>> c = bv.create_component(name="MyComponent") >>> c2 = bv.create_component(name="MySubComponent", parent=c) >>> bv.get_component_by_path("/MyComponent/MySubComponent") == c2 True >>> c3 = bv.create_component(name="MySubComponent", parent=c) >>> c3 <Component "MySubComponent (1)" "(20712aff...")> >>> bv.get_component_by_path("/MyComponent/MySubComponent (1)") == c3 True
- Return type:
Component | None
- get_data_offset_for_address(address: int) int | None[source]
get_data_offset_for_addressreturns the file offset that maps to the given virtual address, if possible.If address falls within a bss segment or an external segment, for example, no mapping is possible, and None will be returned.
- Parameters:
address (int) – virtual address
- Returns:
the file location that is mapped to the given virtual address, or None if no such mapping is possible
- Return type:
Int
- get_data_refs(addr: int, length: int | None = None, max_items: int | None = None) Generator[int, None, None][source]
get_data_refsreturns a list of virtual addresses of _data_ (not code) which referencesaddr, optionally specifying a length. Whenlengthis setget_data_refsreturns the data which references in the rangeaddr-addr``+``length. This function returns both autoanalysis (“auto”) and user-specified (“user”) xrefs. To add a user-specified reference, seeadd_user_data_ref.Warning
If you’re looking at this API, please double check that you don’t mean to use
get_code_refsinstead. get_code_refs returns references from code to the specified address while this API returns references from data (pointers in global variables for example). Also, note there existsget_data_refs_from.
- get_data_refs_for_type(name: str, max_items: int | None = None) Generator[int, None, None][source]
get_data_refs_for_typereturns a list of virtual addresses of data which references the typename. Note, the returned addresses are the actual start of the queried type. For example, suppose there is a DataVariable at 0x1000 that has type A, and type A contains type B at offset 0x10. Then get_data_refs_for_type(‘B’) will return 0x1010 for it.- Parameters:
name (QualifiedName) – name of type to query for references
max_items (int) – optional maximum number of references to fetch
- Returns:
list of integers
- Return type:
list(integer)
- Example:
>>> bv.get_data_refs_for_type('A') [4203812] >>>
- get_data_refs_for_type_field(name: _types.QualifiedNameType, offset: int, max_items: int | None = None) List[int][source]
get_data_refs_for_type_fieldreturns a list of virtual addresses of data which references the typename. Note, the returned addresses are the actual start of the queried type field. For example, suppose there is a DataVariable at 0x1000 that has type A, and type A contains type B at offset 0x10. Then get_data_refs_for_type_field(‘B’, 0x8) will return 0x1018 for it.- Parameters:
name (QualifiedName) – name of type to query for references
offset (int) – offset of the field, relative to the type
max_items (int) – optional maximum number of references to fetch
- Returns:
list of integers
- Return type:
list(integer)
- Example:
>>> bv.get_data_refs_for_type_field('A', 0x8) [4203812] >>>
- get_data_refs_from(addr: int, length: int | None = None) Generator[int, None, None][source]
get_data_refs_fromreturns a list of virtual addresses referenced by the addressaddr. Optionally specifying a length. Whenlengthis setget_data_refs_fromreturns the data referenced in the rangeaddr-addr``+``length. This function returns both autoanalysis (“auto”) and user-specified (“user”) xrefs. To add a user-specified reference, seeadd_user_data_ref. Also, note there existsget_data_refs.
- get_data_refs_from_for_type_field(name: _types.QualifiedNameType, offset: int, max_items: int | None = None) List[int][source]
get_data_refs_from_for_type_fieldreturns a list of virtual addresses of data which are referenced by the typename.Only data referenced by structures with the
__data_var_refsattribute are included.- Parameters:
name (QualifiedName) – name of type to query for references
offset (int) – offset of the field, relative to the type
max_items (int) – optional maximum number of references to fetch
- Returns:
list of integers
- Return type:
list(integer)
- Example:
>>> bv.get_data_refs_from_for_type_field('A', 0x8) [4203812] >>>
- get_data_var_at(addr: int) DataVariable | None[source]
get_data_var_atreturns the data type at a given virtual address.- Parameters:
addr (int) – virtual address to get the data type from
- Returns:
returns the DataVariable at the given virtual address, None on error
- Return type:
- Example:
>>> t = bv.parse_type_string("int foo") >>> bv.define_data_var(bv.entry_point, t[0]) >>> bv.get_data_var_at(bv.entry_point) <var 0x100001174: int32_t>
- get_data_variable_parent_components(data_variable: DataVariable) List[Component][source]
- Parameters:
data_variable (DataVariable) –
- Return type:
- get_disassembly(addr: int, arch: Architecture | None = None) str | None[source]
get_disassemblysimple helper function for printing disassembly of a given address- Parameters:
addr (int) – virtual address of instruction
arch (Architecture) – optional Architecture,
self.archis used if this parameter is None
- Returns:
a str representation of the instruction at virtual address
addror None- Return type:
str or None
- Example:
>>> bv.get_disassembly(bv.entry_point) 'push ebp' >>>
Note
This API is very simplistic and only returns text. See
disassembly_textand instructions for more capable APIs.
- get_entropy(addr: int, length: int, block_size: int = 0) List[float][source]
get_entropyreturns the shannon entropy given the startaddr,lengthin bytes, and optionally inblock_sizechunks.
- get_expression_parser_magic_value(name: str) int | None[source]
Get the value of an expression parser magic value
If the queried magic value exists, the function returns true and the magic value is returned in value. If the queried magic value does not exist, the function returns None.
- get_external_libraries() List[ExternalLibrary][source]
Get a list of all ExternalLibrary in this BinaryView
- Returns:
A list of ExternalLibraries in this BinaryView
- Return type:
- get_external_library(name: str) ExternalLibrary | None[source]
Get an ExternalLibrary in this BinaryView by name
- Parameters:
name (str) – Name of the external library
- Returns:
An ExternalLibrary with the given name, or None
- Return type:
ExternalLibrary | None
- get_external_location(source_symbol: CoreSymbol) ExternalLocation | None[source]
Get the ExternalLocation with the given source symbol in this BinaryView
- Parameters:
source_symbol (CoreSymbol) – The source symbol of the ExternalLocation
- Returns:
An ExternalLocation with the given source symbol, or None
- Return type:
ExternalLocation | None
- get_external_locations() List[ExternalLocation][source]
Get a list of ExternalLocations in this BinaryView
- Returns:
A list of ExternalLocations in this BinaryView
- Return type:
- get_function_analysis_update_disabled() bool[source]
Returns True when functions are prevented from being marked as updates required, False otherwise. :return:
- Return type:
- get_function_at(addr: int, plat: Platform | None = None) Function | None[source]
get_function_atgets a Function object for the function that starts at virtual addressaddr:- Parameters:
- Returns:
returns a Function object or None for the function at the virtual address provided
- Return type:
- Example:
>>> bv.get_function_at(bv.entry_point) <func: x86_64@0x100001174> >>>
- get_functions_at(addr: int) List[Function][source]
get_functions_atget a list ofFunctionobjects (one for each valid platform) that start at the given virtual address. Binary Ninja does not limit the number of platforms in a given file thus there may be multiple functions defined from different architectures at the same location. This API allows you to query all of valid platforms.You may also be interested in
get_functions_containingwhich is useful for requesting all function that contain a given address
- get_functions_by_name(name: str, plat: Platform | None = None, ordered_filter: List[SymbolType] | None = None) List[Function][source]
get_functions_by_namereturns a list ofFunctionobjects function with aSymbolofname.- Parameters:
name (str) – name of the functions
plat (Platform) – (optional) platform
ordered_filter (list(SymbolType)) – (optional) an ordered filter based on SymbolType
- Returns:
returns a list of
Functionobjects or an empty list- Return type:
- Example:
>>> bv.get_functions_by_name("main") [<func: x86_64@0x1587>] >>>
- get_functions_containing(addr: int, plat: Platform | None = None) List[Function][source]
get_functions_containingreturns a list ofFunctionobjects which contain the given address.
- get_incoming_direct_type_references(name: _types.QualifiedNameType) List[_types.QualifiedName][source]
- Parameters:
name (_types.QualifiedNameType) –
- Return type:
List[_types.QualifiedName]
- get_incoming_recursive_type_references(names: _types.QualifiedNameType | List[_types.QualifiedNameType]) List[_types.QualifiedName][source]
- get_instruction_length(addr: int, arch: Architecture | None = None) int[source]
get_instruction_lengthreturns the number of bytes in the instruction of Architecturearchat the virtual addressaddr- Parameters:
addr (int) – virtual address of the instruction query
arch (Architecture) – (optional) the architecture of the instructions if different from the default
- Returns:
Number of bytes in instruction
- Return type:
- Example:
>>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>> bv.get_instruction_length(0x100012f1) 2L >>>
- get_linear_disassembly(settings: DisassemblySettings | None = None) Iterator[LinearDisassemblyLine][source]
get_linear_disassemblygets an iterator for all lines in the linear disassembly of the view for the given disassembly settings.Note
linear_disassembly doesn’t just return disassembly; it will return a single line from the linear view, and thus will contain both data views, and disassembly.
Warning: In order to get deterministic output, the WaitForIL DisassemblyOption should be set to True.
- Parameters:
settings (DisassemblySettings) – instance specifying the desired output formatting. Defaults to None which will use default settings.
- Returns:
An iterator containing formatted disassembly lines.
- Return type:
LinearDisassemblyIterator
- Example:
>>> settings = DisassemblySettings() >>> lines = bv.get_linear_disassembly(settings) >>> for line in lines: ... print(line) ... break ... cf fa ed fe 07 00 00 01 ........
- get_linear_disassembly_position_at(addr: int, settings: DisassemblySettings | None = None) LinearViewCursor[source]
get_linear_disassembly_position_atinstantiates aLinearViewCursorobject for use inget_previous_linear_disassembly_linesorget_next_linear_disassembly_lines.- Parameters:
addr (int) – virtual address of linear disassembly position
settings (DisassemblySettings) – an instantiated
DisassemblySettingsobject, defaults to None which will use default settings
- Returns:
An instantiated
LinearViewCursorobject for the provided virtual address- Return type:
- Example:
>>> settings = DisassemblySettings() >>> pos = bv.get_linear_disassembly_position_at(0x1000149f, settings) >>> lines = bv.get_previous_linear_disassembly_lines(pos) >>> lines [<0x1000149a: pop esi>, <0x1000149b: pop ebp>, <0x1000149c: retn 0xc>, <0x1000149f: >]
- get_load_settings(type_name: str) Settings | None[source]
get_load_settingsretrieve aSettingsobject which defines the load settings for the givenBinaryViewTypetype_name- Parameters:
type_name (str) – the
BinaryViewTypename- Returns:
the load settings
- Return type:
Settings, orNone
- get_load_settings_type_names() List[str][source]
get_load_settings_type_namesretrieve a listBinaryViewTypenames for which load settings exist in thisBinaryViewcontext- Returns:
list of
BinaryViewTypenames- Return type:
- get_modification(addr: int, length: int | None = None) List[ModificationStatus][source]
get_modificationreturns the modified bytes of up tolengthbytes from virtual addressaddr, or iflengthis None returns the ModificationStatus.- Parameters:
- Returns:
List of ModificationStatus values for each byte in range
- Return type:
List[ModificationStatus]
- get_next_basic_block_start_after(addr: int) int[source]
get_next_basic_block_start_afterreturns the virtual address of the BasicBlock that occurs after the virtualaddress
addr
- get_next_data_after(addr: int) int[source]
get_next_data_afterretrieves the virtual address of the next non-code byte.
- get_next_data_var_after(addr: int) DataVariable | None[source]
get_next_data_var_afterretrieves the nextDataVariable, or None.- Parameters:
addr (int) – the virtual address to start looking from.
- Returns:
the next
DataVariable- Return type:
- Example:
>>> bv.get_next_data_var_after(0x10000000) <var 0x1000003c: int32_t> >>>
- get_next_data_var_start_after(addr: int) int[source]
get_next_data_var_start_afterretrieves the next virtual address of the nextDataVariable- Parameters:
addr (int) – the virtual address to start looking from.
- Returns:
the virtual address of the next
DataVariable- Return type:
- Example:
>>> hex(bv.get_next_data_var_start_after(0x10000000)) '0x1000003cL' >>> bv.get_data_var_at(0x1000003c) <var 0x1000003c: int32_t> >>>
- get_next_function_start_after(addr: int) int[source]
get_next_function_start_afterreturns the virtual address of the Function that occurs after the virtual addressaddr- Parameters:
addr (int) – the virtual address to start looking from.
- Returns:
the virtual address of the next Function
- Return type:
- Example:
>>> bv.get_next_function_start_after(bv.entry_point) 268441061L >>> hex(bv.get_next_function_start_after(bv.entry_point)) '0x100015e5L' >>> hex(bv.get_next_function_start_after(0x100015e5)) '0x10001629L' >>> hex(bv.get_next_function_start_after(0x10001629)) '0x1000165eL' >>>
- get_next_linear_disassembly_lines(pos: LinearViewCursor) List[LinearDisassemblyLine][source]
get_next_linear_disassembly_linesretrieves a list ofLinearDisassemblyLineobjects for the next disassembly lines, and updates the LinearViewCursor passed in. This function can be called repeatedly to get more lines of linear disassembly.- Parameters:
pos (LinearViewCursor) – Position to start retrieving linear disassembly lines from
- Returns:
a list of
LinearDisassemblyLineobjects for the next lines.- Example:
>>> settings = DisassemblySettings() >>> pos = bv.get_linear_disassembly_position_at(0x10001483, settings) >>> bv.get_next_linear_disassembly_lines(pos) [<0x10001483: xor eax, eax {0x0}>, <0x10001485: inc eax {0x1}>, ... , <0x10001488: >] >>> bv.get_next_linear_disassembly_lines(pos) [<0x10001488: push dword [ebp+0x10 {arg_c}]>, ... , <0x1000149a: >] >>>
- Return type:
- get_next_valid_offset(addr: int) int[source]
get_next_valid_offsetreturns the next valid offset in the BinaryView starting from the given virtual addressaddr.
- get_outgoing_direct_type_references(name: _types.QualifiedNameType) List[_types.QualifiedName][source]
- Parameters:
name (_types.QualifiedNameType) –
- Return type:
List[_types.QualifiedName]
- get_outgoing_recursive_type_references(names: _types.QualifiedNameType | List[_types.QualifiedNameType]) List[_types.QualifiedName][source]
- get_previous_basic_block_end_before(addr: int) int[source]
get_previous_basic_block_end_before- Parameters:
addr (int) – the virtual address to start looking from.
- Returns:
the virtual address of the previous BasicBlock end
- Return type:
- Example:
>>> hex(bv.entry_point) '0x1000149fL' >>> hex(bv.get_next_basic_block_start_after(bv.entry_point)) '0x100014a8L' >>> hex(bv.get_previous_basic_block_end_before(0x100014a8)) '0x100014a8L'
- get_previous_basic_block_start_before(addr: int) int[source]
get_previous_basic_block_start_beforereturns the virtual address of the BasicBlock that occurs prior to the provided virtual address- Parameters:
addr (int) – the virtual address to start looking from.
- Returns:
the virtual address of the previous BasicBlock
- Return type:
- Example:
>>> hex(bv.entry_point) '0x1000149fL' >>> hex(bv.get_next_basic_block_start_after(bv.entry_point)) '0x100014a8L' >>> hex(bv.get_previous_basic_block_start_before(0x100014a8)) '0x1000149fL' >>>
- get_previous_data_var_before(addr: int) DataVariable | None[source]
get_previous_data_var_beforeretrieves the previousDataVariable, or None.- Parameters:
addr (int) – the virtual address to start looking from.
- Returns:
the previous
DataVariable- Return type:
- Example:
>>> bv.get_previous_data_var_before(0x1000003c) <var 0x10000000: int16_t> >>>
- get_previous_data_var_start_before(addr: int) int[source]
get_previous_data_var_start_before- Parameters:
addr (int) – the virtual address to start looking from.
- Returns:
the virtual address of the previous
DataVariable- Return type:
- Example:
>>> hex(bv.get_previous_data_var_start_before(0x1000003c)) '0x10000000L' >>> bv.get_data_var_at(0x10000000) <var 0x10000000: int16_t> >>>
- get_previous_function_start_before(addr: int) int[source]
get_previous_function_start_beforereturns the virtual address of the Function that occurs prior to the virtual address provided- Parameters:
addr (int) – the virtual address to start looking from.
- Returns:
the virtual address of the previous Function
- Return type:
- Example:
>>> hex(bv.entry_point) '0x1000149fL' >>> hex(bv.get_next_function_start_after(bv.entry_point)) '0x100015e5L' >>> hex(bv.get_previous_function_start_before(0x100015e5)) '0x1000149fL' >>>
- get_previous_linear_disassembly_lines(pos: LinearViewCursor) List[LinearDisassemblyLine][source]
get_previous_linear_disassembly_linesretrieves a list ofLinearDisassemblyLineobjects for the previous disassembly lines, and updates the LinearViewCursor passed in. This function can be called repeatedly to get more lines of linear disassembly.- Parameters:
pos (LinearViewCursor) – Position to start retrieving linear disassembly lines from
- Returns:
a list of
LinearDisassemblyLineobjects for the previous lines.- Example:
>>> settings = DisassemblySettings() >>> pos = bv.get_linear_disassembly_position_at(0x1000149a, settings) >>> bv.get_previous_linear_disassembly_lines(pos) [<0x10001488: push dword [ebp+0x10 {arg_c}]>, ... , <0x1000149a: >] >>> bv.get_previous_linear_disassembly_lines(pos) [<0x10001483: xor eax, eax {0x0}>, ... , <0x10001488: >]
- Return type:
- get_recent_basic_block_at(addr: int) BasicBlock | None[source]
- Parameters:
addr (int) –
- Return type:
BasicBlock | None
- get_segment_at(addr: int) Segment | None[source]
get_segment_atgets the Segment a given virtual address is located in
- get_sizes_referenced(name: _types.QualifiedNameType, offset: int) List[int][source]
get_sizes_referencedreturns a list of access sizes to the specified type.- Parameters:
name (QualifiedName) – name of type to query for references
offset (int) – offset of the field
- Returns:
a list of sizes of the accesses to it.
- Return type:
- Example:
>>> bv.get_sizes_referenced('B', 16) [1, 8] >>>
- get_string_at(addr: int, partial: bool = False) StringReference | None[source]
get_string_atreturns the string that falls on given virtual address.Note
This returns discovered strings and is therefore governed by analysis.limits.minStringLength and other settings. For an alternative API that simply returns any potential c-string at a given location, use
get_ascii_string_at.- Parameters:
- Returns:
returns the StringReference at the given virtual address, otherwise None.
- Return type:
- Example:
>>> bv.get_string_at(0x40302f) <StringType.AsciiString: 0x403028, len 0x12>
- get_strings(start: int | None = None, length: int | None = None) List[StringReference][source]
get_stringsreturns a list of strings defined in the binary in the optional virtual address range:start-(start+length)Note that this API will only return strings that have been identified by the string-analysis and thus governed by the minimum and maximum length settings and unrelated to the type system.
- Parameters:
- Returns:
a list of all strings or a list of strings defined between
startandstart+length- Return type:
- Example:
>>> bv.get_strings(0x1000004d, 1) [<AsciiString: 0x1000004d, len 0x2c>] >>>
- get_symbol_at(addr: int, namespace: _types.NameSpaceType = None) _types.CoreSymbol | None[source]
get_symbol_atreturns the Symbol at the provided virtual address.- Parameters:
addr (int) – virtual address to query for symbol
namespace (_types.NameSpaceType) – (optional) the namespace of the symbols to retrieve
- Returns:
CoreSymbol for the given virtual address
- Return type:
- Example:
>>> bv.get_symbol_at(bv.entry_point) <FunctionSymbol: "_start" @ 0x100001174> >>>
- get_symbol_by_raw_name(name: str, namespace: _types.NameSpaceType = None) _types.CoreSymbol | None[source]
get_symbol_by_raw_nameretrieves a Symbol object for the given raw (mangled) name.- Parameters:
name (str) – raw (mangled) name of Symbol to be retrieved
namespace (_types.NameSpaceType) – (optional) the namespace to search for the given symbol
- Returns:
CoreSymbol object corresponding to the provided raw name
- Return type:
- Example:
>>> bv.get_symbol_by_raw_name('?testf@Foobar@@SA?AW4foo@1@W421@@Z') <FunctionSymbol: "public: static enum Foobar::foo __cdecl Foobar::testf(enum Foobar::foo)" @ 0x10001100> >>>
- get_symbols(start: int | None = None, length: int | None = None, namespace: _types.NameSpaceType = None) List[_types.CoreSymbol][source]
get_symbolsretrieves the list of all Symbol objects in the optionally provided range.- Parameters:
- Returns:
list of all Symbol objects, or those Symbol objects in the range of
start-start+length- Return type:
- Example:
>>> bv.get_symbols(0x1000200c, 1) [<ImportAddressSymbol: "KERNEL32!IsProcessorFeaturePresent" @ 0x1000200c>] >>>
- get_symbols_by_name(name: str, namespace: _types.NameSpaceType = None, ordered_filter: List[SymbolType] | None = None) List[_types.CoreSymbol][source]
get_symbols_by_nameretrieves a list of Symbol objects for the given symbol name and ordered filter- Parameters:
name (str) – name of Symbol object to be retrieved
namespace (_types.NameSpaceType) – (optional) the namespace to search for the given symbol
namespace – (optional) the namespace to search for the given symbol
ordered_filter (List[SymbolType] | None) – (optional) an ordered filter based on SymbolType
- Returns:
Symbol object corresponding to the provided name
- Return type:
- Example:
>>> bv.get_symbols_by_name('?testf@Foobar@@SA?AW4foo@1@W421@@Z') [<FunctionSymbol: "public: static enum Foobar::foo __cdecl Foobar::testf(enum Foobar::foo)" @ 0x10001100>] >>>
- get_symbols_by_raw_name(name: str, namespace: _types.NameSpaceType = None) List[_types.CoreSymbol][source]
- get_symbols_of_type(sym_type: SymbolType, start: int | None = None, length: int | None = None, namespace: _types.NameSpaceType = None) List[_types.CoreSymbol][source]
get_symbols_of_typeretrieves a list of allSymbolobjects of the provided symbol type in the optionallyprovided range.
- Parameters:
sym_type (SymbolType) – A Symbol type:
SymbolTypestart (int | None) – optional start virtual address
length (int | None) – optional length
namespace (_types.NameSpaceType) –
- Returns:
list of all
Symbolobjects of typesym_type, or thoseSymbolobjects in the range ofstart-start+length- Return type:
- Example:
>>> bv.get_symbols_of_type(SymbolType.ImportAddressSymbol, 0x10002028, 1) [<ImportAddressSymbol: "KERNEL32!GetCurrentThreadId" @ 0x10002028>] >>>
- get_tags(auto: bool | None = None) List[Tuple[int, Tag]][source]
tagsgets a list of all dataTagobjects in the view. Tags are returned as a list of (address,Tag) pairs.
- get_tags_at(addr: int, auto: bool | None = None) List[Tag][source]
get_data_tags_atgets a list ofTagobjects for a data address.
- get_tags_in_range(address_range: AddressRange, auto: bool | None = None) List[Tuple[int, Tag]][source]
get_data_tags_in_rangegets a list of all dataTagobjects in a given range. Range is inclusive at the start, exclusive at the end.- Parameters:
address_range (AddressRange) – address range from which to get tags
auto (bool) – If None, gets all tags, if True, gets auto tags, if False, gets auto tags
- Returns:
A list of (address, data tag) tuples
- Return type:
- get_type_archive(id: str) TypeArchive | None[source]
Look up a connected archive by its id
- Parameters:
id (str) – Id of archive
- Returns:
Archive, if one exists with that id. Otherwise None
- Return type:
TypeArchive | None
- get_type_archive_path(id: str) str | None[source]
Look up the path for an attached (but not necessarily connected) type archive by its id
- get_type_archives_for_type_name(name: _types.QualifiedNameType) List[Tuple[TypeArchive, str]][source]
Get a list of all connected type archives that have a given type name
- Returns:
(archive, archive type id) for all archives
- Parameters:
name (_types.QualifiedNameType) –
- Return type:
List[Tuple[TypeArchive, str]]
- get_type_by_id(id: str) Type | None[source]
get_type_by_idreturns the defined type whose unique identifier corresponds with the providedid- Parameters:
id (str) – Unique identifier to lookup
- Returns:
A
Typeor None if the type does not exist- Return type:
Type or None
- Example:
>>> type, name = bv.parse_type_string("int foo") >>> type_id = Type.generate_auto_type_id("source", name) >>> bv.define_type(type_id, name, type) >>> bv.get_type_by_id(type_id) <type: int32_t> >>>
- get_type_by_name(name: _types.QualifiedNameType) _types.Type | None[source]
get_type_by_namereturns the defined type whose name corresponds with the providedname- Parameters:
name (QualifiedName) – Type name to lookup
- Returns:
A
Typeor None if the type does not exist- Return type:
Type or None
- Example:
>>> type, name = bv.parse_type_string("int foo") >>> bv.define_user_type(name, type) >>> bv.get_type_by_name(name) <type: int32_t> >>>
- get_type_id(name: _types.QualifiedNameType) str[source]
get_type_idreturns the unique identifier of the defined type whose name corresponds with the providedname- Parameters:
name (QualifiedName) – Type name to lookup
- Returns:
The unique identifier of the type
- Return type:
- Example:
>>> type, name = bv.parse_type_string("int foo") >>> type_id = Type.generate_auto_type_id("source", name) >>> registered_name = bv.define_type(type_id, name, type) >>> bv.get_type_id(registered_name) == type_id True >>>
- get_type_library(name: str) TypeLibrary | None[source]
get_type_libraryreturns the TypeLibrary- Parameters:
name (str) – Library name to lookup
- Returns:
The Type Library object, if any
- Return type:
TypeLibrary or None
- Example:
- get_type_name_by_id(id: str) QualifiedName | None[source]
get_type_name_by_idreturns the defined type name whose unique identifier corresponds with the providedid- Parameters:
id (str) – Unique identifier to lookup
- Returns:
A QualifiedName or None if the type does not exist
- Return type:
QualifiedName or None
- Example:
>>> type, name = bv.parse_type_string("int foo") >>> type_id = Type.generate_auto_type_id("source", name) >>> bv.define_type(type_id, name, type) 'foo' >>> bv.get_type_name_by_id(type_id) 'foo' >>>
- get_type_refs_for_type(name: _types.QualifiedNameType, max_items: int | None = None) List[_types.TypeReferenceSource][source]
get_type_refs_for_typereturns a list of TypeReferenceSource objects (xrefs or cross-references) that reference the provided QualifiedName.- Parameters:
name (QualifiedName) – name of type to query for references
max_items (int) – optional maximum number of references to fetch
- Returns:
List of references for the given type
- Return type:
- Example:
>>> bv.get_type_refs_for_type('A') ['<type D, offset 0x8, direct>', '<type C, offset 0x10, indirect>'] >>>
- get_type_refs_for_type_field(name: _types.QualifiedNameType, offset: int, max_items: int | None = None) List[_types.TypeReferenceSource][source]
get_type_refs_for_typereturns a list of TypeReferenceSource objects (xrefs or cross-references) that reference the provided type field.- Parameters:
name (QualifiedName) – name of type to query for references
offset (int) – offset of the field, relative to the type
max_items (int) – optional maximum number of references to fetch
- Returns:
List of references for the given type
- Return type:
- Example:
>>> bv.get_type_refs_for_type_field('A', 0x8) ['<type D, offset 0x8, direct>', '<type C, offset 0x10, indirect>'] >>>
- get_types_referenced(name: QualifiedName, offset: int) List[Type][source]
get_types_referencedreturns a list of types related to the type field access.- Parameters:
name (QualifiedName) – name of type to query for references
offset (int) – offset of the field
- Returns:
a list of types related to the type field access.
- Return type:
- Example:
>>> bv.get_types_referenced('B', 0x10) [<type: bool>, <type: char, 0% confidence>] >>>
- get_view_of_type(name: str) BinaryView | None[source]
get_view_of_typereturns the BinaryView associated with the provided name if it exists.- Parameters:
name (str) – Name of the view to be retrieved
- Returns:
BinaryView object associated with the provided name or None on failure
- Return type:
BinaryView or None
- has_initial_analysis() bool[source]
has_initial_analysischeck for the presence of an initial analysis in this BinaryView.- Returns:
True if the BinaryView has a valid initial analysis, False otherwise
- Return type:
- hlil_functions(preload_limit: int | None = None, function_generator: Generator[Function, None, None] | None = None) Generator[HighLevelILFunction, None, None][source]
Generates a list of il functions. This method should be used instead of ‘functions’ property if HLIL is needed and performance is a concern.
- Parameters:
- Return type:
Generator[HighLevelILFunction, None, None]
- import_library_object(name: str, lib: TypeLibrary | None = None) Tuple[TypeLibrary, Type] | None[source]
import_library_objectrecursively imports an object from the specified type library, or, if no library was explicitly provided, the first type library associated with the currentBinaryViewthat provides the name requested.This may have the impact of loading other type libraries as dependencies on other type libraries are lazily resolved when references to types provided by them are first encountered.
Note
If you are implementing a custom BinaryView and use this method to import object types, you should then call
record_imported_objectwith the details of where the object is located.- Parameters:
name (QualifiedName) –
lib (TypeLibrary) –
- Returns:
the object type, with any interior NamedTypeReferences renamed as necessary to be appropriate for the current view
- Return type:
- import_library_type(name: str, lib: TypeLibrary | None = None) Type | None[source]
import_library_typerecursively imports a type from the specified type library, or, if no library was explicitly provided, the first type library associated with the currentBinaryViewthat provides the name requested.This may have the impact of loading other type libraries as dependencies on other type libraries are lazily resolved when references to types provided by them are first encountered.
Note that the name actually inserted into the view may not match the name as it exists in the type library in the event of a name conflict. To aid in this, the
Typeobject returned is a NamedTypeReference to the deconflicted name used.- Parameters:
name (QualifiedName) –
lib (TypeLibrary) –
- Returns:
a NamedTypeReference to the type, taking into account any renaming performed
- Return type:
- import_type_by_guid(guid: str | UUID) Type | None[source]
import_type_by_guidrecursively imports a type interface given its GUID.Note
To support this type of lookup a type library must have contain a metadata key called “type_guids” which is a map Dict[string_guid, string_type_name] or Dict[string_guid, Tuple[string_type_name, type_library_name]]
- insert(addr: int, data: bytes) int[source]
insertinserts the bytes indatato the virtual addressaddr.
- static internal_namespace() NameSpace[source]
Internal namespace for the current BinaryView
- Return type:
- invert_branch(addr: int, arch: Architecture | None = None) bool[source]
invert_branchconvert the branch instruction of architecturearchat the virtual addressaddrto the inverse branch.Note
This API performs a binary patch, analysis may need to be updated afterward. Additionally the binary file must be saved in order to preserve the changes made.
- Parameters:
addr (int) – virtual address of the instruction to be modified
arch (Architecture) – (optional) the architecture of the instructions if different from the default
- Returns:
True on success, False on failure.
- Return type:
- Example:
>>> bv.get_disassembly(0x1000130e) 'je 0x10001317' >>> bv.invert_branch(0x1000130e) True >>> >>> bv.get_disassembly(0x1000130e) 'jne 0x10001317' >>>
- is_always_branch_patch_available(addr: int, arch: Architecture | None = None) bool[source]
is_always_branch_patch_availablequeries the architecture plugin to determine if the instruction ataddrcan be made to always branch. The actual logic of which is implemented in theperform_is_always_branch_patch_availablein the corresponding architecture.- Parameters:
addr (int) – the virtual address of the instruction to be patched
arch (Architecture) – (optional) the architecture for the current view
- Returns:
True if the instruction can be patched, False otherwise
- Return type:
- Example:
>>> bv.get_disassembly(0x100012ed) 'test eax, eax' >>> bv.is_always_branch_patch_available(0x100012ed) False >>> bv.get_disassembly(0x100012ef) 'jg 0x100012f5' >>> bv.is_always_branch_patch_available(0x100012ef) True >>>
- is_invert_branch_patch_available(addr: int, arch: Architecture | None = None) bool[source]
is_invert_branch_patch_availablequeries the architecture plugin to determine if the instruction ataddris a branch that can be inverted. The actual logic of which is implemented in theperform_is_invert_branch_patch_availablein the corresponding architecture.- Parameters:
addr (int) – the virtual address of the instruction to be patched
arch (Architecture) – (optional) the architecture of the instructions if different from the default
- Returns:
True if the instruction can be patched, False otherwise
- Return type:
- Example:
>>> bv.get_disassembly(0x100012ed) 'test eax, eax' >>> bv.is_invert_branch_patch_available(0x100012ed) False >>> bv.get_disassembly(0x100012ef) 'jg 0x100012f5' >>> bv.is_invert_branch_patch_available(0x100012ef) True >>>
- is_never_branch_patch_available(addr: int, arch: Architecture | None = None) bool[source]
is_never_branch_patch_availablequeries the architecture plugin to determine if the instruction at the instruction ataddrcan be made to never branch. The actual logic of which is implemented in theperform_is_never_branch_patch_availablein the corresponding architecture.- Parameters:
addr (int) – the virtual address of the instruction to be patched
arch (Architecture) – (optional) the architecture of the instructions if different from the default
- Returns:
True if the instruction can be patched, False otherwise
- Return type:
- Example:
>>> bv.get_disassembly(0x100012ed) 'test eax, eax' >>> bv.is_never_branch_patch_available(0x100012ed) False >>> bv.get_disassembly(0x100012ef) 'jg 0x100012f5' >>> bv.is_never_branch_patch_available(0x100012ef) True >>>
- is_offset_code_semantics(addr: int) bool[source]
is_offset_code_semanticschecks if a virtual addressaddris semantically valid for code.
- is_offset_executable(addr: int) bool[source]
is_offset_executablechecks if a virtual addressaddris valid for executing.
- is_offset_extern_semantics(addr: int) bool[source]
is_offset_extern_semanticschecks if a virtual addressaddris semantically valid for external references.
- is_offset_readable(addr: int) bool[source]
is_offset_readablechecks if a virtual addressaddris valid for reading.
- is_offset_writable(addr: int) bool[source]
is_offset_writablechecks if a virtual addressaddris valid for writing.
- is_offset_writable_semantics(addr: int) bool[source]
is_offset_writable_semanticschecks if a virtual addressaddris semantically writable. Some sections may have writable permissions for linking purposes but can be treated as read-only for the purposes of analysis.
- is_skip_and_return_value_patch_available(addr: int, arch: Architecture | None = None) bool[source]
is_skip_and_return_value_patch_availablequeries the architecture plugin to determine if the instruction ataddris similar to an x86 “call” instruction which can be made to return a value. The actual logic of which is implemented in theperform_is_skip_and_return_value_patch_availablein the corresponding architecture.- Parameters:
addr (int) – the virtual address of the instruction to be patched
arch (Architecture) – (optional) the architecture of the instructions if different from the default
- Returns:
True if the instruction can be patched, False otherwise
- Return type:
- Example:
>>> bv.get_disassembly(0x100012f6) 'mov dword [0x10003020], eax' >>> bv.is_skip_and_return_value_patch_available(0x100012f6) False >>> bv.get_disassembly(0x100012fb) 'call 0x10001629' >>> bv.is_skip_and_return_value_patch_available(0x100012fb) True >>>
- is_skip_and_return_zero_patch_available(addr: int, arch: Architecture | None = None) bool[source]
is_skip_and_return_zero_patch_availablequeries the architecture plugin to determine if the instruction ataddris similar to an x86 “call” instruction which can be made to return zero. The actual logic of which is implemented in theperform_is_skip_and_return_zero_patch_availablein the corresponding architecture.- Parameters:
addr (int) – the virtual address of the instruction to be patched
arch (Architecture) – (optional) the architecture of the instructions if different from the default
- Returns:
True if the instruction can be patched, False otherwise
- Return type:
- Example:
>>> bv.get_disassembly(0x100012f6) 'mov dword [0x10003020], eax' >>> bv.is_skip_and_return_zero_patch_available(0x100012f6) False >>> bv.get_disassembly(0x100012fb) 'call 0x10001629' >>> bv.is_skip_and_return_zero_patch_available(0x100012fb) True >>>
- is_type_auto_defined(name: _types.QualifiedNameType) bool[source]
is_type_auto_definedqueries the user type list of name. If name is not in the user type list then the name is considered an auto type.- Parameters:
name (QualifiedName) – Name of type to query
- Returns:
True if the type is not a user type. False if the type is a user type.
- Example:
>>> bv.is_type_auto_defined("foo") True >>> bv.define_user_type("foo", bv.parse_type_string("struct {int x,y;}")[0]) >>> bv.is_type_auto_defined("foo") False >>>
- Return type:
- static load(source: str | bytes | bytearray | DataBuffer | PathLike | BinaryView | ProjectFile, update_analysis: bool = True, progress_func: Callable[[int, int], bool] | None = None, options: Mapping[str, Any] = {}) BinaryView | None[source]
loadopens, generates default load options (which are overridable), and returns the first availableBinaryView. If noBinaryViewTypeis available, then aMappedBinaryViewTypeis used to load theBinaryViewwith the specified load options. TheMappedview type attempts to auto-detect the architecture of the file during initialization. If no architecture is detected or specified in the load options, then theMappedview type fails to initialize and returnsNone.Note
Although general container file support is not complete, support for Universal archives exists. It’s possible to control the architecture preference with the ‘files.universal.architecturePreference’ setting. This setting is scoped to SettingsUserScope and can be modified as follows
>>> Settings().set_string_list("files.universal.architecturePreference", ["arm64"])
It’s also possible to override the ‘files.universal.architecturePreference’ user setting by specifying it directly with
load. This specific usage of this setting is experimental and may change in the future>>> bv = binaryninja.load('/bin/ls', options={'files.universal.architecturePreference': ['arm64']})
Warning
The recommended code pattern for opening a BinaryView is to use the
loadAPI as a context manager likewith load('/bin/ls') as bv:which will automatically clean up when done with the view. If using this API directly you will need to call bv.file.close() before the BinaryView leaves scope to ensure the reference is properly removed and prevents memory leaks.- Parameters:
source (str | bytes | bytearray | DataBuffer | PathLike | BinaryView | ProjectFile) – path to file/bndb, raw bytes, or raw view to load
update_analysis (bool) – whether or not to run
update_analysis_and_waitafter opening aBinaryView, defaults toTrueprogress_func (callback) – optional function to be called with the current progress and total count
options (dict) – a dictionary in the form {setting identifier string : object value}
source –
- Returns:
returns a
BinaryViewobject for the given filename orNone- Return type:
BinaryVieworNone- Example:
>>> binaryninja.load('/bin/ls', options={'loader.imageBase': 0xfffffff0000, 'loader.macho.processFunctionStarts' : False}) <BinaryView: '/bin/ls', start 0xfffffff0000, len 0xa290> >>>
- lookup_imported_object_library(addr: int, platform: Platform | None = None) Tuple[TypeLibrary, QualifiedName] | None[source]
lookup_imported_object_librarygives you details of which type library and name was used to determine the type of a symbol at a given address- Parameters:
- Returns:
A tuple of [TypeLibrary, QualifiedName] with the library and name used, or None if it was not imported
- Return type:
Tuple[TypeLibrary, QualifiedName]
- lookup_imported_type_library(name: _types.QualifiedNameType) Tuple[TypeLibrary, _types.QualifiedName] | None[source]
lookup_imported_type_librarygives you details of from which type library and name a given type in the analysis was imported.- Parameters:
name (_types.QualifiedNameType) – Name of type in analysis
- Returns:
A tuple of [TypeLibrary, QualifiedName] with the library and name used, or None if it was not imported
- Return type:
Optional[Tuple[TypeLibrary, QualifiedName]]
- lookup_imported_type_platform(name: _types.QualifiedNameType) Tuple[_platform.Platform, _types.QualifiedName] | None[source]
lookup_imported_type_platformgives you details of from which platform and name a given type in the analysis was imported.- Parameters:
name (_types.QualifiedNameType) – Name of type in analysis
- Returns:
A tuple of [Platform, QualifiedName] with the platform and name used, or None if it was not imported
- Return type:
Optional[Tuple[Platform, QualifiedName]]
- mlil_functions(preload_limit: int | None = None, function_generator: Generator[Function, None, None] | None = None) Generator[MediumLevelILFunction, None, None][source]
Generates a list of il functions. This method should be used instead of ‘functions’ property if MLIL is needed and performance is a concern.
- Parameters:
- Return type:
Generator[MediumLevelILFunction, None, None]
- navigate(view_name: str, offset: int) bool[source]
navigatenavigates the UI to the specified virtual address in the specified ViewThe View name is created by combining a View type (e.g. “Graph”) with a BinaryView type (e.g. “Mach-O”), separated by a colon, resulting in something like “Graph:Mach-O”.
- Parameters:
- Returns:
whether navigation succeeded
- Return type:
- Example:
>>> bv.navigate(bv.view, bv.start) True >>> bv.file.existing_views ['Mach-O', 'Raw'] >>> import binaryninjaui >>> [i.getName() for i in binaryninjaui.ViewType.getTypes()] ['Graph', 'Hex', 'Linear', 'Strings', 'Types', 'Triage', 'Bytes'] >>> bv.navigate('Graph:Mach-O', bv.entry_point) True
- never_branch(addr: int, arch: Architecture | None = None) bool[source]
never_branchconvert the branch instruction of architecturearchat the virtual addressaddrto a fall through.Note
This API performs a binary patch, analysis may need to be updated afterward. Additionally the binary file must be saved in order to preserve the changes made.
- Parameters:
addr (int) – virtual address of the instruction to be modified
arch (Architecture) – (optional) the architecture of the instructions if different from the default
- Returns:
True on success, False on failure.
- Return type:
- Example:
>>> bv.get_disassembly(0x1000130e) 'jne 0x10001317' >>> bv.never_branch(0x1000130e) True >>> bv.get_disassembly(0x1000130e) 'nop' >>>
- static new(data: bytes | bytearray | DataBuffer | None = None, file_metadata: FileMetadata | None = None) BinaryView | None[source]
newcreates a new, RawBinaryViewfor the provided data.- Parameters:
data (Union[
str,bytes,bytearray,DataBuffer,os.PathLike,BinaryView]) – path to file/bndb, raw bytes, or raw view to loadfile_metadata (
FileMetadata) – Optional FileMetadata object for this new view
- Returns:
returns a
BinaryViewobject for the given filename orNone- Return type:
BinaryVieworNone- Example:
>>> binaryninja.load('/bin/ls', options={'loader.imageBase': 0xfffffff0000, 'loader.macho.processFunctionStarts' : False}) <BinaryView: '/bin/ls', start 0xfffffff0000, len 0xa290> >>>
- static open(src, file_metadata=None) BinaryView | None[source]
- Return type:
BinaryView | None
- parse_expression(expression: str, here: int = 0) int[source]
Evaluates a string expression to an integer value.
The parser uses the following rules:
Symbols are defined by the lexer as
[A-Za-z0-9_:<>][A-Za-z0-9_:$\-<>]+or anything enclosed in either single or double quotesSymbols are everything in
bv.symbols, unnamed DataVariables (i.e.data_00005000), unnamed functions (i.e.sub_00005000), or section names (i.e..text)Numbers are defaulted to hexadecimal thus _printf + 10 is equivalent to printf + 0x10 If decimal numbers required use the decimal prefix.
Since numbers and symbols can be ambiguous its recommended that you prefix your numbers with the following:
0x- Hexadecimal0n- Decimal0- Octal
In the case of an ambiguous number/symbol (one with no prefix) for instance
12345we will first attempt to look up the string as a symbol, if a symbol is found its address is used, otherwise we attempt to convert it to a hexadecimal number.The following operations are valid:
+, -, \*, /, %, (), &, \|, ^, ~, ==, !=, >, <, >=, <=Comparison operators return 1 if the condition is true, 0 otherwise.
In addition to the above operators there are dereference operators similar to BNIL style IL:
[<expression>]- read the current address size at<expression>[<expression>].b- read the byte at<expression>[<expression>].w- read the word (2 bytes) at<expression>[<expression>].d- read the dword (4 bytes) at<expression>[<expression>].q- read the quadword (8 bytes) at<expression>
The
$here(or more succinctly:$) keyword can be used in calculations and is defined as thehereparameter, or the currently selected addressThe
$start/$endkeyword represents the address of the first/last bytes in the file respectivelyArbitrary magic values (name-value-pairs) can be added to the expression parser via the
add_expression_parser_magic_valueAPI. Notably, the debugger adds all register values into the expression parser so they can be used directly when navigating. The register values can be referenced like $rbp, $x0, etc. For more details, refer to the related debugger docs.
- parse_possiblevalueset(value: str, state: RegisterValueType, here: int = 0) PossibleValueSet[source]
Evaluates a string representation of a PossibleValueSet into an instance of the
PossibleValueSetvalue.Note
Values are evaluated based on the rules as specified for
parse_expressionAPI. This implies that aConstantValue [0x4000].dcan be provided given that 4 bytes can be read at0x4000. All constants are considered to be in hexadecimal form by default.- The parser uses the following rules:
ConstantValue -
<value>ConstantPointerValue -
<value>StackFrameOffset -
<value>SignedRangeValue -
<value>:<value>:<value>{,<value>:<value>:<value>}*(Multiple ValueRanges can be provided by separating them by commas)UnsignedRangeValue -
<value>:<value>:<value>{,<value>:<value>:<value>}*(Multiple ValueRanges can be provided by separating them by commas)InSetOfValues -
<value>{,<value>}*NotInSetOfValues -
<value>{,<value>}*
- Parameters:
value (str) – PossibleValueSet value to be parsed
state (RegisterValueType) – State for which the value is to be parsed
here (int) – (optional) Base address for relative expressions, defaults to zero
- Return type:
- Example:
>>> psv_c = bv.parse_possiblevalueset("400", RegisterValueType.ConstantValue) >>> psv_c <const 0x400> >>> psv_ur = bv.parse_possiblevalueset("1:10:1", RegisterValueType.UnsignedRangeValue) >>> psv_ur <unsigned ranges: [<range: 0x1 to 0x10>]> >>> psv_is = bv.parse_possiblevalueset("1,2,3", RegisterValueType.InSetOfValues) >>> psv_is <in set([0x1, 0x2, 0x3])> >>>
- parse_type_string(text: str, import_dependencies: bool = True) Tuple[Type, QualifiedName][source]
parse_type_stringparses string containing C into a single typeType. In contrast to theparse_types_from_sourceorparse_types_from_source_file,parse_type_stringcan only load a single type, though it can take advantage of existing type information in the binary view, while those two APIs do not.- Parameters:
- Returns:
A tuple of a
Typeand type name- Return type:
- Example:
>>> bv.parse_type_string("int foo") (<type: int32_t>, 'foo') >>>
- parse_types_from_string(text: str, options: List[str] | None = None, include_dirs: List[str] | None = None, import_dependencies: bool = True) BasicTypeParserResult[source]
parse_types_from_stringparses string containing C into aBasicTypeParserResultobjects. This API unlike theparse_types_from_sourceallows the reference of types already defined in the BinaryView.- Parameters:
text (str) – C source code string of types, variables, and function types, to create
options (List[str] | None) – Optional list of string options to be passed into the type parser
include_dirs (List[str] | None) – Optional list of header search directories
import_dependencies (bool) – If Type Library types should be imported during parsing
- Returns:
BasicTypeParserResult(a SyntaxError is thrown on parse error)- Return type:
- Example:
>>> bv.parse_types_from_string('int foo;\nint bar(int x);\nstruct bas{int x,y;};\n') ({types: {'bas': <type: struct bas>}, variables: {'foo': <type: int32_t>}, functions:{'bar': <type: int32_t(int32_t x)>}}, '') >>>
- perform_get_default_endianness() Endianness[source]
perform_get_default_endiannessimplements a check which returns the Endianness of the BinaryViewNote
This method may be implemented for custom BinaryViews that are not LittleEndian.
Warning
This method must not be called directly.
- Returns:
either
Endianness.LittleEndianorEndianness.BigEndian- Return type:
- perform_get_entry_point() int[source]
perform_get_entry_pointimplements a query for the initial entry point for code execution.Note
This method should be implemented for custom BinaryViews that are executable.
Warning
This method must not be called directly.
- Returns:
the virtual address of the entry point
- Return type:
- perform_get_length() int[source]
perform_get_lengthimplements a query for the size of the virtual address range used by the BinaryView.Note
This method may be overridden by custom BinaryViews. Use
add_auto_segmentto provide data without overriding this method.Warning
This method must not be called directly.
- Returns:
returns the size of the virtual address range used by the BinaryView
- Return type:
- perform_get_modification(addr: int) ModificationStatus[source]
perform_get_modificationimplements query to the whether the virtual addressaddris modified.Note
This method may be overridden by custom BinaryViews. Use
add_auto_segmentto provide data without overriding this method.Warning
This method must not be called directly.
- Parameters:
addr (int) – a virtual address to be checked
- Returns:
one of the following: Original = 0, Changed = 1, Inserted = 2
- Return type:
- perform_get_next_valid_offset(addr: int) int[source]
perform_get_next_valid_offsetimplements a query for the next valid readable, writable, or executable virtual memory address.Note
This method may be overridden by custom BinaryViews. Use
add_auto_segmentto provide data without overriding this method.Warning
This method must not be called directly.
- perform_get_start() int[source]
perform_get_startimplements a query for the first readable, writable, or executable virtual address in the BinaryView.Note
This method may be overridden by custom BinaryViews. Use
add_auto_segmentto provide data without overriding this method.Warning
This method must not be called directly.
- Returns:
returns the first virtual address in the BinaryView
- Return type:
- perform_insert(addr: int, data: bytes) int[source]
perform_insertimplements a mapping between a virtual address and an absolute file offset, inserting the bytesdatato rebased addressaddr.Note
This method may be overridden by custom BinaryViews. If not overridden, inserting is disallowed
Warning
This method must not be called directly.
- perform_is_executable() bool[source]
perform_is_executableimplements a check which returns true if the BinaryView is executable.Note
This method must be implemented for custom BinaryViews that are executable.
Warning
This method must not be called directly.
- Returns:
true if the current BinaryView is executable, false if it is not executable or on error
- Return type:
- perform_is_offset_executable(addr: int) bool[source]
perform_is_offset_executableimplements a check if a virtual addressaddris executable.Note
This method may be overridden by custom BinaryViews. Use
add_auto_segmentto provide data without overriding this method.Warning
This method must not be called directly.
- perform_is_offset_readable(offset: int) bool[source]
perform_is_offset_readableimplements a check if a virtual address is readable.Note
This method may be overridden by custom BinaryViews. Use
add_auto_segmentto provide data without overriding this method.Warning
This method must not be called directly.
- perform_is_offset_writable(addr: int) bool[source]
perform_is_offset_writableimplements a check if a virtual addressaddris writable.Note
This method may be overridden by custom BinaryViews. Use
add_auto_segmentto provide data without overriding this method.Warning
This method must not be called directly.
- perform_is_relocatable() bool[source]
perform_is_relocatableimplements a check which returns true if the BinaryView is relocatable. Defaults to FalseNote
This method may be implemented for custom BinaryViews that are relocatable.
Warning
This method must not be called directly.
- Returns:
True if the BinaryView is relocatable, False otherwise
- Return type:
boolean
- perform_is_valid_offset(addr: int) bool[source]
perform_is_valid_offsetimplements a check if a virtual addressaddris valid.Note
This method may be overridden by custom BinaryViews. Use
add_auto_segmentto provide data without overriding this method.Warning
This method must not be called directly.
- perform_read(addr: int, length: int) bytes[source]
perform_readimplements a mapping between a virtual address and an absolute file offset, readinglengthbytes from the rebased addressaddr.Note
This method may be overridden by custom BinaryViews. Use
add_auto_segmentto provide data without overriding this method.Warning
This method must not be called directly.
- perform_remove(addr: int, length: int) int[source]
perform_removeimplements a mapping between a virtual address and an absolute file offset, removinglengthbytes from the rebased addressaddr.Note
This method may be overridden by custom BinaryViews. If not overridden, removing data is disallowed
Warning
This method must not be called directly.
- perform_write(addr: int, data: bytes) int[source]
perform_writeimplements a mapping between a virtual address and an absolute file offset, writing the bytesdatato rebased addressaddr.Note
This method may be overridden by custom BinaryViews. Use
add_auto_segmentto provide data without overriding this method.Warning
This method must not be called directly.
- pull_types_from_archive(archive: TypeArchive, names: List[_types.QualifiedNameType]) Mapping[_types.QualifiedName, Tuple[_types.QualifiedName, _types.Type]] | None[source]
Pull types from a type archive, updating them and any dependencies
- Parameters:
archive (TypeArchive) – Target type archive
names (List[_types.QualifiedNameType]) – Names of desired types in type archive
- Returns:
{ name: (name, type) } Mapping from archive name to (analysis name, definition), None on error
- Return type:
Mapping[_types.QualifiedName, Tuple[_types.QualifiedName, _types.Type]] | None
- pull_types_from_archive_by_id(archive_id: str, archive_type_ids: List[str]) Mapping[str, str] | None[source]
Pull types from a type archive by id, updating them and any dependencies
- push_types_to_archive(archive: TypeArchive, names: List[_types.QualifiedNameType]) Mapping[_types.QualifiedName, Tuple[_types.QualifiedName, _types.Type]] | None[source]
Push a collection of types, and all their dependencies, into a type archive
- Parameters:
archive (TypeArchive) – Target type archive
names (List[_types.QualifiedNameType]) – Names of types in analysis
- Returns:
{ name: (name, type) } Mapping from analysis name to (archive name, definition), None on error
- Return type:
Mapping[_types.QualifiedName, Tuple[_types.QualifiedName, _types.Type]] | None
- push_types_to_archive_by_id(archive_id: str, type_ids: List[str]) Mapping[str, str] | None[source]
Push a collection of types, and all their dependencies, into a type archive
- query_metadata(key: str) metadata.MetadataValueType[source]
query_metadata retrieves a metadata associated with the given key stored in the current BinaryView.
- Parameters:
key (str) – key to query
- Return type:
metadata associated with the key
- Example:
>>> bv.store_metadata("integer", 1337) >>> bv.query_metadata("integer") 1337L >>> bv.store_metadata("list", [1,2,3]) >>> bv.query_metadata("list") [1L, 2L, 3L] >>> bv.store_metadata("string", "my_data") >>> bv.query_metadata("string") 'my_data'
- range_contains_relocation(addr: int, size: int) bool[source]
Checks if the specified range overlaps with a relocation
- read(addr: int, length: int) bytes[source]
readreturns the data reads at mostlengthbytes from virtual addressaddr.- Parameters:
- Returns:
at most
lengthbytes from the virtual addressaddr, empty string on error or no data- Return type:
- Example:
>>> #Opening a x86_64 Mach-O binary >>> bv = BinaryView.new("/bin/ls") # note that we are using `new` instead of `load` to get the raw view >>> bv.read(0,4) b'\xcf\xfa\xed\xfe'
- read_int(address: int, size: int, sign: bool = True, endian: Endianness | None = None) int[source]
- Parameters:
address (int) –
size (int) –
sign (bool) –
endian (Endianness | None) –
- Return type:
- read_uuid(address: int, ms_format: bool = True) UUID[source]
Reads a UUID from the specified address in the binary view.
- Parameters:
- Returns:
A UUID object
- Raises:
ValueError – If 16 bytes couldn’t be read from the specified address.
- Return type:
- reader(address: int | None = None) BinaryReader[source]
- Parameters:
address (int | None) –
- Return type:
- reanalyze() None[source]
reanalyzecauses all functions to be reanalyzed. This function does not wait for the analysis to finish.- Return type:
None
- rebase(address: int, force: bool | None = False, progress_func: Callable[[int, int], bool] | None = None) BinaryView | None[source]
rebaserebase the existingBinaryViewinto a newBinaryViewat the specified virtual addressNote
This method does not update corresponding UI components. If the BinaryView is associated with UI components then initiate the rebase operation within the UI, e.g. using the command palette. If working with views that are not associated with UI components while the UI is active, then set
forcetoTrueto enable rebasing.- Parameters:
- Returns:
the new
BinaryViewobject orNoneon failure- Return type:
BinaryVieworNone- Example:
>>> from binaryninja import load >>> bv = load('/bin/ls') >>> print(bv) <BinaryView: '/bin/ls', start 0x100000000, len 0x182f8> >>> newbv = bv.rebase(0x400000) >>> print(newbv) <BinaryView: '/bin/ls', start 0x400000, len 0x182f8>
- record_imported_object_library(lib: TypeLibrary, name: str, addr: int, platform: Platform | None = None) None[source]
record_imported_object_libraryshould be called by custom py:py:class:BinaryView implementations when they have successfully imported an object from a type library (e.g. a symbol’s type). Values recorded with this function will then be queryable vialookup_imported_object_library.- Parameters:
lib (TypeLibrary) – Type Library containing the imported type
name (str) – Name of the object in the type library
addr (int) – address of symbol at import site
platform (Platform | None) – Platform of symbol at import site
- Return type:
None
- redo() None[source]
redoredo the last committed transaction in the undo database.- Return type:
None
- Example:
>>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>> with bv.undoable_transaction(): >>> bv.convert_to_nop(0x100012f1) True >>> bv.get_disassembly(0x100012f1) 'nop' >>> bv.undo() >>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>> bv.redo() >>> bv.get_disassembly(0x100012f1) 'nop' >>>
- register_notification(notify: BinaryDataNotification) None[source]
register_notification enables the receipt of callbacks for various analysis events. A full list of callbacks is available in the
BinaryDataNotificationclass. If the notification_barrier is enabled, then it is triggered upon the initial call to register_notification. Subsequent calls for an already registerednotifyinstance also trigger a notification_barrier callback.- Parameters:
notify (BinaryDataNotification) – notify is a subclassed instance of
BinaryDataNotification.- Return type:
None
- register_platform_types(platform: Platform) None[source]
register_platform_typesensures that the platform-specific types for aPlatformare available for the currentBinaryView. This is automatically performed when adding a new function or setting the default platform.- Parameters:
platform (Platform) – Platform containing types to be registered
- Return type:
None
- Example:
>>> platform = Platform["linux-x86"] >>> bv.register_platform_types(platform) >>>
- relocation_ranges_at(addr: int) List[Tuple[int, int]][source]
List of relocation range tuples for a given address
- relocation_ranges_in_range(addr: int, size: int) List[Tuple[int, int]][source]
List of relocation range tuples for a given range
- relocations_at(addr: int) List[Relocation][source]
List of relocations for a given address
- Parameters:
addr (int) –
- Return type:
- remove(addr: int, length: int) int[source]
removeremoves at mostlengthbytes from virtual addressaddr.
- remove_auto_data_tag(addr: int, tag: Tag)[source]
remove_auto_data_tagremoves a Tag object at a data address.
- remove_auto_data_tags_of_type(addr: int, tag_type: str)[source]
remove_auto_data_tags_of_typeremoves all data tags at the given address of the given type.
- remove_auto_segment(start: int, length: int = 0) None[source]
remove_auto_segmentRemoves an automatically generated segment from the current segment mapping. This method removes the most recently added ‘auto’ segment that either matches the specified start address or contains it.- Parameters:
- Return type:
None
Warning
This action is not persistent across saving of a BNDB and must be re-applied each time a BNDB is loaded.
- remove_component(_component: Component | str) bool[source]
Remove a component from the tree entirely.
- remove_data_ref(from_addr: int, to_addr: int) None[source]
remove_data_refremoves an auto data cross-reference (xref) from the addressfrom_addrto the addressto_addr. This function will only remove ones generated during autoanalysis. If the reference does not exist, no action is performed.- Parameters:
- Return type:
None
Note
It is intended to be used from within workflows or other reoccurring analysis tasks. Removed references will be re-created whenever auto analysis is re-run for the
- remove_expression_parser_magic_value(name: str) None[source]
Remove a magic value from the expression parser.
If the magic value gets referenced after removal, an error will occur during the parsing.
- Parameters:
name (str) – name for the magic value to remove
- Returns:
- Return type:
None
- remove_expression_parser_magic_values(names: List[str]) None[source]
Remove a list of magic value from the expression parser
If any of the magic values gets referenced after removal, an error will occur during the parsing.
- remove_external_library(name: str)[source]
Remove an ExternalLibrary from this BinaryView by name. Any associated ExternalLocations will be unassociated from the ExternalLibrary
- Parameters:
name (str) – Name of the external library to remove
- remove_external_location(source_symbol: CoreSymbol)[source]
Remove the ExternalLocation with the given source symbol from this BinaryView
- Parameters:
source_symbol (CoreSymbol) – Source symbol that will be used to determine the ExternalLocation to remove
- remove_function(func: Function, update_refs=False) None[source]
remove_functionremoves the functionfuncfrom the list of functionsWarning
This method should only be used when the function that is removed is expected to re-appear after any other analysis executes that could re-add it. Most users will want to use
remove_user_functionin their scripts.
- remove_metadata(key: str) None[source]
remove_metadata removes the metadata associated with key from the current BinaryView.
- Parameters:
key (str) – key associated with metadata to remove from the BinaryView
- Return type:
None
- Example:
>>> bv.store_metadata("integer", 1337) >>> bv.remove_metadata("integer")
- remove_tag_type(tag_type: str)[source]
remove_tag_typeremoves aTagTypeand all tags that use it- Parameters:
tag_type (str) – The name of the tag type to remove
- Return type:
None
- remove_user_data_ref(from_addr: int, to_addr: int) None[source]
remove_user_data_refremoves a user-specified data cross-reference (xref) from the addressfrom_addrto the addressto_addr. This function will only remove user-specified references, not ones generated during autoanalysis. If the reference does not exist, no action is performed.
- remove_user_data_tag(addr: int, tag: Tag)[source]
remove_user_data_tagremoves aTagobject at a data address. Since this removes a user tag, it will be added to the current undo buffer.
- remove_user_data_tags_of_type(addr: int, tag_type: str)[source]
remove_user_data_tags_of_typeremoves all data tags at the given address of the given type. Since this removes user tags, it will be added to the current undo buffer.
- remove_user_function(func: Function) None[source]
remove_user_functionremoves the functionfuncfrom the list of functions as a user action.Note
This API will prevent the function from being re-created if any analysis later triggers that would re-add it, unlike
remove_function.- Parameters:
func (Function) – a Function object.
- Return type:
None
- Example:
>>> bv.functions [<func: x86_64@0x1>] >>> bv.remove_user_function(next(bv.functions)) >>> bv.functions []
- remove_user_segment(start: int, length: int = 0) None[source]
remove_user_segmentRemoves a user-defined segment from the current segment mapping. This method removes the most recently added ‘user’ segment that either matches the specified start address or contains it.
- rename_type(old_name: _types.QualifiedNameType, new_name: _types.QualifiedNameType) None[source]
rename_typerenames a type in the global list of types for the currentBinaryView- Parameters:
old_name (QualifiedName) – Existing name of type to be renamed
new_name (QualifiedName) – New name of type to be renamed
- Return type:
None
- Example:
>>> type, name = bv.parse_type_string("int foo") >>> bv.define_user_type(name, type) >>> bv.get_type_by_name("foo") <type: int32_t> >>> bv.rename_type("foo", "bar") >>> bv.get_type_by_name("bar") <type: int32_t> >>>
- revert_undo_actions(id: str | None = None) None[source]
revert_undo_actionsreverts the actions taken since a call tobegin_undo_actionsPass as id the value returned bybegin_undo_actions. Empty values of id will revert all changes since the last call tobegin_undo_actions.- Parameters:
id (Optional[str]) – id of undo state, from
begin_undo_actions- Return type:
None
- Example:
>>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>> state = bv.begin_undo_actions() >>> bv.convert_to_nop(0x100012f1) True >>> bv.revert_undo_actions(state) >>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>>
- save(dest: FileAccessor | str) bool[source]
savesaves the original binary file to the provided destinationdestalong with any modifications.Warning
This API will only save the original file from a view. To save a database, use
create_database.
- save_auto_snapshot(progress_func: Callable[[int, int], bool] | None = None, settings: SaveSettings | None = None) bool[source]
save_auto_snapshotsaves the current database to the already created file.Note
create_databaseshould have been called prior to executing this method- Parameters:
progress_func (callback) – optional function to be called with the current progress and total count.
settings (SaveSettings) – optional argument for special save options.
- Returns:
True if it successfully saved the snapshot, False otherwise
- Return type:
- search(pattern: str, start: int | None = None, end: int | None = None, raw: bool = False, ignore_case: bool = False, overlap: bool = False, align: int = 1, limit: int | None = None, progress_callback: Callable[[int, int], bool] | None = None, match_callback: Callable[[int, DataBuffer], bool] | None = None) QueueGenerator[source]
Searches for matches of the specified
patternwithin this BinaryView with an optionally provided address range specified bystartandend. The search pattern can be interpreted in various ways:specified as a string of hexadecimal digits where whitespace is ignored, and the ‘?’ character acts as a wildcard
a regular expression suitable for working with bytes
or if the
rawoption is enabled, the pattern is interpreted as a raw string, and any special characters are escaped and interpreted literally
- Parameters:
pattern (
str) – The pattern to search for.start (
int) – The address to start the search from. (default: None)end (
int) – The address to end the search (inclusive). (default: None)raw (bool) – Whether to interpret the pattern as a raw string (default: False).
ignore_case (bool) – Whether to perform case-insensitive matching (default: False).
overlap (bool) – Whether to allow matches to overlap (default: False).
align (int) – The alignment of matches, must be a power of 2 (default: 1).
limit (int) – The maximum number of matches to return (default: None).
progress_callback (callback) – An optional function to be called with the current progress and total count. This function should return a boolean value that decides whether the search should continue or stop.
match_callback (callback) – A function that gets called when a match is found. The callback takes two parameters: the address of the match, and the actual DataBuffer that satisfies the search. This function can return a boolean value that decides whether the search should continue or stop.
- Returns:
A generator object that yields the offset and matched DataBuffer for each match found.
- Return type:
- Example:
>>> from binaryninja import load >>> bv = load('/bin/ls') >>> print(bv) <BinaryView: '/bin/ls', start 0x100000000, len 0x182f8> >>> bytes(list(bv.search("50 ?4"))[0][1]).hex() '5004' >>> bytes(list(bv.search("[\x20-\x25][\x60-\x67]"))[0][1]).hex() '2062'
- set_analysis_hold(enable: bool) None[source]
set_analysis_holdcontrol the analysis hold for this BinaryView. Enabling analysis hold defers all future analysis updates, therefore causingupdate_analysisorupdate_analysis_and_waitto take no action.- Return type:
None
- Parameters:
enable (bool) –
- set_comment_at(addr: int, comment: str) None[source]
set_comment_atsets a comment for the BinaryView at the address specifiedNote that these are different from function-level comments which are specific to each
Function. For more information, seeaddress_comments.
- static set_default_session_data(name: str, value: str) None[source]
set_default_session_datasaves a variable to the BinaryView. Session data is ephemeral not saved to a database. Consider usingstore_metadataif permanence is needed.
- set_function_analysis_update_disabled(disabled: bool) None[source]
set_function_analysis_update_disabledprevents any function from being marked as updates required, so that they would NOT be re-analyzed when the analysis is updated. The main difference between this API andset_analysis_holdis thatset_analysis_holdonly temporarily holds the analysis, and the functions are still arranged to be updated when the hold is turned off. However, withset_function_analysis_update_disabled, functions would not be put into the analysis queue at all.Use with caution – in most cases, this is NOT what you want, and you should use
set_analysis_holdinstead.- Parameters:
disabled (bool) –
- Returns:
- Return type:
None
- set_load_settings(type_name: str, settings: Settings | None) None[source]
set_load_settingsset aSettingsobject which defines the load settings for the givenBinaryViewTypetype_name- Parameters:
type_name (str) – the
BinaryViewTypenamesettings (Settings) – the load settings
- Return type:
None
- set_manual_type_source_override(entries: Mapping[QualifiedName, Tuple[QualifiedName, str]])[source]
This allows for fine-grained control over how types from this BinaryView are exported to a TypeLibrary by export_type_to_library and export_object_to_library. Types identified by the keys of the dict will NOT be exported to the destination TypeLibrary, but will instead be treated as a type that had come from the string component of the value tuple. This results in the destination TypeLibrary gaining a new dependency.
This is useful if a BinaryView was automatically marked up with a lot of debug information but you want to export only a subset of that information into a new TypeLibrary. By creating a description of which local types correspond to types in other already extant libraries, those types will be avoided during the recursive export.
This data is not persisted and does not impact analysis.
For example, if a BinaryView contains the following types:
struct RECT { ... }; // omitted struct ContrivedExample { RECT rect; };
Then the following python:
overrides = {"RECT": ("tagRECT", "winX64common")} bv.set_manual_type_source_override(overrides) bv.export_type_to_library(dest_new_typelib, "ContrivedExample", bv.get_type_by_name("ContrivedExample"))
Results in dest_new_typelib only having ContrivedExample added, and “RECT” being inserted as a dependency to a the type “tagRECT” found in the typelibrary “winX64common”
- Parameters:
entries (Mapping[QualifiedName, Tuple[QualifiedName, str]]) –
- set_user_global_pointer_value(value: RegisterValue, confidence=255)[source]
Set a user global pointer value. This is useful when the auto analysis fails to find out the value of the global pointer, or the value is wrong. In this case, we can call
set_user_global_pointer_valuewith aConstantRegisterValueorConstantPointerRegisterValueto provide a user global pointer value to assist the analysis.On the other hand, if the auto analysis figures out a global pointer value, but there should not be one, we can call
set_user_global_pointer_valuewith an Undetermined value to override it.Whenever a user global pointer value is set/cleared, an analysis update must occur for it to take effect and all functions using the global pointer to be updated.
We can use
user_global_pointer_value_setto query whether a user global pointer value is set, and useclear_user_global_pointer_valueto clear a user global pointer value. Note,clear_user_global_pointer_valueis different from callingset_user_global_pointer_valuewith anUndeterminedvalue. The former clears the user global pointer value and let the analysis decide the global pointer value, whereas the latte forces the global pointer value to become undetermined.- Parameters:
value (RegisterValue) – the user global pointer value to be set
confidence (int) – the confidence value of the user global pointer value. In most cases this should be set to 255. Setting a value lower than the confidence of the global pointer value from the auto analysis will cause undesired effect.
- Returns:
None
- Return type:
None
- Example:
>>> bv.global_pointer_value <const ptr 0x3fd4> >>> bv.set_user_global_pointer_value(ConstantPointerRegisterValue(0x12345678)) >>> bv.global_pointer_value <const ptr 0x12345678> >>> bv.user_global_pointer_value_set True >>> bv.clear_user_global_pointer_value() >>> bv.global_pointer_value <const ptr 0x3fd4> >>> bv.set_user_global_pointer_value(Undetermined()) >>> bv.global_pointer_value <undetermined>
- should_skip_target_analysis(source_location: ArchAndAddr, source_function: Function, end: int, target_location: ArchAndAddr) bool[source]
should_skip_target_analysischecks if target analysis should be skipped.Note
This method is intended for use by architecture plugins only.
- Parameters:
source_location (_function.ArchAndAddr) – The source location.
source_function (_function.Function) – The source function.
end (int) – The end address of the source branch instruction.
target_location (_function.ArchAndAddr) – The target location.
- Returns:
True if the target analysis should be skipped, False otherwise
- Return type:
- show_graph_report(title: str, graph: FlowGraph) None[source]
show_graph_reportdisplays aFlowGraphobject graph in a new tab withtitle.- Parameters:
title (Text string title of the tab) – Title of the graph
graph (
FlowGraphobject) – The graph you wish to display
- Return type:
None
- show_html_report(title: str, contents: str, plaintext: str = '') None[source]
show_html_reportdisplays the HTML contents in UI applications and plaintext in command-line applications. HTML reports support hyperlinking into the BinaryView. Hyperlinks can be specified as follows:binaryninja://?expr=_startWhereexpr=specifies an expression parsable by theparse_expressionAPI.Note
This API function differently on the command-line vs the UI. In the UI a pop-up is used. On the command-line a simple text prompt is used.
- show_markdown_report(title: str, contents: str, plaintext: str = '') None[source]
show_markdown_reportdisplays the markdown contents in UI applications and plaintext in command-line applications. Markdown reports support hyperlinking into the BinaryView. Hyperlinks can be specified as follows:binaryninja://?expr=_startWhereexpr=specifies an expression parsable by theparse_expressionAPI.Note
This API functions differently on the command-line vs the UI. In the UI a pop-up is used. On the command-line a simple text prompt is used.
- skip_and_return_value(addr: int, value: int, arch: Architecture | None = None) bool[source]
skip_and_return_valueconvert thecallinstruction of architecturearchat the virtual addressaddrto the equivalent of returning a value.- Parameters:
addr (int) – virtual address of the instruction to be modified
value (int) – value to make the instruction return
arch (Architecture) – (optional) the architecture of the instructions if different from the default
- Returns:
True on success, False on failure.
- Return type:
- Example:
>>> bv.get_disassembly(0x1000132a) 'call 0x1000134a' >>> bv.skip_and_return_value(0x1000132a, 42) True >>> #The return value from x86 functions is stored in eax thus: >>> bv.get_disassembly(0x1000132a) 'mov eax, 0x2a' >>>
- store_metadata(key: str, md: Metadata | int | bool | str | bytes | float | List[MetadataValueType] | Tuple[MetadataValueType] | dict, isAuto: bool = False) None[source]
store_metadata stores an object for the given key in the current BinaryView. Objects stored using store_metadata can be retrieved when the database is reopened. Objects stored are not arbitrary python objects! The values stored must be able to be held in a Metadata object. See
Metadatafor more information. Python objects could obviously be serialized using pickle but this intentionally a task left to the user since there is the potential security issues.- Parameters:
key (str) – key value to associate the Metadata object with
md (Varies) – object to store.
isAuto (bool) – whether the metadata is an auto metadata. Most metadata should keep this as False. Only those automatically generated metadata should have this set to True. Auto metadata is not saved into the database and is presumably re-generated when re-opening the database.
- Return type:
None
- Example:
>>> bv.store_metadata("integer", 1337) >>> bv.query_metadata("integer") 1337L >>> bv.store_metadata("list", [1,2,3]) >>> bv.query_metadata("list") [1L, 2L, 3L] >>> bv.store_metadata("string", "my_data") >>> bv.query_metadata("string") 'my_data'
- stringify_unicode_data(arch: Architecture | None, buffer: DataBuffer, null_terminates: bool = True, allow_short_strings: bool = False) Tuple[str | None, StringType | None][source]
stringify_unicode_dataconverts a buffer of unicode data into a string representation. :param arch: The architecture to use for stringification, or None to use the current architecture of the BinaryView :param buffer: The DataBuffer containing the unicode data to stringify :param null_terminates: If True, stops stringification at the first null character, otherwise continues until the end of the buffer :param allow_short_strings: If True, allows short strings to be returned, otherwise only long strings are returned :return: A tuple containing the string representation and its type, or (None, None) if the stringification fails :rtype: Tuple[Optional[str], Optional[StringType]]- Parameters:
arch (Architecture | None) –
buffer (DataBuffer) –
null_terminates (bool) –
allow_short_strings (bool) –
- Return type:
Tuple[str | None, StringType | None]
- tags_by_type(tag_type: TagType) List[Tuple[int, Tag]][source]
tags_by_typefetches tags of a specific type.
- tags_for_data_by_type(tag_type: TagType) List[Tuple[int, Tag]][source]
tags_for_data_by_typefetches data-specific tags of a specific type.
- tags_for_data_with_source(auto: bool = True) List[Tuple[int, Tag]][source]
tags_for_data_with_sourcefetches data-specific tags filtered by source.
- typed_data_accessor(address: int, type: Type) TypedDataAccessor[source]
- Parameters:
- Return type:
- undefine_auto_symbol(sym: CoreSymbol) None[source]
undefine_auto_symbolremoves a symbol from the internal list of automatically discovered Symbol objects.- Parameters:
sym (Symbol) – the symbol to undefine
- Return type:
None
- undefine_data_var(addr: int, blacklist: bool = True) None[source]
undefine_data_varremoves the non-user data variable at the virtual addressaddr.- Parameters:
- Return type:
None
- Example:
>>> bv.undefine_data_var(bv.entry_point) >>>
- undefine_type(type_id: str) None[source]
undefine_typeremoves aTypefrom the global list of types for the currentBinaryView- Parameters:
type_id (str) – Unique identifier of type to be undefined
- Return type:
None
- Example:
>>> type, name = bv.parse_type_string("int foo") >>> type_id = Type.generate_auto_type_id("source", name) >>> bv.define_type(type_id, name, type) >>> bv.get_type_by_name(name) <type: int32_t> >>> bv.undefine_type(type_id) >>> bv.get_type_by_name(name) >>>
- undefine_user_data_var(addr: int) None[source]
undefine_user_data_varremoves the user data variable at the virtual addressaddr.- Parameters:
addr (int) – virtual address to define the data variable to be removed
- Return type:
None
- Example:
>>> bv.undefine_user_data_var(bv.entry_point) >>>
- undefine_user_symbol(sym: CoreSymbol) None[source]
undefine_user_symbolremoves a symbol from the internal list of user added Symbol objects.- Parameters:
sym (CoreSymbol) – the symbol to undefine
- Return type:
None
- undefine_user_type(name: _types.QualifiedNameType) None[source]
undefine_user_typeremoves aTypefrom the global list of user types for the currentBinaryView- Parameters:
name (QualifiedName) – Name of user type to be undefined
- Return type:
None
- Example:
>>> type, name = bv.parse_type_string("int foo") >>> bv.define_user_type(name, type) >>> bv.get_type_by_name(name) <type: int32_t> >>> bv.undefine_user_type(name) >>> bv.get_type_by_name(name) >>>
- undo() None[source]
undoundo the last committed transaction in the undo database.- Return type:
None
- Example:
>>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>> with bv.undoable_transaction(): >>> bv.convert_to_nop(0x100012f1) True >>> bv.get_disassembly(0x100012f1) 'nop' >>> bv.undo() >>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>> bv.redo() >>> bv.get_disassembly(0x100012f1) 'nop' >>>
- undoable_transaction() Generator[source]
undoable_transactiongives you a context in which you can make changes to analysis, and creates an Undo state containing those actions. If an exception is thrown, any changes made to the analysis inside the transaction are reverted.- Returns:
Transaction context manager, which will commit/revert actions depending on if an exception is thrown when it goes out of scope.
- Return type:
Generator
- Example:
>>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>> # Actions inside the transaction will be committed to the undo state upon exit >>> with bv.undoable_transaction(): >>> bv.convert_to_nop(0x100012f1) True >>> bv.get_disassembly(0x100012f1) 'nop' >>> bv.undo() >>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>> # A thrown exception inside the transaction will undo all changes made inside it >>> with bv.undoable_transaction(): >>> bv.convert_to_nop(0x100012f1) # Reverted on thrown exception >>> raise RuntimeError("oh no") RuntimeError: oh no >>> bv.get_disassembly(0x100012f1) 'xor eax, eax'
- unregister_notification(notify: BinaryDataNotification) None[source]
unregister_notification unregisters the
BinaryDataNotificationobject passed to register_notification- Parameters:
notify (BinaryDataNotification) – notify is a subclassed instance of
BinaryDataNotification.- Return type:
None
- update_analysis() None[source]
update_analysisasynchronously starts the analysis process and returns immediately.Usage: Call
update_analysisafter making changes that could affect the analysis results, such as adding or modifying functions. This ensures that the analysis is updated to reflect the latest changes. The analysis runs in the background, allowing other operations to continue.- Return type:
None
- update_analysis_and_wait() None[source]
update_analysis_and_waitstarts the analysis process and blocks until it is complete. This method should be used when it is necessary to ensure that analysis results are fully updated before proceeding with further operations. If an update is already in progress, this method chains a new update request to ensure that the update processes all pending changes before the call was made.Usage: Call
update_analysis_and_waitafter making changes that could affect the analysis results, such as adding or modifying functions, to ensure that the analysis reflects the latest changes. Unlikeupdate_analysis, this method waits for the analysis to finish before returning.Thread Restrictions: - Worker Threads: This function cannot be called from a worker thread. If called from a worker thread, an error will be logged, and the function will return immediately. - UI Threads: This function cannot be called from a UI thread. If called from a UI thread, an error will be logged, and the function will return immediately.
- Return type:
None
- write(addr: int, data: bytes, except_on_relocation: bool = True) int[source]
writewrites the bytes indatato the virtual addressaddr.- Parameters:
- Returns:
number of bytes written to virtual address
addr- Return type:
- Example:
>>> bv.read(0,4) b'BBBB' >>> bv.write(0, b"AAAA") 4 >>> bv.read(0,4) b'AAAA'
- writer(address: int | None = None) BinaryWriter[source]
- Parameters:
address (int | None) –
- Return type:
- property address_comments: Mapping[int, str]
Returns a read-only dict of the address comments attached to this BinaryView
Note that these are different from function-level comments which are specific to each
Function. For annotating code, it is recommended to use comments attached to functions rather than address comments attached to the BinaryView. On the other hand, BinaryView comments can be attached to data whereas function comments cannot.To create a function-level comment, use
set_comment_at.
- property address_size: int
Address size of the binary (read-only)
- property allocated_ranges: List[AddressRange]
List of valid address ranges for this view (read-only) Deprecated: 4.1.5902 Use mapped_address_ranges instead.
- property analysis_changed: bool
boolean analysis state changed of the currently running analysis (read-only)
- property analysis_info: AnalysisInfo
Provides instantaneous analysis state information and a list of current functions under analysis (read-only). All times are given in units of milliseconds (ms). Per-function analysis_time is the aggregation of time spent performing incremental updates and is reset on a full function update. Per-function update_count tracks the current number of incremental updates and is reset on a full function update. Per-function submit_count tracks the current number of full updates that have completed.
Note
submit_count is currently not reset across analysis updates.
- property analysis_is_aborted: bool
analysis_is_abortedchecks if the analysis has been aborted.Note
This property is intended for use by architecture plugins only.
- Returns:
True if the analysis has been aborted, False otherwise
- Return type:
- property analysis_progress: AnalysisProgress
Status of current analysis (read-only)
- property analysis_state: AnalysisState
State of current analysis (read-only)
- property arch: Architecture | None
The architecture associated with the current
BinaryView(read/write)
- property associated_type_archive_type_ids: Mapping[str, Tuple[str, str]]
Get a list of all types in the analysis that are associated with type archives
- Returns:
Map of all analysis types to their corresponding archive / id
- property associated_type_archive_types: Mapping[QualifiedName, Tuple[TypeArchive | None, str]]
Get a list of all types in the analysis that are associated with attached type archives
- Returns:
Map of all analysis types to their corresponding archive / id. If a type is associated with a disconnected type archive, the archive will be None.
- property attached_type_archives: Mapping[str, str]
All attached type archive ids and paths (read-only)
- property auto_metadata: Dict[str, metadata.MetadataValueType]
metadata retrieves the metadata associated with the current BinaryView.
- Return type:
metadata associated with the BinaryView
- Example:
>>> bv.metadata <metadata: {}>
- property auto_type_container: TypeContainer
Type Container for ONLY auto types in the BinaryView. Any changes to types will NOT promote auto types to user types. :return: Auto types only Type Container
- property available_view_types: List[BinaryViewType]
Available view types (read-only)
- property backed_address_ranges: List[AddressRange]
List of backed address ranges for this view (read-only)
- property basic_blocks: Generator[BasicBlock, None, None]
A generator of all BasicBlock objects in the BinaryView
- property connected_type_archives: List[TypeArchive]
All connected type archive objects (read-only)
- property data_vars: Mapping[int, DataVariable]
List of data variables (read-only)
- property debug_info: DebugInfo
The current debug info object for this binary view
- property dependency_sorted_types: TypeMapping
List of all types, sorted such that types are after all types on which they depend (read-only)
Order is guaranteed for any collection of types with no cycles. If you have cycles in type dependencies, order for types in a cycle is not guaranteed.
Note
Dependency order is based on named type references for all non-structure types, i.e.
struct Foo m_foowill induce a dependency, whereasstruct Foo* m_pFoowill not.- Returns:
sorted types as defined above
- property end: int
End offset of the binary (read-only)
- property endianness: Endianness
Endianness of the binary (read-only)
- property entry_functions: FunctionList
A List of entry functions (read-only) This list contains vanilla entry function, and functions like init_array, fini_array, and TLS callbacks etc. User-added entry functions(via add_entry_point) are also included.
We see entry_functions as good starting points for analysis, these functions normally don’t have internal references. However, note that exported functions in a dll/so file are not included.
Note the difference with entry_function
- property entry_point: int
Entry point of the binary (read-only)
- property executable: bool
Whether the binary is an executable (read-only)
- property file: FileMetadata
FileMetadatabacking the BinaryView
- property functions: FunctionList
returns a FunctionList object (read-only)
- property global_pointer_value: RegisterValue
Discovered value of the global pointer register, if the binary uses one (read-only)
- property has_data_variables: bool
Boolean whether the binary has data variables (read-only)
- property has_database: bool
boolean has a database been written to disk (read-only)
- property has_functions: bool
Boolean whether the binary has functions (read-only)
- property has_symbols: bool
Boolean whether the binary has symbols (read-only)
- property hlil_basic_blocks: Generator[HighLevelILBasicBlock, None, None]
A generator of all HighLevelILBasicBlock objects in the BinaryView
- property hlil_instructions: highlevelil.HLILInstructionsType
A generator of hlil instructions
- property image_base: int
Image base of the binary
- property instructions: Generator[Tuple[List[InstructionTextToken], int], None, None]
A generator of instruction tokens and their start addresses
- property length
- property linear_disassembly: Iterator[LinearDisassemblyLine]
Iterator for all lines in the linear disassembly of the view
- property llil_basic_blocks: Generator[LowLevelILBasicBlock, None, None]
A generator of all LowLevelILBasicBlock objects in the BinaryView
- property llil_instructions: lowlevelil.LLILInstructionsType
A generator of llil instructions
- property mapped_address_ranges: List[AddressRange]
List of mapped address ranges for this view (read-only)
- property max_function_size_for_analysis: int
Maximum size of function (sum of basic block sizes in bytes) for auto analysis
- property memory_map
memory_mapreturns the MemoryMap object for the current BinaryView. The MemoryMap object is a proxy object that provides a high-level view of the memory map, allowing you to query and manipulate memory regions. This proxy ensures that the memory map always reflects the latest state of the core MemoryMap object in the underlying BinaryView.
- property metadata: Dict[str, metadata.MetadataValueType]
metadata retrieves the metadata associated with the current BinaryView.
- Return type:
metadata associated with the BinaryView
- Example:
>>> bv.metadata <metadata: {}>
- property mlil_basic_blocks: Generator[MediumLevelILBasicBlock, None, None]
A generator of all MediumLevelILBasicBlock objects in the BinaryView
- property mlil_instructions: Generator[MediumLevelILInstruction, None, None]
A generator of mlil instructions
- property modified: bool
boolean modification state of the BinaryView (read/write)
- property new_auto_function_analysis_suppressed: bool
Whether or not automatically discovered functions will be analyzed
- property offset: int
- property original_base: int
Original image base of the binary. Deprecated: 4.1.5902 Use original_image_base instead.
- property original_image_base: int
Original image base of the binary
- property parameters_for_analysis
- property parent_view: BinaryView | None
View that contains the raw data used by this view (read-only)
- property parse_only: bool
- property preload_limit: int
- property project_file: ProjectFile | None
- registered_view_type = None
- property relocatable: bool
Boolean - is the binary relocatable (read-only)
- property root_component: Component
The root component for the BinaryView (read-only)
This Component cannot be removed, and houses all unparented Components.
- Returns:
The root component
- property saved: bool
boolean state of whether or not the file has been saved (read/write)
- property session_data
Dictionary object where plugins can store arbitrary data associated with the view. This data is ephemeral and not saved to a database. Consider using
store_metadataif permanence is needed.
- property start: int
Start offset of the binary (read-only)
- property strings: List[StringReference]
List of strings (read-only)
- property symbols: SymbolMapping
Dict of symbols (read-only) Items in the dict are lists of all symbols matching that name.
- Example:
>>> bv.symbols['_main'] [<FunctionSymbol: "_main" @ 0x1dd0>] >>> list(bv.symbols) ['_start', '_main', '_printf', '_scanf', ...] >>> bv.symbols['foo'] KeyError: "'foo': symbol not found"
- Returns:
a dict-like generator of symbol names and values
- Return type:
Generator[str, None, None]
- property tag_types: Mapping[str, TagType | List[TagType]]
tag_typesgets a dictionary of all Tag Types present for the view, structured as {Tag Type Name => Tag Type}.
- property tags: List[Tuple[int, Tag]]
tagsgets a list of all dataTagobjects in the view. Tags are returned as a list of (address,Tag) pairs.
- property tags_for_address: List[Tuple[int, Tag]]
tags_for_addressfetches all address-specific tags.
- property tags_for_function: List[Tuple[int, Tag]]
tags_for_functionfetches all function-specific tags.
- property type_archive_type_names: Mapping[QualifiedName, List[Tuple[TypeArchive, str]]]
Get a list of all available type names in all connected archives, and their archive/type id pair
- Returns:
name <-> [(archive, archive type id)] for all type names
- property type_container: TypeContainer
Type Container for all types (user and auto) in the BinaryView. Any auto types modified through the Type Container will be converted into user types. :return: Full view Type Container
- property type_libraries: List[TypeLibrary]
List of imported type libraries (read-only)
- property type_names: List[QualifiedName]
List of defined type names (read-only)
- property types: TypeMapping
- property user_global_pointer_value_set: bool
Check whether a user global pointer value has been set
- property user_type_container: TypeContainer
Type Container for ONLY user types in the BinaryView. :return: User types only Type Container
- property view: str
- property view_type: str
View type (read-only)
- class BinaryViewEvent[source]
Bases:
objectThe
BinaryViewEventobject provides a mechanism for receiving callbacks when a BinaryView is Finalized or the initial analysis is finished. The BinaryView finalized callbacks run before the initial analysis starts. The callbacks run one-after-another in the same order as they get registered. It is a good place to modify the BinaryView to add extra information to it.For newly opened binaries, the initial analysis completion callbacks run after the initial analysis, as well as linear sweep and signature matcher (if they are configured to run), completed. For loading old databases, the callbacks run after the database is loaded, as well as any automatic analysis update finishes.
The callback function receives a BinaryView as its parameter. It is possible to call BinaryView.add_analysis_completion_event() on it to set up other callbacks for analysis completion.
- Example:
>>> def callback(bv): ... print('start: 0x%x' % bv.start) ... >>> BinaryViewType.add_binaryview_finalized_event(callback)
- classmethod register(event_type: BinaryViewEventType, callback: Callable[[BinaryView], None]) None[source]
- Parameters:
event_type (BinaryViewEventType) –
callback (Callable[[BinaryView], None]) –
- Return type:
None
- BinaryViewEventCallback
alias of
Callable[[BinaryView],None]
- class BinaryViewType[source]
Bases:
objectThe
BinaryViewTypeobject is used internally and should not be directly instantiated.- __init__(handle: LP_BNBinaryViewType)[source]
- Parameters:
handle (LP_BNBinaryViewType) –
- static add_binaryview_finalized_event(callback: Callable[[BinaryView], None]) None[source]
add_binaryview_finalized_event adds a callback that gets executed when new binaryview is finalized. For more details, please refer to the documentation of BinaryViewEvent.
Warning
The callback provided must stay in scope for the lifetime of the process, deletion or garbage collection of the callback will result in a crash.
- Parameters:
callback (Callable[[BinaryView], None]) –
- Return type:
None
- static add_binaryview_initial_analysis_completion_event(callback: Callable[[BinaryView], None]) None[source]
add_binaryview_initial_analysis_completion_event adds a callback that gets executed after the initial analysis, as well as linear sweep and signature matcher (if they are configured to run) completed. For more details, please refer to the documentation of BinaryViewEvent.
Warning
The callback provided must stay in scope for the lifetime of the process, deletion or garbage collection of the callback will result in a crash.
- Parameters:
callback (Callable[[BinaryView], None]) –
- Return type:
None
- create(data: BinaryView) BinaryView | None[source]
- Parameters:
data (BinaryView) –
- Return type:
BinaryView | None
- get_arch(ident: int, endian: Endianness) Architecture | None[source]
- Parameters:
ident (int) –
endian (Endianness) –
- Return type:
Architecture | None
- get_load_settings_for_data(data: BinaryView) Settings | None[source]
- Parameters:
data (BinaryView) –
- Return type:
Settings | None
- get_platform(ident: int, arch: Architecture) Platform | None[source]
- Parameters:
ident (int) –
arch (Architecture) –
- Return type:
Platform | None
- is_valid_for_data(data: BinaryView) bool[source]
- Parameters:
data (BinaryView) –
- Return type:
- open(src: str | PathLike, file_metadata: FileMetadata | None = None) BinaryView | None[source]
- Parameters:
file_metadata (FileMetadata | None) –
- Return type:
BinaryView | None
- parse(data: BinaryView) BinaryView | None[source]
- Parameters:
data (BinaryView) –
- Return type:
BinaryView | None
- recognize_platform(ident, endian: Endianness, view: BinaryView, metadata)[source]
- Parameters:
endian (Endianness) –
view (BinaryView) –
- register_arch(ident: int, endian: Endianness, arch: Architecture) None[source]
- Parameters:
ident (int) –
endian (Endianness) –
arch (Architecture) –
- Return type:
None
- register_default_platform(arch: Architecture, plat: Platform) None[source]
- Parameters:
arch (Architecture) –
plat (Platform) –
- Return type:
None
- register_platform(ident: int, arch: Architecture, plat: Platform) None[source]
- Parameters:
ident (int) –
arch (Architecture) –
plat (Platform) –
- Return type:
None
- register_platform_recognizer(ident, endian, cb)[source]
- property is_deprecated: bool
returns if the BinaryViewType is deprecated (read-only)
- property is_force_loadable: bool
returns if the BinaryViewType is force loadable (read-only)
- property long_name: str
BinaryView long name (read-only)
- property name: str
BinaryView name (read-only)
- class BinaryWriter[source]
Bases:
objectclass BinaryWriteris a convenience class for writing binary data.BinaryWriter can be instantiated as follows and the rest of the document will start from this context
>>> from binaryninja import * >>> bv = load("/bin/ls") >>> br = BinaryReader(bv) >>> br.offset 4294967296 >>> bw = BinaryWriter(bv) >>>
Or using the optional endian parameter
>>> from binaryninja import * >>> bv = load("/bin/ls") >>> br = BinaryReader(bv, Endianness.BigEndian) >>> bw = BinaryWriter(bv, Endianness.BigEndian) >>>
- __init__(view: BinaryView, endian: Endianness | None = None, address: int | None = None)[source]
- Parameters:
view (BinaryView) –
endian (Endianness | None) –
address (int | None) –
- seek(offset: int) None[source]
seekupdate internal offset tooffset.- Parameters:
offset (int) – offset to set the internal offset to
- Return type:
None
- Example:
>>> hex(bw.offset) '0x100000008L' >>> bw.seek(0x100000000) >>> hex(bw.offset) '0x100000000L' >>>
- seek_relative(offset: int) None[source]
seek_relativeupdates the internal offset byoffset.- Parameters:
offset (int) – offset to add to the internal offset
- Return type:
None
- Example:
>>> hex(bw.offset) '0x100000008L' >>> bw.seek_relative(-8) >>> hex(bw.offset) '0x100000000L' >>>
- write(value: bytes, address: int | None = None, except_on_relocation=True) bool[source]
writewriteslen(value)bytes to the internal offset, without regard to endianness.- Parameters:
- Returns:
boolean True on success, False on failure.
- Return type:
- Example:
>>> bw.write("AAAA") True >>> br.read(4) 'AAAA' >>>
- write16(value: int, address: int | None = None, except_on_relocation=True) bool[source]
write16writes the lowest order two bytes from the integervalueto the current offset, using internal endianness.
- write16be(value: int, address: int | None = None, except_on_relocation=True) bool[source]
write16bewrites the lowest order two bytes from the big endian integervalueto the current offset.
- write16le(value: int, address: int | None = None, except_on_relocation=True) bool[source]
write16lewrites the lowest order two bytes from the little endian integervalueto the current offset.
- write32(value: int, address: int | None = None, except_on_relocation=True) bool[source]
write32writes the lowest order four bytes from the integervalueto the current offset, using internal endianness.
- write32be(value: int, address: int | None = None, except_on_relocation=True) bool[source]
write32bewrites the lowest order four bytes from the big endian integervalueto the current offset.
- write32le(value: int, address: int | None = None, except_on_relocation=True) bool[source]
write32lewrites the lowest order four bytes from the little endian integervalueto the current offset.
- write64(value: int, address: int | None = None, except_on_relocation=True) bool[source]
write64writes the lowest order eight bytes from the integervalueto the current offset, using internal endianness.
- write64be(value: int, address: int | None = None, except_on_relocation=True) bool[source]
write64bewrites the lowest order eight bytes from the big endian integervalueto the current offset.
- write64le(value: int, address: int | None = None, except_on_relocation=True) bool[source]
write64lewrites the lowest order eight bytes from the little endian integervalueto the current offset.
- write8(value: int, address: int | None = None, except_on_relocation=True) bool[source]
write8lowest order byte from the integervalueto the current offset.- Parameters:
- Returns:
boolean
- Return type:
- Example:
>>> bw.write8(0x42) True >>> br.read(1) 'B' >>>
- property endianness: Endianness
The Endianness to written data. (read/write)
- Getter:
returns the endianness of the reader
- Setter:
sets the endianness of the reader (BigEndian or LittleEndian)
- Type:
- class CoreDataVariable[source]
Bases:
objectCoreDataVariable(_address: int, _type: ‘_types.Type’, _auto_discovered: bool)
- property address: int
- property auto_discovered: bool
- property type: Type
- class DataVariable[source]
Bases:
CoreDataVariable- __init__(view: BinaryView, address: int, type: Type, auto_discovered: bool)[source]
- Parameters:
view (BinaryView) –
address (int) –
type (Type) –
auto_discovered (bool) –
- classmethod from_core_struct(var: BNDataVariable, view: BinaryView) DataVariable[source]
- Parameters:
var (BNDataVariable) –
view (BinaryView) –
- Return type:
- property code_refs: Generator[ReferenceSource, None, None]
code references to this data variable (read-only)
- property data_refs: Generator[int, None, None] | None
data cross references to this data variable (read-only)
- property data_refs_from: Generator[int, None, None] | None
data cross references from this data variable (read-only)
- property symbol: CoreSymbol | None
- property type: Type
- property value: Any
- class DataVariableAndName[source]
Bases:
CoreDataVariable
- class FunctionList[source]
Bases:
object- __init__(view: BinaryView)[source]
- Parameters:
view (BinaryView) –
- class MemoryMap[source]
Bases:
objectThe MemoryMap object is used to describe a system level MemoryMap for which a BinaryView is loaded into. A loaded BinaryView has a view into the MemoryMap which is described by the Segments defined in that BinaryView. The MemoryMap object allows for the addition of multiple, arbitrary overlapping regions of memory. Segmenting of the address space is automatically handled when the MemoryMap is modified and in the case where a portion of the system address space has multiple defined regions, the default ordering gives priority to the most recently added region. This feature is experimental and under active development.
- Example:
>>> base = 0x10000 >>> rom_base = 0xc0000000 >>> segments = SegmentDescriptorList(base) >>> segments.append(start=base, length=0x1000, data_offset=0, data_length=0x1000, flags=SegmentFlag.SegmentReadable|SegmentFlag.SegmentExecutable) >>> segments.append(start=rom_base, length=0x1000, flags=SegmentFlag.SegmentReadable) >>> view = load(bytes.fromhex('5054ebfe'), options={'loader.imageBase': base, 'loader.platform': 'x86', 'loader.segments': json.dumps(segments)}) >>> view.memory_map <region: 0x10000 - 0x10004> size: 0x4 objects: 'origin<Mapped>@0x0' | Mapped<Absolute> | <r-x> <region: 0xc0000000 - 0xc0001000> size: 0x1000 objects: 'origin<Mapped>@0xbfff0000' | Unmapped | <r--> | FILL<0x0> <region: 0xc0001000 - 0xc0001014> size: 0x14 objects: 'origin<Mapped>@0xbfff1000' | Unmapped | <---> | FILL<0x0> >>> view.memory_map.add_memory_region("rom", rom_base, b'\x90' * 4096, SegmentFlag.SegmentReadable | SegmentFlag.SegmentExecutable) True >>> view.memory_map <region: 0x10000 - 0x10004> size: 0x4 objects: 'origin<Mapped>@0x0' | Mapped<Absolute> | <r-x> <region: 0xc0000000 - 0xc0001000> size: 0x1000 objects: 'rom' | Mapped<Relative> | <r-x> 'origin<Mapped>@0xbfff0000' | Unmapped | <r--> | FILL<0x0> <region: 0xc0001000 - 0xc0001014> size: 0x14 objects: 'origin<Mapped>@0xbfff1000' | Unmapped | <---> | FILL<0x0> >>> view.read(rom_base, 16) b'\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90' >>> view.memory_map.add_memory_region("pad", rom_base, b'\xa5' * 8) True >>> view.read(rom_base, 16) b'\xa5\xa5\xa5\xa5\xa5\xa5\xa5\xa5\x90\x90\x90\x90\x90\x90\x90\x90' >>> view.memory_map <region: 0x10000 - 0x10004> size: 0x4 objects: 'origin<Mapped>@0x0' | Mapped<Absolute> | <r-x> <region: 0xc0000000 - 0xc0000008> size: 0x8 objects: 'pad' | Mapped<Relative> | <---> 'rom' | Mapped<Relative> | <r-x> 'origin<Mapped>@0xbfff0000' | Unmapped | <r--> | FILL<0x0> <region: 0xc0000008 - 0xc0001000> size: 0xff8 objects: 'rom' | Mapped<Relative> | <r-x> 'origin<Mapped>@0xbfff0000' | Unmapped | <r--> | FILL<0x0> <region: 0xc0001000 - 0xc0001014> size: 0x14 objects: 'origin<Mapped>@0xbfff1000' | Unmapped | <---> | FILL<0x0>
- __init__(handle: BinaryView)[source]
- Parameters:
handle (BinaryView) –
- add_memory_region(name: str, start: int, source: PathLike | str | bytes | bytearray | BinaryView | DataBuffer | FileAccessor | None = None, flags: SegmentFlag = 0, fill: int = 0, length: int | None = None) bool[source]
Adds a memory region to the memory map. Depending on the source parameter, the memory region is created as one of the following types:
BinaryMemoryRegion (*Unimplemented*): Represents a memory region loaded from a binary format.
DataMemoryRegion: Region backed by flat file or raw data (str, bytes, DataBuffer).
RemoteMemoryRegion: Ephemeral memory region via FileAccessor.
UnbackedMemoryRegion: Region not backed by any data source (requires length to be set).
The source parameter determines the type: - os.PathLike or str: File path to be loaded into memory as a DataMemoryRegion. - bytes or bytearray: Directly loaded into memory as a DataMemoryRegion. - databuffer.DataBuffer: Loaded as a DataMemoryRegion. - fileaccessor.FileAccessor: Remote proxy source. - BinaryView: (Reserved for future). - None: Creates an unbacked memory region (must specify length).
Note
If no flags are specified and the new memory region overlaps with one or more existing regions, the overlapping portions of the new region will inherit the flags of the respective underlying regions.
- Parameters:
name (str): A unique name for the memory region. start (int): Starting address. source (Optional[Union[os.PathLike, str, bytes, bytearray, BinaryView, databuffer.DataBuffer, fileaccessor.FileAccessor]]): Source of data or None for unbacked. length (Optional[int]): Required if source is None (unbacked). flags (SegmentFlag): Flags to apply to the memory region. Defaults to 0 (no flags). fill (int): Fill byte for unbacked regions. Defaults to 0.
- Returns:
bool: True if the memory region was successfully added, False otherwise.
- Raises:
NotImplementedError: If source type is unsupported. ValueError: If source is None and length is not specified.
- Parameters:
name (str) –
start (int) –
source (PathLike | str | bytes | bytearray | BinaryView | DataBuffer | FileAccessor | None) –
flags (SegmentFlag) –
fill (int) –
length (int | None) –
- Return type:
- reset()[source]
- set_logical_memory_map_enabled(enabled: bool) None[source]
Enable or disable the logical memory map.
When enabled, the memory map will present a simplified, logical view that merges and abstracts virtual memory regions based on criteria such as contiguity and flag consistency. This view is designed to provide a higher-level representation for user analysis, hiding underlying mapping details.
When disabled, the memory map will revert to displaying the virtual view, which corresponds directly to the individual segments mapped from the raw file without any merging or abstraction.
- Parameters:
enabled (bool) – True to enable the logical view, False to revert to the virtual view.
- Return type:
None
- set_memory_region_flags(name: str, flags: SegmentFlag) bool[source]
- Parameters:
name (str) –
flags (SegmentFlag) –
- Return type:
- property base
Formatted string of the base memory map, consisting of unresolved auto and user segments (read-only).
- property is_activated
Whether the memory map is activated for the associated view.
- class NotificationType[source]
Bases:
IntFlagAn enumeration.
- BinaryDataUpdates = 14
- ComponentAdded = 4294967296
- ComponentDataVariableAdded = 137438953472
- ComponentDataVariableRemoved = 274877906944
- ComponentFunctionAdded = 34359738368
- ComponentFunctionRemoved = 68719476736
- ComponentMoved = 17179869184
- ComponentNameUpdated = 2147483648
- ComponentRemoved = 8589934592
- ComponentUpdates = 545460846592
- DataInserted = 4
- DataMetadataUpdated = 2048
- DataRemoved = 8
- DataVariableAdded = 256
- DataVariableLifetime = 768
- DataVariableRemoved = 512
- DataVariableUpdated = 1024
- DataVariableUpdates = 1792
- DataWritten = 2
- ExternalLibraryAdded = 549755813888
- ExternalLibraryLifetime = 1649267441664
- ExternalLibraryRemoved = 1099511627776
- ExternalLibraryUpdated = 2199023255552
- ExternalLibraryUpdates = 3848290697216
- ExternalLocationAdded = 4398046511104
- ExternalLocationLifetime = 13194139533312
- ExternalLocationRemoved = 8796093022208
- ExternalLocationUpdated = 17592186044416
- ExternalLocationUpdates = 30786325577728
- FunctionAdded = 16
- FunctionLifetime = 48
- FunctionRemoved = 32
- FunctionUpdateRequested = 128
- FunctionUpdated = 64
- FunctionUpdates = 112
- NotificationBarrier = 1
- RedoEntryTaken = 2251799813685248
- SectionAdded = 268435456
- SectionLifetime = 805306368
- SectionRemoved = 536870912
- SectionUpdated = 1073741824
- SectionUpdates = 1879048192
- SegmentAdded = 33554432
- SegmentLifetime = 100663296
- SegmentRemoved = 67108864
- SegmentUpdated = 134217728
- SegmentUpdates = 234881024
- StringFound = 524288
- StringRemoved = 1048576
- StringUpdates = 1572864
- SymbolAdded = 65536
- SymbolLifetime = 196608
- SymbolRemoved = 131072
- SymbolUpdated = 262144
- SymbolUpdates = 458752
- TagAdded = 8192
- TagLifetime = 24576
- TagRemoved = 16384
- TagTypeUpdated = 4096
- TagUpdated = 32768
- TagUpdates = 57344
- TypeArchiveAttached = 35184372088832
- TypeArchiveConnected = 140737488355328
- TypeArchiveDetached = 70368744177664
- TypeArchiveDisconnected = 281474976710656
- TypeArchiveUpdates = 527765581332480
- TypeDefined = 2097152
- TypeFieldReferenceChanged = 16777216
- TypeLifetime = 6291456
- TypeReferenceChanged = 8388608
- TypeUndefined = 4194304
- TypeUpdates = 31457280
- UndoEntryAdded = 562949953421312
- UndoEntryTaken = 1125899906842624
- UndoUpdates = 3940649673949184
- class ReferenceSource[source]
Bases:
objectReferenceSource(function: Optional[ForwardRef(‘_function.Function’)], arch: Optional[ForwardRef(‘architecture.Architecture’)], address: int)
- __init__(function: Function | None, arch: Architecture | None, address: int) None
- Parameters:
function (Function | None) –
arch (Architecture | None) –
address (int) –
- Return type:
None
- address: int
- arch: Architecture | None
- property hlil: HighLevelILInstruction | None
Returns the high level il instruction at the current location if one exists
- property hlils: Iterator[HighLevelILInstruction]
Returns the high level il instructions at the current location if any exists
- property llil: LowLevelILInstruction | None
Returns the low level il instruction at the current location if one exists
- property llils: Iterator[LowLevelILInstruction]
Returns the low level il instructions at the current location if any exists
- property mlil: MediumLevelILInstruction | None
Returns the medium level il instruction at the current location if one exists
- property mlils: Iterator[MediumLevelILInstruction]
Returns the medium level il instructions at the current location if any exists
- class Relocation[source]
Bases:
object- __init__(handle: LP_BNRelocation)[source]
- Parameters:
handle (LP_BNRelocation) –
- property arch: Architecture | None
The architecture associated with the
Relocation(read/write)
- property info: RelocationInfo
- property reloc: int
The actual pointer that needs to be relocated
- property symbol: CoreSymbol | None
- property target: int
Where the reloc needs to point to
- class RelocationInfo[source]
Bases:
objectRelocationInfo(info: binaryninja._binaryninjacore.BNRelocationInfo)
- __init__(info: BNRelocationInfo)[source]
- Parameters:
info (BNRelocationInfo) –
- addend: int
- address: int
- base: int
- base_relative: bool
- data_relocation: bool
- external: bool
- has_sign: bool
- implicit_addend: bool
- native_type: int
- pc_relative: bool
- section_index: int
- size: int
- symbol_index: int
- target: int
- truncate_size: int
- type: RelocationType
- class Section[source]
Bases:
objectThe
Sectionobject is returned during BinaryView creation and should not be directly instantiated.- __init__(handle: LP_BNSection)[source]
- Parameters:
handle (LP_BNSection) –
- classmethod serialize(image_base: int, name: str, start: int, length: int, semantics: SectionSemantics = SectionSemantics.DefaultSectionSemantics, type: str = '', align: int = 1, entry_size: int = 0, link: str = '', info_section: str = '', info_data: int = 0, auto_defined: bool = True, sections: str = '[]')[source]
Serialize section parameters into a JSON string. This is useful for generating a properly formatted section description as options when using load.
- Parameters:
image_base (int) – The base address of the image.
name (str) – The name of the section.
start (int) – The start address of the section.
length (int) – The length of the section.
semantics (SectionSemantics) – The semantics of the section.
type (str) – The type of the section.
align (int) – The alignment of the section.
entry_size (int) – The entry size of the section.
link (str) – The linked section of the section.
info_section (str) – The info section of the section.
info_data (int) – The info data of the section.
auto_defined (bool) – Whether the section is auto-defined.
sections (str) – An optional, existing array of sections to append to.
- Returns:
A JSON string representing the section.
- Return type:
Deprecated since version 4.3.6653: Use SectionDescriptorList instead.
- property align: int
- property auto_defined: bool
- property end: int
- property entry_size: int
- property info_data: int
- property info_section: str
- property length
- property linked_section: str
- property name: str
- property semantics: SectionSemantics
- property start: int
- property type: str
- class SectionDescriptorList[source]
Bases:
list- __init__(image_base: int)[source]
Initialize the SectionDescriptorList with a base image address.
- Parameters:
image_base (int) – The base address of the image.
- append(name: str, start: int, length: int, semantics: SectionSemantics = SectionSemantics.DefaultSectionSemantics, type: str = '', align: int = 1, entry_size: int = 0, link: str = '', info_section: str = '', info_data: int = 0, auto_defined: bool = True)[source]
Append a section descriptor to the list.
- Parameters:
name (str) – The name of the section.
start (int) – The start address of the section.
length (int) – The length of the section.
semantics (SectionSemantics) – The semantics of the section.
type (str) – The type of the section.
align (int) – The alignment of the section.
entry_size (int) – The size of each entry in the section.
link (str) – An optional link field.
info_section (str) – An optional info_section field.
info_data (int) – An optional info_data field.
auto_defined (bool) – Whether the section is auto-defined.
- class Segment[source]
Bases:
objectThe
Segmentobject is returned during BinaryView creation and should not be directly instantiated.- __init__(handle: LP_BNSegment)[source]
- Parameters:
handle (LP_BNSegment) –
- classmethod serialize(image_base: int, start: int, length: int, data_offset: int = 0, data_length: int = 0, flags: SegmentFlag = SegmentFlag.SegmentReadable, auto_defined=True, segments: str = '[]')[source]
Serialize segment parameters into a JSON string. This is useful for generating a properly formatted segment description as options when using load.
- Parameters:
image_base (int) – The base address of the image.
start (int) – The start address of the segment.
length (int) – The length of the segment.
data_offset (int) – The offset of the data within the segment.
data_length (int) – The length of the data within the segment.
flags (SegmentFlag) – The flags of the segment.
auto_defined (bool) – Whether the segment is auto-defined.
segments (str) – An optional, existing array of segments to append to.
- Returns:
A JSON string representing the segment.
- Return type:
- Example::
>>> base = 0x400000 >>> rom_base = 0xffff0000 >>> segments = SegmentDescriptorList(base) >>> segments.append(start=base, length=0x1000, data_offset=0, data_length=0x1000, flags=SegmentFlag.SegmentReadable|SegmentFlag.SegmentExecutable) >>> segments.append(start=rom_base, length=0x1000, flags=SegmentFlag.SegmentReadable) >>> view = load(bytes.fromhex('5054ebfe'), options={'loader.imageBase': base, 'loader.platform': 'x86', 'loader.segments': json.dumps(segments)})
Deprecated since version 4.3.6653: Use SegmentDescriptorList instead.
- property auto_defined: bool
- property data_end: int
- property data_length: int
- property data_offset: int
- property end: int
- property executable: bool
- property length
- property readable: bool
- property start: int
- property writable: bool
- class SegmentDescriptorList[source]
Bases:
list- __init__(image_base: int)[source]
Initialize the SegmentDescriptorList with a base image address.
- Parameters:
image_base (int) – The base address of the image.
- append(start: int, length: int, data_offset: int = 0, data_length: int = 0, flags: SegmentFlag = SegmentFlag.SegmentReadable, auto_defined: bool = True)[source]
Append a segment descriptor to the list.
- Parameters:
start (int) – The start address of the segment.
length (int) – The length of the segment.
data_offset (int) – The offset of the data within the segment.
data_length (int) – The length of the data within the segment.
flags (SegmentFlag) – The flags of the segment.
auto_defined (bool) – Whether the segment is auto-defined.
- class StringReference[source]
Bases:
object- __init__(bv: BinaryView, string_type: StringType, start: int, length: int)[source]
- Parameters:
bv (BinaryView) –
string_type (StringType) –
start (int) –
length (int) –
- property length: int
- property raw: bytes
- property start: int
- property type: StringType
- property value: str
- property view: BinaryView
- class StructuredDataValue[source]
Bases:
objectStructuredDataValue()
- address: int
- endian: Endianness
- property int: int
- property str: str
- type: Type
- value: bytes
- property width: int
- class SymbolMapping[source]
Bases:
MappingSymbolMapping object is used to improve performance of the bv.symbols API. This allows pythonic code like this to have reasonable performance characteristics
>>> my_symbols = get_my_symbols() >>> for symbol in my_symbols: >>> if bv.symbols[symbol].address == 0x41414141: >>> print("Found")
- __init__(view: BinaryView)[source]
- Parameters:
view (BinaryView) –
- get(k[, d]) D[k] if k in D, else d. d defaults to None.[source]
- Parameters:
key (str) –
default (List[CoreSymbol] | None) –
- Return type:
List[CoreSymbol] | None
- items() a set-like object providing a view on D's items[source]
- Return type:
- values() an object providing a view on D's values[source]
- Return type:
- class Tag[source]
Bases:
objectThe
Tagobject is created by other APIs (create_*_tag) and should not be directly instantiated.- __init__(handle: LP_BNTag)[source]
- Parameters:
handle (LP_BNTag) –
- property data: str
- property id: str
- property type: TagType
- class TagType[source]
Bases:
objectThe
TagTypeobject is created by the create_tag_type API and should not be directly instantiated.- __init__(handle: LP_BNTagType)[source]
- Parameters:
handle (LP_BNTagType) –
- property icon: str
Unicode str containing an emoji to be used as an icon
- property id: str
Unique id of the TagType
- property name: str
Name of the TagType
- property type: TagTypeType
Type from enums.TagTypeType
- property visible: bool
Boolean for whether the tags of this type are visible
- class TypeMapping[source]
Bases:
MappingTypeMapping object is used to improve performance of the bv.types API. This allows pythonic code like this to have reasonable performance characteristics
>>> my_types = get_my_types() >>> for type_name in my_types: >>> if bv.types[type_name].width == 4: >>> print("Found")
- __init__(view: ~binaryninja.binaryview.BinaryView, get_list_fn=<function BNGetAnalysisTypeList>)[source]
- Parameters:
view (BinaryView) –
- get(k[, d]) D[k] if k in D, else d. d defaults to None.[source]
- items() a set-like object providing a view on D's items[source]
- keys() a set-like object providing a view on D's keys[source]
- values() an object providing a view on D's values[source]
- class TypedDataAccessor[source]
Bases:
objectTypedDataAccessor(type: ‘_types.Type’, address: int, view: ‘BinaryView’, endian: binaryninja.enums.Endianness)
- __init__(type: Type, address: int, view: BinaryView, endian: Endianness) None
- Parameters:
type (Type) –
address (int) –
view (BinaryView) –
endian (Endianness) –
- Return type:
None
- as_uuid(ms_format: bool = True) UUID[source]
Converts the object to a UUID object using Microsoft byte ordering.
- Parameters:
ms_format (bool) – Flag indicating whether to use Microsoft byte ordering. Default is True.
- Returns:
The UUID object representing the byte array.
- Return type:
- Raises:
ValueError – If the byte array representation of this data is not exactly 16 bytes long.
- static int_from_bytes(data: bytes, width: int, sign: bool, endian: Endianness | None = None) int[source]
- Parameters:
data (bytes) –
width (int) –
sign (bool) –
endian (Endianness | None) –
- Return type:
- address: int
- endian: Endianness
- type: Type
- property value: Any
- view: BinaryView
- TypedDataReader
alias of
TypedDataAccessor
ActiveAnalysisInfo¶
AdvancedILFunctionList¶
- class AdvancedILFunctionList[source]¶
Bases:
objectThe purpose of this class is to generate IL functions IL function in the background improving the performance of iterating MediumLevelIL and HighLevelILFunctions.
Using this class or the associated helper methods BinaryView.mlil_functions / BinaryView.hlil_functions can improve the performance of ILFunction iteration significantly
The prefetch_limit property is configurable and should be modified based upon your machines hardware and RAM limitations.
Warning
Setting the prefetch_limit excessively high can result in high memory utilization.
- Example:
>>> import timeit >>> len(bv.functions) 4817 >>> # Calculate the average time to generate hlil for all functions withing 'bv': >>> timeit.timeit(lambda:[f.hlil for f in bv.functions], number=1) 21.761621682000168 >>> t1 = _ >>> # Now try again with the advanced analysis iterator >>> timeit.timeit(lambda:[f for f in bv.hlil_functions(128)], number=1) 6.3147709989998475 >>> t1/_ 3.4461458199270947 >>> # This particular binary can iterate hlil functions 3.4x faster >>> # If you don't need IL then its still much faster to just use `bv.functions` >>> timeit.timeit(lambda:[f for f in bv.functions], number=1) 0.02230275600004461
- __init__(view: BinaryView, preload_limit: int = 19, functions: Iterable | None = None)[source]¶
- Parameters:
view (BinaryView) –
preload_limit (int) –
functions (Iterable | None) –
AnalysisCompletionEvent¶
- class AnalysisCompletionEvent[source]¶
Bases:
objectThe
AnalysisCompletionEventobject provides an asynchronous mechanism for receiving callbacks when analysis is complete. The callback runs once. A completion event must be added for each new analysis in order to be notified of each analysis completion. The AnalysisCompletionEvent class takes responsibility for keeping track of the object’s lifetime.- Example:
>>> def on_complete(self): ... print("Analysis Complete", self._view) ... >>> evt = AnalysisCompletionEvent(bv, on_complete) >>>
- __init__(view: BinaryView, callback: Callable[[AnalysisCompletionEvent], None] | Callable[[], None])[source]¶
- Parameters:
view (BinaryView) –
callback (Callable[[AnalysisCompletionEvent], None] | Callable[[], None]) –
- cancel() None[source]¶
The
cancelmethod will cancel analysis for anAnalysisCompletionEvent.Warning
This method should only be used when the system is being shut down and no further analysis should be done afterward.
- Return type:
None
- property view: BinaryView¶
AnalysisInfo¶
- class AnalysisInfo[source]¶
Bases:
objectAnalysisInfo(state: binaryninja.enums.AnalysisState, analysis_time: int, active_info: List[binaryninja.binaryview.ActiveAnalysisInfo])
- __init__(state: AnalysisState, analysis_time: int, active_info: List[ActiveAnalysisInfo]) None¶
- Parameters:
state (AnalysisState) –
analysis_time (int) –
active_info (List[ActiveAnalysisInfo]) –
- Return type:
None
- active_info: List[ActiveAnalysisInfo]¶
- state: AnalysisState¶
AnalysisProgress¶
- class AnalysisProgress[source]¶
Bases:
objectAnalysisProgress(state: binaryninja.enums.AnalysisState, count: int, total: int)
- __init__(state: AnalysisState, count: int, total: int) None¶
- Parameters:
state (AnalysisState) –
count (int) –
total (int) –
- Return type:
None
- state: AnalysisState¶
BinaryDataNotification¶
- class BinaryDataNotification[source]¶
Bases:
objectclass BinaryDataNotificationprovides an interface for receiving event notifications. Usage requires inheriting from this interface, overriding the relevant event handlers, and registering the BinaryDataNotification instance with a BinaryView using the register_notification method.By default, a BinaryDataNotification instance receives notifications for all available notification types. It is recommended for users of this interface to initialize the BinaryDataNotification base class with specific callbacks of interest by passing the appropriate NotificationType flags into the __init__ constructor.
Handlers provided by the user should aim to limit the amount of processing within the callback. The callback context holds a global lock, preventing other threads from making progress during the callback phase. While most of the API can be used safely during this time, care must be taken when issuing a call that can block, as waiting for a thread requiring the global lock can result in deadlock.
The NotificationBarrier is a special NotificationType that is disabled by default. To enable it, the NotificationBarrier flag must be passed to __init__. This notification is designed to facilitate efficient batch processing of other notification types. The idea is to collect other notifications of interest into a cache, which can be very efficient as it doesn’t require additional locks. After some time, the core generates a NotificationBarrier event, providing a safe context to move the cache for processing by a different thread.
To control the time of the next NotificationBarrier event, return the desired number of milliseconds until the next event from the NotificationBarrier callback. Returning zero quiesces future NotificationBarrier events. If the NotificationBarrier is quiesced, the reception of a new callback of interest automatically generates a new NotificationBarrier call after that notification is delivered. This mechanism effectively allows throttling and quiescing when necessary.
Note
Note that the core generates a NotificationBarrier as part of the BinaryDataNotification registration process. Registering the same BinaryDataNotification instance again results in a gratuitous NotificationBarrier event, which can be useful in situations requiring a safe context for processing due to some other asynchronous event (e.g., user interaction).
- Example:
>>> class NotifyTest(binaryninja.BinaryDataNotification): ... def __init__(self): ... super(NotifyTest, self).__init__(binaryninja.NotificationType.NotificationBarrier | binaryninja.NotificationType.FunctionLifetime | binaryninja.NotificationType.FunctionUpdated) ... self.received_event = False ... def notification_barrier(self, view: 'BinaryView') -> int: ... has_events = self.received_event ... self.received_event = False ... log_info("notification_barrier") ... if has_events: ... return 250 ... else: ... return 0 ... def function_added(self, view: 'BinaryView', func: '_function.Function') -> None: ... self.received_event = True ... log_info("function_added") ... def function_removed(self, view: 'BinaryView', func: '_function.Function') -> None: ... self.received_event = True ... log_info("function_removed") ... def function_updated(self, view: 'BinaryView', func: '_function.Function') -> None: ... self.received_event = True ... log_info("function_updated") ... >>> >>> bv.register_notification(NotifyTest()) >>>
- __init__(notifications: NotificationType | None = None)[source]¶
- Parameters:
notifications (NotificationType | None) –
- component_added(view: BinaryView, _component: Component) None[source]¶
- Parameters:
view (BinaryView) –
_component (Component) –
- Return type:
None
- component_data_var_added(view: BinaryView, _component: Component, var: DataVariable)[source]¶
- Parameters:
view (BinaryView) –
_component (Component) –
var (DataVariable) –
- component_data_var_removed(view: BinaryView, _component: Component, var: DataVariable)[source]¶
- Parameters:
view (BinaryView) –
_component (Component) –
var (DataVariable) –
- component_function_added(view: BinaryView, _component: Component, func: Function)[source]¶
- Parameters:
view (BinaryView) –
_component (Component) –
func (Function) –
- component_function_removed(view: BinaryView, _component: Component, func: Function)[source]¶
- Parameters:
view (BinaryView) –
_component (Component) –
func (Function) –
- component_moved(view: BinaryView, formerParent: Component, newParent: Component, _component: Component) None[source]¶
- Parameters:
view (BinaryView) –
formerParent (Component) –
newParent (Component) –
_component (Component) –
- Return type:
None
- component_name_updated(view: BinaryView, previous_name: str, _component: Component) None[source]¶
- Parameters:
view (BinaryView) –
previous_name (str) –
_component (Component) –
- Return type:
None
- component_removed(view: BinaryView, formerParent: Component, _component: Component) None[source]¶
- Parameters:
view (BinaryView) –
formerParent (Component) –
_component (Component) –
- Return type:
None
- data_inserted(view: BinaryView, offset: int, length: int) None[source]¶
- Parameters:
view (BinaryView) –
offset (int) –
length (int) –
- Return type:
None
- data_metadata_updated(view: BinaryView, offset: int) None[source]¶
- Parameters:
view (BinaryView) –
offset (int) –
- Return type:
None
- data_removed(view: BinaryView, offset: int, length: int) None[source]¶
- Parameters:
view (BinaryView) –
offset (int) –
length (int) –
- Return type:
None
- data_var_added(view: BinaryView, var: DataVariable) None[source]¶
Note
data_var_updated will be triggered instead when a user data variable is added over an auto data variable.
- Parameters:
view (BinaryView) –
var (DataVariable) –
- Return type:
None
- data_var_removed(view: BinaryView, var: DataVariable) None[source]¶
Note
data_var_updated will be triggered instead when a user data variable is removed over an auto data variable.
- Parameters:
view (BinaryView) –
var (DataVariable) –
- Return type:
None
- data_var_updated(view: BinaryView, var: DataVariable) None[source]¶
- Parameters:
view (BinaryView) –
var (DataVariable) –
- Return type:
None
- data_written(view: BinaryView, offset: int, length: int) None[source]¶
- Parameters:
view (BinaryView) –
offset (int) –
length (int) –
- Return type:
None
- function_added(view: BinaryView, func: Function) None[source]¶
Note
function_updated will be triggered instead when a user function is added over an auto function.
- Parameters:
view (BinaryView) –
func (Function) –
- Return type:
None
- function_removed(view: BinaryView, func: Function) None[source]¶
Note
function_updated will be triggered instead when a user function is removed over an auto function.
- Parameters:
view (BinaryView) –
func (Function) –
- Return type:
None
- function_update_requested(view: BinaryView, func: Function) None[source]¶
- Parameters:
view (BinaryView) –
func (Function) –
- Return type:
None
- function_updated(view: BinaryView, func: Function) None[source]¶
- Parameters:
view (BinaryView) –
func (Function) –
- Return type:
None
- notification_barrier(view: BinaryView) int[source]¶
- Parameters:
view (BinaryView) –
- Return type:
- redo_entry_taken(view: BinaryView, entry: UndoEntry)[source]¶
- Parameters:
view (BinaryView) –
entry (UndoEntry) –
- section_added(view: BinaryView, section: Section) None[source]¶
- Parameters:
view (BinaryView) –
section (Section) –
- Return type:
None
- section_removed(view: BinaryView, section: Section) None[source]¶
- Parameters:
view (BinaryView) –
section (Section) –
- Return type:
None
- section_updated(view: BinaryView, section: Section) None[source]¶
- Parameters:
view (BinaryView) –
section (Section) –
- Return type:
None
- segment_added(view: BinaryView, segment: Segment) None[source]¶
- Parameters:
view (BinaryView) –
segment (Segment) –
- Return type:
None
- segment_removed(view: BinaryView, segment: Segment) None[source]¶
- Parameters:
view (BinaryView) –
segment (Segment) –
- Return type:
None
- segment_updated(view: BinaryView, segment: Segment) None[source]¶
- Parameters:
view (BinaryView) –
segment (Segment) –
- Return type:
None
- string_found(view: BinaryView, string_type: StringType, offset: int, length: int) None[source]¶
- Parameters:
view (BinaryView) –
string_type (StringType) –
offset (int) –
length (int) –
- Return type:
None
- string_removed(view: BinaryView, string_type: StringType, offset: int, length: int) None[source]¶
- Parameters:
view (BinaryView) –
string_type (StringType) –
offset (int) –
length (int) –
- Return type:
None
- symbol_added(view: BinaryView, sym: CoreSymbol) None[source]¶
- Parameters:
view (BinaryView) –
sym (CoreSymbol) –
- Return type:
None
- symbol_removed(view: BinaryView, sym: CoreSymbol) None[source]¶
- Parameters:
view (BinaryView) –
sym (CoreSymbol) –
- Return type:
None
- symbol_updated(view: BinaryView, sym: CoreSymbol) None[source]¶
- Parameters:
view (BinaryView) –
sym (CoreSymbol) –
- Return type:
None
- tag_added(view: BinaryView, tag: Tag, ref_type: TagReferenceType, auto_defined: bool, arch: Architecture | None, func: Function | None, addr: int) None[source]¶
- Parameters:
view (BinaryView) –
tag (Tag) –
ref_type (TagReferenceType) –
auto_defined (bool) –
arch (Architecture | None) –
func (Function | None) –
addr (int) –
- Return type:
None
- tag_removed(view: BinaryView, tag: Tag, ref_type: TagReferenceType, auto_defined: bool, arch: Architecture | None, func: Function | None, addr: int) None[source]¶
- Parameters:
view (BinaryView) –
tag (Tag) –
ref_type (TagReferenceType) –
auto_defined (bool) –
arch (Architecture | None) –
func (Function | None) –
addr (int) –
- Return type:
None
- tag_type_updated(view: BinaryView, tag_type) None[source]¶
- Parameters:
view (BinaryView) –
- Return type:
None
- tag_updated(view: BinaryView, tag: Tag, ref_type: TagReferenceType, auto_defined: bool, arch: Architecture | None, func: Function | None, addr: int) None[source]¶
- Parameters:
view (BinaryView) –
tag (Tag) –
ref_type (TagReferenceType) –
auto_defined (bool) –
arch (Architecture | None) –
func (Function | None) –
addr (int) –
- Return type:
None
- type_archive_attached(view: BinaryView, id: str, path: str)[source]¶
- Parameters:
view (BinaryView) –
id (str) –
path (str) –
- type_archive_connected(view: BinaryView, archive: TypeArchive)[source]¶
- Parameters:
view (BinaryView) –
archive (TypeArchive) –
- type_archive_detached(view: BinaryView, id: str, path: str)[source]¶
- Parameters:
view (BinaryView) –
id (str) –
path (str) –
- type_archive_disconnected(view: BinaryView, archive: TypeArchive)[source]¶
- Parameters:
view (BinaryView) –
archive (TypeArchive) –
- type_defined(view: BinaryView, name: QualifiedName, type: Type) None[source]¶
- Parameters:
view (BinaryView) –
name (QualifiedName) –
type (Type) –
- Return type:
None
- type_field_ref_changed(view: BinaryView, name: QualifiedName, offset: int) None[source]¶
- Parameters:
view (BinaryView) –
name (QualifiedName) –
offset (int) –
- Return type:
None
- type_ref_changed(view: BinaryView, name: QualifiedName, type: Type) None[source]¶
- Parameters:
view (BinaryView) –
name (QualifiedName) –
type (Type) –
- Return type:
None
- type_undefined(view: BinaryView, name: QualifiedName, type: Type) None[source]¶
- Parameters:
view (BinaryView) –
name (QualifiedName) –
type (Type) –
- Return type:
None
- undo_entry_added(view: BinaryView, entry: UndoEntry)[source]¶
- Parameters:
view (BinaryView) –
entry (UndoEntry) –
- undo_entry_taken(view: BinaryView, entry: UndoEntry)[source]¶
- Parameters:
view (BinaryView) –
entry (UndoEntry) –
BinaryDataNotificationCallbacks¶
- class BinaryDataNotificationCallbacks[source]¶
Bases:
object- __init__(view: BinaryView, notify: BinaryDataNotification)[source]¶
- Parameters:
view (BinaryView) –
notify (BinaryDataNotification) –
- property notify: BinaryDataNotification¶
- property view: BinaryView¶
BinaryReader¶
- class BinaryReader[source]¶
Bases:
objectclass BinaryReaderis a convenience class for reading binary data.BinaryReader can be instantiated as follows and the rest of the document will start from this context
>>> from binaryninja import * >>> bv = load("/bin/ls") >>> br = BinaryReader(bv) >>> hex(br.read32()) '0xfeedfacfL' >>>
Or using the optional endian parameter
>>> from binaryninja import * >>> br = BinaryReader(bv, Endianness.BigEndian) >>> hex(br.read32()) '0xcffaedfeL' >>>
- __init__(view: BinaryView, endian: Endianness | None = None, address: int | None = None)[source]¶
- Parameters:
view (BinaryView) –
endian (Endianness | None) –
address (int | None) –
- read(length: int, address: int | None = None) bytes | None[source]¶
readreturnslengthbytes read from the current offset, addinglengthto offset.
- read16(address: int | None = None) int | None[source]¶
read16returns a two byte integer from offset incrementing the offset by two, using specified endianness.
- read16be(address: int | None = None) int | None[source]¶
read16bereturns a two byte big endian integer from offset incrementing the offset by two.
- read16le(address: int | None = None) int | None[source]¶
read16lereturns a two byte little endian integer from offset incrementing the offset by two.
- read32(address: int | None = None) int | None[source]¶
read32returns a four byte integer from offset incrementing the offset by four, using specified endianness.
- read32be(address: int | None = None) int | None[source]¶
read32bereturns a four byte big endian integer from offset incrementing the offset by four.
- read32le(address: int | None = None) int | None[source]¶
read32lereturns a four byte little endian integer from offset incrementing the offset by four.
- read64(address: int | None = None) int | None[source]¶
read64returns an eight byte integer from offset incrementing the offset by eight, using specified endianness.
- read64be(address: int | None = None) int | None[source]¶
read64bereturns an eight byte big endian integer from offset incrementing the offset by eight.
- read64le(address: int | None = None) int | None[source]¶
read64lereturns an eight byte little endian integer from offset incrementing the offset by eight.
- read8(address: int | None = None) int | None[source]¶
read8returns a one byte integer from offset incrementing the offset.
- seek_relative(offset: int) None[source]¶
seek_relativeupdates the internal offset byoffset.- Parameters:
offset (int) – offset to add to the internal offset
- Return type:
None
- Example:
>>> hex(br.offset) '0x100000008L' >>> br.seek_relative(-8) >>> hex(br.offset) '0x100000000L' >>>
- property endianness: Endianness¶
The Endianness to read data. (read/write)
- Getter:
returns the endianness of the reader
- Setter:
sets the endianness of the reader (BigEndian or LittleEndian)
- Type:
- property eof: bool¶
Is end of file (read-only)
- Getter:
returns boolean, true if end of file, false otherwise
- Type:
BinaryView¶
- class BinaryView[source]¶
Bases:
objectclass BinaryViewimplements a view on binary data, and presents a queryable interface of a binary file. One key job of BinaryView is file format parsing which allows Binary Ninja to read, write, insert, remove portions of the file given a virtual address. For the purposes of this documentation we define a virtual address as the memory address that the various pieces of the physical file will be loaded at.A binary file does not have to have just one BinaryView, thus much of the interface to manipulate disassembly exists within or is accessed through a BinaryView. All files are guaranteed to have at least the
RawBinaryView. TheRawBinaryView is simply a hex editor, but is helpful for manipulating binary files via their absolute addresses.BinaryViews are plugins and thus registered with Binary Ninja at startup, and thus should never be instantiated directly as this is already done. The list of available BinaryViews can be seen in the BinaryViewType class which provides an iterator and map of the various installed BinaryViews:
>>> list(BinaryViewType) [<view type: 'Raw'>, <view type: 'ELF'>, <view type: 'Mach-O'>, <view type: 'PE'>] >>> BinaryViewType['ELF'] <view type: 'ELF'>
To open a file with a given BinaryView the following code is recommended:
>>> with load("/bin/ls") as bv: ... bv <BinaryView: '/bin/ls', start 0x100000000, len 0x142c8>
By convention in the rest of this document we will use bv to mean an open and, analyzed, BinaryView of an executable file. When a BinaryView is open on an executable view analysis is automatically run unless specific named parameters are used to disable updates. If such a parameter is used, updates can be triggered using the
update_analysis_and_waitmethod which disassembles the executable and returns when all disassembly and analysis is complete:>>> bv.update_analysis_and_wait() >>>
Since BinaryNinja’s analysis is multi-threaded (depending on version) this can also be done in the background by using the
update_analysismethod instead.By standard python convention methods which start with ‘_’ should be considered private and should not be called externally. Additionally, methods which begin with
perform_should not be called directly either and are used explicitly for subclassing a BinaryView.Note
An important note on the
*_user_*()methods. Binary Ninja makes a distinction between edits performed by the user and actions performed by auto analysis. Auto analysis actions that can quickly be recalculated are not saved to the database. Auto analysis actions that take a long time and all user edits are stored in the database (e.g.remove_user_functionrather thanremove_function). Thus use_user_methods if saving to the database is desired.- __init__(file_metadata: FileMetadata | None = None, parent_view: BinaryView | None = None, handle: LP_BNBinaryView | None = None)[source]¶
- Parameters:
file_metadata (FileMetadata | None) –
parent_view (BinaryView | None) –
handle (LP_BNBinaryView | None) –
- abort_analysis() None[source]¶
abort_analysisaborts analysis and suspends the workflow machine. This operation is recoverable, and the workflow machine can be re-enabled via theenableAPI on WorkflowMachine.- Return type:
None
- add_analysis_completion_event(callback: Callable[[], None]) AnalysisCompletionEvent[source]¶
add_analysis_completion_eventsets up a call back function to be called when analysis has been completed. This is helpful when usingupdate_analysiswhich does not wait for analysis completion before returning.The callee of this function is not responsible for maintaining the lifetime of the returned AnalysisCompletionEvent object.
Note
The lock held by the callback thread on the BinaryView instance ensures that other BinaryView actions can be safely performed in the callback thread.
Warning
The built-in python console automatically updates analysis after every command is run, which means this call back may not behave as expected if entered interactively.
- Parameters:
callback (callback) – A function to be called with no parameters when analysis has completed.
- Returns:
An initialized AnalysisCompletionEvent object
- Return type:
- Example:
>>> def completionEvent(): ... print("done") ... >>> bv.add_analysis_completion_event(completionEvent) <binaryninja.AnalysisCompletionEvent object at 0x10a2c9f10> >>> bv.update_analysis() done >>>
- add_analysis_option(name: str) None[source]¶
add_analysis_optionadds an analysis option. Analysis options elaborate the analysis phase. The user must start analysis by calling eitherupdate_analysisorupdate_analysis_and_wait.- Parameters:
name (str) – name of the analysis option. Available options are: “linearsweep”, and “signaturematcher”.
- Return type:
None
- Example:
>>> bv.add_analysis_option("linearsweep") >>> bv.update_analysis_and_wait()
- add_auto_section(name: str, start: int, length: int, semantics: SectionSemantics = SectionSemantics.DefaultSectionSemantics, type: str = '', align: int = 1, entry_size: int = 1, linked_section: str = '', info_section: str = '', info_data: int = 0) None[source]¶
- add_auto_segment(start: int, length: int, data_offset: int, data_length: int, flags: SegmentFlag) None[source]¶
add_auto_segmentAdds an analysis segment that specifies how data from the raw file is mapped into a virtual address spaceNote that the segments added may have different size attributes than requested
- Parameters:
start (int) –
length (int) –
data_offset (int) –
data_length (int) –
flags (SegmentFlag) –
- Return type:
None
- add_auto_segments(segments: List[BNSegmentInfo]) None[source]¶
add_auto_segmentsAdds analysis segments that specify how data from the raw file is mapped into a virtual address space- Parameters:
segments (List[core.BNSegmentInfo]) – list of segments to add
- Return type:
None
- add_data_ref(from_addr: int, to_addr: int) None[source]¶
add_data_refadds an auto data cross-reference (xref) from the addressfrom_addrto the addressto_addr.- Parameters:
- Return type:
None
Note
It is intended to be used from within workflows or binary view initialization.
- add_entry_point(addr: int, plat: Platform | None = None) None[source]¶
add_entry_pointadds a virtual address to start analysis from for a given plat.
- add_expression_parser_magic_value(name: str, value: int) None[source]¶
Add a magic value to the expression parser.
If the magic value already exists, its value gets updated. The magic value can be used in the expression by a $ followed by its name, e.g., $foobar. It is optional to include the $ when calling this function, i.e., calling with foobar and $foobar has the same effect.
- add_expression_parser_magic_values(names: List[str], values: List[int]) None[source]¶
Add a list of magic value to the expression parser.
The list names and values must have the same size. The ith name in the names will correspond to the ith value in the values.
If a magic value already exists, its value gets updated. The magic value can be used in the expression by a $ followed by its name, e.g., $foobar. It is optional to include the $ when calling this function, i.e., calling with foobar and $foobar has the same effect.
- add_external_library(name: str, backing_file: ProjectFile | None = None, auto: bool = False) ExternalLibrary[source]¶
Add an ExternalLibrary to this BinaryView
- Parameters:
name (str) – Name of the external library
backing_file (ProjectFile | None) – Optional ProjectFile that backs the external library
auto (bool) – Whether or not this action is the result of automated analysis
- Returns:
The created ExternalLibrary
- Return type:
- add_external_location(source_symbol: CoreSymbol, library: ExternalLibrary | None, target_symbol: str | None, target_address: int | None, auto: bool = False) ExternalLocation[source]¶
Add an ExternalLocation with its source in this BinaryView. ExternalLocations must have a target address and/or symbol.
- Parameters:
source_symbol (CoreSymbol) – Symbol that the association is from
library (ExternalLibrary | None) – Library that the ExternalLocation belongs to
target_symbol (str | None) – Symbol that the ExternalLocation points to
target_address (int | None) – Address that the ExternalLocation points to
auto (bool) – Whether or not this action is the result of automated analysis
- Returns:
The created ExternalLocation
- Return type:
- add_function(addr: int, plat: Platform | None = None, auto_discovered: bool = False, func_type: Function | None = None) Function | None[source]¶
add_functionadd a new function of the givenplatat the virtual addressaddrWarning
This function is used to create auto functions, often used when writing loaders, etc. Most users will want to use
create_user_functionin their scripts.- Parameters:
- Return type:
None
- Example:
>>> bv.add_function(1) >>> bv.functions [<func: x86_64@0x1>]
- add_tag(addr: int, tag_type_name: str, data: str, user: bool = True)[source]¶
add_tagcreates and adds aTagobject at a data address.This API is appropriate for generic data tags. For functions, consider using
add_tag.
- add_to_entry_functions(func: Function) None[source]¶
add_to_entry_functionsadds a function to the entry_functions list.- Parameters:
func (Function) – a Function object
- Return type:
None
- Example:
>>> bv.entry_functions [<func: x86@0x4014c8>, <func: x86@0x401618>] >>> bv.add_to_entry_functions(bv.get_function_at(0x4014da)) >>> bv.entry_functions [<func: x86@0x4014c8>, <func: x86@0x401618>, <func: x86@0x4014da>]
- add_type_library(lib: TypeLibrary) None[source]¶
add_type_librarymake the contents of a type library available for type/import resolution- Parameters:
lib (TypeLibrary) – library to register with the view
- Return type:
None
- add_user_data_ref(from_addr: int, to_addr: int) None[source]¶
add_user_data_refadds a user-specified data cross-reference (xref) from the addressfrom_addrto the addressto_addr. If the reference already exists, no action is performed. To remove the reference, useremove_user_data_ref.
- add_user_section(name: str, start: int, length: int, semantics: SectionSemantics = SectionSemantics.DefaultSectionSemantics, type: str = '', align: int = 1, entry_size: int = 1, linked_section: str = '', info_section: str = '', info_data: int = 0) None[source]¶
add_user_sectioncreates a user-defined section that can help inform analysis by clarifying what types of data exist in what ranges. Note that all data specified must already be mapped by an existing segment.- Parameters:
name (str) – name of the section
start (int) – virtual address of the start of the section
length (int) – length of the section
semantics (SectionSemantics) – SectionSemantics of the section
type (str) – optional type
align (int) – optional byte alignment
entry_size (int) – optional entry size
linked_section (str) – optional name of a linked section
info_section (str) – optional name of an associated informational section
info_data (int) – optional info data
- Return type:
None
- add_user_segment(start: int, length: int, data_offset: int, data_length: int, flags: SegmentFlag) None[source]¶
add_user_segmentcreates a user-defined segment that specifies how data from the raw file is mapped into a virtual address space.- Parameters:
start (int) – virtual address of the start of the segment
length (int) – length of the segment (may be larger than the source data)
data_offset (int) – offset from the parent view
data_length (int) – length of the data from the parent view
flags (SegmentFlag) – SegmentFlags
- Return type:
None
- add_user_segments(segments: List[BNSegmentInfo]) None[source]¶
add_user_segmentsAdds user-defined segments that specify how data from the raw file is mapped into a virtual address space- Parameters:
segments (List[core.BNSegmentInfo]) – list of segments to add
- Return type:
None
- always_branch(addr: int, arch: Architecture | None = None) bool[source]¶
always_branchconvert the instruction of architecturearchat the virtual addressaddrto an unconditional branch.Note
This API performs a binary patch, analysis may need to be updated afterward. Additionally the binary file must be saved in order to preserve the changes made.
- Parameters:
addr (int) – virtual address of the instruction to be modified
arch (Architecture) – (optional) the architecture of the instructions if different from the default
- Returns:
True on success, False on failure.
- Return type:
- Example:
>>> bv.get_disassembly(0x100012ef) 'jg 0x100012f5' >>> bv.always_branch(0x100012ef) True >>> bv.get_disassembly(0x100012ef) 'jmp 0x100012f5' >>>
- apply_debug_info(value: DebugInfo) None[source]¶
Sets the debug info and applies its contents to the current binary view
- Parameters:
value (DebugInfo) –
- Return type:
None
- attach_type_archive(archive: TypeArchive)[source]¶
Attach a given type archive to the analysis and try to connect to it. If attaching was successful, names from that archive will become available to pull, but no types will actually be associated by calling this.
- Parameters:
archive (TypeArchive) – New archive
- attach_type_archive_by_id(id: str, path: str) TypeArchive | None[source]¶
Attach a type archive to the owned analysis and try to connect to it. If attaching was successful, names from that archive will become available to pull, but no types will actually be associated by calling this.
The behavior of this function is rather complicated, in an attempt to enable the ability to have attached, but disconnected Type Archives.
Normal operation:
If there was no previously connected Type Archive whose id matches id, and the file at path contains a Type Archive whose id matches id, it will be attached and connected.
Edge-cases:
If there was a previously connected Type Archive whose id matches id, nothing will happen, and it will simply be returned. If the file at path does not exist, nothing will happen and None will be returned. If the file at path exists but does not contain a Type Archive whose id matches id, nothing will happen and None will be returned. If there was a previously attached but disconnected Type Archive whose id matches id, and the file at path contains a Type Archive whose id matches id, the previously attached Type Archive will have its saved path updated to point to path. The Type Archive at path will be connected and returned.
- Parameters:
- Returns:
Attached archive object, if it could be connected.
- Return type:
TypeArchive | None
- begin_bulk_add_segments() None[source]¶
begin_bulk_add_segmentsBegins a bulk segment addition operation.This function prepares the BinaryView for bulk addition of both auto and user-defined segments. During the bulk operation, segments can be added using add_auto_segment or similar functions without immediately triggering the MemoryMap update process. The queued segments will not take effect until end_bulk_add_segments is called.
- Return type:
None
- begin_undo_actions(anonymous_allowed: bool = True) str[source]¶
begin_undo_actionsstarts recording actions taken so they can be undone at some point.- Parameters:
anonymous_allowed (bool) – Legacy interop: prevent empty calls to
commit_undo_actions`from affecting this undo state. Specifically forundoable_transaction`- Returns:
Id of undo state, for passing to
commit_undo_actions`orrevert_undo_actions.- Return type:
- Example:
>>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>> state = bv.begin_undo_actions() >>> bv.convert_to_nop(0x100012f1) True >>> bv.commit_undo_actions(state) >>> bv.get_disassembly(0x100012f1) 'nop' >>> bv.undo() >>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>>
- bulk_modify_symbols()[source]¶
bulk_modify_symbolsreturns a context manager that improves performance when adding or removing a large number of symbols. Symbols added within the Python with keyword will defer processing until the end of the block. Many symbol getter APIs will return stale results inside the with block, so this function should only be used when symbol queries are not needed at the same time as the modifications.
- can_assemble(arch: Architecture | None = None) bool[source]¶
can_assemblequeries the architecture plugin to determine if the architecture can assemble instructions.- Returns:
True if the architecture can assemble, False otherwise
- Return type:
- Example:
>>> bv.can_assemble() True >>>
- Parameters:
arch (Architecture | None) –
- cancel_bulk_add_segments() None[source]¶
cancel_bulk_add_segmentsCancels a bulk segment addition operation.This function discards all auto and user segments that were queued since the last call to begin_bulk_add_segments without applying them. It allows you to abandon the changes in case they are no longer needed.
Note: If no bulk operation is in progress, calling this function has no effect.
- Return type:
None
- check_for_string_annotation_type(addr: int, allow_short_strings: bool = False, allow_large_strings: bool = False, child_width: int = 0) Tuple[str, StringType] | None[source]¶
Check for string annotation at a given address. This returns the string (and type of the string) as annotated in the UI at a given address. If there’s no annotation, this function returns None.
- Parameters:
addr (int) – address at which to check for string annotation
allow_short_strings (bool) – Allow string shorter than the analysis.limits.minStringLength setting
allow_large_strings (bool) – Allow strings longer than the rendering.strings.maxAnnotationLength setting (up to analysis.limits.maxStringLength)
child_width (int) – What width of strings to look for, 1 for ASCII/UTF8, 2 for UTF16, 4 for UTF32, 0 to check for all
- Return type:
None
- clear_user_global_pointer_value()[source]¶
Clear a previously set user global pointer value, so the auto-analysis can calculate a new value
- commit_undo_actions(id: str | None = None) None[source]¶
commit_undo_actionscommits the actions taken since a call tobegin_undo_actionsPass as id the value returned bybegin_undo_actions. Empty values of id will commit all changes since the last call tobegin_undo_actions.- Parameters:
id (Optional[str]) – id of undo state, from
begin_undo_actions- Return type:
None
- Example:
>>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>> state = bv.begin_undo_actions() >>> bv.convert_to_nop(0x100012f1) True >>> bv.commit_undo_actions(state) >>> bv.get_disassembly(0x100012f1) 'nop' >>> bv.undo() >>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>>
- convert_to_nop(addr: int, arch: Architecture | None = None) bool[source]¶
convert_to_nopconverts the instruction at virtual addressaddrto a nop of the provided architecture.Note
This API performs a binary patch, analysis may need to be updated afterward. Additionally the binary file must be saved in order to preserve the changes made.
- Parameters:
addr (int) – virtual address of the instruction to convert to nops
arch (Architecture) – (optional) the architecture of the instructions if different from the default
- Returns:
True on success, False on failure.
- Return type:
- Example:
>>> bv.get_disassembly(0x100012fb) 'call 0x10001629' >>> bv.convert_to_nop(0x100012fb) True >>> #The above 'call' instruction is 5 bytes, a nop in x86 is 1 byte, >>> # thus 5 nops are used: >>> bv.get_disassembly(0x100012fb) 'nop' >>> bv.get_disassembly(0x100012fb + 1) 'nop' >>> bv.get_disassembly(0x100012fb + 2) 'nop' >>> bv.get_disassembly(0x100012fb + 3) 'nop' >>> bv.get_disassembly(0x100012fb + 4) 'nop' >>> bv.get_disassembly(0x100012fb + 5) 'mov byte [ebp-0x1c], al'
- create_component(name: str | None = None, parent: Component | str | None = None) Component[source]¶
Create a new component with an optional name and parent.
- The parent argument can be either a Component or the Guid of a component that the created component will be
added as a child of
- create_database(filename: str, progress_func: Callable[[int, int], bool] | None = None, settings: SaveSettings | None = None) bool[source]¶
create_databasewrites the current database (.bndb) out to the specified file.Warning
This API will only save a database, NOT the original file from a view. To save the original file, use
save. To update a database, usesave_auto_snapshot- Parameters:
filename (str) – path and filename to write the bndb to, this string should have “.bndb” appended to it.
progress_func (callback) – optional function to be called with the current progress and total count.
settings (SaveSettings) – optional argument for special save options.
- Returns:
True on success, False on failure
- Return type:
Warning
The calling thread must not hold a lock on the BinaryView instance as this action is run on the main thread which requires the lock.
- create_structure_from_offset_access(name: QualifiedName) StructureType[source]¶
- Parameters:
name (QualifiedName) –
- Return type:
- create_structure_member_from_access(name: QualifiedName, offset: int) Type[source]¶
- Parameters:
name (QualifiedName) –
offset (int) –
- Return type:
- create_tag_type(name: str, icon: str) TagType[source]¶
create_tag_typecreates a newTagTypeand adds it to the view
- create_user_function(addr: int, plat: Platform | None = None) Function | None[source]¶
create_user_functionadd a new user function of the givenplatat the virtual addressaddr
- define_auto_symbol(sym: CoreSymbol) None[source]¶
define_auto_symboladds a symbol to the internal list of automatically discovered Symbol objects in a given namespace.Warning
If multiple symbols for the same address are defined, only the most recent symbol will ever be used.
- Parameters:
sym (CoreSymbol) – the symbol to define
- Return type:
None
- define_auto_symbol_and_var_or_function(sym: CoreSymbol, type: Type | None = None, plat: Platform | None = None, type_confidence: int | None = 0) CoreSymbol | None[source]¶
define_auto_symbol_and_var_or_functionDefines an “Auto” symbol, and a Variable/Function alongside it.Warning
If multiple symbols for the same address are defined, only the most recent symbol will ever be used.
- Parameters:
sym (CoreSymbol) – Symbol to define
type (Type | None) – Type for the function/variable being defined (can be None)
plat (Platform | None) – Platform (optional)
type_confidence (int | None) – Optional confidence value for the type
- Return type:
Optional[CoreSymbol]
- define_data_var(addr: int, var_type: str | Type | TypeBuilder, name: str | CoreSymbol | None = None) None[source]¶
define_data_vardefines a non-user data variablevar_typeat the virtual addressaddr.- Parameters:
addr (int) – virtual address to define the given data variable
var_type (StringOrType) – type to be defined at the given virtual address
name (str | CoreSymbol | None) – Optionally additionally define a symbol at this location
name –
- Return type:
None
- Example:
>>> t = bv.parse_type_string("int foo") >>> t (<type: int32_t>, 'foo') >>> bv.define_data_var(bv.entry_point, t[0]) >>> bv.define_data_var(bv.entry_point + 4, "int", "foo") >>> bv.get_symbol_at(bv.entry_point + 4) <DataSymbol: "foo" @ 0x23950> >>> bv.get_data_var_at(bv.entry_point + 4) <var 0x23950: int32_t>
- define_imported_function(import_addr_sym: CoreSymbol, func: Function, type: Type | None = None) None[source]¶
define_imported_functiondefines an imported Functionfuncwith a ImportedFunctionSymbol type.- Parameters:
import_addr_sym (CoreSymbol) – A Symbol object with type ImportedFunctionSymbol
func (Function) – A Function object to define as an imported function
type (Type | None) – Optional type for the function
- Return type:
None
- define_type(type_id: str, default_name: _types.QualifiedNameType | None, type_obj: str | _types.Type | _types.TypeBuilder) _types.QualifiedName[source]¶
define_typeregisters aTypetype_objof the givennamein the global list of types for the currentBinaryView. This method should only be used for automatically generated types.- Parameters:
type_id (str) – Unique identifier for the automatically generated type
default_name (QualifiedName) – Name of the type to be registered
type_obj (StringOrType) – Type object to be registered
- Returns:
Registered name of the type. May not be the same as the requested name if the user has renamed types.
- Return type:
- Example:
>>> type, name = bv.parse_type_string("int foo") >>> registered_name = bv.define_type(Type.generate_auto_type_id("source", name), name, type) >>> bv.get_type_by_name(registered_name) <type: int32_t> >>> registered_name = bv.define_type("mytypeid", None, "int bar") >>> bv.get_type_by_name(registered_name) <type: int32_t>
- define_types(types: List[Tuple[str, _types.QualifiedNameType | None, str | _types.Type | _types.TypeBuilder]], progress_func: Callable[[int, int], bool] | None) Mapping[str, _types.QualifiedName][source]¶
define_typesregisters multiple types as though callingdefine_typemultiple times. The difference with this plural version is that it is optimized for adding many types at the same time, using knowledge of all types at add-time to improve runtime. There is an optionalprogress_funccallback function in case you want updates for a long-running call.Warning
This method should only be used for automatically generated types, see
define_user_typesfor interactive plugin uses.The return values of this function provide a map of each type id and which name was chosen for that type (which may be different from the requested name).
- Parameters:
- Returns:
A map of all the chosen names for the defined types with their ids.
- Return type:
- define_user_data_var(addr: int, var_type: str | Type | TypeBuilder, name: str | CoreSymbol | None = None) DataVariable | None[source]¶
define_user_data_vardefines a user data variablevar_typeat the virtual addressaddr.- Parameters:
addr (int) – virtual address to define the given data variable
var_type (binaryninja.Type) – type to be defined at the given virtual address
name (str | CoreSymbol | None) – Optionally, additionally define a symbol at this same address
name –
- Return type:
Optional[DataVariable]
- Example:
>>> t = bv.parse_type_string("int foo") >>> t (<type: int32_t>, 'foo') >>> bv.define_user_data_var(bv.entry_point, t[0]) <var 0x2394c: int32_t> >>> bv.define_user_data_var(bv.entry_point + 4, "int", "foo") <var 0x23950: int32_t> >>> bv.get_symbol_at(bv.entry_point + 4) <DataSymbol: "foo" @ 0x23950> >>> bv.get_data_var_at(bv.entry_point + 4) <var 0x23950: int32_t>
- define_user_symbol(sym: CoreSymbol) None[source]¶
define_user_symboladds a symbol to the internal list of user added Symbol objects.Warning
If multiple symbols for the same address are defined, only the most recent symbol will ever be used.
- Parameters:
sym (Symbol) – the symbol to define
- Return type:
None
- define_user_type(name: _types.QualifiedNameType | None, type_obj: str | _types.Type | _types.TypeBuilder) None[source]¶
define_user_typeregisters aTypetype_objof the givennamein the global list of user types for the currentBinaryView.- Parameters:
name (QualifiedName) – Name of the user type to be registered
type_obj (StringOrType) – Type object to be registered
- Return type:
None
- Example:
>>> type, name = bv.parse_type_string("int foo") >>> bv.define_user_type(name, type) >>> bv.get_type_by_name(name) <type: int32_t> >>> bv.define_user_type(None, "int bas") >>> bv.get_type_by_name("bas") <type: int32_t>
- define_user_types(types: List[Tuple[_types.QualifiedNameType | None, str | _types.Type | _types.TypeBuilder]], progress_func: Callable[[int, int], bool] | None)[source]¶
define_user_typesregisters multiple types as though callingdefine_user_typemultiple times. The difference with this plural version is that it is optimized for adding many types at the same time, using knowledge of all types at add-time to improve runtime. There is an optionalprogress_funccallback function in case you want updates for a long-running call.
- detach_type_archive(archive: TypeArchive)[source]¶
Detach from a type archive, breaking all associations to types within the archive
- Parameters:
archive (TypeArchive) – Type archive to detach
- detach_type_archive_by_id(id: str)[source]¶
Detach from a type archive, breaking all associations to types within the archive
- Parameters:
id (str) – Id of archive to detach
- disassembly_text(addr: int, arch: Architecture | None = None) Generator[Tuple[str, int], None, None][source]¶
disassembly_texthelper function for getting disassembly of a given address- Parameters:
addr (int) – virtual address of instruction
arch (Architecture) – optional Architecture,
self.archis used if this parameter is None
- Returns:
a str representation of the instruction at virtual address
addror None- Return type:
str or None
- Example:
>>> next(bv.disassembly_text(bv.entry_point)) 'push ebp', 1 >>>
- disassembly_tokens(addr: int, arch: Architecture | None = None) Generator[Tuple[List[InstructionTextToken], int], None, None][source]¶
- Parameters:
addr (int) –
arch (Architecture | None) –
- Return type:
Generator[Tuple[List[InstructionTextToken], int], None, None]
- disassociate_type_archive_type(type: _types.QualifiedNameType) bool[source]¶
Disassociate an associated type, so that it will no longer receive updates from its connected type archive
- Parameters:
type (_types.QualifiedNameType) – Name of type in analysis
- Returns:
True if successful
- Return type:
- disassociate_type_archive_type_by_id(type_id: str) bool[source]¶
Disassociate an associated type id, so that it will no longer receive updates from its connected type archive
- end_bulk_add_segments() None[source]¶
end_bulk_add_segmentsFinalizes and applies all queued segments (auto and user) added during a bulk segment addition operation.This function commits all segments that were queued since the last call to begin_bulk_add_segments. The MemoryMap update process is executed at this point, applying all changes in one batch for improved performance.
Note: This function must be called after begin_bulk_add_segments to apply the queued segments.
- Return type:
None
- eval(expression: str, here: int = 0) int[source]¶
Evaluates a string expression to an integer value. This is a more concise alias for the
parse_expressionAPI
- export_object_to_library(lib: TypeLibrary, name: str | None, type_obj: str | Type | TypeBuilder) None[source]¶
Recursively exports
type_objintolibas an object with aname.This should be used to store definitions for functions, variables, and other things that are named symbols. For example, MessageBoxA might be the name of a function with the type int ()(HWND, LPCSTR, LPCSTR, UINT). If you just want to store a type definition, you probably want
export_type_to_library.As other referenced types are encountered, they are either copied into the destination type library or else the type library that provided the referenced type is added as a dependency for the destination library.
- Parameters:
lib (TypeLibrary) –
name (QualifiedName) –
type_obj (StringOrType) –
- Return type:
None
- export_type_to_library(lib: TypeLibrary, name: str | None, type_obj: str | Type | TypeBuilder) None[source]¶
Recursively exports
type_objintolibas a type with aname.This should be used to store type definitions with no symbol information. For example, color might be a type of enum {RED=0, ORANGE=1, YELLOW=2, …} used by this library. If you have a function, variable, or other object that is exported, you probably want
export_object_to_libraryinstead.As other referenced types are encountered, they are either copied into the destination type library or else the type library that provided the referenced type is added as a dependency for the destination library.
- Parameters:
lib (TypeLibrary) –
name (QualifiedName) –
type_obj (StringOrType) –
- Return type:
None
- static external_namespace() NameSpace[source]¶
External namespace for the current BinaryView
- Return type:
- finalize_new_segments() bool[source]¶
Performs “finalization” on segments added after initial Finalization (performed after an Init() has completed).
- Finalizing a segment involves optimizing the relocation info stored in that segment, so if a segment is added
and relocations are defined for that segment by some automated process, this function should be called afterwards.
- An example of this can be seen in the KernelCache plugin, in KernelCache::LoadImageWithInstallName.
After we load an image, map new segments, and define relocations for all of them, we call this function to let core know it is now safe to finalize the new segments
- Returns:
Whether finalization was successful
- Return type:
- find_all_constant(start: int, end: int, constant: int, settings: DisassemblySettings | None = None, graph_type: FunctionViewType | FunctionGraphType | str = FunctionGraphType.NormalFunctionGraph, progress_func: Callable[[int, int], bool] | None = None, match_callback: Callable[[int, LinearDisassemblyLine], bool] | None = None) QueueGenerator[source]¶
find_all_constantsearches for the integer constantconstantstarting at the virtual addressstartuntil the virtual addressend. Once a match is found, thematch_callbackis called.Note
A
constantis considered used if a line in the linear view expansion of the given function graph type contains a token with a value that matches that constant. This does not search for raw bytes/data in the binary, for that you want to usefind_all_data.- Parameters:
start (int) – virtual address to start searching from.
end (int) – virtual address to end the search.
constant (int) – constant to search for
settings (DisassemblySettings) – DisassemblySettings object used to render the text to be searched
graph_type (FunctionViewType) – the IL to search within
progress_func (callback) – optional function to be called with the current progress and total count. This function should return a boolean value that decides whether the search should continue or stop
match_callback (callback) – function that gets called when a match is found. The callback takes two parameters, i.e., the address of the match, and the LinearDisassemblyLine that contains the matching line. If this parameter is None, this function becomes a generator and yields the matching address and the matching LinearDisassemblyLine. This function can return a boolean value that decides whether the search should continue or stop
- Rtype QueueGenerator:
A generator object that will yield all the found results
- find_all_data(start: int, end: int, data: bytes, flags: FindFlag = FindFlag.FindCaseSensitive, progress_func: Callable[[int, int], bool] | None = None, match_callback: Callable[[int, DataBuffer], bool] | None = None) QueueGenerator[source]¶
find_all_datasearches for the bytesdatastarting at the virtual addressstartuntil the virtual addressend. Once a match is found, thematch_callbackis called.- Parameters:
start (int) – virtual address to start searching from.
end (int) – virtual address to end the search.
data (bytes) – data to search for
flags (FindFlag) –
(optional) defaults to case-insensitive data search
FindFlag
Description
FindCaseSensitive
Case-sensitive search
FindCaseInsensitive
Case-insensitive search
progress_func (callback) – optional function to be called with the current progress and total count. This function should return a boolean value that decides whether the search should continue or stop
match_callback (callback) – function that gets called when a match is found. The callback takes two parameters, i.e., the address of the match, and the actual DataBuffer that satisfies the search. If this parameter is None, this function becomes a generator and yields a tuple of the matching address and the matched DataBuffer. This function can return a boolean value that decides whether the search should continue or stop.
data –
- Rtype QueueGenerator:
A generator object that will yield all the found results
- find_all_text(start: int, end: int, text: str, settings: DisassemblySettings | None = None, flags=FindFlag.FindCaseSensitive, graph_type: FunctionViewType | FunctionGraphType | str = FunctionGraphType.NormalFunctionGraph, progress_func=None, match_callback=None) QueueGenerator[source]¶
find_all_textsearches for stringtextoccurring in the linear view output starting at the virtual addressstartuntil the virtual addressend. Once a match is found, thematch_callbackis called.- Parameters:
start (int) – virtual address to start searching from.
end (int) – virtual address to end the search.
text (str) – text to search for
settings (DisassemblySettings) – DisassemblySettings object used to render the text to be searched
flags (FindFlag) –
(optional) bit-flags list of options, defaults to case-insensitive data search
FindFlag
Description
FindCaseSensitive
Case-sensitive search
FindCaseInsensitive
Case-insensitive search
FindIgnoreWhitespace
Ignore whitespace characters
graph_type (FunctionViewType) – the IL to search within
progress_func (callback) – optional function to be called with the current progress and total count. This function should return a boolean value that decides whether the search should continue or stop
match_callback (callback) – function that gets called when a match is found. The callback takes three parameters, i.e., the address of the match, and the actual string that satisfies the search, and the LinearDisassemblyLine that contains the matching line. If this parameter is None, this function becomes a generator and yields a tuple of the matching address, the matched string, and the matching LinearDisassemblyLine. This function can return a boolean value that decides whether the search should continue or stop
- Rtype QueueGenerator:
A generator object that will yield all the found results
- find_next_constant(start: int, constant: int, settings: DisassemblySettings | None = None, graph_type: FunctionViewType | FunctionGraphType | str = FunctionGraphType.NormalFunctionGraph) int | None[source]¶
find_next_constantsearches for integer constantconstantoccurring in the linear view output starting at the virtual addressstartuntil the end of the BinaryView.- Parameters:
start (int) – virtual address to start searching from.
constant (int) – constant to search for
settings (DisassemblySettings) – disassembly settings
graph_type (FunctionViewType) – the IL to search within
- Return type:
int | None
- find_next_data(start: int, data: bytes, flags: FindFlag = FindFlag.FindCaseSensitive) int | None[source]¶
find_next_datasearches for the bytesdatastarting at the virtual addressstartuntil the end of the BinaryView.- Parameters:
- Return type:
int | None
- find_next_text(start: int, text: str, settings: DisassemblySettings | None = None, flags: int = FindFlag.FindCaseSensitive, graph_type: FunctionViewType | FunctionGraphType | str = FunctionGraphType.NormalFunctionGraph) int | None[source]¶
find_next_textsearches for stringtextoccurring in the linear view output starting at the virtual addressstartuntil the end of the BinaryView.- Parameters:
start (int) – virtual address to start searching from.
text (str) – text to search for
settings (DisassemblySettings) – disassembly settings
flags (FindFlag) –
(optional) bit-flags list of options, defaults to case-insensitive data search
FindFlag
Description
FindCaseSensitive
Case-sensitive search
FindCaseInsensitive
Case-insensitive search
FindIgnoreWhitespace
Ignore whitespace characters
graph_type (FunctionViewType) – the IL to search within
- Return type:
int | None
- forget_undo_actions(id: str | None = None) None[source]¶
forget_undo_actionsremoves the actions taken since a call tobegin_undo_actionsPass as id the value returned bybegin_undo_actions. Empty values of id will remove all changes since the last call tobegin_undo_actions.- Parameters:
id (Optional[str]) – id of undo state, from
begin_undo_actions- Return type:
None
- Example:
>>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>> state = bv.begin_undo_actions() >>> bv.convert_to_nop(0x100012f1) True >>> bv.forget_undo_actions(state) >>> bv.get_disassembly(0x100012f1) 'nop' >>> bv.undo() >>> bv.get_disassembly(0x100012f1) 'nop' >>>
- get_address_for_data_offset(offset: int) int | None[source]¶
get_address_for_data_offsetreturns the virtual address that maps to the specific file offset.- Parameters:
offset (int) – file offset
- Returns:
the virtual address of the first segment that contains that file location
- Return type:
Int
- get_address_input(prompt: str, title: str, current_address: int | None = None) int | None[source]¶
get_address_inputGets a virtual address via a prompt displayed to the user
- get_all_fields_referenced(name: _types.QualifiedNameType) List[int][source]¶
get_all_fields_referencedreturns a list of offsets in the QualifiedName specified by name, which are referenced by code.- Parameters:
name (QualifiedName) – name of type to query for references
- Returns:
List of offsets
- Return type:
list(integer)
- Example:
>>> bv.get_all_fields_referenced('A') [0, 8, 16, 24, 32, 40] >>>
- get_all_sizes_referenced(name: _types.QualifiedNameType) Mapping[int, List[int]][source]¶
get_all_sizes_referencedreturns a map from field offset to a list of sizes of the accesses to it.- Parameters:
name (QualifiedName) – name of type to query for references
- Returns:
A map from field offset to the size of the code accesses to it
- Return type:
map
- Example:
>>> bv.get_all_sizes_referenced('B') {0: [1, 8], 8: [8], 16: [1, 8]} >>>
- get_all_types_referenced(name: _types.QualifiedNameType) Mapping[int, List[_types.Type]][source]¶
get_all_types_referencedreturns a map from field offset to a list of incoming types written to the specified type.- Parameters:
name (QualifiedName) – name of type to query for references
- Returns:
A map from field offset to a list of incoming types written to it
- Return type:
map
- Example:
>>> bv.get_all_types_referenced('B') {0: [<type: char, 0% confidence>], 8: [<type: int64_t, 0% confidence>], 16: [<type: char, 0% confidence>, <type: bool>]} >>>
- get_ascii_string_at(addr: int, min_length: int = 4, max_length: int | None = None, require_cstring: bool = True) StringReference | None[source]¶
get_ascii_string_atreturns an ascii string found ataddr.Note
This returns an ascii string irrespective of whether the core analysis identified a string at that location. For an alternative API that uses existing identified strings, use
get_string_at.- Parameters:
- Returns:
the string found at
addror None if a string does not exist- Return type:
StringReference or None
- Example:
>>> s1 = bv.get_ascii_string_at(0x70d0) >>> s1 <AsciiString: 0x70d0, len 0xb> >>> s1.value 'AWAVAUATUSH' >>> s2 = bv.get_ascii_string_at(0x70d1) >>> s2 <AsciiString: 0x70d1, len 0xa> >>> s2.value 'WAVAUATUSH'
- get_associated_type_archive_type_source(archive: TypeArchive, archive_type: _types.QualifiedNameType) _types.QualifiedName | None[source]¶
Determine the local source type name for a given archive type
- Parameters:
archive (TypeArchive) – Target type archive
archive_type (_types.QualifiedNameType) – Name of target archive type
- Returns:
Name of source analysis type, if this type is associated. None otherwise.
- Return type:
_types.QualifiedName | None
- get_associated_type_archive_type_source_by_id(archive_id: str, archive_type_id: str) str | None[source]¶
Determine the local source type id for a given archive type
- get_associated_type_archive_type_target(name: _types.QualifiedNameType) Tuple[TypeArchive | None, str] | None[source]¶
Determine the target archive / type id of a given analysis type
- Parameters:
name (_types.QualifiedNameType) – Analysis type
- Returns:
(archive, archive type id) if the type is associated. None otherwise.
- Return type:
Tuple[TypeArchive | None, str] | None
- get_associated_type_archive_type_target_by_id(type_id: str) Tuple[str, str] | None[source]¶
Determine the target archive / type id of a given analysis type
- get_associated_types_from_archive(archive: TypeArchive) Mapping[QualifiedName, str][source]¶
Get a list of all types in the analysis that are associated with a specific type archive
- Returns:
Map of all analysis types to their corresponding archive id
- Parameters:
archive (TypeArchive) –
- Return type:
- get_associated_types_from_archive_by_id(archive_id: str) Mapping[str, str][source]¶
Get a list of all types in the analysis that are associated with a specific type archive :return: Map of all analysis types to their corresponding archive id
- get_basic_blocks_at(addr: int) List[BasicBlock][source]¶
get_basic_blocks_atget a list ofBasicBlockobjects which exist at the provided virtual address.- Parameters:
addr (int) – virtual address of BasicBlock desired
- Returns:
a list of
BasicBlockobjects- Return type:
- get_basic_blocks_starting_at(addr: int) List[BasicBlock][source]¶
get_basic_blocks_starting_atget a list ofBasicBlockobjects which start at the provided virtual address.- Parameters:
addr (int) – virtual address of BasicBlock desired
- Returns:
a list of
BasicBlockobjects- Return type:
- get_callees(addr: int, func: Function | None = None, arch: Architecture | None = None) List[int][source]¶
get_calleesreturns a list of virtual addresses called by the call site in the functionfunc, of the architecturearch, and at the addressaddr. If no function is specified, call sites from all functions and containing the address will be considered. If no architecture is specified, the architecture of the function will be used.- Parameters:
addr (int) – virtual address of the call site to query for callees
func (Architecture) – (optional) the function that the call site belongs to
func – (optional) the architecture of the call site
arch (Architecture | None) –
- Returns:
list of integers
- Return type:
list(integer)
- get_callers(addr: int) Generator[ReferenceSource, None, None][source]¶
get_callersreturns a list of ReferenceSource objects (xrefs or cross-references) that call the provided virtual address. In this case, tail calls, jumps, and ordinary calls are considered.- Parameters:
addr (int) – virtual address of callee to query for callers
- Returns:
List of References that call the given virtual address
- Return type:
- Example:
>>> bv.get_callers(here) [<ref: x86@0x4165ff>] >>>
- get_code_refs(addr: int, length: int | None = None, max_items: int | None = None) Generator[ReferenceSource, None, None][source]¶
get_code_refsreturns a generator ofReferenceSourceobjects (xrefs or cross-references) that point to the provided virtual address. This function returns both autoanalysis (“auto”) and user-specified (“user”) xrefs. To add a user-specified reference, seeadd_user_code_ref.The related
get_data_refsis used to find data references to an address unlike this API which returns references that exist in code.Note
Note that get_code_refs returns xrefs to code that references the address being queried. get_data_refs on the other hand returns references that exist in data (pointers in global variables for example). The related
get_code_refs_fromlooks for references that are outgoing from the queried address to other locations.- Parameters:
- Returns:
A generator of References for the given virtual address
- Return type:
Generator[ReferenceSource, None, None]
- Example:
>>> bv.get_code_refs(here) [<ref: x86@0x4165ff>] >>>
- get_code_refs_for_type(name: str, max_items: int | None = None) Generator[ReferenceSource, None, None][source]¶
get_code_refs_for_typereturns a Generator[ReferenceSource] objects (xrefs or cross-references) that reference the provided QualifiedName.- Parameters:
name (QualifiedName) – name of type to query for references
max_items (int) – optional maximum number of references to fetch
- Returns:
List of References for the given type
- Return type:
- Example:
>>> bv.get_code_refs_for_type('A') [<ref: x86@0x4165ff>] >>>
- get_code_refs_for_type_field(name: str, offset: int, max_items: int | None = None) Generator[TypeFieldReference, None, None][source]¶
get_code_refs_for_typereturns a Generator[TypeFieldReference] objects (xrefs or cross-references) that reference the provided type field.- Parameters:
name (QualifiedName) – name of type to query for references
offset (int) – offset of the field, relative to the type
max_items (int) – optional maximum number of references to fetch
- Returns:
Generator of References for the given type
- Return type:
Generator[TypeFieldReference]
- Example:
>>> bv.get_code_refs_for_type_field('A', 0x8) [<ref: x86@0x4165ff>] >>>
- get_code_refs_for_type_fields_from(addr: int, func: Function | None = None, arch: Architecture | None = None, length: int | None = None) List[TypeReferenceSource][source]¶
get_code_refs_for_type_fields_fromreturns a list of type fields referenced by code in the functionfunc, of the architecturearch, and at the addressaddr. If no function is specified, references from all functions and containing the address will be returned. If no architecture is specified, the architecture of the function will be used.- Parameters:
addr (int) – virtual address to query for references
length (int) – optional length of query
func (Function | None) –
arch (Architecture | None) –
- Returns:
list of references
- Return type:
- get_code_refs_for_type_from(addr: int, func: Function | None = None, arch: Architecture | None = None, length: int | None = None) List[TypeReferenceSource][source]¶
get_code_refs_for_type_fromreturns a list of types referenced by code in the functionfunc, of the architecturearch, and at the addressaddr. If no function is specified, references from all functions and containing the address will be returned. If no architecture is specified, the architecture of the function will be used.- Parameters:
addr (int) – virtual address to query for references
length (int) – optional length of query
func (Function | None) –
arch (Architecture | None) –
- Returns:
list of references
- Return type:
- get_code_refs_from(addr: int, func: Function | None = None, arch: Architecture | None = None, length: int | None = None) List[int][source]¶
get_code_refs_fromreturns a list of virtual addresses referenced by code in the functionfunc, of the architecturearch, and at the addressaddr. If no function is specified, references from all functions and containing the address will be returned. If no architecture is specified, the architecture of the function will be used. This function returns both autoanalysis (“auto”) and user-specified (“user”) xrefs. To add a user-specified reference, seeadd_user_code_ref.- Parameters:
addr (int) – virtual address to query for references
length (int) – optional length of query
arch (Architecture) – optional architecture of query
func (Function | None) –
- Returns:
list of integers
- Return type:
list(integer)
- get_comment_at(addr: int) str[source]¶
get_comment_atreturns the address-based comment attached to the given address in this BinaryView Note that address-based comments are different from function-level comments which are specific to eachFunction. For more information, seeaddress_comments.
- get_component_by_path(path: str) Component | None[source]¶
Lookup a Component by its pathname
- Note:
This is a convenience method, and for performance-sensitive lookups, GetComponentByGuid is very highly recommended.
- Parameters:
path (str) –
- Return type:
Component | None
Lookups are done based on the .display_name of the Component.
All lookups are absolute from the root component, and are case-sensitive. Pathnames are delimited with “/”
- Parameters:
path (str) – Pathname of the desired Component
- Returns:
The Component at that pathname
- Example:
>>> c = bv.create_component(name="MyComponent") >>> c2 = bv.create_component(name="MySubComponent", parent=c) >>> bv.get_component_by_path("/MyComponent/MySubComponent") == c2 True >>> c3 = bv.create_component(name="MySubComponent", parent=c) >>> c3 <Component "MySubComponent (1)" "(20712aff...")> >>> bv.get_component_by_path("/MyComponent/MySubComponent (1)") == c3 True
- Return type:
Component | None
- get_data_offset_for_address(address: int) int | None[source]¶
get_data_offset_for_addressreturns the file offset that maps to the given virtual address, if possible.If address falls within a bss segment or an external segment, for example, no mapping is possible, and None will be returned.
- Parameters:
address (int) – virtual address
- Returns:
the file location that is mapped to the given virtual address, or None if no such mapping is possible
- Return type:
Int
- get_data_refs(addr: int, length: int | None = None, max_items: int | None = None) Generator[int, None, None][source]¶
get_data_refsreturns a list of virtual addresses of _data_ (not code) which referencesaddr, optionally specifying a length. Whenlengthis setget_data_refsreturns the data which references in the rangeaddr-addr``+``length. This function returns both autoanalysis (“auto”) and user-specified (“user”) xrefs. To add a user-specified reference, seeadd_user_data_ref.Warning
If you’re looking at this API, please double check that you don’t mean to use
get_code_refsinstead. get_code_refs returns references from code to the specified address while this API returns references from data (pointers in global variables for example). Also, note there existsget_data_refs_from.
- get_data_refs_for_type(name: str, max_items: int | None = None) Generator[int, None, None][source]¶
get_data_refs_for_typereturns a list of virtual addresses of data which references the typename. Note, the returned addresses are the actual start of the queried type. For example, suppose there is a DataVariable at 0x1000 that has type A, and type A contains type B at offset 0x10. Then get_data_refs_for_type(‘B’) will return 0x1010 for it.- Parameters:
name (QualifiedName) – name of type to query for references
max_items (int) – optional maximum number of references to fetch
- Returns:
list of integers
- Return type:
list(integer)
- Example:
>>> bv.get_data_refs_for_type('A') [4203812] >>>
- get_data_refs_for_type_field(name: _types.QualifiedNameType, offset: int, max_items: int | None = None) List[int][source]¶
get_data_refs_for_type_fieldreturns a list of virtual addresses of data which references the typename. Note, the returned addresses are the actual start of the queried type field. For example, suppose there is a DataVariable at 0x1000 that has type A, and type A contains type B at offset 0x10. Then get_data_refs_for_type_field(‘B’, 0x8) will return 0x1018 for it.- Parameters:
name (QualifiedName) – name of type to query for references
offset (int) – offset of the field, relative to the type
max_items (int) – optional maximum number of references to fetch
- Returns:
list of integers
- Return type:
list(integer)
- Example:
>>> bv.get_data_refs_for_type_field('A', 0x8) [4203812] >>>
- get_data_refs_from(addr: int, length: int | None = None) Generator[int, None, None][source]¶
get_data_refs_fromreturns a list of virtual addresses referenced by the addressaddr. Optionally specifying a length. Whenlengthis setget_data_refs_fromreturns the data referenced in the rangeaddr-addr``+``length. This function returns both autoanalysis (“auto”) and user-specified (“user”) xrefs. To add a user-specified reference, seeadd_user_data_ref. Also, note there existsget_data_refs.
- get_data_refs_from_for_type_field(name: _types.QualifiedNameType, offset: int, max_items: int | None = None) List[int][source]¶
get_data_refs_from_for_type_fieldreturns a list of virtual addresses of data which are referenced by the typename.Only data referenced by structures with the
__data_var_refsattribute are included.- Parameters:
name (QualifiedName) – name of type to query for references
offset (int) – offset of the field, relative to the type
max_items (int) – optional maximum number of references to fetch
- Returns:
list of integers
- Return type:
list(integer)
- Example:
>>> bv.get_data_refs_from_for_type_field('A', 0x8) [4203812] >>>
- get_data_var_at(addr: int) DataVariable | None[source]¶
get_data_var_atreturns the data type at a given virtual address.- Parameters:
addr (int) – virtual address to get the data type from
- Returns:
returns the DataVariable at the given virtual address, None on error
- Return type:
- Example:
>>> t = bv.parse_type_string("int foo") >>> bv.define_data_var(bv.entry_point, t[0]) >>> bv.get_data_var_at(bv.entry_point) <var 0x100001174: int32_t>
- get_data_variable_parent_components(data_variable: DataVariable) List[Component][source]¶
- Parameters:
data_variable (DataVariable) –
- Return type:
- get_disassembly(addr: int, arch: Architecture | None = None) str | None[source]¶
get_disassemblysimple helper function for printing disassembly of a given address- Parameters:
addr (int) – virtual address of instruction
arch (Architecture) – optional Architecture,
self.archis used if this parameter is None
- Returns:
a str representation of the instruction at virtual address
addror None- Return type:
str or None
- Example:
>>> bv.get_disassembly(bv.entry_point) 'push ebp' >>>
Note
This API is very simplistic and only returns text. See
disassembly_textand instructions for more capable APIs.
- get_entropy(addr: int, length: int, block_size: int = 0) List[float][source]¶
get_entropyreturns the shannon entropy given the startaddr,lengthin bytes, and optionally inblock_sizechunks.
- get_expression_parser_magic_value(name: str) int | None[source]¶
Get the value of an expression parser magic value
If the queried magic value exists, the function returns true and the magic value is returned in value. If the queried magic value does not exist, the function returns None.
- get_external_libraries() List[ExternalLibrary][source]¶
Get a list of all ExternalLibrary in this BinaryView
- Returns:
A list of ExternalLibraries in this BinaryView
- Return type:
- get_external_library(name: str) ExternalLibrary | None[source]¶
Get an ExternalLibrary in this BinaryView by name
- Parameters:
name (str) – Name of the external library
- Returns:
An ExternalLibrary with the given name, or None
- Return type:
ExternalLibrary | None
- get_external_location(source_symbol: CoreSymbol) ExternalLocation | None[source]¶
Get the ExternalLocation with the given source symbol in this BinaryView
- Parameters:
source_symbol (CoreSymbol) – The source symbol of the ExternalLocation
- Returns:
An ExternalLocation with the given source symbol, or None
- Return type:
ExternalLocation | None
- get_external_locations() List[ExternalLocation][source]¶
Get a list of ExternalLocations in this BinaryView
- Returns:
A list of ExternalLocations in this BinaryView
- Return type:
- get_function_analysis_update_disabled() bool[source]¶
Returns True when functions are prevented from being marked as updates required, False otherwise. :return:
- Return type:
- get_function_at(addr: int, plat: Platform | None = None) Function | None[source]¶
get_function_atgets a Function object for the function that starts at virtual addressaddr:- Parameters:
- Returns:
returns a Function object or None for the function at the virtual address provided
- Return type:
- Example:
>>> bv.get_function_at(bv.entry_point) <func: x86_64@0x100001174> >>>
- get_functions_at(addr: int) List[Function][source]¶
get_functions_atget a list ofFunctionobjects (one for each valid platform) that start at the given virtual address. Binary Ninja does not limit the number of platforms in a given file thus there may be multiple functions defined from different architectures at the same location. This API allows you to query all of valid platforms.You may also be interested in
get_functions_containingwhich is useful for requesting all function that contain a given address
- get_functions_by_name(name: str, plat: Platform | None = None, ordered_filter: List[SymbolType] | None = None) List[Function][source]¶
get_functions_by_namereturns a list ofFunctionobjects function with aSymbolofname.- Parameters:
name (str) – name of the functions
plat (Platform) – (optional) platform
ordered_filter (list(SymbolType)) – (optional) an ordered filter based on SymbolType
- Returns:
returns a list of
Functionobjects or an empty list- Return type:
- Example:
>>> bv.get_functions_by_name("main") [<func: x86_64@0x1587>] >>>
- get_functions_containing(addr: int, plat: Platform | None = None) List[Function][source]¶
get_functions_containingreturns a list ofFunctionobjects which contain the given address.
- get_incoming_direct_type_references(name: _types.QualifiedNameType) List[_types.QualifiedName][source]¶
- Parameters:
name (_types.QualifiedNameType) –
- Return type:
List[_types.QualifiedName]
- get_incoming_recursive_type_references(names: _types.QualifiedNameType | List[_types.QualifiedNameType]) List[_types.QualifiedName][source]¶
- get_instruction_length(addr: int, arch: Architecture | None = None) int[source]¶
get_instruction_lengthreturns the number of bytes in the instruction of Architecturearchat the virtual addressaddr- Parameters:
addr (int) – virtual address of the instruction query
arch (Architecture) – (optional) the architecture of the instructions if different from the default
- Returns:
Number of bytes in instruction
- Return type:
- Example:
>>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>> bv.get_instruction_length(0x100012f1) 2L >>>
- get_linear_disassembly(settings: DisassemblySettings | None = None) Iterator[LinearDisassemblyLine][source]¶
get_linear_disassemblygets an iterator for all lines in the linear disassembly of the view for the given disassembly settings.Note
linear_disassembly doesn’t just return disassembly; it will return a single line from the linear view, and thus will contain both data views, and disassembly.
Warning: In order to get deterministic output, the WaitForIL DisassemblyOption should be set to True.
- Parameters:
settings (DisassemblySettings) – instance specifying the desired output formatting. Defaults to None which will use default settings.
- Returns:
An iterator containing formatted disassembly lines.
- Return type:
LinearDisassemblyIterator
- Example:
>>> settings = DisassemblySettings() >>> lines = bv.get_linear_disassembly(settings) >>> for line in lines: ... print(line) ... break ... cf fa ed fe 07 00 00 01 ........
- get_linear_disassembly_position_at(addr: int, settings: DisassemblySettings | None = None) LinearViewCursor[source]¶
get_linear_disassembly_position_atinstantiates aLinearViewCursorobject for use inget_previous_linear_disassembly_linesorget_next_linear_disassembly_lines.- Parameters:
addr (int) – virtual address of linear disassembly position
settings (DisassemblySettings) – an instantiated
DisassemblySettingsobject, defaults to None which will use default settings
- Returns:
An instantiated
LinearViewCursorobject for the provided virtual address- Return type:
- Example:
>>> settings = DisassemblySettings() >>> pos = bv.get_linear_disassembly_position_at(0x1000149f, settings) >>> lines = bv.get_previous_linear_disassembly_lines(pos) >>> lines [<0x1000149a: pop esi>, <0x1000149b: pop ebp>, <0x1000149c: retn 0xc>, <0x1000149f: >]
- get_load_settings(type_name: str) Settings | None[source]¶
get_load_settingsretrieve aSettingsobject which defines the load settings for the givenBinaryViewTypetype_name- Parameters:
type_name (str) – the
BinaryViewTypename- Returns:
the load settings
- Return type:
Settings, orNone
- get_load_settings_type_names() List[str][source]¶
get_load_settings_type_namesretrieve a listBinaryViewTypenames for which load settings exist in thisBinaryViewcontext- Returns:
list of
BinaryViewTypenames- Return type:
- get_modification(addr: int, length: int | None = None) List[ModificationStatus][source]¶
get_modificationreturns the modified bytes of up tolengthbytes from virtual addressaddr, or iflengthis None returns the ModificationStatus.- Parameters:
- Returns:
List of ModificationStatus values for each byte in range
- Return type:
List[ModificationStatus]
- get_next_basic_block_start_after(addr: int) int[source]¶
get_next_basic_block_start_afterreturns the virtual address of the BasicBlock that occurs after the virtualaddress
addr
- get_next_data_after(addr: int) int[source]¶
get_next_data_afterretrieves the virtual address of the next non-code byte.
- get_next_data_var_after(addr: int) DataVariable | None[source]¶
get_next_data_var_afterretrieves the nextDataVariable, or None.- Parameters:
addr (int) – the virtual address to start looking from.
- Returns:
the next
DataVariable- Return type:
- Example:
>>> bv.get_next_data_var_after(0x10000000) <var 0x1000003c: int32_t> >>>
- get_next_data_var_start_after(addr: int) int[source]¶
get_next_data_var_start_afterretrieves the next virtual address of the nextDataVariable- Parameters:
addr (int) – the virtual address to start looking from.
- Returns:
the virtual address of the next
DataVariable- Return type:
- Example:
>>> hex(bv.get_next_data_var_start_after(0x10000000)) '0x1000003cL' >>> bv.get_data_var_at(0x1000003c) <var 0x1000003c: int32_t> >>>
- get_next_function_start_after(addr: int) int[source]¶
get_next_function_start_afterreturns the virtual address of the Function that occurs after the virtual addressaddr- Parameters:
addr (int) – the virtual address to start looking from.
- Returns:
the virtual address of the next Function
- Return type:
- Example:
>>> bv.get_next_function_start_after(bv.entry_point) 268441061L >>> hex(bv.get_next_function_start_after(bv.entry_point)) '0x100015e5L' >>> hex(bv.get_next_function_start_after(0x100015e5)) '0x10001629L' >>> hex(bv.get_next_function_start_after(0x10001629)) '0x1000165eL' >>>
- get_next_linear_disassembly_lines(pos: LinearViewCursor) List[LinearDisassemblyLine][source]¶
get_next_linear_disassembly_linesretrieves a list ofLinearDisassemblyLineobjects for the next disassembly lines, and updates the LinearViewCursor passed in. This function can be called repeatedly to get more lines of linear disassembly.- Parameters:
pos (LinearViewCursor) – Position to start retrieving linear disassembly lines from
- Returns:
a list of
LinearDisassemblyLineobjects for the next lines.- Example:
>>> settings = DisassemblySettings() >>> pos = bv.get_linear_disassembly_position_at(0x10001483, settings) >>> bv.get_next_linear_disassembly_lines(pos) [<0x10001483: xor eax, eax {0x0}>, <0x10001485: inc eax {0x1}>, ... , <0x10001488: >] >>> bv.get_next_linear_disassembly_lines(pos) [<0x10001488: push dword [ebp+0x10 {arg_c}]>, ... , <0x1000149a: >] >>>
- Return type:
- get_next_valid_offset(addr: int) int[source]¶
get_next_valid_offsetreturns the next valid offset in the BinaryView starting from the given virtual addressaddr.
- get_outgoing_direct_type_references(name: _types.QualifiedNameType) List[_types.QualifiedName][source]¶
- Parameters:
name (_types.QualifiedNameType) –
- Return type:
List[_types.QualifiedName]
- get_outgoing_recursive_type_references(names: _types.QualifiedNameType | List[_types.QualifiedNameType]) List[_types.QualifiedName][source]¶
- get_previous_basic_block_end_before(addr: int) int[source]¶
get_previous_basic_block_end_before- Parameters:
addr (int) – the virtual address to start looking from.
- Returns:
the virtual address of the previous BasicBlock end
- Return type:
- Example:
>>> hex(bv.entry_point) '0x1000149fL' >>> hex(bv.get_next_basic_block_start_after(bv.entry_point)) '0x100014a8L' >>> hex(bv.get_previous_basic_block_end_before(0x100014a8)) '0x100014a8L'
- get_previous_basic_block_start_before(addr: int) int[source]¶
get_previous_basic_block_start_beforereturns the virtual address of the BasicBlock that occurs prior to the provided virtual address- Parameters:
addr (int) – the virtual address to start looking from.
- Returns:
the virtual address of the previous BasicBlock
- Return type:
- Example:
>>> hex(bv.entry_point) '0x1000149fL' >>> hex(bv.get_next_basic_block_start_after(bv.entry_point)) '0x100014a8L' >>> hex(bv.get_previous_basic_block_start_before(0x100014a8)) '0x1000149fL' >>>
- get_previous_data_var_before(addr: int) DataVariable | None[source]¶
get_previous_data_var_beforeretrieves the previousDataVariable, or None.- Parameters:
addr (int) – the virtual address to start looking from.
- Returns:
the previous
DataVariable- Return type:
- Example:
>>> bv.get_previous_data_var_before(0x1000003c) <var 0x10000000: int16_t> >>>
- get_previous_data_var_start_before(addr: int) int[source]¶
get_previous_data_var_start_before- Parameters:
addr (int) – the virtual address to start looking from.
- Returns:
the virtual address of the previous
DataVariable- Return type:
- Example:
>>> hex(bv.get_previous_data_var_start_before(0x1000003c)) '0x10000000L' >>> bv.get_data_var_at(0x10000000) <var 0x10000000: int16_t> >>>
- get_previous_function_start_before(addr: int) int[source]¶
get_previous_function_start_beforereturns the virtual address of the Function that occurs prior to the virtual address provided- Parameters:
addr (int) – the virtual address to start looking from.
- Returns:
the virtual address of the previous Function
- Return type:
- Example:
>>> hex(bv.entry_point) '0x1000149fL' >>> hex(bv.get_next_function_start_after(bv.entry_point)) '0x100015e5L' >>> hex(bv.get_previous_function_start_before(0x100015e5)) '0x1000149fL' >>>
- get_previous_linear_disassembly_lines(pos: LinearViewCursor) List[LinearDisassemblyLine][source]¶
get_previous_linear_disassembly_linesretrieves a list ofLinearDisassemblyLineobjects for the previous disassembly lines, and updates the LinearViewCursor passed in. This function can be called repeatedly to get more lines of linear disassembly.- Parameters:
pos (LinearViewCursor) – Position to start retrieving linear disassembly lines from
- Returns:
a list of
LinearDisassemblyLineobjects for the previous lines.- Example:
>>> settings = DisassemblySettings() >>> pos = bv.get_linear_disassembly_position_at(0x1000149a, settings) >>> bv.get_previous_linear_disassembly_lines(pos) [<0x10001488: push dword [ebp+0x10 {arg_c}]>, ... , <0x1000149a: >] >>> bv.get_previous_linear_disassembly_lines(pos) [<0x10001483: xor eax, eax {0x0}>, ... , <0x10001488: >]
- Return type:
- get_recent_basic_block_at(addr: int) BasicBlock | None[source]¶
- Parameters:
addr (int) –
- Return type:
BasicBlock | None
- get_segment_at(addr: int) Segment | None[source]¶
get_segment_atgets the Segment a given virtual address is located in
- get_sizes_referenced(name: _types.QualifiedNameType, offset: int) List[int][source]¶
get_sizes_referencedreturns a list of access sizes to the specified type.- Parameters:
name (QualifiedName) – name of type to query for references
offset (int) – offset of the field
- Returns:
a list of sizes of the accesses to it.
- Return type:
- Example:
>>> bv.get_sizes_referenced('B', 16) [1, 8] >>>
- get_string_at(addr: int, partial: bool = False) StringReference | None[source]¶
get_string_atreturns the string that falls on given virtual address.Note
This returns discovered strings and is therefore governed by analysis.limits.minStringLength and other settings. For an alternative API that simply returns any potential c-string at a given location, use
get_ascii_string_at.- Parameters:
- Returns:
returns the StringReference at the given virtual address, otherwise None.
- Return type:
- Example:
>>> bv.get_string_at(0x40302f) <StringType.AsciiString: 0x403028, len 0x12>
- get_strings(start: int | None = None, length: int | None = None) List[StringReference][source]¶
get_stringsreturns a list of strings defined in the binary in the optional virtual address range:start-(start+length)Note that this API will only return strings that have been identified by the string-analysis and thus governed by the minimum and maximum length settings and unrelated to the type system.
- Parameters:
- Returns:
a list of all strings or a list of strings defined between
startandstart+length- Return type:
- Example:
>>> bv.get_strings(0x1000004d, 1) [<AsciiString: 0x1000004d, len 0x2c>] >>>
- get_symbol_at(addr: int, namespace: _types.NameSpaceType = None) _types.CoreSymbol | None[source]¶
get_symbol_atreturns the Symbol at the provided virtual address.- Parameters:
addr (int) – virtual address to query for symbol
namespace (_types.NameSpaceType) – (optional) the namespace of the symbols to retrieve
- Returns:
CoreSymbol for the given virtual address
- Return type:
- Example:
>>> bv.get_symbol_at(bv.entry_point) <FunctionSymbol: "_start" @ 0x100001174> >>>
- get_symbol_by_raw_name(name: str, namespace: _types.NameSpaceType = None) _types.CoreSymbol | None[source]¶
get_symbol_by_raw_nameretrieves a Symbol object for the given raw (mangled) name.- Parameters:
name (str) – raw (mangled) name of Symbol to be retrieved
namespace (_types.NameSpaceType) – (optional) the namespace to search for the given symbol
- Returns:
CoreSymbol object corresponding to the provided raw name
- Return type:
- Example:
>>> bv.get_symbol_by_raw_name('?testf@Foobar@@SA?AW4foo@1@W421@@Z') <FunctionSymbol: "public: static enum Foobar::foo __cdecl Foobar::testf(enum Foobar::foo)" @ 0x10001100> >>>
- get_symbols(start: int | None = None, length: int | None = None, namespace: _types.NameSpaceType = None) List[_types.CoreSymbol][source]¶
get_symbolsretrieves the list of all Symbol objects in the optionally provided range.- Parameters:
- Returns:
list of all Symbol objects, or those Symbol objects in the range of
start-start+length- Return type:
- Example:
>>> bv.get_symbols(0x1000200c, 1) [<ImportAddressSymbol: "KERNEL32!IsProcessorFeaturePresent" @ 0x1000200c>] >>>
- get_symbols_by_name(name: str, namespace: _types.NameSpaceType = None, ordered_filter: List[SymbolType] | None = None) List[_types.CoreSymbol][source]¶
get_symbols_by_nameretrieves a list of Symbol objects for the given symbol name and ordered filter- Parameters:
name (str) – name of Symbol object to be retrieved
namespace (_types.NameSpaceType) – (optional) the namespace to search for the given symbol
namespace – (optional) the namespace to search for the given symbol
ordered_filter (List[SymbolType] | None) – (optional) an ordered filter based on SymbolType
- Returns:
Symbol object corresponding to the provided name
- Return type:
- Example:
>>> bv.get_symbols_by_name('?testf@Foobar@@SA?AW4foo@1@W421@@Z') [<FunctionSymbol: "public: static enum Foobar::foo __cdecl Foobar::testf(enum Foobar::foo)" @ 0x10001100>] >>>
- get_symbols_by_raw_name(name: str, namespace: _types.NameSpaceType = None) List[_types.CoreSymbol][source]¶
- get_symbols_of_type(sym_type: SymbolType, start: int | None = None, length: int | None = None, namespace: _types.NameSpaceType = None) List[_types.CoreSymbol][source]¶
get_symbols_of_typeretrieves a list of allSymbolobjects of the provided symbol type in the optionallyprovided range.
- Parameters:
sym_type (SymbolType) – A Symbol type:
SymbolTypestart (int | None) – optional start virtual address
length (int | None) – optional length
namespace (_types.NameSpaceType) –
- Returns:
list of all
Symbolobjects of typesym_type, or thoseSymbolobjects in the range ofstart-start+length- Return type:
- Example:
>>> bv.get_symbols_of_type(SymbolType.ImportAddressSymbol, 0x10002028, 1) [<ImportAddressSymbol: "KERNEL32!GetCurrentThreadId" @ 0x10002028>] >>>
- get_tags(auto: bool | None = None) List[Tuple[int, Tag]][source]¶
tagsgets a list of all dataTagobjects in the view. Tags are returned as a list of (address,Tag) pairs.
- get_tags_at(addr: int, auto: bool | None = None) List[Tag][source]¶
get_data_tags_atgets a list ofTagobjects for a data address.
- get_tags_in_range(address_range: AddressRange, auto: bool | None = None) List[Tuple[int, Tag]][source]¶
get_data_tags_in_rangegets a list of all dataTagobjects in a given range. Range is inclusive at the start, exclusive at the end.- Parameters:
address_range (AddressRange) – address range from which to get tags
auto (bool) – If None, gets all tags, if True, gets auto tags, if False, gets auto tags
- Returns:
A list of (address, data tag) tuples
- Return type:
- get_type_archive(id: str) TypeArchive | None[source]¶
Look up a connected archive by its id
- Parameters:
id (str) – Id of archive
- Returns:
Archive, if one exists with that id. Otherwise None
- Return type:
TypeArchive | None
- get_type_archive_path(id: str) str | None[source]¶
Look up the path for an attached (but not necessarily connected) type archive by its id
- get_type_archives_for_type_name(name: _types.QualifiedNameType) List[Tuple[TypeArchive, str]][source]¶
Get a list of all connected type archives that have a given type name
- Returns:
(archive, archive type id) for all archives
- Parameters:
name (_types.QualifiedNameType) –
- Return type:
List[Tuple[TypeArchive, str]]
- get_type_by_id(id: str) Type | None[source]¶
get_type_by_idreturns the defined type whose unique identifier corresponds with the providedid- Parameters:
id (str) – Unique identifier to lookup
- Returns:
A
Typeor None if the type does not exist- Return type:
Type or None
- Example:
>>> type, name = bv.parse_type_string("int foo") >>> type_id = Type.generate_auto_type_id("source", name) >>> bv.define_type(type_id, name, type) >>> bv.get_type_by_id(type_id) <type: int32_t> >>>
- get_type_by_name(name: _types.QualifiedNameType) _types.Type | None[source]¶
get_type_by_namereturns the defined type whose name corresponds with the providedname- Parameters:
name (QualifiedName) – Type name to lookup
- Returns:
A
Typeor None if the type does not exist- Return type:
Type or None
- Example:
>>> type, name = bv.parse_type_string("int foo") >>> bv.define_user_type(name, type) >>> bv.get_type_by_name(name) <type: int32_t> >>>
- get_type_id(name: _types.QualifiedNameType) str[source]¶
get_type_idreturns the unique identifier of the defined type whose name corresponds with the providedname- Parameters:
name (QualifiedName) – Type name to lookup
- Returns:
The unique identifier of the type
- Return type:
- Example:
>>> type, name = bv.parse_type_string("int foo") >>> type_id = Type.generate_auto_type_id("source", name) >>> registered_name = bv.define_type(type_id, name, type) >>> bv.get_type_id(registered_name) == type_id True >>>
- get_type_library(name: str) TypeLibrary | None[source]¶
get_type_libraryreturns the TypeLibrary- Parameters:
name (str) – Library name to lookup
- Returns:
The Type Library object, if any
- Return type:
TypeLibrary or None
- Example:
- get_type_name_by_id(id: str) QualifiedName | None[source]¶
get_type_name_by_idreturns the defined type name whose unique identifier corresponds with the providedid- Parameters:
id (str) – Unique identifier to lookup
- Returns:
A QualifiedName or None if the type does not exist
- Return type:
QualifiedName or None
- Example:
>>> type, name = bv.parse_type_string("int foo") >>> type_id = Type.generate_auto_type_id("source", name) >>> bv.define_type(type_id, name, type) 'foo' >>> bv.get_type_name_by_id(type_id) 'foo' >>>
- get_type_refs_for_type(name: _types.QualifiedNameType, max_items: int | None = None) List[_types.TypeReferenceSource][source]¶
get_type_refs_for_typereturns a list of TypeReferenceSource objects (xrefs or cross-references) that reference the provided QualifiedName.- Parameters:
name (QualifiedName) – name of type to query for references
max_items (int) – optional maximum number of references to fetch
- Returns:
List of references for the given type
- Return type:
- Example:
>>> bv.get_type_refs_for_type('A') ['<type D, offset 0x8, direct>', '<type C, offset 0x10, indirect>'] >>>
- get_type_refs_for_type_field(name: _types.QualifiedNameType, offset: int, max_items: int | None = None) List[_types.TypeReferenceSource][source]¶
get_type_refs_for_typereturns a list of TypeReferenceSource objects (xrefs or cross-references) that reference the provided type field.- Parameters:
name (QualifiedName) – name of type to query for references
offset (int) – offset of the field, relative to the type
max_items (int) – optional maximum number of references to fetch
- Returns:
List of references for the given type
- Return type:
- Example:
>>> bv.get_type_refs_for_type_field('A', 0x8) ['<type D, offset 0x8, direct>', '<type C, offset 0x10, indirect>'] >>>
- get_types_referenced(name: QualifiedName, offset: int) List[Type][source]¶
get_types_referencedreturns a list of types related to the type field access.- Parameters:
name (QualifiedName) – name of type to query for references
offset (int) – offset of the field
- Returns:
a list of types related to the type field access.
- Return type:
- Example:
>>> bv.get_types_referenced('B', 0x10) [<type: bool>, <type: char, 0% confidence>] >>>
- get_view_of_type(name: str) BinaryView | None[source]¶
get_view_of_typereturns the BinaryView associated with the provided name if it exists.- Parameters:
name (str) – Name of the view to be retrieved
- Returns:
BinaryView object associated with the provided name or None on failure
- Return type:
BinaryView or None
- has_initial_analysis() bool[source]¶
has_initial_analysischeck for the presence of an initial analysis in this BinaryView.- Returns:
True if the BinaryView has a valid initial analysis, False otherwise
- Return type:
- hlil_functions(preload_limit: int | None = None, function_generator: Generator[Function, None, None] | None = None) Generator[HighLevelILFunction, None, None][source]¶
Generates a list of il functions. This method should be used instead of ‘functions’ property if HLIL is needed and performance is a concern.
- Parameters:
- Return type:
Generator[HighLevelILFunction, None, None]
- import_library_object(name: str, lib: TypeLibrary | None = None) Tuple[TypeLibrary, Type] | None[source]¶
import_library_objectrecursively imports an object from the specified type library, or, if no library was explicitly provided, the first type library associated with the currentBinaryViewthat provides the name requested.This may have the impact of loading other type libraries as dependencies on other type libraries are lazily resolved when references to types provided by them are first encountered.
Note
If you are implementing a custom BinaryView and use this method to import object types, you should then call
record_imported_objectwith the details of where the object is located.- Parameters:
name (QualifiedName) –
lib (TypeLibrary) –
- Returns:
the object type, with any interior NamedTypeReferences renamed as necessary to be appropriate for the current view
- Return type:
- import_library_type(name: str, lib: TypeLibrary | None = None) Type | None[source]¶
import_library_typerecursively imports a type from the specified type library, or, if no library was explicitly provided, the first type library associated with the currentBinaryViewthat provides the name requested.This may have the impact of loading other type libraries as dependencies on other type libraries are lazily resolved when references to types provided by them are first encountered.
Note that the name actually inserted into the view may not match the name as it exists in the type library in the event of a name conflict. To aid in this, the
Typeobject returned is a NamedTypeReference to the deconflicted name used.- Parameters:
name (QualifiedName) –
lib (TypeLibrary) –
- Returns:
a NamedTypeReference to the type, taking into account any renaming performed
- Return type:
- import_type_by_guid(guid: str | UUID) Type | None[source]¶
import_type_by_guidrecursively imports a type interface given its GUID.Note
To support this type of lookup a type library must have contain a metadata key called “type_guids” which is a map Dict[string_guid, string_type_name] or Dict[string_guid, Tuple[string_type_name, type_library_name]]
- insert(addr: int, data: bytes) int[source]¶
insertinserts the bytes indatato the virtual addressaddr.
- static internal_namespace() NameSpace[source]¶
Internal namespace for the current BinaryView
- Return type:
- invert_branch(addr: int, arch: Architecture | None = None) bool[source]¶
invert_branchconvert the branch instruction of architecturearchat the virtual addressaddrto the inverse branch.Note
This API performs a binary patch, analysis may need to be updated afterward. Additionally the binary file must be saved in order to preserve the changes made.
- Parameters:
addr (int) – virtual address of the instruction to be modified
arch (Architecture) – (optional) the architecture of the instructions if different from the default
- Returns:
True on success, False on failure.
- Return type:
- Example:
>>> bv.get_disassembly(0x1000130e) 'je 0x10001317' >>> bv.invert_branch(0x1000130e) True >>> >>> bv.get_disassembly(0x1000130e) 'jne 0x10001317' >>>
- is_always_branch_patch_available(addr: int, arch: Architecture | None = None) bool[source]¶
is_always_branch_patch_availablequeries the architecture plugin to determine if the instruction ataddrcan be made to always branch. The actual logic of which is implemented in theperform_is_always_branch_patch_availablein the corresponding architecture.- Parameters:
addr (int) – the virtual address of the instruction to be patched
arch (Architecture) – (optional) the architecture for the current view
- Returns:
True if the instruction can be patched, False otherwise
- Return type:
- Example:
>>> bv.get_disassembly(0x100012ed) 'test eax, eax' >>> bv.is_always_branch_patch_available(0x100012ed) False >>> bv.get_disassembly(0x100012ef) 'jg 0x100012f5' >>> bv.is_always_branch_patch_available(0x100012ef) True >>>
- is_invert_branch_patch_available(addr: int, arch: Architecture | None = None) bool[source]¶
is_invert_branch_patch_availablequeries the architecture plugin to determine if the instruction ataddris a branch that can be inverted. The actual logic of which is implemented in theperform_is_invert_branch_patch_availablein the corresponding architecture.- Parameters:
addr (int) – the virtual address of the instruction to be patched
arch (Architecture) – (optional) the architecture of the instructions if different from the default
- Returns:
True if the instruction can be patched, False otherwise
- Return type:
- Example:
>>> bv.get_disassembly(0x100012ed) 'test eax, eax' >>> bv.is_invert_branch_patch_available(0x100012ed) False >>> bv.get_disassembly(0x100012ef) 'jg 0x100012f5' >>> bv.is_invert_branch_patch_available(0x100012ef) True >>>
- is_never_branch_patch_available(addr: int, arch: Architecture | None = None) bool[source]¶
is_never_branch_patch_availablequeries the architecture plugin to determine if the instruction at the instruction ataddrcan be made to never branch. The actual logic of which is implemented in theperform_is_never_branch_patch_availablein the corresponding architecture.- Parameters:
addr (int) – the virtual address of the instruction to be patched
arch (Architecture) – (optional) the architecture of the instructions if different from the default
- Returns:
True if the instruction can be patched, False otherwise
- Return type:
- Example:
>>> bv.get_disassembly(0x100012ed) 'test eax, eax' >>> bv.is_never_branch_patch_available(0x100012ed) False >>> bv.get_disassembly(0x100012ef) 'jg 0x100012f5' >>> bv.is_never_branch_patch_available(0x100012ef) True >>>
- is_offset_code_semantics(addr: int) bool[source]¶
is_offset_code_semanticschecks if a virtual addressaddris semantically valid for code.
- is_offset_executable(addr: int) bool[source]¶
is_offset_executablechecks if a virtual addressaddris valid for executing.
- is_offset_extern_semantics(addr: int) bool[source]¶
is_offset_extern_semanticschecks if a virtual addressaddris semantically valid for external references.
- is_offset_readable(addr: int) bool[source]¶
is_offset_readablechecks if a virtual addressaddris valid for reading.
- is_offset_writable(addr: int) bool[source]¶
is_offset_writablechecks if a virtual addressaddris valid for writing.
- is_offset_writable_semantics(addr: int) bool[source]¶
is_offset_writable_semanticschecks if a virtual addressaddris semantically writable. Some sections may have writable permissions for linking purposes but can be treated as read-only for the purposes of analysis.
- is_skip_and_return_value_patch_available(addr: int, arch: Architecture | None = None) bool[source]¶
is_skip_and_return_value_patch_availablequeries the architecture plugin to determine if the instruction ataddris similar to an x86 “call” instruction which can be made to return a value. The actual logic of which is implemented in theperform_is_skip_and_return_value_patch_availablein the corresponding architecture.- Parameters:
addr (int) – the virtual address of the instruction to be patched
arch (Architecture) – (optional) the architecture of the instructions if different from the default
- Returns:
True if the instruction can be patched, False otherwise
- Return type:
- Example:
>>> bv.get_disassembly(0x100012f6) 'mov dword [0x10003020], eax' >>> bv.is_skip_and_return_value_patch_available(0x100012f6) False >>> bv.get_disassembly(0x100012fb) 'call 0x10001629' >>> bv.is_skip_and_return_value_patch_available(0x100012fb) True >>>
- is_skip_and_return_zero_patch_available(addr: int, arch: Architecture | None = None) bool[source]¶
is_skip_and_return_zero_patch_availablequeries the architecture plugin to determine if the instruction ataddris similar to an x86 “call” instruction which can be made to return zero. The actual logic of which is implemented in theperform_is_skip_and_return_zero_patch_availablein the corresponding architecture.- Parameters:
addr (int) – the virtual address of the instruction to be patched
arch (Architecture) – (optional) the architecture of the instructions if different from the default
- Returns:
True if the instruction can be patched, False otherwise
- Return type:
- Example:
>>> bv.get_disassembly(0x100012f6) 'mov dword [0x10003020], eax' >>> bv.is_skip_and_return_zero_patch_available(0x100012f6) False >>> bv.get_disassembly(0x100012fb) 'call 0x10001629' >>> bv.is_skip_and_return_zero_patch_available(0x100012fb) True >>>
- is_type_auto_defined(name: _types.QualifiedNameType) bool[source]¶
is_type_auto_definedqueries the user type list of name. If name is not in the user type list then the name is considered an auto type.- Parameters:
name (QualifiedName) – Name of type to query
- Returns:
True if the type is not a user type. False if the type is a user type.
- Example:
>>> bv.is_type_auto_defined("foo") True >>> bv.define_user_type("foo", bv.parse_type_string("struct {int x,y;}")[0]) >>> bv.is_type_auto_defined("foo") False >>>
- Return type:
- is_valid_offset(addr: int) bool[source]¶
is_valid_offsetchecks if a virtual addressaddris valid .
- static load(source: str | bytes | bytearray | DataBuffer | PathLike | BinaryView | ProjectFile, update_analysis: bool = True, progress_func: Callable[[int, int], bool] | None = None, options: Mapping[str, Any] = {}) BinaryView | None[source]¶
loadopens, generates default load options (which are overridable), and returns the first availableBinaryView. If noBinaryViewTypeis available, then aMappedBinaryViewTypeis used to load theBinaryViewwith the specified load options. TheMappedview type attempts to auto-detect the architecture of the file during initialization. If no architecture is detected or specified in the load options, then theMappedview type fails to initialize and returnsNone.Note
Although general container file support is not complete, support for Universal archives exists. It’s possible to control the architecture preference with the ‘files.universal.architecturePreference’ setting. This setting is scoped to SettingsUserScope and can be modified as follows
>>> Settings().set_string_list("files.universal.architecturePreference", ["arm64"])
It’s also possible to override the ‘files.universal.architecturePreference’ user setting by specifying it directly with
load. This specific usage of this setting is experimental and may change in the future>>> bv = binaryninja.load('/bin/ls', options={'files.universal.architecturePreference': ['arm64']})
Warning
The recommended code pattern for opening a BinaryView is to use the
loadAPI as a context manager likewith load('/bin/ls') as bv:which will automatically clean up when done with the view. If using this API directly you will need to call bv.file.close() before the BinaryView leaves scope to ensure the reference is properly removed and prevents memory leaks.- Parameters:
source (str | bytes | bytearray | DataBuffer | PathLike | BinaryView | ProjectFile) – path to file/bndb, raw bytes, or raw view to load
update_analysis (bool) – whether or not to run
update_analysis_and_waitafter opening aBinaryView, defaults toTrueprogress_func (callback) – optional function to be called with the current progress and total count
options (dict) – a dictionary in the form {setting identifier string : object value}
source –
- Returns:
returns a
BinaryViewobject for the given filename orNone- Return type:
BinaryVieworNone- Example:
>>> binaryninja.load('/bin/ls', options={'loader.imageBase': 0xfffffff0000, 'loader.macho.processFunctionStarts' : False}) <BinaryView: '/bin/ls', start 0xfffffff0000, len 0xa290> >>>
- lookup_imported_object_library(addr: int, platform: Platform | None = None) Tuple[TypeLibrary, QualifiedName] | None[source]¶
lookup_imported_object_librarygives you details of which type library and name was used to determine the type of a symbol at a given address- Parameters:
- Returns:
A tuple of [TypeLibrary, QualifiedName] with the library and name used, or None if it was not imported
- Return type:
Tuple[TypeLibrary, QualifiedName]
- lookup_imported_type_library(name: _types.QualifiedNameType) Tuple[TypeLibrary, _types.QualifiedName] | None[source]¶
lookup_imported_type_librarygives you details of from which type library and name a given type in the analysis was imported.- Parameters:
name (_types.QualifiedNameType) – Name of type in analysis
- Returns:
A tuple of [TypeLibrary, QualifiedName] with the library and name used, or None if it was not imported
- Return type:
Optional[Tuple[TypeLibrary, QualifiedName]]
- lookup_imported_type_platform(name: _types.QualifiedNameType) Tuple[_platform.Platform, _types.QualifiedName] | None[source]¶
lookup_imported_type_platformgives you details of from which platform and name a given type in the analysis was imported.- Parameters:
name (_types.QualifiedNameType) – Name of type in analysis
- Returns:
A tuple of [Platform, QualifiedName] with the platform and name used, or None if it was not imported
- Return type:
Optional[Tuple[Platform, QualifiedName]]
- mlil_functions(preload_limit: int | None = None, function_generator: Generator[Function, None, None] | None = None) Generator[MediumLevelILFunction, None, None][source]¶
Generates a list of il functions. This method should be used instead of ‘functions’ property if MLIL is needed and performance is a concern.
- Parameters:
- Return type:
Generator[MediumLevelILFunction, None, None]
navigatenavigates the UI to the specified virtual address in the specified ViewThe View name is created by combining a View type (e.g. “Graph”) with a BinaryView type (e.g. “Mach-O”), separated by a colon, resulting in something like “Graph:Mach-O”.
- Parameters:
- Returns:
whether navigation succeeded
- Return type:
- Example:
>>> bv.navigate(bv.view, bv.start) True >>> bv.file.existing_views ['Mach-O', 'Raw'] >>> import binaryninjaui >>> [i.getName() for i in binaryninjaui.ViewType.getTypes()] ['Graph', 'Hex', 'Linear', 'Strings', 'Types', 'Triage', 'Bytes'] >>> bv.navigate('Graph:Mach-O', bv.entry_point) True
- never_branch(addr: int, arch: Architecture | None = None) bool[source]¶
never_branchconvert the branch instruction of architecturearchat the virtual addressaddrto a fall through.Note
This API performs a binary patch, analysis may need to be updated afterward. Additionally the binary file must be saved in order to preserve the changes made.
- Parameters:
addr (int) – virtual address of the instruction to be modified
arch (Architecture) – (optional) the architecture of the instructions if different from the default
- Returns:
True on success, False on failure.
- Return type:
- Example:
>>> bv.get_disassembly(0x1000130e) 'jne 0x10001317' >>> bv.never_branch(0x1000130e) True >>> bv.get_disassembly(0x1000130e) 'nop' >>>
- static new(data: bytes | bytearray | DataBuffer | None = None, file_metadata: FileMetadata | None = None) BinaryView | None[source]¶
newcreates a new, RawBinaryViewfor the provided data.- Parameters:
data (Union[
str,bytes,bytearray,DataBuffer,os.PathLike,BinaryView]) – path to file/bndb, raw bytes, or raw view to loadfile_metadata (
FileMetadata) – Optional FileMetadata object for this new view
- Returns:
returns a
BinaryViewobject for the given filename orNone- Return type:
BinaryVieworNone- Example:
>>> binaryninja.load('/bin/ls', options={'loader.imageBase': 0xfffffff0000, 'loader.macho.processFunctionStarts' : False}) <BinaryView: '/bin/ls', start 0xfffffff0000, len 0xa290> >>>
- static open(src, file_metadata=None) BinaryView | None[source]¶
- Return type:
BinaryView | None
- parse_expression(expression: str, here: int = 0) int[source]¶
Evaluates a string expression to an integer value.
The parser uses the following rules:
Symbols are defined by the lexer as
[A-Za-z0-9_:<>][A-Za-z0-9_:$\-<>]+or anything enclosed in either single or double quotesSymbols are everything in
bv.symbols, unnamed DataVariables (i.e.data_00005000), unnamed functions (i.e.sub_00005000), or section names (i.e..text)Numbers are defaulted to hexadecimal thus _printf + 10 is equivalent to printf + 0x10 If decimal numbers required use the decimal prefix.
Since numbers and symbols can be ambiguous its recommended that you prefix your numbers with the following:
0x- Hexadecimal0n- Decimal0- Octal
In the case of an ambiguous number/symbol (one with no prefix) for instance
12345we will first attempt to look up the string as a symbol, if a symbol is found its address is used, otherwise we attempt to convert it to a hexadecimal number.The following operations are valid:
+, -, \*, /, %, (), &, \|, ^, ~, ==, !=, >, <, >=, <=Comparison operators return 1 if the condition is true, 0 otherwise.
In addition to the above operators there are dereference operators similar to BNIL style IL:
[<expression>]- read the current address size at<expression>[<expression>].b- read the byte at<expression>[<expression>].w- read the word (2 bytes) at<expression>[<expression>].d- read the dword (4 bytes) at<expression>[<expression>].q- read the quadword (8 bytes) at<expression>
The
$here(or more succinctly:$) keyword can be used in calculations and is defined as thehereparameter, or the currently selected addressThe
$start/$endkeyword represents the address of the first/last bytes in the file respectivelyArbitrary magic values (name-value-pairs) can be added to the expression parser via the
add_expression_parser_magic_valueAPI. Notably, the debugger adds all register values into the expression parser so they can be used directly when navigating. The register values can be referenced like $rbp, $x0, etc. For more details, refer to the related debugger docs.
- parse_possiblevalueset(value: str, state: RegisterValueType, here: int = 0) PossibleValueSet[source]¶
Evaluates a string representation of a PossibleValueSet into an instance of the
PossibleValueSetvalue.Note
Values are evaluated based on the rules as specified for
parse_expressionAPI. This implies that aConstantValue [0x4000].dcan be provided given that 4 bytes can be read at0x4000. All constants are considered to be in hexadecimal form by default.- The parser uses the following rules:
ConstantValue -
<value>ConstantPointerValue -
<value>StackFrameOffset -
<value>SignedRangeValue -
<value>:<value>:<value>{,<value>:<value>:<value>}*(Multiple ValueRanges can be provided by separating them by commas)UnsignedRangeValue -
<value>:<value>:<value>{,<value>:<value>:<value>}*(Multiple ValueRanges can be provided by separating them by commas)InSetOfValues -
<value>{,<value>}*NotInSetOfValues -
<value>{,<value>}*
- Parameters:
value (str) – PossibleValueSet value to be parsed
state (RegisterValueType) – State for which the value is to be parsed
here (int) – (optional) Base address for relative expressions, defaults to zero
- Return type:
- Example:
>>> psv_c = bv.parse_possiblevalueset("400", RegisterValueType.ConstantValue) >>> psv_c <const 0x400> >>> psv_ur = bv.parse_possiblevalueset("1:10:1", RegisterValueType.UnsignedRangeValue) >>> psv_ur <unsigned ranges: [<range: 0x1 to 0x10>]> >>> psv_is = bv.parse_possiblevalueset("1,2,3", RegisterValueType.InSetOfValues) >>> psv_is <in set([0x1, 0x2, 0x3])> >>>
- parse_type_string(text: str, import_dependencies: bool = True) Tuple[Type, QualifiedName][source]¶
parse_type_stringparses string containing C into a single typeType. In contrast to theparse_types_from_sourceorparse_types_from_source_file,parse_type_stringcan only load a single type, though it can take advantage of existing type information in the binary view, while those two APIs do not.- Parameters:
- Returns:
A tuple of a
Typeand type name- Return type:
- Example:
>>> bv.parse_type_string("int foo") (<type: int32_t>, 'foo') >>>
- parse_types_from_string(text: str, options: List[str] | None = None, include_dirs: List[str] | None = None, import_dependencies: bool = True) BasicTypeParserResult[source]¶
parse_types_from_stringparses string containing C into aBasicTypeParserResultobjects. This API unlike theparse_types_from_sourceallows the reference of types already defined in the BinaryView.- Parameters:
text (str) – C source code string of types, variables, and function types, to create
options (List[str] | None) – Optional list of string options to be passed into the type parser
include_dirs (List[str] | None) – Optional list of header search directories
import_dependencies (bool) – If Type Library types should be imported during parsing
- Returns:
BasicTypeParserResult(a SyntaxError is thrown on parse error)- Return type:
- Example:
>>> bv.parse_types_from_string('int foo;\nint bar(int x);\nstruct bas{int x,y;};\n') ({types: {'bas': <type: struct bas>}, variables: {'foo': <type: int32_t>}, functions:{'bar': <type: int32_t(int32_t x)>}}, '') >>>
- perform_get_default_endianness() Endianness[source]¶
perform_get_default_endiannessimplements a check which returns the Endianness of the BinaryViewNote
This method may be implemented for custom BinaryViews that are not LittleEndian.
Warning
This method must not be called directly.
- Returns:
either
Endianness.LittleEndianorEndianness.BigEndian- Return type:
- perform_get_entry_point() int[source]¶
perform_get_entry_pointimplements a query for the initial entry point for code execution.Note
This method should be implemented for custom BinaryViews that are executable.
Warning
This method must not be called directly.
- Returns:
the virtual address of the entry point
- Return type:
- perform_get_length() int[source]¶
perform_get_lengthimplements a query for the size of the virtual address range used by the BinaryView.Note
This method may be overridden by custom BinaryViews. Use
add_auto_segmentto provide data without overriding this method.Warning
This method must not be called directly.
- Returns:
returns the size of the virtual address range used by the BinaryView
- Return type:
- perform_get_modification(addr: int) ModificationStatus[source]¶
perform_get_modificationimplements query to the whether the virtual addressaddris modified.Note
This method may be overridden by custom BinaryViews. Use
add_auto_segmentto provide data without overriding this method.Warning
This method must not be called directly.
- Parameters:
addr (int) – a virtual address to be checked
- Returns:
one of the following: Original = 0, Changed = 1, Inserted = 2
- Return type:
- perform_get_next_valid_offset(addr: int) int[source]¶
perform_get_next_valid_offsetimplements a query for the next valid readable, writable, or executable virtual memory address.Note
This method may be overridden by custom BinaryViews. Use
add_auto_segmentto provide data without overriding this method.Warning
This method must not be called directly.
- perform_get_start() int[source]¶
perform_get_startimplements a query for the first readable, writable, or executable virtual address in the BinaryView.Note
This method may be overridden by custom BinaryViews. Use
add_auto_segmentto provide data without overriding this method.Warning
This method must not be called directly.
- Returns:
returns the first virtual address in the BinaryView
- Return type:
- perform_insert(addr: int, data: bytes) int[source]¶
perform_insertimplements a mapping between a virtual address and an absolute file offset, inserting the bytesdatato rebased addressaddr.Note
This method may be overridden by custom BinaryViews. If not overridden, inserting is disallowed
Warning
This method must not be called directly.
- perform_is_executable() bool[source]¶
perform_is_executableimplements a check which returns true if the BinaryView is executable.Note
This method must be implemented for custom BinaryViews that are executable.
Warning
This method must not be called directly.
- Returns:
true if the current BinaryView is executable, false if it is not executable or on error
- Return type:
- perform_is_offset_executable(addr: int) bool[source]¶
perform_is_offset_executableimplements a check if a virtual addressaddris executable.Note
This method may be overridden by custom BinaryViews. Use
add_auto_segmentto provide data without overriding this method.Warning
This method must not be called directly.
- perform_is_offset_readable(offset: int) bool[source]¶
perform_is_offset_readableimplements a check if a virtual address is readable.Note
This method may be overridden by custom BinaryViews. Use
add_auto_segmentto provide data without overriding this method.Warning
This method must not be called directly.
- perform_is_offset_writable(addr: int) bool[source]¶
perform_is_offset_writableimplements a check if a virtual addressaddris writable.Note
This method may be overridden by custom BinaryViews. Use
add_auto_segmentto provide data without overriding this method.Warning
This method must not be called directly.
- perform_is_relocatable() bool[source]¶
perform_is_relocatableimplements a check which returns true if the BinaryView is relocatable. Defaults to FalseNote
This method may be implemented for custom BinaryViews that are relocatable.
Warning
This method must not be called directly.
- Returns:
True if the BinaryView is relocatable, False otherwise
- Return type:
boolean
- perform_is_valid_offset(addr: int) bool[source]¶
perform_is_valid_offsetimplements a check if a virtual addressaddris valid.Note
This method may be overridden by custom BinaryViews. Use
add_auto_segmentto provide data without overriding this method.Warning
This method must not be called directly.
- perform_read(addr: int, length: int) bytes[source]¶
perform_readimplements a mapping between a virtual address and an absolute file offset, readinglengthbytes from the rebased addressaddr.Note
This method may be overridden by custom BinaryViews. Use
add_auto_segmentto provide data without overriding this method.Warning
This method must not be called directly.
- perform_remove(addr: int, length: int) int[source]¶
perform_removeimplements a mapping between a virtual address and an absolute file offset, removinglengthbytes from the rebased addressaddr.Note
This method may be overridden by custom BinaryViews. If not overridden, removing data is disallowed
Warning
This method must not be called directly.
- perform_write(addr: int, data: bytes) int[source]¶
perform_writeimplements a mapping between a virtual address and an absolute file offset, writing the bytesdatato rebased addressaddr.Note
This method may be overridden by custom BinaryViews. Use
add_auto_segmentto provide data without overriding this method.Warning
This method must not be called directly.
- pull_types_from_archive(archive: TypeArchive, names: List[_types.QualifiedNameType]) Mapping[_types.QualifiedName, Tuple[_types.QualifiedName, _types.Type]] | None[source]¶
Pull types from a type archive, updating them and any dependencies
- Parameters:
archive (TypeArchive) – Target type archive
names (List[_types.QualifiedNameType]) – Names of desired types in type archive
- Returns:
{ name: (name, type) } Mapping from archive name to (analysis name, definition), None on error
- Return type:
Mapping[_types.QualifiedName, Tuple[_types.QualifiedName, _types.Type]] | None
- pull_types_from_archive_by_id(archive_id: str, archive_type_ids: List[str]) Mapping[str, str] | None[source]¶
Pull types from a type archive by id, updating them and any dependencies
- push_types_to_archive(archive: TypeArchive, names: List[_types.QualifiedNameType]) Mapping[_types.QualifiedName, Tuple[_types.QualifiedName, _types.Type]] | None[source]¶
Push a collection of types, and all their dependencies, into a type archive
- Parameters:
archive (TypeArchive) – Target type archive
names (List[_types.QualifiedNameType]) – Names of types in analysis
- Returns:
{ name: (name, type) } Mapping from analysis name to (archive name, definition), None on error
- Return type:
Mapping[_types.QualifiedName, Tuple[_types.QualifiedName, _types.Type]] | None
- push_types_to_archive_by_id(archive_id: str, type_ids: List[str]) Mapping[str, str] | None[source]¶
Push a collection of types, and all their dependencies, into a type archive
- query_metadata(key: str) metadata.MetadataValueType[source]¶
query_metadata retrieves a metadata associated with the given key stored in the current BinaryView.
- Parameters:
key (str) – key to query
- Return type:
metadata associated with the key
- Example:
>>> bv.store_metadata("integer", 1337) >>> bv.query_metadata("integer") 1337L >>> bv.store_metadata("list", [1,2,3]) >>> bv.query_metadata("list") [1L, 2L, 3L] >>> bv.store_metadata("string", "my_data") >>> bv.query_metadata("string") 'my_data'
- range_contains_relocation(addr: int, size: int) bool[source]¶
Checks if the specified range overlaps with a relocation
- read(addr: int, length: int) bytes[source]¶
readreturns the data reads at mostlengthbytes from virtual addressaddr.- Parameters:
- Returns:
at most
lengthbytes from the virtual addressaddr, empty string on error or no data- Return type:
- Example:
>>> #Opening a x86_64 Mach-O binary >>> bv = BinaryView.new("/bin/ls") # note that we are using `new` instead of `load` to get the raw view >>> bv.read(0,4) b'\xcf\xfa\xed\xfe'
- read_int(address: int, size: int, sign: bool = True, endian: Endianness | None = None) int[source]¶
- Parameters:
address (int) –
size (int) –
sign (bool) –
endian (Endianness | None) –
- Return type:
- read_uuid(address: int, ms_format: bool = True) UUID[source]¶
Reads a UUID from the specified address in the binary view.
- Parameters:
- Returns:
A UUID object
- Raises:
ValueError – If 16 bytes couldn’t be read from the specified address.
- Return type:
- reader(address: int | None = None) BinaryReader[source]¶
- Parameters:
address (int | None) –
- Return type:
- reanalyze() None[source]¶
reanalyzecauses all functions to be reanalyzed. This function does not wait for the analysis to finish.- Return type:
None
- rebase(address: int, force: bool | None = False, progress_func: Callable[[int, int], bool] | None = None) BinaryView | None[source]¶
rebaserebase the existingBinaryViewinto a newBinaryViewat the specified virtual addressNote
This method does not update corresponding UI components. If the BinaryView is associated with UI components then initiate the rebase operation within the UI, e.g. using the command palette. If working with views that are not associated with UI components while the UI is active, then set
forcetoTrueto enable rebasing.- Parameters:
- Returns:
the new
BinaryViewobject orNoneon failure- Return type:
BinaryVieworNone- Example:
>>> from binaryninja import load >>> bv = load('/bin/ls') >>> print(bv) <BinaryView: '/bin/ls', start 0x100000000, len 0x182f8> >>> newbv = bv.rebase(0x400000) >>> print(newbv) <BinaryView: '/bin/ls', start 0x400000, len 0x182f8>
- record_imported_object_library(lib: TypeLibrary, name: str, addr: int, platform: Platform | None = None) None[source]¶
record_imported_object_libraryshould be called by custom py:py:class:BinaryView implementations when they have successfully imported an object from a type library (e.g. a symbol’s type). Values recorded with this function will then be queryable vialookup_imported_object_library.- Parameters:
lib (TypeLibrary) – Type Library containing the imported type
name (str) – Name of the object in the type library
addr (int) – address of symbol at import site
platform (Platform | None) – Platform of symbol at import site
- Return type:
None
- redo() None[source]¶
redoredo the last committed transaction in the undo database.- Return type:
None
- Example:
>>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>> with bv.undoable_transaction(): >>> bv.convert_to_nop(0x100012f1) True >>> bv.get_disassembly(0x100012f1) 'nop' >>> bv.undo() >>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>> bv.redo() >>> bv.get_disassembly(0x100012f1) 'nop' >>>
- register_notification(notify: BinaryDataNotification) None[source]¶
register_notification enables the receipt of callbacks for various analysis events. A full list of callbacks is available in the
BinaryDataNotificationclass. If the notification_barrier is enabled, then it is triggered upon the initial call to register_notification. Subsequent calls for an already registerednotifyinstance also trigger a notification_barrier callback.- Parameters:
notify (BinaryDataNotification) – notify is a subclassed instance of
BinaryDataNotification.- Return type:
None
- register_platform_types(platform: Platform) None[source]¶
register_platform_typesensures that the platform-specific types for aPlatformare available for the currentBinaryView. This is automatically performed when adding a new function or setting the default platform.- Parameters:
platform (Platform) – Platform containing types to be registered
- Return type:
None
- Example:
>>> platform = Platform["linux-x86"] >>> bv.register_platform_types(platform) >>>
- relocation_ranges_at(addr: int) List[Tuple[int, int]][source]¶
List of relocation range tuples for a given address
- relocation_ranges_in_range(addr: int, size: int) List[Tuple[int, int]][source]¶
List of relocation range tuples for a given range
- relocations_at(addr: int) List[Relocation][source]¶
List of relocations for a given address
- Parameters:
addr (int) –
- Return type:
- remove(addr: int, length: int) int[source]¶
removeremoves at mostlengthbytes from virtual addressaddr.
- remove_auto_data_tag(addr: int, tag: Tag)[source]¶
remove_auto_data_tagremoves a Tag object at a data address.
- remove_auto_data_tags_of_type(addr: int, tag_type: str)[source]¶
remove_auto_data_tags_of_typeremoves all data tags at the given address of the given type.
- remove_auto_segment(start: int, length: int = 0) None[source]¶
remove_auto_segmentRemoves an automatically generated segment from the current segment mapping. This method removes the most recently added ‘auto’ segment that either matches the specified start address or contains it.- Parameters:
- Return type:
None
Warning
This action is not persistent across saving of a BNDB and must be re-applied each time a BNDB is loaded.
- remove_component(_component: Component | str) bool[source]¶
Remove a component from the tree entirely.
- remove_data_ref(from_addr: int, to_addr: int) None[source]¶
remove_data_refremoves an auto data cross-reference (xref) from the addressfrom_addrto the addressto_addr. This function will only remove ones generated during autoanalysis. If the reference does not exist, no action is performed.- Parameters:
- Return type:
None
Note
It is intended to be used from within workflows or other reoccurring analysis tasks. Removed references will be re-created whenever auto analysis is re-run for the
- remove_expression_parser_magic_value(name: str) None[source]¶
Remove a magic value from the expression parser.
If the magic value gets referenced after removal, an error will occur during the parsing.
- Parameters:
name (str) – name for the magic value to remove
- Returns:
- Return type:
None
- remove_expression_parser_magic_values(names: List[str]) None[source]¶
Remove a list of magic value from the expression parser
If any of the magic values gets referenced after removal, an error will occur during the parsing.
- remove_external_library(name: str)[source]¶
Remove an ExternalLibrary from this BinaryView by name. Any associated ExternalLocations will be unassociated from the ExternalLibrary
- Parameters:
name (str) – Name of the external library to remove
- remove_external_location(source_symbol: CoreSymbol)[source]¶
Remove the ExternalLocation with the given source symbol from this BinaryView
- Parameters:
source_symbol (CoreSymbol) – Source symbol that will be used to determine the ExternalLocation to remove
- remove_function(func: Function, update_refs=False) None[source]¶
remove_functionremoves the functionfuncfrom the list of functionsWarning
This method should only be used when the function that is removed is expected to re-appear after any other analysis executes that could re-add it. Most users will want to use
remove_user_functionin their scripts.
- remove_metadata(key: str) None[source]¶
remove_metadata removes the metadata associated with key from the current BinaryView.
- Parameters:
key (str) – key associated with metadata to remove from the BinaryView
- Return type:
None
- Example:
>>> bv.store_metadata("integer", 1337) >>> bv.remove_metadata("integer")
- remove_tag_type(tag_type: str)[source]¶
remove_tag_typeremoves aTagTypeand all tags that use it- Parameters:
tag_type (str) – The name of the tag type to remove
- Return type:
None
- remove_user_data_ref(from_addr: int, to_addr: int) None[source]¶
remove_user_data_refremoves a user-specified data cross-reference (xref) from the addressfrom_addrto the addressto_addr. This function will only remove user-specified references, not ones generated during autoanalysis. If the reference does not exist, no action is performed.
- remove_user_data_tag(addr: int, tag: Tag)[source]¶
remove_user_data_tagremoves aTagobject at a data address. Since this removes a user tag, it will be added to the current undo buffer.
- remove_user_data_tags_of_type(addr: int, tag_type: str)[source]¶
remove_user_data_tags_of_typeremoves all data tags at the given address of the given type. Since this removes user tags, it will be added to the current undo buffer.
- remove_user_function(func: Function) None[source]¶
remove_user_functionremoves the functionfuncfrom the list of functions as a user action.Note
This API will prevent the function from being re-created if any analysis later triggers that would re-add it, unlike
remove_function.- Parameters:
func (Function) – a Function object.
- Return type:
None
- Example:
>>> bv.functions [<func: x86_64@0x1>] >>> bv.remove_user_function(next(bv.functions)) >>> bv.functions []
- remove_user_segment(start: int, length: int = 0) None[source]¶
remove_user_segmentRemoves a user-defined segment from the current segment mapping. This method removes the most recently added ‘user’ segment that either matches the specified start address or contains it.
- rename_type(old_name: _types.QualifiedNameType, new_name: _types.QualifiedNameType) None[source]¶
rename_typerenames a type in the global list of types for the currentBinaryView- Parameters:
old_name (QualifiedName) – Existing name of type to be renamed
new_name (QualifiedName) – New name of type to be renamed
- Return type:
None
- Example:
>>> type, name = bv.parse_type_string("int foo") >>> bv.define_user_type(name, type) >>> bv.get_type_by_name("foo") <type: int32_t> >>> bv.rename_type("foo", "bar") >>> bv.get_type_by_name("bar") <type: int32_t> >>>
- revert_undo_actions(id: str | None = None) None[source]¶
revert_undo_actionsreverts the actions taken since a call tobegin_undo_actionsPass as id the value returned bybegin_undo_actions. Empty values of id will revert all changes since the last call tobegin_undo_actions.- Parameters:
id (Optional[str]) – id of undo state, from
begin_undo_actions- Return type:
None
- Example:
>>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>> state = bv.begin_undo_actions() >>> bv.convert_to_nop(0x100012f1) True >>> bv.revert_undo_actions(state) >>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>>
- save(dest: FileAccessor | str) bool[source]¶
savesaves the original binary file to the provided destinationdestalong with any modifications.Warning
This API will only save the original file from a view. To save a database, use
create_database.
- save_auto_snapshot(progress_func: Callable[[int, int], bool] | None = None, settings: SaveSettings | None = None) bool[source]¶
save_auto_snapshotsaves the current database to the already created file.Note
create_databaseshould have been called prior to executing this method- Parameters:
progress_func (callback) – optional function to be called with the current progress and total count.
settings (SaveSettings) – optional argument for special save options.
- Returns:
True if it successfully saved the snapshot, False otherwise
- Return type:
- search(pattern: str, start: int | None = None, end: int | None = None, raw: bool = False, ignore_case: bool = False, overlap: bool = False, align: int = 1, limit: int | None = None, progress_callback: Callable[[int, int], bool] | None = None, match_callback: Callable[[int, DataBuffer], bool] | None = None) QueueGenerator[source]¶
Searches for matches of the specified
patternwithin this BinaryView with an optionally provided address range specified bystartandend. The search pattern can be interpreted in various ways:specified as a string of hexadecimal digits where whitespace is ignored, and the ‘?’ character acts as a wildcard
a regular expression suitable for working with bytes
or if the
rawoption is enabled, the pattern is interpreted as a raw string, and any special characters are escaped and interpreted literally
- Parameters:
pattern (
str) – The pattern to search for.start (
int) – The address to start the search from. (default: None)end (
int) – The address to end the search (inclusive). (default: None)raw (bool) – Whether to interpret the pattern as a raw string (default: False).
ignore_case (bool) – Whether to perform case-insensitive matching (default: False).
overlap (bool) – Whether to allow matches to overlap (default: False).
align (int) – The alignment of matches, must be a power of 2 (default: 1).
limit (int) – The maximum number of matches to return (default: None).
progress_callback (callback) – An optional function to be called with the current progress and total count. This function should return a boolean value that decides whether the search should continue or stop.
match_callback (callback) – A function that gets called when a match is found. The callback takes two parameters: the address of the match, and the actual DataBuffer that satisfies the search. This function can return a boolean value that decides whether the search should continue or stop.
- Returns:
A generator object that yields the offset and matched DataBuffer for each match found.
- Return type:
- Example:
>>> from binaryninja import load >>> bv = load('/bin/ls') >>> print(bv) <BinaryView: '/bin/ls', start 0x100000000, len 0x182f8> >>> bytes(list(bv.search("50 ?4"))[0][1]).hex() '5004' >>> bytes(list(bv.search("[\x20-\x25][\x60-\x67]"))[0][1]).hex() '2062'
- set_analysis_hold(enable: bool) None[source]¶
set_analysis_holdcontrol the analysis hold for this BinaryView. Enabling analysis hold defers all future analysis updates, therefore causingupdate_analysisorupdate_analysis_and_waitto take no action.- Return type:
None
- Parameters:
enable (bool) –
- set_comment_at(addr: int, comment: str) None[source]¶
set_comment_atsets a comment for the BinaryView at the address specifiedNote that these are different from function-level comments which are specific to each
Function. For more information, seeaddress_comments.
- static set_default_session_data(name: str, value: str) None[source]¶
set_default_session_datasaves a variable to the BinaryView. Session data is ephemeral not saved to a database. Consider usingstore_metadataif permanence is needed.
- set_function_analysis_update_disabled(disabled: bool) None[source]¶
set_function_analysis_update_disabledprevents any function from being marked as updates required, so that they would NOT be re-analyzed when the analysis is updated. The main difference between this API andset_analysis_holdis thatset_analysis_holdonly temporarily holds the analysis, and the functions are still arranged to be updated when the hold is turned off. However, withset_function_analysis_update_disabled, functions would not be put into the analysis queue at all.Use with caution – in most cases, this is NOT what you want, and you should use
set_analysis_holdinstead.- Parameters:
disabled (bool) –
- Returns:
- Return type:
None
- set_load_settings(type_name: str, settings: Settings | None) None[source]¶
set_load_settingsset aSettingsobject which defines the load settings for the givenBinaryViewTypetype_name- Parameters:
type_name (str) – the
BinaryViewTypenamesettings (Settings) – the load settings
- Return type:
None
- set_manual_type_source_override(entries: Mapping[QualifiedName, Tuple[QualifiedName, str]])[source]¶
This allows for fine-grained control over how types from this BinaryView are exported to a TypeLibrary by export_type_to_library and export_object_to_library. Types identified by the keys of the dict will NOT be exported to the destination TypeLibrary, but will instead be treated as a type that had come from the string component of the value tuple. This results in the destination TypeLibrary gaining a new dependency.
This is useful if a BinaryView was automatically marked up with a lot of debug information but you want to export only a subset of that information into a new TypeLibrary. By creating a description of which local types correspond to types in other already extant libraries, those types will be avoided during the recursive export.
This data is not persisted and does not impact analysis.
For example, if a BinaryView contains the following types:
struct RECT { ... }; // omitted struct ContrivedExample { RECT rect; };
Then the following python:
overrides = {"RECT": ("tagRECT", "winX64common")} bv.set_manual_type_source_override(overrides) bv.export_type_to_library(dest_new_typelib, "ContrivedExample", bv.get_type_by_name("ContrivedExample"))
Results in dest_new_typelib only having ContrivedExample added, and “RECT” being inserted as a dependency to a the type “tagRECT” found in the typelibrary “winX64common”
- Parameters:
entries (Mapping[QualifiedName, Tuple[QualifiedName, str]]) –
- set_user_global_pointer_value(value: RegisterValue, confidence=255)[source]¶
Set a user global pointer value. This is useful when the auto analysis fails to find out the value of the global pointer, or the value is wrong. In this case, we can call
set_user_global_pointer_valuewith aConstantRegisterValueorConstantPointerRegisterValueto provide a user global pointer value to assist the analysis.On the other hand, if the auto analysis figures out a global pointer value, but there should not be one, we can call
set_user_global_pointer_valuewith an Undetermined value to override it.Whenever a user global pointer value is set/cleared, an analysis update must occur for it to take effect and all functions using the global pointer to be updated.
We can use
user_global_pointer_value_setto query whether a user global pointer value is set, and useclear_user_global_pointer_valueto clear a user global pointer value. Note,clear_user_global_pointer_valueis different from callingset_user_global_pointer_valuewith anUndeterminedvalue. The former clears the user global pointer value and let the analysis decide the global pointer value, whereas the latte forces the global pointer value to become undetermined.- Parameters:
value (RegisterValue) – the user global pointer value to be set
confidence (int) – the confidence value of the user global pointer value. In most cases this should be set to 255. Setting a value lower than the confidence of the global pointer value from the auto analysis will cause undesired effect.
- Returns:
None
- Return type:
None
- Example:
>>> bv.global_pointer_value <const ptr 0x3fd4> >>> bv.set_user_global_pointer_value(ConstantPointerRegisterValue(0x12345678)) >>> bv.global_pointer_value <const ptr 0x12345678> >>> bv.user_global_pointer_value_set True >>> bv.clear_user_global_pointer_value() >>> bv.global_pointer_value <const ptr 0x3fd4> >>> bv.set_user_global_pointer_value(Undetermined()) >>> bv.global_pointer_value <undetermined>
- should_skip_target_analysis(source_location: ArchAndAddr, source_function: Function, end: int, target_location: ArchAndAddr) bool[source]¶
should_skip_target_analysischecks if target analysis should be skipped.Note
This method is intended for use by architecture plugins only.
- Parameters:
source_location (_function.ArchAndAddr) – The source location.
source_function (_function.Function) – The source function.
end (int) – The end address of the source branch instruction.
target_location (_function.ArchAndAddr) – The target location.
- Returns:
True if the target analysis should be skipped, False otherwise
- Return type:
- show_graph_report(title: str, graph: FlowGraph) None[source]¶
show_graph_reportdisplays aFlowGraphobject graph in a new tab withtitle.- Parameters:
title (Text string title of the tab) – Title of the graph
graph (
FlowGraphobject) – The graph you wish to display
- Return type:
None
- show_html_report(title: str, contents: str, plaintext: str = '') None[source]¶
show_html_reportdisplays the HTML contents in UI applications and plaintext in command-line applications. HTML reports support hyperlinking into the BinaryView. Hyperlinks can be specified as follows:binaryninja://?expr=_startWhereexpr=specifies an expression parsable by theparse_expressionAPI.Note
This API function differently on the command-line vs the UI. In the UI a pop-up is used. On the command-line a simple text prompt is used.
- show_markdown_report(title: str, contents: str, plaintext: str = '') None[source]¶
show_markdown_reportdisplays the markdown contents in UI applications and plaintext in command-line applications. Markdown reports support hyperlinking into the BinaryView. Hyperlinks can be specified as follows:binaryninja://?expr=_startWhereexpr=specifies an expression parsable by theparse_expressionAPI.Note
This API functions differently on the command-line vs the UI. In the UI a pop-up is used. On the command-line a simple text prompt is used.
- skip_and_return_value(addr: int, value: int, arch: Architecture | None = None) bool[source]¶
skip_and_return_valueconvert thecallinstruction of architecturearchat the virtual addressaddrto the equivalent of returning a value.- Parameters:
addr (int) – virtual address of the instruction to be modified
value (int) – value to make the instruction return
arch (Architecture) – (optional) the architecture of the instructions if different from the default
- Returns:
True on success, False on failure.
- Return type:
- Example:
>>> bv.get_disassembly(0x1000132a) 'call 0x1000134a' >>> bv.skip_and_return_value(0x1000132a, 42) True >>> #The return value from x86 functions is stored in eax thus: >>> bv.get_disassembly(0x1000132a) 'mov eax, 0x2a' >>>
- store_metadata(key: str, md: Metadata | int | bool | str | bytes | float | List[MetadataValueType] | Tuple[MetadataValueType] | dict, isAuto: bool = False) None[source]¶
store_metadata stores an object for the given key in the current BinaryView. Objects stored using store_metadata can be retrieved when the database is reopened. Objects stored are not arbitrary python objects! The values stored must be able to be held in a Metadata object. See
Metadatafor more information. Python objects could obviously be serialized using pickle but this intentionally a task left to the user since there is the potential security issues.- Parameters:
key (str) – key value to associate the Metadata object with
md (Varies) – object to store.
isAuto (bool) – whether the metadata is an auto metadata. Most metadata should keep this as False. Only those automatically generated metadata should have this set to True. Auto metadata is not saved into the database and is presumably re-generated when re-opening the database.
- Return type:
None
- Example:
>>> bv.store_metadata("integer", 1337) >>> bv.query_metadata("integer") 1337L >>> bv.store_metadata("list", [1,2,3]) >>> bv.query_metadata("list") [1L, 2L, 3L] >>> bv.store_metadata("string", "my_data") >>> bv.query_metadata("string") 'my_data'
- stringify_unicode_data(arch: Architecture | None, buffer: DataBuffer, null_terminates: bool = True, allow_short_strings: bool = False) Tuple[str | None, StringType | None][source]¶
stringify_unicode_dataconverts a buffer of unicode data into a string representation. :param arch: The architecture to use for stringification, or None to use the current architecture of the BinaryView :param buffer: The DataBuffer containing the unicode data to stringify :param null_terminates: If True, stops stringification at the first null character, otherwise continues until the end of the buffer :param allow_short_strings: If True, allows short strings to be returned, otherwise only long strings are returned :return: A tuple containing the string representation and its type, or (None, None) if the stringification fails :rtype: Tuple[Optional[str], Optional[StringType]]- Parameters:
arch (Architecture | None) –
buffer (DataBuffer) –
null_terminates (bool) –
allow_short_strings (bool) –
- Return type:
Tuple[str | None, StringType | None]
- tags_by_type(tag_type: TagType) List[Tuple[int, Tag]][source]¶
tags_by_typefetches tags of a specific type.
- tags_for_data_by_type(tag_type: TagType) List[Tuple[int, Tag]][source]¶
tags_for_data_by_typefetches data-specific tags of a specific type.
- tags_for_data_with_source(auto: bool = True) List[Tuple[int, Tag]][source]¶
tags_for_data_with_sourcefetches data-specific tags filtered by source.
- typed_data_accessor(address: int, type: Type) TypedDataAccessor[source]¶
- Parameters:
- Return type:
- undefine_auto_symbol(sym: CoreSymbol) None[source]¶
undefine_auto_symbolremoves a symbol from the internal list of automatically discovered Symbol objects.- Parameters:
sym (Symbol) – the symbol to undefine
- Return type:
None
- undefine_data_var(addr: int, blacklist: bool = True) None[source]¶
undefine_data_varremoves the non-user data variable at the virtual addressaddr.- Parameters:
- Return type:
None
- Example:
>>> bv.undefine_data_var(bv.entry_point) >>>
- undefine_type(type_id: str) None[source]¶
undefine_typeremoves aTypefrom the global list of types for the currentBinaryView- Parameters:
type_id (str) – Unique identifier of type to be undefined
- Return type:
None
- Example:
>>> type, name = bv.parse_type_string("int foo") >>> type_id = Type.generate_auto_type_id("source", name) >>> bv.define_type(type_id, name, type) >>> bv.get_type_by_name(name) <type: int32_t> >>> bv.undefine_type(type_id) >>> bv.get_type_by_name(name) >>>
- undefine_user_data_var(addr: int) None[source]¶
undefine_user_data_varremoves the user data variable at the virtual addressaddr.- Parameters:
addr (int) – virtual address to define the data variable to be removed
- Return type:
None
- Example:
>>> bv.undefine_user_data_var(bv.entry_point) >>>
- undefine_user_symbol(sym: CoreSymbol) None[source]¶
undefine_user_symbolremoves a symbol from the internal list of user added Symbol objects.- Parameters:
sym (CoreSymbol) – the symbol to undefine
- Return type:
None
- undefine_user_type(name: _types.QualifiedNameType) None[source]¶
undefine_user_typeremoves aTypefrom the global list of user types for the currentBinaryView- Parameters:
name (QualifiedName) – Name of user type to be undefined
- Return type:
None
- Example:
>>> type, name = bv.parse_type_string("int foo") >>> bv.define_user_type(name, type) >>> bv.get_type_by_name(name) <type: int32_t> >>> bv.undefine_user_type(name) >>> bv.get_type_by_name(name) >>>
- undo() None[source]¶
undoundo the last committed transaction in the undo database.- Return type:
None
- Example:
>>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>> with bv.undoable_transaction(): >>> bv.convert_to_nop(0x100012f1) True >>> bv.get_disassembly(0x100012f1) 'nop' >>> bv.undo() >>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>> bv.redo() >>> bv.get_disassembly(0x100012f1) 'nop' >>>
- undoable_transaction() Generator[source]¶
undoable_transactiongives you a context in which you can make changes to analysis, and creates an Undo state containing those actions. If an exception is thrown, any changes made to the analysis inside the transaction are reverted.- Returns:
Transaction context manager, which will commit/revert actions depending on if an exception is thrown when it goes out of scope.
- Return type:
Generator
- Example:
>>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>> # Actions inside the transaction will be committed to the undo state upon exit >>> with bv.undoable_transaction(): >>> bv.convert_to_nop(0x100012f1) True >>> bv.get_disassembly(0x100012f1) 'nop' >>> bv.undo() >>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>> # A thrown exception inside the transaction will undo all changes made inside it >>> with bv.undoable_transaction(): >>> bv.convert_to_nop(0x100012f1) # Reverted on thrown exception >>> raise RuntimeError("oh no") RuntimeError: oh no >>> bv.get_disassembly(0x100012f1) 'xor eax, eax'
- unregister_notification(notify: BinaryDataNotification) None[source]¶
unregister_notification unregisters the
BinaryDataNotificationobject passed to register_notification- Parameters:
notify (BinaryDataNotification) – notify is a subclassed instance of
BinaryDataNotification.- Return type:
None
- update_analysis() None[source]¶
update_analysisasynchronously starts the analysis process and returns immediately.Usage: Call
update_analysisafter making changes that could affect the analysis results, such as adding or modifying functions. This ensures that the analysis is updated to reflect the latest changes. The analysis runs in the background, allowing other operations to continue.- Return type:
None
- update_analysis_and_wait() None[source]¶
update_analysis_and_waitstarts the analysis process and blocks until it is complete. This method should be used when it is necessary to ensure that analysis results are fully updated before proceeding with further operations. If an update is already in progress, this method chains a new update request to ensure that the update processes all pending changes before the call was made.Usage: Call
update_analysis_and_waitafter making changes that could affect the analysis results, such as adding or modifying functions, to ensure that the analysis reflects the latest changes. Unlikeupdate_analysis, this method waits for the analysis to finish before returning.Thread Restrictions: - Worker Threads: This function cannot be called from a worker thread. If called from a worker thread, an error will be logged, and the function will return immediately. - UI Threads: This function cannot be called from a UI thread. If called from a UI thread, an error will be logged, and the function will return immediately.
- Return type:
None
- write(addr: int, data: bytes, except_on_relocation: bool = True) int[source]¶
writewrites the bytes indatato the virtual addressaddr.- Parameters:
- Returns:
number of bytes written to virtual address
addr- Return type:
- Example:
>>> bv.read(0,4) b'BBBB' >>> bv.write(0, b"AAAA") 4 >>> bv.read(0,4) b'AAAA'
- writer(address: int | None = None) BinaryWriter[source]¶
- Parameters:
address (int | None) –
- Return type:
- property address_comments: Mapping[int, str]¶
Returns a read-only dict of the address comments attached to this BinaryView
Note that these are different from function-level comments which are specific to each
Function. For annotating code, it is recommended to use comments attached to functions rather than address comments attached to the BinaryView. On the other hand, BinaryView comments can be attached to data whereas function comments cannot.To create a function-level comment, use
set_comment_at.
- property allocated_ranges: List[AddressRange]¶
List of valid address ranges for this view (read-only) Deprecated: 4.1.5902 Use mapped_address_ranges instead.
- property analysis_changed: bool¶
boolean analysis state changed of the currently running analysis (read-only)
- property analysis_info: AnalysisInfo¶
Provides instantaneous analysis state information and a list of current functions under analysis (read-only). All times are given in units of milliseconds (ms). Per-function analysis_time is the aggregation of time spent performing incremental updates and is reset on a full function update. Per-function update_count tracks the current number of incremental updates and is reset on a full function update. Per-function submit_count tracks the current number of full updates that have completed.
Note
submit_count is currently not reset across analysis updates.
- property analysis_is_aborted: bool¶
analysis_is_abortedchecks if the analysis has been aborted.Note
This property is intended for use by architecture plugins only.
- Returns:
True if the analysis has been aborted, False otherwise
- Return type:
- property analysis_progress: AnalysisProgress¶
Status of current analysis (read-only)
- property analysis_state: AnalysisState¶
State of current analysis (read-only)
- property arch: Architecture | None¶
The architecture associated with the current
BinaryView(read/write)
- property associated_type_archive_type_ids: Mapping[str, Tuple[str, str]]¶
Get a list of all types in the analysis that are associated with type archives
- Returns:
Map of all analysis types to their corresponding archive / id
- property associated_type_archive_types: Mapping[QualifiedName, Tuple[TypeArchive | None, str]]¶
Get a list of all types in the analysis that are associated with attached type archives
- Returns:
Map of all analysis types to their corresponding archive / id. If a type is associated with a disconnected type archive, the archive will be None.
- property attached_type_archives: Mapping[str, str]¶
All attached type archive ids and paths (read-only)
- property auto_metadata: Dict[str, metadata.MetadataValueType]¶
metadata retrieves the metadata associated with the current BinaryView.
- Return type:
metadata associated with the BinaryView
- Example:
>>> bv.metadata <metadata: {}>
- property auto_type_container: TypeContainer¶
Type Container for ONLY auto types in the BinaryView. Any changes to types will NOT promote auto types to user types. :return: Auto types only Type Container
- property available_view_types: List[BinaryViewType]¶
Available view types (read-only)
- property backed_address_ranges: List[AddressRange]¶
List of backed address ranges for this view (read-only)
- property basic_blocks: Generator[BasicBlock, None, None]¶
A generator of all BasicBlock objects in the BinaryView
- property connected_type_archives: List[TypeArchive]¶
All connected type archive objects (read-only)
- property data_vars: Mapping[int, DataVariable]¶
List of data variables (read-only)
- property dependency_sorted_types: TypeMapping¶
List of all types, sorted such that types are after all types on which they depend (read-only)
Order is guaranteed for any collection of types with no cycles. If you have cycles in type dependencies, order for types in a cycle is not guaranteed.
Note
Dependency order is based on named type references for all non-structure types, i.e.
struct Foo m_foowill induce a dependency, whereasstruct Foo* m_pFoowill not.- Returns:
sorted types as defined above
- property endianness: Endianness¶
Endianness of the binary (read-only)
- property entry_functions: FunctionList¶
A List of entry functions (read-only) This list contains vanilla entry function, and functions like init_array, fini_array, and TLS callbacks etc. User-added entry functions(via add_entry_point) are also included.
We see entry_functions as good starting points for analysis, these functions normally don’t have internal references. However, note that exported functions in a dll/so file are not included.
Note the difference with entry_function
- property file: FileMetadata¶
FileMetadatabacking the BinaryView
- property functions: FunctionList¶
returns a FunctionList object (read-only)
- property global_pointer_value: RegisterValue¶
Discovered value of the global pointer register, if the binary uses one (read-only)
- property hlil_basic_blocks: Generator[HighLevelILBasicBlock, None, None]¶
A generator of all HighLevelILBasicBlock objects in the BinaryView
- property hlil_instructions: highlevelil.HLILInstructionsType¶
A generator of hlil instructions
- property instructions: Generator[Tuple[List[InstructionTextToken], int], None, None]¶
A generator of instruction tokens and their start addresses
- property length¶
- property linear_disassembly: Iterator[LinearDisassemblyLine]¶
Iterator for all lines in the linear disassembly of the view
- property llil_basic_blocks: Generator[LowLevelILBasicBlock, None, None]¶
A generator of all LowLevelILBasicBlock objects in the BinaryView
- property llil_instructions: lowlevelil.LLILInstructionsType¶
A generator of llil instructions
- property mapped_address_ranges: List[AddressRange]¶
List of mapped address ranges for this view (read-only)
- property max_function_size_for_analysis: int¶
Maximum size of function (sum of basic block sizes in bytes) for auto analysis
- property memory_map¶
memory_mapreturns the MemoryMap object for the current BinaryView. The MemoryMap object is a proxy object that provides a high-level view of the memory map, allowing you to query and manipulate memory regions. This proxy ensures that the memory map always reflects the latest state of the core MemoryMap object in the underlying BinaryView.
- property metadata: Dict[str, metadata.MetadataValueType]¶
metadata retrieves the metadata associated with the current BinaryView.
- Return type:
metadata associated with the BinaryView
- Example:
>>> bv.metadata <metadata: {}>
- property mlil_basic_blocks: Generator[MediumLevelILBasicBlock, None, None]¶
A generator of all MediumLevelILBasicBlock objects in the BinaryView
- property mlil_instructions: Generator[MediumLevelILInstruction, None, None]¶
A generator of mlil instructions
- property new_auto_function_analysis_suppressed: bool¶
Whether or not automatically discovered functions will be analyzed
- property original_base: int¶
Original image base of the binary. Deprecated: 4.1.5902 Use original_image_base instead.
- property parameters_for_analysis¶
- property parent_view: BinaryView | None¶
View that contains the raw data used by this view (read-only)
- property platform: Platform | None¶
The platform associated with the current BinaryView (read/write)
- property project_file: ProjectFile | None¶
- registered_view_type = None¶
- property root_component: Component¶
The root component for the BinaryView (read-only)
This Component cannot be removed, and houses all unparented Components.
- Returns:
The root component
- property session_data¶
Dictionary object where plugins can store arbitrary data associated with the view. This data is ephemeral and not saved to a database. Consider using
store_metadataif permanence is needed.
- property strings: List[StringReference]¶
List of strings (read-only)
- property symbols: SymbolMapping¶
Dict of symbols (read-only) Items in the dict are lists of all symbols matching that name.
- Example:
>>> bv.symbols['_main'] [<FunctionSymbol: "_main" @ 0x1dd0>] >>> list(bv.symbols) ['_start', '_main', '_printf', '_scanf', ...] >>> bv.symbols['foo'] KeyError: "'foo': symbol not found"
- Returns:
a dict-like generator of symbol names and values
- Return type:
Generator[str, None, None]
- property tag_types: Mapping[str, TagType | List[TagType]]¶
tag_typesgets a dictionary of all Tag Types present for the view, structured as {Tag Type Name => Tag Type}.
- property tags: List[Tuple[int, Tag]]¶
tagsgets a list of all dataTagobjects in the view. Tags are returned as a list of (address,Tag) pairs.
- property tags_for_address: List[Tuple[int, Tag]]¶
tags_for_addressfetches all address-specific tags.
- property tags_for_function: List[Tuple[int, Tag]]¶
tags_for_functionfetches all function-specific tags.
- property type_archive_type_names: Mapping[QualifiedName, List[Tuple[TypeArchive, str]]]¶
Get a list of all available type names in all connected archives, and their archive/type id pair
- Returns:
name <-> [(archive, archive type id)] for all type names
- property type_container: TypeContainer¶
Type Container for all types (user and auto) in the BinaryView. Any auto types modified through the Type Container will be converted into user types. :return: Full view Type Container
- property type_libraries: List[TypeLibrary]¶
List of imported type libraries (read-only)
- property type_names: List[QualifiedName]¶
List of defined type names (read-only)
- property types: TypeMapping¶
- property user_global_pointer_value_set: bool¶
Check whether a user global pointer value has been set
- property user_type_container: TypeContainer¶
Type Container for ONLY user types in the BinaryView. :return: User types only Type Container
BinaryViewEvent¶
- class BinaryViewEvent[source]¶
Bases:
objectThe
BinaryViewEventobject provides a mechanism for receiving callbacks when a BinaryView is Finalized or the initial analysis is finished. The BinaryView finalized callbacks run before the initial analysis starts. The callbacks run one-after-another in the same order as they get registered. It is a good place to modify the BinaryView to add extra information to it.For newly opened binaries, the initial analysis completion callbacks run after the initial analysis, as well as linear sweep and signature matcher (if they are configured to run), completed. For loading old databases, the callbacks run after the database is loaded, as well as any automatic analysis update finishes.
The callback function receives a BinaryView as its parameter. It is possible to call BinaryView.add_analysis_completion_event() on it to set up other callbacks for analysis completion.
- Example:
>>> def callback(bv): ... print('start: 0x%x' % bv.start) ... >>> BinaryViewType.add_binaryview_finalized_event(callback)
- classmethod register(event_type: BinaryViewEventType, callback: Callable[[BinaryView], None]) None[source]¶
- Parameters:
event_type (BinaryViewEventType) –
callback (Callable[[BinaryView], None]) –
- Return type:
None
- BinaryViewEventCallback¶
alias of
Callable[[BinaryView],None]
BinaryViewType¶
- class BinaryViewType[source]¶
Bases:
objectThe
BinaryViewTypeobject is used internally and should not be directly instantiated.- static add_binaryview_finalized_event(callback: Callable[[BinaryView], None]) None[source]¶
add_binaryview_finalized_event adds a callback that gets executed when new binaryview is finalized. For more details, please refer to the documentation of BinaryViewEvent.
Warning
The callback provided must stay in scope for the lifetime of the process, deletion or garbage collection of the callback will result in a crash.
- Parameters:
callback (Callable[[BinaryView], None]) –
- Return type:
None
- static add_binaryview_initial_analysis_completion_event(callback: Callable[[BinaryView], None]) None[source]¶
add_binaryview_initial_analysis_completion_event adds a callback that gets executed after the initial analysis, as well as linear sweep and signature matcher (if they are configured to run) completed. For more details, please refer to the documentation of BinaryViewEvent.
Warning
The callback provided must stay in scope for the lifetime of the process, deletion or garbage collection of the callback will result in a crash.
- Parameters:
callback (Callable[[BinaryView], None]) –
- Return type:
None
- create(data: BinaryView) BinaryView | None[source]¶
- Parameters:
data (BinaryView) –
- Return type:
BinaryView | None
- get_arch(ident: int, endian: Endianness) Architecture | None[source]¶
- Parameters:
ident (int) –
endian (Endianness) –
- Return type:
Architecture | None
- get_load_settings_for_data(data: BinaryView) Settings | None[source]¶
- Parameters:
data (BinaryView) –
- Return type:
Settings | None
- get_platform(ident: int, arch: Architecture) Platform | None[source]¶
- Parameters:
ident (int) –
arch (Architecture) –
- Return type:
Platform | None
- is_valid_for_data(data: BinaryView) bool[source]¶
- Parameters:
data (BinaryView) –
- Return type:
- open(src: str | PathLike, file_metadata: FileMetadata | None = None) BinaryView | None[source]¶
- Parameters:
file_metadata (FileMetadata | None) –
- Return type:
BinaryView | None
- parse(data: BinaryView) BinaryView | None[source]¶
- Parameters:
data (BinaryView) –
- Return type:
BinaryView | None
- recognize_platform(ident, endian: Endianness, view: BinaryView, metadata)[source]¶
- Parameters:
endian (Endianness) –
view (BinaryView) –
- register_arch(ident: int, endian: Endianness, arch: Architecture) None[source]¶
- Parameters:
ident (int) –
endian (Endianness) –
arch (Architecture) –
- Return type:
None
- register_default_platform(arch: Architecture, plat: Platform) None[source]¶
- Parameters:
arch (Architecture) –
plat (Platform) –
- Return type:
None
- register_platform(ident: int, arch: Architecture, plat: Platform) None[source]¶
- Parameters:
ident (int) –
arch (Architecture) –
plat (Platform) –
- Return type:
None
BinaryWriter¶
- class BinaryWriter[source]¶
Bases:
objectclass BinaryWriteris a convenience class for writing binary data.BinaryWriter can be instantiated as follows and the rest of the document will start from this context
>>> from binaryninja import * >>> bv = load("/bin/ls") >>> br = BinaryReader(bv) >>> br.offset 4294967296 >>> bw = BinaryWriter(bv) >>>
Or using the optional endian parameter
>>> from binaryninja import * >>> bv = load("/bin/ls") >>> br = BinaryReader(bv, Endianness.BigEndian) >>> bw = BinaryWriter(bv, Endianness.BigEndian) >>>
- __init__(view: BinaryView, endian: Endianness | None = None, address: int | None = None)[source]¶
- Parameters:
view (BinaryView) –
endian (Endianness | None) –
address (int | None) –
- seek(offset: int) None[source]¶
seekupdate internal offset tooffset.- Parameters:
offset (int) – offset to set the internal offset to
- Return type:
None
- Example:
>>> hex(bw.offset) '0x100000008L' >>> bw.seek(0x100000000) >>> hex(bw.offset) '0x100000000L' >>>
- seek_relative(offset: int) None[source]¶
seek_relativeupdates the internal offset byoffset.- Parameters:
offset (int) – offset to add to the internal offset
- Return type:
None
- Example:
>>> hex(bw.offset) '0x100000008L' >>> bw.seek_relative(-8) >>> hex(bw.offset) '0x100000000L' >>>
- write(value: bytes, address: int | None = None, except_on_relocation=True) bool[source]¶
writewriteslen(value)bytes to the internal offset, without regard to endianness.- Parameters:
- Returns:
boolean True on success, False on failure.
- Return type:
- Example:
>>> bw.write("AAAA") True >>> br.read(4) 'AAAA' >>>
- write16(value: int, address: int | None = None, except_on_relocation=True) bool[source]¶
write16writes the lowest order two bytes from the integervalueto the current offset, using internal endianness.
- write16be(value: int, address: int | None = None, except_on_relocation=True) bool[source]¶
write16bewrites the lowest order two bytes from the big endian integervalueto the current offset.
- write16le(value: int, address: int | None = None, except_on_relocation=True) bool[source]¶
write16lewrites the lowest order two bytes from the little endian integervalueto the current offset.
- write32(value: int, address: int | None = None, except_on_relocation=True) bool[source]¶
write32writes the lowest order four bytes from the integervalueto the current offset, using internal endianness.
- write32be(value: int, address: int | None = None, except_on_relocation=True) bool[source]¶
write32bewrites the lowest order four bytes from the big endian integervalueto the current offset.
- write32le(value: int, address: int | None = None, except_on_relocation=True) bool[source]¶
write32lewrites the lowest order four bytes from the little endian integervalueto the current offset.
- write64(value: int, address: int | None = None, except_on_relocation=True) bool[source]¶
write64writes the lowest order eight bytes from the integervalueto the current offset, using internal endianness.
- write64be(value: int, address: int | None = None, except_on_relocation=True) bool[source]¶
write64bewrites the lowest order eight bytes from the big endian integervalueto the current offset.
- write64le(value: int, address: int | None = None, except_on_relocation=True) bool[source]¶
write64lewrites the lowest order eight bytes from the little endian integervalueto the current offset.
- write8(value: int, address: int | None = None, except_on_relocation=True) bool[source]¶
write8lowest order byte from the integervalueto the current offset.- Parameters:
- Returns:
boolean
- Return type:
- Example:
>>> bw.write8(0x42) True >>> br.read(1) 'B' >>>
- property endianness: Endianness¶
The Endianness to written data. (read/write)
- Getter:
returns the endianness of the reader
- Setter:
sets the endianness of the reader (BigEndian or LittleEndian)
- Type:
CoreDataVariable¶
DataVariable¶
- class DataVariable[source]¶
Bases:
CoreDataVariable- __init__(view: BinaryView, address: int, type: Type, auto_discovered: bool)[source]¶
- Parameters:
view (BinaryView) –
address (int) –
type (Type) –
auto_discovered (bool) –
- classmethod from_core_struct(var: BNDataVariable, view: BinaryView) DataVariable[source]¶
- Parameters:
var (BNDataVariable) –
view (BinaryView) –
- Return type:
- property code_refs: Generator[ReferenceSource, None, None]¶
code references to this data variable (read-only)
- property data_refs: Generator[int, None, None] | None¶
data cross references to this data variable (read-only)
- property data_refs_from: Generator[int, None, None] | None¶
data cross references from this data variable (read-only)
- property symbol: CoreSymbol | None¶
DataVariableAndName¶
FunctionList¶
- class FunctionList[source]¶
Bases:
object- __init__(view: BinaryView)[source]¶
- Parameters:
view (BinaryView) –
MemoryMap¶
- class MemoryMap[source]¶
Bases:
objectThe MemoryMap object is used to describe a system level MemoryMap for which a BinaryView is loaded into. A loaded BinaryView has a view into the MemoryMap which is described by the Segments defined in that BinaryView. The MemoryMap object allows for the addition of multiple, arbitrary overlapping regions of memory. Segmenting of the address space is automatically handled when the MemoryMap is modified and in the case where a portion of the system address space has multiple defined regions, the default ordering gives priority to the most recently added region. This feature is experimental and under active development.
- Example:
>>> base = 0x10000 >>> rom_base = 0xc0000000 >>> segments = SegmentDescriptorList(base) >>> segments.append(start=base, length=0x1000, data_offset=0, data_length=0x1000, flags=SegmentFlag.SegmentReadable|SegmentFlag.SegmentExecutable) >>> segments.append(start=rom_base, length=0x1000, flags=SegmentFlag.SegmentReadable) >>> view = load(bytes.fromhex('5054ebfe'), options={'loader.imageBase': base, 'loader.platform': 'x86', 'loader.segments': json.dumps(segments)}) >>> view.memory_map <region: 0x10000 - 0x10004> size: 0x4 objects: 'origin<Mapped>@0x0' | Mapped<Absolute> | <r-x> <region: 0xc0000000 - 0xc0001000> size: 0x1000 objects: 'origin<Mapped>@0xbfff0000' | Unmapped | <r--> | FILL<0x0> <region: 0xc0001000 - 0xc0001014> size: 0x14 objects: 'origin<Mapped>@0xbfff1000' | Unmapped | <---> | FILL<0x0> >>> view.memory_map.add_memory_region("rom", rom_base, b'\x90' * 4096, SegmentFlag.SegmentReadable | SegmentFlag.SegmentExecutable) True >>> view.memory_map <region: 0x10000 - 0x10004> size: 0x4 objects: 'origin<Mapped>@0x0' | Mapped<Absolute> | <r-x> <region: 0xc0000000 - 0xc0001000> size: 0x1000 objects: 'rom' | Mapped<Relative> | <r-x> 'origin<Mapped>@0xbfff0000' | Unmapped | <r--> | FILL<0x0> <region: 0xc0001000 - 0xc0001014> size: 0x14 objects: 'origin<Mapped>@0xbfff1000' | Unmapped | <---> | FILL<0x0> >>> view.read(rom_base, 16) b'\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90' >>> view.memory_map.add_memory_region("pad", rom_base, b'\xa5' * 8) True >>> view.read(rom_base, 16) b'\xa5\xa5\xa5\xa5\xa5\xa5\xa5\xa5\x90\x90\x90\x90\x90\x90\x90\x90' >>> view.memory_map <region: 0x10000 - 0x10004> size: 0x4 objects: 'origin<Mapped>@0x0' | Mapped<Absolute> | <r-x> <region: 0xc0000000 - 0xc0000008> size: 0x8 objects: 'pad' | Mapped<Relative> | <---> 'rom' | Mapped<Relative> | <r-x> 'origin<Mapped>@0xbfff0000' | Unmapped | <r--> | FILL<0x0> <region: 0xc0000008 - 0xc0001000> size: 0xff8 objects: 'rom' | Mapped<Relative> | <r-x> 'origin<Mapped>@0xbfff0000' | Unmapped | <r--> | FILL<0x0> <region: 0xc0001000 - 0xc0001014> size: 0x14 objects: 'origin<Mapped>@0xbfff1000' | Unmapped | <---> | FILL<0x0>
- __init__(handle: BinaryView)[source]¶
- Parameters:
handle (BinaryView) –
- add_memory_region(name: str, start: int, source: PathLike | str | bytes | bytearray | BinaryView | DataBuffer | FileAccessor | None = None, flags: SegmentFlag = 0, fill: int = 0, length: int | None = None) bool[source]¶
Adds a memory region to the memory map. Depending on the source parameter, the memory region is created as one of the following types:
BinaryMemoryRegion (*Unimplemented*): Represents a memory region loaded from a binary format.
DataMemoryRegion: Region backed by flat file or raw data (str, bytes, DataBuffer).
RemoteMemoryRegion: Ephemeral memory region via FileAccessor.
UnbackedMemoryRegion: Region not backed by any data source (requires length to be set).
The source parameter determines the type: - os.PathLike or str: File path to be loaded into memory as a DataMemoryRegion. - bytes or bytearray: Directly loaded into memory as a DataMemoryRegion. - databuffer.DataBuffer: Loaded as a DataMemoryRegion. - fileaccessor.FileAccessor: Remote proxy source. - BinaryView: (Reserved for future). - None: Creates an unbacked memory region (must specify length).
Note
If no flags are specified and the new memory region overlaps with one or more existing regions, the overlapping portions of the new region will inherit the flags of the respective underlying regions.
- Parameters:
name (str): A unique name for the memory region. start (int): Starting address. source (Optional[Union[os.PathLike, str, bytes, bytearray, BinaryView, databuffer.DataBuffer, fileaccessor.FileAccessor]]): Source of data or None for unbacked. length (Optional[int]): Required if source is None (unbacked). flags (SegmentFlag): Flags to apply to the memory region. Defaults to 0 (no flags). fill (int): Fill byte for unbacked regions. Defaults to 0.
- Returns:
bool: True if the memory region was successfully added, False otherwise.
- Raises:
NotImplementedError: If source type is unsupported. ValueError: If source is None and length is not specified.
- Parameters:
name (str) –
start (int) –
source (PathLike | str | bytes | bytearray | BinaryView | DataBuffer | FileAccessor | None) –
flags (SegmentFlag) –
fill (int) –
length (int | None) –
- Return type:
- set_logical_memory_map_enabled(enabled: bool) None[source]¶
Enable or disable the logical memory map.
When enabled, the memory map will present a simplified, logical view that merges and abstracts virtual memory regions based on criteria such as contiguity and flag consistency. This view is designed to provide a higher-level representation for user analysis, hiding underlying mapping details.
When disabled, the memory map will revert to displaying the virtual view, which corresponds directly to the individual segments mapped from the raw file without any merging or abstraction.
- Parameters:
enabled (bool) – True to enable the logical view, False to revert to the virtual view.
- Return type:
None
- set_memory_region_flags(name: str, flags: SegmentFlag) bool[source]¶
- Parameters:
name (str) –
flags (SegmentFlag) –
- Return type:
- property base¶
Formatted string of the base memory map, consisting of unresolved auto and user segments (read-only).
- property is_activated¶
Whether the memory map is activated for the associated view.
ReferenceSource¶
- class ReferenceSource[source]¶
Bases:
objectReferenceSource(function: Optional[ForwardRef(‘_function.Function’)], arch: Optional[ForwardRef(‘architecture.Architecture’)], address: int)
- __init__(function: Function | None, arch: Architecture | None, address: int) None¶
- Parameters:
function (Function | None) –
arch (Architecture | None) –
address (int) –
- Return type:
None
- arch: Architecture | None¶
- property hlil: HighLevelILInstruction | None¶
Returns the high level il instruction at the current location if one exists
- property hlils: Iterator[HighLevelILInstruction]¶
Returns the high level il instructions at the current location if any exists
- property llil: LowLevelILInstruction | None¶
Returns the low level il instruction at the current location if one exists
- property llils: Iterator[LowLevelILInstruction]¶
Returns the low level il instructions at the current location if any exists
- property mlil: MediumLevelILInstruction | None¶
Returns the medium level il instruction at the current location if one exists
- property mlils: Iterator[MediumLevelILInstruction]¶
Returns the medium level il instructions at the current location if any exists
Relocation¶
- class Relocation[source]¶
Bases:
object- property arch: Architecture | None¶
The architecture associated with the
Relocation(read/write)
- property info: RelocationInfo¶
- property symbol: CoreSymbol | None¶
RelocationInfo¶
- class RelocationInfo[source]¶
Bases:
objectRelocationInfo(info: binaryninja._binaryninjacore.BNRelocationInfo)
- type: RelocationType¶
Section¶
- class Section[source]¶
Bases:
objectThe
Sectionobject is returned during BinaryView creation and should not be directly instantiated.- classmethod serialize(image_base: int, name: str, start: int, length: int, semantics: SectionSemantics = SectionSemantics.DefaultSectionSemantics, type: str = '', align: int = 1, entry_size: int = 0, link: str = '', info_section: str = '', info_data: int = 0, auto_defined: bool = True, sections: str = '[]')[source]¶
Serialize section parameters into a JSON string. This is useful for generating a properly formatted section description as options when using load.
- Parameters:
image_base (int) – The base address of the image.
name (str) – The name of the section.
start (int) – The start address of the section.
length (int) – The length of the section.
semantics (SectionSemantics) – The semantics of the section.
type (str) – The type of the section.
align (int) – The alignment of the section.
entry_size (int) – The entry size of the section.
link (str) – The linked section of the section.
info_section (str) – The info section of the section.
info_data (int) – The info data of the section.
auto_defined (bool) – Whether the section is auto-defined.
sections (str) – An optional, existing array of sections to append to.
- Returns:
A JSON string representing the section.
- Return type:
Deprecated since version 4.3.6653: Use SectionDescriptorList instead.
- property length¶
- property semantics: SectionSemantics¶
SectionDescriptorList¶
- class SectionDescriptorList[source]¶
Bases:
list- __init__(image_base: int)[source]¶
Initialize the SectionDescriptorList with a base image address.
- Parameters:
image_base (int) – The base address of the image.
- append(name: str, start: int, length: int, semantics: SectionSemantics = SectionSemantics.DefaultSectionSemantics, type: str = '', align: int = 1, entry_size: int = 0, link: str = '', info_section: str = '', info_data: int = 0, auto_defined: bool = True)[source]¶
Append a section descriptor to the list.
- Parameters:
name (str) – The name of the section.
start (int) – The start address of the section.
length (int) – The length of the section.
semantics (SectionSemantics) – The semantics of the section.
type (str) – The type of the section.
align (int) – The alignment of the section.
entry_size (int) – The size of each entry in the section.
link (str) – An optional link field.
info_section (str) – An optional info_section field.
info_data (int) – An optional info_data field.
auto_defined (bool) – Whether the section is auto-defined.
Segment¶
- class Segment[source]¶
Bases:
objectThe
Segmentobject is returned during BinaryView creation and should not be directly instantiated.- classmethod serialize(image_base: int, start: int, length: int, data_offset: int = 0, data_length: int = 0, flags: SegmentFlag = SegmentFlag.SegmentReadable, auto_defined=True, segments: str = '[]')[source]¶
Serialize segment parameters into a JSON string. This is useful for generating a properly formatted segment description as options when using load.
- Parameters:
image_base (int) – The base address of the image.
start (int) – The start address of the segment.
length (int) – The length of the segment.
data_offset (int) – The offset of the data within the segment.
data_length (int) – The length of the data within the segment.
flags (SegmentFlag) – The flags of the segment.
auto_defined (bool) – Whether the segment is auto-defined.
segments (str) – An optional, existing array of segments to append to.
- Returns:
A JSON string representing the segment.
- Return type:
- Example::
>>> base = 0x400000 >>> rom_base = 0xffff0000 >>> segments = SegmentDescriptorList(base) >>> segments.append(start=base, length=0x1000, data_offset=0, data_length=0x1000, flags=SegmentFlag.SegmentReadable|SegmentFlag.SegmentExecutable) >>> segments.append(start=rom_base, length=0x1000, flags=SegmentFlag.SegmentReadable) >>> view = load(bytes.fromhex('5054ebfe'), options={'loader.imageBase': base, 'loader.platform': 'x86', 'loader.segments': json.dumps(segments)})
Deprecated since version 4.3.6653: Use SegmentDescriptorList instead.
- property length¶
SegmentDescriptorList¶
- class SegmentDescriptorList[source]¶
Bases:
list- __init__(image_base: int)[source]¶
Initialize the SegmentDescriptorList with a base image address.
- Parameters:
image_base (int) – The base address of the image.
- append(start: int, length: int, data_offset: int = 0, data_length: int = 0, flags: SegmentFlag = SegmentFlag.SegmentReadable, auto_defined: bool = True)[source]¶
Append a segment descriptor to the list.
- Parameters:
start (int) – The start address of the segment.
length (int) – The length of the segment.
data_offset (int) – The offset of the data within the segment.
data_length (int) – The length of the data within the segment.
flags (SegmentFlag) – The flags of the segment.
auto_defined (bool) – Whether the segment is auto-defined.
StringReference¶
- class StringReference[source]¶
Bases:
object- __init__(bv: BinaryView, string_type: StringType, start: int, length: int)[source]¶
- Parameters:
bv (BinaryView) –
string_type (StringType) –
start (int) –
length (int) –
- property type: StringType¶
- property view: BinaryView¶
StructuredDataValue¶
SymbolMapping¶
- class SymbolMapping[source]¶
Bases:
MappingSymbolMapping object is used to improve performance of the bv.symbols API. This allows pythonic code like this to have reasonable performance characteristics
>>> my_symbols = get_my_symbols() >>> for symbol in my_symbols: >>> if bv.symbols[symbol].address == 0x41414141: >>> print("Found")
- __init__(view: BinaryView)[source]¶
- Parameters:
view (BinaryView) –
- get(k[, d]) D[k] if k in D, else d. d defaults to None.[source]¶
- Parameters:
key (str) –
default (List[CoreSymbol] | None) –
- Return type:
List[CoreSymbol] | None
Tag¶
TagType¶
- class TagType[source]¶
Bases:
objectThe
TagTypeobject is created by the create_tag_type API and should not be directly instantiated.- property type: TagTypeType¶
Type from enums.TagTypeType
TypeMapping¶
- class TypeMapping[source]¶
Bases:
MappingTypeMapping object is used to improve performance of the bv.types API. This allows pythonic code like this to have reasonable performance characteristics
>>> my_types = get_my_types() >>> for type_name in my_types: >>> if bv.types[type_name].width == 4: >>> print("Found")
- __init__(view: ~binaryninja.binaryview.BinaryView, get_list_fn=<function BNGetAnalysisTypeList>)[source]¶
- Parameters:
view (BinaryView) –
TypedDataAccessor¶
- class TypedDataAccessor[source]¶
Bases:
objectTypedDataAccessor(type: ‘_types.Type’, address: int, view: ‘BinaryView’, endian: binaryninja.enums.Endianness)
- __init__(type: Type, address: int, view: BinaryView, endian: Endianness) None¶
- Parameters:
type (Type) –
address (int) –
view (BinaryView) –
endian (Endianness) –
- Return type:
None
- as_uuid(ms_format: bool = True) UUID[source]¶
Converts the object to a UUID object using Microsoft byte ordering.
- Parameters:
ms_format (bool) – Flag indicating whether to use Microsoft byte ordering. Default is True.
- Returns:
The UUID object representing the byte array.
- Return type:
- Raises:
ValueError – If the byte array representation of this data is not exactly 16 bytes long.
- static int_from_bytes(data: bytes, width: int, sign: bool, endian: Endianness | None = None) int[source]¶
- Parameters:
data (bytes) –
width (int) –
sign (bool) –
endian (Endianness | None) –
- Return type:
- endian: Endianness¶
- view: BinaryView¶
TypedDataReader¶
- TypedDataReader¶
alias of
TypedDataAccessor