summaryrefslogtreecommitdiff
path: root/python
diff options
context:
space:
mode:
authorKyleMiles <krm504@nyu.edu>2022-01-27 22:43:28 -0500
committerKyleMiles <krm504@nyu.edu>2022-01-28 00:24:06 -0500
commit6812c973c9fa9b4ad642ab81856c05f87bd6fcc4 (patch)
treedace4156d03148bcaf02df138ab4e0d93e61bc6f /python
parent519c9db22367f2659d1a54599fab47e6313be06e (diff)
Format All Files
Diffstat (limited to 'python')
-rw-r--r--python/__init__.py32
-rw-r--r--python/architecture.py515
-rw-r--r--python/associateddatastore.py9
-rw-r--r--python/basicblock.py60
-rw-r--r--python/binaryview.py1360
-rw-r--r--python/bncompleter.py20
-rw-r--r--python/callingconvention.py119
-rw-r--r--python/commonil.py5
-rw-r--r--python/compatibility.py3
-rw-r--r--python/database.py512
-rw-r--r--python/databuffer.py14
-rw-r--r--python/dataclasses.py1392
-rw-r--r--python/datarender.py19
-rw-r--r--python/debuginfo.py84
-rw-r--r--python/decorators.py1
-rw-r--r--python/demangle.py40
-rw-r--r--python/downloadprovider.py43
-rw-r--r--python/enterprise.py6
-rw-r--r--python/examples/angr_plugin.py27
-rw-r--r--python/examples/arch_hook.py17
-rw-r--r--python/examples/asm_to_llil_view.py15
-rw-r--r--python/examples/breakpoint.py8
-rwxr-xr-xpython/examples/cli_dis.py5
-rwxr-xr-xpython/examples/cli_lift.py21
-rwxr-xr-xpython/examples/debug_info.py151
-rwxr-xr-xpython/examples/export_svg.py343
-rw-r--r--python/examples/helloglobalarea.py2
-rw-r--r--python/examples/hellopane.py7
-rw-r--r--python/examples/hellosidebar.py3
-rw-r--r--python/examples/instruction_iterator.py3
-rw-r--r--python/examples/jump_table.py6
-rw-r--r--python/examples/linear_mlil.py47
-rw-r--r--python/examples/mappedview.py27
-rw-r--r--python/examples/nds.py134
-rw-r--r--python/examples/nes.py552
-rw-r--r--python/examples/notification_callbacks.py2
-rw-r--r--python/examples/nsf.py9
-rwxr-xr-xpython/examples/pe_stat.py7
-rw-r--r--python/examples/print_syscalls.py4
-rwxr-xr-xpython/examples/typelib_create.py29
-rwxr-xr-xpython/examples/typelib_dump.py173
-rw-r--r--python/examples/ui_notifications.py102
-rw-r--r--python/fileaccessor.py3
-rw-r--r--python/filemetadata.py99
-rw-r--r--python/flowgraph.py58
-rw-r--r--python/function.py814
-rw-r--r--python/functionrecognizer.py16
-rw-r--r--python/generator.cpp129
-rw-r--r--python/highlevelil.py830
-rw-r--r--python/highlight.py15
-rw-r--r--python/interaction.py84
-rw-r--r--python/lineardisassembly.py117
-rw-r--r--python/log.py4
-rw-r--r--python/lowlevelil.py1420
-rw-r--r--python/mediumlevelil.py1093
-rw-r--r--python/metadata.py9
-rw-r--r--python/platform.py73
-rw-r--r--python/plugin.py337
-rw-r--r--python/pluginmanager.py7
-rw-r--r--python/scriptingprovider.py164
-rw-r--r--python/settings.py50
-rw-r--r--python/transform.py18
-rw-r--r--python/typelibrary.py5
-rw-r--r--python/types.py900
-rw-r--r--python/update.py11
-rw-r--r--python/variable.py192
-rw-r--r--python/websocketprovider.py19
-rw-r--r--python/workflow.py55
68 files changed, 6838 insertions, 5612 deletions
diff --git a/python/__init__.py b/python/__init__.py
index 9f193bea..b973118a 100644
--- a/python/__init__.py
+++ b/python/__init__.py
@@ -18,7 +18,6 @@
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
-
import atexit
import sys
import ctypes
@@ -26,7 +25,6 @@ from time import gmtime, struct_time
import os
from typing import Mapping, Optional
-
# Binary Ninja components
import binaryninja._binaryninjacore as core
import binaryninja
@@ -68,9 +66,10 @@ from .commonil import *
from .database import *
# We import each of these by name to prevent conflicts between
# log.py and the function 'log' which we don't import below
-from .log import (redirect_output_to_log, is_output_redirected_to_log,
- log_debug, log_info, log_warn, log_error, log_alert,
- log_to_stdout, log_to_stderr, log_to_file, close_logs)
+from .log import (
+ redirect_output_to_log, is_output_redirected_to_log, log_debug, log_info, log_warn, log_error, log_alert,
+ log_to_stdout, log_to_stderr, log_to_file, close_logs
+)
from .log import log as log_at_level
# Only load Enterprise Client support on Enterprise builds
if core.BNGetProduct() == "Binary Ninja Enterprise Client":
@@ -136,15 +135,17 @@ def _init_plugins():
pass
if not core.BNIsLicenseValidated() or not enterprise.is_license_still_activated():
raise RuntimeError(
- "To use Binary Ninja Enterprise from a headless python script, you must check out a license first.\n"
- "You can either check out a license for an extended time with the UI, or use the binaryninja.enterprise module.")
+ "To use Binary Ninja Enterprise from a headless python script, you must check out a license first.\n"
+ "You can either check out a license for an extended time with the UI, or use the binaryninja.enterprise module."
+ )
if not _plugin_init:
# The first call to BNInitCorePlugins returns True for successful initialization and True in this context indicates headless operation.
# The result is pulled from BNInitPlugins as that now wraps BNInitCorePlugins.
is_headless_init_once = core.BNInitPlugins(not os.environ.get('BN_DISABLE_USER_PLUGINS'))
min_level = Settings().get_string("python.log.minLevel")
- if _enable_default_log and is_headless_init_once and min_level in LogLevel.__members__ and not core_ui_enabled() and sys.stderr.isatty():
+ if _enable_default_log and is_headless_init_once and min_level in LogLevel.__members__ and not core_ui_enabled(
+ ) and sys.stderr.isatty():
log_to_stderr(LogLevel[min_level])
core.BNInitRepoPlugins()
if core.BNIsLicenseValidated():
@@ -162,6 +163,7 @@ def disable_default_log() -> None:
_enable_default_log = False
close_logs()
+
def bundled_plugin_path() -> Optional[str]:
"""
``bundled_plugin_path`` returns a string containing the current plugin path inside the `install path <https://docs.binary.ninja/getting-started.html#binary-path>`_
@@ -171,6 +173,7 @@ def bundled_plugin_path() -> Optional[str]:
"""
return core.BNGetBundledPluginDirectory()
+
def user_plugin_path() -> Optional[str]:
"""
``user_plugin_path`` returns a string containing the current plugin path inside the `user directory <https://docs.binary.ninja/getting-started.html#user-folder>`_
@@ -180,6 +183,7 @@ def user_plugin_path() -> Optional[str]:
"""
return core.BNGetUserPluginDirectory()
+
def user_directory() -> Optional[str]:
"""
``user_directory`` returns a string containing the path to the `user directory <https://docs.binary.ninja/getting-started.html#user-folder>`_
@@ -189,6 +193,7 @@ def user_directory() -> Optional[str]:
"""
return core.BNGetUserDirectory()
+
def core_version() -> Optional[str]:
"""
``core_version`` returns a string containing the current version
@@ -198,6 +203,7 @@ def core_version() -> Optional[str]:
"""
return core.BNGetVersionString()
+
def core_build_id() -> int:
"""
``core_build_id`` returns a integer containing the current build id
@@ -207,6 +213,7 @@ def core_build_id() -> int:
"""
return core.BNGetBuildId()
+
def core_serial() -> Optional[str]:
"""
``core_serial`` returns a string containing the current serial number
@@ -216,28 +223,33 @@ def core_serial() -> Optional[str]:
"""
return core.BNGetSerialNumber()
+
def core_expires() -> struct_time:
'''License Expiration'''
return gmtime(core.BNGetLicenseExpirationTime())
+
def core_product() -> Optional[str]:
'''Product string from the license file'''
return core.BNGetProduct()
+
def core_product_type() -> Optional[str]:
'''Product type from the license file'''
return core.BNGetProductType()
+
def core_license_count() -> int:
'''License count from the license file'''
return core.BNGetLicenseCount()
+
def core_ui_enabled() -> bool:
'''Indicates that a UI exists and the UI has invoked BNInitUI'''
return core.BNIsUIEnabled()
-def core_set_license(licenseData:str) -> None:
+def core_set_license(licenseData: str) -> None:
'''
``core_set_license`` is used to initialize the core with a license file that doesn't necessarily reside on a file system. This is especially useful for headless environments such as docker where loading the license file via an environment variable allows for greater security of the license file itself.
@@ -294,7 +306,7 @@ def connect_pycharm_debugger(port=5678):
# Get pip install string from PyCharm's Python Debug Server Configuration
# e.g. for PyCharm 2021.1.1 #PY-7142.13:
# pip install --user pydevd-pycharm~=211.7142.13
- import pydevd_pycharm # type: ignore
+ import pydevd_pycharm # type: ignore
pydevd_pycharm.settrace('localhost', port=port, stdoutToServer=True, stderrToServer=True, suspend=False)
diff --git a/python/architecture.py b/python/architecture.py
index fd9e28f1..ff598a35 100644
--- a/python/architecture.py
+++ b/python/architecture.py
@@ -26,9 +26,10 @@ from dataclasses import dataclass, field
# Binary Ninja components
import binaryninja
from . import _binaryninjacore as core
-from .enums import (Endianness, ImplicitRegisterExtend, BranchType,
- LowLevelILFlagCondition, FlagRole, LowLevelILOperation,
- InstructionTextTokenType, InstructionTextTokenContext)
+from .enums import (
+ Endianness, ImplicitRegisterExtend, BranchType, LowLevelILFlagCondition, FlagRole, LowLevelILOperation,
+ InstructionTextTokenType, InstructionTextTokenContext
+)
from .log import log_error
from . import lowlevelil
from . import types
@@ -65,11 +66,11 @@ IntrinsicType = Union[IntrinsicName, 'lowlevelil.ILIntrinsic', IntrinsicIndex]
@dataclass(frozen=True)
class RegisterInfo:
- full_width_reg:RegisterName
- size:int
- offset:int = 0
- extend:ImplicitRegisterExtend = ImplicitRegisterExtend.NoExtend
- index:Optional[RegisterIndex] = None
+ full_width_reg: RegisterName
+ size: int
+ offset: int = 0
+ extend: ImplicitRegisterExtend = ImplicitRegisterExtend.NoExtend
+ index: Optional[RegisterIndex] = None
def __repr__(self):
if self.extend == ImplicitRegisterExtend.ZeroExtendToFullWidth:
@@ -83,10 +84,10 @@ class RegisterInfo:
@dataclass(frozen=True)
class RegisterStackInfo:
- storage_regs:List[RegisterName]
- top_relative_regs:List[RegisterName]
- stack_top_reg:RegisterName
- index:Optional[RegisterStackIndex] = None
+ storage_regs: List[RegisterName]
+ top_relative_regs: List[RegisterName]
+ stack_top_reg: RegisterName
+ index: Optional[RegisterStackIndex] = None
def __repr__(self):
return f"<reg stack: {len(self.storage_regs)} regs, stack top in {self.stack_top_reg}>"
@@ -94,8 +95,8 @@ class RegisterStackInfo:
@dataclass(frozen=True)
class IntrinsicInput:
- type:'types.Type'
- name:str = ""
+ type: 'types.Type'
+ name: str = ""
def __repr__(self):
if len(self.name) == 0:
@@ -105,9 +106,9 @@ class IntrinsicInput:
@dataclass(frozen=True)
class IntrinsicInfo:
- inputs:List[IntrinsicInput]
- outputs:List['types.Type']
- index:Optional[int] = None
+ inputs: List[IntrinsicInput]
+ outputs: List['types.Type']
+ index: Optional[int] = None
def __repr__(self):
return f"<intrinsic: {repr(self.inputs)} -> {repr(self.outputs)}>"
@@ -115,9 +116,9 @@ class IntrinsicInfo:
@dataclass(frozen=True)
class InstructionBranch:
- type:BranchType
- target:int
- arch:Optional['Architecture']
+ type: BranchType
+ target: int
+ arch: Optional['Architecture']
def __repr__(self):
if self.arch is not None:
@@ -127,12 +128,12 @@ class InstructionBranch:
@dataclass(frozen=False)
class InstructionInfo:
- length:int = 0
- arch_transition_by_target_addr:bool = False
- branch_delay:bool = False
- branches:List[InstructionBranch] = field(default_factory=list)
+ length: int = 0
+ arch_transition_by_target_addr: bool = False
+ branch_delay: bool = False
+ branches: List[InstructionBranch] = field(default_factory=list)
- def add_branch(self, branch_type:BranchType, target:int = 0, arch:Optional['Architecture'] = None) -> None:
+ def add_branch(self, branch_type: BranchType, target: int = 0, arch: Optional['Architecture'] = None) -> None:
self.branches.append(InstructionBranch(branch_type, target, arch))
def __len__(self):
@@ -158,7 +159,7 @@ class _ArchitectureMetaClass(type):
finally:
core.BNFreeArchitectureList(archs)
- def __getitem__(cls:'_ArchitectureMetaClass', name:str) -> 'Architecture':
+ def __getitem__(cls: '_ArchitectureMetaClass', name: str) -> 'Architecture':
binaryninja._init_plugins()
arch = core.BNGetArchitectureByName(name)
if arch is None:
@@ -207,7 +208,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
global_regs = []
system_regs = []
flags = []
- flag_write_types:List[FlagWriteTypeName] = []
+ flag_write_types: List[FlagWriteTypeName] = []
semantic_flag_classes = []
semantic_flag_groups = []
flag_roles = {}
@@ -235,47 +236,63 @@ class Architecture(metaclass=_ArchitectureMetaClass):
self._cb.getInstructionAlignment = self._cb.getInstructionAlignment.__class__(self._get_instruction_alignment)
self._cb.getMaxInstructionLength = self._cb.getMaxInstructionLength.__class__(self._get_max_instruction_length)
self._cb.getOpcodeDisplayLength = self._cb.getOpcodeDisplayLength.__class__(self._get_opcode_display_length)
- self._cb.getAssociatedArchitectureByAddress = \
- self._cb.getAssociatedArchitectureByAddress.__class__(self._get_associated_arch_by_address)
+ self._cb.getAssociatedArchitectureByAddress = self._cb.getAssociatedArchitectureByAddress.__class__(
+ self._get_associated_arch_by_address
+ )
self._cb.getInstructionInfo = self._cb.getInstructionInfo.__class__(self._get_instruction_info)
self._cb.getInstructionText = self._cb.getInstructionText.__class__(self._get_instruction_text)
self._cb.freeInstructionText = self._cb.freeInstructionText.__class__(self._free_instruction_text)
self._cb.getInstructionLowLevelIL = self._cb.getInstructionLowLevelIL.__class__(
- self._get_instruction_low_level_il)
+ self._get_instruction_low_level_il
+ )
self._cb.getRegisterName = self._cb.getRegisterName.__class__(self._get_register_name)
self._cb.getFlagName = self._cb.getFlagName.__class__(self._get_flag_name)
self._cb.getFlagWriteTypeName = self._cb.getFlagWriteTypeName.__class__(self._get_flag_write_type_name)
- self._cb.getSemanticFlagClassName = self._cb.getSemanticFlagClassName.__class__(self._get_semantic_flag_class_name)
- self._cb.getSemanticFlagGroupName = self._cb.getSemanticFlagGroupName.__class__(self._get_semantic_flag_group_name)
+ self._cb.getSemanticFlagClassName = self._cb.getSemanticFlagClassName.__class__(
+ self._get_semantic_flag_class_name
+ )
+ self._cb.getSemanticFlagGroupName = self._cb.getSemanticFlagGroupName.__class__(
+ self._get_semantic_flag_group_name
+ )
self._cb.getFullWidthRegisters = self._cb.getFullWidthRegisters.__class__(self._get_full_width_registers)
self._cb.getAllRegisters = self._cb.getAllRegisters.__class__(self._get_all_registers)
self._cb.getAllFlags = self._cb.getAllRegisters.__class__(self._get_all_flags)
self._cb.getAllFlagWriteTypes = self._cb.getAllRegisters.__class__(self._get_all_flag_write_types)
- self._cb.getAllSemanticFlagClasses = self._cb.getAllSemanticFlagClasses.__class__(self._get_all_semantic_flag_classes)
- self._cb.getAllSemanticFlagGroups = self._cb.getAllSemanticFlagGroups.__class__(self._get_all_semantic_flag_groups)
+ self._cb.getAllSemanticFlagClasses = self._cb.getAllSemanticFlagClasses.__class__(
+ self._get_all_semantic_flag_classes
+ )
+ self._cb.getAllSemanticFlagGroups = self._cb.getAllSemanticFlagGroups.__class__(
+ self._get_all_semantic_flag_groups
+ )
self._cb.getFlagRole = self._cb.getFlagRole.__class__(self._get_flag_role)
self._cb.getFlagsRequiredForFlagCondition = self._cb.getFlagsRequiredForFlagCondition.__class__(
- self._get_flags_required_for_flag_condition)
+ self._get_flags_required_for_flag_condition
+ )
self._cb.getFlagsRequiredForSemanticFlagGroup = self._cb.getFlagsRequiredForSemanticFlagGroup.__class__(
- self._get_flags_required_for_semantic_flag_group)
+ self._get_flags_required_for_semantic_flag_group
+ )
self._cb.getFlagConditionsForSemanticFlagGroup = self._cb.getFlagConditionsForSemanticFlagGroup.__class__(
- self._get_flag_conditions_for_semantic_flag_group)
+ self._get_flag_conditions_for_semantic_flag_group
+ )
self._cb.freeFlagConditionsForSemanticFlagGroup = self._cb.freeFlagConditionsForSemanticFlagGroup.__class__(
- self._free_flag_conditions_for_semantic_flag_group)
+ self._free_flag_conditions_for_semantic_flag_group
+ )
self._cb.getFlagsWrittenByFlagWriteType = self._cb.getFlagsWrittenByFlagWriteType.__class__(
- self._get_flags_written_by_flag_write_type)
+ self._get_flags_written_by_flag_write_type
+ )
self._cb.getSemanticClassForFlagWriteType = self._cb.getSemanticClassForFlagWriteType.__class__(
- self._get_semantic_class_for_flag_write_type)
- self._cb.getFlagWriteLowLevelIL = self._cb.getFlagWriteLowLevelIL.__class__(
- self._get_flag_write_low_level_il)
+ self._get_semantic_class_for_flag_write_type
+ )
+ self._cb.getFlagWriteLowLevelIL = self._cb.getFlagWriteLowLevelIL.__class__(self._get_flag_write_low_level_il)
self._cb.getFlagConditionLowLevelIL = self._cb.getFlagConditionLowLevelIL.__class__(
- self._get_flag_condition_low_level_il)
+ self._get_flag_condition_low_level_il
+ )
self._cb.getSemanticFlagGroupLowLevelIL = self._cb.getSemanticFlagGroupLowLevelIL.__class__(
- self._get_semantic_flag_group_low_level_il)
+ self._get_semantic_flag_group_low_level_il
+ )
self._cb.freeRegisterList = self._cb.freeRegisterList.__class__(self._free_register_list)
self._cb.getRegisterInfo = self._cb.getRegisterInfo.__class__(self._get_register_info)
- self._cb.getStackPointerRegister = self._cb.getStackPointerRegister.__class__(
- self._get_stack_pointer_register)
+ self._cb.getStackPointerRegister = self._cb.getStackPointerRegister.__class__(self._get_stack_pointer_register)
self._cb.getLinkRegister = self._cb.getLinkRegister.__class__(self._get_link_register)
self._cb.getGlobalRegisters = self._cb.getGlobalRegisters.__class__(self._get_global_registers)
self._cb.getSystemRegisters = self._cb.getSystemRegisters.__class__(self._get_system_registers)
@@ -290,15 +307,20 @@ class Architecture(metaclass=_ArchitectureMetaClass):
self._cb.freeTypeList = self._cb.freeTypeList.__class__(self._free_type_list)
self._cb.assemble = self._cb.assemble.__class__(self._assemble)
self._cb.isNeverBranchPatchAvailable = self._cb.isNeverBranchPatchAvailable.__class__(
- self._is_never_branch_patch_available)
+ self._is_never_branch_patch_available
+ )
self._cb.isAlwaysBranchPatchAvailable = self._cb.isAlwaysBranchPatchAvailable.__class__(
- self._is_always_branch_patch_available)
+ self._is_always_branch_patch_available
+ )
self._cb.isInvertBranchPatchAvailable = self._cb.isInvertBranchPatchAvailable.__class__(
- self._is_invert_branch_patch_available)
+ self._is_invert_branch_patch_available
+ )
self._cb.isSkipAndReturnZeroPatchAvailable = self._cb.isSkipAndReturnZeroPatchAvailable.__class__(
- self._is_skip_and_return_zero_patch_available)
+ self._is_skip_and_return_zero_patch_available
+ )
self._cb.isSkipAndReturnValuePatchAvailable = self._cb.isSkipAndReturnValuePatchAvailable.__class__(
- self._is_skip_and_return_value_patch_available)
+ self._is_skip_and_return_value_patch_available
+ )
self._cb.convertToNop = self._cb.convertToNop.__class__(self._convert_to_nop)
self._cb.alwaysBranch = self._cb.alwaysBranch.__class__(self._always_branch)
self._cb.invertBranch = self._cb.invertBranch.__class__(self._invert_branch)
@@ -313,16 +335,16 @@ class Architecture(metaclass=_ArchitectureMetaClass):
self.__dict__['stack_pointer'] = self.__class__.stack_pointer
self.__dict__['link_reg'] = self.__class__.link_reg
- self._all_regs:Dict[RegisterName, RegisterIndex] = {}
- self._full_width_regs:Dict[RegisterName, RegisterIndex] = {}
- self._regs_by_index:Dict[RegisterIndex, RegisterName] = {}
+ self._all_regs: Dict[RegisterName, RegisterIndex] = {}
+ self._full_width_regs: Dict[RegisterName, RegisterIndex] = {}
+ self._regs_by_index: Dict[RegisterIndex, RegisterName] = {}
self.regs = self.__class__.regs
assert self.regs is not None, "Custom Architecture doesn't specify a register map"
reg_index = RegisterIndex(0)
# Registers used for storage in register stacks must be sequential, so allocate these in order first
- self._all_reg_stacks:Dict[RegisterStackName, RegisterStackIndex] = {}
- self._reg_stacks_by_index:Dict[RegisterStackIndex, RegisterStackName] = {}
+ self._all_reg_stacks: Dict[RegisterStackName, RegisterStackIndex] = {}
+ self._reg_stacks_by_index: Dict[RegisterStackIndex, RegisterStackName] = {}
self.reg_stacks = self.__class__.reg_stacks
assert self.regs is not None, "Custom Architecture doesn't specify a reg_stacks map"
reg_stack_index = RegisterStackIndex(0)
@@ -343,7 +365,9 @@ class Architecture(metaclass=_ArchitectureMetaClass):
self._all_reg_stacks[reg_stack] = reg_stack_index
self._reg_stacks_by_index[reg_stack_index] = reg_stack
rs = self.reg_stacks[reg_stack]
- self.reg_stacks[reg_stack] = RegisterStackInfo(rs.storage_regs, rs.top_relative_regs, rs.stack_top_reg, reg_stack_index)
+ self.reg_stacks[reg_stack] = RegisterStackInfo(
+ rs.storage_regs, rs.top_relative_regs, rs.stack_top_reg, reg_stack_index
+ )
reg_stack_index = RegisterStackIndex(reg_stack_index + 1)
for reg, info in self.regs.items():
@@ -362,9 +386,9 @@ class Architecture(metaclass=_ArchitectureMetaClass):
if info.full_width_reg not in self._full_width_regs:
self._full_width_regs[info.full_width_reg] = self._all_regs[info.full_width_reg]
- self._flags:Dict[FlagName, FlagIndex] = {}
- self._flags_by_index:Dict[FlagIndex, FlagName] = {}
- self.flags:List[FlagName] = self.__class__.flags
+ self._flags: Dict[FlagName, FlagIndex] = {}
+ self._flags_by_index: Dict[FlagIndex, FlagName] = {}
+ self.flags: List[FlagName] = self.__class__.flags
flag_index = FlagIndex(0)
for flag in self.__class__.flags:
if flag not in self._flags:
@@ -372,9 +396,9 @@ class Architecture(metaclass=_ArchitectureMetaClass):
self._flags_by_index[flag_index] = flag
flag_index = FlagIndex(flag_index + 1)
- self._flag_write_types:Dict[FlagWriteTypeName, FlagWriteTypeIndex] = {}
- self._flag_write_types_by_index:Dict[FlagWriteTypeIndex, FlagWriteTypeName] = {}
- self.flag_write_types:List[FlagWriteTypeName] = self.__class__.flag_write_types
+ self._flag_write_types: Dict[FlagWriteTypeName, FlagWriteTypeIndex] = {}
+ self._flag_write_types_by_index: Dict[FlagWriteTypeIndex, FlagWriteTypeName] = {}
+ self.flag_write_types: List[FlagWriteTypeName] = self.__class__.flag_write_types
write_type_index = FlagWriteTypeIndex(1)
for write_type in self.__class__.flag_write_types:
if write_type not in self._flag_write_types:
@@ -382,9 +406,9 @@ class Architecture(metaclass=_ArchitectureMetaClass):
self._flag_write_types_by_index[write_type_index] = write_type
write_type_index = FlagWriteTypeIndex(write_type_index + 1)
- self._semantic_flag_classes:Dict[SemanticClassName, SemanticClassIndex] = {}
- self._semantic_flag_classes_by_index:Dict[SemanticClassIndex, SemanticClassName] = {}
- self.semantic_flag_classes:List[SemanticClassName] = self.__class__.semantic_flag_classes
+ self._semantic_flag_classes: Dict[SemanticClassName, SemanticClassIndex] = {}
+ self._semantic_flag_classes_by_index: Dict[SemanticClassIndex, SemanticClassName] = {}
+ self.semantic_flag_classes: List[SemanticClassName] = self.__class__.semantic_flag_classes
semantic_class_index = SemanticClassIndex(1)
for sem_class in self.__class__.semantic_flag_classes:
if sem_class not in self._semantic_flag_classes:
@@ -392,9 +416,9 @@ class Architecture(metaclass=_ArchitectureMetaClass):
self._semantic_flag_classes_by_index[semantic_class_index] = sem_class
semantic_class_index = SemanticClassIndex(semantic_class_index + 1)
- self._semantic_flag_groups:Dict[SemanticGroupName, SemanticGroupIndex] = {}
- self._semantic_flag_groups_by_index:Dict[SemanticGroupIndex, SemanticGroupName] = {}
- self.semantic_flag_groups:List[SemanticGroupName] = self.__class__.semantic_flag_groups
+ self._semantic_flag_groups: Dict[SemanticGroupName, SemanticGroupIndex] = {}
+ self._semantic_flag_groups_by_index: Dict[SemanticGroupIndex, SemanticGroupName] = {}
+ self.semantic_flag_groups: List[SemanticGroupName] = self.__class__.semantic_flag_groups
semantic_group_index = SemanticGroupIndex(0)
for sem_group in self.__class__.semantic_flag_groups:
if sem_group not in self._semantic_flag_groups:
@@ -402,20 +426,22 @@ class Architecture(metaclass=_ArchitectureMetaClass):
self._semantic_flag_groups_by_index[semantic_group_index] = sem_group
semantic_group_index = SemanticGroupIndex(semantic_group_index + 1)
- self._flag_roles:Dict[FlagIndex, FlagRole] = {}
- self.flag_roles:Dict[FlagName, FlagRole] = self.__class__.flag_roles
+ self._flag_roles: Dict[FlagIndex, FlagRole] = {}
+ self.flag_roles: Dict[FlagName, FlagRole] = self.__class__.flag_roles
for flag in self.__class__.flag_roles:
role = self.__class__.flag_roles[flag]
if isinstance(role, str):
role = FlagRole[role]
self._flag_roles[self._flags[flag]] = role
- self.flags_required_for_flag_condition:Dict['lowlevelil.LowLevelILFlagCondition', List[FlagName]] = self.__class__.flags_required_for_flag_condition
+ self.flags_required_for_flag_condition: Dict['lowlevelil.LowLevelILFlagCondition',
+ List[FlagName]] = self.__class__.flags_required_for_flag_condition
- self._flags_required_by_semantic_flag_group:Dict[SemanticGroupIndex, List[FlagIndex]] = {}
- self.flags_required_for_semantic_flag_group:Dict[SemanticGroupName, List[FlagName]] = self.__class__.flags_required_for_semantic_flag_group
+ self._flags_required_by_semantic_flag_group: Dict[SemanticGroupIndex, List[FlagIndex]] = {}
+ self.flags_required_for_semantic_flag_group: Dict[
+ SemanticGroupName, List[FlagName]] = self.__class__.flags_required_for_semantic_flag_group
for group in self.__class__.flags_required_for_semantic_flag_group:
- flags:List[FlagIndex] = []
+ flags: List[FlagIndex] = []
for flag in self.__class__.flags_required_for_semantic_flag_group[group]:
flags.append(self._flags[flag])
self._flags_required_by_semantic_flag_group[self._semantic_flag_groups[group]] = flags
@@ -428,7 +454,8 @@ class Architecture(metaclass=_ArchitectureMetaClass):
if sem_class is None:
class_cond[0] = self.__class__.flag_conditions_for_semantic_flag_group[group][sem_class]
else:
- class_cond[self._semantic_flag_classes[sem_class]] = self.__class__.flag_conditions_for_semantic_flag_group[group][sem_class]
+ class_cond[self._semantic_flag_classes[sem_class]
+ ] = self.__class__.flag_conditions_for_semantic_flag_group[group][sem_class]
self._flag_conditions_for_semantic_flag_group[self._semantic_flag_groups[group]] = class_cond
self._flags_written_by_flag_write_type = {}
@@ -452,8 +479,8 @@ class Architecture(metaclass=_ArchitectureMetaClass):
self.global_regs = self.__class__.global_regs
self.system_regs = self.__class__.system_regs
- self._intrinsics:Dict[IntrinsicName, IntrinsicIndex] = {}
- self._intrinsics_by_index:Dict[IntrinsicIndex, Tuple[IntrinsicName, IntrinsicInfo]] = {}
+ self._intrinsics: Dict[IntrinsicName, IntrinsicIndex] = {}
+ self._intrinsics_by_index: Dict[IntrinsicIndex, Tuple[IntrinsicName, IntrinsicInfo]] = {}
intrinsic_index = IntrinsicIndex(0)
for intrinsic in self.__class__.intrinsics.keys():
if intrinsic not in self._intrinsics:
@@ -509,7 +536,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
count = ctypes.c_ulonglong()
regs = core.BNGetFullWidthArchitectureRegisters(self.handle, count)
assert regs is not None, "core.BNGetFullWidthArchitectureRegisters returned None"
- result:List[RegisterName] = []
+ result: List[RegisterName] = []
try:
for i in range(0, count.value):
result.append(RegisterName(core.BNGetArchitectureRegisterName(self.handle, regs[i])))
@@ -668,8 +695,9 @@ class Architecture(metaclass=_ArchitectureMetaClass):
try:
buf = ctypes.create_string_buffer(length[0])
ctypes.memmove(buf, data, length[0])
- result = self.get_instruction_low_level_il(buf.raw, addr,
- lowlevelil.LowLevelILFunction(self, core.BNNewLowLevelILFunctionReference(il)))
+ result = self.get_instruction_low_level_il(
+ buf.raw, addr, lowlevelil.LowLevelILFunction(self, core.BNNewLowLevelILFunctionReference(il))
+ )
if result is None:
return False
length[0] = result
@@ -696,7 +724,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
log_error(traceback.format_exc())
return core.BNAllocString("")
- def _get_flag_write_type_name(self, ctxt, write_type:FlagWriteTypeIndex):
+ def _get_flag_write_type_name(self, ctxt, write_type: FlagWriteTypeIndex):
try:
if write_type in self._flag_write_types_by_index:
return core.BNAllocString(self._flag_write_types_by_index[write_type])
@@ -813,7 +841,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
count[0] = 0
return None
- def _get_flag_role(self, ctxt, flag:FlagIndex, sem_class:Optional[SemanticClassName]=None):
+ def _get_flag_role(self, ctxt, flag: FlagIndex, sem_class: Optional[SemanticClassName] = None):
if sem_class in self._semantic_flag_classes:
assert sem_class is not None
_sem_class = self._semantic_flag_classes[sem_class]
@@ -933,8 +961,10 @@ class Architecture(metaclass=_ArchitectureMetaClass):
operand_list.append(lowlevelil.ILRegister(self, operands[i].reg))
else:
operand_list.append(lowlevelil.ILRegister(self, operands[i].reg))
- return self.get_flag_write_low_level_il(op, size, write_type_name, flag_name, operand_list,
- lowlevelil.LowLevelILFunction(self, core.BNNewLowLevelILFunctionReference(il)))
+ return self.get_flag_write_low_level_il(
+ op, size, write_type_name, flag_name, operand_list,
+ lowlevelil.LowLevelILFunction(self, core.BNNewLowLevelILFunctionReference(il))
+ )
except (KeyError, OSError):
log_error(traceback.format_exc())
return False
@@ -945,8 +975,9 @@ class Architecture(metaclass=_ArchitectureMetaClass):
sem_class_name = self._semantic_flag_classes_by_index[sem_class]
else:
sem_class_name = None
- return self.get_flag_condition_low_level_il(cond, sem_class_name,
- lowlevelil.LowLevelILFunction(self, core.BNNewLowLevelILFunctionReference(il)))
+ return self.get_flag_condition_low_level_il(
+ cond, sem_class_name, lowlevelil.LowLevelILFunction(self, core.BNNewLowLevelILFunctionReference(il))
+ )
except OSError:
log_error(traceback.format_exc())
return 0
@@ -957,8 +988,9 @@ class Architecture(metaclass=_ArchitectureMetaClass):
sem_group_name = self._semantic_flag_groups_by_index[sem_group]
else:
sem_group_name = None
- return self.get_semantic_flag_group_low_level_il(sem_group_name,
- lowlevelil.LowLevelILFunction(self, core.BNNewLowLevelILFunctionReference(il)))
+ return self.get_semantic_flag_group_low_level_il(
+ sem_group_name, lowlevelil.LowLevelILFunction(self, core.BNNewLowLevelILFunctionReference(il))
+ )
except OSError:
log_error(traceback.format_exc())
return 0
@@ -1309,10 +1341,10 @@ class Architecture(metaclass=_ArchitectureMetaClass):
log_error(traceback.format_exc())
return False
- def get_associated_arch_by_address(self, addr:int) -> Tuple['Architecture', int]:
+ def get_associated_arch_by_address(self, addr: int) -> Tuple['Architecture', int]:
return self, addr
- def get_instruction_info(self, data:bytes, addr:int) -> Optional[InstructionInfo]:
+ def get_instruction_info(self, data: bytes, addr: int) -> Optional[InstructionInfo]:
"""
``get_instruction_info`` returns an InstructionInfo object for the instruction at the given virtual address
``addr`` with data ``data``.
@@ -1344,7 +1376,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
"""
raise NotImplementedError
- def get_instruction_text(self, data:bytes, addr:int) -> Tuple[List['function.InstructionTextToken'], int]:
+ def get_instruction_text(self, data: bytes, addr: int) -> Tuple[List['function.InstructionTextToken'], int]:
"""
``get_instruction_text`` returns a tuple containing a list of decoded InstructionTextToken objects and the bytes used at the given virtual
address ``addr`` with data ``data``.
@@ -1358,13 +1390,15 @@ class Architecture(metaclass=_ArchitectureMetaClass):
"""
raise NotImplementedError
- def get_instruction_low_level_il_instruction(self, bv:'binaryview.BinaryView', addr:int) -> 'lowlevelil.LowLevelILInstruction':
+ def get_instruction_low_level_il_instruction(
+ self, bv: 'binaryview.BinaryView', addr: int
+ ) -> 'lowlevelil.LowLevelILInstruction':
il = lowlevelil.LowLevelILFunction(self)
data = bv.read(addr, self.max_instr_length)
self.get_instruction_low_level_il(data, addr, il)
return il[0]
- def get_instruction_low_level_il(self, data:bytes, addr:int, il:'lowlevelil.LowLevelILFunction') -> int:
+ def get_instruction_low_level_il(self, data: bytes, addr: int, il: 'lowlevelil.LowLevelILFunction') -> int:
"""
``get_instruction_low_level_il`` appends lowlevelil.ExpressionIndex objects to ``il`` for the instruction at the given
virtual address ``addr`` with data ``data``.
@@ -1382,7 +1416,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
"""
raise NotImplementedError
- def get_low_level_il_from_bytes(self, data:bytes, addr:int) -> 'lowlevelil.LowLevelILInstruction':
+ def get_low_level_il_from_bytes(self, data: bytes, addr: int) -> 'lowlevelil.LowLevelILInstruction':
"""
``get_low_level_il_from_bytes`` converts the instruction in bytes to ``il`` at the given virtual address
@@ -1400,7 +1434,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
self.get_instruction_low_level_il(data, addr, func)
return func[0]
- def get_reg_name(self, reg:RegisterIndex) -> RegisterName:
+ def get_reg_name(self, reg: RegisterIndex) -> RegisterName:
"""
``get_reg_name`` gets a register name from a register index.
@@ -1410,7 +1444,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
"""
return RegisterName(core.BNGetArchitectureRegisterName(self.handle, reg))
- def get_reg_stack_name(self, reg_stack:RegisterStackIndex) -> RegisterStackName:
+ def get_reg_stack_name(self, reg_stack: RegisterStackIndex) -> RegisterStackName:
"""
``get_reg_stack_name`` gets a register stack name from a register stack number.
@@ -1420,14 +1454,14 @@ class Architecture(metaclass=_ArchitectureMetaClass):
"""
return RegisterStackName(core.BNGetArchitectureRegisterStackName(self.handle, reg_stack))
- def get_reg_stack_for_reg(self, reg:RegisterName) -> Optional[RegisterStackName]:
+ def get_reg_stack_for_reg(self, reg: RegisterName) -> Optional[RegisterStackName]:
_reg = self.get_reg_index(reg)
result = core.BNGetArchitectureRegisterStackForRegister(self.handle, _reg)
if result == 0xffffffff:
return None
return self.get_reg_stack_name(RegisterStackIndex(result))
- def get_flag_name(self, flag:FlagIndex) -> FlagName:
+ def get_flag_name(self, flag: FlagIndex) -> FlagName:
"""
``get_flag_name`` gets a flag name from a flag index.
@@ -1437,7 +1471,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
"""
return FlagName(core.BNGetArchitectureFlagName(self.handle, flag))
- def get_reg_index(self, reg:RegisterType) -> RegisterIndex:
+ def get_reg_index(self, reg: RegisterType) -> RegisterIndex:
if isinstance(reg, str):
try:
index = self.regs[reg].index
@@ -1452,7 +1486,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
return RegisterIndex(reg)
raise Exception("Attempting to get register index of non-existant register")
- def get_reg_stack_index(self, reg_stack:RegisterStackType) -> RegisterStackIndex:
+ def get_reg_stack_index(self, reg_stack: RegisterStackType) -> RegisterStackIndex:
if isinstance(reg_stack, str):
reg_stack_info = self.reg_stacks[reg_stack]
if reg_stack_info is not None and reg_stack_info.index is not None:
@@ -1463,7 +1497,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
return RegisterStackIndex(reg_stack)
raise Exception("reg_stack is not convertable to index")
- def get_flag_index(self, flag:FlagType) -> FlagIndex:
+ def get_flag_index(self, flag: FlagType) -> FlagIndex:
if isinstance(flag, str):
return self._flags[FlagName(flag)]
elif isinstance(flag, lowlevelil.ILFlag):
@@ -1472,7 +1506,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
return FlagIndex(flag)
raise Exception("flag is not convertable to index")
- def get_semantic_flag_class_index(self, sem_class:Optional[SemanticClassType]) -> SemanticClassIndex:
+ def get_semantic_flag_class_index(self, sem_class: Optional[SemanticClassType]) -> SemanticClassIndex:
if sem_class is None:
return SemanticClassIndex(0)
if isinstance(sem_class, str):
@@ -1483,7 +1517,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
return SemanticClassIndex(sem_class)
raise Exception("sem_class is not convertable to index")
- def get_semantic_flag_class_name(self, class_index:SemanticClassIndex) -> SemanticClassName:
+ def get_semantic_flag_class_name(self, class_index: SemanticClassIndex) -> SemanticClassName:
"""
``get_semantic_flag_class_name`` gets the name of a semantic flag class from the index.
@@ -1495,14 +1529,14 @@ class Architecture(metaclass=_ArchitectureMetaClass):
raise ValueError("argument 'class_index' must be an integer")
return self._semantic_flag_classes_by_index[class_index]
- def get_semantic_flag_group_index(self, sem_group:SemanticGroupType) -> SemanticGroupIndex:
+ def get_semantic_flag_group_index(self, sem_group: SemanticGroupType) -> SemanticGroupIndex:
if isinstance(sem_group, str):
return self._semantic_flag_groups[SemanticGroupName(sem_group)]
elif isinstance(sem_group, lowlevelil.ILSemanticFlagGroup):
return sem_group.index
return sem_group
- def get_semantic_flag_group_name(self, group_index:SemanticGroupIndex) -> SemanticGroupName:
+ def get_semantic_flag_group_name(self, group_index: SemanticGroupIndex) -> SemanticGroupName:
"""
``get_semantic_flag_group_name`` gets the name of a semantic flag group from the index.
@@ -1514,7 +1548,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
raise ValueError("argument 'group_index' must be an integer")
return self._semantic_flag_groups_by_index[group_index]
- def get_intrinsic_name(self, intrinsic:IntrinsicIndex) -> IntrinsicName:
+ def get_intrinsic_name(self, intrinsic: IntrinsicIndex) -> IntrinsicName:
"""
``get_intrinsic_name`` gets an intrinsic name from an intrinsic number.
@@ -1524,7 +1558,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
"""
return IntrinsicName(core.BNGetArchitectureIntrinsicName(self.handle, intrinsic))
- def get_intrinsic_index(self, intrinsic:IntrinsicType) -> IntrinsicIndex:
+ def get_intrinsic_index(self, intrinsic: IntrinsicType) -> IntrinsicIndex:
"""
``get_intrinsic_index`` gets an intrinsic index given an IntrinsicType.
@@ -1540,7 +1574,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
return IntrinsicIndex(intrinsic)
raise Exception("intrinsic is not convertable to index")
- def get_flag_write_type_name(self, write_type:FlagWriteTypeIndex) -> FlagWriteTypeName:
+ def get_flag_write_type_name(self, write_type: FlagWriteTypeIndex) -> FlagWriteTypeName:
"""
``get_flag_write_type_name`` gets the flag write type name for the given flag.
@@ -1550,7 +1584,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
"""
return FlagWriteTypeName(core.BNGetArchitectureFlagWriteTypeName(self.handle, write_type))
- def get_flag_by_name(self, flag:FlagName) -> FlagIndex:
+ def get_flag_by_name(self, flag: FlagName) -> FlagIndex:
"""
``get_flag_by_name`` get flag name for flag index.
@@ -1560,7 +1594,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
"""
return self._flags[flag]
- def get_flag_write_type_by_name(self, write_type:FlagWriteTypeName) -> FlagWriteTypeIndex:
+ def get_flag_write_type_by_name(self, write_type: FlagWriteTypeName) -> FlagWriteTypeIndex:
"""
``get_flag_write_type_by_name`` gets the flag write type name for the flag write type.
@@ -1570,7 +1604,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
"""
return self._flag_write_types[write_type]
- def get_semantic_flag_class_by_name(self, sem_class:SemanticClassName) -> SemanticClassIndex:
+ def get_semantic_flag_class_by_name(self, sem_class: SemanticClassName) -> SemanticClassIndex:
"""
``get_semantic_flag_class_by_name`` gets the semantic flag class index by name.
@@ -1580,7 +1614,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
"""
return self._semantic_flag_classes[sem_class]
- def get_semantic_flag_group_by_name(self, sem_group:SemanticGroupName) -> SemanticGroupIndex:
+ def get_semantic_flag_group_by_name(self, sem_group: SemanticGroupName) -> SemanticGroupIndex:
"""
``get_semantic_flag_group_by_name`` gets the semantic flag group index by name.
@@ -1590,7 +1624,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
"""
return self._semantic_flag_groups[sem_group]
- def get_flag_role(self, flag:FlagIndex, sem_class:Optional[SemanticClassIndex]= None) -> FlagRole:
+ def get_flag_role(self, flag: FlagIndex, sem_class: Optional[SemanticClassIndex] = None) -> FlagRole:
"""
``get_flag_role`` gets the role of a given flag.
@@ -1603,8 +1637,10 @@ class Architecture(metaclass=_ArchitectureMetaClass):
return self._flag_roles[flag]
return FlagRole.SpecialFlagRole
- def get_flag_write_low_level_il(self, op:LowLevelILOperation, size:int, write_type:Optional[FlagWriteTypeName], flag:FlagType,
- operands:List['lowlevelil.ILRegisterType'], il:'lowlevelil.LowLevelILFunction') -> 'lowlevelil.ExpressionIndex':
+ def get_flag_write_low_level_il(
+ self, op: LowLevelILOperation, size: int, write_type: Optional[FlagWriteTypeName], flag: FlagType,
+ operands: List['lowlevelil.ILRegisterType'], il: 'lowlevelil.LowLevelILFunction'
+ ) -> 'lowlevelil.ExpressionIndex':
"""
:param LowLevelILOperation op:
:param int size:
@@ -1620,8 +1656,10 @@ class Architecture(metaclass=_ArchitectureMetaClass):
return il.unimplemented()
return self.get_default_flag_write_low_level_il(op, size, self._flag_roles[flag], operands, il)
- def get_default_flag_write_low_level_il(self, op:'lowlevelil.LowLevelILOperation', size:int, role:FlagRole,
- operands:List['lowlevelil.ILRegisterType'], il:'lowlevelil.LowLevelILFunction') -> 'lowlevelil.ExpressionIndex':
+ def get_default_flag_write_low_level_il(
+ self, op: 'lowlevelil.LowLevelILOperation', size: int, role: FlagRole,
+ operands: List['lowlevelil.ILRegisterType'], il: 'lowlevelil.LowLevelILFunction'
+ ) -> 'lowlevelil.ExpressionIndex':
"""
:param LowLevelILOperation op:
:param int size:
@@ -1643,11 +1681,16 @@ class Architecture(metaclass=_ArchitectureMetaClass):
else:
operand_list[i].constant = True
operand_list[i].value = operand
- return lowlevelil.ExpressionIndex(core.BNGetDefaultArchitectureFlagWriteLowLevelIL(self.handle, op, size,
- role, operand_list, len(operand_list), il.handle))
+ return lowlevelil.ExpressionIndex(
+ core.BNGetDefaultArchitectureFlagWriteLowLevelIL(
+ self.handle, op, size, role, operand_list, len(operand_list), il.handle
+ )
+ )
- def get_flag_condition_low_level_il(self, cond:'lowlevelil.LowLevelILFlagCondition', sem_class:Optional[SemanticClassType],
- il:'lowlevelil.LowLevelILFunction') -> 'lowlevelil.ExpressionIndex':
+ def get_flag_condition_low_level_il(
+ self, cond: 'lowlevelil.LowLevelILFlagCondition', sem_class: Optional[SemanticClassType],
+ il: 'lowlevelil.LowLevelILFunction'
+ ) -> 'lowlevelil.ExpressionIndex':
"""
:param LowLevelILFlagCondition cond: Flag condition to be computed
:param SemanticClassType sem_class: Semantic class to be used (None for default semantics)
@@ -1656,8 +1699,10 @@ class Architecture(metaclass=_ArchitectureMetaClass):
"""
return self.get_default_flag_condition_low_level_il(cond, sem_class, il)
- def get_default_flag_condition_low_level_il(self, cond:'lowlevelil.LowLevelILFlagCondition',
- sem_class:Optional[SemanticClassType], il:'lowlevelil.LowLevelILFunction') -> 'lowlevelil.ExpressionIndex':
+ def get_default_flag_condition_low_level_il(
+ self, cond: 'lowlevelil.LowLevelILFlagCondition', sem_class: Optional[SemanticClassType],
+ il: 'lowlevelil.LowLevelILFunction'
+ ) -> 'lowlevelil.ExpressionIndex':
"""
:param LowLevelILFlagCondition cond:
:param SemanticClassType sem_class:
@@ -1666,11 +1711,13 @@ class Architecture(metaclass=_ArchitectureMetaClass):
"""
_class_index = None
_class_index = self.get_semantic_flag_class_index(sem_class)
- return lowlevelil.ExpressionIndex(core.BNGetDefaultArchitectureFlagConditionLowLevelIL(self.handle, cond,
- _class_index, il.handle))
+ return lowlevelil.ExpressionIndex(
+ core.BNGetDefaultArchitectureFlagConditionLowLevelIL(self.handle, cond, _class_index, il.handle)
+ )
- def get_semantic_flag_group_low_level_il(self, sem_group:Optional[SemanticGroupType],
- il:'lowlevelil.LowLevelILFunction') -> 'lowlevelil.ExpressionIndex':
+ def get_semantic_flag_group_low_level_il(
+ self, sem_group: Optional[SemanticGroupType], il: 'lowlevelil.LowLevelILFunction'
+ ) -> 'lowlevelil.ExpressionIndex':
"""
:param Optional[SemanticGroupType] sem_group:
:param LowLevelILFunction il:
@@ -1678,13 +1725,14 @@ class Architecture(metaclass=_ArchitectureMetaClass):
"""
return il.unimplemented()
- def get_flags_required_for_flag_condition(self, cond:'lowlevelil.LowLevelILFlagCondition',
- sem_class:Optional[SemanticClassType]=None):
+ def get_flags_required_for_flag_condition(
+ self, cond: 'lowlevelil.LowLevelILFlagCondition', sem_class: Optional[SemanticClassType] = None
+ ):
if cond in self.flags_required_for_flag_condition:
return self.flags_required_for_flag_condition[cond]
return []
- def get_modified_regs_on_write(self, reg:RegisterName) -> List[RegisterName]:
+ def get_modified_regs_on_write(self, reg: RegisterName) -> List[RegisterName]:
"""
``get_modified_regs_on_write`` returns a list of register names that are modified when ``reg`` is written.
@@ -1696,13 +1744,13 @@ class Architecture(metaclass=_ArchitectureMetaClass):
count = ctypes.c_ulonglong()
regs = core.BNGetModifiedArchitectureRegistersOnWrite(self.handle, reg, count)
assert regs is not None, "core.BNGetModifiedArchitectureRegistersOnWrite is not None"
- result:List[RegisterName] = []
+ result: List[RegisterName] = []
for i in range(0, count.value):
result.append(RegisterName(core.BNGetArchitectureRegisterName(self.handle, regs[i])))
core.BNFreeRegisterList(regs)
return result
- def assemble(self, code:str, addr:int=0) -> bytes:
+ def assemble(self, code: str, addr: int = 0) -> bytes:
"""
``assemble`` converts the string of assembly instructions ``code`` loaded at virtual address ``addr`` to the
byte representation of those instructions.
@@ -1729,7 +1777,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
"""
return NotImplemented
- def is_never_branch_patch_available(self, data:bytes, addr:int=0) -> bool:
+ def is_never_branch_patch_available(self, data: bytes, addr: int = 0) -> bool:
"""
``is_never_branch_patch_available`` determines if the instruction ``data`` at ``addr`` can be made to **never branch**.
@@ -1749,7 +1797,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
"""
return NotImplemented
- def is_always_branch_patch_available(self, data:bytes, addr:int=0) -> bool:
+ def is_always_branch_patch_available(self, data: bytes, addr: int = 0) -> bool:
"""
``is_always_branch_patch_available`` determines if the instruction ``data`` at ``addr`` can be made to
**always branch**.
@@ -1770,7 +1818,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
"""
return NotImplemented
- def is_invert_branch_patch_available(self, data:bytes, addr:int=0) -> bool:
+ def is_invert_branch_patch_available(self, data: bytes, addr: int = 0) -> bool:
"""
``is_always_branch_patch_available`` determines if the instruction ``data`` at ``addr`` can be inverted.
@@ -1790,7 +1838,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
"""
return NotImplemented
- def is_skip_and_return_zero_patch_available(self, data:bytes, addr:int=0) -> bool:
+ def is_skip_and_return_zero_patch_available(self, data: bytes, addr: int = 0) -> bool:
"""
``is_skip_and_return_zero_patch_available`` determines if the instruction ``data`` at ``addr`` is a *call-like*
instruction that can be made into an instruction *returns zero*.
@@ -1813,7 +1861,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
"""
return NotImplemented
- def is_skip_and_return_value_patch_available(self, data:bytes, addr:int=0) -> bool:
+ def is_skip_and_return_value_patch_available(self, data: bytes, addr: int = 0) -> bool:
"""
``is_skip_and_return_value_patch_available`` determines if the instruction ``data`` at ``addr`` is a *call-like*
instruction that can be made into an instruction *returns a value*.
@@ -1834,7 +1882,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
"""
return NotImplemented
- def convert_to_nop(self, data:bytes, addr:int=0) -> Optional[bytes]:
+ def convert_to_nop(self, data: bytes, addr: int = 0) -> Optional[bytes]:
"""
``convert_to_nop`` reads the instruction(s) in ``data`` at virtual address ``addr`` and returns a string of nop
instructions of the same length as data.
@@ -1853,7 +1901,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
"""
return NotImplemented
- def always_branch(self, data:bytes, addr:int=0) -> Optional[bytes]:
+ def always_branch(self, data: bytes, addr: int = 0) -> Optional[bytes]:
"""
``always_branch`` reads the instruction(s) in ``data`` at virtual address ``addr`` and returns a string of bytes
of the same length which always branches.
@@ -1875,7 +1923,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
"""
return NotImplemented
- def invert_branch(self, data:bytes, addr:int=0) -> Optional[bytes]:
+ def invert_branch(self, data: bytes, addr: int = 0) -> Optional[bytes]:
"""
``invert_branch`` reads the instruction(s) in ``data`` at virtual address ``addr`` and returns a string of bytes
of the same length which inverts the branch of provided instruction.
@@ -1898,7 +1946,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
"""
return NotImplemented
- def skip_and_return_value(self, data:bytes, addr:int, value:int) -> Optional[bytes]:
+ def skip_and_return_value(self, data: bytes, addr: int, value: int) -> Optional[bytes]:
"""
``skip_and_return_value`` reads the instruction(s) in ``data`` at virtual address ``addr`` and returns a string of
bytes of the same length which doesn't call and instead *return a value*.
@@ -1917,7 +1965,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
"""
return NotImplemented
- def is_view_type_constant_defined(self, type_name:str, const_name:str) -> bool:
+ def is_view_type_constant_defined(self, type_name: str, const_name: str) -> bool:
"""
:param str type_name: the BinaryView type name of the constant to query
@@ -1935,7 +1983,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
"""
return core.BNIsBinaryViewTypeArchitectureConstantDefined(self.handle, type_name, const_name)
- def get_view_type_constant(self, type_name:str, const_name:str, default_value:int=0) -> int:
+ def get_view_type_constant(self, type_name: str, const_name: str, default_value: int = 0) -> int:
"""
``get_view_type_constant`` retrieves the view type constant for the given type_name and const_name.
@@ -1955,7 +2003,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
"""
return core.BNGetBinaryViewTypeArchitectureConstant(self.handle, type_name, const_name, default_value)
- def set_view_type_constant(self, type_name:str, const_name:str, value:int) -> None:
+ def set_view_type_constant(self, type_name: str, const_name: str, value: int) -> None:
"""
``set_view_type_constant`` creates a new binaryview type constant.
@@ -1971,7 +2019,7 @@ class Architecture(metaclass=_ArchitectureMetaClass):
"""
core.BNSetBinaryViewTypeArchitectureConstant(self.handle, type_name, const_name, value)
- def register_calling_convention(self, cc:'callingconvention.CallingConvention') -> None:
+ def register_calling_convention(self, cc: 'callingconvention.CallingConvention') -> None:
"""
``register_calling_convention`` registers a new calling convention for the Architecture.
@@ -1982,8 +2030,10 @@ class Architecture(metaclass=_ArchitectureMetaClass):
_architecture_cache = {}
+
+
class CoreArchitecture(Architecture):
- def __init__(self, handle:core.BNArchitecture):
+ def __init__(self, handle: core.BNArchitecture):
super(CoreArchitecture, self).__init__()
self.handle = core.handle_of_type(handle, core.BNArchitecture)
@@ -1994,8 +2044,9 @@ class CoreArchitecture(Architecture):
self.instr_alignment = core.BNGetArchitectureInstructionAlignment(self.handle)
self.max_instr_length = core.BNGetArchitectureMaxInstructionLength(self.handle)
self.opcode_display_length = core.BNGetArchitectureOpcodeDisplayLength(self.handle)
- self.stack_pointer:str = core.BNGetArchitectureRegisterName(self.handle,
- core.BNGetArchitectureStackPointerRegister(self.handle))
+ self.stack_pointer: str = core.BNGetArchitectureRegisterName(
+ self.handle, core.BNGetArchitectureStackPointerRegister(self.handle)
+ )
link_reg = core.BNGetArchitectureLinkRegister(self.handle)
if link_reg == 0xffffffff:
@@ -2015,8 +2066,9 @@ class CoreArchitecture(Architecture):
assert name is not None, ""
info = core.BNGetArchitectureRegisterInfo(self.handle, regs[i])
full_width_reg = RegisterName(core.BNGetArchitectureRegisterName(self.handle, info.fullWidthRegister))
- self.regs[name] = RegisterInfo(full_width_reg, info.size, info.offset,
- ImplicitRegisterExtend(info.extend), regs[i])
+ self.regs[name] = RegisterInfo(
+ full_width_reg, info.size, info.offset, ImplicitRegisterExtend(info.extend), regs[i]
+ )
self._all_regs[name] = regs[i]
self._regs_by_index[regs[i]] = name
for i in range(0, count.value):
@@ -2042,7 +2094,7 @@ class CoreArchitecture(Architecture):
count = ctypes.c_ulonglong()
write_types = core.BNGetAllArchitectureFlagWriteTypes(self.handle, count)
assert write_types is not None, "core.BNGetAllArchitectureFlagWriteTypes returned None"
- self._flag_write_types:Dict[str, FlagWriteTypeIndex] = {}
+ self._flag_write_types: Dict[str, FlagWriteTypeIndex] = {}
self._flag_write_types_by_index = {}
self.flag_write_types = []
for i in range(0, count.value):
@@ -2054,7 +2106,7 @@ class CoreArchitecture(Architecture):
count = ctypes.c_ulonglong()
sem_classes = core.BNGetAllArchitectureSemanticFlagClasses(self.handle, count)
- assert sem_classes is not None,"core.BNGetAllArchitectureSemanticFlagClasses returned None"
+ assert sem_classes is not None, "core.BNGetAllArchitectureSemanticFlagClasses returned None"
self._semantic_flag_classes = {}
self._semantic_flag_classes_by_index = {}
self.semantic_flag_classes = []
@@ -2067,7 +2119,7 @@ class CoreArchitecture(Architecture):
count = ctypes.c_ulonglong()
sem_groups = core.BNGetAllArchitectureSemanticFlagGroups(self.handle, count)
- assert sem_groups is not None,"core.BNGetAllArchitectureSemanticFlagGroups returned Non"
+ assert sem_groups is not None, "core.BNGetAllArchitectureSemanticFlagGroups returned Non"
self._semantic_flag_groups = {}
self._semantic_flag_groups_by_index = {}
self.semantic_flag_groups = []
@@ -2085,7 +2137,7 @@ class CoreArchitecture(Architecture):
self.flag_roles[flag] = role
self._flag_roles[self._flags[flag]] = role
- self.flags_required_for_flag_condition:Dict[LowLevelILFlagCondition, List[FlagName]] = {}
+ self.flags_required_for_flag_condition: Dict[LowLevelILFlagCondition, List[FlagName]] = {}
for cond in LowLevelILFlagCondition:
count = ctypes.c_ulonglong()
flags = core.BNGetArchitectureFlagsRequiredForFlagCondition(self.handle, cond, 0, count)
@@ -2100,8 +2152,9 @@ class CoreArchitecture(Architecture):
self.flags_required_for_semantic_flag_group = {}
for group in self.semantic_flag_groups:
count = ctypes.c_ulonglong()
- flags = core.BNGetArchitectureFlagsRequiredForSemanticFlagGroup(self.handle,
- self._semantic_flag_groups[group], count)
+ flags = core.BNGetArchitectureFlagsRequiredForSemanticFlagGroup(
+ self.handle, self._semantic_flag_groups[group], count
+ )
assert flags is not None, "core.BNGetArchitectureFlagsRequiredForSemanticFlagGroup returned None"
flag_indexes = []
flag_names = []
@@ -2116,8 +2169,9 @@ class CoreArchitecture(Architecture):
self.flag_conditions_for_semantic_flag_group = {}
for group in self.semantic_flag_groups:
count = ctypes.c_ulonglong()
- conditions = core.BNGetArchitectureFlagConditionsForSemanticFlagGroup(self.handle,
- self._semantic_flag_groups[group], count)
+ conditions = core.BNGetArchitectureFlagConditionsForSemanticFlagGroup(
+ self.handle, self._semantic_flag_groups[group], count
+ )
assert conditions is not None, "core.BNGetArchitectureFlagConditionsForSemanticFlagGroup returned None"
class_index_cond = {}
class_cond = {}
@@ -2126,7 +2180,8 @@ class CoreArchitecture(Architecture):
if conditions[i].semanticClass == 0:
class_cond[None] = conditions[i].condition
elif conditions[i].semanticClass in self._semantic_flag_classes_by_index:
- class_cond[self._semantic_flag_classes_by_index[conditions[i].semanticClass]] = conditions[i].condition
+ class_cond[self._semantic_flag_classes_by_index[conditions[i].semanticClass]
+ ] = conditions[i].condition
core.BNFreeFlagConditionsForSemanticFlagGroup(conditions)
self._flag_conditions_for_semantic_flag_group[self._semantic_flag_groups[group]] = class_index_cond
self.flag_conditions_for_semantic_flag_group[group] = class_cond
@@ -2135,8 +2190,9 @@ class CoreArchitecture(Architecture):
self.flags_written_by_flag_write_type = {}
for write_type in self.flag_write_types:
count = ctypes.c_ulonglong()
- flags = core.BNGetArchitectureFlagsWrittenByFlagWriteType(self.handle,
- self._flag_write_types[write_type], count)
+ flags = core.BNGetArchitectureFlagsWrittenByFlagWriteType(
+ self.handle, self._flag_write_types[write_type], count
+ )
assert flags is not None, "core.BNGetArchitectureFlagsWrittenByFlagWriteType returned None"
flag_indexes = []
flag_names = []
@@ -2150,8 +2206,9 @@ class CoreArchitecture(Architecture):
self._semantic_class_for_flag_write_type = {}
self.semantic_class_for_flag_write_type = {}
for write_type in self.flag_write_types:
- sem_class = core.BNGetArchitectureSemanticClassForFlagWriteType(self.handle,
- self._flag_write_types[write_type])
+ sem_class = core.BNGetArchitectureSemanticClassForFlagWriteType(
+ self.handle, self._flag_write_types[write_type]
+ )
if sem_class == 0:
sem_class_name = None
else:
@@ -2162,14 +2219,14 @@ class CoreArchitecture(Architecture):
count = ctypes.c_ulonglong()
regs = core.BNGetArchitectureGlobalRegisters(self.handle, count)
assert regs is not None, "core.BNGetArchitectureGlobalRegisters returned None"
- self.global_regs:List[RegisterName] = []
+ self.global_regs: List[RegisterName] = []
for i in range(0, count.value):
self.global_regs.append(RegisterName(core.BNGetArchitectureRegisterName(self.handle, regs[i])))
core.BNFreeRegisterList(regs)
count = ctypes.c_ulonglong()
regs = core.BNGetArchitectureSystemRegisters(self.handle, count)
- self.system_regs:List[RegisterName] = []
+ self.system_regs: List[RegisterName] = []
for i in range(0, count.value):
assert regs is not None, "core.BNGetArchitectureSystemRegisters returned None"
self.system_regs.append(RegisterName(core.BNGetArchitectureRegisterName(self.handle, regs[i])))
@@ -2184,10 +2241,10 @@ class CoreArchitecture(Architecture):
for i in range(0, count.value):
name = RegisterStackName(core.BNGetArchitectureRegisterStackName(self.handle, regs[i]))
info = core.BNGetArchitectureRegisterStackInfo(self.handle, regs[i])
- storage:List[RegisterName] = []
+ storage: List[RegisterName] = []
for j in range(0, info.storageCount):
storage.append(RegisterName(core.BNGetArchitectureRegisterName(self.handle, info.firstStorageReg + j)))
- top_rel:List[RegisterName] = []
+ top_rel: List[RegisterName] = []
for j in range(0, info.topRelativeCount):
reg_name = RegisterName(core.BNGetArchitectureRegisterName(self.handle, info.firstTopRelativeReg + j))
top_rel.append(reg_name)
@@ -2200,9 +2257,9 @@ class CoreArchitecture(Architecture):
count = ctypes.c_ulonglong()
intrinsics = core.BNGetAllArchitectureIntrinsics(self.handle, count)
assert intrinsics is not None, "core.BNGetAllArchitectureIntrinsics returned None"
- self._intrinsics:Dict[IntrinsicName, IntrinsicIndex] = {}
- self._intrinsics_by_index:Dict[IntrinsicIndex, Tuple[IntrinsicName, IntrinsicInfo]] = {}
- self._intrinsics_info:Dict[IntrinsicName, IntrinsicInfo] = {}
+ self._intrinsics: Dict[IntrinsicName, IntrinsicIndex] = {}
+ self._intrinsics_by_index: Dict[IntrinsicIndex, Tuple[IntrinsicName, IntrinsicInfo]] = {}
+ self._intrinsics_info: Dict[IntrinsicName, IntrinsicInfo] = {}
for i in range(count.value):
name = IntrinsicName(core.BNGetArchitectureIntrinsicName(self.handle, intrinsics[i]))
input_count = ctypes.c_ulonglong()
@@ -2211,7 +2268,9 @@ class CoreArchitecture(Architecture):
input_list = []
for j in range(0, input_count.value):
input_name = inputs[j].name
- type_obj = types.Type.create(core.BNNewTypeReference(inputs[j].type), confidence = inputs[j].typeConfidence)
+ type_obj = types.Type.create(
+ core.BNNewTypeReference(inputs[j].type), confidence=inputs[j].typeConfidence
+ )
input_list.append(IntrinsicInput(type_obj, input_name))
core.BNFreeNameAndTypeList(inputs, input_count.value)
output_count = ctypes.c_ulonglong()
@@ -2219,7 +2278,9 @@ class CoreArchitecture(Architecture):
assert outputs is not None, "core.BNGetArchitectureIntrinsicOutputs returned None"
output_list = []
for j in range(output_count.value):
- output_list.append(types.Type.create(core.BNNewTypeReference(outputs[j].type), confidence = outputs[j].confidence))
+ output_list.append(
+ types.Type.create(core.BNNewTypeReference(outputs[j].type), confidence=outputs[j].confidence)
+ )
core.BNFreeOutputTypeList(outputs, output_count.value)
self._intrinsics_info[name] = IntrinsicInfo(input_list, output_list)
self._intrinsics[name] = intrinsics[i]
@@ -2234,13 +2295,13 @@ class CoreArchitecture(Architecture):
global _architecture_cache
return _architecture_cache.get(ctypes.addressof(handle.contents)) or cls(handle)
- def get_associated_arch_by_address(self, addr:int) -> Tuple['Architecture', int]:
+ def get_associated_arch_by_address(self, addr: int) -> Tuple['Architecture', int]:
new_addr = ctypes.c_ulonglong()
new_addr.value = addr
result = core.BNGetAssociatedArchitectureByAddress(self.handle, new_addr)
- return CoreArchitecture._from_cache(handle = result), new_addr.value
+ return CoreArchitecture._from_cache(handle=result), new_addr.value
- def get_instruction_info(self, data:bytes, addr:int) -> Optional[InstructionInfo]:
+ def get_instruction_info(self, data: bytes, addr: int) -> Optional[InstructionInfo]:
"""
``get_instruction_info`` returns an InstructionInfo object for the instruction at the given virtual address
``addr`` with data ``data``.
@@ -2271,7 +2332,7 @@ class CoreArchitecture(Architecture):
result.add_branch(BranchType(info.branchType[i]), target, arch)
return result
- def get_instruction_text(self, data:bytes, addr:int) -> Tuple[List['function.InstructionTextToken'], int]:
+ def get_instruction_text(self, data: bytes, addr: int) -> Tuple[List['function.InstructionTextToken'], int]:
"""
``get_instruction_text`` returns a list of InstructionTextToken objects for the instruction at the given virtual
address ``addr`` with data ``data``.
@@ -2295,7 +2356,7 @@ class CoreArchitecture(Architecture):
core.BNFreeInstructionText(tokens, count.value)
return result, result_length
- def get_instruction_low_level_il(self, data:bytes, addr:int, il:lowlevelil.LowLevelILFunction) -> Optional[int]:
+ def get_instruction_low_level_il(self, data: bytes, addr: int, il: lowlevelil.LowLevelILFunction) -> Optional[int]:
"""
``get_instruction_low_level_il`` appends lowlevelil.ExpressionIndex objects to ``il`` for the instruction at the given
virtual address ``addr`` with data ``data``.
@@ -2317,8 +2378,10 @@ class CoreArchitecture(Architecture):
return length.value
return None
- def get_flag_write_low_level_il(self, op:LowLevelILOperation, size:int, write_type:FlagWriteTypeName,
- flag:FlagType, operands:List['lowlevelil.ILRegisterType'], il:'lowlevelil.LowLevelILFunction') -> 'lowlevelil.ExpressionIndex':
+ def get_flag_write_low_level_il(
+ self, op: LowLevelILOperation, size: int, write_type: FlagWriteTypeName, flag: FlagType,
+ operands: List['lowlevelil.ILRegisterType'], il: 'lowlevelil.LowLevelILFunction'
+ ) -> 'lowlevelil.ExpressionIndex':
"""
:param LowLevelILOperation op:
:param int size:
@@ -2341,11 +2404,16 @@ class CoreArchitecture(Architecture):
else:
operand_list[i].constant = True
operand_list[i].value = operand
- return lowlevelil.ExpressionIndex(core.BNGetArchitectureFlagWriteLowLevelIL(self.handle, op, size,
- self._flag_write_types[write_type], flag, operand_list, len(operand_list), il.handle))
+ return lowlevelil.ExpressionIndex(
+ core.BNGetArchitectureFlagWriteLowLevelIL(
+ self.handle, op, size, self._flag_write_types[write_type], flag, operand_list, len(operand_list),
+ il.handle
+ )
+ )
- def get_flag_condition_low_level_il(self, cond:LowLevelILFlagCondition, sem_class:SemanticClassType,
- il:'lowlevelil.LowLevelILFunction') -> 'lowlevelil.ExpressionIndex':
+ def get_flag_condition_low_level_il(
+ self, cond: LowLevelILFlagCondition, sem_class: SemanticClassType, il: 'lowlevelil.LowLevelILFunction'
+ ) -> 'lowlevelil.ExpressionIndex':
"""
:param LowLevelILFlagCondition cond: Flag condition to be computed
:param str sem_class: Semantic class to be used (None for default semantics)
@@ -2353,20 +2421,24 @@ class CoreArchitecture(Architecture):
:rtype: ExpressionIndex
"""
class_index = self.get_semantic_flag_class_index(sem_class)
- return lowlevelil.ExpressionIndex(core.BNGetArchitectureFlagConditionLowLevelIL(self.handle, cond,
- class_index, il.handle))
+ return lowlevelil.ExpressionIndex(
+ core.BNGetArchitectureFlagConditionLowLevelIL(self.handle, cond, class_index, il.handle)
+ )
- def get_semantic_flag_group_low_level_il(self, sem_group:SemanticGroupName,
- il:'lowlevelil.LowLevelILFunction') -> 'lowlevelil.ExpressionIndex':
+ def get_semantic_flag_group_low_level_il(
+ self, sem_group: SemanticGroupName, il: 'lowlevelil.LowLevelILFunction'
+ ) -> 'lowlevelil.ExpressionIndex':
"""
:param str sem_group:
:param LowLevelILFunction il:
:rtype: ExpressionIndex
"""
group_index = self.get_semantic_flag_group_index(sem_group)
- return lowlevelil.ExpressionIndex(core.BNGetArchitectureSemanticFlagGroupLowLevelIL(self.handle, group_index, il.handle))
+ return lowlevelil.ExpressionIndex(
+ core.BNGetArchitectureSemanticFlagGroupLowLevelIL(self.handle, group_index, il.handle)
+ )
- def assemble(self, code:str, addr:int=0) -> bytes:
+ def assemble(self, code: str, addr: int = 0) -> bytes:
"""
``assemble`` converts the string of assembly instructions ``code`` loaded at virtual address ``addr`` to the
byte representation of those instructions.
@@ -2389,7 +2461,7 @@ class CoreArchitecture(Architecture):
raise ValueError(f"Could not assemble: {error_str}")
return bytes(result)
- def is_never_branch_patch_available(self, data:bytes, addr:int=0) -> bool:
+ def is_never_branch_patch_available(self, data: bytes, addr: int = 0) -> bool:
"""
``is_never_branch_patch_available`` determines if the instruction ``data`` at ``addr`` can be made to **never branch**.
@@ -2409,7 +2481,7 @@ class CoreArchitecture(Architecture):
ctypes.memmove(buf, data, len(data))
return core.BNIsArchitectureNeverBranchPatchAvailable(self.handle, buf, addr, len(data))
- def is_always_branch_patch_available(self, data:bytes, addr:int=0) -> bool:
+ def is_always_branch_patch_available(self, data: bytes, addr: int = 0) -> bool:
"""
``is_always_branch_patch_available`` determines if the instruction ``data`` at ``addr`` can be made to
**always branch**.
@@ -2430,7 +2502,7 @@ class CoreArchitecture(Architecture):
ctypes.memmove(buf, data, len(data))
return core.BNIsArchitectureAlwaysBranchPatchAvailable(self.handle, buf, addr, len(data))
- def is_invert_branch_patch_available(self, data:bytes, addr:int=0) -> bool:
+ def is_invert_branch_patch_available(self, data: bytes, addr: int = 0) -> bool:
"""
``is_always_branch_patch_available`` determines if the instruction ``data`` at ``addr`` can be inverted.
@@ -2450,7 +2522,7 @@ class CoreArchitecture(Architecture):
ctypes.memmove(buf, data, len(data))
return core.BNIsArchitectureInvertBranchPatchAvailable(self.handle, buf, addr, len(data))
- def is_skip_and_return_zero_patch_available(self, data:bytes, addr:int=0) -> bool:
+ def is_skip_and_return_zero_patch_available(self, data: bytes, addr: int = 0) -> bool:
"""
``is_skip_and_return_zero_patch_available`` determines if the instruction ``data`` at ``addr`` is a *call-like*
instruction that can be made into an instruction *returns zero*.
@@ -2473,7 +2545,7 @@ class CoreArchitecture(Architecture):
ctypes.memmove(buf, data, len(data))
return core.BNIsArchitectureSkipAndReturnZeroPatchAvailable(self.handle, buf, addr, len(data))
- def is_skip_and_return_value_patch_available(self, data:bytes, addr:int=0) -> bool:
+ def is_skip_and_return_value_patch_available(self, data: bytes, addr: int = 0) -> bool:
"""
``is_skip_and_return_value_patch_available`` determines if the instruction ``data`` at ``addr`` is a *call-like*
instruction that can be made into an instruction *returns a value*.
@@ -2494,7 +2566,7 @@ class CoreArchitecture(Architecture):
ctypes.memmove(buf, data, len(data))
return core.BNIsArchitectureSkipAndReturnValuePatchAvailable(self.handle, buf, addr, len(data))
- def convert_to_nop(self, data:bytes, addr:int=0) -> Optional[bytes]:
+ def convert_to_nop(self, data: bytes, addr: int = 0) -> Optional[bytes]:
"""
``convert_to_nop`` reads the instruction(s) in ``data`` at virtual address ``addr`` and returns a string of nop
instructions of the same length as data.
@@ -2517,7 +2589,7 @@ class CoreArchitecture(Architecture):
ctypes.memmove(result, buf, len(data))
return result.raw
- def always_branch(self, data:bytes, addr:int=0) -> Optional[bytes]:
+ def always_branch(self, data: bytes, addr: int = 0) -> Optional[bytes]:
"""
``always_branch`` reads the instruction(s) in ``data`` at virtual address ``addr`` and returns a string of bytes
of the same length which always branches.
@@ -2543,7 +2615,7 @@ class CoreArchitecture(Architecture):
ctypes.memmove(result, buf, len(data))
return result.raw
- def invert_branch(self, data:bytes, addr:int=0) -> Optional[bytes]:
+ def invert_branch(self, data: bytes, addr: int = 0) -> Optional[bytes]:
"""
``invert_branch`` reads the instruction(s) in ``data`` at virtual address ``addr`` and returns a string of bytes
of the same length which inverts the branch of provided instruction.
@@ -2570,7 +2642,7 @@ class CoreArchitecture(Architecture):
ctypes.memmove(result, buf, len(data))
return result.raw
- def skip_and_return_value(self, data:bytes, addr:int, value:int) -> Optional[bytes]:
+ def skip_and_return_value(self, data: bytes, addr: int, value: int) -> Optional[bytes]:
"""
``skip_and_return_value`` reads the instruction(s) in ``data`` at virtual address ``addr`` and returns a string of
bytes of the same length which doesn't call and instead *return a value*.
@@ -2594,7 +2666,7 @@ class CoreArchitecture(Architecture):
ctypes.memmove(result, buf, len(data))
return result.raw
- def get_flag_role(self, flag:FlagIndex, sem_class:Optional[SemanticClassIndex]= None) -> FlagRole:
+ def get_flag_role(self, flag: FlagIndex, sem_class: Optional[SemanticClassIndex] = None) -> FlagRole:
"""
``get_flag_role`` gets the role of a given flag.
@@ -2607,8 +2679,9 @@ class CoreArchitecture(Architecture):
_sem_class = self.get_semantic_flag_class_index(sem_class)
return FlagRole(core.BNGetArchitectureFlagRole(self.handle, flag, _sem_class))
- def get_flags_required_for_flag_condition(self, cond:LowLevelILFlagCondition,
- sem_class:Optional[SemanticClassType]=None) -> List[FlagName]:
+ def get_flags_required_for_flag_condition(
+ self, cond: LowLevelILFlagCondition, sem_class: Optional[SemanticClassType] = None
+ ) -> List[FlagName]:
_sem_class = self.get_semantic_flag_class_index(sem_class)
count = ctypes.c_ulonglong()
flags = core.BNGetArchitectureFlagsRequiredForFlagCondition(self.handle, cond, _sem_class, count)
@@ -2621,7 +2694,7 @@ class CoreArchitecture(Architecture):
class ArchitectureHook(CoreArchitecture):
- def __init__(self, base_arch:'Architecture'):
+ def __init__(self, base_arch: 'Architecture'):
self._base_arch = base_arch
super(ArchitectureHook, self).__init__(base_arch.handle)
@@ -2659,9 +2732,10 @@ class ArchitectureHook(CoreArchitecture):
return self._base_arch
@base_arch.setter
- def base_arch(self, value:'Architecture') -> None:
+ def base_arch(self, value: 'Architecture') -> None:
self._base_arch = value
+
@dataclass
class InstructionTextToken:
"""
@@ -2711,24 +2785,25 @@ class InstructionTextToken:
========================== ============================================
"""
- type:Union[InstructionTextTokenType, int]
- text:str
- value:int = 0
- size:int = 0
- operand:int = 0xffffffff
- context:InstructionTextTokenContext = InstructionTextTokenContext.NoTokenContext
- address:int = 0
- confidence:int = core.max_confidence
- typeNames:List[str] = field(default_factory=list)
- width:int = 0
+ type: Union[InstructionTextTokenType, int]
+ text: str
+ value: int = 0
+ size: int = 0
+ operand: int = 0xffffffff
+ context: InstructionTextTokenContext = InstructionTextTokenContext.NoTokenContext
+ address: int = 0
+ confidence: int = core.max_confidence
+ typeNames: List[str] = field(default_factory=list)
+ width: int = 0
def __post_init__(self):
if self.width == 0:
self.width = len(self.text)
@staticmethod
- def _from_core_struct(tokens:'ctypes.pointer[core.BNInstructionTextToken]', count:int) -> List['InstructionTextToken']:
- result:List['InstructionTextToken'] = []
+ def _from_core_struct(tokens: 'ctypes.pointer[core.BNInstructionTextToken]',
+ count: int) -> List['InstructionTextToken']:
+ result: List['InstructionTextToken'] = []
for j in range(count):
token_type = InstructionTextTokenType(tokens[j].type)
text = tokens[j].text
@@ -2747,11 +2822,15 @@ class InstructionTextToken:
typeNames.append(tokens[j].typeNames[i].decode("utf-8"))
else:
typeNames.append(tokens[j].typeNames[i])
- result.append(InstructionTextToken(token_type, text, value, size, operand, context, address, confidence, typeNames, width))
+ result.append(
+ InstructionTextToken(
+ token_type, text, value, size, operand, context, address, confidence, typeNames, width
+ )
+ )
return result
@staticmethod
- def _get_core_struct(tokens:List['InstructionTextToken']) -> 'ctypes.Array[core.BNInstructionTextToken]':
+ def _get_core_struct(tokens: List['InstructionTextToken']) -> 'ctypes.Array[core.BNInstructionTextToken]':
""" Helper method for converting between core.BNInstructionTextToken and InstructionTextToken lists """
result = (core.BNInstructionTextToken * len(tokens))()
for j in range(len(tokens)):
diff --git a/python/associateddatastore.py b/python/associateddatastore.py
index 256437a0..66434d56 100644
--- a/python/associateddatastore.py
+++ b/python/associateddatastore.py
@@ -21,14 +21,15 @@
import copy
from typing import Any
+
class _AssociatedDataStore(dict):
_defaults = {}
@classmethod
- def set_default(cls, name:str, value:Any):
+ def set_default(cls, name: str, value: Any):
cls._defaults[name] = value
- def __getattr__(self, name:str) -> Any:
+ def __getattr__(self, name: str) -> Any:
if name in self.__dict__:
return self.__dict__[name]
if name not in self:
@@ -38,8 +39,8 @@ class _AssociatedDataStore(dict):
return result
return self.__getitem__(name)
- def __setattr__(self, name:str, value:Any):
+ def __setattr__(self, name: str, value: Any):
self.__setitem__(name, value)
- def __delattr__(self, name:str):
+ def __delattr__(self, name: str):
self.__delitem__(name)
diff --git a/python/basicblock.py b/python/basicblock.py
index d504933b..24f549d7 100644
--- a/python/basicblock.py
+++ b/python/basicblock.py
@@ -30,13 +30,14 @@ from . import architecture
from . import highlight as _highlight
from . import function as _function
+
@dataclass(frozen=True)
class BasicBlockEdge:
- type:BranchType
- source:'BasicBlock'
- target:'BasicBlock'
- back_edge:bool
- fall_through:bool
+ type: BranchType
+ source: 'BasicBlock'
+ target: 'BasicBlock'
+ back_edge: bool
+ fall_through: bool
def __repr__(self):
if self.type == BranchType.UnresolvedBranch:
@@ -48,14 +49,14 @@ class BasicBlockEdge:
class BasicBlock:
- def __init__(self, handle:core.BNBasicBlockHandle, view:Optional['binaryview.BinaryView']=None):
+ def __init__(self, handle: core.BNBasicBlockHandle, view: Optional['binaryview.BinaryView'] = None):
self._view = view
_handle = core.BNBasicBlockHandle
- self.handle:core.BNBasicBlockHandle = ctypes.cast(handle, _handle)
+ self.handle: core.BNBasicBlockHandle = ctypes.cast(handle, _handle)
self._arch = None
self._func = None
- self._instStarts:Optional[List[int]] = None
- self._instLengths:Optional[List[int]] = None
+ self._instStarts: Optional[List[int]] = None
+ self._instLengths: Optional[List[int]] = None
def __del__(self):
if core is not None:
@@ -129,7 +130,7 @@ class BasicBlock:
data = self.view.read(start, length)
return self.arch.get_instruction_text(data, start)
- def __contains__(self, i:int):
+ def __contains__(self, i: int):
return self.start <= i < self.end
def _buildStartCache(self) -> None:
@@ -142,13 +143,13 @@ class BasicBlock:
start = self.start
while start < self.end:
length = self.view.get_instruction_length(start, self.arch)
- if length == 0: # invalid instruction. avoid infinite loop
+ if length == 0: # invalid instruction. avoid infinite loop
break
self._instLengths.append(length)
self._instStarts.append(start)
start += length
- def _create_instance(self, handle:core.BNBasicBlockHandle, view:'binaryview.BinaryView') -> 'BasicBlock':
+ def _create_instance(self, handle: core.BNBasicBlockHandle, view: 'binaryview.BinaryView') -> 'BasicBlock':
"""Internal method used to instantiate child instances"""
return BasicBlock(handle, view)
@@ -220,12 +221,11 @@ class BasicBlock:
"""Basic block index in list of blocks for the function (read-only)"""
return core.BNGetBasicBlockIndex(self.handle)
-
- def _make_edges(self, edges, count:int, direction:bool) -> List[BasicBlockEdge]:
+ def _make_edges(self, edges, count: int, direction: bool) -> List[BasicBlockEdge]:
assert edges is not None, "Got empty edges list from core"
if self.view is None:
raise ValueError("Attempting to get BasicBlock edges when BinaryView is None")
- result:List[BasicBlockEdge] = []
+ result: List[BasicBlockEdge] = []
try:
for i in range(0, count):
branch_type = BranchType(edges[i].type)
@@ -241,7 +241,6 @@ class BasicBlock:
finally:
core.BNFreeBasicBlockEdgeList(edges, count)
-
@property
def outgoing_edges(self) -> List[BasicBlockEdge]:
"""List of basic block outgoing edges (read-only)"""
@@ -254,7 +253,6 @@ class BasicBlock:
count = ctypes.c_ulonglong(0)
return self._make_edges(core.BNGetBasicBlockIncomingEdges(self.handle, count), count.value, True)
-
@property
def has_undetermined_outgoing_edges(self) -> bool:
"""Whether basic block has undetermined outgoing edges (read-only)"""
@@ -266,7 +264,7 @@ class BasicBlock:
return core.BNBasicBlockCanExit(self.handle)
@can_exit.setter
- def can_exit(self, value:bool) -> None:
+ def can_exit(self, value: bool) -> None:
"""Sets whether basic block can return or is tagged as 'No Return'"""
core.BNBasicBlockSetCanExit(self.handle, value)
@@ -275,9 +273,9 @@ class BasicBlock:
"""Whether basic block has any invalid instructions (read-only)"""
return core.BNBasicBlockHasInvalidInstructions(self.handle)
- def _make_blocks(self, blocks, count:int) -> List['BasicBlock']:
+ def _make_blocks(self, blocks, count: int) -> List['BasicBlock']:
assert blocks is not None, "core returned empty block list"
- result:List['BasicBlock'] = []
+ result: List['BasicBlock'] = []
try:
for i in range(0, count):
handle = core.BNNewBasicBlockReference(blocks[i])
@@ -295,12 +293,11 @@ class BasicBlock:
count = ctypes.c_ulonglong()
return self._make_blocks(core.BNGetBasicBlockDominators(self.handle, count, False), count.value)
-
@property
def post_dominators(self) -> List['BasicBlock']:
"""List of dominators for this basic block (read-only)"""
if self.view is None:
- raise Exception("Attempting to call BasicBlock.post_dominators when BinaryView is None")
+ raise Exception("Attempting to call BasicBlock.post_dominators when BinaryView is None")
count = ctypes.c_ulonglong()
return self._make_blocks(core.BNGetBasicBlockDominators(self.handle, count, True), count.value)
@@ -403,7 +400,7 @@ class BasicBlock:
return _highlight.HighlightColor._from_core_struct(core.BNGetBasicBlockHighlight(self.handle))
@highlight.setter
- def highlight(self, value:'_highlight.HighlightColor') -> None:
+ def highlight(self, value: '_highlight.HighlightColor') -> None:
self.set_user_highlight(value)
@property
@@ -427,10 +424,10 @@ class BasicBlock:
return core.BNIsHighLevelILBasicBlock(self.handle)
@staticmethod
- def get_iterated_dominance_frontier(blocks:List['BasicBlock']) -> List['BasicBlock']:
+ def get_iterated_dominance_frontier(blocks: List['BasicBlock']) -> List['BasicBlock']:
if len(blocks) == 0:
return []
- block_set = (ctypes.POINTER(core.BNBasicBlock) * len(blocks))() # type: ignore
+ block_set = (ctypes.POINTER(core.BNBasicBlock) * len(blocks))() # type: ignore
for i in range(len(blocks)):
block_set[i] = blocks[i].handle
count = ctypes.c_ulonglong()
@@ -449,7 +446,8 @@ class BasicBlock:
def mark_recent_use(self) -> None:
core.BNMarkBasicBlockAsRecentlyUsed(self.handle)
- def get_disassembly_text(self, settings:'_function.DisassemblySettings'=None) -> List['_function.DisassemblyTextLine']:
+ def get_disassembly_text(self,
+ settings: '_function.DisassemblySettings' = None) -> List['_function.DisassemblyTextLine']:
"""
``get_disassembly_text`` returns a list of DisassemblyTextLine objects for the current basic block.
@@ -471,7 +469,7 @@ class BasicBlock:
for i in range(0, count.value):
addr = lines[i].addr
if (lines[i].instrIndex != 0xffffffffffffffff) and hasattr(self, 'il_function'):
- il_instr = self.il_function[lines[i].instrIndex] # type: ignore
+ il_instr = self.il_function[lines[i].instrIndex] # type: ignore
else:
il_instr = None
color = _highlight.HighlightColor._from_core_struct(lines[i].highlight)
@@ -481,7 +479,7 @@ class BasicBlock:
finally:
core.BNFreeDisassemblyTextLines(lines, count.value)
- def set_auto_highlight(self, color:'_highlight.HighlightColor') -> None:
+ def set_auto_highlight(self, color: '_highlight.HighlightColor') -> None:
"""
``set_auto_highlight`` highlights the current BasicBlock with the supplied color.
@@ -495,7 +493,7 @@ class BasicBlock:
color = _highlight.HighlightColor(color)
core.BNSetAutoBasicBlockHighlight(self.handle, color._to_core_struct())
- def set_user_highlight(self, color:'_highlight.HighlightColor') -> None:
+ def set_user_highlight(self, color: '_highlight.HighlightColor') -> None:
"""
``set_user_highlight`` highlights the current BasicBlock with the supplied color
@@ -511,7 +509,7 @@ class BasicBlock:
color = _highlight.HighlightColor(color)
core.BNSetUserBasicBlockHighlight(self.handle, color._to_core_struct())
- def get_instruction_containing_address(self, addr:int) -> Tuple[bool, int]:
+ def get_instruction_containing_address(self, addr: int) -> Tuple[bool, int]:
start = ctypes.c_uint64()
- ret:bool = core.BNGetBasicBlockInstructionContainingAddress(self.handle, addr, start)
+ ret: bool = core.BNGetBasicBlockInstructionContainingAddress(self.handle, addr, start)
return ret, start.value
diff --git a/python/binaryview.py b/python/binaryview.py
index acc437c7..ce9cca92 100644
--- a/python/binaryview.py
+++ b/python/binaryview.py
@@ -34,15 +34,14 @@ from dataclasses import dataclass
import collections
from collections import defaultdict, OrderedDict, deque
-
# Binary Ninja components
import binaryninja
from . import _binaryninjacore as core
-from .enums import (AnalysisState, SymbolType,
- Endianness, ModificationStatus, StringType, SegmentFlag, SectionSemantics, FindFlag,
- TypeClass, BinaryViewEventType, FunctionGraphType, TagReferenceType, TagTypeType,
- RegisterValueType)
-from . import associateddatastore # required for _BinaryViewAssociatedDataStore
+from .enums import (
+ AnalysisState, SymbolType, Endianness, ModificationStatus, StringType, SegmentFlag, SectionSemantics, FindFlag,
+ TypeClass, BinaryViewEventType, FunctionGraphType, TagReferenceType, TagTypeType, RegisterValueType
+)
+from . import associateddatastore # required for _BinaryViewAssociatedDataStore
from .log import log_error, log_warn
from . import typelibrary
from . import fileaccessor
@@ -67,7 +66,6 @@ from . import function as _function
from . import types as _types
from . import platform as _platform
-
PathType = Union[str, os.PathLike]
InstructionsType = Generator[Tuple[List['_function.InstructionTextToken'], int], None, None]
NotificationType = Mapping['BinaryDataNotification', 'BinaryDataNotificationCallbacks']
@@ -76,14 +74,16 @@ DataMatchCallbackType = Callable[[int, 'databuffer.DataBuffer'], bool]
LineMatchCallbackType = Callable[[int, 'lineardisassembly.LinearDisassemblyLine'], bool]
StringOrType = Union[str, '_types.Type', '_types.TypeBuilder']
+
class RelocationWriteException(Exception):
pass
+
@dataclass(frozen=True)
class ReferenceSource:
- function:Optional['_function.Function']
- arch:Optional['architecture.Architecture']
- address:int
+ function: Optional['_function.Function']
+ arch: Optional['architecture.Architecture']
+ address: int
def __repr__(self):
if self.arch:
@@ -92,7 +92,7 @@ class ReferenceSource:
return f"<ref: {self.address:#x}>"
@classmethod
- def _from_core_struct(cls, view:'BinaryView', ref:core.BNReferenceSource) -> 'ReferenceSource':
+ def _from_core_struct(cls, view: 'BinaryView', ref: core.BNReferenceSource) -> 'ReferenceSource':
if ref.func:
func = _function.Function(view, core.BNNewFunctionReference(ref.func))
else:
@@ -109,89 +109,95 @@ class BinaryDataNotification:
def __init__(self):
pass
- def data_written(self, view:'BinaryView', offset:int, length:int) -> None:
+ def data_written(self, view: 'BinaryView', offset: int, length: int) -> None:
pass
- def data_inserted(self, view:'BinaryView', offset:int, length:int) -> None:
+ def data_inserted(self, view: 'BinaryView', offset: int, length: int) -> None:
pass
- def data_removed(self, view:'BinaryView', offset:int, length:int) -> None:
+ def data_removed(self, view: 'BinaryView', offset: int, length: int) -> None:
pass
- def function_added(self, view:'BinaryView', func:'_function.Function') -> None:
+ def function_added(self, view: 'BinaryView', func: '_function.Function') -> None:
pass
- def function_removed(self, view:'BinaryView', func:'_function.Function') -> None:
+ def function_removed(self, view: 'BinaryView', func: '_function.Function') -> None:
pass
- def function_updated(self, view:'BinaryView', func:'_function.Function') -> None:
+ def function_updated(self, view: 'BinaryView', func: '_function.Function') -> None:
pass
- def function_update_requested(self, view:'BinaryView', func:'_function.Function') -> None:
+ def function_update_requested(self, view: 'BinaryView', func: '_function.Function') -> None:
pass
- def data_var_added(self, view:'BinaryView', var:'DataVariable') -> None:
+ def data_var_added(self, view: 'BinaryView', var: 'DataVariable') -> None:
pass
- def data_var_removed(self, view:'BinaryView', var:'DataVariable') -> None:
+ def data_var_removed(self, view: 'BinaryView', var: 'DataVariable') -> None:
pass
- def data_var_updated(self, view:'BinaryView', var:'DataVariable') -> None:
+ def data_var_updated(self, view: 'BinaryView', var: 'DataVariable') -> None:
pass
- def data_metadata_updated(self, view:'BinaryView', offset:int) -> None:
+ def data_metadata_updated(self, view: 'BinaryView', offset: int) -> None:
pass
- def tag_type_updated(self, view:'BinaryView', tag_type) -> None:
+ def tag_type_updated(self, view: 'BinaryView', tag_type) -> None:
pass
- def tag_added(self, view:'BinaryView', tag:'Tag', ref_type:TagReferenceType, auto_defined:bool,
- arch:Optional['architecture.Architecture'], func:Optional[_function.Function], addr:int) -> None:
+ def tag_added(
+ self, view: 'BinaryView', tag: 'Tag', ref_type: TagReferenceType, auto_defined: bool,
+ arch: Optional['architecture.Architecture'], func: Optional[_function.Function], addr: int
+ ) -> None:
pass
- def tag_updated(self, view:'BinaryView', tag:'Tag', ref_type:TagReferenceType, auto_defined:bool,
- arch:Optional['architecture.Architecture'], func:Optional[_function.Function], addr:int) -> None:
+ def tag_updated(
+ self, view: 'BinaryView', tag: 'Tag', ref_type: TagReferenceType, auto_defined: bool,
+ arch: Optional['architecture.Architecture'], func: Optional[_function.Function], addr: int
+ ) -> None:
pass
- def tag_removed(self, view:'BinaryView', tag:'Tag', ref_type:TagReferenceType, auto_defined:bool,
- arch:Optional['architecture.Architecture'], func:Optional[_function.Function], addr:int) -> None:
+ def tag_removed(
+ self, view: 'BinaryView', tag: 'Tag', ref_type: TagReferenceType, auto_defined: bool,
+ arch: Optional['architecture.Architecture'], func: Optional[_function.Function], addr: int
+ ) -> None:
pass
- def symbol_added(self, view:'BinaryView', sym:'_types.CoreSymbol') -> None:
+ def symbol_added(self, view: 'BinaryView', sym: '_types.CoreSymbol') -> None:
pass
- def symbol_updated(self, view:'BinaryView', sym:'_types.CoreSymbol') -> None:
+ def symbol_updated(self, view: 'BinaryView', sym: '_types.CoreSymbol') -> None:
pass
- def symbol_removed(self, view:'BinaryView', sym:'_types.CoreSymbol') -> None:
+ def symbol_removed(self, view: 'BinaryView', sym: '_types.CoreSymbol') -> None:
pass
- def string_found(self, view:'BinaryView', string_type:StringType, offset:int, length:int) -> None:
+ def string_found(self, view: 'BinaryView', string_type: StringType, offset: int, length: int) -> None:
pass
- def string_removed(self, view:'BinaryView', string_type:StringType, offset:int, length:int) -> None:
+ def string_removed(self, view: 'BinaryView', string_type: StringType, offset: int, length: int) -> None:
pass
- def type_defined(self, view:'BinaryView', name:'_types.QualifiedName', type:'_types.Type') -> None:
+ def type_defined(self, view: 'BinaryView', name: '_types.QualifiedName', type: '_types.Type') -> None:
pass
- def type_undefined(self, view:'BinaryView', name:'_types.QualifiedName', type:'_types.Type') -> None:
+ def type_undefined(self, view: 'BinaryView', name: '_types.QualifiedName', type: '_types.Type') -> None:
pass
- def type_ref_changed(self, view:'BinaryView', name:'_types.QualifiedName', type:'_types.Type') -> None:
+ def type_ref_changed(self, view: 'BinaryView', name: '_types.QualifiedName', type: '_types.Type') -> None:
pass
- def type_field_ref_changed(self, view:'BinaryView', name:'_types.QualifiedName', offset: int) -> None:
+ def type_field_ref_changed(self, view: 'BinaryView', name: '_types.QualifiedName', offset: int) -> None:
pass
+
class StringReference:
_decodings = {
- StringType.AsciiString: "ascii",
- StringType.Utf8String: "utf-8",
- StringType.Utf16String: "utf-16",
- StringType.Utf32String: "utf-32",
+ StringType.AsciiString: "ascii", StringType.Utf8String: "utf-8", StringType.Utf16String: "utf-16",
+ StringType.Utf32String: "utf-32",
}
- def __init__(self, bv:'BinaryView', string_type:StringType, start:int, length:int):
+
+ def __init__(self, bv: 'BinaryView', string_type: StringType, start: int, length: int):
self._type = string_type
self._start = start
self._length = length
@@ -219,7 +225,7 @@ class StringReference:
return self._type
@type.setter
- def type(self, value:StringType) -> None:
+ def type(self, value: StringType) -> None:
self._type = value
@property
@@ -227,7 +233,7 @@ class StringReference:
return self._start
@start.setter
- def start(self, value:int) -> None:
+ def start(self, value: int) -> None:
self._start = value
@property
@@ -254,7 +260,10 @@ class AnalysisCompletionEvent:
>>>
"""
_pending_analysis_completion_events = {}
- def __init__(self, view:'BinaryView', callback:Union[Callable[['AnalysisCompletionEvent'], None], Callable[[], None]]):
+
+ def __init__(
+ self, view: 'BinaryView', callback: Union[Callable[['AnalysisCompletionEvent'], None], Callable[[], None]]
+ ):
self._view = view
self.callback = callback
self._cb = ctypes.CFUNCTYPE(None, ctypes.c_void_p)(self._notify)
@@ -274,9 +283,9 @@ class AnalysisCompletionEvent:
arg_offset = inspect.ismethod(self.callback)
callback_spec = inspect.getargspec(self.callback)
if len(callback_spec.args) > arg_offset:
- self.callback(self) # type: ignore
+ self.callback(self) # type: ignore
else:
- self.callback() # type: ignore
+ self.callback() # type: ignore
except:
log_error(traceback.format_exc())
@@ -300,7 +309,7 @@ class AnalysisCompletionEvent:
return self._view
@view.setter
- def view(self, value:'BinaryView') -> None:
+ def view(self, value: 'BinaryView') -> None:
self._view = value
@@ -331,16 +340,18 @@ class BinaryViewEvent:
_binaryview_events = {}
@classmethod
- def register(cls, event_type:BinaryViewEventType, callback:BinaryViewEventCallback) -> None:
- callback_obj = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView))(lambda ctxt, view: cls._notify(view, callback))
+ def register(cls, event_type: BinaryViewEventType, callback: BinaryViewEventCallback) -> None:
+ callback_obj = ctypes.CFUNCTYPE(None, ctypes.c_void_p,
+ ctypes.POINTER(core.BNBinaryView
+ ))(lambda ctxt, view: cls._notify(view, callback))
core.BNRegisterBinaryViewEvent(event_type, callback_obj, None)
cls._binaryview_events[len(cls._binaryview_events)] = callback_obj
@staticmethod
- def _notify(view:core.BNBinaryView, callback:BinaryViewEventCallback) -> None:
+ def _notify(view: core.BNBinaryView, callback: BinaryViewEventCallback) -> None:
try:
- file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
- view_obj = BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
+ file_metadata = filemetadata.FileMetadata(handle=core.BNGetFileForView(view))
+ view_obj = BinaryView(file_metadata=file_metadata, handle=core.BNNewViewReference(view))
callback(view_obj)
except:
log_error(traceback.format_exc())
@@ -348,10 +359,10 @@ class BinaryViewEvent:
@dataclass(frozen=True)
class ActiveAnalysisInfo:
- func:'_function.Function'
- analysis_time:int
- update_count:int
- submit_count:int
+ func: '_function.Function'
+ analysis_time: int
+ update_count: int
+ submit_count: int
def __repr__(self):
return f"<ActiveAnalysisInfo {self.func}, analysis_time {self.analysis_time}, update_count {self.update_count}, submit_count {self.submit_count}>"
@@ -359,9 +370,9 @@ class ActiveAnalysisInfo:
@dataclass(frozen=True)
class AnalysisInfo:
- state:AnalysisState
- analysis_time:int
- active_info:List[ActiveAnalysisInfo]
+ state: AnalysisState
+ analysis_time: int
+ active_info: List[ActiveAnalysisInfo]
def __repr__(self):
return f"<AnalysisInfo {self.state}, analysis_time {self.analysis_time}, active_info {len(self.active_info)}>"
@@ -369,9 +380,9 @@ class AnalysisInfo:
@dataclass(frozen=True)
class AnalysisProgress:
- state:AnalysisState
- count:int
- total:int
+ state: AnalysisState
+ count: int
+ total: int
def __str__(self):
if self.state == AnalysisState.InitialState:
@@ -391,7 +402,7 @@ class AnalysisProgress:
class BinaryDataNotificationCallbacks:
- def __init__(self, view:'BinaryView', notify:'BinaryDataNotification'):
+ def __init__(self, view: 'BinaryView', notify: 'BinaryDataNotification'):
self._view = view
self._notify = notify
self._cb = core.BNBinaryDataNotification()
@@ -427,73 +438,75 @@ class BinaryDataNotificationCallbacks:
def _unregister(self) -> None:
core.BNUnregisterDataNotification(self._view.handle, self._cb)
- def _data_written(self, ctxt, view:core.BNBinaryView, offset:int, length:int) -> None:
+ def _data_written(self, ctxt, view: core.BNBinaryView, offset: int, length: int) -> None:
try:
self._notify.data_written(self._view, offset, length)
except OSError:
log_error(traceback.format_exc())
- def _data_inserted(self, ctxt, view:core.BNBinaryView, offset:int, length:int) -> None:
+ def _data_inserted(self, ctxt, view: core.BNBinaryView, offset: int, length: int) -> None:
try:
self._notify.data_inserted(self._view, offset, length)
except:
log_error(traceback.format_exc())
- def _data_removed(self, ctxt, view:core.BNBinaryView, offset:int, length:int) -> None:
+ def _data_removed(self, ctxt, view: core.BNBinaryView, offset: int, length: int) -> None:
try:
self._notify.data_removed(self._view, offset, length)
except:
log_error(traceback.format_exc())
- def _function_added(self, ctxt, view:core.BNBinaryView, func:core.BNFunction) -> None:
+ def _function_added(self, ctxt, view: core.BNBinaryView, func: core.BNFunction) -> None:
try:
self._notify.function_added(self._view, _function.Function(self._view, core.BNNewFunctionReference(func)))
except:
log_error(traceback.format_exc())
- def _function_removed(self, ctxt, view:core.BNBinaryView, func:core.BNFunction) -> None:
+ def _function_removed(self, ctxt, view: core.BNBinaryView, func: core.BNFunction) -> None:
try:
self._notify.function_removed(self._view, _function.Function(self._view, core.BNNewFunctionReference(func)))
except:
log_error(traceback.format_exc())
- def _function_updated(self, ctxt, view:core.BNBinaryView, func:core.BNFunction) -> None:
+ def _function_updated(self, ctxt, view: core.BNBinaryView, func: core.BNFunction) -> None:
try:
self._notify.function_updated(self._view, _function.Function(self._view, core.BNNewFunctionReference(func)))
except:
log_error(traceback.format_exc())
- def _function_update_requested(self, ctxt, view:core.BNBinaryView, func:core.BNFunction) -> None:
+ def _function_update_requested(self, ctxt, view: core.BNBinaryView, func: core.BNFunction) -> None:
try:
- self._notify.function_update_requested(self._view, _function.Function(self._view, core.BNNewFunctionReference(func)))
+ self._notify.function_update_requested(
+ self._view, _function.Function(self._view, core.BNNewFunctionReference(func))
+ )
except:
log_error(traceback.format_exc())
- def _data_var_added(self, ctxt, view:core.BNBinaryView, var:core.BNDataVariable) -> None:
+ def _data_var_added(self, ctxt, view: core.BNBinaryView, var: core.BNDataVariable) -> None:
try:
self._notify.data_var_added(self._view, DataVariable.from_core_struct(var[0], self._view))
except:
log_error(traceback.format_exc())
- def _data_var_removed(self, ctxt, view:core.BNBinaryView, var:core.BNDataVariable) -> None:
+ def _data_var_removed(self, ctxt, view: core.BNBinaryView, var: core.BNDataVariable) -> None:
try:
self._notify.data_var_removed(self._view, DataVariable.from_core_struct(var[0], self._view))
except:
log_error(traceback.format_exc())
- def _data_var_updated(self, ctxt, view:core.BNBinaryView, var:core.BNDataVariable) -> None:
+ def _data_var_updated(self, ctxt, view: core.BNBinaryView, var: core.BNDataVariable) -> None:
try:
self._notify.data_var_updated(self._view, DataVariable.from_core_struct(var[0], self._view))
except:
log_error(traceback.format_exc())
- def _data_metadata_updated(self, ctxt, view:core.BNBinaryView, offset:int) -> None:
+ def _data_metadata_updated(self, ctxt, view: core.BNBinaryView, offset: int) -> None:
try:
self._notify.data_metadata_updated(self._view, offset)
except:
log_error(traceback.format_exc())
- def _tag_type_updated(self, ctxt, view:core.BNBinaryView, tag_type:core.BNTagType) -> None:
+ def _tag_type_updated(self, ctxt, view: core.BNBinaryView, tag_type: core.BNTagType) -> None:
try:
core_tag_type = core.BNNewTagTypeReference(tag_type)
assert core_tag_type is not None, "core.BNNewTagTypeReference returned None"
@@ -501,7 +514,7 @@ class BinaryDataNotificationCallbacks:
except:
log_error(traceback.format_exc())
- def _tag_added(self, ctxt, view:core.BNBinaryView, tag_ref:core.BNTagReference) -> None:
+ def _tag_added(self, ctxt, view: core.BNBinaryView, tag_ref: core.BNTagReference) -> None:
try:
ref_type = tag_ref[0].refType
auto_defined = tag_ref[0].autoDefined
@@ -512,7 +525,7 @@ class BinaryDataNotificationCallbacks:
if ctypes.cast(tag_ref[0].arch, ctypes.c_void_p).value is None:
arch = None
else:
- arch = architecture.CoreArchitecture._from_cache(tag_ref[0].arch)
+ arch = architecture.CoreArchitecture._from_cache(tag_ref[0].arch)
if ctypes.cast(tag_ref[0].func, ctypes.c_void_p).value is None:
func = None
else:
@@ -522,7 +535,7 @@ class BinaryDataNotificationCallbacks:
except:
log_error(traceback.format_exc())
- def _tag_updated(self, ctxt, view:core.BNBinaryView, tag_ref:core.BNTagReference) -> None:
+ def _tag_updated(self, ctxt, view: core.BNBinaryView, tag_ref: core.BNTagReference) -> None:
try:
ref_type = tag_ref[0].refType
auto_defined = tag_ref[0].autoDefined
@@ -543,7 +556,7 @@ class BinaryDataNotificationCallbacks:
except:
log_error(traceback.format_exc())
- def _tag_removed(self, ctxt, view:core.BNBinaryView, tag_ref:core.BNTagReference) -> None:
+ def _tag_removed(self, ctxt, view: core.BNBinaryView, tag_ref: core.BNTagReference) -> None:
try:
ref_type = tag_ref[0].refType
auto_defined = tag_ref[0].autoDefined
@@ -564,7 +577,7 @@ class BinaryDataNotificationCallbacks:
except:
log_error(traceback.format_exc())
- def _symbol_added(self, ctxt, view:core.BNBinaryView, sym:core.BNSymbol) -> None:
+ def _symbol_added(self, ctxt, view: core.BNBinaryView, sym: core.BNSymbol) -> None:
try:
_handle = core.BNNewSymbolReference(sym)
assert _handle is not None, "core.BNNewSymbolReference returned None"
@@ -572,7 +585,7 @@ class BinaryDataNotificationCallbacks:
except:
log_error(traceback.format_exc())
- def _symbol_updated(self, ctxt, view:core.BNBinaryView, sym:core.BNSymbol) -> None:
+ def _symbol_updated(self, ctxt, view: core.BNBinaryView, sym: core.BNSymbol) -> None:
try:
_handle = core.BNNewSymbolReference(sym)
assert _handle is not None, "core.BNNewSymbolReference returned None"
@@ -580,7 +593,7 @@ class BinaryDataNotificationCallbacks:
except:
log_error(traceback.format_exc())
- def _symbol_removed(self, ctxt, view:core.BNBinaryView, sym:core.BNSymbol) -> None:
+ def _symbol_removed(self, ctxt, view: core.BNBinaryView, sym: core.BNSymbol) -> None:
try:
_handle = core.BNNewSymbolReference(sym)
assert _handle is not None, "core.BNNewSymbolReference returned None"
@@ -588,40 +601,49 @@ class BinaryDataNotificationCallbacks:
except:
log_error(traceback.format_exc())
- def _string_found(self, ctxt, view:core.BNBinaryView, string_type:int, offset:int, length:int) -> None:
+ def _string_found(self, ctxt, view: core.BNBinaryView, string_type: int, offset: int, length: int) -> None:
try:
self._notify.string_found(self._view, StringType(string_type), offset, length)
except:
log_error(traceback.format_exc())
- def _string_removed(self, ctxt, view:core.BNBinaryView, string_type:int, offset:int, length:int) -> None:
+ def _string_removed(self, ctxt, view: core.BNBinaryView, string_type: int, offset: int, length: int) -> None:
try:
self._notify.string_removed(self._view, StringType(string_type), offset, length)
except:
log_error(traceback.format_exc())
- def _type_defined(self, ctxt, view:core.BNBinaryView, name:str, type_obj:'_types.Type') -> None:
+ def _type_defined(self, ctxt, view: core.BNBinaryView, name: str, type_obj: '_types.Type') -> None:
try:
qualified_name = _types.QualifiedName._from_core_struct(name[0])
- self._notify.type_defined(self._view, qualified_name, _types.Type.create(core.BNNewTypeReference(type_obj), platform = self._view.platform))
+ self._notify.type_defined(
+ self._view, qualified_name,
+ _types.Type.create(core.BNNewTypeReference(type_obj), platform=self._view.platform)
+ )
except:
log_error(traceback.format_exc())
- def _type_undefined(self, ctxt, view:core.BNBinaryView, name:str, type_obj:'_types.Type') -> None:
+ def _type_undefined(self, ctxt, view: core.BNBinaryView, name: str, type_obj: '_types.Type') -> None:
try:
qualified_name = _types.QualifiedName._from_core_struct(name[0])
- self._notify.type_undefined(self._view, qualified_name, _types.Type.create(core.BNNewTypeReference(type_obj), platform = self._view.platform))
+ self._notify.type_undefined(
+ self._view, qualified_name,
+ _types.Type.create(core.BNNewTypeReference(type_obj), platform=self._view.platform)
+ )
except:
log_error(traceback.format_exc())
- def _type_ref_changed(self, ctxt, view:core.BNBinaryView, name:str, type_obj:'_types.Type') -> None:
+ def _type_ref_changed(self, ctxt, view: core.BNBinaryView, name: str, type_obj: '_types.Type') -> None:
try:
qualified_name = _types.QualifiedName._from_core_struct(name[0])
- self._notify.type_ref_changed(self._view, qualified_name, _types.Type.create(core.BNNewTypeReference(type_obj), platform = self._view.platform))
+ self._notify.type_ref_changed(
+ self._view, qualified_name,
+ _types.Type.create(core.BNNewTypeReference(type_obj), platform=self._view.platform)
+ )
except:
log_error(traceback.format_exc())
- def _type_field_ref_changed(self, ctxt, view:core.BNBinaryView, name:str, offset:int) -> None:
+ def _type_field_ref_changed(self, ctxt, view: core.BNBinaryView, name: str, offset: int) -> None:
try:
qualified_name = _types.QualifiedName._from_core_struct(name[0])
self._notify.type_field_ref_changed(self._view, qualified_name, offset)
@@ -661,7 +683,8 @@ class _BinaryViewTypeMetaclass(type):
class BinaryViewType(metaclass=_BinaryViewTypeMetaclass):
# Used to force Python callback objects to not get garbage collected
_platform_recognizers = {}
- def __init__(self, handle:core.BNBinaryViewTypeHandle):
+
+ def __init__(self, handle: core.BNBinaryViewTypeHandle):
_handle = core.BNBinaryViewTypeHandle
self.handle = ctypes.cast(handle, _handle)
@@ -696,13 +719,13 @@ class BinaryViewType(metaclass=_BinaryViewTypeMetaclass):
"""returns if the BinaryViewType is deprecated (read-only)"""
return core.BNIsBinaryViewTypeDeprecated(self.handle)
- def create(self, data:'BinaryView') -> Optional['BinaryView']:
+ def create(self, data: 'BinaryView') -> Optional['BinaryView']:
view = core.BNCreateBinaryViewOfType(self.handle, data.handle)
if view is None:
return None
return BinaryView(file_metadata=data.file, handle=view)
- def open(self, src:PathType, file_metadata:'filemetadata.FileMetadata'=None) -> Optional['BinaryView']:
+ def open(self, src: PathType, file_metadata: 'filemetadata.FileMetadata' = None) -> Optional['BinaryView']:
"""
``open`` opens an instance of a particular BinaryViewType and returns it, or None if not possible.
@@ -717,8 +740,9 @@ class BinaryViewType(metaclass=_BinaryViewTypeMetaclass):
return self.create(data)
@classmethod
- def get_view_of_file(cls, filename:PathType, update_analysis:bool=True,
- progress_func:Optional[ProgressFuncType]=None) -> Optional['BinaryView']:
+ def get_view_of_file(
+ cls, filename: PathType, update_analysis: bool = True, progress_func: Optional[ProgressFuncType] = None
+ ) -> Optional['BinaryView']:
"""
``get_view_of_file`` opens and returns the first available :py:class:`BinaryView`, excluding a Raw :py:class:`BinaryViewType` unless no other view is available
@@ -761,15 +785,17 @@ class BinaryViewType(metaclass=_BinaryViewTypeMetaclass):
if isDatabase:
bv = view.get_view_of_type("Raw")
else:
- bv = cls["Raw"].open(filename) # type: ignore
+ bv = cls["Raw"].open(filename) # type: ignore
if bv is not None and update_analysis:
bv.update_analysis_and_wait()
return bv
@classmethod
- def get_view_of_file_with_options(cls, filename:str, update_analysis:Optional[bool]=True,
- progress_func:Optional[ProgressFuncType]=None, options:Mapping[str, Any]={}) -> Optional['BinaryView']:
+ def get_view_of_file_with_options(
+ cls, filename: str, update_analysis: Optional[bool] = True, progress_func: Optional[ProgressFuncType] = None,
+ options: Mapping[str, Any] = {}
+ ) -> Optional['BinaryView']:
"""
``get_view_of_file_with_options`` opens, generates default load options (which are overridable), and returns the first available \
:py:class:`BinaryView`. If no :py:class:`BinaryViewType` is available, then a ``Mapped`` :py:class:`BinaryViewType` is used to load \
@@ -834,7 +860,7 @@ class BinaryViewType(metaclass=_BinaryViewTypeMetaclass):
bvt = available
if bvt is None:
- bvt = cls["Mapped"] # type: ignore
+ bvt = cls["Mapped"] # type: ignore
default_settings = settings.Settings(bvt.name + "_settings")
default_settings.deserialize_schema(settings.Settings().serialize_schema())
@@ -858,7 +884,9 @@ class BinaryViewType(metaclass=_BinaryViewTypeMetaclass):
break
if not arch_entry:
arch_names = [entry['architecture'] for entry in arch_list if entry['architecture']]
- raise Exception(f"Could not load any of: {options['files.universal.architecturePreference']} from Universal image. Entry not found! Available entries: {arch_names}")
+ raise Exception(
+ f"Could not load any of: {options['files.universal.architecturePreference']} from Universal image. Entry not found! Available entries: {arch_names}"
+ )
load_settings = settings.Settings(core.BNGetUniqueIdentifierString())
load_settings.deserialize_schema(arch_entry[0]['loadSchema'])
@@ -893,22 +921,22 @@ class BinaryViewType(metaclass=_BinaryViewTypeMetaclass):
bv.update_analysis_and_wait()
return bv
- def parse(self, data:'BinaryView') -> Optional['BinaryView']:
+ def parse(self, data: 'BinaryView') -> Optional['BinaryView']:
view = core.BNParseBinaryViewOfType(self, data.handle)
if view is None:
return None
return BinaryView(file_metadata=data.file, handle=view)
- def is_valid_for_data(self, data:'BinaryView') -> bool:
+ def is_valid_for_data(self, data: 'BinaryView') -> bool:
return core.BNIsBinaryViewTypeValidForData(self.handle, data.handle)
- def get_default_load_settings_for_data(self, data:'BinaryView') -> Optional['settings.Settings']:
+ def get_default_load_settings_for_data(self, data: 'BinaryView') -> Optional['settings.Settings']:
load_settings = core.BNGetBinaryViewDefaultLoadSettingsForData(self.handle, data.handle)
if load_settings is None:
return None
return settings.Settings(handle=load_settings)
- def get_load_settings_for_data(self, data:'BinaryView') -> Optional['settings.Settings']:
+ def get_load_settings_for_data(self, data: 'BinaryView') -> Optional['settings.Settings']:
view_handle = None
if data is not None:
view_handle = data.handle
@@ -917,27 +945,27 @@ class BinaryViewType(metaclass=_BinaryViewTypeMetaclass):
return None
return settings.Settings(handle=load_settings)
- def register_arch(self, ident:int, endian:Endianness, arch:'architecture.Architecture') -> None:
+ def register_arch(self, ident: int, endian: Endianness, arch: 'architecture.Architecture') -> None:
core.BNRegisterArchitectureForViewType(self.handle, ident, endian, arch.handle)
- def get_arch(self, ident:int, endian:Endianness) -> Optional['architecture.Architecture']:
+ def get_arch(self, ident: int, endian: Endianness) -> Optional['architecture.Architecture']:
arch = core.BNGetArchitectureForViewType(self.handle, ident, endian)
if arch is None:
return None
return architecture.CoreArchitecture._from_cache(arch)
- def register_platform(self, ident:int, arch:'architecture.Architecture', plat:'_platform.Platform') -> None:
+ def register_platform(self, ident: int, arch: 'architecture.Architecture', plat: '_platform.Platform') -> None:
core.BNRegisterPlatformForViewType(self.handle, ident, arch.handle, plat.handle)
- def register_default_platform(self, arch:'architecture.Architecture', plat:'_platform.Platform') -> None:
+ def register_default_platform(self, arch: 'architecture.Architecture', plat: '_platform.Platform') -> None:
core.BNRegisterDefaultPlatformForViewType(self.handle, arch.handle, plat.handle)
def register_platform_recognizer(self, ident, endian, cb):
def callback(cb, view, meta):
try:
- file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
- view_obj = BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
- meta_obj = metadata.Metadata(handle = core.BNNewMetadataReference(meta))
+ file_metadata = filemetadata.FileMetadata(handle=core.BNGetFileForView(view))
+ view_obj = BinaryView(file_metadata=file_metadata, handle=core.BNNewViewReference(view))
+ meta_obj = metadata.Metadata(handle=core.BNNewMetadataReference(meta))
plat = cb(view_obj, meta_obj)
if plat:
handle = core.BNNewPlatformReference(plat.handle)
@@ -947,25 +975,26 @@ class BinaryViewType(metaclass=_BinaryViewTypeMetaclass):
binaryninja.log_error(traceback.format_exc())
return None
- callback_obj = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNMetadata))(lambda ctxt, view, meta: callback(cb, view, meta))
+ callback_obj = ctypes.CFUNCTYPE(
+ ctypes.c_void_p, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNMetadata)
+ )(lambda ctxt, view, meta: callback(cb, view, meta))
core.BNRegisterPlatformRecognizerForViewType(self.handle, ident, endian, callback_obj, None)
self.__class__._platform_recognizers[len(self.__class__._platform_recognizers)] = callback_obj
-
- def get_platform(self, ident:int, arch:'architecture.Architecture') -> Optional['_platform.Platform']:
+ def get_platform(self, ident: int, arch: 'architecture.Architecture') -> Optional['_platform.Platform']:
plat = core.BNGetPlatformForViewType(self.handle, ident, arch.handle)
if plat is None:
return None
- return _platform.Platform(handle = plat)
+ return _platform.Platform(handle=plat)
def recognize_platform(self, ident, endian, view, metadata):
plat = core.BNRecognizePlatformForViewType(self.handle, ident, endian, view.handle, metadata.handle)
if plat is None:
return None
- return binaryninja.platform.Platform(handle = plat)
+ return binaryninja.platform.Platform(handle=plat)
@staticmethod
- def add_binaryview_finalized_event(callback:BinaryViewEvent.BinaryViewEventCallback) -> None:
+ def add_binaryview_finalized_event(callback: BinaryViewEvent.BinaryViewEventCallback) -> None:
"""
`add_binaryview_finalized_event` adds a callback that gets executed
when new binaryview is finalized.
@@ -974,7 +1003,7 @@ class BinaryViewType(metaclass=_BinaryViewTypeMetaclass):
BinaryViewEvent.register(BinaryViewEventType.BinaryViewFinalizationEvent, callback)
@staticmethod
- def add_binaryview_initial_analysis_completion_event(callback:BinaryViewEvent.BinaryViewEventCallback) -> None:
+ def add_binaryview_initial_analysis_completion_event(callback: BinaryViewEvent.BinaryViewEventCallback) -> None:
"""
`add_binaryview_initial_analysis_completion_event` adds a callback
that gets executed after the initial analysis, as well as linear
@@ -985,7 +1014,7 @@ class BinaryViewType(metaclass=_BinaryViewTypeMetaclass):
class Segment:
- def __init__(self, handle:core.BNSegmentHandle):
+ def __init__(self, handle: core.BNSegmentHandle):
self.handle = handle
def __del__(self):
@@ -993,9 +1022,9 @@ class Segment:
core.BNFreeSegment(self.handle)
def __repr__(self):
- r ="r" if self.readable else "-"
- w ="w" if self.writable else "-"
- x ="x" if self.executable else "-"
+ r = "r" if self.readable else "-"
+ w = "w" if self.writable else "-"
+ x = "x" if self.executable else "-"
return f"<segment: {self.start:#x}-{self.end:#x}, {r}{w}{x}>"
def __len__(self):
@@ -1014,7 +1043,7 @@ class Segment:
def __hash__(self):
return hash(ctypes.addressof(self.handle.contents))
- def __contains__(self, i:int):
+ def __contains__(self, i: int):
return i >= self.start and i < self.end
@property
@@ -1069,7 +1098,7 @@ class Segment:
finally:
core.BNFreeRelocationRanges(ranges)
- def relocation_ranges_at(self, addr:int) -> List[Tuple[int, int]]:
+ def relocation_ranges_at(self, addr: int) -> List[Tuple[int, int]]:
"""List of relocation range tuples (read-only)"""
count = ctypes.c_ulonglong()
@@ -1082,7 +1111,7 @@ class Segment:
class Section:
- def __init__(self, handle:core.BNSectionHandle):
+ def __init__(self, handle: core.BNSectionHandle):
self.handle = handle
def __del__(self):
@@ -1108,7 +1137,7 @@ class Section:
def __hash__(self):
return hash(ctypes.addressof(self.handle.contents))
- def __contains__(self, i:int):
+ def __contains__(self, i: int):
return i >= self.start and i < self.end
@property
@@ -1155,13 +1184,13 @@ class Section:
def end(self) -> int:
return self.start + len(self)
- def range_contains_relocation(self, addr:int, size:int) -> bool:
+ def range_contains_relocation(self, addr: int, size: int) -> bool:
"""Checks if the specified range overlaps with a relocation"""
return core.BNSegmentRangeContainsRelocation(self.handle, addr, size)
class TagType:
- def __init__(self, handle:core.BNTagTypeHandle):
+ def __init__(self, handle: core.BNTagTypeHandle):
self.handle = handle
def __del__(self):
@@ -1195,7 +1224,7 @@ class TagType:
return core.BNTagTypeGetName(self.handle)
@name.setter
- def name(self, value:str) -> None:
+ def name(self, value: str) -> None:
core.BNTagTypeSetName(self.handle, value)
@property
@@ -1204,7 +1233,7 @@ class TagType:
return core.BNTagTypeGetIcon(self.handle)
@icon.setter
- def icon(self, value:str) -> None:
+ def icon(self, value: str) -> None:
core.BNTagTypeSetIcon(self.handle, value)
@property
@@ -1213,7 +1242,7 @@ class TagType:
return core.BNTagTypeGetVisible(self.handle)
@visible.setter
- def visible(self, value:bool) -> None:
+ def visible(self, value: bool) -> None:
core.BNTagTypeSetVisible(self.handle, value)
@property
@@ -1222,12 +1251,12 @@ class TagType:
return TagTypeType(core.BNTagTypeGetType(self.handle))
@type.setter
- def type(self, value:TagTypeType) -> None:
+ def type(self, value: TagTypeType) -> None:
core.BNTagTypeSetType(self.handle, value)
class Tag:
- def __init__(self, handle:core.BNTagHandle):
+ def __init__(self, handle: core.BNTagHandle):
self.handle = handle
def __del__(self):
@@ -1265,7 +1294,7 @@ class Tag:
return core.BNTagGetData(self.handle)
@data.setter
- def data(self, value:str) -> None:
+ def data(self, value: str) -> None:
core.BNTagSetData(self.handle, value)
@@ -1284,10 +1313,10 @@ class SymbolMapping(collections.abc.Mapping): # type: ignore
>>> print("Found")
"""
- def __init__(self, view:'BinaryView'):
+ def __init__(self, view: 'BinaryView'):
self._symbol_list = None
self._count = None
- self._symbol_cache:Optional[Mapping[bytes, List[_types.CoreSymbol]]] = None
+ self._symbol_cache: Optional[Mapping[bytes, List[_types.CoreSymbol]]] = None
self._view = view
self._n = 0
@@ -1384,10 +1413,10 @@ class TypeMapping(collections.abc.Mapping): # type: ignore
>>> print("Found")
"""
- def __init__(self, view:'BinaryView'):
+ def __init__(self, view: 'BinaryView'):
self._type_list = None
self._count = None
- self._type_cache:Optional[Mapping[_types.QualifiedName, _types.Type]] = None
+ self._type_cache: Optional[Mapping[_types.QualifiedName, _types.Type]] = None
self._view = view
def __repr__(self):
@@ -1418,7 +1447,7 @@ class TypeMapping(collections.abc.Mapping): # type: ignore
self._count = count.value
for i in range(len(self)):
name = _types.QualifiedName._from_core_struct(self._type_list[i].name)
- type = _types.Type.create(core.BNNewTypeReference(self._type_list[i].type), platform = self._view.platform)
+ type = _types.Type.create(core.BNNewTypeReference(self._type_list[i].type), platform=self._view.platform)
self._type_cache[name] = type
yield name, type
@@ -1442,7 +1471,7 @@ class TypeMapping(collections.abc.Mapping): # type: ignore
return self.view == other.view
def __ne__(self, other):
- return not(self == other)
+ return not (self == other)
def keys(self):
if self._type_cache is None:
@@ -1470,7 +1499,7 @@ class TypeMapping(collections.abc.Mapping): # type: ignore
class FunctionList:
- def __init__(self, view:'BinaryView'):
+ def __init__(self, view: 'BinaryView'):
count = ctypes.c_ulonglong(0)
_funcs = core.BNGetAnalysisFunctionList(view.handle, count)
assert _funcs is not None, "core.BNGetAnalysisFunctionList returned None"
@@ -1491,7 +1520,7 @@ class FunctionList:
self._n += 1
return _function.Function(self._view, func)
- def __getitem__(self, i:Union[int, slice]) -> Union['_function.Function', List['_function.Function']]:
+ def __getitem__(self, i: Union[int, slice]) -> Union['_function.Function', List['_function.Function']]:
if isinstance(i, int):
if i < 0:
i = len(self) + i
@@ -1545,7 +1574,7 @@ class AdvancedILFunctionList:
>>> timeit.timeit(lambda:[f for f in bv.functions], number=1)
0.02230275600004461
"""
- def __init__(self, view:'BinaryView', preload_limit:int = 5, functions:Optional[Iterable]=None):
+ def __init__(self, view: 'BinaryView', preload_limit: int = 5, functions: Optional[Iterable] = None):
self._view = view
self._func_queue = deque()
self._preload_limit = preload_limit
@@ -1614,13 +1643,17 @@ class BinaryView:
to the database is desired.
"""
name: Optional[str] = None
- long_name: Optional[str] = None
+ long_name: Optional[str] = None
_registered = False
_registered_cb = None
registered_view_type = None
_associated_data = {}
_registered_instances = []
- def __init__(self, file_metadata:'filemetadata.FileMetadata'=None, parent_view:'BinaryView'=None, handle:core.BNBinaryViewHandle=None):
+
+ def __init__(
+ self, file_metadata: 'filemetadata.FileMetadata' = None, parent_view: 'BinaryView' = None,
+ handle: core.BNBinaryViewHandle = None
+ ):
if handle is not None:
_handle = handle
if file_metadata is None:
@@ -1785,7 +1818,7 @@ class BinaryView:
else:
raise IndexError("index out of range")
- def __contains__(self, i:int):
+ def __contains__(self, i: int):
for s in self.segments:
if i in s:
return True
@@ -1803,7 +1836,9 @@ class BinaryView:
cls._registered_cb.create = cls._registered_cb.create.__class__(cls._create)
cls._registered_cb.parse = cls._registered_cb.parse.__class__(cls._parse)
cls._registered_cb.isValidForData = cls._registered_cb.isValidForData.__class__(cls._is_valid_for_data)
- cls._registered_cb.getLoadSettingsForData = cls._registered_cb.getLoadSettingsForData.__class__(cls._get_load_settings_for_data)
+ cls._registered_cb.getLoadSettingsForData = cls._registered_cb.getLoadSettingsForData.__class__(
+ cls._get_load_settings_for_data
+ )
view_handle = core.BNRegisterBinaryViewType(cls.name, cls.long_name, cls._registered_cb)
assert view_handle is not None, "core.BNRegisterBinaryViewType returned None"
cls.registered_view_type = BinaryViewType(view_handle)
@@ -1814,14 +1849,14 @@ class BinaryView:
return self._parse_only
@parse_only.setter
- def parse_only(self, value:bool) -> None:
+ def parse_only(self, value: bool) -> None:
self._parse_only = value
@classmethod
- def _create(cls, ctxt, data:core.BNBinaryView):
+ def _create(cls, ctxt, data: core.BNBinaryView):
try:
file_metadata = filemetadata.FileMetadata(handle=core.BNGetFileForView(data))
- view = cls(BinaryView(file_metadata=file_metadata, handle=core.BNNewViewReference(data))) # type: ignore
+ view = cls(BinaryView(file_metadata=file_metadata, handle=core.BNNewViewReference(data))) # type: ignore
if view is None:
return None
view.parse_only = False
@@ -1833,10 +1868,10 @@ class BinaryView:
return None
@classmethod
- def _parse(cls, ctxt, data:core.BNBinaryView):
+ def _parse(cls, ctxt, data: core.BNBinaryView):
try:
file_metadata = filemetadata.FileMetadata(handle=core.BNGetFileForView(data))
- view = cls(BinaryView(file_metadata=file_metadata, handle=core.BNNewViewReference(data))) # type: ignore
+ view = cls(BinaryView(file_metadata=file_metadata, handle=core.BNNewViewReference(data))) # type: ignore
if view is None:
return None
view.parse_only = True
@@ -1851,7 +1886,7 @@ class BinaryView:
def _is_valid_for_data(cls, ctxt, data):
try:
# I'm not sure whats going on here even so I've suppressed the linter warning
- return cls.is_valid_for_data(BinaryView(handle=core.BNNewViewReference(data))) # type: ignore
+ return cls.is_valid_for_data(BinaryView(handle=core.BNNewViewReference(data))) # type: ignore
except:
log_error(traceback.format_exc())
return False
@@ -1861,7 +1896,9 @@ class BinaryView:
try:
attr = getattr(cls, "get_load_settings_for_data", None)
if callable(attr):
- result = cls.get_load_settings_for_data(BinaryView(handle=core.BNNewViewReference(data))) # type: ignore
+ result = cls.get_load_settings_for_data(
+ BinaryView(handle=core.BNNewViewReference(data))
+ ) # type: ignore
settings_handle = core.BNNewSettingsReference(result.handle)
assert settings_handle is not None, "core.BNNewSettingsReference returned None"
return ctypes.cast(settings_handle, ctypes.c_void_p).value
@@ -1887,7 +1924,7 @@ class BinaryView:
return BinaryView(file_metadata=file_metadata, handle=view)
@staticmethod
- def new(data:bytes=None, file_metadata:Optional['filemetadata.FileMetadata']=None) -> Optional['BinaryView']:
+ def new(data: bytes = None, file_metadata: Optional['filemetadata.FileMetadata'] = None) -> Optional['BinaryView']:
binaryninja._init_plugins()
if file_metadata is None:
file_metadata = filemetadata.FileMetadata()
@@ -1901,13 +1938,13 @@ class BinaryView:
return BinaryView(file_metadata=file_metadata, handle=view)
@classmethod
- def _unregister(cls, view:core.BNBinaryView) -> None:
+ def _unregister(cls, view: core.BNBinaryView) -> None:
handle = ctypes.cast(view, ctypes.c_void_p)
if handle.value in cls._associated_data:
del cls._associated_data[handle.value]
@staticmethod
- def set_default_session_data(name:str, value:str) -> None:
+ def set_default_session_data(name: str, value: str) -> None:
"""
``set_default_session_data`` saves a variable to the BinaryView.
@@ -1926,7 +1963,7 @@ class BinaryView:
return self._preload_limit
@preload_limit.setter
- def preload_limit(self, value:int) -> None:
+ def preload_limit(self, value: int) -> None:
self._preload_limit = value
@property
@@ -1948,7 +1985,7 @@ class BinaryView:
yield from func.basic_blocks
@property
- def hlil_basic_blocks(self) -> Generator['highlevelil.HighLevelILBasicBlock', None, None]:
+ def hlil_basic_blocks(self) -> Generator['highlevelil.HighLevelILBasicBlock', None, None]:
"""A generator of all HighLevelILBasicBlock objects in the BinaryView"""
for func in self.hlil_functions():
yield from func.basic_blocks
@@ -1994,7 +2031,7 @@ class BinaryView:
return self._file.modified
@modified.setter
- def modified(self, value:bool) -> None:
+ def modified(self, value: bool) -> None:
self._file.modified = value
@property
@@ -2012,7 +2049,7 @@ class BinaryView:
return self._file.view
@view.setter
- def view(self, value:str) -> None:
+ def view(self, value: str) -> None:
self._file.view = value
@property
@@ -2020,7 +2057,7 @@ class BinaryView:
return self._file.offset
@offset.setter
- def offset(self, value:int) -> None:
+ def offset(self, value: int) -> None:
self._file.offset = value
@property
@@ -2052,7 +2089,7 @@ class BinaryView:
return architecture.CoreArchitecture._from_cache(handle=arch)
@arch.setter
- def arch(self, value:'architecture.Architecture') -> None:
+ def arch(self, value: 'architecture.Architecture') -> None:
if value is None:
core.BNSetDefaultArchitecture(self.handle, None)
else:
@@ -2067,7 +2104,7 @@ class BinaryView:
return _platform.Platform(self.arch, handle=plat)
@platform.setter
- def platform(self, value:Optional['_platform.Platform']) -> None:
+ def platform(self, value: Optional['_platform.Platform']) -> None:
if value is None:
core.BNSetDefaultPlatform(self.handle, None)
else:
@@ -2098,20 +2135,30 @@ class BinaryView:
"""returns a FunctionList object (read-only)"""
return FunctionList(self)
- def mlil_functions(self, preload_limit:Optional[int] = None, function_generator:Generator['_function.Function', None, None] = None) -> Generator['mediumlevelil.MediumLevelILFunction', None, None]:
+ def mlil_functions(
+ self, preload_limit: Optional[int] = None, function_generator: Generator['_function.Function', None,
+ None] = None
+ ) -> Generator['mediumlevelil.MediumLevelILFunction', None, None]:
"""
Generates a list of il functions. This method should be used instead of 'functions' property if
MLIL is needed and performance is a concern.
"""
- for func in AdvancedILFunctionList(self, self.preload_limit if preload_limit is None else preload_limit, function_generator):
+ for func in AdvancedILFunctionList(
+ self, self.preload_limit if preload_limit is None else preload_limit, function_generator
+ ):
yield func.mlil
- def hlil_functions(self, preload_limit:Optional[int] = None, function_generator:Generator['_function.Function', None, None] = None) -> Generator['highlevelil.HighLevelILFunction', None, None]:
+ def hlil_functions(
+ self, preload_limit: Optional[int] = None, function_generator: Generator['_function.Function', None,
+ None] = None
+ ) -> Generator['highlevelil.HighLevelILFunction', None, None]:
"""
Generates a list of il functions. This method should be used instead of 'functions' property if
HLIL is needed and performance is a concern.
"""
- for func in AdvancedILFunctionList(self, self.preload_limit if preload_limit is None else preload_limit, function_generator):
+ for func in AdvancedILFunctionList(
+ self, self.preload_limit if preload_limit is None else preload_limit, function_generator
+ ):
yield func.hlil
@property
@@ -2211,7 +2258,7 @@ class BinaryView:
return self._file.saved
@saved.setter
- def saved(self, value:bool) -> None:
+ def saved(self, value: bool) -> None:
self._file.saved = value
@property
@@ -2228,11 +2275,14 @@ class BinaryView:
info_ref = core.BNGetAnalysisInfo(self.handle)
assert info_ref is not None, "core.BNGetAnalysisInfo returned None"
info = info_ref[0]
- active_info_list:List[ActiveAnalysisInfo] = []
+ active_info_list: List[ActiveAnalysisInfo] = []
try:
for i in range(0, info.count):
func = _function.Function(self, core.BNNewFunctionReference(info.activeInfo[i].func))
- active_info = ActiveAnalysisInfo(func, info.activeInfo[i].analysisTime, info.activeInfo[i].updateCount, info.activeInfo[i].submitCount)
+ active_info = ActiveAnalysisInfo(
+ func, info.activeInfo[i].analysisTime, info.activeInfo[i].updateCount,
+ info.activeInfo[i].submitCount
+ )
active_info_list.append(active_info)
return AnalysisInfo(info.state, info.analysisTime, active_info_list)
finally:
@@ -2281,7 +2331,6 @@ class BinaryView:
finally:
core.BNFreeTypeNameList(name_list, count.value)
-
@property
def type_libraries(self) -> List['typelibrary.TypeLibrary']:
"""List of imported type libraries (read-only)"""
@@ -2296,7 +2345,6 @@ class BinaryView:
finally:
core.BNFreeTypeLibraryList(libraries, count.value)
-
@property
def segments(self) -> List['Segment']:
"""List of segments (read-only)"""
@@ -2374,7 +2422,7 @@ class BinaryView:
return core.BNGetMaxFunctionSizeForAnalysis(self.handle)
@max_function_size_for_analysis.setter
- def max_function_size_for_analysis(self, size:int) -> None:
+ def max_function_size_for_analysis(self, size: int) -> None:
core.BNSetMaxFunctionSizeForAnalysis(self.handle, size)
@property
@@ -2388,7 +2436,7 @@ class BinaryView:
finally:
core.BNFreeRelocationRanges(ranges)
- def relocation_ranges_at(self, addr:int) -> List[Tuple[int, int]]:
+ def relocation_ranges_at(self, addr: int) -> List[Tuple[int, int]]:
"""List of relocation range tuples for a given address"""
count = ctypes.c_ulonglong()
@@ -2399,7 +2447,7 @@ class BinaryView:
finally:
core.BNFreeRelocationRanges(ranges)
- def range_contains_relocation(self, addr:int, size:int) -> bool:
+ def range_contains_relocation(self, addr: int, size: int) -> bool:
"""Checks if the specified range overlaps with a relocation"""
return core.BNRangeContainsRelocation(self.handle, addr, size)
@@ -2409,7 +2457,7 @@ class BinaryView:
return core.BNGetNewAutoFunctionAnalysisSuppressed(self.handle)
@new_auto_function_analysis_suppressed.setter
- def new_auto_function_analysis_suppressed(self, suppress:bool) -> None:
+ def new_auto_function_analysis_suppressed(self, suppress: bool) -> None:
core.BNSetNewAutoFunctionAnalysisSuppressed(self.handle, suppress)
def _init(self, ctxt):
@@ -2570,7 +2618,9 @@ class BinaryView:
def init(self) -> bool:
return True
- def disassembly_tokens(self, addr:int, arch:Optional['architecture.Architecture']=None) -> Generator[Tuple[List['_function.InstructionTextToken'], int], None, None]:
+ def disassembly_tokens(
+ self, addr: int, arch: Optional['architecture.Architecture'] = None
+ ) -> Generator[Tuple[List['_function.InstructionTextToken'], int], None, None]:
if arch is None:
if self.arch is None:
raise Exception("Can not call method disassembly with no Architecture specified")
@@ -2584,7 +2634,8 @@ class BinaryView:
break
yield (tokens, size)
- def disassembly_text(self, addr:int, arch:Optional['architecture.Architecture']=None) -> Generator[Tuple[str, int], None, None]:
+ def disassembly_text(self, addr: int,
+ arch: Optional['architecture.Architecture'] = None) -> Generator[Tuple[str, int], None, None]:
"""
``disassembly_text`` helper function for getting disassembly of a given address
@@ -2611,7 +2662,7 @@ class BinaryView:
break
yield (''.join(str(a) for a in tokens).strip(), size)
- def get_disassembly(self, addr:int, arch:Optional['architecture.Architecture']=None) -> Optional[str]:
+ def get_disassembly(self, addr: int, arch: Optional['architecture.Architecture'] = None) -> Optional[str]:
"""
``get_disassembly`` simple helper function for printing disassembly of a given address
:param int addr: virtual address of instruction
@@ -2659,7 +2710,7 @@ class BinaryView:
"""
return 0
- def perform_read(self, addr:int, length:int) -> bytes:
+ def perform_read(self, addr: int, length: int) -> bytes:
"""
``perform_read`` implements a mapping between a virtual address and an absolute file offset, reading
``length`` bytes from the rebased address ``addr``.
@@ -2676,7 +2727,7 @@ class BinaryView:
"""
return b""
- def perform_write(self, addr:int, data:bytes) -> int:
+ def perform_write(self, addr: int, data: bytes) -> int:
"""
``perform_write`` implements a mapping between a virtual address and an absolute file offset, writing
the bytes ``data`` to rebased address ``addr``.
@@ -2693,7 +2744,7 @@ class BinaryView:
"""
return 0
- def perform_insert(self, addr:int, data:bytes) -> int:
+ def perform_insert(self, addr: int, data: bytes) -> int:
"""
``perform_insert`` implements a mapping between a virtual address and an absolute file offset, inserting
the bytes ``data`` to rebased address ``addr``.
@@ -2709,7 +2760,7 @@ class BinaryView:
"""
return 0
- def perform_remove(self, addr:int, length:int) -> int:
+ def perform_remove(self, addr: int, length: int) -> int:
"""
``perform_remove`` implements a mapping between a virtual address and an absolute file offset, removing
``length`` bytes from the rebased address ``addr``.
@@ -2725,7 +2776,7 @@ class BinaryView:
"""
return 0
- def perform_get_modification(self, addr:int) -> ModificationStatus:
+ def perform_get_modification(self, addr: int) -> ModificationStatus:
"""
``perform_get_modification`` implements query to the whether the virtual address ``addr`` is modified.
@@ -2740,7 +2791,7 @@ class BinaryView:
"""
return ModificationStatus.Original
- def perform_is_valid_offset(self, addr:int) -> bool:
+ def perform_is_valid_offset(self, addr: int) -> bool:
"""
``perform_is_valid_offset`` implements a check if an virtual address ``addr`` is valid.
@@ -2756,7 +2807,7 @@ class BinaryView:
data = self.read(addr, 1)
return (data is not None) and (len(data) == 1)
- def perform_is_offset_readable(self, offset:int) -> bool:
+ def perform_is_offset_readable(self, offset: int) -> bool:
"""
``perform_is_offset_readable`` implements a check if an virtual address is readable.
@@ -2771,7 +2822,7 @@ class BinaryView:
"""
return self.is_valid_offset(offset)
- def perform_is_offset_writable(self, addr:int) -> bool:
+ def perform_is_offset_writable(self, addr: int) -> bool:
"""
``perform_is_offset_writable`` implements a check if a virtual address ``addr`` is writable.
@@ -2786,7 +2837,7 @@ class BinaryView:
"""
return self.is_valid_offset(addr)
- def perform_is_offset_executable(self, addr:int) -> bool:
+ def perform_is_offset_executable(self, addr: int) -> bool:
"""
``perform_is_offset_executable`` implements a check if a virtual address ``addr`` is executable.
@@ -2801,7 +2852,7 @@ class BinaryView:
"""
return self.is_valid_offset(addr)
- def perform_get_next_valid_offset(self, addr:int) -> int:
+ def perform_get_next_valid_offset(self, addr: int) -> int:
"""
``perform_get_next_valid_offset`` implements a query for the next valid readable, writable, or executable virtual
memory address.
@@ -2886,7 +2937,10 @@ class BinaryView:
"""
return False
- def create_database(self, filename:str, progress_func:Optional[ProgressFuncType]=None, settings:Optional['filemetadata.SaveSettings']=None) -> bool:
+ def create_database(
+ self, filename: str, progress_func: Optional[ProgressFuncType] = None,
+ settings: Optional['filemetadata.SaveSettings'] = None
+ ) -> bool:
"""
``create_database`` writes the current database (.bndb) out to the specified file.
@@ -2902,7 +2956,9 @@ class BinaryView:
"""
return self._file.create_database(filename, progress_func, settings)
- def save_auto_snapshot(self, progress_func:Optional[ProgressFuncType]=None, settings:Optional['filemetadata.SaveSettings']=None) -> bool:
+ def save_auto_snapshot(
+ self, progress_func: Optional[ProgressFuncType] = None, settings: Optional['filemetadata.SaveSettings'] = None
+ ) -> bool:
"""
``save_auto_snapshot`` saves the current database to the already created file.
@@ -2915,7 +2971,7 @@ class BinaryView:
"""
return self._file.save_auto_snapshot(progress_func, settings)
- def get_view_of_type(self, name:str) -> Optional['BinaryView']:
+ def get_view_of_type(self, name: str) -> Optional['BinaryView']:
"""
``get_view_of_type`` returns the BinaryView associated with the provided name if it exists.
@@ -3019,7 +3075,7 @@ class BinaryView:
"""
self._file.redo()
- def navigate(self, view_name:str, offset:int) -> bool:
+ def navigate(self, view_name: str, offset: int) -> bool:
"""
``navigate`` navigates the UI to the specified virtual address
@@ -3037,7 +3093,7 @@ class BinaryView:
"""
return self._file.navigate(view_name, offset)
- def read(self, addr:int, length:int) -> bytes:
+ def read(self, addr: int, length: int) -> bytes:
"""
``read`` returns the data reads at most ``length`` bytes from virtual address ``addr``.
@@ -3060,7 +3116,7 @@ class BinaryView:
buf = databuffer.DataBuffer(handle=core.BNReadViewBuffer(self.handle, addr, length))
return bytes(buf)
- def read_int(self, address:int, size:int, sign:bool=True, endian:Optional[Endianness]=None) -> int:
+ def read_int(self, address: int, size: int, sign: bool = True, endian: Optional[Endianness] = None) -> int:
_endian = self.endianness
if endian is not None:
_endian = endian
@@ -3069,7 +3125,7 @@ class BinaryView:
raise ValueError(f"Couldn't read {size} bytes from address: {address:#x}")
return TypedDataAccessor.int_from_bytes(data, size, sign, _endian)
- def read_pointer(self, address:int, size=None) -> int:
+ def read_pointer(self, address: int, size=None) -> int:
_size = size
if size is None:
if self.arch is None:
@@ -3077,7 +3133,7 @@ class BinaryView:
_size = self.arch.address_size
return self.read_int(address, _size, False, self.endianness)
- def write(self, addr:int, data:bytes, except_on_relocation:bool = True) -> int:
+ def write(self, addr: int, data: bytes, except_on_relocation: bool = True) -> int:
"""
``write`` writes the bytes in ``data`` to the virtual address ``addr``.
@@ -3103,7 +3159,7 @@ class BinaryView:
return core.BNWriteViewBuffer(self.handle, addr, buf.handle)
- def insert(self, addr:int, data:bytes) -> int:
+ def insert(self, addr: int, data: bytes) -> int:
"""
``insert`` inserts the bytes in ``data`` to the virtual address ``addr``.
@@ -3124,7 +3180,7 @@ class BinaryView:
buf = databuffer.DataBuffer(data)
return core.BNInsertViewBuffer(self.handle, addr, buf.handle)
- def remove(self, addr:int, length:int) -> int:
+ def remove(self, addr: int, length: int) -> int:
"""
``remove`` removes at most ``length`` bytes from virtual address ``addr``.
@@ -3143,7 +3199,7 @@ class BinaryView:
"""
return core.BNRemoveViewData(self.handle, addr, length)
- def get_entropy(self, addr:int, length:int, block_size:int=0) -> List[float]:
+ def get_entropy(self, addr: int, length: int, block_size: int = 0) -> List[float]:
"""
``get_entropy`` returns the shannon entropy given the start ``addr``, ``length`` in bytes, and optionally in
``block_size`` chunks.
@@ -3159,14 +3215,14 @@ class BinaryView:
return result
if block_size == 0:
block_size = length
- data = (ctypes.c_float * ((length // block_size) + 1))()
+ data = (ctypes.c_float * ((length//block_size) + 1))()
length = core.BNGetEntropy(self.handle, addr, length, block_size, data)
for i in range(0, length):
result.append(float(data[i]))
return result
- def get_modification(self, addr:int, length:int=None) -> List[ModificationStatus]:
+ def get_modification(self, addr: int, length: int = None) -> List[ModificationStatus]:
"""
``get_modification`` returns the modified bytes of up to ``length`` bytes from virtual address ``addr``, or if
``length`` is None returns the ModificationStatus.
@@ -3182,7 +3238,7 @@ class BinaryView:
length = core.BNGetModificationArray(self.handle, addr, data, length)
return [ModificationStatus(a) for a in data[:length]]
- def is_valid_offset(self, addr:int) -> bool:
+ def is_valid_offset(self, addr: int) -> bool:
"""
``is_valid_offset`` checks if an virtual address ``addr`` is valid .
@@ -3192,7 +3248,7 @@ class BinaryView:
"""
return core.BNIsValidOffset(self.handle, addr)
- def is_offset_readable(self, addr:int) -> bool:
+ def is_offset_readable(self, addr: int) -> bool:
"""
``is_offset_readable`` checks if an virtual address ``addr`` is valid for reading.
@@ -3202,7 +3258,7 @@ class BinaryView:
"""
return core.BNIsOffsetReadable(self.handle, addr)
- def is_offset_writable(self, addr:int) -> bool:
+ def is_offset_writable(self, addr: int) -> bool:
"""
``is_offset_writable`` checks if an virtual address ``addr`` is valid for writing.
@@ -3212,7 +3268,7 @@ class BinaryView:
"""
return core.BNIsOffsetWritable(self.handle, addr)
- def is_offset_executable(self, addr:int) -> bool:
+ def is_offset_executable(self, addr: int) -> bool:
"""
``is_offset_executable`` checks if an virtual address ``addr`` is valid for executing.
@@ -3222,7 +3278,7 @@ class BinaryView:
"""
return core.BNIsOffsetExecutable(self.handle, addr)
- def is_offset_code_semantics(self, addr:int) -> bool:
+ def is_offset_code_semantics(self, addr: int) -> bool:
"""
``is_offset_code_semantics`` checks if an virtual address ``addr`` is semantically valid for code.
@@ -3232,7 +3288,7 @@ class BinaryView:
"""
return core.BNIsOffsetCodeSemantics(self.handle, addr)
- def is_offset_extern_semantics(self, addr:int) -> bool:
+ def is_offset_extern_semantics(self, addr: int) -> bool:
"""
``is_offset_extern_semantics`` checks if an virtual address ``addr`` is semantically valid for external references.
@@ -3242,7 +3298,7 @@ class BinaryView:
"""
return core.BNIsOffsetExternSemantics(self.handle, addr)
- def is_offset_writable_semantics(self, addr:int) -> bool:
+ def is_offset_writable_semantics(self, addr: int) -> bool:
"""
``is_offset_writable_semantics`` checks if an virtual address ``addr`` is semantically writable. Some sections
may have writable permissions for linking purposes but can be treated as read-only for the purposes of
@@ -3254,7 +3310,7 @@ class BinaryView:
"""
return core.BNIsOffsetWritableSemantics(self.handle, addr)
- def save(self, dest:Union['fileaccessor.FileAccessor', str]) -> bool:
+ def save(self, dest: Union['fileaccessor.FileAccessor', str]) -> bool:
"""
``save`` saves the original binary file to the provided destination ``dest`` along with any modifications.
@@ -3266,7 +3322,7 @@ class BinaryView:
return core.BNSaveToFile(self.handle, dest._cb)
return core.BNSaveToFilename(self.handle, str(dest))
- def register_notification(self, notify:BinaryDataNotification) -> None:
+ def register_notification(self, notify: BinaryDataNotification) -> None:
"""
`register_notification` provides a mechanism for receiving callbacks for various analysis events. A full
list of callbacks can be seen in :py:Class:`BinaryDataNotification`.
@@ -3278,7 +3334,7 @@ class BinaryView:
cb._register()
self._notifications[notify] = cb
- def unregister_notification(self, notify:BinaryDataNotification) -> None:
+ def unregister_notification(self, notify: BinaryDataNotification) -> None:
"""
`unregister_notification` unregisters the :py:Class:`BinaryDataNotification` object passed to
`register_notification`
@@ -3290,7 +3346,7 @@ class BinaryView:
self._notifications[notify]._unregister()
del self._notifications[notify]
- def add_function(self, addr:int, plat:Optional['_platform.Platform']=None) -> None:
+ def add_function(self, addr: int, plat: Optional['_platform.Platform'] = None) -> None:
"""
``add_function`` add a new function of the given ``plat`` at the virtual address ``addr``
@@ -3312,7 +3368,7 @@ class BinaryView:
raise AttributeError("Provided platform is not of type `Platform`")
core.BNAddFunctionForAnalysis(self.handle, plat.handle, addr)
- def add_entry_point(self, addr:int, plat:Optional['_platform.Platform']=None) -> None:
+ def add_entry_point(self, addr: int, plat: Optional['_platform.Platform'] = None) -> None:
"""
``add_entry_point`` adds an virtual address to start analysis from for a given plat.
@@ -3331,7 +3387,7 @@ class BinaryView:
raise AttributeError("Provided platform is not of type `Platform`")
core.BNAddEntryPointForAnalysis(self.handle, plat.handle, addr)
- def remove_function(self, func:'_function.Function') -> None:
+ def remove_function(self, func: '_function.Function') -> None:
"""
``remove_function`` removes the function ``func`` from the list of functions
@@ -3349,7 +3405,7 @@ class BinaryView:
"""
core.BNRemoveAnalysisFunction(self.handle, func.handle)
- def create_user_function(self, addr:int, plat:Optional['_platform.Platform']=None) -> '_function.Function':
+ def create_user_function(self, addr: int, plat: Optional['_platform.Platform'] = None) -> '_function.Function':
"""
``create_user_function`` add a new *user* function of the given ``plat`` at the virtual address ``addr``
@@ -3369,7 +3425,7 @@ class BinaryView:
plat = self.platform
return _function.Function(self, core.BNCreateUserFunction(self.handle, plat.handle, addr))
- def remove_user_function(self, func:'_function.Function') -> None:
+ def remove_user_function(self, func: '_function.Function') -> None:
"""
``remove_user_function`` removes the function ``func`` from the list of functions as a user action.
@@ -3387,7 +3443,7 @@ class BinaryView:
"""
core.BNRemoveUserFunction(self.handle, func.handle)
- def add_analysis_option(self, name:str) -> None:
+ def add_analysis_option(self, name: str) -> None:
"""
``add_analysis_option`` adds an analysis option. Analysis options elaborate the analysis phase. The user must
start analysis by calling either :func:`update_analysis` or :func:`update_analysis_and_wait`.
@@ -3411,7 +3467,7 @@ class BinaryView:
"""
return core.BNHasInitialAnalysis(self.handle)
- def set_analysis_hold(self, enable:bool) -> None:
+ def set_analysis_hold(self, enable: bool) -> None:
"""
``set_analysis_hold`` control the analysis hold for this BinaryView. Enabling analysis hold defers all future
analysis updates, therefore causing :func:`update_analysis` or :func:`update_analysis_and_wait` to take no action.
@@ -3452,7 +3508,9 @@ class BinaryView:
"""
core.BNAbortAnalysis(self.handle)
- def define_data_var(self, addr:int, var_type:StringOrType, name:Optional[Union[str, '_types.CoreSymbol']]=None) -> None:
+ def define_data_var(
+ self, addr: int, var_type: StringOrType, name: Optional[Union[str, '_types.CoreSymbol']] = None
+ ) -> None:
"""
``define_data_var`` defines a non-user data variable ``var_type`` at the virtual address ``addr``.
@@ -3483,7 +3541,9 @@ class BinaryView:
name = _types.Symbol(SymbolType.DataSymbol, addr, name)
self.define_auto_symbol(name)
- def define_user_data_var(self, addr:int, var_type:StringOrType, name:Optional[Union[str, '_types.CoreSymbol']]=None) -> Optional['DataVariable']:
+ def define_user_data_var(
+ self, addr: int, var_type: StringOrType, name: Optional[Union[str, '_types.CoreSymbol']] = None
+ ) -> Optional['DataVariable']:
"""
``define_user_data_var`` defines a user data variable ``var_type`` at the virtual address ``addr``.
@@ -3518,7 +3578,7 @@ class BinaryView:
return self.get_data_var_at(addr)
- def undefine_data_var(self, addr:int) -> None:
+ def undefine_data_var(self, addr: int) -> None:
"""
``undefine_data_var`` removes the non-user data variable at the virtual address ``addr``.
@@ -3531,7 +3591,7 @@ class BinaryView:
"""
core.BNUndefineDataVariable(self.handle, addr)
- def undefine_user_data_var(self, addr:int) -> None:
+ def undefine_user_data_var(self, addr: int) -> None:
"""
``undefine_user_data_var`` removes the user data variable at the virtual address ``addr``.
@@ -3544,7 +3604,7 @@ class BinaryView:
"""
core.BNUndefineUserDataVariable(self.handle, addr)
- def get_data_var_at(self, addr:int) -> Optional['DataVariable']:
+ def get_data_var_at(self, addr: int) -> Optional['DataVariable']:
"""
``get_data_var_at`` returns the data type at a given virtual address.
@@ -3564,7 +3624,8 @@ class BinaryView:
return None
return DataVariable.from_core_struct(var, self)
- def get_functions_containing(self, addr:int, plat:Optional['_platform.Platform']=None) -> List['_function.Function']:
+ def get_functions_containing(self, addr: int,
+ plat: Optional['_platform.Platform'] = None) -> List['_function.Function']:
"""
``get_functions_containing`` returns a list of functions which contain the given address.
@@ -3584,7 +3645,9 @@ class BinaryView:
finally:
core.BNFreeFunctionList(funcs, count.value)
- def get_functions_by_name(self, name:str, plat:Optional['_platform.Platform']=None, ordered_filter:Optional[List[SymbolType]]=None) -> List['_function.Function']:
+ def get_functions_by_name(
+ self, name: str, plat: Optional['_platform.Platform'] = None, ordered_filter: Optional[List[SymbolType]] = None
+ ) -> List['_function.Function']:
"""``get_functions_by_name`` returns a list of Function objects
function with a Symbol of ``name``.
@@ -3600,9 +3663,9 @@ class BinaryView:
>>>
"""
if ordered_filter is None:
- ordered_filter = [SymbolType.FunctionSymbol,
- SymbolType.ImportedFunctionSymbol,
- SymbolType.LibraryFunctionSymbol]
+ ordered_filter = [
+ SymbolType.FunctionSymbol, SymbolType.ImportedFunctionSymbol, SymbolType.LibraryFunctionSymbol
+ ]
if plat == None:
plat = self.platform
@@ -3616,7 +3679,7 @@ class BinaryView:
fns.append(fn)
return fns
- def get_function_at(self, addr:int, plat:Optional['_platform.Platform']=None) -> Optional['_function.Function']:
+ def get_function_at(self, addr: int, plat: Optional['_platform.Platform'] = None) -> Optional['_function.Function']:
"""
``get_function_at`` gets a Function object for the function that starts at virtual address ``addr``:
@@ -3644,7 +3707,7 @@ class BinaryView:
return None
return _function.Function(self, func)
- def get_functions_at(self, addr:int) -> List['_function.Function']:
+ def get_functions_at(self, addr: int) -> List['_function.Function']:
"""
``get_functions_at`` get a list of binaryninja.Function objects (one for each valid platform) that start at the
@@ -3670,13 +3733,13 @@ class BinaryView:
finally:
core.BNFreeFunctionList(funcs, count.value)
- def get_recent_function_at(self, addr:int) -> Optional['_function.Function']:
+ def get_recent_function_at(self, addr: int) -> Optional['_function.Function']:
func = core.BNGetRecentAnalysisFunctionForAddress(self.handle, addr)
if func is None:
return None
return _function.Function(self, func)
- def get_basic_blocks_at(self, addr:int) -> List['basicblock.BasicBlock']:
+ def get_basic_blocks_at(self, addr: int) -> List['basicblock.BasicBlock']:
"""
``get_basic_blocks_at`` get a list of :py:Class:`BasicBlock` objects which exist at the provided virtual address.
@@ -3697,7 +3760,7 @@ class BinaryView:
finally:
core.BNFreeBasicBlockList(blocks, count.value)
- def get_basic_blocks_starting_at(self, addr:int) -> List['basicblock.BasicBlock']:
+ def get_basic_blocks_starting_at(self, addr: int) -> List['basicblock.BasicBlock']:
"""
``get_basic_blocks_starting_at`` get a list of :py:Class:`BasicBlock` objects which start at the provided virtual address.
@@ -3718,13 +3781,13 @@ class BinaryView:
finally:
core.BNFreeBasicBlockList(blocks, count.value)
- def get_recent_basic_block_at(self, addr:int) -> Optional['basicblock.BasicBlock']:
+ def get_recent_basic_block_at(self, addr: int) -> Optional['basicblock.BasicBlock']:
block = core.BNGetRecentBasicBlockForAddress(self.handle, addr)
if block is None:
return None
return basicblock.BasicBlock(block, self)
- def get_code_refs(self, addr:int, length:int=None) -> Generator['ReferenceSource', None, None]:
+ def get_code_refs(self, addr: int, length: int = None) -> Generator['ReferenceSource', None, None]:
"""
``get_code_refs`` returns a Generator[ReferenceSource] objects (xrefs or cross-references) that point to the provided virtual address.
This function returns both autoanalysis ("auto") and user-specified ("user") xrefs.
@@ -3755,7 +3818,10 @@ class BinaryView:
finally:
core.BNFreeCodeReferences(refs, count.value)
- def get_code_refs_from(self, addr:int, func:Optional['_function.Function']=None, arch:Optional['architecture.Architecture']=None, length:Optional[int]=None) -> List[int]:
+ def get_code_refs_from(
+ self, addr: int, func: Optional['_function.Function'] = None,
+ arch: Optional['architecture.Architecture'] = None, length: Optional[int] = None
+ ) -> List[int]:
"""
``get_code_refs_from`` returns a list of virtual addresses referenced by code in the function ``func``,
of the architecture ``arch``, and at the address ``addr``. If no function is specified, references from
@@ -3791,7 +3857,7 @@ class BinaryView:
core.BNFreeAddressList(refs)
return result
- def get_data_refs(self, addr:int, length:int=None) -> Generator[int, None, None]:
+ def get_data_refs(self, addr: int, length: int = None) -> Generator[int, None, None]:
"""
``get_data_refs`` returns a list of virtual addresses of data which references ``addr``. Optionally specifying
a length. When ``length`` is set ``get_data_refs`` returns the data which references in the range ``addr``-``addr``+``length``.
@@ -3822,7 +3888,7 @@ class BinaryView:
finally:
core.BNFreeDataReferences(refs)
- def get_data_refs_from(self, addr:int, length:int=None) -> Generator[int, None, None]:
+ def get_data_refs_from(self, addr: int, length: int = None) -> Generator[int, None, None]:
"""
``get_data_refs_from`` returns a list of virtual addresses referenced by the address ``addr``. Optionally specifying
a length. When ``length`` is set ``get_data_refs_from`` returns the data referenced in the range ``addr``-``addr``+``length``.
@@ -3853,7 +3919,7 @@ class BinaryView:
finally:
core.BNFreeDataReferences(refs)
- def get_code_refs_for_type(self, name:str) -> Generator[ReferenceSource, None, None]:
+ def get_code_refs_for_type(self, name: str) -> Generator[ReferenceSource, None, None]:
"""
``get_code_refs_for_type`` returns a Generator[ReferenceSource] objects (xrefs or cross-references) that reference the provided QualifiedName.
@@ -3878,8 +3944,8 @@ class BinaryView:
finally:
core.BNFreeCodeReferences(refs, count.value)
-
- def get_code_refs_for_type_field(self, name:str, offset:int) -> Generator['_types.TypeFieldReference', None, None]:
+ def get_code_refs_for_type_field(self, name: str,
+ offset: int) -> Generator['_types.TypeFieldReference', None, None]:
"""
``get_code_refs_for_type`` returns a Generator[TypeFieldReference] objects (xrefs or cross-references) that reference the provided type field.
@@ -3913,13 +3979,14 @@ class BinaryView:
size = refs[i].size
typeObj = None
if refs[i].incomingType.type:
- typeObj = _types.Type(core.BNNewTypeReference(refs[i].incomingType.type),
- confidence = refs[i].incomingType.confidence)
+ typeObj = _types.Type(
+ core.BNNewTypeReference(refs[i].incomingType.type), confidence=refs[i].incomingType.confidence
+ )
yield _types.TypeFieldReference(func, arch, addr, size, typeObj)
finally:
core.BNFreeTypeFieldReferences(refs, count.value)
- def get_data_refs_for_type(self, name:str) -> Generator[int, None, None]:
+ def get_data_refs_for_type(self, name: str) -> Generator[int, None, None]:
"""
``get_data_refs_for_type`` returns a list of virtual addresses of data which references the type ``name``.
Note, the returned addresses are the actual start of the queried type. For example, suppose there is a DataVariable
@@ -3946,8 +4013,7 @@ class BinaryView:
finally:
core.BNFreeDataReferences(refs)
-
- def get_data_refs_for_type_field(self, name:'_types.QualifiedNameType', offset:int) -> List[int]:
+ def get_data_refs_for_type_field(self, name: '_types.QualifiedNameType', offset: int) -> List[int]:
"""
``get_data_refs_for_type_field`` returns a list of virtual addresses of data which references the type ``name``.
Note, the returned addresses are the actual start of the queried type field. For example, suppose there is a
@@ -3977,8 +4043,7 @@ class BinaryView:
finally:
core.BNFreeDataReferences(refs)
-
- def get_type_refs_for_type(self, name:'_types.QualifiedNameType') -> List['_types.TypeReferenceSource']:
+ def get_type_refs_for_type(self, name: '_types.QualifiedNameType') -> List['_types.TypeReferenceSource']:
"""
``get_type_refs_for_type`` returns a list of TypeReferenceSource objects (xrefs or cross-references) that reference the provided QualifiedName.
@@ -4000,14 +4065,16 @@ class BinaryView:
result = []
try:
for i in range(0, count.value):
- type_field = _types.TypeReferenceSource(_types.QualifiedName._from_core_struct(refs[i].name), refs[i].offset, refs[i].type)
+ type_field = _types.TypeReferenceSource(
+ _types.QualifiedName._from_core_struct(refs[i].name), refs[i].offset, refs[i].type
+ )
result.append(type_field)
return result
finally:
core.BNFreeTypeReferences(refs, count.value)
-
- def get_type_refs_for_type_field(self, name:'_types.QualifiedNameType', offset:int) -> List['_types.TypeReferenceSource']:
+ def get_type_refs_for_type_field(self, name: '_types.QualifiedNameType',
+ offset: int) -> List['_types.TypeReferenceSource']:
"""
``get_type_refs_for_type`` returns a list of TypeReferenceSource objects (xrefs or cross-references) that reference the provided type field.
@@ -4030,13 +4097,18 @@ class BinaryView:
result = []
try:
for i in range(0, count.value):
- type_field = _types.TypeReferenceSource(_types.QualifiedName._from_core_struct(refs[i].name), refs[i].offset, refs[i].type)
+ type_field = _types.TypeReferenceSource(
+ _types.QualifiedName._from_core_struct(refs[i].name), refs[i].offset, refs[i].type
+ )
result.append(type_field)
return result
finally:
core.BNFreeTypeReferences(refs, count.value)
- def get_code_refs_for_type_from(self, addr:int, func:Optional['_function.Function']=None, arch:Optional['architecture.Architecture']= None, length:Optional[int] = None) -> List['_types.TypeReferenceSource']:
+ def get_code_refs_for_type_from(
+ self, addr: int, func: Optional['_function.Function'] = None,
+ arch: Optional['architecture.Architecture'] = None, length: Optional[int] = None
+ ) -> List['_types.TypeReferenceSource']:
"""
``get_code_refs_for_type_from`` returns a list of types referenced by code in the function ``func``,
of the architecture ``arch``, and at the address ``addr``. If no function is specified, references from
@@ -4065,13 +4137,18 @@ class BinaryView:
assert refs is not None, "core.BNGetCodeReferencesForTypeFromInRange returned None"
try:
for i in range(0, count.value):
- type_field = _types.TypeReferenceSource(_types.QualifiedName._from_core_struct(refs[i].name), refs[i].offset, refs[i].type)
+ type_field = _types.TypeReferenceSource(
+ _types.QualifiedName._from_core_struct(refs[i].name), refs[i].offset, refs[i].type
+ )
result.append(type_field)
finally:
core.BNFreeTypeReferences(refs, count.value)
return result
- def get_code_refs_for_type_fields_from(self, addr:int, func:Optional['_function.Function']=None, arch:Optional['architecture.Architecture']= None, length:Optional[int] = None) -> List['_types.TypeReferenceSource']:
+ def get_code_refs_for_type_fields_from(
+ self, addr: int, func: Optional['_function.Function'] = None,
+ arch: Optional['architecture.Architecture'] = None, length: Optional[int] = None
+ ) -> List['_types.TypeReferenceSource']:
"""
``get_code_refs_for_type_fields_from`` returns a list of type fields referenced by code in the function ``func``,
of the architecture ``arch``, and at the address ``addr``. If no function is specified, references from
@@ -4100,13 +4177,15 @@ class BinaryView:
assert refs is not None, "core.BNGetCodeReferencesForTypeFieldsFromInRange returned None"
try:
for i in range(0, count.value):
- type_field = _types.TypeReferenceSource(_types.QualifiedName._from_core_struct(refs[i].name), refs[i].offset, refs[i].type)
+ type_field = _types.TypeReferenceSource(
+ _types.QualifiedName._from_core_struct(refs[i].name), refs[i].offset, refs[i].type
+ )
result.append(type_field)
finally:
core.BNFreeTypeReferences(refs, count.value)
return result
- def add_user_data_ref(self, from_addr:int, to_addr:int) -> None:
+ def add_user_data_ref(self, from_addr: int, to_addr: int) -> None:
"""
``add_user_data_ref`` adds a user-specified data cross-reference (xref) from the address ``from_addr`` to the address ``to_addr``.
If the reference already exists, no action is performed. To remove the reference, use :func:`remove_user_data_ref`.
@@ -4117,8 +4196,7 @@ class BinaryView:
"""
core.BNAddUserDataReference(self.handle, from_addr, to_addr)
-
- def remove_user_data_ref(self, from_addr:int, to_addr:int) -> None:
+ def remove_user_data_ref(self, from_addr: int, to_addr: int) -> None:
"""
``remove_user_data_ref`` removes a user-specified data cross-reference (xref) from the address ``from_addr`` to the address ``to_addr``.
This function will only remove user-specified references, not ones generated during autoanalysis.
@@ -4130,8 +4208,7 @@ class BinaryView:
"""
core.BNRemoveUserDataReference(self.handle, from_addr, to_addr)
-
- def get_all_fields_referenced(self, name:'_types.QualifiedNameType') -> List[int]:
+ def get_all_fields_referenced(self, name: '_types.QualifiedNameType') -> List[int]:
"""
``get_all_fields_referenced`` returns a list of offsets in the QualifiedName
specified by name, which are referenced by code.
@@ -4159,7 +4236,7 @@ class BinaryView:
finally:
core.BNFreeDataReferences(refs)
- def get_all_sizes_referenced(self, name:'_types.QualifiedNameType') -> Mapping[int, List[int]]:
+ def get_all_sizes_referenced(self, name: '_types.QualifiedNameType') -> Mapping[int, List[int]]:
"""
``get_all_sizes_referenced`` returns a map from field offset to a list of sizes of
the accesses to it.
@@ -4178,7 +4255,7 @@ class BinaryView:
_name = _types.QualifiedName(name)._to_core_struct()
refs = core.BNGetAllSizesReferenced(self.handle, _name, count)
assert refs is not None, "core.BNGetAllSizesReferenced returned None"
- result:Mapping[int, List[int]] = {}
+ result: Mapping[int, List[int]] = {}
try:
for i in range(0, count.value):
result[refs[i].offset] = []
@@ -4188,7 +4265,7 @@ class BinaryView:
finally:
core.BNFreeTypeFieldReferenceSizeInfo(refs, count.value)
- def get_all_types_referenced(self, name:'_types.QualifiedNameType') -> Mapping[int, List['_types.Type']]:
+ def get_all_types_referenced(self, name: '_types.QualifiedNameType') -> Mapping[int, List['_types.Type']]:
"""
``get_all_types_referenced`` returns a map from field offset to a related to the
type field access.
@@ -4209,19 +4286,20 @@ class BinaryView:
refs = core.BNGetAllTypesReferenced(self.handle, _name, count)
assert refs is not None, "core.BNGetAllTypesReferenced returned None"
- result:Mapping[int, List['_types.Type']] = {}
+ result: Mapping[int, List['_types.Type']] = {}
try:
for i in range(0, count.value):
result[refs[i].offset] = []
for j in range(0, refs[i].count):
- typeObj = _types.Type.create(core.BNNewTypeReference(refs[i].types[j].type),
- self.platform, refs[i].types[j].confidence)
+ typeObj = _types.Type.create(
+ core.BNNewTypeReference(refs[i].types[j].type), self.platform, refs[i].types[j].confidence
+ )
result[refs[i].offset].append(typeObj)
return result
finally:
core.BNFreeTypeFieldReferenceTypeInfo(refs, count.value)
- def get_sizes_referenced(self, name:'_types.QualifiedNameType', offset:int) -> List[int]:
+ def get_sizes_referenced(self, name: '_types.QualifiedNameType', offset: int) -> List[int]:
"""
``get_sizes_referenced`` returns a list of sizes of the accesses to it.
@@ -4249,7 +4327,7 @@ class BinaryView:
finally:
core.BNFreeTypeFieldReferenceSizes(refs, count.value)
- def get_types_referenced(self, name:'_types.QualifiedName', offset:int) -> List['_types.Type']:
+ def get_types_referenced(self, name: '_types.QualifiedName', offset: int) -> List['_types.Type']:
"""
``get_types_referenced`` returns a list of types related to the type field access.
@@ -4270,14 +4348,13 @@ class BinaryView:
try:
result = []
for i in range(0, count.value):
- typeObj = _types.Type.create(core.BNNewTypeReference(refs[i].type),
- confidence = refs[i].confidence)
+ typeObj = _types.Type.create(core.BNNewTypeReference(refs[i].type), confidence=refs[i].confidence)
result.append(typeObj)
return result
finally:
core.BNFreeTypeFieldReferenceTypes(refs, count.value)
- def create_structure_from_offset_access(self, name:'_types.QualifiedName') -> '_types.StructureType':
+ def create_structure_from_offset_access(self, name: '_types.QualifiedName') -> '_types.StructureType':
newMemberAdded = ctypes.c_bool(False)
_name = _types.QualifiedName(name)._to_core_struct()
struct = core.BNCreateStructureFromOffsetAccess(self.handle, _name, newMemberAdded)
@@ -4285,16 +4362,15 @@ class BinaryView:
raise Exception("BNCreateStructureFromOffsetAccess failed to create struct from offsets")
return _types.StructureType.from_core_struct(struct)
- def create_structure_member_from_access(self, name:'_types.QualifiedName', offset:int) -> '_types.Type':
+ def create_structure_member_from_access(self, name: '_types.QualifiedName', offset: int) -> '_types.Type':
_name = _types.QualifiedName(name)._to_core_struct()
result = core.BNCreateStructureMemberFromAccess(self.handle, _name, offset)
if not result.type:
raise Exception("BNCreateStructureMemberFromAccess failed to create struct member offsets")
- return _types.Type.create(core.BNNewTypeReference(result.type),
- confidence = result.confidence)
+ return _types.Type.create(core.BNNewTypeReference(result.type), confidence=result.confidence)
- def get_callers(self, addr:int) -> Generator[ReferenceSource, None, None]:
+ def get_callers(self, addr: int) -> Generator[ReferenceSource, None, None]:
"""
``get_callers`` returns 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.
@@ -4318,7 +4394,8 @@ class BinaryView:
finally:
core.BNFreeCodeReferences(refs, count.value)
- def get_callees(self, addr:int, func:'_function.Function'=None, arch:'architecture.Architecture'=None) -> List[int]:
+ def get_callees(self, addr: int, func: '_function.Function' = None,
+ arch: 'architecture.Architecture' = None) -> List[int]:
"""
``get_callees`` returns a list of virtual addresses called by the call site in the function ``func``,
of the architecture ``arch``, and at the address ``addr``. If no function is specified, call sites from
@@ -4350,7 +4427,7 @@ class BinaryView:
core.BNFreeAddressList(refs)
return result
- def get_symbol_at(self, addr:int, namespace:'_types.NameSpaceType'=None) -> Optional['_types.CoreSymbol']:
+ def get_symbol_at(self, addr: int, namespace: '_types.NameSpaceType' = None) -> Optional['_types.CoreSymbol']:
"""
``get_symbol_at`` returns the Symbol at the provided virtual address.
@@ -4370,7 +4447,7 @@ class BinaryView:
return None
return _types.CoreSymbol(sym)
- def get_symbols_by_raw_name(self, name:str, namespace:'_types.NameSpaceType'=None) -> List['_types.CoreSymbol']:
+ def get_symbols_by_raw_name(self, name: str, namespace: '_types.NameSpaceType' = None) -> List['_types.CoreSymbol']:
_namespace = _types.NameSpace.get_core_struct(namespace)
count = ctypes.c_ulonglong(0)
syms = core.BNGetSymbolsByRawName(self.handle, name, count, _namespace)
@@ -4385,7 +4462,8 @@ class BinaryView:
finally:
core.BNFreeSymbolList(syms, count.value)
- def get_symbol_by_raw_name(self, name:str, namespace:'_types.NameSpaceType'=None) -> Optional['_types.CoreSymbol']:
+ def get_symbol_by_raw_name(self, name: str,
+ namespace: '_types.NameSpaceType' = None) -> Optional['_types.CoreSymbol']:
"""
``get_symbol_by_raw_name`` retrieves a Symbol object for the given a raw (mangled) name.
@@ -4405,7 +4483,9 @@ class BinaryView:
return None
return _types.CoreSymbol(sym)
- def get_symbols_by_name(self, name:str, namespace:'_types.NameSpaceType'=None, ordered_filter:Optional[List[SymbolType]]=None) -> List['_types.CoreSymbol']:
+ def get_symbols_by_name(
+ self, name: str, namespace: '_types.NameSpaceType' = None, ordered_filter: Optional[List[SymbolType]] = None
+ ) -> List['_types.CoreSymbol']:
"""
``get_symbols_by_name`` retrieves a list of Symbol objects for the given symbol name and ordered filter
@@ -4422,13 +4502,11 @@ class BinaryView:
>>>
"""
if ordered_filter is None:
- ordered_filter = [SymbolType.FunctionSymbol,
- SymbolType.ImportedFunctionSymbol,
- SymbolType.LibraryFunctionSymbol,
- SymbolType.DataSymbol,
- SymbolType.ImportedDataSymbol,
- SymbolType.ImportAddressSymbol,
- SymbolType.ExternalSymbol]
+ ordered_filter = [
+ SymbolType.FunctionSymbol, SymbolType.ImportedFunctionSymbol, SymbolType.LibraryFunctionSymbol,
+ SymbolType.DataSymbol, SymbolType.ImportedDataSymbol, SymbolType.ImportAddressSymbol,
+ SymbolType.ExternalSymbol
+ ]
_namespace = _types.NameSpace.get_core_struct(namespace)
count = ctypes.c_ulonglong(0)
@@ -4440,12 +4518,16 @@ class BinaryView:
handle = core.BNNewSymbolReference(syms[i])
assert handle is not None, "core.BNNewSymbolReference returned None"
result.append(_types.CoreSymbol(handle))
- result = sorted(filter(lambda sym: sym.type in ordered_filter, result), key=lambda sym: ordered_filter.index(sym.type))
+ result = sorted(
+ filter(lambda sym: sym.type in ordered_filter, result), key=lambda sym: ordered_filter.index(sym.type)
+ )
return result
finally:
core.BNFreeSymbolList(syms, count.value)
- def get_symbols(self, start:Optional[int]=None, length:Optional[int]=None, namespace:'_types.NameSpaceType'=None) -> List['_types.CoreSymbol']:
+ def get_symbols(
+ self, start: Optional[int] = None, length: Optional[int] = None, namespace: '_types.NameSpaceType' = None
+ ) -> List['_types.CoreSymbol']:
"""
``get_symbols`` retrieves the list of all Symbol objects in the optionally provided range.
@@ -4479,8 +4561,10 @@ class BinaryView:
finally:
core.BNFreeSymbolList(syms, count.value)
- def get_symbols_of_type(self, sym_type:SymbolType, start:Optional[int]=None, length:Optional[int]=None,
- namespace:'_types.NameSpaceType'=None) -> List['_types.CoreSymbol']:
+ def get_symbols_of_type(
+ self, sym_type: SymbolType, start: Optional[int] = None, length: Optional[int] = None,
+ namespace: '_types.NameSpaceType' = None
+ ) -> List['_types.CoreSymbol']:
"""
``get_symbols_of_type`` retrieves a list of all Symbol objects of the provided symbol type in the optionally
provided range.
@@ -4517,7 +4601,7 @@ class BinaryView:
finally:
core.BNFreeSymbolList(syms, count.value)
- def define_auto_symbol(self, sym:'_types.CoreSymbol') -> None:
+ def define_auto_symbol(self, sym: '_types.CoreSymbol') -> None:
"""
``define_auto_symbol`` adds a symbol to the internal list of automatically discovered Symbol objects in a given
namespace.
@@ -4529,8 +4613,9 @@ class BinaryView:
"""
core.BNDefineAutoSymbol(self.handle, sym.handle)
- def define_auto_symbol_and_var_or_function(self, sym:'_types.CoreSymbol', sym_type:SymbolType,
- plat:Optional['_platform.Platform']=None) -> Optional['_types.CoreSymbol']:
+ def define_auto_symbol_and_var_or_function(
+ self, sym: '_types.CoreSymbol', sym_type: SymbolType, plat: Optional['_platform.Platform'] = None
+ ) -> Optional['_types.CoreSymbol']:
"""
``define_auto_symbol_and_var_or_function``
@@ -4558,7 +4643,7 @@ class BinaryView:
return None
return _types.CoreSymbol(_sym)
- def undefine_auto_symbol(self, sym:'_types.CoreSymbol') -> None:
+ def undefine_auto_symbol(self, sym: '_types.CoreSymbol') -> None:
"""
``undefine_auto_symbol`` removes a symbol from the internal list of automatically discovered Symbol objects.
@@ -4567,7 +4652,7 @@ class BinaryView:
"""
core.BNUndefineAutoSymbol(self.handle, sym.handle)
- def define_user_symbol(self, sym:'_types.CoreSymbol') -> None:
+ def define_user_symbol(self, sym: '_types.CoreSymbol') -> None:
"""
``define_user_symbol`` adds a symbol to the internal list of user added Symbol objects.
@@ -4578,7 +4663,7 @@ class BinaryView:
"""
core.BNDefineUserSymbol(self.handle, sym.handle)
- def undefine_user_symbol(self, sym:'_types.CoreSymbol') -> None:
+ def undefine_user_symbol(self, sym: '_types.CoreSymbol') -> None:
"""
``undefine_user_symbol`` removes a symbol from the internal list of user added Symbol objects.
@@ -4587,7 +4672,9 @@ class BinaryView:
"""
core.BNUndefineUserSymbol(self.handle, sym.handle)
- def define_imported_function(self, import_addr_sym:'_types.CoreSymbol', func:'_function.Function', type:Optional['_types.Type']=None) -> None:
+ def define_imported_function(
+ self, import_addr_sym: '_types.CoreSymbol', func: '_function.Function', type: Optional['_types.Type'] = None
+ ) -> None:
"""
``define_imported_function`` defines an imported Function ``func`` with a ImportedFunctionSymbol type.
@@ -4595,9 +4682,11 @@ class BinaryView:
:param Function func: A Function object to define as an imported function
:rtype: None
"""
- core.BNDefineImportedFunction(self.handle, import_addr_sym.handle, func.handle, None if type is None else type.handle)
+ core.BNDefineImportedFunction(
+ self.handle, import_addr_sym.handle, func.handle, None if type is None else type.handle
+ )
- def create_tag_type(self, name:str, icon:str) -> 'TagType':
+ def create_tag_type(self, name: str, icon: str) -> 'TagType':
"""
``create_tag_type`` creates a new Tag Type and adds it to the view
@@ -4619,7 +4708,7 @@ class BinaryView:
core.BNAddTagType(self.handle, tag_type.handle)
return tag_type
- def remove_tag_type(self, tag_type:'TagType') -> None:
+ def remove_tag_type(self, tag_type: 'TagType') -> None:
"""
``remove_tag_type`` removes a new Tag Type and all tags that use it
@@ -4642,7 +4731,7 @@ class BinaryView:
count = ctypes.c_ulonglong(0)
types = core.BNGetTagTypes(self.handle, count)
assert types is not None, "core.BNGetTagTypes returned None"
- result:Mapping[str, Union['TagType', List['TagType']]] = {}
+ result: Mapping[str, Union['TagType', List['TagType']]] = {}
try:
for i in range(0, count.value):
tag_handle = core.BNNewTagTypeReference(types[i])
@@ -4661,7 +4750,7 @@ class BinaryView:
finally:
core.BNFreeTagTypeList(types, count.value)
- def get_tag_type(self, name:str) -> Optional['TagType']:
+ def get_tag_type(self, name: str) -> Optional['TagType']:
"""
Get a tag type by its name. Shorthand for get_tag_type_by_name()
:param name: Name of the tag type
@@ -4670,7 +4759,7 @@ class BinaryView:
"""
return self.get_tag_type_by_name(name)
- def get_tag_type_by_name(self, name:str) -> Optional['TagType']:
+ def get_tag_type_by_name(self, name: str) -> Optional['TagType']:
"""
Get a tag type by its name
:param name: Name of the tag type
@@ -4682,7 +4771,7 @@ class BinaryView:
return None
return TagType(tag_type)
- def get_tag_type_by_id(self, id:str) -> Optional['TagType']:
+ def get_tag_type_by_id(self, id: str) -> Optional['TagType']:
"""
Get a tag type by its id
:param id: Id of the tag type
@@ -4694,13 +4783,13 @@ class BinaryView:
return None
return TagType(tag_type)
- def create_user_tag(self, type:'TagType', data:str) -> 'Tag':
+ def create_user_tag(self, type: 'TagType', data: str) -> 'Tag':
return self.create_tag(type, data, True)
- def create_auto_tag(self, type:'TagType', data:str) -> 'Tag':
+ def create_auto_tag(self, type: 'TagType', data: str) -> 'Tag':
return self.create_tag(type, data, False)
- def create_tag(self, tag_type:'TagType', data:str, user:bool=True) -> 'Tag':
+ def create_tag(self, tag_type: 'TagType', data: str, user: bool = True) -> 'Tag':
"""
``create_tag`` creates a new Tag object but does not add it anywhere.
Use :py:meth:`create_user_data_tag` to create and add in one step.
@@ -4725,7 +4814,7 @@ class BinaryView:
core.BNAddTag(self.handle, tag.handle, user)
return tag
- def get_tag(self, id:str) -> Optional['Tag']:
+ def get_tag(self, id: str) -> Optional['Tag']:
"""
Get a tag by its id. Note this does not tell you anything about where it is used.
:param id: Tag id
@@ -4807,7 +4896,7 @@ class BinaryView:
finally:
core.BNFreeTagReferences(refs, count.value)
- def get_data_tags_at(self, addr:int) -> List['Tag']:
+ def get_data_tags_at(self, addr: int) -> List['Tag']:
"""
``get_data_tags_at`` gets a list of all Tags for a data address.
@@ -4828,7 +4917,7 @@ class BinaryView:
finally:
core.BNFreeTagList(tags, count.value)
- def get_auto_data_tags_at(self, addr:int) -> List['Tag']:
+ def get_auto_data_tags_at(self, addr: int) -> List['Tag']:
"""
``get_auto_data_tags_at`` gets a list of all auto-defined Tags for a data address.
@@ -4849,7 +4938,7 @@ class BinaryView:
finally:
core.BNFreeTagList(tags, count.value)
- def get_user_data_tags_at(self, addr:int) -> List['Tag']:
+ def get_user_data_tags_at(self, addr: int) -> List['Tag']:
"""
``get_user_data_tags_at`` gets a list of all user Tags for a data address.
@@ -4870,7 +4959,7 @@ class BinaryView:
finally:
core.BNFreeTagList(tags, count.value)
- def get_data_tags_of_type(self, addr:int, tag_type:'TagType') -> List['Tag']:
+ def get_data_tags_of_type(self, addr: int, tag_type: 'TagType') -> List['Tag']:
"""
``get_data_tags_of_type`` gets a list of all Tags for a data address of a given type.
@@ -4892,7 +4981,7 @@ class BinaryView:
finally:
core.BNFreeTagList(tags, count.value)
- def get_auto_data_tags_of_type(self, addr:int, tag_type:'TagType') -> List['Tag']:
+ def get_auto_data_tags_of_type(self, addr: int, tag_type: 'TagType') -> List['Tag']:
"""
``get_auto_data_tags_of_type`` gets a list of all auto-defined Tags for a data address of a given type.
@@ -4914,7 +5003,7 @@ class BinaryView:
finally:
core.BNFreeTagList(tags, count.value)
- def get_user_data_tags_of_type(self, addr:int, tag_type:'TagType') -> List['Tag']:
+ def get_user_data_tags_of_type(self, addr: int, tag_type: 'TagType') -> List['Tag']:
"""
``get_user_data_tags_of_type`` gets a list of all user Tags for a data address of a given type.
@@ -4936,7 +5025,7 @@ class BinaryView:
finally:
core.BNFreeTagList(tags, count.value)
- def get_data_tags_in_range(self, address_range:'variable.AddressRange') -> List[Tuple[int, 'Tag']]:
+ def get_data_tags_in_range(self, address_range: 'variable.AddressRange') -> List[Tuple[int, 'Tag']]:
"""
``get_data_tags_in_range`` gets a list of all data Tags in a given range.
Range is inclusive at the start, exclusive at the end.
@@ -4959,7 +5048,7 @@ class BinaryView:
finally:
core.BNFreeTagReferences(refs, count.value)
- def get_auto_data_tags_in_range(self, address_range:'variable.AddressRange') -> List[Tuple[int, 'Tag']]:
+ def get_auto_data_tags_in_range(self, address_range: 'variable.AddressRange') -> List[Tuple[int, 'Tag']]:
"""
``get_auto_data_tags_in_range`` gets a list of all auto-defined data Tags in a given range.
Range is inclusive at the start, exclusive at the end.
@@ -4982,7 +5071,7 @@ class BinaryView:
finally:
core.BNFreeTagReferences(refs, count.value)
- def get_user_data_tags_in_range(self, address_range:'variable.AddressRange') -> List[Tuple[int, 'Tag']]:
+ def get_user_data_tags_in_range(self, address_range: 'variable.AddressRange') -> List[Tuple[int, 'Tag']]:
"""
``get_user_data_tags_in_range`` gets a list of all user data Tags in a given range.
Range is inclusive at the start, exclusive at the end.
@@ -5005,7 +5094,7 @@ class BinaryView:
finally:
core.BNFreeTagReferences(refs, count.value)
- def add_user_data_tag(self, addr:int, tag:'Tag') -> None:
+ def add_user_data_tag(self, addr: int, tag: 'Tag') -> None:
"""
``add_user_data_tag`` adds an already-created Tag object at a data address.
Since this adds a user tag, it will be added to the current undo buffer.
@@ -5018,7 +5107,7 @@ class BinaryView:
"""
core.BNAddUserDataTag(self.handle, addr, tag.handle)
- def create_user_data_tag(self, addr:int, type:'TagType', data:str, unique:bool=False) -> 'Tag':
+ def create_user_data_tag(self, addr: int, type: 'TagType', data: str, unique: bool = False) -> 'Tag':
"""
``create_user_data_tag`` creates and adds a Tag object at a data
address. Since this adds a user tag, it will be added to the current
@@ -5050,7 +5139,7 @@ class BinaryView:
core.BNAddUserDataTag(self.handle, addr, tag.handle)
return tag
- def remove_user_data_tag(self, addr:int, tag:Tag) -> None:
+ def remove_user_data_tag(self, addr: int, tag: Tag) -> None:
"""
``remove_user_data_tag`` removes a Tag object at a data address.
Since this removes a user tag, it will be added to the current undo buffer.
@@ -5061,7 +5150,7 @@ class BinaryView:
"""
core.BNRemoveUserDataTag(self.handle, addr, tag.handle)
- def remove_user_data_tags_of_type(self, addr:int, tag_type:'TagType') -> None:
+ def remove_user_data_tags_of_type(self, addr: int, tag_type: 'TagType') -> None:
"""
``remove_user_data_tags_of_type`` removes 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.
@@ -5072,7 +5161,7 @@ class BinaryView:
"""
core.BNRemoveUserDataTagsOfType(self.handle, addr, tag_type.handle)
- def add_auto_data_tag(self, addr:int, tag:'Tag') -> None:
+ def add_auto_data_tag(self, addr: int, tag: 'Tag') -> None:
"""
``add_auto_data_tag`` adds an already-created Tag object at a data address.
If you want want to create the tag as well, consider using
@@ -5084,7 +5173,7 @@ class BinaryView:
"""
core.BNAddAutoDataTag(self.handle, addr, tag.handle)
- def create_auto_data_tag(self, addr:int, type:'TagType', data:str, unique:bool=False) -> 'Tag':
+ def create_auto_data_tag(self, addr: int, type: 'TagType', data: str, unique: bool = False) -> 'Tag':
"""
``create_auto_data_tag`` creates and adds a Tag object at a data address.
@@ -5105,7 +5194,7 @@ class BinaryView:
core.BNAddAutoDataTag(self.handle, addr, tag.handle)
return tag
- def remove_auto_data_tag(self, addr:int, tag:'Tag') -> None:
+ def remove_auto_data_tag(self, addr: int, tag: 'Tag') -> None:
"""
``remove_auto_data_tag`` removes a Tag object at a data address.
Since this removes a user tag, it will be added to the current undo buffer.
@@ -5116,7 +5205,7 @@ class BinaryView:
"""
core.BNRemoveAutoDataTag(self.handle, addr, tag.handle)
- def remove_auto_data_tags_of_type(self, addr:int, tag_type:'TagType') -> None:
+ def remove_auto_data_tags_of_type(self, addr: int, tag_type: 'TagType') -> None:
"""
``remove_auto_data_tags_of_type`` removes 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.
@@ -5127,7 +5216,7 @@ class BinaryView:
"""
core.BNRemoveAutoDataTagsOfType(self.handle, addr, tag_type.handle)
- def can_assemble(self, arch:Optional['architecture.Architecture']=None) -> bool:
+ def can_assemble(self, arch: Optional['architecture.Architecture'] = None) -> bool:
"""
``can_assemble`` queries the architecture plugin to determine if the architecture can assemble instructions.
@@ -5145,7 +5234,7 @@ class BinaryView:
arch = self.arch
return core.BNCanAssemble(self.handle, arch.handle)
- def is_never_branch_patch_available(self, addr:int, arch:Optional['architecture.Architecture']=None) -> bool:
+ def is_never_branch_patch_available(self, addr: int, arch: Optional['architecture.Architecture'] = None) -> bool:
"""
``is_never_branch_patch_available`` queries the architecture plugin to determine if the instruction at the
instruction at ``addr`` can be made to **never branch**. The actual logic of which is implemented in the
@@ -5173,7 +5262,7 @@ class BinaryView:
arch = self.arch
return core.BNIsNeverBranchPatchAvailable(self.handle, arch.handle, addr)
- def is_always_branch_patch_available(self, addr:int, arch:Optional['architecture.Architecture']=None) -> bool:
+ def is_always_branch_patch_available(self, addr: int, arch: Optional['architecture.Architecture'] = None) -> bool:
"""
``is_always_branch_patch_available`` queries the architecture plugin to determine if the
instruction at ``addr`` can be made to **always branch**. The actual logic of which is implemented in the
@@ -5201,7 +5290,7 @@ class BinaryView:
arch = self.arch
return core.BNIsAlwaysBranchPatchAvailable(self.handle, arch.handle, addr)
- def is_invert_branch_patch_available(self, addr:int, arch:Optional['architecture.Architecture']=None) -> bool:
+ def is_invert_branch_patch_available(self, addr: int, arch: Optional['architecture.Architecture'] = None) -> bool:
"""
``is_invert_branch_patch_available`` queries the architecture plugin to determine if the instruction at ``addr``
is a branch that can be inverted. The actual logic of which is implemented in the
@@ -5230,7 +5319,9 @@ class BinaryView:
arch = self.arch
return core.BNIsInvertBranchPatchAvailable(self.handle, arch.handle, addr)
- def is_skip_and_return_zero_patch_available(self, addr:int, arch:Optional['architecture.Architecture']=None) -> bool:
+ def is_skip_and_return_zero_patch_available(
+ self, addr: int, arch: Optional['architecture.Architecture'] = None
+ ) -> bool:
"""
``is_skip_and_return_zero_patch_available`` queries the architecture plugin to determine if the
instruction at ``addr`` is similar to an x86 "call" instruction which can be made to return zero. The actual
@@ -5259,7 +5350,9 @@ class BinaryView:
arch = self.arch
return core.BNIsSkipAndReturnZeroPatchAvailable(self.handle, arch.handle, addr)
- def is_skip_and_return_value_patch_available(self, addr:int, arch:Optional['architecture.Architecture']=None) -> bool:
+ def is_skip_and_return_value_patch_available(
+ self, addr: int, arch: Optional['architecture.Architecture'] = None
+ ) -> bool:
"""
``is_skip_and_return_value_patch_available`` queries the architecture plugin to determine if the
instruction at ``addr`` is similar to an x86 "call" instruction which can be made to return a value. The actual
@@ -5288,7 +5381,7 @@ class BinaryView:
arch = self.arch
return core.BNIsSkipAndReturnValuePatchAvailable(self.handle, arch.handle, addr)
- def convert_to_nop(self, addr:int, arch:Optional['architecture.Architecture']=None) -> bool:
+ def convert_to_nop(self, addr: int, arch: Optional['architecture.Architecture'] = None) -> bool:
"""
``convert_to_nop`` converts the instruction at virtual address ``addr`` to a nop of the provided architecture.
@@ -5326,7 +5419,7 @@ class BinaryView:
arch = self.arch
return core.BNConvertToNop(self.handle, arch.handle, addr)
- def always_branch(self, addr:int, arch:Optional['architecture.Architecture']=None) -> bool:
+ def always_branch(self, addr: int, arch: Optional['architecture.Architecture'] = None) -> bool:
"""
``always_branch`` convert the instruction of architecture ``arch`` at the virtual address ``addr`` to an
unconditional branch.
@@ -5354,7 +5447,7 @@ class BinaryView:
arch = self.arch
return core.BNAlwaysBranch(self.handle, arch.handle, addr)
- def never_branch(self, addr:int, arch:Optional['architecture.Architecture']=None) -> bool:
+ def never_branch(self, addr: int, arch: Optional['architecture.Architecture'] = None) -> bool:
"""
``never_branch`` convert the branch instruction of architecture ``arch`` at the virtual address ``addr`` to
a fall through.
@@ -5382,7 +5475,7 @@ class BinaryView:
arch = self.arch
return core.BNConvertToNop(self.handle, arch.handle, addr)
- def invert_branch(self, addr:int, arch:Optional['architecture.Architecture']=None) -> bool:
+ def invert_branch(self, addr: int, arch: Optional['architecture.Architecture'] = None) -> bool:
"""
``invert_branch`` convert the branch instruction of architecture ``arch`` at the virtual address ``addr`` to the
inverse branch.
@@ -5411,7 +5504,7 @@ class BinaryView:
arch = self.arch
return core.BNInvertBranch(self.handle, arch.handle, addr)
- def skip_and_return_value(self, addr:int, value:int, arch:Optional['architecture.Architecture']=None) -> bool:
+ def skip_and_return_value(self, addr: int, value: int, arch: Optional['architecture.Architecture'] = None) -> bool:
"""
``skip_and_return_value`` convert the ``call`` instruction of architecture ``arch`` at the virtual address
``addr`` to the equivalent of returning a value.
@@ -5438,7 +5531,7 @@ class BinaryView:
arch = self.arch
return core.BNSkipAndReturnValue(self.handle, arch.handle, addr, value)
- def get_instruction_length(self, addr:int, arch:Optional['architecture.Architecture']=None) -> int:
+ def get_instruction_length(self, addr: int, arch: Optional['architecture.Architecture'] = None) -> int:
"""
``get_instruction_length`` returns the number of bytes in the instruction of Architecture ``arch`` at the virtual
address ``addr``
@@ -5461,16 +5554,16 @@ class BinaryView:
arch = self.arch
return core.BNGetInstructionLength(self.handle, arch.handle, addr)
- def notify_data_written(self, offset:int, length:int) -> None:
+ def notify_data_written(self, offset: int, length: int) -> None:
core.BNNotifyDataWritten(self.handle, offset, length)
- def notify_data_inserted(self, offset:int, length:int) -> None:
+ def notify_data_inserted(self, offset: int, length: int) -> None:
core.BNNotifyDataInserted(self.handle, offset, length)
- def notify_data_removed(self, offset:int, length:int) -> None:
+ def notify_data_removed(self, offset: int, length: int) -> None:
core.BNNotifyDataRemoved(self.handle, offset, length)
- def get_strings(self, start:Optional[int] = None, length:Optional[int] = None) -> List['StringReference']:
+ def get_strings(self, start: Optional[int] = None, length: Optional[int] = None) -> List['StringReference']:
"""
``get_strings`` returns a list of strings defined in the binary in the optional virtual address range:
``start-(start+length)``
@@ -5504,7 +5597,7 @@ class BinaryView:
finally:
core.BNFreeStringReferenceList(strings)
- def get_string_at(self, addr:int, partial:bool=False) -> Optional['StringReference']:
+ def get_string_at(self, addr: int, partial: bool = False) -> Optional['StringReference']:
"""
``get_string_at`` returns the string that falls on given virtual address.
@@ -5530,7 +5623,8 @@ class BinaryView:
length = str_ref.length - (addr - str_ref.start) if partial else str_ref.length
return StringReference(self, StringType(str_ref.type), start, length)
- def get_ascii_string_at(self, addr:int, min_length:int=4, max_length:int=None, require_cstring:bool=True) -> Optional['StringReference']:
+ def get_ascii_string_at(self, addr: int, min_length: int = 4, max_length: int = None,
+ require_cstring: bool = True) -> Optional['StringReference']:
"""
``get_ascii_string_at`` returns an ascii string found at ``addr``.
@@ -5575,7 +5669,7 @@ class BinaryView:
return None
return StringReference(self, StringType.AsciiString, addr, length)
- def add_analysis_completion_event(self, callback:Callable[[], None]) -> 'AnalysisCompletionEvent':
+ def add_analysis_completion_event(self, callback: Callable[[], None]) -> 'AnalysisCompletionEvent':
"""
``add_analysis_completion_event`` sets up a call back function to be called when analysis has been completed.
This is helpful when using :func:`update_analysis` which does not wait for analysis completion before returning.
@@ -5600,7 +5694,7 @@ class BinaryView:
"""
return AnalysisCompletionEvent(self, callback)
- def get_next_function_start_after(self, addr:int) -> int:
+ def get_next_function_start_after(self, addr: int) -> int:
"""
``get_next_function_start_after`` returns the virtual address of the Function that occurs after the virtual address
``addr``
@@ -5622,7 +5716,7 @@ class BinaryView:
"""
return core.BNGetNextFunctionStartAfterAddress(self.handle, addr)
- def get_next_basic_block_start_after(self, addr:int) -> int:
+ def get_next_basic_block_start_after(self, addr: int) -> int:
"""
``get_next_basic_block_start_after`` returns the virtual address of the BasicBlock that occurs after the virtual
address ``addr``
@@ -5640,7 +5734,7 @@ class BinaryView:
"""
return core.BNGetNextBasicBlockStartAfterAddress(self.handle, addr)
- def get_next_data_after(self, addr:int) -> int:
+ def get_next_data_after(self, addr: int) -> int:
"""
``get_next_data_after`` retrieves the virtual address of the next non-code byte.
@@ -5654,7 +5748,7 @@ class BinaryView:
"""
return core.BNGetNextDataAfterAddress(self.handle, addr)
- def get_next_data_var_after(self, addr:int) -> Optional['DataVariable']:
+ def get_next_data_var_after(self, addr: int) -> Optional['DataVariable']:
"""
``get_next_data_var_after`` retrieves the next :py:Class:`DataVariable`, or None.
@@ -5680,7 +5774,7 @@ class BinaryView:
break
return DataVariable.from_core_struct(var, self)
- def get_next_data_var_start_after(self, addr:int) -> int:
+ def get_next_data_var_start_after(self, addr: int) -> int:
"""
``get_next_data_var_start_after`` retrieves the next virtual address of the next :py:Class:`DataVariable`
@@ -5697,7 +5791,7 @@ class BinaryView:
"""
return core.BNGetNextDataVariableStartAfterAddress(self.handle, addr)
- def get_previous_function_start_before(self, addr:int) -> int:
+ def get_previous_function_start_before(self, addr: int) -> int:
"""
``get_previous_function_start_before`` returns the virtual address of the Function that occurs prior to the
virtual address provided
@@ -5717,7 +5811,7 @@ class BinaryView:
"""
return core.BNGetPreviousFunctionStartBeforeAddress(self.handle, addr)
- def get_previous_basic_block_start_before(self, addr:int) -> int:
+ def get_previous_basic_block_start_before(self, addr: int) -> int:
"""
``get_previous_basic_block_start_before`` returns the virtual address of the BasicBlock that occurs prior to the
provided virtual address
@@ -5737,7 +5831,7 @@ class BinaryView:
"""
return core.BNGetPreviousBasicBlockStartBeforeAddress(self.handle, addr)
- def get_previous_basic_block_end_before(self, addr:int) -> int:
+ def get_previous_basic_block_end_before(self, addr: int) -> int:
"""
``get_previous_basic_block_end_before``
@@ -5754,7 +5848,7 @@ class BinaryView:
"""
return core.BNGetPreviousBasicBlockEndBeforeAddress(self.handle, addr)
- def get_previous_data_before(self, addr:int) -> int:
+ def get_previous_data_before(self, addr: int) -> int:
"""
``get_previous_data_before``
@@ -5769,7 +5863,7 @@ class BinaryView:
"""
return core.BNGetPreviousDataBeforeAddress(self.handle, addr)
- def get_previous_data_var_before(self, addr:int) -> Optional['DataVariable']:
+ def get_previous_data_var_before(self, addr: int) -> Optional['DataVariable']:
"""
``get_previous_data_var_before`` retrieves the previous :py:Class:`DataVariable`, or None.
@@ -5790,7 +5884,7 @@ class BinaryView:
return None
return DataVariable.from_core_struct(var, self)
- def get_previous_data_var_start_before(self, addr:int) -> int:
+ def get_previous_data_var_start_before(self, addr: int) -> int:
"""
``get_previous_data_var_start_before``
@@ -5807,7 +5901,9 @@ class BinaryView:
"""
return core.BNGetPreviousDataVariableStartBeforeAddress(self.handle, addr)
- def get_linear_disassembly_position_at(self, addr:int, settings:'_function.DisassemblySettings'=None) -> 'lineardisassembly.LinearViewCursor':
+ def get_linear_disassembly_position_at(
+ self, addr: int, settings: '_function.DisassemblySettings' = None
+ ) -> 'lineardisassembly.LinearViewCursor':
"""
``get_linear_disassembly_position_at`` instantiates a :py:class:`LinearViewCursor <binaryninja.lineardisassembly.LinearViewCursor>` object for use in
:py:meth:`get_previous_linear_disassembly_lines` or :py:meth:`get_next_linear_disassembly_lines`.
@@ -5829,7 +5925,9 @@ class BinaryView:
pos.seek_to_address(addr)
return pos
- def get_previous_linear_disassembly_lines(self, pos:'lineardisassembly.LinearViewCursor') -> List['lineardisassembly.LinearDisassemblyLine']:
+ def get_previous_linear_disassembly_lines(
+ self, pos: 'lineardisassembly.LinearViewCursor'
+ ) -> List['lineardisassembly.LinearDisassemblyLine']:
"""
``get_previous_linear_disassembly_lines`` retrieves a list of :py:class:`LinearDisassemblyLine` objects for the
previous disassembly lines, and updates the LinearViewCursor passed in. This function can be called
@@ -5853,7 +5951,9 @@ class BinaryView:
result = pos.lines
return result
- def get_next_linear_disassembly_lines(self, pos:'lineardisassembly.LinearViewCursor') -> List['lineardisassembly.LinearDisassemblyLine']:
+ def get_next_linear_disassembly_lines(
+ self, pos: 'lineardisassembly.LinearViewCursor'
+ ) -> List['lineardisassembly.LinearDisassemblyLine']:
"""
``get_next_linear_disassembly_lines`` retrieves a list of :py:class:`LinearDisassemblyLine` objects for the
next disassembly lines, and updates the LinearViewCursor passed in. This function can be called
@@ -5878,8 +5978,9 @@ class BinaryView:
return result
return result
- def get_linear_disassembly(self, settings:'_function.DisassemblySettings'=None) -> \
- Iterator['lineardisassembly.LinearDisassemblyLine']:
+ def get_linear_disassembly(
+ self, settings: '_function.DisassemblySettings' = None
+ ) -> Iterator['lineardisassembly.LinearDisassemblyLine']:
"""
``get_linear_disassembly`` gets an iterator for all lines in the linear disassembly of the view for the given
disassembly settings.
@@ -5902,12 +6003,13 @@ class BinaryView:
"""
@dataclass
class LinearDisassemblyIterator:
- view:'BinaryView'
- settings:Optional['_function.DisassemblySettings'] = None
+ view: 'BinaryView'
+ settings: Optional['_function.DisassemblySettings'] = None
def __iter__(self):
- pos = lineardisassembly.LinearViewCursor(lineardisassembly.LinearViewObject.disassembly(
- self.view, self.settings))
+ pos = lineardisassembly.LinearViewCursor(
+ lineardisassembly.LinearViewObject.disassembly(self.view, self.settings)
+ )
while True:
lines = self.view.get_next_linear_disassembly_lines(pos)
if len(lines) == 0:
@@ -5917,7 +6019,7 @@ class BinaryView:
return iter(LinearDisassemblyIterator(self, settings))
- def parse_type_string(self, text:str) -> Tuple['_types.Type', '_types.QualifiedName']:
+ def parse_type_string(self, text: str) -> Tuple['_types.Type', '_types.QualifiedName']:
"""
``parse_type_string`` parses string containing C into a single type :py:Class:`Type`.
In contrast to the :py:'platform
@@ -5944,13 +6046,13 @@ class BinaryView:
error_str = errors.value.decode("utf-8")
core.free_string(errors)
raise SyntaxError(error_str)
- type_obj = _types.Type.create(core.BNNewTypeReference(result.type), platform = self.platform)
+ type_obj = _types.Type.create(core.BNNewTypeReference(result.type), platform=self.platform)
name = _types.QualifiedName._from_core_struct(result.name)
return type_obj, name
finally:
core.BNFreeQualifiedNameAndType(result)
- def parse_types_from_string(self, text:str) -> '_types.TypeParserResult':
+ def parse_types_from_string(self, text: str) -> '_types.TypeParserResult':
"""
``parse_types_from_string`` parses string containing C into a :py:Class:`TypeParserResult` objects. This API
unlike the :py:meth:`Platform.parse_types_from_source` allows the reference of types already defined
@@ -5980,23 +6082,31 @@ class BinaryView:
core.free_string(errors)
raise SyntaxError(error_str)
- type_dict:Mapping[_types.QualifiedName, _types.Type] = {}
- variables:Mapping[_types.QualifiedName, _types.Type] = {}
- functions:Mapping[_types.QualifiedName, _types.Type] = {}
+ type_dict: Mapping[_types.QualifiedName, _types.Type] = {}
+ variables: Mapping[_types.QualifiedName, _types.Type] = {}
+ functions: Mapping[_types.QualifiedName, _types.Type] = {}
for i in range(0, parse.typeCount):
name = _types.QualifiedName._from_core_struct(parse.types[i].name)
- type_dict[name] = _types.Type.create(core.BNNewTypeReference(parse.types[i].type), platform = self.platform)
+ type_dict[name] = _types.Type.create(
+ core.BNNewTypeReference(parse.types[i].type), platform=self.platform
+ )
for i in range(0, parse.variableCount):
name = _types.QualifiedName._from_core_struct(parse.variables[i].name)
- variables[name] = _types.Type.create(core.BNNewTypeReference(parse.variables[i].type), platform = self.platform)
+ variables[name] = _types.Type.create(
+ core.BNNewTypeReference(parse.variables[i].type), platform=self.platform
+ )
for i in range(0, parse.functionCount):
name = _types.QualifiedName._from_core_struct(parse.functions[i].name)
- functions[name] = _types.Type.create(core.BNNewTypeReference(parse.functions[i].type), platform = self.platform)
+ functions[name] = _types.Type.create(
+ core.BNNewTypeReference(parse.functions[i].type), platform=self.platform
+ )
return _types.TypeParserResult(type_dict, variables, functions)
finally:
core.BNFreeTypeParserResult(parse)
- def parse_possiblevalueset(self, value:str, state:RegisterValueType, here:int=0) -> 'variable.PossibleValueSet':
+ def parse_possiblevalueset(
+ self, value: str, state: RegisterValueType, here: int = 0
+ ) -> 'variable.PossibleValueSet':
"""
Evaluates a string representation of a PossibleValueSet into an instance of the ``PossibleValueSet`` value.
@@ -6043,7 +6153,7 @@ class BinaryView:
raise ValueError(error_str)
return variable.PossibleValueSet(self.arch, result)
- def get_type_by_name(self, name:'_types.QualifiedNameType') -> Optional['_types.Type']:
+ def get_type_by_name(self, name: '_types.QualifiedNameType') -> Optional['_types.Type']:
"""
``get_type_by_name`` returns the defined type whose name corresponds with the provided ``name``
@@ -6062,9 +6172,9 @@ class BinaryView:
obj = core.BNGetAnalysisTypeByName(self.handle, _name)
if not obj:
return None
- return _types.Type.create(obj, platform = self.platform)
+ return _types.Type.create(obj, platform=self.platform)
- def get_type_by_id(self, id:str) -> Optional['_types.Type']:
+ def get_type_by_id(self, id: str) -> Optional['_types.Type']:
"""
``get_type_by_id`` returns the defined type whose unique identifier corresponds with the provided ``id``
@@ -6083,9 +6193,9 @@ class BinaryView:
obj = core.BNGetAnalysisTypeById(self.handle, id)
if not obj:
return None
- return _types.Type.create(obj, platform = self.platform)
+ return _types.Type.create(obj, platform=self.platform)
- def get_type_name_by_id(self, id:str) -> Optional['_types.QualifiedName']:
+ def get_type_name_by_id(self, id: str) -> Optional['_types.QualifiedName']:
"""
``get_type_name_by_id`` returns the defined type name whose unique identifier corresponds with the provided ``id``
@@ -6109,7 +6219,7 @@ class BinaryView:
return None
return result
- def get_type_id(self, name:'_types.QualifiedNameType') -> str:
+ def get_type_id(self, name: '_types.QualifiedNameType') -> str:
"""
``get_type_id`` returns the unique identifier of the defined type whose name corresponds with the
provided ``name``
@@ -6129,7 +6239,7 @@ class BinaryView:
_name = _types.QualifiedName(name)._to_core_struct()
return core.BNGetAnalysisTypeId(self.handle, _name)
- def add_type_library(self, lib:'typelibrary.TypeLibrary') -> None:
+ def add_type_library(self, lib: 'typelibrary.TypeLibrary') -> None:
"""
``add_type_library`` make the contents of a type library available for type/import resolution
@@ -6140,7 +6250,7 @@ class BinaryView:
raise ValueError("must pass in a TypeLibrary object")
core.BNAddBinaryViewTypeLibrary(self.handle, lib.handle)
- def get_type_library(self, name:str) -> Optional['typelibrary.TypeLibrary']:
+ def get_type_library(self, name: str) -> Optional['typelibrary.TypeLibrary']:
"""
``get_type_library`` returns the TypeLibrary
@@ -6155,7 +6265,7 @@ class BinaryView:
return None
return typelibrary.TypeLibrary(handle)
- def is_type_auto_defined(self, name:'_types.QualifiedNameType') -> bool:
+ def is_type_auto_defined(self, name: '_types.QualifiedNameType') -> bool:
"""
``is_type_auto_defined`` queries the user type list of name. If name is not in the *user* type list then the name
is considered an *auto* type.
@@ -6173,7 +6283,9 @@ class BinaryView:
_name = _types.QualifiedName(name)._to_core_struct()
return core.BNIsAnalysisTypeAutoDefined(self.handle, _name)
- def define_type(self, type_id:str, default_name:Optional['_types.QualifiedNameType'], type_obj:StringOrType) -> '_types.QualifiedName':
+ def define_type(
+ self, type_id: str, default_name: Optional['_types.QualifiedNameType'], type_obj: StringOrType
+ ) -> '_types.QualifiedName':
"""
``define_type`` registers a :py:Class:`Type` ``type_obj`` of the given ``name`` in the global list of types for
the current :py:Class:`BinaryView`. This method should only be used for automatically generated types.
@@ -6205,7 +6317,7 @@ class BinaryView:
core.BNFreeQualifiedName(reg_name)
return result
- def define_user_type(self, name:Optional['_types.QualifiedNameType'], type_obj:StringOrType) -> None:
+ def define_user_type(self, name: Optional['_types.QualifiedNameType'], type_obj: StringOrType) -> None:
"""
``define_user_type`` registers a :py:Class:`Type` ``type_obj`` of the given ``name`` in the global list of user
types for the current :py:Class:`BinaryView`.
@@ -6232,7 +6344,7 @@ class BinaryView:
_name = _types.QualifiedName(name)._to_core_struct()
core.BNDefineUserAnalysisType(self.handle, _name, type_obj.handle)
- def undefine_type(self, type_id:str) -> None:
+ def undefine_type(self, type_id: str) -> None:
"""
``undefine_type`` removes a :py:Class:`Type` from the global list of types for the current :py:Class:`BinaryView`
@@ -6251,7 +6363,7 @@ class BinaryView:
"""
core.BNUndefineAnalysisType(self.handle, type_id)
- def undefine_user_type(self, name:'_types.QualifiedNameType') -> None:
+ def undefine_user_type(self, name: '_types.QualifiedNameType') -> None:
"""
``undefine_user_type`` removes a :py:Class:`Type` from the global list of user types for the current
:py:Class:`BinaryView`
@@ -6271,7 +6383,7 @@ class BinaryView:
_name = _types.QualifiedName(name)._to_core_struct()
core.BNUndefineUserAnalysisType(self.handle, _name)
- def rename_type(self, old_name:'_types.QualifiedNameType', new_name:'_types.QualifiedNameType') -> None:
+ def rename_type(self, old_name: '_types.QualifiedNameType', new_name: '_types.QualifiedNameType') -> None:
"""
``rename_type`` renames a type in the global list of types for the current :py:Class:`BinaryView`
@@ -6293,7 +6405,7 @@ class BinaryView:
_new_name = _types.QualifiedName(new_name)._to_core_struct()
core.BNRenameAnalysisType(self.handle, _old_name, _new_name)
- def import_library_type(self, name:str, lib:typelibrary.TypeLibrary = None) -> Optional['_types.Type']:
+ def import_library_type(self, name: str, lib: typelibrary.TypeLibrary = None) -> Optional['_types.Type']:
"""
``import_library_type`` recursively imports a type from the specified type library, or, if
no library was explicitly provided, the first type library associated with the current :py:Class:`BinaryView`
@@ -6312,12 +6424,14 @@ class BinaryView:
:rtype: Type
"""
_name = _types.QualifiedName(name)
- handle = core.BNBinaryViewImportTypeLibraryType(self.handle, None if lib is None else lib.handle, _name._to_core_struct())
+ handle = core.BNBinaryViewImportTypeLibraryType(
+ self.handle, None if lib is None else lib.handle, _name._to_core_struct()
+ )
if handle is None:
return None
- return _types.Type.create(handle, platform = self.platform)
+ return _types.Type.create(handle, platform=self.platform)
- def import_library_object(self, name:str, lib:typelibrary.TypeLibrary = None) -> Optional['_types.Type']:
+ def import_library_object(self, name: str, lib: typelibrary.TypeLibrary = None) -> Optional['_types.Type']:
"""
``import_library_object`` recursively imports an object from the specified type library, or, if
no library was explicitly provided, the first type library associated with the current :py:Class:`BinaryView`
@@ -6332,12 +6446,14 @@ class BinaryView:
:rtype: Type
"""
_name = _types.QualifiedName(name)
- handle = core.BNBinaryViewImportTypeLibraryObject(self.handle, None if lib is None else lib.handle, _name._to_core_struct())
+ handle = core.BNBinaryViewImportTypeLibraryObject(
+ self.handle, None if lib is None else lib.handle, _name._to_core_struct()
+ )
if handle is None:
return None
- return _types.Type.create(handle, platform = self.platform)
+ return _types.Type.create(handle, platform=self.platform)
- def export_type_to_library(self, lib:typelibrary.TypeLibrary, name:Optional[str], type_obj:StringOrType) -> None:
+ def export_type_to_library(self, lib: typelibrary.TypeLibrary, name: Optional[str], type_obj: StringOrType) -> None:
"""
``export_type_to_library`` recursively exports ``type_obj`` into ``lib`` as a type with name ``name``
@@ -6364,7 +6480,9 @@ class BinaryView:
raise ValueError("name can only be None if named type is derived from string passed to type_obj")
core.BNBinaryViewExportTypeToTypeLibrary(self.handle, lib.handle, _name._to_core_struct(), type_obj.handle)
- def export_object_to_library(self, lib:typelibrary.TypeLibrary, name:Optional[str], type_obj:StringOrType) -> None:
+ def export_object_to_library(
+ self, lib: typelibrary.TypeLibrary, name: Optional[str], type_obj: StringOrType
+ ) -> None:
"""
``export_object_to_library`` recursively exports ``type_obj`` into ``lib`` as an object with name ``name``
@@ -6392,7 +6510,7 @@ class BinaryView:
raise ValueError("name can only be None if named type is derived from string passed to type_obj")
core.BNBinaryViewExportObjectToTypeLibrary(self.handle, lib.handle, _name._to_core_struct(), type_obj.handle)
- def register_platform_types(self, platform:'_platform.Platform') -> None:
+ def register_platform_types(self, platform: '_platform.Platform') -> None:
"""
``register_platform_types`` ensures that the platform-specific types for a :py:Class:`Platform` are available
for the current :py:Class:`BinaryView`. This is automatically performed when adding a new function or setting
@@ -6408,7 +6526,7 @@ class BinaryView:
"""
core.BNRegisterPlatformTypes(self.handle, platform.handle)
- def find_next_data(self, start:int, data:bytes, flags:FindFlag=FindFlag.FindCaseSensitive) -> Optional[int]:
+ def find_next_data(self, start: int, data: bytes, flags: FindFlag = FindFlag.FindCaseSensitive) -> Optional[int]:
"""
``find_next_data`` searches for the bytes ``data`` starting at the virtual address ``start`` until the end of the BinaryView.
@@ -6432,10 +6550,11 @@ class BinaryView:
return None
return result.value
-
- def find_next_text(self, start:int, text:str, settings:_function.DisassemblySettings=None,
- flags:FindFlag=FindFlag.FindCaseSensitive,
- graph_type:FunctionGraphType = FunctionGraphType.NormalFunctionGraph) -> Optional[int]:
+ def find_next_text(
+ self, start: int, text: str, settings: _function.DisassemblySettings = None,
+ flags: FindFlag = FindFlag.FindCaseSensitive,
+ graph_type: FunctionGraphType = FunctionGraphType.NormalFunctionGraph
+ ) -> Optional[int]:
"""
``find_next_text`` searches for string ``text`` occurring in the linear view output starting at the virtual
address ``start`` until the end of the BinaryView.
@@ -6461,13 +6580,14 @@ class BinaryView:
raise TypeError("settings parameter is not DisassemblySettings type")
result = ctypes.c_ulonglong()
- if not core.BNFindNextText(self.handle, start, text, result, settings.handle, flags,
- graph_type):
+ if not core.BNFindNextText(self.handle, start, text, result, settings.handle, flags, graph_type):
return None
return result.value
- def find_next_constant(self, start:int, constant:int, settings:_function.DisassemblySettings=None,
- graph_type:FunctionGraphType = FunctionGraphType.NormalFunctionGraph) -> Optional[int]:
+ def find_next_constant(
+ self, start: int, constant: int, settings: _function.DisassemblySettings = None,
+ graph_type: FunctionGraphType = FunctionGraphType.NormalFunctionGraph
+ ) -> Optional[int]:
"""
``find_next_constant`` searches for integer constant ``constant`` occurring in the linear view output starting at the virtual
address ``start`` until the end of the BinaryView.
@@ -6485,8 +6605,7 @@ class BinaryView:
raise TypeError("settings parameter is not DisassemblySettings type")
result = ctypes.c_ulonglong()
- if not core.BNFindNextConstant(self.handle, start, constant, result, settings.handle,
- graph_type):
+ if not core.BNFindNextConstant(self.handle, start, constant, result, settings.handle, graph_type):
return None
return result.value
@@ -6507,8 +6626,10 @@ class BinaryView:
if (not self.thread.is_alive()) and self.results.empty():
raise StopIteration
- def find_all_data(self, start:int, end:int, data:bytes, flags:FindFlag = FindFlag.FindCaseSensitive,
- progress_func:ProgressFuncType = None, match_callback:DataMatchCallbackType = None) -> QueueGenerator:
+ def find_all_data(
+ self, start: int, end: int, data: bytes, flags: FindFlag = FindFlag.FindCaseSensitive,
+ progress_func: ProgressFuncType = None, match_callback: DataMatchCallbackType = None
+ ) -> QueueGenerator:
"""
``find_all_data`` searches for the bytes ``data`` starting at the virtual address ``start``
until the virtual address ``end``. Once a match is found, the ``match_callback`` is called.
@@ -6542,35 +6663,40 @@ class BinaryView:
raise TypeError('flag parameter must have type FindFlag')
if progress_func:
- progress_func_obj = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p,
- ctypes.c_ulonglong, ctypes.c_ulonglong)\
- (lambda ctxt, cur, total: progress_func(cur, total))
+ progress_func_obj = ctypes.CFUNCTYPE(
+ ctypes.c_bool, ctypes.c_void_p, ctypes.c_ulonglong, ctypes.c_ulonglong
+ )(lambda ctxt, cur, total: progress_func(cur, total))
else:
- progress_func_obj = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p,
- ctypes.c_ulonglong, ctypes.c_ulonglong)\
- (lambda ctxt, cur, total: True)
+ progress_func_obj = ctypes.CFUNCTYPE(
+ ctypes.c_bool, ctypes.c_void_p, ctypes.c_ulonglong, ctypes.c_ulonglong
+ )(lambda ctxt, cur, total: True)
if match_callback:
# the `not match_callback(...) is False` tolerates the users who forget to return
# `True` from inside the callback
- match_callback_obj = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p,
- ctypes.c_ulonglong, ctypes.POINTER(core.BNDataBuffer))\
- (lambda ctxt, addr, match: not match_callback(addr, databuffer.DataBuffer(handle = match)) is False)
- return core.BNFindAllDataWithProgress(self.handle, start, end, buf.handle, flags,
- None, progress_func_obj, None, match_callback_obj)
+ match_callback_obj = ctypes.CFUNCTYPE(
+ ctypes.c_bool, ctypes.c_void_p, ctypes.c_ulonglong, ctypes.POINTER(core.BNDataBuffer)
+ )(lambda ctxt, addr, match: not match_callback(addr, databuffer.DataBuffer(handle=match)) is False)
+ return core.BNFindAllDataWithProgress(
+ self.handle, start, end, buf.handle, flags, None, progress_func_obj, None, match_callback_obj
+ )
else:
results = queue.Queue()
- match_callback_obj = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p,
- ctypes.c_ulonglong, ctypes.POINTER(core.BNDataBuffer))\
- (lambda ctxt, addr, match:
- results.put((addr, databuffer.DataBuffer(handle = match))) or True)
+ match_callback_obj = ctypes.CFUNCTYPE(
+ ctypes.c_bool, ctypes.c_void_p, ctypes.c_ulonglong, ctypes.POINTER(core.BNDataBuffer)
+ )(lambda ctxt, addr, match: results.put((addr, databuffer.DataBuffer(handle=match))) or True)
- t = threading.Thread(target = lambda: core.BNFindAllDataWithProgress(self.handle,
- start, end, buf.handle, flags, None, progress_func_obj, None, match_callback_obj))
+ t = threading.Thread(
+ target=lambda: core.BNFindAllDataWithProgress(
+ self.handle, start, end, buf.handle, flags, None, progress_func_obj, None, match_callback_obj
+ )
+ )
return self.QueueGenerator(t, results)
- def _LinearDisassemblyLine_convertor(self, lines:core.BNLinearDisassemblyLineHandle) -> 'lineardisassembly.LinearDisassemblyLine':
+ def _LinearDisassemblyLine_convertor(
+ self, lines: core.BNLinearDisassemblyLineHandle
+ ) -> 'lineardisassembly.LinearDisassemblyLine':
func = None
block = None
line = lines[0]
@@ -6583,13 +6709,14 @@ class BinaryView:
color = highlight.HighlightColor._from_core_struct(line.contents.highlight)
addr = line.contents.addr
tokens = _function.InstructionTextToken._from_core_struct(line.contents.tokens, line.contents.count)
- contents = _function.DisassemblyTextLine(tokens, addr, color = color)
+ contents = _function.DisassemblyTextLine(tokens, addr, color=color)
return lineardisassembly.LinearDisassemblyLine(line.type, func, block, contents)
- def find_all_text(self, start:int, end:int, text:str, settings:_function.DisassemblySettings = None,
- flags = FindFlag.FindCaseSensitive,
- graph_type = FunctionGraphType.NormalFunctionGraph, progress_func = None,
- match_callback = None) -> QueueGenerator:
+ def find_all_text(
+ self, start: int, end: int, text: str, settings: _function.DisassemblySettings = None,
+ flags=FindFlag.FindCaseSensitive, graph_type=FunctionGraphType.NormalFunctionGraph, progress_func=None,
+ match_callback=None
+ ) -> QueueGenerator:
"""
``find_all_text`` searches for string ``text`` occurring in the linear view output starting
at the virtual address ``start`` until the virtual address ``end``. Once a match is found,
@@ -6631,43 +6758,54 @@ class BinaryView:
raise TypeError('flag parameter must have type FindFlag')
if progress_func:
- progress_func_obj = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p,
- ctypes.c_ulonglong, ctypes.c_ulonglong)\
- (lambda ctxt, cur, total: progress_func(cur, total))
+ progress_func_obj = ctypes.CFUNCTYPE(
+ ctypes.c_bool, ctypes.c_void_p, ctypes.c_ulonglong, ctypes.c_ulonglong
+ )(lambda ctxt, cur, total: progress_func(cur, total))
else:
- progress_func_obj = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p,
- ctypes.c_ulonglong, ctypes.c_ulonglong)\
- (lambda ctxt, cur, total: True)
+ progress_func_obj = ctypes.CFUNCTYPE(
+ ctypes.c_bool, ctypes.c_void_p, ctypes.c_ulonglong, ctypes.c_ulonglong
+ )(lambda ctxt, cur, total: True)
if match_callback:
# The reason we use `not match_callback(...) is False` is the user tends to happily
# deal with the returned data, but forget to return True at the end of the callback.
# Then only the first result will be returned.
- match_callback_obj = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p,
- ctypes.c_ulonglong, ctypes.c_char_p,
- ctypes.POINTER(core.BNLinearDisassemblyLine))\
- (lambda ctxt, addr, match, line: not match_callback(addr, match,\
- self._LinearDisassemblyLine_convertor(line)) is False)
+ match_callback_obj = ctypes.CFUNCTYPE(
+ ctypes.c_bool, ctypes.c_void_p, ctypes.c_ulonglong, ctypes.c_char_p,
+ ctypes.POINTER(core.BNLinearDisassemblyLine)
+ )(
+ lambda ctxt, addr, match, line:
+ not match_callback(addr, match, self._LinearDisassemblyLine_convertor(line)) is False
+ )
- return core.BNFindAllTextWithProgress(self.handle, start, end, text,
- settings.handle, flags, graph_type, None, progress_func_obj, None, match_callback_obj)
+ return core.BNFindAllTextWithProgress(
+ self.handle, start, end, text, settings.handle, flags, graph_type, None, progress_func_obj, None,
+ match_callback_obj
+ )
else:
results = queue.Queue()
- match_callback_obj = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p,
- ctypes.c_ulonglong, ctypes.c_char_p,
- ctypes.POINTER(core.BNLinearDisassemblyLine))\
- (lambda ctxt, addr, match, line: results.put((addr, match,\
- self._LinearDisassemblyLine_convertor(line))) or True)
+ match_callback_obj = ctypes.CFUNCTYPE(
+ ctypes.c_bool, ctypes.c_void_p, ctypes.c_ulonglong, ctypes.c_char_p,
+ ctypes.POINTER(core.BNLinearDisassemblyLine)
+ )(
+ lambda ctxt, addr, match, line: results.put((addr, match, self._LinearDisassemblyLine_convertor(line)))
+ or True
+ )
- t = threading.Thread(target = lambda: core.BNFindAllTextWithProgress(self.handle,
- start, end, text, settings.handle, flags, graph_type, None, progress_func_obj, None,
- match_callback_obj))
+ t = threading.Thread(
+ target=lambda: core.BNFindAllTextWithProgress(
+ self.handle, start, end, text, settings.handle, flags, graph_type, None, progress_func_obj, None,
+ match_callback_obj
+ )
+ )
return self.QueueGenerator(t, results)
- def find_all_constant(self, start:int, end:int, constant:int, settings:_function.DisassemblySettings = None,
- graph_type:FunctionGraphType = FunctionGraphType.NormalFunctionGraph, progress_func:ProgressFuncType = None,
- match_callback:LineMatchCallbackType = None) -> QueueGenerator:
+ def find_all_constant(
+ self, start: int, end: int, constant: int, settings: _function.DisassemblySettings = None,
+ graph_type: FunctionGraphType = FunctionGraphType.NormalFunctionGraph, progress_func: ProgressFuncType = None,
+ match_callback: LineMatchCallbackType = None
+ ) -> QueueGenerator:
"""
``find_all_constant`` searches for the integer constant ``constant`` starting at the
virtual address ``start`` until the virtual address ``end``. Once a match is found,
@@ -6698,32 +6836,35 @@ class BinaryView:
raise TypeError("settings parameter is not DisassemblySettings type")
if progress_func:
- progress_func_obj = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p,
- ctypes.c_ulonglong, ctypes.c_ulonglong)\
- (lambda ctxt, cur, total: progress_func(cur, total))
+ progress_func_obj = ctypes.CFUNCTYPE(
+ ctypes.c_bool, ctypes.c_void_p, ctypes.c_ulonglong, ctypes.c_ulonglong
+ )(lambda ctxt, cur, total: progress_func(cur, total))
else:
- progress_func_obj = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p,
- ctypes.c_ulonglong, ctypes.c_ulonglong)\
- (lambda ctxt, cur, total: True)
+ progress_func_obj = ctypes.CFUNCTYPE(
+ ctypes.c_bool, ctypes.c_void_p, ctypes.c_ulonglong, ctypes.c_ulonglong
+ )(lambda ctxt, cur, total: True)
if match_callback:
- match_callback_obj = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p,\
- ctypes.c_ulonglong, ctypes.POINTER(core.BNLinearDisassemblyLine))\
- (lambda ctxt, addr, line: not match_callback(addr,\
- self._LinearDisassemblyLine_convertor(line)) is False)
+ match_callback_obj = ctypes.CFUNCTYPE(
+ ctypes.c_bool, ctypes.c_void_p, ctypes.c_ulonglong, ctypes.POINTER(core.BNLinearDisassemblyLine)
+ )(lambda ctxt, addr, line: not match_callback(addr, self._LinearDisassemblyLine_convertor(line)) is False)
- return core.BNFindAllConstantWithProgress(self.handle, start, end, constant,
- settings.handle, graph_type, None, progress_func_obj, None, match_callback_obj)
+ return core.BNFindAllConstantWithProgress(
+ self.handle, start, end, constant, settings.handle, graph_type, None, progress_func_obj, None,
+ match_callback_obj
+ )
else:
results = queue.Queue()
- match_callback_obj = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p,\
- ctypes.c_ulonglong, ctypes.POINTER(core.BNLinearDisassemblyLine))\
- (lambda ctxt, addr, line: results.put((addr,\
- self._LinearDisassemblyLine_convertor(line))) or True)
+ match_callback_obj = ctypes.CFUNCTYPE(
+ ctypes.c_bool, ctypes.c_void_p, ctypes.c_ulonglong, ctypes.POINTER(core.BNLinearDisassemblyLine)
+ )(lambda ctxt, addr, line: results.put((addr, self._LinearDisassemblyLine_convertor(line))) or True)
- t = threading.Thread(target = lambda: core.BNFindAllConstantWithProgress(self.handle,
- start, end, constant, settings.handle, graph_type, None, progress_func_obj, None,\
- match_callback_obj))
+ t = threading.Thread(
+ target=lambda: core.BNFindAllConstantWithProgress(
+ self.handle, start, end, constant, settings.handle, graph_type, None, progress_func_obj, None,
+ match_callback_obj
+ )
+ )
return self.QueueGenerator(t, results)
@@ -6740,9 +6881,10 @@ class BinaryView:
handle = core.BNGetWorkflowForBinaryView(self.handle)
if handle is None:
return None
- return _workflow.Workflow(handle = handle)
+ return _workflow.Workflow(handle=handle)
- def rebase(self, address:int, force:bool = False, progress_func:ProgressFuncType = None) -> Optional['BinaryView']:
+ def rebase(self, address: int, force: bool = False,
+ progress_func: ProgressFuncType = None) -> Optional['BinaryView']:
"""
``rebase`` rebase the existing :py:class:`BinaryView` into a new :py:class:`BinaryView` at the specified virtual address
@@ -6757,22 +6899,27 @@ class BinaryView:
"""
result = False
if core.BNIsUIEnabled() and not force:
- log_warn("The BinaryView rebase API does not update cooresponding UI components. If the BinaryView is not associated with the UI rerun with 'force = True'.")
+ log_warn(
+ "The BinaryView rebase API does not update cooresponding UI components. If the BinaryView is not associated with the UI rerun with 'force = True'."
+ )
return None
if progress_func is None:
result = core.BNRebase(self.handle, address)
else:
- result = core.BNRebaseWithProgress(self.handle, address, None, ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_ulonglong, ctypes.c_ulonglong)(
- lambda ctxt, cur, total: progress_func(cur, total)))
+ result = core.BNRebaseWithProgress(
+ self.handle, address, None,
+ ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_ulonglong,
+ ctypes.c_ulonglong)(lambda ctxt, cur, total: progress_func(cur, total))
+ )
if result:
return self.get_view_of_type(self.view_type)
else:
return None
- def show_plain_text_report(self, title:str, contents:str) -> None:
+ def show_plain_text_report(self, title: str, contents: str) -> None:
core.BNShowPlainTextReport(self.handle, title, contents)
- def show_markdown_report(self, title:str, contents:str, plaintext:str = "") -> None:
+ def show_markdown_report(self, title: str, contents: str, plaintext: str = "") -> None:
"""
``show_markdown_report`` displays 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:
@@ -6790,7 +6937,7 @@ class BinaryView:
"""
core.BNShowMarkdownReport(self.handle, title, contents, plaintext)
- def show_html_report(self, title:str, contents:str, plaintext:str = "") -> None:
+ def show_html_report(self, title: str, contents: str, plaintext: str = "") -> None:
"""
``show_html_report`` displays 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:
@@ -6808,7 +6955,7 @@ class BinaryView:
"""
core.BNShowHTMLReport(self.handle, title, contents, plaintext)
- def show_graph_report(self, title:str, graph:flowgraph.FlowGraph) -> None:
+ def show_graph_report(self, title: str, graph: flowgraph.FlowGraph) -> None:
"""
``show_graph_report`` displays a :py:Class:`FlowGraph` object `graph` in a new tab with ``title``.
@@ -6819,7 +6966,7 @@ class BinaryView:
"""
core.BNShowGraphReport(self.handle, title, graph.handle)
- def get_address_input(self, prompt:str, title:str, current_address:int = None) -> Optional[int]:
+ def get_address_input(self, prompt: str, title: str, current_address: int = None) -> Optional[int]:
if current_address is None:
current_address = self._file.offset
value = ctypes.c_ulonglong()
@@ -6827,10 +6974,10 @@ class BinaryView:
return None
return value.value
- def add_auto_segment(self, start:int, length:int, data_offset:int, data_length:int, flags:SegmentFlag) -> None:
+ def add_auto_segment(self, start: int, length: int, data_offset: int, data_length: int, flags: SegmentFlag) -> None:
core.BNAddAutoSegment(self.handle, start, length, data_offset, data_length, flags)
- def remove_auto_segment(self, start:int, length:int) -> None:
+ def remove_auto_segment(self, start: int, length: int) -> None:
"""
``remove_auto_segment`` removes an automatically generated segment from the current segment mapping.
@@ -6843,7 +6990,7 @@ class BinaryView:
"""
core.BNRemoveAutoSegment(self.handle, start, length)
- def add_user_segment(self, start:int, length:int, data_offset:int, data_length:int, flags:SegmentFlag) -> None:
+ def add_user_segment(self, start: int, length: int, data_offset: int, data_length: int, flags: SegmentFlag) -> None:
"""
``add_user_segment`` creates a user-defined segment that specifies how data from the raw file is mapped into a virtual address space.
@@ -6856,10 +7003,10 @@ class BinaryView:
"""
core.BNAddUserSegment(self.handle, start, length, data_offset, data_length, flags)
- def remove_user_segment(self, start:int, length:int) -> None:
+ def remove_user_segment(self, start: int, length: int) -> None:
core.BNRemoveUserSegment(self.handle, start, length)
- def get_segment_at(self, addr:int) -> Optional[Segment]:
+ def get_segment_at(self, addr: int) -> Optional[Segment]:
seg = core.BNGetSegmentAt(self.handle, addr)
if not seg:
return None
@@ -6867,7 +7014,7 @@ class BinaryView:
assert segment_handle is not None, "core.BNNewSegmentReference returned None"
return Segment(segment_handle)
- def get_address_for_data_offset(self, offset:int) -> Optional[int]:
+ def get_address_for_data_offset(self, offset: int) -> Optional[int]:
"""
``get_address_for_data_offset`` returns the virtual address that maps to the specific file offset.
@@ -6880,7 +7027,7 @@ class BinaryView:
return None
return address.value
- def get_data_offset_for_address(self, address:int) -> Optional[int]:
+ def get_data_offset_for_address(self, address: int) -> Optional[int]:
"""
``get_data_offset_for_address`` returns the file offset that maps to the given virtual address, if possible.
@@ -6897,17 +7044,24 @@ class BinaryView:
return offset + segment.data_offset
return None
- def add_auto_section(self, 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:
- core.BNAddAutoSection(self.handle, name, start, length, semantics, type, align, entry_size, linked_section,
- info_section, info_data)
+ def add_auto_section(
+ self, 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:
+ core.BNAddAutoSection(
+ self.handle, name, start, length, semantics, type, align, entry_size, linked_section, info_section,
+ info_data
+ )
- def remove_auto_section(self, name:str) -> None:
+ def remove_auto_section(self, name: str) -> None:
core.BNRemoveAutoSection(self.handle, name)
- def add_user_section(self, 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:
+ def add_user_section(
+ self, 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:
"""
``add_user_section`` creates 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.
@@ -6924,13 +7078,15 @@ class BinaryView:
:param int info_data: optional info data
:rtype: None
"""
- core.BNAddUserSection(self.handle, name, start, length, semantics, type, align, entry_size, linked_section,
- info_section, info_data)
+ core.BNAddUserSection(
+ self.handle, name, start, length, semantics, type, align, entry_size, linked_section, info_section,
+ info_data
+ )
- def remove_user_section(self, name:str) -> None:
+ def remove_user_section(self, name: str) -> None:
core.BNRemoveUserSection(self.handle, name)
- def get_sections_at(self, addr:int) -> List[Section]:
+ def get_sections_at(self, addr: int) -> List[Section]:
count = ctypes.c_ulonglong(0)
section_list = core.BNGetSectionsAt(self.handle, addr, count)
assert section_list is not None, "core.BNGetSectionsAt returned None"
@@ -6944,7 +7100,7 @@ class BinaryView:
finally:
core.BNFreeSectionList(section_list, count.value)
- def get_section_by_name(self, name:str) -> Optional[Section]:
+ def get_section_by_name(self, name: str) -> Optional[Section]:
section = core.BNGetSectionByName(self.handle, name)
if section is None:
return None
@@ -6953,7 +7109,7 @@ class BinaryView:
result = Section(section_handle)
return result
- def get_unique_section_names(self, name_list:List[str]) -> List[str]:
+ def get_unique_section_names(self, name_list: List[str]) -> List[str]:
incoming_names = (ctypes.c_char_p * len(name_list))()
for i in range(0, len(name_list)):
incoming_names[i] = name_list[i].encode("utf-8")
@@ -6990,7 +7146,7 @@ class BinaryView:
finally:
core.BNFreeAddressList(addrs)
- def get_comment_at(self, addr:int) -> str:
+ def get_comment_at(self, addr: int) -> str:
"""
``get_comment_at`` returns 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 each _function.
@@ -7001,7 +7157,7 @@ class BinaryView:
"""
return core.BNGetGlobalCommentForAddress(self.handle, addr)
- def set_comment_at(self, addr:int, comment:str) -> None:
+ def set_comment_at(self, addr: int, comment: str) -> None:
"""
``set_comment_at`` sets a comment for the BinaryView at the address specified
@@ -7039,7 +7195,7 @@ class BinaryView:
raise ValueError("Attempting to apply_debug_info with something which isn't and instance of 'DebugInfo'")
core.BNApplyDebugInfo(self.handle, value.handle)
- def query_metadata(self, key:str) -> 'metadata.MetadataValueType':
+ def query_metadata(self, key: str) -> 'metadata.MetadataValueType':
"""
`query_metadata` retrieves a metadata associated with the given key stored in the current BinaryView.
@@ -7062,7 +7218,7 @@ class BinaryView:
raise KeyError(key)
return metadata.Metadata(handle=md_handle).value
- def store_metadata(self, key:str, md:metadata.MetadataValueType, isAuto:bool = False) -> None:
+ def store_metadata(self, key: str, md: metadata.MetadataValueType, isAuto: bool = False) -> None:
"""
`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
@@ -7094,7 +7250,7 @@ class BinaryView:
_md = metadata.Metadata(_md)
core.BNBinaryViewStoreMetadata(self.handle, key, _md.handle, isAuto)
- def remove_metadata(self, key:str) -> None:
+ def remove_metadata(self, key: str) -> None:
"""
`remove_metadata` removes the metadata associated with key from the current BinaryView.
@@ -7126,7 +7282,7 @@ class BinaryView:
finally:
core.BNFreeStringList(names, count.value)
- def get_load_settings(self, type_name:str) -> Optional[settings.Settings]:
+ def get_load_settings(self, type_name: str) -> Optional[settings.Settings]:
"""
``get_load_settings`` retrieve a :py:class:`Settings` object which defines the load settings for the given :py:class:`BinaryViewType` ``type_name``
@@ -7139,7 +7295,7 @@ class BinaryView:
return None
return settings.Settings(handle=settings_handle)
- def set_load_settings(self, type_name:str, settings:settings.Settings) -> None:
+ def set_load_settings(self, type_name: str, settings: settings.Settings) -> None:
"""
``set_load_settings`` set a :py:class:`settings.Settings` object which defines the load settings for the given :py:class:`BinaryViewType` ``type_name``
@@ -7151,7 +7307,7 @@ class BinaryView:
settings = settings.handle
core.BNBinaryViewSetLoadSettings(self.handle, type_name, settings)
- def parse_expression(self, expression:str, here:int=0) -> int:
+ def parse_expression(self, expression: str, here: int = 0) -> int:
r"""
Evaluates a string expression to an integer value.
@@ -7194,22 +7350,22 @@ class BinaryView:
raise ValueError(error_str)
return offset.value
- def eval(self, expression:str, here:int=0) -> int:
+ def eval(self, expression: str, here: int = 0) -> int:
"""
Evaluates an string expression to an integer value. This is a more concise alias for the :py:meth:`parse_expression` API
"""
return self.parse_expression(expression, here)
- def reader(self, address:Optional[int]=None) -> 'BinaryReader':
+ def reader(self, address: Optional[int] = None) -> 'BinaryReader':
return BinaryReader(self, address=address)
- def writer(self, address:Optional[int]=None) -> 'BinaryWriter':
+ def writer(self, address: Optional[int] = None) -> 'BinaryWriter':
return BinaryWriter(self, address=address)
@property
def libraries(self) -> List[str]:
try:
- result:List[str] = []
+ result: List[str] = []
libs = self.query_metadata("Libraries")
assert isinstance(libs, metadata.Metadata)
for s in libs:
@@ -7219,7 +7375,7 @@ class BinaryView:
except KeyError:
return []
- def typed_data_accessor(self, address:int, type:'_types.Type') -> 'TypedDataAccessor':
+ def typed_data_accessor(self, address: int, type: '_types.Type') -> 'TypedDataAccessor':
return TypedDataAccessor(type, address, self, self.endianness)
@@ -7244,7 +7400,7 @@ class BinaryReader:
'0xcffaedfeL'
>>>
"""
- def __init__(self, view:'BinaryView', endian:Optional[Endianness]=None, address:Optional[int]=None):
+ def __init__(self, view: 'BinaryView', endian: Optional[Endianness] = None, address: Optional[int] = None):
_handle = core.BNCreateBinaryReader(view.handle)
assert _handle is not None, "core.BNCreateBinaryReader returned None"
self._handle = _handle
@@ -7285,7 +7441,7 @@ class BinaryReader:
return Endianness(core.BNGetBinaryReaderEndianness(self._handle))
@endianness.setter
- def endianness(self, value:Endianness) -> None:
+ def endianness(self, value: Endianness) -> None:
core.BNSetBinaryReaderEndianness(self._handle, value)
@property
@@ -7300,7 +7456,7 @@ class BinaryReader:
return core.BNGetReaderPosition(self._handle)
@offset.setter
- def offset(self, value:int) -> None:
+ def offset(self, value: int) -> None:
core.BNSeekBinaryReader(self._handle, value)
@property
@@ -7313,7 +7469,7 @@ class BinaryReader:
"""
return core.BNIsEndOfFile(self._handle)
- def read(self, length:int, address:Optional[int]=None) -> Optional[bytes]:
+ def read(self, length: int, address: Optional[int] = None) -> Optional[bytes]:
"""
``read`` returns ``length`` bytes read from the current offset, adding ``length`` to offset.
@@ -7335,7 +7491,7 @@ class BinaryReader:
return None
return dest.raw
- def read8(self, address:Optional[int]=None) -> Optional[int]:
+ def read8(self, address: Optional[int] = None) -> Optional[int]:
"""
``read8`` returns a one byte integer from offset incrementing the offset.
@@ -7357,7 +7513,7 @@ class BinaryReader:
return None
return result.value
- def read16(self, address:Optional[int]=None) -> Optional[int]:
+ def read16(self, address: Optional[int] = None) -> Optional[int]:
"""
``read16`` returns a two byte integer from offset incrementing the offset by two, using specified endianness.
@@ -7379,7 +7535,7 @@ class BinaryReader:
return None
return result.value
- def read32(self, address:Optional[int]=None) -> Optional[int]:
+ def read32(self, address: Optional[int] = None) -> Optional[int]:
"""
``read32`` returns a four byte integer from offset incrementing the offset by four, using specified endianness.
@@ -7401,7 +7557,7 @@ class BinaryReader:
return None
return result.value
- def read64(self, address:Optional[int]=None) -> Optional[int]:
+ def read64(self, address: Optional[int] = None) -> Optional[int]:
"""
``read64`` returns an eight byte integer from offset incrementing the offset by eight, using specified endianness.
@@ -7423,7 +7579,7 @@ class BinaryReader:
return None
return result.value
- def read16le(self, address:Optional[int]=None) -> Optional[int]:
+ def read16le(self, address: Optional[int] = None) -> Optional[int]:
"""
``read16le`` returns a two byte little endian integer from offset incrementing the offset by two.
@@ -7445,7 +7601,7 @@ class BinaryReader:
return None
return struct.unpack("<H", result)[0]
- def read32le(self, address:Optional[int]=None) -> Optional[int]:
+ def read32le(self, address: Optional[int] = None) -> Optional[int]:
"""
``read32le`` returns a four byte little endian integer from offset incrementing the offset by four.
@@ -7467,7 +7623,7 @@ class BinaryReader:
return None
return struct.unpack("<I", result)[0]
- def read64le(self, address:Optional[int]=None) -> Optional[int]:
+ def read64le(self, address: Optional[int] = None) -> Optional[int]:
"""
``read64le`` returns an eight byte little endian integer from offset incrementing the offset by eight.
@@ -7489,7 +7645,7 @@ class BinaryReader:
return None
return struct.unpack("<Q", result)[0]
- def read16be(self, address:Optional[int]=None) -> Optional[int]:
+ def read16be(self, address: Optional[int] = None) -> Optional[int]:
"""
``read16be`` returns a two byte big endian integer from offset incrementing the offset by two.
@@ -7511,7 +7667,7 @@ class BinaryReader:
return None
return struct.unpack(">H", result)[0]
- def read32be(self, address:Optional[int]=None) -> Optional[int]:
+ def read32be(self, address: Optional[int] = None) -> Optional[int]:
"""
``read32be`` returns a four byte big endian integer from offset incrementing the offset by four.
@@ -7532,7 +7688,7 @@ class BinaryReader:
return None
return struct.unpack(">I", result)[0]
- def read64be(self, address:Optional[int]=None) -> Optional[int]:
+ def read64be(self, address: Optional[int] = None) -> Optional[int]:
"""
``read64be`` returns an eight byte big endian integer from offset incrementing the offset by eight.
@@ -7553,7 +7709,7 @@ class BinaryReader:
return None
return struct.unpack(">Q", result)[0]
- def seek(self, offset:int) -> None:
+ def seek(self, offset: int) -> None:
"""
``seek`` update internal offset to ``offset``.
@@ -7570,7 +7726,7 @@ class BinaryReader:
"""
core.BNSeekBinaryReader(self._handle, offset)
- def seek_relative(self, offset:int) -> None:
+ def seek_relative(self, offset: int) -> None:
"""
``seek_relative`` updates the internal offset by ``offset``.
@@ -7610,7 +7766,7 @@ class BinaryWriter:
>>> bw = BinaryWriter(bv, Endianness.BigEndian)
>>>
"""
- def __init__(self, view:BinaryView, endian:Optional[Endianness] = None, address:Optional[int]=None):
+ def __init__(self, view: BinaryView, endian: Optional[Endianness] = None, address: Optional[int] = None):
self._handle = core.BNCreateBinaryWriter(view.handle)
assert self._handle is not None, "core.BNCreateBinaryWriter returned None"
self._view = view
@@ -7654,7 +7810,7 @@ class BinaryWriter:
return core.BNGetBinaryWriterEndianness(self._handle)
@endianness.setter
- def endianness(self, value:Endianness) -> None:
+ def endianness(self, value: Endianness) -> None:
core.BNSetBinaryWriterEndianness(self._handle, value)
@property
@@ -7669,10 +7825,10 @@ class BinaryWriter:
return core.BNGetWriterPosition(self._handle)
@offset.setter
- def offset(self, value:int) -> None:
+ def offset(self, value: int) -> None:
core.BNSeekBinaryWriter(self._handle, value)
- def write(self, value:bytes, address:Optional[int]=None, except_on_relocation=True) -> bool:
+ def write(self, value: bytes, address: Optional[int] = None, except_on_relocation=True) -> bool:
"""
``write`` writes ``len(value)`` bytes to the internal offset, without regard to endianness.
@@ -7700,7 +7856,7 @@ class BinaryWriter:
ctypes.memmove(buf, value, len(value))
return core.BNWriteData(self._handle, buf, len(value))
- def write8(self, value:int, address:Optional[int]=None, except_on_relocation=True) -> bool:
+ def write8(self, value: int, address: Optional[int] = None, except_on_relocation=True) -> bool:
"""
``write8`` lowest order byte from the integer ``value`` to the current offset.
@@ -7724,7 +7880,7 @@ class BinaryWriter:
raise RelocationWriteException("Attempting to write to a location which has a relocation")
return core.BNWrite8(self._handle, value)
- def write16(self, value:int, address:Optional[int]=None, except_on_relocation=True) -> bool:
+ def write16(self, value: int, address: Optional[int] = None, except_on_relocation=True) -> bool:
"""
``write16`` writes the lowest order two bytes from the integer ``value`` to the current offset, using internal endianness.
@@ -7741,7 +7897,7 @@ class BinaryWriter:
raise RelocationWriteException("Attempting to write to a location which has a relocation")
return core.BNWrite16(self._handle, value)
- def write32(self, value:int, address:Optional[int]=None, except_on_relocation=True) -> bool:
+ def write32(self, value: int, address: Optional[int] = None, except_on_relocation=True) -> bool:
"""
``write32`` writes the lowest order four bytes from the integer ``value`` to the current offset, using internal endianness.
@@ -7758,7 +7914,7 @@ class BinaryWriter:
raise RelocationWriteException("Attempting to write to a location which has a relocation")
return core.BNWrite32(self._handle, value)
- def write64(self, value:int, address:Optional[int]=None, except_on_relocation=True) -> bool:
+ def write64(self, value: int, address: Optional[int] = None, except_on_relocation=True) -> bool:
"""
``write64`` writes the lowest order eight bytes from the integer ``value`` to the current offset, using internal endianness.
@@ -7775,7 +7931,7 @@ class BinaryWriter:
raise RelocationWriteException("Attempting to write to a location which has a relocation")
return core.BNWrite64(self._handle, value)
- def write16le(self, value:int, address:Optional[int]=None, except_on_relocation=True) -> bool:
+ def write16le(self, value: int, address: Optional[int] = None, except_on_relocation=True) -> bool:
"""
``write16le`` writes the lowest order two bytes from the little endian integer ``value`` to the current offset.
@@ -7789,7 +7945,7 @@ class BinaryWriter:
self.seek(address)
return self.write(struct.pack("<H", value), except_on_relocation=except_on_relocation)
- def write32le(self, value:int, address:Optional[int]=None, except_on_relocation=True) -> bool:
+ def write32le(self, value: int, address: Optional[int] = None, except_on_relocation=True) -> bool:
"""
``write32le`` writes the lowest order four bytes from the little endian integer ``value`` to the current offset.
@@ -7803,7 +7959,7 @@ class BinaryWriter:
self.seek(address)
return self.write(struct.pack("<I", value), except_on_relocation=except_on_relocation)
- def write64le(self, value:int, address:Optional[int]=None, except_on_relocation=True) -> bool:
+ def write64le(self, value: int, address: Optional[int] = None, except_on_relocation=True) -> bool:
"""
``write64le`` writes the lowest order eight bytes from the little endian integer ``value`` to the current offset.
@@ -7817,7 +7973,7 @@ class BinaryWriter:
self.seek(address)
return self.write(struct.pack("<Q", value), except_on_relocation=except_on_relocation)
- def write16be(self, value:int, address:Optional[int]=None, except_on_relocation=True) -> bool:
+ def write16be(self, value: int, address: Optional[int] = None, except_on_relocation=True) -> bool:
"""
``write16be`` writes the lowest order two bytes from the big endian integer ``value`` to the current offset.
@@ -7831,7 +7987,7 @@ class BinaryWriter:
self.seek(address)
return self.write(struct.pack(">H", value), except_on_relocation=except_on_relocation)
- def write32be(self, value:int, address:Optional[int]=None, except_on_relocation=True) -> bool:
+ def write32be(self, value: int, address: Optional[int] = None, except_on_relocation=True) -> bool:
"""
``write32be`` writes the lowest order four bytes from the big endian integer ``value`` to the current offset.
@@ -7845,7 +8001,7 @@ class BinaryWriter:
self.seek(address)
return self.write(struct.pack(">I", value), except_on_relocation=except_on_relocation)
- def write64be(self, value:int, address:Optional[int]=None, except_on_relocation=True) -> bool:
+ def write64be(self, value: int, address: Optional[int] = None, except_on_relocation=True) -> bool:
"""
``write64be`` writes the lowest order eight bytes from the big endian integer ``value`` to the current offset.
@@ -7859,7 +8015,7 @@ class BinaryWriter:
self.seek(address)
return self.write(struct.pack(">Q", value), except_on_relocation=except_on_relocation)
- def seek(self, offset:int) -> None:
+ def seek(self, offset: int) -> None:
"""
``seek`` update internal offset to ``offset``.
@@ -7876,7 +8032,7 @@ class BinaryWriter:
"""
core.BNSeekBinaryWriter(self._handle, offset)
- def seek_relative(self, offset:int) -> None:
+ def seek_relative(self, offset: int) -> None:
"""
``seek_relative`` updates the internal offset by ``offset``.
@@ -7899,10 +8055,10 @@ class StructuredDataValue(object):
"""
DEPRECATED use: TypedDataAccessor instead.
"""
- type:'_types.Type'
- address:int
- value:bytes
- endian:Endianness
+ type: '_types.Type'
+ address: int
+ value: bytes
+ endian: Endianness
def __str__(self):
decode_str = "{}B".format(self.type.width)
@@ -7956,7 +8112,7 @@ class StructuredDataView(object):
003e
>>>
"""
- def __init__(self, bv:'BinaryView', structure_name:'_types.QualifiedNameType', address:int):
+ def __init__(self, bv: 'BinaryView', structure_name: '_types.QualifiedNameType', address: int):
self._bv = bv
self._structure_name = structure_name
self._address = address
@@ -7988,7 +8144,7 @@ class StructuredDataView(object):
return self[key]
- def __getitem__(self, key:str) -> Optional[StructuredDataValue]:
+ def __getitem__(self, key: str) -> Optional[StructuredDataValue]:
m = self._members.get(key, None)
if m is None:
return None
@@ -8027,10 +8183,10 @@ class StructuredDataView(object):
@dataclass
class TypedDataAccessor:
- type:'_types.Type'
- address:int
- view:'BinaryView'
- endian:Endianness
+ type: '_types.Type'
+ address: int
+ view: 'BinaryView'
+ endian: Endianness
def __post_init__(self):
if not isinstance(self.type, _types.Type):
@@ -8060,7 +8216,7 @@ class TypedDataAccessor:
return self.int_from_bytes(bytes(self), len(self), bool(_type.signed), self.endian)
raise Exception(f"Attempting to coerce non integral type: {type(_type)} to an integer")
- def __getitem__(self, key:Union[str, int]) -> 'TypedDataAccessor':
+ def __getitem__(self, key: Union[str, int]) -> 'TypedDataAccessor':
_type = self.type
if isinstance(_type, _types.NamedTypeReferenceType):
_type = _type.target(self.view)
@@ -8078,12 +8234,14 @@ class TypedDataAccessor:
return TypedDataAccessor(m.type.immutable_copy(), self.address + m.offset, self.view, self.endian)
@staticmethod
- def byte_order(endian) -> str: # as of python3.8 -> Literal["little", "big"]
+ def byte_order(endian) -> str: # as of python3.8 -> Literal["little", "big"]
return "little" if endian == Endianness.LittleEndian else "big"
@staticmethod
- def int_from_bytes(data:bytes, width:int, sign:bool, endian:Optional[Endianness]=None) -> int:
- return int.from_bytes(data[0:width], byteorder=TypedDataAccessor.byte_order(endian), signed=sign) # type: ignore
+ def int_from_bytes(data: bytes, width: int, sign: bool, endian: Optional[Endianness] = None) -> int:
+ return int.from_bytes(
+ data[0:width], byteorder=TypedDataAccessor.byte_order(endian), signed=sign
+ ) # type: ignore
def __float__(self):
if not isinstance(self.type, _types.FloatType):
@@ -8104,14 +8262,13 @@ class TypedDataAccessor:
return self._value_helper(self.type, self.view.read(self.address, len(self.type)))
@value.setter
- def value(self, data:Union[bytes, int]) -> None:
+ def value(self, data: Union[bytes, int]) -> None:
if isinstance(data, int):
- integral_types = (_types.IntegerType, _types.IntegerBuilder,
- _types.BoolType, _types.BoolBuilder,
- _types.CharType, _types.CharBuilder,
- _types.WideCharType, _types.WideCharBuilder,
- _types.PointerType, _types.PointerBuilder,
- _types.EnumerationType, _types.EnumerationBuilder)
+ integral_types = (
+ _types.IntegerType, _types.IntegerBuilder, _types.BoolType, _types.BoolBuilder, _types.CharType,
+ _types.CharBuilder, _types.WideCharType, _types.WideCharBuilder, _types.PointerType,
+ _types.PointerBuilder, _types.EnumerationType, _types.EnumerationBuilder
+ )
if not isinstance(self.type, integral_types):
raise TypeError(f"Can't set the value of type {type(self.type)} to int value")
to_write = data.to_bytes(len(self), TypedDataAccessor.byte_order(self.endian)) # type: ignore
@@ -8131,7 +8288,7 @@ class TypedDataAccessor:
count = self.view.write(self.address, to_write)
assert count == len(to_write), "Unable to write all bytes to the location, segment might not have file backing"
- def _value_helper(self, _type:'_types.Type', data:bytes) -> Any:
+ def _value_helper(self, _type: '_types.Type', data: bytes) -> Any:
if not isinstance(_type, _types.Type):
raise TypeError(f"Attempting to get value of TypeBuilder of type {type(_type)}")
if isinstance(_type, _types.NamedTypeReferenceType):
@@ -8140,7 +8297,7 @@ class TypedDataAccessor:
raise ValueError("Couldn't find target for type")
_type = target
- if isinstance(_type, (_types.VoidType, _types.FunctionType)): #, _types.VarArgsType, _types.ValueType)):
+ if isinstance(_type, (_types.VoidType, _types.FunctionType)): #, _types.VarArgsType, _types.ValueType)):
return None
elif isinstance(_type, _types.BoolType):
return bool(self)
@@ -8153,7 +8310,8 @@ class TypedDataAccessor:
elif isinstance(_type, _types.StructureType):
result = {}
for member in _type.members:
- result[member.name] = TypedDataAccessor(member.type, self.address + member.offset, self.view, self.endian).value
+ result[member.name
+ ] = TypedDataAccessor(member.type, self.address + member.offset, self.view, self.endian).value
return result
elif isinstance(_type, _types.EnumerationType):
value = int(self)
@@ -8168,7 +8326,9 @@ class TypedDataAccessor:
if _type.element_type.width == 1 and _type.element_type.type_class == TypeClass.IntegerTypeClass:
return bytes(self)
for offset in range(0, len(_type), _type.element_type.width):
- result.append(TypedDataAccessor(_type.element_type, self.address + offset, self.view, self.endian).value)
+ result.append(
+ TypedDataAccessor(_type.element_type, self.address + offset, self.view, self.endian).value
+ )
return result
else:
raise TypeError(f"Unhandled `Type` {type(_type)}")
@@ -8177,11 +8337,12 @@ class TypedDataAccessor:
# for backward compatibility
TypedDataReader = TypedDataAccessor
+
@dataclass
class CoreDataVariable:
- _address:int
- _type:'_types.Type'
- _auto_discovered:bool
+ _address: int
+ _type: '_types.Type'
+ _auto_discovered: bool
def __len__(self):
return len(self._type)
@@ -8200,15 +8361,16 @@ class CoreDataVariable:
class DataVariable(CoreDataVariable):
- def __init__(self, view:BinaryView, address:int, type:'_types.Type', auto_discovered:bool):
+ def __init__(self, view: BinaryView, address: int, type: '_types.Type', auto_discovered: bool):
super(DataVariable, self).__init__(address, type, auto_discovered)
self.view = view
self._sdv = TypedDataAccessor(self.type, self.address, self.view, self.view.endianness)
@classmethod
- def from_core_struct(cls, var:core.BNDataVariable, view:'BinaryView') -> 'DataVariable':
- var_type = _types.Type.create(core.BNNewTypeReference(var.type), platform=view.platform,
- confidence=var.typeConfidence)
+ def from_core_struct(cls, var: core.BNDataVariable, view: 'BinaryView') -> 'DataVariable':
+ var_type = _types.Type.create(
+ core.BNNewTypeReference(var.type), platform=view.platform, confidence=var.typeConfidence
+ )
return cls(view, var.address, var_type, var.autoDiscovered)
@property
@@ -8237,10 +8399,10 @@ class DataVariable(CoreDataVariable):
return self._sdv.value
@value.setter
- def value(self, data:bytes) -> None:
+ def value(self, data: bytes) -> None:
self._sdv.value = data
- def __getitem__(self, item:str):
+ def __getitem__(self, item: str):
return self._sdv[item]
@property
@@ -8248,7 +8410,7 @@ class DataVariable(CoreDataVariable):
return self._type
@type.setter
- def type(self, value:Optional['_types.Type']) -> None: # type: ignore
+ def type(self, value: Optional['_types.Type']) -> None: # type: ignore
_type = value if value is not None else _types.VoidType.create()
assert self.view.define_user_data_var(self.address, _type) is not None, "Unable to set DataVariable's type"
self._type = _type
@@ -8258,7 +8420,7 @@ class DataVariable(CoreDataVariable):
return self.view.get_symbol_at(self.address)
@symbol.setter
- def symbol(self, value:Optional[Union[str, '_types.CoreSymbol']]) -> None: # type: ignore
+ def symbol(self, value: Optional[Union[str, '_types.CoreSymbol']]) -> None: # type: ignore
if value is None or value == "":
if self.symbol is not None:
self.view.undefine_user_symbol(self.symbol)
@@ -8277,14 +8439,14 @@ class DataVariable(CoreDataVariable):
return self.symbol.name
@name.setter
- def name(self, value:str) -> None:
+ def name(self, value: str) -> None:
self.symbol = value
class DataVariableAndName(CoreDataVariable):
- def __init__(self, addr:int, var_type:'_types.Type', var_name:str, auto_discovered:bool) -> None:
+ def __init__(self, addr: int, var_type: '_types.Type', var_name: str, auto_discovered: bool) -> None:
super(DataVariableAndName, self).__init__(addr, var_type, auto_discovered)
self.name = var_name
def __repr__(self) -> str:
- return f"<var {self.address:#x}: {self.type} {self.name}>" \ No newline at end of file
+ return f"<var {self.address:#x}: {self.type} {self.name}>"
diff --git a/python/bncompleter.py b/python/bncompleter.py
index ba012a2a..ff093b9d 100644
--- a/python/bncompleter.py
+++ b/python/bncompleter.py
@@ -48,6 +48,7 @@ from typing import Optional
__all__ = ["Completer"]
+
def fnsignature(obj):
if sys.version_info[0:2] >= (3, 5):
try:
@@ -59,14 +60,14 @@ def fnsignature(obj):
try:
args = inspect.getargspec(obj).args
args.remove('self')
- sig = "(" + ','.join(args) + ")"
+ sig = "(" + ','.join(args) + ")"
except:
sig = "()"
return sig
class Completer:
- def __init__(self, namespace = None):
+ def __init__(self, namespace=None):
"""Create a new completer for the command line.
Completer([namespace]) -> completer instance.
@@ -93,7 +94,7 @@ class Completer:
self.use_main_ns = 0
self.namespace = namespace
- def complete(self, text:str, state) -> Optional[str]:
+ def complete(self, text: str, state) -> Optional[str]:
"""Return the next possible completion for 'text'.
This is called successively with state == 0, 1, 2, ... until it
@@ -140,16 +141,14 @@ class Completer:
seen.add(word)
if word in {'finally', 'try'}:
word = word + ':'
- elif word not in {'False', 'None', 'True',
- 'break', 'continue', 'pass',
- 'else'}:
+ elif word not in {'False', 'None', 'True', 'break', 'continue', 'pass', 'else'}:
word = word + ' '
matches.append(word)
#Not sure why in the console builtins becomes a dict but this works for now.
if hasattr(__builtins__, '__dict__'): # type: ignore # remove this ignore > pyright 1.1.149
- builtins = __builtins__.__dict__ # type: ignore # remove this ignore > pyright 1.1.149
+ builtins = __builtins__.__dict__ # type: ignore # remove this ignore > pyright 1.1.149
else:
- builtins = __builtins__ # type: ignore # remove this ignore > pyright 1.1.149
+ builtins = __builtins__ # type: ignore # remove this ignore > pyright 1.1.149
for nspace in [self.namespace, builtins]:
for word, val in nspace.items():
if word[:n] == text and word not in seen:
@@ -196,7 +195,7 @@ class Completer:
noprefix = None
while True:
for word in words:
- if (word[:n] == attr and not (noprefix and word[:n+1] == noprefix)):
+ if (word[:n] == attr and not (noprefix and word[:n + 1] == noprefix)):
match = f"{expr}.{word}"
try:
val = inspect.getattr_static(thisobject, word)
@@ -214,9 +213,10 @@ class Completer:
matches.sort()
return matches
+
def get_class_members(klass):
ret = dir(klass)
- if hasattr(klass,'__bases__'):
+ if hasattr(klass, '__bases__'):
for base in klass.__bases__:
ret = ret + get_class_members(base)
return ret
diff --git a/python/callingconvention.py b/python/callingconvention.py
index 89040119..44d835b7 100644
--- a/python/callingconvention.py
+++ b/python/callingconvention.py
@@ -29,8 +29,7 @@ from . import variable
from . import function
from . import architecture
-FunctionOrILFunction = Union["binaryninja.function.Function",
- "binaryninja.lowlevelil.LowLevelILFunction",
+FunctionOrILFunction = Union["binaryninja.function.Function", "binaryninja.lowlevelil.LowLevelILFunction",
"binaryninja.mediumlevelil.MediumLevelILFunction",
"binaryninja.highlevelil.HighLevelILFunction"]
@@ -54,7 +53,10 @@ class CallingConvention:
_registered_calling_conventions = []
- def __init__(self, arch:'architecture.Architecture'=None, name:str=None, handle=None, confidence:int=core.max_confidence):
+ def __init__(
+ self, arch: 'architecture.Architecture' = None, name: str = None, handle=None,
+ confidence: int = core.max_confidence
+ ):
if handle is None:
if arch is None or name is None:
raise ValueError("Must specify either handle or architecture and name")
@@ -64,23 +66,49 @@ class CallingConvention:
self._cb.context = 0
self._cb.getCallerSavedRegisters = self._cb.getCallerSavedRegisters.__class__(self._get_caller_saved_regs)
self._cb.getCalleeSavedRegisters = self._cb.getCalleeSavedRegisters.__class__(self._get_callee_saved_regs)
- self._cb.getIntegerArgumentRegisters = self._cb.getIntegerArgumentRegisters.__class__(self._get_int_arg_regs)
+ self._cb.getIntegerArgumentRegisters = self._cb.getIntegerArgumentRegisters.__class__(
+ self._get_int_arg_regs
+ )
self._cb.getFloatArgumentRegisters = self._cb.getFloatArgumentRegisters.__class__(self._get_float_arg_regs)
self._cb.freeRegisterList = self._cb.freeRegisterList.__class__(self._free_register_list)
- self._cb.areArgumentRegistersSharedIndex = self._cb.areArgumentRegistersSharedIndex.__class__(self._arg_regs_share_index)
- self._cb.areArgumentRegistersUsedForVarArgs = self._cb.areArgumentRegistersUsedForVarArgs.__class__(self._arg_regs_used_for_varargs)
- self._cb.isStackReservedForArgumentRegisters = self._cb.isStackReservedForArgumentRegisters.__class__(self._stack_reserved_for_arg_regs)
- self._cb.isStackAdjustedOnReturn = self._cb.isStackAdjustedOnReturn.__class__(self._stack_adjusted_on_return)
+ self._cb.areArgumentRegistersSharedIndex = self._cb.areArgumentRegistersSharedIndex.__class__(
+ self._arg_regs_share_index
+ )
+ self._cb.areArgumentRegistersUsedForVarArgs = self._cb.areArgumentRegistersUsedForVarArgs.__class__(
+ self._arg_regs_used_for_varargs
+ )
+ self._cb.isStackReservedForArgumentRegisters = self._cb.isStackReservedForArgumentRegisters.__class__(
+ self._stack_reserved_for_arg_regs
+ )
+ self._cb.isStackAdjustedOnReturn = self._cb.isStackAdjustedOnReturn.__class__(
+ self._stack_adjusted_on_return
+ )
self._cb.isEligibleForHeuristics = self._cb.isEligibleForHeuristics.__class__(self._eligible_for_heuristics)
- self._cb.getIntegerReturnValueRegister = self._cb.getIntegerReturnValueRegister.__class__(self._get_int_return_reg)
- self._cb.getHighIntegerReturnValueRegister = self._cb.getHighIntegerReturnValueRegister.__class__(self._get_high_int_return_reg)
- self._cb.getFloatReturnValueRegister = self._cb.getFloatReturnValueRegister.__class__(self._get_float_return_reg)
- self._cb.getGlobalPointerRegister = self._cb.getGlobalPointerRegister.__class__(self._get_global_pointer_reg)
- self._cb.getImplicitlyDefinedRegisters = self._cb.getImplicitlyDefinedRegisters.__class__(self._get_implicitly_defined_regs)
- self._cb.getIncomingRegisterValue = self._cb.getIncomingRegisterValue.__class__(self._get_incoming_reg_value)
+ self._cb.getIntegerReturnValueRegister = self._cb.getIntegerReturnValueRegister.__class__(
+ self._get_int_return_reg
+ )
+ self._cb.getHighIntegerReturnValueRegister = self._cb.getHighIntegerReturnValueRegister.__class__(
+ self._get_high_int_return_reg
+ )
+ self._cb.getFloatReturnValueRegister = self._cb.getFloatReturnValueRegister.__class__(
+ self._get_float_return_reg
+ )
+ self._cb.getGlobalPointerRegister = self._cb.getGlobalPointerRegister.__class__(
+ self._get_global_pointer_reg
+ )
+ self._cb.getImplicitlyDefinedRegisters = self._cb.getImplicitlyDefinedRegisters.__class__(
+ self._get_implicitly_defined_regs
+ )
+ self._cb.getIncomingRegisterValue = self._cb.getIncomingRegisterValue.__class__(
+ self._get_incoming_reg_value
+ )
self._cb.getIncomingFlagValue = self._cb.getIncomingFlagValue.__class__(self._get_incoming_flag_value)
- self._cb.getIncomingVariableForParameterVariable = self._cb.getIncomingVariableForParameterVariable.__class__(self._get_incoming_var_for_parameter_var)
- self._cb.getParameterVariableForIncomingVariable = self._cb.getParameterVariableForIncomingVariable.__class__(self._get_parameter_var_for_incoming_var)
+ self._cb.getIncomingVariableForParameterVariable = self._cb.getIncomingVariableForParameterVariable.__class__(
+ self._get_incoming_var_for_parameter_var
+ )
+ self._cb.getParameterVariableForIncomingVariable = self._cb.getParameterVariableForIncomingVariable.__class__(
+ self._get_parameter_var_for_incoming_var
+ )
_handle = core.BNCreateCallingConvention(arch.handle, name, self._cb)
self.__class__._registered_calling_conventions.append(self)
else:
@@ -352,7 +380,7 @@ class CallingConvention:
def _get_incoming_reg_value(self, ctxt, reg, func, result):
try:
- func_obj = function.Function(handle = core.BNNewFunctionReference(func))
+ func_obj = function.Function(handle=core.BNNewFunctionReference(func))
reg_name = self.arch.get_reg_name(reg)
api_obj = self.perform_get_incoming_reg_value(reg_name, func_obj)._to_core_struct()
except:
@@ -363,7 +391,7 @@ class CallingConvention:
def _get_incoming_flag_value(self, ctxt, reg, func, result):
try:
- func_obj = function.Function(handle = core.BNNewFunctionReference(func))
+ func_obj = function.Function(handle=core.BNNewFunctionReference(func))
reg_name = self.arch.get_reg_name(reg)
api_obj = self.perform_get_incoming_flag_value(reg_name, func_obj)._to_core_struct()
except:
@@ -377,7 +405,7 @@ class CallingConvention:
if func is None:
func_obj = None
else:
- func_obj = function.Function(handle = core.BNNewFunctionReference(func))
+ func_obj = function.Function(handle=core.BNNewFunctionReference(func))
in_var_obj = variable.CoreVariable.from_BNVariable(in_var[0])
out_var = self.perform_get_incoming_var_for_parameter_var(in_var_obj, func_obj)
result[0].type = out_var.source_type
@@ -394,7 +422,7 @@ class CallingConvention:
if func is None:
func_obj = None
else:
- func_obj = function.Function(handle = core.BNNewFunctionReference(func))
+ func_obj = function.Function(handle=core.BNNewFunctionReference(func))
in_var_obj = variable.CoreVariable.from_BNVariable(in_var[0])
out_var = self.perform_get_parameter_var_for_incoming_var(in_var_obj, func_obj)
result[0].type = out_var.source_type
@@ -406,45 +434,62 @@ class CallingConvention:
result[0].index = in_var[0].index
result[0].storage = in_var[0].storage
- def perform_get_incoming_reg_value(self, reg:'architecture.RegisterName', func:'function.Function') -> 'variable.RegisterValue':
+ def perform_get_incoming_reg_value(
+ self, reg: 'architecture.RegisterName', func: 'function.Function'
+ ) -> 'variable.RegisterValue':
reg_stack = self.arch.get_reg_stack_for_reg(reg)
if reg_stack is not None:
if reg == self.arch.reg_stacks[reg_stack].stack_top_reg:
return variable.ConstantRegisterValue(0)
return variable.Undetermined()
- def perform_get_incoming_flag_value(self, reg:'architecture.RegisterName', func:'function.Function') -> 'variable.RegisterValue':
+ def perform_get_incoming_flag_value(
+ self, reg: 'architecture.RegisterName', func: 'function.Function'
+ ) -> 'variable.RegisterValue':
return variable.Undetermined()
- def perform_get_incoming_var_for_parameter_var(self, in_var:'variable.CoreVariable',
- func:Optional['function.Function']=None) -> 'variable.CoreVariable':
+ def perform_get_incoming_var_for_parameter_var(
+ self, in_var: 'variable.CoreVariable', func: Optional['function.Function'] = None
+ ) -> 'variable.CoreVariable':
out_var = core.BNGetDefaultIncomingVariableForParameterVariable(self.handle, in_var.to_BNVariable())
return variable.CoreVariable.from_BNVariable(out_var)
- def perform_get_parameter_var_for_incoming_var(self, in_var:'variable.CoreVariable',
- func:Optional['function.Function']=None) -> 'variable.CoreVariable':
+ def perform_get_parameter_var_for_incoming_var(
+ self, in_var: 'variable.CoreVariable', func: Optional['function.Function'] = None
+ ) -> 'variable.CoreVariable':
out_var = core.BNGetDefaultParameterVariableForIncomingVariable(self.handle, in_var.to_BNVariable())
return variable.CoreVariable.from_BNVariable(out_var)
- def with_confidence(self, confidence:int) -> 'CallingConvention':
- return CallingConvention(self.arch, handle = core.BNNewCallingConventionReference(self.handle),
- confidence = confidence)
+ def with_confidence(self, confidence: int) -> 'CallingConvention':
+ return CallingConvention(
+ self.arch, handle=core.BNNewCallingConventionReference(self.handle), confidence=confidence
+ )
- def get_incoming_reg_value(self, reg:'architecture.RegisterType', func:'function.Function') -> 'variable.RegisterValue':
+ def get_incoming_reg_value(
+ self, reg: 'architecture.RegisterType', func: 'function.Function'
+ ) -> 'variable.RegisterValue':
reg_num = self.arch.get_reg_index(reg)
func_handle = None
if func is not None:
func_handle = func.handle
- return variable.RegisterValue.from_BNRegisterValue(core.BNGetIncomingRegisterValue(self.handle, reg_num, func_handle), self.arch)
+ return variable.RegisterValue.from_BNRegisterValue(
+ core.BNGetIncomingRegisterValue(self.handle, reg_num, func_handle), self.arch
+ )
- def get_incoming_flag_value(self, flag:'architecture.FlagIndex', func:'function.Function') -> 'variable.RegisterValue':
+ def get_incoming_flag_value(
+ self, flag: 'architecture.FlagIndex', func: 'function.Function'
+ ) -> 'variable.RegisterValue':
reg_num = self.arch.get_flag_index(flag)
func_handle = None
if func is not None:
func_handle = func.handle
- return variable.RegisterValue.from_BNRegisterValue(core.BNGetIncomingFlagValue(self.handle, reg_num, func_handle), self.arch)
+ return variable.RegisterValue.from_BNRegisterValue(
+ core.BNGetIncomingFlagValue(self.handle, reg_num, func_handle), self.arch
+ )
- def get_incoming_var_for_parameter_var(self, in_var:'variable.CoreVariable', func:FunctionOrILFunction) -> 'variable.Variable':
+ def get_incoming_var_for_parameter_var(
+ self, in_var: 'variable.CoreVariable', func: FunctionOrILFunction
+ ) -> 'variable.Variable':
in_buf = in_var.to_BNVariable()
if func is None:
func_obj = None
@@ -453,7 +498,9 @@ class CallingConvention:
out_var = core.BNGetIncomingVariableForParameterVariable(self.handle, in_buf, func_obj)
return variable.Variable.from_BNVariable(func, out_var)
- def get_parameter_var_for_incoming_var(self, in_var:'variable.CoreVariable', func:FunctionOrILFunction) -> 'variable.Variable':
+ def get_parameter_var_for_incoming_var(
+ self, in_var: 'variable.CoreVariable', func: FunctionOrILFunction
+ ) -> 'variable.Variable':
in_buf = in_var.to_BNVariable()
if func is None:
func_obj = None
@@ -467,5 +514,5 @@ class CallingConvention:
return self._arch
@arch.setter
- def arch(self, value:'architecture.Architecture') -> None:
+ def arch(self, value: 'architecture.Architecture') -> None:
self._arch = value
diff --git a/python/commonil.py b/python/commonil.py
index 9e9f6fea..7517574d 100644
--- a/python/commonil.py
+++ b/python/commonil.py
@@ -24,11 +24,12 @@ from .enums import BranchType
from .interaction import show_graph_report
from .log import log_warn
+
# This file contains a list of top level abstract classes for implementing BNIL instructions
@dataclass(frozen=True, repr=False, eq=False)
class BaseILInstruction:
@classmethod
- def prepend_parent(cls, graph:FlowGraph, node:FlowGraphNode, nodes={}):
+ def prepend_parent(cls, graph: FlowGraph, node: FlowGraphNode, nodes={}):
for parent in cls.__bases__:
if not issubclass(parent, BaseILInstruction):
continue
@@ -54,6 +55,7 @@ class BaseILInstruction:
def show_hierarchy_graph(cls):
show_graph_report(f"{cls.__name__}", cls.add_subgraph(FlowGraph(), {}))
+
@dataclass(frozen=True, repr=False, eq=False)
class Constant(BaseILInstruction):
pass
@@ -123,6 +125,7 @@ class Localcall(Call):
class Tailcall(Localcall):
pass
+
@dataclass(frozen=True, repr=False, eq=False)
class Return(Terminal):
pass
diff --git a/python/compatibility.py b/python/compatibility.py
index bae8a6d3..fef7e49b 100644
--- a/python/compatibility.py
+++ b/python/compatibility.py
@@ -20,6 +20,7 @@
import sys
+
def pyNativeStr(arg):
if isinstance(arg, str):
return arg
@@ -36,5 +37,3 @@ def valid_import(mod_name):
mod_loader = importlib.find_loader(mod_name)
found = mod_loader is not None
return found
-
-
diff --git a/python/database.py b/python/database.py
index a563d99c..b9b81058 100644
--- a/python/database.py
+++ b/python/database.py
@@ -28,322 +28,322 @@ from . import filemetadata
class KeyValueStore:
- """
+ """
``class KeyValueStore`` maintains access to the raw data stored in Snapshots and various
other Database-related structures.
"""
- def __init__(self, buffer: Optional[databuffer.DataBuffer] = None, handle=None):
- if handle is not None:
- self.handle = core.handle_of_type(handle, core.BNKeyValueStore)
- else:
- if buffer is None:
- _handle = core.BNCreateKeyValueStore()
- else:
- _handle = core.BNCreateKeyValueStoreFromDataBuffer(buffer.handle)
- assert _handle is not None
- self.handle = _handle
+ def __init__(self, buffer: Optional[databuffer.DataBuffer] = None, handle=None):
+ if handle is not None:
+ self.handle = core.handle_of_type(handle, core.BNKeyValueStore)
+ else:
+ if buffer is None:
+ _handle = core.BNCreateKeyValueStore()
+ else:
+ _handle = core.BNCreateKeyValueStoreFromDataBuffer(buffer.handle)
+ assert _handle is not None
+ self.handle = _handle
- def __del__(self):
- core.BNFreeKeyValueStore(self.handle)
+ def __del__(self):
+ core.BNFreeKeyValueStore(self.handle)
- def __getitem__(self, item: str) -> databuffer.DataBuffer:
- return self.get_value(item)
+ def __getitem__(self, item: str) -> databuffer.DataBuffer:
+ return self.get_value(item)
- def __setitem__(self, key: str, value: databuffer.DataBuffer):
- return self.set_value(key, value)
+ def __setitem__(self, key: str, value: databuffer.DataBuffer):
+ return self.set_value(key, value)
- @property
- def keys(self):
- """Get a list of all keys stored in the kvs (read-only)"""
- count = ctypes.c_ulonglong(0)
- value = core.BNGetKeyValueStoreKeys(self.handle, count)
- assert value is not None
+ @property
+ def keys(self):
+ """Get a list of all keys stored in the kvs (read-only)"""
+ count = ctypes.c_ulonglong(0)
+ value = core.BNGetKeyValueStoreKeys(self.handle, count)
+ assert value is not None
- result = []
- try:
- for i in range(0, count.value):
- result.append(value[i])
- return result
- finally:
- core.BNFreeStringList(value, count)
+ result = []
+ try:
+ for i in range(0, count.value):
+ result.append(value[i])
+ return result
+ finally:
+ core.BNFreeStringList(value, count)
- def get_value(self, key: str) -> databuffer.DataBuffer:
- """Get the value for a single key"""
- handle = core.BNGetKeyValueStoreBuffer(self.handle, key)
- assert handle is not None
- return databuffer.DataBuffer(handle=handle)
+ def get_value(self, key: str) -> databuffer.DataBuffer:
+ """Get the value for a single key"""
+ handle = core.BNGetKeyValueStoreBuffer(self.handle, key)
+ assert handle is not None
+ return databuffer.DataBuffer(handle=handle)
- def set_value(self, key: str, value: databuffer.DataBuffer):
- """Set the value for a single key"""
- core.BNSetKeyValueStoreBuffer(self.handle, key, value.handle)
+ def set_value(self, key: str, value: databuffer.DataBuffer):
+ """Set the value for a single key"""
+ core.BNSetKeyValueStoreBuffer(self.handle, key, value.handle)
- @property
- def serialized_data(self) -> databuffer.DataBuffer:
- """Get the stored representation of the kvs (read-only)"""
- handle = core.BNGetKeyValueStoreSerializedData(self.handle)
- assert handle is not None
- return databuffer.DataBuffer(handle=handle)
+ @property
+ def serialized_data(self) -> databuffer.DataBuffer:
+ """Get the stored representation of the kvs (read-only)"""
+ handle = core.BNGetKeyValueStoreSerializedData(self.handle)
+ assert handle is not None
+ return databuffer.DataBuffer(handle=handle)
- def begin_namespace(self, name: str):
- """Begin storing new keys into a namespace"""
- core.BNBeginKeyValueStoreNamespace(self.handle, name)
+ def begin_namespace(self, name: str):
+ """Begin storing new keys into a namespace"""
+ core.BNBeginKeyValueStoreNamespace(self.handle, name)
- def end_namespace(self):
- """End storing new keys into a namespace"""
- core.BNEndKeyValueStoreNamespace(self.handle)
+ def end_namespace(self):
+ """End storing new keys into a namespace"""
+ core.BNEndKeyValueStoreNamespace(self.handle)
- @property
- def empty(self) -> bool:
- """If the kvs is empty (read-only)"""
- return core.BNIsKeyValueStoreEmpty(self.handle)
+ @property
+ def empty(self) -> bool:
+ """If the kvs is empty (read-only)"""
+ return core.BNIsKeyValueStoreEmpty(self.handle)
- @property
- def value_size(self) -> bool:
- """Number of values in the kvs (read-only)"""
- return core.BNGetKeyValueStoreValueSize(self.handle)
+ @property
+ def value_size(self) -> bool:
+ """Number of values in the kvs (read-only)"""
+ return core.BNGetKeyValueStoreValueSize(self.handle)
- @property
- def data_size(self) -> bool:
- """Length of serialized data (read-only)"""
- return core.BNGetKeyValueStoreDataSize(self.handle)
+ @property
+ def data_size(self) -> bool:
+ """Length of serialized data (read-only)"""
+ return core.BNGetKeyValueStoreDataSize(self.handle)
- @property
- def value_storage_size(self) -> bool:
- """Size of all data in storage (read-only)"""
- return core.BNGetKeyValueStoreValueStorageSize(self.handle)
+ @property
+ def value_storage_size(self) -> bool:
+ """Size of all data in storage (read-only)"""
+ return core.BNGetKeyValueStoreValueStorageSize(self.handle)
- @property
- def namespace_size(self) -> bool:
- """Number of namespaces pushed with begin_namespace (read-only)"""
- return core.BNGetKeyValueStoreNamespaceSize(self.handle)
+ @property
+ def namespace_size(self) -> bool:
+ """Number of namespaces pushed with begin_namespace (read-only)"""
+ return core.BNGetKeyValueStoreNamespaceSize(self.handle)
class Snapshot:
- """
+ """
``class Snapshot`` is a model of an individual database snapshot, created on save.
"""
- def __init__(self, handle):
- self.handle = core.handle_of_type(handle, core.BNSnapshot)
+ def __init__(self, handle):
+ self.handle = core.handle_of_type(handle, core.BNSnapshot)
- def __del__(self):
- core.BNFreeSnapshot(self.handle)
+ def __del__(self):
+ core.BNFreeSnapshot(self.handle)
- @property
- def database(self) -> 'Database':
- """Get the owning database (read-only)"""
- return Database(handle=core.BNGetSnapshotDatabase(self.handle))
+ @property
+ def database(self) -> 'Database':
+ """Get the owning database (read-only)"""
+ return Database(handle=core.BNGetSnapshotDatabase(self.handle))
- @property
- def id(self) -> int:
- """Get the numerical id (read-only)"""
- return core.BNGetSnapshotId(self.handle)
+ @property
+ def id(self) -> int:
+ """Get the numerical id (read-only)"""
+ return core.BNGetSnapshotId(self.handle)
- @property
- def name(self) -> str:
- """Get the displayed snapshot name (read-only)"""
- return core.BNGetSnapshotName(self.handle)
+ @property
+ def name(self) -> str:
+ """Get the displayed snapshot name (read-only)"""
+ return core.BNGetSnapshotName(self.handle)
- @property
- def is_auto_save(self) -> bool:
- """If the snapshot was the result of an auto-save (read-only)"""
- return core.BNIsSnapshotAutoSave(self.handle)
+ @property
+ def is_auto_save(self) -> bool:
+ """If the snapshot was the result of an auto-save (read-only)"""
+ return core.BNIsSnapshotAutoSave(self.handle)
- @property
- def has_contents(self) -> bool:
- """If the snapshot has contents, and has not been trimmed (read-only)"""
- return core.BNSnapshotHasContents(self.handle)
+ @property
+ def has_contents(self) -> bool:
+ """If the snapshot has contents, and has not been trimmed (read-only)"""
+ return core.BNSnapshotHasContents(self.handle)
- @property
- def has_undo(self) -> bool:
- """If the snapshot has undo data (read-only)"""
- return core.BNSnapshotHasUndo(self.handle)
+ @property
+ def has_undo(self) -> bool:
+ """If the snapshot has undo data (read-only)"""
+ return core.BNSnapshotHasUndo(self.handle)
- @property
- def first_parent(self) -> Optional['Snapshot']:
- """Get the first parent of the snapshot, or None if it has no parents (read-only)"""
- handle = core.BNGetSnapshotFirstParent(self.handle)
- if handle is None:
- return None
- return Snapshot(handle=handle)
+ @property
+ def first_parent(self) -> Optional['Snapshot']:
+ """Get the first parent of the snapshot, or None if it has no parents (read-only)"""
+ handle = core.BNGetSnapshotFirstParent(self.handle)
+ if handle is None:
+ return None
+ return Snapshot(handle=handle)
- @property
- def parents(self) -> List['Snapshot']:
- """Get a list of all parent snapshots of the snapshot (read-only)"""
- count = ctypes.c_ulonglong(0)
- parents = core.BNGetSnapshotParents(self.handle, count)
+ @property
+ def parents(self) -> List['Snapshot']:
+ """Get a list of all parent snapshots of the snapshot (read-only)"""
+ count = ctypes.c_ulonglong(0)
+ parents = core.BNGetSnapshotParents(self.handle, count)
- result = []
- try:
- for i in range(0, count.value):
- handle = core.BNNewSnapshotReference(parents[i])
- result.append(Snapshot(handle=handle))
- return result
- finally:
- core.BNFreeSnapshotList(parents, count)
+ result = []
+ try:
+ for i in range(0, count.value):
+ handle = core.BNNewSnapshotReference(parents[i])
+ result.append(Snapshot(handle=handle))
+ return result
+ finally:
+ core.BNFreeSnapshotList(parents, count)
- @property
- def children(self) -> List['Snapshot']:
- """Get a list of all child snapshots of the snapshot (read-only)"""
- count = ctypes.c_ulonglong(0)
- children = core.BNGetSnapshotChildren(self.handle, count)
+ @property
+ def children(self) -> List['Snapshot']:
+ """Get a list of all child snapshots of the snapshot (read-only)"""
+ count = ctypes.c_ulonglong(0)
+ children = core.BNGetSnapshotChildren(self.handle, count)
- result = []
- try:
- for i in range(0, count.value):
- handle = core.BNNewSnapshotReference(children[i])
- result.append(Snapshot(handle=handle))
- return result
- finally:
- core.BNFreeSnapshotList(children, count)
+ result = []
+ try:
+ for i in range(0, count.value):
+ handle = core.BNNewSnapshotReference(children[i])
+ result.append(Snapshot(handle=handle))
+ return result
+ finally:
+ core.BNFreeSnapshotList(children, count)
- @property
- def file_contents(self) -> databuffer.DataBuffer:
- """Get a buffer of the raw data at the time of the snapshot (read-only)"""
- assert self.has_contents
- handle = core.BNGetSnapshotFileContents(self.handle)
- assert handle is not None
- return databuffer.DataBuffer(handle=handle)
+ @property
+ def file_contents(self) -> databuffer.DataBuffer:
+ """Get a buffer of the raw data at the time of the snapshot (read-only)"""
+ assert self.has_contents
+ handle = core.BNGetSnapshotFileContents(self.handle)
+ assert handle is not None
+ return databuffer.DataBuffer(handle=handle)
- @property
- def file_contents_hash(self) -> databuffer.DataBuffer:
- """Get a hash of the data at the time of the snapshot (read-only)"""
- assert self.has_contents
- handle = core.BNGetSnapshotFileContentsHash(self.handle)
- assert handle is not None
- return databuffer.DataBuffer(handle=handle)
+ @property
+ def file_contents_hash(self) -> databuffer.DataBuffer:
+ """Get a hash of the data at the time of the snapshot (read-only)"""
+ assert self.has_contents
+ handle = core.BNGetSnapshotFileContentsHash(self.handle)
+ assert handle is not None
+ return databuffer.DataBuffer(handle=handle)
- @property
- def undo_entries(self):
- """Get a list of undo entries at the time of the snapshot (read-only)"""
- assert self.has_undo
- raise NotImplementedError("GetUndoEntries is not implemented in python")
+ @property
+ def undo_entries(self):
+ """Get a list of undo entries at the time of the snapshot (read-only)"""
+ assert self.has_undo
+ raise NotImplementedError("GetUndoEntries is not implemented in python")
- @property
- def data(self) -> KeyValueStore:
- """Get the backing kvs data with snapshot fields (read-only)"""
- assert self.has_contents
- handle = core.BNReadSnapshotData(self.handle)
- assert handle is not None
- return KeyValueStore(handle=handle)
+ @property
+ def data(self) -> KeyValueStore:
+ """Get the backing kvs data with snapshot fields (read-only)"""
+ assert self.has_contents
+ handle = core.BNReadSnapshotData(self.handle)
+ assert handle is not None
+ return KeyValueStore(handle=handle)
- def has_ancestor(self, other: 'Snapshot') -> bool:
- """Determine if this snapshot has another as an ancestor"""
- return core.BNSnapshotHasAncestor(self.handle, other.handle)
+ def has_ancestor(self, other: 'Snapshot') -> bool:
+ """Determine if this snapshot has another as an ancestor"""
+ return core.BNSnapshotHasAncestor(self.handle, other.handle)
class Database:
- """
+ """
``class Database`` provides lower level access to raw snapshot data used to construct analysis data
"""
- def __init__(self, handle):
- self.handle = core.handle_of_type(handle, core.BNDatabase)
+ def __init__(self, handle):
+ self.handle = core.handle_of_type(handle, core.BNDatabase)
- def __del__(self):
- core.BNFreeDatabase(self.handle)
+ def __del__(self):
+ core.BNFreeDatabase(self.handle)
- def __getitem__(self, item: int) -> Optional[Snapshot]:
- return self.get_snapshot(item)
+ def __getitem__(self, item: int) -> Optional[Snapshot]:
+ return self.get_snapshot(item)
- def get_snapshot(self, id: int) -> Optional[Snapshot]:
- """Get a snapshot by its id, or None if no snapshot with that id exists"""
- snap = core.BNGetDatabaseSnapshot(self.handle, id)
- if snap is None:
- return None
- return Snapshot(handle=snap)
+ def get_snapshot(self, id: int) -> Optional[Snapshot]:
+ """Get a snapshot by its id, or None if no snapshot with that id exists"""
+ snap = core.BNGetDatabaseSnapshot(self.handle, id)
+ if snap is None:
+ return None
+ return Snapshot(handle=snap)
- @property
- def snapshots(self) -> List[Snapshot]:
- """Get a list of all snapshots in the database (read-only)"""
- count = ctypes.c_ulonglong(0)
- snapshots = core.BNGetDatabaseSnapshots(self.handle, count)
- assert snapshots is not None
+ @property
+ def snapshots(self) -> List[Snapshot]:
+ """Get a list of all snapshots in the database (read-only)"""
+ count = ctypes.c_ulonglong(0)
+ snapshots = core.BNGetDatabaseSnapshots(self.handle, count)
+ assert snapshots is not None
- result = []
- try:
- for i in range(0, count.value):
- handle = core.BNNewSnapshotReference(snapshots[i])
- result.append(Snapshot(handle=handle))
- return result
- finally:
- core.BNFreeSnapshotList(snapshots, count)
+ result = []
+ try:
+ for i in range(0, count.value):
+ handle = core.BNNewSnapshotReference(snapshots[i])
+ result.append(Snapshot(handle=handle))
+ return result
+ finally:
+ core.BNFreeSnapshotList(snapshots, count)
- @property
- def current_snapshot(self) -> Optional[Snapshot]:
- """Get the current snapshot"""
- snap = core.BNGetDatabaseCurrentSnapshot(self.handle)
- if snap is None:
- return None
- return Snapshot(handle=snap)
+ @property
+ def current_snapshot(self) -> Optional[Snapshot]:
+ """Get the current snapshot"""
+ snap = core.BNGetDatabaseCurrentSnapshot(self.handle)
+ if snap is None:
+ return None
+ return Snapshot(handle=snap)
- @current_snapshot.setter
- def current_snapshot(self, value: Snapshot):
- core.BNSetDatabaseCurrentSnapshot(self.handle, value.id)
+ @current_snapshot.setter
+ def current_snapshot(self, value: Snapshot):
+ core.BNSetDatabaseCurrentSnapshot(self.handle, value.id)
- def remove_snapsot(self, id: int):
- """Remove a snapshot in the database by id"""
- core.BNRemoveDatabaseSnapshot(self.handle, id)
+ def remove_snapsot(self, id: int):
+ """Remove a snapshot in the database by id"""
+ core.BNRemoveDatabaseSnapshot(self.handle, id)
- @property
- def global_keys(self) -> List[str]:
- """Get a list of keys for all globals in the database (read-only)"""
- count = ctypes.c_ulonglong(0)
- value = core.BNGetDatabaseGlobalKeys(self.handle, count)
- assert value is not None
+ @property
+ def global_keys(self) -> List[str]:
+ """Get a list of keys for all globals in the database (read-only)"""
+ count = ctypes.c_ulonglong(0)
+ value = core.BNGetDatabaseGlobalKeys(self.handle, count)
+ assert value is not None
- result = []
- try:
- for i in range(0, count.value):
- result.append(value[i])
- return result
- finally:
- core.BNFreeStringList(value, count)
+ result = []
+ try:
+ for i in range(0, count.value):
+ result.append(value[i])
+ return result
+ finally:
+ core.BNFreeStringList(value, count)
- @property
- def globals(self) -> Dict[str, str]:
- """Get a dictionary of all globals (read-only)"""
- count = ctypes.c_ulonglong(0)
- value = core.BNGetDatabaseGlobalKeys(self.handle, count)
- assert value is not None
+ @property
+ def globals(self) -> Dict[str, str]:
+ """Get a dictionary of all globals (read-only)"""
+ count = ctypes.c_ulonglong(0)
+ value = core.BNGetDatabaseGlobalKeys(self.handle, count)
+ assert value is not None
- result = {}
- try:
- for i in range(0, count.value):
- key = value[i]
- result[key] = self.read_global(key)
- return result
- finally:
- core.BNFreeStringList(value, count)
+ result = {}
+ try:
+ for i in range(0, count.value):
+ key = value[i]
+ result[key] = self.read_global(key)
+ return result
+ finally:
+ core.BNFreeStringList(value, count)
- def read_global(self, key: str) -> str:
- """Get a specific global by key"""
- value = core.BNReadDatabaseGlobal(self.handle, key)
- assert value is not None
- return value
+ def read_global(self, key: str) -> str:
+ """Get a specific global by key"""
+ value = core.BNReadDatabaseGlobal(self.handle, key)
+ assert value is not None
+ return value
- def write_global(self, key: str, value: str):
- """Write a global into the database"""
- core.BNWriteDatabaseGlobal(self.handle, key, value)
+ def write_global(self, key: str, value: str):
+ """Write a global into the database"""
+ core.BNWriteDatabaseGlobal(self.handle, key, value)
- def read_global_data(self, key: str) -> databuffer.DataBuffer:
- """Get a specific global by key, as a binary buffer"""
- handle = core.BNReadDatabaseGlobalData(self.handle, key)
- assert handle is not None
- return databuffer.DataBuffer(handle=handle)
+ def read_global_data(self, key: str) -> databuffer.DataBuffer:
+ """Get a specific global by key, as a binary buffer"""
+ handle = core.BNReadDatabaseGlobalData(self.handle, key)
+ assert handle is not None
+ return databuffer.DataBuffer(handle=handle)
- def write_global_data(self, key: str, value: databuffer.DataBuffer):
- """Write a binary buffer into a global in the database"""
- core.BNWriteDatabaseGlobalData(self.handle, key, value.handle)
+ def write_global_data(self, key: str, value: databuffer.DataBuffer):
+ """Write a binary buffer into a global in the database"""
+ core.BNWriteDatabaseGlobalData(self.handle, key, value.handle)
- @property
- def file(self) -> 'filemetadata.FileMetadata':
- """Get the owning FileMetadata (read-only)"""
- handle = core.BNGetDatabaseFile(self.handle)
- assert handle is not None
- return filemetadata.FileMetadata(handle=handle)
+ @property
+ def file(self) -> 'filemetadata.FileMetadata':
+ """Get the owning FileMetadata (read-only)"""
+ handle = core.BNGetDatabaseFile(self.handle)
+ assert handle is not None
+ return filemetadata.FileMetadata(handle=handle)
- @property
- def analysis_cache(self) -> KeyValueStore:
- """Get the backing analysis cache kvs (read-only)"""
- handle = core.BNReadDatabaseAnalysisCache(self.handle)
- assert handle is not None
- return KeyValueStore(handle=handle)
+ @property
+ def analysis_cache(self) -> KeyValueStore:
+ """Get the backing analysis cache kvs (read-only)"""
+ handle = core.BNReadDatabaseAnalysisCache(self.handle)
+ assert handle is not None
+ return KeyValueStore(handle=handle)
diff --git a/python/databuffer.py b/python/databuffer.py
index df16cc54..f4905cbd 100644
--- a/python/databuffer.py
+++ b/python/databuffer.py
@@ -25,8 +25,10 @@ from typing import Optional, Union
from . import _binaryninjacore as core
DataBufferInputType = Union[str, bytes, 'DataBuffer', int]
+
+
class DataBuffer:
- def __init__(self, contents:Union[str, bytes, 'DataBuffer', int]=b"", handle=None):
+ def __init__(self, contents: Union[str, bytes, 'DataBuffer', int] = b"", handle=None):
if handle is not None:
self.handle = core.handle_of_type(handle, core.BNDataBuffer)
elif isinstance(contents, int):
@@ -147,24 +149,24 @@ class DataBuffer:
return core.BNDataBufferToBase64(self.handle)
def base64_decode(self) -> 'DataBuffer':
- return DataBuffer(handle = core.BNDecodeBase64(str(self)))
+ return DataBuffer(handle=core.BNDecodeBase64(str(self)))
def zlib_compress(self) -> Optional['DataBuffer']:
buf = core.BNZlibCompress(self.handle)
if buf is None:
return None
- return DataBuffer(handle = buf)
+ return DataBuffer(handle=buf)
def zlib_decompress(self) -> Optional['DataBuffer']:
buf = core.BNZlibDecompress(self.handle)
if buf is None:
return None
- return DataBuffer(handle = buf)
+ return DataBuffer(handle=buf)
-def escape_string(text:bytes) -> str:
+def escape_string(text: bytes) -> str:
return DataBuffer(text).escape()
-def unescape_string(text:bytes) -> 'DataBuffer':
+def unescape_string(text: bytes) -> 'DataBuffer':
return DataBuffer(text).unescape()
diff --git a/python/dataclasses.py b/python/dataclasses.py
index ddd59c66..9bfab21c 100644
--- a/python/dataclasses.py
+++ b/python/dataclasses.py
@@ -5,21 +5,12 @@ import types
import inspect
import keyword
-__all__ = ['dataclass',
- 'field',
- 'Field',
- 'FrozenInstanceError',
- 'InitVar',
- 'MISSING',
+__all__ = [
+ 'dataclass', 'field', 'Field', 'FrozenInstanceError', 'InitVar', 'MISSING',
- # Helper functions.
- 'fields',
- 'asdict',
- 'astuple',
- 'make_dataclass',
- 'replace',
- 'is_dataclass',
- ]
+ # Helper functions.
+ 'fields', 'asdict', 'astuple', 'make_dataclass', 'replace', 'is_dataclass',
+]
# Conditions for adding methods. The boxes indicate what action the
# dataclass decorator takes. For all of these tables, when I talk
@@ -66,7 +57,6 @@ __all__ = ['dataclass',
# | True | add | | <- the default
# +=======+=======+=======+
-
# __setattr__
# __delattr__
#
@@ -148,32 +138,43 @@ __all__ = ['dataclass',
# Raised when an attempt is made to modify a frozen class.
-class FrozenInstanceError(AttributeError): pass
+class FrozenInstanceError(AttributeError):
+ pass
+
# A sentinel object for default values to signal that a default
# factory will be used. This is given a nice repr() which will appear
# in the function signature of dataclasses' constructors.
class _HAS_DEFAULT_FACTORY_CLASS:
- def __repr__(self):
- return '<factory>'
+ def __repr__(self):
+ return '<factory>'
+
+
_HAS_DEFAULT_FACTORY = _HAS_DEFAULT_FACTORY_CLASS()
+
# A sentinel object to detect if a parameter is supplied or not. Use
# a class to give it a better repr.
class _MISSING_TYPE:
- pass
+ pass
+
+
MISSING = _MISSING_TYPE()
# Since most per-field metadata will be unused, create an empty
# read-only proxy that can be shared among all fields.
_EMPTY_METADATA = types.MappingProxyType({})
+
# Markers for the various kinds of fields and pseudo-fields.
class _FIELD_BASE:
- def __init__(self, name):
- self.name = name
- def __repr__(self):
- return self.name
+ def __init__(self, name):
+ self.name = name
+
+ def __repr__(self):
+ return self.name
+
+
_FIELD = _FIELD_BASE('_FIELD')
_FIELD_CLASSVAR = _FIELD_BASE('_FIELD_CLASSVAR')
_FIELD_INITVAR = _FIELD_BASE('_FIELD_INITVAR')
@@ -195,12 +196,14 @@ _POST_INIT_NAME = '__post_init__'
# https://bugs.python.org/issue33453 for details.
_MODULE_IDENTIFIER_RE = re.compile(r'^(?:\s*(\w+)\s*\.)?\s*(\w+)')
+
class _InitVarMeta(type):
- def __getitem__(self, params):
- return self
+ def __getitem__(self, params):
+ return self
+
class InitVar(metaclass=_InitVarMeta):
- pass
+ pass
# Instances of Field are only ever created from within this module,
@@ -214,97 +217,86 @@ class InitVar(metaclass=_InitVarMeta):
# When cls._FIELDS is filled in with a list of Field objects, the name
# and type fields will have been populated.
class Field:
- __slots__ = ('name',
- 'type',
- 'default',
- 'default_factory',
- 'repr',
- 'hash',
- 'init',
- 'compare',
- 'metadata',
- '_field_type', # Private: not to be used by user code.
- )
+ __slots__ = (
+ 'name', 'type', 'default', 'default_factory', 'repr', 'hash', 'init', 'compare', 'metadata',
+ '_field_type', # Private: not to be used by user code.
+ )
- def __init__(self, default, default_factory, init, repr, hash, compare,
- metadata):
- self.name = None
- self.type = None
- self.default = default
- self.default_factory = default_factory
- self.init = init
- self.repr = repr
- self.hash = hash
- self.compare = compare
- self.metadata = (_EMPTY_METADATA
- if metadata is None or len(metadata) == 0 else
- types.MappingProxyType(metadata))
- self._field_type = None
+ def __init__(self, default, default_factory, init, repr, hash, compare, metadata):
+ self.name = None
+ self.type = None
+ self.default = default
+ self.default_factory = default_factory
+ self.init = init
+ self.repr = repr
+ self.hash = hash
+ self.compare = compare
+ self.metadata = (
+ _EMPTY_METADATA if metadata is None or len(metadata) == 0 else types.MappingProxyType(metadata)
+ )
+ self._field_type = None
- def __repr__(self):
- return ('Field('
- f'name={self.name!r},'
- f'type={self.type!r},'
- f'default={self.default!r},'
- f'default_factory={self.default_factory!r},'
- f'init={self.init!r},'
- f'repr={self.repr!r},'
- f'hash={self.hash!r},'
- f'compare={self.compare!r},'
- f'metadata={self.metadata!r},'
- f'_field_type={self._field_type}'
- ')')
+ def __repr__(self):
+ return (
+ 'Field('
+ f'name={self.name!r},'
+ f'type={self.type!r},'
+ f'default={self.default!r},'
+ f'default_factory={self.default_factory!r},'
+ f'init={self.init!r},'
+ f'repr={self.repr!r},'
+ f'hash={self.hash!r},'
+ f'compare={self.compare!r},'
+ f'metadata={self.metadata!r},'
+ f'_field_type={self._field_type}'
+ ')'
+ )
- # This is used to support the PEP 487 __set_name__ protocol in the
- # case where we're using a field that contains a descriptor as a
- # defaul value. For details on __set_name__, see
- # https://www.python.org/dev/peps/pep-0487/#implementation-details.
- #
- # Note that in _process_class, this Field object is overwritten
- # with the default value, so the end result is a descriptor that
- # had __set_name__ called on it at the right time.
- def __set_name__(self, owner, name):
- func = getattr(type(self.default), '__set_name__', None)
- if func:
- # There is a __set_name__ method on the descriptor, call
- # it.
- func(self.default, owner, name)
+ # This is used to support the PEP 487 __set_name__ protocol in the
+ # case where we're using a field that contains a descriptor as a
+ # defaul value. For details on __set_name__, see
+ # https://www.python.org/dev/peps/pep-0487/#implementation-details.
+ #
+ # Note that in _process_class, this Field object is overwritten
+ # with the default value, so the end result is a descriptor that
+ # had __set_name__ called on it at the right time.
+ def __set_name__(self, owner, name):
+ func = getattr(type(self.default), '__set_name__', None)
+ if func:
+ # There is a __set_name__ method on the descriptor, call
+ # it.
+ func(self.default, owner, name)
class _DataclassParams:
- __slots__ = ('init',
- 'repr',
- 'eq',
- 'order',
- 'unsafe_hash',
- 'frozen',
- )
+ __slots__ = ('init', 'repr', 'eq', 'order', 'unsafe_hash', 'frozen', )
- def __init__(self, init, repr, eq, order, unsafe_hash, frozen):
- self.init = init
- self.repr = repr
- self.eq = eq
- self.order = order
- self.unsafe_hash = unsafe_hash
- self.frozen = frozen
+ def __init__(self, init, repr, eq, order, unsafe_hash, frozen):
+ self.init = init
+ self.repr = repr
+ self.eq = eq
+ self.order = order
+ self.unsafe_hash = unsafe_hash
+ self.frozen = frozen
- def __repr__(self):
- return ('_DataclassParams('
- f'init={self.init!r},'
- f'repr={self.repr!r},'
- f'eq={self.eq!r},'
- f'order={self.order!r},'
- f'unsafe_hash={self.unsafe_hash!r},'
- f'frozen={self.frozen!r}'
- ')')
+ def __repr__(self):
+ return (
+ '_DataclassParams('
+ f'init={self.init!r},'
+ f'repr={self.repr!r},'
+ f'eq={self.eq!r},'
+ f'order={self.order!r},'
+ f'unsafe_hash={self.unsafe_hash!r},'
+ f'frozen={self.frozen!r}'
+ ')'
+ )
# This function is used instead of exposing Field creation directly,
# so that a type checker can be told (via overloads) that this is a
# function whose type depends on its parameters.
-def field(*, default=MISSING, default_factory=MISSING, init=True, repr=True,
- hash=None, compare=True, metadata=None):
- """Return an object to identify dataclass fields.
+def field(*, default=MISSING, default_factory=MISSING, init=True, repr=True, hash=None, compare=True, metadata=None):
+ """Return an object to identify dataclass fields.
default is the default value of the field. default_factory is a
0-argument function called to initialize a field's value. If init
@@ -318,392 +310,386 @@ def field(*, default=MISSING, default_factory=MISSING, init=True, repr=True,
It is an error to specify both default and default_factory.
"""
- if default is not MISSING and default_factory is not MISSING:
- raise ValueError('cannot specify both default and default_factory')
- return Field(default, default_factory, init, repr, hash, compare,
- metadata)
+ if default is not MISSING and default_factory is not MISSING:
+ raise ValueError('cannot specify both default and default_factory')
+ return Field(default, default_factory, init, repr, hash, compare, metadata)
def _tuple_str(obj_name, fields):
- # Return a string representing each field of obj_name as a tuple
- # member. So, if fields is ['x', 'y'] and obj_name is "self",
- # return "(self.x,self.y)".
+ # Return a string representing each field of obj_name as a tuple
+ # member. So, if fields is ['x', 'y'] and obj_name is "self",
+ # return "(self.x,self.y)".
- # Special case for the 0-tuple.
- if not fields:
- return '()'
- # Note the trailing comma, needed if this turns out to be a 1-tuple.
- return f'({",".join([f"{obj_name}.{f.name}" for f in fields])},)'
+ # Special case for the 0-tuple.
+ if not fields:
+ return '()'
+ # Note the trailing comma, needed if this turns out to be a 1-tuple.
+ return f'({",".join([f"{obj_name}.{f.name}" for f in fields])},)'
-def _create_fn(name, args, body, *, globals=None, locals=None,
- return_type=MISSING):
- # Note that we mutate locals when exec() is called. Caller
- # beware! The only callers are internal to this module, so no
- # worries about external callers.
- if locals is None:
- locals = {}
- return_annotation = ''
- if return_type is not MISSING:
- locals['_return_type'] = return_type
- return_annotation = '->_return_type'
- args = ','.join(args)
- body = '\n'.join(f' {b}' for b in body)
+def _create_fn(name, args, body, *, globals=None, locals=None, return_type=MISSING):
+ # Note that we mutate locals when exec() is called. Caller
+ # beware! The only callers are internal to this module, so no
+ # worries about external callers.
+ if locals is None:
+ locals = {}
+ return_annotation = ''
+ if return_type is not MISSING:
+ locals['_return_type'] = return_type
+ return_annotation = '->_return_type'
+ args = ','.join(args)
+ body = '\n'.join(f' {b}' for b in body)
- # Compute the text of the entire function.
- txt = f'def {name}({args}){return_annotation}:\n{body}'
+ # Compute the text of the entire function.
+ txt = f'def {name}({args}){return_annotation}:\n{body}'
- exec(txt, globals, locals)
- return locals[name]
+ exec(txt, globals, locals)
+ return locals[name]
def _field_assign(frozen, name, value, self_name):
- # If we're a frozen class, then assign to our fields in __init__
- # via object.__setattr__. Otherwise, just use a simple
- # assignment.
- #
- # self_name is what "self" is called in this function: don't
- # hard-code "self", since that might be a field name.
- if frozen:
- return f'object.__setattr__({self_name},{name!r},{value})'
- return f'{self_name}.{name}={value}'
+ # If we're a frozen class, then assign to our fields in __init__
+ # via object.__setattr__. Otherwise, just use a simple
+ # assignment.
+ #
+ # self_name is what "self" is called in this function: don't
+ # hard-code "self", since that might be a field name.
+ if frozen:
+ return f'object.__setattr__({self_name},{name!r},{value})'
+ return f'{self_name}.{name}={value}'
def _field_init(f, frozen, globals, self_name):
- # Return the text of the line in the body of __init__ that will
- # initialize this field.
+ # Return the text of the line in the body of __init__ that will
+ # initialize this field.
- default_name = f'_dflt_{f.name}'
- if f.default_factory is not MISSING:
- if f.init:
- # This field has a default factory. If a parameter is
- # given, use it. If not, call the factory.
- globals[default_name] = f.default_factory
- value = (f'{default_name}() '
- f'if {f.name} is _HAS_DEFAULT_FACTORY '
- f'else {f.name}')
- else:
- # This is a field that's not in the __init__ params, but
- # has a default factory function. It needs to be
- # initialized here by calling the factory function,
- # because there's no other way to initialize it.
+ default_name = f'_dflt_{f.name}'
+ if f.default_factory is not MISSING:
+ if f.init:
+ # This field has a default factory. If a parameter is
+ # given, use it. If not, call the factory.
+ globals[default_name] = f.default_factory
+ value = (f'{default_name}() '
+ f'if {f.name} is _HAS_DEFAULT_FACTORY '
+ f'else {f.name}')
+ else:
+ # This is a field that's not in the __init__ params, but
+ # has a default factory function. It needs to be
+ # initialized here by calling the factory function,
+ # because there's no other way to initialize it.
- # For a field initialized with a default=defaultvalue, the
- # class dict just has the default value
- # (cls.fieldname=defaultvalue). But that won't work for a
- # default factory, the factory must be called in __init__
- # and we must assign that to self.fieldname. We can't
- # fall back to the class dict's value, both because it's
- # not set, and because it might be different per-class
- # (which, after all, is why we have a factory function!).
+ # For a field initialized with a default=defaultvalue, the
+ # class dict just has the default value
+ # (cls.fieldname=defaultvalue). But that won't work for a
+ # default factory, the factory must be called in __init__
+ # and we must assign that to self.fieldname. We can't
+ # fall back to the class dict's value, both because it's
+ # not set, and because it might be different per-class
+ # (which, after all, is why we have a factory function!).
- globals[default_name] = f.default_factory
- value = f'{default_name}()'
- else:
- # No default factory.
- if f.init:
- if f.default is MISSING:
- # There's no default, just do an assignment.
- value = f.name
- elif f.default is not MISSING:
- globals[default_name] = f.default
- value = f.name
- else:
- # This field does not need initialization. Signify that
- # to the caller by returning None.
- return None
+ globals[default_name] = f.default_factory
+ value = f'{default_name}()'
+ else:
+ # No default factory.
+ if f.init:
+ if f.default is MISSING:
+ # There's no default, just do an assignment.
+ value = f.name
+ elif f.default is not MISSING:
+ globals[default_name] = f.default
+ value = f.name
+ else:
+ # This field does not need initialization. Signify that
+ # to the caller by returning None.
+ return None
- # Only test this now, so that we can create variables for the
- # default. However, return None to signify that we're not going
- # to actually do the assignment statement for InitVars.
- if f._field_type is _FIELD_INITVAR:
- return None
+ # Only test this now, so that we can create variables for the
+ # default. However, return None to signify that we're not going
+ # to actually do the assignment statement for InitVars.
+ if f._field_type is _FIELD_INITVAR:
+ return None
- # Now, actually generate the field assignment.
- return _field_assign(frozen, f.name, value, self_name)
+ # Now, actually generate the field assignment.
+ return _field_assign(frozen, f.name, value, self_name)
def _init_param(f):
- # Return the __init__ parameter string for this field. For
- # example, the equivalent of 'x:int=3' (except instead of 'int',
- # reference a variable set to int, and instead of '3', reference a
- # variable set to 3).
- if f.default is MISSING and f.default_factory is MISSING:
- # There's no default, and no default_factory, just output the
- # variable name and type.
- default = ''
- elif f.default is not MISSING:
- # There's a default, this will be the name that's used to look
- # it up.
- default = f'=_dflt_{f.name}'
- elif f.default_factory is not MISSING:
- # There's a factory function. Set a marker.
- default = '=_HAS_DEFAULT_FACTORY'
- return f'{f.name}:_type_{f.name}{default}'
+ # Return the __init__ parameter string for this field. For
+ # example, the equivalent of 'x:int=3' (except instead of 'int',
+ # reference a variable set to int, and instead of '3', reference a
+ # variable set to 3).
+ if f.default is MISSING and f.default_factory is MISSING:
+ # There's no default, and no default_factory, just output the
+ # variable name and type.
+ default = ''
+ elif f.default is not MISSING:
+ # There's a default, this will be the name that's used to look
+ # it up.
+ default = f'=_dflt_{f.name}'
+ elif f.default_factory is not MISSING:
+ # There's a factory function. Set a marker.
+ default = '=_HAS_DEFAULT_FACTORY'
+ return f'{f.name}:_type_{f.name}{default}'
def _init_fn(fields, frozen, has_post_init, self_name):
- # fields contains both real fields and InitVar pseudo-fields.
+ # fields contains both real fields and InitVar pseudo-fields.
- # Make sure we don't have fields without defaults following fields
- # with defaults. This actually would be caught when exec-ing the
- # function source code, but catching it here gives a better error
- # message, and future-proofs us in case we build up the function
- # using ast.
- seen_default = False
- for f in fields:
- # Only consider fields in the __init__ call.
- if f.init:
- if not (f.default is MISSING and f.default_factory is MISSING):
- seen_default = True
- elif seen_default:
- raise TypeError(f'non-default argument {f.name!r} '
- 'follows default argument')
+ # Make sure we don't have fields without defaults following fields
+ # with defaults. This actually would be caught when exec-ing the
+ # function source code, but catching it here gives a better error
+ # message, and future-proofs us in case we build up the function
+ # using ast.
+ seen_default = False
+ for f in fields:
+ # Only consider fields in the __init__ call.
+ if f.init:
+ if not (f.default is MISSING and f.default_factory is MISSING):
+ seen_default = True
+ elif seen_default:
+ raise TypeError(f'non-default argument {f.name!r} '
+ 'follows default argument')
- globals = {'MISSING': MISSING,
- '_HAS_DEFAULT_FACTORY': _HAS_DEFAULT_FACTORY}
+ globals = {'MISSING': MISSING, '_HAS_DEFAULT_FACTORY': _HAS_DEFAULT_FACTORY}
- body_lines = []
- for f in fields:
- line = _field_init(f, frozen, globals, self_name)
- # line is None means that this field doesn't require
- # initialization (it's a pseudo-field). Just skip it.
- if line:
- body_lines.append(line)
+ body_lines = []
+ for f in fields:
+ line = _field_init(f, frozen, globals, self_name)
+ # line is None means that this field doesn't require
+ # initialization (it's a pseudo-field). Just skip it.
+ if line:
+ body_lines.append(line)
- # Does this class have a post-init function?
- if has_post_init:
- params_str = ','.join(f.name for f in fields
- if f._field_type is _FIELD_INITVAR)
- body_lines.append(f'{self_name}.{_POST_INIT_NAME}({params_str})')
+ # Does this class have a post-init function?
+ if has_post_init:
+ params_str = ','.join(f.name for f in fields if f._field_type is _FIELD_INITVAR)
+ body_lines.append(f'{self_name}.{_POST_INIT_NAME}({params_str})')
- # If no body lines, use 'pass'.
- if not body_lines:
- body_lines = ['pass']
+ # If no body lines, use 'pass'.
+ if not body_lines:
+ body_lines = ['pass']
- locals = {f'_type_{f.name}': f.type for f in fields}
- return _create_fn('__init__',
- [self_name] + [_init_param(f) for f in fields if f.init],
- body_lines,
- locals=locals,
- globals=globals,
- return_type=None)
+ locals = {f'_type_{f.name}': f.type for f in fields}
+ return _create_fn(
+ '__init__', [self_name] + [_init_param(f) for f in fields if f.init], body_lines, locals=locals,
+ globals=globals, return_type=None
+ )
def _repr_fn(fields):
- return _create_fn('__repr__',
- ('self',),
- ['return self.__class__.__qualname__ + f"(' +
- ', '.join([f"{f.name}={{self.{f.name}!r}}"
- for f in fields]) +
- ')"'])
+ return _create_fn(
+ '__repr__', ('self', ), [
+ 'return self.__class__.__qualname__ + f"(' + ', '.join([f"{f.name}={{self.{f.name}!r}}"
+ for f in fields]) + ')"'
+ ]
+ )
def _frozen_get_del_attr(cls, fields):
- # XXX: globals is modified on the first call to _create_fn, then
- # the modified version is used in the second call. Is this okay?
- globals = {'cls': cls,
- 'FrozenInstanceError': FrozenInstanceError}
- if fields:
- fields_str = '(' + ','.join(repr(f.name) for f in fields) + ',)'
- else:
- # Special case for the zero-length tuple.
- fields_str = '()'
- return (_create_fn('__setattr__',
- ('self', 'name', 'value'),
- (f'if type(self) is cls or name in {fields_str}:',
- ' raise FrozenInstanceError(f"cannot assign to field {name!r}")',
- f'super(cls, self).__setattr__(name, value)'),
- globals=globals),
- _create_fn('__delattr__',
- ('self', 'name'),
- (f'if type(self) is cls or name in {fields_str}:',
- ' raise FrozenInstanceError(f"cannot delete field {name!r}")',
- f'super(cls, self).__delattr__(name)'),
- globals=globals),
- )
+ # XXX: globals is modified on the first call to _create_fn, then
+ # the modified version is used in the second call. Is this okay?
+ globals = {'cls': cls, 'FrozenInstanceError': FrozenInstanceError}
+ if fields:
+ fields_str = '(' + ','.join(repr(f.name) for f in fields) + ',)'
+ else:
+ # Special case for the zero-length tuple.
+ fields_str = '()'
+ return (
+ _create_fn(
+ '__setattr__', ('self', 'name', 'value'), (
+ f'if type(self) is cls or name in {fields_str}:',
+ ' raise FrozenInstanceError(f"cannot assign to field {name!r}")',
+ f'super(cls, self).__setattr__(name, value)'
+ ), globals=globals
+ ),
+ _create_fn(
+ '__delattr__', ('self', 'name'), (
+ f'if type(self) is cls or name in {fields_str}:',
+ ' raise FrozenInstanceError(f"cannot delete field {name!r}")', f'super(cls, self).__delattr__(name)'
+ ), globals=globals
+ ),
+ )
def _cmp_fn(name, op, self_tuple, other_tuple):
- # Create a comparison function. If the fields in the object are
- # named 'x' and 'y', then self_tuple is the string
- # '(self.x,self.y)' and other_tuple is the string
- # '(other.x,other.y)'.
+ # Create a comparison function. If the fields in the object are
+ # named 'x' and 'y', then self_tuple is the string
+ # '(self.x,self.y)' and other_tuple is the string
+ # '(other.x,other.y)'.
- return _create_fn(name,
- ('self', 'other'),
- [ 'if other.__class__ is self.__class__:',
- f' return {self_tuple}{op}{other_tuple}',
- 'return NotImplemented'])
+ return _create_fn(
+ name, ('self', 'other'),
+ ['if other.__class__ is self.__class__:', f' return {self_tuple}{op}{other_tuple}', 'return NotImplemented']
+ )
def _hash_fn(fields):
- self_tuple = _tuple_str('self', fields)
- return _create_fn('__hash__',
- ('self',),
- [f'return hash({self_tuple})'])
+ self_tuple = _tuple_str('self', fields)
+ return _create_fn('__hash__', ('self', ), [f'return hash({self_tuple})'])
def _is_classvar(a_type, typing):
- # This test uses a typing internal class, but it's the best way to
- # test if this is a ClassVar.
- return type(a_type) is typing._ClassVar
+ # This test uses a typing internal class, but it's the best way to
+ # test if this is a ClassVar.
+ return type(a_type) is typing._ClassVar
def _is_initvar(a_type, dataclasses):
- # The module we're checking against is the module we're
- # currently in (dataclasses.py).
- return a_type is dataclasses.InitVar
+ # The module we're checking against is the module we're
+ # currently in (dataclasses.py).
+ return a_type is dataclasses.InitVar
def _is_type(annotation, cls, a_module, a_type, is_type_predicate):
- # Given a type annotation string, does it refer to a_type in
- # a_module? For example, when checking that annotation denotes a
- # ClassVar, then a_module is typing, and a_type is
- # typing.ClassVar.
+ # Given a type annotation string, does it refer to a_type in
+ # a_module? For example, when checking that annotation denotes a
+ # ClassVar, then a_module is typing, and a_type is
+ # typing.ClassVar.
- # It's possible to look up a_module given a_type, but it involves
- # looking in sys.modules (again!), and seems like a waste since
- # the caller already knows a_module.
+ # It's possible to look up a_module given a_type, but it involves
+ # looking in sys.modules (again!), and seems like a waste since
+ # the caller already knows a_module.
- # - annotation is a string type annotation
- # - cls is the class that this annotation was found in
- # - a_module is the module we want to match
- # - a_type is the type in that module we want to match
- # - is_type_predicate is a function called with (obj, a_module)
- # that determines if obj is of the desired type.
+ # - annotation is a string type annotation
+ # - cls is the class that this annotation was found in
+ # - a_module is the module we want to match
+ # - a_type is the type in that module we want to match
+ # - is_type_predicate is a function called with (obj, a_module)
+ # that determines if obj is of the desired type.
- # Since this test does not do a local namespace lookup (and
- # instead only a module (global) lookup), there are some things it
- # gets wrong.
+ # Since this test does not do a local namespace lookup (and
+ # instead only a module (global) lookup), there are some things it
+ # gets wrong.
- # With string annotations, cv0 will be detected as a ClassVar:
- # CV = ClassVar
- # @dataclass
- # class C0:
- # cv0: CV
+ # With string annotations, cv0 will be detected as a ClassVar:
+ # CV = ClassVar
+ # @dataclass
+ # class C0:
+ # cv0: CV
- # But in this example cv1 will not be detected as a ClassVar:
- # @dataclass
- # class C1:
- # CV = ClassVar
- # cv1: CV
+ # But in this example cv1 will not be detected as a ClassVar:
+ # @dataclass
+ # class C1:
+ # CV = ClassVar
+ # cv1: CV
- # In C1, the code in this function (_is_type) will look up "CV" in
- # the module and not find it, so it will not consider cv1 as a
- # ClassVar. This is a fairly obscure corner case, and the best
- # way to fix it would be to eval() the string "CV" with the
- # correct global and local namespaces. However that would involve
- # a eval() penalty for every single field of every dataclass
- # that's defined. It was judged not worth it.
+ # In C1, the code in this function (_is_type) will look up "CV" in
+ # the module and not find it, so it will not consider cv1 as a
+ # ClassVar. This is a fairly obscure corner case, and the best
+ # way to fix it would be to eval() the string "CV" with the
+ # correct global and local namespaces. However that would involve
+ # a eval() penalty for every single field of every dataclass
+ # that's defined. It was judged not worth it.
- match = _MODULE_IDENTIFIER_RE.match(annotation)
- if match:
- ns = None
- module_name = match.group(1)
- if not module_name:
- # No module name, assume the class's module did
- # "from dataclasses import InitVar".
- ns = sys.modules.get(cls.__module__).__dict__
- else:
- # Look up module_name in the class's module.
- module = sys.modules.get(cls.__module__)
- if module and module.__dict__.get(module_name) is a_module:
- ns = sys.modules.get(a_type.__module__).__dict__
- if ns and is_type_predicate(ns.get(match.group(2)), a_module):
- return True
- return False
+ match = _MODULE_IDENTIFIER_RE.match(annotation)
+ if match:
+ ns = None
+ module_name = match.group(1)
+ if not module_name:
+ # No module name, assume the class's module did
+ # "from dataclasses import InitVar".
+ ns = sys.modules.get(cls.__module__).__dict__
+ else:
+ # Look up module_name in the class's module.
+ module = sys.modules.get(cls.__module__)
+ if module and module.__dict__.get(module_name) is a_module:
+ ns = sys.modules.get(a_type.__module__).__dict__
+ if ns and is_type_predicate(ns.get(match.group(2)), a_module):
+ return True
+ return False
def _get_field(cls, a_name, a_type):
- # Return a Field object for this field name and type. ClassVars
- # and InitVars are also returned, but marked as such (see
- # f._field_type).
+ # Return a Field object for this field name and type. ClassVars
+ # and InitVars are also returned, but marked as such (see
+ # f._field_type).
- # If the default value isn't derived from Field, then it's only a
- # normal default value. Convert it to a Field().
- default = getattr(cls, a_name, MISSING)
- if isinstance(default, Field):
- f = default
- else:
- if isinstance(default, types.MemberDescriptorType):
- # This is a field in __slots__, so it has no default value.
- default = MISSING
- f = field(default=default)
+ # If the default value isn't derived from Field, then it's only a
+ # normal default value. Convert it to a Field().
+ default = getattr(cls, a_name, MISSING)
+ if isinstance(default, Field):
+ f = default
+ else:
+ if isinstance(default, types.MemberDescriptorType):
+ # This is a field in __slots__, so it has no default value.
+ default = MISSING
+ f = field(default=default)
- # Only at this point do we know the name and the type. Set them.
- f.name = a_name
- f.type = a_type
+ # Only at this point do we know the name and the type. Set them.
+ f.name = a_name
+ f.type = a_type
- # Assume it's a normal field until proven otherwise. We're next
- # going to decide if it's a ClassVar or InitVar, everything else
- # is just a normal field.
- f._field_type = _FIELD
+ # Assume it's a normal field until proven otherwise. We're next
+ # going to decide if it's a ClassVar or InitVar, everything else
+ # is just a normal field.
+ f._field_type = _FIELD
- # In addition to checking for actual types here, also check for
- # string annotations. get_type_hints() won't always work for us
- # (see https://github.com/python/typing/issues/508 for example),
- # plus it's expensive and would require an eval for every stirng
- # annotation. So, make a best effort to see if this is a ClassVar
- # or InitVar using regex's and checking that the thing referenced
- # is actually of the correct type.
+ # In addition to checking for actual types here, also check for
+ # string annotations. get_type_hints() won't always work for us
+ # (see https://github.com/python/typing/issues/508 for example),
+ # plus it's expensive and would require an eval for every stirng
+ # annotation. So, make a best effort to see if this is a ClassVar
+ # or InitVar using regex's and checking that the thing referenced
+ # is actually of the correct type.
- # For the complete discussion, see https://bugs.python.org/issue33453
+ # For the complete discussion, see https://bugs.python.org/issue33453
- # If typing has not been imported, then it's impossible for any
- # annotation to be a ClassVar. So, only look for ClassVar if
- # typing has been imported by any module (not necessarily cls's
- # module).
- typing = sys.modules.get('typing')
- if typing:
- if (_is_classvar(a_type, typing)
- or (isinstance(f.type, str)
- and _is_type(f.type, cls, typing, typing.ClassVar,
- _is_classvar))):
- f._field_type = _FIELD_CLASSVAR
+ # If typing has not been imported, then it's impossible for any
+ # annotation to be a ClassVar. So, only look for ClassVar if
+ # typing has been imported by any module (not necessarily cls's
+ # module).
+ typing = sys.modules.get('typing')
+ if typing:
+ if (
+ _is_classvar(a_type, typing)
+ or (isinstance(f.type, str) and _is_type(f.type, cls, typing, typing.ClassVar, _is_classvar))
+ ):
+ f._field_type = _FIELD_CLASSVAR
- # If the type is InitVar, or if it's a matching string annotation,
- # then it's an InitVar.
- if f._field_type is _FIELD:
- # The module we're checking against is the module we're
- # currently in (dataclasses.py).
- dataclasses = sys.modules[__name__]
- if (_is_initvar(a_type, dataclasses)
- or (isinstance(f.type, str)
- and _is_type(f.type, cls, dataclasses, dataclasses.InitVar,
- _is_initvar))):
- f._field_type = _FIELD_INITVAR
+ # If the type is InitVar, or if it's a matching string annotation,
+ # then it's an InitVar.
+ if f._field_type is _FIELD:
+ # The module we're checking against is the module we're
+ # currently in (dataclasses.py).
+ dataclasses = sys.modules[__name__]
+ if (
+ _is_initvar(a_type, dataclasses)
+ or (isinstance(f.type, str) and _is_type(f.type, cls, dataclasses, dataclasses.InitVar, _is_initvar))
+ ):
+ f._field_type = _FIELD_INITVAR
- # Validations for individual fields. This is delayed until now,
- # instead of in the Field() constructor, since only here do we
- # know the field name, which allows for better error reporting.
+ # Validations for individual fields. This is delayed until now,
+ # instead of in the Field() constructor, since only here do we
+ # know the field name, which allows for better error reporting.
- # Special restrictions for ClassVar and InitVar.
- if f._field_type in (_FIELD_CLASSVAR, _FIELD_INITVAR):
- if f.default_factory is not MISSING:
- raise TypeError(f'field {f.name} cannot have a '
- 'default factory')
- # Should I check for other field settings? default_factory
- # seems the most serious to check for. Maybe add others. For
- # example, how about init=False (or really,
- # init=<not-the-default-init-value>)? It makes no sense for
- # ClassVar and InitVar to specify init=<anything>.
+ # Special restrictions for ClassVar and InitVar.
+ if f._field_type in (_FIELD_CLASSVAR, _FIELD_INITVAR):
+ if f.default_factory is not MISSING:
+ raise TypeError(f'field {f.name} cannot have a '
+ 'default factory')
+ # Should I check for other field settings? default_factory
+ # seems the most serious to check for. Maybe add others. For
+ # example, how about init=False (or really,
+ # init=<not-the-default-init-value>)? It makes no sense for
+ # ClassVar and InitVar to specify init=<anything>.
- # For real fields, disallow mutable defaults for known types.
- if f._field_type is _FIELD and isinstance(f.default, (list, dict, set)):
- raise ValueError(f'mutable default {type(f.default)} for field '
- f'{f.name} is not allowed: use default_factory')
+ # For real fields, disallow mutable defaults for known types.
+ if f._field_type is _FIELD and isinstance(f.default, (list, dict, set)):
+ raise ValueError(
+ f'mutable default {type(f.default)} for field '
+ f'{f.name} is not allowed: use default_factory'
+ )
- return f
+ return f
def _set_new_attribute(cls, name, value):
- # Never overwrites an existing attribute. Returns True if the
- # attribute already exists.
- if name in cls.__dict__:
- return True
- setattr(cls, name, value)
- return False
+ # Never overwrites an existing attribute. Returns True if the
+ # attribute already exists.
+ if name in cls.__dict__:
+ return True
+ setattr(cls, name, value)
+ return False
# Decide if/how we're going to create a hash function. Key is
@@ -711,17 +697,21 @@ def _set_new_attribute(cls, name, value):
# take. The common case is to do nothing, so instead of providing a
# function that is a no-op, use None to signify that.
+
def _hash_set_none(cls, fields):
- return None
+ return None
+
def _hash_add(cls, fields):
- flds = [f for f in fields if (f.compare if f.hash is None else f.hash)]
- return _hash_fn(flds)
+ flds = [f for f in fields if (f.compare if f.hash is None else f.hash)]
+ return _hash_fn(flds)
+
def _hash_exception(cls, fields):
- # Raise an exception.
- raise TypeError(f'Cannot overwrite attribute __hash__ '
- f'in class {cls.__name__}')
+ # Raise an exception.
+ raise TypeError(f'Cannot overwrite attribute __hash__ '
+ f'in class {cls.__name__}')
+
#
# +-------------------------------------- unsafe_hash?
@@ -733,208 +723,185 @@ def _hash_exception(cls, fields):
# | | | | |
# v v v v v
_hash_action = {(False, False, False, False): None,
- (False, False, False, True ): None,
- (False, False, True, False): None,
- (False, False, True, True ): None,
- (False, True, False, False): _hash_set_none,
- (False, True, False, True ): None,
- (False, True, True, False): _hash_add,
- (False, True, True, True ): None,
- (True, False, False, False): _hash_add,
- (True, False, False, True ): _hash_exception,
- (True, False, True, False): _hash_add,
- (True, False, True, True ): _hash_exception,
- (True, True, False, False): _hash_add,
- (True, True, False, True ): _hash_exception,
- (True, True, True, False): _hash_add,
- (True, True, True, True ): _hash_exception,
- }
+ (False, False, False, True): None, (False, False, True, False): None, (False, False, True, True): None,
+ (False, True, False, False): _hash_set_none, (False, True, False, True): None,
+ (False, True, True, False): _hash_add, (False, True, True, True): None,
+ (True, False, False, False): _hash_add, (True, False, False, True): _hash_exception,
+ (True, False, True, False): _hash_add, (True, False, True, True): _hash_exception,
+ (True, True, False, False): _hash_add, (True, True, False, True): _hash_exception,
+ (True, True, True, False): _hash_add, (True, True, True, True): _hash_exception, }
# See https://bugs.python.org/issue32929#msg312829 for an if-statement
# version of this table.
def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen):
- # Now that dicts retain insertion order, there's no reason to use
- # an ordered dict. I am leveraging that ordering here, because
- # derived class fields overwrite base class fields, but the order
- # is defined by the base class, which is found first.
- fields = {}
+ # Now that dicts retain insertion order, there's no reason to use
+ # an ordered dict. I am leveraging that ordering here, because
+ # derived class fields overwrite base class fields, but the order
+ # is defined by the base class, which is found first.
+ fields = {}
- setattr(cls, _PARAMS, _DataclassParams(init, repr, eq, order,
- unsafe_hash, frozen))
+ setattr(cls, _PARAMS, _DataclassParams(init, repr, eq, order, unsafe_hash, frozen))
- # Find our base classes in reverse MRO order, and exclude
- # ourselves. In reversed order so that more derived classes
- # override earlier field definitions in base classes. As long as
- # we're iterating over them, see if any are frozen.
- any_frozen_base = False
- has_dataclass_bases = False
- for b in cls.__mro__[-1:0:-1]:
- # Only process classes that have been processed by our
- # decorator. That is, they have a _FIELDS attribute.
- base_fields = getattr(b, _FIELDS, None)
- if base_fields:
- has_dataclass_bases = True
- for f in base_fields.values():
- fields[f.name] = f
- if getattr(b, _PARAMS).frozen:
- any_frozen_base = True
+ # Find our base classes in reverse MRO order, and exclude
+ # ourselves. In reversed order so that more derived classes
+ # override earlier field definitions in base classes. As long as
+ # we're iterating over them, see if any are frozen.
+ any_frozen_base = False
+ has_dataclass_bases = False
+ for b in cls.__mro__[-1:0:-1]:
+ # Only process classes that have been processed by our
+ # decorator. That is, they have a _FIELDS attribute.
+ base_fields = getattr(b, _FIELDS, None)
+ if base_fields:
+ has_dataclass_bases = True
+ for f in base_fields.values():
+ fields[f.name] = f
+ if getattr(b, _PARAMS).frozen:
+ any_frozen_base = True
- # Annotations that are defined in this class (not in base
- # classes). If __annotations__ isn't present, then this class
- # adds no new annotations. We use this to compute fields that are
- # added by this class.
- #
- # Fields are found from cls_annotations, which is guaranteed to be
- # ordered. Default values are from class attributes, if a field
- # has a default. If the default value is a Field(), then it
- # contains additional info beyond (and possibly including) the
- # actual default value. Pseudo-fields ClassVars and InitVars are
- # included, despite the fact that they're not real fields. That's
- # dealt with later.
- cls_annotations = cls.__dict__.get('__annotations__', {})
+ # Annotations that are defined in this class (not in base
+ # classes). If __annotations__ isn't present, then this class
+ # adds no new annotations. We use this to compute fields that are
+ # added by this class.
+ #
+ # Fields are found from cls_annotations, which is guaranteed to be
+ # ordered. Default values are from class attributes, if a field
+ # has a default. If the default value is a Field(), then it
+ # contains additional info beyond (and possibly including) the
+ # actual default value. Pseudo-fields ClassVars and InitVars are
+ # included, despite the fact that they're not real fields. That's
+ # dealt with later.
+ cls_annotations = cls.__dict__.get('__annotations__', {})
- # Now find fields in our class. While doing so, validate some
- # things, and set the default values (as class attributes) where
- # we can.
- cls_fields = [_get_field(cls, name, type)
- for name, type in cls_annotations.items()]
- for f in cls_fields:
- fields[f.name] = f
+ # Now find fields in our class. While doing so, validate some
+ # things, and set the default values (as class attributes) where
+ # we can.
+ cls_fields = [_get_field(cls, name, type) for name, type in cls_annotations.items()]
+ for f in cls_fields:
+ fields[f.name] = f
- # If the class attribute (which is the default value for this
- # field) exists and is of type 'Field', replace it with the
- # real default. This is so that normal class introspection
- # sees a real default value, not a Field.
- if isinstance(getattr(cls, f.name, None), Field):
- if f.default is MISSING:
- # If there's no default, delete the class attribute.
- # This happens if we specify field(repr=False), for
- # example (that is, we specified a field object, but
- # no default value). Also if we're using a default
- # factory. The class attribute should not be set at
- # all in the post-processed class.
- delattr(cls, f.name)
- else:
- setattr(cls, f.name, f.default)
+ # If the class attribute (which is the default value for this
+ # field) exists and is of type 'Field', replace it with the
+ # real default. This is so that normal class introspection
+ # sees a real default value, not a Field.
+ if isinstance(getattr(cls, f.name, None), Field):
+ if f.default is MISSING:
+ # If there's no default, delete the class attribute.
+ # This happens if we specify field(repr=False), for
+ # example (that is, we specified a field object, but
+ # no default value). Also if we're using a default
+ # factory. The class attribute should not be set at
+ # all in the post-processed class.
+ delattr(cls, f.name)
+ else:
+ setattr(cls, f.name, f.default)
- # Do we have any Field members that don't also have annotations?
- for name, value in cls.__dict__.items():
- if isinstance(value, Field) and not name in cls_annotations:
- raise TypeError(f'{name!r} is a field but has no type annotation')
+ # Do we have any Field members that don't also have annotations?
+ for name, value in cls.__dict__.items():
+ if isinstance(value, Field) and not name in cls_annotations:
+ raise TypeError(f'{name!r} is a field but has no type annotation')
- # Check rules that apply if we are derived from any dataclasses.
- if has_dataclass_bases:
- # Raise an exception if any of our bases are frozen, but we're not.
- if any_frozen_base and not frozen:
- raise TypeError('cannot inherit non-frozen dataclass from a '
- 'frozen one')
+ # Check rules that apply if we are derived from any dataclasses.
+ if has_dataclass_bases:
+ # Raise an exception if any of our bases are frozen, but we're not.
+ if any_frozen_base and not frozen:
+ raise TypeError('cannot inherit non-frozen dataclass from a '
+ 'frozen one')
- # Raise an exception if we're frozen, but none of our bases are.
- if not any_frozen_base and frozen:
- raise TypeError('cannot inherit frozen dataclass from a '
- 'non-frozen one')
+ # Raise an exception if we're frozen, but none of our bases are.
+ if not any_frozen_base and frozen:
+ raise TypeError('cannot inherit frozen dataclass from a '
+ 'non-frozen one')
- # Remember all of the fields on our class (including bases). This
- # also marks this class as being a dataclass.
- setattr(cls, _FIELDS, fields)
+ # Remember all of the fields on our class (including bases). This
+ # also marks this class as being a dataclass.
+ setattr(cls, _FIELDS, fields)
- # Was this class defined with an explicit __hash__? Note that if
- # __eq__ is defined in this class, then python will automatically
- # set __hash__ to None. This is a heuristic, as it's possible
- # that such a __hash__ == None was not auto-generated, but it
- # close enough.
- class_hash = cls.__dict__.get('__hash__', MISSING)
- has_explicit_hash = not (class_hash is MISSING or
- (class_hash is None and '__eq__' in cls.__dict__))
+ # Was this class defined with an explicit __hash__? Note that if
+ # __eq__ is defined in this class, then python will automatically
+ # set __hash__ to None. This is a heuristic, as it's possible
+ # that such a __hash__ == None was not auto-generated, but it
+ # close enough.
+ class_hash = cls.__dict__.get('__hash__', MISSING)
+ has_explicit_hash = not (class_hash is MISSING or (class_hash is None and '__eq__' in cls.__dict__))
- # If we're generating ordering methods, we must be generating the
- # eq methods.
- if order and not eq:
- raise ValueError('eq must be true if order is true')
+ # If we're generating ordering methods, we must be generating the
+ # eq methods.
+ if order and not eq:
+ raise ValueError('eq must be true if order is true')
- if init:
- # Does this class have a post-init function?
- has_post_init = hasattr(cls, _POST_INIT_NAME)
+ if init:
+ # Does this class have a post-init function?
+ has_post_init = hasattr(cls, _POST_INIT_NAME)
- # Include InitVars and regular fields (so, not ClassVars).
- flds = [f for f in fields.values()
- if f._field_type in (_FIELD, _FIELD_INITVAR)]
- _set_new_attribute(cls, '__init__',
- _init_fn(flds,
- frozen,
- has_post_init,
- # The name to use for the "self"
- # param in __init__. Use "self"
- # if possible.
- '__dataclass_self__' if 'self' in fields
- else 'self',
- ))
+ # Include InitVars and regular fields (so, not ClassVars).
+ flds = [f for f in fields.values() if f._field_type in (_FIELD, _FIELD_INITVAR)]
+ _set_new_attribute(
+ cls, '__init__',
+ _init_fn(
+ flds, frozen, has_post_init,
+ # The name to use for the "self"
+ # param in __init__. Use "self"
+ # if possible.
+ '__dataclass_self__' if 'self' in fields else 'self',
+ )
+ )
- # Get the fields as a list, and include only real fields. This is
- # used in all of the following methods.
- field_list = [f for f in fields.values() if f._field_type is _FIELD]
+ # Get the fields as a list, and include only real fields. This is
+ # used in all of the following methods.
+ field_list = [f for f in fields.values() if f._field_type is _FIELD]
- if repr:
- flds = [f for f in field_list if f.repr]
- _set_new_attribute(cls, '__repr__', _repr_fn(flds))
+ if repr:
+ flds = [f for f in field_list if f.repr]
+ _set_new_attribute(cls, '__repr__', _repr_fn(flds))
- if eq:
- # Create _eq__ method. There's no need for a __ne__ method,
- # since python will call __eq__ and negate it.
- flds = [f for f in field_list if f.compare]
- self_tuple = _tuple_str('self', flds)
- other_tuple = _tuple_str('other', flds)
- _set_new_attribute(cls, '__eq__',
- _cmp_fn('__eq__', '==',
- self_tuple, other_tuple))
+ if eq:
+ # Create _eq__ method. There's no need for a __ne__ method,
+ # since python will call __eq__ and negate it.
+ flds = [f for f in field_list if f.compare]
+ self_tuple = _tuple_str('self', flds)
+ other_tuple = _tuple_str('other', flds)
+ _set_new_attribute(cls, '__eq__', _cmp_fn('__eq__', '==', self_tuple, other_tuple))
- if order:
- # Create and set the ordering methods.
- flds = [f for f in field_list if f.compare]
- self_tuple = _tuple_str('self', flds)
- other_tuple = _tuple_str('other', flds)
- for name, op in [('__lt__', '<'),
- ('__le__', '<='),
- ('__gt__', '>'),
- ('__ge__', '>='),
- ]:
- if _set_new_attribute(cls, name,
- _cmp_fn(name, op, self_tuple, other_tuple)):
- raise TypeError(f'Cannot overwrite attribute {name} '
- f'in class {cls.__name__}. Consider using '
- 'functools.total_ordering')
+ if order:
+ # Create and set the ordering methods.
+ flds = [f for f in field_list if f.compare]
+ self_tuple = _tuple_str('self', flds)
+ other_tuple = _tuple_str('other', flds)
+ for name, op in [('__lt__', '<'), ('__le__', '<='), ('__gt__', '>'), ('__ge__', '>='), ]:
+ if _set_new_attribute(cls, name, _cmp_fn(name, op, self_tuple, other_tuple)):
+ raise TypeError(
+ f'Cannot overwrite attribute {name} '
+ f'in class {cls.__name__}. Consider using '
+ 'functools.total_ordering'
+ )
- if frozen:
- for fn in _frozen_get_del_attr(cls, field_list):
- if _set_new_attribute(cls, fn.__name__, fn):
- raise TypeError(f'Cannot overwrite attribute {fn.__name__} '
- f'in class {cls.__name__}')
+ if frozen:
+ for fn in _frozen_get_del_attr(cls, field_list):
+ if _set_new_attribute(cls, fn.__name__, fn):
+ raise TypeError(f'Cannot overwrite attribute {fn.__name__} '
+ f'in class {cls.__name__}')
- # Decide if/how we're going to create a hash function.
- hash_action = _hash_action[bool(unsafe_hash),
- bool(eq),
- bool(frozen),
- has_explicit_hash]
- if hash_action:
- # No need to call _set_new_attribute here, since by the time
- # we're here the overwriting is unconditional.
- cls.__hash__ = hash_action(cls, field_list)
+ # Decide if/how we're going to create a hash function.
+ hash_action = _hash_action[bool(unsafe_hash), bool(eq), bool(frozen), has_explicit_hash]
+ if hash_action:
+ # No need to call _set_new_attribute here, since by the time
+ # we're here the overwriting is unconditional.
+ cls.__hash__ = hash_action(cls, field_list)
- if not getattr(cls, '__doc__'):
- # Create a class doc-string.
- cls.__doc__ = (cls.__name__ +
- str(inspect.signature(cls)).replace(' -> None', ''))
+ if not getattr(cls, '__doc__'):
+ # Create a class doc-string.
+ cls.__doc__ = (cls.__name__ + str(inspect.signature(cls)).replace(' -> None', ''))
- return cls
+ return cls
# _cls should never be specified by keyword, so start it with an
# underscore. The presence of _cls is used to detect if this
# decorator is being called with parameters or not.
-def dataclass(_cls=None, *, init=True, repr=True, eq=True, order=False,
- unsafe_hash=False, frozen=False):
- """Returns the same class as was passed in, with dunder methods
+def dataclass(_cls=None, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False):
+ """Returns the same class as was passed in, with dunder methods
added based on the fields defined in the class.
Examines PEP 526 __annotations__ to determine fields.
@@ -945,50 +912,49 @@ def dataclass(_cls=None, *, init=True, repr=True, eq=True, order=False,
__hash__() method function is added. If frozen is true, fields may
not be assigned to after instance creation.
"""
+ def wrap(cls):
+ return _process_class(cls, init, repr, eq, order, unsafe_hash, frozen)
- def wrap(cls):
- return _process_class(cls, init, repr, eq, order, unsafe_hash, frozen)
-
- # See if we're being called as @dataclass or @dataclass().
- if _cls is None:
- # We're called with parens.
- return wrap
+ # See if we're being called as @dataclass or @dataclass().
+ if _cls is None:
+ # We're called with parens.
+ return wrap
- # We're called as @dataclass without parens.
- return wrap(_cls)
+ # We're called as @dataclass without parens.
+ return wrap(_cls)
def fields(class_or_instance):
- """Return a tuple describing the fields of this dataclass.
+ """Return a tuple describing the fields of this dataclass.
Accepts a dataclass or an instance of one. Tuple elements are of
type Field.
"""
- # Might it be worth caching this, per class?
- try:
- fields = getattr(class_or_instance, _FIELDS)
- except AttributeError:
- raise TypeError('must be called with a dataclass type or instance')
+ # Might it be worth caching this, per class?
+ try:
+ fields = getattr(class_or_instance, _FIELDS)
+ except AttributeError:
+ raise TypeError('must be called with a dataclass type or instance')
- # Exclude pseudo-fields. Note that fields is sorted by insertion
- # order, so the order of the tuple is as the fields were defined.
- return tuple(f for f in fields.values() if f._field_type is _FIELD)
+ # Exclude pseudo-fields. Note that fields is sorted by insertion
+ # order, so the order of the tuple is as the fields were defined.
+ return tuple(f for f in fields.values() if f._field_type is _FIELD)
def _is_dataclass_instance(obj):
- """Returns True if obj is an instance of a dataclass."""
- return not isinstance(obj, type) and hasattr(obj, _FIELDS)
+ """Returns True if obj is an instance of a dataclass."""
+ return not isinstance(obj, type) and hasattr(obj, _FIELDS)
def is_dataclass(obj):
- """Returns True if obj is a dataclass or an instance of a
+ """Returns True if obj is a dataclass or an instance of a
dataclass."""
- return hasattr(obj, _FIELDS)
+ return hasattr(obj, _FIELDS)
def asdict(obj, *, dict_factory=dict):
- """Return the fields of a dataclass instance as a new dictionary mapping
+ """Return the fields of a dataclass instance as a new dictionary mapping
field names to field values.
Example usage:
@@ -1006,29 +972,28 @@ def asdict(obj, *, dict_factory=dict):
dataclass instances. This will also look into built-in containers:
tuples, lists, and dicts.
"""
- if not _is_dataclass_instance(obj):
- raise TypeError("asdict() should be called on dataclass instances")
- return _asdict_inner(obj, dict_factory)
+ if not _is_dataclass_instance(obj):
+ raise TypeError("asdict() should be called on dataclass instances")
+ return _asdict_inner(obj, dict_factory)
def _asdict_inner(obj, dict_factory):
- if _is_dataclass_instance(obj):
- result = []
- for f in fields(obj):
- value = _asdict_inner(getattr(obj, f.name), dict_factory)
- result.append((f.name, value))
- return dict_factory(result)
- elif isinstance(obj, (list, tuple)):
- return type(obj)(_asdict_inner(v, dict_factory) for v in obj)
- elif isinstance(obj, dict):
- return type(obj)((_asdict_inner(k, dict_factory), _asdict_inner(v, dict_factory))
- for k, v in obj.items())
- else:
- return copy.deepcopy(obj)
+ if _is_dataclass_instance(obj):
+ result = []
+ for f in fields(obj):
+ value = _asdict_inner(getattr(obj, f.name), dict_factory)
+ result.append((f.name, value))
+ return dict_factory(result)
+ elif isinstance(obj, (list, tuple)):
+ return type(obj)(_asdict_inner(v, dict_factory) for v in obj)
+ elif isinstance(obj, dict):
+ return type(obj)((_asdict_inner(k, dict_factory), _asdict_inner(v, dict_factory)) for k, v in obj.items())
+ else:
+ return copy.deepcopy(obj)
def astuple(obj, *, tuple_factory=tuple):
- """Return the fields of a dataclass instance as a new tuple of field values.
+ """Return the fields of a dataclass instance as a new tuple of field values.
Example usage::
@@ -1046,31 +1011,31 @@ def astuple(obj, *, tuple_factory=tuple):
tuples, lists, and dicts.
"""
- if not _is_dataclass_instance(obj):
- raise TypeError("astuple() should be called on dataclass instances")
- return _astuple_inner(obj, tuple_factory)
+ if not _is_dataclass_instance(obj):
+ raise TypeError("astuple() should be called on dataclass instances")
+ return _astuple_inner(obj, tuple_factory)
def _astuple_inner(obj, tuple_factory):
- if _is_dataclass_instance(obj):
- result = []
- for f in fields(obj):
- value = _astuple_inner(getattr(obj, f.name), tuple_factory)
- result.append(value)
- return tuple_factory(result)
- elif isinstance(obj, (list, tuple)):
- return type(obj)(_astuple_inner(v, tuple_factory) for v in obj)
- elif isinstance(obj, dict):
- return type(obj)((_astuple_inner(k, tuple_factory), _astuple_inner(v, tuple_factory))
- for k, v in obj.items())
- else:
- return copy.deepcopy(obj)
+ if _is_dataclass_instance(obj):
+ result = []
+ for f in fields(obj):
+ value = _astuple_inner(getattr(obj, f.name), tuple_factory)
+ result.append(value)
+ return tuple_factory(result)
+ elif isinstance(obj, (list, tuple)):
+ return type(obj)(_astuple_inner(v, tuple_factory) for v in obj)
+ elif isinstance(obj, dict):
+ return type(obj)((_astuple_inner(k, tuple_factory), _astuple_inner(v, tuple_factory)) for k, v in obj.items())
+ else:
+ return copy.deepcopy(obj)
-def make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True,
- repr=True, eq=True, order=False, unsafe_hash=False,
- frozen=False):
- """Return a new dynamically created dataclass.
+def make_dataclass(
+ cls_name, fields, *, bases=(), namespace=None, init=True, repr=True, eq=True, order=False, unsafe_hash=False,
+ frozen=False
+):
+ """Return a new dynamically created dataclass.
The dataclass name will be 'cls_name'. 'fields' is an iterable
of either (name), (name, type) or (name, type, Field) objects. If type is
@@ -1093,48 +1058,47 @@ def make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True,
dataclass().
"""
- if namespace is None:
- namespace = {}
- else:
- # Copy namespace since we're going to mutate it.
- namespace = namespace.copy()
+ if namespace is None:
+ namespace = {}
+ else:
+ # Copy namespace since we're going to mutate it.
+ namespace = namespace.copy()
- # While we're looking through the field names, validate that they
- # are identifiers, are not keywords, and not duplicates.
- seen = set()
- anns = {}
- for item in fields:
- if isinstance(item, str):
- name = item
- tp = 'typing.Any'
- elif len(item) == 2:
- name, tp, = item
- elif len(item) == 3:
- name, tp, spec = item
- namespace[name] = spec
- else:
- raise TypeError(f'Invalid field: {item!r}')
+ # While we're looking through the field names, validate that they
+ # are identifiers, are not keywords, and not duplicates.
+ seen = set()
+ anns = {}
+ for item in fields:
+ if isinstance(item, str):
+ name = item
+ tp = 'typing.Any'
+ elif len(item) == 2:
+ name, tp, = item
+ elif len(item) == 3:
+ name, tp, spec = item
+ namespace[name] = spec
+ else:
+ raise TypeError(f'Invalid field: {item!r}')
- if not isinstance(name, str) or not name.isidentifier():
- raise TypeError(f'Field names must be valid identifers: {name!r}')
- if keyword.iskeyword(name):
- raise TypeError(f'Field names must not be keywords: {name!r}')
- if name in seen:
- raise TypeError(f'Field name duplicated: {name!r}')
+ if not isinstance(name, str) or not name.isidentifier():
+ raise TypeError(f'Field names must be valid identifers: {name!r}')
+ if keyword.iskeyword(name):
+ raise TypeError(f'Field names must not be keywords: {name!r}')
+ if name in seen:
+ raise TypeError(f'Field name duplicated: {name!r}')
- seen.add(name)
- anns[name] = tp
+ seen.add(name)
+ anns[name] = tp
- namespace['__annotations__'] = anns
- # We use `types.new_class()` instead of simply `type()` to allow dynamic creation
- # of generic dataclassses.
- cls = types.new_class(cls_name, bases, {}, lambda ns: ns.update(namespace))
- return dataclass(cls, init=init, repr=repr, eq=eq, order=order,
- unsafe_hash=unsafe_hash, frozen=frozen)
+ namespace['__annotations__'] = anns
+ # We use `types.new_class()` instead of simply `type()` to allow dynamic creation
+ # of generic dataclassses.
+ cls = types.new_class(cls_name, bases, {}, lambda ns: ns.update(namespace))
+ return dataclass(cls, init=init, repr=repr, eq=eq, order=order, unsafe_hash=unsafe_hash, frozen=frozen)
def replace(obj, **changes):
- """Return a new object replacing specified fields with new values.
+ """Return a new object replacing specified fields with new values.
This is especially useful for frozen classes. Example usage:
@@ -1148,37 +1112,39 @@ def replace(obj, **changes):
assert c1.x == 3 and c1.y == 2
"""
- # We're going to mutate 'changes', but that's okay because it's a
- # new dict, even if called with 'replace(obj, **my_changes)'.
+ # We're going to mutate 'changes', but that's okay because it's a
+ # new dict, even if called with 'replace(obj, **my_changes)'.
- if not _is_dataclass_instance(obj):
- raise TypeError("replace() should be called on dataclass instances")
+ if not _is_dataclass_instance(obj):
+ raise TypeError("replace() should be called on dataclass instances")
- # It's an error to have init=False fields in 'changes'.
- # If a field is not in 'changes', read its value from the provided obj.
+ # It's an error to have init=False fields in 'changes'.
+ # If a field is not in 'changes', read its value from the provided obj.
- for f in getattr(obj, _FIELDS).values():
- # Only consider normal fields or InitVars.
- if f._field_type is _FIELD_CLASSVAR:
- continue
+ for f in getattr(obj, _FIELDS).values():
+ # Only consider normal fields or InitVars.
+ if f._field_type is _FIELD_CLASSVAR:
+ continue
- if not f.init:
- # Error if this field is specified in changes.
- if f.name in changes:
- raise ValueError(f'field {f.name} is declared with '
- 'init=False, it cannot be specified with '
- 'replace()')
- continue
+ if not f.init:
+ # Error if this field is specified in changes.
+ if f.name in changes:
+ raise ValueError(
+ f'field {f.name} is declared with '
+ 'init=False, it cannot be specified with '
+ 'replace()'
+ )
+ continue
- if f.name not in changes:
- if f._field_type is _FIELD_INITVAR:
- raise ValueError(f"InitVar {f.name!r} "
- 'must be specified with replace()')
- changes[f.name] = getattr(obj, f.name)
+ if f.name not in changes:
+ if f._field_type is _FIELD_INITVAR:
+ raise ValueError(f"InitVar {f.name!r} "
+ 'must be specified with replace()')
+ changes[f.name] = getattr(obj, f.name)
- # Create the new object, which calls __init__() and
- # __post_init__() (if defined), using all of the init fields we've
- # added and/or left in 'changes'. If there are values supplied in
- # changes that aren't fields, this will correctly raise a
- # TypeError.
- return obj.__class__(**changes)
+ # Create the new object, which calls __init__() and
+ # __post_init__() (if defined), using all of the init fields we've
+ # added and/or left in 'changes'. If there are values supplied in
+ # changes that aren't fields, this will correctly raise a
+ # TypeError.
+ return obj.__class__(**changes)
diff --git a/python/datarender.py b/python/datarender.py
index b5b21073..88f9d6d1 100644
--- a/python/datarender.py
+++ b/python/datarender.py
@@ -18,7 +18,6 @@
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
-
import traceback
import ctypes
@@ -49,6 +48,7 @@ class TypeContext:
"""The offset into the given type object"""
return self._offset
+
class DataRenderer:
"""
DataRenderer objects tell the Linear View how to render specific types.
@@ -95,8 +95,10 @@ class DataRenderer:
@staticmethod
def is_type_of_struct_name(t, name, context):
- return (t.type_class == enums.TypeClass.StructureTypeClass and len(context) > 0
- and isinstance(context[-1].type, types.NamedTypeReferenceType) and context[-1].type.name == name)
+ return (
+ t.type_class == enums.TypeClass.StructureTypeClass and len(context) > 0
+ and isinstance(context[-1].type, types.NamedTypeReferenceType) and context[-1].type.name == name
+ )
def register_type_specific(self):
core.BNRegisterTypeSpecificDataRenderer(core.BNGetDataRendererContainer(), self.handle)
@@ -119,7 +121,9 @@ class DataRenderer:
type = types.Type.create(handle=core.BNNewTypeReference(type))
pycontext = []
for i in range(0, ctxCount):
- pycontext.append(TypeContext(types.Type.create(core.BNNewTypeReference(context[i].type)), context[i].offset))
+ pycontext.append(
+ TypeContext(types.Type.create(core.BNNewTypeReference(context[i].type)), context[i].offset)
+ )
return self.perform_is_valid_for_data(ctxt, view, addr, type, pycontext)
except:
log_error(traceback.format_exc())
@@ -134,7 +138,9 @@ class DataRenderer:
prefixTokens = function.InstructionTextToken._from_core_struct(prefix, prefixCount)
pycontext = []
for i in range(ctxCount):
- pycontext.append(TypeContext(types.Type.create(core.BNNewTypeReference(typeCtx[i].type)), typeCtx[i].offset))
+ pycontext.append(
+ TypeContext(types.Type.create(core.BNNewTypeReference(typeCtx[i].type)), typeCtx[i].offset)
+ )
result = self.perform_get_lines_for_data(ctxt, view, addr, type, prefixTokens, width, pycontext)
@@ -143,7 +149,8 @@ class DataRenderer:
for i in range(len(result)):
line = result[i]
color = line.highlight
- if not isinstance(color, enums.HighlightStandardColor) and not isinstance(color, highlight.HighlightColor):
+ if not isinstance(color,
+ enums.HighlightStandardColor) and not isinstance(color, highlight.HighlightColor):
raise ValueError("Specified color is not one of HighlightStandardColor, highlight.HighlightColor")
if isinstance(color, enums.HighlightStandardColor):
color = highlight.HighlightColor(color)
diff --git a/python/debuginfo.py b/python/debuginfo.py
index ba96c27f..a48182e6 100644
--- a/python/debuginfo.py
+++ b/python/debuginfo.py
@@ -33,7 +33,6 @@ from .log import log_error
from . import binaryview
from . import filemetadata
-
_debug_info_parsers = {}
@@ -98,18 +97,21 @@ class _DebugInfoParserMetaClass(type):
@staticmethod
def _is_valid(view: core.BNBinaryView, callback: Callable[['binaryview.BinaryView'], bool]) -> bool:
try:
- file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
- view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
+ file_metadata = filemetadata.FileMetadata(handle=core.BNGetFileForView(view))
+ view_obj = binaryview.BinaryView(file_metadata=file_metadata, handle=core.BNNewViewReference(view))
return callback(view_obj)
except:
log_error(traceback.format_exc())
return False
@staticmethod
- def _parse_info(debug_info: core.BNDebugInfo, view: core.BNBinaryView, callback: Callable[["DebugInfo", 'binaryview.BinaryView'], None]) -> None:
+ def _parse_info(
+ debug_info: core.BNDebugInfo, view: core.BNBinaryView,
+ callback: Callable[["DebugInfo", 'binaryview.BinaryView'], None]
+ ) -> None:
try:
- file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
- view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
+ file_metadata = filemetadata.FileMetadata(handle=core.BNGetFileForView(view))
+ view_obj = binaryview.BinaryView(file_metadata=file_metadata, handle=core.BNNewViewReference(view))
parser_ref = core.BNNewDebugInfoReference(debug_info)
assert parser_ref is not None, "core.BNNewDebugInfoReference returned None"
callback(DebugInfo(parser_ref), view_obj)
@@ -117,12 +119,19 @@ class _DebugInfoParserMetaClass(type):
log_error(traceback.format_exc())
@classmethod
- def register(cls, name: str, is_valid: Callable[['binaryview.BinaryView'], bool], parse_info: Callable[["DebugInfo", 'binaryview.BinaryView'], None]) -> "DebugInfoParser":
+ def register(
+ cls, name: str, is_valid: Callable[['binaryview.BinaryView'], bool],
+ parse_info: Callable[["DebugInfo", 'binaryview.BinaryView'], None]
+ ) -> "DebugInfoParser":
"""Registers a DebugInfoParser. See ``debuginfo.DebugInfoParser`` for more details."""
binaryninja._init_plugins()
- is_valid_cb = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView))(lambda ctxt, view: cls._is_valid(view, is_valid))
- parse_info_cb = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(core.BNDebugInfo), ctypes.POINTER(core.BNBinaryView))(lambda ctxt, debug_info, view: cls._parse_info(debug_info, view, parse_info))
+ is_valid_cb = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p,
+ ctypes.POINTER(core.BNBinaryView
+ ))(lambda ctxt, view: cls._is_valid(view, is_valid))
+ parse_info_cb = ctypes.CFUNCTYPE(
+ None, ctypes.c_void_p, ctypes.POINTER(core.BNDebugInfo), ctypes.POINTER(core.BNBinaryView)
+ )(lambda ctxt, debug_info, view: cls._parse_info(debug_info, view, parse_info))
# Don't let our callbacks get garbage collected
global _debug_info_parsers
@@ -231,15 +240,15 @@ class DebugFunctionInfo(object):
Functions will not be created if an address is not provided, but will be able to be queried from debug info for later user analysis.
"""
- short_name:Optional[str] = None
- full_name:Optional[str] = None
- raw_name:Optional[str] = None
- address:Optional[int] = None
- return_type:Optional[_types.Type] = None
- parameters:Optional[List[Tuple[str, _types.Type]]] = None
- variable_parameters:Optional[bool] = None
- calling_convention:Optional[callingconvention.CallingConvention] = None
- platform:Optional['_platform.Platform'] = None
+ short_name: Optional[str] = None
+ full_name: Optional[str] = None
+ raw_name: Optional[str] = None
+ address: Optional[int] = None
+ return_type: Optional[_types.Type] = None
+ parameters: Optional[List[Tuple[str, _types.Type]]] = None
+ variable_parameters: Optional[bool] = None
+ calling_convention: Optional[callingconvention.CallingConvention] = None
+ platform: Optional['_platform.Platform'] = None
def __repr__(self) -> str:
suffix = f"@{self.address:#x}>" if self.address != 0 else ">"
@@ -301,7 +310,10 @@ class DebugInfo(object):
parameters: List[Tuple[str, _types.Type]] = []
for j in range(functions[i].parameterCount):
- parameters.append((functions[i].parameterNames[j], _types.Type(core.BNNewTypeReference(functions[i].parameterTypes[j]))))
+ parameters.append((
+ functions[i].parameterNames[j],
+ _types.Type(core.BNNewTypeReference(functions[i].parameterTypes[j]))
+ ))
if functions[i].returnType:
return_type = _types.Type(core.BNNewTypeReference(functions[i].returnType))
@@ -309,7 +321,9 @@ class DebugInfo(object):
return_type = None
if functions[i].callingConvention:
- calling_convention = callingconvention.CallingConvention(handle=core.BNNewCallingConventionReference(functions[i].callingConvention))
+ calling_convention = callingconvention.CallingConvention(
+ handle=core.BNNewCallingConventionReference(functions[i].callingConvention)
+ )
else:
calling_convention = None
@@ -319,15 +333,8 @@ class DebugInfo(object):
func_platform = None
yield DebugFunctionInfo(
- functions[i].address,
- functions[i].shortName,
- functions[i].fullName,
- functions[i].rawName,
- return_type,
- parameters,
- functions[i].variableParameters,
- calling_convention,
- func_platform
+ functions[i].address, functions[i].shortName, functions[i].fullName, functions[i].rawName,
+ return_type, parameters, functions[i].variableParameters, calling_convention, func_platform
)
finally:
core.BNFreeDebugFunctions(functions, count.value)
@@ -345,10 +352,11 @@ class DebugInfo(object):
try:
for i in range(0, count.value):
yield binaryview.DataVariableAndName(
- data_variables[i].address,
- _types.Type(core.BNNewTypeReference(data_variables[i].type), confidence=data_variables[i].typeConfidence),
- data_variables[i].name,
- data_variables[i].autoDiscovered)
+ data_variables[i].address,
+ _types.Type(
+ core.BNNewTypeReference(data_variables[i].type), confidence=data_variables[i].typeConfidence
+ ), data_variables[i].name, data_variables[i].autoDiscovered
+ )
finally:
core.BNFreeDataVariablesAndName(data_variables, count.value)
@@ -357,7 +365,7 @@ class DebugInfo(object):
"""A generator of all data variables provided by DebugInfoParsers"""
return self.data_variables_from_parser()
- def add_type(self, name: str, new_type:'_types.Type') -> bool:
+ def add_type(self, name: str, new_type: '_types.Type') -> bool:
"""Adds a type scoped under the current parser's name to the debug info"""
if isinstance(new_type, _types.Type):
return core.BNAddDebugType(self.handle, name, new_type.handle)
@@ -406,8 +414,12 @@ class DebugInfo(object):
func_info.parameterTypes = None
func_info.parameterCount = parameter_count
else:
- func_info.parameterNames = (ctypes.c_char_p * parameter_count)(*map(lambda pair: binaryninja.cstr(pair[0]), new_func.parameters)) # type: ignore
- func_info.parameterTypes = (ctypes.POINTER(core.BNType) * parameter_count)(*map(lambda pair: pair[1].handle, new_func.parameters)) # type: ignore
+ func_info.parameterNames = (ctypes.c_char_p * parameter_count)(
+ *map(lambda pair: binaryninja.cstr(pair[0]), new_func.parameters)
+ ) # type: ignore
+ func_info.parameterTypes = (ctypes.POINTER(core.BNType) * parameter_count)(
+ *map(lambda pair: pair[1].handle, new_func.parameters)
+ ) # type: ignore
func_info.parameterCount = parameter_count
return core.BNAddDebugFunction(self.handle, func_info)
diff --git a/python/decorators.py b/python/decorators.py
index fcd3a8be..e02829f8 100644
--- a/python/decorators.py
+++ b/python/decorators.py
@@ -10,4 +10,3 @@ def passive(cls):
cls.__doc__ = passive_note
return cls
-
diff --git a/python/demangle.py b/python/demangle.py
index 3f22d294..6e9185ec 100644
--- a/python/demangle.py
+++ b/python/demangle.py
@@ -44,7 +44,7 @@ def get_qualified_name(names):
return "::".join(names)
-def demangle_ms(arch, mangled_name, options = False):
+def demangle_ms(arch, mangled_name, options=False):
"""
``demangle_ms`` demangles a mangled Microsoft Visual Studio C++ name to a Type object.
@@ -64,9 +64,19 @@ def demangle_ms(arch, mangled_name, options = False):
outName = ctypes.POINTER(ctypes.c_char_p)()
outSize = ctypes.c_ulonglong()
names = []
- if (isinstance(options, binaryview.BinaryView) and core.BNDemangleMSWithOptions(arch.handle, mangled_name, ctypes.byref(handle), ctypes.byref(outName), ctypes.byref(outSize), options)) or \
- (isinstance(options, bool) and core.BNDemangleMS(arch.handle, mangled_name, ctypes.byref(handle), ctypes.byref(outName), ctypes.byref(outSize), options)) or \
- (options is None and core.BNDemangleMSWithOptions(arch.handle, mangled_name, ctypes.byref(handle), ctypes.byref(outName), ctypes.byref(outSize), None)):
+ if (
+ isinstance(options, binaryview.BinaryView) and core.BNDemangleMSWithOptions(
+ arch.handle, mangled_name, ctypes.byref(handle), ctypes.byref(outName), ctypes.byref(outSize), options
+ )
+ ) or (
+ isinstance(options, bool) and core.BNDemangleMS(
+ arch.handle, mangled_name, ctypes.byref(handle), ctypes.byref(outName), ctypes.byref(outSize), options
+ )
+ ) or (
+ options is None and core.BNDemangleMSWithOptions(
+ arch.handle, mangled_name, ctypes.byref(handle), ctypes.byref(outName), ctypes.byref(outSize), None
+ )
+ ):
for i in range(outSize.value):
names.append(outName[i].decode('utf8')) # type: ignore
core.BNFreeDemangledName(ctypes.byref(outName), outSize.value)
@@ -74,7 +84,7 @@ def demangle_ms(arch, mangled_name, options = False):
return (None, mangled_name)
-def demangle_gnu3(arch, mangled_name, options = None):
+def demangle_gnu3(arch, mangled_name, options=None):
"""
``demangle_gnu3`` demangles a mangled name to a Type object.
@@ -89,9 +99,19 @@ def demangle_gnu3(arch, mangled_name, options = None):
outName = ctypes.POINTER(ctypes.c_char_p)()
outSize = ctypes.c_ulonglong()
names = []
- if (isinstance(options, binaryview.BinaryView) and core.BNDemangleGNU3WithOptions(arch.handle, mangled_name, ctypes.byref(handle), ctypes.byref(outName), ctypes.byref(outSize), options)) or \
- (isinstance(options, bool) and core.BNDemangleGNU3(arch.handle, mangled_name, ctypes.byref(handle), ctypes.byref(outName), ctypes.byref(outSize), options)) or \
- (options is None and core.BNDemangleGNU3WithOptions(arch.handle, mangled_name, ctypes.byref(handle), ctypes.byref(outName), ctypes.byref(outSize), None)):
+ if (
+ isinstance(options, binaryview.BinaryView) and core.BNDemangleGNU3WithOptions(
+ arch.handle, mangled_name, ctypes.byref(handle), ctypes.byref(outName), ctypes.byref(outSize), options
+ )
+ ) or (
+ isinstance(options, bool) and core.BNDemangleGNU3(
+ arch.handle, mangled_name, ctypes.byref(handle), ctypes.byref(outName), ctypes.byref(outSize), options
+ )
+ ) or (
+ options is None and core.BNDemangleGNU3WithOptions(
+ arch.handle, mangled_name, ctypes.byref(handle), ctypes.byref(outName), ctypes.byref(outSize), None
+ )
+ ):
for i in range(outSize.value):
names.append(outName[i].decode('utf8')) # type: ignore
core.BNFreeDemangledName(ctypes.byref(outName), outSize.value)
@@ -125,7 +145,7 @@ def simplify_name_to_string(input_name):
return result
-def simplify_name_to_qualified_name(input_name, simplify = True):
+def simplify_name_to_qualified_name(input_name, simplify=True):
"""
``simplify_name_to_qualified_name`` simplifies a templated C++ name with default arguments and returns a qualified name. This can also tokenize a string to a qualified name with/without simplifying it
@@ -158,5 +178,5 @@ def simplify_name_to_qualified_name(input_name, simplify = True):
name_count = len(native_result)
native_result = types.QualifiedName(native_result)
- core.BNRustFreeStringArray(result, name_count+1)
+ core.BNRustFreeStringArray(result, name_count + 1)
return native_result
diff --git a/python/downloadprovider.py b/python/downloadprovider.py
index 793dc298..ed61136c 100644
--- a/python/downloadprovider.py
+++ b/python/downloadprovider.py
@@ -18,7 +18,6 @@
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
-
import abc
import ctypes
from json import dumps
@@ -52,7 +51,7 @@ class DownloadInstance(object):
self.headers = headers
self.content = content
- def __init__(self, provider, handle = None):
+ def __init__(self, provider, handle=None):
if handle is None:
self._cb = core.BNDownloadInstanceCallbacks()
self._cb.context = 0
@@ -88,7 +87,8 @@ class DownloadInstance(object):
def _perform_custom_request(self, ctxt, method, url, header_count, header_keys, header_values, response):
# Cast response to an array of length 1 so ctypes can write to the pointer
# out_response = ((BNDownloadInstanceResponse*)[1])response
- out_response = (ctypes.POINTER(core.BNDownloadInstanceResponse) * 1).from_address(ctypes.addressof(response.contents)) # type: ignore
+ out_response = (ctypes.POINTER(core.BNDownloadInstanceResponse)
+ * 1).from_address(ctypes.addressof(response.contents)) # type: ignore
try:
# Extract headers
keys_ptr = ctypes.cast(header_keys, ctypes.POINTER(ctypes.c_char_p))
@@ -103,7 +103,9 @@ class DownloadInstance(object):
def data_generator():
while True:
read_buffer = ctypes.create_string_buffer(0x1000)
- read_len = core.BNReadDataForDownloadInstance(self.handle, ctypes.cast(read_buffer, ctypes.POINTER(ctypes.c_uint8)), 0x1000)
+ read_len = core.BNReadDataForDownloadInstance(
+ self.handle, ctypes.cast(read_buffer, ctypes.POINTER(ctypes.c_uint8)), 0x1000
+ )
if read_len == 0:
break
if read_len < 0:
@@ -203,7 +205,7 @@ class DownloadInstance(object):
if "Content-Type" not in headers:
headers["Content-Type"] = "application/x-www-form-urlencoded"
else:
- assert(type(data) == bytes)
+ assert (type(data) == bytes)
self._data = data
if len(data) > 0 and "Content-Length" not in headers:
@@ -226,7 +228,9 @@ class DownloadInstance(object):
header_values[i] = to_bytes(value)
response = ctypes.POINTER(core.BNDownloadInstanceResponse)()
- result = core.BNPerformCustomRequest(self.handle, method, url, len(headers), header_keys, header_values, response, callbacks)
+ result = core.BNPerformCustomRequest(
+ self.handle, method, url, len(headers), header_keys, header_values, response, callbacks
+ )
if result != 0:
return None
@@ -246,6 +250,7 @@ class DownloadInstance(object):
def put(self, url, headers=None, data=None, json=None):
return self.request("POST", url, headers, data, json)
+
class _DownloadProviderMetaclass(type):
def __iter__(self):
binaryninja._init_plugins()
@@ -270,7 +275,7 @@ class DownloadProvider(metaclass=_DownloadProviderMetaclass):
instance_class = None
_registered_providers = []
- def __init__(self, handle = None):
+ def __init__(self, handle=None):
if handle is not None:
self.handle = core.handle_of_type(handle, core.BNDownloadProvider)
self.__dict__["name"] = core.BNGetDownloadProviderName(handle)
@@ -299,7 +304,7 @@ class DownloadProvider(metaclass=_DownloadProviderMetaclass):
result = core.BNCreateDownloadProviderInstance(self.handle)
if result is None:
return None
- return DownloadInstance(self, handle = result)
+ return DownloadInstance(self, handle=result)
_loaded = False
@@ -398,7 +403,10 @@ try:
if b"Content-Length" in headers:
del headers[b"Content-Length"]
- r = requests.request(method.decode('utf8'), url.decode('utf8'), headers=headers, data=data_generator, proxies=proxies, stream=True)
+ r = requests.request(
+ method.decode('utf8'), url.decode('utf8'), headers=headers, data=data_generator, proxies=proxies,
+ stream=True
+ )
total_size = 0
for (key, value) in r.headers.items():
@@ -465,7 +473,9 @@ if not _loaded and (sys.platform != "win32") and (sys.version_info >= (2, 7, 9))
core.BNSetErrorForDownloadInstance(self.handle, "Bytes written mismatch!")
return -1
bytes_sent = bytes_sent + bytes_wrote
- continue_download = core.BNNotifyProgressForDownloadInstance(self.handle, bytes_sent, total_size)
+ continue_download = core.BNNotifyProgressForDownloadInstance(
+ self.handle, bytes_sent, total_size
+ )
if continue_download is False:
core.BNSetErrorForDownloadInstance(self.handle, "Download aborted!")
return -1
@@ -490,7 +500,6 @@ if not _loaded and (sys.platform != "win32") and (sys.version_info >= (2, 7, 9))
urllib2 (python2) does not have a parameter for custom request methods
So this is a shim class to deal with that
"""
-
def __init__(self, *args, **kwargs):
if "method" in kwargs:
self._method = kwargs["method"]
@@ -518,7 +527,9 @@ if not _loaded and (sys.platform != "win32") and (sys.version_info >= (2, 7, 9))
if b"Content-Length" in headers:
del headers[b"Content-Length"]
- req = PythonDownloadInstance.CustomRequest(url.decode('utf8'), data=data_generator, headers=headers, method=method.decode('utf8'))
+ req = PythonDownloadInstance.CustomRequest(
+ url.decode('utf8'), data=data_generator, headers=headers, method=method.decode('utf8')
+ )
result = urlopen(req)
except HTTPError as he:
result = he
@@ -562,8 +573,12 @@ if not _loaded:
log_error("Please install the requests package into the selected Python environment:")
log_error(" python -m pip install requests")
else:
- log_error("On Python versions below 2.7.9, the pip requests[security] package is required for network connectivity!")
- log_error("On an Ubuntu 14.04 install, the following three commands are sufficient to enable networking for the current user:")
+ log_error(
+ "On Python versions below 2.7.9, the pip requests[security] package is required for network connectivity!"
+ )
+ log_error(
+ "On an Ubuntu 14.04 install, the following three commands are sufficient to enable networking for the current user:"
+ )
log_error(" sudo apt install python-pip")
log_error(" python -m pip install pip --upgrade --user")
log_error(" python -m pip install requests[security] --upgrade --user")
diff --git a/python/enterprise.py b/python/enterprise.py
index 18062153..e3c0e26c 100644
--- a/python/enterprise.py
+++ b/python/enterprise.py
@@ -271,7 +271,6 @@ class LicenseCheckout:
# License is released at end of scope
"""
-
def __init__(self, duration=900, cache=False):
self.desired_duration = duration
self.desired_cache = cache
@@ -284,8 +283,9 @@ class LicenseCheckout:
connect()
if not is_authenticated():
raise RuntimeError(
- "Could not checkout a license: Not authenticated. "
- "Please use binaryninja.enterprise.authenticate_with_credentials or authenticate_with_method first!")
+ "Could not checkout a license: Not authenticated. "
+ "Please use binaryninja.enterprise.authenticate_with_credentials or authenticate_with_method first!"
+ )
acquire_license(self.desired_duration, self.desired_cache)
def __exit__(self, exc_type, exc_val, exc_tb):
diff --git a/python/examples/angr_plugin.py b/python/examples/angr_plugin.py
index 940aff8b..5f2eeba0 100644
--- a/python/examples/angr_plugin.py
+++ b/python/examples/angr_plugin.py
@@ -18,7 +18,6 @@
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
-
# This plugin assumes angr is already installed and available on the system. See the angr documentation
# for information about installing angr. It should be installed using the virtualenv method.
#
@@ -72,7 +71,7 @@ class Solver(BackgroundTaskThread):
def run(self):
# Create an angr project and an explorer with the user's settings
p = angr.Project(self.binary.name)
- e = p.surveyors.Explorer(find = self.find, avoid = self.avoid)
+ e = p.surveyors.Explorer(find=self.find, avoid=self.avoid)
# Solve loop
while not e.done:
@@ -98,7 +97,7 @@ class Solver(BackgroundTaskThread):
text_report = "Found %d path%s.\n\n" % (len(e.found), "s" if len(e.found) != 1 else "")
i = 1
for f in e.found:
- text_report += "Path %d\n" % i + "=" * 10 + "\n"
+ text_report += "Path %d\n"%i + "="*10 + "\n"
text_report += "stdin:\n" + escaped_output(f.state.posix.dumps(0)) + "\n\n"
text_report += "stdout:\n" + escaped_output(f.state.posix.dumps(1)) + "\n\n"
text_report += "stderr:\n" + escaped_output(f.state.posix.dumps(2)) + "\n\n"
@@ -115,7 +114,7 @@ def find_instr(bv, addr):
# Highlight the instruction in green
blocks = bv.get_basic_blocks_at(addr)
for block in blocks:
- block.set_auto_highlight(HighlightColor(HighlightStandardColor.GreenHighlightColor, alpha = 128))
+ block.set_auto_highlight(HighlightColor(HighlightStandardColor.GreenHighlightColor, alpha=128))
block.function.set_auto_instr_highlight(addr, HighlightStandardColor.GreenHighlightColor)
# Add the instruction to the list associated with the current view
@@ -126,7 +125,7 @@ def avoid_instr(bv, addr):
# Highlight the instruction in red
blocks = bv.get_basic_blocks_at(addr)
for block in blocks:
- block.set_auto_highlight(HighlightColor(HighlightStandardColor.RedHighlightColor, alpha = 128))
+ block.set_auto_highlight(HighlightColor(HighlightStandardColor.RedHighlightColor, alpha=128))
block.function.set_auto_instr_highlight(addr, HighlightStandardColor.RedHighlightColor)
# Add the instruction to the list associated with the current view
@@ -135,9 +134,11 @@ def avoid_instr(bv, addr):
def solve(bv):
if len(bv.session_data.angr_find) == 0:
- show_message_box("Angr Solve", "You have not specified a goal instruction.\n\n" +
- "Please right click on the goal instruction and select \"Find Path to This Instruction\" to " +
- "continue.", MessageBoxButtonSet.OKButtonSet, MessageBoxIcon.ErrorIcon)
+ show_message_box(
+ "Angr Solve", "You have not specified a goal instruction.\n\n"
+ + "Please right click on the goal instruction and select \"Find Path to This Instruction\" to " + "continue.",
+ MessageBoxButtonSet.OKButtonSet, MessageBoxIcon.ErrorIcon
+ )
return
# Start a solver thread for the path associated with the view
@@ -146,8 +147,10 @@ def solve(bv):
# Register commands for the user to interact with the plugin
-PluginCommand.register_for_address("Find Path to This Instruction",
- "When solving, find a path that gets to this instruction", find_instr)
-PluginCommand.register_for_address("Avoid This Instruction",
- "When solving, avoid paths that reach this instruction", avoid_instr)
+PluginCommand.register_for_address(
+ "Find Path to This Instruction", "When solving, find a path that gets to this instruction", find_instr
+)
+PluginCommand.register_for_address(
+ "Avoid This Instruction", "When solving, avoid paths that reach this instruction", avoid_instr
+)
PluginCommand.register("Solve With Angr", "Attempt to solve for a path that satisfies the constraints given", solve)
diff --git a/python/examples/arch_hook.py b/python/examples/arch_hook.py
index 452bd2b6..a6e280cc 100644
--- a/python/examples/arch_hook.py
+++ b/python/examples/arch_hook.py
@@ -1,16 +1,17 @@
from binaryninja.architecture import Architecture, ArchitectureHook
+
class X86ReturnHook(ArchitectureHook):
- def get_instruction_text(self, data, addr):
- # Call the original implementation's method by calling the superclass
- result, length = super(X86ReturnHook, self).get_instruction_text(data, addr)
+ def get_instruction_text(self, data, addr):
+ # Call the original implementation's method by calling the superclass
+ result, length = super(X86ReturnHook, self).get_instruction_text(data, addr)
+
+ # Patch the name of the 'retn' instruction to 'ret'
+ if len(result) > 0 and result[0].text == 'retn':
+ result[0].text = 'ret'
- # Patch the name of the 'retn' instruction to 'ret'
- if len(result) > 0 and result[0].text == 'retn':
- result[0].text = 'ret'
+ return result, length
- return result, length
# Install the hook by constructing it with the desired architecture to hook, then registering it
X86ReturnHook(Architecture['x86']).register()
-
diff --git a/python/examples/asm_to_llil_view.py b/python/examples/asm_to_llil_view.py
index 18c77547..3b7fb374 100644
--- a/python/examples/asm_to_llil_view.py
+++ b/python/examples/asm_to_llil_view.py
@@ -1,5 +1,5 @@
# Copyright (c) 2019-2022 Vector 35 Inc
-#
+#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
@@ -103,13 +103,18 @@ class DisassemblyAndLowLevelILGraph(FlowGraph):
for line in lines:
if line.il_instruction is None:
# For assembly lines, show address
- line.tokens.insert(0, InstructionTextToken(InstructionTextTokenType.AddressDisplayToken,
- "%.8x" % line.address, line.address))
+ line.tokens.insert(
+ 0, InstructionTextToken(InstructionTextTokenType.AddressDisplayToken, "%.8x" % line.address, line.address)
+ )
line.tokens.insert(1, InstructionTextToken(InstructionTextTokenType.TextToken, " "))
else:
# For IL lines, show IL instruction index
- line.tokens.insert(0, InstructionTextToken(InstructionTextTokenType.AnnotationToken,
- "%8s" % ("[%d]" % line.il_instruction.instr_index)))
+ line.tokens.insert(
+ 0,
+ InstructionTextToken(
+ InstructionTextTokenType.AnnotationToken, "%8s" % ("[%d]" % line.il_instruction.instr_index)
+ )
+ )
line.tokens.insert(1, InstructionTextToken(InstructionTextTokenType.AnnotationToken, " => "))
nodes[block.start].lines = lines
diff --git a/python/examples/breakpoint.py b/python/examples/breakpoint.py
index ab2ccfa5..20ff2b6b 100644
--- a/python/examples/breakpoint.py
+++ b/python/examples/breakpoint.py
@@ -18,7 +18,6 @@
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
-
from binaryninja.plugin import PluginCommand
from binaryninja.log import log_error
@@ -29,12 +28,7 @@ def write_breakpoint(view, start, length):
register_for_address
register_for_function
"""
- bkpt_str = {
- "x86": "int3",
- "x86_64": "int3",
- "armv7": "bkpt",
- "aarch64": "brk #0",
- "mips32": "break"}
+ bkpt_str = {"x86": "int3", "x86_64": "int3", "armv7": "bkpt", "aarch64": "brk #0", "mips32": "break"}
if view.arch.name not in bkpt_str:
log_error("Architecture %s not supported" % view.arch.name)
diff --git a/python/examples/cli_dis.py b/python/examples/cli_dis.py
index 8f863db3..cbd4b8f1 100755
--- a/python/examples/cli_dis.py
+++ b/python/examples/cli_dis.py
@@ -55,12 +55,12 @@ archName = sys.argv[1]
bytesList = sys.argv[2:]
# parse byte arguments
-data = b''.join(list(map(lambda x: int(x,16).to_bytes(1,'big'), bytesList)))
+data = b''.join(list(map(lambda x: int(x, 16).to_bytes(1, 'big'), bytesList)))
# disassemble
arch = binaryninja.Architecture[archName]
toksAndLen = arch.get_instruction_text(data, 0)
-if not toksAndLen or toksAndLen[1]==0:
+if not toksAndLen or toksAndLen[1] == 0:
print('disassembly failed')
sys.exit(-1)
@@ -68,4 +68,3 @@ if not toksAndLen or toksAndLen[1]==0:
toks = toksAndLen[0]
strs = map(lambda x: x.text, toks)
print(GREEN, ''.join(strs), NORMAL)
-
diff --git a/python/examples/cli_lift.py b/python/examples/cli_lift.py
index b335a5e4..946f8c3a 100755
--- a/python/examples/cli_lift.py
+++ b/python/examples/cli_lift.py
@@ -34,16 +34,18 @@ from binaryninja import lowlevelil
RED = '\x1B[31m'
NORMAL = '\x1B[0m'
+
def traverse_IL(il, indent):
if isinstance(il, lowlevelil.LowLevelILInstruction):
print('\t'*indent + il.operation.name)
for o in il.operands:
- traverse_IL(o, indent+1)
+ traverse_IL(o, indent + 1)
else:
print('\t'*indent + str(il))
+
if __name__ == '__main__':
if not sys.argv[2:]:
@@ -63,7 +65,7 @@ if __name__ == '__main__':
bytesList = sys.argv[2:]
# parse byte arguments
- data = b''.join(list(map(lambda x: int(x,16).to_bytes(1,'big'), bytesList)))
+ data = b''.join(list(map(lambda x: int(x, 16).to_bytes(1, 'big'), bytesList)))
plat = binaryninja.Platform[platName]
bv = binaryview.BinaryView.new(data)
@@ -71,13 +73,13 @@ if __name__ == '__main__':
bv.add_function(0, plat=plat)
-# print('print all the functions, their basic blocks, and their mc instructions')
-# for func in bv.functions:
-# print(repr(func))
-# for block in func:
-# print("\t{0}".format(block))
-# for insn in block:
-# print("\t\t{0}".format(insn))
+ # print('print all the functions, their basic blocks, and their mc instructions')
+ # for func in bv.functions:
+ # print(repr(func))
+ # for block in func:
+ # print("\t{0}".format(block))
+ # for insn in block:
+ # print("\t\t{0}".format(insn))
print(RED)
for func in bv.functions:
@@ -87,4 +89,3 @@ if __name__ == '__main__':
for insn in block:
traverse_IL(insn, 0)
print(NORMAL)
-
diff --git a/python/examples/debug_info.py b/python/examples/debug_info.py
index 8f379544..28175ba1 100755
--- a/python/examples/debug_info.py
+++ b/python/examples/debug_info.py
@@ -29,7 +29,6 @@
# bv.apply_debug_info(debug_info)
# ```
-
# The rest of this file serves as a test and example of implementing debug info parsers, and the resultant debug info.
#
# All that is required is to provide functions similar to "is_valid" and "parse_info" below, and call
@@ -98,50 +97,56 @@
# }
# ```
-
import binaryninja as bn
import os
-
filename = os.path.join(os.path.dirname(os.path.abspath(__file__)), "test_debug_info")
-
# Some setup code not just for informative printing
-
print = print
if __name__ != "__main__":
- print = bn.log_error
+ print = bn.log_error
-def pretty_print_add_data_variable(debug_info: bn.debuginfo.DebugInfo, address: int, t: bn.types.Type, name: str = None) -> None:
- print(f" Adding data variable of type `{t}` at {hex(address)} : {debug_info.add_data_variable(address, t, name)}")
+def pretty_print_add_data_variable(
+ debug_info: bn.debuginfo.DebugInfo, address: int, t: bn.types.Type, name: str = None
+) -> None:
+ print(f" Adding data variable of type `{t}` at {hex(address)} : {debug_info.add_data_variable(address, t, name)}")
-def pretty_print_add_function(debug_info: bn.debuginfo.DebugInfo, address: int, short_name: str = None, full_name: str = None, raw_name: str = None, return_type = None, parameters = None) -> None:
- function_info = bn.debuginfo.DebugFunctionInfo(address, short_name, full_name, raw_name, return_type, parameters)
- if parameters is not None:
- print(f" Adding function `{return_type} {short_name}({', '.join(f'{t} {name}' for name, t in parameters)})` at {hex(address)} : {debug_info.add_function(function_info)}")
- else:
- print(f" Adding function `{return_type} {short_name}()` at {hex(address)} : {debug_info.add_function(function_info)}")
+def pretty_print_add_function(
+ debug_info: bn.debuginfo.DebugInfo, address: int, short_name: str = None, full_name: str = None, raw_name: str = None,
+ return_type=None, parameters=None
+) -> None:
+ function_info = bn.debuginfo.DebugFunctionInfo(address, short_name, full_name, raw_name, return_type, parameters)
+ if parameters is not None:
+ print(
+ f" Adding function `{return_type} {short_name}({', '.join(f'{t} {name}' for name, t in parameters)})` at {hex(address)} : {debug_info.add_function(function_info)}"
+ )
+ else:
+ print(
+ f" Adding function `{return_type} {short_name}()` at {hex(address)} : {debug_info.add_function(function_info)}"
+ )
# The beginning of the actual debug info plugin
def is_valid(bv: bn.binaryview.BinaryView):
- sym = bv.get_symbol_by_raw_name("__elf_interp")
- if sym is None:
- return False
- else:
- var = bv.get_data_var_at(sym.address)
- return b"test_debug_info_parsing" == bv.read(sym.address, var.type.width-1)
+ sym = bv.get_symbol_by_raw_name("__elf_interp")
+ if sym is None:
+ return False
+ else:
+ var = bv.get_data_var_at(sym.address)
+ return b"test_debug_info_parsing" == bv.read(sym.address, var.type.width - 1)
def parse_info(debug_info: bn.debuginfo.DebugInfo, bv: bn.binaryview.BinaryView):
- print("Adding types")
- types = []
- for name, t in bv.parse_types_from_string("""
+ print("Adding types")
+ types = []
+ for name, t in bv.parse_types_from_string(
+ """
struct test_type_1 {
int a;
char b[4];
@@ -153,62 +158,81 @@ def parse_info(debug_info: bn.debuginfo.DebugInfo, bv: bn.binaryview.BinaryView)
struct test_type_1 a;
struct test_type_1* b;
struct test_type_2* c;
- };""").types.items():
- print(f" Adding type \"{name}\" `{t}` : {debug_info.add_type(str(name), t)}")
- types.append(t)
+ };"""
+ ).types.items():
+ print(f" Adding type \"{name}\" `{t}` : {debug_info.add_type(str(name), t)}")
+ types.append(t)
- print("Adding data variables")
- pretty_print_add_data_variable(debug_info, 0x4030, types[0], "test_var_1")
- pretty_print_add_data_variable(debug_info, 0x4010, bn.types.Type.int(4, True), "test_var_2")
- # Names are optional
- pretty_print_add_data_variable(debug_info, 0x4014, bn.types.Type.int(4, True))
+ print("Adding data variables")
+ pretty_print_add_data_variable(debug_info, 0x4030, types[0], "test_var_1")
+ pretty_print_add_data_variable(debug_info, 0x4010, bn.types.Type.int(4, True), "test_var_2")
+ # Names are optional
+ pretty_print_add_data_variable(debug_info, 0x4014, bn.types.Type.int(4, True))
- t = bn.types.Type.int(4, True)
- t.const = True
- pretty_print_add_data_variable(debug_info, 0x2004, t, "test_var_3")
+ t = bn.types.Type.int(4, True)
+ t.const = True
+ pretty_print_add_data_variable(debug_info, 0x2004, t, "test_var_3")
- print("Adding functions")
- char_star = bv.parse_type_string("char*")[0]
- pretty_print_add_function(debug_info, 0x1129, "no_return_type_no_parameters", None, None, bn.types.Type.void(), None)
- pretty_print_add_function(debug_info, 0x1134, "used_parameter", None, None, bn.types.Type.bool(), [("value", bn.types.Type.bool())])
- pretty_print_add_function(debug_info, 0x1155, "unused_parameters", None, None, bn.types.Type.int(4, True), [("value_1", bn.types.Type.bool()), ("value_2", bn.types.Type.int(4, True)), ("value_3", char_star)])
- pretty_print_add_function(debug_info, 0x1170, "used_and_unused_parameters_1", None, None, bn.types.Type.int(4, True), [("value_1", bn.types.Type.int(4, True)), ("value_2", bn.types.Type.int(4, True)), ("value_3", char_star), ("value_4", bn.types.Type.bool())])
- pretty_print_add_function(debug_info, 0x1191, "used_and_unused_parameters_2", None, None, bn.types.Type.int(1, False), [("value_1", bn.types.Type.bool()), ("value_2", bn.types.Type.int(1, False)), ("value_3", char_star), ("value_4", bn.types.Type.int(1, False)), ("value_5", bn.types.Type.char())])
- pretty_print_add_function(debug_info, 0x11c0, "local_parameters", None, None, bn.types.Type.void(), [("value_1", bn.types.Type.bool()), ("value_2", bn.types.Type.int(1, False)), ("value_3", char_star), ("value_4", bn.types.Type.int(1, False)), ("value_5", bn.types.Type.char())])
+ print("Adding functions")
+ char_star = bv.parse_type_string("char*")[0]
+ pretty_print_add_function(debug_info, 0x1129, "no_return_type_no_parameters", None, None, bn.types.Type.void(), None)
+ pretty_print_add_function(
+ debug_info, 0x1134, "used_parameter", None, None, bn.types.Type.bool(), [("value", bn.types.Type.bool())]
+ )
+ pretty_print_add_function(
+ debug_info, 0x1155, "unused_parameters", None, None, bn.types.Type.int(4, True),
+ [("value_1", bn.types.Type.bool()), ("value_2", bn.types.Type.int(4, True)), ("value_3", char_star)]
+ )
+ pretty_print_add_function(
+ debug_info, 0x1170, "used_and_unused_parameters_1", None, None, bn.types.Type.int(4, True),
+ [("value_1", bn.types.Type.int(4, True)), ("value_2", bn.types.Type.int(4, True)), ("value_3", char_star),
+ ("value_4", bn.types.Type.bool())]
+ )
+ pretty_print_add_function(
+ debug_info, 0x1191, "used_and_unused_parameters_2", None, None, bn.types.Type.int(1, False),
+ [("value_1", bn.types.Type.bool()), ("value_2", bn.types.Type.int(1, False)), ("value_3", char_star),
+ ("value_4", bn.types.Type.int(1, False)), ("value_5", bn.types.Type.char())]
+ )
+ pretty_print_add_function(
+ debug_info, 0x11c0, "local_parameters", None, None, bn.types.Type.void(), [("value_1", bn.types.Type.bool()),
+ ("value_2", bn.types.Type.int(1, False)),
+ ("value_3", char_star),
+ ("value_4", bn.types.Type.int(1, False)),
+ ("value_5", bn.types.Type.char())]
+ )
parser = bn.debuginfo.DebugInfoParser.register("test debug info parser", is_valid, parse_info)
print(f"Registered parser: {parser.name}")
-
# The above is all that is needed for a DebugInfo plugin
# The below serves to test the correctness of (the Python bindings' implementation of) debug info parsers' functionality.
-
bn.debuginfo.DebugInfoParser.register("dummy extra debug parser 1", lambda bv: False, lambda di, bv: None)
-bn.debuginfo.DebugInfoParser.register("dummy extra debug parser 2", lambda bv: bv.view_type != "Raw", lambda di, bv: None)
+bn.debuginfo.DebugInfoParser.register(
+ "dummy extra debug parser 2", lambda bv: bv.view_type != "Raw", lambda di, bv: None
+)
# Test fetching parser list and fetching by name
print(f"Availible parsers: {len(list(bn.debuginfo.DebugInfoParser))}")
for p in bn.debuginfo.DebugInfoParser:
- if p == parser:
- print(f" {bn.debuginfo.DebugInfoParser[p.name].name} (the one we just registered)")
- else:
- print(f" {bn.debuginfo.DebugInfoParser[p.name].name}")
+ if p == parser:
+ print(f" {bn.debuginfo.DebugInfoParser[p.name].name} (the one we just registered)")
+ else:
+ print(f" {bn.debuginfo.DebugInfoParser[p.name].name}")
# Test calling our `is_valid` callback
bv = bn.open_view(filename, options={"analysis.experimental.parseDebugInfo": False})
if parser.is_valid_for_view(bv):
- print("Parser is valid")
+ print("Parser is valid")
else:
- print("Parser is NOT valid!")
- quit()
-
+ print("Parser is NOT valid!")
+ quit()
# Test getting list of valid parsers, and DebugInfoParser's repr
print("")
for p in bn.debuginfo.DebugInfoParser.get_parsers_for_view(bv):
- print(f"`{p.name}` is valid for `{bv}`")
+ print(f"`{p.name}` is valid for `{bv}`")
print("")
# Test calling our `parse_info` callback
@@ -219,32 +243,31 @@ print("\nEach of the following pairs of prints should be the same\n")
print("All types:")
for name, t in debug_info.types:
- print(f" \"{name}\": `{t}`")
+ print(f" \"{name}\": `{t}`")
print("Types from parser:")
for name, t in debug_info.types_from_parser(parser.name):
- print(f" \"{name}\": `{t}`")
+ print(f" \"{name}\": `{t}`")
print("")
print("All functions:")
for func in debug_info.functions:
- print(f" {func}")
+ print(f" {func}")
print("Functions from parser:")
for func in debug_info.functions_from_parser(parser.name):
- print(f" {func}")
+ print(f" {func}")
print("")
print("All data variables:")
for data_var in debug_info.data_variables:
- print(f" {data_var}")
+ print(f" {data_var}")
print("Data variables from parser:")
for data_var in debug_info.data_variables_from_parser(parser.name):
- print(f" {data_var}")
-
+ print(f" {data_var}")
print("Appling debug info!")
bv.apply_debug_info(debug_info)
@@ -254,16 +277,16 @@ bv.update_analysis_and_wait()
print("")
print("Types:")
for name, t in debug_info.types:
- print(f" {bv.get_type_by_name(name)}")
+ print(f" {bv.get_type_by_name(name)}")
print("")
print("Functions:")
for func in debug_info.functions:
- print(f" {bv.get_function_at(func.address)}")
+ print(f" {bv.get_function_at(func.address)}")
print("")
print("Data variables:")
for data_var in debug_info.data_variables:
- print(f" {bv.get_data_var_at(data_var.address)}")
+ print(f" {bv.get_data_var_at(data_var.address)}")
diff --git a/python/examples/export_svg.py b/python/examples/export_svg.py
index c96873e1..8166b27a 100755
--- a/python/examples/export_svg.py
+++ b/python/examples/export_svg.py
@@ -12,119 +12,126 @@ from binaryninja.enums import MessageBoxButtonSet, MessageBoxIcon, MessageBoxBut
from binaryninja.function import DisassemblySettings
from binaryninja.plugin import PluginCommand
-colors = {'green': [162, 217, 175], 'red': [222, 143, 151], 'blue': [128, 198, 233], 'cyan': [142, 230, 237], 'lightCyan': [
- 176, 221, 228], 'orange': [237, 189, 129], 'yellow': [237, 223, 179], 'magenta': [218, 196, 209], 'none': [74, 74, 74],
- 'disabled': [144, 144, 144]}
-
-escape_table = {
- "'": "&#39;",
- ">": "&#62;",
- "<": "&#60;",
- '"': "&#34;",
- ' ': "&#160;"
+colors = {
+ 'green': [162, 217, 175], 'red': [222, 143, 151], 'blue': [128, 198, 233], 'cyan': [142, 230, 237],
+ 'lightCyan': [176, 221, 228], 'orange': [237, 189, 129], 'yellow': [237, 223, 179], 'magenta': [218, 196, 209],
+ 'none': [74, 74, 74], 'disabled': [144, 144, 144]
}
+escape_table = {"'": "&#39;", ">": "&#62;", "<": "&#60;", '"': "&#34;", ' ': "&#160;"}
+
def escape(toescape):
- # handle extended unicode
- toescape = toescape.encode('ascii', 'xmlcharrefreplace')
- # still escape the basics
- if sys.version_info[0] == 3:
- return ''.join(escape_table.get(chr(i), chr(i)) for i in toescape)
- else:
- return ''.join(escape_table.get(i, i) for i in toescape)
+ # handle extended unicode
+ toescape = toescape.encode('ascii', 'xmlcharrefreplace')
+ # still escape the basics
+ if sys.version_info[0] == 3:
+ return ''.join(escape_table.get(chr(i), chr(i)) for i in toescape)
+ else:
+ return ''.join(escape_table.get(i, i) for i in toescape)
def save_svg(bv, function):
- sym = bv.get_symbol_at(function.start)
- if sym:
- offset = sym.name
- else:
- offset = "%x" % function.start
- path = Path(os.path.dirname(bv.file.filename))
- origname = os.path.basename(bv.file.filename)
- filename = path / f'binaryninja-{origname}-{offset}.html'
+ sym = bv.get_symbol_at(function.start)
+ if sym:
+ offset = sym.name
+ else:
+ offset = "%x" % function.start
+ path = Path(os.path.dirname(bv.file.filename))
+ origname = os.path.basename(bv.file.filename)
+ filename = path / f'binaryninja-{origname}-{offset}.html'
- functionChoice = TextLineField("Blank to accept default")
- # TODO: implement linear disassembly settings and output
- modeChoices = ["Graph"]
- modeChoiceField = ChoiceField("Mode", modeChoices)
- if Settings().get_bool('ui.debugMode'):
- formChoices = ["Assembly", "Lifted IL", "LLIL", "LLIL SSA", "Mapped Medium", "Mapped Medium SSA", "MLIL", "MLIL SSA", "HLIL", "HLIL SSA"]
- formChoiceField = ChoiceField("Form", formChoices)
- else:
- formChoices = ["Assembly", "LLIL", "MLIL", "HLIL"]
- formChoiceField = ChoiceField("Form", formChoices)
+ functionChoice = TextLineField("Blank to accept default")
+ # TODO: implement linear disassembly settings and output
+ modeChoices = ["Graph"]
+ modeChoiceField = ChoiceField("Mode", modeChoices)
+ if Settings().get_bool('ui.debugMode'):
+ formChoices = [
+ "Assembly", "Lifted IL", "LLIL", "LLIL SSA", "Mapped Medium", "Mapped Medium SSA", "MLIL", "MLIL SSA", "HLIL",
+ "HLIL SSA"
+ ]
+ formChoiceField = ChoiceField("Form", formChoices)
+ else:
+ formChoices = ["Assembly", "LLIL", "MLIL", "HLIL"]
+ formChoiceField = ChoiceField("Form", formChoices)
- showOpcodes = ChoiceField("Show Opcodes", ["Yes", "No"])
- showAddresses = ChoiceField("Show Addresses", ["Yes", "No"])
+ showOpcodes = ChoiceField("Show Opcodes", ["Yes", "No"])
+ showAddresses = ChoiceField("Show Addresses", ["Yes", "No"])
- saveFileChoices = SaveFileNameField("Output file", 'HTML files (*.html)', str(filename))
- if not get_form_input([f'Current Function: {offset}', functionChoice, formChoiceField, modeChoiceField, showOpcodes, showAddresses, saveFileChoices], "SVG Export") or saveFileChoices.result is None:
- return
- if saveFileChoices.result == '':
- outputfile = filename
- else:
- outputfile = saveFileChoices.result
- content = render_svg(function, offset, modeChoices[modeChoiceField.result], formChoices[formChoiceField.result], showOpcodes.result == 0, showAddresses.result == 0, origname)
- output = open(outputfile, 'w')
- output.write(content)
- output.close()
- result = show_message_box("Open SVG", "Would you like to view the exported SVG?",
- buttons=MessageBoxButtonSet.YesNoButtonSet, icon=MessageBoxIcon.QuestionIcon)
- if result == MessageBoxButtonResult.YesButton:
- # might need more testing, latest py3 on windows seems.... broken with these APIs relative to other platforms
- if sys.platform == 'win32':
- webbrowser.open(outputfile)
- else:
- webbrowser.open('file://' + str(outputfile))
+ saveFileChoices = SaveFileNameField("Output file", 'HTML files (*.html)', str(filename))
+ if not get_form_input([
+ f'Current Function: {offset}', functionChoice, formChoiceField, modeChoiceField, showOpcodes, showAddresses,
+ saveFileChoices
+ ], "SVG Export") or saveFileChoices.result is None:
+ return
+ if saveFileChoices.result == '':
+ outputfile = filename
+ else:
+ outputfile = saveFileChoices.result
+ content = render_svg(
+ function, offset, modeChoices[modeChoiceField.result], formChoices[formChoiceField.result], showOpcodes.result == 0,
+ showAddresses.result == 0, origname
+ )
+ output = open(outputfile, 'w')
+ output.write(content)
+ output.close()
+ result = show_message_box(
+ "Open SVG", "Would you like to view the exported SVG?", buttons=MessageBoxButtonSet.YesNoButtonSet,
+ icon=MessageBoxIcon.QuestionIcon
+ )
+ if result == MessageBoxButtonResult.YesButton:
+ # might need more testing, latest py3 on windows seems.... broken with these APIs relative to other platforms
+ if sys.platform == 'win32':
+ webbrowser.open(outputfile)
+ else:
+ webbrowser.open('file://' + str(outputfile))
def instruction_data_flow(function, address):
- # TODO: Extract data flow information
- length = function.view.get_instruction_length(address)
- func_bytes = function.view.read(address, length)
- if sys.version_info[0] == 3:
- hex = func_bytes.hex()
- else:
- hex = func_bytes.encode('hex')
- padded = ' '.join([hex[i:i + 2] for i in range(0, len(hex), 2)])
- return 'Opcode: {bytes}'.format(bytes=padded)
+ # TODO: Extract data flow information
+ length = function.view.get_instruction_length(address)
+ func_bytes = function.view.read(address, length)
+ if sys.version_info[0] == 3:
+ hex = func_bytes.hex()
+ else:
+ hex = func_bytes.encode('hex')
+ padded = ' '.join([hex[i:i + 2] for i in range(0, len(hex), 2)])
+ return 'Opcode: {bytes}'.format(bytes=padded)
def render_svg(function, offset, mode, form, showOpcodes, showAddresses, origname):
- settings = DisassemblySettings()
- if showOpcodes:
- settings.set_option(DisassemblyOption.ShowOpcode, True)
- if showAddresses:
- settings.set_option(DisassemblyOption.ShowAddress, True)
- if form == "LLIL":
- graph_type = FunctionGraphType.LowLevelILFunctionGraph
- elif form == "LLIL SSA":
- graph_type = FunctionGraphType.LowLevelILSSAFormFunctionGraph
- elif form == "Lifted IL":
- graph_type = FunctionGraphType.LiftedILFunctionGraph
- elif form == "Mapped Medium":
- graph_type = FunctionGraphType.MappedMediumLevelILFunctionGraph
- elif form == "Mapped Medium SSA":
- graph_type = FunctionGraphType.MappedMediumLevelILSSAFormFunctionGraph
- elif form == "MLIL":
- graph_type = FunctionGraphType.MediumLevelILFunctionGraph
- elif form == "MLIL SSA":
- graph_type = FunctionGraphType.MediumLevelILSSAFormFunctionGraph
- elif form == "HLIL":
- graph_type = FunctionGraphType.HighLevelILFunctionGraph
- elif form == "HLIL SSA":
- graph_type = FunctionGraphType.HighLevelILSSAFormFunctionGraph
- else:
- graph_type = FunctionGraphType.NormalFunctionGraph
- graph = function.create_graph(graph_type=graph_type, settings=settings)
- graph.layout_and_wait()
- heightconst = 15
- ratio = 0.48
- widthconst = heightconst * ratio
+ settings = DisassemblySettings()
+ if showOpcodes:
+ settings.set_option(DisassemblyOption.ShowOpcode, True)
+ if showAddresses:
+ settings.set_option(DisassemblyOption.ShowAddress, True)
+ if form == "LLIL":
+ graph_type = FunctionGraphType.LowLevelILFunctionGraph
+ elif form == "LLIL SSA":
+ graph_type = FunctionGraphType.LowLevelILSSAFormFunctionGraph
+ elif form == "Lifted IL":
+ graph_type = FunctionGraphType.LiftedILFunctionGraph
+ elif form == "Mapped Medium":
+ graph_type = FunctionGraphType.MappedMediumLevelILFunctionGraph
+ elif form == "Mapped Medium SSA":
+ graph_type = FunctionGraphType.MappedMediumLevelILSSAFormFunctionGraph
+ elif form == "MLIL":
+ graph_type = FunctionGraphType.MediumLevelILFunctionGraph
+ elif form == "MLIL SSA":
+ graph_type = FunctionGraphType.MediumLevelILSSAFormFunctionGraph
+ elif form == "HLIL":
+ graph_type = FunctionGraphType.HighLevelILFunctionGraph
+ elif form == "HLIL SSA":
+ graph_type = FunctionGraphType.HighLevelILSSAFormFunctionGraph
+ else:
+ graph_type = FunctionGraphType.NormalFunctionGraph
+ graph = function.create_graph(graph_type=graph_type, settings=settings)
+ graph.layout_and_wait()
+ heightconst = 15
+ ratio = 0.48
+ widthconst = heightconst * ratio
- output = '''<html>
+ output = '''<html>
<head>
<style type="text/css">
@import url(https://fonts.googleapis.com/css?family=Source+Code+Pro);
@@ -205,7 +212,7 @@ def render_svg(function, offset, mode, form, showOpcodes, showAddresses, orignam
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
</head>
'''
- output += '''<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="{width}" height="{height}">
+ output += '''<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="{width}" height="{height}">
<defs>
<marker id="arrow-TrueBranch" class="arrow TrueBranch" viewBox="0 0 10 10" refX="10" refY="5" markerUnits="strokeWidth" markerWidth="8" markerHeight="6" orient="auto">
<path d="M 0 0 L 10 5 L 0 10 z" />
@@ -221,83 +228,87 @@ def render_svg(function, offset, mode, form, showOpcodes, showAddresses, orignam
</marker>
</defs>
'''.format(width=graph.width * widthconst + 20, height=graph.height * heightconst + 20)
- output += ''' <g id="functiongraph0" class="functiongraph">
+ output += ''' <g id="functiongraph0" class="functiongraph">
<title>Function Graph 0</title>
'''
- edges = ''
- for i, block in enumerate(graph):
+ edges = ''
+ for i, block in enumerate(graph):
- # Calculate basic block location and coordinates
- x = ((block.x) * widthconst)
- y = ((block.y) * heightconst)
- width = ((block.width) * widthconst)
- height = ((block.height) * heightconst)
+ # Calculate basic block location and coordinates
+ x = ((block.x) * widthconst)
+ y = ((block.y) * heightconst)
+ width = ((block.width) * widthconst)
+ height = ((block.height) * heightconst)
- # Render block
- output += ' <g id="basicblock{i}">\n'.format(i=i)
- output += ' <title>Basic Block {i}</title>\n'.format(i=i)
- rgb = colors['none']
- try:
- bb = block.basic_block
- if hasattr(bb.highlight, 'color'):
- color_code = bb.highlight.color
- color_str = bb.highlight._standard_color_to_str(color_code)
- if color_str in colors:
- rgb = colors[color_str]
- else:
- rgb = [bb.highlight.red, bb.highlight.green, bb.highlight.blue]
- except:
- pass
- output += ' <rect class="basicblock" x="{x}" y="{y}" fill-opacity="0.4" height="{height}" width="{width}" fill="rgb({r},{g},{b})"/>\n'.format(
- x=x, y=y, width=width + 16, height=height + 12, r=rgb[0], g=rgb[1], b=rgb[2])
+ # Render block
+ output += ' <g id="basicblock{i}">\n'.format(i=i)
+ output += ' <title>Basic Block {i}</title>\n'.format(i=i)
+ rgb = colors['none']
+ try:
+ bb = block.basic_block
+ if hasattr(bb.highlight, 'color'):
+ color_code = bb.highlight.color
+ color_str = bb.highlight._standard_color_to_str(color_code)
+ if color_str in colors:
+ rgb = colors[color_str]
+ else:
+ rgb = [bb.highlight.red, bb.highlight.green, bb.highlight.blue]
+ except:
+ pass
+ output += ' <rect class="basicblock" x="{x}" y="{y}" fill-opacity="0.4" height="{height}" width="{width}" fill="rgb({r},{g},{b})"/>\n'.format(
+ x=x, y=y, width=width + 16, height=height + 12, r=rgb[0], g=rgb[1], b=rgb[2]
+ )
- # Render instructions, unfortunately tspans don't allow copying/pasting more
- # than one line at a time, need SVG 1.2 textarea tags for that it looks like
+ # Render instructions, unfortunately tspans don't allow copying/pasting more
+ # than one line at a time, need SVG 1.2 textarea tags for that it looks like
- output += ' <text x="{x}" y="{y}">\n'.format(
- x=x, y=y + (i + 1) * heightconst)
- for i, line in enumerate(block.lines):
- output += ' <tspan id="instr-{address}" x="{x}" y="{y}">'.format(
- x=x + 6, y=y + 6 + (i + 0.7) * heightconst, address=hex(line.address)[:-1])
- hover = instruction_data_flow(function, line.address)
- output += '<title>{hover}</title>'.format(hover=hover)
- for token in line.tokens:
- # TODO: add hover for hex, function, and reg tokens
- output += '<tspan class="{tokentype}">{text}</tspan>'.format(
- text=escape(token.text), tokentype=InstructionTextTokenType(token.type).name)
- output += '</tspan>\n'
- output += ' </text>\n'
- output += ' </g>\n'
+ output += ' <text x="{x}" y="{y}">\n'.format(x=x, y=y + (i+1) * heightconst)
+ for i, line in enumerate(block.lines):
+ output += ' <tspan id="instr-{address}" x="{x}" y="{y}">'.format(
+ x=x + 6, y=y + 6 + (i+0.7) * heightconst, address=hex(line.address)[:-1]
+ )
+ hover = instruction_data_flow(function, line.address)
+ output += '<title>{hover}</title>'.format(hover=hover)
+ for token in line.tokens:
+ # TODO: add hover for hex, function, and reg tokens
+ output += '<tspan class="{tokentype}">{text}</tspan>'.format(
+ text=escape(token.text), tokentype=InstructionTextTokenType(token.type).name
+ )
+ output += '</tspan>\n'
+ output += ' </text>\n'
+ output += ' </g>\n'
- # Edges are rendered in a seperate chunk so they have priority over the
- # basic blocks or else they'd render below them
+ # Edges are rendered in a seperate chunk so they have priority over the
+ # basic blocks or else they'd render below them
- for edge in block.outgoing_edges:
- points = ""
- x, y = edge.points[0]
- points += str(x * widthconst) + "," + \
- str(y * heightconst + 12) + " "
- for x, y in edge.points[1:-1]:
- points += str(x * widthconst) + "," + \
- str(y * heightconst) + " "
- x, y = edge.points[-1]
- points += str(x * widthconst) + "," + \
- str(y * heightconst + 0) + " "
- if edge.back_edge:
- edges += ' <polyline class="back_edge {type}" points="{points}" marker-end="url(#arrow-{type})"/>\n'.format(
- type=BranchType(edge.type).name, points=points)
- else:
- edges += ' <polyline class="edge {type}" points="{points}" marker-end="url(#arrow-{type})"/>\n'.format(
- type=BranchType(edge.type).name, points=points)
- output += ' ' + edges + '\n'
- output += ' </g>\n'
- output += '</svg>'
+ for edge in block.outgoing_edges:
+ points = ""
+ x, y = edge.points[0]
+ points += str(x * widthconst) + "," + \
+ str(y * heightconst + 12) + " "
+ for x, y in edge.points[1:-1]:
+ points += str(x * widthconst) + "," + \
+ str(y * heightconst) + " "
+ x, y = edge.points[-1]
+ points += str(x * widthconst) + "," + \
+ str(y * heightconst + 0) + " "
+ if edge.back_edge:
+ edges += ' <polyline class="back_edge {type}" points="{points}" marker-end="url(#arrow-{type})"/>\n'.format(
+ type=BranchType(edge.type).name, points=points
+ )
+ else:
+ edges += ' <polyline class="edge {type}" points="{points}" marker-end="url(#arrow-{type})"/>\n'.format(
+ type=BranchType(edge.type).name, points=points
+ )
+ output += ' ' + edges + '\n'
+ output += ' </g>\n'
+ output += '</svg>'
- output += '<p>This CFG generated by <a href="https://binary.ninja/">Binary Ninja</a> from {filename} on {timestring} showing {function} as {form}.</p>'.format(
- filename=origname, timestring=time.strftime("%c"), function=offset, form=form)
- output += '</html>'
- return output
+ output += '<p>This CFG generated by <a href="https://binary.ninja/">Binary Ninja</a> from {filename} on {timestring} showing {function} as {form}.</p>'.format(
+ filename=origname, timestring=time.strftime("%c"), function=offset, form=form
+ )
+ output += '</html>'
+ return output
-PluginCommand.register_for_function(
- "Export to SVG", "Exports an SVG of the current function", save_svg)
+PluginCommand.register_for_function("Export to SVG", "Exports an SVG of the current function", save_svg)
diff --git a/python/examples/helloglobalarea.py b/python/examples/helloglobalarea.py
index d4b1b5ed..b0ac8ede 100644
--- a/python/examples/helloglobalarea.py
+++ b/python/examples/helloglobalarea.py
@@ -29,6 +29,7 @@ from PySide6.QtGui import QImage, QPixmap, QPainter, QFont, QColor
instance_id = 0
+
# Global area widgets must derive from GlobalAreaWidget, not QWidget. GlobalAreaWidget is a QWidget but
# provides callbacks for global area events, and must be created with a title.
class HelloGlobalAreaWidget(GlobalAreaWidget):
@@ -77,6 +78,7 @@ class HelloGlobalAreaWidget(GlobalAreaWidget):
def contextMenuEvent(self, event):
self.m_contextMenuManager.show(self.m_menu, self.actionHandler)
+
# Register the global area widget constructor with Binary Ninja. This will create a new
# global area widget for each window. The callback function receives a `UIContext` object
# for identifying the window.
diff --git a/python/examples/hellopane.py b/python/examples/hellopane.py
index 2b9fbe29..06651a6f 100644
--- a/python/examples/hellopane.py
+++ b/python/examples/hellopane.py
@@ -29,6 +29,7 @@ from PySide6.QtGui import QImage, QPixmap, QPainter, QFont, QColor
instance_id = 0
+
# Class to handle UI context notifications. This will be used to listen for view and address
# changes and update the pane accordingly.
class HelloNotifications(UIContextNotification):
@@ -51,6 +52,7 @@ class HelloNotifications(UIContextNotification):
def OnAddressChange(self, context, frame, view, location):
self.widget.updateState()
+
# Pane widget itself. This can be any QWidget.
class HelloPaneWidget(QWidget, UIContextNotification):
def __init__(self, data):
@@ -120,6 +122,9 @@ class HelloPaneWidget(QWidget, UIContextNotification):
def canCreatePane(context):
return context.context and context.binaryView
+
UIAction.registerAction("Hello Pane")
-UIActionHandler.globalActions().bindAction("Hello Pane", UIAction(HelloPaneWidget.createPane, HelloPaneWidget.canCreatePane))
+UIActionHandler.globalActions().bindAction(
+ "Hello Pane", UIAction(HelloPaneWidget.createPane, HelloPaneWidget.canCreatePane)
+)
Menu.mainMenu("Tools").addAction("Hello Pane", "Hello")
diff --git a/python/examples/hellosidebar.py b/python/examples/hellosidebar.py
index fe7cbae2..69721d4c 100644
--- a/python/examples/hellosidebar.py
+++ b/python/examples/hellosidebar.py
@@ -29,6 +29,7 @@ from PySide6.QtGui import QImage, QPixmap, QPainter, QFont, QColor
instance_id = 0
+
# Sidebar widgets must derive from SidebarWidget, not QWidget. SidebarWidget is a QWidget but
# provides callbacks for sidebar events, and must be created with a title.
class HelloSidebarWidget(SidebarWidget):
@@ -77,6 +78,7 @@ class HelloSidebarWidget(SidebarWidget):
def contextMenuEvent(self, event):
self.m_contextMenuManager.show(self.m_menu, self.actionHandler)
+
class HelloSidebarWidgetType(SidebarWidgetType):
def __init__(self):
# Sidebar icons are 28x28 points. Should be at least 56x56 pixels for
@@ -102,6 +104,7 @@ class HelloSidebarWidgetType(SidebarWidgetType):
# widget is visible and the BinaryView becomes active.
return HelloSidebarWidget("Hello", frame, data)
+
# Register the sidebar widget type with Binary Ninja. This will make it appear as an icon in the
# sidebar and the `createWidget` method will be called when a widget is required.
Sidebar.addSidebarWidgetType(HelloSidebarWidgetType())
diff --git a/python/examples/instruction_iterator.py b/python/examples/instruction_iterator.py
index 9a5d864a..b5cf426f 100644
--- a/python/examples/instruction_iterator.py
+++ b/python/examples/instruction_iterator.py
@@ -32,7 +32,6 @@ binja.log_info("START: 0x%x" % bv.start)
binja.log_info("ENTRY: 0x%x" % bv.entry_point)
binja.log_info("ARCH: %s" % bv.arch.name)
binja.log_info("\n-------- Function List --------")
-
""" print all the functions, their basic blocks, and their il instructions """
for func in bv.functions:
binja.log_info(repr(func))
@@ -41,8 +40,6 @@ for func in bv.functions:
for insn in block:
binja.log_info("\t\t{0}".format(insn))
-
-
""" print all the functions, their basic blocks, and their mc instructions """
for func in bv.functions:
binja.log_info(repr(func))
diff --git a/python/examples/jump_table.py b/python/examples/jump_table.py
index 6ee60ce5..2132c950 100644
--- a/python/examples/jump_table.py
+++ b/python/examples/jump_table.py
@@ -50,13 +50,15 @@ def find_jump_table(bv, addr):
# Collect the branch targets for any tables referenced by the clicked instruction
branches = []
for token in tokens:
- if InstructionTextTokenType(token.type) == InstructionTextTokenType.PossibleAddressToken: # Table addresses will be a "possible address" token
+ if InstructionTextTokenType(
+ token.type
+ ) == InstructionTextTokenType.PossibleAddressToken: # Table addresses will be a "possible address" token
tbl = token.value
print("Found possible table at 0x%x" % tbl)
i = 0
while True:
# Read the next pointer from the table
- data = bv.read(tbl + (i * addrsize), addrsize)
+ data = bv.read(tbl + (i*addrsize), addrsize)
if len(data) == addrsize:
if addrsize == 4:
ptr = struct.unpack("<I", data)[0]
diff --git a/python/examples/linear_mlil.py b/python/examples/linear_mlil.py
index 9be79ad1..e4df1765 100644
--- a/python/examples/linear_mlil.py
+++ b/python/examples/linear_mlil.py
@@ -1,5 +1,5 @@
# Copyright (c) 2019-2022 Vector 35 Inc
-#
+#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
@@ -46,16 +46,28 @@ class LinearMLILView(TokenizedTextView):
# Sort basic blocks by IL instruction index
blocks = il.basic_blocks
- blocks.sort(key = lambda block: block.start)
+ blocks.sort(key=lambda block: block.start)
# Function header
result = []
- result.append(LinearDisassemblyLine(LinearDisassemblyLineType.FunctionHeaderStartLineType,
- self.function, None, DisassemblyTextLine([], self.function.start)))
- result.append(LinearDisassemblyLine(LinearDisassemblyLineType.FunctionHeaderLineType,
- self.function, None, DisassemblyTextLine(self.function.type_tokens, self.function.start)))
- result.append(LinearDisassemblyLine(LinearDisassemblyLineType.FunctionHeaderEndLineType,
- self.function, None, DisassemblyTextLine([], self.function.start)))
+ result.append(
+ LinearDisassemblyLine(
+ LinearDisassemblyLineType.FunctionHeaderStartLineType, self.function, None,
+ DisassemblyTextLine([], self.function.start)
+ )
+ )
+ result.append(
+ LinearDisassemblyLine(
+ LinearDisassemblyLineType.FunctionHeaderLineType, self.function, None,
+ DisassemblyTextLine(self.function.type_tokens, self.function.start)
+ )
+ )
+ result.append(
+ LinearDisassemblyLine(
+ LinearDisassemblyLineType.FunctionHeaderEndLineType, self.function, None,
+ DisassemblyTextLine([], self.function.start)
+ )
+ )
# Display IL instructions in order
lastAddr = self.function.start
@@ -64,20 +76,27 @@ class LinearMLILView(TokenizedTextView):
for block in il:
if lastBlock is not None:
# Blank line between basic blocks
- result.append(LinearDisassemblyLine(LinearDisassemblyLineType.CodeDisassemblyLineType,
- self.function, block, DisassemblyTextLine([], lastAddr)))
+ result.append(
+ LinearDisassemblyLine(
+ LinearDisassemblyLineType.CodeDisassemblyLineType, self.function, block, DisassemblyTextLine([], lastAddr)
+ )
+ )
for i in block:
lines, length = renderer.get_disassembly_text(i.instr_index)
lastAddr = i.address
lineIndex = 0
for line in lines:
- result.append(LinearDisassemblyLine(LinearDisassemblyLineType.CodeDisassemblyLineType,
- self.function, block, line))
+ result.append(
+ LinearDisassemblyLine(LinearDisassemblyLineType.CodeDisassemblyLineType, self.function, block, line)
+ )
lineIndex += 1
lastBlock = block
- result.append(LinearDisassemblyLine(LinearDisassemblyLineType.FunctionEndLineType,
- self.function, lastBlock, DisassemblyTextLine([], lastAddr)))
+ result.append(
+ LinearDisassemblyLine(
+ LinearDisassemblyLineType.FunctionEndLineType, self.function, lastBlock, DisassemblyTextLine([], lastAddr)
+ )
+ )
return result
diff --git a/python/examples/mappedview.py b/python/examples/mappedview.py
index 18bef17f..645096f5 100644
--- a/python/examples/mappedview.py
+++ b/python/examples/mappedview.py
@@ -35,13 +35,14 @@ import traceback
use_default_loader_settings = True
+
class MappedView(BinaryView):
name = "Mapped (Python)"
long_name = "Mapped (Python)"
load_address = 0x100000
def __init__(self, data):
- BinaryView.__init__(self, parent_view = data, file_metadata = data.file)
+ BinaryView.__init__(self, parent_view=data, file_metadata=data.file)
@staticmethod
def is_valid_for_data(data):
@@ -74,7 +75,10 @@ class MappedView(BinaryView):
load_settings = registered_view.get_default_load_settings_for_data(view)
# Specify default load settings that can be overridden (from the UI).
- overrides = ["loader.architecture", "loader.platform", "loader.entryPointOffset", "loader.imageBase", "loader.segments", "loader.sections"]
+ overrides = [
+ "loader.architecture", "loader.platform", "loader.entryPointOffset", "loader.imageBase", "loader.segments",
+ "loader.sections"
+ ]
for override in overrides:
if load_settings.contains(override):
load_settings.update_property(override, json.dumps({'readOnly': False}))
@@ -84,11 +88,12 @@ class MappedView(BinaryView):
load_settings.update_property("loader.entryPointOffset", json.dumps({'default': 0}))
# Specify additional custom settings.
- load_settings.register_setting("loader.my_custom_arch.customLoadSetting",
- '{"title" : "My Custom Load Setting",\
+ load_settings.register_setting(
+ "loader.my_custom_arch.customLoadSetting", '{"title" : "My Custom Load Setting",\
"type" : "boolean",\
"default" : false,\
- "description" : "My custom load setting description."}')
+ "description" : "My custom load setting description."}'
+ )
return load_settings
@@ -116,7 +121,7 @@ class MappedView(BinaryView):
if load_settings is None:
if self.parse_only is True:
self.arch = Architecture['x86'] # type: ignore
- self.platform = Architecture['x86'].standalone_platform # type: ignore
+ self.platform = Architecture['x86'].standalone_platform # type: ignore
assert self.parent_view is not None
self.add_auto_segment(0, len(self.parent_view), 0, len(self.parent_view), SegmentFlag.SegmentReadable)
return True
@@ -126,10 +131,13 @@ class MappedView(BinaryView):
load_settings = self.__class__.get_load_settings_for_data(self.parent_view)
arch = load_settings.get_string("loader.architecture", self)
- self.arch = Architecture[arch] # type: ignore
- self.platform = Architecture[arch].standalone_platform # type: ignore
+ self.arch = Architecture[arch] # type: ignore
+ self.platform = Architecture[arch].standalone_platform # type: ignore
self.load_address = load_settings.get_integer("loader.imageBase", self)
- self.add_auto_segment(self.load_address, len(self.parent_view), 0, len(self.parent_view), SegmentFlag.SegmentReadable | SegmentFlag.SegmentExecutable)
+ self.add_auto_segment(
+ self.load_address, len(self.parent_view), 0, len(self.parent_view),
+ SegmentFlag.SegmentReadable | SegmentFlag.SegmentExecutable
+ )
if load_settings.contains("loader.entryPointOffset"):
self.entry_point_offset = load_settings.get_integer("loader.entryPointOffset", self)
self.add_entry_point(self.load_address + self.entry_point_offset)
@@ -156,4 +164,5 @@ class MappedView(BinaryView):
def perform_get_address_size(self):
return self.arch.address_size
+
MappedView.register()
diff --git a/python/examples/nds.py b/python/examples/nds.py
index e7192abf..7b53c31f 100644
--- a/python/examples/nds.py
+++ b/python/examples/nds.py
@@ -29,88 +29,92 @@ import traceback
def crc16(data):
- crc = 0xffff
- for ch in data:
- crc ^= ord(ch)
- for bit in range(0, 8):
- if (crc & 1) == 1:
- crc = (crc >> 1) ^ 0xa001
- else:
- crc >>= 1
- return crc
+ crc = 0xffff
+ for ch in data:
+ crc ^= ord(ch)
+ for bit in range(0, 8):
+ if (crc & 1) == 1:
+ crc = (crc >> 1) ^ 0xa001
+ else:
+ crc >>= 1
+ return crc
class DSView(BinaryView):
- def __init__(self, data):
- BinaryView.__init__(self, file_metadata = data.file, parent_view = data)
- self.raw = data
+ def __init__(self, data):
+ BinaryView.__init__(self, file_metadata=data.file, parent_view=data)
+ self.raw = data
- @staticmethod
- def is_valid_for_data(data):
- hdr = data.read(0, 0x160)
- if len(hdr) < 0x160:
- return False
- if struct.unpack("<H", hdr[0x15e:0x160])[0] != crc16(hdr[0:0x15e]):
- return False
- if struct.unpack("<H", hdr[0x15c:0x15e])[0] != crc16(hdr[0xc0:0x15c]):
- return False
- return True
+ @staticmethod
+ def is_valid_for_data(data):
+ hdr = data.read(0, 0x160)
+ if len(hdr) < 0x160:
+ return False
+ if struct.unpack("<H", hdr[0x15e:0x160])[0] != crc16(hdr[0:0x15e]):
+ return False
+ if struct.unpack("<H", hdr[0x15c:0x15e])[0] != crc16(hdr[0xc0:0x15c]):
+ return False
+ return True
- def init_common(self):
- self.platform = Architecture["armv7"].standalone_platform # type: ignore
- self.hdr = self.raw.read(0, 0x160)
+ def init_common(self):
+ self.platform = Architecture["armv7"].standalone_platform # type: ignore
+ self.hdr = self.raw.read(0, 0x160)
- def init_arm9(self):
- try:
- self.init_common()
- self.arm9_offset = struct.unpack("<L", self.hdr[0x20:0x24])[0]
- self.arm_entry_addr = struct.unpack("<L", self.hdr[0x24:0x28])[0]
- self.arm9_load_addr = struct.unpack("<L", self.hdr[0x28:0x2C])[0]
- self.arm9_size = struct.unpack("<L", self.hdr[0x2C:0x30])[0]
- self.add_auto_segment(self.arm9_load_addr, self.arm9_size, self.arm9_offset, self.arm9_size,
- SegmentFlag.SegmentReadable | SegmentFlag.SegmentExecutable)
- self.add_entry_point(Architecture['armv7'].standalone_platform, self.arm_entry_addr) # type: ignore
- return True
- except:
- log_error(traceback.format_exc())
- return False
+ def init_arm9(self):
+ try:
+ self.init_common()
+ self.arm9_offset = struct.unpack("<L", self.hdr[0x20:0x24])[0]
+ self.arm_entry_addr = struct.unpack("<L", self.hdr[0x24:0x28])[0]
+ self.arm9_load_addr = struct.unpack("<L", self.hdr[0x28:0x2C])[0]
+ self.arm9_size = struct.unpack("<L", self.hdr[0x2C:0x30])[0]
+ self.add_auto_segment(
+ self.arm9_load_addr, self.arm9_size, self.arm9_offset, self.arm9_size,
+ SegmentFlag.SegmentReadable | SegmentFlag.SegmentExecutable
+ )
+ self.add_entry_point(Architecture['armv7'].standalone_platform, self.arm_entry_addr) # type: ignore
+ return True
+ except:
+ log_error(traceback.format_exc())
+ return False
- def init_arm7(self):
- try:
- self.init_common()
- self.arm7_offset = struct.unpack("<L", self.hdr[0x30:0x34])[0]
- self.arm_entry_addr = struct.unpack("<L", self.hdr[0x34:0x38])[0]
- self.arm7_load_addr = struct.unpack("<L", self.hdr[0x38:0x3C])[0]
- self.arm7_size = struct.unpack("<L", self.hdr[0x3C:0x40])[0]
- self.add_auto_segment(self.arm7_load_addr, self.arm7_size, self.arm7_offset, self.arm7_size,
- SegmentFlag.SegmentReadable | SegmentFlag.SegmentExecutable)
- self.add_entry_point(Architecture['armv7'].standalone_platform, self.arm_entry_addr) # type: ignore
- return True
- except:
- log_error(traceback.format_exc())
- return False
+ def init_arm7(self):
+ try:
+ self.init_common()
+ self.arm7_offset = struct.unpack("<L", self.hdr[0x30:0x34])[0]
+ self.arm_entry_addr = struct.unpack("<L", self.hdr[0x34:0x38])[0]
+ self.arm7_load_addr = struct.unpack("<L", self.hdr[0x38:0x3C])[0]
+ self.arm7_size = struct.unpack("<L", self.hdr[0x3C:0x40])[0]
+ self.add_auto_segment(
+ self.arm7_load_addr, self.arm7_size, self.arm7_offset, self.arm7_size,
+ SegmentFlag.SegmentReadable | SegmentFlag.SegmentExecutable
+ )
+ self.add_entry_point(Architecture['armv7'].standalone_platform, self.arm_entry_addr) # type: ignore
+ return True
+ except:
+ log_error(traceback.format_exc())
+ return False
- def perform_is_executable(self):
- return True
+ def perform_is_executable(self):
+ return True
- def perform_get_entry_point(self):
- return self.arm_entry_addr
+ def perform_get_entry_point(self):
+ return self.arm_entry_addr
class DSARM9View(DSView):
- name = "DSARM9"
- long_name = "DS ARM9 ROM"
+ name = "DSARM9"
+ long_name = "DS ARM9 ROM"
- def init(self):
- return self.init_arm9()
+ def init(self):
+ return self.init_arm9()
class DSARM7View(DSView):
- name = "DSARM7"
- long_name = "DS ARM7 ROM"
+ name = "DSARM7"
+ long_name = "DS ARM7 ROM"
- def init(self):
- return self.init_arm7()
+ def init(self):
+ return self.init_arm7()
DSARM9View.register()
diff --git a/python/examples/nes.py b/python/examples/nes.py
index 7e24d16b..7c7857a4 100644
--- a/python/examples/nes.py
+++ b/python/examples/nes.py
@@ -29,43 +29,43 @@ from binaryninja.function import InstructionTextToken
from binaryninja.binaryview import BinaryView
from binaryninja.types import Symbol
from binaryninja.log import log_error
-from binaryninja.enums import (BranchType, InstructionTextTokenType,
- LowLevelILOperation, LowLevelILFlagCondition, FlagRole, SegmentFlag, SymbolType)
-
+from binaryninja.enums import (
+ BranchType, InstructionTextTokenType, LowLevelILOperation, LowLevelILFlagCondition, FlagRole, SegmentFlag, SymbolType
+)
InstructionNames = [
- "brk", "ora", None, None, None, "ora", "asl", None, # 0x00
- "php", "ora", "asl@", None, None, "ora", "asl", None, # 0x08
- "bpl", "ora", None, None, None, "ora", "asl", None, # 0x10
- "clc", "ora", None, None, None, "ora", "asl", None, # 0x18
- "jsr", "and", None, None, "bit", "and", "rol", None, # 0x20
- "plp", "and", "rol@", None, "bit", "and", "rol", None, # 0x28
- "bmi", "and", None, None, None, "and", "rol", None, # 0x30
- "sec", "and", None, None, None, "and", "rol", None, # 0x38
- "rti", "eor", None, None, None, "eor", "lsr", None, # 0x40
- "pha", "eor", "lsr@", None, "jmp", "eor", "lsr", None, # 0x48
- "bvc", "eor", None, None, None, "eor", "lsr", None, # 0x50
- "cli", "eor", None, None, None, "eor", "lsr", None, # 0x58
- "rts", "adc", None, None, None, "adc", "ror", None, # 0x60
- "pla", "adc", "ror@", None, "jmp", "adc", "ror", None, # 0x68
- "bvs", "adc", None, None, None, "adc", "ror", None, # 0x70
- "sei", "adc", None, None, None, "adc", "ror", None, # 0x78
- None, "sta", None, None, "sty", "sta", "stx", None, # 0x80
- "dey", None, "txa", None, "sty", "sta", "stx", None, # 0x88
- "bcc", "sta", None, None, "sty", "sta", "stx", None, # 0x90
- "tya", "sta", "txs", None, None, "sta", None, None, # 0x98
- "ldy", "lda", "ldx", None, "ldy", "lda", "ldx", None, # 0xa0
- "tay", "lda", "tax", None, "ldy", "lda", "ldx", None, # 0xa8
- "bcs", "lda", None, None, "ldy", "lda", "ldx", None, # 0xb0
- "clv", "lda", "tsx", None, "ldy", "lda", "ldx", None, # 0xb8
- "cpy", "cmp", None, None, "cpy", "cmp", "dec", None, # 0xc0
- "iny", "cmp", "dex", None, "cpy", "cmp", "dec", None, # 0xc8
- "bne", "cmp", None, None, None, "cmp", "dec", None, # 0xd0
- "cld", "cmp", None, None, None, "cmp", "dec", None, # 0xd8
- "cpx", "sbc", None, None, "cpx", "sbc", "inc", None, # 0xe0
- "inx", "sbc", "nop", None, "cpx", "sbc", "inc", None, # 0xe8
- "beq", "sbc", None, None, None, "sbc", "inc", None, # 0xf0
- "sed", "sbc", None, None, None, "sbc", "inc", None # 0xf8
+ "brk", "ora", None, None, None, "ora", "asl", None, # 0x00
+ "php", "ora", "asl@", None, None, "ora", "asl", None, # 0x08
+ "bpl", "ora", None, None, None, "ora", "asl", None, # 0x10
+ "clc", "ora", None, None, None, "ora", "asl", None, # 0x18
+ "jsr", "and", None, None, "bit", "and", "rol", None, # 0x20
+ "plp", "and", "rol@", None, "bit", "and", "rol", None, # 0x28
+ "bmi", "and", None, None, None, "and", "rol", None, # 0x30
+ "sec", "and", None, None, None, "and", "rol", None, # 0x38
+ "rti", "eor", None, None, None, "eor", "lsr", None, # 0x40
+ "pha", "eor", "lsr@", None, "jmp", "eor", "lsr", None, # 0x48
+ "bvc", "eor", None, None, None, "eor", "lsr", None, # 0x50
+ "cli", "eor", None, None, None, "eor", "lsr", None, # 0x58
+ "rts", "adc", None, None, None, "adc", "ror", None, # 0x60
+ "pla", "adc", "ror@", None, "jmp", "adc", "ror", None, # 0x68
+ "bvs", "adc", None, None, None, "adc", "ror", None, # 0x70
+ "sei", "adc", None, None, None, "adc", "ror", None, # 0x78
+ None, "sta", None, None, "sty", "sta", "stx", None, # 0x80
+ "dey", None, "txa", None, "sty", "sta", "stx", None, # 0x88
+ "bcc", "sta", None, None, "sty", "sta", "stx", None, # 0x90
+ "tya", "sta", "txs", None, None, "sta", None, None, # 0x98
+ "ldy", "lda", "ldx", None, "ldy", "lda", "ldx", None, # 0xa0
+ "tay", "lda", "tax", None, "ldy", "lda", "ldx", None, # 0xa8
+ "bcs", "lda", None, None, "ldy", "lda", "ldx", None, # 0xb0
+ "clv", "lda", "tsx", None, "ldy", "lda", "ldx", None, # 0xb8
+ "cpy", "cmp", None, None, "cpy", "cmp", "dec", None, # 0xc0
+ "iny", "cmp", "dex", None, "cpy", "cmp", "dec", None, # 0xc8
+ "bne", "cmp", None, None, None, "cmp", "dec", None, # 0xd0
+ "cld", "cmp", None, None, None, "cmp", "dec", None, # 0xd8
+ "cpx", "sbc", None, None, "cpx", "sbc", "inc", None, # 0xe0
+ "inx", "sbc", "nop", None, "cpx", "sbc", "inc", None, # 0xe8
+ "beq", "sbc", None, None, None, "sbc", "inc", None, # 0xf0
+ "sed", "sbc", None, None, None, "sbc", "inc", None # 0xf8
]
NONE = 0
@@ -91,103 +91,151 @@ ZERO_X_DEST = 19
ZERO_Y = 20
ZERO_Y_DEST = 21
InstructionOperandTypes = [
- NONE, IND_X, NONE, NONE, NONE, ZERO, ZERO_DEST, NONE, # 0x00
- NONE, IMMED, ACCUM, NONE, NONE, ABS, ABS_DEST, NONE, # 0x08
- REL, IND_Y, NONE, NONE, NONE, ZERO_X, ZERO_X_DEST, NONE, # 0x10
- NONE, ABS_Y, NONE, NONE, NONE, ABS_X, ABS_X_DEST, NONE, # 0x18
- ADDR, IND_X, NONE, NONE, ZERO, ZERO, ZERO_DEST, NONE, # 0x20
- NONE, IMMED, ACCUM, NONE, ABS, ABS, ABS_DEST, NONE, # 0x28
- REL, IND_Y, NONE, NONE, NONE, ZERO_X, ZERO_X_DEST, NONE, # 0x30
- NONE, ABS_Y, NONE, NONE, NONE, ABS_X, ABS_X_DEST, NONE, # 0x38
- NONE, IND_X, NONE, NONE, NONE, ZERO, ZERO_DEST, NONE, # 0x40
- NONE, IMMED, ACCUM, NONE, ADDR, ABS, ABS_DEST, NONE, # 0x48
- REL, IND_Y, NONE, NONE, NONE, ZERO_X, ZERO_X_DEST, NONE, # 0x50
- NONE, ABS_Y, NONE, NONE, NONE, ABS_X, ABS_X_DEST, NONE, # 0x58
- NONE, IND_X, NONE, NONE, NONE, ZERO, ZERO_DEST, NONE, # 0x60
- NONE, IMMED, ACCUM, NONE, IND, ABS, ABS_DEST, NONE, # 0x68
- REL, IND_Y, NONE, NONE, NONE, ZERO_X, ZERO_X_DEST, NONE, # 0x70
- NONE, ABS_Y, NONE, NONE, NONE, ABS_X, ABS_X_DEST, NONE, # 0x78
- NONE, IND_X_DEST, NONE, NONE, ZERO_DEST, ZERO_DEST, ZERO_DEST, NONE, # 0x80
- NONE, NONE, NONE, NONE, ABS_DEST, ABS_DEST, ABS_DEST, NONE, # 0x88
- REL, IND_Y_DEST, NONE, NONE, ZERO_X_DEST, ZERO_X_DEST, ZERO_Y_DEST, NONE, # 0x90
- NONE, ABS_Y_DEST, NONE, NONE, NONE, ABS_X_DEST, NONE, NONE, # 0x98
- IMMED, IND_X, IMMED, NONE, ZERO, ZERO, ZERO, NONE, # 0xa0
- NONE, IMMED, NONE, NONE, ABS, ABS, ABS, NONE, # 0xa8
- REL, IND_Y, NONE, NONE, ZERO_X, ZERO_X, ZERO_Y, NONE, # 0xb0
- NONE, ABS_Y, NONE, NONE, ABS_X, ABS_X, ABS_Y, NONE, # 0xb8
- IMMED, IND_X, NONE, NONE, ZERO, ZERO, ZERO_DEST, NONE, # 0xc0
- NONE, IMMED, NONE, NONE, ABS, ABS, ABS_DEST, NONE, # 0xc8
- REL, IND_Y, NONE, NONE, NONE, ZERO_X, ZERO_X_DEST, NONE, # 0xd0
- NONE, ABS_Y, NONE, NONE, NONE, ABS_X, ABS_X_DEST, NONE, # 0xd8
- IMMED, IND_X, NONE, NONE, ZERO, ZERO, ZERO_DEST, NONE, # 0xe0
- NONE, IMMED, NONE, NONE, ABS, ABS, ABS_DEST, NONE, # 0xe8
- REL, IND_Y, NONE, NONE, NONE, ZERO_X, ZERO_X_DEST, NONE, # 0xf0
- NONE, ABS_Y, NONE, NONE, NONE, ABS_X, ABS_X_DEST, NONE # 0xf8
+ NONE, IND_X, NONE, NONE, NONE, ZERO, ZERO_DEST, NONE, # 0x00
+ NONE, IMMED, ACCUM, NONE, NONE, ABS, ABS_DEST, NONE, # 0x08
+ REL, IND_Y, NONE, NONE, NONE, ZERO_X, ZERO_X_DEST, NONE, # 0x10
+ NONE, ABS_Y, NONE, NONE, NONE, ABS_X, ABS_X_DEST, NONE, # 0x18
+ ADDR, IND_X, NONE, NONE, ZERO, ZERO, ZERO_DEST, NONE, # 0x20
+ NONE, IMMED, ACCUM, NONE, ABS, ABS, ABS_DEST, NONE, # 0x28
+ REL, IND_Y, NONE, NONE, NONE, ZERO_X, ZERO_X_DEST, NONE, # 0x30
+ NONE, ABS_Y, NONE, NONE, NONE, ABS_X, ABS_X_DEST, NONE, # 0x38
+ NONE, IND_X, NONE, NONE, NONE, ZERO, ZERO_DEST, NONE, # 0x40
+ NONE, IMMED, ACCUM, NONE, ADDR, ABS, ABS_DEST, NONE, # 0x48
+ REL, IND_Y, NONE, NONE, NONE, ZERO_X, ZERO_X_DEST, NONE, # 0x50
+ NONE, ABS_Y, NONE, NONE, NONE, ABS_X, ABS_X_DEST, NONE, # 0x58
+ NONE, IND_X, NONE, NONE, NONE, ZERO, ZERO_DEST, NONE, # 0x60
+ NONE, IMMED, ACCUM, NONE, IND, ABS, ABS_DEST, NONE, # 0x68
+ REL, IND_Y, NONE, NONE, NONE, ZERO_X, ZERO_X_DEST, NONE, # 0x70
+ NONE, ABS_Y, NONE, NONE, NONE, ABS_X, ABS_X_DEST, NONE, # 0x78
+ NONE, IND_X_DEST, NONE, NONE, ZERO_DEST, ZERO_DEST, ZERO_DEST, NONE, # 0x80
+ NONE, NONE, NONE, NONE, ABS_DEST, ABS_DEST, ABS_DEST, NONE, # 0x88
+ REL, IND_Y_DEST, NONE, NONE, ZERO_X_DEST, ZERO_X_DEST, ZERO_Y_DEST, NONE, # 0x90
+ NONE, ABS_Y_DEST, NONE, NONE, NONE, ABS_X_DEST, NONE, NONE, # 0x98
+ IMMED, IND_X, IMMED, NONE, ZERO, ZERO, ZERO, NONE, # 0xa0
+ NONE, IMMED, NONE, NONE, ABS, ABS, ABS, NONE, # 0xa8
+ REL, IND_Y, NONE, NONE, ZERO_X, ZERO_X, ZERO_Y, NONE, # 0xb0
+ NONE, ABS_Y, NONE, NONE, ABS_X, ABS_X, ABS_Y, NONE, # 0xb8
+ IMMED, IND_X, NONE, NONE, ZERO, ZERO, ZERO_DEST, NONE, # 0xc0
+ NONE, IMMED, NONE, NONE, ABS, ABS, ABS_DEST, NONE, # 0xc8
+ REL, IND_Y, NONE, NONE, NONE, ZERO_X, ZERO_X_DEST, NONE, # 0xd0
+ NONE, ABS_Y, NONE, NONE, NONE, ABS_X, ABS_X_DEST, NONE, # 0xd8
+ IMMED, IND_X, NONE, NONE, ZERO, ZERO, ZERO_DEST, NONE, # 0xe0
+ NONE, IMMED, NONE, NONE, ABS, ABS, ABS_DEST, NONE, # 0xe8
+ REL, IND_Y, NONE, NONE, NONE, ZERO_X, ZERO_X_DEST, NONE, # 0xf0
+ NONE, ABS_Y, NONE, NONE, NONE, ABS_X, ABS_X_DEST, NONE # 0xf8
]
OperandLengths = [
- 0, # NONE
- 2, # ABS
- 2, # ABS_DEST
- 2, # ABS_X
- 2, # ABS_X_DEST
- 2, # ABS_Y
- 2, # ABS_Y_DEST
- 0, # ACCUM
- 2, # ADDR
- 1, # IMMED
- 2, # IND
- 1, # IND_X
- 1, # IND_X_DEST
- 1, # IND_Y
- 1, # IND_Y_DEST
- 1, # REL
- 1, # ZERO
- 1, # ZERO_DEST
- 1, # ZERO_X
- 1, # ZERO_X_DEST
- 1, # ZERO_Y
- 1 # ZERO_Y_DEST
+ 0, # NONE
+ 2, # ABS
+ 2, # ABS_DEST
+ 2, # ABS_X
+ 2, # ABS_X_DEST
+ 2, # ABS_Y
+ 2, # ABS_Y_DEST
+ 0, # ACCUM
+ 2, # ADDR
+ 1, # IMMED
+ 2, # IND
+ 1, # IND_X
+ 1, # IND_X_DEST
+ 1, # IND_Y
+ 1, # IND_Y_DEST
+ 1, # REL
+ 1, # ZERO
+ 1, # ZERO_DEST
+ 1, # ZERO_X
+ 1, # ZERO_X_DEST
+ 1, # ZERO_Y
+ 1 # ZERO_Y_DEST
]
-OperandTokens:List[Callable[[int], List[InstructionTextToken]]] = [
- lambda value: [], # NONE
- lambda value: [InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.4x" % value, value)], # ABS
- lambda value: [InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.4x" % value, value)], # ABS_DEST
- lambda value: [InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.4x" % value, value),
- InstructionTextToken(InstructionTextTokenType.TextToken, ", "), InstructionTextToken(InstructionTextTokenType.RegisterToken, "x")], # ABS_X
- lambda value: [InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.4x" % value, value),
- InstructionTextToken(InstructionTextTokenType.TextToken, ", "), InstructionTextToken(InstructionTextTokenType.RegisterToken, "x")], # ABS_X_DEST
- lambda value: [InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.4x" % value, value),
- InstructionTextToken(InstructionTextTokenType.TextToken, ", "), InstructionTextToken(InstructionTextTokenType.RegisterToken, "y")], # ABS_Y
- lambda value: [InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.4x" % value, value),
- InstructionTextToken(InstructionTextTokenType.TextToken, ", "), InstructionTextToken(InstructionTextTokenType.RegisterToken, "y")], # ABS_Y_DEST
- lambda value: [InstructionTextToken(InstructionTextTokenType.RegisterToken, "a")], # ACCUM
- lambda value: [InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.4x" % value, value)], # ADDR
- lambda value: [InstructionTextToken(InstructionTextTokenType.TextToken, "#"), InstructionTextToken(InstructionTextTokenType.IntegerToken, "$%.2x" % value, value)], # IMMED
- lambda value: [InstructionTextToken(InstructionTextTokenType.TextToken, "["), InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.4x" % value, value),
- InstructionTextToken(InstructionTextTokenType.TextToken, "]")], # IND
- lambda value: [InstructionTextToken(InstructionTextTokenType.TextToken, "["), InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.2x" % value, value),
- InstructionTextToken(InstructionTextTokenType.TextToken, ", "), InstructionTextToken(InstructionTextTokenType.RegisterToken, "x"),
- InstructionTextToken(InstructionTextTokenType.TextToken, "]")], # IND_X
- lambda value: [InstructionTextToken(InstructionTextTokenType.TextToken, "["), InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.2x" % value, value),
- InstructionTextToken(InstructionTextTokenType.TextToken, ", "), InstructionTextToken(InstructionTextTokenType.RegisterToken, "x"),
- InstructionTextToken(InstructionTextTokenType.TextToken, "]")], # IND_X_DEST
- lambda value: [InstructionTextToken(InstructionTextTokenType.TextToken, "["), InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.2x" % value, value),
- InstructionTextToken(InstructionTextTokenType.TextToken, "], "), InstructionTextToken(InstructionTextTokenType.RegisterToken, "y")], # IND_Y
- lambda value: [InstructionTextToken(InstructionTextTokenType.TextToken, "["), InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.2x" % value, value),
- InstructionTextToken(InstructionTextTokenType.TextToken, "], "), InstructionTextToken(InstructionTextTokenType.RegisterToken, "y")], # IND_Y_DEST
- lambda value: [InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.4x" % value, value)], # REL
- lambda value: [InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.2x" % value, value)], # ZERO
- lambda value: [InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.2x" % value, value)], # ZERO_DEST
- lambda value: [InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.2x" % value, value),
- InstructionTextToken(InstructionTextTokenType.TextToken, ", "), InstructionTextToken(InstructionTextTokenType.RegisterToken, "x")], # ZERO_X
- lambda value: [InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.2x" % value, value),
- InstructionTextToken(InstructionTextTokenType.TextToken, ", "), InstructionTextToken(InstructionTextTokenType.RegisterToken, "x")], # ZERO_X_DEST
- lambda value: [InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.2x" % value, value),
- InstructionTextToken(InstructionTextTokenType.TextToken, ", "), InstructionTextToken(InstructionTextTokenType.RegisterToken, "y")], # ZERO_Y
- lambda value: [InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.2x" % value, value),
- InstructionTextToken(InstructionTextTokenType.TextToken, ", "), InstructionTextToken(InstructionTextTokenType.RegisterToken, "y")] # ZERO_Y_DEST
+OperandTokens: List[Callable[[int], List[InstructionTextToken]]] = [
+ lambda value: [], # NONE
+ lambda value: [InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.4x" % value, value)], # ABS
+ lambda value: [InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.4x" % value, value)
+ ], # ABS_DEST
+ lambda value: [
+ InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.4x" % value, value),
+ InstructionTextToken(InstructionTextTokenType.TextToken, ", "),
+ InstructionTextToken(InstructionTextTokenType.RegisterToken, "x")
+ ], # ABS_X
+ lambda value: [
+ InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.4x" % value, value),
+ InstructionTextToken(InstructionTextTokenType.TextToken, ", "),
+ InstructionTextToken(InstructionTextTokenType.RegisterToken, "x")
+ ], # ABS_X_DEST
+ lambda value: [
+ InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.4x" % value, value),
+ InstructionTextToken(InstructionTextTokenType.TextToken, ", "),
+ InstructionTextToken(InstructionTextTokenType.RegisterToken, "y")
+ ], # ABS_Y
+ lambda value: [
+ InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.4x" % value, value),
+ InstructionTextToken(InstructionTextTokenType.TextToken, ", "),
+ InstructionTextToken(InstructionTextTokenType.RegisterToken, "y")
+ ], # ABS_Y_DEST
+ lambda value: [InstructionTextToken(InstructionTextTokenType.RegisterToken, "a")], # ACCUM
+ lambda value: [InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.4x" % value, value)], # ADDR
+ lambda value: [
+ InstructionTextToken(InstructionTextTokenType.TextToken, "#"),
+ InstructionTextToken(InstructionTextTokenType.IntegerToken, "$%.2x" % value, value)
+ ], # IMMED
+ lambda value: [
+ InstructionTextToken(InstructionTextTokenType.TextToken, "["),
+ InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.4x" % value, value),
+ InstructionTextToken(InstructionTextTokenType.TextToken, "]")
+ ], # IND
+ lambda value: [
+ InstructionTextToken(InstructionTextTokenType.TextToken, "["),
+ InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.2x" % value, value),
+ InstructionTextToken(InstructionTextTokenType.TextToken, ", "),
+ InstructionTextToken(InstructionTextTokenType.RegisterToken, "x"),
+ InstructionTextToken(InstructionTextTokenType.TextToken, "]")
+ ], # IND_X
+ lambda value: [
+ InstructionTextToken(InstructionTextTokenType.TextToken, "["),
+ InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.2x" % value, value),
+ InstructionTextToken(InstructionTextTokenType.TextToken, ", "),
+ InstructionTextToken(InstructionTextTokenType.RegisterToken, "x"),
+ InstructionTextToken(InstructionTextTokenType.TextToken, "]")
+ ], # IND_X_DEST
+ lambda value: [
+ InstructionTextToken(InstructionTextTokenType.TextToken, "["),
+ InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.2x" % value, value),
+ InstructionTextToken(InstructionTextTokenType.TextToken, "], "),
+ InstructionTextToken(InstructionTextTokenType.RegisterToken, "y")
+ ], # IND_Y
+ lambda value: [
+ InstructionTextToken(InstructionTextTokenType.TextToken, "["),
+ InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.2x" % value, value),
+ InstructionTextToken(InstructionTextTokenType.TextToken, "], "),
+ InstructionTextToken(InstructionTextTokenType.RegisterToken, "y")
+ ], # IND_Y_DEST
+ lambda value: [InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.4x" % value, value)], # REL
+ lambda value: [InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.2x" % value, value)], # ZERO
+ lambda value: [InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.2x" % value, value)
+ ], # ZERO_DEST
+ lambda value: [
+ InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.2x" % value, value),
+ InstructionTextToken(InstructionTextTokenType.TextToken, ", "),
+ InstructionTextToken(InstructionTextTokenType.RegisterToken, "x")
+ ], # ZERO_X
+ lambda value: [
+ InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.2x" % value, value),
+ InstructionTextToken(InstructionTextTokenType.TextToken, ", "),
+ InstructionTextToken(InstructionTextTokenType.RegisterToken, "x")
+ ], # ZERO_X_DEST
+ lambda value: [
+ InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.2x" % value, value),
+ InstructionTextToken(InstructionTextTokenType.TextToken, ", "),
+ InstructionTextToken(InstructionTextTokenType.RegisterToken, "y")
+ ], # ZERO_Y
+ lambda value: [
+ InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, "$%.2x" % value, value),
+ InstructionTextToken(InstructionTextTokenType.TextToken, ", "),
+ InstructionTextToken(InstructionTextTokenType.RegisterToken, "y")
+ ] # ZERO_Y_DEST
]
@@ -218,28 +266,28 @@ def load_zero_page_16(il, value):
OperandIL = [
- lambda il, value: None, # NONE
- lambda il, value: il.load(1, il.const_pointer(2, value)), # ABS
- lambda il, value: il.const(2, value), # ABS_DEST
- lambda il, value: il.load(1, il.add(2, il.const(2, value), il.zero_extend(2, il.reg(1, "x")))), # ABS_X
- lambda il, value: il.add(2, il.const(2, value), il.zero_extend(2, il.reg(1, "x"))), # ABS_X_DEST
- lambda il, value: il.load(1, il.add(2, il.const(2, value), il.zero_extend(2, il.reg(1, "y")))), # ABS_Y
- lambda il, value: il.add(2, il.const(2, value), il.zero_extend(2, il.reg(1, "y"))), # ABS_Y_DEST
- lambda il, value: il.reg(1, "a"), # ACCUM
- lambda il, value: il.const_pointer(2, value), # ADDR
- lambda il, value: il.const(1, value), # IMMED
- lambda il, value: indirect_load(il, value), # IND
- lambda il, value: il.load(1, load_zero_page_16(il, il.add(1, il.const(1, value), il.reg(1, "x")))), # IND_X
- lambda il, value: load_zero_page_16(il, il.add(1, il.const(1, value), il.reg(1, "x"))), # IND_X_DEST
- lambda il, value: il.load(1, il.add(2, load_zero_page_16(il, il.const(1, value)), il.reg(1, "y"))), # IND_Y
- lambda il, value: il.add(2, load_zero_page_16(il, il.const(1, value)), il.reg(1, "y")), # IND_Y_DEST
- lambda il, value: il.const_pointer(2, value), # REL
- lambda il, value: il.load(1, il.const_pointer(2, value)), # ZERO
- lambda il, value: il.const_pointer(2, value), # ZERO_DEST
- lambda il, value: il.load(1, il.zero_extend(2, il.add(1, il.const(1, value), il.reg(1, "x")))), # ZERO_X
- lambda il, value: il.zero_extend(2, il.add(1, il.const(1, value), il.reg(1, "x"))), # ZERO_X_DEST
- lambda il, value: il.load(1, il.zero_extend(2, il.add(1, il.const(1, value), il.reg(1, "y")))), # ZERO_Y
- lambda il, value: il.zero_extend(2, il.add(1, il.const(1, value), il.reg(1, "y"))) # ZERO_Y_DEST
+ lambda il, value: None, # NONE
+ lambda il, value: il.load(1, il.const_pointer(2, value)), # ABS
+ lambda il, value: il.const(2, value), # ABS_DEST
+ lambda il, value: il.load(1, il.add(2, il.const(2, value), il.zero_extend(2, il.reg(1, "x")))), # ABS_X
+ lambda il, value: il.add(2, il.const(2, value), il.zero_extend(2, il.reg(1, "x"))), # ABS_X_DEST
+ lambda il, value: il.load(1, il.add(2, il.const(2, value), il.zero_extend(2, il.reg(1, "y")))), # ABS_Y
+ lambda il, value: il.add(2, il.const(2, value), il.zero_extend(2, il.reg(1, "y"))), # ABS_Y_DEST
+ lambda il, value: il.reg(1, "a"), # ACCUM
+ lambda il, value: il.const_pointer(2, value), # ADDR
+ lambda il, value: il.const(1, value), # IMMED
+ lambda il, value: indirect_load(il, value), # IND
+ lambda il, value: il.load(1, load_zero_page_16(il, il.add(1, il.const(1, value), il.reg(1, "x")))), # IND_X
+ lambda il, value: load_zero_page_16(il, il.add(1, il.const(1, value), il.reg(1, "x"))), # IND_X_DEST
+ lambda il, value: il.load(1, il.add(2, load_zero_page_16(il, il.const(1, value)), il.reg(1, "y"))), # IND_Y
+ lambda il, value: il.add(2, load_zero_page_16(il, il.const(1, value)), il.reg(1, "y")), # IND_Y_DEST
+ lambda il, value: il.const_pointer(2, value), # REL
+ lambda il, value: il.load(1, il.const_pointer(2, value)), # ZERO
+ lambda il, value: il.const_pointer(2, value), # ZERO_DEST
+ lambda il, value: il.load(1, il.zero_extend(2, il.add(1, il.const(1, value), il.reg(1, "x")))), # ZERO_X
+ lambda il, value: il.zero_extend(2, il.add(1, il.const(1, value), il.reg(1, "x"))), # ZERO_X_DEST
+ lambda il, value: il.load(1, il.zero_extend(2, il.add(1, il.const(1, value), il.reg(1, "y")))), # ZERO_Y
+ lambda il, value: il.zero_extend(2, il.add(1, il.const(1, value), il.reg(1, "y"))) # ZERO_Y_DEST
]
@@ -280,8 +328,7 @@ def get_p_value(il):
b = il.flag_bit(1, "b", 4)
v = il.flag_bit(1, "v", 6)
s = il.flag_bit(1, "s", 7)
- return il.or_expr(1, il.or_expr(1, il.or_expr(1, il.or_expr(1, il.or_expr(1,
- il.or_expr(1, c, z), i), d), b), v), s)
+ return il.or_expr(1, il.or_expr(1, il.or_expr(1, il.or_expr(1, il.or_expr(1, il.or_expr(1, c, z), i), d), b), v), s)
def set_p_value(il, value):
@@ -302,66 +349,80 @@ def rti(il):
InstructionIL = {
- "adc": lambda il, operand: il.set_reg(1, "a", il.add_carry(1, il.reg(1, "a"), operand, il.flag("c"), flags = "*")),
- "asl": lambda il, operand: il.store(1, operand, il.shift_left(1, il.load(1, operand), il.const(1, 1), flags = "czs")),
- "asl@": lambda il, operand: il.set_reg(1, "a", il.shift_left(1, operand, il.const(1, 1), flags = "czs")),
- "and": lambda il, operand: il.set_reg(1, "a", il.and_expr(1, il.reg(1, "a"), operand, flags = "zs")),
- "bcc": lambda il, operand: cond_branch(il, il.flag_condition(LowLevelILFlagCondition.LLFC_UGE), operand),
- "bcs": lambda il, operand: cond_branch(il, il.flag_condition(LowLevelILFlagCondition.LLFC_ULT), operand),
- "beq": lambda il, operand: cond_branch(il, il.flag_condition(LowLevelILFlagCondition.LLFC_E), operand),
- "bit": lambda il, operand: il.and_expr(1, il.reg(1, "a"), operand, flags = "czs"),
- "bmi": lambda il, operand: cond_branch(il, il.flag_condition(LowLevelILFlagCondition.LLFC_NEG), operand),
- "bne": lambda il, operand: cond_branch(il, il.flag_condition(LowLevelILFlagCondition.LLFC_NE), operand),
- "bpl": lambda il, operand: cond_branch(il, il.flag_condition(LowLevelILFlagCondition.LLFC_POS), operand),
- "brk": lambda il, operand: il.system_call(),
- "bvc": lambda il, operand: cond_branch(il, il.not_expr(0, il.flag("v")), operand),
- "bvs": lambda il, operand: cond_branch(il, il.flag("v"), operand),
- "clc": lambda il, operand: il.set_flag("c", il.const(0, 0)),
- "cld": lambda il, operand: il.set_flag("d", il.const(0, 0)),
- "cli": lambda il, operand: il.set_flag("i", il.const(0, 0)),
- "clv": lambda il, operand: il.set_flag("v", il.const(0, 0)),
- "cmp": lambda il, operand: il.sub(1, il.reg(1, "a"), operand, flags = "czs"),
- "cpx": lambda il, operand: il.sub(1, il.reg(1, "x"), operand, flags = "czs"),
- "cpy": lambda il, operand: il.sub(1, il.reg(1, "y"), operand, flags = "czs"),
- "dec": lambda il, operand: il.store(1, operand, il.sub(1, il.load(1, operand), il.const(1, 1), flags = "zs")),
- "dex": lambda il, operand: il.set_reg(1, "x", il.sub(1, il.reg(1, "x"), il.const(1, 1), flags = "zs")),
- "dey": lambda il, operand: il.set_reg(1, "y", il.sub(1, il.reg(1, "y"), il.const(1, 1), flags = "zs")),
- "eor": lambda il, operand: il.set_reg(1, "a", il.xor_expr(1, il.reg(1, "a"), operand, flags = "zs")),
- "inc": lambda il, operand: il.store(1, operand, il.add(1, il.load(1, operand), il.const(1, 1), flags = "zs")),
- "inx": lambda il, operand: il.set_reg(1, "x", il.add(1, il.reg(1, "x"), il.const(1, 1), flags = "zs")),
- "iny": lambda il, operand: il.set_reg(1, "y", il.add(1, il.reg(1, "y"), il.const(1, 1), flags = "zs")),
- "jmp": lambda il, operand: jump(il, operand),
- "jsr": lambda il, operand: il.call(operand),
- "lda": lambda il, operand: il.set_reg(1, "a", operand, flags = "zs"),
- "ldx": lambda il, operand: il.set_reg(1, "x", operand, flags = "zs"),
- "ldy": lambda il, operand: il.set_reg(1, "y", operand, flags = "zs"),
- "lsr": lambda il, operand: il.store(1, operand, il.logical_shift_right(1, il.load(1, operand), il.const(1, 1), flags = "czs")),
- "lsr@": lambda il, operand: il.set_reg(1, "a", il.logical_shift_right(1, il.reg(1, "a"), il.const(1, 1), flags = "czs")),
- "nop": lambda il, operand: il.nop(),
- "ora": lambda il, operand: il.set_reg(1, "a", il.or_expr(1, il.reg(1, "a"), operand, flags = "zs")),
- "pha": lambda il, operand: il.push(1, il.reg(1, "a")),
- "php": lambda il, operand: il.push(1, get_p_value(il)),
- "pla": lambda il, operand: il.set_reg(1, "a", il.pop(1), flags = "zs"),
- "plp": lambda il, operand: set_p_value(il, il.pop(1)),
- "rol": lambda il, operand: il.store(1, operand, il.rotate_left_carry(1, il.load(1, operand), il.const(1, 1), il.flag("c"), flags = "czs")),
- "rol@": lambda il, operand: il.set_reg(1, "a", il.rotate_left_carry(1, il.reg(1, "a"), il.const(1, 1), il.flag("c"), flags = "czs")),
- "ror": lambda il, operand: il.store(1, operand, il.rotate_right_carry(1, il.load(1, operand), il.const(1, 1), il.flag("c"), flags = "czs")),
- "ror@": lambda il, operand: il.set_reg(1, "a", il.rotate_right_carry(1, il.reg(1, "a"), il.const(1, 1), il.flag("c"), flags = "czs")),
- "rti": lambda il, operand: rti(il),
- "rts": lambda il, operand: il.ret(il.add(2, il.pop(2), il.const(2, 1))),
- "sbc": lambda il, operand: il.set_reg(1, "a", il.sub_borrow(1, il.reg(1, "a"), operand, il.flag("c"), flags = "*")),
- "sec": lambda il, operand: il.set_flag("c", il.const(0, 1)),
- "sed": lambda il, operand: il.set_flag("d", il.const(0, 1)),
- "sei": lambda il, operand: il.set_flag("i", il.const(0, 1)),
- "sta": lambda il, operand: il.store(1, operand, il.reg(1, "a")),
- "stx": lambda il, operand: il.store(1, operand, il.reg(1, "x")),
- "sty": lambda il, operand: il.store(1, operand, il.reg(1, "y")),
- "tax": lambda il, operand: il.set_reg(1, "x", il.reg(1, "a"), flags = "zs"),
- "tay": lambda il, operand: il.set_reg(1, "y", il.reg(1, "a"), flags = "zs"),
- "tsx": lambda il, operand: il.set_reg(1, "x", il.reg(1, "s"), flags = "zs"),
- "txa": lambda il, operand: il.set_reg(1, "a", il.reg(1, "x"), flags = "zs"),
- "txs": lambda il, operand: il.set_reg(1, "s", il.reg(1, "x")),
- "tya": lambda il, operand: il.set_reg(1, "a", il.reg(1, "y"), flags = "zs")
+ "adc":
+ lambda il, operand: il.set_reg(1, "a", il.add_carry(1, il.reg(1, "a"), operand, il.flag("c"), flags="*")), "asl":
+ lambda il, operand: il.store(1, operand, il.shift_left(1, il.load(1, operand), il.const(1, 1), flags="czs")),
+ "asl@":
+ lambda il, operand: il.set_reg(1, "a", il.shift_left(1, operand, il.const(1, 1), flags="czs")), "and":
+ lambda il, operand: il.set_reg(1, "a", il.and_expr(1, il.reg(1, "a"), operand, flags="zs")), "bcc":
+ lambda il, operand: cond_branch(il, il.flag_condition(LowLevelILFlagCondition.LLFC_UGE), operand), "bcs":
+ lambda il, operand: cond_branch(il, il.flag_condition(LowLevelILFlagCondition.LLFC_ULT), operand), "beq":
+ lambda il, operand: cond_branch(il, il.flag_condition(LowLevelILFlagCondition.LLFC_E), operand), "bit":
+ lambda il, operand: il.and_expr(1, il.reg(1, "a"), operand, flags="czs"), "bmi":
+ lambda il, operand: cond_branch(il, il.flag_condition(LowLevelILFlagCondition.LLFC_NEG), operand),
+ "bne":
+ lambda il, operand: cond_branch(il, il.flag_condition(LowLevelILFlagCondition.LLFC_NE), operand), "bpl":
+ lambda il, operand: cond_branch(il, il.flag_condition(LowLevelILFlagCondition.LLFC_POS), operand), "brk":
+ lambda il, operand: il.system_call(), "bvc":
+ lambda il, operand: cond_branch(il, il.not_expr(0, il.flag("v")), operand), "bvs":
+ lambda il, operand: cond_branch(il, il.flag("v"), operand), "clc":
+ lambda il, operand: il.set_flag("c", il.const(0, 0)), "cld":
+ lambda il, operand: il.set_flag("d", il.const(0, 0)), "cli":
+ lambda il, operand: il.set_flag("i", il.const(0, 0)), "clv":
+ lambda il, operand: il.set_flag("v", il.const(0, 0)), "cmp":
+ lambda il, operand: il.sub(1, il.reg(1, "a"), operand, flags="czs"), "cpx":
+ lambda il, operand: il.sub(1, il.reg(1, "x"), operand, flags="czs"), "cpy":
+ lambda il, operand: il.sub(1, il.reg(1, "y"), operand, flags="czs"),
+ "dec":
+ lambda il, operand: il.store(1, operand, il.sub(1, il.load(1, operand), il.const(1, 1), flags="zs")), "dex":
+ lambda il, operand: il.set_reg(1, "x", il.sub(1, il.reg(1, "x"), il.const(1, 1), flags="zs")), "dey":
+ lambda il, operand: il.set_reg(1, "y", il.sub(1, il.reg(1, "y"), il.const(1, 1), flags="zs")), "eor":
+ lambda il, operand: il.set_reg(1, "a", il.xor_expr(1, il.reg(1, "a"), operand, flags="zs")), "inc":
+ lambda il, operand: il.store(1, operand, il.add(1, il.load(1, operand), il.const(1, 1), flags="zs")), "inx":
+ lambda il, operand: il.set_reg(1, "x", il.add(1, il.reg(1, "x"), il.const(1, 1), flags="zs")), "iny":
+ lambda il, operand: il.set_reg(1, "y", il.add(1, il.reg(1, "y"), il.const(1, 1), flags="zs")), "jmp":
+ lambda il, operand: jump(il, operand), "jsr":
+ lambda il, operand: il.call(operand), "lda":
+ lambda il, operand: il.set_reg(1, "a", operand, flags="zs"), "ldx":
+ lambda il, operand: il.set_reg(1, "x", operand, flags="zs"), "ldy":
+ lambda il, operand: il.set_reg(1, "y", operand, flags="zs"),
+ "lsr":
+ lambda il, operand: il.
+ store(1, operand, il.logical_shift_right(1, il.load(1, operand), il.const(1, 1), flags="czs")), "lsr@":
+ lambda il, operand: il.set_reg(1, "a", il.logical_shift_right(1, il.reg(1, "a"), il.const(1, 1), flags="czs")),
+ "nop":
+ lambda il, operand: il.nop(), "ora":
+ lambda il, operand: il.set_reg(1, "a", il.or_expr(1, il.reg(1, "a"), operand, flags="zs")), "pha":
+ lambda il, operand: il.push(1, il.reg(1, "a")), "php":
+ lambda il, operand: il.push(1, get_p_value(il)), "pla":
+ lambda il, operand: il.set_reg(1, "a", il.pop(1), flags="zs"), "plp":
+ lambda il, operand: set_p_value(il, il.pop(1)),
+ "rol":
+ lambda il, operand: il.
+ store(1, operand, il.rotate_left_carry(1, il.load(1, operand), il.const(1, 1), il.flag("c"), flags="czs")), "rol@":
+ lambda il, operand: il.
+ set_reg(1, "a", il.rotate_left_carry(1, il.reg(1, "a"), il.const(1, 1), il.flag("c"), flags="czs")), "ror":
+ lambda il, operand: il.
+ store(1, operand, il.rotate_right_carry(1, il.load(1, operand), il.const(1, 1), il.flag("c"), flags="czs")),
+ "ror@":
+ lambda il, operand: il.
+ set_reg(1, "a", il.rotate_right_carry(1, il.reg(1, "a"), il.const(1, 1), il.flag("c"), flags="czs")), "rti":
+ lambda il, operand: rti(il), "rts":
+ lambda il, operand: il.ret(il.add(2, il.pop(2), il.const(2, 1))), "sbc":
+ lambda il, operand: il.set_reg(1, "a", il.sub_borrow(1, il.reg(1, "a"), operand, il.flag("c"), flags="*")),
+ "sec":
+ lambda il, operand: il.set_flag("c", il.const(0, 1)), "sed":
+ lambda il, operand: il.set_flag("d", il.const(0, 1)), "sei":
+ lambda il, operand: il.set_flag("i", il.const(0, 1)), "sta":
+ lambda il, operand: il.store(1, operand, il.reg(1, "a")), "stx":
+ lambda il, operand: il.store(1, operand, il.reg(1, "x")), "sty":
+ lambda il, operand: il.store(1, operand, il.reg(1, "y")), "tax":
+ lambda il, operand: il.set_reg(1, "x", il.reg(1, "a"), flags="zs"), "tay":
+ lambda il, operand: il.set_reg(1, "y", il.reg(1, "a"), flags="zs"), "tsx":
+ lambda il, operand: il.set_reg(1, "x", il.reg(1, "s"), flags="zs"), "txa":
+ lambda il, operand: il.set_reg(1, "a", il.reg(1, "x"), flags="zs"), "txs":
+ lambda il, operand: il.set_reg(1, "s", il.reg(1, "x")), "tya":
+ lambda il, operand: il.set_reg(1, "a", il.reg(1, "y"), flags="zs")
}
@@ -372,33 +433,23 @@ class M6502(Architecture):
instr_alignment = 1
max_instr_length = 3
regs = {
- "a": RegisterInfo(RegisterName("a"), 1),
- "x": RegisterInfo(RegisterName("x"), 1),
- "y": RegisterInfo(RegisterName("y"), 1),
- "s": RegisterInfo(RegisterName("s"), 1)
+ "a": RegisterInfo(RegisterName("a"), 1), "x": RegisterInfo(RegisterName("x"), 1),
+ "y": RegisterInfo(RegisterName("y"), 1), "s": RegisterInfo(RegisterName("s"), 1)
}
stack_pointer = "s"
flags = ["c", "z", "i", "d", "b", "v", "s"]
flag_write_types = ["*", "czs", "zvs", "zs"]
flag_roles = {
- "c": FlagRole.SpecialFlagRole, # Not a normal carry flag, subtract result is inverted
- "z": FlagRole.ZeroFlagRole,
- "v": FlagRole.OverflowFlagRole,
- "s": FlagRole.NegativeSignFlagRole
+ "c": FlagRole.SpecialFlagRole, # Not a normal carry flag, subtract result is inverted
+ "z": FlagRole.ZeroFlagRole, "v": FlagRole.OverflowFlagRole, "s": FlagRole.NegativeSignFlagRole
}
flags_required_for_flag_condition = {
- LowLevelILFlagCondition.LLFC_UGE: ["c"],
- LowLevelILFlagCondition.LLFC_ULT: ["c"],
- LowLevelILFlagCondition.LLFC_E: ["z"],
- LowLevelILFlagCondition.LLFC_NE: ["z"],
- LowLevelILFlagCondition.LLFC_NEG: ["s"],
- LowLevelILFlagCondition.LLFC_POS: ["s"]
+ LowLevelILFlagCondition.LLFC_UGE: ["c"], LowLevelILFlagCondition.LLFC_ULT: ["c"],
+ LowLevelILFlagCondition.LLFC_E: ["z"], LowLevelILFlagCondition.LLFC_NE: ["z"],
+ LowLevelILFlagCondition.LLFC_NEG: ["s"], LowLevelILFlagCondition.LLFC_POS: ["s"]
}
flags_written_by_flag_write_type = {
- "*": ["c", "z", "v", "s"],
- "czs": ["c", "z", "s"],
- "zvs": ["z", "v", "s"],
- "zs": ["z", "s"]
+ "*": ["c", "z", "v", "s"], "czs": ["c", "z", "s"], "zvs": ["z", "v", "s"], "zs": ["z", "s"]
}
def decode_instruction(self, data, addr):
@@ -482,12 +533,16 @@ class M6502(Architecture):
return Architecture.get_flag_write_low_level_il(self, op, size, write_type, flag, operands, il)
def is_never_branch_patch_available(self, data, addr):
- if (data[0:1] == b"\x10") or (data[0:1] == b"\x30") or (data[0:1] == b"\x50") or (data[0:1] == b"\x70") or (data[0:1] == b"\x90") or (data[0:1] == b"\xb0") or (data[0:1] == b"\xd0") or (data[0:1] == b"\xf0"):
+ if (data[0:1] == b"\x10") or (data[0:1] == b"\x30") or (data[0:1] == b"\x50") or (data[0:1] == b"\x70") or (
+ data[0:1] == b"\x90"
+ ) or (data[0:1] == b"\xb0") or (data[0:1] == b"\xd0") or (data[0:1] == b"\xf0"):
return True
return False
def is_invert_branch_patch_available(self, data, addr):
- if (data[0:1] == b"\x10") or (data[0:1] == b"\x30") or (data[0:1] == b"\x50") or (data[0:1] == b"\x70") or (data[0:1] == b"\x90") or (data[0:1] == b"\xb0") or (data[0:1] == b"\xd0") or (data[0:1] == b"\xf0"):
+ if (data[0:1] == b"\x10") or (data[0:1] == b"\x30") or (data[0:1] == b"\x50") or (data[0:1] == b"\x70") or (
+ data[0:1] == b"\x90"
+ ) or (data[0:1] == b"\xb0") or (data[0:1] == b"\xd0") or (data[0:1] == b"\xf0"):
return True
return False
@@ -504,12 +559,16 @@ class M6502(Architecture):
return b"\xea" * len(data)
def never_branch(self, data, addr):
- if (data[0:1] == b"\x10") or (data[0:1] == b"\x30") or (data[0:1] == b"\x50") or (data[0:1] == b"\x70") or (data[0:1] == b"\x90") or (data[0:1] == b"\xb0") or (data[0:1] == b"\xd0") or (data[0:1] == b"\xf0"):
+ if (data[0:1] == b"\x10") or (data[0:1] == b"\x30") or (data[0:1] == b"\x50") or (data[0:1] == b"\x70") or (
+ data[0:1] == b"\x90"
+ ) or (data[0:1] == b"\xb0") or (data[0:1] == b"\xd0") or (data[0:1] == b"\xf0"):
return b"\xea" * len(data)
return None
def invert_branch(self, data, addr):
- if (data[0:1] == b"\x10") or (data[0:1] == b"\x30") or (data[0:1] == b"\x50") or (data[0:1] == b"\x70") or (data[0:1] == b"\x90") or (data[0:1] == b"\xb0") or (data[0:1] == b"\xd0") or (data[0:1] == b"\xf0"):
+ if (data[0:1] == b"\x10") or (data[0:1] == b"\x30") or (data[0:1] == b"\x50") or (data[0:1] == b"\x70") or (
+ data[0:1] == b"\x90"
+ ) or (data[0:1] == b"\xb0") or (data[0:1] == b"\xd0") or (data[0:1] == b"\xf0"):
return chr(ord(data[0:1]) ^ 0x20) + data[1:]
return None
@@ -523,8 +582,9 @@ class NESView(BinaryView):
name = "NES"
long_name = "NES ROM"
bank = None
+
def __init__(self, data):
- BinaryView.__init__(self, parent_view = data, file_metadata = data.file)
+ BinaryView.__init__(self, parent_view=data, file_metadata=data.file)
self.platform = Architecture['6502'].standalone_platform # type: ignore
@classmethod
@@ -554,14 +614,20 @@ class NESView(BinaryView):
self.rom_length = self.rom_banks * 0x4000
# Add mapping for RAM and hardware registers, not backed by file contents
- self.add_auto_segment(0, 0x8000, 0, 0, SegmentFlag.SegmentReadable | SegmentFlag.SegmentWritable | SegmentFlag.SegmentExecutable)
+ self.add_auto_segment(
+ 0, 0x8000, 0, 0, SegmentFlag.SegmentReadable | SegmentFlag.SegmentWritable | SegmentFlag.SegmentExecutable
+ )
# Add ROM mappings
assert self.__class__.bank is not None
- self.add_auto_segment(0x8000, 0x4000, self.rom_offset + (self.__class__.bank * 0x4000), 0x4000,
- SegmentFlag.SegmentReadable | SegmentFlag.SegmentExecutable)
- self.add_auto_segment(0xc000, 0x4000, self.rom_offset + self.rom_length - 0x4000, 0x4000,
- SegmentFlag.SegmentReadable | SegmentFlag.SegmentExecutable)
+ self.add_auto_segment(
+ 0x8000, 0x4000, self.rom_offset + (self.__class__.bank * 0x4000), 0x4000,
+ SegmentFlag.SegmentReadable | SegmentFlag.SegmentExecutable
+ )
+ self.add_auto_segment(
+ 0xc000, 0x4000, self.rom_offset + self.rom_length - 0x4000, 0x4000,
+ SegmentFlag.SegmentReadable | SegmentFlag.SegmentExecutable
+ )
nmi = struct.unpack("<H", self.read(0xfffa, 2))[0]
start = struct.unpack("<H", self.read(0xfffc, 2))[0]
@@ -605,9 +671,10 @@ class NESView(BinaryView):
self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4016, "JOY1"))
self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4017, "JOY2"))
- sym_files = [self.file.filename + ".%x.nl" % self.__class__.bank,
- self.file.filename + ".ram.nl",
- self.file.filename + ".%x.nl" % (self.rom_banks - 1)]
+ sym_files = [
+ self.file.filename + ".%x.nl" % self.__class__.bank, self.file.filename + ".ram.nl",
+ self.file.filename + ".%x.nl" % (self.rom_banks - 1)
+ ]
for f in sym_files:
if os.path.exists(f):
with open(f, "r") as f:
@@ -637,6 +704,7 @@ class NESView(BinaryView):
banks = []
for i in range(0, 32):
+
class NESViewBank(NESView):
bank = i
name = "NES Bank %X" % i
diff --git a/python/examples/notification_callbacks.py b/python/examples/notification_callbacks.py
index 015cd458..d3cbf26b 100644
--- a/python/examples/notification_callbacks.py
+++ b/python/examples/notification_callbacks.py
@@ -27,6 +27,7 @@ def reg_notif(view):
demo_notification = DemoNotification(view)
view.register_notification(demo_notification)
+
class DemoNotification(BinaryDataNotification):
def __init__(self, view):
self.view = view
@@ -100,4 +101,5 @@ class DemoNotification(BinaryDataNotification):
def type_field_ref_changed(self, *args):
log.log_info(inspect.stack()[0][3] + str(args))
+
PluginCommand.register("Register Notification", "", reg_notif)
diff --git a/python/examples/nsf.py b/python/examples/nsf.py
index 76a78f1c..5121d888 100644
--- a/python/examples/nsf.py
+++ b/python/examples/nsf.py
@@ -87,11 +87,14 @@ class NSFView(BinaryView):
log_info("Bank switching not implemented in this loader.")
# Add mapping for RAM and hardware registers, not backed by file contents
- self.add_auto_segment(0, 0x8000, 0, 0, SegmentFlag.SegmentReadable | SegmentFlag.SegmentWritable | SegmentFlag.SegmentExecutable)
+ self.add_auto_segment(
+ 0, 0x8000, 0, 0, SegmentFlag.SegmentReadable | SegmentFlag.SegmentWritable | SegmentFlag.SegmentExecutable
+ )
# Add ROM mappings
- self.add_auto_segment(0x8000, 0x4000, self.rom_offset, 0x4000,
- SegmentFlag.SegmentReadable | SegmentFlag.SegmentExecutable)
+ self.add_auto_segment(
+ 0x8000, 0x4000, self.rom_offset, 0x4000, SegmentFlag.SegmentReadable | SegmentFlag.SegmentExecutable
+ )
self.define_auto_symbol(Symbol(SymbolType.FunctionSymbol, self.play_address, "_play"))
self.define_auto_symbol(Symbol(SymbolType.FunctionSymbol, self.init_address, "_init"))
diff --git a/python/examples/pe_stat.py b/python/examples/pe_stat.py
index f5a6d89f..2e3f7755 100755
--- a/python/examples/pe_stat.py
+++ b/python/examples/pe_stat.py
@@ -27,7 +27,7 @@ import sys
import binaryninja
from collections import defaultdict
-opc2count = defaultdict(lambda:0)
+opc2count = defaultdict(lambda: 0)
target = sys.argv[1]
print('opening %s' % target)
@@ -48,6 +48,5 @@ total = sum([x[1] for x in opc2count.items()])
print('op frequency %')
print('-- --------- -')
-for opc in sorted(opc2count.keys(), key=lambda x:opc2count[x], reverse=True):
- print(opc.ljust(8), str(opc2count[opc]).ljust(16), '%.1f%%'%(100.0*opc2count[opc]/total))
-
+for opc in sorted(opc2count.keys(), key=lambda x: opc2count[x], reverse=True):
+ print(opc.ljust(8), str(opc2count[opc]).ljust(16), '%.1f%%' % (100.0 * opc2count[opc] / total))
diff --git a/python/examples/print_syscalls.py b/python/examples/print_syscalls.py
index 0ed40fb9..9956636f 100644
--- a/python/examples/print_syscalls.py
+++ b/python/examples/print_syscalls.py
@@ -19,7 +19,6 @@
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
-
# Thanks to @theqlabs from arm.ninja for the nice writeup and idea for this plugin:
# http://arm.ninja/2016/03/08/intro-to-binary-ninja-api/
@@ -41,8 +40,7 @@ def print_syscalls(fileName):
register = calling_convention.int_arg_regs[0]
for func in bv.functions:
- syscalls = (il for il in chain.from_iterable(func.low_level_il)
- if il.operation == LowLevelILOperation.LLIL_SYSCALL)
+ syscalls = (il for il in chain.from_iterable(func.low_level_il) if il.operation == LowLevelILOperation.LLIL_SYSCALL)
for il in syscalls:
value = func.get_reg_value_at(il.address, register).value
print("System call address: {:#x} - {:d}".format(il.address, value))
diff --git a/python/examples/typelib_create.py b/python/examples/typelib_create.py
index 303fa350..2ac3855d 100755
--- a/python/examples/typelib_create.py
+++ b/python/examples/typelib_create.py
@@ -36,13 +36,16 @@ typelib.add_named_type('MyPointerType', Type.pointer(arch, Type.char()))
# typedef int MyTypedefType;
typelib.add_named_type('MyTypedefType', Type.int(4))
+
# example of typedef to typedef
# typedef MyTypedefType MySuperSpecialType;
-def create_named_type_reference(type_name:str, to_what:NamedTypeReferenceClass):
- return NamedTypeReferenceType.create(named_type_class=to_what, guid=None, name=type_name)
+def create_named_type_reference(type_name: str, to_what: NamedTypeReferenceClass):
+ return NamedTypeReferenceType.create(named_type_class=to_what, guid=None, name=type_name)
+
-typelib.add_named_type('MySuperSpecialType',
- create_named_type_reference('MySpecialType', NamedTypeReferenceClass.TypedefNamedTypeClass))
+typelib.add_named_type(
+ 'MySuperSpecialType', create_named_type_reference('MySpecialType', NamedTypeReferenceClass.TypedefNamedTypeClass)
+)
# We can demonstrate three type classes in the following example:
# StructureTypeClass, PointerTypeClass, NamedTypeReferenceClass
@@ -57,11 +60,11 @@ typelib.add_named_type('MySuperSpecialType',
# }
with StructureBuilder.builder(typelib, 'Rectangle') as struct_type:
- struct_type.append(Type.int(4), 'width')
- struct_type.append(Type.int(4), 'height')
- struct_type.append(Type.pointer(arch,
- create_named_type_reference('Point', NamedTypeReferenceClass.StructNamedTypeClass)),
- 'center')
+ struct_type.append(Type.int(4), 'width')
+ struct_type.append(Type.int(4), 'height')
+ struct_type.append(
+ Type.pointer(arch, create_named_type_reference('Point', NamedTypeReferenceClass.StructNamedTypeClass)), 'center'
+ )
# add a named type "Rectangle2":
# this type cannot be applied to variables until struct Point is declared
@@ -74,10 +77,9 @@ with StructureBuilder.builder(typelib, 'Rectangle') as struct_type:
# }
with StructureBuilder.builder(typelib, 'Rectangle2') as struct_type:
- struct_type.append(Type.int(4), 'width')
- struct_type.append(Type.int(4), 'height')
- struct_type.append(create_named_type_reference('Point', NamedTypeReferenceClass.StructNamedTypeClass),
- 'center')
+ struct_type.append(Type.int(4), 'width')
+ struct_type.append(Type.int(4), 'height')
+ struct_type.append(create_named_type_reference('Point', NamedTypeReferenceClass.StructNamedTypeClass), 'center')
# example: EnumerationTypeClass
enum_type = EnumerationBuilder.create([], None, arch=arch)
@@ -119,4 +121,3 @@ typelib.add_named_object('_MySuperComputation', ftype)
typelib.finalize()
print('writing test.bntl')
typelib.write_to_file('test.bntl')
-
diff --git a/python/examples/typelib_dump.py b/python/examples/typelib_dump.py
index 4beff0db..750ac78c 100755
--- a/python/examples/typelib_dump.py
+++ b/python/examples/typelib_dump.py
@@ -18,103 +18,106 @@ from binaryninja import typelibrary
#
# etc...
+
def obj2str(t, depth=0):
- indent = ' '*depth
- result = ''
+ indent = ' ' * depth
+ result = ''
+
+ if type(t) == binaryninja.types.StructureType:
+ result = '%sStructure\n' % (indent)
+ for m in t.members:
+ result += obj2str(m, depth + 1)
+ elif type(t) == binaryninja.types.StructureMember:
+ result = '%sStructureMember "%s"\n' % (indent, t._name)
+ result += type2str(t.type, depth + 1)
+ elif type(t) == binaryninja.types.FunctionParameter:
+ result = '%sFunctionParameter "%s"\n' % (indent, t.name)
+ result += type2str(t.type, depth + 1)
+ elif type(t) == binaryninja.types.NamedTypeReferenceType:
+ result = '%sNamedTypeReference %s\n' % (indent, repr(t))
+ elif type(t) == binaryninja.types.EnumerationType:
+ result = '%sEnumeration\n' % indent
+ for m in t.members:
+ result += obj2str(m, depth + 1)
+ elif type(t) == binaryninja.types.EnumerationMember:
+ result = '%sEnumerationMember %s==%d\n' % (indent, t.name, t.value)
+ elif t == None:
+ result = 'unimplemented'
+
+ return result
- if type(t) == binaryninja.types.StructureType:
- result = '%sStructure\n' % (indent)
- for m in t.members:
- result += obj2str(m, depth+1)
- elif type(t) == binaryninja.types.StructureMember:
- result = '%sStructureMember "%s"\n' % (indent, t._name)
- result += type2str(t.type, depth+1)
- elif type(t) == binaryninja.types.FunctionParameter:
- result = '%sFunctionParameter "%s"\n' % (indent, t.name)
- result += type2str(t.type, depth+1)
- elif type(t) == binaryninja.types.NamedTypeReferenceType:
- result = '%sNamedTypeReference %s\n' % (indent, repr(t))
- elif type(t) == binaryninja.types.EnumerationType:
- result = '%sEnumeration\n' % indent
- for m in t.members:
- result += obj2str(m, depth+1)
- elif type(t) == binaryninja.types.EnumerationMember:
- result = '%sEnumerationMember %s==%d\n' % (indent, t.name, t.value)
- elif t == None:
- result = 'unimplemented'
- return result
+def type2str(t: binaryninja.types.Type, depth=0):
+ indent = ' ' * depth
+ result = 'unimplemented'
-def type2str(t:binaryninja.types.Type, depth=0):
- indent = ' '*depth
- result = 'unimplemented'
+ assert isinstance(t, binaryninja.types.Type)
+ tc = t.type_class
- assert isinstance(t, binaryninja.types.Type)
- tc = t.type_class
+ if tc == TypeClass.VoidTypeClass:
+ result = '%sType class=Void\n' % indent
+ elif tc == TypeClass.BoolTypeClass:
+ result = '%sType class=Bool\n' % indent
+ elif tc == TypeClass.IntegerTypeClass:
+ result = '%sType class=Integer width=%d\n' % (indent, t.width)
+ elif tc == TypeClass.FloatTypeClass:
+ result = '%sType class=Float\n' % indent
+ elif tc == TypeClass.StructureTypeClass:
+ result = '%sType class=Structure\n' % indent
+ result += obj2str(t.structure, depth + 1)
+ elif tc == TypeClass.EnumerationTypeClass:
+ result = '%sType class=Enumeration\n' % indent
+ result += obj2str(t.enumeration, depth + 1)
+ elif tc == TypeClass.PointerTypeClass:
+ result = '%sType class=Pointer\n' % indent
+ result += type2str(t.target, depth + 1)
+ elif tc == TypeClass.ArrayTypeClass:
+ result = '%sType class=Array\n' % indent
+ elif tc == TypeClass.FunctionTypeClass:
+ result = '%sType class=Function\n' % indent
+ result += type2str(t.return_value, depth + 1)
+ for param in t.parameters:
+ result += obj2str(param, depth + 1)
+ elif tc == TypeClass.VarArgsTypeClass:
+ result = '%sType class=VarArgs\n' % indent
+ elif tc == TypeClass.ValueTypeClass:
+ result = '%sType class=Value\n' % indent
+ elif tc == TypeClass.NamedTypeReferenceClass:
+ result = '%sType class=NamedTypeReference\n' % indent
+ result += obj2str(t.named_type_reference, depth + 1)
+ elif tc == TypeClass.WideCharTypeClass:
+ result = '%sType class=WideChar\n' % indent
- if tc == TypeClass.VoidTypeClass:
- result = '%sType class=Void\n' % indent
- elif tc == TypeClass.BoolTypeClass:
- result = '%sType class=Bool\n' % indent
- elif tc == TypeClass.IntegerTypeClass:
- result = '%sType class=Integer width=%d\n' % (indent, t.width)
- elif tc == TypeClass.FloatTypeClass:
- result = '%sType class=Float\n' % indent
- elif tc == TypeClass.StructureTypeClass:
- result = '%sType class=Structure\n' % indent
- result += obj2str(t.structure, depth+1)
- elif tc == TypeClass.EnumerationTypeClass:
- result = '%sType class=Enumeration\n' % indent
- result += obj2str(t.enumeration, depth+1)
- elif tc == TypeClass.PointerTypeClass:
- result = '%sType class=Pointer\n' % indent
- result += type2str(t.target, depth+1)
- elif tc == TypeClass.ArrayTypeClass:
- result = '%sType class=Array\n' % indent
- elif tc == TypeClass.FunctionTypeClass:
- result = '%sType class=Function\n' % indent
- result += type2str(t.return_value, depth+1)
- for param in t.parameters:
- result += obj2str(param, depth+1)
- elif tc == TypeClass.VarArgsTypeClass:
- result = '%sType class=VarArgs\n' % indent
- elif tc == TypeClass.ValueTypeClass:
- result = '%sType class=Value\n' % indent
- elif tc == TypeClass.NamedTypeReferenceClass:
- result = '%sType class=NamedTypeReference\n' % indent
- result += obj2str(t.named_type_reference, depth+1)
- elif tc == TypeClass.WideCharTypeClass:
- result = '%sType class=WideChar\n' % indent
+ return result
- return result
if __name__ == '__main__':
- binaryninja._init_plugins()
+ binaryninja._init_plugins()
- if len(sys.argv) <= 1:
- raise Exception('supply typelib file')
+ if len(sys.argv) <= 1:
+ raise Exception('supply typelib file')
- fpath = sys.argv[-1]
- print(' reading: %s' % fpath)
+ fpath = sys.argv[-1]
+ print(' reading: %s' % fpath)
- tl = typelibrary.TypeLibrary.load_from_file(fpath)
- print(' name: %s' % tl.name)
- print(' arch: %s' % tl.arch)
- print(' guid: %s' % tl.guid)
- print('dependency_name: %s' % tl.dependency_name)
- print('alternate_names: %s' % tl.alternate_names)
- print(' platform_names: %s' % tl.platform_names)
- print('')
+ tl = typelibrary.TypeLibrary.load_from_file(fpath)
+ print(' name: %s' % tl.name)
+ print(' arch: %s' % tl.arch)
+ print(' guid: %s' % tl.guid)
+ print('dependency_name: %s' % tl.dependency_name)
+ print('alternate_names: %s' % tl.alternate_names)
+ print(' platform_names: %s' % tl.platform_names)
+ print('')
- print(' named_objects: %d' % len(tl.named_objects))
- for (key, val) in tl.named_objects.items():
- print('\t"%s" %s' % (str(key), str(val)))
+ print(' named_objects: %d' % len(tl.named_objects))
+ for (key, val) in tl.named_objects.items():
+ print('\t"%s" %s' % (str(key), str(val)))
- print('')
+ print('')
- print(' named_types: %d' % len(tl.named_types))
- for (key,val) in tl.named_types.items():
- line = 'typelib.named_types["%s"] =' % (str(key))
- print(line)
- print('-'*len(line))
- print(type2str(val))
+ print(' named_types: %d' % len(tl.named_types))
+ for (key, val) in tl.named_types.items():
+ line = 'typelib.named_types["%s"] =' % (str(key))
+ print(line)
+ print('-' * len(line))
+ print(type2str(val))
diff --git a/python/examples/ui_notifications.py b/python/examples/ui_notifications.py
index 9d423f77..4a708061 100644
--- a/python/examples/ui_notifications.py
+++ b/python/examples/ui_notifications.py
@@ -20,74 +20,74 @@
from binaryninjaui import *
+
class UINotification(UIContextNotification):
- def __init__(self):
- UIContextNotification.__init__(self)
- UIContext.registerNotification(self)
- print("py UIContext.registerNotification")
+ def __init__(self):
+ UIContextNotification.__init__(self)
+ UIContext.registerNotification(self)
+ print("py UIContext.registerNotification")
- def __del__(self):
- UIContext.unregisterNotification(self)
- print("py UIContext.unregisterNotification")
+ def __del__(self):
+ UIContext.unregisterNotification(self)
+ print("py UIContext.unregisterNotification")
- def OnContextOpen(self, context):
- print("py OnContextOpen")
+ def OnContextOpen(self, context):
+ print("py OnContextOpen")
- def OnContextClose(self, context):
- print("py OnContextClose")
+ def OnContextClose(self, context):
+ print("py OnContextClose")
- def OnBeforeOpenDatabase(self, context, metadata):
- print(f"py OnBeforeOpenDatabase {metadata.filename}")
- return True
+ def OnBeforeOpenDatabase(self, context, metadata):
+ print(f"py OnBeforeOpenDatabase {metadata.filename}")
+ return True
- def OnAfterOpenDatabase(self, context, metadata, data):
- print(f"py OnAfterOpenDatabase {metadata.filename} {data.name}")
- return True
+ def OnAfterOpenDatabase(self, context, metadata, data):
+ print(f"py OnAfterOpenDatabase {metadata.filename} {data.name}")
+ return True
- def OnBeforeOpenFile(self, context, file):
- print(f"py OnBeforeOpenFile {file.getFilename()}")
- return True
+ def OnBeforeOpenFile(self, context, file):
+ print(f"py OnBeforeOpenFile {file.getFilename()}")
+ return True
- def OnAfterOpenFile(self, context, file, frame):
- print(f"py OnAfterOpenFile {file.getFilename()} {frame.getShortFileName()}")
+ def OnAfterOpenFile(self, context, file, frame):
+ print(f"py OnAfterOpenFile {file.getFilename()} {frame.getShortFileName()}")
- def OnBeforeSaveFile(self, context, file, frame):
- print(f"py OnBeforeSaveFile {file.getFilename()} {frame.getShortFileName()}")
- return True
+ def OnBeforeSaveFile(self, context, file, frame):
+ print(f"py OnBeforeSaveFile {file.getFilename()} {frame.getShortFileName()}")
+ return True
- def OnAfterSaveFile(self, context, file, frame):
- print(f"py OnAfterSaveFile {file.getFilename()} {frame.getShortFileName()}")
+ def OnAfterSaveFile(self, context, file, frame):
+ print(f"py OnAfterSaveFile {file.getFilename()} {frame.getShortFileName()}")
- def OnBeforeCloseFile(self, context, file, frame):
- print(f"py OnBeforeCloseFile {file.getFilename()} {frame.getShortFileName()}")
- return True
+ def OnBeforeCloseFile(self, context, file, frame):
+ print(f"py OnBeforeCloseFile {file.getFilename()} {frame.getShortFileName()}")
+ return True
- def OnAfterCloseFile(self, context, file, frame):
- print(f"py OnAfterCloseFile {file.getFilename()} {frame.getShortFileName()}")
+ def OnAfterCloseFile(self, context, file, frame):
+ print(f"py OnAfterCloseFile {file.getFilename()} {frame.getShortFileName()}")
- def OnViewChange(self, context, frame, type):
- if frame:
- print(f"py OnViewChange {frame.getShortFileName()} / {type}")
- else:
- print("py OnViewChange")
+ def OnViewChange(self, context, frame, type):
+ if frame:
+ print(f"py OnViewChange {frame.getShortFileName()} / {type}")
+ else:
+ print("py OnViewChange")
- def OnAddressChange(self, context, frame, view, location):
- if frame:
- print(f"py OnAddressChange {frame.getShortFileName()} {location.getOffset()}")
- else:
- print(f"py OnAddressChange {location.getOffset()}")
+ def OnAddressChange(self, context, frame, view, location):
+ if frame:
+ print(f"py OnAddressChange {frame.getShortFileName()} {location.getOffset()}")
+ else:
+ print(f"py OnAddressChange {location.getOffset()}")
- def GetNameForFile(self, context, file, name):
- # This function only works in C++: Name is an out param (cpp: &name), and not modifiable by python.
- print(f"py GetNameForFile {file.getFilename()} {name}")
- return False
+ def GetNameForFile(self, context, file, name):
+ # This function only works in C++: Name is an out param (cpp: &name), and not modifiable by python.
+ print(f"py GetNameForFile {file.getFilename()} {name}")
+ return False
- def GetNameForPath(self, context, path, name):
- # This function only works in C++: Name is an out param (cpp: &name), and not modifiable by python.
- print(f"py GetNameForPath {path} {name}")
- return False
+ def GetNameForPath(self, context, path, name):
+ # This function only works in C++: Name is an out param (cpp: &name), and not modifiable by python.
+ print(f"py GetNameForPath {path} {name}")
+ return False
# Register as a global so it doesn't get destructed
notif = UINotification()
-
diff --git a/python/fileaccessor.py b/python/fileaccessor.py
index 85642bff..451b2d20 100644
--- a/python/fileaccessor.py
+++ b/python/fileaccessor.py
@@ -25,6 +25,7 @@ import ctypes
from . import _binaryninjacore as core
from .log import log_error
+
class FileAccessor:
def __init__(self):
self._cb = core.BNFileAccessor()
@@ -39,7 +40,7 @@ class FileAccessor:
def read(self, offset, length):
return NotImplemented
- def write(self, offset:int, data:bytes):
+ def write(self, offset: int, data: bytes):
return NotImplemented
def __len__(self):
diff --git a/python/filemetadata.py b/python/filemetadata.py
index c9f9a050..5fde78d9 100644
--- a/python/filemetadata.py
+++ b/python/filemetadata.py
@@ -26,7 +26,7 @@ from typing import Any, Callable, Optional, List
import binaryninja
from . import _binaryninjacore as core
from .enums import SaveOption
-from . import associateddatastore #required for _FileMetadataAssociatedDataStore
+from . import associateddatastore #required for _FileMetadataAssociatedDataStore
from .log import log_error
from . import binaryview
from . import database
@@ -34,6 +34,7 @@ from . import database
ProgressFuncType = Callable[[int, int], bool]
ViewName = str
+
class NavigationHandler:
def _register(self, handle) -> None:
self._cb = core.BNNavigationHandler()
@@ -43,7 +44,7 @@ class NavigationHandler:
self._cb.navigate = self._cb.navigate.__class__(self._navigate)
core.BNSetFileMetadataNavigationHandler(handle, self._cb)
- def _get_current_view(self, ctxt:Any):
+ def _get_current_view(self, ctxt: Any):
try:
view = self.get_current_view()
except:
@@ -51,14 +52,14 @@ class NavigationHandler:
view = ""
return core.BNAllocString(view)
- def _get_current_offset(self, ctxt:Any) -> int:
+ def _get_current_offset(self, ctxt: Any) -> int:
try:
return self.get_current_offset()
except:
log_error(traceback.format_exc())
return 0
- def _navigate(self, ctxt:Any, view:ViewName, offset:int) -> bool:
+ def _navigate(self, ctxt: Any, view: ViewName, offset: int) -> bool:
try:
return self.navigate(view, offset)
except:
@@ -71,7 +72,7 @@ class NavigationHandler:
def get_current_offset(self) -> int:
return NotImplemented
- def navigate(self, view:ViewName, offset:int) -> bool:
+ def navigate(self, view: ViewName, offset: int) -> bool:
return NotImplemented
@@ -79,7 +80,6 @@ class SaveSettings:
"""
``class SaveSettings`` is used to specify actions and options that apply to saving a database (.bndb).
"""
-
def __init__(self, handle=None):
if handle is None:
self.handle = core.BNCreateSaveSettings()
@@ -90,12 +90,12 @@ class SaveSettings:
if core is not None:
core.BNFreeSaveSettings(self.handle)
- def is_option_set(self, option:SaveOption) -> bool:
+ def is_option_set(self, option: SaveOption) -> bool:
if isinstance(option, str):
option = SaveOption[option]
return core.BNIsSaveSettingsOptionSet(self.handle, option)
- def set_option(self, option:SaveOption, state:bool=True):
+ def set_option(self, option: SaveOption, state: bool = True):
"""
Set a SaveOption in this instance.
@@ -122,7 +122,7 @@ class FileMetadata:
_associated_data = {}
- def __init__(self, filename:Optional[str]=None, handle:Optional[core.BNFileMetadataHandle]=None):
+ def __init__(self, filename: Optional[str] = None, handle: Optional[core.BNFileMetadataHandle] = None):
"""
Instantiates a new FileMetadata class.
@@ -137,7 +137,7 @@ class FileMetadata:
_handle = core.BNCreateFileMetadata()
if filename is not None:
core.BNSetFilename(_handle, str(filename))
- self._nav:Optional[NavigationHandler] = None
+ self._nav: Optional[NavigationHandler] = None
assert _handle is not None
self.handle = _handle
@@ -168,7 +168,7 @@ class FileMetadata:
return self._nav
@nav.setter
- def nav(self, value:NavigationHandler) -> None:
+ def nav(self, value: NavigationHandler) -> None:
self._nav = value
@classmethod
@@ -178,7 +178,7 @@ class FileMetadata:
del cls._associated_data[handle.value]
@staticmethod
- def set_default_session_data(name:str, value:Any) -> None:
+ def set_default_session_data(name: str, value: Any) -> None:
_FileMetadataAssociatedDataStore.set_default(name, value)
@property
@@ -187,7 +187,7 @@ class FileMetadata:
return core.BNGetOriginalFilename(self.handle)
@original_filename.setter
- def original_filename(self, value:str) -> None:
+ def original_filename(self, value: str) -> None:
core.BNSetOriginalFilename(self.handle, str(value))
@property
@@ -196,7 +196,7 @@ class FileMetadata:
return core.BNGetFilename(self.handle)
@filename.setter
- def filename(self, value:str) -> None:
+ def filename(self, value: str) -> None:
core.BNSetFilename(self.handle, str(value))
@property
@@ -205,7 +205,7 @@ class FileMetadata:
return core.BNIsFileModified(self.handle)
@modified.setter
- def modified(self, value:bool) -> None:
+ def modified(self, value: bool) -> None:
if value:
core.BNMarkFileModified(self.handle)
else:
@@ -217,7 +217,7 @@ class FileMetadata:
return core.BNIsAnalysisChanged(self.handle)
@property
- def has_database(self, binary_view_type:ViewName="") -> bool:
+ def has_database(self, binary_view_type: ViewName = "") -> bool:
"""Whether the FileMetadata is backed by a database, or if specified, a specific BinaryViewType (read-only)"""
return core.BNIsBackedByDatabase(self.handle, binary_view_type)
@@ -226,7 +226,7 @@ class FileMetadata:
return core.BNGetCurrentView(self.handle)
@view.setter
- def view(self, value:ViewName) -> None:
+ def view(self, value: ViewName) -> None:
core.BNNavigate(self.handle, str(value), core.BNGetCurrentOffset(self.handle))
@property
@@ -235,7 +235,7 @@ class FileMetadata:
return core.BNGetCurrentOffset(self.handle)
@offset.setter
- def offset(self, value:int) -> None:
+ def offset(self, value: int) -> None:
core.BNNavigate(self.handle, core.BNGetCurrentView(self.handle), value)
@property
@@ -244,7 +244,7 @@ class FileMetadata:
view = core.BNGetFileViewOfType(self.handle, "Raw")
if view is None:
return None
- return binaryview.BinaryView(file_metadata = self, handle = view)
+ return binaryview.BinaryView(file_metadata=self, handle=view)
@property
def database(self) -> Optional['database.Database']:
@@ -260,7 +260,7 @@ class FileMetadata:
return not core.BNIsFileModified(self.handle)
@saved.setter
- def saved(self, value:bool) -> None:
+ def saved(self, value: bool) -> None:
if value:
core.BNMarkFileSaved(self.handle)
else:
@@ -272,7 +272,7 @@ class FileMetadata:
return self._nav
@navigation.setter
- def navigation(self, value:NavigationHandler) -> None:
+ def navigation(self, value: NavigationHandler) -> None:
value._register(self.handle)
self._nav = value
@@ -392,7 +392,7 @@ class FileMetadata:
"""
core.BNRedo(self.handle)
- def navigate(self, view:ViewName, offset:int) -> bool:
+ def navigate(self, view: ViewName, offset: int) -> bool:
"""
``navigate`` navigates the UI to the specified virtual address
@@ -410,7 +410,9 @@ class FileMetadata:
"""
return core.BNNavigate(self.handle, str(view), offset)
- def create_database(self, filename:str, progress_func:Optional[ProgressFuncType]= None, settings:SaveSettings=None):
+ def create_database(
+ self, filename: str, progress_func: Optional[ProgressFuncType] = None, settings: SaveSettings = None
+ ):
"""
``create_database`` writes the current database (.bndb) out to the specified file.
@@ -433,28 +435,32 @@ class FileMetadata:
return core.BNCreateDatabase(self.raw.handle, str(filename), _settings)
else:
_progress_func = progress_func
- return core.BNCreateDatabaseWithProgress(self.raw.handle, str(filename), None,
- ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_ulonglong, ctypes.c_ulonglong)(
- lambda ctxt, cur, total: _progress_func(cur, total)), settings)
+ return core.BNCreateDatabaseWithProgress(
+ self.raw.handle, str(filename), None,
+ ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_ulonglong,
+ ctypes.c_ulonglong)(lambda ctxt, cur, total: _progress_func(cur, total)), settings
+ )
- def open_existing_database(self, filename:str, progress_func:Callable[[int, int], bool]=None):
+ def open_existing_database(self, filename: str, progress_func: Callable[[int, int], bool] = None):
if progress_func is None:
view = core.BNOpenExistingDatabase(self.handle, str(filename))
else:
- view = core.BNOpenExistingDatabaseWithProgress(self.handle, str(filename), None,
- ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_ulonglong, ctypes.c_ulonglong)(
- lambda ctxt, cur, total: progress_func(cur, total)))
+ view = core.BNOpenExistingDatabaseWithProgress(
+ self.handle, str(filename), None,
+ ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_ulonglong,
+ ctypes.c_ulonglong)(lambda ctxt, cur, total: progress_func(cur, total))
+ )
if view is None:
return None
- return binaryview.BinaryView(file_metadata = self, handle = view)
+ return binaryview.BinaryView(file_metadata=self, handle=view)
- def open_database_for_configuration(self, filename:str) -> Optional['binaryview.BinaryView']:
+ def open_database_for_configuration(self, filename: str) -> Optional['binaryview.BinaryView']:
view = core.BNOpenDatabaseForConfiguration(self.handle, str(filename))
if view is None:
return None
- return binaryview.BinaryView(file_metadata = self, handle = view)
+ return binaryview.BinaryView(file_metadata=self, handle=view)
- def save_auto_snapshot(self, progress_func:Optional[ProgressFuncType]=None, settings:SaveSettings=None):
+ def save_auto_snapshot(self, progress_func: Optional[ProgressFuncType] = None, settings: SaveSettings = None):
_settings = None
if settings is not None:
_settings = settings.handle
@@ -464,21 +470,28 @@ class FileMetadata:
return core.BNSaveAutoSnapshot(self.raw.handle, _settings)
else:
_progress_func = progress_func
- return core.BNSaveAutoSnapshotWithProgress(self.raw.handle, None,
- ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_ulonglong, ctypes.c_ulonglong)(
- lambda ctxt, cur, total: _progress_func(cur, total)), _settings)
+ return core.BNSaveAutoSnapshotWithProgress(
+ self.raw.handle, None,
+ ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_ulonglong,
+ ctypes.c_ulonglong)(lambda ctxt, cur, total: _progress_func(cur, total)), _settings
+ )
- def merge_user_analysis(self, path:str, progress_func:ProgressFuncType, excluded_hashes:Optional[List[str]]=None):
+ def merge_user_analysis(
+ self, path: str, progress_func: ProgressFuncType, excluded_hashes: Optional[List[str]] = None
+ ):
if excluded_hashes is None:
excluded_hashes = []
excluded = (ctypes.c_char_p * len(excluded_hashes))()
for i in range(len(excluded_hashes)):
excluded[i] = core.cstr(excluded_hashes[i])
- return core.BNMergeUserAnalysis(self.handle, str(path), None,
- ctypes.CFUNCTYPE(None, ctypes.c_bool, ctypes.c_ulonglong, ctypes.c_ulonglong)(
- lambda ctxt, cur, total: progress_func(cur, total)), excluded, len(excluded_hashes))
+ return core.BNMergeUserAnalysis(
+ self.handle, str(path), None,
+ ctypes.CFUNCTYPE(None, ctypes.c_bool, ctypes.c_ulonglong,
+ ctypes.c_ulonglong)(lambda ctxt, cur, total: progress_func(cur, total)), excluded,
+ len(excluded_hashes)
+ )
- def get_view_of_type(self, name:str) -> Optional['binaryview.BinaryView']:
+ def get_view_of_type(self, name: str) -> Optional['binaryview.BinaryView']:
view = core.BNGetFileViewOfType(self.handle, str(name))
if view is None:
view_type = core.BNGetBinaryViewTypeByName(str(name))
@@ -489,7 +502,7 @@ class FileMetadata:
view = core.BNCreateBinaryViewOfType(view_type, self.raw.handle)
if view is None:
return None
- return binaryview.BinaryView(file_metadata = self, handle = view)
+ return binaryview.BinaryView(file_metadata=self, handle=view)
def open_project(self) -> bool:
return core.BNOpenProject(self.handle)
diff --git a/python/flowgraph.py b/python/flowgraph.py
index 7f4be6e2..165dd2b7 100644
--- a/python/flowgraph.py
+++ b/python/flowgraph.py
@@ -26,8 +26,9 @@ from typing import Optional
# Binary Ninja components
import binaryninja
from . import _binaryninjacore as core
-from .enums import (BranchType, InstructionTextTokenType, HighlightStandardColor, FlowGraphOption,
- EdgePenStyle, ThemeColor)
+from .enums import (
+ BranchType, InstructionTextTokenType, HighlightStandardColor, FlowGraphOption, EdgePenStyle, ThemeColor
+)
from . import function
from . import binaryview
from . import lowlevelil
@@ -52,8 +53,8 @@ class FlowGraphEdge:
return "<%s: %s>" % (self.type.name, repr(self.target))
def __eq__(self, other):
- return (self.type, self.source, self.target, self.points, self.back_edge, self.style) == \
- (other.type, other.source, other.target, other.points, other.back_edge, other.style)
+ return (self.type, self.source, self.target, self.points, self.back_edge,
+ self.style) == (other.type, other.source, other.target, other.points, other.back_edge, other.style)
def __hash__(self):
return hash((self.type, self.source, self.target, self.points, self.back_edge, self.style))
@@ -77,14 +78,14 @@ class EdgeStyle:
return EdgeStyle(edge_style.style, edge_style.width, edge_style.color)
def __eq__(self, other):
- return (self.style, self.width, self.color) == \
- (other.style, other.width, other.color)
+ return (self.style, self.width, self.color) == (other.style, other.width, other.color)
def __hash__(self):
return hash((self.style, self.width, self.color))
+
class FlowGraphNode:
- def __init__(self, graph = None, handle = None):
+ def __init__(self, graph=None, handle=None):
_handle = handle
if _handle is None:
if graph is None:
@@ -94,7 +95,7 @@ class FlowGraphNode:
self.handle = _handle
self._graph = graph
if self._graph is None:
- self._graph = FlowGraph(handle = core.BNGetFlowGraphNodeOwner(self.handle))
+ self._graph = FlowGraph(handle=core.BNGetFlowGraphNodeOwner(self.handle))
def __del__(self):
if core is not None:
@@ -131,7 +132,8 @@ class FlowGraphNode:
try:
for i in range(0, count.value):
addr = lines[i].addr
- if (lines[i].instrIndex != 0xffffffffffffffff) and (block is not None) and hasattr(block, 'il_function'):
+ if (lines[i].instrIndex != 0xffffffffffffffff) and (block
+ is not None) and hasattr(block, 'il_function'):
il_instr = block.__dict__['il_function'][lines[i].instrIndex]
else:
il_instr = None
@@ -142,7 +144,7 @@ class FlowGraphNode:
@property
def graph(self):
- return self._graph
+ return self._graph
@graph.setter
def graph(self, value):
@@ -159,14 +161,18 @@ class FlowGraphNode:
core.BNFreeBasicBlock(block)
return None
- view = binaryview.BinaryView(handle = core.BNGetFunctionData(func_handle))
+ view = binaryview.BinaryView(handle=core.BNGetFunctionData(func_handle))
func = function.Function(view, func_handle)
if core.BNIsLowLevelILBasicBlock(block):
- block = lowlevelil.LowLevelILBasicBlock(block,
- lowlevelil.LowLevelILFunction(func.arch, core.BNGetBasicBlockLowLevelILFunction(block), func), view)
+ block = lowlevelil.LowLevelILBasicBlock(
+ block, lowlevelil.LowLevelILFunction(func.arch, core.BNGetBasicBlockLowLevelILFunction(block), func),
+ view
+ )
elif core.BNIsMediumLevelILBasicBlock(block):
- mlil_func = mediumlevelil.MediumLevelILFunction(func.arch, core.BNGetBasicBlockMediumLevelILFunction(block), func)
+ mlil_func = mediumlevelil.MediumLevelILFunction(
+ func.arch, core.BNGetBasicBlockMediumLevelILFunction(block), func
+ )
block = mediumlevelil.MediumLevelILBasicBlock(block, mlil_func, view)
elif core.BNIsHighLevelILBasicBlock(block):
hlil_func = highlevelil.HighLevelILFunction(func.arch, core.BNGetBasicBlockHighLevelILFunction(block), func)
@@ -230,7 +236,9 @@ class FlowGraphNode:
for i in range(0, len(lines)):
line = lines[i]
if isinstance(line, str):
- line = function.DisassemblyTextLine([function.InstructionTextToken(InstructionTextTokenType.TextToken, line)])
+ line = function.DisassemblyTextLine([
+ function.InstructionTextToken(InstructionTextTokenType.TextToken, line)
+ ])
if not isinstance(line, function.DisassemblyTextLine):
line = function.DisassemblyTextLine(line)
if line.address is None:
@@ -269,7 +277,9 @@ class FlowGraphNode:
points = []
for j in range(0, edges[i].pointCount):
points.append((edges[i].points[j].x, edges[i].points[j].y))
- result.append(FlowGraphEdge(branch_type, self, target, points, edges[i].backEdge, EdgeStyle(edges[i].style)))
+ result.append(
+ FlowGraphEdge(branch_type, self, target, points, edges[i].backEdge, EdgeStyle(edges[i].style))
+ )
core.BNFreeFlowGraphNodeEdgeList(edges, count.value)
return result
@@ -288,7 +298,9 @@ class FlowGraphNode:
points = []
for j in range(0, edges[i].pointCount):
points.append((edges[i].points[j].x, edges[i].points[j].y))
- result.append(FlowGraphEdge(branch_type, self, target, points, edges[i].backEdge, EdgeStyle(edges[i].style)))
+ result.append(
+ FlowGraphEdge(branch_type, self, target, points, edges[i].backEdge, EdgeStyle(edges[i].style))
+ )
core.BNFreeFlowGraphNodeEdgeList(edges, count.value)
return result
@@ -336,7 +348,7 @@ class FlowGraphNode:
class FlowGraphLayoutRequest:
- def __init__(self, graph, callback = None):
+ def __init__(self, graph, callback=None):
self.on_complete = callback
self._cb = ctypes.CFUNCTYPE(None, ctypes.c_void_p)(self._complete)
self.handle = core.BNStartFlowGraphLayout(graph.handle, None, self._cb)
@@ -402,7 +414,7 @@ class FlowGraph:
"""
_registered_instances = []
- def __init__(self, handle:Optional[core.BNCustomFlowGraphHandle] = None):
+ def __init__(self, handle: Optional[core.BNCustomFlowGraphHandle] = None):
_handle = handle
if _handle is None:
self._ext_cb = core.BNCustomFlowGraph()
@@ -541,7 +553,7 @@ class FlowGraph:
func = core.BNGetFunctionForFlowGraph(self.handle)
if func is None:
return None
- return function.Function(handle = func)
+ return function.Function(handle=func)
@function.setter
def function(self, func):
@@ -555,7 +567,7 @@ class FlowGraph:
view = core.BNGetViewForFlowGraph(self.handle)
if view is None:
return None
- return binaryview.BinaryView(handle = view)
+ return binaryview.BinaryView(handle=view)
@view.setter
def view(self, view):
@@ -732,7 +744,7 @@ class FlowGraph:
def shows_secondary_reg_highlighting(self, value):
self.set_option(FlowGraphOption.FlowGraphShowsSecondaryRegisterHighlighting, value)
- def layout(self, callback = None):
+ def layout(self, callback=None):
"""
``layout`` starts rendering a graph for display. Once a layout is complete, each node will contain
coordinates and extents that can be used to render a graph with minimum additional computation.
@@ -807,7 +819,7 @@ class FlowGraph:
"""
return NotImplemented
- def set_option(self, option, value = True):
+ def set_option(self, option, value=True):
core.BNSetFlowGraphOption(self.handle, option, value)
def is_option_set(self, option):
diff --git a/python/function.py b/python/function.py
index 61cc11a8..2e93ac2e 100644
--- a/python/function.py
+++ b/python/function.py
@@ -26,9 +26,10 @@ from dataclasses import dataclass
# Binary Ninja components
from . import _binaryninjacore as core
-from .enums import (AnalysisSkipReason, FunctionGraphType, SymbolType, InstructionTextTokenType,
- HighlightStandardColor, HighlightColorStyle, DisassemblyOption,
- IntegerDisplayType, FunctionAnalysisSkipOverride)
+from .enums import (
+ AnalysisSkipReason, FunctionGraphType, SymbolType, InstructionTextTokenType, HighlightStandardColor,
+ HighlightColorStyle, DisassemblyOption, IntegerDisplayType, FunctionAnalysisSkipOverride
+)
from . import associateddatastore # Required in the main scope due to being an argument for _FunctionAssociatedDataStore
from . import types
@@ -50,30 +51,35 @@ from . import platform as _platform
# The following imports are for backward compatibility with API version < 3.0
# so old plugins which do 'from binaryninja.function import RegisterInfo' will still work
-from .architecture import (RegisterInfo, RegisterStackInfo, IntrinsicInput,
- IntrinsicInfo, InstructionBranch, InstructionInfo, InstructionTextToken)
-from .variable import (Variable, LookupTableEntry, RegisterValue, ValueRange,
- PossibleValueSet, StackVariableReference, ConstantReference, IndirectBranchInfo,
- ParameterVariables, AddressRange)
+from .architecture import (
+ RegisterInfo, RegisterStackInfo, IntrinsicInput, IntrinsicInfo, InstructionBranch, InstructionInfo,
+ InstructionTextToken
+)
+from .variable import (
+ Variable, LookupTableEntry, RegisterValue, ValueRange, PossibleValueSet, StackVariableReference, ConstantReference,
+ IndirectBranchInfo, ParameterVariables, AddressRange
+)
from .enums import RegisterValueType
ExpressionIndex = int
InstructionIndex = int
AnyFunctionType = Union['Function', 'lowlevelil.LowLevelILFunction', 'mediumlevelil.MediumLevelILFunction',
- 'highlevelil.HighLevelILFunction']
+ 'highlevelil.HighLevelILFunction']
ILFunctionType = Union['lowlevelil.LowLevelILFunction', 'mediumlevelil.MediumLevelILFunction',
- 'highlevelil.HighLevelILFunction']
+ 'highlevelil.HighLevelILFunction']
ILInstructionType = Union['lowlevelil.LowLevelILInstruction', 'mediumlevelil.MediumLevelILInstruction',
- 'highlevelil.HighLevelILInstruction']
+ 'highlevelil.HighLevelILInstruction']
StringOrType = Union[str, 'types.Type', 'types.TypeBuilder']
+
def _function_name_():
return inspect.stack()[1][0].f_code.co_name
+
@dataclass(frozen=True)
class ArchAndAddr:
- arch:'architecture.Architecture'
- addr:int
+ arch: 'architecture.Architecture'
+ addr: int
def __repr__(self):
return f"<archandaddr {self.arch} @ {self.addr:#x}>"
@@ -84,7 +90,7 @@ class _FunctionAssociatedDataStore(associateddatastore._AssociatedDataStore):
class DisassemblySettings:
- def __init__(self, handle:core.BNDisassemblySettingsHandle=None):
+ def __init__(self, handle: core.BNDisassemblySettingsHandle = None):
if handle is None:
self.handle = core.BNCreateDisassemblySettings()
else:
@@ -99,7 +105,7 @@ class DisassemblySettings:
return core.BNGetDisassemblyWidth(self.handle)
@width.setter
- def width(self, value:int) -> None:
+ def width(self, value: int) -> None:
core.BNSetDisassemblyWidth(self.handle, value)
@property
@@ -107,15 +113,15 @@ class DisassemblySettings:
return core.BNGetDisassemblyMaximumSymbolWidth(self.handle)
@max_symbol_width.setter
- def max_symbol_width(self, value:int) -> None:
+ def max_symbol_width(self, value: int) -> None:
core.BNSetDisassemblyMaximumSymbolWidth(self.handle, value)
- def is_option_set(self, option:DisassemblyOption) -> bool:
+ def is_option_set(self, option: DisassemblyOption) -> bool:
if isinstance(option, str):
option = DisassemblyOption[option]
return core.BNIsDisassemblySettingsOptionSet(self.handle, option)
- def set_option(self, option:DisassemblyOption, state:bool=True) -> None:
+ def set_option(self, option: DisassemblyOption, state: bool = True) -> None:
if isinstance(option, str):
option = DisassemblyOption[option]
core.BNSetDisassemblySettingsOption(self.handle, option, state)
@@ -123,14 +129,14 @@ class DisassemblySettings:
@dataclass
class ILReferenceSource:
- func:Optional['Function']
- arch:Optional['architecture.Architecture']
- address:int
- il_type:FunctionGraphType
- expr_id:ExpressionIndex
+ func: Optional['Function']
+ arch: Optional['architecture.Architecture']
+ address: int
+ il_type: FunctionGraphType
+ expr_id: ExpressionIndex
@staticmethod
- def get_il_name(il_type:FunctionGraphType) -> str:
+ def get_il_name(il_type: FunctionGraphType) -> str:
if il_type == FunctionGraphType.NormalFunctionGraph:
return 'disassembly'
if il_type == FunctionGraphType.LowLevelILFunctionGraph:
@@ -162,15 +168,18 @@ class ILReferenceSource:
@dataclass
class VariableReferenceSource:
- var:'variable.Variable'
- src:ILReferenceSource
+ var: 'variable.Variable'
+ src: ILReferenceSource
def __repr__(self):
return f"<var: {repr(self.var)}, src: {repr(self.src)}>"
class BasicBlockList:
- def __init__(self, function:Union['Function', 'lowlevelil.LowLevelILFunction', 'mediumlevelil.MediumLevelILFunction', 'highlevelil.HighLevelILFunction']):
+ def __init__(
+ self, function: Union['Function', 'lowlevelil.LowLevelILFunction', 'mediumlevelil.MediumLevelILFunction',
+ 'highlevelil.HighLevelILFunction']
+ ):
self._count, self._blocks = function._basic_block_list()
self._function = function
self._n = 0
@@ -196,7 +205,7 @@ class BasicBlockList:
self._n += 1
return self._function._instantiate_block(block)
- def __getitem__(self, i:Union[int, slice]) -> Union['basicblock.BasicBlock', List['basicblock.BasicBlock']]:
+ def __getitem__(self, i: Union[int, slice]) -> Union['basicblock.BasicBlock', List['basicblock.BasicBlock']]:
if isinstance(i, int):
if i < 0:
i = len(self) + i
@@ -218,45 +227,47 @@ class BasicBlockList:
raise ValueError("BasicBlockList.__getitem__ supports argument of type integer or slice only")
-
class LowLevelILBasicBlockList(BasicBlockList):
-
def __repr__(self):
return f"<LowLevelILBasicBlockList {len(self)} BasicBlocks: {list(self)}>"
- def __getitem__(self, i:Union[int, slice]) -> Union['lowlevelil.LowLevelILBasicBlock', List['lowlevelil.LowLevelILBasicBlock']]:
- return BasicBlockList.__getitem__(self, i) # type: ignore
+ def __getitem__(
+ self, i: Union[int, slice]
+ ) -> Union['lowlevelil.LowLevelILBasicBlock', List['lowlevelil.LowLevelILBasicBlock']]:
+ return BasicBlockList.__getitem__(self, i) # type: ignore
def __next__(self) -> 'lowlevelil.LowLevelILBasicBlock':
- return BasicBlockList.__next__(self) # type: ignore
+ return BasicBlockList.__next__(self) # type: ignore
class MediumLevelILBasicBlockList(BasicBlockList):
-
def __repr__(self):
return f"<MediumLevelILBasicBlockList {len(self)} BasicBlocks: {list(self)}>"
- def __getitem__(self, i:Union[int, slice]) -> Union['mediumlevelil.MediumLevelILBasicBlock', List['mediumlevelil.MediumLevelILBasicBlock']]:
- return BasicBlockList.__getitem__(self, i) # type: ignore
+ def __getitem__(
+ self, i: Union[int, slice]
+ ) -> Union['mediumlevelil.MediumLevelILBasicBlock', List['mediumlevelil.MediumLevelILBasicBlock']]:
+ return BasicBlockList.__getitem__(self, i) # type: ignore
def __next__(self) -> 'mediumlevelil.MediumLevelILBasicBlock':
- return BasicBlockList.__next__(self) # type: ignore
+ return BasicBlockList.__next__(self) # type: ignore
class HighLevelILBasicBlockList(BasicBlockList):
-
def __repr__(self):
return f"<HighLevelILBasicBlockList {len(self)} BasicBlocks: {list(self)}>"
- def __getitem__(self, i:Union[int, slice]) -> Union['highlevelil.HighLevelILBasicBlock', List['highlevelil.HighLevelILBasicBlock']]:
- return BasicBlockList.__getitem__(self, i) # type: ignore
+ def __getitem__(
+ self, i: Union[int, slice]
+ ) -> Union['highlevelil.HighLevelILBasicBlock', List['highlevelil.HighLevelILBasicBlock']]:
+ return BasicBlockList.__getitem__(self, i) # type: ignore
def __next__(self) -> 'highlevelil.HighLevelILBasicBlock':
- return BasicBlockList.__next__(self) # type: ignore
+ return BasicBlockList.__next__(self) # type: ignore
class TagList:
- def __init__(self, function:'Function'):
+ def __init__(self, function: 'Function'):
self._count = ctypes.c_ulonglong()
tags = core.BNGetAddressTagReferences(function.handle, self._count)
assert tags is not None, "core.BNGetAddressTagReferences returned None"
@@ -287,7 +298,10 @@ class TagList:
self._n += 1
return arch, address, binaryview.Tag(core_tag)
- def __getitem__(self, i:Union[int, slice]) -> Union[Tuple['architecture.Architecture', int, 'binaryview.Tag'], List[Tuple['architecture.Architecture', int, 'binaryview.Tag']]]:
+ def __getitem__(
+ self, i: Union[int, slice]
+ ) -> Union[Tuple['architecture.Architecture', int, 'binaryview.Tag'], List[Tuple['architecture.Architecture', int,
+ 'binaryview.Tag']]]:
if isinstance(i, int):
if i < 0:
i = len(self) + i
@@ -322,15 +336,13 @@ class Function:
>>> current_function = bv.functions[0]
>>> here = current_function.start
"""
-
-
- def __init__(self, view:Optional['binaryview.BinaryView']=None, handle:Optional[core.BNFunctionHandle]=None):
+ def __init__(self, view: Optional['binaryview.BinaryView'] = None, handle: Optional[core.BNFunctionHandle] = None):
self._advanced_analysis_requests = 0
assert handle is not None, "creation of standalone 'Function' objects is not implemented"
FunctionHandle = ctypes.POINTER(core.BNFunction)
self.handle = ctypes.cast(handle, FunctionHandle)
if view is None:
- self._view = binaryview.BinaryView(handle = core.BNGetFunctionData(self.handle))
+ self._view = binaryview.BinaryView(handle=core.BNGetFunctionData(self.handle))
else:
self._view = view
self._arch = None
@@ -349,32 +361,32 @@ class Function:
else:
return f"<func: {self.start:#x}>"
- def __eq__(self, other:'Function') -> bool:
+ def __eq__(self, other: 'Function') -> bool:
if not isinstance(other, self.__class__):
return NotImplemented
return ctypes.addressof(self.handle.contents) == ctypes.addressof(other.handle.contents)
- def __ne__(self, other:'Function') -> bool:
+ def __ne__(self, other: 'Function') -> bool:
if not isinstance(other, self.__class__):
return NotImplemented
return not (self == other)
- def __lt__(self, other:'Function') -> bool:
+ def __lt__(self, other: 'Function') -> bool:
if not isinstance(other, self.__class__):
return NotImplemented
return self.start < other.start
- def __gt__(self, other:'Function') -> bool:
+ def __gt__(self, other: 'Function') -> bool:
if not isinstance(other, self.__class__):
return NotImplemented
return self.start > other.start
- def __le__(self, other:'Function') -> bool:
+ def __le__(self, other: 'Function') -> bool:
if not isinstance(other, self.__class__):
return NotImplemented
return self.start <= other.start
- def __ge__(self, other:'Function') -> bool:
+ def __ge__(self, other: 'Function') -> bool:
if not isinstance(other, self.__class__):
return NotImplemented
return self.start >= other.start
@@ -394,19 +406,19 @@ class Function:
result += token.text
return result
- def __contains__(self, value:Union[basicblock.BasicBlock, int]):
+ def __contains__(self, value: Union[basicblock.BasicBlock, int]):
if isinstance(value, basicblock.BasicBlock):
return value.function == self
return self in [block.function for block in self.view.get_basic_blocks_at(int(value))]
@classmethod
- def _unregister(cls, func:'core.BNFunction') -> None:
+ def _unregister(cls, func: 'core.BNFunction') -> None:
handle = ctypes.cast(func, ctypes.c_void_p)
if handle.value in cls._associated_data:
del cls._associated_data[handle.value]
@staticmethod
- def set_default_session_data(name:str, value) -> None:
+ def set_default_session_data(name: str, value) -> None:
_FunctionAssociatedDataStore.set_default(name, value)
@property
@@ -415,7 +427,7 @@ class Function:
return self.symbol.name
@name.setter
- def name(self, value:Union[str, 'types.CoreSymbol']) -> None: # type: ignore
+ def name(self, value: Union[str, 'types.CoreSymbol']) -> None: # type: ignore
if value is None:
if self.symbol is not None:
self.view.undefine_user_symbol(self.symbol)
@@ -450,7 +462,7 @@ class Function:
plat = core.BNGetFunctionPlatform(self.handle)
if plat is None:
return None
- self._platform = _platform.Platform(handle = plat)
+ self._platform = _platform.Platform(handle=plat)
return self._platform
@property
@@ -516,10 +528,10 @@ class Function:
def can_return(self) -> 'types.BoolWithConfidence':
"""Whether function can return"""
result = core.BNCanFunctionReturn(self.handle)
- return types.BoolWithConfidence(result.value, confidence = result.confidence)
+ return types.BoolWithConfidence(result.value, confidence=result.confidence)
@can_return.setter
- def can_return(self, value:'types.BoolWithConfidence') -> None:
+ def can_return(self, value: 'types.BoolWithConfidence') -> None:
bc = core.BNBoolWithConfidence()
bc.value = bool(value)
if hasattr(value, 'confidence'):
@@ -564,15 +576,15 @@ class Function:
core.BNFreeAddressList(addrs)
return result
- def create_user_tag(self, type:'binaryview.TagType', data:str="") -> 'binaryview.Tag':
+ def create_user_tag(self, type: 'binaryview.TagType', data: str = "") -> 'binaryview.Tag':
"""Create a _user_ Tag object"""
return self.create_tag(type, data, True)
- def create_auto_tag(self, type:'binaryview.TagType', data:str="") -> 'binaryview.Tag':
+ def create_auto_tag(self, type: 'binaryview.TagType', data: str = "") -> 'binaryview.Tag':
"""Create an _auto_ Tag object"""
return self.create_tag(type, data, False)
- def create_tag(self, type:'binaryview.TagType', data:str="", user:bool=True) -> 'binaryview.Tag':
+ def create_tag(self, type: 'binaryview.TagType', data: str = "", user: bool = True) -> 'binaryview.Tag':
"""
``create_tag`` creates a new Tag object but does not add it anywhere.
Use :py:meth:`create_user_address_tag` or
@@ -602,7 +614,8 @@ class Function:
"""
return TagList(self)
- def get_address_tags_at(self, addr:int, arch:Optional['architecture.Architecture']=None) -> List['binaryview.Tag']:
+ def get_address_tags_at(self, addr: int,
+ arch: Optional['architecture.Architecture'] = None) -> List['binaryview.Tag']:
"""
``get_address_tags_at`` gets a generator of all Tags in the function at a given address.
@@ -627,8 +640,9 @@ class Function:
finally:
core.BNFreeTagList(tags, count.value)
-
- def add_user_address_tag(self, addr:int, tag:'binaryview.Tag', arch:Optional['architecture.Architecture']=None) -> None:
+ def add_user_address_tag(
+ self, addr: int, tag: 'binaryview.Tag', arch: Optional['architecture.Architecture'] = None
+ ) -> None:
"""
``add_user_address_tag`` adds an already-created Tag object at a given address.
Since this adds a user tag, it will be added to the current undo buffer.
@@ -646,8 +660,10 @@ class Function:
arch = self.arch
core.BNAddUserAddressTag(self.handle, arch.handle, addr, tag.handle)
- def create_user_address_tag(self, addr:int, tag_type:'binaryview.TagType', data:str, unique:bool=False,
- arch:Optional['architecture.Architecture']=None) -> 'binaryview.Tag':
+ def create_user_address_tag(
+ self, addr: int, tag_type: 'binaryview.TagType', data: str, unique: bool = False,
+ arch: Optional['architecture.Architecture'] = None
+ ) -> 'binaryview.Tag':
"""
``create_user_address_tag`` creates and adds a Tag object at a given
address. Since this adds a user tag, it will be added to the current
@@ -678,7 +694,9 @@ class Function:
core.BNAddUserAddressTag(self.handle, arch.handle, addr, tag.handle)
return tag
- def remove_user_address_tag(self, addr:int, tag:'binaryview.TagType', arch:Optional['architecture.Architecture']=None) -> None:
+ def remove_user_address_tag(
+ self, addr: int, tag: 'binaryview.TagType', arch: Optional['architecture.Architecture'] = None
+ ) -> None:
"""
``remove_user_address_tag`` removes a Tag object at a given address.
Since this removes a user tag, it will be added to the current undo buffer.
@@ -694,7 +712,9 @@ class Function:
arch = self.arch
core.BNRemoveUserAddressTag(self.handle, arch.handle, addr, tag.handle)
- def add_auto_address_tag(self, addr:int, tag:'binaryview.TagType', arch:Optional['architecture.Architecture']=None) -> None:
+ def add_auto_address_tag(
+ self, addr: int, tag: 'binaryview.TagType', arch: Optional['architecture.Architecture'] = None
+ ) -> None:
"""
``add_auto_address_tag`` adds an already-created Tag object at a given address.
If you want want to create the tag as well, consider using
@@ -711,7 +731,10 @@ class Function:
arch = self.arch
core.BNAddAutoAddressTag(self.handle, arch.handle, addr, tag.handle)
- def create_auto_address_tag(self, addr:int, type:'binaryview.TagType', data:str, unique:bool=False, arch:Optional['architecture.Architecture']=None) -> 'binaryview.Tag':
+ def create_auto_address_tag(
+ self, addr: int, type: 'binaryview.TagType', data: str, unique: bool = False,
+ arch: Optional['architecture.Architecture'] = None
+ ) -> 'binaryview.Tag':
"""
``create_auto_address_tag`` creates and adds a Tag object at a given address.
@@ -757,7 +780,7 @@ class Function:
finally:
core.BNFreeTagList(tags, count.value)
- def add_user_function_tag(self, tag:'binaryview.Tag') -> None:
+ def add_user_function_tag(self, tag: 'binaryview.Tag') -> None:
"""
``add_user_function_tag`` adds an already-created Tag object as a function tag.
Since this adds a user tag, it will be added to the current undo buffer.
@@ -769,7 +792,7 @@ class Function:
"""
core.BNAddUserFunctionTag(self.handle, tag.handle)
- def create_user_function_tag(self, type:'binaryview.TagType', data:str, unique:bool=False) -> 'binaryview.Tag':
+ def create_user_function_tag(self, type: 'binaryview.TagType', data: str, unique: bool = False) -> 'binaryview.Tag':
"""
``add_user_function_tag`` creates and adds a Tag object as a function tag.
Since this adds a user tag, it will be added to the current undo buffer.
@@ -789,7 +812,7 @@ class Function:
core.BNAddUserFunctionTag(self.handle, tag.handle)
return tag
- def remove_user_function_tag(self, tag:'binaryview.Tag') -> None:
+ def remove_user_function_tag(self, tag: 'binaryview.Tag') -> None:
"""
``remove_user_function_tag`` removes a Tag object as a function tag.
Since this removes a user tag, it will be added to the current undo buffer.
@@ -799,7 +822,7 @@ class Function:
"""
core.BNRemoveUserFunctionTag(self.handle, tag.handle)
- def add_auto_function_tag(self, tag:'binaryview.Tag') -> None:
+ def add_auto_function_tag(self, tag: 'binaryview.Tag') -> None:
"""
``add_auto_function_tag`` adds an already-created Tag object as a function tag.
If you want want to create the tag as well, consider using
@@ -809,7 +832,7 @@ class Function:
"""
core.BNAddAutoFunctionTag(self.handle, tag.handle)
- def create_auto_function_tag(self, type:'binaryview.TagType', data:str, unique:bool=False) -> 'binaryview.Tag':
+ def create_auto_function_tag(self, type: 'binaryview.TagType', data: str, unique: bool = False) -> 'binaryview.Tag':
"""
``create_auto_function_tag`` creates and adds a Tag object as a function tag.
@@ -914,10 +937,10 @@ class Function:
Function type object, can be set with either a string representing the function prototype
(`str(function)` shows examples) or a :py:class:`Type` object
"""
- return types.FunctionType(core.BNGetFunctionType(self.handle), platform = self.platform)
+ return types.FunctionType(core.BNGetFunctionType(self.handle), platform=self.platform)
@function_type.setter
- def function_type(self, value:Union['types.FunctionType', str]) -> None: # type: ignore
+ def function_type(self, value: Union['types.FunctionType', str]) -> None: # type: ignore
if isinstance(value, str):
(parsed_value, new_name) = self.view.parse_type_string(value)
self.name = str(new_name)
@@ -977,7 +1000,13 @@ class Function:
assert branches is not None, "core.BNGetIndirectBranches returned None"
result = []
for i in range(0, count.value):
- result.append(variable.IndirectBranchInfo(architecture.CoreArchitecture._from_cache(branches[i].sourceArch), branches[i].sourceAddr, architecture.CoreArchitecture._from_cache(branches[i].destArch), branches[i].destAddr, branches[i].autoDefined))
+ result.append(
+ variable.IndirectBranchInfo(
+ architecture.CoreArchitecture._from_cache(branches[i].sourceArch), branches[i].sourceAddr,
+ architecture.CoreArchitecture._from_cache(branches[i].destArch), branches[i].destAddr,
+ branches[i].autoDefined
+ )
+ )
core.BNFreeIndirectBranchList(branches)
return result
@@ -1031,10 +1060,12 @@ class Function:
result = core.BNGetFunctionReturnType(self.handle)
if not result.type:
return None
- return types.Type.create(core.BNNewTypeReference(result.type), platform = self.platform, confidence = result.confidence)
+ return types.Type.create(
+ core.BNNewTypeReference(result.type), platform=self.platform, confidence=result.confidence
+ )
@return_type.setter
- def return_type(self, value:StringOrType) -> None: # type: ignore
+ def return_type(self, value: StringOrType) -> None: # type: ignore
type_conf = core.BNTypeWithConfidence()
if value is None:
type_conf.type = None
@@ -1058,12 +1089,12 @@ class Function:
reg_set = []
for i in range(0, result.count):
reg_set.append(self.arch.get_reg_name(result.regs[i]))
- regs = types.RegisterSet(reg_set, confidence = result.confidence)
+ regs = types.RegisterSet(reg_set, confidence=result.confidence)
core.BNFreeRegisterSet(result)
return regs
@return_regs.setter
- def return_regs(self, value:Union['types.RegisterSet', List['architecture.RegisterType']]) -> None: # type: ignore
+ def return_regs(self, value: Union['types.RegisterSet', List['architecture.RegisterType']]) -> None: # type: ignore
regs = core.BNRegisterSetWithConfidence()
regs.regs = (ctypes.c_uint * len(value))()
regs.count = len(value)
@@ -1083,10 +1114,10 @@ class Function:
result = core.BNGetFunctionCallingConvention(self.handle)
if not result.convention:
return None
- return callingconvention.CallingConvention(None, handle = result.convention, confidence = result.confidence)
+ return callingconvention.CallingConvention(None, handle=result.convention, confidence=result.confidence)
@calling_convention.setter
- def calling_convention(self, value:'callingconvention.CallingConvention') -> None:
+ def calling_convention(self, value: 'callingconvention.CallingConvention') -> None:
conv_conf = core.BNCallingConventionWithConfidence()
if value is None:
conv_conf.convention = None
@@ -1108,7 +1139,9 @@ class Function:
return variable.ParameterVariables(var_list, confidence, self)
@parameter_vars.setter
- def parameter_vars(self, value:Optional[Union['variable.ParameterVariables', List['variable.Variable']]]) -> None: # type: ignore
+ def parameter_vars(
+ self, value: Optional[Union['variable.ParameterVariables', List['variable.Variable']]]
+ ) -> None: # type: ignore
if value is None:
var_list = []
else:
@@ -1132,10 +1165,10 @@ class Function:
def has_variable_arguments(self) -> 'types.BoolWithConfidence':
"""Whether the function takes a variable number of arguments"""
result = core.BNFunctionHasVariableArguments(self.handle)
- return types.BoolWithConfidence(result.value, confidence = result.confidence)
+ return types.BoolWithConfidence(result.value, confidence=result.confidence)
@has_variable_arguments.setter
- def has_variable_arguments(self, value:Union[bool, 'types.BoolWithConfidence']) -> None: # type: ignore
+ def has_variable_arguments(self, value: Union[bool, 'types.BoolWithConfidence']) -> None: # type: ignore
bc = core.BNBoolWithConfidence()
bc.value = bool(value)
if isinstance(value, types.BoolWithConfidence):
@@ -1148,10 +1181,10 @@ class Function:
def stack_adjustment(self) -> 'types.OffsetWithConfidence':
"""Number of bytes removed from the stack after return"""
result = core.BNGetFunctionStackAdjustment(self.handle)
- return types.OffsetWithConfidence(result.value, confidence = result.confidence)
+ return types.OffsetWithConfidence(result.value, confidence=result.confidence)
@stack_adjustment.setter
- def stack_adjustment(self, value:'types.OffsetWithConfidence') -> None:
+ def stack_adjustment(self, value: 'types.OffsetWithConfidence') -> None:
oc = core.BNOffsetWithConfidence()
oc.value = int(value)
if hasattr(value, 'confidence'):
@@ -1161,7 +1194,9 @@ class Function:
core.BNSetUserFunctionStackAdjustment(self.handle, oc)
@property
- def reg_stack_adjustments(self) -> Mapping['architecture.RegisterStackName', 'types.RegisterStackAdjustmentWithConfidence']:
+ def reg_stack_adjustments(
+ self
+ ) -> Mapping['architecture.RegisterStackName', 'types.RegisterStackAdjustmentWithConfidence']:
"""Number of entries removed from each register stack after return"""
count = ctypes.c_ulonglong()
adjust = core.BNGetFunctionRegisterStackAdjustments(self.handle, count)
@@ -1171,15 +1206,16 @@ class Function:
result = {}
for i in range(0, count.value):
name = self.arch.get_reg_stack_name(adjust[i].regStack)
- value = types.RegisterStackAdjustmentWithConfidence(adjust[i].adjustment,
- confidence = adjust[i].confidence)
+ value = types.RegisterStackAdjustmentWithConfidence(adjust[i].adjustment, confidence=adjust[i].confidence)
result[name] = value
core.BNFreeRegisterStackAdjustments(adjust)
return result
@reg_stack_adjustments.setter
- def reg_stack_adjustments(self,
- value:Mapping['architecture.RegisterStackName', Union[int, 'types.RegisterStackAdjustmentWithConfidence']]) -> None: # type: ignore
+ def reg_stack_adjustments(
+ self, value: Mapping['architecture.RegisterStackName', Union[int,
+ 'types.RegisterStackAdjustmentWithConfidence']]
+ ) -> None: # type: ignore
adjust = (core.BNRegisterStackAdjustment * len(value))()
if self.arch is None:
raise Exception("Can not get property return_regs with unspecified Architecture")
@@ -1206,12 +1242,14 @@ class Function:
reg_set = []
for i in range(0, result.count):
reg_set.append(self.arch.get_reg_name(result.regs[i]))
- regs = types.RegisterSet(reg_set, confidence = result.confidence)
+ regs = types.RegisterSet(reg_set, confidence=result.confidence)
core.BNFreeRegisterSet(result)
return regs
@clobbered_regs.setter
- def clobbered_regs(self, value:Union['types.RegisterSet', List['architecture.RegisterType']]) -> None: # type: ignore
+ def clobbered_regs(
+ self, value: Union['types.RegisterSet', List['architecture.RegisterType']]
+ ) -> None: # type: ignore
regs = core.BNRegisterSetWithConfidence()
if self.arch is None:
@@ -1238,7 +1276,7 @@ class Function:
return core.BNGetFunctionComment(self.handle)
@comment.setter
- def comment(self, comment:str) -> None:
+ def comment(self, comment: str) -> None:
"""Sets a comment for the current function"""
core.BNSetFunctionComment(self.handle, comment)
@@ -1284,7 +1322,7 @@ class Function:
return core.BNIsFunctionAnalysisSkipped(self.handle)
@analysis_skipped.setter
- def analysis_skipped(self, skip:bool) -> None:
+ def analysis_skipped(self, skip: bool) -> None:
if skip:
core.BNSetFunctionAnalysisSkipOverride(self.handle, FunctionAnalysisSkipOverride.AlwaysSkipFunctionAnalysis)
else:
@@ -1301,7 +1339,7 @@ class Function:
return FunctionAnalysisSkipOverride(core.BNGetFunctionAnalysisSkipOverride(self.handle))
@analysis_skip_override.setter
- def analysis_skip_override(self, override:FunctionAnalysisSkipOverride) -> None:
+ def analysis_skip_override(self, override: FunctionAnalysisSkipOverride) -> None:
core.BNSetFunctionAnalysisSkipOverride(self.handle, override)
@property
@@ -1315,14 +1353,14 @@ class Function:
def mark_recent_use(self) -> None:
core.BNMarkFunctionAsRecentlyUsed(self.handle)
- def get_comment_at(self, addr:int) -> str:
+ def get_comment_at(self, addr: int) -> str:
return core.BNGetCommentForAddress(self.handle, addr)
- def set_comment(self, addr:int, comment:str) -> None:
+ def set_comment(self, addr: int, comment: str) -> None:
"""Deprecated method provided for compatibility. Use set_comment_at instead."""
core.BNSetCommentForAddress(self.handle, addr, comment)
- def set_comment_at(self, addr:int, comment:str) -> None:
+ def set_comment_at(self, addr: int, comment: str) -> None:
"""
``set_comment_at`` sets a comment for the current function at the address specified
@@ -1336,7 +1374,9 @@ class Function:
"""
core.BNSetCommentForAddress(self.handle, addr, comment)
- def add_user_code_ref(self, from_addr:int, to_addr:int, arch:Optional['architecture.Architecture']=None) -> None:
+ def add_user_code_ref(
+ self, from_addr: int, to_addr: int, arch: Optional['architecture.Architecture'] = None
+ ) -> None:
"""
``add_user_code_ref`` places a user-defined cross-reference from the instruction at
the given address and architecture to the specified target address. If the specified
@@ -1360,7 +1400,9 @@ class Function:
core.BNAddUserCodeReference(self.handle, arch.handle, from_addr, to_addr)
- def remove_user_code_ref(self, from_addr:int, to_addr:int, from_arch:Optional['architecture.Architecture']=None) -> None:
+ def remove_user_code_ref(
+ self, from_addr: int, to_addr: int, from_arch: Optional['architecture.Architecture'] = None
+ ) -> None:
"""
``remove_user_code_ref`` removes a user-defined cross-reference.
If the given address is not contained within this function, or if there is no
@@ -1383,8 +1425,9 @@ class Function:
core.BNRemoveUserCodeReference(self.handle, from_arch.handle, from_addr, to_addr)
- def add_user_type_ref(self, from_addr:int, name:'types.QualifiedNameType',
- from_arch:Optional['architecture.Architecture']=None) -> None:
+ def add_user_type_ref(
+ self, from_addr: int, name: 'types.QualifiedNameType', from_arch: Optional['architecture.Architecture'] = None
+ ) -> None:
"""
``add_user_type_ref`` places a user-defined type cross-reference from the instruction at
the given address and architecture to the specified type. If the specified
@@ -1409,7 +1452,9 @@ class Function:
_name = types.QualifiedName(name)._to_core_struct()
core.BNAddUserTypeReference(self.handle, from_arch.handle, from_addr, _name)
- def remove_user_type_ref(self, from_addr:int, name:'types.QualifiedNameType', from_arch:Optional['architecture.Architecture']=None) -> None:
+ def remove_user_type_ref(
+ self, from_addr: int, name: 'types.QualifiedNameType', from_arch: Optional['architecture.Architecture'] = None
+ ) -> None:
"""
``remove_user_type_ref`` removes a user-defined type cross-reference.
If the given address is not contained within this function, or if there is no
@@ -1433,8 +1478,10 @@ class Function:
_name = types.QualifiedName(name)._to_core_struct()
core.BNRemoveUserTypeReference(self.handle, from_arch.handle, from_addr, _name)
- def add_user_type_field_ref(self, from_addr:int, name:'types.QualifiedNameType', offset:int,
- from_arch:Optional['architecture.Architecture']=None, size:int=0) -> None:
+ def add_user_type_field_ref(
+ self, from_addr: int, name: 'types.QualifiedNameType', offset: int,
+ from_arch: Optional['architecture.Architecture'] = None, size: int = 0
+ ) -> None:
"""
``add_user_type_field_ref`` places a user-defined type field cross-reference from the
instruction at the given address and architecture to the specified type. If the specified
@@ -1459,11 +1506,12 @@ class Function:
from_arch = self.arch
_name = types.QualifiedName(name)._to_core_struct()
- core.BNAddUserTypeFieldReference(self.handle, from_arch.handle, from_addr, _name,
- offset, size)
+ core.BNAddUserTypeFieldReference(self.handle, from_arch.handle, from_addr, _name, offset, size)
- def remove_user_type_field_ref(self, from_addr:int, name:'types.QualifiedNameType', offset:int,
- from_arch:Optional['architecture.Architecture']=None, size:int=0) -> None:
+ def remove_user_type_field_ref(
+ self, from_addr: int, name: 'types.QualifiedNameType', offset: int,
+ from_arch: Optional['architecture.Architecture'] = None, size: int = 0
+ ) -> None:
"""
``remove_user_type_field_ref`` removes a user-defined type field cross-reference.
If the given address is not contained within this function, or if there is no
@@ -1487,10 +1535,11 @@ class Function:
from_arch = self.arch
_name = types.QualifiedName(name)._to_core_struct()
- core.BNRemoveUserTypeFieldReference(self.handle, from_arch.handle, from_addr, _name,
- offset, size)
+ core.BNRemoveUserTypeFieldReference(self.handle, from_arch.handle, from_addr, _name, offset, size)
- def get_low_level_il_at(self, addr:int, arch:Optional['architecture.Architecture']=None) -> Optional['lowlevelil.LowLevelILInstruction']:
+ def get_low_level_il_at(
+ self, addr: int, arch: Optional['architecture.Architecture'] = None
+ ) -> Optional['lowlevelil.LowLevelILInstruction']:
"""
``get_low_level_il_at`` gets the LowLevelILInstruction corresponding to the given virtual address
@@ -1515,7 +1564,8 @@ class Function:
return self.llil[idx]
- def get_llil_at(self, addr:int, arch:Optional['architecture.Architecture']=None) -> Optional['lowlevelil.LowLevelILInstruction']:
+ def get_llil_at(self, addr: int,
+ arch: Optional['architecture.Architecture'] = None) -> Optional['lowlevelil.LowLevelILInstruction']:
"""
``get_llil_at`` gets the LowLevelILInstruction corresponding to the given virtual address
@@ -1540,7 +1590,8 @@ class Function:
return self.llil[idx]
- def get_llils_at(self, addr:int, arch:Optional['architecture.Architecture']=None) -> List['lowlevelil.LowLevelILInstruction']:
+ def get_llils_at(self, addr: int,
+ arch: Optional['architecture.Architecture'] = None) -> List['lowlevelil.LowLevelILInstruction']:
"""
``get_llils_at`` gets the LowLevelILInstruction(s) corresponding to the given virtual address
@@ -1566,7 +1617,7 @@ class Function:
core.BNFreeILInstructionList(instrs)
return result
- def get_low_level_il_exits_at(self, addr:int, arch:Optional['architecture.Architecture']=None) -> List[int]:
+ def get_low_level_il_exits_at(self, addr: int, arch: Optional['architecture.Architecture'] = None) -> List[int]:
if arch is None:
if self.arch is None:
raise Exception(f"Can't call {_function_name_()} for function with no architecture specified")
@@ -1580,8 +1631,9 @@ class Function:
core.BNFreeILInstructionList(exits)
return result
- def get_reg_value_at(self, addr:int, reg:'architecture.RegisterType',
- arch:Optional['architecture.Architecture']=None) -> 'variable.RegisterValue':
+ def get_reg_value_at(
+ self, addr: int, reg: 'architecture.RegisterType', arch: Optional['architecture.Architecture'] = None
+ ) -> 'variable.RegisterValue':
"""
``get_reg_value_at`` gets the value the provided string register address corresponding to the given virtual address
@@ -1645,8 +1697,9 @@ class Function:
core.BNFreeTagReferences(tags, count.value)
return result
- def get_reg_value_after(self, addr:int, reg:'architecture.RegisterType',
- arch:Optional['architecture.Architecture']=None) -> 'variable.RegisterValue':
+ def get_reg_value_after(
+ self, addr: int, reg: 'architecture.RegisterType', arch: Optional['architecture.Architecture'] = None
+ ) -> 'variable.RegisterValue':
"""
``get_reg_value_after`` gets the value instruction address corresponding to the given virtual address
@@ -1861,8 +1914,9 @@ class Function:
core.BNFreeTagReferences(refs, count.value)
return result
- def get_stack_contents_at(self, addr:int, offset:int, size:int,
- arch:Optional['architecture.Architecture']=None) -> 'variable.RegisterValue':
+ def get_stack_contents_at(
+ self, addr: int, offset: int, size: int, arch: Optional['architecture.Architecture'] = None
+ ) -> 'variable.RegisterValue':
"""
``get_stack_contents_at`` returns the RegisterValue for the item on the stack in the current function at the
given virtual address ``addr``, stack offset ``offset`` and size of ``size``. Optionally specifying the architecture.
@@ -1883,27 +1937,29 @@ class Function:
"""
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
value = core.BNGetStackContentsAtInstruction(self.handle, arch.handle, addr, offset, size)
result = variable.RegisterValue.from_BNRegisterValue(value, arch)
return result
- def get_stack_contents_after(self, addr:int, offset:int, size:int,
- arch:Optional['architecture.Architecture']=None) -> 'variable.RegisterValue':
+ def get_stack_contents_after(
+ self, addr: int, offset: int, size: int, arch: Optional['architecture.Architecture'] = None
+ ) -> 'variable.RegisterValue':
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
value = core.BNGetStackContentsAfterInstruction(self.handle, arch.handle, addr, offset, size)
result = variable.RegisterValue.from_BNRegisterValue(value, arch)
return result
- def get_parameter_at(self, addr:int, func_type:Optional['types.Type'], i:int,
- arch:Optional['architecture.Architecture']=None) -> 'variable.RegisterValue':
+ def get_parameter_at(
+ self, addr: int, func_type: Optional['types.Type'], i: int, arch: Optional['architecture.Architecture'] = None
+ ) -> 'variable.RegisterValue':
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
_func_type = None
@@ -1925,12 +1981,13 @@ class Function:
"""
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
core.BNRemoveUserAddressTagsOfType(self.handle, arch.handle, addr, tag_type.handle)
- def get_parameter_at_low_level_il_instruction(self, instr:'lowlevelil.InstructionIndex',
- func_type:'types.Type', i:int) -> 'variable.RegisterValue':
+ def get_parameter_at_low_level_il_instruction(
+ self, instr: 'lowlevelil.InstructionIndex', func_type: 'types.Type', i: int
+ ) -> 'variable.RegisterValue':
_func_type = None
if func_type is not None:
_func_type = func_type.handle
@@ -1938,10 +1995,11 @@ class Function:
result = variable.RegisterValue.from_BNRegisterValue(value, self.arch)
return result
- def get_regs_read_by(self, addr:int, arch:Optional['architecture.Architecture']=None) -> List['architecture.RegisterName']:
+ def get_regs_read_by(self, addr: int,
+ arch: Optional['architecture.Architecture'] = None) -> List['architecture.RegisterName']:
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
count = ctypes.c_ulonglong()
regs = core.BNGetRegistersReadByInstruction(self.handle, arch.handle, addr, count)
@@ -1952,10 +2010,11 @@ class Function:
core.BNFreeRegisterList(regs)
return result
- def get_regs_written_by(self, addr:int, arch:Optional['architecture.Architecture']=None) -> List['architecture.RegisterName']:
+ def get_regs_written_by(self, addr: int,
+ arch: Optional['architecture.Architecture'] = None) -> List['architecture.RegisterName']:
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
count = ctypes.c_ulonglong()
regs = core.BNGetRegistersWrittenByInstruction(self.handle, arch.handle, addr, count)
@@ -1966,7 +2025,9 @@ class Function:
core.BNFreeRegisterList(regs)
return result
- def remove_auto_address_tag(self, addr:int, tag:'binaryview.TagType', arch:Optional['architecture.Architecture']=None) -> None:
+ def remove_auto_address_tag(
+ self, addr: int, tag: 'binaryview.TagType', arch: Optional['architecture.Architecture'] = None
+ ) -> None:
"""
``remove_auto_address_tag`` removes a Tag object at a given address.
@@ -1977,7 +2038,7 @@ class Function:
"""
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
core.BNRemoveAutoAddressTag(self.handle, arch.handle, addr, tag.handle)
@@ -1992,25 +2053,31 @@ class Function:
"""
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
core.BNRemoveAutoAddressTagsOfType(self.handle, arch.handle, addr, tag_type.handle)
- def get_stack_vars_referenced_by(self, addr:int,
- arch:Optional['architecture.Architecture']=None) -> List['variable.StackVariableReference']:
+ def get_stack_vars_referenced_by(
+ self, addr: int, arch: Optional['architecture.Architecture'] = None
+ ) -> List['variable.StackVariableReference']:
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
count = ctypes.c_ulonglong()
refs = core.BNGetStackVariablesReferencedByInstruction(self.handle, arch.handle, addr, count)
assert refs is not None, "core.BNGetStackVariablesReferencedByInstruction returned None"
result = []
for i in range(0, count.value):
- var_type = types.Type.create(core.BNNewTypeReference(refs[i].type), platform = self.platform, confidence = refs[i].typeConfidence)
+ var_type = types.Type.create(
+ core.BNNewTypeReference(refs[i].type), platform=self.platform, confidence=refs[i].typeConfidence
+ )
var = variable.Variable.from_identifier(self, refs[i].varIdentifier)
- result.append(variable.StackVariableReference(refs[i].sourceOperand, var_type, refs[i].name, var,
- refs[i].referencedOffset, refs[i].size))
+ result.append(
+ variable.StackVariableReference(
+ refs[i].sourceOperand, var_type, refs[i].name, var, refs[i].referencedOffset, refs[i].size
+ )
+ )
core.BNFreeStackVariableReferenceList(refs, count.value)
return result
@@ -2050,11 +2117,12 @@ class Function:
core.BNFreeTagList(tags, count.value)
return result
- def get_lifted_il_at(self, addr:int,
- arch:Optional['architecture.Architecture']=None) -> Optional['lowlevelil.LowLevelILInstruction']:
+ def get_lifted_il_at(
+ self, addr: int, arch: Optional['architecture.Architecture'] = None
+ ) -> Optional['lowlevelil.LowLevelILInstruction']:
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
idx = core.BNGetLiftedILForInstruction(self.handle, arch.handle, addr)
@@ -2064,8 +2132,9 @@ class Function:
return self.lifted_il[idx]
- def get_lifted_ils_at(self, addr:int,
- arch:Optional['architecture.Architecture']=None) -> List['lowlevelil.LowLevelILInstruction']:
+ def get_lifted_ils_at(
+ self, addr: int, arch: Optional['architecture.Architecture'] = None
+ ) -> List['lowlevelil.LowLevelILInstruction']:
"""
``get_lifted_ils_at`` gets the Lifted IL Instruction(s) corresponding to the given virtual address
@@ -2079,7 +2148,7 @@ class Function:
"""
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
count = ctypes.c_ulonglong()
instrs = core.BNGetLiftedILInstructionsForAddress(self.handle, arch.handle, addr, count)
@@ -2157,22 +2226,24 @@ class Function:
"""
core.BNRemoveUserFunctionTagsOfType(self.handle, tag_type.handle)
- def get_constants_referenced_by(self, addr:int,
- arch:'architecture.Architecture'=None) -> List[variable.ConstantReference]:
+ def get_constants_referenced_by(self, addr: int,
+ arch: 'architecture.Architecture' = None) -> List[variable.ConstantReference]:
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
count = ctypes.c_ulonglong()
refs = core.BNGetConstantsReferencedByInstruction(self.handle, arch.handle, addr, count)
assert refs is not None, "core.BNGetConstantsReferencedByInstruction returned None"
result = []
for i in range(0, count.value):
- result.append(variable.ConstantReference(refs[i].value, refs[i].size, refs[i].pointer, refs[i].intermediate))
+ result.append(
+ variable.ConstantReference(refs[i].value, refs[i].size, refs[i].pointer, refs[i].intermediate)
+ )
core.BNFreeConstantReferenceList(refs)
return result
- def remove_auto_function_tag(self, tag:'binaryview.Tag') -> None:
+ def remove_auto_function_tag(self, tag: 'binaryview.Tag') -> None:
"""
``remove_user_function_tag`` removes a Tag object as a function tag.
@@ -2190,10 +2261,11 @@ class Function:
"""
core.BNRemoveAutoFunctionTagsOfType(self.handle, tag_type.handle)
- def get_lifted_il_flag_uses_for_definition(self, i:'lowlevelil.InstructionIndex',
- flag:'architecture.FlagType') -> List['lowlevelil.LowLevelILInstruction']:
+ def get_lifted_il_flag_uses_for_definition(
+ self, i: 'lowlevelil.InstructionIndex', flag: 'architecture.FlagType'
+ ) -> List['lowlevelil.LowLevelILInstruction']:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
flag = self.arch.get_flag_index(flag)
count = ctypes.c_ulonglong()
instrs = core.BNGetLiftedILFlagUsesForDefinition(self.handle, i, flag, count)
@@ -2204,10 +2276,10 @@ class Function:
core.BNFreeILInstructionList(instrs)
return result
- def get_lifted_il_flag_definitions_for_use(self, i:'lowlevelil.InstructionIndex',
- flag:'architecture.FlagType') -> List['lowlevelil.InstructionIndex']:
+ def get_lifted_il_flag_definitions_for_use(self, i: 'lowlevelil.InstructionIndex',
+ flag: 'architecture.FlagType') -> List['lowlevelil.InstructionIndex']:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
flag = self.arch.get_flag_index(flag)
count = ctypes.c_ulonglong()
@@ -2219,10 +2291,10 @@ class Function:
core.BNFreeILInstructionList(instrs)
return result
- def get_flags_read_by_lifted_il_instruction(self, i:'lowlevelil.InstructionIndex') -> \
- List['architecture.FlagName']:
+ def get_flags_read_by_lifted_il_instruction(self,
+ i: 'lowlevelil.InstructionIndex') -> List['architecture.FlagName']:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
count = ctypes.c_ulonglong()
flags = core.BNGetFlagsReadByLiftedILInstruction(self.handle, i, count)
@@ -2233,11 +2305,11 @@ class Function:
core.BNFreeRegisterList(flags)
return result
- def get_flags_written_by_lifted_il_instruction(self, i:'lowlevelil.InstructionIndex') -> \
- List['architecture.FlagName']:
+ def get_flags_written_by_lifted_il_instruction(self,
+ i: 'lowlevelil.InstructionIndex') -> List['architecture.FlagName']:
count = ctypes.c_ulonglong()
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
flags = core.BNGetFlagsWrittenByLiftedILInstruction(self.handle, i, count)
assert flags is not None, "core.BNGetFlagsWrittenByLiftedILInstruction returned None"
@@ -2247,29 +2319,33 @@ class Function:
core.BNFreeRegisterList(flags)
return result
- def create_graph(self, graph_type:FunctionGraphType=FunctionGraphType.NormalFunctionGraph,
- settings:'DisassemblySettings'=None) -> flowgraph.CoreFlowGraph:
+ def create_graph(
+ self, graph_type: FunctionGraphType = FunctionGraphType.NormalFunctionGraph,
+ settings: 'DisassemblySettings' = None
+ ) -> flowgraph.CoreFlowGraph:
if settings is not None:
settings_obj = settings.handle
else:
settings_obj = None
return flowgraph.CoreFlowGraph(core.BNCreateFunctionGraph(self.handle, graph_type, settings_obj))
- def apply_imported_types(self, sym:'types.CoreSymbol', type:Optional[StringOrType]=None) -> None:
+ def apply_imported_types(self, sym: 'types.CoreSymbol', type: Optional[StringOrType] = None) -> None:
if isinstance(type, str):
(type, _) = self.view.parse_type_string(type)
core.BNApplyImportedTypes(self.handle, sym.handle, None if type is None else type.handle)
- def apply_auto_discovered_type(self, func_type:StringOrType) -> None:
+ def apply_auto_discovered_type(self, func_type: StringOrType) -> None:
if isinstance(func_type, str):
(func_type, _) = self.view.parse_type_string(func_type)
core.BNApplyAutoDiscoveredFunctionType(self.handle, func_type.handle)
- def set_auto_indirect_branches(self, source:int, branches:List[Tuple['architecture.Architecture', int]],
- source_arch:Optional['architecture.Architecture']=None) -> None:
+ def set_auto_indirect_branches(
+ self, source: int, branches: List[Tuple['architecture.Architecture', int]],
+ source_arch: Optional['architecture.Architecture'] = None
+ ) -> None:
if source_arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
source_arch = self.arch
branch_list = (core.BNArchitectureAndAddress * len(branches))()
for i in range(len(branches)):
@@ -2277,11 +2353,13 @@ class Function:
branch_list[i].address = branches[i][1]
core.BNSetAutoIndirectBranches(self.handle, source_arch.handle, source, branch_list, len(branches))
- def set_user_indirect_branches(self, source:int, branches:List[Tuple['architecture.Architecture', int]],
- source_arch:Optional['architecture.Architecture']=None) -> None:
+ def set_user_indirect_branches(
+ self, source: int, branches: List[Tuple['architecture.Architecture', int]],
+ source_arch: Optional['architecture.Architecture'] = None
+ ) -> None:
if source_arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
source_arch = self.arch
branch_list = (core.BNArchitectureAndAddress * len(branches))()
for i in range(len(branches)):
@@ -2289,10 +2367,12 @@ class Function:
branch_list[i].address = branches[i][1]
core.BNSetUserIndirectBranches(self.handle, source_arch.handle, source, branch_list, len(branches))
- def get_indirect_branches_at(self, addr:int, arch:Optional['architecture.Architecture']=None) -> List['variable.IndirectBranchInfo']:
+ def get_indirect_branches_at(
+ self, addr: int, arch: Optional['architecture.Architecture'] = None
+ ) -> List['variable.IndirectBranchInfo']:
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
count = ctypes.c_ulonglong()
branches = core.BNGetIndirectBranchesAt(self.handle, arch.handle, addr, count)
@@ -2300,13 +2380,19 @@ class Function:
assert branches is not None, "core.BNGetIndirectBranchesAt returned None"
result = []
for i in range(count.value):
- result.append(variable.IndirectBranchInfo(architecture.CoreArchitecture._from_cache(branches[i].sourceArch), branches[i].sourceAddr, architecture.CoreArchitecture._from_cache(branches[i].destArch), branches[i].destAddr, branches[i].autoDefined))
+ result.append(
+ variable.IndirectBranchInfo(
+ architecture.CoreArchitecture._from_cache(branches[i].sourceArch), branches[i].sourceAddr,
+ architecture.CoreArchitecture._from_cache(branches[i].destArch), branches[i].destAddr,
+ branches[i].autoDefined
+ )
+ )
return result
finally:
core.BNFreeIndirectBranchList(branches)
- def get_block_annotations(self, addr:int, arch:Optional['architecture.Architecture']=None) -> \
- List[List['InstructionTextToken']]:
+ def get_block_annotations(self, addr: int,
+ arch: Optional['architecture.Architecture'] = None) -> List[List['InstructionTextToken']]:
if arch is None:
if self.arch is None:
raise Exception("can not get_block_annotations if Function.arch is None")
@@ -2322,17 +2408,17 @@ class Function:
finally:
core.BNFreeInstructionTextLines(lines, count.value)
- def set_auto_type(self, value:StringOrType) -> None:
+ def set_auto_type(self, value: StringOrType) -> None:
if isinstance(value, str):
(value, _) = self.view.parse_type_string(value)
core.BNSetFunctionAutoType(self.handle, value.handle)
- def set_user_type(self, value:StringOrType) -> None:
+ def set_user_type(self, value: StringOrType) -> None:
if isinstance(value, str):
(value, _) = self.view.parse_type_string(value)
core.BNSetFunctionUserType(self.handle, value.handle)
- def set_auto_return_type(self, value:StringOrType) -> None:
+ def set_auto_return_type(self, value: StringOrType) -> None:
type_conf = core.BNTypeWithConfidence()
if value is None:
type_conf.type = None
@@ -2346,7 +2432,7 @@ class Function:
type_conf.confidence = value.confidence
core.BNSetAutoFunctionReturnType(self.handle, type_conf)
- def set_auto_return_regs(self, value:Union['types.RegisterSet', List['architecture.RegisterType']]) -> None:
+ def set_auto_return_regs(self, value: Union['types.RegisterSet', List['architecture.RegisterType']]) -> None:
regs = core.BNRegisterSetWithConfidence()
regs.regs = (ctypes.c_uint * len(value))()
regs.count = len(value)
@@ -2361,7 +2447,7 @@ class Function:
regs.confidence = core.max_confidence
core.BNSetAutoFunctionReturnRegisters(self.handle, regs)
- def set_auto_calling_convention(self, value:'callingconvention.CallingConvention') -> None:
+ def set_auto_calling_convention(self, value: 'callingconvention.CallingConvention') -> None:
conv_conf = core.BNCallingConventionWithConfidence()
if value is None:
conv_conf.convention = None
@@ -2371,8 +2457,9 @@ class Function:
conv_conf.confidence = value.confidence
core.BNSetAutoFunctionCallingConvention(self.handle, conv_conf)
- def set_auto_parameter_vars(self, value:Optional[Union[List['variable.Variable'], 'variable.Variable', \
- 'variable.ParameterVariables']]) -> None:
+ def set_auto_parameter_vars(
+ self, value: Optional[Union[List['variable.Variable'], 'variable.Variable', 'variable.ParameterVariables']]
+ ) -> None:
if value is None:
var_list = []
elif isinstance(value, variable.Variable):
@@ -2396,7 +2483,7 @@ class Function:
var_conf.confidence = core.max_confidence
core.BNSetAutoFunctionParameterVariables(self.handle, var_conf)
- def set_auto_has_variable_arguments(self, value:Union[bool, 'types.BoolWithConfidence']) -> None:
+ def set_auto_has_variable_arguments(self, value: Union[bool, 'types.BoolWithConfidence']) -> None:
bc = core.BNBoolWithConfidence()
bc.value = bool(value)
if isinstance(value, types.BoolWithConfidence):
@@ -2405,7 +2492,7 @@ class Function:
bc.confidence = core.max_confidence
core.BNSetAutoFunctionHasVariableArguments(self.handle, bc)
- def set_auto_can_return(self, value:Union[bool, 'types.BoolWithConfidence']) -> None:
+ def set_auto_can_return(self, value: Union[bool, 'types.BoolWithConfidence']) -> None:
bc = core.BNBoolWithConfidence()
bc.value = bool(value)
if isinstance(value, types.BoolWithConfidence):
@@ -2414,7 +2501,7 @@ class Function:
bc.confidence = core.max_confidence
core.BNSetAutoFunctionCanReturn(self.handle, bc)
- def set_auto_stack_adjustment(self, value:Union[int, 'types.OffsetWithConfidence']) -> None:
+ def set_auto_stack_adjustment(self, value: Union[int, 'types.OffsetWithConfidence']) -> None:
oc = core.BNOffsetWithConfidence()
oc.value = int(value)
if isinstance(value, types.OffsetWithConfidence):
@@ -2423,7 +2510,9 @@ class Function:
oc.confidence = core.max_confidence
core.BNSetAutoFunctionStackAdjustment(self.handle, oc)
- def set_auto_reg_stack_adjustments(self, value:Mapping['architecture.RegisterStackName', 'types.RegisterStackAdjustmentWithConfidence']):
+ def set_auto_reg_stack_adjustments(
+ self, value: Mapping['architecture.RegisterStackName', 'types.RegisterStackAdjustmentWithConfidence']
+ ):
adjust = (core.BNRegisterStackAdjustment * len(value))()
i = 0
if self.arch is None:
@@ -2440,7 +2529,7 @@ class Function:
i += 1
core.BNSetAutoFunctionRegisterStackAdjustments(self.handle, adjust, len(value))
- def set_auto_clobbered_regs(self, value:List['architecture.RegisterType']) -> None:
+ def set_auto_clobbered_regs(self, value: List['architecture.RegisterType']) -> None:
regs = core.BNRegisterSetWithConfidence()
regs.regs = (ctypes.c_uint * len(value))()
regs.count = len(value)
@@ -2455,7 +2544,9 @@ class Function:
regs.confidence = core.max_confidence
core.BNSetAutoFunctionClobberedRegisters(self.handle, regs)
- def get_int_display_type(self, instr_addr:int, value:int, operand:int, arch:Optional['architecture.Architecture']=None) -> IntegerDisplayType:
+ def get_int_display_type(
+ self, instr_addr: int, value: int, operand: int, arch: Optional['architecture.Architecture'] = None
+ ) -> IntegerDisplayType:
"""
Get the current text display type for an integer token in the disassembly or IL views
:param int instr_addr: Address of the instruction or IL line containing the token
@@ -2465,11 +2556,16 @@ class Function:
"""
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
- return IntegerDisplayType(core.BNGetIntegerConstantDisplayType(self.handle, arch.handle, instr_addr, value, operand))
+ return IntegerDisplayType(
+ core.BNGetIntegerConstantDisplayType(self.handle, arch.handle, instr_addr, value, operand)
+ )
- def set_int_display_type(self, instr_addr:int, value:int, operand:int, display_type:IntegerDisplayType, arch:Optional['architecture.Architecture']=None) -> None:
+ def set_int_display_type(
+ self, instr_addr: int, value: int, operand: int, display_type: IntegerDisplayType,
+ arch: Optional['architecture.Architecture'] = None
+ ) -> None:
"""
Change the text display type for an integer token in the disassembly or IL views
:param int instr_addr: Address of the instruction or IL line containing the token
@@ -2480,7 +2576,7 @@ class Function:
"""
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
if isinstance(display_type, str):
display_type = IntegerDisplayType[display_type]
@@ -2502,7 +2598,8 @@ class Function:
core.BNReleaseAdvancedFunctionAnalysisData(self.handle)
self._advanced_analysis_requests -= 1
- def get_basic_block_at(self, addr:int, arch:Optional['architecture.Architecture']=None) -> Optional['basicblock.BasicBlock']:
+ def get_basic_block_at(self, addr: int,
+ arch: Optional['architecture.Architecture'] = None) -> Optional['basicblock.BasicBlock']:
"""
``get_basic_block_at`` returns the BasicBlock of the optionally specified Architecture ``arch`` at the given
address ``addr``.
@@ -2515,14 +2612,16 @@ class Function:
"""
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
block = core.BNGetFunctionBasicBlockAtAddress(self.handle, arch.handle, addr)
if not block:
return None
return basicblock.BasicBlock(block, self._view)
- def get_instr_highlight(self, addr:int, arch:Optional['architecture.Architecture']=None) -> '_highlight.HighlightColor':
+ def get_instr_highlight(
+ self, addr: int, arch: Optional['architecture.Architecture'] = None
+ ) -> '_highlight.HighlightColor':
"""
:Example:
>>> current_function.set_user_instr_highlight(here, highlight.HighlightColor(red=0xff, blue=0xff, green=0))
@@ -2531,19 +2630,23 @@ class Function:
"""
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
color = core.BNGetInstructionHighlight(self.handle, arch.handle, addr)
if color.style == HighlightColorStyle.StandardHighlightColor:
- return _highlight.HighlightColor(color = color.color, alpha = color.alpha)
+ return _highlight.HighlightColor(color=color.color, alpha=color.alpha)
elif color.style == HighlightColorStyle.MixedHighlightColor:
- return _highlight.HighlightColor(color = color.color, mix_color = color.mixColor, mix = color.mix, alpha = color.alpha)
+ return _highlight.HighlightColor(
+ color=color.color, mix_color=color.mixColor, mix=color.mix, alpha=color.alpha
+ )
elif color.style == HighlightColorStyle.CustomHighlightColor:
- return _highlight.HighlightColor(red = color.r, green = color.g, blue = color.b, alpha = color.alpha)
- return _highlight.HighlightColor(color = HighlightStandardColor.NoHighlightColor)
+ return _highlight.HighlightColor(red=color.r, green=color.g, blue=color.b, alpha=color.alpha)
+ return _highlight.HighlightColor(color=HighlightStandardColor.NoHighlightColor)
- def set_auto_instr_highlight(self, addr:int, color:Union['_highlight.HighlightColor', HighlightStandardColor],
- arch:Optional['architecture.Architecture']=None):
+ def set_auto_instr_highlight(
+ self, addr: int, color: Union['_highlight.HighlightColor', HighlightStandardColor],
+ arch: Optional['architecture.Architecture'] = None
+ ):
"""
``set_auto_instr_highlight`` highlights the instruction at the specified address with the supplied color
@@ -2555,17 +2658,18 @@ class Function:
"""
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
if not isinstance(color, HighlightStandardColor) and not isinstance(color, _highlight.HighlightColor):
raise ValueError("Specified color is not one of HighlightStandardColor, _highlight.HighlightColor")
if isinstance(color, HighlightStandardColor):
- color = _highlight.HighlightColor(color = color)
+ color = _highlight.HighlightColor(color=color)
core.BNSetAutoInstructionHighlight(self.handle, arch.handle, addr, color._to_core_struct())
-
- def set_user_instr_highlight(self, addr:int, color:Union['_highlight.HighlightColor', HighlightStandardColor],
- arch:Optional['architecture.Architecture']=None):
+ def set_user_instr_highlight(
+ self, addr: int, color: Union['_highlight.HighlightColor', HighlightStandardColor],
+ arch: Optional['architecture.Architecture'] = None
+ ):
"""
``set_user_instr_highlight`` highlights the instruction at the specified address with the supplied color
@@ -2579,7 +2683,7 @@ class Function:
"""
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
if not isinstance(color, HighlightStandardColor) and not isinstance(color, _highlight.HighlightColor):
raise ValueError("Specified color is not one of HighlightStandardColor, highlight.HighlightColor")
@@ -2587,49 +2691,52 @@ class Function:
color = _highlight.HighlightColor(color)
core.BNSetUserInstructionHighlight(self.handle, arch.handle, addr, color._to_core_struct())
- def create_auto_stack_var(self, offset:int, var_type:StringOrType, name:str) -> None:
+ def create_auto_stack_var(self, offset: int, var_type: StringOrType, name: str) -> None:
if isinstance(var_type, str):
(var_type, _) = self.view.parse_type_string(var_type)
tc = var_type._to_core_struct()
core.BNCreateAutoStackVariable(self.handle, offset, tc, name)
- def create_user_stack_var(self, offset:int, var_type:StringOrType, name:str) -> None:
+ def create_user_stack_var(self, offset: int, var_type: StringOrType, name: str) -> None:
if isinstance(var_type, str):
(var_type, _) = self.view.parse_type_string(var_type)
tc = var_type._to_core_struct()
core.BNCreateUserStackVariable(self.handle, offset, tc, name)
- def delete_auto_stack_var(self, offset:int) -> None:
+ def delete_auto_stack_var(self, offset: int) -> None:
core.BNDeleteAutoStackVariable(self.handle, offset)
- def delete_user_stack_var(self, offset:int) -> None:
+ def delete_user_stack_var(self, offset: int) -> None:
core.BNDeleteUserStackVariable(self.handle, offset)
- def create_auto_var(self, var:'variable.Variable', var_type:StringOrType, name:str,
- ignore_disjoint_uses:bool=False) -> None:
+ def create_auto_var(
+ self, var: 'variable.Variable', var_type: StringOrType, name: str, ignore_disjoint_uses: bool = False
+ ) -> None:
if isinstance(var_type, str):
(var_type, _) = self.view.parse_type_string(var_type)
tc = var_type._to_core_struct()
core.BNCreateAutoVariable(self.handle, var.to_BNVariable(), tc, name, ignore_disjoint_uses)
- def create_user_var(self, var:'variable.Variable', var_type:StringOrType, name:str,
- ignore_disjoint_uses:bool=False) -> None:
+ def create_user_var(
+ self, var: 'variable.Variable', var_type: StringOrType, name: str, ignore_disjoint_uses: bool = False
+ ) -> None:
if isinstance(var_type, str):
(var_type, _) = self.view.parse_type_string(var_type)
tc = var_type._to_core_struct()
core.BNCreateUserVariable(self.handle, var.to_BNVariable(), tc, name, ignore_disjoint_uses)
- def delete_user_var(self, var:'variable.Variable') -> None:
+ def delete_user_var(self, var: 'variable.Variable') -> None:
core.BNDeleteUserVariable(self.handle, var.to_BNVariable())
- def is_var_user_defined(self, var:'variable.Variable') -> bool:
+ def is_var_user_defined(self, var: 'variable.Variable') -> bool:
return core.BNIsVariableUserDefined(self.handle, var.to_BNVariable())
- def get_stack_var_at_frame_offset(self, offset:int, addr:int, arch:Optional['architecture.Architecture']=None) -> \
- Optional['variable.Variable']:
+ def get_stack_var_at_frame_offset(
+ self, offset: int, addr: int, arch: Optional['architecture.Architecture'] = None
+ ) -> Optional['variable.Variable']:
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
found_var = core.BNVariableNameAndType()
if not core.BNGetStackVariableAtFrameOffset(self.handle, arch.handle, addr, offset, found_var):
@@ -2638,7 +2745,7 @@ class Function:
core.BNFreeVariableNameAndType(found_var)
return result
- def get_type_tokens(self, settings:'DisassemblySettings'=None) -> List['DisassemblyTextLine']:
+ def get_type_tokens(self, settings: 'DisassemblySettings' = None) -> List['DisassemblyTextLine']:
_settings = None
if settings is not None:
_settings = settings.handle
@@ -2650,32 +2757,36 @@ class Function:
addr = lines[i].addr
color = _highlight.HighlightColor._from_core_struct(lines[i].highlight)
tokens = InstructionTextToken._from_core_struct(lines[i].tokens, lines[i].count)
- result.append(DisassemblyTextLine(tokens, addr, color = color))
+ result.append(DisassemblyTextLine(tokens, addr, color=color))
core.BNFreeDisassemblyTextLines(lines, count.value)
return result
- def get_reg_value_at_exit(self, reg:'architecture.RegisterType') -> 'variable.RegisterValue':
+ def get_reg_value_at_exit(self, reg: 'architecture.RegisterType') -> 'variable.RegisterValue':
if self.arch is None:
raise Exception("can not get_reg_value_at_exit if Function.arch is")
result = core.BNGetFunctionRegisterValueAtExit(self.handle, self.arch.get_reg_index(reg))
return variable.RegisterValue.from_BNRegisterValue(result, self.arch)
- def set_auto_call_stack_adjustment(self, addr:int, adjust:Union[int, 'types.OffsetWithConfidence'],
- arch:Optional['architecture.Architecture']=None) -> None:
+ def set_auto_call_stack_adjustment(
+ self, addr: int, adjust: Union[int, 'types.OffsetWithConfidence'],
+ arch: Optional['architecture.Architecture'] = None
+ ) -> None:
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
if not isinstance(adjust, types.OffsetWithConfidence):
adjust = types.OffsetWithConfidence(adjust)
core.BNSetAutoCallStackAdjustment(self.handle, arch.handle, addr, adjust.value, adjust.confidence)
- def set_auto_call_reg_stack_adjustment(self, addr:int, adjust:Mapping['architecture.RegisterStackName', int],
- arch:Optional['architecture.Architecture']=None) -> None:
+ def set_auto_call_reg_stack_adjustment(
+ self, addr: int, adjust: Mapping['architecture.RegisterStackName', int],
+ arch: Optional['architecture.Architecture'] = None
+ ) -> None:
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
adjust_buf = (core.BNRegisterStackAdjustment * len(adjust))()
i = 0
@@ -2689,25 +2800,29 @@ class Function:
i += 1
core.BNSetAutoCallRegisterStackAdjustment(self.handle, arch.handle, addr, adjust_buf, len(adjust))
- def set_auto_call_reg_stack_adjustment_for_reg_stack(self, addr:int, reg_stack:'architecture.RegisterStackType',
- adjust, arch:Optional['architecture.Architecture']=None) -> None:
+ def set_auto_call_reg_stack_adjustment_for_reg_stack(
+ self, addr: int, reg_stack: 'architecture.RegisterStackType', adjust,
+ arch: Optional['architecture.Architecture'] = None
+ ) -> None:
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
reg_stack = arch.get_reg_stack_index(reg_stack)
if not isinstance(adjust, types.RegisterStackAdjustmentWithConfidence):
adjust = types.RegisterStackAdjustmentWithConfidence(adjust)
- core.BNSetAutoCallRegisterStackAdjustmentForRegisterStack(self.handle, arch.handle, addr, reg_stack,
- adjust.value, adjust.confidence)
+ core.BNSetAutoCallRegisterStackAdjustmentForRegisterStack(
+ self.handle, arch.handle, addr, reg_stack, adjust.value, adjust.confidence
+ )
- def set_call_type_adjustment(self, addr:int, adjust_type:StringOrType, arch:Optional['architecture.Architecture']=None) -> \
- None:
+ def set_call_type_adjustment(
+ self, addr: int, adjust_type: StringOrType, arch: Optional['architecture.Architecture'] = None
+ ) -> None:
if isinstance(adjust_type, str):
(adjust_type, _) = self.view.parse_type_string(adjust_type)
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
if adjust_type is None:
tc = None
@@ -2715,22 +2830,26 @@ class Function:
tc = adjust_type._to_core_struct()
core.BNSetUserCallTypeAdjustment(self.handle, arch.handle, addr, tc)
- def set_call_stack_adjustment(self, addr:int, adjust:Union[int, 'types.OffsetWithConfidence'],
- arch:Optional['architecture.Architecture']=None):
+ def set_call_stack_adjustment(
+ self, addr: int, adjust: Union[int, 'types.OffsetWithConfidence'],
+ arch: Optional['architecture.Architecture'] = None
+ ):
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
if not isinstance(adjust, types.OffsetWithConfidence):
adjust = types.OffsetWithConfidence(adjust)
core.BNSetUserCallStackAdjustment(self.handle, arch.handle, addr, adjust.value, adjust.confidence)
- def set_call_reg_stack_adjustment(self, addr:int,
- adjust:Mapping['architecture.RegisterStackName', 'types.RegisterStackAdjustmentWithConfidence'],
- arch:Optional['architecture.Architecture']=None) -> None:
+ def set_call_reg_stack_adjustment(
+ self, addr: int, adjust: Mapping['architecture.RegisterStackName',
+ 'types.RegisterStackAdjustmentWithConfidence'],
+ arch: Optional['architecture.Architecture'] = None
+ ) -> None:
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
adjust_buf = (core.BNRegisterStackAdjustment * len(adjust))()
i = 0
@@ -2744,72 +2863,82 @@ class Function:
i += 1
core.BNSetUserCallRegisterStackAdjustment(self.handle, arch.handle, addr, adjust_buf, len(adjust))
- def set_call_reg_stack_adjustment_for_reg_stack(self, addr:int, reg_stack:'architecture.RegisterStackType',
- adjust:Union[int, 'types.RegisterStackAdjustmentWithConfidence'], arch:Optional['architecture.Architecture']=None) -> None:
+ def set_call_reg_stack_adjustment_for_reg_stack(
+ self, addr: int, reg_stack: 'architecture.RegisterStackType',
+ adjust: Union[int,
+ 'types.RegisterStackAdjustmentWithConfidence'], arch: Optional['architecture.Architecture'] = None
+ ) -> None:
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
reg_stack = arch.get_reg_stack_index(reg_stack)
if not isinstance(adjust, types.RegisterStackAdjustmentWithConfidence):
adjust = types.RegisterStackAdjustmentWithConfidence(adjust)
- core.BNSetUserCallRegisterStackAdjustmentForRegisterStack(self.handle, arch.handle, addr, reg_stack,
- adjust.value, adjust.confidence)
+ core.BNSetUserCallRegisterStackAdjustmentForRegisterStack(
+ self.handle, arch.handle, addr, reg_stack, adjust.value, adjust.confidence
+ )
- def get_call_type_adjustment(self, addr:int, arch:Optional['architecture.Architecture']=None) -> Optional['types.Type']:
+ def get_call_type_adjustment(self, addr: int,
+ arch: Optional['architecture.Architecture'] = None) -> Optional['types.Type']:
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
result = core.BNGetCallTypeAdjustment(self.handle, arch.handle, addr)
if not result.type:
return None
platform = self.platform
- return types.Type.create(core.BNNewTypeReference(result.type), platform = platform, confidence = result.confidence)
+ return types.Type.create(core.BNNewTypeReference(result.type), platform=platform, confidence=result.confidence)
- def get_call_stack_adjustment(self, addr:int, arch:Optional['architecture.Architecture']=None) -> 'types.OffsetWithConfidence':
+ def get_call_stack_adjustment(
+ self, addr: int, arch: Optional['architecture.Architecture'] = None
+ ) -> 'types.OffsetWithConfidence':
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
result = core.BNGetCallStackAdjustment(self.handle, arch.handle, addr)
- return types.OffsetWithConfidence(result.value, confidence = result.confidence)
+ return types.OffsetWithConfidence(result.value, confidence=result.confidence)
- def get_call_reg_stack_adjustment(self, addr:int, arch:Optional['architecture.Architecture']=None) -> \
- Dict['architecture.RegisterStackName', 'types.RegisterStackAdjustmentWithConfidence']:
+ def get_call_reg_stack_adjustment(
+ self, addr: int, arch: Optional['architecture.Architecture'] = None
+ ) -> Dict['architecture.RegisterStackName', 'types.RegisterStackAdjustmentWithConfidence']:
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
count = ctypes.c_ulonglong()
adjust = core.BNGetCallRegisterStackAdjustment(self.handle, arch.handle, addr, count)
assert adjust is not None, "core.BNGetCallRegisterStackAdjustment returned None"
result = {}
for i in range(0, count.value):
- result[arch.get_reg_stack_name(adjust[i].regStack)] = types.RegisterStackAdjustmentWithConfidence(
- adjust[i].adjustment, confidence = adjust[i].confidence)
+ result[arch.get_reg_stack_name(
+ adjust[i].regStack
+ )] = types.RegisterStackAdjustmentWithConfidence(adjust[i].adjustment, confidence=adjust[i].confidence)
core.BNFreeRegisterStackAdjustments(adjust)
return result
- def get_call_reg_stack_adjustment_for_reg_stack(self, addr:int, reg_stack:'architecture.RegisterStackType',
- arch:Optional['architecture.Architecture']=None) -> 'types.RegisterStackAdjustmentWithConfidence':
+ def get_call_reg_stack_adjustment_for_reg_stack(
+ self, addr: int, reg_stack: 'architecture.RegisterStackType', arch: Optional['architecture.Architecture'] = None
+ ) -> 'types.RegisterStackAdjustmentWithConfidence':
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
reg_stack = arch.get_reg_stack_index(reg_stack)
adjust = core.BNGetCallRegisterStackAdjustmentForRegisterStack(self.handle, arch.handle, addr, reg_stack)
- result = types.RegisterStackAdjustmentWithConfidence(adjust.adjustment, confidence = adjust.confidence)
+ result = types.RegisterStackAdjustmentWithConfidence(adjust.adjustment, confidence=adjust.confidence)
return result
- def is_call_instruction(self, addr:int, arch:Optional['architecture.Architecture']=None) -> bool:
+ def is_call_instruction(self, addr: int, arch: Optional['architecture.Architecture'] = None) -> bool:
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
return core.BNIsCallInstruction(self.handle, arch.handle, addr)
- def set_user_var_value(self, var:'variable.Variable', def_addr:int, value:'variable.PossibleValueSet') -> None:
+ def set_user_var_value(self, var: 'variable.Variable', def_addr: int, value: 'variable.PossibleValueSet') -> None:
"""
`set_user_var_value` allows the user to specify a PossibleValueSet value for an MLIL variable at its \
definition site.
@@ -2849,7 +2978,7 @@ class Function:
core.BNSetUserVariableValue(self.handle, var.to_BNVariable(), def_site, value._to_core_struct())
- def clear_user_var_value(self, var:'variable.Variable', def_addr:int) -> None:
+ def clear_user_var_value(self, var: 'variable.Variable', def_addr: int) -> None:
"""
Clears a previously defined user variable value.
@@ -2876,8 +3005,9 @@ class Function:
core.BNClearUserVariableValue(self.handle, var.to_BNVariable(), def_site)
- def get_all_user_var_values(self) -> \
- Mapping['variable.Variable', Mapping['ArchAndAddr', 'variable.PossibleValueSet']]:
+ def get_all_user_var_values(
+ self
+ ) -> Mapping['variable.Variable', Mapping['ArchAndAddr', 'variable.PossibleValueSet']]:
"""
Returns a map of current defined user variable values.
@@ -2909,7 +3039,7 @@ class Function:
for def_site in all_values[var]:
self.clear_user_var_value(var, def_site.addr)
- def request_debug_report(self, name:str) -> None:
+ def request_debug_report(self, name: str) -> None:
"""
``request_debug_report`` can generate internal debug reports for a variety of analysis.
Current list of possible values include:
@@ -3002,9 +3132,9 @@ class Function:
handle = core.BNGetWorkflowForFunction(self.handle)
if handle is None:
return None
- return workflow.Workflow(handle = handle)
+ return workflow.Workflow(handle=handle)
- def get_mlil_var_refs(self, var:'variable.Variable') -> List[ILReferenceSource]:
+ def get_mlil_var_refs(self, var: 'variable.Variable') -> List[ILReferenceSource]:
"""
``get_mlil_var_refs`` returns a list of ILReferenceSource objects (IL xrefs or cross-references)
that reference the given variable. The variable is a local variable that can be either on the stack,
@@ -3035,13 +3165,12 @@ class Function:
else:
arch = None
- result.append(ILReferenceSource(
- func, arch, refs[i].addr, refs[i].type, refs[i].exprId))
+ result.append(ILReferenceSource(func, arch, refs[i].addr, refs[i].type, refs[i].exprId))
core.BNFreeILReferences(refs, count.value)
return result
- def get_mlil_var_refs_from(self, addr:int, length:int=None, arch:Optional['architecture.Architecture']=None) -> \
- List[VariableReferenceSource]:
+ def get_mlil_var_refs_from(self, addr: int, length: int = None,
+ arch: Optional['architecture.Architecture'] = None) -> List[VariableReferenceSource]:
"""
``get_mlil_var_refs_from`` returns a list of variables referenced by code in the function ``func``,
of the architecture ``arch``, and at the address ``addr``. If no function is specified, references from
@@ -3062,7 +3191,7 @@ class Function:
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
if length is None:
@@ -3087,7 +3216,7 @@ class Function:
core.BNFreeVariableReferenceSourceList(refs, count.value)
return result
- def get_hlil_var_refs(self, var:'variable.Variable') -> List[ILReferenceSource]:
+ def get_hlil_var_refs(self, var: 'variable.Variable') -> List[ILReferenceSource]:
"""
``get_hlil_var_refs`` returns a list of ILReferenceSource objects (IL xrefs or cross-references)
that reference the given variable. The variable is a local variable that can be either on the stack,
@@ -3114,13 +3243,12 @@ class Function:
arch = architecture.CoreArchitecture._from_cache(refs[i].arch)
else:
arch = None
- result.append(ILReferenceSource(
- func, arch, refs[i].addr, refs[i].type, refs[i].exprId))
+ result.append(ILReferenceSource(func, arch, refs[i].addr, refs[i].type, refs[i].exprId))
core.BNFreeILReferences(refs, count.value)
return result
- def get_hlil_var_refs_from(self, addr:int, length:int=None, arch:Optional['architecture.Architecture']=None) -> \
- List[VariableReferenceSource]:
+ def get_hlil_var_refs_from(self, addr: int, length: int = None,
+ arch: Optional['architecture.Architecture'] = None) -> List[VariableReferenceSource]:
"""
``get_hlil_var_refs_from`` returns a list of variables referenced by code in the function ``func``,
of the architecture ``arch``, and at the address ``addr``. If no function is specified, references from
@@ -3161,11 +3289,11 @@ class Function:
core.BNFreeVariableReferenceSourceList(refs, count.value)
return result
- def get_instruction_containing_address(self, addr:int, arch:Optional['architecture.Architecture']=None) -> \
- Optional[int]:
+ def get_instruction_containing_address(self, addr: int,
+ arch: Optional['architecture.Architecture'] = None) -> Optional[int]:
if arch is None:
if self.arch is None:
- raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
+ raise ValueError(f"Can't call {_function_name_()} for function with no architecture specified")
arch = self.arch
start = ctypes.c_ulonglong()
@@ -3175,7 +3303,7 @@ class Function:
class AdvancedFunctionAnalysisDataRequestor:
- def __init__(self, func:'Function'=None):
+ def __init__(self, func: 'Function' = None):
self._function = func
if self._function is not None:
self._function.request_advanced_analysis_data()
@@ -3189,7 +3317,7 @@ class AdvancedFunctionAnalysisDataRequestor:
return self._function
@function.setter
- def function(self, func:'Function') -> None:
+ def function(self, func: 'Function') -> None:
if self._function is not None:
self._function.release_advanced_analysis_data()
self._function = func
@@ -3204,13 +3332,15 @@ class AdvancedFunctionAnalysisDataRequestor:
@dataclass
class DisassemblyTextLine:
- tokens:List['InstructionTextToken']
- highlight:'_highlight.HighlightColor'
- address:Optional[int]
- il_instruction:Optional[ILInstructionType]
+ tokens: List['InstructionTextToken']
+ highlight: '_highlight.HighlightColor'
+ address: Optional[int]
+ il_instruction: Optional[ILInstructionType]
- def __init__(self, tokens:List['InstructionTextToken'], address:int=None, il_instr:ILInstructionType=None,
- color:Union['_highlight.HighlightColor', HighlightStandardColor]=None):
+ def __init__(
+ self, tokens: List['InstructionTextToken'], address: int = None, il_instr: ILInstructionType = None,
+ color: Union['_highlight.HighlightColor', HighlightStandardColor] = None
+ ):
self.address = address
self.tokens = tokens
self.il_instruction = il_instr
@@ -3235,8 +3365,10 @@ class DisassemblyTextLine:
class DisassemblyTextRenderer:
- def __init__(self, func:AnyFunctionType=None, settings:'DisassemblySettings'=None,
- handle:core.BNDisassemblySettings=None):
+ def __init__(
+ self, func: AnyFunctionType = None, settings: 'DisassemblySettings' = None,
+ handle: core.BNDisassemblySettings = None
+ ):
if handle is None:
if func is None:
raise ValueError("function required for disassembly")
@@ -3262,30 +3394,30 @@ class DisassemblyTextRenderer:
@property
def function(self) -> 'Function':
- return Function(handle = core.BNGetDisassemblyTextRendererFunction(self.handle))
+ return Function(handle=core.BNGetDisassemblyTextRendererFunction(self.handle))
@property
def il_function(self) -> Optional[ILFunctionType]:
llil = core.BNGetDisassemblyTextRendererLowLevelILFunction(self.handle)
if llil:
- return lowlevelil.LowLevelILFunction(handle = llil)
+ return lowlevelil.LowLevelILFunction(handle=llil)
mlil = core.BNGetDisassemblyTextRendererMediumLevelILFunction(self.handle)
if mlil:
- return mediumlevelil.MediumLevelILFunction(handle = mlil)
+ return mediumlevelil.MediumLevelILFunction(handle=mlil)
hlil = core.BNGetDisassemblyTextRendererHighLevelILFunction(self.handle)
if hlil:
- return highlevelil.HighLevelILFunction(handle = hlil)
+ return highlevelil.HighLevelILFunction(handle=hlil)
return None
@property
def basic_block(self) -> Optional['basicblock.BasicBlock']:
result = core.BNGetDisassemblyTextRendererBasicBlock(self.handle)
if result:
- return basicblock.BasicBlock(handle = result)
+ return basicblock.BasicBlock(handle=result)
return None
@basic_block.setter
- def basic_block(self, block:'basicblock.BasicBlock') -> None:
+ def basic_block(self, block: 'basicblock.BasicBlock') -> None:
if block is not None:
core.BNSetDisassemblyTextRendererBasicBlock(self.handle, block.handle)
else:
@@ -3293,18 +3425,20 @@ class DisassemblyTextRenderer:
@property
def arch(self) -> 'architecture.Architecture':
- return architecture.CoreArchitecture._from_cache(handle = core.BNGetDisassemblyTextRendererArchitecture(self.handle))
+ return architecture.CoreArchitecture._from_cache(
+ handle=core.BNGetDisassemblyTextRendererArchitecture(self.handle)
+ )
@arch.setter
- def arch(self, arch:'architecture.Architecture') -> None:
+ def arch(self, arch: 'architecture.Architecture') -> None:
core.BNSetDisassemblyTextRendererArchitecture(self.handle, arch.handle)
@property
def settings(self) -> 'DisassemblySettings':
- return DisassemblySettings(handle = core.BNGetDisassemblyTextRendererSettings(self.handle))
+ return DisassemblySettings(handle=core.BNGetDisassemblyTextRendererSettings(self.handle))
@settings.setter
- def settings(self, settings:'DisassemblySettings') -> None:
+ def settings(self, settings: 'DisassemblySettings') -> None:
if settings is not None:
core.BNSetDisassemblyTextRendererSettings(self.handle, settings.handle)
core.BNSetDisassemblyTextRendererSettings(self.handle, None)
@@ -3317,7 +3451,7 @@ class DisassemblyTextRenderer:
def has_data_flow(self) -> bool:
return core.BNDisassemblyTextRendererHasDataFlow(self.handle)
- def get_instruction_annotations(self, addr:int) -> List['InstructionTextToken']:
+ def get_instruction_annotations(self, addr: int) -> List['InstructionTextToken']:
count = ctypes.c_ulonglong()
tokens = core.BNGetDisassemblyTextRendererInstructionAnnotations(self.handle, addr, count)
assert tokens is not None, "core.BNGetDisassemblyTextRendererInstructionAnnotations returned None"
@@ -3325,7 +3459,7 @@ class DisassemblyTextRenderer:
core.BNFreeInstructionText(tokens, count.value)
return result
- def get_instruction_text(self, addr:int) -> Generator[Tuple[Optional['DisassemblyTextLine'], int], None, None]:
+ def get_instruction_text(self, addr: int) -> Generator[Tuple[Optional['DisassemblyTextLine'], int], None, None]:
count = ctypes.c_ulonglong()
length = ctypes.c_ulonglong()
lines = ctypes.POINTER(core.BNDisassemblyTextLine)()
@@ -3346,7 +3480,7 @@ class DisassemblyTextRenderer:
finally:
core.BNFreeDisassemblyTextLines(lines, count.value)
- def get_disassembly_text(self, addr:int) -> Generator[Tuple[Optional['DisassemblyTextLine'], int], None, None]:
+ def get_disassembly_text(self, addr: int) -> Generator[Tuple[Optional['DisassemblyTextLine'], int], None, None]:
count = ctypes.c_ulonglong()
length = ctypes.c_ulonglong()
length.value = 0
@@ -3369,8 +3503,10 @@ class DisassemblyTextRenderer:
finally:
core.BNFreeDisassemblyTextLines(lines, count.value)
- def post_process_lines(self, addr:int, length:int, in_lines:Union[str, List[str], List['DisassemblyTextLine']],
- indent_spaces:str=''):
+ def post_process_lines(
+ self, addr: int, length: int, in_lines: Union[str, List[str], List['DisassemblyTextLine']],
+ indent_spaces: str = ''
+ ):
if isinstance(in_lines, str):
in_lines = in_lines.split('\n')
line_buf = (core.BNDisassemblyTextLine * len(in_lines))()
@@ -3399,7 +3535,9 @@ class DisassemblyTextRenderer:
line_buf[i].count = len(line.tokens)
line_buf[i].tokens = InstructionTextToken._get_core_struct(line.tokens)
count = ctypes.c_ulonglong()
- lines = core.BNPostProcessDisassemblyTextRendererLines(self.handle, addr, length, line_buf, len(in_lines), count, indent_spaces)
+ lines = core.BNPostProcessDisassemblyTextRendererLines(
+ self.handle, addr, length, line_buf, len(in_lines), count, indent_spaces
+ )
assert lines is not None, "core.BNPostProcessDisassemblyTextRendererLines returned None"
il_function = self.il_function
try:
@@ -3418,7 +3556,7 @@ class DisassemblyTextRenderer:
def reset_deduplicated_comments(self) -> None:
core.BNResetDisassemblyTextRendererDeduplicatedComments(self.handle)
- def add_symbol_token(self, tokens:List['InstructionTextToken'], addr:int, size:int, operand:int=None) -> bool:
+ def add_symbol_token(self, tokens: List['InstructionTextToken'], addr: int, size: int, operand: int = None) -> bool:
if operand is None:
operand = 0xffffffff
count = ctypes.c_ulonglong()
@@ -3431,8 +3569,9 @@ class DisassemblyTextRenderer:
core.BNFreeInstructionText(new_tokens, count.value)
return True
- def add_stack_var_reference_tokens(self, tokens:List['InstructionTextToken'],
- ref:'variable.StackVariableReference') -> None:
+ def add_stack_var_reference_tokens(
+ self, tokens: List['InstructionTextToken'], ref: 'variable.StackVariableReference'
+ ) -> None:
stack_ref = core.BNStackVariableReference()
if ref.source_operand is None:
stack_ref.sourceOperand = 0xffffffff
@@ -3456,11 +3595,13 @@ class DisassemblyTextRenderer:
core.BNFreeInstructionText(new_tokens, count.value)
@staticmethod
- def is_integer_token(token:'InstructionTextToken') -> bool:
+ def is_integer_token(token: 'InstructionTextToken') -> bool:
return core.BNIsIntegerToken(token.type)
- def add_integer_token(self, tokens:List['InstructionTextToken'], int_token:'InstructionTextToken', addr:int,
- arch:Optional['architecture.Architecture']=None) -> None:
+ def add_integer_token(
+ self, tokens: List['InstructionTextToken'], int_token: 'InstructionTextToken', addr: int,
+ arch: Optional['architecture.Architecture'] = None
+ ) -> None:
if arch is not None:
arch = arch.handle
in_token_obj = InstructionTextToken._get_core_struct([int_token])
@@ -3471,8 +3612,10 @@ class DisassemblyTextRenderer:
tokens += result
core.BNFreeInstructionText(new_tokens, count.value)
- def wrap_comment(self, lines:List['DisassemblyTextLine'], cur_line:'DisassemblyTextLine', comment:str,
- has_auto_annotations:bool, leading_spaces:str=" ", indent_spaces:str= "") -> None:
+ def wrap_comment(
+ self, lines: List['DisassemblyTextLine'], cur_line: 'DisassemblyTextLine', comment: str,
+ has_auto_annotations: bool, leading_spaces: str = " ", indent_spaces: str = ""
+ ) -> None:
cur_line_obj = core.BNDisassemblyTextLine()
cur_line_obj.addr = cur_line.address
if cur_line.il_instruction is None:
@@ -3483,8 +3626,9 @@ class DisassemblyTextRenderer:
cur_line_obj.tokens = InstructionTextToken._get_core_struct(cur_line.tokens)
cur_line_obj.count = len(cur_line.tokens)
count = ctypes.c_ulonglong()
- new_lines = core.BNDisassemblyTextRendererWrapComment(self.handle, cur_line_obj, count, comment,
- has_auto_annotations, leading_spaces, indent_spaces)
+ new_lines = core.BNDisassemblyTextRendererWrapComment(
+ self.handle, cur_line_obj, count, comment, has_auto_annotations, leading_spaces, indent_spaces
+ )
assert new_lines is not None, "core.BNDisassemblyTextRendererWrapComment returned None"
il_function = self.il_function
for i in range(0, count.value):
diff --git a/python/functionrecognizer.py b/python/functionrecognizer.py
index 1b3f13b8..1d84eadc 100644
--- a/python/functionrecognizer.py
+++ b/python/functionrecognizer.py
@@ -54,10 +54,10 @@ class FunctionRecognizer:
def _recognize_low_level_il(self, ctxt, data, func, il):
try:
- file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(data))
- view = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(data))
- func = function.Function(view, handle = core.BNNewFunctionReference(func))
- il = lowlevelil.LowLevelILFunction(func.arch, handle = core.BNNewLowLevelILFunctionReference(il))
+ file_metadata = filemetadata.FileMetadata(handle=core.BNGetFileForView(data))
+ view = binaryview.BinaryView(file_metadata=file_metadata, handle=core.BNNewViewReference(data))
+ func = function.Function(view, handle=core.BNNewFunctionReference(func))
+ il = lowlevelil.LowLevelILFunction(func.arch, handle=core.BNNewLowLevelILFunctionReference(il))
return self.recognize_low_level_il(view, func, il)
except:
log_error(traceback.format_exc())
@@ -68,10 +68,10 @@ class FunctionRecognizer:
def _recognize_medium_level_il(self, ctxt, data, func, il):
try:
- file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(data))
- view = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(data))
- func = function.Function(view, handle = core.BNNewFunctionReference(func))
- il = mediumlevelil.MediumLevelILFunction(func.arch, handle = core.BNNewMediumLevelILFunctionReference(il))
+ file_metadata = filemetadata.FileMetadata(handle=core.BNGetFileForView(data))
+ view = binaryview.BinaryView(file_metadata=file_metadata, handle=core.BNNewViewReference(data))
+ func = function.Function(view, handle=core.BNNewFunctionReference(func))
+ il = mediumlevelil.MediumLevelILFunction(func.arch, handle=core.BNNewMediumLevelILFunctionReference(il))
return self.recognize_medium_level_il(view, func, il)
except:
log_error(traceback.format_exc())
diff --git a/python/generator.cpp b/python/generator.cpp
index 135bc958..99d2d455 100644
--- a/python/generator.cpp
+++ b/python/generator.cpp
@@ -27,41 +27,41 @@ using namespace std;
map<string, string> g_pythonKeywordReplacements = {
- {"False", "False_"},
- {"True", "True_"},
- {"None", "None_"},
- {"and", "and_"},
- {"as", "as_"},
- {"assert", "assert_"},
- {"async", "async_"},
- {"await", "await_"},
- {"break", "break_"},
- {"class", "class_"},
- {"continue", "continue_"},
- {"def", "def_"},
- {"del", "del_"},
- {"elif", "elif_"},
- {"else", "else_"},
- {"except", "except_"},
- {"finally", "finally_"},
- {"for", "for_"},
- {"from", "from_"},
- {"global", "global_"},
- {"if", "if_"},
- {"import", "import_"},
- {"in", "in_"},
- {"is", "is_"},
- {"lambda", "lambda_"},
- {"nonlocal", "nonlocal_"},
- {"not", "not_"},
- {"or", "or_"},
- {"pass", "pass_"},
- {"raise", "raise_"},
- {"return", "return_"},
- {"try", "try_"},
- {"while", "while_"},
- {"with", "with_"},
- {"yield", "yield_"},
+ {"False", "False_"},
+ {"True", "True_"},
+ {"None", "None_"},
+ {"and", "and_"},
+ {"as", "as_"},
+ {"assert", "assert_"},
+ {"async", "async_"},
+ {"await", "await_"},
+ {"break", "break_"},
+ {"class", "class_"},
+ {"continue", "continue_"},
+ {"def", "def_"},
+ {"del", "del_"},
+ {"elif", "elif_"},
+ {"else", "else_"},
+ {"except", "except_"},
+ {"finally", "finally_"},
+ {"for", "for_"},
+ {"from", "from_"},
+ {"global", "global_"},
+ {"if", "if_"},
+ {"import", "import_"},
+ {"in", "in_"},
+ {"is", "is_"},
+ {"lambda", "lambda_"},
+ {"nonlocal", "nonlocal_"},
+ {"not", "not_"},
+ {"or", "or_"},
+ {"pass", "pass_"},
+ {"raise", "raise_"},
+ {"return", "return_"},
+ {"try", "try_"},
+ {"while", "while_"},
+ {"with", "with_"},
+ {"yield", "yield_"},
};
@@ -126,8 +126,8 @@ void OutputType(FILE* out, Type* type, bool isReturnType = false, bool isCallbac
fprintf(out, "ctypes.c_void_p");
break;
}
- else if ((type->GetChildType()->GetClass() == IntegerTypeClass) &&
- (type->GetChildType()->GetWidth() == 1) && (type->GetChildType()->IsSigned()))
+ else if ((type->GetChildType()->GetClass() == IntegerTypeClass) && (type->GetChildType()->GetWidth() == 1)
+ && (type->GetChildType()->IsSigned()))
{
if (isReturnType)
fprintf(out, "ctypes.POINTER(ctypes.c_byte)");
@@ -194,8 +194,8 @@ void OutputSwizzledType(FILE* out, Type* type)
fprintf(out, "Optional[ctypes.c_void_p]");
break;
}
- else if ((type->GetChildType()->GetClass() == IntegerTypeClass) &&
- (type->GetChildType()->GetWidth() == 1) && (type->GetChildType()->IsSigned()))
+ else if ((type->GetChildType()->GetClass() == IntegerTypeClass) && (type->GetChildType()->GetWidth() == 1)
+ && (type->GetChildType()->IsSigned()))
{
fprintf(out, "Optional[str]");
break;
@@ -300,12 +300,13 @@ int main(int argc, char* argv[])
bool stringField = false;
for (auto& arg : i.second->GetStructure()->GetMembers())
{
- if ((arg.type->GetClass() == PointerTypeClass) &&
- (arg.type->GetChildType()->GetWidth() == 1) &&
- (arg.type->GetChildType()->IsSigned()))
+ if ((arg.type->GetClass() == PointerTypeClass) && (arg.type->GetChildType()->GetWidth() == 1)
+ && (arg.type->GetChildType()->IsSigned()))
{
- fprintf(out, "\t@property\n\tdef %s(self):\n\t\treturn pyNativeStr(self._%s)\n", arg.name.c_str(), arg.name.c_str());
- fprintf(out, "\t@%s.setter\n\tdef %s(self, value):\n\t\tself._%s = cstr(value)\n", arg.name.c_str(), arg.name.c_str(), arg.name.c_str());
+ fprintf(out, "\t@property\n\tdef %s(self):\n\t\treturn pyNativeStr(self._%s)\n", arg.name.c_str(),
+ arg.name.c_str());
+ fprintf(out, "\t@%s.setter\n\tdef %s(self, value):\n\t\tself._%s = cstr(value)\n", arg.name.c_str(),
+ arg.name.c_str(), arg.name.c_str());
stringField = true;
}
}
@@ -328,8 +329,8 @@ int main(int argc, char* argv[])
fprintf(enums, "\t%s = %" PRId64 "\n", j.name.c_str(), j.value);
}
}
- else if ((i.second->GetClass() == BoolTypeClass) || (i.second->GetClass() == IntegerTypeClass) ||
- (i.second->GetClass() == FloatTypeClass) || (i.second->GetClass() == ArrayTypeClass))
+ else if ((i.second->GetClass() == BoolTypeClass) || (i.second->GetClass() == IntegerTypeClass)
+ || (i.second->GetClass() == FloatTypeClass) || (i.second->GetClass() == ArrayTypeClass))
{
fprintf(out, "%s = ", name.c_str());
OutputType(out, i.second);
@@ -359,9 +360,9 @@ int main(int argc, char* argv[])
bool requiresDependency = false;
for (auto& j : type->GetStructure()->GetMembers())
{
- if ((j.type->GetClass() == NamedTypeReferenceClass) &&
- (types[j.type->GetNamedTypeReference()->GetName()]->GetClass() == StructureTypeClass) &&
- (finishedStructs.count(j.type->GetNamedTypeReference()->GetName()) == 0))
+ if ((j.type->GetClass() == NamedTypeReferenceClass)
+ && (types[j.type->GetNamedTypeReference()->GetName()]->GetClass() == StructureTypeClass)
+ && (finishedStructs.count(j.type->GetNamedTypeReference()->GetName()) == 0))
{
// This structure needs another structure that isn't fully defined yet, need to wait
// for the dependencies to be defined
@@ -377,9 +378,8 @@ int main(int argc, char* argv[])
for (auto& j : type->GetStructure()->GetMembers())
{
// To help the python->C wrappers
- if ((j.type->GetClass() == PointerTypeClass) &&
- (j.type->GetChildType()->GetWidth() == 1) &&
- (j.type->GetChildType()->IsSigned()))
+ if ((j.type->GetClass() == PointerTypeClass) && (j.type->GetChildType()->GetWidth() == 1)
+ && (j.type->GetChildType()->IsSigned()))
{
fprintf(out, "\t\t(\"_%s\", ", j.name.c_str());
}
@@ -395,7 +395,8 @@ int main(int argc, char* argv[])
else if (type->GetClass() == NamedTypeReferenceClass)
{
fprintf(out, "%s = %s\n", name.c_str(), type->GetNamedTypeReference()->GetName().GetString().c_str());
- fprintf(out, "%sHandle = %sHandle\n", name.c_str(), type->GetNamedTypeReference()->GetName().GetString().c_str());
+ fprintf(out, "%sHandle = %sHandle\n", name.c_str(),
+ type->GetNamedTypeReference()->GetName().GetString().c_str());
finishedStructs.insert(i);
processedSome = true;
}
@@ -420,9 +421,9 @@ int main(int argc, char* argv[])
// Check for a string result, these will be automatically wrapped to free the string
// memory and return a Python string
- bool stringResult = (i.second->GetChildType()->GetClass() == PointerTypeClass) &&
- (i.second->GetChildType()->GetChildType()->GetWidth() == 1) &&
- (i.second->GetChildType()->GetChildType()->IsSigned());
+ bool stringResult = (i.second->GetChildType()->GetClass() == PointerTypeClass)
+ && (i.second->GetChildType()->GetChildType()->GetWidth() == 1)
+ && (i.second->GetChildType()->GetChildType()->IsSigned());
// Pointer returns will be automatically wrapped to return None on null pointer
bool pointerResult = (i.second->GetChildType()->GetClass() == PointerTypeClass);
@@ -475,7 +476,8 @@ int main(int argc, char* argv[])
}
else
{
- // As of writing this, only BNLog's have variable instruction lengths, but in an attempt not to break in the future:
+ // As of writing this, only BNLog's have variable instruction lengths, but in an attempt not to break in the
+ // future:
if (funcName.compare(0, 6, "_BNLog") == 0)
{
if (funcName != "_BNLog")
@@ -497,7 +499,7 @@ int main(int argc, char* argv[])
if (!i.second->HasVariableArguments())
{
size_t argN = 0;
- for (auto& arg: i.second->GetParameters())
+ for (auto& arg : i.second->GetParameters())
{
string argName = arg.name;
if (g_pythonKeywordReplacements.find(argName) != g_pythonKeywordReplacements.end())
@@ -514,7 +516,7 @@ int main(int argc, char* argv[])
OutputSwizzledType(out, arg.type);
else
OutputType(out, arg.type);
- argN ++;
+ argN++;
}
}
fprintf(out, "\n\t\t) -> ");
@@ -536,10 +538,9 @@ int main(int argc, char* argv[])
if (argName.empty())
argName = "arg" + to_string(argN);
- if (swizzleArgs && (arg.type->GetClass() == PointerTypeClass) &&
- (arg.type->GetChildType()->GetClass() == IntegerTypeClass) &&
- (arg.type->GetChildType()->GetWidth() == 1) &&
- (arg.type->GetChildType()->IsSigned()))
+ if (swizzleArgs && (arg.type->GetClass() == PointerTypeClass)
+ && (arg.type->GetChildType()->GetClass() == IntegerTypeClass)
+ && (arg.type->GetChildType()->GetWidth() == 1) && (arg.type->GetChildType()->IsSigned()))
{
stringArgFuncCall += string("cstr(") + argName + "), ";
}
@@ -550,7 +551,7 @@ int main(int argc, char* argv[])
argN++;
}
if (argN > 0)
- stringArgFuncCall = stringArgFuncCall.substr(0, stringArgFuncCall.size()-2);
+ stringArgFuncCall = stringArgFuncCall.substr(0, stringArgFuncCall.size() - 2);
stringArgFuncCall += ")";
if (stringResult)
diff --git a/python/highlevelil.py b/python/highlevelil.py
index b813c2ec..1aafd316 100644
--- a/python/highlevelil.py
+++ b/python/highlevelil.py
@@ -38,9 +38,10 @@ from . import highlight
from . import flowgraph
from . import variable
from .interaction import show_graph_report
-from .commonil import (BaseILInstruction, Tailcall, Syscall, Localcall, Comparison, Signed, UnaryOperation, BinaryOperation,
- SSA, Phi, Loop, ControlFlow, Memory, Constant, Arithmetic, DoublePrecision, Terminal,
- FloatingPoint)
+from .commonil import (
+ BaseILInstruction, Tailcall, Syscall, Localcall, Comparison, Signed, UnaryOperation, BinaryOperation, SSA, Phi,
+ Loop, ControlFlow, Memory, Constant, Arithmetic, DoublePrecision, Terminal, FloatingPoint
+)
LinesType = Generator['function.DisassemblyTextLine', None, None]
ExpressionIndex = NewType('ExpressionIndex', int)
@@ -48,30 +49,23 @@ InstructionIndex = NewType('InstructionIndex', int)
HLILInstructionsType = Generator['HighLevelILInstruction', None, None]
HLILBasicBlocksType = Generator['HighLevelILBasicBlock', None, None]
OperandsType = Tuple[ExpressionIndex, ExpressionIndex, ExpressionIndex, ExpressionIndex, ExpressionIndex]
-HighLevelILOperandType = Union[
- 'HighLevelILInstruction',
- 'lowlevelil.ILIntrinsic',
- 'variable.Variable',
- 'mediumlevelil.SSAVariable',
- List[int],
- List['variable.Variable'],
- List['mediumlevelil.SSAVariable'],
- List['HighLevelILInstruction'],
- Optional[int],
- float,
- 'GotoLabel'
-]
+HighLevelILOperandType = Union['HighLevelILInstruction', 'lowlevelil.ILIntrinsic', 'variable.Variable',
+ 'mediumlevelil.SSAVariable', List[int], List['variable.Variable'],
+ List['mediumlevelil.SSAVariable'], List['HighLevelILInstruction'], Optional[int], float,
+ 'GotoLabel']
VariablesList = List[Union['mediumlevelil.SSAVariable', 'variable.Variable']]
+
class VariableReferenceType(Enum):
Read = 0
Written = 1
AddressTaken = 2
+
@dataclass(frozen=True)
class HighLevelILOperationAndSize:
- operation:HighLevelILOperation
- size:int
+ operation: HighLevelILOperation
+ size: int
def __repr__(self):
if self.size == 0:
@@ -81,8 +75,8 @@ class HighLevelILOperationAndSize:
@dataclass(frozen=True)
class GotoLabel:
- function:'HighLevelILFunction'
- id:int
+ function: 'HighLevelILFunction'
+ id: int
def __repr__(self):
return f"<label: {self.name}>"
@@ -100,7 +94,7 @@ class GotoLabel:
return core.BNGetGotoLabelName(self.function.source_function.handle, self.id)
@name.setter
- def name(self, value:str) -> None:
+ def name(self, value: str) -> None:
assert self.function.source_function is not None, "Cant set name of function without source_function"
core.BNSetUserGotoLabelName(self.function.source_function.handle, self.id, value)
@@ -115,17 +109,20 @@ class GotoLabel:
@dataclass(frozen=True, order=True)
class CoreHighLevelILInstruction:
- operation:HighLevelILOperation
- source_operand:int
- size:int
- operands:OperandsType
- address:int
- parent:ExpressionIndex
+ operation: HighLevelILOperation
+ source_operand: int
+ size: int
+ operands: OperandsType
+ address: int
+ parent: ExpressionIndex
@classmethod
- def from_BNHighLevelILInstruction(cls, instr:core.BNHighLevelILInstruction) -> 'CoreHighLevelILInstruction':
- operands:OperandsType = tuple([ExpressionIndex(instr.operands[i]) for i in range(5)]) # type: ignore
- return cls(HighLevelILOperation(instr.operation), instr.sourceOperand, instr.size, operands, instr.address, instr.parent)
+ def from_BNHighLevelILInstruction(cls, instr: core.BNHighLevelILInstruction) -> 'CoreHighLevelILInstruction':
+ operands: OperandsType = tuple([ExpressionIndex(instr.operands[i]) for i in range(5)]) # type: ignore
+ return cls(
+ HighLevelILOperation(instr.operation), instr.sourceOperand, instr.size, operands, instr.address,
+ instr.parent
+ )
@dataclass(frozen=True)
@@ -134,132 +131,162 @@ class HighLevelILInstruction(BaseILInstruction):
``class HighLevelILInstruction`` High Level Intermediate Language Instructions form an abstract syntax tree of
the code. Control flow structures are present as high level constructs in the HLIL tree.
"""
- function:'HighLevelILFunction'
- expr_index:ExpressionIndex
- core_instr:CoreHighLevelILInstruction
- as_ast:bool
- instr_index:InstructionIndex
- ILOperations:ClassVar[Mapping[HighLevelILOperation, List[Tuple[str,str]]]] = {
- HighLevelILOperation.HLIL_NOP: [],
- HighLevelILOperation.HLIL_BLOCK: [("body", "expr_list")],
- HighLevelILOperation.HLIL_IF: [("condition", "expr"), ("true", "expr"), ("false", "expr")],
- HighLevelILOperation.HLIL_WHILE: [("condition", "expr"), ("body", "expr")],
- HighLevelILOperation.HLIL_WHILE_SSA: [("condition_phi", "expr"), ("condition", "expr"), ("body", "expr")],
- HighLevelILOperation.HLIL_DO_WHILE: [("body", "expr"), ("condition", "expr")],
- HighLevelILOperation.HLIL_DO_WHILE_SSA: [("body", "expr"), ("condition_phi", "expr"), ("condition", "expr")],
- HighLevelILOperation.HLIL_FOR: [("init", "expr"), ("condition", "expr"), ("update", "expr"), ("body", "expr")],
- HighLevelILOperation.HLIL_FOR_SSA: [("init", "expr"), ("condition_phi", "expr"), ("condition", "expr"), ("update", "expr"), ("body", "expr")],
- HighLevelILOperation.HLIL_SWITCH: [("condition", "expr"), ("default", "expr"), ("cases", "expr_list")],
- HighLevelILOperation.HLIL_CASE: [("values", "expr_list"), ("body", "expr")],
- HighLevelILOperation.HLIL_BREAK: [],
- HighLevelILOperation.HLIL_CONTINUE: [],
- HighLevelILOperation.HLIL_JUMP: [("dest", "expr")],
- HighLevelILOperation.HLIL_RET: [("src", "expr_list")],
- HighLevelILOperation.HLIL_NORET: [],
- HighLevelILOperation.HLIL_GOTO: [("target", "label")],
- HighLevelILOperation.HLIL_LABEL: [("target", "label")],
- HighLevelILOperation.HLIL_VAR_DECLARE: [("var", "var")],
- HighLevelILOperation.HLIL_VAR_INIT: [("dest", "var"), ("src", "expr")],
- HighLevelILOperation.HLIL_VAR_INIT_SSA: [("dest", "var_ssa"), ("src", "expr")],
- HighLevelILOperation.HLIL_ASSIGN: [("dest", "expr"), ("src", "expr")],
- HighLevelILOperation.HLIL_ASSIGN_UNPACK: [("dest", "expr_list"), ("src", "expr")],
- HighLevelILOperation.HLIL_ASSIGN_MEM_SSA: [("dest", "expr"), ("dest_memory", "int"), ("src", "expr"), ("src_memory", "int")],
- HighLevelILOperation.HLIL_ASSIGN_UNPACK_MEM_SSA: [("dest", "expr_list"), ("dest_memory", "int"), ("src", "expr"), ("src_memory", "int")],
- HighLevelILOperation.HLIL_VAR: [("var", "var")],
- HighLevelILOperation.HLIL_VAR_SSA: [("var", "var_ssa")],
- HighLevelILOperation.HLIL_VAR_PHI: [("dest", "var_ssa"), ("src", "var_ssa_list")],
- HighLevelILOperation.HLIL_MEM_PHI: [("dest", "int"), ("src", "int_list")],
- HighLevelILOperation.HLIL_STRUCT_FIELD: [("src", "expr"), ("offset", "int"), ("member_index", "member_index")],
- HighLevelILOperation.HLIL_ARRAY_INDEX: [("src", "expr"), ("index", "expr")],
- HighLevelILOperation.HLIL_ARRAY_INDEX_SSA: [("src", "expr"), ("src_memory", "int"), ("index", "expr")],
- HighLevelILOperation.HLIL_SPLIT: [("high", "expr"), ("low", "expr")],
- HighLevelILOperation.HLIL_DEREF: [("src", "expr")],
- HighLevelILOperation.HLIL_DEREF_FIELD: [("src", "expr"), ("offset", "int"), ("member_index", "member_index")],
- HighLevelILOperation.HLIL_DEREF_SSA: [("src", "expr"), ("src_memory", "int")],
- HighLevelILOperation.HLIL_DEREF_FIELD_SSA: [("src", "expr"), ("src_memory", "int"), ("offset", "int"), ("member_index", "member_index")],
- HighLevelILOperation.HLIL_ADDRESS_OF: [("src", "expr")],
- HighLevelILOperation.HLIL_CONST: [("constant", "int")],
- HighLevelILOperation.HLIL_CONST_PTR: [("constant", "int")],
- HighLevelILOperation.HLIL_EXTERN_PTR: [("constant", "int"), ("offset", "int")],
- HighLevelILOperation.HLIL_FLOAT_CONST: [("constant", "float")],
- HighLevelILOperation.HLIL_IMPORT: [("constant", "int")],
- HighLevelILOperation.HLIL_ADD: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_ADC: [("left", "expr"), ("right", "expr"), ("carry", "expr")],
- HighLevelILOperation.HLIL_SUB: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_SBB: [("left", "expr"), ("right", "expr"), ("carry", "expr")],
- HighLevelILOperation.HLIL_AND: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_OR: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_XOR: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_LSL: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_LSR: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_ASR: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_ROL: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_RLC: [("left", "expr"), ("right", "expr"), ("carry", "expr")],
- HighLevelILOperation.HLIL_ROR: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_RRC: [("left", "expr"), ("right", "expr"), ("carry", "expr")],
- HighLevelILOperation.HLIL_MUL: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_MULU_DP: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_MULS_DP: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_DIVU: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_DIVU_DP: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_DIVS: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_DIVS_DP: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_MODU: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_MODU_DP: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_MODS: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_MODS_DP: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_NEG: [("src", "expr")],
- HighLevelILOperation.HLIL_NOT: [("src", "expr")],
- HighLevelILOperation.HLIL_SX: [("src", "expr")],
- HighLevelILOperation.HLIL_ZX: [("src", "expr")],
- HighLevelILOperation.HLIL_LOW_PART: [("src", "expr")],
- HighLevelILOperation.HLIL_CALL: [("dest", "expr"), ("params", "expr_list")],
- HighLevelILOperation.HLIL_CALL_SSA: [("dest", "expr"), ("params", "expr_list"), ("dest_memory", "int"), ("src_memory", "int")],
- HighLevelILOperation.HLIL_CMP_E: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_CMP_NE: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_CMP_SLT: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_CMP_ULT: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_CMP_SLE: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_CMP_ULE: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_CMP_SGE: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_CMP_UGE: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_CMP_SGT: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_CMP_UGT: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_TEST_BIT: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_BOOL_TO_INT: [("src", "expr")],
- HighLevelILOperation.HLIL_ADD_OVERFLOW: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_SYSCALL: [("params", "expr_list")],
- HighLevelILOperation.HLIL_SYSCALL_SSA: [("params", "expr_list"), ("dest_memory", "int"), ("src_memory", "int")],
- HighLevelILOperation.HLIL_TAILCALL: [("dest", "expr"), ("params", "expr_list")],
- HighLevelILOperation.HLIL_BP: [],
- HighLevelILOperation.HLIL_TRAP: [("vector", "int")],
- HighLevelILOperation.HLIL_INTRINSIC: [("intrinsic", "intrinsic"), ("params", "expr_list")],
- HighLevelILOperation.HLIL_INTRINSIC_SSA: [("intrinsic", "intrinsic"), ("params", "expr_list"), ("dest_memory", "int"), ("src_memory", "int")],
- HighLevelILOperation.HLIL_UNDEF: [],
- HighLevelILOperation.HLIL_UNIMPL: [],
- HighLevelILOperation.HLIL_UNIMPL_MEM: [("src", "expr")],
- HighLevelILOperation.HLIL_FADD: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_FSUB: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_FMUL: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_FDIV: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_FSQRT: [("src", "expr")],
- HighLevelILOperation.HLIL_FNEG: [("src", "expr")],
- HighLevelILOperation.HLIL_FABS: [("src", "expr")],
- HighLevelILOperation.HLIL_FLOAT_TO_INT: [("src", "expr")],
- HighLevelILOperation.HLIL_INT_TO_FLOAT: [("src", "expr")],
- HighLevelILOperation.HLIL_FLOAT_CONV: [("src", "expr")],
- HighLevelILOperation.HLIL_ROUND_TO_INT: [("src", "expr")],
- HighLevelILOperation.HLIL_FLOOR: [("src", "expr")],
- HighLevelILOperation.HLIL_CEIL: [("src", "expr")],
- HighLevelILOperation.HLIL_FTRUNC: [("src", "expr")],
- HighLevelILOperation.HLIL_FCMP_E: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_FCMP_NE: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_FCMP_LT: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_FCMP_LE: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_FCMP_GE: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_FCMP_GT: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_FCMP_O: [("left", "expr"), ("right", "expr")],
- HighLevelILOperation.HLIL_FCMP_UO: [("left", "expr"), ("right", "expr")]
+ function: 'HighLevelILFunction'
+ expr_index: ExpressionIndex
+ core_instr: CoreHighLevelILInstruction
+ as_ast: bool
+ instr_index: InstructionIndex
+ ILOperations: ClassVar[Mapping[HighLevelILOperation, List[Tuple[str, str]]]] = {
+ HighLevelILOperation.HLIL_NOP: [], HighLevelILOperation.HLIL_BLOCK: [("body", "expr_list")],
+ HighLevelILOperation.HLIL_IF: [("condition", "expr"), ("true", "expr"),
+ ("false", "expr")], HighLevelILOperation.HLIL_WHILE: [("condition", "expr"),
+ ("body", "expr")],
+ HighLevelILOperation.HLIL_WHILE_SSA: [("condition_phi", "expr"), ("condition", "expr"),
+ ("body", "expr")], HighLevelILOperation.HLIL_DO_WHILE: [
+ ("body", "expr"), ("condition", "expr")
+ ], HighLevelILOperation.HLIL_DO_WHILE_SSA: [("body", "expr"),
+ ("condition_phi", "expr"),
+ ("condition", "expr")],
+ HighLevelILOperation.HLIL_FOR: [("init", "expr"), ("condition", "expr"), ("update", "expr"),
+ ("body", "expr")], HighLevelILOperation.HLIL_FOR_SSA: [
+ ("init", "expr"), ("condition_phi", "expr"), ("condition", "expr"),
+ ("update", "expr"), ("body", "expr")
+ ], HighLevelILOperation.HLIL_SWITCH: [
+ ("condition", "expr"), ("default", "expr"), ("cases", "expr_list")
+ ], HighLevelILOperation.HLIL_CASE: [("values", "expr_list"), ("body", "expr")],
+ HighLevelILOperation.HLIL_BREAK: [], HighLevelILOperation.HLIL_CONTINUE: [], HighLevelILOperation.HLIL_JUMP: [
+ ("dest", "expr")
+ ], HighLevelILOperation.HLIL_RET: [("src", "expr_list")], HighLevelILOperation.HLIL_NORET: [],
+ HighLevelILOperation.HLIL_GOTO: [("target", "label")], HighLevelILOperation.HLIL_LABEL: [
+ ("target", "label")
+ ], HighLevelILOperation.HLIL_VAR_DECLARE: [("var", "var")], HighLevelILOperation.HLIL_VAR_INIT: [
+ ("dest", "var"), ("src", "expr")
+ ], HighLevelILOperation.HLIL_VAR_INIT_SSA: [
+ ("dest", "var_ssa"), ("src", "expr")
+ ], HighLevelILOperation.HLIL_ASSIGN: [("dest", "expr"),
+ ("src", "expr")], HighLevelILOperation.HLIL_ASSIGN_UNPACK: [
+ ("dest", "expr_list"), ("src", "expr")
+ ], HighLevelILOperation.HLIL_ASSIGN_MEM_SSA: [("dest", "expr"),
+ ("dest_memory", "int"),
+ ("src", "expr"),
+ ("src_memory", "int")],
+ HighLevelILOperation.HLIL_ASSIGN_UNPACK_MEM_SSA: [
+ ("dest", "expr_list"), ("dest_memory", "int"), ("src", "expr"), ("src_memory", "int")
+ ], HighLevelILOperation.HLIL_VAR: [("var", "var")], HighLevelILOperation.HLIL_VAR_SSA: [
+ ("var", "var_ssa")
+ ], HighLevelILOperation.HLIL_VAR_PHI: [("dest", "var_ssa"),
+ ("src", "var_ssa_list")], HighLevelILOperation.HLIL_MEM_PHI: [
+ ("dest", "int"), ("src", "int_list")
+ ], HighLevelILOperation.HLIL_STRUCT_FIELD: [
+ ("src", "expr"), ("offset", "int"), ("member_index", "member_index")
+ ], HighLevelILOperation.HLIL_ARRAY_INDEX: [
+ ("src", "expr"), ("index", "expr")
+ ], HighLevelILOperation.HLIL_ARRAY_INDEX_SSA: [("src", "expr"),
+ ("src_memory", "int"),
+ ("index", "expr")],
+ HighLevelILOperation.HLIL_SPLIT: [("high", "expr"), ("low", "expr")], HighLevelILOperation.HLIL_DEREF: [
+ ("src", "expr")
+ ], HighLevelILOperation.HLIL_DEREF_FIELD: [
+ ("src", "expr"), ("offset", "int"), ("member_index", "member_index")
+ ], HighLevelILOperation.HLIL_DEREF_SSA: [
+ ("src", "expr"), ("src_memory", "int")
+ ], HighLevelILOperation.HLIL_DEREF_FIELD_SSA: [
+ ("src", "expr"), ("src_memory", "int"), ("offset", "int"),
+ ("member_index", "member_index")
+ ], HighLevelILOperation.HLIL_ADDRESS_OF: [("src", "expr")], HighLevelILOperation.HLIL_CONST: [
+ ("constant", "int")
+ ], HighLevelILOperation.HLIL_CONST_PTR: [("constant", "int")], HighLevelILOperation.HLIL_EXTERN_PTR: [
+ ("constant", "int"), ("offset", "int")
+ ], HighLevelILOperation.HLIL_FLOAT_CONST: [("constant", "float")], HighLevelILOperation.HLIL_IMPORT: [
+ ("constant", "int")
+ ], HighLevelILOperation.HLIL_ADD: [("left", "expr"), ("right", "expr")], HighLevelILOperation.HLIL_ADC: [
+ ("left", "expr"), ("right", "expr"), ("carry", "expr")
+ ], HighLevelILOperation.HLIL_SUB: [("left", "expr"), ("right", "expr")], HighLevelILOperation.HLIL_SBB: [
+ ("left", "expr"), ("right", "expr"), ("carry", "expr")
+ ], HighLevelILOperation.HLIL_AND: [("left", "expr"), ("right", "expr")], HighLevelILOperation.HLIL_OR: [
+ ("left", "expr"), ("right", "expr")
+ ], HighLevelILOperation.HLIL_XOR: [("left", "expr"), ("right", "expr")], HighLevelILOperation.HLIL_LSL: [
+ ("left", "expr"), ("right", "expr")
+ ], HighLevelILOperation.HLIL_LSR: [("left", "expr"), ("right", "expr")], HighLevelILOperation.HLIL_ASR: [
+ ("left", "expr"), ("right", "expr")
+ ], HighLevelILOperation.HLIL_ROL: [("left", "expr"), ("right", "expr")], HighLevelILOperation.HLIL_RLC: [
+ ("left", "expr"), ("right", "expr"), ("carry", "expr")
+ ], HighLevelILOperation.HLIL_ROR: [("left", "expr"), ("right", "expr")], HighLevelILOperation.HLIL_RRC: [
+ ("left", "expr"), ("right", "expr"), ("carry", "expr")
+ ], HighLevelILOperation.HLIL_MUL: [("left", "expr"), ("right", "expr")], HighLevelILOperation.HLIL_MULU_DP: [
+ ("left", "expr"), ("right", "expr")
+ ], HighLevelILOperation.HLIL_MULS_DP: [("left", "expr"), ("right", "expr")], HighLevelILOperation.HLIL_DIVU: [
+ ("left", "expr"), ("right", "expr")
+ ], HighLevelILOperation.HLIL_DIVU_DP: [("left", "expr"), ("right", "expr")], HighLevelILOperation.HLIL_DIVS: [
+ ("left", "expr"), ("right", "expr")
+ ], HighLevelILOperation.HLIL_DIVS_DP: [("left", "expr"), ("right", "expr")], HighLevelILOperation.HLIL_MODU: [
+ ("left", "expr"), ("right", "expr")
+ ], HighLevelILOperation.HLIL_MODU_DP: [("left", "expr"), ("right", "expr")], HighLevelILOperation.HLIL_MODS: [
+ ("left", "expr"), ("right", "expr")
+ ], HighLevelILOperation.HLIL_MODS_DP: [("left", "expr"), ("right", "expr")], HighLevelILOperation.HLIL_NEG: [
+ ("src", "expr")
+ ], HighLevelILOperation.HLIL_NOT: [("src", "expr")], HighLevelILOperation.HLIL_SX: [
+ ("src", "expr")
+ ], HighLevelILOperation.HLIL_ZX: [("src", "expr")], HighLevelILOperation.HLIL_LOW_PART: [
+ ("src", "expr")
+ ], HighLevelILOperation.HLIL_CALL: [
+ ("dest", "expr"), ("params", "expr_list")
+ ], HighLevelILOperation.HLIL_CALL_SSA: [
+ ("dest", "expr"), ("params", "expr_list"), ("dest_memory", "int"), ("src_memory", "int")
+ ], HighLevelILOperation.HLIL_CMP_E: [("left", "expr"), ("right", "expr")], HighLevelILOperation.HLIL_CMP_NE: [
+ ("left", "expr"), ("right", "expr")
+ ], HighLevelILOperation.HLIL_CMP_SLT: [("left", "expr"), ("right", "expr")],
+ HighLevelILOperation.HLIL_CMP_ULT: [("left", "expr"), ("right", "expr")], HighLevelILOperation.HLIL_CMP_SLE: [
+ ("left", "expr"), ("right", "expr")
+ ], HighLevelILOperation.HLIL_CMP_ULE: [("left", "expr"),
+ ("right", "expr")], HighLevelILOperation.HLIL_CMP_SGE: [
+ ("left", "expr"), ("right", "expr")
+ ], HighLevelILOperation.HLIL_CMP_UGE: [("left", "expr"),
+ ("right", "expr")],
+ HighLevelILOperation.HLIL_CMP_SGT: [("left", "expr"), ("right", "expr")], HighLevelILOperation.HLIL_CMP_UGT: [
+ ("left", "expr"), ("right", "expr")
+ ], HighLevelILOperation.HLIL_TEST_BIT: [
+ ("left", "expr"), ("right", "expr")
+ ], HighLevelILOperation.HLIL_BOOL_TO_INT: [("src", "expr")], HighLevelILOperation.HLIL_ADD_OVERFLOW: [
+ ("left", "expr"), ("right", "expr")
+ ], HighLevelILOperation.HLIL_SYSCALL: [("params", "expr_list")], HighLevelILOperation.HLIL_SYSCALL_SSA: [
+ ("params", "expr_list"), ("dest_memory", "int"), ("src_memory", "int")
+ ], HighLevelILOperation.HLIL_TAILCALL: [
+ ("dest", "expr"), ("params", "expr_list")
+ ], HighLevelILOperation.HLIL_BP: [], HighLevelILOperation.HLIL_TRAP: [
+ ("vector", "int")
+ ], HighLevelILOperation.HLIL_INTRINSIC: [("intrinsic", "intrinsic"),
+ ("params", "expr_list")], HighLevelILOperation.HLIL_INTRINSIC_SSA: [
+ ("intrinsic", "intrinsic"), ("params", "expr_list"),
+ ("dest_memory", "int"), ("src_memory", "int")
+ ], HighLevelILOperation.HLIL_UNDEF: [],
+ HighLevelILOperation.HLIL_UNIMPL: [], HighLevelILOperation.HLIL_UNIMPL_MEM: [
+ ("src", "expr")
+ ], HighLevelILOperation.HLIL_FADD: [("left", "expr"), ("right", "expr")], HighLevelILOperation.HLIL_FSUB: [
+ ("left", "expr"), ("right", "expr")
+ ], HighLevelILOperation.HLIL_FMUL: [("left", "expr"), ("right", "expr")], HighLevelILOperation.HLIL_FDIV: [
+ ("left", "expr"), ("right", "expr")
+ ], HighLevelILOperation.HLIL_FSQRT: [("src", "expr")], HighLevelILOperation.HLIL_FNEG: [
+ ("src", "expr")
+ ], HighLevelILOperation.HLIL_FABS: [("src", "expr")], HighLevelILOperation.HLIL_FLOAT_TO_INT: [
+ ("src", "expr")
+ ], HighLevelILOperation.HLIL_INT_TO_FLOAT: [("src", "expr")], HighLevelILOperation.HLIL_FLOAT_CONV: [
+ ("src", "expr")
+ ], HighLevelILOperation.HLIL_ROUND_TO_INT: [("src", "expr")], HighLevelILOperation.HLIL_FLOOR: [
+ ("src", "expr")
+ ], HighLevelILOperation.HLIL_CEIL: [("src", "expr")], HighLevelILOperation.HLIL_FTRUNC: [
+ ("src", "expr")
+ ], HighLevelILOperation.HLIL_FCMP_E: [("left", "expr"), ("right", "expr")], HighLevelILOperation.HLIL_FCMP_NE: [
+ ("left", "expr"), ("right", "expr")
+ ], HighLevelILOperation.HLIL_FCMP_LT: [
+ ("left", "expr"), ("right", "expr")
+ ], HighLevelILOperation.HLIL_FCMP_LE: [
+ ("left", "expr"), ("right", "expr")
+ ], HighLevelILOperation.HLIL_FCMP_GE: [
+ ("left", "expr"), ("right", "expr")
+ ], HighLevelILOperation.HLIL_FCMP_GT: [("left", "expr"), ("right", "expr")], HighLevelILOperation.HLIL_FCMP_O: [
+ ("left", "expr"), ("right", "expr")
+ ], HighLevelILOperation.HLIL_FCMP_UO: [("left", "expr"), ("right", "expr")]
}
@staticmethod
@@ -271,7 +298,10 @@ class HighLevelILInstruction(BaseILInstruction):
show_graph_report("HLIL Class Hierarchy Graph", graph)
@classmethod
- def create(cls, func:'HighLevelILFunction', expr_index:ExpressionIndex, as_ast:bool=True, instr_index:Optional[InstructionIndex]=None) -> 'HighLevelILInstruction':
+ def create(
+ cls, func: 'HighLevelILFunction', expr_index: ExpressionIndex, as_ast: bool = True,
+ instr_index: Optional[InstructionIndex] = None
+ ) -> 'HighLevelILInstruction':
assert func.arch is not None, "Attempted to create IL instruction with function missing an Architecture"
instr = core.BNGetHighLevelILByIndex(func.handle, expr_index, as_ast)
assert instr is not None, "core.BNGetHighLevelILByIndex returned None"
@@ -306,27 +336,27 @@ class HighLevelILInstruction(BaseILInstruction):
continuation = "..."
return f"<{self.operation.name}: {first_line}{continuation}>"
- def __eq__(self, other:'HighLevelILInstruction'):
+ def __eq__(self, other: 'HighLevelILInstruction'):
if not isinstance(other, HighLevelILInstruction):
return NotImplemented
return self.function == other.function and self.expr_index == other.expr_index
- def __lt__(self, other:'HighLevelILInstruction'):
+ def __lt__(self, other: 'HighLevelILInstruction'):
if not isinstance(other, HighLevelILInstruction):
return NotImplemented
return self.function == other.function and self.expr_index < other.expr_index
- def __le__(self, other:'HighLevelILInstruction'):
+ def __le__(self, other: 'HighLevelILInstruction'):
if not isinstance(other, HighLevelILInstruction):
return NotImplemented
return self.function == other.function and self.expr_index <= other.expr_index
- def __gt__(self, other:'HighLevelILInstruction'):
+ def __gt__(self, other: 'HighLevelILInstruction'):
if not isinstance(other, HighLevelILInstruction):
return NotImplemented
return self.function == other.function and self.expr_index > other.expr_index
- def __ge__(self, other:'HighLevelILInstruction'):
+ def __ge__(self, other: 'HighLevelILInstruction'):
if not isinstance(other, HighLevelILInstruction):
return NotImplemented
return self.function == other.function and self.expr_index >= other.expr_index
@@ -356,8 +386,8 @@ class HighLevelILInstruction(BaseILInstruction):
@property
def prefix_operands(self) -> List[Union[HighLevelILOperandType, HighLevelILOperationAndSize]]:
"""All operands in the expression tree in prefix order"""
- result:List[Union[HighLevelILOperandType, HighLevelILOperationAndSize]] = [
- HighLevelILOperationAndSize(self.operation, self.size)]
+ result: List[Union[HighLevelILOperandType,
+ HighLevelILOperationAndSize]] = [HighLevelILOperationAndSize(self.operation, self.size)]
for operand in self.operands:
if isinstance(operand, HighLevelILInstruction):
result.extend(operand.prefix_operands)
@@ -368,7 +398,7 @@ class HighLevelILInstruction(BaseILInstruction):
@property
def postfix_operands(self) -> List[Union[HighLevelILOperandType, HighLevelILOperationAndSize]]:
"""All operands in the expression tree in postfix order"""
- result:List[Union[HighLevelILOperandType, HighLevelILOperationAndSize]] = []
+ result: List[Union[HighLevelILOperandType, HighLevelILOperationAndSize]] = []
for operand in self.operands:
if isinstance(operand, HighLevelILInstruction):
result.extend(operand.postfix_operands)
@@ -488,16 +518,20 @@ class HighLevelILInstruction(BaseILInstruction):
def ssa_form(self) -> 'HighLevelILInstruction':
"""SSA form of expression (read-only)"""
assert self.function.ssa_form is not None
- return HighLevelILInstruction.create(self.function.ssa_form,
- ExpressionIndex(core.BNGetHighLevelILSSAExprIndex(self.function.handle, self.expr_index)), self.as_ast)
+ return HighLevelILInstruction.create(
+ self.function.ssa_form,
+ ExpressionIndex(core.BNGetHighLevelILSSAExprIndex(self.function.handle, self.expr_index)), self.as_ast
+ )
@property
def non_ssa_form(self) -> Optional['HighLevelILInstruction']:
"""Non-SSA form of expression (read-only)"""
if self.function.non_ssa_form is None:
return None
- return HighLevelILInstruction.create(self.function.non_ssa_form,
- ExpressionIndex(core.BNGetHighLevelILNonSSAExprIndex(self.function.handle, self.expr_index)), self.as_ast)
+ return HighLevelILInstruction.create(
+ self.function.non_ssa_form,
+ ExpressionIndex(core.BNGetHighLevelILNonSSAExprIndex(self.function.handle, self.expr_index)), self.as_ast
+ )
@property
def medium_level_il(self) -> Optional['mediumlevelil.MediumLevelILInstruction']:
@@ -588,10 +622,12 @@ class HighLevelILInstruction(BaseILInstruction):
platform = None
if self.function.source_function:
platform = self.function.source_function.platform
- return types.Type.create(core.BNNewTypeReference(result.type), platform = platform, confidence = result.confidence)
+ return types.Type.create(
+ core.BNNewTypeReference(result.type), platform=platform, confidence=result.confidence
+ )
return None
- def get_possible_values(self, options:Optional[List[DataFlowQueryOption]]=None) -> 'variable.PossibleValueSet':
+ def get_possible_values(self, options: Optional[List[DataFlowQueryOption]] = None) -> 'variable.PossibleValueSet':
mlil = self.mlil
if mlil is None:
return variable.PossibleValueSet()
@@ -604,15 +640,15 @@ class HighLevelILInstruction(BaseILInstruction):
"""Version of active memory contents in SSA form for this instruction"""
return core.BNGetHighLevelILSSAMemoryVersionAtILInstruction(self.function.handle, self.instr_index)
- def get_ssa_var_version(self, var:'variable.Variable') -> int:
+ def get_ssa_var_version(self, var: 'variable.Variable') -> int:
var_data = var.to_BNVariable()
return core.BNGetHighLevelILSSAVarVersionAtILInstruction(self.function.handle, var_data, self.instr_index)
- def get_int(self, operand_index:int) -> int:
+ def get_int(self, operand_index: int) -> int:
value = self.core_instr.operands[operand_index]
return (value & ((1 << 63) - 1)) - (value & (1 << 63))
- def get_float(self, operand_index:int) -> float:
+ def get_float(self, operand_index: int) -> float:
value = self.core_instr.operands[operand_index]
if self.core_instr.size == 4:
return struct.unpack("f", struct.pack("I", value & 0xffffffff))[0]
@@ -621,35 +657,35 @@ class HighLevelILInstruction(BaseILInstruction):
else:
return float(value)
- def get_expr(self, operand_index:int) -> 'HighLevelILInstruction':
- return HighLevelILInstruction.create(self.function,
- ExpressionIndex(self.core_instr.operands[operand_index]))
+ def get_expr(self, operand_index: int) -> 'HighLevelILInstruction':
+ return HighLevelILInstruction.create(self.function, ExpressionIndex(self.core_instr.operands[operand_index]))
- def get_intrinsic(self, operand_index:int) -> 'lowlevelil.ILIntrinsic':
+ def get_intrinsic(self, operand_index: int) -> 'lowlevelil.ILIntrinsic':
if self.function.arch is None:
raise ValueError("Attempting to create ILIntrinsic from function with no Architecture")
- return lowlevelil.ILIntrinsic(self.function.arch,
- architecture.IntrinsicIndex(self.core_instr.operands[operand_index]))
+ return lowlevelil.ILIntrinsic(
+ self.function.arch, architecture.IntrinsicIndex(self.core_instr.operands[operand_index])
+ )
- def get_var(self, operand_index:int) -> 'variable.Variable':
+ def get_var(self, operand_index: int) -> 'variable.Variable':
value = self.core_instr.operands[operand_index]
return variable.Variable.from_identifier(self.function, value)
- def get_var_ssa(self, operand_index1:int, operand_index2:int) -> 'mediumlevelil.SSAVariable':
+ def get_var_ssa(self, operand_index1: int, operand_index2: int) -> 'mediumlevelil.SSAVariable':
var = variable.Variable.from_identifier(self.function, self.core_instr.operands[operand_index1])
version = self.core_instr.operands[operand_index2]
return mediumlevelil.SSAVariable(var, version)
- def get_var_ssa_dest_and_src(self, operand_index1:int, operand_index2:int) -> 'mediumlevelil.SSAVariable':
+ def get_var_ssa_dest_and_src(self, operand_index1: int, operand_index2: int) -> 'mediumlevelil.SSAVariable':
var = variable.Variable.from_identifier(self.function, self.core_instr.operands[operand_index1])
dest_version = self.core_instr.operands[operand_index2]
return mediumlevelil.SSAVariable(var, dest_version)
- def get_int_list(self, operand_index:int) -> List[int]:
+ def get_int_list(self, operand_index: int) -> List[int]:
count = ctypes.c_ulonglong()
operand_list = core.BNHighLevelILGetOperandList(self.function.handle, self.expr_index, operand_index, count)
assert operand_list is not None, "core.BNHighLevelILGetOperandList returned None"
- value:List[int] = []
+ value: List[int] = []
try:
for j in range(count.value):
value.append(operand_list[j])
@@ -657,11 +693,11 @@ class HighLevelILInstruction(BaseILInstruction):
finally:
core.BNHighLevelILFreeOperandList(operand_list)
- def get_expr_list(self, operand_index1:int, operand_index2:int) -> List['HighLevelILInstruction']:
+ def get_expr_list(self, operand_index1: int, operand_index2: int) -> List['HighLevelILInstruction']:
count = ctypes.c_ulonglong()
operand_list = core.BNHighLevelILGetOperandList(self.function.handle, self.expr_index, operand_index1, count)
assert operand_list is not None, "core.BNHighLevelILGetOperandList returned None"
- value:List[HighLevelILInstruction] = []
+ value: List[HighLevelILInstruction] = []
try:
for j in range(count.value):
value.append(HighLevelILInstruction.create(self.function, operand_list[j], self.as_ast))
@@ -669,8 +705,7 @@ class HighLevelILInstruction(BaseILInstruction):
finally:
core.BNHighLevelILFreeOperandList(operand_list)
-
- def get_var_ssa_list(self, operand_index1:int, _:int) -> List['mediumlevelil.SSAVariable']:
+ def get_var_ssa_list(self, operand_index1: int, _: int) -> List['mediumlevelil.SSAVariable']:
count = ctypes.c_ulonglong()
operand_list = core.BNHighLevelILGetOperandList(self.function.handle, self.expr_index, operand_index1, count)
assert operand_list is not None, "core.BNHighLevelILGetOperandList returned None"
@@ -678,20 +713,21 @@ class HighLevelILInstruction(BaseILInstruction):
try:
for j in range(count.value // 2):
var_id = operand_list[j * 2]
- var_version = operand_list[(j * 2) + 1]
- value.append(mediumlevelil.SSAVariable(variable.Variable.from_identifier(self.function,
- var_id), var_version))
+ var_version = operand_list[(j*2) + 1]
+ value.append(
+ mediumlevelil.SSAVariable(variable.Variable.from_identifier(self.function, var_id), var_version)
+ )
return value
finally:
core.BNMediumLevelILFreeOperandList(operand_list)
- def get_member_index(self, operand_index:int) -> Optional[int]:
+ def get_member_index(self, operand_index: int) -> Optional[int]:
value = self.core_instr.operands[operand_index]
if (value & (1 << 63)) != 0:
value = None
return value
- def get_label(self, operand_index:int) -> GotoLabel:
+ def get_label(self, operand_index: int) -> GotoLabel:
return GotoLabel(self.function, self.core_instr.operands[operand_index])
@property
@@ -701,7 +737,6 @@ class HighLevelILInstruction(BaseILInstruction):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILUnaryBase(HighLevelILInstruction, UnaryOperation):
-
@property
def src(self) -> HighLevelILInstruction:
return self.get_expr(0)
@@ -713,7 +748,6 @@ class HighLevelILUnaryBase(HighLevelILInstruction, UnaryOperation):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILBinaryBase(HighLevelILInstruction, BinaryOperation):
-
@property
def left(self) -> HighLevelILInstruction:
return self.get_expr(0)
@@ -734,7 +768,6 @@ class HighLevelILComparisonBase(HighLevelILBinaryBase, Comparison):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILCarryBase(HighLevelILInstruction, Arithmetic):
-
@property
def left(self) -> HighLevelILInstruction:
return self.get_expr(0)
@@ -759,7 +792,6 @@ class HighLevelILNop(HighLevelILInstruction):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILBlock(HighLevelILInstruction):
-
@property
def body(self) -> List[HighLevelILInstruction]:
return self.get_expr_list(0, 1)
@@ -771,7 +803,6 @@ class HighLevelILBlock(HighLevelILInstruction):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILIf(HighLevelILInstruction, ControlFlow):
-
@property
def condition(self) -> HighLevelILInstruction:
return self.get_expr(0)
@@ -791,7 +822,6 @@ class HighLevelILIf(HighLevelILInstruction, ControlFlow):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILWhile(HighLevelILInstruction, Loop):
-
@property
def condition(self) -> HighLevelILInstruction:
return self.get_expr(0)
@@ -807,7 +837,6 @@ class HighLevelILWhile(HighLevelILInstruction, Loop):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILWhileSsa(HighLevelILInstruction, Loop, SSA):
-
@property
def condition_phi(self) -> HighLevelILInstruction:
return self.get_expr(0)
@@ -827,7 +856,6 @@ class HighLevelILWhileSsa(HighLevelILInstruction, Loop, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILDoWhile(HighLevelILInstruction, Loop):
-
@property
def body(self) -> HighLevelILInstruction:
return self.get_expr(0)
@@ -843,7 +871,6 @@ class HighLevelILDoWhile(HighLevelILInstruction, Loop):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILDoWhileSsa(HighLevelILInstruction, Loop, SSA):
-
@property
def body(self) -> HighLevelILInstruction:
return self.get_expr(0)
@@ -863,7 +890,6 @@ class HighLevelILDoWhileSsa(HighLevelILInstruction, Loop, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILFor(HighLevelILInstruction, Loop):
-
@property
def init(self) -> HighLevelILInstruction:
return self.get_expr(0)
@@ -887,7 +913,6 @@ class HighLevelILFor(HighLevelILInstruction, Loop):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILForSsa(HighLevelILInstruction, Loop, SSA):
-
@property
def init(self) -> HighLevelILInstruction:
return self.get_expr(0)
@@ -915,7 +940,6 @@ class HighLevelILForSsa(HighLevelILInstruction, Loop, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILSwitch(HighLevelILInstruction, ControlFlow):
-
@property
def condition(self) -> HighLevelILInstruction:
return self.get_expr(0)
@@ -935,7 +959,6 @@ class HighLevelILSwitch(HighLevelILInstruction, ControlFlow):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILCase(HighLevelILInstruction):
-
@property
def values(self) -> List[HighLevelILInstruction]:
return self.get_expr_list(0, 1)
@@ -953,6 +976,7 @@ class HighLevelILCase(HighLevelILInstruction):
class HighLevelILBreak(HighLevelILInstruction, Terminal):
pass
+
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILContinue(HighLevelILInstruction, ControlFlow):
pass
@@ -960,7 +984,6 @@ class HighLevelILContinue(HighLevelILInstruction, ControlFlow):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILJump(HighLevelILInstruction, Terminal):
-
@property
def dest(self) -> HighLevelILInstruction:
return self.get_expr(0)
@@ -972,7 +995,6 @@ class HighLevelILJump(HighLevelILInstruction, Terminal):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILRet(HighLevelILInstruction, ControlFlow):
-
@property
def src(self) -> List[HighLevelILInstruction]:
return self.get_expr_list(0, 1)
@@ -989,7 +1011,6 @@ class HighLevelILNoret(HighLevelILInstruction, Terminal):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILGoto(HighLevelILInstruction, Terminal):
-
@property
def target(self) -> GotoLabel:
return self.get_label(0)
@@ -1001,7 +1022,6 @@ class HighLevelILGoto(HighLevelILInstruction, Terminal):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILLabel(HighLevelILInstruction):
-
@property
def target(self) -> GotoLabel:
return self.get_label(0)
@@ -1013,7 +1033,6 @@ class HighLevelILLabel(HighLevelILInstruction):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILVarDeclare(HighLevelILInstruction):
-
@property
def var(self) -> 'variable.Variable':
return self.get_var(0)
@@ -1025,7 +1044,6 @@ class HighLevelILVarDeclare(HighLevelILInstruction):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILVarInit(HighLevelILInstruction):
-
@property
def dest(self) -> 'variable.Variable':
return self.get_var(0)
@@ -1045,7 +1063,6 @@ class HighLevelILVarInit(HighLevelILInstruction):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILVarInitSsa(HighLevelILInstruction, SSA):
-
@property
def dest(self) -> 'mediumlevelil.SSAVariable':
return self.get_var_ssa(0, 1)
@@ -1065,7 +1082,6 @@ class HighLevelILVarInitSsa(HighLevelILInstruction, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILAssign(HighLevelILInstruction):
-
@property
def dest(self) -> HighLevelILInstruction:
return self.get_expr(0)
@@ -1090,7 +1106,6 @@ class HighLevelILAssign(HighLevelILInstruction):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILAssignUnpack(HighLevelILInstruction):
-
@property
def dest(self) -> List[HighLevelILInstruction]:
return self.get_expr_list(0, 1)
@@ -1116,7 +1131,6 @@ class HighLevelILAssignUnpack(HighLevelILInstruction):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILAssignMemSsa(HighLevelILInstruction, SSA):
-
@property
def dest(self) -> HighLevelILInstruction:
return self.get_expr(0)
@@ -1140,7 +1154,6 @@ class HighLevelILAssignMemSsa(HighLevelILInstruction, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILAssignUnpackMemSsa(HighLevelILInstruction, SSA, Memory):
-
@property
def dest(self) -> List[HighLevelILInstruction]:
return self.get_expr_list(0, 1)
@@ -1164,7 +1177,6 @@ class HighLevelILAssignUnpackMemSsa(HighLevelILInstruction, SSA, Memory):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILVar(HighLevelILInstruction):
-
@property
def var(self) -> 'variable.Variable':
return self.get_var(0)
@@ -1176,7 +1188,6 @@ class HighLevelILVar(HighLevelILInstruction):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILVarSsa(HighLevelILInstruction, SSA):
-
@property
def var(self) -> 'mediumlevelil.SSAVariable':
return self.get_var_ssa(0, 1)
@@ -1188,7 +1199,6 @@ class HighLevelILVarSsa(HighLevelILInstruction, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILVarPhi(HighLevelILInstruction, Phi):
-
@property
def dest(self) -> 'mediumlevelil.SSAVariable':
return self.get_var_ssa(0, 1)
@@ -1208,7 +1218,6 @@ class HighLevelILVarPhi(HighLevelILInstruction, Phi):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILMemPhi(HighLevelILInstruction, Memory, Phi):
-
@property
def dest(self) -> int:
return self.get_int(0)
@@ -1224,7 +1233,6 @@ class HighLevelILMemPhi(HighLevelILInstruction, Memory, Phi):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILStructField(HighLevelILInstruction):
-
@property
def src(self) -> HighLevelILInstruction:
return self.get_expr(0)
@@ -1241,9 +1249,9 @@ class HighLevelILStructField(HighLevelILInstruction):
def operands(self) -> List[HighLevelILOperandType]:
return [self.src, self.offset, self.member_index]
+
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILArrayIndex(HighLevelILInstruction):
-
@property
def src(self) -> HighLevelILInstruction:
return self.get_expr(0)
@@ -1259,7 +1267,6 @@ class HighLevelILArrayIndex(HighLevelILInstruction):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILArrayIndexSsa(HighLevelILInstruction, SSA):
-
@property
def src(self) -> HighLevelILInstruction:
return self.get_expr(0)
@@ -1279,7 +1286,6 @@ class HighLevelILArrayIndexSsa(HighLevelILInstruction, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILSplit(HighLevelILInstruction):
-
@property
def high(self) -> HighLevelILInstruction:
return self.get_expr(0)
@@ -1300,7 +1306,6 @@ class HighLevelILDeref(HighLevelILUnaryBase):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILDerefField(HighLevelILInstruction):
-
@property
def src(self) -> HighLevelILInstruction:
return self.get_expr(0)
@@ -1320,7 +1325,6 @@ class HighLevelILDerefField(HighLevelILInstruction):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILDerefSsa(HighLevelILInstruction, SSA):
-
@property
def src(self) -> HighLevelILInstruction:
return self.get_expr(0)
@@ -1336,7 +1340,6 @@ class HighLevelILDerefSsa(HighLevelILInstruction, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILDerefFieldSsa(HighLevelILInstruction, SSA):
-
@property
def src(self) -> HighLevelILInstruction:
return self.get_expr(0)
@@ -1360,7 +1363,6 @@ class HighLevelILDerefFieldSsa(HighLevelILInstruction, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILAddressOf(HighLevelILUnaryBase):
-
@property
def vars_address_taken(self) -> VariablesList:
if isinstance(self.src, HighLevelILVar):
@@ -1372,7 +1374,6 @@ class HighLevelILAddressOf(HighLevelILUnaryBase):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILConst(HighLevelILInstruction, Constant):
-
@property
def constant(self) -> int:
return self.get_int(0)
@@ -1384,7 +1385,6 @@ class HighLevelILConst(HighLevelILInstruction, Constant):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILConstPtr(HighLevelILInstruction, Constant):
-
@property
def constant(self) -> int:
return self.get_int(0)
@@ -1396,7 +1396,6 @@ class HighLevelILConstPtr(HighLevelILInstruction, Constant):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILExternPtr(HighLevelILInstruction, Constant):
-
@property
def constant(self) -> int:
return self.get_int(0)
@@ -1412,7 +1411,6 @@ class HighLevelILExternPtr(HighLevelILInstruction, Constant):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILFloatConst(HighLevelILInstruction, Constant):
-
@property
def constant(self) -> float:
return self.get_float(0)
@@ -1424,7 +1422,6 @@ class HighLevelILFloatConst(HighLevelILInstruction, Constant):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILImport(HighLevelILInstruction, Constant):
-
@property
def constant(self) -> int:
return self.get_int(0)
@@ -1586,7 +1583,6 @@ class HighLevelILLowPart(HighLevelILUnaryBase, Arithmetic):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILCall(HighLevelILInstruction, Localcall):
-
@property
def dest(self) -> HighLevelILInstruction:
return self.get_expr(0)
@@ -1602,7 +1598,6 @@ class HighLevelILCall(HighLevelILInstruction, Localcall):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILCallSsa(HighLevelILInstruction, Localcall, SSA):
-
@property
def dest(self) -> HighLevelILInstruction:
return self.get_expr(0)
@@ -1691,7 +1686,6 @@ class HighLevelILAddOverflow(HighLevelILBinaryBase, Arithmetic):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILSyscall(HighLevelILInstruction, Syscall):
-
@property
def params(self) -> List[HighLevelILInstruction]:
return self.get_expr_list(0, 1)
@@ -1703,7 +1697,6 @@ class HighLevelILSyscall(HighLevelILInstruction, Syscall):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILSyscallSsa(HighLevelILInstruction, Syscall, SSA):
-
@property
def params(self) -> List[HighLevelILInstruction]:
return self.get_expr_list(0, 1)
@@ -1723,7 +1716,6 @@ class HighLevelILSyscallSsa(HighLevelILInstruction, Syscall, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILTailcall(HighLevelILInstruction, Tailcall):
-
@property
def dest(self) -> HighLevelILInstruction:
return self.get_expr(0)
@@ -1744,7 +1736,6 @@ class HighLevelILBp(HighLevelILInstruction, Terminal):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILTrap(HighLevelILInstruction, Terminal):
-
@property
def vector(self) -> int:
return self.get_int(0)
@@ -1756,7 +1747,6 @@ class HighLevelILTrap(HighLevelILInstruction, Terminal):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILIntrinsic(HighLevelILInstruction):
-
@property
def intrinsic(self) -> 'lowlevelil.ILIntrinsic':
return self.get_intrinsic(0)
@@ -1772,7 +1762,6 @@ class HighLevelILIntrinsic(HighLevelILInstruction):
@dataclass(frozen=True, repr=False, eq=False)
class HighLevelILIntrinsicSsa(HighLevelILInstruction, SSA):
-
@property
def intrinsic(self) -> 'lowlevelil.ILIntrinsic':
return self.get_intrinsic(0)
@@ -1920,135 +1909,150 @@ class HighLevelILFcmpUo(HighLevelILComparisonBase, FloatingPoint):
ILInstruction = {
- HighLevelILOperation.HLIL_NOP:HighLevelILNop, # ,
- HighLevelILOperation.HLIL_BLOCK:HighLevelILBlock, # ("body", "expr_list"),
- HighLevelILOperation.HLIL_IF:HighLevelILIf, # ("condition", "expr"), ("true", "expr"), ("false", "expr"),
- HighLevelILOperation.HLIL_WHILE:HighLevelILWhile, # ("condition", "expr"), ("body", "expr"),
- HighLevelILOperation.HLIL_WHILE_SSA:HighLevelILWhileSsa, # ("condition_phi", "expr"), ("condition", "expr"), ("body", "expr"),
- HighLevelILOperation.HLIL_DO_WHILE:HighLevelILDoWhile, # ("body", "expr"), ("condition", "expr"),
- HighLevelILOperation.HLIL_DO_WHILE_SSA:HighLevelILDoWhileSsa, # ("body", "expr"), ("condition_phi", "expr"), ("condition", "expr"),
- HighLevelILOperation.HLIL_FOR:HighLevelILFor, # ("init", "expr"), ("condition", "expr"), ("update", "expr"), ("body", "expr"),
- HighLevelILOperation.HLIL_FOR_SSA:HighLevelILForSsa, # ("init", "expr"), ("condition_phi", "expr"), ("condition", "expr"), ("update", "expr"), ("body", "expr"),
- HighLevelILOperation.HLIL_SWITCH:HighLevelILSwitch, # ("condition", "expr"), ("default", "expr"), ("cases", "expr_list"),
- HighLevelILOperation.HLIL_CASE:HighLevelILCase, # ("values", "expr_list"), ("body", "expr"),
- HighLevelILOperation.HLIL_BREAK:HighLevelILBreak, # ,
- HighLevelILOperation.HLIL_CONTINUE:HighLevelILContinue, # ,
- HighLevelILOperation.HLIL_JUMP:HighLevelILJump, # ("dest", "expr"),
- HighLevelILOperation.HLIL_RET:HighLevelILRet, # ("src", "expr_list"),
- HighLevelILOperation.HLIL_NORET:HighLevelILNoret, # ,
- HighLevelILOperation.HLIL_GOTO:HighLevelILGoto, # ("target", "label"),
- HighLevelILOperation.HLIL_LABEL:HighLevelILLabel, # ("target", "label"),
- HighLevelILOperation.HLIL_VAR_DECLARE:HighLevelILVarDeclare, # ("var", "var"),
- HighLevelILOperation.HLIL_VAR_INIT:HighLevelILVarInit, # ("dest", "var"), ("src", "expr"),
- HighLevelILOperation.HLIL_VAR_INIT_SSA:HighLevelILVarInitSsa, # ("dest", "var_ssa"), ("src", "expr"),
- HighLevelILOperation.HLIL_ASSIGN:HighLevelILAssign, # ("dest", "expr"), ("src", "expr"),
- HighLevelILOperation.HLIL_ASSIGN_UNPACK:HighLevelILAssignUnpack, # ("dest", "expr_list"), ("src", "expr"),
- HighLevelILOperation.HLIL_ASSIGN_MEM_SSA:HighLevelILAssignMemSsa, # ("dest", "expr"), ("dest_memory", "int"), ("src", "expr"), ("src_memory", "int"),
- HighLevelILOperation.HLIL_ASSIGN_UNPACK_MEM_SSA:HighLevelILAssignUnpackMemSsa, # ("dest", "expr_list"), ("dest_memory", "int"), ("src", "expr"), ("src_memory", "int"),
- HighLevelILOperation.HLIL_VAR:HighLevelILVar, # ("var", "var"),
- HighLevelILOperation.HLIL_VAR_SSA:HighLevelILVarSsa, # ("var", "var_ssa"),
- HighLevelILOperation.HLIL_VAR_PHI:HighLevelILVarPhi, # ("dest", "var_ssa"), ("src", "var_ssa_list"),
- HighLevelILOperation.HLIL_MEM_PHI:HighLevelILMemPhi, # ("dest", "int"), ("src", "int_list"),
- HighLevelILOperation.HLIL_ARRAY_INDEX:HighLevelILArrayIndex, # ("src", "expr"), ("index", "expr"),
- HighLevelILOperation.HLIL_ARRAY_INDEX_SSA:HighLevelILArrayIndexSsa, # ("src", "expr"), ("src_memory", "int"), ("index", "expr"),
- HighLevelILOperation.HLIL_SPLIT:HighLevelILSplit, # ("high", "expr"), ("low", "expr"),
- HighLevelILOperation.HLIL_DEREF:HighLevelILDeref, # ("src", "expr"),
- HighLevelILOperation.HLIL_STRUCT_FIELD:HighLevelILStructField, # ("src", "expr"), ("offset", "int"), ("member_index", "member_index"),
- HighLevelILOperation.HLIL_DEREF_FIELD:HighLevelILDerefField, # ("src", "expr"), ("offset", "int"), ("member_index", "member_index"),
- HighLevelILOperation.HLIL_DEREF_SSA:HighLevelILDerefSsa, # ("src", "expr"), ("src_memory", "int"),
- HighLevelILOperation.HLIL_DEREF_FIELD_SSA:HighLevelILDerefFieldSsa, # ("src", "expr"), ("src_memory", "int"), ("offset", "int"), ("member_index", "member_index"),
- HighLevelILOperation.HLIL_ADDRESS_OF:HighLevelILAddressOf, # ("src", "expr"),
- HighLevelILOperation.HLIL_CONST:HighLevelILConst, # ("constant", "int"),
- HighLevelILOperation.HLIL_CONST_PTR:HighLevelILConstPtr, # ("constant", "int"),
- HighLevelILOperation.HLIL_EXTERN_PTR:HighLevelILExternPtr, # ("constant", "int"), ("offset", "int"),
- HighLevelILOperation.HLIL_FLOAT_CONST:HighLevelILFloatConst, # ("constant", "float"),
- HighLevelILOperation.HLIL_IMPORT:HighLevelILImport, # ("constant", "int"),
- HighLevelILOperation.HLIL_ADD:HighLevelILAdd, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_ADC:HighLevelILAdc, # ("left", "expr"), ("right", "expr"), ("carry", "expr"),
- HighLevelILOperation.HLIL_SUB:HighLevelILSub, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_SBB:HighLevelILSbb, # ("left", "expr"), ("right", "expr"), ("carry", "expr"),
- HighLevelILOperation.HLIL_AND:HighLevelILAnd, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_OR:HighLevelILOr, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_XOR:HighLevelILXor, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_LSL:HighLevelILLsl, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_LSR:HighLevelILLsr, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_ASR:HighLevelILAsr, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_ROL:HighLevelILRol, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_RLC:HighLevelILRlc, # ("left", "expr"), ("right", "expr"), ("carry", "expr"),
- HighLevelILOperation.HLIL_ROR:HighLevelILRor, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_RRC:HighLevelILRrc, # ("left", "expr"), ("right", "expr"), ("carry", "expr"),
- HighLevelILOperation.HLIL_MUL:HighLevelILMul, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_MULU_DP:HighLevelILMuluDp, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_MULS_DP:HighLevelILMulsDp, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_DIVU:HighLevelILDivu, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_DIVU_DP:HighLevelILDivuDp, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_DIVS:HighLevelILDivs, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_DIVS_DP:HighLevelILDivsDp, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_MODU:HighLevelILModu, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_MODU_DP:HighLevelILModuDp, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_MODS:HighLevelILMods, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_MODS_DP:HighLevelILModsDp, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_NEG:HighLevelILNeg, # ("src", "expr"),
- HighLevelILOperation.HLIL_NOT:HighLevelILNot, # ("src", "expr"),
- HighLevelILOperation.HLIL_SX:HighLevelILSx, # ("src", "expr"),
- HighLevelILOperation.HLIL_ZX:HighLevelILZx, # ("src", "expr"),
- HighLevelILOperation.HLIL_LOW_PART:HighLevelILLowPart, # ("src", "expr"),
- HighLevelILOperation.HLIL_CALL:HighLevelILCall, # ("dest", "expr"), ("params", "expr_list"),
- HighLevelILOperation.HLIL_CALL_SSA:HighLevelILCallSsa, # ("dest", "expr"), ("params", "expr_list"), ("dest_memory", "int"), ("src_memory", "int"),
- HighLevelILOperation.HLIL_CMP_E:HighLevelILCmpE, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_CMP_NE:HighLevelILCmpNe, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_CMP_SLT:HighLevelILCmpSlt, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_CMP_ULT:HighLevelILCmpUlt, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_CMP_SLE:HighLevelILCmpSle, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_CMP_ULE:HighLevelILCmpUle, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_CMP_SGE:HighLevelILCmpSge, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_CMP_UGE:HighLevelILCmpUge, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_CMP_SGT:HighLevelILCmpSgt, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_CMP_UGT:HighLevelILCmpUgt, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_TEST_BIT:HighLevelILTestBit, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_BOOL_TO_INT:HighLevelILBoolToInt, # ("src", "expr"),
- HighLevelILOperation.HLIL_ADD_OVERFLOW:HighLevelILAddOverflow, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_SYSCALL:HighLevelILSyscall, # ("params", "expr_list"),
- HighLevelILOperation.HLIL_SYSCALL_SSA:HighLevelILSyscallSsa, # ("params", "expr_list"), ("dest_memory", "int"), ("src_memory", "int"),
- HighLevelILOperation.HLIL_TAILCALL:HighLevelILTailcall, # ("dest", "expr"), ("params", "expr_list"),
- HighLevelILOperation.HLIL_BP:HighLevelILBp, # ,
- HighLevelILOperation.HLIL_TRAP:HighLevelILTrap, # ("vector", "int"),
- HighLevelILOperation.HLIL_INTRINSIC:HighLevelILIntrinsic, # ("intrinsic", "intrinsic"), ("params", "expr_list"),
- HighLevelILOperation.HLIL_INTRINSIC_SSA:HighLevelILIntrinsicSsa, # ("intrinsic", "intrinsic"), ("params", "expr_list"), ("dest_memory", "int"), ("src_memory", "int"),
- HighLevelILOperation.HLIL_UNDEF:HighLevelILUndef, # ,
- HighLevelILOperation.HLIL_UNIMPL:HighLevelILUnimpl, # ,
- HighLevelILOperation.HLIL_UNIMPL_MEM:HighLevelILUnimplMem, # ("src", "expr"),
- HighLevelILOperation.HLIL_FADD:HighLevelILFadd, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_FSUB:HighLevelILFsub, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_FMUL:HighLevelILFmul, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_FDIV:HighLevelILFdiv, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_FSQRT:HighLevelILFsqrt, # ("src", "expr"),
- HighLevelILOperation.HLIL_FNEG:HighLevelILFneg, # ("src", "expr"),
- HighLevelILOperation.HLIL_FABS:HighLevelILFabs, # ("src", "expr"),
- HighLevelILOperation.HLIL_FLOAT_TO_INT:HighLevelILFloatToInt, # ("src", "expr"),
- HighLevelILOperation.HLIL_INT_TO_FLOAT:HighLevelILIntToFloat, # ("src", "expr"),
- HighLevelILOperation.HLIL_FLOAT_CONV:HighLevelILFloatConv, # ("src", "expr"),
- HighLevelILOperation.HLIL_ROUND_TO_INT:HighLevelILRoundToInt, # ("src", "expr"),
- HighLevelILOperation.HLIL_FLOOR:HighLevelILFloor, # ("src", "expr"),
- HighLevelILOperation.HLIL_CEIL:HighLevelILCeil, # ("src", "expr"),
- HighLevelILOperation.HLIL_FTRUNC:HighLevelILFtrunc, # ("src", "expr"),
- HighLevelILOperation.HLIL_FCMP_E:HighLevelILFcmpE, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_FCMP_NE:HighLevelILFcmpNe, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_FCMP_LT:HighLevelILFcmpLt, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_FCMP_LE:HighLevelILFcmpLe, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_FCMP_GE:HighLevelILFcmpGe, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_FCMP_GT:HighLevelILFcmpGt, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_FCMP_O:HighLevelILFcmpO, # ("left", "expr"), ("right", "expr"),
- HighLevelILOperation.HLIL_FCMP_UO:HighLevelILFcmpUo, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_NOP: HighLevelILNop, # ,
+ HighLevelILOperation.HLIL_BLOCK: HighLevelILBlock, # ("body", "expr_list"),
+ HighLevelILOperation.HLIL_IF: HighLevelILIf, # ("condition", "expr"), ("true", "expr"), ("false", "expr"),
+ HighLevelILOperation.HLIL_WHILE: HighLevelILWhile, # ("condition", "expr"), ("body", "expr"),
+ HighLevelILOperation.HLIL_WHILE_SSA:
+ HighLevelILWhileSsa, # ("condition_phi", "expr"), ("condition", "expr"), ("body", "expr"),
+ HighLevelILOperation.HLIL_DO_WHILE: HighLevelILDoWhile, # ("body", "expr"), ("condition", "expr"),
+ HighLevelILOperation.HLIL_DO_WHILE_SSA:
+ HighLevelILDoWhileSsa, # ("body", "expr"), ("condition_phi", "expr"), ("condition", "expr"),
+ HighLevelILOperation.HLIL_FOR:
+ HighLevelILFor, # ("init", "expr"), ("condition", "expr"), ("update", "expr"), ("body", "expr"),
+ HighLevelILOperation.HLIL_FOR_SSA:
+ HighLevelILForSsa, # ("init", "expr"), ("condition_phi", "expr"), ("condition", "expr"), ("update", "expr"), ("body", "expr"),
+ HighLevelILOperation.HLIL_SWITCH:
+ HighLevelILSwitch, # ("condition", "expr"), ("default", "expr"), ("cases", "expr_list"),
+ HighLevelILOperation.HLIL_CASE: HighLevelILCase, # ("values", "expr_list"), ("body", "expr"),
+ HighLevelILOperation.HLIL_BREAK: HighLevelILBreak, # ,
+ HighLevelILOperation.HLIL_CONTINUE: HighLevelILContinue, # ,
+ HighLevelILOperation.HLIL_JUMP: HighLevelILJump, # ("dest", "expr"),
+ HighLevelILOperation.HLIL_RET: HighLevelILRet, # ("src", "expr_list"),
+ HighLevelILOperation.HLIL_NORET: HighLevelILNoret, # ,
+ HighLevelILOperation.HLIL_GOTO: HighLevelILGoto, # ("target", "label"),
+ HighLevelILOperation.HLIL_LABEL: HighLevelILLabel, # ("target", "label"),
+ HighLevelILOperation.HLIL_VAR_DECLARE: HighLevelILVarDeclare, # ("var", "var"),
+ HighLevelILOperation.HLIL_VAR_INIT: HighLevelILVarInit, # ("dest", "var"), ("src", "expr"),
+ HighLevelILOperation.HLIL_VAR_INIT_SSA: HighLevelILVarInitSsa, # ("dest", "var_ssa"), ("src", "expr"),
+ HighLevelILOperation.HLIL_ASSIGN: HighLevelILAssign, # ("dest", "expr"), ("src", "expr"),
+ HighLevelILOperation.HLIL_ASSIGN_UNPACK: HighLevelILAssignUnpack, # ("dest", "expr_list"), ("src", "expr"),
+ HighLevelILOperation.HLIL_ASSIGN_MEM_SSA:
+ HighLevelILAssignMemSsa, # ("dest", "expr"), ("dest_memory", "int"), ("src", "expr"), ("src_memory", "int"),
+ HighLevelILOperation.HLIL_ASSIGN_UNPACK_MEM_SSA:
+ HighLevelILAssignUnpackMemSsa, # ("dest", "expr_list"), ("dest_memory", "int"), ("src", "expr"), ("src_memory", "int"),
+ HighLevelILOperation.HLIL_VAR: HighLevelILVar, # ("var", "var"),
+ HighLevelILOperation.HLIL_VAR_SSA: HighLevelILVarSsa, # ("var", "var_ssa"),
+ HighLevelILOperation.HLIL_VAR_PHI: HighLevelILVarPhi, # ("dest", "var_ssa"), ("src", "var_ssa_list"),
+ HighLevelILOperation.HLIL_MEM_PHI: HighLevelILMemPhi, # ("dest", "int"), ("src", "int_list"),
+ HighLevelILOperation.HLIL_ARRAY_INDEX: HighLevelILArrayIndex, # ("src", "expr"), ("index", "expr"),
+ HighLevelILOperation.HLIL_ARRAY_INDEX_SSA:
+ HighLevelILArrayIndexSsa, # ("src", "expr"), ("src_memory", "int"), ("index", "expr"),
+ HighLevelILOperation.HLIL_SPLIT: HighLevelILSplit, # ("high", "expr"), ("low", "expr"),
+ HighLevelILOperation.HLIL_DEREF: HighLevelILDeref, # ("src", "expr"),
+ HighLevelILOperation.HLIL_STRUCT_FIELD:
+ HighLevelILStructField, # ("src", "expr"), ("offset", "int"), ("member_index", "member_index"),
+ HighLevelILOperation.HLIL_DEREF_FIELD:
+ HighLevelILDerefField, # ("src", "expr"), ("offset", "int"), ("member_index", "member_index"),
+ HighLevelILOperation.HLIL_DEREF_SSA: HighLevelILDerefSsa, # ("src", "expr"), ("src_memory", "int"),
+ HighLevelILOperation.HLIL_DEREF_FIELD_SSA:
+ HighLevelILDerefFieldSsa, # ("src", "expr"), ("src_memory", "int"), ("offset", "int"), ("member_index", "member_index"),
+ HighLevelILOperation.HLIL_ADDRESS_OF: HighLevelILAddressOf, # ("src", "expr"),
+ HighLevelILOperation.HLIL_CONST: HighLevelILConst, # ("constant", "int"),
+ HighLevelILOperation.HLIL_CONST_PTR: HighLevelILConstPtr, # ("constant", "int"),
+ HighLevelILOperation.HLIL_EXTERN_PTR: HighLevelILExternPtr, # ("constant", "int"), ("offset", "int"),
+ HighLevelILOperation.HLIL_FLOAT_CONST: HighLevelILFloatConst, # ("constant", "float"),
+ HighLevelILOperation.HLIL_IMPORT: HighLevelILImport, # ("constant", "int"),
+ HighLevelILOperation.HLIL_ADD: HighLevelILAdd, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_ADC: HighLevelILAdc, # ("left", "expr"), ("right", "expr"), ("carry", "expr"),
+ HighLevelILOperation.HLIL_SUB: HighLevelILSub, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_SBB: HighLevelILSbb, # ("left", "expr"), ("right", "expr"), ("carry", "expr"),
+ HighLevelILOperation.HLIL_AND: HighLevelILAnd, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_OR: HighLevelILOr, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_XOR: HighLevelILXor, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_LSL: HighLevelILLsl, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_LSR: HighLevelILLsr, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_ASR: HighLevelILAsr, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_ROL: HighLevelILRol, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_RLC: HighLevelILRlc, # ("left", "expr"), ("right", "expr"), ("carry", "expr"),
+ HighLevelILOperation.HLIL_ROR: HighLevelILRor, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_RRC: HighLevelILRrc, # ("left", "expr"), ("right", "expr"), ("carry", "expr"),
+ HighLevelILOperation.HLIL_MUL: HighLevelILMul, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_MULU_DP: HighLevelILMuluDp, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_MULS_DP: HighLevelILMulsDp, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_DIVU: HighLevelILDivu, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_DIVU_DP: HighLevelILDivuDp, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_DIVS: HighLevelILDivs, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_DIVS_DP: HighLevelILDivsDp, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_MODU: HighLevelILModu, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_MODU_DP: HighLevelILModuDp, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_MODS: HighLevelILMods, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_MODS_DP: HighLevelILModsDp, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_NEG: HighLevelILNeg, # ("src", "expr"),
+ HighLevelILOperation.HLIL_NOT: HighLevelILNot, # ("src", "expr"),
+ HighLevelILOperation.HLIL_SX: HighLevelILSx, # ("src", "expr"),
+ HighLevelILOperation.HLIL_ZX: HighLevelILZx, # ("src", "expr"),
+ HighLevelILOperation.HLIL_LOW_PART: HighLevelILLowPart, # ("src", "expr"),
+ HighLevelILOperation.HLIL_CALL: HighLevelILCall, # ("dest", "expr"), ("params", "expr_list"),
+ HighLevelILOperation.HLIL_CALL_SSA:
+ HighLevelILCallSsa, # ("dest", "expr"), ("params", "expr_list"), ("dest_memory", "int"), ("src_memory", "int"),
+ HighLevelILOperation.HLIL_CMP_E: HighLevelILCmpE, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_CMP_NE: HighLevelILCmpNe, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_CMP_SLT: HighLevelILCmpSlt, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_CMP_ULT: HighLevelILCmpUlt, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_CMP_SLE: HighLevelILCmpSle, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_CMP_ULE: HighLevelILCmpUle, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_CMP_SGE: HighLevelILCmpSge, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_CMP_UGE: HighLevelILCmpUge, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_CMP_SGT: HighLevelILCmpSgt, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_CMP_UGT: HighLevelILCmpUgt, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_TEST_BIT: HighLevelILTestBit, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_BOOL_TO_INT: HighLevelILBoolToInt, # ("src", "expr"),
+ HighLevelILOperation.HLIL_ADD_OVERFLOW: HighLevelILAddOverflow, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_SYSCALL: HighLevelILSyscall, # ("params", "expr_list"),
+ HighLevelILOperation.HLIL_SYSCALL_SSA:
+ HighLevelILSyscallSsa, # ("params", "expr_list"), ("dest_memory", "int"), ("src_memory", "int"),
+ HighLevelILOperation.HLIL_TAILCALL: HighLevelILTailcall, # ("dest", "expr"), ("params", "expr_list"),
+ HighLevelILOperation.HLIL_BP: HighLevelILBp, # ,
+ HighLevelILOperation.HLIL_TRAP: HighLevelILTrap, # ("vector", "int"),
+ HighLevelILOperation.HLIL_INTRINSIC: HighLevelILIntrinsic, # ("intrinsic", "intrinsic"), ("params", "expr_list"),
+ HighLevelILOperation.HLIL_INTRINSIC_SSA:
+ HighLevelILIntrinsicSsa, # ("intrinsic", "intrinsic"), ("params", "expr_list"), ("dest_memory", "int"), ("src_memory", "int"),
+ HighLevelILOperation.HLIL_UNDEF: HighLevelILUndef, # ,
+ HighLevelILOperation.HLIL_UNIMPL: HighLevelILUnimpl, # ,
+ HighLevelILOperation.HLIL_UNIMPL_MEM: HighLevelILUnimplMem, # ("src", "expr"),
+ HighLevelILOperation.HLIL_FADD: HighLevelILFadd, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_FSUB: HighLevelILFsub, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_FMUL: HighLevelILFmul, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_FDIV: HighLevelILFdiv, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_FSQRT: HighLevelILFsqrt, # ("src", "expr"),
+ HighLevelILOperation.HLIL_FNEG: HighLevelILFneg, # ("src", "expr"),
+ HighLevelILOperation.HLIL_FABS: HighLevelILFabs, # ("src", "expr"),
+ HighLevelILOperation.HLIL_FLOAT_TO_INT: HighLevelILFloatToInt, # ("src", "expr"),
+ HighLevelILOperation.HLIL_INT_TO_FLOAT: HighLevelILIntToFloat, # ("src", "expr"),
+ HighLevelILOperation.HLIL_FLOAT_CONV: HighLevelILFloatConv, # ("src", "expr"),
+ HighLevelILOperation.HLIL_ROUND_TO_INT: HighLevelILRoundToInt, # ("src", "expr"),
+ HighLevelILOperation.HLIL_FLOOR: HighLevelILFloor, # ("src", "expr"),
+ HighLevelILOperation.HLIL_CEIL: HighLevelILCeil, # ("src", "expr"),
+ HighLevelILOperation.HLIL_FTRUNC: HighLevelILFtrunc, # ("src", "expr"),
+ HighLevelILOperation.HLIL_FCMP_E: HighLevelILFcmpE, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_FCMP_NE: HighLevelILFcmpNe, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_FCMP_LT: HighLevelILFcmpLt, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_FCMP_LE: HighLevelILFcmpLe, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_FCMP_GE: HighLevelILFcmpGe, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_FCMP_GT: HighLevelILFcmpGt, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_FCMP_O: HighLevelILFcmpO, # ("left", "expr"), ("right", "expr"),
+ HighLevelILOperation.HLIL_FCMP_UO: HighLevelILFcmpUo, # ("left", "expr"), ("right", "expr"),
}
+
class HighLevelILExpr:
"""
``class HighLevelILExpr`` hold the index of IL Expressions.
.. note:: Deprecated. Use ExpressionIndex instead
"""
- def __init__(self, index:ExpressionIndex):
+ def __init__(self, index: ExpressionIndex):
self._index = index
def __int__(self):
@@ -2064,15 +2068,17 @@ class HighLevelILFunction:
``class HighLevelILFunction`` contains the a HighLevelILInstruction object that makes up the abstract syntax tree of
a function.
"""
- def __init__(self, arch:Optional['architecture.Architecture']=None, handle:core.BNHighLevelILFunction=None,
- source_func:'function.Function'=None):
+ def __init__(
+ self, arch: Optional['architecture.Architecture'] = None, handle: core.BNHighLevelILFunction = None,
+ source_func: 'function.Function' = None
+ ):
self._arch = arch
self._source_function = source_func
if handle is not None:
HLILHandle = ctypes.POINTER(core.BNHighLevelILFunction)
_handle = ctypes.cast(handle, HLILHandle)
if self._source_function is None:
- self._source_function = function.Function(handle = core.BNGetHighLevelILOwnerFunction(_handle))
+ self._source_function = function.Function(handle=core.BNGetHighLevelILOwnerFunction(_handle))
if self._arch is None:
self._arch = self._source_function.arch
else:
@@ -2116,7 +2122,7 @@ class HighLevelILFunction:
def __len__(self):
return int(core.BNGetHighLevelILInstructionCount(self.handle))
- def __getitem__(self, i:Union[HighLevelILExpr, int]) -> HighLevelILInstruction:
+ def __getitem__(self, i: Union[HighLevelILExpr, int]) -> HighLevelILInstruction:
if isinstance(i, slice) or isinstance(i, tuple):
raise IndexError("expected integer instruction index")
if isinstance(i, HighLevelILExpr):
@@ -2125,8 +2131,9 @@ class HighLevelILFunction:
raise IndexError("index out of range")
if i < 0:
i = len(self) + i
- return HighLevelILInstruction.create(self, ExpressionIndex(core.BNGetHighLevelILIndexForInstruction(self.handle, i)), False,
- InstructionIndex(i))
+ return HighLevelILInstruction.create(
+ self, ExpressionIndex(core.BNGetHighLevelILIndexForInstruction(self.handle, i)), False, InstructionIndex(i)
+ )
def __setitem__(self, i, j):
raise IndexError("instruction modification not implemented")
@@ -2155,10 +2162,10 @@ class HighLevelILFunction:
return core.BNHighLevelILGetCurrentAddress(self.handle)
@current_address.setter
- def current_address(self, value:int) -> None:
+ def current_address(self, value: int) -> None:
core.BNHighLevelILSetCurrentAddress(self.handle, self.arch.handle, value)
- def set_current_address(self, value:int, arch:Optional['architecture.Architecture'] = None) -> None:
+ def set_current_address(self, value: int, arch: Optional['architecture.Architecture'] = None) -> None:
if arch is None:
arch = self.arch
core.BNHighLevelILSetCurrentAddress(self.handle, arch.handle, value)
@@ -2172,7 +2179,7 @@ class HighLevelILFunction:
return HighLevelILInstruction.create(self, ExpressionIndex(expr_index))
@root.setter
- def root(self, value:HighLevelILInstruction) -> None:
+ def root(self, value: HighLevelILInstruction) -> None:
core.BNSetHighLevelILRootExpr(self.handle, value.expr_index)
def _basic_block_list(self):
@@ -2224,7 +2231,7 @@ class HighLevelILFunction:
return self._source_function
@source_function.setter
- def source_function(self, value:'function.Function') -> None:
+ def source_function(self, value: 'function.Function') -> None:
self._source_function = value
@property
@@ -2240,26 +2247,26 @@ class HighLevelILFunction:
"""Alias for medium_level_il"""
return self.medium_level_il
- def get_ssa_instruction_index(self, instr:int) -> int:
+ def get_ssa_instruction_index(self, instr: int) -> int:
return core.BNGetHighLevelILSSAInstructionIndex(self.handle, instr)
- def get_non_ssa_instruction_index(self, instr:int) -> int:
+ def get_non_ssa_instruction_index(self, instr: int) -> int:
return core.BNGetHighLevelILNonSSAInstructionIndex(self.handle, instr)
- def get_ssa_var_definition(self, ssa_var:'mediumlevelil.SSAVariable') -> Optional[HighLevelILInstruction]:
+ def get_ssa_var_definition(self, ssa_var: 'mediumlevelil.SSAVariable') -> Optional[HighLevelILInstruction]:
var_data = ssa_var.var.to_BNVariable()
result = core.BNGetHighLevelILSSAVarDefinition(self.handle, var_data, ssa_var.version)
if result >= core.BNGetHighLevelILExprCount(self.handle):
return None
return HighLevelILInstruction.create(self, ExpressionIndex(result))
- def get_ssa_memory_definition(self, version:int) -> Optional[HighLevelILInstruction]:
+ def get_ssa_memory_definition(self, version: int) -> Optional[HighLevelILInstruction]:
result = core.BNGetHighLevelILSSAMemoryDefinition(self.handle, version)
if result >= core.BNGetHighLevelILExprCount(self.handle):
return None
return HighLevelILInstruction.create(self, ExpressionIndex(result))
- def get_ssa_var_uses(self, ssa_var:'mediumlevelil.SSAVariable') -> List[HighLevelILInstruction]:
+ def get_ssa_var_uses(self, ssa_var: 'mediumlevelil.SSAVariable') -> List[HighLevelILInstruction]:
count = ctypes.c_ulonglong()
var_data = ssa_var.var.to_BNVariable()
instrs = core.BNGetHighLevelILSSAVarUses(self.handle, var_data, ssa_var.version, count)
@@ -2270,7 +2277,7 @@ class HighLevelILFunction:
core.BNFreeILInstructionList(instrs)
return result
- def get_ssa_memory_uses(self, version:int) -> List[HighLevelILInstruction]:
+ def get_ssa_memory_uses(self, version: int) -> List[HighLevelILInstruction]:
count = ctypes.c_ulonglong()
instrs = core.BNGetHighLevelILSSAMemoryUses(self.handle, version, count)
assert instrs is not None, "core.BNGetHighLevelILSSAMemoryUses returned None"
@@ -2280,7 +2287,7 @@ class HighLevelILFunction:
core.BNFreeILInstructionList(instrs)
return result
- def is_ssa_var_live(self, ssa_var:'mediumlevelil.SSAVariable') -> bool:
+ def is_ssa_var_live(self, ssa_var: 'mediumlevelil.SSAVariable') -> bool:
"""
``is_ssa_var_live`` determines if ``ssa_var`` is live at any point in the function
@@ -2311,7 +2318,7 @@ class HighLevelILFunction:
var_data.storage = ssa_var.var.storage
return core.BNIsHighLevelILSSAVarLiveAt(self.handle, var_data, ssa_var.version, instr)
- def get_var_definitions(self, var:'variable.Variable') -> List[HighLevelILInstruction]:
+ def get_var_definitions(self, var: 'variable.Variable') -> List[HighLevelILInstruction]:
count = ctypes.c_ulonglong()
var_data = var.to_BNVariable()
instrs = core.BNGetHighLevelILVariableDefinitions(self.handle, var_data, count)
@@ -2322,7 +2329,7 @@ class HighLevelILFunction:
core.BNFreeILInstructionList(instrs)
return result
- def get_var_uses(self, var:'variable.Variable') -> List[HighLevelILInstruction]:
+ def get_var_uses(self, var: 'variable.Variable') -> List[HighLevelILInstruction]:
count = ctypes.c_ulonglong()
var_data = var.to_BNVariable()
instrs = core.BNGetHighLevelILVariableUses(self.handle, var_data, count)
@@ -2333,8 +2340,10 @@ class HighLevelILFunction:
core.BNFreeILInstructionList(instrs)
return result
- def expr(self, operation:Union[str, HighLevelILOperation], a:int = 0, b:int = 0, c:int = 0,
- d:int = 0, e:int = 0, size:int = 0) -> ExpressionIndex:
+ def expr(
+ self, operation: Union[str, HighLevelILOperation], a: int = 0, b: int = 0, c: int = 0, d: int = 0, e: int = 0,
+ size: int = 0
+ ) -> ExpressionIndex:
if isinstance(operation, str):
operation_value = HighLevelILOperation[operation]
else:
@@ -2342,7 +2351,7 @@ class HighLevelILFunction:
operation_value = operation.value
return ExpressionIndex(core.BNHighLevelILAddExpr(self.handle, operation_value, size, a, b, c, d, e))
- def add_operand_list(self, operands:List[int]) -> ExpressionIndex:
+ def add_operand_list(self, operands: List[int]) -> ExpressionIndex:
"""
``add_operand_list`` returns an operand list expression for the given list of integer operands.
@@ -2363,7 +2372,7 @@ class HighLevelILFunction:
"""
core.BNFinalizeHighLevelILFunction(self.handle)
- def create_graph(self, settings:'function.DisassemblySettings'=None) -> 'flowgraph.CoreFlowGraph':
+ def create_graph(self, settings: 'function.DisassemblySettings' = None) -> 'flowgraph.CoreFlowGraph':
if settings is not None:
settings_obj = settings.handle
else:
@@ -2382,14 +2391,20 @@ class HighLevelILFunction:
if self.source_function is None:
return []
- if self.il_form in [FunctionGraphType.HighLevelILFunctionGraph, FunctionGraphType.HighLevelILSSAFormFunctionGraph]:
+ if self.il_form in [
+ FunctionGraphType.HighLevelILFunctionGraph, FunctionGraphType.HighLevelILSSAFormFunctionGraph
+ ]:
count = ctypes.c_ulonglong()
core_variables = core.BNGetHighLevelILVariables(self.handle, count)
assert core_variables is not None, "core.BNGetHighLevelILVariables returned None"
try:
result = []
for var_i in range(count.value):
- result.append(variable.Variable(self, core_variables[var_i].type, core_variables[var_i].index, core_variables[var_i].storage))
+ result.append(
+ variable.Variable(
+ self, core_variables[var_i].type, core_variables[var_i].index, core_variables[var_i].storage
+ )
+ )
return result
finally:
core.BNFreeVariableList(core_variables)
@@ -2401,14 +2416,20 @@ class HighLevelILFunction:
if self.source_function is None:
return []
- if self.il_form in [FunctionGraphType.HighLevelILFunctionGraph, FunctionGraphType.HighLevelILSSAFormFunctionGraph]:
+ if self.il_form in [
+ FunctionGraphType.HighLevelILFunctionGraph, FunctionGraphType.HighLevelILSSAFormFunctionGraph
+ ]:
count = ctypes.c_ulonglong()
core_variables = core.BNGetHighLevelILAliasedVariables(self.handle, count)
assert core_variables is not None, "core.BNGetHighLevelILAliasedVariables returned None"
try:
result = []
for var_i in range(count.value):
- result.append(variable.Variable(self, core_variables[var_i].type, core_variables[var_i].index, core_variables[var_i].storage))
+ result.append(
+ variable.Variable(
+ self, core_variables[var_i].type, core_variables[var_i].index, core_variables[var_i].storage
+ )
+ )
return result
finally:
core.BNFreeVariableList(core_variables)
@@ -2428,11 +2449,20 @@ class HighLevelILFunction:
result = []
for var_i in range(variable_count.value):
version_count = ctypes.c_ulonglong()
- versions = core.BNGetHighLevelILVariableSSAVersions(self.handle, core_variables[var_i], version_count)
+ versions = core.BNGetHighLevelILVariableSSAVersions(
+ self.handle, core_variables[var_i], version_count
+ )
assert versions is not None, "core.BNGetHighLevelILVariableSSAVersions returned None"
try:
for version_i in range(version_count.value):
- result.append(mediumlevelil.SSAVariable(variable.Variable(self, core_variables[var_i].type, core_variables[var_i].index, core_variables[var_i].storage), versions[version_i]))
+ result.append(
+ mediumlevelil.SSAVariable(
+ variable.Variable(
+ self, core_variables[var_i].type, core_variables[var_i].index,
+ core_variables[var_i].storage
+ ), versions[version_i]
+ )
+ )
finally:
core.BNFreeILInstructionList(versions)
return result
@@ -2443,7 +2473,7 @@ class HighLevelILFunction:
return []
- def get_medium_level_il_expr_index(self, expr:ExpressionIndex) -> Optional['mediumlevelil.ExpressionIndex']:
+ def get_medium_level_il_expr_index(self, expr: ExpressionIndex) -> Optional['mediumlevelil.ExpressionIndex']:
medium_il = self.medium_level_il
if medium_il is None:
return None
@@ -2455,7 +2485,7 @@ class HighLevelILFunction:
return None
return mediumlevelil.ExpressionIndex(result)
- def get_medium_level_il_expr_indexes(self, expr:ExpressionIndex) -> List['mediumlevelil.ExpressionIndex']:
+ def get_medium_level_il_expr_indexes(self, expr: ExpressionIndex) -> List['mediumlevelil.ExpressionIndex']:
count = ctypes.c_ulonglong()
exprs = core.BNGetMediumLevelILExprIndexesFromHighLevelIL(self.handle, expr, count)
assert exprs is not None, "core.BNGetMediumLevelILExprIndexesFromHighLevelIL returned None"
@@ -2465,13 +2495,13 @@ class HighLevelILFunction:
core.BNFreeILInstructionList(exprs)
return result
- def get_label(self, label_idx:int) -> Optional[HighLevelILInstruction]:
+ def get_label(self, label_idx: int) -> Optional[HighLevelILInstruction]:
result = core.BNGetHighLevelILExprIndexForLabel(self.handle, label_idx)
if result >= core.BNGetHighLevelILExprCount(self.handle):
return None
return HighLevelILInstruction.create(self, ExpressionIndex(result))
- def get_label_uses(self, label_idx:int) -> List[HighLevelILInstruction]:
+ def get_label_uses(self, label_idx: int) -> List[HighLevelILInstruction]:
count = ctypes.c_ulonglong()
uses = core.BNGetHighLevelILUsesForLabel(self.handle, label_idx, count)
assert uses is not None, "core.BNGetHighLevelILUsesForLabel returned None"
@@ -2483,7 +2513,9 @@ class HighLevelILFunction:
class HighLevelILBasicBlock(basicblock.BasicBlock):
- def __init__(self, handle:core.BNBasicBlockHandle, owner:HighLevelILFunction, view:Optional['binaryview.BinaryView']):
+ def __init__(
+ self, handle: core.BNBasicBlockHandle, owner: HighLevelILFunction, view: Optional['binaryview.BinaryView']
+ ):
super(HighLevelILBasicBlock, self).__init__(handle, view)
self._il_function = owner
@@ -2502,7 +2534,7 @@ class HighLevelILBasicBlock(basicblock.BasicBlock):
else:
return self.il_function[self.end + idx]
- def _create_instance(self, handle:core.BNBasicBlockHandle, view:'binaryview.BinaryView'):
+ def _create_instance(self, handle: core.BNBasicBlockHandle, view: 'binaryview.BinaryView'):
"""Internal method by super to instantiate child instances"""
return HighLevelILBasicBlock(handle, self.il_function, view)
diff --git a/python/highlight.py b/python/highlight.py
index b1666f54..a224ef30 100644
--- a/python/highlight.py
+++ b/python/highlight.py
@@ -18,14 +18,13 @@
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
-
# Binary Ninja components
from . import _binaryninjacore as core
from .enums import HighlightColorStyle, HighlightStandardColor
class HighlightColor:
- def __init__(self, color = None, mix_color = None, mix = None, red = None, green = None, blue = None, alpha = 255):
+ def __init__(self, color=None, mix_color=None, mix=None, red=None, green=None, blue=None, alpha=255):
if (red is not None) and (green is not None) and (blue is not None):
self._style = HighlightColorStyle.CustomHighlightColor
self._red = red
@@ -141,10 +140,13 @@ class HighlightColor:
return "<color: %s, alpha %d>" % (self._standard_color_to_str(self.color), self.alpha)
if self.style == HighlightColorStyle.MixedHighlightColor:
if self.alpha == 255:
- return "<color: mix %s to %s factor %d>" % (self._standard_color_to_str(self.color),
- self._standard_color_to_str(self.mix_color), self.mix)
- return "<color: mix %s to %s factor %d, alpha %d>" % (self._standard_color_to_str(self.color),
- self._standard_color_to_str(self.mix_color), self.mix, self.alpha)
+ return "<color: mix %s to %s factor %d>" % (
+ self._standard_color_to_str(self.color), self._standard_color_to_str(self.mix_color), self.mix
+ )
+ return "<color: mix %s to %s factor %d, alpha %d>" % (
+ self._standard_color_to_str(self.color), self._standard_color_to_str(self.mix_color
+ ), self.mix, self.alpha
+ )
if self.style == HighlightColorStyle.CustomHighlightColor:
if self.alpha == 255:
return "<color: #%.2x%.2x%.2x>" % (self.red, self.green, self.blue)
@@ -184,4 +186,3 @@ class HighlightColor:
elif color.style == HighlightColorStyle.CustomHighlightColor:
return HighlightColor(red=color.r, green=color.g, blue=color.b, alpha=color.alpha)
return HighlightColor(color=HighlightStandardColor.NoHighlightColor)
-
diff --git a/python/interaction.py b/python/interaction.py
index 7389f023..978de6b2 100644
--- a/python/interaction.py
+++ b/python/interaction.py
@@ -35,7 +35,7 @@ class LabelField:
"""
``LabelField`` adds a text label to the display.
"""
- def __init__(self, text:str):
+ def __init__(self, text: str):
self._text = text
def _fill_core_struct(self, value):
@@ -54,7 +54,7 @@ class LabelField:
return self._text
@text.setter
- def text(self, value:str) -> None:
+ def text(self, value: str) -> None:
self._text = value
@@ -501,7 +501,7 @@ class InteractionHandler:
def _show_plain_text_report(self, ctxt, view, title, contents):
try:
if view:
- view = binaryview.BinaryView(handle = core.BNNewViewReference(view))
+ view = binaryview.BinaryView(handle=core.BNNewViewReference(view))
else:
view = None
self.show_plain_text_report(view, title, contents)
@@ -511,7 +511,7 @@ class InteractionHandler:
def _show_markdown_report(self, ctxt, view, title, contents, plaintext):
try:
if view:
- view = binaryview.BinaryView(handle = core.BNNewViewReference(view))
+ view = binaryview.BinaryView(handle=core.BNNewViewReference(view))
else:
view = None
self.show_markdown_report(view, title, contents, plaintext)
@@ -521,7 +521,7 @@ class InteractionHandler:
def _show_html_report(self, ctxt, view, title, contents, plaintext):
try:
if view:
- view = binaryview.BinaryView(handle = core.BNNewViewReference(view))
+ view = binaryview.BinaryView(handle=core.BNNewViewReference(view))
else:
view = None
self.show_html_report(view, title, contents, plaintext)
@@ -531,7 +531,7 @@ class InteractionHandler:
def _show_graph_report(self, ctxt, view, title, graph):
try:
if view:
- view = binaryview.BinaryView(handle = core.BNNewViewReference(view))
+ view = binaryview.BinaryView(handle=core.BNNewViewReference(view))
else:
view = None
self.show_graph_report(view, title, flowgraph.CoreFlowGraph(core.BNNewFlowGraphReference(graph)))
@@ -567,7 +567,7 @@ class InteractionHandler:
def _get_address_input(self, ctxt, result, prompt, title, view, current_address):
try:
if view:
- view = binaryview.BinaryView(handle = core.BNNewViewReference(view))
+ view = binaryview.BinaryView(handle=core.BNNewViewReference(view))
else:
view = None
value = self.get_address_input(prompt, title, view, current_address)
@@ -630,27 +630,61 @@ class InteractionHandler:
elif fields[i].type == FormInputFieldType.SeparatorFormField:
field_objs.append(SeparatorField())
elif fields[i].type == FormInputFieldType.TextLineFormField:
- field_objs.append(TextLineField(fields[i].prompt, default=fields[i].stringDefault if fields[i].hasDefault else None))
+ field_objs.append(
+ TextLineField(
+ fields[i].prompt, default=fields[i].stringDefault if fields[i].hasDefault else None
+ )
+ )
elif fields[i].type == FormInputFieldType.MultilineTextFormField:
- field_objs.append(MultilineTextField(fields[i].prompt, default=fields[i].stringDefault if fields[i].hasDefault else None))
+ field_objs.append(
+ MultilineTextField(
+ fields[i].prompt, default=fields[i].stringDefault if fields[i].hasDefault else None
+ )
+ )
elif fields[i].type == FormInputFieldType.IntegerFormField:
- field_objs.append(IntegerField(fields[i].prompt, default=fields[i].intDefault if fields[i].hasDefault else None))
+ field_objs.append(
+ IntegerField(fields[i].prompt, default=fields[i].intDefault if fields[i].hasDefault else None)
+ )
elif fields[i].type == FormInputFieldType.AddressFormField:
view = None
if fields[i].view:
- view = binaryview.BinaryView(handle = core.BNNewViewReference(fields[i].view))
- field_objs.append(AddressField(fields[i].prompt, view, fields[i].currentAddress, default=fields[i].addressDefault if fields[i].hasDefault else None))
+ view = binaryview.BinaryView(handle=core.BNNewViewReference(fields[i].view))
+ field_objs.append(
+ AddressField(
+ fields[i].prompt, view, fields[i].currentAddress,
+ default=fields[i].addressDefault if fields[i].hasDefault else None
+ )
+ )
elif fields[i].type == FormInputFieldType.ChoiceFormField:
choices = []
for j in range(0, fields[i].count):
choices.append(fields[i].choices[j])
- field_objs.append(ChoiceField(fields[i].prompt, choices, default=fields[i].choiceDefault if fields[i].hasDefault else None))
+ field_objs.append(
+ ChoiceField(
+ fields[i].prompt, choices, default=fields[i].choiceDefault if fields[i].hasDefault else None
+ )
+ )
elif fields[i].type == FormInputFieldType.OpenFileNameFormField:
- field_objs.append(OpenFileNameField(fields[i].prompt, fields[i].ext, default=fields[i].stringDefault if fields[i].hasDefault else None))
+ field_objs.append(
+ OpenFileNameField(
+ fields[i].prompt, fields[i].ext,
+ default=fields[i].stringDefault if fields[i].hasDefault else None
+ )
+ )
elif fields[i].type == FormInputFieldType.SaveFileNameFormField:
- field_objs.append(SaveFileNameField(fields[i].prompt, fields[i].ext, fields[i].defaultName, default=fields[i].stringDefault if fields[i].hasDefault else None))
+ field_objs.append(
+ SaveFileNameField(
+ fields[i].prompt, fields[i].ext, fields[i].defaultName,
+ default=fields[i].stringDefault if fields[i].hasDefault else None
+ )
+ )
elif fields[i].type == FormInputFieldType.DirectoryNameFormField:
- field_objs.append(DirectoryNameField(fields[i].prompt, fields[i].defaultName, default=fields[i].stringDefault if fields[i].hasDefault else None))
+ field_objs.append(
+ DirectoryNameField(
+ fields[i].prompt, fields[i].defaultName,
+ default=fields[i].stringDefault if fields[i].hasDefault else None
+ )
+ )
else:
field_objs.append(LabelField(fields[i].prompt))
if not self.get_form_input(field_objs, title):
@@ -730,7 +764,7 @@ class InteractionHandler:
class PlainTextReport:
- def __init__(self, title, contents, view = None):
+ def __init__(self, title, contents, view=None):
self._view = view
self._title = title
self._contents = contents
@@ -767,7 +801,7 @@ class PlainTextReport:
class MarkdownReport:
- def __init__(self, title, contents, plaintext = "", view = None):
+ def __init__(self, title, contents, plaintext="", view=None):
self._view = view
self._title = title
self._contents = contents
@@ -813,7 +847,7 @@ class MarkdownReport:
class HTMLReport:
- def __init__(self, title, contents, plaintext = "", view = None):
+ def __init__(self, title, contents, plaintext="", view=None):
self._view = view
self._title = title
self._contents = contents
@@ -859,7 +893,7 @@ class HTMLReport:
class FlowGraphReport:
- def __init__(self, title, graph, view = None):
+ def __init__(self, title, graph, view=None):
self._view = view
self._title = title
self._graph = graph
@@ -893,7 +927,7 @@ class FlowGraphReport:
class ReportCollection:
- def __init__(self, handle = None):
+ def __init__(self, handle=None):
if handle is None:
self.handle = core.BNCreateReportCollection()
else:
@@ -907,7 +941,7 @@ class ReportCollection:
title = core.BNGetReportTitle(self.handle, i)
view = core.BNGetReportView(self.handle, i)
if view:
- view = binaryview.BinaryView(handle = view)
+ view = binaryview.BinaryView(handle=view)
else:
view = None
if report_type == ReportType.PlainTextReportType:
@@ -1163,7 +1197,7 @@ def get_choice_input(prompt, title, choices):
return value.value
-def get_open_filename_input(prompt:str, ext:str="") -> Optional[str]:
+def get_open_filename_input(prompt: str, ext: str = "") -> Optional[str]:
"""
``get_open_filename_input`` prompts the user for a file name to open
@@ -1191,7 +1225,7 @@ def get_open_filename_input(prompt:str, ext:str="") -> Optional[str]:
return result.decode("utf-8")
-def get_save_filename_input(prompt:str, ext:str="", default_name:str="") -> Optional[str]:
+def get_save_filename_input(prompt: str, ext: str = "", default_name: str = "") -> Optional[str]:
"""
``get_save_filename_input`` prompts the user for a file name to save as, optionally providing a file extension and \
default_name
@@ -1216,7 +1250,7 @@ def get_save_filename_input(prompt:str, ext:str="", default_name:str="") -> Opti
return result.decode("utf-8")
-def get_directory_name_input(prompt:str, default_name:str=""):
+def get_directory_name_input(prompt: str, default_name: str = ""):
"""
``get_directory_name_input`` prompts the user for a directory name to save as, optionally providing a default_name
diff --git a/python/lineardisassembly.py b/python/lineardisassembly.py
index f87e8b33..ddc8fd5d 100644
--- a/python/lineardisassembly.py
+++ b/python/lineardisassembly.py
@@ -45,7 +45,7 @@ class LinearDisassemblyLine:
class LinearViewObjectIdentifier:
- def __init__(self, name, start = None, end = None):
+ def __init__(self, name, start=None, end=None):
self._name = name
self._start = start
self._end = end
@@ -73,7 +73,7 @@ class LinearViewObjectIdentifier:
def __hash__(self):
return hash((self._name, self._start, self._end))
- def _to_core_struct(self, obj = None):
+ def _to_core_struct(self, obj=None):
if obj is None:
result = core.BNLinearViewObjectIdentifier()
else:
@@ -129,7 +129,7 @@ class LinearViewObjectIdentifier:
class LinearViewObject:
- def __init__(self, handle, parent = None):
+ def __init__(self, handle, parent=None):
self.handle = handle
self._parent = parent
@@ -246,174 +246,223 @@ class LinearViewObject:
next_obj = next_obj.handle
count = ctypes.c_ulonglong(0)
- return LinearViewCursor._make_lines(core.BNGetLinearViewObjectLines(self.handle, prev_obj, next_obj, count), count.value)
+ return LinearViewCursor._make_lines(
+ core.BNGetLinearViewObjectLines(self.handle, prev_obj, next_obj, count), count.value
+ )
def ordering_index_for_child(self, child):
return core.BNGetLinearViewObjectOrderingIndexForChild(self.handle, child.handle)
@staticmethod
- def disassembly(view:'binaryview.BinaryView', settings:Optional['_function.DisassemblySettings'] = None) -> 'LinearViewObject':
+ def disassembly(
+ view: 'binaryview.BinaryView', settings: Optional['_function.DisassemblySettings'] = None
+ ) -> 'LinearViewObject':
_settings = settings
if _settings is not None:
_settings = _settings.handle
return LinearViewObject(core.BNCreateLinearViewDisassembly(view.handle, _settings))
@staticmethod
- def lifted_il(view:'binaryview.BinaryView', settings:Optional['_function.DisassemblySettings'] = None) -> 'LinearViewObject':
+ def lifted_il(
+ view: 'binaryview.BinaryView', settings: Optional['_function.DisassemblySettings'] = None
+ ) -> 'LinearViewObject':
_settings = settings
if _settings is not None:
_settings = _settings.handle
return LinearViewObject(core.BNCreateLinearViewLiftedIL(view.handle, _settings))
@staticmethod
- def llil(view:'binaryview.BinaryView', settings:Optional['_function.DisassemblySettings'] = None) -> 'LinearViewObject':
+ def llil(
+ view: 'binaryview.BinaryView', settings: Optional['_function.DisassemblySettings'] = None
+ ) -> 'LinearViewObject':
_settings = settings
if _settings is not None:
_settings = _settings.handle
return LinearViewObject(core.BNCreateLinearViewLowLevelIL(view.handle, _settings))
@staticmethod
- def llil_ssa_form(view:'binaryview.BinaryView', settings:Optional['_function.DisassemblySettings'] = None) -> 'LinearViewObject':
+ def llil_ssa_form(
+ view: 'binaryview.BinaryView', settings: Optional['_function.DisassemblySettings'] = None
+ ) -> 'LinearViewObject':
_settings = settings
if _settings is not None:
_settings = _settings.handle
return LinearViewObject(core.BNCreateLinearViewLowLevelILSSAForm(view.handle, _settings))
@staticmethod
- def mlil(view:'binaryview.BinaryView', settings:Optional['_function.DisassemblySettings'] = None) -> 'LinearViewObject':
+ def mlil(
+ view: 'binaryview.BinaryView', settings: Optional['_function.DisassemblySettings'] = None
+ ) -> 'LinearViewObject':
_settings = settings
if _settings is not None:
_settings = _settings.handle
return LinearViewObject(core.BNCreateLinearViewMediumLevelIL(view.handle, _settings))
@staticmethod
- def mlil_ssa_form(view:'binaryview.BinaryView', settings:Optional['_function.DisassemblySettings'] = None) -> 'LinearViewObject':
+ def mlil_ssa_form(
+ view: 'binaryview.BinaryView', settings: Optional['_function.DisassemblySettings'] = None
+ ) -> 'LinearViewObject':
_settings = settings
if _settings is not None:
_settings = _settings.handle
return LinearViewObject(core.BNCreateLinearViewMediumLevelILSSAForm(view.handle, _settings))
@staticmethod
- def mmlil(view:'binaryview.BinaryView', settings:Optional['_function.DisassemblySettings'] = None) -> 'LinearViewObject':
+ def mmlil(
+ view: 'binaryview.BinaryView', settings: Optional['_function.DisassemblySettings'] = None
+ ) -> 'LinearViewObject':
_settings = settings
if _settings is not None:
_settings = _settings.handle
return LinearViewObject(core.BNCreateLinearViewMappedMediumLevelIL(view.handle, _settings))
@staticmethod
- def mmlil_ssa_form(view:'binaryview.BinaryView', settings:Optional['_function.DisassemblySettings'] = None) -> 'LinearViewObject':
+ def mmlil_ssa_form(
+ view: 'binaryview.BinaryView', settings: Optional['_function.DisassemblySettings'] = None
+ ) -> 'LinearViewObject':
_settings = settings
if _settings is not None:
_settings = _settings.handle
return LinearViewObject(core.BNCreateLinearViewMappedMediumLevelILSSAForm(view.handle, _settings))
@staticmethod
- def hlil(view:'binaryview.BinaryView', settings:Optional['_function.DisassemblySettings'] = None) -> 'LinearViewObject':
+ def hlil(
+ view: 'binaryview.BinaryView', settings: Optional['_function.DisassemblySettings'] = None
+ ) -> 'LinearViewObject':
_settings = settings
if _settings is not None:
_settings = _settings.handle
return LinearViewObject(core.BNCreateLinearViewHighLevelIL(view.handle, _settings))
@staticmethod
- def hlil_ssa_form(view:'binaryview.BinaryView', settings:Optional['_function.DisassemblySettings'] = None) -> 'LinearViewObject':
+ def hlil_ssa_form(
+ view: 'binaryview.BinaryView', settings: Optional['_function.DisassemblySettings'] = None
+ ) -> 'LinearViewObject':
_settings = settings
if _settings is not None:
_settings = _settings.handle
return LinearViewObject(core.BNCreateLinearViewHighLevelILSSAForm(view.handle, _settings))
@staticmethod
- def language_representation(view:'binaryview.BinaryView', settings:Optional['_function.DisassemblySettings'] = None) -> 'LinearViewObject':
+ def language_representation(
+ view: 'binaryview.BinaryView', settings: Optional['_function.DisassemblySettings'] = None
+ ) -> 'LinearViewObject':
_settings = settings
if _settings is not None:
_settings = _settings.handle
return LinearViewObject(core.BNCreateLinearViewLanguageRepresentation(view.handle, _settings))
@staticmethod
- def data_only(view:'binaryview.BinaryView', settings:Optional['_function.DisassemblySettings'] = None) -> 'LinearViewObject':
+ def data_only(
+ view: 'binaryview.BinaryView', settings: Optional['_function.DisassemblySettings'] = None
+ ) -> 'LinearViewObject':
_settings = settings
if _settings is not None:
_settings = _settings.handle
return LinearViewObject(core.BNCreateLinearViewDataOnly(view.handle, _settings))
@staticmethod
- def single_function_disassembly(func:'_function.Function', settings:Optional['_function.DisassemblySettings'] = None) -> 'LinearViewObject':
+ def single_function_disassembly(
+ func: '_function.Function', settings: Optional['_function.DisassemblySettings'] = None
+ ) -> 'LinearViewObject':
_settings = settings
if _settings is not None:
_settings = _settings.handle
return LinearViewObject(core.BNCreateLinearViewSingleFunctionDisassembly(func.handle, _settings))
@staticmethod
- def single_function_lifted_il(func:'_function.Function', settings:Optional['_function.DisassemblySettings'] = None) -> 'LinearViewObject':
+ def single_function_lifted_il(
+ func: '_function.Function', settings: Optional['_function.DisassemblySettings'] = None
+ ) -> 'LinearViewObject':
_settings = settings
if _settings is not None:
_settings = _settings.handle
return LinearViewObject(core.BNCreateLinearViewSingleFunctionLiftedIL(func.handle, _settings))
@staticmethod
- def single_function_llil(func:'_function.Function', settings:Optional['_function.DisassemblySettings'] = None) -> 'LinearViewObject':
+ def single_function_llil(
+ func: '_function.Function', settings: Optional['_function.DisassemblySettings'] = None
+ ) -> 'LinearViewObject':
_settings = settings
if _settings is not None:
_settings = _settings.handle
return LinearViewObject(core.BNCreateLinearViewSingleFunctionLowLevelIL(func.handle, _settings))
@staticmethod
- def single_function_llil_ssa_form(func:'_function.Function', settings:Optional['_function.DisassemblySettings'] = None) -> 'LinearViewObject':
+ def single_function_llil_ssa_form(
+ func: '_function.Function', settings: Optional['_function.DisassemblySettings'] = None
+ ) -> 'LinearViewObject':
_settings = settings
if _settings is not None:
_settings = _settings.handle
return LinearViewObject(core.BNCreateLinearViewSingleFunctionLowLevelILSSAForm(func.handle, _settings))
@staticmethod
- def single_function_mlil(func:'_function.Function', settings:Optional['_function.DisassemblySettings'] = None) -> 'LinearViewObject':
+ def single_function_mlil(
+ func: '_function.Function', settings: Optional['_function.DisassemblySettings'] = None
+ ) -> 'LinearViewObject':
_settings = settings
if _settings is not None:
_settings = _settings.handle
return LinearViewObject(core.BNCreateLinearViewSingleFunctionMediumLevelIL(func.handle, _settings))
@staticmethod
- def single_function_mlil_ssa_form(func:'_function.Function', settings:Optional['_function.DisassemblySettings'] = None) -> 'LinearViewObject':
+ def single_function_mlil_ssa_form(
+ func: '_function.Function', settings: Optional['_function.DisassemblySettings'] = None
+ ) -> 'LinearViewObject':
_settings = settings
if _settings is not None:
_settings = _settings.handle
return LinearViewObject(core.BNCreateLinearViewSingleFunctionMediumLevelILSSAForm(func.handle, _settings))
@staticmethod
- def single_function_mmlil(func:'_function.Function', settings:Optional['_function.DisassemblySettings'] = None) -> 'LinearViewObject':
+ def single_function_mmlil(
+ func: '_function.Function', settings: Optional['_function.DisassemblySettings'] = None
+ ) -> 'LinearViewObject':
_settings = settings
if _settings is not None:
_settings = _settings.handle
return LinearViewObject(core.BNCreateLinearViewSingleFunctionMappedMediumLevelIL(func.handle, _settings))
@staticmethod
- def single_function_mmlil_ssa_form(func:'_function.Function', settings:Optional['_function.DisassemblySettings'] = None) -> 'LinearViewObject':
+ def single_function_mmlil_ssa_form(
+ func: '_function.Function', settings: Optional['_function.DisassemblySettings'] = None
+ ) -> 'LinearViewObject':
_settings = settings
if _settings is not None:
_settings = _settings.handle
return LinearViewObject(core.BNCreateLinearViewSingleFunctionMappedMediumLevelILSSAForm(func.handle, _settings))
@staticmethod
- def single_function_hlil(func:'_function.Function', settings:Optional['_function.DisassemblySettings'] = None) -> 'LinearViewObject':
+ def single_function_hlil(
+ func: '_function.Function', settings: Optional['_function.DisassemblySettings'] = None
+ ) -> 'LinearViewObject':
_settings = settings
if _settings is not None:
_settings = _settings.handle
return LinearViewObject(core.BNCreateLinearViewSingleFunctionHighLevelIL(func.handle, _settings))
@staticmethod
- def single_function_hlil_ssa_form(func:'_function.Function', settings:Optional['_function.DisassemblySettings'] = None) -> 'LinearViewObject':
+ def single_function_hlil_ssa_form(
+ func: '_function.Function', settings: Optional['_function.DisassemblySettings'] = None
+ ) -> 'LinearViewObject':
_settings = settings
if _settings is not None:
_settings = _settings.handle
return LinearViewObject(core.BNCreateLinearViewSingleFunctionHighLevelILSSAForm(func.handle, _settings))
@staticmethod
- def single_function_language_representation(view:'binaryview.BinaryView', settings:Optional['_function.DisassemblySettings'] = None) -> 'LinearViewObject':
+ def single_function_language_representation(
+ view: 'binaryview.BinaryView', settings: Optional['_function.DisassemblySettings'] = None
+ ) -> 'LinearViewObject':
_settings = settings
if _settings is not None:
_settings = _settings.handle
return LinearViewObject(core.BNCreateLinearViewSingleFunctionLanguageRepresentation(view.handle, _settings))
+
class LinearViewCursor:
- def __init__(self, root_object, handle = None):
+ def __init__(self, root_object, handle=None):
if handle is not None:
self.handle = handle
else:
@@ -529,7 +578,7 @@ class LinearViewCursor:
def seek_to_address(self, addr):
core.BNSeekLinearViewCursorToAddress(self.handle, addr)
- def seek_to_path(self, path, addr = None):
+ def seek_to_path(self, path, addr=None):
if isinstance(path, LinearViewCursor):
if addr is None:
return core.BNSeekLinearViewCursorToCursorPath(self.handle, path.handle)
@@ -551,7 +600,7 @@ class LinearViewCursor:
return core.BNLinearViewCursorNext(self.handle)
@staticmethod
- def _make_lines(lines, count:int) -> List['LinearDisassemblyLine']:
+ def _make_lines(lines, count: int) -> List['LinearDisassemblyLine']:
assert lines is not None, "core returned None for LinearDisassembly lines"
try:
result = []
@@ -566,8 +615,10 @@ class LinearViewCursor:
block = basicblock.BasicBlock(core_block, None)
color = highlight.HighlightColor._from_core_struct(lines[i].contents.highlight)
addr = lines[i].contents.addr
- tokens = _function.InstructionTextToken._from_core_struct(lines[i].contents.tokens, lines[i].contents.count)
- contents = _function.DisassemblyTextLine(tokens, addr, color = color)
+ tokens = _function.InstructionTextToken._from_core_struct(
+ lines[i].contents.tokens, lines[i].contents.count
+ )
+ contents = _function.DisassemblyTextLine(tokens, addr, color=color)
result.append(LinearDisassemblyLine(lines[i].type, func, block, contents))
return result
finally:
@@ -579,7 +630,7 @@ class LinearViewCursor:
return LinearViewCursor._make_lines(core.BNGetLinearViewCursorLines(self.handle, count), count.value)
def duplicate(self):
- return LinearViewCursor(None, handle = core.BNDuplicateLinearViewCursor(self.handle))
+ return LinearViewCursor(None, handle=core.BNDuplicateLinearViewCursor(self.handle))
@staticmethod
def compare(a, b):
diff --git a/python/log.py b/python/log.py
index 21e3bae2..04d8693a 100644
--- a/python/log.py
+++ b/python/log.py
@@ -18,12 +18,10 @@
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
-
# Binary Ninja components
from . import _binaryninjacore as core
from .enums import LogLevel
-
_output_to_log = False
@@ -163,7 +161,7 @@ def log_to_stderr(min_level):
core.BNLogToStderr(min_level)
-def log_to_file(min_level, path, append = False):
+def log_to_file(min_level, path, append=False):
"""
``log_to_file`` redirects minimum log level to a file named ``path``, optionally appending rather than overwriting.
diff --git a/python/lowlevelil.py b/python/lowlevelil.py
index 87eb5a34..2849c2bf 100644
--- a/python/lowlevelil.py
+++ b/python/lowlevelil.py
@@ -26,7 +26,7 @@ from dataclasses import dataclass
# Binary Ninja components
from .enums import LowLevelILOperation, LowLevelILFlagCondition, DataFlowQueryOption, FunctionGraphType
from . import _binaryninjacore as core
-from . import basicblock #required for LowLevelILBasicBlock
+from . import basicblock #required for LowLevelILBasicBlock
from . import function
from . import mediumlevelil
from . import highlevelil
@@ -36,9 +36,11 @@ from . import binaryview
from . import architecture
from . import types
from .interaction import show_graph_report
-from .commonil import (BaseILInstruction, Constant, BinaryOperation, Tailcall, UnaryOperation, Comparison, SSA,
- Phi, FloatingPoint, ControlFlow, Terminal, Syscall, Localcall, StackOperation, Return,
- Signed, Arithmetic, Carry, DoublePrecision, Memory, Load, Store, RegisterStack, SetReg)
+from .commonil import (
+ BaseILInstruction, Constant, BinaryOperation, Tailcall, UnaryOperation, Comparison, SSA, Phi, FloatingPoint,
+ ControlFlow, Terminal, Syscall, Localcall, StackOperation, Return, Signed, Arithmetic, Carry, DoublePrecision,
+ Memory, Load, Store, RegisterStack, SetReg
+)
ExpressionIndex = NewType('ExpressionIndex', int)
InstructionIndex = NewType('InstructionIndex', int)
@@ -48,45 +50,27 @@ InstructionOrExpression = Union['LowLevelILInstruction', Index]
ILRegisterType = Union[str, 'ILRegister', int]
LLILInstructionsType = Generator['LowLevelILInstruction', None, None]
OperandsType = Tuple[ExpressionIndex, ExpressionIndex, ExpressionIndex, ExpressionIndex]
-LowLevelILOperandType = Union[
- 'LowLevelILOperationAndSize',
- 'ILRegister',
- 'ILFlag',
- 'ILIntrinsic',
- 'ILRegisterStack',
- int,
- Dict[int, int],
- float,
- 'LowLevelILInstruction',
- Dict['architecture.RegisterStackName', int],
- 'SSAFlag',
- 'SSARegister',
- 'SSARegisterStack',
- 'ILSemanticFlagClass',
- 'ILSemanticFlagGroup',
- 'LowLevelILFlagCondition',
- List[int],
- List['LowLevelILInstruction'],
- List[Union['ILFlag', 'ILRegister']],
- List['SSARegister'],
- List['SSARegisterStack'],
- List['SSAFlag'],
- List['SSARegisterOrFlag'],
- None
-]
+LowLevelILOperandType = Union['LowLevelILOperationAndSize', 'ILRegister', 'ILFlag', 'ILIntrinsic', 'ILRegisterStack',
+ int, Dict[int, int], float, 'LowLevelILInstruction',
+ Dict['architecture.RegisterStackName', int], 'SSAFlag', 'SSARegister', 'SSARegisterStack',
+ 'ILSemanticFlagClass', 'ILSemanticFlagGroup', 'LowLevelILFlagCondition', List[int],
+ List['LowLevelILInstruction'], List[Union['ILFlag', 'ILRegister']], List['SSARegister'],
+ List['SSARegisterStack'], List['SSAFlag'], List['SSARegisterOrFlag'], None]
+
class LowLevelILLabel:
- def __init__(self, handle:core.BNLowLevelILLabel=None):
+ def __init__(self, handle: core.BNLowLevelILLabel = None):
if handle is None:
self.handle = (core.BNLowLevelILLabel * 1)()
core.BNLowLevelILInitLabel(self.handle)
else:
self.handle = handle
+
@dataclass(frozen=True)
class ILRegister:
- arch:'architecture.Architecture'
- index:'architecture.RegisterIndex'
+ arch: 'architecture.Architecture'
+ index: 'architecture.RegisterIndex'
def __repr__(self):
return f"<reg {self.name}>"
@@ -124,8 +108,8 @@ class ILRegister:
@dataclass(frozen=True)
class ILRegisterStack:
- arch:'architecture.Architecture'
- index:'architecture.RegisterStackIndex'
+ arch: 'architecture.Architecture'
+ index: 'architecture.RegisterStackIndex'
def __repr__(self):
return f"<reg-stack {self.name}>"
@@ -147,8 +131,8 @@ class ILRegisterStack:
@dataclass(frozen=True)
class ILFlag:
- arch:'architecture.Architecture'
- index:'architecture.FlagIndex'
+ arch: 'architecture.Architecture'
+ index: 'architecture.FlagIndex'
def __repr__(self):
return f"<flag {self.name}>"
@@ -173,8 +157,8 @@ class ILFlag:
@dataclass(frozen=True)
class ILSemanticFlagClass:
- arch:'architecture.Architecture'
- index:'architecture.SemanticClassIndex'
+ arch: 'architecture.Architecture'
+ index: 'architecture.SemanticClassIndex'
def __repr__(self):
return self.name
@@ -192,8 +176,8 @@ class ILSemanticFlagClass:
@dataclass(frozen=True)
class ILSemanticFlagGroup:
- arch:'architecture.Architecture'
- index:'architecture.SemanticGroupIndex'
+ arch: 'architecture.Architecture'
+ index: 'architecture.SemanticGroupIndex'
def __repr__(self):
return self.name
@@ -211,8 +195,8 @@ class ILSemanticFlagGroup:
@dataclass(frozen=True)
class ILIntrinsic:
- arch:'architecture.Architecture'
- index:'architecture.IntrinsicIndex'
+ arch: 'architecture.Architecture'
+ index: 'architecture.IntrinsicIndex'
def __repr__(self):
return self.name
@@ -237,8 +221,8 @@ class ILIntrinsic:
@dataclass(frozen=True)
class SSARegister:
- reg:ILRegister
- version:int
+ reg: ILRegister
+ version: int
def __repr__(self):
return f"<ssa {self.reg} version {self.version}>"
@@ -246,8 +230,8 @@ class SSARegister:
@dataclass(frozen=True)
class SSARegisterStack:
- reg_stack:ILRegisterStack
- version:int
+ reg_stack: ILRegisterStack
+ version: int
def __repr__(self):
return f"<ssa {self.reg_stack} version {self.version}>"
@@ -255,8 +239,8 @@ class SSARegisterStack:
@dataclass(frozen=True)
class SSAFlag:
- flag:ILFlag
- version:int
+ flag: ILFlag
+ version: int
def __repr__(self):
return f"<ssa {self.flag} version {self.version}>"
@@ -264,8 +248,8 @@ class SSAFlag:
@dataclass(frozen=True)
class SSARegisterOrFlag:
- reg_or_flag:Union[ILRegister, ILFlag]
- version:int
+ reg_or_flag: Union[ILRegister, ILFlag]
+ version: int
def __repr__(self):
return f"<ssa {self.reg_or_flag} version {self.version}>"
@@ -273,8 +257,8 @@ class SSARegisterOrFlag:
@dataclass(frozen=True)
class LowLevelILOperationAndSize:
- operation:'LowLevelILOperation'
- size:int
+ operation: 'LowLevelILOperation'
+ size: int
def __repr__(self):
if self.size == 0:
@@ -284,20 +268,22 @@ class LowLevelILOperationAndSize:
@dataclass(frozen=True)
class CoreLowLevelILInstruction:
- operation:LowLevelILOperation
- size:int
- flags:int
- source_operand:ExpressionIndex
- operands:OperandsType
- address:int
+ operation: LowLevelILOperation
+ size: int
+ flags: int
+ source_operand: ExpressionIndex
+ operands: OperandsType
+ address: int
@classmethod
- def from_BNLowLevelILInstruction(cls, instr:core.BNLowLevelILInstruction) -> 'CoreLowLevelILInstruction':
- operands:OperandsType = (ExpressionIndex(instr.operands[0]),
- ExpressionIndex(instr.operands[1]),
- ExpressionIndex(instr.operands[2]),
- ExpressionIndex(instr.operands[3]))
- return cls(LowLevelILOperation(instr.operation), instr.size, instr.flags, instr.sourceOperand, operands, instr.address)
+ def from_BNLowLevelILInstruction(cls, instr: core.BNLowLevelILInstruction) -> 'CoreLowLevelILInstruction':
+ operands: OperandsType = (
+ ExpressionIndex(instr.operands[0]), ExpressionIndex(instr.operands[1]), ExpressionIndex(instr.operands[2]),
+ ExpressionIndex(instr.operands[3])
+ )
+ return cls(
+ LowLevelILOperation(instr.operation), instr.size, instr.flags, instr.sourceOperand, operands, instr.address
+ )
@dataclass(frozen=True)
@@ -308,146 +294,167 @@ class LowLevelILInstruction(BaseILInstruction):
Infix notation is thus more natural to read than other notations (e.g. x86 ``mov eax, 0`` vs. LLIL ``eax = 0``).
"""
- function:'LowLevelILFunction'
- expr_index:ExpressionIndex
- instr:CoreLowLevelILInstruction
- instr_index:Optional[InstructionIndex]
- ILOperations:ClassVar[Dict[LowLevelILOperation, List[Tuple[str,str]]]] = {
- LowLevelILOperation.LLIL_NOP: [],
- LowLevelILOperation.LLIL_SET_REG: [("dest", "reg"), ("src", "expr")],
- LowLevelILOperation.LLIL_SET_REG_SPLIT: [("hi", "reg"), ("lo", "reg"), ("src", "expr")],
- LowLevelILOperation.LLIL_SET_REG_STACK_REL: [("stack", "reg_stack"), ("dest", "expr"), ("src", "expr")],
- LowLevelILOperation.LLIL_REG_STACK_PUSH: [("stack", "reg_stack"), ("src", "expr")],
- LowLevelILOperation.LLIL_SET_FLAG: [("dest", "flag"), ("src", "expr")],
- LowLevelILOperation.LLIL_LOAD: [("src", "expr")],
- LowLevelILOperation.LLIL_STORE: [("dest", "expr"), ("src", "expr")],
- LowLevelILOperation.LLIL_PUSH: [("src", "expr")],
- LowLevelILOperation.LLIL_POP: [],
- LowLevelILOperation.LLIL_REG: [("src", "reg")],
- LowLevelILOperation.LLIL_REG_SPLIT: [("hi", "reg"), ("lo", "reg")],
- LowLevelILOperation.LLIL_REG_STACK_REL: [("stack", "reg_stack"), ("src", "expr")],
- LowLevelILOperation.LLIL_REG_STACK_POP: [("stack", "reg_stack")],
- LowLevelILOperation.LLIL_REG_STACK_FREE_REG: [("dest", "reg")],
- LowLevelILOperation.LLIL_REG_STACK_FREE_REL: [("stack", "reg_stack"), ("dest", "expr")],
- LowLevelILOperation.LLIL_CONST: [("constant", "int")],
- LowLevelILOperation.LLIL_CONST_PTR: [("constant", "int")],
- LowLevelILOperation.LLIL_EXTERN_PTR: [("constant", "int"), ("offset", "int")],
- LowLevelILOperation.LLIL_FLOAT_CONST: [("constant", "float")],
- LowLevelILOperation.LLIL_FLAG: [("src", "flag")],
- LowLevelILOperation.LLIL_FLAG_BIT: [("src", "flag"), ("bit", "int")],
- LowLevelILOperation.LLIL_ADD: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_ADC: [("left", "expr"), ("right", "expr"), ("carry", "expr")],
- LowLevelILOperation.LLIL_SUB: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_SBB: [("left", "expr"), ("right", "expr"), ("carry", "expr")],
- LowLevelILOperation.LLIL_AND: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_OR: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_XOR: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_LSL: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_LSR: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_ASR: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_ROL: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_RLC: [("left", "expr"), ("right", "expr"), ("carry", "expr")],
- LowLevelILOperation.LLIL_ROR: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_RRC: [("left", "expr"), ("right", "expr"), ("carry", "expr")],
- LowLevelILOperation.LLIL_MUL: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_MULU_DP: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_MULS_DP: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_DIVU: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_DIVU_DP: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_DIVS: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_DIVS_DP: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_MODU: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_MODU_DP: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_MODS: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_MODS_DP: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_NEG: [("src", "expr")],
- LowLevelILOperation.LLIL_NOT: [("src", "expr")],
- LowLevelILOperation.LLIL_SX: [("src", "expr")],
- LowLevelILOperation.LLIL_ZX: [("src", "expr")],
- LowLevelILOperation.LLIL_LOW_PART: [("src", "expr")],
- LowLevelILOperation.LLIL_JUMP: [("dest", "expr")],
- LowLevelILOperation.LLIL_JUMP_TO: [("dest", "expr"), ("targets", "target_map")],
- LowLevelILOperation.LLIL_CALL: [("dest", "expr")],
- LowLevelILOperation.LLIL_CALL_STACK_ADJUST: [("dest", "expr"), ("stack_adjustment", "int"), ("reg_stack_adjustments", "reg_stack_adjust")],
- LowLevelILOperation.LLIL_TAILCALL: [("dest", "expr")],
- LowLevelILOperation.LLIL_RET: [("dest", "expr")],
- LowLevelILOperation.LLIL_NORET: [],
- LowLevelILOperation.LLIL_IF: [("condition", "expr"), ("true", "int"), ("false", "int")],
- LowLevelILOperation.LLIL_GOTO: [("dest", "int")],
- LowLevelILOperation.LLIL_FLAG_COND: [("condition", "cond"), ("semantic_class", "sem_class")],
- LowLevelILOperation.LLIL_FLAG_GROUP: [("semantic_group", "sem_group")],
- LowLevelILOperation.LLIL_CMP_E: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_CMP_NE: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_CMP_SLT: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_CMP_ULT: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_CMP_SLE: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_CMP_ULE: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_CMP_SGE: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_CMP_UGE: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_CMP_SGT: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_CMP_UGT: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_TEST_BIT: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_BOOL_TO_INT: [("src", "expr")],
- LowLevelILOperation.LLIL_ADD_OVERFLOW: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_SYSCALL: [],
- LowLevelILOperation.LLIL_INTRINSIC: [("output", "reg_or_flag_list"), ("intrinsic", "intrinsic"), ("param", "expr")],
- LowLevelILOperation.LLIL_INTRINSIC_SSA: [("output", "reg_or_flag_ssa_list"), ("intrinsic", "intrinsic"), ("param", "expr")],
- LowLevelILOperation.LLIL_BP: [],
- LowLevelILOperation.LLIL_TRAP: [("vector", "int")],
- LowLevelILOperation.LLIL_UNDEF: [],
- LowLevelILOperation.LLIL_UNIMPL: [],
- LowLevelILOperation.LLIL_UNIMPL_MEM: [("src", "expr")],
- LowLevelILOperation.LLIL_FADD: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_FSUB: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_FMUL: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_FDIV: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_FSQRT: [("src", "expr")],
- LowLevelILOperation.LLIL_FNEG: [("src", "expr")],
- LowLevelILOperation.LLIL_FABS: [("src", "expr")],
- LowLevelILOperation.LLIL_FLOAT_TO_INT: [("src", "expr")],
- LowLevelILOperation.LLIL_INT_TO_FLOAT: [("src", "expr")],
- LowLevelILOperation.LLIL_FLOAT_CONV: [("src", "expr")],
- LowLevelILOperation.LLIL_ROUND_TO_INT: [("src", "expr")],
- LowLevelILOperation.LLIL_FLOOR: [("src", "expr")],
- LowLevelILOperation.LLIL_CEIL: [("src", "expr")],
- LowLevelILOperation.LLIL_FTRUNC: [("src", "expr")],
- LowLevelILOperation.LLIL_FCMP_E: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_FCMP_NE: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_FCMP_LT: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_FCMP_LE: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_FCMP_GE: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_FCMP_GT: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_FCMP_O: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_FCMP_UO: [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_SET_REG_SSA: [("dest", "reg_ssa"), ("src", "expr")],
- LowLevelILOperation.LLIL_SET_REG_SSA_PARTIAL: [("full_reg", "reg_ssa"), ("dest", "reg"), ("src", "expr")],
- LowLevelILOperation.LLIL_SET_REG_SPLIT_SSA: [("hi", "expr"), ("lo", "expr"), ("src", "expr")],
- LowLevelILOperation.LLIL_SET_REG_STACK_REL_SSA: [("stack", "expr"), ("dest", "expr"), ("top", "expr"), ("src", "expr")],
- LowLevelILOperation.LLIL_SET_REG_STACK_ABS_SSA: [("stack", "expr"), ("dest", "reg"), ("src", "expr")],
- LowLevelILOperation.LLIL_REG_SPLIT_DEST_SSA: [("dest", "reg_ssa")],
- LowLevelILOperation.LLIL_REG_STACK_DEST_SSA: [("src", "reg_stack_ssa_dest_and_src")],
- LowLevelILOperation.LLIL_REG_SSA: [("src", "reg_ssa")],
- LowLevelILOperation.LLIL_REG_SSA_PARTIAL: [("full_reg", "reg_ssa"), ("src", "reg")],
- LowLevelILOperation.LLIL_REG_SPLIT_SSA: [("hi", "reg_ssa"), ("lo", "reg_ssa")],
- LowLevelILOperation.LLIL_REG_STACK_REL_SSA: [("stack", "reg_stack_ssa"), ("src", "expr"), ("top", "expr")],
- LowLevelILOperation.LLIL_REG_STACK_ABS_SSA: [("stack", "reg_stack_ssa"), ("src", "reg")],
- LowLevelILOperation.LLIL_REG_STACK_FREE_REL_SSA: [("stack", "expr"), ("dest", "expr"), ("top", "expr")],
- LowLevelILOperation.LLIL_REG_STACK_FREE_ABS_SSA: [("stack", "expr"), ("dest", "reg")],
- LowLevelILOperation.LLIL_SET_FLAG_SSA: [("dest", "flag_ssa"), ("src", "expr")],
- LowLevelILOperation.LLIL_FLAG_SSA: [("src", "flag_ssa")],
- LowLevelILOperation.LLIL_FLAG_BIT_SSA: [("src", "flag_ssa"), ("bit", "int")],
- LowLevelILOperation.LLIL_CALL_SSA: [("output", "expr"), ("dest", "expr"), ("stack", "expr"), ("param", "expr")],
- LowLevelILOperation.LLIL_SYSCALL_SSA: [("output", "expr"), ("stack", "expr"), ("param", "expr")],
- LowLevelILOperation.LLIL_TAILCALL_SSA: [("output", "expr"), ("dest", "expr"), ("stack", "expr"), ("param", "expr")],
- LowLevelILOperation.LLIL_CALL_OUTPUT_SSA: [("dest_memory", "int"), ("dest", "reg_ssa_list")],
- LowLevelILOperation.LLIL_CALL_STACK_SSA: [("src", "reg_ssa"), ("src_memory", "int")],
- LowLevelILOperation.LLIL_CALL_PARAM: [("src", "expr_list")],
- LowLevelILOperation.LLIL_LOAD_SSA: [("src", "expr"), ("src_memory", "int")],
- LowLevelILOperation.LLIL_STORE_SSA: [("dest", "expr"), ("dest_memory", "int"), ("src_memory", "int"), ("src", "expr")],
- LowLevelILOperation.LLIL_REG_PHI: [("dest", "reg_ssa"), ("src", "reg_ssa_list")],
- LowLevelILOperation.LLIL_REG_STACK_PHI: [("dest", "reg_stack_ssa"), ("src", "reg_stack_ssa_list")],
- LowLevelILOperation.LLIL_FLAG_PHI: [("dest", "flag_ssa"), ("src", "flag_ssa_list")],
- LowLevelILOperation.LLIL_MEM_PHI: [("dest_memory", "int"), ("src_memory", "int_list")]
+ function: 'LowLevelILFunction'
+ expr_index: ExpressionIndex
+ instr: CoreLowLevelILInstruction
+ instr_index: Optional[InstructionIndex]
+ ILOperations: ClassVar[Dict[LowLevelILOperation, List[Tuple[str, str]]]] = {
+ LowLevelILOperation.LLIL_NOP: [], LowLevelILOperation.LLIL_SET_REG: [("dest", "reg"), ("src", "expr")],
+ LowLevelILOperation.LLIL_SET_REG_SPLIT: [("hi", "reg"), ("lo", "reg"),
+ ("src", "expr")], LowLevelILOperation.LLIL_SET_REG_STACK_REL: [
+ ("stack", "reg_stack"), ("dest", "expr"), ("src", "expr")
+ ], LowLevelILOperation.LLIL_REG_STACK_PUSH: [("stack", "reg_stack"),
+ ("src", "expr")],
+ LowLevelILOperation.LLIL_SET_FLAG: [("dest", "flag"), ("src", "expr")], LowLevelILOperation.LLIL_LOAD: [
+ ("src", "expr")
+ ], LowLevelILOperation.LLIL_STORE: [("dest", "expr"),
+ ("src", "expr")], LowLevelILOperation.LLIL_PUSH: [("src", "expr")],
+ LowLevelILOperation.LLIL_POP: [], LowLevelILOperation.LLIL_REG: [("src", "reg")],
+ LowLevelILOperation.LLIL_REG_SPLIT: [("hi", "reg"), ("lo", "reg")], LowLevelILOperation.LLIL_REG_STACK_REL: [
+ ("stack", "reg_stack"), ("src", "expr")
+ ], LowLevelILOperation.LLIL_REG_STACK_POP: [("stack", "reg_stack")],
+ LowLevelILOperation.LLIL_REG_STACK_FREE_REG: [("dest", "reg")], LowLevelILOperation.LLIL_REG_STACK_FREE_REL: [
+ ("stack", "reg_stack"), ("dest", "expr")
+ ], LowLevelILOperation.LLIL_CONST: [("constant", "int")], LowLevelILOperation.LLIL_CONST_PTR: [
+ ("constant", "int")
+ ], LowLevelILOperation.LLIL_EXTERN_PTR: [
+ ("constant", "int"), ("offset", "int")
+ ], LowLevelILOperation.LLIL_FLOAT_CONST: [("constant", "float")], LowLevelILOperation.LLIL_FLAG: [
+ ("src", "flag")
+ ], LowLevelILOperation.LLIL_FLAG_BIT: [("src", "flag"), ("bit", "int")], LowLevelILOperation.LLIL_ADD: [
+ ("left", "expr"), ("right", "expr")
+ ], LowLevelILOperation.LLIL_ADC: [
+ ("left", "expr"), ("right", "expr"), ("carry", "expr")
+ ], LowLevelILOperation.LLIL_SUB: [("left", "expr"), ("right", "expr")], LowLevelILOperation.LLIL_SBB: [
+ ("left", "expr"), ("right", "expr"), ("carry", "expr")
+ ], LowLevelILOperation.LLIL_AND: [("left", "expr"), ("right", "expr")], LowLevelILOperation.LLIL_OR: [
+ ("left", "expr"), ("right", "expr")
+ ], LowLevelILOperation.LLIL_XOR: [("left", "expr"), ("right", "expr")], LowLevelILOperation.LLIL_LSL: [
+ ("left", "expr"), ("right", "expr")
+ ], LowLevelILOperation.LLIL_LSR: [("left", "expr"), ("right", "expr")], LowLevelILOperation.LLIL_ASR: [
+ ("left", "expr"), ("right", "expr")
+ ], LowLevelILOperation.LLIL_ROL: [("left", "expr"), ("right", "expr")], LowLevelILOperation.LLIL_RLC: [
+ ("left", "expr"), ("right", "expr"), ("carry", "expr")
+ ], LowLevelILOperation.LLIL_ROR: [("left", "expr"), ("right", "expr")], LowLevelILOperation.LLIL_RRC: [
+ ("left", "expr"), ("right", "expr"), ("carry", "expr")
+ ], LowLevelILOperation.LLIL_MUL: [("left", "expr"), ("right", "expr")], LowLevelILOperation.LLIL_MULU_DP: [
+ ("left", "expr"), ("right", "expr")
+ ], LowLevelILOperation.LLIL_MULS_DP: [("left", "expr"), ("right", "expr")], LowLevelILOperation.LLIL_DIVU: [
+ ("left", "expr"), ("right", "expr")
+ ], LowLevelILOperation.LLIL_DIVU_DP: [("left", "expr"), ("right", "expr")], LowLevelILOperation.LLIL_DIVS: [
+ ("left", "expr"), ("right", "expr")
+ ], LowLevelILOperation.LLIL_DIVS_DP: [("left", "expr"), ("right", "expr")], LowLevelILOperation.LLIL_MODU: [
+ ("left", "expr"), ("right", "expr")
+ ], LowLevelILOperation.LLIL_MODU_DP: [("left", "expr"), ("right", "expr")], LowLevelILOperation.LLIL_MODS: [
+ ("left", "expr"), ("right", "expr")
+ ], LowLevelILOperation.LLIL_MODS_DP: [("left", "expr"), ("right", "expr")], LowLevelILOperation.LLIL_NEG: [
+ ("src", "expr")
+ ], LowLevelILOperation.LLIL_NOT: [("src", "expr")], LowLevelILOperation.LLIL_SX: [
+ ("src", "expr")
+ ], LowLevelILOperation.LLIL_ZX: [("src", "expr")], LowLevelILOperation.LLIL_LOW_PART: [
+ ("src", "expr")
+ ], LowLevelILOperation.LLIL_JUMP: [("dest", "expr")], LowLevelILOperation.LLIL_JUMP_TO: [
+ ("dest", "expr"), ("targets", "target_map")
+ ], LowLevelILOperation.LLIL_CALL: [("dest", "expr")], LowLevelILOperation.LLIL_CALL_STACK_ADJUST: [
+ ("dest", "expr"), ("stack_adjustment", "int"), ("reg_stack_adjustments", "reg_stack_adjust")
+ ], LowLevelILOperation.LLIL_TAILCALL: [("dest", "expr")], LowLevelILOperation.LLIL_RET: [
+ ("dest", "expr")
+ ], LowLevelILOperation.LLIL_NORET: [], LowLevelILOperation.LLIL_IF: [
+ ("condition", "expr"), ("true", "int"), ("false", "int")
+ ], LowLevelILOperation.LLIL_GOTO: [("dest", "int")], LowLevelILOperation.LLIL_FLAG_COND: [
+ ("condition", "cond"), ("semantic_class", "sem_class")
+ ], LowLevelILOperation.LLIL_FLAG_GROUP: [("semantic_group", "sem_group")], LowLevelILOperation.LLIL_CMP_E: [
+ ("left", "expr"), ("right", "expr")
+ ], LowLevelILOperation.LLIL_CMP_NE: [("left", "expr"), ("right", "expr")], LowLevelILOperation.LLIL_CMP_SLT: [
+ ("left", "expr"), ("right", "expr")
+ ], LowLevelILOperation.LLIL_CMP_ULT: [("left", "expr"), ("right", "expr")], LowLevelILOperation.LLIL_CMP_SLE: [
+ ("left", "expr"), ("right", "expr")
+ ], LowLevelILOperation.LLIL_CMP_ULE: [("left", "expr"), ("right", "expr")], LowLevelILOperation.LLIL_CMP_SGE: [
+ ("left", "expr"), ("right", "expr")
+ ], LowLevelILOperation.LLIL_CMP_UGE: [("left", "expr"), ("right", "expr")], LowLevelILOperation.LLIL_CMP_SGT: [
+ ("left", "expr"), ("right", "expr")
+ ], LowLevelILOperation.LLIL_CMP_UGT: [("left", "expr"), ("right", "expr")], LowLevelILOperation.LLIL_TEST_BIT: [
+ ("left", "expr"), ("right", "expr")
+ ], LowLevelILOperation.LLIL_BOOL_TO_INT: [("src", "expr")], LowLevelILOperation.LLIL_ADD_OVERFLOW: [
+ ("left", "expr"), ("right", "expr")
+ ], LowLevelILOperation.LLIL_SYSCALL: [], LowLevelILOperation.LLIL_INTRINSIC: [
+ ("output", "reg_or_flag_list"), ("intrinsic", "intrinsic"), ("param", "expr")
+ ], LowLevelILOperation.LLIL_INTRINSIC_SSA: [
+ ("output", "reg_or_flag_ssa_list"), ("intrinsic", "intrinsic"), ("param", "expr")
+ ], LowLevelILOperation.LLIL_BP: [], LowLevelILOperation.LLIL_TRAP: [("vector", "int")],
+ LowLevelILOperation.LLIL_UNDEF: [], LowLevelILOperation.LLIL_UNIMPL: [], LowLevelILOperation.LLIL_UNIMPL_MEM: [
+ ("src", "expr")
+ ], LowLevelILOperation.LLIL_FADD: [("left", "expr"), ("right", "expr")], LowLevelILOperation.LLIL_FSUB: [
+ ("left", "expr"), ("right", "expr")
+ ], LowLevelILOperation.LLIL_FMUL: [("left", "expr"), ("right", "expr")], LowLevelILOperation.LLIL_FDIV: [
+ ("left", "expr"), ("right", "expr")
+ ], LowLevelILOperation.LLIL_FSQRT: [("src", "expr")], LowLevelILOperation.LLIL_FNEG: [
+ ("src", "expr")
+ ], LowLevelILOperation.LLIL_FABS: [("src", "expr")], LowLevelILOperation.LLIL_FLOAT_TO_INT: [
+ ("src", "expr")
+ ], LowLevelILOperation.LLIL_INT_TO_FLOAT: [("src", "expr")], LowLevelILOperation.LLIL_FLOAT_CONV: [
+ ("src", "expr")
+ ], LowLevelILOperation.LLIL_ROUND_TO_INT: [("src", "expr")], LowLevelILOperation.LLIL_FLOOR: [
+ ("src", "expr")
+ ], LowLevelILOperation.LLIL_CEIL: [("src", "expr")], LowLevelILOperation.LLIL_FTRUNC: [
+ ("src", "expr")
+ ], LowLevelILOperation.LLIL_FCMP_E: [("left", "expr"), ("right", "expr")], LowLevelILOperation.LLIL_FCMP_NE: [
+ ("left", "expr"), ("right", "expr")
+ ], LowLevelILOperation.LLIL_FCMP_LT: [("left", "expr"), ("right", "expr")], LowLevelILOperation.LLIL_FCMP_LE: [
+ ("left", "expr"), ("right", "expr")
+ ], LowLevelILOperation.LLIL_FCMP_GE: [("left", "expr"), ("right", "expr")], LowLevelILOperation.LLIL_FCMP_GT: [
+ ("left", "expr"), ("right", "expr")
+ ], LowLevelILOperation.LLIL_FCMP_O: [("left", "expr"), ("right", "expr")], LowLevelILOperation.LLIL_FCMP_UO: [
+ ("left", "expr"), ("right", "expr")
+ ], LowLevelILOperation.LLIL_SET_REG_SSA: [("dest", "reg_ssa"),
+ ("src", "expr")], LowLevelILOperation.LLIL_SET_REG_SSA_PARTIAL: [
+ ("full_reg", "reg_ssa"), ("dest", "reg"), ("src", "expr")
+ ], LowLevelILOperation.LLIL_SET_REG_SPLIT_SSA: [
+ ("hi", "expr"), ("lo", "expr"), ("src", "expr")
+ ], LowLevelILOperation.LLIL_SET_REG_STACK_REL_SSA: [
+ ("stack", "expr"), ("dest", "expr"), ("top", "expr"),
+ ("src", "expr")
+ ], LowLevelILOperation.LLIL_SET_REG_STACK_ABS_SSA: [
+ ("stack", "expr"), ("dest", "reg"), ("src", "expr")
+ ], LowLevelILOperation.LLIL_REG_SPLIT_DEST_SSA: [("dest", "reg_ssa")],
+ LowLevelILOperation.LLIL_REG_STACK_DEST_SSA: [
+ ("src", "reg_stack_ssa_dest_and_src")
+ ], LowLevelILOperation.LLIL_REG_SSA: [("src", "reg_ssa")], LowLevelILOperation.LLIL_REG_SSA_PARTIAL: [
+ ("full_reg", "reg_ssa"), ("src", "reg")
+ ], LowLevelILOperation.LLIL_REG_SPLIT_SSA: [("hi", "reg_ssa"),
+ ("lo", "reg_ssa")], LowLevelILOperation.LLIL_REG_STACK_REL_SSA: [
+ ("stack", "reg_stack_ssa"), ("src", "expr"), ("top", "expr")
+ ], LowLevelILOperation.LLIL_REG_STACK_ABS_SSA: [
+ ("stack", "reg_stack_ssa"), ("src", "reg")
+ ], LowLevelILOperation.LLIL_REG_STACK_FREE_REL_SSA: [
+ ("stack", "expr"), ("dest", "expr"), ("top", "expr")
+ ], LowLevelILOperation.LLIL_REG_STACK_FREE_ABS_SSA: [
+ ("stack", "expr"), ("dest", "reg")
+ ], LowLevelILOperation.LLIL_SET_FLAG_SSA: [("dest", "flag_ssa"),
+ ("src", "expr")],
+ LowLevelILOperation.LLIL_FLAG_SSA: [("src", "flag_ssa")], LowLevelILOperation.LLIL_FLAG_BIT_SSA: [
+ ("src", "flag_ssa"), ("bit", "int")
+ ], LowLevelILOperation.LLIL_CALL_SSA: [("output", "expr"), ("dest", "expr"), ("stack", "expr"),
+ ("param", "expr")], LowLevelILOperation.LLIL_SYSCALL_SSA: [
+ ("output", "expr"), ("stack", "expr"), ("param", "expr")
+ ], LowLevelILOperation.LLIL_TAILCALL_SSA: [
+ ("output", "expr"), ("dest", "expr"), ("stack", "expr"),
+ ("param", "expr")
+ ], LowLevelILOperation.LLIL_CALL_OUTPUT_SSA: [
+ ("dest_memory", "int"), ("dest", "reg_ssa_list")
+ ], LowLevelILOperation.LLIL_CALL_STACK_SSA: [("src", "reg_ssa"),
+ ("src_memory", "int")],
+ LowLevelILOperation.LLIL_CALL_PARAM: [("src", "expr_list")], LowLevelILOperation.LLIL_LOAD_SSA: [
+ ("src", "expr"), ("src_memory", "int")
+ ], LowLevelILOperation.LLIL_STORE_SSA: [("dest", "expr"), ("dest_memory", "int"), ("src_memory", "int"),
+ ("src", "expr")], LowLevelILOperation.LLIL_REG_PHI: [
+ ("dest", "reg_ssa"), ("src", "reg_ssa_list")
+ ], LowLevelILOperation.LLIL_REG_STACK_PHI: [
+ ("dest", "reg_stack_ssa"), ("src", "reg_stack_ssa_list")
+ ], LowLevelILOperation.LLIL_FLAG_PHI: [
+ ("dest", "flag_ssa"), ("src", "flag_ssa_list")
+ ], LowLevelILOperation.LLIL_MEM_PHI: [("dest_memory", "int"),
+ ("src_memory", "int_list")]
}
@staticmethod
@@ -459,7 +466,9 @@ class LowLevelILInstruction(BaseILInstruction):
show_graph_report("LLIL Class Hierarchy Graph", graph)
@classmethod
- def create(cls, func:'LowLevelILFunction', expr_index:ExpressionIndex, instr_index:Optional[InstructionIndex]=None) -> 'LowLevelILInstruction':
+ def create(
+ cls, func: 'LowLevelILFunction', expr_index: ExpressionIndex, instr_index: Optional[InstructionIndex] = None
+ ) -> 'LowLevelILInstruction':
assert func.arch is not None, "Attempted to create IL instruction with function missing an Architecture"
inst = core.BNGetLowLevelILByIndex(func.handle, expr_index)
assert inst is not None, "core.BNGetLowLevelILByIndex returned None"
@@ -478,32 +487,32 @@ class LowLevelILInstruction(BaseILInstruction):
def __repr__(self):
return f"<llil: {self}>"
- def __eq__(self, other:'LowLevelILInstruction') -> bool:
+ def __eq__(self, other: 'LowLevelILInstruction') -> bool:
if not isinstance(other, LowLevelILInstruction):
return NotImplemented
return self.function == other.function and self.expr_index == other.expr_index
- def __ne__(self, other:'LowLevelILInstruction') -> bool:
+ def __ne__(self, other: 'LowLevelILInstruction') -> bool:
if not isinstance(other, LowLevelILInstruction):
return NotImplemented
return not (self == other)
- def __lt__(self, other:'LowLevelILInstruction') -> bool:
+ def __lt__(self, other: 'LowLevelILInstruction') -> bool:
if not isinstance(other, LowLevelILInstruction):
return NotImplemented
return self.function == other.function and self.expr_index < other.expr_index
- def __le__(self, other:'LowLevelILInstruction') -> bool:
+ def __le__(self, other: 'LowLevelILInstruction') -> bool:
if not isinstance(other, LowLevelILInstruction):
return NotImplemented
return self.function == other.function and self.expr_index <= other.expr_index
- def __gt__(self, other:'LowLevelILInstruction') -> bool:
+ def __gt__(self, other: 'LowLevelILInstruction') -> bool:
if not isinstance(other, LowLevelILInstruction):
return NotImplemented
return self.function == other.function and self.expr_index > other.expr_index
- def __ge__(self, other:'LowLevelILInstruction') -> bool:
+ def __ge__(self, other: 'LowLevelILInstruction') -> bool:
if not isinstance(other, LowLevelILInstruction):
return NotImplemented
return self.function == other.function and self.expr_index >= other.expr_index
@@ -533,8 +542,9 @@ class LowLevelILInstruction(BaseILInstruction):
count = ctypes.c_ulonglong()
assert self.function.arch is not None, f"self.function.arch is None"
tokens = ctypes.POINTER(core.BNInstructionTextToken)()
- result = core.BNGetLowLevelILExprText(self.function.handle, self.function.arch.handle,
- self.expr_index, tokens, count)
+ result = core.BNGetLowLevelILExprText(
+ self.function.handle, self.function.arch.handle, self.expr_index, tokens, count
+ )
assert result, "core.BNGetLowLevelILExprText returned False"
try:
return function.InstructionTextToken._from_core_struct(tokens, count.value)
@@ -555,18 +565,23 @@ class LowLevelILInstruction(BaseILInstruction):
"""SSA form of expression (read-only)"""
ssa_func = self.function.ssa_form
assert ssa_func is not None
- return LowLevelILInstruction.create(ssa_func,
- ExpressionIndex(core.BNGetLowLevelILSSAExprIndex(self.function.handle, self.expr_index)),
- core.BNGetLowLevelILSSAInstructionIndex(self.function.handle, self.instr_index) if self.instr_index is not None else None)
+ return LowLevelILInstruction.create(
+ ssa_func, ExpressionIndex(core.BNGetLowLevelILSSAExprIndex(self.function.handle, self.expr_index)),
+ core.BNGetLowLevelILSSAInstructionIndex(self.function.handle, self.instr_index)
+ if self.instr_index is not None else None
+ )
@property
def non_ssa_form(self) -> 'LowLevelILInstruction':
"""Non-SSA form of expression (read-only)"""
non_ssa_function = self.function.non_ssa_form
assert non_ssa_function is not None
- return LowLevelILInstruction.create(non_ssa_function,
- ExpressionIndex(core.BNGetLowLevelILNonSSAExprIndex(self.function.handle, self.expr_index)),
- core.BNGetLowLevelILNonSSAInstructionIndex(self.function.handle, self.instr_index) if self.instr_index is not None else None)
+ return LowLevelILInstruction.create(
+ non_ssa_function,
+ ExpressionIndex(core.BNGetLowLevelILNonSSAExprIndex(self.function.handle, self.expr_index)),
+ core.BNGetLowLevelILNonSSAInstructionIndex(self.function.handle, self.instr_index)
+ if self.instr_index is not None else None
+ )
@property
def medium_level_il(self) -> Optional['mediumlevelil.MediumLevelILInstruction']:
@@ -644,7 +659,7 @@ class LowLevelILInstruction(BaseILInstruction):
@property
def prefix_operands(self) -> List[LowLevelILOperandType]:
"""All operands in the expression tree in prefix order"""
- result:List[LowLevelILOperandType] = [LowLevelILOperationAndSize(self.instr.operation, self.instr.size)]
+ result: List[LowLevelILOperandType] = [LowLevelILOperationAndSize(self.instr.operation, self.instr.size)]
for operand in self.operands:
if isinstance(operand, LowLevelILInstruction):
assert id(self) != id(operand), f"circular reference {operand}({repr(operand)}) is {self}({repr(self)})"
@@ -656,7 +671,7 @@ class LowLevelILInstruction(BaseILInstruction):
@property
def postfix_operands(self) -> List[LowLevelILOperandType]:
"""All operands in the expression tree in postfix order"""
- result:List[LowLevelILOperandType] = []
+ result: List[LowLevelILOperandType] = []
for operand in self.operands:
if isinstance(operand, LowLevelILInstruction):
assert id(self) != id(operand), f"circular reference {operand}({repr(operand)}) is {self}({repr(self)})"
@@ -667,7 +682,7 @@ class LowLevelILInstruction(BaseILInstruction):
return result
@staticmethod
- def _make_options_array(options:Optional[List[DataFlowQueryOption]]):
+ def _make_options_array(options: Optional[List[DataFlowQueryOption]]):
if options is None:
options = []
idx = 0
@@ -677,50 +692,56 @@ class LowLevelILInstruction(BaseILInstruction):
idx += 1
return option_array, len(options)
- def get_possible_values(self, options:Optional[List[DataFlowQueryOption]]=None) -> variable.PossibleValueSet:
+ def get_possible_values(self, options: Optional[List[DataFlowQueryOption]] = None) -> variable.PossibleValueSet:
option_array, option_size = LowLevelILInstruction._make_options_array(options)
value = core.BNGetLowLevelILPossibleExprValues(self.function.handle, self.expr_index, option_array, option_size)
result = variable.PossibleValueSet(self.function.arch, value)
core.BNFreePossibleValueSet(value)
return result
- def get_reg_value(self, reg:'architecture.RegisterType') -> variable.RegisterValue:
+ def get_reg_value(self, reg: 'architecture.RegisterType') -> variable.RegisterValue:
if self.function.arch is None:
raise Exception("Can not call get_reg_value on function with Architecture set to None")
reg = self.function.arch.get_reg_index(reg)
value = core.BNGetLowLevelILRegisterValueAtInstruction(self.function.handle, reg, self.instr_index)
return variable.RegisterValue.from_BNRegisterValue(value, self.function.arch)
- def get_reg_value_after(self, reg:'architecture.RegisterType') -> variable.RegisterValue:
+ def get_reg_value_after(self, reg: 'architecture.RegisterType') -> variable.RegisterValue:
if self.function.arch is None:
raise Exception("Can not call get_reg_value_after on function with Architecture set to None")
reg = self.function.arch.get_reg_index(reg)
value = core.BNGetLowLevelILRegisterValueAfterInstruction(self.function.handle, reg, self.instr_index)
return variable.RegisterValue.from_BNRegisterValue(value, self.function.arch)
- def get_possible_reg_values(self, reg:'architecture.RegisterType', options:List[DataFlowQueryOption]=None) -> 'variable.PossibleValueSet':
+ def get_possible_reg_values(
+ self, reg: 'architecture.RegisterType', options: List[DataFlowQueryOption] = None
+ ) -> 'variable.PossibleValueSet':
if self.function.arch is None:
raise Exception("Can not call get_possible_reg_values on function with Architecture set to None")
reg = self.function.arch.get_reg_index(reg)
option_array, option_size = LowLevelILInstruction._make_options_array(options)
- value = core.BNGetLowLevelILPossibleRegisterValuesAtInstruction(self.function.handle, reg, self.instr_index,
- option_array, option_size)
+ value = core.BNGetLowLevelILPossibleRegisterValuesAtInstruction(
+ self.function.handle, reg, self.instr_index, option_array, option_size
+ )
result = variable.PossibleValueSet(self.function.arch, value)
core.BNFreePossibleValueSet(value)
return result
- def get_possible_reg_values_after(self, reg:'architecture.RegisterType', options:Optional[List[DataFlowQueryOption]]=None) -> 'variable.PossibleValueSet':
+ def get_possible_reg_values_after(
+ self, reg: 'architecture.RegisterType', options: Optional[List[DataFlowQueryOption]] = None
+ ) -> 'variable.PossibleValueSet':
if self.function.arch is None:
raise Exception("Can not call get_possible_reg_values_after on function with Architecture set to None")
reg = self.function.arch.get_reg_index(reg)
option_array, option_size = LowLevelILInstruction._make_options_array(options)
- value = core.BNGetLowLevelILPossibleRegisterValuesAfterInstruction(self.function.handle, reg, self.instr_index,
- option_array, option_size)
+ value = core.BNGetLowLevelILPossibleRegisterValuesAfterInstruction(
+ self.function.handle, reg, self.instr_index, option_array, option_size
+ )
result = variable.PossibleValueSet(self.function.arch, value)
core.BNFreePossibleValueSet(value)
return result
- def get_flag_value(self, flag:'architecture.FlagType') -> 'variable.RegisterValue':
+ def get_flag_value(self, flag: 'architecture.FlagType') -> 'variable.RegisterValue':
if self.function.arch is None:
raise Exception("Can not call get_flag_value on function with Architecture set to None")
flag = self.function.arch.get_flag_index(flag)
@@ -728,7 +749,7 @@ class LowLevelILInstruction(BaseILInstruction):
result = variable.RegisterValue.from_BNRegisterValue(value, self.function.arch)
return result
- def get_flag_value_after(self, flag:'architecture.FlagType') -> 'variable.RegisterValue':
+ def get_flag_value_after(self, flag: 'architecture.FlagType') -> 'variable.RegisterValue':
if self.function.arch is None:
raise Exception("Can not call get_flag_value_after on function with Architecture set to None")
flag = self.function.arch.get_flag_index(flag)
@@ -736,50 +757,62 @@ class LowLevelILInstruction(BaseILInstruction):
result = variable.RegisterValue.from_BNRegisterValue(value, self.function.arch)
return result
- def get_possible_flag_values(self, flag:'architecture.FlagType', options:Optional[List[DataFlowQueryOption]]=None) -> 'variable.PossibleValueSet':
+ def get_possible_flag_values(
+ self, flag: 'architecture.FlagType', options: Optional[List[DataFlowQueryOption]] = None
+ ) -> 'variable.PossibleValueSet':
if self.function.arch is None:
raise Exception("Can not call get_possible_flag_values on function with Architecture set to None")
flag = self.function.arch.get_flag_index(flag)
option_array, option_size = LowLevelILInstruction._make_options_array(options)
- value = core.BNGetLowLevelILPossibleFlagValuesAtInstruction(self.function.handle, flag, self.instr_index,
- option_array, option_size)
+ value = core.BNGetLowLevelILPossibleFlagValuesAtInstruction(
+ self.function.handle, flag, self.instr_index, option_array, option_size
+ )
result = variable.PossibleValueSet(self.function.arch, value)
core.BNFreePossibleValueSet(value)
return result
- def get_possible_flag_values_after(self, flag:'architecture.FlagType', options:Optional[List[DataFlowQueryOption]]=None) -> 'variable.PossibleValueSet':
+ def get_possible_flag_values_after(
+ self, flag: 'architecture.FlagType', options: Optional[List[DataFlowQueryOption]] = None
+ ) -> 'variable.PossibleValueSet':
if self.function.arch is None:
raise Exception("Can not call get_possible_flag_values_after on function with Architecture set to None")
flag = self.function.arch.get_flag_index(flag)
option_array, option_size = LowLevelILInstruction._make_options_array(options)
- value = core.BNGetLowLevelILPossibleFlagValuesAfterInstruction(self.function.handle, flag, self.instr_index,
- option_array, option_size)
+ value = core.BNGetLowLevelILPossibleFlagValuesAfterInstruction(
+ self.function.handle, flag, self.instr_index, option_array, option_size
+ )
result = variable.PossibleValueSet(self.function.arch, value)
core.BNFreePossibleValueSet(value)
return result
- def get_stack_contents(self, offset:int, size:int) -> 'variable.RegisterValue':
+ def get_stack_contents(self, offset: int, size: int) -> 'variable.RegisterValue':
value = core.BNGetLowLevelILStackContentsAtInstruction(self.function.handle, offset, size, self.instr_index)
result = variable.RegisterValue.from_BNRegisterValue(value, self.function.arch)
return result
- def get_stack_contents_after(self, offset:int, size:int) -> 'variable.RegisterValue':
+ def get_stack_contents_after(self, offset: int, size: int) -> 'variable.RegisterValue':
value = core.BNGetLowLevelILStackContentsAfterInstruction(self.function.handle, offset, size, self.instr_index)
result = variable.RegisterValue.from_BNRegisterValue(value, self.function.arch)
return result
- def get_possible_stack_contents(self, offset:int, size:int, options:Optional[List[DataFlowQueryOption]]=None) -> variable.PossibleValueSet:
+ def get_possible_stack_contents(
+ self, offset: int, size: int, options: Optional[List[DataFlowQueryOption]] = None
+ ) -> variable.PossibleValueSet:
option_array, option_size = LowLevelILInstruction._make_options_array(options)
- value = core.BNGetLowLevelILPossibleStackContentsAtInstruction(self.function.handle, offset, size, self.instr_index,
- option_array, option_size)
+ value = core.BNGetLowLevelILPossibleStackContentsAtInstruction(
+ self.function.handle, offset, size, self.instr_index, option_array, option_size
+ )
result = variable.PossibleValueSet(self.function.arch, value)
core.BNFreePossibleValueSet(value)
return result
- def get_possible_stack_contents_after(self, offset:int, size:int, options:Optional[List[DataFlowQueryOption]]=None) -> variable.PossibleValueSet:
+ def get_possible_stack_contents_after(
+ self, offset: int, size: int, options: Optional[List[DataFlowQueryOption]] = None
+ ) -> variable.PossibleValueSet:
option_array, option_size = LowLevelILInstruction._make_options_array(options)
- value = core.BNGetLowLevelILPossibleStackContentsAfterInstruction(self.function.handle, offset, size, self.instr_index,
- option_array, option_size)
+ value = core.BNGetLowLevelILPossibleStackContentsAfterInstruction(
+ self.function.handle, offset, size, self.instr_index, option_array, option_size
+ )
result = variable.PossibleValueSet(self.function.arch, value)
core.BNFreePossibleValueSet(value)
return result
@@ -788,36 +821,36 @@ class LowLevelILInstruction(BaseILInstruction):
def flags(self) -> Optional['architecture.FlagWriteTypeName']:
return self.function.arch.get_flag_write_type_name(architecture.FlagWriteTypeIndex(self.instr.flags))
- def _get_reg(self, operand_index:int) -> ILRegister:
+ def _get_reg(self, operand_index: int) -> ILRegister:
return ILRegister(self.function.arch, architecture.RegisterIndex(self.instr.operands[operand_index]))
- def _get_flag(self, operand_index:int) -> ILFlag:
+ def _get_flag(self, operand_index: int) -> ILFlag:
return ILFlag(self.function.arch, architecture.FlagIndex(self.instr.operands[operand_index]))
- def _get_intrinsic(self, operand_index:int) -> ILIntrinsic:
+ def _get_intrinsic(self, operand_index: int) -> ILIntrinsic:
return ILIntrinsic(self.function.arch, architecture.IntrinsicIndex(self.instr.operands[operand_index]))
- def _get_reg_stack(self, operand_index:int) -> ILRegisterStack:
+ def _get_reg_stack(self, operand_index: int) -> ILRegisterStack:
return ILRegisterStack(self.function.arch, architecture.RegisterStackIndex(self.instr.operands[operand_index]))
- def _get_int(self, operand_index:int) -> int:
+ def _get_int(self, operand_index: int) -> int:
return (self.instr.operands[operand_index] & ((1 << 63) - 1)) - (self.instr.operands[operand_index] & (1 << 63))
- def _get_target_map(self, operand_index:int) -> Dict[int, int]:
+ def _get_target_map(self, operand_index: int) -> Dict[int, int]:
count = ctypes.c_ulonglong()
operand_list = core.BNLowLevelILGetOperandList(self.function.handle, self.expr_index, operand_index, count)
assert operand_list is not None, "core.BNLowLevelILGetOperandList returned None"
try:
- value:Dict[int, int] = {}
+ value: Dict[int, int] = {}
for j in range(count.value // 2):
key = operand_list[j * 2]
- target = operand_list[(j * 2) + 1]
+ target = operand_list[(j*2) + 1]
value[key] = target
return value
finally:
core.BNLowLevelILFreeOperandList(operand_list)
- def _get_float(self, operand_index:int) -> Union[int, float]:
+ def _get_float(self, operand_index: int) -> Union[int, float]:
if self.instr.size == 4:
return struct.unpack("f", struct.pack("I", self.instr.operands[operand_index] & 0xffffffff))[0]
elif self.instr.size == 8:
@@ -825,18 +858,18 @@ class LowLevelILInstruction(BaseILInstruction):
else:
return self.instr.operands[operand_index]
- def _get_expr(self, operand_index:int) -> 'LowLevelILInstruction':
+ def _get_expr(self, operand_index: int) -> 'LowLevelILInstruction':
return LowLevelILInstruction.create(self.function, self.instr.operands[operand_index], self.instr_index)
- def _get_reg_stack_adjust(self, operand_index:int) -> Dict['architecture.RegisterStackName', int]:
+ def _get_reg_stack_adjust(self, operand_index: int) -> Dict['architecture.RegisterStackName', int]:
count = ctypes.c_ulonglong()
operand_list = core.BNLowLevelILGetOperandList(self.function.handle, self.expr_index, operand_index, count)
assert operand_list is not None, "core.BNLowLevelILGetOperandList returned None"
- result:Dict['architecture.RegisterStackName', int] = {}
+ result: Dict['architecture.RegisterStackName', int] = {}
try:
for j in range(count.value // 2):
reg_stack = operand_list[j * 2]
- adjust = operand_list[(j * 2) + 1]
+ adjust = operand_list[(j*2) + 1]
if adjust & 0x80000000:
adjust |= ~0x80000000
result[self.function.arch.get_reg_stack_name(reg_stack)] = adjust
@@ -844,38 +877,44 @@ class LowLevelILInstruction(BaseILInstruction):
finally:
core.BNLowLevelILFreeOperandList(operand_list)
- def _get_flag_ssa(self, operand_index1:int, operand_index2:int) -> SSAFlag:
- return SSAFlag(ILFlag(self.function.arch, architecture.FlagIndex(self.instr.operands[operand_index1])),
- self.instr.operands[operand_index2])
+ def _get_flag_ssa(self, operand_index1: int, operand_index2: int) -> SSAFlag:
+ return SSAFlag(
+ ILFlag(self.function.arch, architecture.FlagIndex(self.instr.operands[operand_index1])),
+ self.instr.operands[operand_index2]
+ )
- def _get_reg_ssa(self, operand_index1:int, operand_index2:int) -> SSARegister:
- return SSARegister(ILRegister(self.function.arch,
- architecture.RegisterIndex(self.instr.operands[operand_index1])),
- self.instr.operands[operand_index2])
+ def _get_reg_ssa(self, operand_index1: int, operand_index2: int) -> SSARegister:
+ return SSARegister(
+ ILRegister(self.function.arch, architecture.RegisterIndex(self.instr.operands[operand_index1])),
+ self.instr.operands[operand_index2]
+ )
- def _get_reg_stack_ssa(self, operand_index1:int, operand_index2:int) -> SSARegisterStack:
- reg_stack = ILRegisterStack(self.function.arch,
- architecture.RegisterStackIndex(self.instr.operands[operand_index1]))
+ def _get_reg_stack_ssa(self, operand_index1: int, operand_index2: int) -> SSARegisterStack:
+ reg_stack = ILRegisterStack(
+ self.function.arch, architecture.RegisterStackIndex(self.instr.operands[operand_index1])
+ )
return SSARegisterStack(reg_stack, self.instr.operands[operand_index2])
- def _get_sem_class(self, operand_index:int) -> Optional[ILSemanticFlagClass]:
+ def _get_sem_class(self, operand_index: int) -> Optional[ILSemanticFlagClass]:
if self.instr.operands[operand_index] == 0:
return None
- return ILSemanticFlagClass(self.function.arch,
- architecture.SemanticClassIndex(self.instr.operands[operand_index]))
+ return ILSemanticFlagClass(
+ self.function.arch, architecture.SemanticClassIndex(self.instr.operands[operand_index])
+ )
- def _get_sem_group(self, operand_index:int) -> ILSemanticFlagGroup:
- return ILSemanticFlagGroup(self.function.arch,
- architecture.SemanticGroupIndex(self.instr.operands[operand_index]))
+ def _get_sem_group(self, operand_index: int) -> ILSemanticFlagGroup:
+ return ILSemanticFlagGroup(
+ self.function.arch, architecture.SemanticGroupIndex(self.instr.operands[operand_index])
+ )
- def _get_cond(self, operand_index:int) -> LowLevelILFlagCondition:
+ def _get_cond(self, operand_index: int) -> LowLevelILFlagCondition:
return LowLevelILFlagCondition(self.instr.operands[operand_index])
- def _get_int_list(self, operand_index:int) -> List[int]:
+ def _get_int_list(self, operand_index: int) -> List[int]:
count = ctypes.c_ulonglong()
operand_list = core.BNLowLevelILGetOperandList(self.function.handle, self.expr_index, operand_index, count)
assert operand_list is not None, "core.BNLowLevelILGetOperandList returned None"
- result:List[int] = []
+ result: List[int] = []
try:
for j in range(count.value):
result.append(operand_list[j])
@@ -883,7 +922,7 @@ class LowLevelILInstruction(BaseILInstruction):
finally:
core.BNLowLevelILFreeOperandList(operand_list)
- def _get_expr_list(self, operand_index:int) -> List['LowLevelILInstruction']:
+ def _get_expr_list(self, operand_index: int) -> List['LowLevelILInstruction']:
count = ctypes.c_ulonglong()
operand_list = core.BNLowLevelILGetOperandList(self.function.handle, self.expr_index, operand_index, count)
assert operand_list is not None, "core.BNLowLevelILGetOperandList returned None"
@@ -895,12 +934,12 @@ class LowLevelILInstruction(BaseILInstruction):
finally:
core.BNLowLevelILFreeOperandList(operand_list)
- def _get_reg_or_flag_list(self, operand_index:int) -> List[Union[ILFlag, ILRegister]]:
+ def _get_reg_or_flag_list(self, operand_index: int) -> List[Union[ILFlag, ILRegister]]:
count = ctypes.c_ulonglong()
operand_list = core.BNLowLevelILGetOperandList(self.function.handle, self.expr_index, operand_index, count)
assert operand_list is not None, "core.BNLowLevelILGetOperandList returned None"
- result:List[Union[ILFlag, ILRegister]] = []
+ result: List[Union[ILFlag, ILRegister]] = []
try:
for j in range(count.value):
if (operand_list[j] & (1 << 32)) != 0:
@@ -911,7 +950,7 @@ class LowLevelILInstruction(BaseILInstruction):
finally:
core.BNLowLevelILFreeOperandList(operand_list)
- def _get_reg_ssa_list(self, operand_index:int) -> List[SSARegister]:
+ def _get_reg_ssa_list(self, operand_index: int) -> List[SSARegister]:
count = ctypes.c_ulonglong()
operand_list = core.BNLowLevelILGetOperandList(self.function.handle, self.expr_index, operand_index, count)
assert operand_list is not None, "core.BNLowLevelILGetOperandList returned None"
@@ -919,52 +958,52 @@ class LowLevelILInstruction(BaseILInstruction):
try:
for j in range(count.value // 2):
reg = operand_list[j * 2]
- reg_version = operand_list[(j * 2) + 1]
+ reg_version = operand_list[(j*2) + 1]
result.append(SSARegister(ILRegister(self.function.arch, reg), reg_version))
return result
finally:
core.BNLowLevelILFreeOperandList(operand_list)
- def _get_reg_stack_ssa_list(self, operand_index:int) -> List[SSARegisterStack]:
+ def _get_reg_stack_ssa_list(self, operand_index: int) -> List[SSARegisterStack]:
count = ctypes.c_ulonglong()
operand_list = core.BNLowLevelILGetOperandList(self.function.handle, self.expr_index, operand_index, count)
assert operand_list is not None, "core.BNLowLevelILGetOperandList returned None"
- result:List[SSARegisterStack] = []
+ result: List[SSARegisterStack] = []
try:
for j in range(count.value // 2):
reg_stack = operand_list[j * 2]
- reg_version = operand_list[(j * 2) + 1]
+ reg_version = operand_list[(j*2) + 1]
result.append(SSARegisterStack(ILRegisterStack(self.function.arch, reg_stack), reg_version))
return result
finally:
core.BNLowLevelILFreeOperandList(operand_list)
- def _get_flag_ssa_list(self, operand_index:int) -> List[SSAFlag]:
+ def _get_flag_ssa_list(self, operand_index: int) -> List[SSAFlag]:
count = ctypes.c_ulonglong()
operand_list = core.BNLowLevelILGetOperandList(self.function.handle, self.expr_index, operand_index, count)
assert operand_list is not None, "core.BNLowLevelILGetOperandList returned None"
try:
- result:List[SSAFlag] = []
+ result: List[SSAFlag] = []
for j in range(count.value // 2):
flag = operand_list[j * 2]
- flag_version = operand_list[(j * 2) + 1]
+ flag_version = operand_list[(j*2) + 1]
result.append(SSAFlag(ILFlag(self.function.arch, flag), flag_version))
return result
finally:
core.BNLowLevelILFreeOperandList(operand_list)
- def _get_reg_or_flag_ssa_list(self, operand_index:int) -> List[SSARegisterOrFlag]:
+ def _get_reg_or_flag_ssa_list(self, operand_index: int) -> List[SSARegisterOrFlag]:
count = ctypes.c_ulonglong()
operand_list = core.BNLowLevelILGetOperandList(self.function.handle, self.expr_index, operand_index, count)
assert operand_list is not None, "core.BNLowLevelILGetOperandList returned None"
- result:List[SSARegisterOrFlag] = []
+ result: List[SSARegisterOrFlag] = []
try:
for j in range(count.value // 2):
if (operand_list[j * 2] & (1 << 32)) != 0:
reg_or_flag = ILFlag(self.function.arch, operand_list[j * 2] & 0xffffffff)
else:
reg_or_flag = ILRegister(self.function.arch, operand_list[j * 2] & 0xffffffff)
- reg_version = operand_list[(j * 2) + 1]
+ reg_version = operand_list[(j*2) + 1]
result.append(SSARegisterOrFlag(reg_or_flag, reg_version))
return result
finally:
@@ -973,7 +1012,6 @@ class LowLevelILInstruction(BaseILInstruction):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILBinaryBase(LowLevelILInstruction, BinaryOperation):
-
@property
def left(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -994,7 +1032,6 @@ class LowLevelILComparisonBase(LowLevelILBinaryBase):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILCarryBase(LowLevelILInstruction, Carry):
-
@property
def left(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -1014,7 +1051,6 @@ class LowLevelILCarryBase(LowLevelILInstruction, Carry):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILUnaryBase(LowLevelILInstruction, UnaryOperation):
-
@property
def src(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -1026,29 +1062,28 @@ class LowLevelILUnaryBase(LowLevelILInstruction, UnaryOperation):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILConstantBase(LowLevelILInstruction, Constant):
-
def __int__(self):
return self.constant
def __bool__(self):
return self.constant != 0
- def __eq__(self, other:'LowLevelILConstantBase'):
+ def __eq__(self, other: 'LowLevelILConstantBase'):
return self.constant == other.constant
- def __ne__(self, other:'LowLevelILConstantBase'):
+ def __ne__(self, other: 'LowLevelILConstantBase'):
return self.constant != other.constant
- def __lt__(self, other:'LowLevelILConstantBase'):
+ def __lt__(self, other: 'LowLevelILConstantBase'):
return self.constant < other.constant
- def __gt__(self, other:'LowLevelILConstantBase'):
+ def __gt__(self, other: 'LowLevelILConstantBase'):
return self.constant > other.constant
- def __le__(self, other:'LowLevelILConstantBase'):
+ def __le__(self, other: 'LowLevelILConstantBase'):
return self.constant <= other.constant
- def __ge__(self, other:'LowLevelILConstantBase'):
+ def __ge__(self, other: 'LowLevelILConstantBase'):
return self.constant >= other.constant
def __hash__(self):
@@ -1125,7 +1160,6 @@ class LowLevelILLowPart(LowLevelILUnaryBase, Arithmetic):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILJump(LowLevelILInstruction, Terminal):
-
@property
def dest(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -1137,7 +1171,6 @@ class LowLevelILJump(LowLevelILInstruction, Terminal):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILCall(LowLevelILInstruction, Localcall):
-
@property
def dest(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -1149,7 +1182,6 @@ class LowLevelILCall(LowLevelILInstruction, Localcall):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILTailcall(LowLevelILInstruction, Tailcall):
-
@property
def dest(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -1161,7 +1193,6 @@ class LowLevelILTailcall(LowLevelILInstruction, Tailcall):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILRet(LowLevelILInstruction, Return):
-
@property
def dest(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -1173,7 +1204,6 @@ class LowLevelILRet(LowLevelILInstruction, Return):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILUnimplMem(LowLevelILInstruction, Memory):
-
@property
def src(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -1185,7 +1215,6 @@ class LowLevelILUnimplMem(LowLevelILInstruction, Memory):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILFsqrt(LowLevelILInstruction, FloatingPoint, Arithmetic):
-
@property
def src(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -1197,7 +1226,6 @@ class LowLevelILFsqrt(LowLevelILInstruction, FloatingPoint, Arithmetic):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILFneg(LowLevelILInstruction, FloatingPoint, Arithmetic):
-
@property
def src(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -1209,7 +1237,6 @@ class LowLevelILFneg(LowLevelILInstruction, FloatingPoint, Arithmetic):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILFabs(LowLevelILInstruction, FloatingPoint, Arithmetic):
-
@property
def src(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -1221,7 +1248,6 @@ class LowLevelILFabs(LowLevelILInstruction, FloatingPoint, Arithmetic):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILFloatToInt(LowLevelILInstruction, FloatingPoint, Arithmetic):
-
@property
def src(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -1233,7 +1259,6 @@ class LowLevelILFloatToInt(LowLevelILInstruction, FloatingPoint, Arithmetic):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILIntToFloat(LowLevelILInstruction, FloatingPoint, Arithmetic):
-
@property
def src(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -1245,7 +1270,6 @@ class LowLevelILIntToFloat(LowLevelILInstruction, FloatingPoint, Arithmetic):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILFloatConv(LowLevelILInstruction, FloatingPoint, Arithmetic):
-
@property
def src(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -1257,7 +1281,6 @@ class LowLevelILFloatConv(LowLevelILInstruction, FloatingPoint, Arithmetic):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILRoundToInt(LowLevelILInstruction, FloatingPoint, Arithmetic):
-
@property
def src(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -1269,7 +1292,6 @@ class LowLevelILRoundToInt(LowLevelILInstruction, FloatingPoint, Arithmetic):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILFloor(LowLevelILInstruction, FloatingPoint, Arithmetic):
-
@property
def src(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -1281,7 +1303,6 @@ class LowLevelILFloor(LowLevelILInstruction, FloatingPoint, Arithmetic):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILCeil(LowLevelILInstruction, FloatingPoint, Arithmetic):
-
@property
def src(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -1293,7 +1314,6 @@ class LowLevelILCeil(LowLevelILInstruction, FloatingPoint, Arithmetic):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILFtrunc(LowLevelILInstruction, FloatingPoint, Arithmetic):
-
@property
def src(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -1305,7 +1325,6 @@ class LowLevelILFtrunc(LowLevelILInstruction, FloatingPoint, Arithmetic):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILLoad(LowLevelILInstruction, Load):
-
@property
def src(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -1317,7 +1336,6 @@ class LowLevelILLoad(LowLevelILInstruction, Load):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILPush(LowLevelILInstruction, StackOperation):
-
@property
def src(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -1329,7 +1347,6 @@ class LowLevelILPush(LowLevelILInstruction, StackOperation):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILReg(LowLevelILInstruction):
-
@property
def src(self) -> ILRegister:
return self._get_reg(0)
@@ -1341,7 +1358,6 @@ class LowLevelILReg(LowLevelILInstruction):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILRegStackPop(LowLevelILInstruction, RegisterStack):
-
@property
def stack(self) -> ILRegisterStack:
return self._get_reg_stack(0)
@@ -1353,7 +1369,6 @@ class LowLevelILRegStackPop(LowLevelILInstruction, RegisterStack):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILRegStackFreeReg(LowLevelILInstruction, RegisterStack):
-
@property
def dest(self) -> ILRegister:
return self._get_reg(0)
@@ -1375,7 +1390,6 @@ class LowLevelILConstPtr(LowLevelILConstantBase):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILFloatConst(LowLevelILConstantBase, FloatingPoint):
-
@property
def constant(self) -> Union[int, float]:
return self._get_float(0)
@@ -1387,7 +1401,6 @@ class LowLevelILFloatConst(LowLevelILConstantBase, FloatingPoint):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILFlag(LowLevelILInstruction):
-
@property
def src(self) -> ILFlag:
return self._get_flag(0)
@@ -1399,7 +1412,6 @@ class LowLevelILFlag(LowLevelILInstruction):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILGoto(LowLevelILInstruction, Terminal):
-
@property
def dest(self) -> int:
return self._get_int(0)
@@ -1411,7 +1423,6 @@ class LowLevelILGoto(LowLevelILInstruction, Terminal):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILFlagGroup(LowLevelILInstruction):
-
@property
def semantic_group(self) -> ILSemanticFlagGroup:
return self._get_sem_group(0)
@@ -1423,7 +1434,6 @@ class LowLevelILFlagGroup(LowLevelILInstruction):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILBoolToInt(LowLevelILInstruction):
-
@property
def src(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -1435,7 +1445,6 @@ class LowLevelILBoolToInt(LowLevelILInstruction):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILTrap(LowLevelILInstruction, Terminal):
-
@property
def vector(self) -> int:
return self._get_int(0)
@@ -1447,7 +1456,6 @@ class LowLevelILTrap(LowLevelILInstruction, Terminal):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILRegSplitDestSsa(LowLevelILInstruction, SSA):
-
@property
def dest(self) -> SSARegister:
return self._get_reg_ssa(0, 1)
@@ -1459,7 +1467,6 @@ class LowLevelILRegSplitDestSsa(LowLevelILInstruction, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILRegStackDestSsa(LowLevelILInstruction, RegisterStack, SSA):
-
@property
def dest(self) -> SSARegisterStack:
return self._get_reg_stack_ssa(0, 1)
@@ -1475,7 +1482,6 @@ class LowLevelILRegStackDestSsa(LowLevelILInstruction, RegisterStack, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILRegSsa(LowLevelILInstruction, SSA):
-
@property
def src(self) -> SSARegister:
return self._get_reg_ssa(0, 1)
@@ -1487,7 +1493,6 @@ class LowLevelILRegSsa(LowLevelILInstruction, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILFlagSsa(LowLevelILInstruction, SSA):
-
@property
def src(self) -> SSAFlag:
return self._get_flag_ssa(0, 1)
@@ -1499,7 +1504,6 @@ class LowLevelILFlagSsa(LowLevelILInstruction, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILCallParam(LowLevelILInstruction, SSA):
-
@property
def src(self) -> List['LowLevelILInstruction']:
return self._get_expr_list(0)
@@ -1511,7 +1515,6 @@ class LowLevelILCallParam(LowLevelILInstruction, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILMemPhi(LowLevelILInstruction, Memory, Phi):
-
@property
def dest_memory(self) -> int:
return self._get_int(0)
@@ -1527,7 +1530,6 @@ class LowLevelILMemPhi(LowLevelILInstruction, Memory, Phi):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILSetReg(LowLevelILInstruction, SetReg):
-
@property
def dest(self) -> ILRegister:
return self._get_reg(0)
@@ -1543,7 +1545,6 @@ class LowLevelILSetReg(LowLevelILInstruction, SetReg):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILRegStackPush(LowLevelILInstruction, RegisterStack):
-
@property
def stack(self) -> ILRegisterStack:
return self._get_reg_stack(0)
@@ -1559,7 +1560,6 @@ class LowLevelILRegStackPush(LowLevelILInstruction, RegisterStack):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILSetFlag(LowLevelILInstruction):
-
@property
def dest(self) -> ILFlag:
return self._get_flag(0)
@@ -1575,7 +1575,6 @@ class LowLevelILSetFlag(LowLevelILInstruction):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILStore(LowLevelILInstruction, Store):
-
@property
def dest(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -1591,7 +1590,6 @@ class LowLevelILStore(LowLevelILInstruction, Store):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILRegSplit(LowLevelILInstruction):
-
@property
def hi(self) -> ILRegister:
return self._get_reg(0)
@@ -1607,7 +1605,6 @@ class LowLevelILRegSplit(LowLevelILInstruction):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILRegStackRel(LowLevelILInstruction, RegisterStack):
-
@property
def stack(self) -> ILRegisterStack:
return self._get_reg_stack(0)
@@ -1623,7 +1620,6 @@ class LowLevelILRegStackRel(LowLevelILInstruction, RegisterStack):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILRegStackFreeRel(LowLevelILInstruction, RegisterStack):
-
@property
def stack(self) -> ILRegisterStack:
return self._get_reg_stack(0)
@@ -1639,7 +1635,6 @@ class LowLevelILRegStackFreeRel(LowLevelILInstruction, RegisterStack):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILExternPtr(LowLevelILConstantBase):
-
@property
def constant(self) -> int:
return self._get_int(0)
@@ -1655,7 +1650,6 @@ class LowLevelILExternPtr(LowLevelILConstantBase):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILFlagBit(LowLevelILInstruction):
-
@property
def src(self) -> ILFlag:
return self._get_flag(0)
@@ -1795,7 +1789,7 @@ class LowLevelILCmpUlt(LowLevelILComparisonBase):
@dataclass(frozen=True, repr=False, eq=False)
-class LowLevelILCmpSle(LowLevelILComparisonBase,Signed):
+class LowLevelILCmpSle(LowLevelILComparisonBase, Signed):
pass
@@ -1891,7 +1885,6 @@ class LowLevelILFcmpUo(LowLevelILInstruction, Comparison, FloatingPoint):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILJumpTo(LowLevelILInstruction):
-
@property
def dest(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -1907,7 +1900,6 @@ class LowLevelILJumpTo(LowLevelILInstruction):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILFlagCond(LowLevelILInstruction):
-
@property
def condition(self) -> LowLevelILFlagCondition:
return self._get_cond(0)
@@ -1928,7 +1920,6 @@ class LowLevelILAddOverflow(LowLevelILBinaryBase, Arithmetic):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILSetRegSsa(LowLevelILInstruction, SetReg, SSA):
-
@property
def dest(self) -> SSARegister:
return self._get_reg_ssa(0, 1)
@@ -1944,7 +1935,6 @@ class LowLevelILSetRegSsa(LowLevelILInstruction, SetReg, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILRegSsaPartial(LowLevelILInstruction, SetReg, SSA):
-
@property
def full_reg(self) -> SSARegister:
return self._get_reg_ssa(0, 1)
@@ -1960,7 +1950,6 @@ class LowLevelILRegSsaPartial(LowLevelILInstruction, SetReg, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILRegSplitSsa(LowLevelILInstruction, SetReg, SSA):
-
@property
def hi(self) -> SSARegister:
return self._get_reg_ssa(0, 1)
@@ -1976,7 +1965,6 @@ class LowLevelILRegSplitSsa(LowLevelILInstruction, SetReg, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILRegStackAbsSsa(LowLevelILInstruction, RegisterStack, SSA):
-
@property
def stack(self) -> SSARegisterStack:
return self._get_reg_stack_ssa(0, 1)
@@ -1992,7 +1980,6 @@ class LowLevelILRegStackAbsSsa(LowLevelILInstruction, RegisterStack, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILRegStackFreeAbsSsa(LowLevelILInstruction, RegisterStack):
-
@property
def stack(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -2008,7 +1995,6 @@ class LowLevelILRegStackFreeAbsSsa(LowLevelILInstruction, RegisterStack):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILSetFlagSsa(LowLevelILInstruction, SSA):
-
@property
def dest(self) -> SSAFlag:
return self._get_flag_ssa(0, 1)
@@ -2024,7 +2010,6 @@ class LowLevelILSetFlagSsa(LowLevelILInstruction, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILFlagBitSsa(LowLevelILInstruction, SSA):
-
@property
def src(self) -> SSAFlag:
return self._get_flag_ssa(0, 1)
@@ -2040,7 +2025,6 @@ class LowLevelILFlagBitSsa(LowLevelILInstruction, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILCallOutputSsa(LowLevelILInstruction, SSA):
-
@property
def dest_memory(self) -> int:
return self._get_int(0)
@@ -2056,7 +2040,6 @@ class LowLevelILCallOutputSsa(LowLevelILInstruction, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILCallStackSsa(LowLevelILInstruction, SSA):
-
@property
def src(self) -> SSARegister:
return self._get_reg_ssa(0, 1)
@@ -2072,7 +2055,6 @@ class LowLevelILCallStackSsa(LowLevelILInstruction, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILLoadSsa(LowLevelILInstruction, Load, SSA):
-
@property
def src(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -2088,7 +2070,6 @@ class LowLevelILLoadSsa(LowLevelILInstruction, Load, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILRegPhi(LowLevelILInstruction, Phi):
-
@property
def dest(self) -> SSARegister:
return self._get_reg_ssa(0, 1)
@@ -2104,7 +2085,6 @@ class LowLevelILRegPhi(LowLevelILInstruction, Phi):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILRegStackPhi(LowLevelILInstruction, RegisterStack, Phi):
-
@property
def dest(self) -> SSARegisterStack:
return self._get_reg_stack_ssa(0, 1)
@@ -2120,7 +2100,6 @@ class LowLevelILRegStackPhi(LowLevelILInstruction, RegisterStack, Phi):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILFlagPhi(LowLevelILInstruction, Phi):
-
@property
def dest(self) -> SSAFlag:
return self._get_flag_ssa(0, 1)
@@ -2136,7 +2115,6 @@ class LowLevelILFlagPhi(LowLevelILInstruction, Phi):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILSetRegSplit(LowLevelILInstruction, SetReg):
-
@property
def hi(self) -> ILRegister:
return self._get_reg(0)
@@ -2156,7 +2134,6 @@ class LowLevelILSetRegSplit(LowLevelILInstruction, SetReg):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILSetRegStackRel(LowLevelILInstruction, RegisterStack):
-
@property
def stack(self) -> ILRegisterStack:
return self._get_reg_stack(0)
@@ -2196,7 +2173,6 @@ class LowLevelILRrc(LowLevelILCarryBase):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILCallStackAdjust(LowLevelILInstruction, Localcall):
-
@property
def dest(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -2216,7 +2192,6 @@ class LowLevelILCallStackAdjust(LowLevelILInstruction, Localcall):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILIf(LowLevelILInstruction, ControlFlow):
-
@property
def condition(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -2236,7 +2211,6 @@ class LowLevelILIf(LowLevelILInstruction, ControlFlow):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILIntrinsic(LowLevelILInstruction):
-
@property
def output(self) -> List[Union[ILFlag, ILRegister]]:
return self._get_reg_or_flag_list(0)
@@ -2256,7 +2230,6 @@ class LowLevelILIntrinsic(LowLevelILInstruction):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILIntrinsicSsa(LowLevelILInstruction, SSA):
-
@property
def output(self) -> List[SSARegisterOrFlag]:
return self._get_reg_or_flag_ssa_list(0)
@@ -2276,7 +2249,6 @@ class LowLevelILIntrinsicSsa(LowLevelILInstruction, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILSetRegSsaPartial(LowLevelILInstruction, SetReg, SSA):
-
@property
def full_reg(self) -> SSARegister:
return self._get_reg_ssa(0, 1)
@@ -2296,7 +2268,6 @@ class LowLevelILSetRegSsaPartial(LowLevelILInstruction, SetReg, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILSetRegSplitSsa(LowLevelILInstruction, SetReg, SSA):
-
@property
def hi(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -2335,7 +2306,6 @@ class LowLevelILSetRegStackAbsSsa(LowLevelILInstruction, RegisterStack, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILRegStackRelSsa(LowLevelILInstruction, RegisterStack, SSA):
-
@property
def stack(self) -> SSARegisterStack:
return self._get_reg_stack_ssa(0, 1)
@@ -2355,7 +2325,6 @@ class LowLevelILRegStackRelSsa(LowLevelILInstruction, RegisterStack, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILRegStackFreeRelSsa(LowLevelILInstruction, RegisterStack, SSA):
-
@property
def stack(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -2375,7 +2344,6 @@ class LowLevelILRegStackFreeRelSsa(LowLevelILInstruction, RegisterStack, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILSyscallSsa(LowLevelILInstruction, Syscall, SSA):
-
@property
def output(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -2395,7 +2363,6 @@ class LowLevelILSyscallSsa(LowLevelILInstruction, Syscall, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILSetRegStackRelSsa(LowLevelILInstruction, RegisterStack, SSA):
-
@property
def stack(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -2419,7 +2386,6 @@ class LowLevelILSetRegStackRelSsa(LowLevelILInstruction, RegisterStack, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILCallSsa(LowLevelILInstruction, Localcall, SSA):
-
@property
def output(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -2443,7 +2409,6 @@ class LowLevelILCallSsa(LowLevelILInstruction, Localcall, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILTailcallSsa(LowLevelILInstruction, Tailcall, SSA, Terminal):
-
@property
def output(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -2467,7 +2432,6 @@ class LowLevelILTailcallSsa(LowLevelILInstruction, Tailcall, SSA, Terminal):
@dataclass(frozen=True, repr=False, eq=False)
class LowLevelILStoreSsa(LowLevelILInstruction, Store, SSA):
-
@property
def dest(self) -> LowLevelILInstruction:
return self._get_expr(0)
@@ -2490,141 +2454,141 @@ class LowLevelILStoreSsa(LowLevelILInstruction, Store, SSA):
ILInstruction:Dict[LowLevelILOperation, LowLevelILInstruction] = { # type: ignore
- LowLevelILOperation.LLIL_NOP: LowLevelILNop, # [],
- LowLevelILOperation.LLIL_SET_REG: LowLevelILSetReg, # [("dest", "reg"), ("src", "expr")],
- LowLevelILOperation.LLIL_SET_REG_SPLIT: LowLevelILSetRegSplit, # [("hi", "reg"), ("lo", "reg"), ("src", "expr")],
- LowLevelILOperation.LLIL_SET_REG_STACK_REL: LowLevelILSetRegStackRel, # [("stack", "reg_stack"), ("dest", "expr"), ("src", "expr")],
- LowLevelILOperation.LLIL_REG_STACK_PUSH: LowLevelILRegStackPush, # [("stack", "reg_stack"), ("src", "expr")],
- LowLevelILOperation.LLIL_SET_FLAG: LowLevelILSetFlag, # [("dest", "flag"), ("src", "expr")],
- LowLevelILOperation.LLIL_LOAD: LowLevelILLoad, # [("src", "expr")],
- LowLevelILOperation.LLIL_STORE: LowLevelILStore, # [("dest", "expr"), ("src", "expr")],
- LowLevelILOperation.LLIL_PUSH: LowLevelILPush, # [("src", "expr")],
- LowLevelILOperation.LLIL_POP: LowLevelILPop, # [],
- LowLevelILOperation.LLIL_REG: LowLevelILReg, # [("src", "reg")],
- LowLevelILOperation.LLIL_REG_SPLIT: LowLevelILRegSplit, # [("hi", "reg"), ("lo", "reg")],
- LowLevelILOperation.LLIL_REG_STACK_REL: LowLevelILRegStackRel, # [("stack", "reg_stack"), ("src", "expr")],
- LowLevelILOperation.LLIL_REG_STACK_POP: LowLevelILRegStackPop, # [("stack", "reg_stack")],
- LowLevelILOperation.LLIL_REG_STACK_FREE_REG: LowLevelILRegStackFreeReg, # [("dest", "reg")],
- LowLevelILOperation.LLIL_REG_STACK_FREE_REL: LowLevelILRegStackFreeRel, # [("stack", "reg_stack"), ("dest", "expr")],
- LowLevelILOperation.LLIL_CONST: LowLevelILConst, # [("constant", "int")],
- LowLevelILOperation.LLIL_CONST_PTR: LowLevelILConstPtr, # [("constant", "int")],
- LowLevelILOperation.LLIL_EXTERN_PTR: LowLevelILExternPtr, # [("constant", "int"), ("offset", "int")],
- LowLevelILOperation.LLIL_FLOAT_CONST: LowLevelILFloatConst, # [("constant", "float")],
- LowLevelILOperation.LLIL_FLAG: LowLevelILFlag, # [("src", "flag")],
- LowLevelILOperation.LLIL_FLAG_BIT: LowLevelILFlagBit, # [("src", "flag"), ("bit", "int")],
- LowLevelILOperation.LLIL_ADD: LowLevelILAdd, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_ADC: LowLevelILAdc, # [("left", "expr"), ("right", "expr"), ("carry", "expr")],
- LowLevelILOperation.LLIL_SUB: LowLevelILSub, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_SBB: LowLevelILSbb, # [("left", "expr"), ("right", "expr"), ("carry", "expr")],
- LowLevelILOperation.LLIL_AND: LowLevelILAnd, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_OR: LowLevelILOr, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_XOR: LowLevelILXor, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_LSL: LowLevelILLsl, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_LSR: LowLevelILLsr, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_ASR: LowLevelILAsr, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_ROL: LowLevelILRol, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_RLC: LowLevelILRlc, # [("left", "expr"), ("right", "expr"), ("carry", "expr")],
- LowLevelILOperation.LLIL_ROR: LowLevelILRor, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_RRC: LowLevelILRrc, # [("left", "expr"), ("right", "expr"), ("carry", "expr")],
- LowLevelILOperation.LLIL_MUL: LowLevelILMul, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_MULU_DP: LowLevelILMuluDp, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_MULS_DP: LowLevelILMulsDp, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_DIVU: LowLevelILDivu, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_DIVU_DP: LowLevelILDivuDp, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_DIVS: LowLevelILDivs, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_DIVS_DP: LowLevelILDivsDp, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_MODU: LowLevelILModu, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_MODU_DP: LowLevelILModuDp, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_MODS: LowLevelILMods, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_MODS_DP: LowLevelILModsDp, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_NEG: LowLevelILNeg, # [("src", "expr")],
- LowLevelILOperation.LLIL_NOT: LowLevelILNot, # [("src", "expr")],
- LowLevelILOperation.LLIL_SX: LowLevelILSx, # [("src", "expr")],
- LowLevelILOperation.LLIL_ZX: LowLevelILZx, # [("src", "expr")],
- LowLevelILOperation.LLIL_LOW_PART: LowLevelILLowPart, # [("src", "expr")],
- LowLevelILOperation.LLIL_JUMP: LowLevelILJump, # [("dest", "expr")],
- LowLevelILOperation.LLIL_JUMP_TO: LowLevelILJumpTo, # [("dest", "expr"), ("targets", "target_map")],
- LowLevelILOperation.LLIL_CALL: LowLevelILCall, # [("dest", "expr")],
- LowLevelILOperation.LLIL_CALL_STACK_ADJUST: LowLevelILCallStackAdjust, # [("dest", "expr"), ("stack_adjustment", "int"), ("reg_stack_adjustments", "reg_stack_adjust")],
- LowLevelILOperation.LLIL_TAILCALL: LowLevelILTailcall, # [("dest", "expr")],
- LowLevelILOperation.LLIL_RET: LowLevelILRet, # [("dest", "expr")],
- LowLevelILOperation.LLIL_NORET: LowLevelILNoret, # [],
- LowLevelILOperation.LLIL_IF: LowLevelILIf, # [("condition", "expr"), ("true", "int"), ("false", "int")],
- LowLevelILOperation.LLIL_GOTO: LowLevelILGoto, # [("dest", "int")],
- LowLevelILOperation.LLIL_FLAG_COND: LowLevelILFlagCond, # [("condition", "cond"), ("semantic_class", "sem_class")],
- LowLevelILOperation.LLIL_FLAG_GROUP: LowLevelILFlagGroup, # [("semantic_group", "sem_group")],
- LowLevelILOperation.LLIL_CMP_E: LowLevelILCmpE, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_CMP_NE: LowLevelILCmpNe, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_CMP_SLT: LowLevelILCmpSlt, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_CMP_ULT: LowLevelILCmpUlt, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_CMP_SLE: LowLevelILCmpSle, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_CMP_ULE: LowLevelILCmpUle, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_CMP_SGE: LowLevelILCmpSge, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_CMP_UGE: LowLevelILCmpUge, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_CMP_SGT: LowLevelILCmpSgt, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_CMP_UGT: LowLevelILCmpUgt, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_TEST_BIT: LowLevelILTestBit, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_BOOL_TO_INT: LowLevelILBoolToInt, # [("src", "expr")],
- LowLevelILOperation.LLIL_ADD_OVERFLOW: LowLevelILAddOverflow, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_SYSCALL: LowLevelILSyscall, # [],
- LowLevelILOperation.LLIL_INTRINSIC: LowLevelILIntrinsic, # [("output", "reg_or_flag_list"), ("intrinsic", "intrinsic"), ("param", "expr")],
- LowLevelILOperation.LLIL_INTRINSIC_SSA: LowLevelILIntrinsicSsa, # [("output", "reg_or_flag_ssa_list"), ("intrinsic", "intrinsic"), ("param", "expr")],
- LowLevelILOperation.LLIL_BP: LowLevelILBp, # [],
- LowLevelILOperation.LLIL_TRAP: LowLevelILTrap, # [("vector", "int")],
- LowLevelILOperation.LLIL_UNDEF: LowLevelILUndef, # [],
- LowLevelILOperation.LLIL_UNIMPL: LowLevelILUnimpl, # [],
- LowLevelILOperation.LLIL_UNIMPL_MEM: LowLevelILUnimplMem, # [("src", "expr")],
- LowLevelILOperation.LLIL_FADD: LowLevelILFadd, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_FSUB: LowLevelILFsub, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_FMUL: LowLevelILFmul, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_FDIV: LowLevelILFdiv, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_FSQRT: LowLevelILFsqrt, # [("src", "expr")],
- LowLevelILOperation.LLIL_FNEG: LowLevelILFneg, # [("src", "expr")],
- LowLevelILOperation.LLIL_FABS: LowLevelILFabs, # [("src", "expr")],
- LowLevelILOperation.LLIL_FLOAT_TO_INT: LowLevelILFloatToInt, # [("src", "expr")],
- LowLevelILOperation.LLIL_INT_TO_FLOAT: LowLevelILIntToFloat, # [("src", "expr")],
- LowLevelILOperation.LLIL_FLOAT_CONV: LowLevelILFloatConv, # [("src", "expr")],
- LowLevelILOperation.LLIL_ROUND_TO_INT: LowLevelILRoundToInt, # [("src", "expr")],
- LowLevelILOperation.LLIL_FLOOR: LowLevelILFloor, # [("src", "expr")],
- LowLevelILOperation.LLIL_CEIL: LowLevelILCeil, # [("src", "expr")],
- LowLevelILOperation.LLIL_FTRUNC: LowLevelILFtrunc, # [("src", "expr")],
- LowLevelILOperation.LLIL_FCMP_E: LowLevelILFcmpE, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_FCMP_NE: LowLevelILFcmpNe, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_FCMP_LT: LowLevelILFcmpLt, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_FCMP_LE: LowLevelILFcmpLe, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_FCMP_GE: LowLevelILFcmpGe, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_FCMP_GT: LowLevelILFcmpGt, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_FCMP_O: LowLevelILFcmpO, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_FCMP_UO: LowLevelILFcmpUo, # [("left", "expr"), ("right", "expr")],
- LowLevelILOperation.LLIL_SET_REG_SSA: LowLevelILSetRegSsa, # [("dest", "reg_ssa"), ("src", "expr")],
- LowLevelILOperation.LLIL_SET_REG_SSA_PARTIAL: LowLevelILSetRegSsaPartial, # [("full_reg", "reg_ssa"), ("dest", "reg"), ("src", "expr")],
- LowLevelILOperation.LLIL_SET_REG_SPLIT_SSA: LowLevelILSetRegSplitSsa, # [("hi", "expr"), ("lo", "expr"), ("src", "expr")],
- LowLevelILOperation.LLIL_SET_REG_STACK_REL_SSA: LowLevelILSetRegStackRelSsa, # [("stack", "expr"), ("dest", "expr"), ("top", "expr"), ("src", "expr")],
- LowLevelILOperation.LLIL_SET_REG_STACK_ABS_SSA: LowLevelILSetRegStackAbsSsa, # [("stack", "expr"), ("dest", "reg"), ("src", "expr")],
- LowLevelILOperation.LLIL_REG_SPLIT_DEST_SSA: LowLevelILRegSplitDestSsa, # [("dest", "reg_ssa")],
- LowLevelILOperation.LLIL_REG_STACK_DEST_SSA: LowLevelILRegStackDestSsa, # [("src", "reg_stack_ssa_dest_and_src")],
- LowLevelILOperation.LLIL_REG_SSA: LowLevelILRegSsa, # [("src", "reg_ssa")],
- LowLevelILOperation.LLIL_REG_SSA_PARTIAL: LowLevelILRegSsaPartial, # [("full_reg", "reg_ssa"), ("src", "reg")],
- LowLevelILOperation.LLIL_REG_SPLIT_SSA: LowLevelILRegSplitSsa, # [("hi", "reg_ssa"), ("lo", "reg_ssa")],
- LowLevelILOperation.LLIL_REG_STACK_REL_SSA: LowLevelILRegStackRelSsa, # [("stack", "reg_stack_ssa"), ("src", "expr"), ("top", "expr")],
- LowLevelILOperation.LLIL_REG_STACK_ABS_SSA: LowLevelILRegStackAbsSsa, # [("stack", "reg_stack_ssa"), ("src", "reg")],
- LowLevelILOperation.LLIL_REG_STACK_FREE_REL_SSA: LowLevelILRegStackFreeRelSsa, # [("stack", "expr"), ("dest", "expr"), ("top", "expr")],
- LowLevelILOperation.LLIL_REG_STACK_FREE_ABS_SSA: LowLevelILRegStackFreeAbsSsa, # [("stack", "expr"), ("dest", "reg")],
- LowLevelILOperation.LLIL_SET_FLAG_SSA: LowLevelILSetFlagSsa, # [("dest", "flag_ssa"), ("src", "expr")],
- LowLevelILOperation.LLIL_FLAG_SSA: LowLevelILFlagSsa, # [("src", "flag_ssa")],
- LowLevelILOperation.LLIL_FLAG_BIT_SSA: LowLevelILFlagBitSsa, # [("src", "flag_ssa"), ("bit", "int")],
- LowLevelILOperation.LLIL_CALL_SSA: LowLevelILCallSsa, # [("output", "expr"), ("dest", "expr"), ("stack", "expr"), ("param", "expr")],
- LowLevelILOperation.LLIL_SYSCALL_SSA: LowLevelILSyscallSsa, # [("output", "expr"), ("stack", "expr"), ("param", "expr")],
- LowLevelILOperation.LLIL_TAILCALL_SSA: LowLevelILTailcallSsa, # [("output", "expr"), ("dest", "expr"), ("stack", "expr"), ("param", "expr")],
- LowLevelILOperation.LLIL_CALL_OUTPUT_SSA: LowLevelILCallOutputSsa, # [("dest_memory", "int"), ("dest", "reg_ssa_list")],
- LowLevelILOperation.LLIL_CALL_STACK_SSA: LowLevelILCallStackSsa, # [("src", "reg_ssa"), ("src_memory", "int")],
- LowLevelILOperation.LLIL_CALL_PARAM: LowLevelILCallParam, # [("src", "expr_list")],
- LowLevelILOperation.LLIL_LOAD_SSA: LowLevelILLoadSsa, # [("src", "expr"), ("src_memory", "int")],
- LowLevelILOperation.LLIL_STORE_SSA: LowLevelILStoreSsa, # [("dest", "expr"), ("dest_memory", "int"), ("src_memory", "int"), ("src", "expr")],
- LowLevelILOperation.LLIL_REG_PHI: LowLevelILRegPhi, # [("dest", "reg_ssa"), ("src", "reg_ssa_list")],
- LowLevelILOperation.LLIL_REG_STACK_PHI: LowLevelILRegStackPhi, # [("dest", "reg_stack_ssa"), ("src", "reg_stack_ssa_list")],
- LowLevelILOperation.LLIL_FLAG_PHI: LowLevelILFlagPhi, # [("dest", "flag_ssa"), ("src", "flag_ssa_list")],
- LowLevelILOperation.LLIL_MEM_PHI: LowLevelILMemPhi, # [("dest_memory", "int"), ("src_memory", "int_list")]
+ LowLevelILOperation.LLIL_NOP: LowLevelILNop, # [],
+ LowLevelILOperation.LLIL_SET_REG: LowLevelILSetReg, # [("dest", "reg"), ("src", "expr")],
+ LowLevelILOperation.LLIL_SET_REG_SPLIT: LowLevelILSetRegSplit, # [("hi", "reg"), ("lo", "reg"), ("src", "expr")],
+ LowLevelILOperation.LLIL_SET_REG_STACK_REL: LowLevelILSetRegStackRel, # [("stack", "reg_stack"), ("dest", "expr"), ("src", "expr")],
+ LowLevelILOperation.LLIL_REG_STACK_PUSH: LowLevelILRegStackPush, # [("stack", "reg_stack"), ("src", "expr")],
+ LowLevelILOperation.LLIL_SET_FLAG: LowLevelILSetFlag, # [("dest", "flag"), ("src", "expr")],
+ LowLevelILOperation.LLIL_LOAD: LowLevelILLoad, # [("src", "expr")],
+ LowLevelILOperation.LLIL_STORE: LowLevelILStore, # [("dest", "expr"), ("src", "expr")],
+ LowLevelILOperation.LLIL_PUSH: LowLevelILPush, # [("src", "expr")],
+ LowLevelILOperation.LLIL_POP: LowLevelILPop, # [],
+ LowLevelILOperation.LLIL_REG: LowLevelILReg, # [("src", "reg")],
+ LowLevelILOperation.LLIL_REG_SPLIT: LowLevelILRegSplit, # [("hi", "reg"), ("lo", "reg")],
+ LowLevelILOperation.LLIL_REG_STACK_REL: LowLevelILRegStackRel, # [("stack", "reg_stack"), ("src", "expr")],
+ LowLevelILOperation.LLIL_REG_STACK_POP: LowLevelILRegStackPop, # [("stack", "reg_stack")],
+ LowLevelILOperation.LLIL_REG_STACK_FREE_REG: LowLevelILRegStackFreeReg, # [("dest", "reg")],
+ LowLevelILOperation.LLIL_REG_STACK_FREE_REL: LowLevelILRegStackFreeRel, # [("stack", "reg_stack"), ("dest", "expr")],
+ LowLevelILOperation.LLIL_CONST: LowLevelILConst, # [("constant", "int")],
+ LowLevelILOperation.LLIL_CONST_PTR: LowLevelILConstPtr, # [("constant", "int")],
+ LowLevelILOperation.LLIL_EXTERN_PTR: LowLevelILExternPtr, # [("constant", "int"), ("offset", "int")],
+ LowLevelILOperation.LLIL_FLOAT_CONST: LowLevelILFloatConst, # [("constant", "float")],
+ LowLevelILOperation.LLIL_FLAG: LowLevelILFlag, # [("src", "flag")],
+ LowLevelILOperation.LLIL_FLAG_BIT: LowLevelILFlagBit, # [("src", "flag"), ("bit", "int")],
+ LowLevelILOperation.LLIL_ADD: LowLevelILAdd, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_ADC: LowLevelILAdc, # [("left", "expr"), ("right", "expr"), ("carry", "expr")],
+ LowLevelILOperation.LLIL_SUB: LowLevelILSub, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_SBB: LowLevelILSbb, # [("left", "expr"), ("right", "expr"), ("carry", "expr")],
+ LowLevelILOperation.LLIL_AND: LowLevelILAnd, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_OR: LowLevelILOr, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_XOR: LowLevelILXor, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_LSL: LowLevelILLsl, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_LSR: LowLevelILLsr, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_ASR: LowLevelILAsr, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_ROL: LowLevelILRol, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_RLC: LowLevelILRlc, # [("left", "expr"), ("right", "expr"), ("carry", "expr")],
+ LowLevelILOperation.LLIL_ROR: LowLevelILRor, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_RRC: LowLevelILRrc, # [("left", "expr"), ("right", "expr"), ("carry", "expr")],
+ LowLevelILOperation.LLIL_MUL: LowLevelILMul, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_MULU_DP: LowLevelILMuluDp, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_MULS_DP: LowLevelILMulsDp, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_DIVU: LowLevelILDivu, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_DIVU_DP: LowLevelILDivuDp, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_DIVS: LowLevelILDivs, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_DIVS_DP: LowLevelILDivsDp, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_MODU: LowLevelILModu, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_MODU_DP: LowLevelILModuDp, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_MODS: LowLevelILMods, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_MODS_DP: LowLevelILModsDp, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_NEG: LowLevelILNeg, # [("src", "expr")],
+ LowLevelILOperation.LLIL_NOT: LowLevelILNot, # [("src", "expr")],
+ LowLevelILOperation.LLIL_SX: LowLevelILSx, # [("src", "expr")],
+ LowLevelILOperation.LLIL_ZX: LowLevelILZx, # [("src", "expr")],
+ LowLevelILOperation.LLIL_LOW_PART: LowLevelILLowPart, # [("src", "expr")],
+ LowLevelILOperation.LLIL_JUMP: LowLevelILJump, # [("dest", "expr")],
+ LowLevelILOperation.LLIL_JUMP_TO: LowLevelILJumpTo, # [("dest", "expr"), ("targets", "target_map")],
+ LowLevelILOperation.LLIL_CALL: LowLevelILCall, # [("dest", "expr")],
+ LowLevelILOperation.LLIL_CALL_STACK_ADJUST: LowLevelILCallStackAdjust, # [("dest", "expr"), ("stack_adjustment", "int"), ("reg_stack_adjustments", "reg_stack_adjust")],
+ LowLevelILOperation.LLIL_TAILCALL: LowLevelILTailcall, # [("dest", "expr")],
+ LowLevelILOperation.LLIL_RET: LowLevelILRet, # [("dest", "expr")],
+ LowLevelILOperation.LLIL_NORET: LowLevelILNoret, # [],
+ LowLevelILOperation.LLIL_IF: LowLevelILIf, # [("condition", "expr"), ("true", "int"), ("false", "int")],
+ LowLevelILOperation.LLIL_GOTO: LowLevelILGoto, # [("dest", "int")],
+ LowLevelILOperation.LLIL_FLAG_COND: LowLevelILFlagCond, # [("condition", "cond"), ("semantic_class", "sem_class")],
+ LowLevelILOperation.LLIL_FLAG_GROUP: LowLevelILFlagGroup, # [("semantic_group", "sem_group")],
+ LowLevelILOperation.LLIL_CMP_E: LowLevelILCmpE, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_CMP_NE: LowLevelILCmpNe, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_CMP_SLT: LowLevelILCmpSlt, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_CMP_ULT: LowLevelILCmpUlt, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_CMP_SLE: LowLevelILCmpSle, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_CMP_ULE: LowLevelILCmpUle, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_CMP_SGE: LowLevelILCmpSge, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_CMP_UGE: LowLevelILCmpUge, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_CMP_SGT: LowLevelILCmpSgt, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_CMP_UGT: LowLevelILCmpUgt, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_TEST_BIT: LowLevelILTestBit, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_BOOL_TO_INT: LowLevelILBoolToInt, # [("src", "expr")],
+ LowLevelILOperation.LLIL_ADD_OVERFLOW: LowLevelILAddOverflow, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_SYSCALL: LowLevelILSyscall, # [],
+ LowLevelILOperation.LLIL_INTRINSIC: LowLevelILIntrinsic, # [("output", "reg_or_flag_list"), ("intrinsic", "intrinsic"), ("param", "expr")],
+ LowLevelILOperation.LLIL_INTRINSIC_SSA: LowLevelILIntrinsicSsa, # [("output", "reg_or_flag_ssa_list"), ("intrinsic", "intrinsic"), ("param", "expr")],
+ LowLevelILOperation.LLIL_BP: LowLevelILBp, # [],
+ LowLevelILOperation.LLIL_TRAP: LowLevelILTrap, # [("vector", "int")],
+ LowLevelILOperation.LLIL_UNDEF: LowLevelILUndef, # [],
+ LowLevelILOperation.LLIL_UNIMPL: LowLevelILUnimpl, # [],
+ LowLevelILOperation.LLIL_UNIMPL_MEM: LowLevelILUnimplMem, # [("src", "expr")],
+ LowLevelILOperation.LLIL_FADD: LowLevelILFadd, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_FSUB: LowLevelILFsub, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_FMUL: LowLevelILFmul, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_FDIV: LowLevelILFdiv, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_FSQRT: LowLevelILFsqrt, # [("src", "expr")],
+ LowLevelILOperation.LLIL_FNEG: LowLevelILFneg, # [("src", "expr")],
+ LowLevelILOperation.LLIL_FABS: LowLevelILFabs, # [("src", "expr")],
+ LowLevelILOperation.LLIL_FLOAT_TO_INT: LowLevelILFloatToInt, # [("src", "expr")],
+ LowLevelILOperation.LLIL_INT_TO_FLOAT: LowLevelILIntToFloat, # [("src", "expr")],
+ LowLevelILOperation.LLIL_FLOAT_CONV: LowLevelILFloatConv, # [("src", "expr")],
+ LowLevelILOperation.LLIL_ROUND_TO_INT: LowLevelILRoundToInt, # [("src", "expr")],
+ LowLevelILOperation.LLIL_FLOOR: LowLevelILFloor, # [("src", "expr")],
+ LowLevelILOperation.LLIL_CEIL: LowLevelILCeil, # [("src", "expr")],
+ LowLevelILOperation.LLIL_FTRUNC: LowLevelILFtrunc, # [("src", "expr")],
+ LowLevelILOperation.LLIL_FCMP_E: LowLevelILFcmpE, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_FCMP_NE: LowLevelILFcmpNe, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_FCMP_LT: LowLevelILFcmpLt, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_FCMP_LE: LowLevelILFcmpLe, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_FCMP_GE: LowLevelILFcmpGe, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_FCMP_GT: LowLevelILFcmpGt, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_FCMP_O: LowLevelILFcmpO, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_FCMP_UO: LowLevelILFcmpUo, # [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_SET_REG_SSA: LowLevelILSetRegSsa, # [("dest", "reg_ssa"), ("src", "expr")],
+ LowLevelILOperation.LLIL_SET_REG_SSA_PARTIAL: LowLevelILSetRegSsaPartial, # [("full_reg", "reg_ssa"), ("dest", "reg"), ("src", "expr")],
+ LowLevelILOperation.LLIL_SET_REG_SPLIT_SSA: LowLevelILSetRegSplitSsa, # [("hi", "expr"), ("lo", "expr"), ("src", "expr")],
+ LowLevelILOperation.LLIL_SET_REG_STACK_REL_SSA: LowLevelILSetRegStackRelSsa, # [("stack", "expr"), ("dest", "expr"), ("top", "expr"), ("src", "expr")],
+ LowLevelILOperation.LLIL_SET_REG_STACK_ABS_SSA: LowLevelILSetRegStackAbsSsa, # [("stack", "expr"), ("dest", "reg"), ("src", "expr")],
+ LowLevelILOperation.LLIL_REG_SPLIT_DEST_SSA: LowLevelILRegSplitDestSsa, # [("dest", "reg_ssa")],
+ LowLevelILOperation.LLIL_REG_STACK_DEST_SSA: LowLevelILRegStackDestSsa, # [("src", "reg_stack_ssa_dest_and_src")],
+ LowLevelILOperation.LLIL_REG_SSA: LowLevelILRegSsa, # [("src", "reg_ssa")],
+ LowLevelILOperation.LLIL_REG_SSA_PARTIAL: LowLevelILRegSsaPartial, # [("full_reg", "reg_ssa"), ("src", "reg")],
+ LowLevelILOperation.LLIL_REG_SPLIT_SSA: LowLevelILRegSplitSsa, # [("hi", "reg_ssa"), ("lo", "reg_ssa")],
+ LowLevelILOperation.LLIL_REG_STACK_REL_SSA: LowLevelILRegStackRelSsa, # [("stack", "reg_stack_ssa"), ("src", "expr"), ("top", "expr")],
+ LowLevelILOperation.LLIL_REG_STACK_ABS_SSA: LowLevelILRegStackAbsSsa, # [("stack", "reg_stack_ssa"), ("src", "reg")],
+ LowLevelILOperation.LLIL_REG_STACK_FREE_REL_SSA: LowLevelILRegStackFreeRelSsa, # [("stack", "expr"), ("dest", "expr"), ("top", "expr")],
+ LowLevelILOperation.LLIL_REG_STACK_FREE_ABS_SSA: LowLevelILRegStackFreeAbsSsa, # [("stack", "expr"), ("dest", "reg")],
+ LowLevelILOperation.LLIL_SET_FLAG_SSA: LowLevelILSetFlagSsa, # [("dest", "flag_ssa"), ("src", "expr")],
+ LowLevelILOperation.LLIL_FLAG_SSA: LowLevelILFlagSsa, # [("src", "flag_ssa")],
+ LowLevelILOperation.LLIL_FLAG_BIT_SSA: LowLevelILFlagBitSsa, # [("src", "flag_ssa"), ("bit", "int")],
+ LowLevelILOperation.LLIL_CALL_SSA: LowLevelILCallSsa, # [("output", "expr"), ("dest", "expr"), ("stack", "expr"), ("param", "expr")],
+ LowLevelILOperation.LLIL_SYSCALL_SSA: LowLevelILSyscallSsa, # [("output", "expr"), ("stack", "expr"), ("param", "expr")],
+ LowLevelILOperation.LLIL_TAILCALL_SSA: LowLevelILTailcallSsa, # [("output", "expr"), ("dest", "expr"), ("stack", "expr"), ("param", "expr")],
+ LowLevelILOperation.LLIL_CALL_OUTPUT_SSA: LowLevelILCallOutputSsa, # [("dest_memory", "int"), ("dest", "reg_ssa_list")],
+ LowLevelILOperation.LLIL_CALL_STACK_SSA: LowLevelILCallStackSsa, # [("src", "reg_ssa"), ("src_memory", "int")],
+ LowLevelILOperation.LLIL_CALL_PARAM: LowLevelILCallParam, # [("src", "expr_list")],
+ LowLevelILOperation.LLIL_LOAD_SSA: LowLevelILLoadSsa, # [("src", "expr"), ("src_memory", "int")],
+ LowLevelILOperation.LLIL_STORE_SSA: LowLevelILStoreSsa, # [("dest", "expr"), ("dest_memory", "int"), ("src_memory", "int"), ("src", "expr")],
+ LowLevelILOperation.LLIL_REG_PHI: LowLevelILRegPhi, # [("dest", "reg_ssa"), ("src", "reg_ssa_list")],
+ LowLevelILOperation.LLIL_REG_STACK_PHI: LowLevelILRegStackPhi, # [("dest", "reg_stack_ssa"), ("src", "reg_stack_ssa_list")],
+ LowLevelILOperation.LLIL_FLAG_PHI: LowLevelILFlagPhi, # [("dest", "flag_ssa"), ("src", "flag_ssa_list")],
+ LowLevelILOperation.LLIL_MEM_PHI: LowLevelILMemPhi, # [("dest_memory", "int"), ("src_memory", "int_list")]
}
@@ -2634,7 +2598,7 @@ class LowLevelILExpr:
.. note:: Deprecated. Use ExpressionIndex instead
"""
- def __init__(self, index:ExpressionIndex):
+ def __init__(self, index: ExpressionIndex):
self._index = index
def __int__(self):
@@ -2673,8 +2637,10 @@ class LowLevelILFunction:
LLFC_NO !overflow No overflow
======================= ========== ===============================
"""
- def __init__(self, arch:Optional['architecture.Architecture']=None, handle:Optional[core.BNLowLevelILFunction]=None,
- source_func:'function.Function'=None):
+ def __init__(
+ self, arch: Optional['architecture.Architecture'] = None, handle: Optional[core.BNLowLevelILFunction] = None,
+ source_func: 'function.Function' = None
+ ):
self._arch = arch
self._source_function = source_func
if handle is not None:
@@ -2683,7 +2649,7 @@ class LowLevelILFunction:
if self._source_function is None:
source_handle = core.BNGetLowLevelILOwnerFunction(_handle)
if source_handle:
- self._source_function = function.Function(handle = source_handle)
+ self._source_function = function.Function(handle=source_handle)
else:
self._source_function = None
if self._arch is None:
@@ -2740,7 +2706,9 @@ class LowLevelILFunction:
raise IndexError("index out of range")
if i < 0:
i = len(self) + i
- return LowLevelILInstruction.create(self, ExpressionIndex(core.BNGetLowLevelILIndexForInstruction(self.handle, i)), i)
+ return LowLevelILInstruction.create(
+ self, ExpressionIndex(core.BNGetLowLevelILIndexForInstruction(self.handle, i)), i
+ )
def __setitem__(self, i, j):
raise IndexError("instruction modification not implemented")
@@ -2766,10 +2734,10 @@ class LowLevelILFunction:
return core.BNLowLevelILGetCurrentAddress(self.handle)
@current_address.setter
- def current_address(self, value:int) -> None:
+ def current_address(self, value: int) -> None:
core.BNLowLevelILSetCurrentAddress(self.handle, self.arch.handle, value)
- def set_current_address(self, value:int, arch:Optional['architecture.Architecture']=None) -> None:
+ def set_current_address(self, value: int, arch: Optional['architecture.Architecture'] = None) -> None:
if arch is None:
arch = self.arch
core.BNLowLevelILSetCurrentAddress(self.handle, arch.handle, value)
@@ -2858,7 +2826,7 @@ class LowLevelILFunction:
return self._source_function
@source_function.setter
- def source_function(self, value:'function.Function') -> None:
+ def source_function(self, value: 'function.Function') -> None:
self._source_function = value
@property
@@ -2951,11 +2919,15 @@ class LowLevelILFunction:
try:
for var_i in range(register_stack_count.value):
version_count = ctypes.c_ulonglong()
- versions = core.BNGetLowLevelRegisterStackSSAVersions(self.handle, register_stacks[var_i], version_count)
+ versions = core.BNGetLowLevelRegisterStackSSAVersions(
+ self.handle, register_stacks[var_i], version_count
+ )
assert versions is not None, "core.BNGetLowLevelRegisterStackSSAVersions returned None"
try:
for version_i in range(version_count.value):
- result.append(SSARegisterStack(ILRegisterStack(self.arch, register_stacks[var_i]), versions[version_i]))
+ result.append(
+ SSARegisterStack(ILRegisterStack(self.arch, register_stacks[var_i]), versions[version_i])
+ )
finally:
core.BNFreeLLILVariableVersionList(versions)
finally:
@@ -3006,7 +2978,10 @@ class LowLevelILFunction:
if self._source_function is None:
return []
- if self.il_form in [FunctionGraphType.LiftedILFunctionGraph, FunctionGraphType.LowLevelILFunctionGraph, FunctionGraphType.LowLevelILSSAFormFunctionGraph]:
+ if self.il_form in [
+ FunctionGraphType.LiftedILFunctionGraph, FunctionGraphType.LowLevelILFunctionGraph,
+ FunctionGraphType.LowLevelILSSAFormFunctionGraph
+ ]:
return self.registers + self.register_stacks + self.flags # type: ignore
return []
@@ -3020,7 +2995,7 @@ class LowLevelILFunction:
return self.ssa_form.ssa_vars
return []
- def get_instruction_start(self, addr:int, arch:Optional['architecture.Architecture']=None) -> Optional[int]:
+ def get_instruction_start(self, addr: int, arch: Optional['architecture.Architecture'] = None) -> Optional[int]:
if arch is None:
arch = self.arch
result = core.BNLowLevelILGetInstructionStart(self.handle, arch.handle, addr)
@@ -3031,15 +3006,17 @@ class LowLevelILFunction:
def clear_indirect_branches(self) -> None:
core.BNLowLevelILClearIndirectBranches(self.handle)
- def set_indirect_branches(self, branches:List[Tuple['architecture.Architecture', int]]) -> None:
+ def set_indirect_branches(self, branches: List[Tuple['architecture.Architecture', int]]) -> None:
branch_list = (core.BNArchitectureAndAddress * len(branches))()
for i in range(len(branches)):
branch_list[i].arch = branches[i][0].handle
branch_list[i].address = branches[i][1]
core.BNLowLevelILSetIndirectBranches(self.handle, branch_list, len(branches))
- def expr(self, operation, a:int=0, b:int=0, c:int=0, d:int=0, size:int=0,
- flags:Union['architecture.FlagWriteTypeName', 'architecture.FlagType', 'architecture.FlagIndex']=None):
+ def expr(
+ self, operation, a: int = 0, b: int = 0, c: int = 0, d: int = 0, size: int = 0,
+ flags: Union['architecture.FlagWriteTypeName', 'architecture.FlagType', 'architecture.FlagIndex'] = None
+ ):
_flags = architecture.FlagIndex(0)
if isinstance(operation, str):
operation = LowLevelILOperation[operation]
@@ -3057,7 +3034,7 @@ class LowLevelILFunction:
assert False, "flags type unsupported"
return ExpressionIndex(core.BNLowLevelILAddExpr(self.handle, operation, size, _flags, a, b, c, d))
- def replace_expr(self, original:InstructionOrExpression, new:InstructionOrExpression) -> None:
+ def replace_expr(self, original: InstructionOrExpression, new: InstructionOrExpression) -> None:
"""
``replace_expr`` allows modification of ExpressionIndexessions but ONLY during lifting.
@@ -3079,7 +3056,7 @@ class LowLevelILFunction:
core.BNReplaceLowLevelILExpr(self.handle, original, new)
- def append(self, expr:ExpressionIndex) -> int:
+ def append(self, expr: ExpressionIndex) -> int:
"""
``append`` adds the ExpressionIndex ``expr`` to the current LowLevelILFunction.
@@ -3098,8 +3075,10 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_NOP)
- def set_reg(self, size:int, reg:'architecture.RegisterType', value:ExpressionIndex,
- flags:Optional['architecture.FlagType']=None) -> ExpressionIndex:
+ def set_reg(
+ self, size: int, reg: 'architecture.RegisterType', value: ExpressionIndex,
+ flags: Optional['architecture.FlagType'] = None
+ ) -> ExpressionIndex:
"""
``set_reg`` sets the register ``reg`` of size ``size`` to the expression ``value``
@@ -3113,10 +3092,12 @@ class LowLevelILFunction:
_reg = ExpressionIndex(self.arch.get_reg_index(reg))
if flags is None:
flags = architecture.FlagIndex(0)
- return self.expr(LowLevelILOperation.LLIL_SET_REG, _reg, value, size = size, flags = flags)
+ return self.expr(LowLevelILOperation.LLIL_SET_REG, _reg, value, size=size, flags=flags)
- def set_reg_split(self, size:int, hi:'architecture.RegisterType', lo:'architecture.RegisterType',
- value:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def set_reg_split(
+ self, size: int, hi: 'architecture.RegisterType', lo: 'architecture.RegisterType', value: ExpressionIndex,
+ flags: 'architecture.FlagType' = None
+ ) -> ExpressionIndex:
"""
``set_reg_split`` uses ``hi`` and ``lo`` as a single extended register setting ``hi:lo`` to the expression
``value``.
@@ -3133,10 +3114,12 @@ class LowLevelILFunction:
_lo = ExpressionIndex(self.arch.get_reg_index(lo))
if flags is None:
flags = architecture.FlagIndex(0)
- return self.expr(LowLevelILOperation.LLIL_SET_REG_SPLIT, _hi, _lo, value, size = size, flags = flags)
+ return self.expr(LowLevelILOperation.LLIL_SET_REG_SPLIT, _hi, _lo, value, size=size, flags=flags)
- def set_reg_stack_top_relative(self, size:int, reg_stack:'architecture.RegisterStackType', entry:ExpressionIndex,
- value:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def set_reg_stack_top_relative(
+ self, size: int, reg_stack: 'architecture.RegisterStackType', entry: ExpressionIndex, value: ExpressionIndex,
+ flags: 'architecture.FlagType' = None
+ ) -> ExpressionIndex:
"""
``set_reg_stack_top_relative`` sets the top-relative entry ``entry`` of size ``size`` in register
stack ``reg_stack`` to the expression ``value``
@@ -3152,11 +3135,12 @@ class LowLevelILFunction:
_reg_stack = ExpressionIndex(self.arch.get_reg_stack_index(reg_stack))
if flags is None:
flags = architecture.FlagIndex(0)
- return self.expr(LowLevelILOperation.LLIL_SET_REG_STACK_REL, _reg_stack, entry, value,
- size = size, flags = flags)
+ return self.expr(LowLevelILOperation.LLIL_SET_REG_STACK_REL, _reg_stack, entry, value, size=size, flags=flags)
- def reg_stack_push(self, size:int, reg_stack:'architecture.RegisterStackType', value:ExpressionIndex,
- flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def reg_stack_push(
+ self, size: int, reg_stack: 'architecture.RegisterStackType', value: ExpressionIndex,
+ flags: 'architecture.FlagType' = None
+ ) -> ExpressionIndex:
"""
``reg_stack_push`` pushes the expression ``value`` of size ``size`` onto the top of the register
stack ``reg_stack``
@@ -3171,9 +3155,9 @@ class LowLevelILFunction:
_reg_stack = ExpressionIndex(self.arch.get_reg_stack_index(reg_stack))
if flags is None:
flags = architecture.FlagIndex(0)
- return self.expr(LowLevelILOperation.LLIL_REG_STACK_PUSH, _reg_stack, value, size = size, flags = flags)
+ return self.expr(LowLevelILOperation.LLIL_REG_STACK_PUSH, _reg_stack, value, size=size, flags=flags)
- def set_flag(self, flag:'architecture.FlagName', value:ExpressionIndex) -> ExpressionIndex:
+ def set_flag(self, flag: 'architecture.FlagName', value: ExpressionIndex) -> ExpressionIndex:
"""
``set_flag`` sets the flag ``flag`` to the ExpressionIndex ``value``
@@ -3182,10 +3166,9 @@ class LowLevelILFunction:
:return: The expression FLAG.flag = value
:rtype: ExpressionIndex
"""
- return self.expr(LowLevelILOperation.LLIL_SET_FLAG, ExpressionIndex(self.arch.get_flag_by_name(flag)),
- value)
+ return self.expr(LowLevelILOperation.LLIL_SET_FLAG, ExpressionIndex(self.arch.get_flag_by_name(flag)), value)
- def load(self, size:int, addr:ExpressionIndex) -> ExpressionIndex:
+ def load(self, size: int, addr: ExpressionIndex) -> ExpressionIndex:
"""
``load`` Reads ``size`` bytes from the expression ``addr``
@@ -3196,7 +3179,9 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_LOAD, addr, size=size)
- def store(self, size:int, addr:ExpressionIndex, value:ExpressionIndex, flags:Optional['architecture.FlagName']=None) -> ExpressionIndex:
+ def store(
+ self, size: int, addr: ExpressionIndex, value: ExpressionIndex, flags: Optional['architecture.FlagName'] = None
+ ) -> ExpressionIndex:
"""
``store`` Writes ``size`` bytes to expression ``addr`` read from expression ``value``
@@ -3209,7 +3194,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_STORE, addr, value, size=size, flags=flags)
- def push(self, size:int, value:ExpressionIndex) -> ExpressionIndex:
+ def push(self, size: int, value: ExpressionIndex) -> ExpressionIndex:
"""
``push`` writes ``size`` bytes from expression ``value`` to the stack, adjusting the stack by ``size``.
@@ -3220,7 +3205,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_PUSH, value, size=size)
- def pop(self, size:int) -> ExpressionIndex:
+ def pop(self, size: int) -> ExpressionIndex:
"""
``pop`` reads ``size`` bytes from the stack, adjusting the stack by ``size``.
@@ -3230,7 +3215,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_POP, size=size)
- def reg(self, size:int, reg:'architecture.RegisterType') -> ExpressionIndex:
+ def reg(self, size: int, reg: 'architecture.RegisterType') -> ExpressionIndex:
"""
``reg`` returns a register of size ``size`` with name ``reg``
@@ -3242,7 +3227,7 @@ class LowLevelILFunction:
_reg = ExpressionIndex(self.arch.get_reg_index(reg))
return self.expr(LowLevelILOperation.LLIL_REG, _reg, size=size)
- def reg_split(self, size:int, hi:'architecture.RegisterType', lo:'architecture.RegisterType') -> ExpressionIndex:
+ def reg_split(self, size: int, hi: 'architecture.RegisterType', lo: 'architecture.RegisterType') -> ExpressionIndex:
"""
``reg_split`` combines registers of size ``size`` with names ``hi`` and ``lo``
@@ -3256,7 +3241,9 @@ class LowLevelILFunction:
_lo = ExpressionIndex(self.arch.get_reg_index(lo))
return self.expr(LowLevelILOperation.LLIL_REG_SPLIT, _hi, _lo, size=size)
- def reg_stack_top_relative(self, size:int, reg_stack:'architecture.RegisterStackType', entry:ExpressionIndex) -> ExpressionIndex:
+ def reg_stack_top_relative(
+ self, size: int, reg_stack: 'architecture.RegisterStackType', entry: ExpressionIndex
+ ) -> ExpressionIndex:
"""
``reg_stack_top_relative`` returns a register stack entry of size ``size`` at top-relative
location ``entry`` in register stack with name ``reg_stack``
@@ -3270,7 +3257,7 @@ class LowLevelILFunction:
_reg_stack = self.arch.get_reg_stack_index(reg_stack)
return self.expr(LowLevelILOperation.LLIL_REG_STACK_REL, _reg_stack, entry, size=size)
- def reg_stack_pop(self, size:int, reg_stack:'architecture.RegisterStackType') -> ExpressionIndex:
+ def reg_stack_pop(self, size: int, reg_stack: 'architecture.RegisterStackType') -> ExpressionIndex:
"""
``reg_stack_pop`` returns the top entry of size ``size`` in register stack with name ``reg_stack``, and
removes the entry from the stack
@@ -3283,7 +3270,7 @@ class LowLevelILFunction:
_reg_stack = ExpressionIndex(self.arch.get_reg_stack_index(reg_stack))
return self.expr(LowLevelILOperation.LLIL_REG_STACK_POP, _reg_stack, size=size)
- def const(self, size:int, value:int) -> ExpressionIndex:
+ def const(self, size: int, value: int) -> ExpressionIndex:
"""
``const`` returns an expression for the constant integer ``value`` with size ``size``
@@ -3294,7 +3281,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_CONST, ExpressionIndex(value), size=size)
- def const_pointer(self, size:int, value:int) -> ExpressionIndex:
+ def const_pointer(self, size: int, value: int) -> ExpressionIndex:
"""
``const_pointer`` returns an expression for the constant pointer ``value`` with size ``size``
@@ -3305,7 +3292,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_CONST_PTR, value, size=size)
- def reloc_pointer(self, size:int, value:int) -> ExpressionIndex:
+ def reloc_pointer(self, size: int, value: int) -> ExpressionIndex:
"""
``reloc_pointer`` returns an expression for the constant relocated pointer ``value`` with size ``size``
@@ -3316,7 +3303,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_EXTERN_PTR, value, size=size)
- def float_const_raw(self, size:int, value:int) -> ExpressionIndex:
+ def float_const_raw(self, size: int, value: int) -> ExpressionIndex:
"""
``float_const_raw`` returns an expression for the constant raw binary floating point
value ``value`` with size ``size``
@@ -3328,7 +3315,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_FLOAT_CONST, value, size=size)
- def float_const_single(self, value:float) -> ExpressionIndex:
+ def float_const_single(self, value: float) -> ExpressionIndex:
"""
``float_const_single`` returns an expression for the single precision floating point value ``value``
@@ -3338,7 +3325,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_FLOAT_CONST, struct.unpack("I", struct.pack("f", value))[0], size=4)
- def float_const_double(self, value:float) -> ExpressionIndex:
+ def float_const_double(self, value: float) -> ExpressionIndex:
"""
``float_const_double`` returns an expression for the double precision floating point value ``value``
@@ -3348,7 +3335,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_FLOAT_CONST, struct.unpack("Q", struct.pack("d", value))[0], size=8)
- def flag(self, reg:'architecture.FlagName') -> ExpressionIndex:
+ def flag(self, reg: 'architecture.FlagName') -> ExpressionIndex:
"""
``flag`` returns a flag expression for the given flag name.
@@ -3358,7 +3345,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_FLAG, self.arch.get_flag_by_name(reg))
- def flag_bit(self, size:int, reg:'architecture.FlagName', bit:int) -> ExpressionIndex:
+ def flag_bit(self, size: int, reg: 'architecture.FlagName', bit: int) -> ExpressionIndex:
"""
``flag_bit`` sets the flag named ``reg`` and size ``size`` to the constant integer value ``bit``
@@ -3370,7 +3357,9 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_FLAG_BIT, self.arch.get_flag_by_name(reg), bit, size=size)
- def add(self, size:int, a:ExpressionIndex, b:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def add(
+ self, size: int, a: ExpressionIndex, b: ExpressionIndex, flags: 'architecture.FlagType' = None
+ ) -> ExpressionIndex:
"""
``add`` adds expression ``a`` to expression ``b`` potentially setting flags ``flags`` and returning
an expression of ``size`` bytes.
@@ -3384,8 +3373,10 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_ADD, a, b, size=size, flags=flags)
- def add_carry(self, size:int, a:ExpressionIndex, b:ExpressionIndex, carry:ExpressionIndex,
- flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def add_carry(
+ self, size: int, a: ExpressionIndex, b: ExpressionIndex, carry: ExpressionIndex,
+ flags: 'architecture.FlagType' = None
+ ) -> ExpressionIndex:
"""
``add_carry`` adds with carry expression ``a`` to expression ``b`` potentially setting flags ``flags`` and
returning an expression of ``size`` bytes.
@@ -3400,7 +3391,9 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_ADC, a, b, carry, size=size, flags=flags)
- def sub(self, size:int, a:ExpressionIndex, b:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def sub(
+ self, size: int, a: ExpressionIndex, b: ExpressionIndex, flags: 'architecture.FlagType' = None
+ ) -> ExpressionIndex:
"""
``sub`` subtracts expression ``b`` from expression ``a`` potentially setting flags ``flags`` and returning
an expression of ``size`` bytes.
@@ -3414,8 +3407,10 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_SUB, a, b, size=size, flags=flags)
- def sub_borrow(self, size:int, a:ExpressionIndex, b:ExpressionIndex, carry:ExpressionIndex,
- flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def sub_borrow(
+ self, size: int, a: ExpressionIndex, b: ExpressionIndex, carry: ExpressionIndex,
+ flags: 'architecture.FlagType' = None
+ ) -> ExpressionIndex:
"""
``sub_borrow`` subtracts with borrow expression ``b`` from expression ``a`` potentially setting flags ``flags``
and returning an expression of ``size`` bytes.
@@ -3430,7 +3425,9 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_SBB, a, b, carry, size=size, flags=flags)
- def and_expr(self, size:int, a:ExpressionIndex, b:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def and_expr(
+ self, size: int, a: ExpressionIndex, b: ExpressionIndex, flags: 'architecture.FlagType' = None
+ ) -> ExpressionIndex:
"""
``and_expr`` bitwise and's expression ``a`` and expression ``b`` potentially setting flags ``flags``
and returning an expression of ``size`` bytes.
@@ -3444,7 +3441,9 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_AND, a, b, size=size, flags=flags)
- def or_expr(self, size:int, a:ExpressionIndex, b:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def or_expr(
+ self, size: int, a: ExpressionIndex, b: ExpressionIndex, flags: 'architecture.FlagType' = None
+ ) -> ExpressionIndex:
"""
``or_expr`` bitwise or's expression ``a`` and expression ``b`` potentially setting flags ``flags``
and returning an expression of ``size`` bytes.
@@ -3458,7 +3457,9 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_OR, a, b, size=size, flags=flags)
- def xor_expr(self, size:int, a:ExpressionIndex, b:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def xor_expr(
+ self, size: int, a: ExpressionIndex, b: ExpressionIndex, flags: 'architecture.FlagType' = None
+ ) -> ExpressionIndex:
"""
``xor_expr`` xor's expression ``a`` with expression ``b`` potentially setting flags ``flags``
and returning an expression of ``size`` bytes.
@@ -3472,7 +3473,9 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_XOR, a, b, size=size, flags=flags)
- def shift_left(self, size:int, a:ExpressionIndex, b:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def shift_left(
+ self, size: int, a: ExpressionIndex, b: ExpressionIndex, flags: 'architecture.FlagType' = None
+ ) -> ExpressionIndex:
"""
``shift_left`` shifts left expression ``a`` by expression ``b`` from expression ``a`` potentially setting flags ``flags``
and returning an expression of ``size`` bytes.
@@ -3486,7 +3489,9 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_LSL, a, b, size=size, flags=flags)
- def logical_shift_right(self, size:int, a:ExpressionIndex, b:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def logical_shift_right(
+ self, size: int, a: ExpressionIndex, b: ExpressionIndex, flags: 'architecture.FlagType' = None
+ ) -> ExpressionIndex:
"""
``logical_shift_right`` shifts logically right expression ``a`` by expression ``b`` potentially setting flags
``flags`` and returning an expression of ``size`` bytes.
@@ -3500,7 +3505,9 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_LSR, a, b, size=size, flags=flags)
- def arith_shift_right(self, size:int, a:ExpressionIndex, b:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def arith_shift_right(
+ self, size: int, a: ExpressionIndex, b: ExpressionIndex, flags: 'architecture.FlagType' = None
+ ) -> ExpressionIndex:
"""
``arith_shift_right`` shifts arithmetic right expression ``a`` by expression ``b`` potentially setting flags
``flags`` and returning an expression of ``size`` bytes.
@@ -3514,7 +3521,9 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_ASR, a, b, size=size, flags=flags)
- def rotate_left(self, size:int, a:ExpressionIndex, b:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def rotate_left(
+ self, size: int, a: ExpressionIndex, b: ExpressionIndex, flags: 'architecture.FlagType' = None
+ ) -> ExpressionIndex:
"""
``rotate_left`` bitwise rotates left expression ``a`` by expression ``b`` potentially setting flags ``flags``
and returning an expression of ``size`` bytes.
@@ -3528,8 +3537,10 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_ROL, a, b, size=size, flags=flags)
- def rotate_left_carry(self, size:int, a:ExpressionIndex, b:ExpressionIndex, carry:ExpressionIndex,
- flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def rotate_left_carry(
+ self, size: int, a: ExpressionIndex, b: ExpressionIndex, carry: ExpressionIndex,
+ flags: 'architecture.FlagType' = None
+ ) -> ExpressionIndex:
"""
``rotate_left_carry`` bitwise rotates left with carry expression ``a`` by expression ``b`` potentially setting
flags ``flags`` and returning an expression of ``size`` bytes.
@@ -3544,7 +3555,9 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_RLC, a, b, carry, size=size, flags=flags)
- def rotate_right(self, size:int, a:ExpressionIndex, b:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def rotate_right(
+ self, size: int, a: ExpressionIndex, b: ExpressionIndex, flags: 'architecture.FlagType' = None
+ ) -> ExpressionIndex:
"""
``rotate_right`` bitwise rotates right expression ``a`` by expression ``b`` potentially setting flags ``flags``
and returning an expression of ``size`` bytes.
@@ -3558,8 +3571,10 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_ROR, a, b, size=size, flags=flags)
- def rotate_right_carry(self, size:int, a:ExpressionIndex, b:ExpressionIndex, carry:ExpressionIndex,
- flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def rotate_right_carry(
+ self, size: int, a: ExpressionIndex, b: ExpressionIndex, carry: ExpressionIndex,
+ flags: 'architecture.FlagType' = None
+ ) -> ExpressionIndex:
"""
``rotate_right_carry`` bitwise rotates right with carry expression ``a`` by expression ``b`` potentially setting
flags ``flags`` and returning an expression of ``size`` bytes.
@@ -3574,7 +3589,9 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_RRC, a, b, carry, size=size, flags=flags)
- def mult(self, size:int, a:ExpressionIndex, b:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def mult(
+ self, size: int, a: ExpressionIndex, b: ExpressionIndex, flags: 'architecture.FlagType' = None
+ ) -> ExpressionIndex:
"""
``mult`` multiplies expression ``a`` by expression ``b`` potentially setting flags ``flags`` and returning an
expression of ``size`` bytes.
@@ -3588,7 +3605,9 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_MUL, a, b, size=size, flags=flags)
- def mult_double_prec_signed(self, size:int, a:ExpressionIndex, b:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def mult_double_prec_signed(
+ self, size: int, a: ExpressionIndex, b: ExpressionIndex, flags: 'architecture.FlagType' = None
+ ) -> ExpressionIndex:
"""
``mult_double_prec_signed`` multiplies signed with double precision expression ``a`` by expression ``b``
potentially setting flags ``flags`` and returning an expression of ``size`` bytes.
@@ -3602,7 +3621,9 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_MULS_DP, a, b, size=size, flags=flags)
- def mult_double_prec_unsigned(self, size:int, a:ExpressionIndex, b:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def mult_double_prec_unsigned(
+ self, size: int, a: ExpressionIndex, b: ExpressionIndex, flags: 'architecture.FlagType' = None
+ ) -> ExpressionIndex:
"""
``mult_double_prec_unsigned`` multiplies unsigned with double precision expression ``a`` by expression ``b``
potentially setting flags ``flags`` and returning an expression of ``size`` bytes.
@@ -3616,7 +3637,9 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_MULU_DP, a, b, size=size, flags=flags)
- def div_signed(self, size:int, a:ExpressionIndex, b:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def div_signed(
+ self, size: int, a: ExpressionIndex, b: ExpressionIndex, flags: 'architecture.FlagType' = None
+ ) -> ExpressionIndex:
"""
``div_signed`` signed divide expression ``a`` by expression ``b`` potentially setting flags ``flags``
and returning an expression of ``size`` bytes.
@@ -3630,7 +3653,9 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_DIVS, a, b, size=size, flags=flags)
- def div_double_prec_signed(self, size:int, a:ExpressionIndex, b:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def div_double_prec_signed(
+ self, size: int, a: ExpressionIndex, b: ExpressionIndex, flags: 'architecture.FlagType' = None
+ ) -> ExpressionIndex:
"""
``div_double_prec_signed`` signed double precision divide using expression ``a`` as a
single double precision register by expression ``b`` potentially setting flags ``flags`` and returning an
@@ -3645,7 +3670,9 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_DIVS_DP, a, b, size=size, flags=flags)
- def div_unsigned(self, size:int, a:ExpressionIndex, b:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def div_unsigned(
+ self, size: int, a: ExpressionIndex, b: ExpressionIndex, flags: 'architecture.FlagType' = None
+ ) -> ExpressionIndex:
"""
``div_unsigned`` unsigned divide expression ``a`` by expression ``b`` potentially setting flags ``flags``
and returning an expression of ``size`` bytes.
@@ -3659,7 +3686,9 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_DIVU, a, b, size=size, flags=flags)
- def div_double_prec_unsigned(self, size:int, a:ExpressionIndex, b:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def div_double_prec_unsigned(
+ self, size: int, a: ExpressionIndex, b: ExpressionIndex, flags: 'architecture.FlagType' = None
+ ) -> ExpressionIndex:
"""
``div_double_prec_unsigned`` unsigned double precision divide using expression ``a`` as
a single double precision register by expression ``b`` potentially setting flags ``flags`` and returning an
@@ -3674,7 +3703,9 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_DIVU_DP, a, b, size=size, flags=flags)
- def mod_signed(self, size:int, a:ExpressionIndex, b:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def mod_signed(
+ self, size: int, a: ExpressionIndex, b: ExpressionIndex, flags: 'architecture.FlagType' = None
+ ) -> ExpressionIndex:
"""
``mod_signed`` signed modulus expression ``a`` by expression ``b`` potentially setting flags ``flags``
and returning an expression of ``size`` bytes.
@@ -3688,7 +3719,9 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_MODS, a, b, size=size, flags=flags)
- def mod_double_prec_signed(self, size:int, a:ExpressionIndex, b:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def mod_double_prec_signed(
+ self, size: int, a: ExpressionIndex, b: ExpressionIndex, flags: 'architecture.FlagType' = None
+ ) -> ExpressionIndex:
"""
``mod_double_prec_signed`` signed double precision modulus using expression ``a`` as a single
double precision register by expression ``b`` potentially setting flags ``flags`` and returning an expression
@@ -3703,7 +3736,9 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_MODS_DP, a, b, size=size, flags=flags)
- def mod_unsigned(self, size:int, a:ExpressionIndex, b:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def mod_unsigned(
+ self, size: int, a: ExpressionIndex, b: ExpressionIndex, flags: 'architecture.FlagType' = None
+ ) -> ExpressionIndex:
"""
``mod_unsigned`` unsigned modulus expression ``a`` by expression ``b`` potentially setting flags ``flags``
and returning an expression of ``size`` bytes.
@@ -3717,7 +3752,9 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_MODU, a, b, size=size, flags=flags)
- def mod_double_prec_unsigned(self, size:int, a:ExpressionIndex, b:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def mod_double_prec_unsigned(
+ self, size: int, a: ExpressionIndex, b: ExpressionIndex, flags: 'architecture.FlagType' = None
+ ) -> ExpressionIndex:
"""
``mod_double_prec_unsigned`` unsigned double precision modulus using expression ``a`` as
a single double precision register by expression ``b`` potentially setting flags ``flags`` and returning an
@@ -3732,7 +3769,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_MODU_DP, a, b, size=size, flags=flags)
- def neg_expr(self, size:int, value:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def neg_expr(self, size: int, value: ExpressionIndex, flags: 'architecture.FlagType' = None) -> ExpressionIndex:
"""
``neg_expr`` two's complement sign negation of expression ``value`` of size ``size`` potentially setting flags
@@ -3744,7 +3781,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_NEG, value, size=size, flags=flags)
- def not_expr(self, size:int, value:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def not_expr(self, size: int, value: ExpressionIndex, flags: 'architecture.FlagType' = None) -> ExpressionIndex:
"""
``not_expr`` bitwise inverse of expression ``value`` of size ``size`` potentially setting flags
@@ -3756,7 +3793,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_NOT, value, size=size, flags=flags)
- def sign_extend(self, size:int, value:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def sign_extend(self, size: int, value: ExpressionIndex, flags: 'architecture.FlagType' = None) -> ExpressionIndex:
"""
``sign_extend`` two's complement sign-extends the expression in ``value`` to ``size`` bytes
@@ -3768,7 +3805,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_SX, value, size=size, flags=flags)
- def zero_extend(self, size:int, value:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def zero_extend(self, size: int, value: ExpressionIndex, flags: 'architecture.FlagType' = None) -> ExpressionIndex:
"""
``zero_extend`` zero-extends the expression in ``value`` to ``size`` bytes
@@ -3779,7 +3816,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_ZX, value, size=size, flags=flags)
- def low_part(self, size:int, value:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def low_part(self, size: int, value: ExpressionIndex, flags: 'architecture.FlagType' = None) -> ExpressionIndex:
"""
``low_part`` truncates ``value`` to ``size`` bytes
@@ -3790,7 +3827,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_LOW_PART, value, size=size, flags=flags)
- def jump(self, dest:ExpressionIndex) -> ExpressionIndex:
+ def jump(self, dest: ExpressionIndex) -> ExpressionIndex:
"""
``jump`` returns an expression which jumps (branches) to the expression ``dest``
@@ -3800,7 +3837,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_JUMP, dest)
- def call(self, dest:ExpressionIndex) -> ExpressionIndex:
+ def call(self, dest: ExpressionIndex) -> ExpressionIndex:
"""
``call`` returns an expression which first pushes the address of the next instruction onto the stack then jumps
(branches) to the expression ``dest``
@@ -3811,7 +3848,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_CALL, dest)
- def call_stack_adjust(self, dest:ExpressionIndex, stack_adjust:int) -> ExpressionIndex:
+ def call_stack_adjust(self, dest: ExpressionIndex, stack_adjust: int) -> ExpressionIndex:
"""
``call_stack_adjust`` returns an expression which first pushes the address of the next instruction onto the stack
then jumps (branches) to the expression ``dest``. After the function exits, ``stack_adjust`` is added to the
@@ -3823,7 +3860,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_CALL_STACK_ADJUST, dest, stack_adjust)
- def tailcall(self, dest:ExpressionIndex) -> ExpressionIndex:
+ def tailcall(self, dest: ExpressionIndex) -> ExpressionIndex:
"""
``tailcall`` returns an expression which jumps (branches) to the expression ``dest``
@@ -3833,7 +3870,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_TAILCALL, dest)
- def ret(self, dest:ExpressionIndex) -> ExpressionIndex:
+ def ret(self, dest: ExpressionIndex) -> ExpressionIndex:
"""
``ret`` returns an expression which jumps (branches) to the expression ``dest``. ``ret`` is a special alias for
jump that makes the disassembler stop disassembling.
@@ -3853,8 +3890,10 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_NORET)
- def flag_condition(self, cond:Union[str, LowLevelILFlagCondition, int],
- sem_class:Optional['architecture.SemanticClassType']=None) -> ExpressionIndex:
+ def flag_condition(
+ self, cond: Union[str, LowLevelILFlagCondition, int],
+ sem_class: Optional['architecture.SemanticClassType'] = None
+ ) -> ExpressionIndex:
"""
``flag_condition`` returns a flag_condition expression for the given LowLevelILFlagCondition
@@ -3870,7 +3909,7 @@ class LowLevelILFunction:
class_index = self.arch.get_semantic_flag_class_index(sem_class)
return self.expr(LowLevelILOperation.LLIL_FLAG_COND, cond, architecture.SemanticClassIndex(class_index))
- def flag_group(self, sem_group:'architecture.SemanticGroupName') -> ExpressionIndex:
+ def flag_group(self, sem_group: 'architecture.SemanticGroupName') -> ExpressionIndex:
"""
``flag_group`` returns a flag_group expression for the given semantic flag group
@@ -3881,7 +3920,7 @@ class LowLevelILFunction:
group = self.arch.get_semantic_flag_group_index(sem_group)
return self.expr(LowLevelILOperation.LLIL_FLAG_GROUP, group)
- def compare_equal(self, size:int, a:ExpressionIndex, b:ExpressionIndex) -> ExpressionIndex:
+ def compare_equal(self, size: int, a: ExpressionIndex, b: ExpressionIndex) -> ExpressionIndex:
"""
``compare_equal`` returns comparison expression of size ``size`` checking if expression ``a`` is equal to
expression ``b``
@@ -3892,9 +3931,9 @@ class LowLevelILFunction:
:return: a comparison expression.
:rtype: ExpressionIndex
"""
- return self.expr(LowLevelILOperation.LLIL_CMP_E, a, b, size = size)
+ return self.expr(LowLevelILOperation.LLIL_CMP_E, a, b, size=size)
- def compare_not_equal(self, size:int, a:ExpressionIndex, b:ExpressionIndex) -> ExpressionIndex:
+ def compare_not_equal(self, size: int, a: ExpressionIndex, b: ExpressionIndex) -> ExpressionIndex:
"""
``compare_not_equal`` returns comparison expression of size ``size`` checking if expression ``a`` is not equal to
expression ``b``
@@ -3905,9 +3944,9 @@ class LowLevelILFunction:
:return: a comparison expression.
:rtype: ExpressionIndex
"""
- return self.expr(LowLevelILOperation.LLIL_CMP_NE, a, b, size = size)
+ return self.expr(LowLevelILOperation.LLIL_CMP_NE, a, b, size=size)
- def compare_signed_less_than(self, size:int, a:ExpressionIndex, b:ExpressionIndex) -> ExpressionIndex:
+ def compare_signed_less_than(self, size: int, a: ExpressionIndex, b: ExpressionIndex) -> ExpressionIndex:
"""
``compare_signed_less_than`` returns comparison expression of size ``size`` checking if expression ``a`` is
signed less than expression ``b``
@@ -3918,9 +3957,9 @@ class LowLevelILFunction:
:return: a comparison expression.
:rtype: ExpressionIndex
"""
- return self.expr(LowLevelILOperation.LLIL_CMP_SLT, a, b, size = size)
+ return self.expr(LowLevelILOperation.LLIL_CMP_SLT, a, b, size=size)
- def compare_unsigned_less_than(self, size:int, a:ExpressionIndex, b:ExpressionIndex) -> ExpressionIndex:
+ def compare_unsigned_less_than(self, size: int, a: ExpressionIndex, b: ExpressionIndex) -> ExpressionIndex:
"""
``compare_unsigned_less_than`` returns comparison expression of size ``size`` checking if expression ``a`` is
unsigned less than expression ``b``
@@ -3931,9 +3970,9 @@ class LowLevelILFunction:
:return: a comparison expression.
:rtype: ExpressionIndex
"""
- return self.expr(LowLevelILOperation.LLIL_CMP_ULT, a, b, size = size)
+ return self.expr(LowLevelILOperation.LLIL_CMP_ULT, a, b, size=size)
- def compare_signed_less_equal(self, size:int, a:ExpressionIndex, b:ExpressionIndex) -> ExpressionIndex:
+ def compare_signed_less_equal(self, size: int, a: ExpressionIndex, b: ExpressionIndex) -> ExpressionIndex:
"""
``compare_signed_less_equal`` returns comparison expression of size ``size`` checking if expression ``a`` is
signed less than or equal to expression ``b``
@@ -3944,9 +3983,9 @@ class LowLevelILFunction:
:return: a comparison expression.
:rtype: ExpressionIndex
"""
- return self.expr(LowLevelILOperation.LLIL_CMP_SLE, a, b, size = size)
+ return self.expr(LowLevelILOperation.LLIL_CMP_SLE, a, b, size=size)
- def compare_unsigned_less_equal(self, size:int, a:ExpressionIndex, b:ExpressionIndex) -> ExpressionIndex:
+ def compare_unsigned_less_equal(self, size: int, a: ExpressionIndex, b: ExpressionIndex) -> ExpressionIndex:
"""
``compare_unsigned_less_equal`` returns comparison expression of size ``size`` checking if expression ``a`` is
unsigned less than or equal to expression ``b``
@@ -3957,9 +3996,9 @@ class LowLevelILFunction:
:return: a comparison expression.
:rtype: ExpressionIndex
"""
- return self.expr(LowLevelILOperation.LLIL_CMP_ULE, a, b, size = size)
+ return self.expr(LowLevelILOperation.LLIL_CMP_ULE, a, b, size=size)
- def compare_signed_greater_equal(self, size:int, a:ExpressionIndex, b:ExpressionIndex) -> ExpressionIndex:
+ def compare_signed_greater_equal(self, size: int, a: ExpressionIndex, b: ExpressionIndex) -> ExpressionIndex:
"""
``compare_signed_greater_equal`` returns comparison expression of size ``size`` checking if expression ``a`` is
signed greater than or equal to expression ``b``
@@ -3970,9 +4009,9 @@ class LowLevelILFunction:
:return: a comparison expression.
:rtype: ExpressionIndex
"""
- return self.expr(LowLevelILOperation.LLIL_CMP_SGE, a, b, size = size)
+ return self.expr(LowLevelILOperation.LLIL_CMP_SGE, a, b, size=size)
- def compare_unsigned_greater_equal(self, size:int, a:ExpressionIndex, b:ExpressionIndex) -> ExpressionIndex:
+ def compare_unsigned_greater_equal(self, size: int, a: ExpressionIndex, b: ExpressionIndex) -> ExpressionIndex:
"""
``compare_unsigned_greater_equal`` returns comparison expression of size ``size`` checking if expression ``a``
is unsigned greater than or equal to expression ``b``
@@ -3983,9 +4022,9 @@ class LowLevelILFunction:
:return: a comparison expression.
:rtype: ExpressionIndex
"""
- return self.expr(LowLevelILOperation.LLIL_CMP_UGE, a, b, size = size)
+ return self.expr(LowLevelILOperation.LLIL_CMP_UGE, a, b, size=size)
- def compare_signed_greater_than(self, size:int, a:ExpressionIndex, b:ExpressionIndex) -> ExpressionIndex:
+ def compare_signed_greater_than(self, size: int, a: ExpressionIndex, b: ExpressionIndex) -> ExpressionIndex:
"""
``compare_signed_greater_than`` returns comparison expression of size ``size`` checking if expression ``a`` is
signed greater than or equal to expression ``b``
@@ -3996,9 +4035,9 @@ class LowLevelILFunction:
:return: a comparison expression.
:rtype: ExpressionIndex
"""
- return self.expr(LowLevelILOperation.LLIL_CMP_SGT, a, b, size = size)
+ return self.expr(LowLevelILOperation.LLIL_CMP_SGT, a, b, size=size)
- def compare_unsigned_greater_than(self, size:int, a:ExpressionIndex, b:ExpressionIndex) -> ExpressionIndex:
+ def compare_unsigned_greater_than(self, size: int, a: ExpressionIndex, b: ExpressionIndex) -> ExpressionIndex:
"""
``compare_unsigned_greater_than`` returns comparison expression of size ``size`` checking if expression ``a`` is
unsigned greater than or equal to expression ``b``
@@ -4009,10 +4048,10 @@ class LowLevelILFunction:
:return: a comparison expression.
:rtype: ExpressionIndex
"""
- return self.expr(LowLevelILOperation.LLIL_CMP_UGT, a, b, size = size)
+ return self.expr(LowLevelILOperation.LLIL_CMP_UGT, a, b, size=size)
- def test_bit(self, size:int, a:ExpressionIndex, b:ExpressionIndex) -> ExpressionIndex:
- return self.expr(LowLevelILOperation.LLIL_TEST_BIT, a, b, size = size)
+ def test_bit(self, size: int, a: ExpressionIndex, b: ExpressionIndex) -> ExpressionIndex:
+ return self.expr(LowLevelILOperation.LLIL_TEST_BIT, a, b, size=size)
def system_call(self) -> ExpressionIndex:
"""
@@ -4023,8 +4062,10 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_SYSCALL)
- def intrinsic(self, outputs:List[Union[ILFlag, ExpressionIndex]], intrinsic:'architecture.IntrinsicType',
- params:List[ExpressionIndex], flags:'architecture.FlagType'=None):
+ def intrinsic(
+ self, outputs: List[Union[ILFlag, ExpressionIndex]], intrinsic: 'architecture.IntrinsicType',
+ params: List[ExpressionIndex], flags: 'architecture.FlagType' = None
+ ):
"""
``intrinsic`` return an intrinsic expression.
@@ -4041,8 +4082,10 @@ class LowLevelILFunction:
for param in params:
param_list.append(param)
call_param = self.expr(LowLevelILOperation.LLIL_CALL_PARAM, len(params), self.add_operand_list(param_list))
- return self.expr(LowLevelILOperation.LLIL_INTRINSIC, len(outputs), self.add_operand_list(output_list),
- self.arch.get_intrinsic_index(intrinsic), call_param, flags = flags)
+ return self.expr(
+ LowLevelILOperation.LLIL_INTRINSIC, len(outputs), self.add_operand_list(output_list),
+ self.arch.get_intrinsic_index(intrinsic), call_param, flags=flags
+ )
def breakpoint(self) -> ExpressionIndex:
"""
@@ -4053,7 +4096,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_BP)
- def trap(self, value:int) -> ExpressionIndex:
+ def trap(self, value: int) -> ExpressionIndex:
"""
``trap`` returns a processor trap (interrupt) expression of the given integer ``value``.
@@ -4083,7 +4126,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_UNIMPL)
- def unimplemented_memory_ref(self, size:int, addr:ExpressionIndex) -> ExpressionIndex:
+ def unimplemented_memory_ref(self, size: int, addr: ExpressionIndex) -> ExpressionIndex:
"""
``unimplemented_memory_ref`` a memory reference to expression ``addr`` of size ``size`` with unimplemented operation.
@@ -4092,9 +4135,11 @@ class LowLevelILFunction:
:return: the unimplemented memory reference expression.
:rtype: ExpressionIndex
"""
- return self.expr(LowLevelILOperation.LLIL_UNIMPL_MEM, addr, size = size)
+ return self.expr(LowLevelILOperation.LLIL_UNIMPL_MEM, addr, size=size)
- def float_add(self, size:int, a:ExpressionIndex, b:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def float_add(
+ self, size: int, a: ExpressionIndex, b: ExpressionIndex, flags: 'architecture.FlagType' = None
+ ) -> ExpressionIndex:
"""
``float_add`` adds floating point expression ``a`` to expression ``b`` potentially setting flags ``flags``
and returning an expression of ``size`` bytes.
@@ -4108,7 +4153,9 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_FADD, a, b, size=size, flags=flags)
- def float_sub(self, size:int, a:ExpressionIndex, b:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def float_sub(
+ self, size: int, a: ExpressionIndex, b: ExpressionIndex, flags: 'architecture.FlagType' = None
+ ) -> ExpressionIndex:
"""
``float_sub`` subtracts floating point expression ``b`` from expression ``a`` potentially setting flags ``flags``
and returning an expression of ``size`` bytes.
@@ -4122,7 +4169,9 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_FSUB, a, b, size=size, flags=flags)
- def float_mult(self, size:int, a:ExpressionIndex, b:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def float_mult(
+ self, size: int, a: ExpressionIndex, b: ExpressionIndex, flags: 'architecture.FlagType' = None
+ ) -> ExpressionIndex:
"""
``float_mult`` multiplies floating point expression ``a`` by expression ``b`` potentially setting flags ``flags``
and returning an expression of ``size`` bytes.
@@ -4136,7 +4185,9 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_FMUL, a, b, size=size, flags=flags)
- def float_div(self, size:int, a:ExpressionIndex, b:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def float_div(
+ self, size: int, a: ExpressionIndex, b: ExpressionIndex, flags: 'architecture.FlagType' = None
+ ) -> ExpressionIndex:
"""
``float_div`` divides floating point expression ``a`` by expression ``b`` potentially setting flags ``flags``
and returning an expression of ``size`` bytes.
@@ -4150,7 +4201,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_FDIV, a, b, size=size, flags=flags)
- def float_sqrt(self, size:int, value:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def float_sqrt(self, size: int, value: ExpressionIndex, flags: 'architecture.FlagType' = None) -> ExpressionIndex:
"""
``float_sqrt`` returns square root of floating point expression ``value`` of size ``size`` potentially setting flags
@@ -4162,7 +4213,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_FSQRT, value, size=size, flags=flags)
- def float_neg(self, size:int, value:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def float_neg(self, size: int, value: ExpressionIndex, flags: 'architecture.FlagType' = None) -> ExpressionIndex:
"""
``float_neg`` returns sign negation of floating point expression ``value`` of size ``size`` potentially setting flags
@@ -4174,7 +4225,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_FNEG, value, size=size, flags=flags)
- def float_abs(self, size:int, value:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def float_abs(self, size: int, value: ExpressionIndex, flags: 'architecture.FlagType' = None) -> ExpressionIndex:
"""
``float_abs`` returns absolute value of floating point expression ``value`` of size ``size`` potentially setting flags
@@ -4186,7 +4237,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_FABS, value, size=size, flags=flags)
- def float_to_int(self, size:int, value:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def float_to_int(self, size: int, value: ExpressionIndex, flags: 'architecture.FlagType' = None) -> ExpressionIndex:
"""
``float_to_int`` returns integer value of floating point expression ``value`` of size ``size`` potentially setting flags
@@ -4198,7 +4249,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_FLOAT_TO_INT, value, size=size, flags=flags)
- def int_to_float(self, size:int, value:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def int_to_float(self, size: int, value: ExpressionIndex, flags: 'architecture.FlagType' = None) -> ExpressionIndex:
"""
``int_to_float`` returns floating point value of integer expression ``value`` of size ``size`` potentially setting flags
@@ -4210,7 +4261,9 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_INT_TO_FLOAT, value, size=size, flags=flags)
- def float_convert(self, size:int, value:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def float_convert(
+ self, size: int, value: ExpressionIndex, flags: 'architecture.FlagType' = None
+ ) -> ExpressionIndex:
"""
``int_to_float`` converts floating point value of expression ``value`` to size ``size`` potentially setting flags
@@ -4222,7 +4275,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_FLOAT_CONV, value, size=size, flags=flags)
- def round_to_int(self, size:int, value:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def round_to_int(self, size: int, value: ExpressionIndex, flags: 'architecture.FlagType' = None) -> ExpressionIndex:
"""
``round_to_int`` rounds a floating point value to the nearest integer
@@ -4234,7 +4287,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_ROUND_TO_INT, value, size=size, flags=flags)
- def floor(self, size:int, value:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def floor(self, size: int, value: ExpressionIndex, flags: 'architecture.FlagType' = None) -> ExpressionIndex:
"""
``floor`` rounds a floating point value to an integer towards negative infinity
@@ -4246,7 +4299,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_FLOOR, value, size=size, flags=flags)
- def ceil(self, size:int, value:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def ceil(self, size: int, value: ExpressionIndex, flags: 'architecture.FlagType' = None) -> ExpressionIndex:
"""
``ceil`` rounds a floating point value to an integer towards positive infinity
@@ -4258,7 +4311,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_CEIL, value, size=size, flags=flags)
- def float_trunc(self, size:int, value:ExpressionIndex, flags:'architecture.FlagType'=None) -> ExpressionIndex:
+ def float_trunc(self, size: int, value: ExpressionIndex, flags: 'architecture.FlagType' = None) -> ExpressionIndex:
"""
``float_trunc`` rounds a floating point value to an integer towards zero
@@ -4270,7 +4323,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_FTRUNC, value, size=size, flags=flags)
- def float_compare_equal(self, size:int, a:ExpressionIndex, b:ExpressionIndex) -> ExpressionIndex:
+ def float_compare_equal(self, size: int, a: ExpressionIndex, b: ExpressionIndex) -> ExpressionIndex:
"""
``float_compare_equal`` returns floating point comparison expression of size ``size`` checking if
expression ``a`` is equal to expression ``b``
@@ -4284,7 +4337,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_FCMP_E, a, b)
- def float_compare_not_equal(self, size:int, a:ExpressionIndex, b:ExpressionIndex) -> ExpressionIndex:
+ def float_compare_not_equal(self, size: int, a: ExpressionIndex, b: ExpressionIndex) -> ExpressionIndex:
"""
``float_compare_not_equal`` returns floating point comparison expression of size ``size`` checking if
expression ``a`` is not equal to expression ``b``
@@ -4298,7 +4351,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_FCMP_NE, a, b)
- def float_compare_less_than(self, size:int, a:ExpressionIndex, b:ExpressionIndex) -> ExpressionIndex:
+ def float_compare_less_than(self, size: int, a: ExpressionIndex, b: ExpressionIndex) -> ExpressionIndex:
"""
``float_compare_less_than`` returns floating point comparison expression of size ``size`` checking if
expression ``a`` is less than to expression ``b``
@@ -4312,7 +4365,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_FCMP_LT, a, b)
- def float_compare_less_equal(self, size:int, a:ExpressionIndex, b:ExpressionIndex) -> ExpressionIndex:
+ def float_compare_less_equal(self, size: int, a: ExpressionIndex, b: ExpressionIndex) -> ExpressionIndex:
"""
``float_compare_less_equal`` returns floating point comparison expression of size ``size`` checking if
expression ``a`` is less than or equal to expression ``b``
@@ -4326,7 +4379,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_FCMP_LE, a, b)
- def float_compare_greater_equal(self, size:int, a:ExpressionIndex, b:ExpressionIndex) -> ExpressionIndex:
+ def float_compare_greater_equal(self, size: int, a: ExpressionIndex, b: ExpressionIndex) -> ExpressionIndex:
"""
``float_compare_greater_equal`` returns floating point comparison expression of size ``size`` checking if
expression ``a`` is greater than or equal to expression ``b``
@@ -4340,7 +4393,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_FCMP_GE, a, b)
- def float_compare_greater_than(self, size:int, a:ExpressionIndex, b:ExpressionIndex) -> ExpressionIndex:
+ def float_compare_greater_than(self, size: int, a: ExpressionIndex, b: ExpressionIndex) -> ExpressionIndex:
"""
``float_compare_greater_than`` returns floating point comparison expression of size ``size`` checking if
expression ``a`` is greater than or equal to expression ``b``
@@ -4354,7 +4407,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_FCMP_GT, a, b)
- def float_compare_unordered(self, size:int, a:ExpressionIndex, b:ExpressionIndex) -> ExpressionIndex:
+ def float_compare_unordered(self, size: int, a: ExpressionIndex, b: ExpressionIndex) -> ExpressionIndex:
"""
``float_compare_unordered`` returns floating point comparison expression of size ``size`` checking if
expression ``a`` is unordered relative to expression ``b``
@@ -4368,7 +4421,7 @@ class LowLevelILFunction:
"""
return self.expr(LowLevelILOperation.LLIL_FCMP_UO, a, b)
- def goto(self, label:LowLevelILLabel) -> ExpressionIndex:
+ def goto(self, label: LowLevelILLabel) -> ExpressionIndex:
"""
``goto`` returns a goto expression which jumps to the provided LowLevelILLabel.
@@ -4378,7 +4431,7 @@ class LowLevelILFunction:
"""
return ExpressionIndex(core.BNLowLevelILGoto(self.handle, label.handle))
- def if_expr(self, operand:ExpressionIndex, t:LowLevelILLabel, f:LowLevelILLabel) -> ExpressionIndex:
+ def if_expr(self, operand: ExpressionIndex, t: LowLevelILLabel, f: LowLevelILLabel) -> ExpressionIndex:
"""
``if_expr`` returns the ``if`` expression which depending on condition ``operand`` jumps to the LowLevelILLabel
``t`` when the condition expression ``operand`` is non-zero and ``f`` when it's zero.
@@ -4391,7 +4444,7 @@ class LowLevelILFunction:
"""
return ExpressionIndex(core.BNLowLevelILIf(self.handle, operand, t.handle, f.handle))
- def mark_label(self, label:LowLevelILLabel) -> None:
+ def mark_label(self, label: LowLevelILLabel) -> None:
"""
``mark_label`` assigns a LowLevelILLabel to the current IL address.
@@ -4400,7 +4453,7 @@ class LowLevelILFunction:
"""
core.BNLowLevelILMarkLabel(self.handle, label.handle)
- def add_label_map(self, labels:Dict[int, LowLevelILLabel]) -> ExpressionIndex:
+ def add_label_map(self, labels: Dict[int, LowLevelILLabel]) -> ExpressionIndex:
"""
``add_label_map`` returns a label list expression for the given list of LowLevelILLabel objects.
@@ -4417,7 +4470,7 @@ class LowLevelILFunction:
return ExpressionIndex(core.BNLowLevelILAddLabelMap(self.handle, value_list, label_list, len(labels)))
- def add_operand_list(self, operands:List[Union[ExpressionIndex, ExpressionIndex]]) -> ExpressionIndex:
+ def add_operand_list(self, operands: List[Union[ExpressionIndex, ExpressionIndex]]) -> ExpressionIndex:
"""
``add_operand_list`` returns an operand list expression for the given list of integer operands.
@@ -4435,7 +4488,7 @@ class LowLevelILFunction:
raise Exception("Invalid operand type")
return ExpressionIndex(core.BNLowLevelILAddOperandList(self.handle, operand_list, len(operands)))
- def operand(self, n:int, expr:ExpressionIndex) -> ExpressionIndex:
+ def operand(self, n: int, expr: ExpressionIndex) -> ExpressionIndex:
"""
``operand`` sets the operand number of the expression ``expr`` and passes back ``expr`` without modification.
@@ -4463,7 +4516,7 @@ class LowLevelILFunction:
"""
core.BNGenerateLowLevelILSSAForm(self.handle)
- def add_label_for_address(self, arch:'architecture.Architecture', addr:int) -> None:
+ def add_label_for_address(self, arch: 'architecture.Architecture', addr: int) -> None:
"""
``add_label_for_address`` adds a low-level IL label for the given architecture ``arch`` at the given virtual
address ``addr``
@@ -4475,7 +4528,7 @@ class LowLevelILFunction:
arch = arch.handle
core.BNAddLowLevelILLabelForAddress(self.handle, arch, addr)
- def get_label_for_address(self, arch:'architecture.Architecture', addr:int) -> Optional[LowLevelILLabel]:
+ def get_label_for_address(self, arch: 'architecture.Architecture', addr: int) -> Optional[LowLevelILLabel]:
"""
``get_label_for_address`` returns the LowLevelILLabel for the given Architecture ``arch`` and IL address ``addr``.
@@ -4491,33 +4544,33 @@ class LowLevelILFunction:
return None
return LowLevelILLabel(label)
- def get_ssa_instruction_index(self, instr:InstructionIndex) -> InstructionIndex:
+ def get_ssa_instruction_index(self, instr: InstructionIndex) -> InstructionIndex:
return core.BNGetLowLevelILSSAInstructionIndex(self.handle, instr)
- def get_non_ssa_instruction_index(self, instr:InstructionIndex) -> InstructionIndex:
+ def get_non_ssa_instruction_index(self, instr: InstructionIndex) -> InstructionIndex:
return core.BNGetLowLevelILNonSSAInstructionIndex(self.handle, instr)
- def get_ssa_reg_definition(self, reg_ssa:SSARegister) -> Optional[LowLevelILInstruction]:
+ def get_ssa_reg_definition(self, reg_ssa: SSARegister) -> Optional[LowLevelILInstruction]:
reg = self.arch.get_reg_index(reg_ssa.reg)
result = core.BNGetLowLevelILSSARegisterDefinition(self.handle, reg, reg_ssa.version)
if result >= core.BNGetLowLevelILInstructionCount(self.handle):
return None
return self[result]
- def get_ssa_flag_definition(self, flag_ssa:SSAFlag) -> Optional[LowLevelILInstruction]:
+ def get_ssa_flag_definition(self, flag_ssa: SSAFlag) -> Optional[LowLevelILInstruction]:
flag = self.arch.get_flag_index(flag_ssa.flag)
result = core.BNGetLowLevelILSSAFlagDefinition(self.handle, flag, flag_ssa.version)
if result >= core.BNGetLowLevelILInstructionCount(self.handle):
return None
return self[result]
- def get_ssa_memory_definition(self, index:int) -> Optional[LowLevelILInstruction]:
+ def get_ssa_memory_definition(self, index: int) -> Optional[LowLevelILInstruction]:
result = core.BNGetLowLevelILSSAMemoryDefinition(self.handle, index)
if result >= core.BNGetLowLevelILInstructionCount(self.handle):
return None
return self[result]
- def get_ssa_reg_uses(self, reg_ssa:SSARegister) -> List[LowLevelILInstruction]:
+ def get_ssa_reg_uses(self, reg_ssa: SSARegister) -> List[LowLevelILInstruction]:
reg = self.arch.get_reg_index(reg_ssa.reg)
count = ctypes.c_ulonglong()
instrs = core.BNGetLowLevelILSSARegisterUses(self.handle, reg, reg_ssa.version, count)
@@ -4528,7 +4581,7 @@ class LowLevelILFunction:
core.BNFreeILInstructionList(instrs)
return result
- def get_ssa_flag_uses(self, flag_ssa:SSAFlag) -> List[LowLevelILInstruction]:
+ def get_ssa_flag_uses(self, flag_ssa: SSAFlag) -> List[LowLevelILInstruction]:
flag = self.arch.get_flag_index(flag_ssa.flag)
count = ctypes.c_ulonglong()
instrs = core.BNGetLowLevelILSSAFlagUses(self.handle, flag, flag_ssa.version, count)
@@ -4539,7 +4592,7 @@ class LowLevelILFunction:
core.BNFreeILInstructionList(instrs)
return result
- def get_ssa_memory_uses(self, index:int) -> List[LowLevelILInstruction]:
+ def get_ssa_memory_uses(self, index: int) -> List[LowLevelILInstruction]:
count = ctypes.c_ulonglong()
instrs = core.BNGetLowLevelILSSAMemoryUses(self.handle, index, count)
assert instrs is not None, "core.BNGetLowLevelILSSAMemoryUses returned None"
@@ -4549,19 +4602,20 @@ class LowLevelILFunction:
core.BNFreeILInstructionList(instrs)
return result
- def get_ssa_reg_value(self, reg_ssa:SSARegister) -> 'variable.RegisterValue':
+ def get_ssa_reg_value(self, reg_ssa: SSARegister) -> 'variable.RegisterValue':
reg = self.arch.get_reg_index(reg_ssa.reg)
value = core.BNGetLowLevelILSSARegisterValue(self.handle, reg, reg_ssa.version)
result = variable.RegisterValue.from_BNRegisterValue(value, self._arch)
return result
- def get_ssa_flag_value(self, flag_ssa:SSAFlag) -> 'variable.RegisterValue':
+ def get_ssa_flag_value(self, flag_ssa: SSAFlag) -> 'variable.RegisterValue':
flag = self.arch.get_flag_index(flag_ssa.flag)
value = core.BNGetLowLevelILSSAFlagValue(self.handle, flag, flag_ssa.version)
result = variable.RegisterValue.from_BNRegisterValue(value, self._arch)
return result
- def get_medium_level_il_instruction_index(self, instr:InstructionIndex) -> Optional['mediumlevelil.InstructionIndex']:
+ def get_medium_level_il_instruction_index(self,
+ instr: InstructionIndex) -> Optional['mediumlevelil.InstructionIndex']:
med_il = self.medium_level_il
if med_il is None:
return None
@@ -4570,7 +4624,7 @@ class LowLevelILFunction:
return None
return result
- def get_medium_level_il_expr_index(self, expr:ExpressionIndex) -> Optional['mediumlevelil.ExpressionIndex']:
+ def get_medium_level_il_expr_index(self, expr: ExpressionIndex) -> Optional['mediumlevelil.ExpressionIndex']:
med_il = self.medium_level_il
if med_il is None:
return None
@@ -4579,7 +4633,7 @@ class LowLevelILFunction:
return None
return result
- def get_medium_level_il_expr_indexes(self, expr:ExpressionIndex) -> List['mediumlevelil.ExpressionIndex']:
+ def get_medium_level_il_expr_indexes(self, expr: ExpressionIndex) -> List['mediumlevelil.ExpressionIndex']:
count = ctypes.c_ulonglong()
exprs = core.BNGetMediumLevelILExprIndexes(self.handle, expr, count)
assert exprs is not None, "core.BNGetMediumLevelILExprIndexes returned None"
@@ -4589,7 +4643,7 @@ class LowLevelILFunction:
core.BNFreeILInstructionList(exprs)
return result
- def get_mapped_medium_level_il_instruction_index(self, instr:InstructionIndex) -> Optional[InstructionIndex]:
+ def get_mapped_medium_level_il_instruction_index(self, instr: InstructionIndex) -> Optional[InstructionIndex]:
med_il = self.mapped_medium_level_il
if med_il is None:
return None
@@ -4598,7 +4652,7 @@ class LowLevelILFunction:
return None
return result
- def get_mapped_medium_level_il_expr_index(self, expr:ExpressionIndex) -> Optional['mediumlevelil.ExpressionIndex']:
+ def get_mapped_medium_level_il_expr_index(self, expr: ExpressionIndex) -> Optional['mediumlevelil.ExpressionIndex']:
med_il = self.mapped_medium_level_il
if med_il is None:
return None
@@ -4607,7 +4661,7 @@ class LowLevelILFunction:
return None
return result
- def get_high_level_il_instruction_index(self, instr:InstructionIndex) -> Optional['highlevelil.InstructionIndex']:
+ def get_high_level_il_instruction_index(self, instr: InstructionIndex) -> Optional['highlevelil.InstructionIndex']:
med_il = self.medium_level_il
if med_il is None:
return None
@@ -4616,7 +4670,7 @@ class LowLevelILFunction:
return None
return med_il.get_high_level_il_instruction_index(mlil_instr)
- def get_high_level_il_expr_index(self, expr:ExpressionIndex) -> Optional['highlevelil.ExpressionIndex']:
+ def get_high_level_il_expr_index(self, expr: ExpressionIndex) -> Optional['highlevelil.ExpressionIndex']:
med_il = self.medium_level_il
if med_il is None:
return None
@@ -4625,7 +4679,7 @@ class LowLevelILFunction:
return None
return med_il.get_high_level_il_expr_index(mlil_expr)
- def create_graph(self, settings:Optional['function.DisassemblySettings']=None) -> flowgraph.CoreFlowGraph:
+ def create_graph(self, settings: Optional['function.DisassemblySettings'] = None) -> flowgraph.CoreFlowGraph:
if settings is not None:
settings_obj = settings.handle
else:
@@ -4634,7 +4688,9 @@ class LowLevelILFunction:
class LowLevelILBasicBlock(basicblock.BasicBlock):
- def __init__(self, handle:core.BNBasicBlockHandle, owner:LowLevelILFunction, view:Optional['binaryview.BinaryView']):
+ def __init__(
+ self, handle: core.BNBasicBlockHandle, owner: LowLevelILFunction, view: Optional['binaryview.BinaryView']
+ ):
super(LowLevelILBasicBlock, self).__init__(handle, view)
self._il_function = owner
@@ -4681,13 +4737,13 @@ class LowLevelILBasicBlock(basicblock.BasicBlock):
return self._il_function
-def LLIL_TEMP(n:Union[ILRegister, int]) -> int:
+def LLIL_TEMP(n: Union[ILRegister, int]) -> int:
return int(n) | 0x80000000
-def LLIL_REG_IS_TEMP(n:Union[ILRegister, int]) -> bool:
+def LLIL_REG_IS_TEMP(n: Union[ILRegister, int]) -> bool:
return (int(n) & 0x80000000) != 0
-def LLIL_GET_TEMP_REG_INDEX(n:Union[ILRegister, int]) -> int:
+def LLIL_GET_TEMP_REG_INDEX(n: Union[ILRegister, int]) -> int:
return int(n) & 0x7fffffff
diff --git a/python/mediumlevelil.py b/python/mediumlevelil.py
index 51413c79..e0bc60d1 100644
--- a/python/mediumlevelil.py
+++ b/python/mediumlevelil.py
@@ -37,9 +37,11 @@ from . import variable
from . import architecture
from . import binaryview
from .interaction import show_graph_report
-from .commonil import (BaseILInstruction, Constant, BinaryOperation, UnaryOperation, Comparison, SSA,
- Phi, FloatingPoint, ControlFlow, Terminal, Call, Localcall, Syscall, Tailcall, Return,
- Signed, Arithmetic, Carry, DoublePrecision, Memory, Load, Store, RegisterStack, SetVar)
+from .commonil import (
+ BaseILInstruction, Constant, BinaryOperation, UnaryOperation, Comparison, SSA, Phi, FloatingPoint, ControlFlow,
+ Terminal, Call, Localcall, Syscall, Tailcall, Return, Signed, Arithmetic, Carry, DoublePrecision, Memory, Load,
+ Store, RegisterStack, SetVar
+)
TokenList = List['function.InstructionTextToken']
ExpressionIndex = NewType('ExpressionIndex', int)
@@ -47,25 +49,16 @@ InstructionIndex = NewType('InstructionIndex', int)
MLILInstructionsType = Generator['MediumLevelILInstruction', None, None]
MLILBasicBlocksType = Generator['MediumLevelILBasicBlock', None, None]
OperandsType = Tuple[ExpressionIndex, ExpressionIndex, ExpressionIndex, ExpressionIndex, ExpressionIndex]
-MediumLevelILOperandType = Union[
- int,
- float,
- 'MediumLevelILOperationAndSize',
- 'MediumLevelILInstruction',
- 'lowlevelil.ILIntrinsic',
- 'variable.Variable',
- 'SSAVariable',
- List[int],
- List['variable.Variable'],
- List['SSAVariable'],
- List['MediumLevelILInstruction'],
- Mapping[int, int]
- ]
+MediumLevelILOperandType = Union[int, float, 'MediumLevelILOperationAndSize', 'MediumLevelILInstruction',
+ 'lowlevelil.ILIntrinsic', 'variable.Variable', 'SSAVariable', List[int],
+ List['variable.Variable'], List['SSAVariable'], List['MediumLevelILInstruction'],
+ Mapping[int, int]]
+
@dataclass(frozen=True, repr=False, order=True)
class SSAVariable:
- var:'variable.Variable'
- version:int
+ var: 'variable.Variable'
+ version: int
def __repr__(self):
return f"<ssa {self.var} version {self.version}>"
@@ -88,7 +81,7 @@ class SSAVariable:
class MediumLevelILLabel:
- def __init__(self, handle:Optional[core.BNMediumLevelILLabel]=None):
+ def __init__(self, handle: Optional[core.BNMediumLevelILLabel] = None):
if handle is None:
self.handle = (core.BNMediumLevelILLabel * 1)()
core.BNMediumLevelILInitLabel(self.handle)
@@ -98,8 +91,8 @@ class MediumLevelILLabel:
@dataclass(frozen=True, repr=False)
class MediumLevelILOperationAndSize:
- operation:MediumLevelILOperation
- size:int
+ operation: MediumLevelILOperation
+ size: int
def __repr__(self):
if self.size == 0:
@@ -109,16 +102,15 @@ class MediumLevelILOperationAndSize:
@dataclass(frozen=True)
class CoreMediumLevelILInstruction:
- operation:MediumLevelILOperation
- source_operand:int
- size:int
- operands:OperandsType
- address:int
-
+ operation: MediumLevelILOperation
+ source_operand: int
+ size: int
+ operands: OperandsType
+ address: int
@classmethod
- def from_BNMediumLevelILInstruction(cls, instr:core.BNMediumLevelILInstruction) -> 'CoreMediumLevelILInstruction':
- operands:OperandsType = tuple([ExpressionIndex(instr.operands[i]) for i in range(5)]) # type: ignore
+ def from_BNMediumLevelILInstruction(cls, instr: core.BNMediumLevelILInstruction) -> 'CoreMediumLevelILInstruction':
+ operands: OperandsType = tuple([ExpressionIndex(instr.operands[i]) for i in range(5)]) # type: ignore
return cls(MediumLevelILOperation(instr.operation), instr.sourceOperand, instr.size, operands, instr.address)
@@ -130,142 +122,199 @@ class MediumLevelILInstruction(BaseILInstruction):
Infix notation is thus more natural to read than other notations (e.g. x86 ``mov eax, 0`` vs. MLIL ``eax = 0``).
"""
- function:'MediumLevelILFunction'
- expr_index:ExpressionIndex
- instr:CoreMediumLevelILInstruction
- instr_index:InstructionIndex
- ILOperations:ClassVar[Mapping[MediumLevelILOperation, List[Tuple[str,str]]]] = {
- MediumLevelILOperation.MLIL_NOP: [],
- MediumLevelILOperation.MLIL_SET_VAR: [("dest", "var"), ("src", "expr")],
- MediumLevelILOperation.MLIL_SET_VAR_FIELD: [("dest", "var"), ("offset", "int"), ("src", "expr")],
- MediumLevelILOperation.MLIL_SET_VAR_SPLIT: [("high", "var"), ("low", "var"), ("src", "expr")],
- MediumLevelILOperation.MLIL_LOAD: [("src", "expr")],
- MediumLevelILOperation.MLIL_LOAD_STRUCT: [("src", "expr"), ("offset", "int")],
- MediumLevelILOperation.MLIL_STORE: [("dest", "expr"), ("src", "expr")],
- MediumLevelILOperation.MLIL_STORE_STRUCT: [("dest", "expr"), ("offset", "int"), ("src", "expr")],
- MediumLevelILOperation.MLIL_VAR: [("src", "var")],
- MediumLevelILOperation.MLIL_VAR_FIELD: [("src", "var"), ("offset", "int")],
- MediumLevelILOperation.MLIL_VAR_SPLIT: [("high", "var"), ("low", "var")],
- MediumLevelILOperation.MLIL_ADDRESS_OF: [("src", "var")],
- MediumLevelILOperation.MLIL_ADDRESS_OF_FIELD: [("src", "var"), ("offset", "int")],
- MediumLevelILOperation.MLIL_CONST: [("constant", "int")],
- MediumLevelILOperation.MLIL_CONST_PTR: [("constant", "int")],
- MediumLevelILOperation.MLIL_EXTERN_PTR: [("constant", "int"), ("offset", "int")],
- MediumLevelILOperation.MLIL_FLOAT_CONST: [("constant", "float")],
- MediumLevelILOperation.MLIL_IMPORT: [("constant", "int")],
- MediumLevelILOperation.MLIL_ADD: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_ADC: [("left", "expr"), ("right", "expr"), ("carry", "expr")],
- MediumLevelILOperation.MLIL_SUB: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_SBB: [("left", "expr"), ("right", "expr"), ("carry", "expr")],
- MediumLevelILOperation.MLIL_AND: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_OR: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_XOR: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_LSL: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_LSR: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_ASR: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_ROL: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_RLC: [("left", "expr"), ("right", "expr"), ("carry", "expr")],
- MediumLevelILOperation.MLIL_ROR: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_RRC: [("left", "expr"), ("right", "expr"), ("carry", "expr")],
- MediumLevelILOperation.MLIL_MUL: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_MULU_DP: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_MULS_DP: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_DIVU: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_DIVU_DP: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_DIVS: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_DIVS_DP: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_MODU: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_MODU_DP: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_MODS: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_MODS_DP: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_NEG: [("src", "expr")],
- MediumLevelILOperation.MLIL_NOT: [("src", "expr")],
- MediumLevelILOperation.MLIL_SX: [("src", "expr")],
- MediumLevelILOperation.MLIL_ZX: [("src", "expr")],
- MediumLevelILOperation.MLIL_LOW_PART: [("src", "expr")],
- MediumLevelILOperation.MLIL_JUMP: [("dest", "expr")],
- MediumLevelILOperation.MLIL_JUMP_TO: [("dest", "expr"), ("targets", "target_map")],
- MediumLevelILOperation.MLIL_RET_HINT: [("dest", "expr")],
- MediumLevelILOperation.MLIL_CALL: [("output", "var_list"), ("dest", "expr"), ("params", "expr_list")],
- MediumLevelILOperation.MLIL_CALL_UNTYPED: [("output", "expr"), ("dest", "expr"), ("params", "expr"), ("stack", "expr")],
- MediumLevelILOperation.MLIL_CALL_OUTPUT: [("dest", "var_list")],
- MediumLevelILOperation.MLIL_CALL_PARAM: [("src", "var_list")],
- MediumLevelILOperation.MLIL_RET: [("src", "expr_list")],
- MediumLevelILOperation.MLIL_NORET: [],
- MediumLevelILOperation.MLIL_IF: [("condition", "expr"), ("true", "int"), ("false", "int")],
- MediumLevelILOperation.MLIL_GOTO: [("dest", "int")],
- MediumLevelILOperation.MLIL_CMP_E: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_CMP_NE: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_CMP_SLT: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_CMP_ULT: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_CMP_SLE: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_CMP_ULE: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_CMP_SGE: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_CMP_UGE: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_CMP_SGT: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_CMP_UGT: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_TEST_BIT: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_BOOL_TO_INT: [("src", "expr")],
- MediumLevelILOperation.MLIL_ADD_OVERFLOW: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_SYSCALL: [("output", "var_list"), ("params", "expr_list")],
- MediumLevelILOperation.MLIL_SYSCALL_UNTYPED: [("output", "expr"), ("params", "expr"), ("stack", "expr")],
- MediumLevelILOperation.MLIL_TAILCALL: [("output", "var_list"), ("dest", "expr"), ("params", "expr_list")],
- MediumLevelILOperation.MLIL_TAILCALL_UNTYPED: [("output", "expr"), ("dest", "expr"), ("params", "expr"), ("stack", "expr")],
- MediumLevelILOperation.MLIL_BP: [],
- MediumLevelILOperation.MLIL_TRAP: [("vector", "int")],
- MediumLevelILOperation.MLIL_INTRINSIC: [("output", "var_list"), ("intrinsic", "intrinsic"), ("params", "expr_list")],
- MediumLevelILOperation.MLIL_INTRINSIC_SSA: [("output", "var_ssa_list"), ("intrinsic", "intrinsic"), ("params", "expr_list")],
- MediumLevelILOperation.MLIL_FREE_VAR_SLOT: [("dest", "var")],
- MediumLevelILOperation.MLIL_FREE_VAR_SLOT_SSA: [("prev", "var_ssa_dest_and_src")],
- MediumLevelILOperation.MLIL_UNDEF: [],
- MediumLevelILOperation.MLIL_UNIMPL: [],
- MediumLevelILOperation.MLIL_UNIMPL_MEM: [("src", "expr")],
- MediumLevelILOperation.MLIL_FADD: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_FSUB: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_FMUL: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_FDIV: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_FSQRT: [("src", "expr")],
- MediumLevelILOperation.MLIL_FNEG: [("src", "expr")],
- MediumLevelILOperation.MLIL_FABS: [("src", "expr")],
- MediumLevelILOperation.MLIL_FLOAT_TO_INT: [("src", "expr")],
- MediumLevelILOperation.MLIL_INT_TO_FLOAT: [("src", "expr")],
- MediumLevelILOperation.MLIL_FLOAT_CONV: [("src", "expr")],
- MediumLevelILOperation.MLIL_ROUND_TO_INT: [("src", "expr")],
- MediumLevelILOperation.MLIL_FLOOR: [("src", "expr")],
- MediumLevelILOperation.MLIL_CEIL: [("src", "expr")],
- MediumLevelILOperation.MLIL_FTRUNC: [("src", "expr")],
- MediumLevelILOperation.MLIL_FCMP_E: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_FCMP_NE: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_FCMP_LT: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_FCMP_LE: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_FCMP_GE: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_FCMP_GT: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_FCMP_O: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_FCMP_UO: [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_SET_VAR_SSA: [("dest", "var_ssa"), ("src", "expr")],
- MediumLevelILOperation.MLIL_SET_VAR_SSA_FIELD: [("prev", "var_ssa_dest_and_src"), ("offset", "int"), ("src", "expr")],
- MediumLevelILOperation.MLIL_SET_VAR_SPLIT_SSA: [("high", "var_ssa"), ("low", "var_ssa"), ("src", "expr")],
- MediumLevelILOperation.MLIL_SET_VAR_ALIASED: [("prev", "var_ssa_dest_and_src"), ("src", "expr")],
- MediumLevelILOperation.MLIL_SET_VAR_ALIASED_FIELD: [("prev", "var_ssa_dest_and_src"), ("offset", "int"), ("src", "expr")],
- MediumLevelILOperation.MLIL_VAR_SSA: [("src", "var_ssa")],
- MediumLevelILOperation.MLIL_VAR_SSA_FIELD: [("src", "var_ssa"), ("offset", "int")],
- MediumLevelILOperation.MLIL_VAR_ALIASED: [("src", "var_ssa")],
- MediumLevelILOperation.MLIL_VAR_ALIASED_FIELD: [("src", "var_ssa"), ("offset", "int")],
- MediumLevelILOperation.MLIL_VAR_SPLIT_SSA: [("high", "var_ssa"), ("low", "var_ssa")],
- MediumLevelILOperation.MLIL_CALL_SSA: [("output", "expr"), ("dest", "expr"), ("params", "expr_list"), ("src_memory", "int")],
- MediumLevelILOperation.MLIL_CALL_UNTYPED_SSA: [("output", "expr"), ("dest", "expr"), ("params", "expr"), ("stack", "expr")],
- MediumLevelILOperation.MLIL_SYSCALL_SSA: [("output", "expr"), ("params", "expr_list"), ("src_memory", "int")],
- MediumLevelILOperation.MLIL_SYSCALL_UNTYPED_SSA: [("output", "expr"), ("params", "expr"), ("stack", "expr")],
- MediumLevelILOperation.MLIL_TAILCALL_SSA: [("output", "expr"), ("dest", "expr"), ("params", "expr_list"), ("src_memory", "int")],
- MediumLevelILOperation.MLIL_TAILCALL_UNTYPED_SSA: [("output", "expr"), ("dest", "expr"), ("params", "expr"), ("stack", "expr")],
- MediumLevelILOperation.MLIL_CALL_OUTPUT_SSA: [("dest_memory", "int"), ("dest", "var_ssa_list")],
- MediumLevelILOperation.MLIL_CALL_PARAM_SSA: [("src_memory", "int"), ("src", "var_ssa_list")],
- MediumLevelILOperation.MLIL_LOAD_SSA: [("src", "expr"), ("src_memory", "int")],
- MediumLevelILOperation.MLIL_LOAD_STRUCT_SSA: [("src", "expr"), ("offset", "int"), ("src_memory", "int")],
- MediumLevelILOperation.MLIL_STORE_SSA: [("dest", "expr"), ("dest_memory", "int"), ("src_memory", "int"), ("src", "expr")],
- MediumLevelILOperation.MLIL_STORE_STRUCT_SSA: [("dest", "expr"), ("offset", "int"), ("dest_memory", "int"), ("src_memory", "int"), ("src", "expr")],
- MediumLevelILOperation.MLIL_VAR_PHI: [("dest", "var_ssa"), ("src", "var_ssa_list")],
- MediumLevelILOperation.MLIL_MEM_PHI: [("dest_memory", "int"), ("src_memory", "int_list")]
+ function: 'MediumLevelILFunction'
+ expr_index: ExpressionIndex
+ instr: CoreMediumLevelILInstruction
+ instr_index: InstructionIndex
+ ILOperations: ClassVar[Mapping[MediumLevelILOperation, List[Tuple[str, str]]]] = {
+ MediumLevelILOperation.MLIL_NOP: [], MediumLevelILOperation.MLIL_SET_VAR: [("dest", "var"), ("src", "expr")],
+ MediumLevelILOperation.MLIL_SET_VAR_FIELD: [("dest", "var"), ("offset", "int"),
+ ("src", "expr")], MediumLevelILOperation.MLIL_SET_VAR_SPLIT: [
+ ("high", "var"), ("low", "var"), ("src", "expr")
+ ], MediumLevelILOperation.MLIL_LOAD: [("src", "expr")],
+ MediumLevelILOperation.MLIL_LOAD_STRUCT: [("src", "expr"),
+ ("offset", "int")], MediumLevelILOperation.MLIL_STORE: [
+ ("dest", "expr"), ("src", "expr")
+ ], MediumLevelILOperation.MLIL_STORE_STRUCT: [("dest", "expr"),
+ ("offset", "int"),
+ ("src", "expr")],
+ MediumLevelILOperation.MLIL_VAR: [("src", "var")], MediumLevelILOperation.MLIL_VAR_FIELD: [
+ ("src", "var"), ("offset", "int")
+ ], MediumLevelILOperation.MLIL_VAR_SPLIT: [("high", "var"), ("low", "var")],
+ MediumLevelILOperation.MLIL_ADDRESS_OF: [("src", "var")], MediumLevelILOperation.MLIL_ADDRESS_OF_FIELD: [
+ ("src", "var"), ("offset", "int")
+ ], MediumLevelILOperation.MLIL_CONST: [("constant", "int")], MediumLevelILOperation.MLIL_CONST_PTR: [
+ ("constant", "int")
+ ], MediumLevelILOperation.MLIL_EXTERN_PTR: [
+ ("constant", "int"), ("offset", "int")
+ ], MediumLevelILOperation.MLIL_FLOAT_CONST: [("constant", "float")], MediumLevelILOperation.MLIL_IMPORT: [
+ ("constant", "int")
+ ], MediumLevelILOperation.MLIL_ADD: [("left", "expr"), ("right", "expr")], MediumLevelILOperation.MLIL_ADC: [
+ ("left", "expr"), ("right", "expr"), ("carry", "expr")
+ ], MediumLevelILOperation.MLIL_SUB: [("left", "expr"), ("right", "expr")], MediumLevelILOperation.MLIL_SBB: [
+ ("left", "expr"), ("right", "expr"), ("carry", "expr")
+ ], MediumLevelILOperation.MLIL_AND: [("left", "expr"), ("right", "expr")], MediumLevelILOperation.MLIL_OR: [
+ ("left", "expr"), ("right", "expr")
+ ], MediumLevelILOperation.MLIL_XOR: [("left", "expr"), ("right", "expr")], MediumLevelILOperation.MLIL_LSL: [
+ ("left", "expr"), ("right", "expr")
+ ], MediumLevelILOperation.MLIL_LSR: [("left", "expr"), ("right", "expr")], MediumLevelILOperation.MLIL_ASR: [
+ ("left", "expr"), ("right", "expr")
+ ], MediumLevelILOperation.MLIL_ROL: [("left", "expr"), ("right", "expr")], MediumLevelILOperation.MLIL_RLC: [
+ ("left", "expr"), ("right", "expr"), ("carry", "expr")
+ ], MediumLevelILOperation.MLIL_ROR: [("left", "expr"),
+ ("right", "expr")], MediumLevelILOperation.MLIL_RRC: [("left", "expr"),
+ ("right", "expr"),
+ ("carry", "expr")],
+ MediumLevelILOperation.MLIL_MUL: [("left", "expr"), ("right", "expr")], MediumLevelILOperation.MLIL_MULU_DP: [
+ ("left", "expr"), ("right", "expr")
+ ], MediumLevelILOperation.MLIL_MULS_DP: [("left", "expr"),
+ ("right", "expr")], MediumLevelILOperation.MLIL_DIVU: [
+ ("left", "expr"), ("right", "expr")
+ ], MediumLevelILOperation.MLIL_DIVU_DP: [("left", "expr"),
+ ("right", "expr")],
+ MediumLevelILOperation.MLIL_DIVS: [("left", "expr"), ("right", "expr")], MediumLevelILOperation.MLIL_DIVS_DP: [
+ ("left", "expr"), ("right", "expr")
+ ], MediumLevelILOperation.MLIL_MODU: [("left", "expr"),
+ ("right", "expr")], MediumLevelILOperation.MLIL_MODU_DP: [
+ ("left", "expr"), ("right", "expr")
+ ], MediumLevelILOperation.MLIL_MODS: [("left", "expr"),
+ ("right", "expr")],
+ MediumLevelILOperation.MLIL_MODS_DP: [("left", "expr"), ("right", "expr")], MediumLevelILOperation.MLIL_NEG: [
+ ("src", "expr")
+ ], MediumLevelILOperation.MLIL_NOT: [("src", "expr")], MediumLevelILOperation.MLIL_SX: [
+ ("src", "expr")
+ ], MediumLevelILOperation.MLIL_ZX: [("src", "expr")], MediumLevelILOperation.MLIL_LOW_PART: [
+ ("src", "expr")
+ ], MediumLevelILOperation.MLIL_JUMP: [("dest", "expr")], MediumLevelILOperation.MLIL_JUMP_TO: [
+ ("dest", "expr"), ("targets", "target_map")
+ ], MediumLevelILOperation.MLIL_RET_HINT: [("dest", "expr")], MediumLevelILOperation.MLIL_CALL: [
+ ("output", "var_list"), ("dest", "expr"), ("params", "expr_list")
+ ], MediumLevelILOperation.MLIL_CALL_UNTYPED: [
+ ("output", "expr"), ("dest", "expr"), ("params", "expr"), ("stack", "expr")
+ ], MediumLevelILOperation.MLIL_CALL_OUTPUT: [("dest", "var_list")], MediumLevelILOperation.MLIL_CALL_PARAM: [
+ ("src", "var_list")
+ ], MediumLevelILOperation.MLIL_RET: [
+ ("src", "expr_list")
+ ], MediumLevelILOperation.MLIL_NORET: [], MediumLevelILOperation.MLIL_IF: [
+ ("condition", "expr"), ("true", "int"), ("false", "int")
+ ], MediumLevelILOperation.MLIL_GOTO: [("dest", "int")], MediumLevelILOperation.MLIL_CMP_E: [
+ ("left", "expr"), ("right", "expr")
+ ], MediumLevelILOperation.MLIL_CMP_NE: [("left", "expr"),
+ ("right", "expr")], MediumLevelILOperation.MLIL_CMP_SLT: [
+ ("left", "expr"), ("right", "expr")
+ ], MediumLevelILOperation.MLIL_CMP_ULT: [
+ ("left", "expr"), ("right", "expr")
+ ], MediumLevelILOperation.MLIL_CMP_SLE: [
+ ("left", "expr"), ("right", "expr")
+ ], MediumLevelILOperation.MLIL_CMP_ULE: [
+ ("left", "expr"), ("right", "expr")
+ ], MediumLevelILOperation.MLIL_CMP_SGE: [
+ ("left", "expr"), ("right", "expr")
+ ], MediumLevelILOperation.MLIL_CMP_UGE: [
+ ("left", "expr"), ("right", "expr")
+ ], MediumLevelILOperation.MLIL_CMP_SGT: [
+ ("left", "expr"), ("right", "expr")
+ ], MediumLevelILOperation.MLIL_CMP_UGT: [
+ ("left", "expr"), ("right", "expr")
+ ], MediumLevelILOperation.MLIL_TEST_BIT: [("left", "expr"),
+ ("right", "expr")],
+ MediumLevelILOperation.MLIL_BOOL_TO_INT: [("src", "expr")], MediumLevelILOperation.MLIL_ADD_OVERFLOW: [
+ ("left", "expr"), ("right", "expr")
+ ], MediumLevelILOperation.MLIL_SYSCALL: [
+ ("output", "var_list"), ("params", "expr_list")
+ ], MediumLevelILOperation.MLIL_SYSCALL_UNTYPED: [
+ ("output", "expr"), ("params", "expr"), ("stack", "expr")
+ ], MediumLevelILOperation.MLIL_TAILCALL: [
+ ("output", "var_list"), ("dest", "expr"), ("params", "expr_list")
+ ], MediumLevelILOperation.MLIL_TAILCALL_UNTYPED: [("output", "expr"), ("dest", "expr"), ("params", "expr"),
+ ("stack", "expr")], MediumLevelILOperation.MLIL_BP: [],
+ MediumLevelILOperation.MLIL_TRAP: [("vector", "int")], MediumLevelILOperation.MLIL_INTRINSIC: [
+ ("output", "var_list"), ("intrinsic", "intrinsic"), ("params", "expr_list")
+ ], MediumLevelILOperation.MLIL_INTRINSIC_SSA: [
+ ("output", "var_ssa_list"), ("intrinsic", "intrinsic"), ("params", "expr_list")
+ ], MediumLevelILOperation.MLIL_FREE_VAR_SLOT: [
+ ("dest", "var")
+ ], MediumLevelILOperation.MLIL_FREE_VAR_SLOT_SSA: [
+ ("prev", "var_ssa_dest_and_src")
+ ], MediumLevelILOperation.MLIL_UNDEF: [], MediumLevelILOperation.MLIL_UNIMPL: [],
+ MediumLevelILOperation.MLIL_UNIMPL_MEM: [("src", "expr")], MediumLevelILOperation.MLIL_FADD: [
+ ("left", "expr"), ("right", "expr")
+ ], MediumLevelILOperation.MLIL_FSUB: [("left", "expr"), ("right", "expr")], MediumLevelILOperation.MLIL_FMUL: [
+ ("left", "expr"), ("right", "expr")
+ ], MediumLevelILOperation.MLIL_FDIV: [("left", "expr"), ("right", "expr")], MediumLevelILOperation.MLIL_FSQRT: [
+ ("src", "expr")
+ ], MediumLevelILOperation.MLIL_FNEG: [("src", "expr")], MediumLevelILOperation.MLIL_FABS: [
+ ("src", "expr")
+ ], MediumLevelILOperation.MLIL_FLOAT_TO_INT: [("src", "expr")], MediumLevelILOperation.MLIL_INT_TO_FLOAT: [
+ ("src", "expr")
+ ], MediumLevelILOperation.MLIL_FLOAT_CONV: [("src", "expr")], MediumLevelILOperation.MLIL_ROUND_TO_INT: [
+ ("src", "expr")
+ ], MediumLevelILOperation.MLIL_FLOOR: [("src", "expr")], MediumLevelILOperation.MLIL_CEIL: [
+ ("src", "expr")
+ ], MediumLevelILOperation.MLIL_FTRUNC: [("src", "expr")], MediumLevelILOperation.MLIL_FCMP_E: [
+ ("left", "expr"), ("right", "expr")
+ ], MediumLevelILOperation.MLIL_FCMP_NE: [
+ ("left", "expr"), ("right", "expr")
+ ], MediumLevelILOperation.MLIL_FCMP_LT: [
+ ("left", "expr"), ("right", "expr")
+ ], MediumLevelILOperation.MLIL_FCMP_LE: [
+ ("left", "expr"), ("right", "expr")
+ ], MediumLevelILOperation.MLIL_FCMP_GE: [
+ ("left", "expr"), ("right", "expr")
+ ], MediumLevelILOperation.MLIL_FCMP_GT: [
+ ("left", "expr"), ("right", "expr")
+ ], MediumLevelILOperation.MLIL_FCMP_O: [
+ ("left", "expr"), ("right", "expr")
+ ], MediumLevelILOperation.MLIL_FCMP_UO: [
+ ("left", "expr"), ("right", "expr")
+ ], MediumLevelILOperation.MLIL_SET_VAR_SSA: [
+ ("dest", "var_ssa"), ("src", "expr")
+ ], MediumLevelILOperation.MLIL_SET_VAR_SSA_FIELD: [
+ ("prev", "var_ssa_dest_and_src"), ("offset", "int"), ("src", "expr")
+ ], MediumLevelILOperation.MLIL_SET_VAR_SPLIT_SSA: [
+ ("high", "var_ssa"), ("low", "var_ssa"), ("src", "expr")
+ ], MediumLevelILOperation.MLIL_SET_VAR_ALIASED: [
+ ("prev", "var_ssa_dest_and_src"), ("src", "expr")
+ ], MediumLevelILOperation.MLIL_SET_VAR_ALIASED_FIELD: [
+ ("prev", "var_ssa_dest_and_src"), ("offset", "int"), ("src", "expr")
+ ], MediumLevelILOperation.MLIL_VAR_SSA: [("src", "var_ssa")], MediumLevelILOperation.MLIL_VAR_SSA_FIELD: [
+ ("src", "var_ssa"), ("offset", "int")
+ ], MediumLevelILOperation.MLIL_VAR_ALIASED: [
+ ("src", "var_ssa")
+ ], MediumLevelILOperation.MLIL_VAR_ALIASED_FIELD: [
+ ("src", "var_ssa"), ("offset", "int")
+ ], MediumLevelILOperation.MLIL_VAR_SPLIT_SSA: [
+ ("high", "var_ssa"), ("low", "var_ssa")
+ ], MediumLevelILOperation.MLIL_CALL_SSA: [
+ ("output", "expr"), ("dest", "expr"),
+ ("params", "expr_list"), ("src_memory", "int")
+ ], MediumLevelILOperation.MLIL_CALL_UNTYPED_SSA: [
+ ("output", "expr"), ("dest", "expr"), ("params", "expr"), ("stack", "expr")
+ ], MediumLevelILOperation.MLIL_SYSCALL_SSA: [
+ ("output", "expr"), ("params", "expr_list"),
+ ("src_memory", "int")
+ ], MediumLevelILOperation.MLIL_SYSCALL_UNTYPED_SSA: [
+ ("output", "expr"), ("params", "expr"), ("stack", "expr")
+ ], MediumLevelILOperation.MLIL_TAILCALL_SSA: [
+ ("output", "expr"), ("dest", "expr"), ("params", "expr_list"), ("src_memory", "int")
+ ], MediumLevelILOperation.MLIL_TAILCALL_UNTYPED_SSA: [
+ ("output", "expr"), ("dest", "expr"), ("params", "expr"), ("stack", "expr")
+ ], MediumLevelILOperation.MLIL_CALL_OUTPUT_SSA: [
+ ("dest_memory", "int"), ("dest", "var_ssa_list")
+ ], MediumLevelILOperation.MLIL_CALL_PARAM_SSA: [
+ ("src_memory", "int"), ("src", "var_ssa_list")
+ ], MediumLevelILOperation.MLIL_LOAD_SSA: [
+ ("src", "expr"), ("src_memory", "int")
+ ], MediumLevelILOperation.MLIL_LOAD_STRUCT_SSA: [
+ ("src", "expr"), ("offset", "int"), ("src_memory", "int")
+ ], MediumLevelILOperation.MLIL_STORE_SSA: [("dest", "expr"), ("dest_memory", "int"), ("src_memory", "int"),
+ ("src", "expr")], MediumLevelILOperation.MLIL_STORE_STRUCT_SSA: [
+ ("dest", "expr"), ("offset", "int"), ("dest_memory", "int"),
+ ("src_memory", "int"), ("src", "expr")
+ ], MediumLevelILOperation.MLIL_VAR_PHI: [
+ ("dest", "var_ssa"), ("src", "var_ssa_list")
+ ], MediumLevelILOperation.MLIL_MEM_PHI: [("dest_memory", "int"),
+ ("src_memory", "int_list")]
}
@staticmethod
@@ -277,7 +326,9 @@ class MediumLevelILInstruction(BaseILInstruction):
show_graph_report("MLIL Class Hierarchy Graph", graph)
@classmethod
- def create(cls, func:'MediumLevelILFunction', expr_index:ExpressionIndex, instr_index:Optional[InstructionIndex]=None) -> 'MediumLevelILInstruction':
+ def create(
+ cls, func: 'MediumLevelILFunction', expr_index: ExpressionIndex, instr_index: Optional[InstructionIndex] = None
+ ) -> 'MediumLevelILInstruction':
assert func.arch is not None, "Attempted to create IL instruction with function missing an Architecture"
inst = core.BNGetMediumLevelILByIndex(func.handle, expr_index)
assert inst is not None, "core.BNGetMediumLevelILByIndex returned None"
@@ -299,27 +350,27 @@ class MediumLevelILInstruction(BaseILInstruction):
def __repr__(self):
return f"<mlil: {self}>"
- def __eq__(self, other:'MediumLevelILInstruction') -> bool:
+ def __eq__(self, other: 'MediumLevelILInstruction') -> bool:
if not isinstance(other, MediumLevelILInstruction):
return NotImplemented
return self.function == other.function and self.expr_index == other.expr_index
- def __lt__(self, other:'MediumLevelILInstruction') -> bool:
+ def __lt__(self, other: 'MediumLevelILInstruction') -> bool:
if not isinstance(other, MediumLevelILInstruction):
return NotImplemented
return self.function == other.function and self.expr_index < other.expr_index
- def __le__(self, other:'MediumLevelILInstruction') -> bool:
+ def __le__(self, other: 'MediumLevelILInstruction') -> bool:
if not isinstance(other, MediumLevelILInstruction):
return NotImplemented
return self.function == other.function and self.expr_index <= other.expr_index
- def __gt__(self, other:'MediumLevelILInstruction') -> bool:
+ def __gt__(self, other: 'MediumLevelILInstruction') -> bool:
if not isinstance(other, MediumLevelILInstruction):
return NotImplemented
return self.function == other.function and self.expr_index > other.expr_index
- def __ge__(self, other:'MediumLevelILInstruction') -> bool:
+ def __ge__(self, other: 'MediumLevelILInstruction') -> bool:
if not isinstance(other, MediumLevelILInstruction):
return NotImplemented
return self.function == other.function and self.expr_index >= other.expr_index
@@ -333,8 +384,9 @@ class MediumLevelILInstruction(BaseILInstruction):
count = ctypes.c_ulonglong()
tokens = ctypes.POINTER(core.BNInstructionTextToken)()
assert self.function.arch is not None, f"type(self.function): {type(self.function)} "
- result = core.BNGetMediumLevelILExprText(self.function.handle, self.function.arch.handle,
- self.expr_index, tokens, count, None)
+ result = core.BNGetMediumLevelILExprText(
+ self.function.handle, self.function.arch.handle, self.expr_index, tokens, count, None
+ )
assert result, "core.BNGetMediumLevelILExprText returned False"
try:
return function.InstructionTextToken._from_core_struct(tokens, count.value)
@@ -354,16 +406,19 @@ class MediumLevelILInstruction(BaseILInstruction):
"""SSA form of expression (read-only)"""
ssa_func = self.function.ssa_form
assert ssa_func is not None
- return MediumLevelILInstruction.create(ssa_func,
- ExpressionIndex(core.BNGetMediumLevelILSSAExprIndex(self.function.handle, self.expr_index)))
+ return MediumLevelILInstruction.create(
+ ssa_func, ExpressionIndex(core.BNGetMediumLevelILSSAExprIndex(self.function.handle, self.expr_index))
+ )
@property
def non_ssa_form(self) -> 'MediumLevelILInstruction':
"""Non-SSA form of expression (read-only)"""
non_ssa_func = self.function.non_ssa_form
assert non_ssa_func is not None
- return MediumLevelILInstruction.create(non_ssa_func,
- ExpressionIndex(core.BNGetMediumLevelILNonSSAExprIndex(self.function.handle, self.expr_index)))
+ return MediumLevelILInstruction.create(
+ non_ssa_func,
+ ExpressionIndex(core.BNGetMediumLevelILNonSSAExprIndex(self.function.handle, self.expr_index))
+ )
@property
def value(self) -> variable.RegisterValue:
@@ -446,7 +501,7 @@ class MediumLevelILInstruction(BaseILInstruction):
@property
def prefix_operands(self) -> List[MediumLevelILOperandType]:
"""All operands in the expression tree in prefix order"""
- result:List[MediumLevelILOperandType] = [MediumLevelILOperationAndSize(self.operation, self.size)]
+ result: List[MediumLevelILOperandType] = [MediumLevelILOperationAndSize(self.operation, self.size)]
for operand in self.operands:
if isinstance(operand, MediumLevelILInstruction):
result.extend(operand.prefix_operands)
@@ -457,7 +512,7 @@ class MediumLevelILInstruction(BaseILInstruction):
@property
def postfix_operands(self) -> List[MediumLevelILOperandType]:
"""All operands in the expression tree in postfix order"""
- result:List[MediumLevelILOperandType] = []
+ result: List[MediumLevelILOperandType] = []
for operand in self.operands:
if isinstance(operand, MediumLevelILInstruction):
result.extend(operand.postfix_operands)
@@ -507,11 +562,13 @@ class MediumLevelILInstruction(BaseILInstruction):
platform = None
if self.function.source_function:
platform = self.function.source_function.platform
- return types.Type.create(core.BNNewTypeReference(result.type), platform = platform, confidence = result.confidence)
+ return types.Type.create(
+ core.BNNewTypeReference(result.type), platform=platform, confidence=result.confidence
+ )
return None
@staticmethod
- def _make_options_array(options:Optional[List[DataFlowQueryOption]]):
+ def _make_options_array(options: Optional[List[DataFlowQueryOption]]):
if options is None:
options = []
idx = 0
@@ -521,134 +578,153 @@ class MediumLevelILInstruction(BaseILInstruction):
idx += 1
return option_array, len(options)
- def get_possible_values(self, options:Optional[List[DataFlowQueryOption]]=None) -> variable.PossibleValueSet:
+ def get_possible_values(self, options: Optional[List[DataFlowQueryOption]] = None) -> variable.PossibleValueSet:
option_array, size = MediumLevelILInstruction._make_options_array(options)
value = core.BNGetMediumLevelILPossibleExprValues(self.function.handle, self.expr_index, option_array, size)
result = variable.PossibleValueSet(self.function.arch, value)
core.BNFreePossibleValueSet(value)
return result
- def get_ssa_var_possible_values(self, ssa_var:SSAVariable, options:List[DataFlowQueryOption]=[]):
+ def get_ssa_var_possible_values(self, ssa_var: SSAVariable, options: List[DataFlowQueryOption] = []):
var_data = ssa_var.var.to_BNVariable()
option_array, size = MediumLevelILInstruction._make_options_array(options)
- value = core.BNGetMediumLevelILPossibleSSAVarValues(self.function.handle, var_data, ssa_var.version,
- self.instr_index, option_array, size)
+ value = core.BNGetMediumLevelILPossibleSSAVarValues(
+ self.function.handle, var_data, ssa_var.version, self.instr_index, option_array, size
+ )
result = variable.PossibleValueSet(self.function.arch, value)
core.BNFreePossibleValueSet(value)
return result
- def get_ssa_var_version(self, var:variable.Variable) -> int:
+ def get_ssa_var_version(self, var: variable.Variable) -> int:
var_data = var.to_BNVariable()
return core.BNGetMediumLevelILSSAVarVersionAtILInstruction(self.function.handle, var_data, self.instr_index)
- def get_var_for_reg(self, reg:'architecture.RegisterType') -> variable.Variable:
+ def get_var_for_reg(self, reg: 'architecture.RegisterType') -> variable.Variable:
reg = self.function.arch.get_reg_index(reg)
result = core.BNGetMediumLevelILVariableForRegisterAtInstruction(self.function.handle, reg, self.instr_index)
return variable.Variable.from_BNVariable(self.function, result)
- def get_var_for_flag(self, flag:'architecture.FlagType') -> variable.Variable:
+ def get_var_for_flag(self, flag: 'architecture.FlagType') -> variable.Variable:
flag = self.function.arch.get_flag_index(flag)
result = core.BNGetMediumLevelILVariableForFlagAtInstruction(self.function.handle, flag, self.instr_index)
return variable.Variable.from_BNVariable(self.function, result)
- def get_var_for_stack_location(self, offset:int) -> variable.Variable:
- result = core.BNGetMediumLevelILVariableForStackLocationAtInstruction(self.function.handle, offset, self.instr_index)
+ def get_var_for_stack_location(self, offset: int) -> variable.Variable:
+ result = core.BNGetMediumLevelILVariableForStackLocationAtInstruction(
+ self.function.handle, offset, self.instr_index
+ )
return variable.Variable.from_BNVariable(self.function, result)
- def get_reg_value(self, reg:'architecture.RegisterType') -> 'variable.RegisterValue':
+ def get_reg_value(self, reg: 'architecture.RegisterType') -> 'variable.RegisterValue':
reg = self.function.arch.get_reg_index(reg)
value = core.BNGetMediumLevelILRegisterValueAtInstruction(self.function.handle, reg, self.instr_index)
result = variable.RegisterValue.from_BNRegisterValue(value, self.function.arch)
return result
- def get_reg_value_after(self, reg:'architecture.RegisterType') -> 'variable.RegisterValue':
+ def get_reg_value_after(self, reg: 'architecture.RegisterType') -> 'variable.RegisterValue':
reg = self.function.arch.get_reg_index(reg)
value = core.BNGetMediumLevelILRegisterValueAfterInstruction(self.function.handle, reg, self.instr_index)
result = variable.RegisterValue.from_BNRegisterValue(value, self.function.arch)
return result
- def get_possible_reg_values(self, reg:'architecture.RegisterType',
- options:Optional[List[DataFlowQueryOption]]=None) -> 'variable.PossibleValueSet':
+ def get_possible_reg_values(
+ self, reg: 'architecture.RegisterType', options: Optional[List[DataFlowQueryOption]] = None
+ ) -> 'variable.PossibleValueSet':
option_array, size = MediumLevelILInstruction._make_options_array(options)
reg = self.function.arch.get_reg_index(reg)
- value = core.BNGetMediumLevelILPossibleRegisterValuesAtInstruction(self.function.handle, reg, self.instr_index,
- option_array, size)
+ value = core.BNGetMediumLevelILPossibleRegisterValuesAtInstruction(
+ self.function.handle, reg, self.instr_index, option_array, size
+ )
result = variable.PossibleValueSet(self.function.arch, value)
core.BNFreePossibleValueSet(value)
return result
- def get_possible_reg_values_after(self, reg:'architecture.RegisterType',
- options:Optional[List[DataFlowQueryOption]]=None) -> 'variable.PossibleValueSet':
+ def get_possible_reg_values_after(
+ self, reg: 'architecture.RegisterType', options: Optional[List[DataFlowQueryOption]] = None
+ ) -> 'variable.PossibleValueSet':
reg = self.function.arch.get_reg_index(reg)
option_array, size = MediumLevelILInstruction._make_options_array(options)
- value = core.BNGetMediumLevelILPossibleRegisterValuesAfterInstruction(self.function.handle, reg, self.instr_index,
- option_array, size)
+ value = core.BNGetMediumLevelILPossibleRegisterValuesAfterInstruction(
+ self.function.handle, reg, self.instr_index, option_array, size
+ )
result = variable.PossibleValueSet(self.function.arch, value)
core.BNFreePossibleValueSet(value)
return result
- def get_flag_value(self, flag:'architecture.FlagType') -> 'variable.RegisterValue':
+ def get_flag_value(self, flag: 'architecture.FlagType') -> 'variable.RegisterValue':
flag = self.function.arch.get_flag_index(flag)
value = core.BNGetMediumLevelILFlagValueAtInstruction(self.function.handle, flag, self.instr_index)
result = variable.RegisterValue.from_BNRegisterValue(value, self.function.arch)
return result
- def get_flag_value_after(self, flag:'architecture.FlagType') -> 'variable.RegisterValue':
+ def get_flag_value_after(self, flag: 'architecture.FlagType') -> 'variable.RegisterValue':
flag = self.function.arch.get_flag_index(flag)
value = core.BNGetMediumLevelILFlagValueAfterInstruction(self.function.handle, flag, self.instr_index)
result = variable.RegisterValue.from_BNRegisterValue(value, self.function.arch)
return result
- def get_possible_flag_values(self, flag:'architecture.FlagType',
- options:Optional[List[DataFlowQueryOption]]=None) -> 'variable.PossibleValueSet':
+ def get_possible_flag_values(
+ self, flag: 'architecture.FlagType', options: Optional[List[DataFlowQueryOption]] = None
+ ) -> 'variable.PossibleValueSet':
flag = self.function.arch.get_flag_index(flag)
option_array, size = MediumLevelILInstruction._make_options_array(options)
- value = core.BNGetMediumLevelILPossibleFlagValuesAtInstruction(self.function.handle, flag, self.instr_index,
- option_array, size)
+ value = core.BNGetMediumLevelILPossibleFlagValuesAtInstruction(
+ self.function.handle, flag, self.instr_index, option_array, size
+ )
result = variable.PossibleValueSet(self.function.arch, value)
core.BNFreePossibleValueSet(value)
return result
- def get_possible_flag_values_after(self, flag:'architecture.FlagType',
- options:Optional[List[DataFlowQueryOption]]=None) -> 'variable.PossibleValueSet':
+ def get_possible_flag_values_after(
+ self, flag: 'architecture.FlagType', options: Optional[List[DataFlowQueryOption]] = None
+ ) -> 'variable.PossibleValueSet':
flag = self.function.arch.get_flag_index(flag)
option_array, size = MediumLevelILInstruction._make_options_array(options)
- value = core.BNGetMediumLevelILPossibleFlagValuesAfterInstruction(self.function.handle, flag, self.instr_index,
- option_array, size)
+ value = core.BNGetMediumLevelILPossibleFlagValuesAfterInstruction(
+ self.function.handle, flag, self.instr_index, option_array, size
+ )
result = variable.PossibleValueSet(self.function.arch, value)
core.BNFreePossibleValueSet(value)
return result
- def get_stack_contents(self, offset:int, size:int) -> 'variable.RegisterValue':
+ def get_stack_contents(self, offset: int, size: int) -> 'variable.RegisterValue':
value = core.BNGetMediumLevelILStackContentsAtInstruction(self.function.handle, offset, size, self.instr_index)
result = variable.RegisterValue.from_BNRegisterValue(value, self.function.arch)
return result
- def get_stack_contents_after(self, offset:int, size:int) -> 'variable.RegisterValue':
- value = core.BNGetMediumLevelILStackContentsAfterInstruction(self.function.handle, offset, size, self.instr_index)
+ def get_stack_contents_after(self, offset: int, size: int) -> 'variable.RegisterValue':
+ value = core.BNGetMediumLevelILStackContentsAfterInstruction(
+ self.function.handle, offset, size, self.instr_index
+ )
result = variable.RegisterValue.from_BNRegisterValue(value, self.function.arch)
return result
- def get_possible_stack_contents(self, offset:int, size:int,
- options:Optional[List[DataFlowQueryOption]]=None) -> 'variable.PossibleValueSet':
+ def get_possible_stack_contents(
+ self, offset: int, size: int, options: Optional[List[DataFlowQueryOption]] = None
+ ) -> 'variable.PossibleValueSet':
option_array, option_size = MediumLevelILInstruction._make_options_array(options)
- value = core.BNGetMediumLevelILPossibleStackContentsAtInstruction(self.function.handle, offset, size, self.instr_index,
- option_array, option_size)
+ value = core.BNGetMediumLevelILPossibleStackContentsAtInstruction(
+ self.function.handle, offset, size, self.instr_index, option_array, option_size
+ )
result = variable.PossibleValueSet(self.function.arch, value)
core.BNFreePossibleValueSet(value)
return result
- def get_possible_stack_contents_after(self, offset:int, size:int,
- options:List[DataFlowQueryOption]=None) -> 'variable.PossibleValueSet':
+ def get_possible_stack_contents_after(
+ self, offset: int, size: int, options: List[DataFlowQueryOption] = None
+ ) -> 'variable.PossibleValueSet':
option_array, option_size = MediumLevelILInstruction._make_options_array(options)
- value = core.BNGetMediumLevelILPossibleStackContentsAfterInstruction(self.function.handle, offset, size, self.instr_index,
- option_array, option_size)
+ value = core.BNGetMediumLevelILPossibleStackContentsAfterInstruction(
+ self.function.handle, offset, size, self.instr_index, option_array, option_size
+ )
result = variable.PossibleValueSet(self.function.arch, value)
core.BNFreePossibleValueSet(value)
return result
- def get_branch_dependence(self, branch_instr:int) -> ILBranchDependence:
- return ILBranchDependence(core.BNGetMediumLevelILBranchDependence(self.function.handle, self.instr_index, branch_instr))
+ def get_branch_dependence(self, branch_instr: int) -> ILBranchDependence:
+ return ILBranchDependence(
+ core.BNGetMediumLevelILBranchDependence(self.function.handle, self.instr_index, branch_instr)
+ )
@property
def operation(self) -> MediumLevelILOperation:
@@ -670,11 +746,11 @@ class MediumLevelILInstruction(BaseILInstruction):
def core_operands(self) -> OperandsType:
return self.instr.operands
- def _get_int(self, operand_index:int) -> int:
+ def _get_int(self, operand_index: int) -> int:
value = self.instr.operands[operand_index]
return (value & ((1 << 63) - 1)) - (value & (1 << 63))
- def _get_float(self, operand_index:int) -> float:
+ def _get_float(self, operand_index: int) -> float:
value = self.instr.operands[operand_index]
if self.instr.size == 4:
return struct.unpack("f", struct.pack("I", value & 0xffffffff))[0]
@@ -683,34 +759,34 @@ class MediumLevelILInstruction(BaseILInstruction):
else:
return float(value)
- def _get_expr(self, operand_index:int) -> 'MediumLevelILInstruction':
- return MediumLevelILInstruction.create(self.function,
- ExpressionIndex(self.instr.operands[operand_index]))
+ def _get_expr(self, operand_index: int) -> 'MediumLevelILInstruction':
+ return MediumLevelILInstruction.create(self.function, ExpressionIndex(self.instr.operands[operand_index]))
- def _get_intrinsic(self, operand_index:int) -> 'lowlevelil.ILIntrinsic':
+ def _get_intrinsic(self, operand_index: int) -> 'lowlevelil.ILIntrinsic':
assert self.function.arch is not None, "Attempting to create ILIntrinsic from function with no Architecture"
- return lowlevelil.ILIntrinsic(self.function.arch,
- architecture.IntrinsicIndex(self.instr.operands[operand_index]))
+ return lowlevelil.ILIntrinsic(
+ self.function.arch, architecture.IntrinsicIndex(self.instr.operands[operand_index])
+ )
- def _get_var(self, operand_index:int) -> variable.Variable:
+ def _get_var(self, operand_index: int) -> variable.Variable:
value = self.instr.operands[operand_index]
return variable.Variable.from_identifier(self.function, value)
- def _get_var_ssa(self, operand_index1:int, operand_index2:int) -> SSAVariable:
+ def _get_var_ssa(self, operand_index1: int, operand_index2: int) -> SSAVariable:
var = variable.Variable.from_identifier(self.function, self.instr.operands[operand_index1])
version = self.instr.operands[operand_index2]
return SSAVariable(var, version)
- def _get_var_ssa_dest_and_src(self, operand_index1:int, operand_index2:int) -> SSAVariable:
+ def _get_var_ssa_dest_and_src(self, operand_index1: int, operand_index2: int) -> SSAVariable:
var = variable.Variable.from_identifier(self.function, self.instr.operands[operand_index1])
dest_version = self.instr.operands[operand_index2]
return SSAVariable(var, dest_version)
- def _get_int_list(self, operand_index:int) -> List[int]:
+ def _get_int_list(self, operand_index: int) -> List[int]:
count = ctypes.c_ulonglong()
operand_list = core.BNMediumLevelILGetOperandList(self.function.handle, self.expr_index, operand_index, count)
assert operand_list is not None, "core.BNMediumLevelILGetOperandList returned None"
- value:List[int] = []
+ value: List[int] = []
try:
for j in range(count.value):
value.append(operand_list[j])
@@ -718,7 +794,7 @@ class MediumLevelILInstruction(BaseILInstruction):
finally:
core.BNMediumLevelILFreeOperandList(operand_list)
- def _get_var_list(self, operand_index1:int, operand_index2:int) -> List[variable.Variable]:
+ def _get_var_list(self, operand_index1: int, operand_index2: int) -> List[variable.Variable]:
# We keep this extra parameter around because when this function is called
# the subclasses that call this don't use the next operand
# without this parameter it looks like this operand is being skipped unintentionally
@@ -727,7 +803,7 @@ class MediumLevelILInstruction(BaseILInstruction):
count = ctypes.c_ulonglong()
operand_list = core.BNMediumLevelILGetOperandList(self.function.handle, self.expr_index, operand_index1, count)
assert operand_list is not None, "core.BNMediumLevelILGetOperandList returned None"
- value:List[variable.Variable] = []
+ value: List[variable.Variable] = []
try:
for j in range(count.value):
value.append(variable.Variable.from_identifier(self.function, operand_list[j]))
@@ -735,7 +811,7 @@ class MediumLevelILInstruction(BaseILInstruction):
finally:
core.BNMediumLevelILFreeOperandList(operand_list)
- def _get_var_ssa_list(self, operand_index1:int, _:int) -> List[SSAVariable]:
+ def _get_var_ssa_list(self, operand_index1: int, _: int) -> List[SSAVariable]:
count = ctypes.c_ulonglong()
operand_list = core.BNMediumLevelILGetOperandList(self.function.handle, self.expr_index, operand_index1, count)
assert operand_list is not None, "core.BNMediumLevelILGetOperandList returned None"
@@ -743,18 +819,17 @@ class MediumLevelILInstruction(BaseILInstruction):
try:
for j in range(count.value // 2):
var_id = operand_list[j * 2]
- var_version = operand_list[(j * 2) + 1]
- value.append(SSAVariable(variable.Variable.from_identifier(self.function,
- var_id), var_version))
+ var_version = operand_list[(j*2) + 1]
+ value.append(SSAVariable(variable.Variable.from_identifier(self.function, var_id), var_version))
return value
finally:
core.BNMediumLevelILFreeOperandList(operand_list)
- def _get_expr_list(self, operand_index1:int, _:int) -> List['MediumLevelILInstruction']:
+ def _get_expr_list(self, operand_index1: int, _: int) -> List['MediumLevelILInstruction']:
count = ctypes.c_ulonglong()
operand_list = core.BNMediumLevelILGetOperandList(self.function.handle, self.expr_index, operand_index1, count)
assert operand_list is not None, "core.BNMediumLevelILGetOperandList returned None"
- value:List['MediumLevelILInstruction'] = []
+ value: List['MediumLevelILInstruction'] = []
try:
for j in range(count.value):
value.append(MediumLevelILInstruction.create(self.function, operand_list[j], None))
@@ -762,15 +837,15 @@ class MediumLevelILInstruction(BaseILInstruction):
finally:
core.BNMediumLevelILFreeOperandList(operand_list)
- def _get_target_map(self, operand_index1:int, _:int) -> Mapping[int, int]:
+ def _get_target_map(self, operand_index1: int, _: int) -> Mapping[int, int]:
count = ctypes.c_ulonglong()
operand_list = core.BNMediumLevelILGetOperandList(self.function.handle, self.expr_index, operand_index1, count)
assert operand_list is not None, "core.BNMediumLevelILGetOperandList returned None"
- value:Dict[int, int] = {}
+ value: Dict[int, int] = {}
try:
for j in range(count.value // 2):
key = operand_list[j * 2]
- target = operand_list[(j * 2) + 1]
+ target = operand_list[(j*2) + 1]
value[key] = target
return value
finally:
@@ -811,7 +886,6 @@ class MediumLevelILCallBase(MediumLevelILInstruction, Call):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILUnaryBase(MediumLevelILInstruction, UnaryOperation):
-
@property
def src(self) -> MediumLevelILInstruction:
return self._get_expr(0)
@@ -823,7 +897,6 @@ class MediumLevelILUnaryBase(MediumLevelILInstruction, UnaryOperation):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILBinaryBase(MediumLevelILInstruction, BinaryOperation):
-
@property
def left(self) -> MediumLevelILInstruction:
return self._get_expr(0)
@@ -844,7 +917,6 @@ class MediumLevelILComparisonBase(MediumLevelILBinaryBase, Comparison):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILCarryBase(MediumLevelILInstruction, Carry):
-
@property
def left(self) -> MediumLevelILInstruction:
return self._get_expr(0)
@@ -889,7 +961,6 @@ class MediumLevelILUnimpl(MediumLevelILInstruction):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILLoad(MediumLevelILInstruction, Load):
-
@property
def src(self) -> MediumLevelILInstruction:
return self._get_expr(0)
@@ -901,7 +972,6 @@ class MediumLevelILLoad(MediumLevelILInstruction, Load):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILVar(MediumLevelILInstruction):
-
@property
def src(self) -> variable.Variable:
return self._get_var(0)
@@ -913,7 +983,6 @@ class MediumLevelILVar(MediumLevelILInstruction):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILAddressOf(MediumLevelILInstruction):
-
@property
def src(self) -> variable.Variable:
return self._get_var(0)
@@ -929,7 +998,6 @@ class MediumLevelILAddressOf(MediumLevelILInstruction):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILConst(MediumLevelILConstBase):
-
@property
def constant(self) -> int:
return self._get_int(0)
@@ -941,7 +1009,6 @@ class MediumLevelILConst(MediumLevelILConstBase):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILConstPtr(MediumLevelILConstBase):
-
@property
def constant(self) -> int:
return self._get_int(0)
@@ -953,7 +1020,6 @@ class MediumLevelILConstPtr(MediumLevelILConstBase):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILFloatConst(MediumLevelILConstBase, FloatingPoint):
-
@property
def constant(self) -> float:
return self._get_float(0)
@@ -965,7 +1031,6 @@ class MediumLevelILFloatConst(MediumLevelILConstBase, FloatingPoint):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILImport(MediumLevelILConstBase):
-
@property
def constant(self) -> int:
return self._get_int(0)
@@ -1002,7 +1067,6 @@ class MediumLevelILLowPart(MediumLevelILUnaryBase, Arithmetic):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILJump(MediumLevelILInstruction, Terminal):
-
@property
def dest(self) -> MediumLevelILInstruction:
return self._get_expr(0)
@@ -1014,7 +1078,6 @@ class MediumLevelILJump(MediumLevelILInstruction, Terminal):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILRetHint(MediumLevelILInstruction, ControlFlow):
-
@property
def dest(self) -> MediumLevelILInstruction:
return self._get_expr(0)
@@ -1026,7 +1089,6 @@ class MediumLevelILRetHint(MediumLevelILInstruction, ControlFlow):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILCallOutput(MediumLevelILInstruction):
-
@property
def dest(self) -> List[variable.Variable]:
return self._get_var_list(0, 1)
@@ -1042,7 +1104,6 @@ class MediumLevelILCallOutput(MediumLevelILInstruction):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILCallParam(MediumLevelILInstruction):
-
@property
def src(self) -> List[variable.Variable]:
return self._get_var_list(0, 1)
@@ -1054,7 +1115,6 @@ class MediumLevelILCallParam(MediumLevelILInstruction):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILRet(MediumLevelILInstruction, Return):
-
@property
def src(self) -> List[MediumLevelILInstruction]:
return self._get_expr_list(0, 1)
@@ -1066,7 +1126,6 @@ class MediumLevelILRet(MediumLevelILInstruction, Return):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILGoto(MediumLevelILInstruction, Terminal):
-
@property
def dest(self) -> int:
return self._get_int(0)
@@ -1078,7 +1137,6 @@ class MediumLevelILGoto(MediumLevelILInstruction, Terminal):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILBoolToInt(MediumLevelILInstruction):
-
@property
def src(self) -> MediumLevelILInstruction:
return self._get_expr(0)
@@ -1090,7 +1148,6 @@ class MediumLevelILBoolToInt(MediumLevelILInstruction):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILFreeVarSlot(MediumLevelILInstruction, RegisterStack):
-
@property
def dest(self) -> variable.Variable:
return self._get_var(0)
@@ -1102,7 +1159,6 @@ class MediumLevelILFreeVarSlot(MediumLevelILInstruction, RegisterStack):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILTrap(MediumLevelILInstruction, Terminal):
-
@property
def vector(self) -> int:
return self._get_int(0)
@@ -1114,7 +1170,6 @@ class MediumLevelILTrap(MediumLevelILInstruction, Terminal):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILFreeVarSlotSsa(MediumLevelILInstruction, SSA, RegisterStack):
-
@property
def dest(self) -> SSAVariable:
return self._get_var_ssa_dest_and_src(0, 1)
@@ -1130,7 +1185,6 @@ class MediumLevelILFreeVarSlotSsa(MediumLevelILInstruction, SSA, RegisterStack):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILUnimplMem(MediumLevelILInstruction, Memory):
-
@property
def src(self) -> MediumLevelILInstruction:
return self._get_expr(0)
@@ -1192,7 +1246,6 @@ class MediumLevelILFtrunc(MediumLevelILUnaryBase, Arithmetic, FloatingPoint):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILVarSsa(MediumLevelILInstruction, SSA):
-
@property
def src(self) -> SSAVariable:
return self._get_var_ssa(0, 1)
@@ -1204,7 +1257,6 @@ class MediumLevelILVarSsa(MediumLevelILInstruction, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILVarAliased(MediumLevelILInstruction, SSA):
-
@property
def src(self) -> SSAVariable:
return self._get_var_ssa(0, 1)
@@ -1216,7 +1268,6 @@ class MediumLevelILVarAliased(MediumLevelILInstruction, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILSetVar(MediumLevelILInstruction, SetVar):
-
@property
def dest(self) -> variable.Variable:
return self._get_var(0)
@@ -1240,7 +1291,6 @@ class MediumLevelILSetVar(MediumLevelILInstruction, SetVar):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILLoadStruct(MediumLevelILInstruction, Load):
-
@property
def src(self) -> MediumLevelILInstruction:
return self._get_expr(0)
@@ -1256,7 +1306,6 @@ class MediumLevelILLoadStruct(MediumLevelILInstruction, Load):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILStore(MediumLevelILInstruction, Store):
-
@property
def dest(self) -> MediumLevelILInstruction:
return self._get_expr(0)
@@ -1272,7 +1321,6 @@ class MediumLevelILStore(MediumLevelILInstruction, Store):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILVarField(MediumLevelILInstruction):
-
@property
def src(self) -> variable.Variable:
return self._get_var(0)
@@ -1288,7 +1336,6 @@ class MediumLevelILVarField(MediumLevelILInstruction):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILVarSplit(MediumLevelILInstruction):
-
@property
def high(self) -> variable.Variable:
return self._get_var(0)
@@ -1304,7 +1351,6 @@ class MediumLevelILVarSplit(MediumLevelILInstruction):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILAddressOfField(MediumLevelILInstruction):
-
@property
def src(self) -> variable.Variable:
return self._get_var(0)
@@ -1320,7 +1366,6 @@ class MediumLevelILAddressOfField(MediumLevelILInstruction):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILExternPtr(MediumLevelILConstBase):
-
@property
def constant(self) -> int:
return self._get_int(0)
@@ -1501,7 +1546,6 @@ class MediumLevelILAddOverflow(MediumLevelILBinaryBase, Arithmetic):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILSyscall(MediumLevelILInstruction, Syscall):
-
@property
def output(self) -> List[variable.Variable]:
return self._get_var_list(0, 1)
@@ -1517,7 +1561,6 @@ class MediumLevelILSyscall(MediumLevelILInstruction, Syscall):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILVarSsaField(MediumLevelILInstruction, SSA):
-
@property
def src(self) -> SSAVariable:
return self._get_var_ssa(0, 1)
@@ -1533,7 +1576,6 @@ class MediumLevelILVarSsaField(MediumLevelILInstruction, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILVarAliasedField(MediumLevelILInstruction, SSA):
-
@property
def src(self) -> SSAVariable:
return self._get_var_ssa(0, 1)
@@ -1549,7 +1591,6 @@ class MediumLevelILVarAliasedField(MediumLevelILInstruction, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILVarSplitSsa(MediumLevelILInstruction, SSA):
-
@property
def high(self) -> SSAVariable:
return self._get_var_ssa(0, 1)
@@ -1565,7 +1606,6 @@ class MediumLevelILVarSplitSsa(MediumLevelILInstruction, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILCallOutputSsa(MediumLevelILInstruction, SSA):
-
@property
def dest_memory(self) -> int:
return self._get_int(0)
@@ -1585,7 +1625,6 @@ class MediumLevelILCallOutputSsa(MediumLevelILInstruction, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILCallParamSsa(MediumLevelILInstruction, SSA):
-
@property
def src_memory(self) -> int:
return self._get_int(0)
@@ -1601,7 +1640,6 @@ class MediumLevelILCallParamSsa(MediumLevelILInstruction, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILLoadSsa(MediumLevelILInstruction, Load, SSA):
-
@property
def src(self) -> MediumLevelILInstruction:
return self._get_expr(0)
@@ -1617,7 +1655,6 @@ class MediumLevelILLoadSsa(MediumLevelILInstruction, Load, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILVarPhi(MediumLevelILInstruction, SetVar, Phi, SSA):
-
@property
def dest(self) -> SSAVariable:
return self._get_var_ssa(0, 1)
@@ -1637,7 +1674,6 @@ class MediumLevelILVarPhi(MediumLevelILInstruction, SetVar, Phi, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILMemPhi(MediumLevelILInstruction, Memory, Phi):
-
@property
def dest_memory(self) -> int:
return self._get_int(0)
@@ -1653,7 +1689,6 @@ class MediumLevelILMemPhi(MediumLevelILInstruction, Memory, Phi):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILSetVarSsa(MediumLevelILInstruction, SetVar, SSA):
-
@property
def dest(self) -> SSAVariable:
return self._get_var_ssa(0, 1)
@@ -1737,7 +1772,6 @@ class MediumLevelILFdiv(MediumLevelILBinaryBase, Arithmetic, FloatingPoint):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILJumpTo(MediumLevelILInstruction, Terminal):
-
@property
def dest(self) -> MediumLevelILInstruction:
return self._get_expr(0)
@@ -1753,7 +1787,6 @@ class MediumLevelILJumpTo(MediumLevelILInstruction, Terminal):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILSetVarAliased(MediumLevelILInstruction, SetVar, SSA):
-
@property
def dest(self) -> SSAVariable:
return self._get_var_ssa_dest_and_src(0, 1)
@@ -1779,10 +1812,8 @@ class MediumLevelILSetVarAliased(MediumLevelILInstruction, SetVar, SSA):
return [self.dest]
-
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILSyscallUntyped(MediumLevelILCallBase, Syscall):
-
@property
def output(self) -> List[variable.Variable]:
inst = self._get_expr(0)
@@ -1806,7 +1837,6 @@ class MediumLevelILSyscallUntyped(MediumLevelILCallBase, Syscall):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILIntrinsic(MediumLevelILInstruction):
-
@property
def output(self) -> List[variable.Variable]:
return self._get_var_list(0, 1)
@@ -1821,7 +1851,7 @@ class MediumLevelILIntrinsic(MediumLevelILInstruction):
@property
def vars_read(self) -> List[variable.Variable]:
- result:List[variable.Variable] = []
+ result: List[variable.Variable] = []
for i in self.params:
result.extend(i.vars_read) # type: ignore
return result
@@ -1837,7 +1867,6 @@ class MediumLevelILIntrinsic(MediumLevelILInstruction):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILIntrinsicSsa(MediumLevelILInstruction, SSA):
-
@property
def output(self) -> List[SSAVariable]:
return self._get_var_ssa_list(0, 1)
@@ -1852,7 +1881,7 @@ class MediumLevelILIntrinsicSsa(MediumLevelILInstruction, SSA):
@property
def vars_read(self) -> List[SSAVariable]:
- result:List[SSAVariable] = []
+ result: List[SSAVariable] = []
for i in self.params:
result.extend(i.vars_read) # type: ignore
return result
@@ -1868,7 +1897,6 @@ class MediumLevelILIntrinsicSsa(MediumLevelILInstruction, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILSetVarSsaField(MediumLevelILInstruction, SetVar, SSA):
-
@property
def dest(self) -> SSAVariable:
return self._get_var_ssa_dest_and_src(0, 1)
@@ -1900,7 +1928,6 @@ class MediumLevelILSetVarSsaField(MediumLevelILInstruction, SetVar, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILSetVarSplitSsa(MediumLevelILInstruction, SetVar, SSA):
-
@property
def high(self) -> SSAVariable:
return self._get_var_ssa(0, 1)
@@ -1928,7 +1955,6 @@ class MediumLevelILSetVarSplitSsa(MediumLevelILInstruction, SetVar, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILSetVarAliasedField(MediumLevelILInstruction, SetVar, SSA):
-
@property
def dest(self) -> SSAVariable:
return self._get_var_ssa_dest_and_src(0, 1)
@@ -1956,7 +1982,6 @@ class MediumLevelILSetVarAliasedField(MediumLevelILInstruction, SetVar, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILSyscallSsa(MediumLevelILCallBase, Syscall, SSA):
-
@property
def output(self) -> List[SSAVariable]:
inst = self._get_expr(0)
@@ -1984,29 +2009,36 @@ class MediumLevelILSyscallSsa(MediumLevelILCallBase, Syscall, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILSyscallUntypedSsa(MediumLevelILCallBase, Syscall, SSA):
-
@property
def output(self) -> List[SSAVariable]:
inst = self._get_expr(0)
- assert isinstance(inst, MediumLevelILCallOutputSsa), "MediumLevelILSyscallUntypedSsa return bad type for 'output'"
+ assert isinstance(
+ inst, MediumLevelILCallOutputSsa
+ ), "MediumLevelILSyscallUntypedSsa return bad type for 'output'"
return inst.dest
@property
def output_dest_memory(self) -> int:
inst = self._get_expr(0)
- assert isinstance(inst, MediumLevelILCallOutputSsa), "MediumLevelILSyscallUntypedSsa return bad type for 'output_dest_memory'"
+ assert isinstance(
+ inst, MediumLevelILCallOutputSsa
+ ), "MediumLevelILSyscallUntypedSsa return bad type for 'output_dest_memory'"
return inst.dest_memory
@property
def params(self) -> List[SSAVariable]:
inst = self._get_expr(1)
- assert isinstance(inst, MediumLevelILCallParamSsa), "MediumLevelILSyscallUntypedSsa return bad type for 'params'"
+ assert isinstance(
+ inst, MediumLevelILCallParamSsa
+ ), "MediumLevelILSyscallUntypedSsa return bad type for 'params'"
return inst.src
@property
def params_src_memory(self) -> int:
inst = self._get_expr(1)
- assert isinstance(inst, MediumLevelILCallParamSsa), "MediumLevelILSyscallUntypedSsa return bad type for 'params_src_memory'"
+ assert isinstance(
+ inst, MediumLevelILCallParamSsa
+ ), "MediumLevelILSyscallUntypedSsa return bad type for 'params_src_memory'"
return inst.src_memory
@property
@@ -2020,7 +2052,6 @@ class MediumLevelILSyscallUntypedSsa(MediumLevelILCallBase, Syscall, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILLoadStructSsa(MediumLevelILInstruction, Load, SSA):
-
@property
def src(self) -> MediumLevelILInstruction:
return self._get_expr(0)
@@ -2040,7 +2071,6 @@ class MediumLevelILLoadStructSsa(MediumLevelILInstruction, Load, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILSetVarField(MediumLevelILInstruction, SetVar):
-
@property
def dest(self) -> variable.Variable:
return self._get_var(0)
@@ -2060,7 +2090,6 @@ class MediumLevelILSetVarField(MediumLevelILInstruction, SetVar):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILSetVarSplit(MediumLevelILInstruction, SetVar):
-
@property
def high(self) -> variable.Variable:
return self._get_var(0)
@@ -2084,7 +2113,6 @@ class MediumLevelILSetVarSplit(MediumLevelILInstruction, SetVar):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILStoreStruct(MediumLevelILInstruction, Store):
-
@property
def dest(self) -> MediumLevelILInstruction:
return self._get_expr(0)
@@ -2124,7 +2152,6 @@ class MediumLevelILRrc(MediumLevelILCarryBase):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILCall(MediumLevelILCallBase, Localcall):
-
@property
def output(self) -> List[variable.Variable]:
return self._get_var_list(0, 1)
@@ -2144,7 +2171,6 @@ class MediumLevelILCall(MediumLevelILCallBase, Localcall):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILIf(MediumLevelILInstruction, Terminal):
-
@property
def condition(self) -> MediumLevelILInstruction:
return self._get_expr(0)
@@ -2164,7 +2190,6 @@ class MediumLevelILIf(MediumLevelILInstruction, Terminal):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILTailcallUntyped(MediumLevelILCallBase, Tailcall):
-
@property
def output(self) -> List[variable.Variable]:
inst = self._get_expr(0)
@@ -2192,7 +2217,6 @@ class MediumLevelILTailcallUntyped(MediumLevelILCallBase, Tailcall):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILCallSsa(MediumLevelILCallBase, Localcall, SSA):
-
@property
def output(self) -> List[SSAVariable]:
inst = self._get_expr(0)
@@ -2224,7 +2248,6 @@ class MediumLevelILCallSsa(MediumLevelILCallBase, Localcall, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILCallUntypedSsa(MediumLevelILCallBase, Localcall, SSA):
-
@property
def output(self) -> List[SSAVariable]:
inst = self._get_expr(0)
@@ -2250,7 +2273,9 @@ class MediumLevelILCallUntypedSsa(MediumLevelILCallBase, Localcall, SSA):
@property
def params_src_memory(self):
inst = self._get_expr(2)
- assert isinstance(inst, MediumLevelILCallParamSsa), "MediumLevelILCallUntypedSsa return bad type for 'params_src_memory'"
+ assert isinstance(
+ inst, MediumLevelILCallParamSsa
+ ), "MediumLevelILCallUntypedSsa return bad type for 'params_src_memory'"
return inst.src_memory
@property
@@ -2264,7 +2289,6 @@ class MediumLevelILCallUntypedSsa(MediumLevelILCallBase, Localcall, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILTailcall(MediumLevelILCallBase, Tailcall):
-
@property
def output(self) -> List[variable.Variable]:
return self._get_var_list(0, 1)
@@ -2284,7 +2308,6 @@ class MediumLevelILTailcall(MediumLevelILCallBase, Tailcall):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILTailcallSsa(MediumLevelILCallBase, Tailcall, SSA):
-
@property
def output(self) -> List[SSAVariable]:
inst = self._get_expr(0)
@@ -2316,17 +2339,20 @@ class MediumLevelILTailcallSsa(MediumLevelILCallBase, Tailcall, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILTailcallUntypedSsa(MediumLevelILCallBase, Tailcall, SSA):
-
@property
def output(self) -> List[SSAVariable]:
inst = self._get_expr(0)
- assert isinstance(inst, MediumLevelILCallOutputSsa), "MediumLevelILTailcallUntypedSsa return bad type for 'output'"
+ assert isinstance(
+ inst, MediumLevelILCallOutputSsa
+ ), "MediumLevelILTailcallUntypedSsa return bad type for 'output'"
return inst.dest
@property
def output_dest_memory(self) -> int:
inst = self._get_expr(0)
- assert isinstance(inst, MediumLevelILCallOutputSsa), "MediumLevelILTailcallUntypedSsa return bad type for 'output'"
+ assert isinstance(
+ inst, MediumLevelILCallOutputSsa
+ ), "MediumLevelILTailcallUntypedSsa return bad type for 'output'"
return inst.dest_memory
@property
@@ -2336,7 +2362,9 @@ class MediumLevelILTailcallUntypedSsa(MediumLevelILCallBase, Tailcall, SSA):
@property
def params(self) -> List[SSAVariable]:
inst = self._get_expr(2)
- assert isinstance(inst, MediumLevelILCallParamSsa), "MediumLevelILTailcallUntypedSsa return bad type for 'params'"
+ assert isinstance(
+ inst, MediumLevelILCallParamSsa
+ ), "MediumLevelILTailcallUntypedSsa return bad type for 'params'"
return inst.src
@property
@@ -2350,7 +2378,6 @@ class MediumLevelILTailcallUntypedSsa(MediumLevelILCallBase, Tailcall, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILStoreSsa(MediumLevelILInstruction, Store, SSA):
-
@property
def dest(self) -> MediumLevelILInstruction:
return self._get_expr(0)
@@ -2374,7 +2401,6 @@ class MediumLevelILStoreSsa(MediumLevelILInstruction, Store, SSA):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILCallUntyped(MediumLevelILCallBase, Localcall):
-
@property
def output(self) -> List[variable.Variable]:
inst = self._get_expr(0)
@@ -2402,7 +2428,6 @@ class MediumLevelILCallUntyped(MediumLevelILCallBase, Localcall):
@dataclass(frozen=True, repr=False, eq=False)
class MediumLevelILStoreStructSsa(MediumLevelILInstruction, Store, SSA):
-
@property
def dest(self) -> MediumLevelILInstruction:
return self._get_expr(0)
@@ -2429,139 +2454,166 @@ class MediumLevelILStoreStructSsa(MediumLevelILInstruction, Store, SSA):
ILInstruction = {
- MediumLevelILOperation.MLIL_NOP:MediumLevelILNop, # [],
- MediumLevelILOperation.MLIL_NORET:MediumLevelILNoret, # [],
- MediumLevelILOperation.MLIL_BP:MediumLevelILBp, # [],
- MediumLevelILOperation.MLIL_UNDEF:MediumLevelILUndef, # [],
- MediumLevelILOperation.MLIL_UNIMPL:MediumLevelILUnimpl, # [],
- MediumLevelILOperation.MLIL_LOAD:MediumLevelILLoad, # [("src", "expr")],
- MediumLevelILOperation.MLIL_VAR:MediumLevelILVar, # [("src", "var")],
- MediumLevelILOperation.MLIL_ADDRESS_OF:MediumLevelILAddressOf, # [("src", "var")],
- MediumLevelILOperation.MLIL_CONST:MediumLevelILConst, # [("constant", "int")],
- MediumLevelILOperation.MLIL_CONST_PTR:MediumLevelILConstPtr, # [("constant", "int")],
- MediumLevelILOperation.MLIL_FLOAT_CONST:MediumLevelILFloatConst, # [("constant", "float")],
- MediumLevelILOperation.MLIL_IMPORT:MediumLevelILImport, # [("constant", "int")],
- MediumLevelILOperation.MLIL_SET_VAR:MediumLevelILSetVar, # [("dest", "var"), ("src", "expr")],
- MediumLevelILOperation.MLIL_LOAD_STRUCT:MediumLevelILLoadStruct, # [("src", "expr"), ("offset", "int")],
- MediumLevelILOperation.MLIL_STORE:MediumLevelILStore, # [("dest", "expr"), ("src", "expr")],
- MediumLevelILOperation.MLIL_VAR_FIELD:MediumLevelILVarField, # [("src", "var"), ("offset", "int")],
- MediumLevelILOperation.MLIL_VAR_SPLIT:MediumLevelILVarSplit, # [("high", "var"), ("low", "var")],
- MediumLevelILOperation.MLIL_ADDRESS_OF_FIELD:MediumLevelILAddressOfField, # [("src", "var"), ("offset", "int")],
- MediumLevelILOperation.MLIL_EXTERN_PTR:MediumLevelILExternPtr, # [("constant", "int"), ("offset", "int")],
- MediumLevelILOperation.MLIL_ADD:MediumLevelILAdd, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_SUB:MediumLevelILSub, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_AND:MediumLevelILAnd, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_OR:MediumLevelILOr, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_XOR:MediumLevelILXor, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_LSL:MediumLevelILLsl, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_LSR:MediumLevelILLsr, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_ASR:MediumLevelILAsr, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_ROL:MediumLevelILRol, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_ROR:MediumLevelILRor, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_MUL:MediumLevelILMul, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_MULU_DP:MediumLevelILMuluDp, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_MULS_DP:MediumLevelILMulsDp, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_DIVU:MediumLevelILDivu, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_DIVU_DP:MediumLevelILDivuDp, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_DIVS:MediumLevelILDivs, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_DIVS_DP:MediumLevelILDivsDp, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_MODU:MediumLevelILModu, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_MODU_DP:MediumLevelILModuDp, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_MODS:MediumLevelILMods, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_MODS_DP:MediumLevelILModsDp, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_NEG:MediumLevelILNeg, # [("src", "expr")],
- MediumLevelILOperation.MLIL_NOT:MediumLevelILNot, # [("src", "expr")],
- MediumLevelILOperation.MLIL_SX:MediumLevelILSx, # [("src", "expr")],
- MediumLevelILOperation.MLIL_ZX:MediumLevelILZx, # [("src", "expr")],
- MediumLevelILOperation.MLIL_LOW_PART:MediumLevelILLowPart, # [("src", "expr")],
- MediumLevelILOperation.MLIL_JUMP:MediumLevelILJump, # [("dest", "expr")],
- MediumLevelILOperation.MLIL_RET_HINT:MediumLevelILRetHint, # [("dest", "expr")],
- MediumLevelILOperation.MLIL_CALL_OUTPUT:MediumLevelILCallOutput, # [("dest", "var_list")],
- MediumLevelILOperation.MLIL_CALL_PARAM:MediumLevelILCallParam, # [("src", "var_list")],
- MediumLevelILOperation.MLIL_RET:MediumLevelILRet, # [("src", "expr_list")],
- MediumLevelILOperation.MLIL_GOTO:MediumLevelILGoto, # [("dest", "int")],
- MediumLevelILOperation.MLIL_BOOL_TO_INT:MediumLevelILBoolToInt, # [("src", "expr")],
- MediumLevelILOperation.MLIL_FREE_VAR_SLOT:MediumLevelILFreeVarSlot, # [("dest", "var")],
- MediumLevelILOperation.MLIL_TRAP:MediumLevelILTrap, # [("vector", "int")],
- MediumLevelILOperation.MLIL_FREE_VAR_SLOT_SSA:MediumLevelILFreeVarSlotSsa, # [("prev", "var_ssa_dest_and_src")],
- MediumLevelILOperation.MLIL_UNIMPL_MEM:MediumLevelILUnimplMem, # [("src", "expr")],
- MediumLevelILOperation.MLIL_FSQRT:MediumLevelILFsqrt, # [("src", "expr")],
- MediumLevelILOperation.MLIL_FNEG:MediumLevelILFneg, # [("src", "expr")],
- MediumLevelILOperation.MLIL_FABS:MediumLevelILFabs, # [("src", "expr")],
- MediumLevelILOperation.MLIL_FLOAT_TO_INT:MediumLevelILFloatToInt, # [("src", "expr")],
- MediumLevelILOperation.MLIL_INT_TO_FLOAT:MediumLevelILIntToFloat, # [("src", "expr")],
- MediumLevelILOperation.MLIL_FLOAT_CONV:MediumLevelILFloatConv, # [("src", "expr")],
- MediumLevelILOperation.MLIL_ROUND_TO_INT:MediumLevelILRoundToInt, # [("src", "expr")],
- MediumLevelILOperation.MLIL_FLOOR:MediumLevelILFloor, # [("src", "expr")],
- MediumLevelILOperation.MLIL_CEIL:MediumLevelILCeil, # [("src", "expr")],
- MediumLevelILOperation.MLIL_FTRUNC:MediumLevelILFtrunc, # [("src", "expr")],
- MediumLevelILOperation.MLIL_VAR_SSA:MediumLevelILVarSsa, # [("src", "var_ssa")],
- MediumLevelILOperation.MLIL_VAR_ALIASED:MediumLevelILVarAliased, # [("src", "var_ssa")],
- MediumLevelILOperation.MLIL_CMP_E:MediumLevelILCmpE, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_CMP_NE:MediumLevelILCmpNe, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_CMP_SLT:MediumLevelILCmpSlt, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_CMP_ULT:MediumLevelILCmpUlt, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_CMP_SLE:MediumLevelILCmpSle, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_CMP_ULE:MediumLevelILCmpUle, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_CMP_SGE:MediumLevelILCmpSge, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_CMP_UGE:MediumLevelILCmpUge, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_CMP_SGT:MediumLevelILCmpSgt, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_CMP_UGT:MediumLevelILCmpUgt, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_TEST_BIT:MediumLevelILTestBit, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_ADD_OVERFLOW:MediumLevelILAddOverflow, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_SYSCALL:MediumLevelILSyscall, # [("output", "var_list"), ("params", "expr_list")],
- MediumLevelILOperation.MLIL_VAR_SSA_FIELD:MediumLevelILVarSsaField, # [("src", "var_ssa"), ("offset", "int")],
- MediumLevelILOperation.MLIL_VAR_ALIASED_FIELD:MediumLevelILVarAliasedField, # [("src", "var_ssa"), ("offset", "int")],
- MediumLevelILOperation.MLIL_VAR_SPLIT_SSA:MediumLevelILVarSplitSsa, # [("high", "var_ssa"), ("low", "var_ssa")],
- MediumLevelILOperation.MLIL_CALL_OUTPUT_SSA:MediumLevelILCallOutputSsa, # [("dest_memory", "int"), ("dest", "var_ssa_list")],
- MediumLevelILOperation.MLIL_CALL_PARAM_SSA:MediumLevelILCallParamSsa, # [("src_memory", "int"), ("src", "var_ssa_list")],
- MediumLevelILOperation.MLIL_LOAD_SSA:MediumLevelILLoadSsa, # [("src", "expr"), ("src_memory", "int")],
- MediumLevelILOperation.MLIL_VAR_PHI:MediumLevelILVarPhi, # [("dest", "var_ssa"), ("src", "var_ssa_list")],
- MediumLevelILOperation.MLIL_MEM_PHI:MediumLevelILMemPhi, # [("dest_memory", "int"), ("src_memory", "int_list")],
- MediumLevelILOperation.MLIL_SET_VAR_SSA:MediumLevelILSetVarSsa, # [("dest", "var_ssa"), ("src", "expr")],
- MediumLevelILOperation.MLIL_FCMP_E:MediumLevelILFcmpE, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_FCMP_NE:MediumLevelILFcmpNe, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_FCMP_LT:MediumLevelILFcmpLt, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_FCMP_LE:MediumLevelILFcmpLe, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_FCMP_GE:MediumLevelILFcmpGe, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_FCMP_GT:MediumLevelILFcmpGt, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_FCMP_O:MediumLevelILFcmpO, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_FCMP_UO:MediumLevelILFcmpUo, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_FADD:MediumLevelILFadd, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_FSUB:MediumLevelILFsub, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_FMUL:MediumLevelILFmul, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_FDIV:MediumLevelILFdiv, # [("left", "expr"), ("right", "expr")],
- MediumLevelILOperation.MLIL_JUMP_TO:MediumLevelILJumpTo, # [("dest", "expr"), ("targets", "target_map")],
- MediumLevelILOperation.MLIL_SET_VAR_ALIASED:MediumLevelILSetVarAliased, # [("prev", "var_ssa_dest_and_src"), ("src", "expr")],
- MediumLevelILOperation.MLIL_SYSCALL_UNTYPED:MediumLevelILSyscallUntyped, # [("output", "expr"), ("params", "expr"), ("stack", "expr")],
- MediumLevelILOperation.MLIL_TAILCALL:MediumLevelILTailcall, # [("output", "var_list"), ("dest", "expr"), ("params", "expr_list")],
- MediumLevelILOperation.MLIL_INTRINSIC:MediumLevelILIntrinsic, # [("output", "var_list"), ("intrinsic", "intrinsic"), ("params", "expr_list")],
- MediumLevelILOperation.MLIL_INTRINSIC_SSA:MediumLevelILIntrinsicSsa, # [("output", "var_ssa_list"), ("intrinsic", "intrinsic"), ("params", "expr_list")],
- MediumLevelILOperation.MLIL_SET_VAR_SSA_FIELD:MediumLevelILSetVarSsaField, # [("prev", "var_ssa_dest_and_src"), ("offset", "int"), ("src", "expr")],
- MediumLevelILOperation.MLIL_SET_VAR_SPLIT_SSA:MediumLevelILSetVarSplitSsa, # [("high", "var_ssa"), ("low", "var_ssa"), ("src", "expr")],
- MediumLevelILOperation.MLIL_SET_VAR_ALIASED_FIELD:MediumLevelILSetVarAliasedField, # [("prev", "var_ssa_dest_and_src"), ("offset", "int"), ("src", "expr")],
- MediumLevelILOperation.MLIL_SYSCALL_SSA:MediumLevelILSyscallSsa, # [("output", "expr"), ("params", "expr_list"), ("src_memory", "int")],
- MediumLevelILOperation.MLIL_SYSCALL_UNTYPED_SSA:MediumLevelILSyscallUntypedSsa, # [("output", "expr"), ("params", "expr"), ("stack", "expr")],
- MediumLevelILOperation.MLIL_LOAD_STRUCT_SSA:MediumLevelILLoadStructSsa, # [("src", "expr"), ("offset", "int"), ("src_memory", "int")],
- MediumLevelILOperation.MLIL_SET_VAR_FIELD:MediumLevelILSetVarField, # [("dest", "var"), ("offset", "int"), ("src", "expr")],
- MediumLevelILOperation.MLIL_SET_VAR_SPLIT:MediumLevelILSetVarSplit, # [("high", "var"), ("low", "var"), ("src", "expr")],
- MediumLevelILOperation.MLIL_STORE_STRUCT:MediumLevelILStoreStruct, # [("dest", "expr"), ("offset", "int"), ("src", "expr")],
- MediumLevelILOperation.MLIL_ADC:MediumLevelILAdc, # [("left", "expr"), ("right", "expr"), ("carry", "expr")],
- MediumLevelILOperation.MLIL_SBB:MediumLevelILSbb, # [("left", "expr"), ("right", "expr"), ("carry", "expr")],
- MediumLevelILOperation.MLIL_RLC:MediumLevelILRlc, # [("left", "expr"), ("right", "expr"), ("carry", "expr")],
- MediumLevelILOperation.MLIL_RRC:MediumLevelILRrc, # [("left", "expr"), ("right", "expr"), ("carry", "expr")],
- MediumLevelILOperation.MLIL_TAILCALL_UNTYPED:MediumLevelILTailcallUntyped, # [("output", "expr"), ("dest", "expr"), ("params", "expr"), ("stack", "expr")],
- MediumLevelILOperation.MLIL_CALL_SSA:MediumLevelILCallSsa, # [("output", "expr"), ("dest", "expr"), ("params", "expr_list"), ("src_memory", "int")],
- MediumLevelILOperation.MLIL_CALL_UNTYPED_SSA:MediumLevelILCallUntypedSsa, # [("output", "expr"), ("dest", "expr"), ("params", "expr"), ("stack", "expr")],
- MediumLevelILOperation.MLIL_TAILCALL_SSA:MediumLevelILTailcallSsa, # [("output", "expr"), ("dest", "expr"), ("params", "expr_list"), ("src_memory", "int")],
- MediumLevelILOperation.MLIL_TAILCALL_UNTYPED_SSA:MediumLevelILTailcallUntypedSsa, # [("output", "expr"), ("dest", "expr"), ("params", "expr"), ("stack", "expr")],
- MediumLevelILOperation.MLIL_CALL:MediumLevelILCall, # [("output", "var_list"), ("dest", "expr"), ("params", "expr_list")],
- MediumLevelILOperation.MLIL_IF:MediumLevelILIf, # [("condition", "expr"), ("true", "int"), ("false", "int")],
- MediumLevelILOperation.MLIL_STORE_SSA:MediumLevelILStoreSsa, # [("dest", "expr"), ("dest_memory", "int"), ("src_memory", "int"), ("src", "expr")],
- MediumLevelILOperation.MLIL_CALL_UNTYPED:MediumLevelILCallUntyped, # [("output", "expr"), ("dest", "expr"), ("params", "expr"), ("stack", "expr")],
- MediumLevelILOperation.MLIL_STORE_STRUCT_SSA:MediumLevelILStoreStructSsa, # [("dest", "expr"), ("offset", "int"), ("dest_memory", "int"), ("src_memory", "int"), ("src", "expr")],
+ MediumLevelILOperation.MLIL_NOP: MediumLevelILNop, # [],
+ MediumLevelILOperation.MLIL_NORET: MediumLevelILNoret, # [],
+ MediumLevelILOperation.MLIL_BP: MediumLevelILBp, # [],
+ MediumLevelILOperation.MLIL_UNDEF: MediumLevelILUndef, # [],
+ MediumLevelILOperation.MLIL_UNIMPL: MediumLevelILUnimpl, # [],
+ MediumLevelILOperation.MLIL_LOAD: MediumLevelILLoad, # [("src", "expr")],
+ MediumLevelILOperation.MLIL_VAR: MediumLevelILVar, # [("src", "var")],
+ MediumLevelILOperation.MLIL_ADDRESS_OF: MediumLevelILAddressOf, # [("src", "var")],
+ MediumLevelILOperation.MLIL_CONST: MediumLevelILConst, # [("constant", "int")],
+ MediumLevelILOperation.MLIL_CONST_PTR: MediumLevelILConstPtr, # [("constant", "int")],
+ MediumLevelILOperation.MLIL_FLOAT_CONST: MediumLevelILFloatConst, # [("constant", "float")],
+ MediumLevelILOperation.MLIL_IMPORT: MediumLevelILImport, # [("constant", "int")],
+ MediumLevelILOperation.MLIL_SET_VAR: MediumLevelILSetVar, # [("dest", "var"), ("src", "expr")],
+ MediumLevelILOperation.MLIL_LOAD_STRUCT: MediumLevelILLoadStruct, # [("src", "expr"), ("offset", "int")],
+ MediumLevelILOperation.MLIL_STORE: MediumLevelILStore, # [("dest", "expr"), ("src", "expr")],
+ MediumLevelILOperation.MLIL_VAR_FIELD: MediumLevelILVarField, # [("src", "var"), ("offset", "int")],
+ MediumLevelILOperation.MLIL_VAR_SPLIT: MediumLevelILVarSplit, # [("high", "var"), ("low", "var")],
+ MediumLevelILOperation.MLIL_ADDRESS_OF_FIELD: MediumLevelILAddressOfField, # [("src", "var"), ("offset", "int")],
+ MediumLevelILOperation.MLIL_EXTERN_PTR: MediumLevelILExternPtr, # [("constant", "int"), ("offset", "int")],
+ MediumLevelILOperation.MLIL_ADD: MediumLevelILAdd, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_SUB: MediumLevelILSub, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_AND: MediumLevelILAnd, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_OR: MediumLevelILOr, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_XOR: MediumLevelILXor, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_LSL: MediumLevelILLsl, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_LSR: MediumLevelILLsr, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_ASR: MediumLevelILAsr, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_ROL: MediumLevelILRol, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_ROR: MediumLevelILRor, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_MUL: MediumLevelILMul, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_MULU_DP: MediumLevelILMuluDp, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_MULS_DP: MediumLevelILMulsDp, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_DIVU: MediumLevelILDivu, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_DIVU_DP: MediumLevelILDivuDp, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_DIVS: MediumLevelILDivs, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_DIVS_DP: MediumLevelILDivsDp, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_MODU: MediumLevelILModu, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_MODU_DP: MediumLevelILModuDp, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_MODS: MediumLevelILMods, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_MODS_DP: MediumLevelILModsDp, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_NEG: MediumLevelILNeg, # [("src", "expr")],
+ MediumLevelILOperation.MLIL_NOT: MediumLevelILNot, # [("src", "expr")],
+ MediumLevelILOperation.MLIL_SX: MediumLevelILSx, # [("src", "expr")],
+ MediumLevelILOperation.MLIL_ZX: MediumLevelILZx, # [("src", "expr")],
+ MediumLevelILOperation.MLIL_LOW_PART: MediumLevelILLowPart, # [("src", "expr")],
+ MediumLevelILOperation.MLIL_JUMP: MediumLevelILJump, # [("dest", "expr")],
+ MediumLevelILOperation.MLIL_RET_HINT: MediumLevelILRetHint, # [("dest", "expr")],
+ MediumLevelILOperation.MLIL_CALL_OUTPUT: MediumLevelILCallOutput, # [("dest", "var_list")],
+ MediumLevelILOperation.MLIL_CALL_PARAM: MediumLevelILCallParam, # [("src", "var_list")],
+ MediumLevelILOperation.MLIL_RET: MediumLevelILRet, # [("src", "expr_list")],
+ MediumLevelILOperation.MLIL_GOTO: MediumLevelILGoto, # [("dest", "int")],
+ MediumLevelILOperation.MLIL_BOOL_TO_INT: MediumLevelILBoolToInt, # [("src", "expr")],
+ MediumLevelILOperation.MLIL_FREE_VAR_SLOT: MediumLevelILFreeVarSlot, # [("dest", "var")],
+ MediumLevelILOperation.MLIL_TRAP: MediumLevelILTrap, # [("vector", "int")],
+ MediumLevelILOperation.MLIL_FREE_VAR_SLOT_SSA: MediumLevelILFreeVarSlotSsa, # [("prev", "var_ssa_dest_and_src")],
+ MediumLevelILOperation.MLIL_UNIMPL_MEM: MediumLevelILUnimplMem, # [("src", "expr")],
+ MediumLevelILOperation.MLIL_FSQRT: MediumLevelILFsqrt, # [("src", "expr")],
+ MediumLevelILOperation.MLIL_FNEG: MediumLevelILFneg, # [("src", "expr")],
+ MediumLevelILOperation.MLIL_FABS: MediumLevelILFabs, # [("src", "expr")],
+ MediumLevelILOperation.MLIL_FLOAT_TO_INT: MediumLevelILFloatToInt, # [("src", "expr")],
+ MediumLevelILOperation.MLIL_INT_TO_FLOAT: MediumLevelILIntToFloat, # [("src", "expr")],
+ MediumLevelILOperation.MLIL_FLOAT_CONV: MediumLevelILFloatConv, # [("src", "expr")],
+ MediumLevelILOperation.MLIL_ROUND_TO_INT: MediumLevelILRoundToInt, # [("src", "expr")],
+ MediumLevelILOperation.MLIL_FLOOR: MediumLevelILFloor, # [("src", "expr")],
+ MediumLevelILOperation.MLIL_CEIL: MediumLevelILCeil, # [("src", "expr")],
+ MediumLevelILOperation.MLIL_FTRUNC: MediumLevelILFtrunc, # [("src", "expr")],
+ MediumLevelILOperation.MLIL_VAR_SSA: MediumLevelILVarSsa, # [("src", "var_ssa")],
+ MediumLevelILOperation.MLIL_VAR_ALIASED: MediumLevelILVarAliased, # [("src", "var_ssa")],
+ MediumLevelILOperation.MLIL_CMP_E: MediumLevelILCmpE, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_CMP_NE: MediumLevelILCmpNe, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_CMP_SLT: MediumLevelILCmpSlt, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_CMP_ULT: MediumLevelILCmpUlt, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_CMP_SLE: MediumLevelILCmpSle, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_CMP_ULE: MediumLevelILCmpUle, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_CMP_SGE: MediumLevelILCmpSge, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_CMP_UGE: MediumLevelILCmpUge, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_CMP_SGT: MediumLevelILCmpSgt, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_CMP_UGT: MediumLevelILCmpUgt, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_TEST_BIT: MediumLevelILTestBit, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_ADD_OVERFLOW: MediumLevelILAddOverflow, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_SYSCALL: MediumLevelILSyscall, # [("output", "var_list"), ("params", "expr_list")],
+ MediumLevelILOperation.MLIL_VAR_SSA_FIELD: MediumLevelILVarSsaField, # [("src", "var_ssa"), ("offset", "int")],
+ MediumLevelILOperation.MLIL_VAR_ALIASED_FIELD:
+ MediumLevelILVarAliasedField, # [("src", "var_ssa"), ("offset", "int")],
+ MediumLevelILOperation.MLIL_VAR_SPLIT_SSA: MediumLevelILVarSplitSsa, # [("high", "var_ssa"), ("low", "var_ssa")],
+ MediumLevelILOperation.MLIL_CALL_OUTPUT_SSA:
+ MediumLevelILCallOutputSsa, # [("dest_memory", "int"), ("dest", "var_ssa_list")],
+ MediumLevelILOperation.MLIL_CALL_PARAM_SSA:
+ MediumLevelILCallParamSsa, # [("src_memory", "int"), ("src", "var_ssa_list")],
+ MediumLevelILOperation.MLIL_LOAD_SSA: MediumLevelILLoadSsa, # [("src", "expr"), ("src_memory", "int")],
+ MediumLevelILOperation.MLIL_VAR_PHI: MediumLevelILVarPhi, # [("dest", "var_ssa"), ("src", "var_ssa_list")],
+ MediumLevelILOperation.MLIL_MEM_PHI: MediumLevelILMemPhi, # [("dest_memory", "int"), ("src_memory", "int_list")],
+ MediumLevelILOperation.MLIL_SET_VAR_SSA: MediumLevelILSetVarSsa, # [("dest", "var_ssa"), ("src", "expr")],
+ MediumLevelILOperation.MLIL_FCMP_E: MediumLevelILFcmpE, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_FCMP_NE: MediumLevelILFcmpNe, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_FCMP_LT: MediumLevelILFcmpLt, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_FCMP_LE: MediumLevelILFcmpLe, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_FCMP_GE: MediumLevelILFcmpGe, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_FCMP_GT: MediumLevelILFcmpGt, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_FCMP_O: MediumLevelILFcmpO, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_FCMP_UO: MediumLevelILFcmpUo, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_FADD: MediumLevelILFadd, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_FSUB: MediumLevelILFsub, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_FMUL: MediumLevelILFmul, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_FDIV: MediumLevelILFdiv, # [("left", "expr"), ("right", "expr")],
+ MediumLevelILOperation.MLIL_JUMP_TO: MediumLevelILJumpTo, # [("dest", "expr"), ("targets", "target_map")],
+ MediumLevelILOperation.MLIL_SET_VAR_ALIASED:
+ MediumLevelILSetVarAliased, # [("prev", "var_ssa_dest_and_src"), ("src", "expr")],
+ MediumLevelILOperation.MLIL_SYSCALL_UNTYPED:
+ MediumLevelILSyscallUntyped, # [("output", "expr"), ("params", "expr"), ("stack", "expr")],
+ MediumLevelILOperation.MLIL_TAILCALL:
+ MediumLevelILTailcall, # [("output", "var_list"), ("dest", "expr"), ("params", "expr_list")],
+ MediumLevelILOperation.MLIL_INTRINSIC:
+ MediumLevelILIntrinsic, # [("output", "var_list"), ("intrinsic", "intrinsic"), ("params", "expr_list")],
+ MediumLevelILOperation.MLIL_INTRINSIC_SSA:
+ MediumLevelILIntrinsicSsa, # [("output", "var_ssa_list"), ("intrinsic", "intrinsic"), ("params", "expr_list")],
+ MediumLevelILOperation.MLIL_SET_VAR_SSA_FIELD:
+ MediumLevelILSetVarSsaField, # [("prev", "var_ssa_dest_and_src"), ("offset", "int"), ("src", "expr")],
+ MediumLevelILOperation.MLIL_SET_VAR_SPLIT_SSA:
+ MediumLevelILSetVarSplitSsa, # [("high", "var_ssa"), ("low", "var_ssa"), ("src", "expr")],
+ MediumLevelILOperation.MLIL_SET_VAR_ALIASED_FIELD:
+ MediumLevelILSetVarAliasedField, # [("prev", "var_ssa_dest_and_src"), ("offset", "int"), ("src", "expr")],
+ MediumLevelILOperation.MLIL_SYSCALL_SSA:
+ MediumLevelILSyscallSsa, # [("output", "expr"), ("params", "expr_list"), ("src_memory", "int")],
+ MediumLevelILOperation.MLIL_SYSCALL_UNTYPED_SSA:
+ MediumLevelILSyscallUntypedSsa, # [("output", "expr"), ("params", "expr"), ("stack", "expr")],
+ MediumLevelILOperation.MLIL_LOAD_STRUCT_SSA:
+ MediumLevelILLoadStructSsa, # [("src", "expr"), ("offset", "int"), ("src_memory", "int")],
+ MediumLevelILOperation.MLIL_SET_VAR_FIELD:
+ MediumLevelILSetVarField, # [("dest", "var"), ("offset", "int"), ("src", "expr")],
+ MediumLevelILOperation.MLIL_SET_VAR_SPLIT:
+ MediumLevelILSetVarSplit, # [("high", "var"), ("low", "var"), ("src", "expr")],
+ MediumLevelILOperation.MLIL_STORE_STRUCT:
+ MediumLevelILStoreStruct, # [("dest", "expr"), ("offset", "int"), ("src", "expr")],
+ MediumLevelILOperation.MLIL_ADC: MediumLevelILAdc, # [("left", "expr"), ("right", "expr"), ("carry", "expr")],
+ MediumLevelILOperation.MLIL_SBB: MediumLevelILSbb, # [("left", "expr"), ("right", "expr"), ("carry", "expr")],
+ MediumLevelILOperation.MLIL_RLC: MediumLevelILRlc, # [("left", "expr"), ("right", "expr"), ("carry", "expr")],
+ MediumLevelILOperation.MLIL_RRC: MediumLevelILRrc, # [("left", "expr"), ("right", "expr"), ("carry", "expr")],
+ MediumLevelILOperation.MLIL_TAILCALL_UNTYPED:
+ MediumLevelILTailcallUntyped, # [("output", "expr"), ("dest", "expr"), ("params", "expr"), ("stack", "expr")],
+ MediumLevelILOperation.MLIL_CALL_SSA:
+ MediumLevelILCallSsa, # [("output", "expr"), ("dest", "expr"), ("params", "expr_list"), ("src_memory", "int")],
+ MediumLevelILOperation.MLIL_CALL_UNTYPED_SSA:
+ MediumLevelILCallUntypedSsa, # [("output", "expr"), ("dest", "expr"), ("params", "expr"), ("stack", "expr")],
+ MediumLevelILOperation.MLIL_TAILCALL_SSA:
+ MediumLevelILTailcallSsa, # [("output", "expr"), ("dest", "expr"), ("params", "expr_list"), ("src_memory", "int")],
+ MediumLevelILOperation.MLIL_TAILCALL_UNTYPED_SSA:
+ MediumLevelILTailcallUntypedSsa, # [("output", "expr"), ("dest", "expr"), ("params", "expr"), ("stack", "expr")],
+ MediumLevelILOperation.MLIL_CALL:
+ MediumLevelILCall, # [("output", "var_list"), ("dest", "expr"), ("params", "expr_list")],
+ MediumLevelILOperation.MLIL_IF: MediumLevelILIf, # [("condition", "expr"), ("true", "int"), ("false", "int")],
+ MediumLevelILOperation.MLIL_STORE_SSA:
+ MediumLevelILStoreSsa, # [("dest", "expr"), ("dest_memory", "int"), ("src_memory", "int"), ("src", "expr")],
+ MediumLevelILOperation.MLIL_CALL_UNTYPED:
+ MediumLevelILCallUntyped, # [("output", "expr"), ("dest", "expr"), ("params", "expr"), ("stack", "expr")],
+ MediumLevelILOperation.MLIL_STORE_STRUCT_SSA:
+ MediumLevelILStoreStructSsa, # [("dest", "expr"), ("offset", "int"), ("dest_memory", "int"), ("src_memory", "int"), ("src", "expr")],
}
+
class MediumLevelILExpr:
"""
``class MediumLevelILExpr`` hold the index of IL Expressions.
@@ -2585,15 +2637,17 @@ class MediumLevelILFunction:
objects can be added to the MediumLevelILFunction by calling :func:`append` and passing the result of the various class
methods which return ExpressionIndex objects.
"""
- def __init__(self, arch:Optional['architecture.Architecture']=None,
- handle:Optional[core.BNMediumLevelILFunction]=None, source_func:Optional['function.Function']=None):
+ def __init__(
+ self, arch: Optional['architecture.Architecture'] = None, handle: Optional[core.BNMediumLevelILFunction] = None,
+ source_func: Optional['function.Function'] = None
+ ):
_arch = arch
_source_function = source_func
if handle is not None:
MLILHandle = ctypes.POINTER(core.BNMediumLevelILFunction)
_handle = ctypes.cast(handle, MLILHandle)
if _source_function is None:
- _source_function = function.Function(handle = core.BNGetMediumLevelILOwnerFunction(_handle))
+ _source_function = function.Function(handle=core.BNGetMediumLevelILOwnerFunction(_handle))
if _arch is None:
_arch = _source_function.arch
else:
@@ -2640,13 +2694,15 @@ class MediumLevelILFunction:
def __getitem__(self, i) -> 'MediumLevelILInstruction':
if isinstance(i, slice) or isinstance(i, tuple):
raise IndexError("expected integer instruction index")
- elif isinstance(i, MediumLevelILInstruction): # for backwards compatibility
+ elif isinstance(i, MediumLevelILInstruction): # for backwards compatibility
return i
if i < -len(self) or i >= len(self):
raise IndexError("index out of range")
if i < 0:
i = len(self) + i
- return MediumLevelILInstruction.create(self, ExpressionIndex(core.BNGetMediumLevelILIndexForInstruction(self.handle, i)), i)
+ return MediumLevelILInstruction.create(
+ self, ExpressionIndex(core.BNGetMediumLevelILIndexForInstruction(self.handle, i)), i
+ )
def __setitem__(self, i, j):
raise IndexError("instruction modification not implemented")
@@ -2672,10 +2728,10 @@ class MediumLevelILFunction:
return core.BNMediumLevelILGetCurrentAddress(self.handle)
@current_address.setter
- def current_address(self, value:int) -> None:
+ def current_address(self, value: int) -> None:
core.BNMediumLevelILSetCurrentAddress(self.handle, self._arch.handle, value)
- def set_current_address(self, value:int, arch:Optional['architecture.Architecture']=None) -> None:
+ def set_current_address(self, value: int, arch: Optional['architecture.Architecture'] = None) -> None:
_arch = arch
if _arch is None:
_arch = self._arch
@@ -2741,7 +2797,7 @@ class MediumLevelILFunction:
def hlil(self) -> Optional[highlevelil.HighLevelILFunction]:
return self.high_level_il
- def get_instruction_start(self, addr:int, arch:Optional['architecture.Architecture']=None) -> Optional[int]:
+ def get_instruction_start(self, addr: int, arch: Optional['architecture.Architecture'] = None) -> Optional[int]:
_arch = arch
if _arch is None:
if self._arch is None:
@@ -2752,8 +2808,10 @@ class MediumLevelILFunction:
return None
return result
- def expr(self, operation:MediumLevelILOperation, a:int=0, b:int=0, c:int=0, d:int=0, e:int=0,
- size:int=0) -> ExpressionIndex:
+ def expr(
+ self, operation: MediumLevelILOperation, a: int = 0, b: int = 0, c: int = 0, d: int = 0, e: int = 0,
+ size: int = 0
+ ) -> ExpressionIndex:
_operation = operation
if isinstance(operation, str):
_operation = MediumLevelILOperation[operation]
@@ -2761,7 +2819,7 @@ class MediumLevelILFunction:
_operation = operation.value
return ExpressionIndex(core.BNMediumLevelILAddExpr(self.handle, _operation, size, a, b, c, d, e))
- def append(self, expr:ExpressionIndex) -> int:
+ def append(self, expr: ExpressionIndex) -> int:
"""
``append`` adds the ExpressionIndex ``expr`` to the current MediumLevelILFunction.
@@ -2771,7 +2829,7 @@ class MediumLevelILFunction:
"""
return core.BNMediumLevelILAddInstruction(self.handle, expr)
- def goto(self, label:MediumLevelILLabel) -> ExpressionIndex:
+ def goto(self, label: MediumLevelILLabel) -> ExpressionIndex:
"""
``goto`` returns a goto expression which jumps to the provided MediumLevelILLabel.
@@ -2781,7 +2839,7 @@ class MediumLevelILFunction:
"""
return ExpressionIndex(core.BNMediumLevelILGoto(self.handle, label.handle))
- def if_expr(self, operand:ExpressionIndex, t:MediumLevelILLabel, f:MediumLevelILLabel) -> ExpressionIndex:
+ def if_expr(self, operand: ExpressionIndex, t: MediumLevelILLabel, f: MediumLevelILLabel) -> ExpressionIndex:
"""
``if_expr`` returns the ``if`` expression which depending on condition ``operand`` jumps to the MediumLevelILLabel
``t`` when the condition expression ``operand`` is non-zero and ``f`` when it's zero.
@@ -2794,7 +2852,7 @@ class MediumLevelILFunction:
"""
return ExpressionIndex(core.BNMediumLevelILIf(self.handle, operand, t.handle, f.handle))
- def mark_label(self, label:MediumLevelILLabel) -> None:
+ def mark_label(self, label: MediumLevelILLabel) -> None:
"""
``mark_label`` assigns a MediumLevelILLabel to the current IL address.
@@ -2803,7 +2861,7 @@ class MediumLevelILFunction:
"""
core.BNMediumLevelILMarkLabel(self.handle, label.handle)
- def add_label_map(self, labels:Mapping[int, MediumLevelILLabel]) -> ExpressionIndex:
+ def add_label_map(self, labels: Mapping[int, MediumLevelILLabel]) -> ExpressionIndex:
"""
``add_label_map`` returns a label list expression for the given list of MediumLevelILLabel objects.
@@ -2820,7 +2878,7 @@ class MediumLevelILFunction:
return ExpressionIndex(core.BNMediumLevelILAddLabelMap(self.handle, value_list, label_list, len(labels)))
- def add_operand_list(self, operands:List[ExpressionIndex]) -> ExpressionIndex:
+ def add_operand_list(self, operands: List[ExpressionIndex]) -> ExpressionIndex:
"""
``add_operand_list`` returns an operand list expression for the given list of integer operands.
@@ -2842,26 +2900,26 @@ class MediumLevelILFunction:
"""
core.BNFinalizeMediumLevelILFunction(self.handle)
- def get_ssa_instruction_index(self, instr:InstructionIndex) -> InstructionIndex:
+ def get_ssa_instruction_index(self, instr: InstructionIndex) -> InstructionIndex:
return InstructionIndex(core.BNGetMediumLevelILSSAInstructionIndex(self.handle, instr))
- def get_non_ssa_instruction_index(self, instr:InstructionIndex) -> InstructionIndex:
+ def get_non_ssa_instruction_index(self, instr: InstructionIndex) -> InstructionIndex:
return InstructionIndex(core.BNGetMediumLevelILNonSSAInstructionIndex(self.handle, instr))
- def get_ssa_var_definition(self, ssa_var:SSAVariable) -> Optional[MediumLevelILInstruction]:
+ def get_ssa_var_definition(self, ssa_var: SSAVariable) -> Optional[MediumLevelILInstruction]:
var_data = ssa_var.var.to_BNVariable()
result = core.BNGetMediumLevelILSSAVarDefinition(self.handle, var_data, ssa_var.version)
if result >= core.BNGetMediumLevelILInstructionCount(self.handle):
return None
return self[result]
- def get_ssa_memory_definition(self, version:int) -> Optional[MediumLevelILInstruction]:
+ def get_ssa_memory_definition(self, version: int) -> Optional[MediumLevelILInstruction]:
result = core.BNGetMediumLevelILSSAMemoryDefinition(self.handle, version)
if result >= core.BNGetMediumLevelILInstructionCount(self.handle):
return None
return self[result]
- def get_ssa_var_uses(self, ssa_var:SSAVariable) -> List[MediumLevelILInstruction]:
+ def get_ssa_var_uses(self, ssa_var: SSAVariable) -> List[MediumLevelILInstruction]:
count = ctypes.c_ulonglong()
var_data = ssa_var.var.to_BNVariable()
instrs = core.BNGetMediumLevelILSSAVarUses(self.handle, var_data, ssa_var.version, count)
@@ -2872,7 +2930,7 @@ class MediumLevelILFunction:
core.BNFreeILInstructionList(instrs)
return result
- def get_ssa_memory_uses(self, version:int) -> List[MediumLevelILInstruction]:
+ def get_ssa_memory_uses(self, version: int) -> List[MediumLevelILInstruction]:
count = ctypes.c_ulonglong()
instrs = core.BNGetMediumLevelILSSAMemoryUses(self.handle, version, count)
assert instrs is not None, "core.BNGetMediumLevelILSSAMemoryUses returned None"
@@ -2882,7 +2940,7 @@ class MediumLevelILFunction:
core.BNFreeILInstructionList(instrs)
return result
- def is_ssa_var_live(self, ssa_var:SSAVariable) -> bool:
+ def is_ssa_var_live(self, ssa_var: SSAVariable) -> bool:
"""
``is_ssa_var_live`` determines if ``ssa_var`` is live at any point in the function
@@ -2893,7 +2951,7 @@ class MediumLevelILFunction:
var_data = ssa_var.var.to_BNVariable()
return core.BNIsMediumLevelILSSAVarLive(self.handle, var_data, ssa_var.version)
- def get_var_definitions(self, var:'variable.Variable') -> List[MediumLevelILInstruction]:
+ def get_var_definitions(self, var: 'variable.Variable') -> List[MediumLevelILInstruction]:
count = ctypes.c_ulonglong()
var_data = var.to_BNVariable()
instrs = core.BNGetMediumLevelILVariableDefinitions(self.handle, var_data, count)
@@ -2904,7 +2962,7 @@ class MediumLevelILFunction:
core.BNFreeILInstructionList(instrs)
return result
- def get_var_uses(self, var:'variable.Variable') -> List[MediumLevelILInstruction]:
+ def get_var_uses(self, var: 'variable.Variable') -> List[MediumLevelILInstruction]:
count = ctypes.c_ulonglong()
var_data = var.to_BNVariable()
instrs = core.BNGetMediumLevelILVariableUses(self.handle, var_data, count)
@@ -2917,13 +2975,13 @@ class MediumLevelILFunction:
finally:
core.BNFreeILInstructionList(instrs)
- def get_ssa_var_value(self, ssa_var:SSAVariable) -> 'variable.RegisterValue':
+ def get_ssa_var_value(self, ssa_var: SSAVariable) -> 'variable.RegisterValue':
var_data = ssa_var.var.to_BNVariable()
value = core.BNGetMediumLevelILSSAVarValue(self.handle, var_data, ssa_var.version)
result = variable.RegisterValue.from_BNRegisterValue(value, self._arch)
return result
- def get_low_level_il_instruction_index(self, instr:InstructionIndex) -> Optional['lowlevelil.InstructionIndex']:
+ def get_low_level_il_instruction_index(self, instr: InstructionIndex) -> Optional['lowlevelil.InstructionIndex']:
low_il = self.low_level_il
if low_il is None:
return None
@@ -2935,7 +2993,7 @@ class MediumLevelILFunction:
return None
return lowlevelil.InstructionIndex(result)
- def get_low_level_il_expr_index(self, expr:ExpressionIndex) -> Optional['lowlevelil.ExpressionIndex']:
+ def get_low_level_il_expr_index(self, expr: ExpressionIndex) -> Optional['lowlevelil.ExpressionIndex']:
low_il = self.low_level_il
if low_il is None:
return None
@@ -2947,17 +3005,17 @@ class MediumLevelILFunction:
return None
return lowlevelil.ExpressionIndex(result)
- def get_low_level_il_expr_indexes(self, expr:ExpressionIndex) -> List['lowlevelil.ExpressionIndex']:
+ def get_low_level_il_expr_indexes(self, expr: ExpressionIndex) -> List['lowlevelil.ExpressionIndex']:
count = ctypes.c_ulonglong()
exprs = core.BNGetLowLevelILExprIndexes(self.handle, expr, count)
assert exprs is not None, "core.BNGetLowLevelILExprIndexes returned None"
- result:List['lowlevelil.ExpressionIndex'] = []
+ result: List['lowlevelil.ExpressionIndex'] = []
for i in range(0, count.value):
result.append(lowlevelil.ExpressionIndex(exprs[i]))
core.BNFreeILInstructionList(exprs)
return result
- def get_high_level_il_instruction_index(self, instr:InstructionIndex) -> Optional['highlevelil.InstructionIndex']:
+ def get_high_level_il_instruction_index(self, instr: InstructionIndex) -> Optional['highlevelil.InstructionIndex']:
high_il = self.high_level_il
if high_il is None:
return None
@@ -2966,7 +3024,7 @@ class MediumLevelILFunction:
return None
return highlevelil.InstructionIndex(result)
- def get_high_level_il_expr_index(self, expr:ExpressionIndex) -> Optional['highlevelil.ExpressionIndex']:
+ def get_high_level_il_expr_index(self, expr: ExpressionIndex) -> Optional['highlevelil.ExpressionIndex']:
high_il = self.high_level_il
if high_il is None:
return None
@@ -2975,17 +3033,17 @@ class MediumLevelILFunction:
return None
return highlevelil.ExpressionIndex(result)
- def get_high_level_il_expr_indexes(self, expr:ExpressionIndex) -> List['highlevelil.ExpressionIndex']:
+ def get_high_level_il_expr_indexes(self, expr: ExpressionIndex) -> List['highlevelil.ExpressionIndex']:
count = ctypes.c_ulonglong()
exprs = core.BNGetHighLevelILExprIndexes(self.handle, expr, count)
assert exprs is not None, "core.BNGetHighLevelILExprIndexes returned None"
- result:List['highlevelil.ExpressionIndex'] = []
+ result: List['highlevelil.ExpressionIndex'] = []
for i in range(0, count.value):
result.append(highlevelil.ExpressionIndex(exprs[i]))
core.BNFreeILInstructionList(exprs)
return result
- def create_graph(self, settings:'function.DisassemblySettings'=None) -> flowgraph.CoreFlowGraph:
+ def create_graph(self, settings: 'function.DisassemblySettings' = None) -> flowgraph.CoreFlowGraph:
if settings is not None:
settings_obj = settings.handle
else:
@@ -3020,14 +3078,22 @@ class MediumLevelILFunction:
if self.source_function is None:
return []
- if self.il_form in [FunctionGraphType.MediumLevelILFunctionGraph, FunctionGraphType.MediumLevelILSSAFormFunctionGraph, FunctionGraphType.MappedMediumLevelILFunctionGraph, FunctionGraphType.MappedMediumLevelILSSAFormFunctionGraph]:
+ if self.il_form in [
+ FunctionGraphType.MediumLevelILFunctionGraph, FunctionGraphType.MediumLevelILSSAFormFunctionGraph,
+ FunctionGraphType.MappedMediumLevelILFunctionGraph,
+ FunctionGraphType.MappedMediumLevelILSSAFormFunctionGraph
+ ]:
count = ctypes.c_ulonglong()
core_variables = core.BNGetMediumLevelILVariables(self.handle, count)
assert core_variables is not None, "core.BNGetMediumLevelILVariables returned None"
result = []
try:
for var_i in range(count.value):
- result.append(variable.Variable(self, core_variables[var_i].type, core_variables[var_i].index, core_variables[var_i].storage))
+ result.append(
+ variable.Variable(
+ self, core_variables[var_i].type, core_variables[var_i].index, core_variables[var_i].storage
+ )
+ )
return result
finally:
core.BNFreeVariableList(core_variables)
@@ -3039,14 +3105,20 @@ class MediumLevelILFunction:
if self.source_function is None:
return []
- if self.il_form in [FunctionGraphType.MediumLevelILFunctionGraph, FunctionGraphType.MediumLevelILSSAFormFunctionGraph]:
+ if self.il_form in [
+ FunctionGraphType.MediumLevelILFunctionGraph, FunctionGraphType.MediumLevelILSSAFormFunctionGraph
+ ]:
count = ctypes.c_ulonglong()
core_variables = core.BNGetMediumLevelILAliasedVariables(self.handle, count)
assert core_variables is not None, "core.BNGetMediumLevelILAliasedVariables returned None"
try:
result = []
for var_i in range(count.value):
- result.append(variable.Variable(self, core_variables[var_i].type, core_variables[var_i].index, core_variables[var_i].storage))
+ result.append(
+ variable.Variable(
+ self, core_variables[var_i].type, core_variables[var_i].index, core_variables[var_i].storage
+ )
+ )
return result
finally:
core.BNFreeVariableList(core_variables)
@@ -3058,7 +3130,10 @@ class MediumLevelILFunction:
if self.source_function is None:
return []
- if self.il_form in [FunctionGraphType.MediumLevelILSSAFormFunctionGraph, FunctionGraphType.MappedMediumLevelILSSAFormFunctionGraph]:
+ if self.il_form in [
+ FunctionGraphType.MediumLevelILSSAFormFunctionGraph,
+ FunctionGraphType.MappedMediumLevelILSSAFormFunctionGraph
+ ]:
variable_count = ctypes.c_ulonglong()
core_variables = core.BNGetMediumLevelILVariables(self.handle, variable_count)
assert core_variables is not None, "core.BNGetMediumLevelILVariables returned None"
@@ -3066,27 +3141,39 @@ class MediumLevelILFunction:
result = []
for var_i in range(variable_count.value):
version_count = ctypes.c_ulonglong()
- versions = core.BNGetMediumLevelILVariableSSAVersions(self.handle, core_variables[var_i], version_count)
+ versions = core.BNGetMediumLevelILVariableSSAVersions(
+ self.handle, core_variables[var_i], version_count
+ )
assert versions is not None, "core.BNGetMediumLevelILVariableSSAVersions returned None"
try:
for version_i in range(version_count.value):
- result.append(SSAVariable(variable.Variable(self,
- core_variables[var_i].type, core_variables[var_i].index,
- core_variables[var_i].storage), versions[version_i]))
+ result.append(
+ SSAVariable(
+ variable.Variable(
+ self, core_variables[var_i].type, core_variables[var_i].index,
+ core_variables[var_i].storage
+ ), versions[version_i]
+ )
+ )
finally:
core.BNFreeILInstructionList(versions)
return result
finally:
core.BNFreeVariableList(core_variables)
- elif self.il_form in [FunctionGraphType.MediumLevelILFunctionGraph, FunctionGraphType.MappedMediumLevelILFunctionGraph]:
+ elif self.il_form in [
+ FunctionGraphType.MediumLevelILFunctionGraph, FunctionGraphType.MappedMediumLevelILFunctionGraph
+ ]:
return self.ssa_form.ssa_vars
return []
class MediumLevelILBasicBlock(basicblock.BasicBlock):
- def __init__(self, handle:core.BNBasicBlockHandle, owner:MediumLevelILFunction, view:Optional['binaryview.BinaryView']=None):
+ def __init__(
+ self, handle: core.BNBasicBlockHandle, owner: MediumLevelILFunction,
+ view: Optional['binaryview.BinaryView'] = None
+ ):
super(MediumLevelILBasicBlock, self).__init__(handle, view)
self._il_function = owner
@@ -3123,7 +3210,9 @@ class MediumLevelILBasicBlock(basicblock.BasicBlock):
else:
return False
- def _create_instance(self, handle:core.BNBasicBlockHandle, view:'binaryview.BinaryView') -> 'MediumLevelILBasicBlock':
+ def _create_instance(
+ self, handle: core.BNBasicBlockHandle, view: 'binaryview.BinaryView'
+ ) -> 'MediumLevelILBasicBlock':
"""Internal method by super to instantiate child instances"""
return MediumLevelILBasicBlock(handle, self.il_function, view)
diff --git a/python/metadata.py b/python/metadata.py
index c7820ee9..4c643112 100644
--- a/python/metadata.py
+++ b/python/metadata.py
@@ -27,9 +27,12 @@ from .enums import MetadataType
MetadataValueType = Union[int, bool, str, bytes, float, List['MetadataValueType'], Tuple['MetadataValueType'], dict]
+
class Metadata:
- def __init__(self, value:MetadataValueType=None, signed:Optional[bool]=None,
- raw:Optional[bool]=None, handle:Optional[core.BNMetadata]=None):
+ def __init__(
+ self, value: MetadataValueType = None, signed: Optional[bool] = None, raw: Optional[bool] = None,
+ handle: Optional[core.BNMetadata] = None
+ ):
if handle is not None:
self.handle = handle
elif isinstance(value, int):
@@ -278,4 +281,4 @@ class Metadata:
elif isinstance(key_or_index, int) and self.is_array:
core.BNMetadataRemoveIndex(self.handle, key_or_index)
else:
- raise TypeError("remove only valid for dict and array objects") \ No newline at end of file
+ raise TypeError("remove only valid for dict and array objects")
diff --git a/python/platform.py b/python/platform.py
index 050aa21e..28a2a5f2 100644
--- a/python/platform.py
+++ b/python/platform.py
@@ -39,7 +39,7 @@ class _PlatformMetaClass(type):
assert platforms is not None, "core.BNGetPlatformList returned None"
try:
for i in range(0, count.value):
- yield Platform(handle = core.BNNewPlatformReference(platforms[i]))
+ yield Platform(handle=core.BNNewPlatformReference(platforms[i]))
finally:
core.BNFreePlatformList(platforms, count.value)
@@ -48,7 +48,7 @@ class _PlatformMetaClass(type):
platform = core.BNGetPlatformByName(str(value))
if platform is None:
raise KeyError("'%s' is not a valid platform" % str(value))
- return Platform(handle = platform)
+ return Platform(handle=platform)
class Platform(metaclass=_PlatformMetaClass):
@@ -57,10 +57,10 @@ class Platform(metaclass=_PlatformMetaClass):
calling conventions used.
"""
name = None
- type_file_path = None # path to platform types file
- type_include_dirs = [] # list of directories available to #include from type_file_path
+ type_file_path = None # path to platform types file
+ type_include_dirs = [] # list of directories available to #include from type_file_path
- def __init__(self, arch:'architecture.Architecture'=None, handle=None):
+ def __init__(self, arch: 'architecture.Architecture' = None, handle=None):
if handle is None:
if arch is None:
raise ValueError("platform must have an associated architecture")
@@ -73,7 +73,10 @@ class Platform(metaclass=_PlatformMetaClass):
dir_buf = (ctypes.c_char_p * len(self.__class__.type_include_dirs))()
for (i, dir) in enumerate(self.__class__.type_include_dirs):
dir_buf[i] = dir.encode('charmap')
- _handle = core.BNCreatePlatformWithTypes(arch.handle, self.__class__.name, self.__class__.type_file_path, dir_buf, len(self.__class__.type_include_dirs))
+ _handle = core.BNCreatePlatformWithTypes(
+ arch.handle, self.__class__.name, self.__class__.type_file_path, dir_buf,
+ len(self.__class__.type_include_dirs)
+ )
assert _handle is not None
else:
_handle = handle
@@ -121,7 +124,7 @@ class Platform(metaclass=_PlatformMetaClass):
return result
@classmethod
- def get_list(cls, os = None, arch = None):
+ def get_list(cls, os=None, arch=None):
binaryninja._init_plugins()
count = ctypes.c_ulonglong()
if os is None:
@@ -135,7 +138,7 @@ class Platform(metaclass=_PlatformMetaClass):
assert platforms is not None, "core.BNGetPlatformListByArchitecture returned None"
result = []
for i in range(0, count.value):
- result.append(Platform(handle = core.BNNewPlatformReference(platforms[i])))
+ result.append(Platform(handle=core.BNNewPlatformReference(platforms[i])))
core.BNFreePlatformList(platforms, count.value)
return result
@@ -251,7 +254,7 @@ class Platform(metaclass=_PlatformMetaClass):
result = {}
for i in range(0, count.value):
name = types.QualifiedName._from_core_struct(type_list[i].name)
- result[name] = types.Type.create(core.BNNewTypeReference(type_list[i].type), platform = self)
+ result[name] = types.Type.create(core.BNNewTypeReference(type_list[i].type), platform=self)
core.BNFreeTypeList(type_list, count.value)
return result
@@ -264,7 +267,7 @@ class Platform(metaclass=_PlatformMetaClass):
result = {}
for i in range(0, count.value):
name = types.QualifiedName._from_core_struct(type_list[i].name)
- result[name] = types.Type.create(core.BNNewTypeReference(type_list[i].type), platform = self)
+ result[name] = types.Type.create(core.BNNewTypeReference(type_list[i].type), platform=self)
core.BNFreeTypeList(type_list, count.value)
return result
@@ -277,7 +280,7 @@ class Platform(metaclass=_PlatformMetaClass):
result = {}
for i in range(0, count.value):
name = types.QualifiedName._from_core_struct(type_list[i].name)
- result[name] = types.Type.create(core.BNNewTypeReference(type_list[i].type), platform = self)
+ result[name] = types.Type.create(core.BNNewTypeReference(type_list[i].type), platform=self)
core.BNFreeTypeList(type_list, count.value)
return result
@@ -290,7 +293,7 @@ class Platform(metaclass=_PlatformMetaClass):
result = {}
for i in range(0, count.value):
name = types.QualifiedName._from_core_struct(call_list[i].name)
- t = types.Type.create(core.BNNewTypeReference(call_list[i].type), platform = self)
+ t = types.Type.create(core.BNNewTypeReference(call_list[i].type), platform=self)
result[call_list[i].number] = (name, t)
core.BNFreeSystemCallList(call_list, count.value)
return result
@@ -338,7 +341,7 @@ class Platform(metaclass=_PlatformMetaClass):
result = core.BNGetRelatedPlatform(self.handle, arch.handle)
if not result:
return None
- return Platform(handle = result)
+ return Platform(handle=result)
def add_related_platform(self, arch, platform):
core.BNAddRelatedPlatform(self.handle, arch.handle, platform.handle)
@@ -347,28 +350,28 @@ class Platform(metaclass=_PlatformMetaClass):
new_addr = ctypes.c_ulonglong()
new_addr.value = addr
result = core.BNGetAssociatedPlatformByAddress(self.handle, new_addr)
- return Platform(handle = result), new_addr.value
+ return Platform(handle=result), new_addr.value
def get_type_by_name(self, name):
name = types.QualifiedName(name)._to_core_struct()
obj = core.BNGetPlatformTypeByName(self.handle, name)
if not obj:
return None
- return types.Type.create(core.BNNewTypeReference(obj), platform = self)
+ return types.Type.create(core.BNNewTypeReference(obj), platform=self)
def get_variable_by_name(self, name):
name = types.QualifiedName(name)._to_core_struct()
obj = core.BNGetPlatformVariableByName(self.handle, name)
if not obj:
return None
- return types.Type.create(core.BNNewTypeReference(obj), platform = self)
+ return types.Type.create(core.BNNewTypeReference(obj), platform=self)
def get_function_by_name(self, name, exactMatch=False):
name = types.QualifiedName(name)._to_core_struct()
obj = core.BNGetPlatformFunctionByName(self.handle, name, exactMatch)
if not obj:
return None
- return types.Type.create(core.BNNewTypeReference(obj), platform = self)
+ return types.Type.create(core.BNNewTypeReference(obj), platform=self)
def get_system_call_name(self, number):
return core.BNGetPlatformSystemCallName(self.handle, number)
@@ -377,7 +380,7 @@ class Platform(metaclass=_PlatformMetaClass):
obj = core.BNGetPlatformSystemCallType(self.handle, number)
if not obj:
return None
- return types.Type.create(core.BNNewTypeReference(obj), platform = self)
+ return types.Type.create(core.BNNewTypeReference(obj), platform=self)
def generate_auto_platform_type_id(self, name):
name = types.QualifiedName(name)._to_core_struct()
@@ -390,7 +393,9 @@ class Platform(metaclass=_PlatformMetaClass):
def get_auto_platform_type_id_source(self):
return core.BNGetAutoPlatformTypeIdSource(self.handle)
- def parse_types_from_source(self, source, filename=None, include_dirs:Optional[List[str]]=None, auto_type_source=None):
+ def parse_types_from_source(
+ self, source, filename=None, include_dirs: Optional[List[str]] = None, auto_type_source=None
+ ):
"""
``parse_types_from_source`` parses the source string and any needed headers searching for them in
the optional list of directories provided in ``include_dirs``.
@@ -421,29 +426,30 @@ class Platform(metaclass=_PlatformMetaClass):
dir_buf[i] = include_dirs[i].encode('charmap')
parse = core.BNTypeParserResult()
errors = ctypes.c_char_p()
- result = core.BNParseTypesFromSource(self.handle, source, filename, parse, errors, dir_buf,
- len(include_dirs), auto_type_source)
+ result = core.BNParseTypesFromSource(
+ self.handle, source, filename, parse, errors, dir_buf, len(include_dirs), auto_type_source
+ )
assert errors.value is not None, "core.BNParseTypesFromSource returned errors set to None"
error_str = errors.value.decode("utf-8")
core.free_string(errors)
if not result:
raise SyntaxError(error_str)
- type_dict:Dict[types.QualifiedName, types.Type] = {}
- variables:Dict[types.QualifiedName, types.Type] = {}
- functions:Dict[types.QualifiedName, types.Type] = {}
+ type_dict: Dict[types.QualifiedName, types.Type] = {}
+ variables: Dict[types.QualifiedName, types.Type] = {}
+ functions: Dict[types.QualifiedName, types.Type] = {}
for i in range(0, parse.typeCount):
name = types.QualifiedName._from_core_struct(parse.types[i].name)
- type_dict[name] = types.Type.create(core.BNNewTypeReference(parse.types[i].type), platform = self)
+ type_dict[name] = types.Type.create(core.BNNewTypeReference(parse.types[i].type), platform=self)
for i in range(0, parse.variableCount):
name = types.QualifiedName._from_core_struct(parse.variables[i].name)
- variables[name] = types.Type.create(core.BNNewTypeReference(parse.variables[i].type), platform = self)
+ variables[name] = types.Type.create(core.BNNewTypeReference(parse.variables[i].type), platform=self)
for i in range(0, parse.functionCount):
name = types.QualifiedName._from_core_struct(parse.functions[i].name)
- functions[name] = types.Type.create(core.BNNewTypeReference(parse.functions[i].type), platform = self)
+ functions[name] = types.Type.create(core.BNNewTypeReference(parse.functions[i].type), platform=self)
core.BNFreeTypeParserResult(parse)
return types.TypeParserResult(type_dict, variables, functions)
- def parse_types_from_source_file(self, filename, include_dirs:Optional[List[str]]=None, auto_type_source=None):
+ def parse_types_from_source_file(self, filename, include_dirs: Optional[List[str]] = None, auto_type_source=None):
"""
``parse_types_from_source_file`` parses the source file ``filename`` and any needed headers searching for them in
the optional list of directories provided in ``include_dirs``.
@@ -473,8 +479,9 @@ class Platform(metaclass=_PlatformMetaClass):
dir_buf[i] = include_dirs[i].encode('charmap')
parse = core.BNTypeParserResult()
errors = ctypes.c_char_p()
- result = core.BNParseTypesFromSourceFile(self.handle, filename, parse, errors, dir_buf,
- len(include_dirs), auto_type_source)
+ result = core.BNParseTypesFromSourceFile(
+ self.handle, filename, parse, errors, dir_buf, len(include_dirs), auto_type_source
+ )
assert errors.value is not None, "core.BNParseTypesFromSourceFile returned errors set to None"
error_str = errors.value.decode("utf-8")
core.free_string(errors)
@@ -485,13 +492,13 @@ class Platform(metaclass=_PlatformMetaClass):
functions = {}
for i in range(0, parse.typeCount):
name = types.QualifiedName._from_core_struct(parse.types[i].name)
- type_dict[name] = types.Type.create(core.BNNewTypeReference(parse.types[i].type), platform = self)
+ type_dict[name] = types.Type.create(core.BNNewTypeReference(parse.types[i].type), platform=self)
for i in range(0, parse.variableCount):
name = types.QualifiedName._from_core_struct(parse.variables[i].name)
- variables[name] = types.Type.create(core.BNNewTypeReference(parse.variables[i].type), platform = self)
+ variables[name] = types.Type.create(core.BNNewTypeReference(parse.variables[i].type), platform=self)
for i in range(0, parse.functionCount):
name = types.QualifiedName._from_core_struct(parse.functions[i].name)
- functions[name] = types.Type.create(core.BNNewTypeReference(parse.functions[i].type), platform = self)
+ functions[name] = types.Type.create(core.BNNewTypeReference(parse.functions[i].type), platform=self)
core.BNFreeTypeParserResult(parse)
return types.TypeParserResult(type_dict, variables, functions)
diff --git a/python/plugin.py b/python/plugin.py
index 5dbc4fa7..741fe4a1 100644
--- a/python/plugin.py
+++ b/python/plugin.py
@@ -115,8 +115,8 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
@staticmethod
def _default_action(view, action):
try:
- file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
- view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
+ file_metadata = filemetadata.FileMetadata(handle=core.BNGetFileForView(view))
+ view_obj = binaryview.BinaryView(file_metadata=file_metadata, handle=core.BNNewViewReference(view))
action(view_obj)
except:
log_error(traceback.format_exc())
@@ -124,8 +124,8 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
@staticmethod
def _address_action(view, addr, action):
try:
- file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
- view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
+ file_metadata = filemetadata.FileMetadata(handle=core.BNGetFileForView(view))
+ view_obj = binaryview.BinaryView(file_metadata=file_metadata, handle=core.BNNewViewReference(view))
action(view_obj, addr)
except:
log_error(traceback.format_exc())
@@ -133,8 +133,8 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
@staticmethod
def _range_action(view, addr, length, action):
try:
- file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
- view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
+ file_metadata = filemetadata.FileMetadata(handle=core.BNGetFileForView(view))
+ view_obj = binaryview.BinaryView(file_metadata=file_metadata, handle=core.BNNewViewReference(view))
action(view_obj, addr, length)
except:
log_error(traceback.format_exc())
@@ -142,8 +142,8 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
@staticmethod
def _function_action(view, func, action):
try:
- file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
- view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
+ file_metadata = filemetadata.FileMetadata(handle=core.BNGetFileForView(view))
+ view_obj = binaryview.BinaryView(file_metadata=file_metadata, handle=core.BNNewViewReference(view))
func_obj = function.Function(view_obj, core.BNNewFunctionReference(func))
action(view_obj, func_obj)
except:
@@ -152,8 +152,8 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
@staticmethod
def _low_level_il_function_action(view, func, action):
try:
- file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
- view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
+ file_metadata = filemetadata.FileMetadata(handle=core.BNGetFileForView(view))
+ view_obj = binaryview.BinaryView(file_metadata=file_metadata, handle=core.BNNewViewReference(view))
owner = function.Function(view_obj, core.BNGetLowLevelILOwnerFunction(func))
func_obj = lowlevelil.LowLevelILFunction(owner.arch, core.BNNewLowLevelILFunctionReference(func), owner)
action(view_obj, func_obj)
@@ -163,8 +163,8 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
@staticmethod
def _low_level_il_instruction_action(view, func, instr, action):
try:
- file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
- view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
+ file_metadata = filemetadata.FileMetadata(handle=core.BNGetFileForView(view))
+ view_obj = binaryview.BinaryView(file_metadata=file_metadata, handle=core.BNNewViewReference(view))
owner = function.Function(view_obj, core.BNGetLowLevelILOwnerFunction(func))
func_obj = lowlevelil.LowLevelILFunction(owner.arch, core.BNNewLowLevelILFunctionReference(func), owner)
action(view_obj, func_obj[instr])
@@ -174,10 +174,12 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
@staticmethod
def _medium_level_il_function_action(view, func, action):
try:
- file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
- view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
+ file_metadata = filemetadata.FileMetadata(handle=core.BNGetFileForView(view))
+ view_obj = binaryview.BinaryView(file_metadata=file_metadata, handle=core.BNNewViewReference(view))
owner = function.Function(view_obj, core.BNGetMediumLevelILOwnerFunction(func))
- func_obj = mediumlevelil.MediumLevelILFunction(owner.arch, core.BNNewMediumLevelILFunctionReference(func), owner)
+ func_obj = mediumlevelil.MediumLevelILFunction(
+ owner.arch, core.BNNewMediumLevelILFunctionReference(func), owner
+ )
action(view_obj, func_obj)
except:
log_error(traceback.format_exc())
@@ -185,10 +187,12 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
@staticmethod
def _medium_level_il_instruction_action(view, func, instr, action):
try:
- file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
- view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
+ file_metadata = filemetadata.FileMetadata(handle=core.BNGetFileForView(view))
+ view_obj = binaryview.BinaryView(file_metadata=file_metadata, handle=core.BNNewViewReference(view))
owner = function.Function(view_obj, core.BNGetMediumLevelILOwnerFunction(func))
- func_obj = mediumlevelil.MediumLevelILFunction(owner.arch, core.BNNewMediumLevelILFunctionReference(func), owner)
+ func_obj = mediumlevelil.MediumLevelILFunction(
+ owner.arch, core.BNNewMediumLevelILFunctionReference(func), owner
+ )
action(view_obj, func_obj[instr])
except:
log_error(traceback.format_exc())
@@ -196,8 +200,8 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
@staticmethod
def _high_level_il_function_action(view, func, action):
try:
- file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
- view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
+ file_metadata = filemetadata.FileMetadata(handle=core.BNGetFileForView(view))
+ view_obj = binaryview.BinaryView(file_metadata=file_metadata, handle=core.BNNewViewReference(view))
owner = function.Function(view_obj, core.BNGetHighLevelILOwnerFunction(func))
func_obj = highlevelil.HighLevelILFunction(owner.arch, core.BNNewHighLevelILFunctionReference(func), owner)
action(view_obj, func_obj)
@@ -207,8 +211,8 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
@staticmethod
def _high_level_il_instruction_action(view, func, instr, action):
try:
- file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
- view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
+ file_metadata = filemetadata.FileMetadata(handle=core.BNGetFileForView(view))
+ view_obj = binaryview.BinaryView(file_metadata=file_metadata, handle=core.BNNewViewReference(view))
owner = function.Function(view_obj, core.BNGetHighLevelILOwnerFunction(func))
func_obj = highlevelil.HighLevelILFunction(owner.arch, core.BNNewHighLevelILFunctionReference(func), owner)
action(view_obj, func_obj[instr])
@@ -220,8 +224,8 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
try:
if is_valid is None:
return True
- file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
- view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
+ file_metadata = filemetadata.FileMetadata(handle=core.BNGetFileForView(view))
+ view_obj = binaryview.BinaryView(file_metadata=file_metadata, handle=core.BNNewViewReference(view))
return is_valid(view_obj)
except:
log_error(traceback.format_exc())
@@ -232,8 +236,8 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
try:
if is_valid is None:
return True
- file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
- view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
+ file_metadata = filemetadata.FileMetadata(handle=core.BNGetFileForView(view))
+ view_obj = binaryview.BinaryView(file_metadata=file_metadata, handle=core.BNNewViewReference(view))
return is_valid(view_obj, addr)
except:
log_error(traceback.format_exc())
@@ -244,8 +248,8 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
try:
if is_valid is None:
return True
- file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
- view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
+ file_metadata = filemetadata.FileMetadata(handle=core.BNGetFileForView(view))
+ view_obj = binaryview.BinaryView(file_metadata=file_metadata, handle=core.BNNewViewReference(view))
return is_valid(view_obj, addr, length)
except:
log_error(traceback.format_exc())
@@ -256,8 +260,8 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
try:
if is_valid is None:
return True
- file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
- view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
+ file_metadata = filemetadata.FileMetadata(handle=core.BNGetFileForView(view))
+ view_obj = binaryview.BinaryView(file_metadata=file_metadata, handle=core.BNNewViewReference(view))
func_obj = function.Function(view_obj, core.BNNewFunctionReference(func))
return is_valid(view_obj, func_obj)
except:
@@ -269,8 +273,8 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
try:
if is_valid is None:
return True
- file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
- view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
+ file_metadata = filemetadata.FileMetadata(handle=core.BNGetFileForView(view))
+ view_obj = binaryview.BinaryView(file_metadata=file_metadata, handle=core.BNNewViewReference(view))
owner = function.Function(view_obj, core.BNGetLowLevelILOwnerFunction(func))
func_obj = lowlevelil.LowLevelILFunction(owner.arch, core.BNNewLowLevelILFunctionReference(func), owner)
return is_valid(view_obj, func_obj)
@@ -283,8 +287,8 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
try:
if is_valid is None:
return True
- file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
- view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
+ file_metadata = filemetadata.FileMetadata(handle=core.BNGetFileForView(view))
+ view_obj = binaryview.BinaryView(file_metadata=file_metadata, handle=core.BNNewViewReference(view))
owner = function.Function(view_obj, core.BNGetLowLevelILOwnerFunction(func))
func_obj = lowlevelil.LowLevelILFunction(owner.arch, core.BNNewLowLevelILFunctionReference(func), owner)
return is_valid(view_obj, func_obj[instr])
@@ -297,10 +301,12 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
try:
if is_valid is None:
return True
- file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
- view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
+ file_metadata = filemetadata.FileMetadata(handle=core.BNGetFileForView(view))
+ view_obj = binaryview.BinaryView(file_metadata=file_metadata, handle=core.BNNewViewReference(view))
owner = function.Function(view_obj, core.BNGetMediumLevelILOwnerFunction(func))
- func_obj = mediumlevelil.MediumLevelILFunction(owner.arch, core.BNNewMediumLevelILFunctionReference(func), owner)
+ func_obj = mediumlevelil.MediumLevelILFunction(
+ owner.arch, core.BNNewMediumLevelILFunctionReference(func), owner
+ )
return is_valid(view_obj, func_obj)
except:
log_error(traceback.format_exc())
@@ -311,10 +317,12 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
try:
if is_valid is None:
return True
- file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
- view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
+ file_metadata = filemetadata.FileMetadata(handle=core.BNGetFileForView(view))
+ view_obj = binaryview.BinaryView(file_metadata=file_metadata, handle=core.BNNewViewReference(view))
owner = function.Function(view_obj, core.BNGetMediumLevelILOwnerFunction(func))
- func_obj = mediumlevelil.MediumLevelILFunction(owner.arch, core.BNNewMediumLevelILFunctionReference(func), owner)
+ func_obj = mediumlevelil.MediumLevelILFunction(
+ owner.arch, core.BNNewMediumLevelILFunctionReference(func), owner
+ )
return is_valid(view_obj, func_obj[instr])
except:
log_error(traceback.format_exc())
@@ -325,8 +333,8 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
try:
if is_valid is None:
return True
- file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
- view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
+ file_metadata = filemetadata.FileMetadata(handle=core.BNGetFileForView(view))
+ view_obj = binaryview.BinaryView(file_metadata=file_metadata, handle=core.BNNewViewReference(view))
owner = function.Function(view_obj, core.BNGetHighLevelILOwnerFunction(func))
func_obj = highlevelil.HighLevelILFunction(owner.arch, core.BNNewHighLevelILFunctionReference(func), owner)
return is_valid(view_obj, func_obj)
@@ -339,8 +347,8 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
try:
if is_valid is None:
return True
- file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
- view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
+ file_metadata = filemetadata.FileMetadata(handle=core.BNGetFileForView(view))
+ view_obj = binaryview.BinaryView(file_metadata=file_metadata, handle=core.BNNewViewReference(view))
owner = function.Function(view_obj, core.BNGetHighLevelILOwnerFunction(func))
func_obj = highlevelil.HighLevelILFunction(owner.arch, core.BNNewHighLevelILFunctionReference(func), owner)
return is_valid(view_obj, func_obj[instr])
@@ -349,11 +357,9 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
return False
@classmethod
- def register(cls,
- name: str,
- description: str,
- action: Callable[[binaryview.BinaryView], None],
- is_valid: Optional[Callable[[binaryview.BinaryView], bool]] = None
+ def register(
+ cls, name: str, description: str, action: Callable[[binaryview.BinaryView], None],
+ is_valid: Optional[Callable[[binaryview.BinaryView], bool]] = None
):
r"""
``register`` Register a plugin
@@ -367,17 +373,19 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
.. warning:: Calling ``register`` with the same function name will replace the existing function but will leak the memory of the original plugin.
"""
binaryninja._init_plugins()
- action_obj = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView))(lambda ctxt, view: cls._default_action(view, action))
- is_valid_obj = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView))(lambda ctxt, view: cls._default_is_valid(view, is_valid))
+ action_obj = ctypes.CFUNCTYPE(None, ctypes.c_void_p,
+ ctypes.POINTER(core.BNBinaryView
+ ))(lambda ctxt, view: cls._default_action(view, action))
+ is_valid_obj = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p,
+ ctypes.POINTER(core.BNBinaryView
+ ))(lambda ctxt, view: cls._default_is_valid(view, is_valid))
cls._registered_commands.append((action_obj, is_valid_obj))
core.BNRegisterPluginCommand(name, description, action_obj, is_valid_obj, None)
@classmethod
- def register_for_address(cls,
- name: str,
- description: str,
- action: Callable[[binaryview.BinaryView, int], None],
- is_valid: Optional[Callable[[binaryview.BinaryView, int], bool]] = None
+ def register_for_address(
+ cls, name: str, description: str, action: Callable[[binaryview.BinaryView, int], None],
+ is_valid: Optional[Callable[[binaryview.BinaryView, int], bool]] = None
):
r"""
``register_for_address`` Register a plugin to be called with an address argument
@@ -391,17 +399,19 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
.. warning:: Calling ``register_for_address`` with the same function name will replace the existing function but will leak the memory of the original plugin.
"""
binaryninja._init_plugins()
- action_obj = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.c_ulonglong)(lambda ctxt, view, addr: cls._address_action(view, addr, action))
- is_valid_obj = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.c_ulonglong)(lambda ctxt, view, addr: cls._address_is_valid(view, addr, is_valid))
+ action_obj = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(
+ core.BNBinaryView
+ ), ctypes.c_ulonglong)(lambda ctxt, view, addr: cls._address_action(view, addr, action))
+ is_valid_obj = ctypes.CFUNCTYPE(
+ ctypes.c_bool, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.c_ulonglong
+ )(lambda ctxt, view, addr: cls._address_is_valid(view, addr, is_valid))
cls._registered_commands.append((action_obj, is_valid_obj))
core.BNRegisterPluginCommandForAddress(name, description, action_obj, is_valid_obj, None)
@classmethod
- def register_for_range(cls,
- name: str,
- description: str,
- action: Callable[[binaryview.BinaryView, int, int], None],
- is_valid: Optional[Callable[[binaryview.BinaryView, int, int], bool]] = None
+ def register_for_range(
+ cls, name: str, description: str, action: Callable[[binaryview.BinaryView, int, int], None],
+ is_valid: Optional[Callable[[binaryview.BinaryView, int, int], bool]] = None
):
r"""
``register_for_range`` Register a plugin to be called with a range argument
@@ -415,17 +425,19 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
.. warning:: Calling ``register_for_range`` with the same function name will replace the existing function but will leak the memory of the original plugin.
"""
binaryninja._init_plugins()
- action_obj = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.c_ulonglong, ctypes.c_ulonglong)(lambda ctxt, view, addr, length: cls._range_action(view, addr, length, action))
- is_valid_obj = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.c_ulonglong, ctypes.c_ulonglong)(lambda ctxt, view, addr, length: cls._range_is_valid(view, addr, length, is_valid))
+ action_obj = ctypes.CFUNCTYPE(
+ None, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.c_ulonglong, ctypes.c_ulonglong
+ )(lambda ctxt, view, addr, length: cls._range_action(view, addr, length, action))
+ is_valid_obj = ctypes.CFUNCTYPE(
+ ctypes.c_bool, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.c_ulonglong, ctypes.c_ulonglong
+ )(lambda ctxt, view, addr, length: cls._range_is_valid(view, addr, length, is_valid))
cls._registered_commands.append((action_obj, is_valid_obj))
core.BNRegisterPluginCommandForRange(name, description, action_obj, is_valid_obj, None)
@classmethod
- def register_for_function(cls,
- name: str,
- description: str,
- action: Callable[[binaryview.BinaryView, function.Function], None],
- is_valid: Optional[Callable[[binaryview.BinaryView, function.Function], bool]] = None
+ def register_for_function(
+ cls, name: str, description: str, action: Callable[[binaryview.BinaryView, function.Function], None],
+ is_valid: Optional[Callable[[binaryview.BinaryView, function.Function], bool]] = None
):
r"""
``register_for_function`` Register a plugin to be called with a function argument
@@ -439,17 +451,20 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
.. warning:: Calling ``register_for_function`` with the same function name will replace the existing function but will leak the memory of the original plugin.
"""
binaryninja._init_plugins()
- action_obj = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNFunction))(lambda ctxt, view, func: cls._function_action(view, func, action))
- is_valid_obj = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNFunction))(lambda ctxt, view, func: cls._function_is_valid(view, func, is_valid))
+ action_obj = ctypes.CFUNCTYPE(
+ None, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNFunction)
+ )(lambda ctxt, view, func: cls._function_action(view, func, action))
+ is_valid_obj = ctypes.CFUNCTYPE(
+ ctypes.c_bool, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNFunction)
+ )(lambda ctxt, view, func: cls._function_is_valid(view, func, is_valid))
cls._registered_commands.append((action_obj, is_valid_obj))
core.BNRegisterPluginCommandForFunction(name, description, action_obj, is_valid_obj, None)
@classmethod
- def register_for_low_level_il_function(cls,
- name: str,
- description: str,
- action: Callable[[binaryview.BinaryView, lowlevelil.LowLevelILFunction], None],
- is_valid: Optional[Callable[[binaryview.BinaryView, lowlevelil.LowLevelILFunction], bool]] = None
+ def register_for_low_level_il_function(
+ cls, name: str, description: str, action: Callable[[binaryview.BinaryView, lowlevelil.LowLevelILFunction],
+ None],
+ is_valid: Optional[Callable[[binaryview.BinaryView, lowlevelil.LowLevelILFunction], bool]] = None
):
r"""
``register_for_low_level_il_function`` Register a plugin to be called with a low level IL function argument
@@ -463,17 +478,21 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
.. warning:: Calling ``register_for_low_level_il_function`` with the same function name will replace the existing function but will leak the memory of the original plugin.
"""
binaryninja._init_plugins()
- action_obj = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNLowLevelILFunction))(lambda ctxt, view, func: cls._low_level_il_function_action(view, func, action))
- is_valid_obj = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNLowLevelILFunction))(lambda ctxt, view, func: cls._low_level_il_function_is_valid(view, func, is_valid))
+ action_obj = ctypes.CFUNCTYPE(
+ None, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNLowLevelILFunction)
+ )(lambda ctxt, view, func: cls._low_level_il_function_action(view, func, action))
+ is_valid_obj = ctypes.CFUNCTYPE(
+ ctypes.c_bool, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView),
+ ctypes.POINTER(core.BNLowLevelILFunction)
+ )(lambda ctxt, view, func: cls._low_level_il_function_is_valid(view, func, is_valid))
cls._registered_commands.append((action_obj, is_valid_obj))
core.BNRegisterPluginCommandForLowLevelILFunction(name, description, action_obj, is_valid_obj, None)
@classmethod
- def register_for_low_level_il_instruction(cls,
- name: str,
- description: str,
- action: Callable[[binaryview.BinaryView, lowlevelil.LowLevelILInstruction], None],
- is_valid: Optional[Callable[[binaryview.BinaryView, lowlevelil.LowLevelILInstruction], bool]] = None
+ def register_for_low_level_il_instruction(
+ cls, name: str, description: str, action: Callable[[binaryview.BinaryView, lowlevelil.LowLevelILInstruction],
+ None],
+ is_valid: Optional[Callable[[binaryview.BinaryView, lowlevelil.LowLevelILInstruction], bool]] = None
):
r"""
``register_for_low_level_il_instruction`` Register a plugin to be called with a low level IL instruction argument
@@ -487,17 +506,22 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
.. warning:: Calling ``register_for_low_level_il_instruction`` with the same function name will replace the existing function but will leak the memory of the original plugin.
"""
binaryninja._init_plugins()
- action_obj = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNLowLevelILFunction), ctypes.c_ulonglong)(lambda ctxt, view, func, instr: cls._low_level_il_instruction_action(view, func, instr, action))
- is_valid_obj = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNLowLevelILFunction), ctypes.c_ulonglong)(lambda ctxt, view, func, instr: cls._low_level_il_instruction_is_valid(view, func, instr, is_valid))
+ action_obj = ctypes.CFUNCTYPE(
+ None, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNLowLevelILFunction),
+ ctypes.c_ulonglong
+ )(lambda ctxt, view, func, instr: cls._low_level_il_instruction_action(view, func, instr, action))
+ is_valid_obj = ctypes.CFUNCTYPE(
+ ctypes.c_bool, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView),
+ ctypes.POINTER(core.BNLowLevelILFunction), ctypes.c_ulonglong
+ )(lambda ctxt, view, func, instr: cls._low_level_il_instruction_is_valid(view, func, instr, is_valid))
cls._registered_commands.append((action_obj, is_valid_obj))
core.BNRegisterPluginCommandForLowLevelILInstruction(name, description, action_obj, is_valid_obj, None)
@classmethod
- def register_for_medium_level_il_function(cls,
- name: str,
- description: str,
- action: Callable[[binaryview.BinaryView, mediumlevelil.MediumLevelILFunction], None],
- is_valid: Optional[Callable[[binaryview.BinaryView, mediumlevelil.MediumLevelILFunction], bool]] = None
+ def register_for_medium_level_il_function(
+ cls, name: str, description: str, action: Callable[[binaryview.BinaryView, mediumlevelil.MediumLevelILFunction],
+ None],
+ is_valid: Optional[Callable[[binaryview.BinaryView, mediumlevelil.MediumLevelILFunction], bool]] = None
):
r"""
``register_for_medium_level_il_function`` Register a plugin to be called with a medium level IL function argument
@@ -511,17 +535,21 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
.. warning:: Calling ``register_for_medium_level_il_function`` with the same function name will replace the existing function but will leak the memory of the original plugin.
"""
binaryninja._init_plugins()
- action_obj = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNMediumLevelILFunction))(lambda ctxt, view, func: cls._medium_level_il_function_action(view, func, action))
- is_valid_obj = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNMediumLevelILFunction))(lambda ctxt, view, func: cls._medium_level_il_function_is_valid(view, func, is_valid))
+ action_obj = ctypes.CFUNCTYPE(
+ None, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNMediumLevelILFunction)
+ )(lambda ctxt, view, func: cls._medium_level_il_function_action(view, func, action))
+ is_valid_obj = ctypes.CFUNCTYPE(
+ ctypes.c_bool, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView),
+ ctypes.POINTER(core.BNMediumLevelILFunction)
+ )(lambda ctxt, view, func: cls._medium_level_il_function_is_valid(view, func, is_valid))
cls._registered_commands.append((action_obj, is_valid_obj))
core.BNRegisterPluginCommandForMediumLevelILFunction(name, description, action_obj, is_valid_obj, None)
@classmethod
- def register_for_medium_level_il_instruction(cls,
- name: str,
- description: str,
- action: Callable[[binaryview.BinaryView, mediumlevelil.MediumLevelILInstruction], None],
- is_valid: Optional[Callable[[binaryview.BinaryView, mediumlevelil.MediumLevelILInstruction], bool]] = None
+ def register_for_medium_level_il_instruction(
+ cls, name: str, description: str,
+ action: Callable[[binaryview.BinaryView, mediumlevelil.MediumLevelILInstruction], None],
+ is_valid: Optional[Callable[[binaryview.BinaryView, mediumlevelil.MediumLevelILInstruction], bool]] = None
):
r"""
``register_for_medium_level_il_instruction`` Register a plugin to be called with a medium level IL instruction argument
@@ -535,17 +563,22 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
.. warning:: Calling ``register_for_medium_level_il_instruction`` with the same function name will replace the existing function but will leak the memory of the original plugin.
"""
binaryninja._init_plugins()
- action_obj = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNMediumLevelILFunction), ctypes.c_ulonglong)(lambda ctxt, view, func, instr: cls._medium_level_il_instruction_action(view, func, instr, action))
- is_valid_obj = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNMediumLevelILFunction), ctypes.c_ulonglong)(lambda ctxt, view, func, instr: cls._medium_level_il_instruction_is_valid(view, func, instr, is_valid))
+ action_obj = ctypes.CFUNCTYPE(
+ None, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNMediumLevelILFunction),
+ ctypes.c_ulonglong
+ )(lambda ctxt, view, func, instr: cls._medium_level_il_instruction_action(view, func, instr, action))
+ is_valid_obj = ctypes.CFUNCTYPE(
+ ctypes.c_bool, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView),
+ ctypes.POINTER(core.BNMediumLevelILFunction), ctypes.c_ulonglong
+ )(lambda ctxt, view, func, instr: cls._medium_level_il_instruction_is_valid(view, func, instr, is_valid))
cls._registered_commands.append((action_obj, is_valid_obj))
core.BNRegisterPluginCommandForMediumLevelILInstruction(name, description, action_obj, is_valid_obj, None)
@classmethod
- def register_for_high_level_il_function(cls,
- name: str,
- description: str,
- action: Callable[[binaryview.BinaryView, highlevelil.HighLevelILFunction], None],
- is_valid: Optional[Callable[[binaryview.BinaryView, highlevelil.HighLevelILFunction], bool]] = None
+ def register_for_high_level_il_function(
+ cls, name: str, description: str, action: Callable[[binaryview.BinaryView, highlevelil.HighLevelILFunction],
+ None],
+ is_valid: Optional[Callable[[binaryview.BinaryView, highlevelil.HighLevelILFunction], bool]] = None
):
r"""
``register_for_high_level_il_function`` Register a plugin to be called with a high level IL function argument
@@ -559,17 +592,21 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
.. warning:: Calling ``register_for_high_level_il_function`` with the same function name will replace the existing function but will leak the memory of the original plugin.
"""
binaryninja._init_plugins()
- action_obj = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNHighLevelILFunction))(lambda ctxt, view, func: cls._high_level_il_function_action(view, func, action))
- is_valid_obj = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNHighLevelILFunction))(lambda ctxt, view, func: cls._high_level_il_function_is_valid(view, func, is_valid))
+ action_obj = ctypes.CFUNCTYPE(
+ None, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNHighLevelILFunction)
+ )(lambda ctxt, view, func: cls._high_level_il_function_action(view, func, action))
+ is_valid_obj = ctypes.CFUNCTYPE(
+ ctypes.c_bool, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView),
+ ctypes.POINTER(core.BNHighLevelILFunction)
+ )(lambda ctxt, view, func: cls._high_level_il_function_is_valid(view, func, is_valid))
cls._registered_commands.append((action_obj, is_valid_obj))
core.BNRegisterPluginCommandForHighLevelILFunction(name, description, action_obj, is_valid_obj, None)
@classmethod
- def register_for_high_level_il_instruction(cls,
- name: str,
- description: str,
- action: Callable[[binaryview.BinaryView, highlevelil.HighLevelILInstruction], None],
- is_valid: Optional[Callable[[binaryview.BinaryView, highlevelil.HighLevelILInstruction], bool]] = None
+ def register_for_high_level_il_instruction(
+ cls, name: str, description: str, action: Callable[[binaryview.BinaryView, highlevelil.HighLevelILInstruction],
+ None],
+ is_valid: Optional[Callable[[binaryview.BinaryView, highlevelil.HighLevelILInstruction], bool]] = None
):
r"""
``register_for_high_level_il_instruction`` Register a plugin to be called with a high level IL instruction argument
@@ -583,8 +620,14 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
.. warning:: Calling ``register_for_high_level_il_instruction`` with the same function name will replace the existing function but will leak the memory of the original plugin.
"""
binaryninja._init_plugins()
- action_obj = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNHighLevelILFunction), ctypes.c_ulonglong)(lambda ctxt, view, func, instr: cls._high_level_il_instruction_action(view, func, instr, action))
- is_valid_obj = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNHighLevelILFunction), ctypes.c_ulonglong)(lambda ctxt, view, func, instr: cls._high_level_il_instruction_is_valid(view, func, instr, is_valid))
+ action_obj = ctypes.CFUNCTYPE(
+ None, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNHighLevelILFunction),
+ ctypes.c_ulonglong
+ )(lambda ctxt, view, func, instr: cls._high_level_il_instruction_action(view, func, instr, action))
+ is_valid_obj = ctypes.CFUNCTYPE(
+ ctypes.c_bool, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView),
+ ctypes.POINTER(core.BNHighLevelILFunction), ctypes.c_ulonglong
+ )(lambda ctxt, view, func, instr: cls._high_level_il_instruction_is_valid(view, func, instr, is_valid))
cls._registered_commands.append((action_obj, is_valid_obj))
core.BNRegisterPluginCommandForHighLevelILInstruction(name, description, action_obj, is_valid_obj, None)
@@ -614,7 +657,9 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
return False
if not self._command.rangeIsValid:
return True
- return self._command.rangeIsValid(self._command.context, context.view.handle, context.address, context.length)
+ return self._command.rangeIsValid(
+ self._command.context, context.view.handle, context.address, context.length
+ )
elif self._command.type == PluginCommandType.FunctionPluginCommand:
if context.function is None:
return False
@@ -626,7 +671,9 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
return False
if not self._command.lowLevelILFunctionIsValid:
return True
- return self._command.lowLevelILFunctionIsValid(self._command.context, context.view.handle, context.function.handle)
+ return self._command.lowLevelILFunctionIsValid(
+ self._command.context, context.view.handle, context.function.handle
+ )
elif self._command.type == PluginCommandType.LowLevelILInstructionPluginCommand:
if context.instruction is None:
return False
@@ -634,14 +681,18 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
return False
if not self._command.lowLevelILInstructionIsValid:
return True
- return self._command.lowLevelILInstructionIsValid(self._command.context, context.view.handle,
- context.instruction.function.handle, context.instruction.instr_index)
+ return self._command.lowLevelILInstructionIsValid(
+ self._command.context, context.view.handle, context.instruction.function.handle,
+ context.instruction.instr_index
+ )
elif self._command.type == PluginCommandType.MediumLevelILFunctionPluginCommand:
if context.function is None:
return False
if not self._command.mediumLevelILFunctionIsValid:
return True
- return self._command.mediumLevelILFunctionIsValid(self._command.context, context.view.handle, context.function.handle)
+ return self._command.mediumLevelILFunctionIsValid(
+ self._command.context, context.view.handle, context.function.handle
+ )
elif self._command.type == PluginCommandType.MediumLevelILInstructionPluginCommand:
if context.instruction is None:
return False
@@ -649,14 +700,18 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
return False
if not self._command.mediumLevelILInstructionIsValid:
return True
- return self._command.mediumLevelILInstructionIsValid(self._command.context, context.view.handle,
- context.instruction.function.handle, context.instruction.instr_index)
+ return self._command.mediumLevelILInstructionIsValid(
+ self._command.context, context.view.handle, context.instruction.function.handle,
+ context.instruction.instr_index
+ )
elif self._command.type == PluginCommandType.HighLevelILFunctionPluginCommand:
if context.function is None:
return False
if not self._command.highLevelILFunctionIsValid:
return True
- return self._command.highLevelILFunctionIsValid(self._command.context, context.view.handle, context.function.handle)
+ return self._command.highLevelILFunctionIsValid(
+ self._command.context, context.view.handle, context.function.handle
+ )
elif self._command.type == PluginCommandType.HighLevelILInstructionPluginCommand:
if context.instruction is None:
return False
@@ -664,8 +719,10 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
return False
if not self._command.highLevelILInstructionIsValid:
return True
- return self._command.highLevelILInstructionIsValid(self._command.context, context.view.handle,
- context.instruction.function.handle, context.instruction.instr_index)
+ return self._command.highLevelILInstructionIsValid(
+ self._command.context, context.view.handle, context.instruction.function.handle,
+ context.instruction.instr_index
+ )
return False
def execute(self, context):
@@ -692,18 +749,28 @@ class PluginCommand(metaclass=_PluginCommandMetaClass):
elif self._command.type == PluginCommandType.LowLevelILFunctionPluginCommand:
self._command.lowLevelILFunctionCommand(self._command.context, context.view.handle, context.function.handle)
elif self._command.type == PluginCommandType.LowLevelILInstructionPluginCommand:
- self._command.lowLevelILInstructionCommand(self._command.context, context.view.handle,
- context.instruction.function.handle, context.instruction.instr_index)
+ self._command.lowLevelILInstructionCommand(
+ self._command.context, context.view.handle, context.instruction.function.handle,
+ context.instruction.instr_index
+ )
elif self._command.type == PluginCommandType.MediumLevelILFunctionPluginCommand:
- self._command.mediumLevelILFunctionCommand(self._command.context, context.view.handle, context.function.handle)
+ self._command.mediumLevelILFunctionCommand(
+ self._command.context, context.view.handle, context.function.handle
+ )
elif self._command.type == PluginCommandType.MediumLevelILInstructionPluginCommand:
- self._command.mediumLevelILInstructionCommand(self._command.context, context.view.handle,
- context.instruction.function.handle, context.instruction.instr_index)
+ self._command.mediumLevelILInstructionCommand(
+ self._command.context, context.view.handle, context.instruction.function.handle,
+ context.instruction.instr_index
+ )
elif self._command.type == PluginCommandType.HighLevelILFunctionPluginCommand:
- self._command.highLevelILFunctionCommand(self._command.context, context.view.handle, context.function.handle)
+ self._command.highLevelILFunctionCommand(
+ self._command.context, context.view.handle, context.function.handle
+ )
elif self._command.type == PluginCommandType.HighLevelILInstructionPluginCommand:
- self._command.highLevelILInstructionCommand(self._command.context, context.view.handle,
- context.instruction.function.handle, context.instruction.instr_index)
+ self._command.highLevelILInstructionCommand(
+ self._command.context, context.view.handle, context.instruction.function.handle,
+ context.instruction.instr_index
+ )
def __repr__(self):
return "<PluginCommand: %s>" % self._name
@@ -796,7 +863,7 @@ class _BackgroundTaskMetaclass(type):
class BackgroundTask(metaclass=_BackgroundTaskMetaclass):
- def __init__(self, initial_progress_text = "", can_cancel = False, handle = None):
+ def __init__(self, initial_progress_text="", can_cancel=False, handle=None):
if handle is None:
self.handle = core.BNBeginBackgroundTask(initial_progress_text, can_cancel)
else:
@@ -848,9 +915,9 @@ class BackgroundTask(metaclass=_BackgroundTaskMetaclass):
class BackgroundTaskThread(BackgroundTask):
- def __init__(self, initial_progress_text:str="", can_cancel:bool=False):
+ def __init__(self, initial_progress_text: str = "", can_cancel: bool = False):
class _Thread(threading.Thread):
- def __init__(self, task:'BackgroundTaskThread'):
+ def __init__(self, task: 'BackgroundTaskThread'):
threading.Thread.__init__(self)
self.task = task
diff --git a/python/pluginmanager.py b/python/pluginmanager.py
index 1b5e1b72..dfa64222 100644
--- a/python/pluginmanager.py
+++ b/python/pluginmanager.py
@@ -41,7 +41,9 @@ class RepoPlugin:
core.BNFreePlugin(self.handle)
def __repr__(self):
- return "<{} {}/{}>".format(self.path, "installed" if self.installed else "not-installed", "enabled" if self.enabled else "disabled")
+ return "<{} {}/{}>".format(
+ self.path, "installed" if self.installed else "not-installed", "enabled" if self.enabled else "disabled"
+ )
@property
def path(self):
@@ -183,7 +185,6 @@ class RepoPlugin:
"""String version of the plugin"""
return core.BNPluginGetVersion(self.handle)
-
def install_instructions(self, platform):
"""
Installation instructions for the given platform
@@ -256,6 +257,7 @@ class RepoPlugin:
"""Returns a datetime object representing the plugins last update"""
return datetime.fromtimestamp(core.BNPluginGetLastUpdate(self.handle))
+
class Repository:
"""
``Repository`` is a read-only class. Use RepositoryManager to Enable/Disable/Install/Uninstall plugins.
@@ -349,7 +351,6 @@ class RepositoryManager:
binaryninja._init_plugins()
return Repository(core.BNNewRepositoryReference(core.BNRepositoryManagerGetDefaultRepository(self.handle)))
-
def add_repository(self, url=None, repopath=None):
"""
``add_repository`` adds a new plugin repository for the manager to track.
diff --git a/python/scriptingprovider.py b/python/scriptingprovider.py
index 092afdb0..67781451 100644
--- a/python/scriptingprovider.py
+++ b/python/scriptingprovider.py
@@ -18,7 +18,6 @@
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
-
import code
import traceback
import ctypes
@@ -112,7 +111,7 @@ class ScriptingOutputListener:
class ScriptingInstance:
_registered_instances = []
- def __init__(self, provider, handle = None):
+ def __init__(self, provider, handle=None):
if handle is None:
self._cb = core.BNScriptingInstanceCallbacks()
self._cb.context = 0
@@ -167,7 +166,7 @@ class ScriptingInstance:
def _set_current_binary_view(self, ctxt, view):
try:
if view:
- view = binaryview.BinaryView(handle = core.BNNewViewReference(view))
+ view = binaryview.BinaryView(handle=core.BNNewViewReference(view))
else:
view = None
self.perform_set_current_binary_view(view)
@@ -177,7 +176,7 @@ class ScriptingInstance:
def _set_current_function(self, ctxt, func):
try:
if func:
- func = function.Function(handle = core.BNNewFunctionReference(func))
+ func = function.Function(handle=core.BNNewFunctionReference(func))
else:
func = None
self.perform_set_current_function(func)
@@ -193,8 +192,9 @@ class ScriptingInstance:
else:
core_block = core.BNNewBasicBlockReference(block)
assert core_block is not None, "core.BNNewBasicBlockReference returned None"
- block = basicblock.BasicBlock(core_block,
- binaryview.BinaryView(handle = core.BNGetFunctionData(func)))
+ block = basicblock.BasicBlock(
+ core_block, binaryview.BinaryView(handle=core.BNGetFunctionData(func))
+ )
core.BNFreeFunction(func)
else:
block = None
@@ -218,7 +218,9 @@ class ScriptingInstance:
try:
if not isinstance(text, str):
text = text.decode("charmap")
- return ctypes.cast(self.perform_complete_input(text, state).encode("utf-8"), ctypes.c_void_p).value # type: ignore
+ return ctypes.cast(
+ self.perform_complete_input(text, state).encode("utf-8"), ctypes.c_void_p
+ ).value # type: ignore
except:
log_error(traceback.format_exc())
return "".encode("utf-8")
@@ -258,7 +260,7 @@ class ScriptingInstance:
return NotImplemented
@abc.abstractmethod
- def perform_complete_input(self, text:str, state) -> str:
+ def perform_complete_input(self, text: str, state) -> str:
return NotImplemented
@abc.abstractmethod
@@ -356,7 +358,7 @@ class ScriptingProvider(metaclass=_ScriptingProviderMetaclass):
apiName = ''
instance_class: Optional['ScriptingInstance'] = None
- def __init__(self, handle = None):
+ def __init__(self, handle=None):
if handle is not None:
self.handle = core.handle_of_type(handle, core.BNScriptingProvider)
self.__dict__["name"] = core.BNGetScriptingProviderName(handle)
@@ -388,15 +390,15 @@ class ScriptingProvider(metaclass=_ScriptingProviderMetaclass):
result = core.BNCreateScriptingProviderInstance(self.handle)
if result is None:
return None
- return ScriptingInstance(self, handle = result)
+ return ScriptingInstance(self, handle=result)
- def _load_module(self, ctx, repo_path:bytes, plugin_path:bytes, force:bool) -> bool:
+ def _load_module(self, ctx, repo_path: bytes, plugin_path: bytes, force: bool) -> bool:
return False
- def _install_modules(self, ctx, modules:bytes) -> bool:
+ def _install_modules(self, ctx, modules: bytes) -> bool:
return False
- def _module_installed(self, ctx, module:str) -> bool:
+ def _module_installed(self, ctx, module: str) -> bool:
return False
@@ -522,7 +524,6 @@ class _PythonScriptingInstanceInput:
class BlacklistedDict(dict):
-
def __init__(self, blacklist, *args):
super(BlacklistedDict, self).__init__(*args)
self.__blacklist = set(blacklist)
@@ -530,7 +531,10 @@ class BlacklistedDict(dict):
def __setitem__(self, k, v):
if self.blacklist_enabled and k in self.__blacklist:
- log_error('Setting variable "{}" will have no affect as it is automatically controlled by the ScriptingProvider.'.format(k))
+ log_error(
+ 'Setting variable "{}" will have no affect as it is automatically controlled by the ScriptingProvider.'.
+ format(k)
+ )
super(BlacklistedDict, self).__setitem__(k, v)
def enable_blacklist(self, enabled):
@@ -579,8 +583,13 @@ class PythonScriptingInstance(ScriptingInstance):
super(PythonScriptingInstance.InterpreterThread, self).__init__()
self.instance = instance
# Note: "current_address" and "here" are interactive auto-variables (i.e. can be set by user and programmatically)
- blacklisted_vars = {"current_view", "bv", "current_function", "current_basic_block", "current_selection", "current_llil", "current_mlil", "current_hlil"}
- self.locals = BlacklistedDict(blacklisted_vars, {"__name__": "__console__", "__doc__": None, "binaryninja": sys.modules[__name__]})
+ blacklisted_vars = {
+ "current_view", "bv", "current_function", "current_basic_block", "current_selection", "current_llil",
+ "current_mlil", "current_hlil"
+ }
+ self.locals = BlacklistedDict(
+ blacklisted_vars, {"__name__": "__console__", "__doc__": None, "binaryninja": sys.modules[__name__]}
+ )
self.interpreter = code.InteractiveConsole(self.locals)
self.event = threading.Event()
self.daemon = True
@@ -608,14 +617,16 @@ class PythonScriptingInstance(ScriptingInstance):
self.code = None
self.input = ""
- self.completer = bncompleter.Completer(namespace = self.locals)
+ self.completer = bncompleter.Completer(namespace=self.locals)
startup_file = os.path.join(binaryninja.user_directory(), "startup.py")
if not os.path.isfile(startup_file):
with open(startup_file, 'w') as f:
- f.write("""# Commands in this file will be run in the interactive python console on startup
+ f.write(
+ """# Commands in this file will be run in the interactive python console on startup
from binaryninja import *
-""")
+"""
+ )
with open(startup_file, 'r') as f:
self.interpreter.runsource(f.read(), filename="startup.py", symbol="exec")
@@ -676,17 +687,28 @@ from binaryninja import *
tryNavigate = True
if isinstance(self.locals["here"], str) or isinstance(self.locals["current_address"], str):
try:
- self.locals["here"] = self.active_view.parse_expression(self.locals["here"], self.active_addr)
+ self.locals["here"] = self.active_view.parse_expression(
+ self.locals["here"], self.active_addr
+ )
except ValueError as e:
sys.stderr.write(str(e))
tryNavigate = False
if tryNavigate:
if self.locals["here"] != self.active_addr:
- if not self.active_view.file.navigate(self.active_view.file.view, self.locals["here"]):
- sys.stderr.write("Address 0x%x is not valid for the current view\n" % self.locals["here"])
+ if not self.active_view.file.navigate(
+ self.active_view.file.view, self.locals["here"]
+ ):
+ sys.stderr.write(
+ "Address 0x%x is not valid for the current view\n" % self.locals["here"]
+ )
elif self.locals["current_address"] != self.active_addr:
- if not self.active_view.file.navigate(self.active_view.file.view, self.locals["current_address"]):
- sys.stderr.write("Address 0x%x is not valid for the current view\n" % self.locals["current_address"])
+ if not self.active_view.file.navigate(
+ self.active_view.file.view, self.locals["current_address"]
+ ):
+ sys.stderr.write(
+ "Address 0x%x is not valid for the current view\n"
+ % self.locals["current_address"]
+ )
if self.active_view is not None:
self.active_view.update_analysis()
except:
@@ -722,7 +744,6 @@ from binaryninja import *
self.locals["current_hlil"] = self.active_func.hlil
self.locals.blacklist_enabled = True
-
def get_selected_data(self):
if self.active_view is None:
return None
@@ -782,7 +803,9 @@ from binaryninja import *
def perform_cancel_script_input(self):
for tid, tobj in threading._active.items(): # type: ignore
if tobj is self.interpreter:
- if ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), ctypes.py_object(KeyboardInterrupt)) != 1:
+ if ctypes.pythonapi.PyThreadState_SetAsyncExc(
+ ctypes.c_long(tid), ctypes.py_object(KeyboardInterrupt)
+ ) != 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), None)
break
@@ -818,8 +841,8 @@ from binaryninja import *
class PythonScriptingProvider(ScriptingProvider):
name = "Python"
- apiName = f"python{sys.version_info.major}" # Used for plugin compatibility testing
- instance_class:TypeHintType[PythonScriptingInstance] = PythonScriptingInstance
+ apiName = f"python{sys.version_info.major}" # Used for plugin compatibility testing
+ instance_class: TypeHintType[PythonScriptingInstance] = PythonScriptingInstance
@property
def _python_bin(self) -> Optional[str]:
@@ -828,7 +851,7 @@ class PythonScriptingProvider(ScriptingProvider):
python_bin, status = self._get_executable_for_libpython(python_lib, python_bin_override)
return python_bin
- def _load_module(self, ctx, _repo_path:bytes, _module:bytes, force:bool):
+ def _load_module(self, ctx, _repo_path: bytes, _module: bytes, force: bool):
repo_path = _repo_path.decode("utf-8")
module = _module.decode("utf-8")
try:
@@ -839,8 +862,9 @@ class PythonScriptingProvider(ScriptingProvider):
raise ValueError(f"Plugin API name is not {self.name}")
if not force and core.core_platform not in plugin.install_platforms:
- raise ValueError(f"Current platform {core.core_platform} isn't in list of "\
- f"valid platforms for this plugin {plugin.install_platforms}")
+ raise ValueError(
+ f"Current platform {core.core_platform} isn't in list of valid platforms for this plugin {plugin.install_platforms}"
+ )
if not plugin.installed:
plugin.installed = True
@@ -872,10 +896,10 @@ class PythonScriptingProvider(ScriptingProvider):
except subprocess.SubprocessError as se:
return (False, str(se))
- def _pip_exists(self, python_bin:str) -> bool:
+ def _pip_exists(self, python_bin: str) -> bool:
return self._run_args([python_bin, "-m", "pip", "--version"])[0]
- def _satisfied_dependencies(self, python_bin:str) -> Generator[str, None, None]:
+ def _satisfied_dependencies(self, python_bin: str) -> Generator[str, None, None]:
if python_bin is None:
return None
success, result = self._run_args([python_bin, "-m", "pip", "freeze"])
@@ -885,44 +909,56 @@ class PythonScriptingProvider(ScriptingProvider):
yield line.split("==", 2)[0]
def _bin_version(self, python_bin: str):
- return self._run_args([str(python_bin), "-c", "import sys; sys.stdout.write(f'{sys.version_info.major}.{sys.version_info.minor}')"])[1]
+ return self._run_args([
+ str(python_bin), "-c", "import sys; sys.stdout.write(f'{sys.version_info.major}.{sys.version_info.minor}')"
+ ])[1]
def _get_executable_for_libpython(self, python_lib: str, python_bin: str) -> Tuple[Optional[str], str]:
python_lib_version = f"{sys.version_info.major}.{sys.version_info.minor}"
if python_bin is not None and python_bin != "":
python_bin_version = self._bin_version(python_bin)
if python_lib_version != python_bin_version:
- return (None, f"Specified Python Binary Override is the wrong version. Expected: {python_lib_version} got: {python_bin_version}")
+ return (
+ None,
+ f"Specified Python Binary Override is the wrong version. Expected: {python_lib_version} got: {python_bin_version}"
+ )
return (python_bin, "Success")
using_bundled_python = not python_lib
if sys.platform == "darwin":
if using_bundled_python:
- return (None, "Failed: Bundled python doesn't support dependency installation. Specify a full python installation in your 'Python Interpreter' and try again")
+ return (
+ None,
+ "Failed: Bundled python doesn't support dependency installation. Specify a full python installation in your 'Python Interpreter' and try again"
+ )
python_bin = str(Path(python_lib).parent / f"bin/python{python_lib_version}")
elif sys.platform == "linux":
+
class Dl_info(ctypes.Structure):
- _fields_ = [
- ("dli_fname", ctypes.c_char_p),
- ("dli_fbase", ctypes.c_void_p),
- ("dli_sname", ctypes.c_char_p),
- ("dli_saddr", ctypes.c_void_p),
- ]
+ _fields_ = [("dli_fname", ctypes.c_char_p), ("dli_fbase", ctypes.c_void_p),
+ ("dli_sname", ctypes.c_char_p), ("dli_saddr", ctypes.c_void_p), ]
+
def _linked_libpython():
libdl = ctypes.CDLL(find_library("dl"))
libdl.dladdr.argtypes = [ctypes.c_void_p, ctypes.POINTER(Dl_info)]
libdl.dladdr.restype = ctypes.c_int
dlinfo = Dl_info()
- retcode = libdl.dladdr(ctypes.cast(ctypes.pythonapi.Py_GetVersion, ctypes.c_void_p), ctypes.pointer(dlinfo))
+ retcode = libdl.dladdr(
+ ctypes.cast(ctypes.pythonapi.Py_GetVersion, ctypes.c_void_p), ctypes.pointer(dlinfo)
+ )
if retcode == 0: # means error
return None
return os.path.realpath(dlinfo.dli_fname.decode())
+
if using_bundled_python:
python_lib = _linked_libpython()
if python_lib is None:
- return (None, "Failed: No python specified. Specify a full python installation in your 'Python Interpreter' and try again")
+ return (
+ None,
+ "Failed: No python specified. Specify a full python installation in your 'Python Interpreter' and try again"
+ )
if python_lib == os.path.realpath(sys.executable):
python_bin = python_lib
@@ -939,7 +975,7 @@ class PythonScriptingProvider(ScriptingProvider):
if using_bundled_python:
python_bin = Path(binaryninja.get_install_directory()) / "plugins\\python\\python.exe"
else:
- python_bin = Path(python_lib).parent / "python.exe"
+ python_bin = Path(python_lib).parent / "python.exe"
python_bin_version = self._bin_version(python_bin)
if python_bin_version != python_lib_version:
return (None, f"Failed: Python version not equal {python_bin_version} and {python_lib_version}")
@@ -956,26 +992,35 @@ class PythonScriptingProvider(ScriptingProvider):
python_bin_override = settings.Settings().get_string("python.binaryOverride")
python_bin, status = self._get_executable_for_libpython(python_lib, python_bin_override)
if python_bin is not None and not self._pip_exists(str(python_bin)):
- log_error(f"Pip not installed for configured python: {python_bin}.\n"
- "Please install pip or switch python versions.")
+ log_error(
+ f"Pip not installed for configured python: {python_bin}.\n"
+ "Please install pip or switch python versions."
+ )
return False
if sys.platform == "darwin" and not any([python_bin, python_lib, python_bin_override]):
- log_error(f"Plugin requirement installation unsupported on MacOS with bundled Python: {status}\n"
- "Please specify a path to a python library in the 'Python Interpreter' setting")
+ log_error(
+ f"Plugin requirement installation unsupported on MacOS with bundled Python: {status}\n"
+ "Please specify a path to a python library in the 'Python Interpreter' setting"
+ )
return False
elif python_bin is None:
- log_error(f"Unable to discover python executable required for installing python modules: {status}\n"
- "Please specify a path to a python binary in the 'Python Path Override'")
+ log_error(
+ f"Unable to discover python executable required for installing python modules: {status}\n"
+ "Please specify a path to a python binary in the 'Python Path Override'"
+ )
return False
- python_bin_version = subprocess.check_output([python_bin, "-c",
- "import sys; sys.stdout.write(f'{sys.version_info.major}.{sys.version_info.minor}')"]).decode("utf-8")
+ python_bin_version = subprocess.check_output([
+ python_bin, "-c", "import sys; sys.stdout.write(f'{sys.version_info.major}.{sys.version_info.minor}')"
+ ]).decode("utf-8")
python_lib_version = f"{sys.version_info.major}.{sys.version_info.minor}"
if (python_bin_version != python_lib_version):
- log_error(f"Python Binary Setting {python_bin_version} incompatible with python library {python_lib_version}")
+ log_error(
+ f"Python Binary Setting {python_bin_version} incompatible with python library {python_lib_version}"
+ )
return False
- args:List[str] = [str(python_bin), "-m", "pip", "--isolated", "--disable-pip-version-check"]
+ args: List[str] = [str(python_bin), "-m", "pip", "--isolated", "--disable-pip-version-check"]
proxy_settings = settings.Settings().get_string("network.httpsProxy")
if proxy_settings:
args.extend(["--proxy", proxy_settings])
@@ -989,7 +1034,9 @@ class PythonScriptingProvider(ScriptingProvider):
user_dir = binaryninja.user_directory()
if user_dir is None:
raise Exception("Unable to find user directory.")
- site_package_dir = Path(user_dir) / f"python{sys.version_info.major}{sys.version_info.minor}" / "site-packages"
+ site_package_dir = Path(
+ user_dir
+ ) / f"python{sys.version_info.major}{sys.version_info.minor}" / "site-packages"
site_package_dir.mkdir(parents=True, exist_ok=True)
args.extend(["--target", str(site_package_dir)])
args.extend(list(filter(len, modules.split("\n"))))
@@ -999,7 +1046,7 @@ class PythonScriptingProvider(ScriptingProvider):
log_error(f"Error while attempting to install requirements {result}")
return status
- def _module_installed(self, ctx, module:str) -> bool:
+ def _module_installed(self, ctx, module: str) -> bool:
if self._python_bin is None:
return False
return re.split('>|=|,', module.strip(), 1)[0] in self._satisfied_dependencies(self._python_bin)
@@ -1011,6 +1058,7 @@ original_stdin = sys.stdin
original_stdout = sys.stdout
original_stderr = sys.stderr
+
def redirect_stdio():
sys.stdin = _PythonScriptingInstanceInput(sys.stdin)
sys.stdout = _PythonScriptingInstanceOutput(sys.stdout, False)
diff --git a/python/settings.py b/python/settings.py
index 7e057780..172c7392 100644
--- a/python/settings.py
+++ b/python/settings.py
@@ -120,7 +120,7 @@ class Settings:
"""
default_handle = core.BNCreateSettings("default")
- def __init__(self, instance_id:str="default", handle=None):
+ def __init__(self, instance_id: str = "default", handle=None):
if handle is None:
if instance_id is None or instance_id == "":
instance_id = "default"
@@ -158,7 +158,7 @@ class Settings:
"""Returns the ``instance_id`` for this :class:`Settings` repository (read-only)"""
return self._instance_id
- def set_resource_id(self, resource_id = None):
+ def set_resource_id(self, resource_id=None):
"""
``set_resource_id`` Sets the resource identifier for this class:`Settings` instance. When accessing setting values at the \
``SettingsResourceScope`` level, the resource identifier is passed along through the backing store interface.
@@ -256,53 +256,53 @@ class Settings:
def update_property(self, key, setting_property):
return core.BNSettingsUpdateProperty(self.handle, key, setting_property)
- def deserialize_schema(self, schema, scope = SettingsScope.SettingsAutoScope, merge = True):
+ def deserialize_schema(self, schema, scope=SettingsScope.SettingsAutoScope, merge=True):
return core.BNSettingsDeserializeSchema(self.handle, schema, scope, merge)
def serialize_schema(self):
return core.BNSettingsSerializeSchema(self.handle)
- def deserialize_settings(self, contents, view = None, scope = SettingsScope.SettingsAutoScope):
+ def deserialize_settings(self, contents, view=None, scope=SettingsScope.SettingsAutoScope):
if view is not None:
view = view.handle
return core.BNDeserializeSettings(self.handle, contents, view, scope)
- def serialize_settings(self, view = None, scope = SettingsScope.SettingsAutoScope):
+ def serialize_settings(self, view=None, scope=SettingsScope.SettingsAutoScope):
if view is not None:
view = view.handle
return core.BNSerializeSettings(self.handle, view, scope)
- def reset(self, key, view = None, scope = SettingsScope.SettingsAutoScope):
+ def reset(self, key, view=None, scope=SettingsScope.SettingsAutoScope):
if view is not None:
view = view.handle
return core.BNSettingsReset(self.handle, key, view, scope)
- def reset_all(self, view = None, scope = SettingsScope.SettingsAutoScope, schema_only = True):
+ def reset_all(self, view=None, scope=SettingsScope.SettingsAutoScope, schema_only=True):
if view is not None:
view = view.handle
return core.BNSettingsResetAll(self.handle, view, scope, schema_only)
- def get_bool(self, key, view = None):
+ def get_bool(self, key, view=None):
if view is not None:
view = view.handle
return core.BNSettingsGetBool(self.handle, key, view, None)
- def get_double(self, key, view = None):
+ def get_double(self, key, view=None):
if view is not None:
view = view.handle
return core.BNSettingsGetDouble(self.handle, key, view, None)
- def get_integer(self, key, view = None):
+ def get_integer(self, key, view=None):
if view is not None:
view = view.handle
return core.BNSettingsGetUInt64(self.handle, key, view, None)
- def get_string(self, key, view = None):
+ def get_string(self, key, view=None):
if view is not None:
view = view.handle
return core.BNSettingsGetString(self.handle, key, view, None)
- def get_string_list(self, key, view = None):
+ def get_string_list(self, key, view=None):
if view is not None:
view = view.handle
length = ctypes.c_ulonglong()
@@ -314,40 +314,40 @@ class Settings:
core.BNFreeStringList(result, length)
return out_list
- def get_json(self, key, view = None):
+ def get_json(self, key, view=None):
if view is not None:
view = view.handle
return core.BNSettingsGetJson(self.handle, key, view, None)
- def get_bool_with_scope(self, key, view = None, scope = SettingsScope.SettingsAutoScope):
+ def get_bool_with_scope(self, key, view=None, scope=SettingsScope.SettingsAutoScope):
if view is not None:
view = view.handle
c_scope = core.SettingsScopeEnum(scope)
result = core.BNSettingsGetBool(self.handle, key, view, ctypes.byref(c_scope))
return (result, SettingsScope(c_scope.value))
- def get_double_with_scope(self, key, view = None, scope = SettingsScope.SettingsAutoScope):
+ def get_double_with_scope(self, key, view=None, scope=SettingsScope.SettingsAutoScope):
if view is not None:
view = view.handle
c_scope = core.SettingsScopeEnum(scope)
result = core.BNSettingsGetDouble(self.handle, key, view, ctypes.byref(c_scope))
return (result, SettingsScope(c_scope.value))
- def get_integer_with_scope(self, key, view = None, scope = SettingsScope.SettingsAutoScope):
+ def get_integer_with_scope(self, key, view=None, scope=SettingsScope.SettingsAutoScope):
if view is not None:
view = view.handle
c_scope = core.SettingsScopeEnum(scope)
result = core.BNSettingsGetUInt64(self.handle, key, view, ctypes.byref(c_scope))
return (result, SettingsScope(c_scope.value))
- def get_string_with_scope(self, key, view = None, scope = SettingsScope.SettingsAutoScope):
+ def get_string_with_scope(self, key, view=None, scope=SettingsScope.SettingsAutoScope):
if view is not None:
view = view.handle
c_scope = core.SettingsScopeEnum(scope)
result = core.BNSettingsGetString(self.handle, key, view, ctypes.byref(c_scope))
return (result, SettingsScope(c_scope.value))
- def get_string_list_with_scope(self, key, view = None, scope = SettingsScope.SettingsAutoScope):
+ def get_string_list_with_scope(self, key, view=None, scope=SettingsScope.SettingsAutoScope):
if view is not None:
view = view.handle
c_scope = core.SettingsScopeEnum(scope)
@@ -360,34 +360,34 @@ class Settings:
core.BNFreeStringList(result, length)
return (out_list, SettingsScope(c_scope.value))
- def get_json_with_scope(self, key, view = None, scope = SettingsScope.SettingsAutoScope):
+ def get_json_with_scope(self, key, view=None, scope=SettingsScope.SettingsAutoScope):
if view is not None:
view = view.handle
c_scope = core.SettingsScopeEnum(scope)
result = core.BNSettingsGetJson(self.handle, key, view, ctypes.byref(c_scope))
return (result, SettingsScope(c_scope.value))
- def set_bool(self, key, value, view = None, scope = SettingsScope.SettingsAutoScope):
+ def set_bool(self, key, value, view=None, scope=SettingsScope.SettingsAutoScope):
if view is not None:
view = view.handle
return core.BNSettingsSetBool(self.handle, view, scope, key, value)
- def set_double(self, key, value, view = None, scope = SettingsScope.SettingsAutoScope):
+ def set_double(self, key, value, view=None, scope=SettingsScope.SettingsAutoScope):
if view is not None:
view = view.handle
return core.BNSettingsSetDouble(self.handle, view, scope, key, value)
- def set_integer(self, key, value, view = None, scope = SettingsScope.SettingsAutoScope):
+ def set_integer(self, key, value, view=None, scope=SettingsScope.SettingsAutoScope):
if view is not None:
view = view.handle
return core.BNSettingsSetUInt64(self.handle, view, scope, key, value)
- def set_string(self, key, value, view = None, scope = SettingsScope.SettingsAutoScope):
+ def set_string(self, key, value, view=None, scope=SettingsScope.SettingsAutoScope):
if view is not None:
view = view.handle
return core.BNSettingsSetString(self.handle, view, scope, key, value)
- def set_string_list(self, key, value, view = None, scope = SettingsScope.SettingsAutoScope):
+ def set_string_list(self, key, value, view=None, scope=SettingsScope.SettingsAutoScope):
if view is not None:
view = view.handle
length = ctypes.c_ulonglong()
@@ -397,7 +397,7 @@ class Settings:
string_list[i] = value[i].encode('charmap')
return core.BNSettingsSetStringList(self.handle, view, scope, key, string_list, length)
- def set_json(self, key, value, view = None, scope = SettingsScope.SettingsAutoScope):
+ def set_json(self, key, value, view=None, scope=SettingsScope.SettingsAutoScope):
if view is not None:
view = view.handle
return core.BNSettingsSetJson(self.handle, view, scope, key, value)
diff --git a/python/transform.py b/python/transform.py
index 03f9c93e..7b75099a 100644
--- a/python/transform.py
+++ b/python/transform.py
@@ -51,7 +51,7 @@ class _TransformMetaClass(type):
class TransformParameter:
- def __init__(self, name, long_name = None, fixed_length = 0):
+ def __init__(self, name, long_name=None, fixed_length=0):
self._name = name
if long_name is None:
self._long_name = name
@@ -60,9 +60,7 @@ class TransformParameter:
self._fixed_length = fixed_length
def __repr__(self):
- return "<TransformParameter: {} fixed length: {}>".format(
- self._long_name, self._fixed_length
- )
+ return "<TransformParameter: {} fixed length: {}>".format(self._long_name, self._fixed_length)
@property
def name(self):
@@ -196,10 +194,10 @@ class Transform(metaclass=_TransformMetaClass):
def _decode(self, ctxt, input_buf, output_buf, params, count):
try:
- input_obj = databuffer.DataBuffer(handle = core.BNDuplicateDataBuffer(input_buf))
+ input_obj = databuffer.DataBuffer(handle=core.BNDuplicateDataBuffer(input_buf))
param_map = {}
for i in range(0, count):
- data = databuffer.DataBuffer(handle = core.BNDuplicateDataBuffer(params[i].value))
+ data = databuffer.DataBuffer(handle=core.BNDuplicateDataBuffer(params[i].value))
param_map[params[i].name] = bytes(data)
result = self.perform_decode(bytes(input_obj), param_map)
if result is None:
@@ -213,10 +211,10 @@ class Transform(metaclass=_TransformMetaClass):
def _encode(self, ctxt, input_buf, output_buf, params, count):
try:
- input_obj = databuffer.DataBuffer(handle = core.BNDuplicateDataBuffer(input_buf))
+ input_obj = databuffer.DataBuffer(handle=core.BNDuplicateDataBuffer(input_buf))
param_map = {}
for i in range(0, count):
- data = databuffer.DataBuffer(handle = core.BNDuplicateDataBuffer(params[i].value))
+ data = databuffer.DataBuffer(handle=core.BNDuplicateDataBuffer(params[i].value))
param_map[params[i].name] = bytes(data)
result = self.perform_encode(bytes(input_obj), param_map)
if result is None:
@@ -238,7 +236,7 @@ class Transform(metaclass=_TransformMetaClass):
def perform_encode(self, data, params):
return None
- def decode(self, input_buf, params = {}):
+ def decode(self, input_buf, params={}):
if isinstance(input_buf, int) or isinstance(input_buf, int):
return None
input_buf = databuffer.DataBuffer(input_buf)
@@ -254,7 +252,7 @@ class Transform(metaclass=_TransformMetaClass):
return None
return bytes(output_buf)
- def encode(self, input_buf, params = {}):
+ def encode(self, input_buf, params={}):
if isinstance(input_buf, int) or isinstance(input_buf, int):
return None
input_buf = databuffer.DataBuffer(input_buf)
diff --git a/python/typelibrary.py b/python/typelibrary.py
index 2fa68452..84ce3a8d 100644
--- a/python/typelibrary.py
+++ b/python/typelibrary.py
@@ -264,7 +264,7 @@ class TypeLibrary:
"""
core.BNTypeLibraryRemoveMetadata(self.handle, key)
- def add_named_object(self, name:'types.QualifiedName', type:'types.Type') -> None:
+ def add_named_object(self, name: 'types.QualifiedName', type: 'types.Type') -> None:
"""
`add_named_object` directly inserts a named object into the type library's object store.
This is not done recursively, so care should be taken that types referring to other types
@@ -285,7 +285,7 @@ class TypeLibrary:
raise ValueError("type must be a Type")
core.BNAddTypeLibraryNamedObject(self.handle, name._to_core_struct(), type.handle)
- def add_named_type(self, name:'types.QualifiedName', type:'types.Type') -> None:
+ def add_named_type(self, name: 'types.QualifiedName', type: 'types.Type') -> None:
"""
`add_named_type` directly inserts a named object into the type library's object store.
This is not done recursively, so care should be taken that types referring to other types
@@ -367,4 +367,3 @@ class TypeLibrary:
result[name] = types.Type.create(core.BNNewTypeReference(named_types[i].type))
core.BNFreeQualifiedNameAndTypeArray(named_types, count.value)
return result
-
diff --git a/python/types.py b/python/types.py
index 944f03d0..e4392434 100644
--- a/python/types.py
+++ b/python/types.py
@@ -26,8 +26,10 @@ from abc import abstractmethod
# Binary Ninja components
from . import _binaryninjacore as core
-from .enums import (StructureVariant, SymbolType, SymbolBinding, TypeClass,
- NamedTypeReferenceClass, ReferenceType, VariableSourceType, TypeReferenceType, MemberAccess, MemberScope)
+from .enums import (
+ StructureVariant, SymbolType, SymbolBinding, TypeClass, NamedTypeReferenceClass, ReferenceType, VariableSourceType,
+ TypeReferenceType, MemberAccess, MemberScope
+)
from . import callingconvention
from . import function as _function
from . import variable
@@ -41,7 +43,7 @@ BoolWithConfidenceType = Union[bool, 'BoolWithConfidence']
OffsetWithConfidenceType = Union[int, 'OffsetWithConfidence']
ParamsType = Union[List['Type'], List['FunctionParameter'], List[Tuple['Type', str]]]
MembersType = Union[List['StructureMember'], List['Type'], List[Tuple['Type', str]]]
-EnumMembersType = Union[List[Tuple[str,int]], List[str], List['EnumerationMember']]
+EnumMembersType = Union[List[Tuple[str, int]], List[str], List['EnumerationMember']]
SomeType = Union['TypeBuilder', 'Type']
TypeContainer = Union['binaryview.BinaryView', 'typelibrary.TypeLibrary']
NameSpaceType = Optional[Union[str, List[str], 'NameSpace']]
@@ -53,9 +55,10 @@ MemberName = str
MemberIndex = int
MemberOffset = int
+
class QualifiedName:
- def __init__(self, name:Optional[QualifiedNameType]=None):
- self._name:List[str] = []
+ def __init__(self, name: Optional[QualifiedNameType] = None):
+ self._name: List[str] = []
if isinstance(name, str):
self._name = [name]
elif isinstance(name, bytes):
@@ -146,15 +149,15 @@ class QualifiedName:
return self._name
@name.setter
- def name(self, value:List[str]) -> None:
+ def name(self, value: List[str]) -> None:
self._name = value
@dataclass(frozen=True)
class TypeReferenceSource:
- name:QualifiedName
- offset:int
- ref_type:TypeReferenceType
+ name: QualifiedName
+ offset: int
+ ref_type: TypeReferenceType
def __repr__(self):
if self.ref_type == TypeReferenceType.DirectTypeReferenceType:
@@ -180,14 +183,14 @@ class NameSpace(QualifiedName):
return result
@staticmethod
- def _from_core_struct(name:core.BNNameSpace) -> 'NameSpace':
+ def _from_core_struct(name: core.BNNameSpace) -> 'NameSpace':
result = []
for i in range(0, name.nameCount):
result.append(name.name[i].decode("utf-8"))
return NameSpace(result)
@staticmethod
- def get_core_struct(name:Optional[Union[str, List[str], 'NameSpace']]) -> Optional[core.BNNameSpace]:
+ def get_core_struct(name: Optional[Union[str, List[str], 'NameSpace']]) -> Optional[core.BNNameSpace]:
if name is None:
return None
if isinstance(name, NameSpace):
@@ -197,7 +200,7 @@ class NameSpace(QualifiedName):
class CoreSymbol:
- def __init__(self, handle:core.BNSymbolHandle):
+ def __init__(self, handle: core.BNSymbolHandle):
self._handle = handle
def __del__(self):
@@ -307,7 +310,9 @@ class Symbol(CoreSymbol):
LibraryFunctionSymbol Symbols for external functions outside the library
=========================== ==============================================================
"""
- def __init__(self, sym_type, addr, short_name, full_name=None, raw_name=None, binding=None, namespace=None, ordinal=0):
+ def __init__(
+ self, sym_type, addr, short_name, full_name=None, raw_name=None, binding=None, namespace=None, ordinal=0
+ ):
if isinstance(sym_type, str):
sym_type = SymbolType[sym_type]
if full_name is None:
@@ -324,9 +329,9 @@ class Symbol(CoreSymbol):
@dataclass
class FunctionParameter:
- type:SomeType
- name:str = ""
- location:Optional['variable.VariableNameAndType'] = None
+ type: SomeType
+ name: str = ""
+ location: Optional['variable.VariableNameAndType'] = None
def __repr__(self):
if (self.location is not None) and (self.location.name != self.name):
@@ -342,8 +347,8 @@ class FunctionParameter:
@dataclass(frozen=True)
class OffsetWithConfidence:
- value:int
- confidence:int=core.max_confidence
+ value: int
+ confidence: int = core.max_confidence
def __int__(self):
return self.value
@@ -376,11 +381,11 @@ class OffsetWithConfidence:
return result
@classmethod
- def from_core_struct(cls, core_struct:core.BNOffsetWithConfidence) -> 'OffsetWithConfidence':
+ def from_core_struct(cls, core_struct: core.BNOffsetWithConfidence) -> 'OffsetWithConfidence':
return cls(core_struct.value, core_struct.confidence)
@staticmethod
- def get_core_struct(value:OffsetWithConfidenceType) -> core.BNOffsetWithConfidence:
+ def get_core_struct(value: OffsetWithConfidenceType) -> core.BNOffsetWithConfidence:
if isinstance(value, OffsetWithConfidence):
return value._to_core_struct()
else:
@@ -389,8 +394,8 @@ class OffsetWithConfidence:
@dataclass(frozen=True)
class BoolWithConfidence:
- value:bool
- confidence:int=core.max_confidence
+ value: bool
+ confidence: int = core.max_confidence
def __eq__(self, other):
if not isinstance(other, self.__class__):
@@ -411,11 +416,11 @@ class BoolWithConfidence:
return result
@classmethod
- def from_core_struct(cls, core_struct:core.BNBoolWithConfidence) -> 'BoolWithConfidence':
+ def from_core_struct(cls, core_struct: core.BNBoolWithConfidence) -> 'BoolWithConfidence':
return cls(core_struct.value, core_struct.confidence)
@staticmethod
- def get_core_struct(value:BoolWithConfidenceType) -> core.BNBoolWithConfidence:
+ def get_core_struct(value: BoolWithConfidenceType) -> core.BNBoolWithConfidence:
if isinstance(value, BoolWithConfidence):
return value._to_core_struct()
else:
@@ -424,12 +429,12 @@ class BoolWithConfidence:
@dataclass
class MutableTypeBuilder:
- type:'TypeBuilder'
- container:TypeContainer
- name:QualifiedName
- platform:Optional['_platform.Platform']
- confidence:int
- user:bool = True
+ type: 'TypeBuilder'
+ container: TypeContainer
+ name: QualifiedName
+ platform: Optional['_platform.Platform']
+ confidence: int
+ user: bool = True
def __enter__(self):
return self.type
@@ -446,7 +451,10 @@ class MutableTypeBuilder:
class TypeBuilder:
- def __init__(self, handle:core.BNTypeBuilderHandle, platform:'_platform.Platform'=None, confidence:int=core.max_confidence):
+ def __init__(
+ self, handle: core.BNTypeBuilderHandle, platform: '_platform.Platform' = None,
+ confidence: int = core.max_confidence
+ ):
assert isinstance(handle, core.BNTypeBuilderHandle), "handle isn't an instance of BNTypeBuilderHandle"
self._handle = handle
self.platform = platform
@@ -456,12 +464,12 @@ class TypeBuilder:
if core is not None:
core.BNFreeTypeBuilder(self._handle)
- def __eq__(self, other:'TypeBuilder') -> bool:
+ def __eq__(self, other: 'TypeBuilder') -> bool:
if not isinstance(other, TypeBuilder):
raise ValueError(f"Unable compare equality of TypeBuilder and {type(other)}")
return self.immutable_copy() == other.immutable_copy()
- def __ne__(self, other:'TypeBuilder') -> bool:
+ def __ne__(self, other: 'TypeBuilder') -> bool:
return not self.__eq__(other)
def __repr__(self):
@@ -482,17 +490,13 @@ class TypeBuilder:
def immutable_copy(self):
Types = {
- TypeClass.VoidTypeClass:VoidType,
- TypeClass.BoolTypeClass:BoolType,
- TypeClass.IntegerTypeClass:IntegerType,
- TypeClass.FloatTypeClass:FloatType,
- TypeClass.PointerTypeClass:PointerType,
- TypeClass.ArrayTypeClass:ArrayType,
- TypeClass.FunctionTypeClass:FunctionType,
- TypeClass.WideCharTypeClass:WideCharType,
- # TypeClass.StructureTypeClass:StructureType,
- # TypeClass.EnumerationTypeClass:EnumerationType,
- # TypeClass.NamedTypeReferenceClass:NamedTypeReferenceType,
+ TypeClass.VoidTypeClass: VoidType, TypeClass.BoolTypeClass: BoolType,
+ TypeClass.IntegerTypeClass: IntegerType, TypeClass.FloatTypeClass: FloatType,
+ TypeClass.PointerTypeClass: PointerType, TypeClass.ArrayTypeClass: ArrayType,
+ TypeClass.FunctionTypeClass: FunctionType, TypeClass.WideCharTypeClass: WideCharType,
+ # TypeClass.StructureTypeClass:StructureType,
+ # TypeClass.EnumerationTypeClass:EnumerationType,
+ # TypeClass.NamedTypeReferenceClass:NamedTypeReferenceType,
}
return Types[self.type_class](self.finalized, self.platform, self.confidence)
@@ -505,8 +509,10 @@ class TypeBuilder:
return NotImplemented
@classmethod
- def builder(cls, container:TypeContainer, name:'QualifiedName', user:bool=True,
- platform:'_platform.Platform'=None, confidence:int=core.max_confidence) -> 'MutableTypeBuilder':
+ def builder(
+ cls, container: TypeContainer, name: 'QualifiedName', user: bool = True, platform: '_platform.Platform' = None,
+ confidence: int = core.max_confidence
+ ) -> 'MutableTypeBuilder':
return MutableTypeBuilder(cls.create(), container, name, platform, confidence, user)
@staticmethod
@@ -518,11 +524,13 @@ class TypeBuilder:
return BoolBuilder.create()
@staticmethod
- def char(alternate_name:str="") -> 'CharBuilder':
+ def char(alternate_name: str = "") -> 'CharBuilder':
return CharBuilder.create(alternate_name)
@staticmethod
- def int(width:_int, sign:BoolWithConfidenceType=BoolWithConfidence(True), altname:str="") -> 'IntegerBuilder':
+ def int(
+ width: _int, sign: BoolWithConfidenceType = BoolWithConfidence(True), altname: str = ""
+ ) -> 'IntegerBuilder':
"""
``int`` class method for creating an int Type.
:param int width: width of the integer in bytes
@@ -532,7 +540,7 @@ class TypeBuilder:
return IntegerBuilder.create(width, sign, altname)
@staticmethod
- def float(width:_int, altname:str="") -> 'FloatBuilder':
+ def float(width: _int, altname: str = "") -> 'FloatBuilder':
"""
``float`` class method for creating floating point Types.
:param int width: width of the floating point number in bytes
@@ -541,7 +549,7 @@ class TypeBuilder:
return FloatBuilder.create(width, altname)
@staticmethod
- def wide_char(width:_int, altname:str="") -> 'WideCharBuilder':
+ def wide_char(width: _int, altname: str = "") -> 'WideCharBuilder':
"""
``wide_char`` class method for creating wide char Types.
:param int width: width of the wide character in bytes
@@ -550,39 +558,50 @@ class TypeBuilder:
return WideCharBuilder.create(width, altname)
@staticmethod
- def named_type_from_type(name:QualifiedName, type_class:Optional[NamedTypeReferenceClass]=None) -> 'NamedTypeReferenceBuilder':
+ def named_type_from_type(
+ name: QualifiedName, type_class: Optional[NamedTypeReferenceClass] = None
+ ) -> 'NamedTypeReferenceBuilder':
return NamedTypeReferenceBuilder.named_type_from_type(name, type_class)
@staticmethod
- def named_type_from_type_and_id(type_id:str, name:QualifiedName, type:Optional['Type']=None) -> 'NamedTypeReferenceBuilder':
+ def named_type_from_type_and_id(
+ type_id: str, name: QualifiedName, type: Optional['Type'] = None
+ ) -> 'NamedTypeReferenceBuilder':
return NamedTypeReferenceBuilder.named_type_from_type_and_id(type_id, name, type)
@staticmethod
- def named_type_from_registered_type(view:'binaryview.BinaryView', name:QualifiedName) -> 'NamedTypeReferenceBuilder':
+ def named_type_from_registered_type(
+ view: 'binaryview.BinaryView', name: QualifiedName
+ ) -> 'NamedTypeReferenceBuilder':
return NamedTypeReferenceBuilder.named_type_from_registered_type(view, name)
@staticmethod
- def pointer(arch:'architecture.Architecture', type:'Type',
- const:BoolWithConfidenceType=BoolWithConfidence(False),
- volatile:BoolWithConfidenceType=BoolWithConfidence(False),
- ref_type:ReferenceType=ReferenceType.PointerReferenceType) -> 'PointerBuilder':
+ def pointer(
+ arch: 'architecture.Architecture', type: 'Type', const: BoolWithConfidenceType = BoolWithConfidence(False),
+ volatile: BoolWithConfidenceType = BoolWithConfidence(False),
+ ref_type: ReferenceType = ReferenceType.PointerReferenceType
+ ) -> 'PointerBuilder':
return PointerBuilder.create(type, arch.address_size, arch, const, volatile, ref_type)
@staticmethod
- def pointer_of_width(width:_int, type:'Type',
- const:BoolWithConfidenceType=BoolWithConfidence(False),
- volatile:BoolWithConfidenceType=BoolWithConfidence(False),
- ref_type:ReferenceType=ReferenceType.PointerReferenceType) -> 'PointerBuilder':
+ def pointer_of_width(
+ width: _int, type: 'Type', const: BoolWithConfidenceType = BoolWithConfidence(False),
+ volatile: BoolWithConfidenceType = BoolWithConfidence(False),
+ ref_type: ReferenceType = ReferenceType.PointerReferenceType
+ ) -> 'PointerBuilder':
return PointerBuilder.create(type, width, None, const, volatile, ref_type)
@staticmethod
- def array(type:'Type', count:_int) -> 'ArrayBuilder':
+ def array(type: 'Type', count: _int) -> 'ArrayBuilder':
return ArrayBuilder.create(type, count)
@staticmethod
- def function(ret:Optional['Type']=None, params:Optional[ParamsType]=None, calling_convention:'callingconvention.CallingConvention'=None,
- variable_arguments:BoolWithConfidenceType=BoolWithConfidence(False),
- stack_adjust:OffsetWithConfidenceType=0) -> 'FunctionBuilder':
+ def function(
+ ret: Optional['Type'] = None, params: Optional[ParamsType] = None,
+ calling_convention: 'callingconvention.CallingConvention' = None,
+ variable_arguments: BoolWithConfidenceType = BoolWithConfidence(False),
+ stack_adjust: OffsetWithConfidenceType = 0
+ ) -> 'FunctionBuilder':
"""
``function`` class method for creating an function Type.
:param Type ret: return Type of the function
@@ -594,29 +613,36 @@ class TypeBuilder:
return FunctionBuilder.create(ret, calling_convention, params, variable_arguments, stack_adjust)
@staticmethod
- def structure(members:Optional[MembersType]=None, packed:_bool=False, type:StructureVariant=StructureVariant.StructStructureType) -> 'StructureBuilder':
+ def structure(
+ members: Optional[MembersType] = None, packed: _bool = False,
+ type: StructureVariant = StructureVariant.StructStructureType
+ ) -> 'StructureBuilder':
return StructureBuilder.create(members, type=type, packed=packed)
-
+
@staticmethod
- def union(members:Optional[MembersType]=None, packed:_bool=False) -> 'StructureBuilder':
+ def union(members: Optional[MembersType] = None, packed: _bool = False) -> 'StructureBuilder':
return StructureBuilder.create(members, type=StructureVariant.UnionStructureType, packed=packed)
-
+
@staticmethod
- def class_type(members:Optional[MembersType]=None, packed:_bool=False) -> 'StructureBuilder':
+ def class_type(members: Optional[MembersType] = None, packed: _bool = False) -> 'StructureBuilder':
return StructureBuilder.create(members, type=StructureVariant.ClassStructureType, packed=packed)
@staticmethod
- def enumeration(arch:Optional['architecture.Architecture']=None, members:Optional[List[EnumMembersType]]=None,
- width:Optional[_int]=None, sign:BoolWithConfidenceType=BoolWithConfidence(False)) -> 'EnumerationBuilder':
+ def enumeration(
+ arch: Optional['architecture.Architecture'] = None, members: Optional[List[EnumMembersType]] = None,
+ width: Optional[_int] = None, sign: BoolWithConfidenceType = BoolWithConfidence(False)
+ ) -> 'EnumerationBuilder':
return EnumerationBuilder.create(members, width, arch, sign)
@staticmethod
- def named_type_reference(type_class:NamedTypeReferenceClass, name:QualifiedName,
- type_id:Optional[str]=None, alignment:_int=1, width:_int=0,
- const:BoolWithConfidenceType=BoolWithConfidence(False),
- volatile:BoolWithConfidenceType=BoolWithConfidence(False)) -> 'NamedTypeReferenceBuilder':
- return NamedTypeReferenceBuilder.create(type_class, type_id, name, width, alignment,
- None, core.max_confidence, const, volatile)
+ def named_type_reference(
+ type_class: NamedTypeReferenceClass, name: QualifiedName, type_id: Optional[str] = None, alignment: _int = 1,
+ width: _int = 0, const: BoolWithConfidenceType = BoolWithConfidence(False),
+ volatile: BoolWithConfidenceType = BoolWithConfidence(False)
+ ) -> 'NamedTypeReferenceBuilder':
+ return NamedTypeReferenceBuilder.create(
+ type_class, type_id, name, width, alignment, None, core.max_confidence, const, volatile
+ )
@property
def width(self) -> _int:
@@ -637,20 +663,24 @@ class TypeBuilder:
def const(self) -> BoolWithConfidence:
"""Whether type is const (read/write)"""
result = core.BNIsTypeBuilderConst(self._handle)
- return BoolWithConfidence(result.value, confidence = result.confidence)
+ return BoolWithConfidence(result.value, confidence=result.confidence)
@const.setter
- def const(self, value:BoolWithConfidenceType) -> None: # type: ignore # We explicitly allow 'set' type to be different than 'get' type
+ def const(
+ self, value: BoolWithConfidenceType
+ ) -> None: # type: ignore # We explicitly allow 'set' type to be different than 'get' type
core.BNTypeBuilderSetConst(self._handle, BoolWithConfidence.get_core_struct(value))
@property
def volatile(self) -> BoolWithConfidence:
"""Whether type is volatile (read/write)"""
result = core.BNIsTypeBuilderVolatile(self._handle)
- return BoolWithConfidence(result.value, confidence = result.confidence)
+ return BoolWithConfidence(result.value, confidence=result.confidence)
@volatile.setter
- def volatile(self, value:BoolWithConfidenceType) -> None: # type: ignore # We explicitly allow 'set' type to be different than 'get' type
+ def volatile(
+ self, value: BoolWithConfidenceType
+ ) -> None: # type: ignore # We explicitly allow 'set' type to be different than 'get' type
core.BNTypeBuilderSetVolatile(self._handle, BoolWithConfidence.get_core_struct(value))
@property
@@ -666,7 +696,7 @@ class TypeBuilder:
return Type.create(handle, self.platform, type_conf.confidence)
@child.setter
- def child(self, value:SomeType) -> None: # type: ignore
+ def child(self, value: SomeType) -> None: # type: ignore
core.BNTypeBuilderSetChildType(self._handle, value.immutable_copy()._to_core_struct())
@property
@@ -674,7 +704,7 @@ class TypeBuilder:
return core.BNGetTypeBuilderAlternateName(self._handle)
@alternate_name.setter
- def alternate_name(self, name:str) -> None:
+ def alternate_name(self, name: str) -> None:
core.BNTypeBuilderSetAlternateName(self._handle, name)
@property
@@ -685,7 +715,7 @@ class TypeBuilder:
return core.BNTypeBuilderGetSystemCallNumber(self._handle)
@system_call_number.setter
- def system_call_number(self, value:int) -> None:
+ def system_call_number(self, value: int) -> None:
core.BNTypeBuilderSetSystemCallNumber(self._handle, True, value)
def clear_system_call(self) -> None:
@@ -700,13 +730,14 @@ class TypeBuilder:
return BoolWithConfidence.from_core_struct(core.BNIsTypeBuilderSigned(self._handle))
@signed.setter
- def signed(self, value:BoolWithConfidenceType) -> None: # type: ignore
+ def signed(self, value: BoolWithConfidenceType) -> None: # type: ignore
_value = BoolWithConfidence.get_core_struct(value)
core.BNTypeBuilderSetSigned(self._handle, _value)
+
class VoidBuilder(TypeBuilder):
@classmethod
- def create(cls, platform:'_platform.Platform'=None, confidence:int=core.max_confidence) -> 'VoidBuilder':
+ def create(cls, platform: '_platform.Platform' = None, confidence: int = core.max_confidence) -> 'VoidBuilder':
handle = core.BNCreateVoidTypeBuilder()
assert handle is not None, "core.BNCreateVoidTypeBuilder returned None"
return cls(handle, platform, confidence)
@@ -714,7 +745,7 @@ class VoidBuilder(TypeBuilder):
class BoolBuilder(TypeBuilder):
@classmethod
- def create(cls, platform:'_platform.Platform'=None, confidence:int=core.max_confidence) -> 'BoolBuilder':
+ def create(cls, platform: '_platform.Platform' = None, confidence: int = core.max_confidence) -> 'BoolBuilder':
handle = core.BNCreateBoolTypeBuilder()
assert handle is not None, "core.BNCreateBoolTypeBuilder returned None"
return cls(handle, platform, confidence)
@@ -722,8 +753,10 @@ class BoolBuilder(TypeBuilder):
class IntegerBuilder(TypeBuilder):
@classmethod
- def create(cls, width:int, sign:BoolWithConfidenceType=True, alternate_name:str="",
- platform:'_platform.Platform'=None, confidence:int=core.max_confidence) -> 'IntegerBuilder':
+ def create(
+ cls, width: int, sign: BoolWithConfidenceType = True, alternate_name: str = "",
+ platform: '_platform.Platform' = None, confidence: int = core.max_confidence
+ ) -> 'IntegerBuilder':
_sign = BoolWithConfidence.get_core_struct(sign)
handle = core.BNCreateIntegerTypeBuilder(width, _sign, alternate_name)
assert handle is not None, "core.BNCreateIntegerTypeBuilder returned None"
@@ -732,8 +765,9 @@ class IntegerBuilder(TypeBuilder):
class CharBuilder(IntegerBuilder):
@classmethod
- def create(cls, alternate_name:str="",
- platform:'_platform.Platform'=None, confidence:int=core.max_confidence) -> 'CharBuilder':
+ def create(
+ cls, alternate_name: str = "", platform: '_platform.Platform' = None, confidence: int = core.max_confidence
+ ) -> 'CharBuilder':
handle = core.BNCreateIntegerTypeBuilder(1, BoolWithConfidence.get_core_struct(False), alternate_name)
assert handle is not None, "BNCreateIntegerTypeBuilder returned None"
return cls(handle, platform, confidence)
@@ -741,8 +775,10 @@ class CharBuilder(IntegerBuilder):
class FloatBuilder(TypeBuilder):
@classmethod
- def create(cls, width:int, alternate_name:str="",
- platform:'_platform.Platform'=None, confidence:int=core.max_confidence) -> 'FloatBuilder':
+ def create(
+ cls, width: int, alternate_name: str = "", platform: '_platform.Platform' = None,
+ confidence: int = core.max_confidence
+ ) -> 'FloatBuilder':
handle = core.BNCreateFloatTypeBuilder(width, alternate_name)
assert handle is not None, "core.BNCreateFloatTypeBuilder returned None"
return cls(handle, platform, confidence)
@@ -750,8 +786,10 @@ class FloatBuilder(TypeBuilder):
class WideCharBuilder(TypeBuilder):
@classmethod
- def create(cls, width:int, alternate_name:str="",
- platform:'_platform.Platform'=None, confidence:int=core.max_confidence) -> 'WideCharBuilder':
+ def create(
+ cls, width: int, alternate_name: str = "", platform: '_platform.Platform' = None,
+ confidence: int = core.max_confidence
+ ) -> 'WideCharBuilder':
handle = core.BNCreateWideCharTypeBuilder(width, alternate_name)
assert handle is not None, "core.BNCreateWideCharTypeBuilder returned None"
return cls(handle, platform, confidence)
@@ -759,10 +797,12 @@ class WideCharBuilder(TypeBuilder):
class PointerBuilder(TypeBuilder):
@classmethod
- def create(cls, type:'Type', width:int=4, arch:Optional['architecture.Architecture']=None,
- const:BoolWithConfidenceType=False, volatile:BoolWithConfidenceType=False,
- ref_type:ReferenceType=ReferenceType.PointerReferenceType,
- platform:'_platform.Platform'=None, confidence:int=core.max_confidence) -> 'PointerBuilder':
+ def create(
+ cls, type: 'Type', width: int = 4, arch: Optional['architecture.Architecture'] = None,
+ const: BoolWithConfidenceType = False, volatile: BoolWithConfidenceType = False,
+ ref_type: ReferenceType = ReferenceType.PointerReferenceType, platform: '_platform.Platform' = None,
+ confidence: int = core.max_confidence
+ ) -> 'PointerBuilder':
assert width is not None or arch is not None, "Must specify either a width or architecture when creating a pointer"
_width = width
if arch is not None:
@@ -770,8 +810,7 @@ class PointerBuilder(TypeBuilder):
_const = BoolWithConfidence.get_core_struct(const)
_volatile = BoolWithConfidence.get_core_struct(volatile)
- handle = core.BNCreatePointerTypeBuilderOfWidth(_width, type._to_core_struct(), _const,
- _volatile, ref_type)
+ handle = core.BNCreatePointerTypeBuilderOfWidth(_width, type._to_core_struct(), _const, _volatile, ref_type)
assert handle is not None, "BNCreatePointerTypeBuilderOfWidth returned None"
return cls(handle, platform, confidence)
@@ -786,8 +825,10 @@ class PointerBuilder(TypeBuilder):
class ArrayBuilder(TypeBuilder):
@classmethod
- def create(cls, type:SomeType, element_count:int,
- platform:'_platform.Platform'=None, confidence:int=core.max_confidence) -> 'ArrayBuilder':
+ def create(
+ cls, type: SomeType, element_count: int, platform: '_platform.Platform' = None,
+ confidence: int = core.max_confidence
+ ) -> 'ArrayBuilder':
handle = core.BNCreateArrayTypeBuilder(type._to_core_struct(), element_count)
assert handle is not None, "BNCreateArrayTypeBuilder returned None"
return cls(handle, platform, confidence)
@@ -803,10 +844,12 @@ class ArrayBuilder(TypeBuilder):
class FunctionBuilder(TypeBuilder):
@classmethod
- def create(cls, return_type:Optional[SomeType]=None, calling_convention:Optional['callingconvention.CallingConvention']=None,
- params:Optional[ParamsType]=None, var_args:BoolWithConfidenceType=False,
- stack_adjust:OffsetWithConfidenceType=0, platform:'_platform.Platform'=None,
- confidence:int=core.max_confidence) -> 'FunctionBuilder':
+ def create(
+ cls, return_type: Optional[SomeType] = None,
+ calling_convention: Optional['callingconvention.CallingConvention'] = None, params: Optional[ParamsType] = None,
+ var_args: BoolWithConfidenceType = False, stack_adjust: OffsetWithConfidenceType = 0,
+ platform: '_platform.Platform' = None, confidence: int = core.max_confidence
+ ) -> 'FunctionBuilder':
param_buf = FunctionBuilder._to_core_struct(params)
if return_type is None:
ret_conf = Type.void()._to_core_struct()
@@ -825,8 +868,9 @@ class FunctionBuilder(TypeBuilder):
stack_adjust_conf = OffsetWithConfidence.get_core_struct(stack_adjust)
if params is None:
params = []
- handle = core.BNCreateFunctionTypeBuilder(ret_conf, conv_conf, param_buf, len(params),
- vararg_conf, stack_adjust_conf)
+ handle = core.BNCreateFunctionTypeBuilder(
+ ret_conf, conv_conf, param_buf, len(params), vararg_conf, stack_adjust_conf
+ )
assert handle is not None, "BNCreateFunctionTypeBuilder returned None"
return cls(handle, platform, confidence)
@@ -839,10 +883,10 @@ class FunctionBuilder(TypeBuilder):
return self.child.mutable_copy()
@return_value.setter
- def return_value(self, value:SomeType) -> None: # type: ignore
+ def return_value(self, value: SomeType) -> None: # type: ignore
self.child = value
- def append(self, type:Union[SomeType, FunctionParameter], name:str=""):
+ def append(self, type: Union[SomeType, FunctionParameter], name: str = ""):
if isinstance(type, FunctionParameter):
self.parameters = [*self.parameters, type]
else:
@@ -858,7 +902,7 @@ class FunctionBuilder(TypeBuilder):
return BoolWithConfidence.from_core_struct(core.BNFunctionTypeBuilderCanReturn(self._handle))
@can_return.setter
- def can_return(self, value:BoolWithConfidenceType) -> None: # type: ignore
+ def can_return(self, value: BoolWithConfidenceType) -> None: # type: ignore
core.BNSetFunctionTypeBuilderCanReturn(self._handle, BoolWithConfidence.get_core_struct(value))
@property
@@ -873,17 +917,21 @@ class FunctionBuilder(TypeBuilder):
assert params is not None, "core.BNGetTypeBuilderParameters returned None"
result = []
for i in range(0, count.value):
- param_type = Type.create(core.BNNewTypeReference(params[i].type), platform = self.platform, confidence = params[i].typeConfidence)
+ param_type = Type.create(
+ core.BNNewTypeReference(params[i].type), platform=self.platform, confidence=params[i].typeConfidence
+ )
if params[i].defaultLocation:
param_location = None
else:
name = params[i].name
- if (params[i].location.type == VariableSourceType.RegisterVariableSourceType) and (self.platform is not None):
+ if (params[i].location.type
+ == VariableSourceType.RegisterVariableSourceType) and (self.platform is not None):
name = self.platform.arch.get_reg_name(params[i].location.storage)
elif params[i].location.type == VariableSourceType.StackVariableSourceType:
name = "arg_%x" % params[i].location.storage
- param_location = variable.VariableNameAndType(params[i].location.type, params[i].location.index,
- params[i].location.storage, name, param_type)
+ param_location = variable.VariableNameAndType(
+ params[i].location.type, params[i].location.index, params[i].location.storage, name, param_type
+ )
result.append(FunctionParameter(param_type, params[i].name, param_location))
core.BNFreeTypeParameterList(params, count.value)
return result
@@ -893,7 +941,7 @@ class FunctionBuilder(TypeBuilder):
return BoolWithConfidence.from_core_struct(core.BNTypeBuilderHasVariableArguments(self._handle))
@staticmethod
- def _to_core_struct(params:Optional[ParamsType]=None):
+ def _to_core_struct(params: Optional[ParamsType] = None):
if params is None:
params = []
param_buf = (core.BNFunctionParameter * len(params))()
@@ -920,7 +968,9 @@ class FunctionBuilder(TypeBuilder):
elif isinstance(param, tuple):
name, _type = param
assert isinstance(name, str), f"Conversion from unsupported function parameter type {type(param)}"
- assert isinstance(_type, (Type, TypeBuilder)), f"Conversion from unsupported function parameter type {type(param)}"
+ assert isinstance(
+ _type, (Type, TypeBuilder)
+ ), f"Conversion from unsupported function parameter type {type(param)}"
core_param.name = name
core_param.type = _type.handle
core_param.typeConfidence = _type.confidence
@@ -930,31 +980,32 @@ class FunctionBuilder(TypeBuilder):
return param_buf
@parameters.setter
- def parameters(self, params:List[FunctionParameter]) -> None:
+ def parameters(self, params: List[FunctionParameter]) -> None:
core.BNSetFunctionTypeBuilderParameters(self._handle, FunctionBuilder._to_core_struct(params), len(params))
@dataclass
class StructureMember:
- type:'Type'
- name:str
- offset:int
- access:MemberAccess = MemberAccess.NoAccess
- scope:MemberScope = MemberScope.NoScope
+ type: 'Type'
+ name: str
+ offset: int
+ access: MemberAccess = MemberAccess.NoAccess
+ scope: MemberScope = MemberScope.NoScope
def __repr__(self):
if len(self.name) == 0:
return f"<member: {self.type}, offset {self.offset:#x}>"
- return f"<{self.type.get_string_before_name()} {self.name}{self.type.get_string_after_name()}" + \
- f", offset {self.offset:#x}>"
+ return f"<{self.type.get_string_before_name()} {self.name}{self.type.get_string_after_name()}, offset {self.offset:#x}>"
def __len__(self):
return len(self.type)
class StructureBuilder(TypeBuilder):
- def __init__(self, handle:core.BNTypeBuilderHandle, builder_handle:core.BNStructureBuilderHandle,
- platform:'_platform.Platform'=None, confidence:int=core.max_confidence):
+ def __init__(
+ self, handle: core.BNTypeBuilderHandle, builder_handle: core.BNStructureBuilderHandle,
+ platform: '_platform.Platform' = None, confidence: int = core.max_confidence
+ ):
super(StructureBuilder, self).__init__(handle, platform, confidence)
assert builder_handle is not None, "Can't instantiate Structure with builder_handle set to None"
self.builder_handle = builder_handle
@@ -966,12 +1017,18 @@ class StructureBuilder(TypeBuilder):
for member in members:
if isinstance(member, Tuple):
_type, _name = member
- core.BNAddStructureBuilderMember(structure_builder_handle, _type._to_core_struct(), _name, MemberAccess.NoAccess, MemberScope.NoScope)
+ core.BNAddStructureBuilderMember(
+ structure_builder_handle, _type._to_core_struct(), _name, MemberAccess.NoAccess, MemberScope.NoScope
+ )
elif isinstance(member, StructureMember):
- core.BNAddStructureBuilderMemberAtOffset(structure_builder_handle, member.type._to_core_struct(),
- member.name, member.offset, False, member.access, member.scope)
+ core.BNAddStructureBuilderMemberAtOffset(
+ structure_builder_handle, member.type._to_core_struct(), member.name, member.offset, False,
+ member.access, member.scope
+ )
elif isinstance(member, (TypeBuilder, Type)):
- core.BNAddStructureBuilderMember(structure_builder_handle, member._to_core_struct(), "", MemberAccess.NoAccess, MemberScope.NoScope)
+ core.BNAddStructureBuilderMember(
+ structure_builder_handle, member._to_core_struct(), "", MemberAccess.NoAccess, MemberScope.NoScope
+ )
else:
raise ValueError(f"Structure member type {member} not supported")
@@ -979,11 +1036,11 @@ class StructureBuilder(TypeBuilder):
StructureBuilder._add_members_to_builder(self.builder_handle, members)
@classmethod
- def create(cls, members:MembersType=None,
- type:StructureVariant=StructureVariant.StructStructureType,
- packed:bool=False,
- width:Optional[int]=None, platform:'_platform.Platform'=None,
- confidence:int=core.max_confidence) -> 'StructureBuilder':
+ def create(
+ cls, members: MembersType = None, type: StructureVariant = StructureVariant.StructStructureType,
+ packed: bool = False, width: Optional[int] = None, platform: '_platform.Platform' = None,
+ confidence: int = core.max_confidence
+ ) -> 'StructureBuilder':
structure_builder_handle = core.BNCreateStructureBuilderWithOptions(type, packed)
assert structure_builder_handle is not None, "core.BNCreateStructureBuilderWithOptions returned None"
if width is not None:
@@ -1011,14 +1068,18 @@ class StructureBuilder(TypeBuilder):
result = []
for i in range(0, count.value):
t = Type.create(core.BNNewTypeReference(members[i].type), confidence=members[i].typeConfidence)
- result.append(StructureMember(t, members[i].name, members[i].offset,
- MemberAccess(members[i].access), MemberScope(members[i].scope)))
+ result.append(
+ StructureMember(
+ t, members[i].name, members[i].offset, MemberAccess(members[i].access),
+ MemberScope(members[i].scope)
+ )
+ )
return result
finally:
core.BNFreeStructureMemberList(members, count.value)
@members.setter
- def members(self, members:MembersType=None) -> None:
+ def members(self, members: MembersType = None) -> None:
count = len(self.members)
# remove members in reverse order
for i in reversed(range(count)):
@@ -1030,7 +1091,7 @@ class StructureBuilder(TypeBuilder):
return core.BNIsStructureBuilderPacked(self.builder_handle)
@packed.setter
- def packed(self, value:bool) -> None:
+ def packed(self, value: bool) -> None:
core.BNSetStructureBuilderPacked(self.builder_handle, value)
@property
@@ -1038,7 +1099,7 @@ class StructureBuilder(TypeBuilder):
return core.BNGetStructureBuilderAlignment(self.builder_handle)
@alignment.setter
- def alignment(self, value:int) -> None:
+ def alignment(self, value: int) -> None:
core.BNSetStructureBuilderAlignment(self.builder_handle, value)
@property
@@ -1046,7 +1107,7 @@ class StructureBuilder(TypeBuilder):
return core.BNGetStructureBuilderWidth(self.builder_handle)
@width.setter
- def width(self, value:int) -> None:
+ def width(self, value: int) -> None:
core.BNSetStructureBuilderWidth(self.builder_handle, value)
@property
@@ -1058,17 +1119,19 @@ class StructureBuilder(TypeBuilder):
return StructureVariant(core.BNGetStructureBuilderType(self.builder_handle))
@type.setter
- def type(self, value:StructureVariant) -> None:
+ def type(self, value: StructureVariant) -> None:
core.BNSetStructureBuilderType(self.builder_handle, value)
- def __getitem__(self, name:str) -> Optional[StructureMember]:
+ def __getitem__(self, name: str) -> Optional[StructureMember]:
member = core.BNGetStructureBuilderMemberByName(self.builder_handle, name)
if member is None:
return None
try:
- return StructureMember(Type(core.BNNewTypeReference(member.contents.type),
- confidence=member.contents.typeConfidence), member.contents.name, member.contents.offset,
- MemberAccess(member.contents.access), MemberScope(member.contents.scope))
+ return StructureMember(
+ Type(core.BNNewTypeReference(member.contents.type), confidence=member.contents.typeConfidence),
+ member.contents.name, member.contents.offset, MemberAccess(member.contents.access),
+ MemberScope(member.contents.scope)
+ )
finally:
core.BNFreeStructureMember(member)
@@ -1079,55 +1142,63 @@ class StructureBuilder(TypeBuilder):
def __len__(self) -> int:
return self.width
- def member_at_offset(self, offset:int) -> Optional[StructureMember]:
+ def member_at_offset(self, offset: int) -> Optional[StructureMember]:
for member in self.members:
if member.offset == offset:
return member
return None
- def index_by_name(self, name:MemberName) -> Optional[MemberIndex]:
+ def index_by_name(self, name: MemberName) -> Optional[MemberIndex]:
for i, member in enumerate(self.members):
if member.name == name:
return i
return None
- def index_by_offset(self, offset:MemberOffset) -> Optional[MemberIndex]:
+ def index_by_offset(self, offset: MemberOffset) -> Optional[MemberIndex]:
for i, member in enumerate(self.members):
if member.offset == offset:
return i
return None
- def replace(self, index:int, type:SomeType, name:str="", overwrite_existing:bool=True):
- core.BNReplaceStructureBuilderMember(self.builder_handle, index,
- type._to_core_struct(), name, overwrite_existing)
+ def replace(self, index: int, type: SomeType, name: str = "", overwrite_existing: bool = True):
+ core.BNReplaceStructureBuilderMember(
+ self.builder_handle, index, type._to_core_struct(), name, overwrite_existing
+ )
- def remove(self, index:int):
+ def remove(self, index: int):
core.BNRemoveStructureBuilderMember(self.builder_handle, index)
- def insert(self, offset:int, type:SomeType, name:str="", overwrite_existing:bool=True,
- access:MemberAccess=MemberAccess.NoAccess, scope:MemberScope=MemberScope.NoScope):
- core.BNAddStructureBuilderMemberAtOffset(self.builder_handle,
- type._to_core_struct(), name, offset, overwrite_existing, access, scope)
+ def insert(
+ self, offset: int, type: SomeType, name: str = "", overwrite_existing: bool = True,
+ access: MemberAccess = MemberAccess.NoAccess, scope: MemberScope = MemberScope.NoScope
+ ):
+ core.BNAddStructureBuilderMemberAtOffset(
+ self.builder_handle, type._to_core_struct(), name, offset, overwrite_existing, access, scope
+ )
- def append(self, type:SomeType, name:MemberName="", access:MemberAccess=MemberAccess.NoAccess,
- scope:MemberScope=MemberScope.NoScope) -> 'StructureBuilder':
+ def append(
+ self, type: SomeType, name: MemberName = "", access: MemberAccess = MemberAccess.NoAccess,
+ scope: MemberScope = MemberScope.NoScope
+ ) -> 'StructureBuilder':
# appends a member at the end of the structure growing the structure
- core.BNAddStructureBuilderMember(self.builder_handle,
- type._to_core_struct(), name, access, scope)
+ core.BNAddStructureBuilderMember(self.builder_handle, type._to_core_struct(), name, access, scope)
return self
- def add_member_at_offset(self, name:MemberName, type:SomeType, offset:MemberOffset, overwrite_existing:bool=True,
- access:MemberAccess=MemberAccess.NoAccess, scope:MemberScope=MemberScope.NoScope) -> 'StructureBuilder':
+ def add_member_at_offset(
+ self, name: MemberName, type: SomeType, offset: MemberOffset, overwrite_existing: bool = True,
+ access: MemberAccess = MemberAccess.NoAccess, scope: MemberScope = MemberScope.NoScope
+ ) -> 'StructureBuilder':
# Adds structure member to the given offset optionally clearing any members within the range offset-offset+len(type)
- core.BNAddStructureBuilderMemberAtOffset(self.builder_handle, type._to_core_struct(), name,
- offset, overwrite_existing, access, scope)
+ core.BNAddStructureBuilderMemberAtOffset(
+ self.builder_handle, type._to_core_struct(), name, offset, overwrite_existing, access, scope
+ )
return self
@dataclass(frozen=True)
class EnumerationMember:
- name:str
- value:Optional[int] = None
+ name: str
+ value: Optional[int] = None
def __repr__(self):
value = f"{self.value:#x}" if self.value is not None else "auto()"
@@ -1138,16 +1209,20 @@ class EnumerationMember:
class EnumerationBuilder(TypeBuilder):
- def __init__(self, handle:core.BNTypeBuilderHandle, enum_builder_handle:core.BNEnumerationBuilderHandle,
- platform:'_platform.Platform'=None, confidence:int=core.max_confidence):
+ def __init__(
+ self, handle: core.BNTypeBuilderHandle, enum_builder_handle: core.BNEnumerationBuilderHandle,
+ platform: '_platform.Platform' = None, confidence: int = core.max_confidence
+ ):
super(EnumerationBuilder, self).__init__(handle, platform, confidence)
assert isinstance(enum_builder_handle, core.BNEnumerationBuilderHandle)
self.enum_builder_handle = enum_builder_handle
@classmethod
- def create(cls, members:Optional[List[EnumMembersType]]=None, width:Optional[int]=None,
- arch:Optional['architecture.Architecture']=None, sign:BoolWithConfidenceType=False,
- platform:'_platform.Platform'=None, confidence:int=core.max_confidence) -> 'EnumerationBuilder':
+ def create(
+ cls, members: Optional[List[EnumMembersType]] = None, width: Optional[int] = None,
+ arch: Optional['architecture.Architecture'] = None, sign: BoolWithConfidenceType = False,
+ platform: '_platform.Platform' = None, confidence: int = core.max_confidence
+ ) -> 'EnumerationBuilder':
if members is None:
members = []
@@ -1182,19 +1257,21 @@ class EnumerationBuilder(TypeBuilder):
result = []
try:
for i in range(count.value):
- result.append(EnumerationMember(members[i].name, members[i].value if not members[i].isDefault else None))
+ result.append(
+ EnumerationMember(members[i].name, members[i].value if not members[i].isDefault else None)
+ )
return result
finally:
core.BNFreeEnumerationMemberList(members, count.value)
@members.setter
- def members(self, members:List[EnumMembersType]) -> None: # type: ignore
+ def members(self, members: List[EnumMembersType]) -> None: # type: ignore
for i in reversed(range(len(self.members))):
self.remove(i)
EnumerationBuilder._add_members(self.enum_builder_handle, members)
@staticmethod
- def _add_members(enum_builder_handle, members:List[EnumMembersType]):
+ def _add_members(enum_builder_handle, members: List[EnumMembersType]):
for i, member in enumerate(members):
value = None
if isinstance(member, Tuple):
@@ -1210,16 +1287,15 @@ class EnumerationBuilder(TypeBuilder):
else:
core.BNAddEnumerationBuilderMemberWithValue(enum_builder_handle, name, value)
-
- def append(self, name:str, value:Optional[int]=None) -> 'EnumerationBuilder':
+ def append(self, name: str, value: Optional[int] = None) -> 'EnumerationBuilder':
EnumerationBuilder._add_members(self.enum_builder_handle, [EnumerationMember(name, value)])
return self
- def remove(self, i:int) -> 'EnumerationBuilder':
+ def remove(self, i: int) -> 'EnumerationBuilder':
core.BNRemoveEnumerationBuilderMember(self.enum_builder_handle, i)
return self
- def replace(self, i:int, name:str, value:Optional[int]=None) -> 'EnumerationBuilder':
+ def replace(self, i: int, name: str, value: Optional[int] = None) -> 'EnumerationBuilder':
core.BNReplaceEnumerationBuilderMember(self.enum_builder_handle, i, name, value)
return self
@@ -1227,7 +1303,7 @@ class EnumerationBuilder(TypeBuilder):
for member in self.members:
yield member
- def __getitem__(self, value:Union[str, int, slice]):
+ def __getitem__(self, value: Union[str, int, slice]):
if isinstance(value, str):
for member in self.members:
if member.name == value:
@@ -1240,7 +1316,7 @@ class EnumerationBuilder(TypeBuilder):
else:
raise ValueError(f"Incompatible type {type(value)} for __getitem__")
- def __setitem__(self, item:Union[str, int], value:Union[Optional[int], EnumerationMember]):
+ def __setitem__(self, item: Union[str, int], value: Union[Optional[int], EnumerationMember]):
if isinstance(item, str):
for i, member in enumerate(self.members):
if member.name == item:
@@ -1252,25 +1328,33 @@ class EnumerationBuilder(TypeBuilder):
class NamedTypeReferenceBuilder(TypeBuilder):
- def __init__(self, handle:core.BNTypeBuilderHandle, ntr_builder_handle:core.BNNamedTypeReferenceBuilderHandle,
- platform:'_platform.Platform'=None, confidence:int=core.max_confidence):
+ def __init__(
+ self, handle: core.BNTypeBuilderHandle, ntr_builder_handle: core.BNNamedTypeReferenceBuilderHandle,
+ platform: '_platform.Platform' = None, confidence: int = core.max_confidence
+ ):
assert ntr_builder_handle is not None, "Failed to construct NameTypeReference"
assert handle is not None, "Failed to construct NameTypeReference"
- assert isinstance(ntr_builder_handle, core.BNNamedTypeReferenceBuilderHandle), "Failed to construct NameTypeReference"
+ assert isinstance(
+ ntr_builder_handle, core.BNNamedTypeReferenceBuilderHandle
+ ), "Failed to construct NameTypeReference"
super(NamedTypeReferenceBuilder, self).__init__(handle, platform, confidence)
self.ntr_builder_handle = ntr_builder_handle
@classmethod
- def create(cls, type_class:NamedTypeReferenceClass=NamedTypeReferenceClass.UnknownNamedTypeClass,
- type_id:Optional[str]=None, name:QualifiedName=QualifiedName(""), width:int=0, align:int=1,
- platform:'_platform.Platform'=None, confidence:int=core.max_confidence,
- const:BoolWithConfidenceType=False, volatile:BoolWithConfidenceType=False) -> 'NamedTypeReferenceBuilder':
+ def create(
+ cls, type_class: NamedTypeReferenceClass = NamedTypeReferenceClass.UnknownNamedTypeClass,
+ type_id: Optional[str] = None, name: QualifiedName = QualifiedName(""), width: int = 0, align: int = 1,
+ platform: '_platform.Platform' = None, confidence: int = core.max_confidence,
+ const: BoolWithConfidenceType = False, volatile: BoolWithConfidenceType = False
+ ) -> 'NamedTypeReferenceBuilder':
ntr_builder_handle = core.BNCreateNamedTypeBuilder(type_class, type_id, QualifiedName(name)._to_core_struct())
assert ntr_builder_handle is not None, "core.BNCreateNamedTypeBuilder returned None"
_const = BoolWithConfidence.get_core_struct(const)
_volatile = BoolWithConfidence.get_core_struct(volatile)
- type_builder_handle = core.BNCreateNamedTypeReferenceBuilderWithBuilder(ntr_builder_handle, width, align, _const, _volatile)
+ type_builder_handle = core.BNCreateNamedTypeReferenceBuilderWithBuilder(
+ ntr_builder_handle, width, align, _const, _volatile
+ )
assert type_builder_handle is not None, "core.BNCreateNamedTypeReferenceBuilderWithBuilder returned None"
return cls(type_builder_handle, ntr_builder_handle, platform, confidence)
@@ -1302,14 +1386,20 @@ class NamedTypeReferenceBuilder(TypeBuilder):
return NamedTypeReferenceClass(core.BNGetTypeReferenceBuilderClass(self.ntr_builder_handle))
@staticmethod
- def named_type(named_type:'NamedTypeReferenceBuilder', width:int=0, align:int=1,
- const:BoolWithConfidenceType=BoolWithConfidence(False),
- volatile:BoolWithConfidenceType=BoolWithConfidence(False)) -> 'NamedTypeReferenceBuilder':
- return NamedTypeReferenceBuilder.create(named_type.named_type_class, named_type.id,
- named_type.name, width, align, None, core.max_confidence, const, volatile)
+ def named_type(
+ named_type: 'NamedTypeReferenceBuilder', width: int = 0, align: int = 1,
+ const: BoolWithConfidenceType = BoolWithConfidence(False),
+ volatile: BoolWithConfidenceType = BoolWithConfidence(False)
+ ) -> 'NamedTypeReferenceBuilder':
+ return NamedTypeReferenceBuilder.create(
+ named_type.named_type_class, named_type.id, named_type.name, width, align, None, core.max_confidence, const,
+ volatile
+ )
@staticmethod
- def named_type_from_type_and_id(type_id:str, name:QualifiedName, type:Optional['Type']=None) -> 'NamedTypeReferenceBuilder':
+ def named_type_from_type_and_id(
+ type_id: str, name: QualifiedName, type: Optional['Type'] = None
+ ) -> 'NamedTypeReferenceBuilder':
if type is None:
return NamedTypeReferenceBuilder.create(NamedTypeReferenceClass.UnknownNamedTypeClass, type_id, name)
elif type.type_class == TypeClass.StructureTypeClass:
@@ -1325,14 +1415,20 @@ class NamedTypeReferenceBuilder(TypeBuilder):
return NamedTypeReferenceBuilder.create(NamedTypeReferenceClass.TypedefNamedTypeClass, type_id, name)
@staticmethod
- def named_type_from_type(name:QualifiedName, type_class:Optional[NamedTypeReferenceClass]=None) -> 'NamedTypeReferenceBuilder':
+ def named_type_from_type(
+ name: QualifiedName, type_class: Optional[NamedTypeReferenceClass] = None
+ ) -> 'NamedTypeReferenceBuilder':
if type_class is None:
- return NamedTypeReferenceBuilder.create(NamedTypeReferenceClass.UnknownNamedTypeClass, str(uuid.uuid4()), name)
+ return NamedTypeReferenceBuilder.create(
+ NamedTypeReferenceClass.UnknownNamedTypeClass, str(uuid.uuid4()), name
+ )
else:
return NamedTypeReferenceBuilder.create(type_class, str(uuid.uuid4()), name)
@staticmethod
- def named_type_from_registered_type(view:'binaryview.BinaryView', name:QualifiedName) -> 'NamedTypeReferenceBuilder':
+ def named_type_from_registered_type(
+ view: 'binaryview.BinaryView', name: QualifiedName
+ ) -> 'NamedTypeReferenceBuilder':
type = view.get_type_by_name(name)
if type is None:
raise ValueError(f"Unable to find type named {name}")
@@ -1365,14 +1461,16 @@ class Type:
:py:meth:`parse_types_from_source_file <platform.Platform.parse_types_from_source_file>`
"""
- def __init__(self, handle, platform:'_platform.Platform'=None, confidence:int=core.max_confidence):
+ def __init__(self, handle, platform: '_platform.Platform' = None, confidence: int = core.max_confidence):
assert isinstance(handle.contents, core.BNType), "Attempting to create mutable Type"
self._handle = handle
self._confidence = confidence
self._platform = platform
@classmethod
- def create(cls, handle=core.BNTypeHandle, platform:'_platform.Platform'=None, confidence:int=core.max_confidence) -> 'Type':
+ def create(
+ cls, handle=core.BNTypeHandle, platform: '_platform.Platform' = None, confidence: int = core.max_confidence
+ ) -> 'Type':
assert handle is not None, "Passed a handle which is None"
assert isinstance(handle, core.BNTypeHandle)
type_class = TypeClass(core.BNGetTypeClass(handle))
@@ -1458,7 +1556,7 @@ class Type:
"""Type string as a list of tokens (read-only)"""
return self.get_tokens()
- def get_tokens(self, base_confidence = core.max_confidence) -> List['_function.InstructionTextToken']:
+ def get_tokens(self, base_confidence=core.max_confidence) -> List['_function.InstructionTextToken']:
count = ctypes.c_ulonglong()
platform = None
if self._platform is not None:
@@ -1470,7 +1568,7 @@ class Type:
core.BNFreeInstructionText(tokens, count.value)
return result
- def get_tokens_before_name(self, base_confidence = core.max_confidence) -> List['_function.InstructionTextToken']:
+ def get_tokens_before_name(self, base_confidence=core.max_confidence) -> List['_function.InstructionTextToken']:
count = ctypes.c_ulonglong()
platform = None
if self._platform is not None:
@@ -1481,7 +1579,7 @@ class Type:
core.BNFreeInstructionText(tokens, count.value)
return result
- def get_tokens_after_name(self, base_confidence = core.max_confidence) -> List['_function.InstructionTextToken']:
+ def get_tokens_after_name(self, base_confidence=core.max_confidence) -> List['_function.InstructionTextToken']:
count = ctypes.c_ulonglong()
platform = None
if self._platform is not None:
@@ -1493,14 +1591,14 @@ class Type:
return result
def with_confidence(self, confidence) -> 'Type':
- return Type.create(handle = core.BNNewTypeReference(self._handle), platform = self._platform, confidence = confidence)
+ return Type.create(handle=core.BNNewTypeReference(self._handle), platform=self._platform, confidence=confidence)
@property
def confidence(self) -> _int:
return self._confidence
@confidence.setter
- def confidence(self, value:_int) -> None:
+ def confidence(self, value: _int) -> None:
self._confidence = value
@property
@@ -1508,22 +1606,18 @@ class Type:
return self._platform
@platform.setter
- def platform(self, value:'_platform.Platform') -> None:
+ def platform(self, value: '_platform.Platform') -> None:
self._platform = value
def mutable_copy(self) -> 'TypeBuilder':
TypeBuilders = {
- TypeClass.VoidTypeClass:VoidBuilder,
- TypeClass.BoolTypeClass:BoolBuilder,
- TypeClass.IntegerTypeClass:IntegerBuilder,
- TypeClass.FloatTypeClass:FloatBuilder,
- TypeClass.PointerTypeClass:PointerBuilder,
- TypeClass.ArrayTypeClass:ArrayBuilder,
- TypeClass.FunctionTypeClass:FunctionBuilder,
- TypeClass.WideCharTypeClass:WideCharBuilder,
- # TypeClass.StructureTypeClass:Structure,
- # TypeClass.EnumerationTypeClass:Enumeration,
- # TypeClass.NamedTypeReferenceClass:NamedTypeReference,
+ TypeClass.VoidTypeClass: VoidBuilder, TypeClass.BoolTypeClass: BoolBuilder,
+ TypeClass.IntegerTypeClass: IntegerBuilder, TypeClass.FloatTypeClass: FloatBuilder,
+ TypeClass.PointerTypeClass: PointerBuilder, TypeClass.ArrayTypeClass: ArrayBuilder,
+ TypeClass.FunctionTypeClass: FunctionBuilder, TypeClass.WideCharTypeClass: WideCharBuilder,
+ # TypeClass.StructureTypeClass:Structure,
+ # TypeClass.EnumerationTypeClass:Enumeration,
+ # TypeClass.NamedTypeReferenceClass:NamedTypeReference,
}
builder_handle = core.BNCreateTypeBuilderFromType(self._handle)
assert builder_handle is not None, "core.BNCreateTypeBuilderFromType returned None"
@@ -1532,12 +1626,14 @@ class Type:
def immutable_copy(self) -> 'Type':
return self
- def get_builder(self, bv:'binaryview.BinaryView') -> 'MutableTypeBuilder':
+ def get_builder(self, bv: 'binaryview.BinaryView') -> 'MutableTypeBuilder':
return MutableTypeBuilder(self.mutable_copy(), bv, self.registered_name, self.platform, self._confidence)
@staticmethod
- def builder(bv:'binaryview.BinaryView', name:Optional[QualifiedName]=None, id:Optional[str]=None,
- platform:'_platform.Platform'=None, confidence:int=core.max_confidence) -> 'MutableTypeBuilder':
+ def builder(
+ bv: 'binaryview.BinaryView', name: Optional[QualifiedName] = None, id: Optional[str] = None,
+ platform: '_platform.Platform' = None, confidence: int = core.max_confidence
+ ) -> 'MutableTypeBuilder':
type = None
if name is None and id is None:
raise ValueError("Must specify either a name or id to create a builder object")
@@ -1560,13 +1656,15 @@ class Type:
return MutableTypeBuilder(type.mutable_copy(), bv, name, platform, confidence)
def with_replaced_structure(self, from_struct, to_struct):
- return Type.create(handle = core.BNTypeWithReplacedStructure(self._handle, from_struct.handle, to_struct.handle))
+ return Type.create(handle=core.BNTypeWithReplacedStructure(self._handle, from_struct.handle, to_struct.handle))
def with_replaced_enumeration(self, from_enum, to_enum):
- return Type.create(handle = core.BNTypeWithReplacedEnumeration(self._handle, from_enum.handle, to_enum.handle))
+ return Type.create(handle=core.BNTypeWithReplacedEnumeration(self._handle, from_enum.handle, to_enum.handle))
def with_replaced_named_type_reference(self, from_ref, to_ref):
- return Type.create(handle = core.BNTypeWithReplacedNamedTypeReference(self._handle, from_ref.handle, to_ref.handle))
+ return Type.create(
+ handle=core.BNTypeWithReplacedNamedTypeReference(self._handle, from_ref.handle, to_ref.handle)
+ )
@staticmethod
def void() -> 'VoidType':
@@ -1577,11 +1675,11 @@ class Type:
return BoolType.create()
@staticmethod
- def char(alternate_name:str="") -> 'CharType':
+ def char(alternate_name: str = "") -> 'CharType':
return CharType.create(alternate_name)
@staticmethod
- def int(width:_int, sign:BoolWithConfidenceType=True, alternate_name:str="") -> 'IntegerType':
+ def int(width: _int, sign: BoolWithConfidenceType = True, alternate_name: str = "") -> 'IntegerType':
"""
``int`` class method for creating an int Type.
:param int width: width of the integer in bytes
@@ -1591,7 +1689,7 @@ class Type:
return IntegerType.create(width, sign, alternate_name)
@staticmethod
- def float(width:_int, alternate_name:str="") -> 'FloatType':
+ def float(width: _int, alternate_name: str = "") -> 'FloatType':
"""
``float`` class method for creating floating point Types.
:param int width: width of the floating point number in bytes
@@ -1600,7 +1698,7 @@ class Type:
return FloatType.create(width, alternate_name)
@staticmethod
- def wide_char(width:_int, alternate_name:str="") -> 'WideCharType':
+ def wide_char(width: _int, alternate_name: str = "") -> 'WideCharType':
"""
``wide_char`` class method for creating wide char Types.
:param int width: width of the wide character in bytes
@@ -1609,42 +1707,47 @@ class Type:
return WideCharType.create(width=width, alternate_name=alternate_name)
@staticmethod
- def structure_type(structure:'StructureBuilder') -> 'StructureType':
+ def structure_type(structure: 'StructureBuilder') -> 'StructureType':
result = structure.immutable_copy()
assert isinstance(result, StructureType)
return result
@staticmethod
- def named_type(named_type:'NamedTypeReferenceBuilder') -> 'NamedTypeReferenceType':
+ def named_type(named_type: 'NamedTypeReferenceBuilder') -> 'NamedTypeReferenceType':
result = named_type.immutable_copy()
assert isinstance(result, NamedTypeReferenceType)
return result
@staticmethod
- def named_type_from_type(name:QualifiedName, type:'Type') -> 'NamedTypeReferenceType':
+ def named_type_from_type(name: QualifiedName, type: 'Type') -> 'NamedTypeReferenceType':
return NamedTypeReferenceType.create_from_type(name, type)
@staticmethod
- def named_type_from_type_and_id(type_id:str, name:QualifiedName, type:Optional['Type']=None) -> 'NamedTypeReferenceType':
+ def named_type_from_type_and_id(
+ type_id: str, name: QualifiedName, type: Optional['Type'] = None
+ ) -> 'NamedTypeReferenceType':
return NamedTypeReferenceType.create_from_type(name, type, type_id)
@staticmethod
- def generate_named_type_reference(guid:str, name:QualifiedName) -> 'NamedTypeReferenceType':
+ def generate_named_type_reference(guid: str, name: QualifiedName) -> 'NamedTypeReferenceType':
return NamedTypeReferenceType.create(NamedTypeReferenceClass.TypedefNamedTypeClass, guid, name)
@staticmethod
- def named_type_from_registered_type(view:'binaryview.BinaryView', name:QualifiedName) -> 'NamedTypeReferenceType':
+ def named_type_from_registered_type(view: 'binaryview.BinaryView', name: QualifiedName) -> 'NamedTypeReferenceType':
return NamedTypeReferenceType.create_from_registered_type(view, name)
@staticmethod
- def enumeration_type(arch, enum:'EnumerationBuilder', width:_int=None, sign:_bool=False) -> 'EnumerationType':
+ def enumeration_type(
+ arch, enum: 'EnumerationBuilder', width: _int = None, sign: _bool = False
+ ) -> 'EnumerationType':
return EnumerationType.create(enum.members, enum.width, arch, enum.signed)
@staticmethod
- def pointer(arch:'architecture.Architecture', type:'Type',
- const:BoolWithConfidenceType=BoolWithConfidence(False),
- volatile:BoolWithConfidenceType=BoolWithConfidence(False),
- ref_type:ReferenceType=ReferenceType.PointerReferenceType, width:_int=None) -> 'PointerType':
+ def pointer(
+ arch: 'architecture.Architecture', type: 'Type', const: BoolWithConfidenceType = BoolWithConfidence(False),
+ volatile: BoolWithConfidenceType = BoolWithConfidence(False),
+ ref_type: ReferenceType = ReferenceType.PointerReferenceType, width: _int = None
+ ) -> 'PointerType':
if arch is not None:
width = arch.address_size
@@ -1654,20 +1757,23 @@ class Type:
return PointerType.create_with_width(width, type, const, volatile, ref_type)
@staticmethod
- def pointer_of_width(width:_int, type:'Type',
- const:BoolWithConfidenceType=False,
- volatile:BoolWithConfidenceType=False,
- ref_type:ReferenceType=ReferenceType.PointerReferenceType) -> 'PointerType':
+ def pointer_of_width(
+ width: _int, type: 'Type', const: BoolWithConfidenceType = False, volatile: BoolWithConfidenceType = False,
+ ref_type: ReferenceType = ReferenceType.PointerReferenceType
+ ) -> 'PointerType':
return PointerType.create_with_width(width, type, const, volatile, ref_type)
@staticmethod
- def array(type:'Type', count:_int) -> 'ArrayType':
+ def array(type: 'Type', count: _int) -> 'ArrayType':
return ArrayType.create(type, count)
@staticmethod
- def function(ret:Optional['Type']=None, params:Optional[ParamsType]=None, calling_convention:'callingconvention.CallingConvention'=None,
- variable_arguments:BoolWithConfidenceType=False,
- stack_adjust:OffsetWithConfidence=OffsetWithConfidence(0)) -> 'FunctionType':
+ def function(
+ ret: Optional['Type'] = None, params: Optional[ParamsType] = None,
+ calling_convention: 'callingconvention.CallingConvention' = None,
+ variable_arguments: BoolWithConfidenceType = False,
+ stack_adjust: OffsetWithConfidence = OffsetWithConfidence(0)
+ ) -> 'FunctionType':
"""
``function`` class method for creating an function Type.
:param Type ret: return Type of the function
@@ -1679,35 +1785,42 @@ class Type:
return FunctionType.create(ret, params, calling_convention, variable_arguments, stack_adjust)
@staticmethod
- def from_core_struct(core_type:core.BNType):
+ def from_core_struct(core_type: core.BNType):
return Type.create(core.BNNewTypeReference(core_type))
@staticmethod
- def structure(members:MembersType=None, packed:_bool=False, type:StructureVariant=StructureVariant.StructStructureType) -> 'StructureType':
+ def structure(
+ members: MembersType = None, packed: _bool = False,
+ type: StructureVariant = StructureVariant.StructStructureType
+ ) -> 'StructureType':
return StructureType.create(members, packed, type)
-
+
@staticmethod
- def union(members:Optional[MembersType]=None, packed:_bool=False) -> 'StructureType':
+ def union(members: Optional[MembersType] = None, packed: _bool = False) -> 'StructureType':
return StructureType.create(members, type=StructureVariant.UnionStructureType, packed=packed)
-
+
@staticmethod
- def class_type(members:Optional[MembersType]=None, packed:_bool=False) -> 'StructureType':
+ def class_type(members: Optional[MembersType] = None, packed: _bool = False) -> 'StructureType':
return StructureType.create(members, type=StructureVariant.ClassStructureType, packed=packed)
@staticmethod
- def enumeration(arch:Optional['architecture.Architecture']=None, members:Optional[List[EnumMembersType]]=None,
- width:Optional[_int]=None, sign:BoolWithConfidenceType=False) -> 'EnumerationType':
+ def enumeration(
+ arch: Optional['architecture.Architecture'] = None, members: Optional[List[EnumMembersType]] = None,
+ width: Optional[_int] = None, sign: BoolWithConfidenceType = False
+ ) -> 'EnumerationType':
if members is None:
members = []
return EnumerationType.create(members, width, arch, sign)
@staticmethod
- def named_type_reference(type_class:NamedTypeReferenceClass, name:QualifiedName,
- type_id:Optional[str]=None, alignment:_int=1, width:_int=0,
- const:BoolWithConfidenceType=BoolWithConfidence(False),
- volatile:BoolWithConfidenceType=BoolWithConfidence(False)):
- return NamedTypeReferenceType.create(type_class, type_id, name, alignment, width,
- None, core.max_confidence, const, volatile)
+ def named_type_reference(
+ type_class: NamedTypeReferenceClass, name: QualifiedName, type_id: Optional[str] = None, alignment: _int = 1,
+ width: _int = 0, const: BoolWithConfidenceType = BoolWithConfidence(False),
+ volatile: BoolWithConfidenceType = BoolWithConfidence(False)
+ ):
+ return NamedTypeReferenceType.create(
+ type_class, type_id, name, alignment, width, None, core.max_confidence, const, volatile
+ )
@property
@abstractmethod
@@ -1715,12 +1828,12 @@ class Type:
raise NotImplementedError("Name not implemented for this type")
@staticmethod
- def generate_auto_type_id(source:str, name:str) -> str:
+ def generate_auto_type_id(source: str, name: str) -> str:
_name = QualifiedName(name)._to_core_struct()
return core.BNGenerateAutoTypeId(source, _name)
@staticmethod
- def generate_auto_demangled_type_id(name:str) -> str:
+ def generate_auto_demangled_type_id(name: str) -> str:
_name = QualifiedName(name)._to_core_struct()
return core.BNGenerateAutoDemangledTypeId(_name)
@@ -1740,13 +1853,13 @@ class Type:
def const(self):
"""Whether type is const (read/write)"""
result = core.BNIsTypeConst(self._handle)
- return BoolWithConfidence(result.value, confidence = result.confidence)
+ return BoolWithConfidence(result.value, confidence=result.confidence)
@property
def volatile(self):
"""Whether type is volatile (read/write)"""
result = core.BNIsTypeVolatile(self._handle)
- return BoolWithConfidence(result.value, confidence = result.confidence)
+ return BoolWithConfidence(result.value, confidence=result.confidence)
@property
def system_call_number(self) -> Optional[_int]:
@@ -1758,8 +1871,8 @@ class Type:
@dataclass(frozen=True)
class RegisterStackAdjustmentWithConfidence:
- value:int
- confidence:int=core.max_confidence
+ value: int
+ confidence: int = core.max_confidence
def __int__(self):
return self.value
@@ -1767,7 +1880,7 @@ class RegisterStackAdjustmentWithConfidence:
class VoidType(Type):
@classmethod
- def create(cls, platform:'_platform.Platform'=None, confidence:int=core.max_confidence) -> 'VoidType':
+ def create(cls, platform: '_platform.Platform' = None, confidence: int = core.max_confidence) -> 'VoidType':
core_void = core.BNCreateVoidType()
assert core_void is not None, "core.BNCreateVoidType returned None"
return cls(core.BNNewTypeReference(core_void), platform, confidence)
@@ -1775,19 +1888,21 @@ class VoidType(Type):
class BoolType(Type):
@classmethod
- def create(cls, platform:'_platform.Platform'=None, confidence:int=core.max_confidence) -> 'BoolType':
+ def create(cls, platform: '_platform.Platform' = None, confidence: int = core.max_confidence) -> 'BoolType':
handle = core.BNCreateBoolType()
assert handle is not None, "core.BNCreateBoolType returned None"
return cls(core.BNNewTypeReference(handle), platform, confidence)
class IntegerType(Type):
- def __init__(self, handle, platform:'_platform.Platform'=None, confidence:int=core.max_confidence):
+ def __init__(self, handle, platform: '_platform.Platform' = None, confidence: int = core.max_confidence):
super(IntegerType, self).__init__(handle, platform, confidence)
@classmethod
- def create(cls, width:int, sign:BoolWithConfidenceType=True, alternate_name:str="",
- platform:'_platform.Platform'=None, confidence:int=core.max_confidence) -> 'IntegerType':
+ def create(
+ cls, width: int, sign: BoolWithConfidenceType = True, alternate_name: str = "",
+ platform: '_platform.Platform' = None, confidence: int = core.max_confidence
+ ) -> 'IntegerType':
_sign = BoolWithConfidence.get_core_struct(sign)
handle = core.BNCreateIntegerType(width, _sign, alternate_name)
assert handle is not None, "core.BNCreateIntegerType returned None"
@@ -1801,14 +1916,17 @@ class IntegerType(Type):
class CharType(IntegerType):
@classmethod
- def create(cls, altname:str="char", platform:'_platform.Platform'=None,
- confidence:int=core.max_confidence) -> 'CharType':
+ def create(
+ cls, altname: str = "char", platform: '_platform.Platform' = None, confidence: int = core.max_confidence
+ ) -> 'CharType':
return cls(IntegerType.create(1, True, altname).handle, platform, confidence)
class FloatType(Type):
@classmethod
- def create(cls, width:int, altname:str="", platform:'_platform.Platform'=None, confidence:int=core.max_confidence) -> 'FloatType':
+ def create(
+ cls, width: int, altname: str = "", platform: '_platform.Platform' = None, confidence: int = core.max_confidence
+ ) -> 'FloatType':
"""
``float`` class method for creating floating point Types.
@@ -1821,7 +1939,7 @@ class FloatType(Type):
class StructureType(Type):
- def __init__(self, handle, platform:'_platform.Platform'=None, confidence:int=core.max_confidence):
+ def __init__(self, handle, platform: '_platform.Platform' = None, confidence: int = core.max_confidence):
assert handle is not None, "Attempted to create EnumerationType with handle which is None"
super(StructureType, self).__init__(handle, platform, confidence)
struct_handle = core.BNGetTypeStructure(handle)
@@ -1829,8 +1947,11 @@ class StructureType(Type):
self.struct_handle = struct_handle
@classmethod
- def create(cls, members:MembersType=None, packed:bool=False, type:StructureVariant=StructureVariant.StructStructureType,
- platform:'_platform.Platform'=None, confidence:int=core.max_confidence) -> 'StructureType':
+ def create(
+ cls, members: MembersType = None, packed: bool = False,
+ type: StructureVariant = StructureVariant.StructStructureType, platform: '_platform.Platform' = None,
+ confidence: int = core.max_confidence
+ ) -> 'StructureType':
builder = core.BNCreateStructureBuilderWithOptions(type, packed)
assert builder is not None, "core.BNCreateStructureBuilder returned None"
StructureBuilder._add_members_to_builder(builder, members)
@@ -1850,7 +1971,7 @@ class StructureType(Type):
return StructureBuilder(type_builder_handle, structure_builder_handle, self.platform, self.confidence)
@classmethod
- def from_core_struct(cls, structure:core.BNStructure) -> 'StructureType':
+ def from_core_struct(cls, structure: core.BNStructure) -> 'StructureType':
return cls(core.BNNewTypeReference(core.BNCreateStructureType(structure)))
def __del__(self):
@@ -1860,28 +1981,32 @@ class StructureType(Type):
def __hash__(self):
return hash(ctypes.addressof(self.struct_handle.contents))
- def __getitem__(self, name:str) -> StructureMember:
+ def __getitem__(self, name: str) -> StructureMember:
member = None
try:
member = core.BNGetStructureMemberByName(self.struct_handle, name)
if member is None:
raise ValueError(f"Member {name} is not part of structure")
- return StructureMember(Type.create(core.BNNewTypeReference(member.contents.type), confidence=member.contents.typeConfidence),
- member.contents.name, member.contents.offset, MemberAccess(member.contents.access),
- MemberScope(member.contents.scope))
+ return StructureMember(
+ Type.create(core.BNNewTypeReference(member.contents.type), confidence=member.contents.typeConfidence),
+ member.contents.name, member.contents.offset, MemberAccess(member.contents.access),
+ MemberScope(member.contents.scope)
+ )
finally:
if member is not None:
core.BNFreeStructureMember(member)
- def member_at_offset(self, offset:int) -> StructureMember:
+ def member_at_offset(self, offset: int) -> StructureMember:
member = None
try:
member = core.BNGetStructureMemberAtOffset(self.struct_handle, offset, None)
if member is None:
raise ValueError(f"No member exists a offset {offset}")
- return StructureMember(Type.create(core.BNNewTypeReference(member.contents.type), confidence=member.contents.typeConfidence),
- member.contents.name, member.contents.offset, MemberAccess(member.contents.access),
- MemberScope(member.contents.scope))
+ return StructureMember(
+ Type.create(core.BNNewTypeReference(member.contents.type), confidence=member.contents.typeConfidence),
+ member.contents.name, member.contents.offset, MemberAccess(member.contents.access),
+ MemberScope(member.contents.scope)
+ )
finally:
core.BNFreeStructureMember(member)
@@ -1894,9 +2019,13 @@ class StructureType(Type):
try:
result = []
for i in range(0, count.value):
- result.append(StructureMember(Type.create(core.BNNewTypeReference(members[i].type), confidence=members[i].typeConfidence),
- members[i].name, members[i].offset, MemberAccess(members[i].access),
- MemberScope(members[i].scope)))
+ result.append(
+ StructureMember(
+ Type.create(core.BNNewTypeReference(members[i].type), confidence=members[i].typeConfidence),
+ members[i].name, members[i].offset, MemberAccess(members[i].access),
+ MemberScope(members[i].scope)
+ )
+ )
finally:
core.BNFreeStructureMemberList(members, count.value)
return result
@@ -1920,27 +2049,34 @@ class StructureType(Type):
return StructureVariant(core.BNGetStructureType(self.struct_handle))
def with_replaced_structure(self, from_struct, to_struct) -> 'StructureType':
- return StructureType(core.BNStructureWithReplacedStructure(self.struct_handle, from_struct.handle, to_struct.handle))
+ return StructureType(
+ core.BNStructureWithReplacedStructure(self.struct_handle, from_struct.handle, to_struct.handle)
+ )
def with_replaced_enumeration(self, from_enum, to_enum) -> 'StructureType':
- return StructureType(core.BNStructureWithReplacedEnumeration(self.struct_handle, from_enum.handle, to_enum.handle))
+ return StructureType(
+ core.BNStructureWithReplacedEnumeration(self.struct_handle, from_enum.handle, to_enum.handle)
+ )
def with_replaced_named_type_reference(self, from_ref, to_ref) -> 'StructureType':
- return StructureType(core.BNStructureWithReplacedNamedTypeReference(self.struct_handle, from_ref.handle, to_ref.handle))
+ return StructureType(
+ core.BNStructureWithReplacedNamedTypeReference(self.struct_handle, from_ref.handle, to_ref.handle)
+ )
- def generate_named_type_reference(self, guid:str, name:QualifiedName):
+ def generate_named_type_reference(self, guid: str, name: QualifiedName):
if self.type == StructureVariant.StructStructureType:
ntr_type = NamedTypeReferenceClass.StructNamedTypeClass
elif self.type == StructureVariant.UnionStructureType:
ntr_type = NamedTypeReferenceClass.UnionNamedTypeClass
else:
ntr_type = NamedTypeReferenceClass.ClassNamedTypeClass
- return NamedTypeReferenceType.create(ntr_type, guid, name, self.alignment,
- self.width, self.platform, self.confidence)
+ return NamedTypeReferenceType.create(
+ ntr_type, guid, name, self.alignment, self.width, self.platform, self.confidence
+ )
class EnumerationType(IntegerType):
- def __init__(self, handle, platform:'_platform.Platform'=None, confidence:int=core.max_confidence):
+ def __init__(self, handle, platform: '_platform.Platform' = None, confidence: int = core.max_confidence):
assert handle is not None, "Attempted to create EnumerationType without handle"
super(EnumerationType, self).__init__(handle, platform, confidence)
enum_handle = core.BNGetTypeEnumeration(handle)
@@ -1968,9 +2104,11 @@ class EnumerationType(IntegerType):
return result
@classmethod
- def create(cls, members=List[EnumMembersType], width:Optional[int]=None,
- arch:Optional['architecture.Architecture']=None, sign:BoolWithConfidenceType=False,
- platform:'_platform.Platform'=None, confidence:int=core.max_confidence) -> 'EnumerationType':
+ def create(
+ cls, members=List[EnumMembersType], width: Optional[int] = None,
+ arch: Optional['architecture.Architecture'] = None, sign: BoolWithConfidenceType = False,
+ platform: '_platform.Platform' = None, confidence: int = core.max_confidence
+ ) -> 'EnumerationType':
if width is None:
if arch is None:
raise ValueError("One of the following parameters must not be None: (arch, width)")
@@ -1998,10 +2136,9 @@ class EnumerationType(IntegerType):
assert enumeration_builder_handle is not None, "core.BNCreateEnumerationBuilderFromEnumeration returned None"
return EnumerationBuilder(type_builder_handle, enumeration_builder_handle, self.platform, self.confidence)
- def generate_named_type_reference(self, guid:str, name:QualifiedName):
+ def generate_named_type_reference(self, guid: str, name: QualifiedName):
ntr_type = NamedTypeReferenceClass.EnumNamedTypeClass
- return NamedTypeReferenceType.create(ntr_type, guid, name,
- platform=self.platform, confidence=self.confidence)
+ return NamedTypeReferenceType.create(ntr_type, guid, name, platform=self.platform, confidence=self.confidence)
class PointerType(Type):
@@ -2010,16 +2147,19 @@ class PointerType(Type):
return ReferenceType(core.BNTypeGetReferenceType(self._handle))
@classmethod
- def create(cls, arch:'architecture.Architecture', type:SomeType, const:BoolWithConfidenceType=False,
- volatile:BoolWithConfidenceType=False, ref_type:ReferenceType=ReferenceType.PointerReferenceType,
- platform:'_platform.Platform'=None, confidence:int=core.max_confidence) -> 'PointerType':
+ def create(
+ cls, arch: 'architecture.Architecture', type: SomeType, const: BoolWithConfidenceType = False,
+ volatile: BoolWithConfidenceType = False, ref_type: ReferenceType = ReferenceType.PointerReferenceType,
+ platform: '_platform.Platform' = None, confidence: int = core.max_confidence
+ ) -> 'PointerType':
return cls.create_with_width(arch.address_size, type, const, volatile, ref_type, platform, confidence)
@staticmethod
- def from_bools(const:BoolWithConfidenceType, volatile:BoolWithConfidenceType) -> Tuple[BoolWithConfidence, BoolWithConfidence]:
+ def from_bools(const: BoolWithConfidenceType,
+ volatile: BoolWithConfidenceType) -> Tuple[BoolWithConfidence, BoolWithConfidence]:
_const = const
if const is None:
- _const = BoolWithConfidence(False, confidence = 0)
+ _const = BoolWithConfidence(False, confidence=0)
elif isinstance(const, bool):
_const = BoolWithConfidence(const)
if not isinstance(_const, BoolWithConfidence):
@@ -2027,7 +2167,7 @@ class PointerType(Type):
_volatile = volatile
if volatile is None:
- _volatile = BoolWithConfidence(False, confidence = 0)
+ _volatile = BoolWithConfidence(False, confidence=0)
elif isinstance(volatile, bool):
_volatile = BoolWithConfidence(volatile)
if not isinstance(_volatile, BoolWithConfidence):
@@ -2036,17 +2176,20 @@ class PointerType(Type):
return (_const, _volatile)
@classmethod
- def create_with_width(cls, width:int, type:SomeType, const:BoolWithConfidenceType=False,
- volatile:BoolWithConfidenceType=False, ref_type:ReferenceType=None, platform:'_platform.Platform'=None,
- confidence:int=core.max_confidence) -> 'PointerType':
+ def create_with_width(
+ cls, width: int, type: SomeType, const: BoolWithConfidenceType = False,
+ volatile: BoolWithConfidenceType = False, ref_type: ReferenceType = None, platform: '_platform.Platform' = None,
+ confidence: int = core.max_confidence
+ ) -> 'PointerType':
_const, _volatile = PointerType.from_bools(const, volatile)
type = type.immutable_copy()
if ref_type is None:
ref_type = ReferenceType.PointerReferenceType
type_conf = type._to_core_struct()
- core_type = core.BNCreatePointerTypeOfWidth(width, type_conf, _const._to_core_struct(),
- _volatile._to_core_struct(), ref_type)
+ core_type = core.BNCreatePointerTypeOfWidth(
+ width, type_conf, _const._to_core_struct(), _volatile._to_core_struct(), ref_type
+ )
assert core_type is not None, "core.BNCreatePointerTypeOfWidth returned None"
return cls(core.BNNewTypeReference(core_type), platform, confidence)
@@ -2060,7 +2203,10 @@ class PointerType(Type):
class ArrayType(Type):
@classmethod
- def create(cls, element_type:Type, count:int, platform:'_platform.Platform'=None, confidence:int=core.max_confidence) -> 'ArrayType':
+ def create(
+ cls, element_type: Type, count: int, platform: '_platform.Platform' = None,
+ confidence: int = core.max_confidence
+ ) -> 'ArrayType':
type_conf = element_type._to_core_struct()
core_array = core.BNCreateArrayType(type_conf, count)
assert core_array is not None, "core.BNCreateArrayType returned None"
@@ -2080,9 +2226,13 @@ class ArrayType(Type):
class FunctionType(Type):
@classmethod
- def create(cls, ret:Optional[Type]=None, params:ParamsType=None,
- calling_convention:'callingconvention.CallingConvention'=None, variable_arguments:BoolWithConfidenceType=BoolWithConfidence(False),
- stack_adjust:OffsetWithConfidence=OffsetWithConfidence(0), platform:'_platform.Platform'=None, confidence:int=core.max_confidence) -> 'FunctionType':
+ def create(
+ cls, ret: Optional[Type] = None, params: ParamsType = None,
+ calling_convention: 'callingconvention.CallingConvention' = None,
+ variable_arguments: BoolWithConfidenceType = BoolWithConfidence(False),
+ stack_adjust: OffsetWithConfidence = OffsetWithConfidence(0), platform: '_platform.Platform' = None,
+ confidence: int = core.max_confidence
+ ) -> 'FunctionType':
if ret is None:
ret = VoidType.create()
if params is None:
@@ -2100,8 +2250,9 @@ class FunctionType(Type):
_variable_arguments = BoolWithConfidence.get_core_struct(variable_arguments)
_stack_adjust = OffsetWithConfidence.get_core_struct(stack_adjust)
- func_type = core.BNCreateFunctionType(ret_conf, conv_conf, param_buf, len(params),
- _variable_arguments, _stack_adjust)
+ func_type = core.BNCreateFunctionType(
+ ret_conf, conv_conf, param_buf, len(params), _variable_arguments, _stack_adjust
+ )
assert func_type is not None, f"core.BNCreateFunctionType returned None {ret_conf} {conv_conf} {param_buf} {_variable_arguments} {_stack_adjust}"
return cls(core.BNNewTypeReference(func_type), platform, confidence)
@@ -2109,7 +2260,7 @@ class FunctionType(Type):
def stack_adjustment(self) -> OffsetWithConfidence:
"""Stack adjustment for function (read-only)"""
result = core.BNGetTypeStackAdjustment(self._handle)
- return OffsetWithConfidence(result.value, confidence = result.confidence)
+ return OffsetWithConfidence(result.value, confidence=result.confidence)
@property
def return_value(self) -> Type:
@@ -2117,7 +2268,7 @@ class FunctionType(Type):
result = core.BNGetChildType(self._handle)
if result is None:
return Type.void()
- return Type.create(core.BNNewTypeReference(result.type), platform = self._platform, confidence = result.confidence)
+ return Type.create(core.BNNewTypeReference(result.type), platform=self._platform, confidence=result.confidence)
@property
def calling_convention(self) -> Optional[callingconvention.CallingConvention]:
@@ -2125,7 +2276,7 @@ class FunctionType(Type):
result = core.BNGetTypeCallingConvention(self._handle)
if not result.convention:
return None
- return callingconvention.CallingConvention(None, handle = result.convention, confidence = result.confidence)
+ return callingconvention.CallingConvention(None, handle=result.convention, confidence=result.confidence)
@property
def parameters(self) -> List[FunctionParameter]:
@@ -2135,17 +2286,21 @@ class FunctionType(Type):
assert params is not None, "core.BNGetTypeParameters returned None"
result = []
for i in range(0, count.value):
- param_type = Type.create(core.BNNewTypeReference(params[i].type), platform = self._platform, confidence = params[i].typeConfidence)
+ param_type = Type.create(
+ core.BNNewTypeReference(params[i].type), platform=self._platform, confidence=params[i].typeConfidence
+ )
if params[i].defaultLocation:
param_location = None
else:
name = params[i].name
- if (params[i].location.type == VariableSourceType.RegisterVariableSourceType) and (self._platform is not None):
+ if (params[i].location.type
+ == VariableSourceType.RegisterVariableSourceType) and (self._platform is not None):
name = self._platform.arch.get_reg_name(params[i].location.storage)
elif params[i].location.type == VariableSourceType.StackVariableSourceType:
name = "arg_%x" % params[i].location.storage
- param_location = variable.VariableNameAndType(params[i].location.type, params[i].location.index,
- params[i].location.storage, name, param_type)
+ param_location = variable.VariableNameAndType(
+ params[i].location.type, params[i].location.index, params[i].location.storage, name, param_type
+ )
result.append(FunctionParameter(param_type, params[i].name, param_location))
core.BNFreeTypeParameterList(params, count.value)
return result
@@ -2154,17 +2309,19 @@ class FunctionType(Type):
def has_variable_arguments(self) -> BoolWithConfidence:
"""Whether type has variable arguments (read-only)"""
result = core.BNTypeHasVariableArguments(self._handle)
- return BoolWithConfidence(result.value, confidence = result.confidence)
+ return BoolWithConfidence(result.value, confidence=result.confidence)
@property
def can_return(self) -> BoolWithConfidence:
"""Whether type can return"""
result = core.BNFunctionTypeCanReturn(self._handle)
- return BoolWithConfidence(result.value, confidence = result.confidence)
+ return BoolWithConfidence(result.value, confidence=result.confidence)
class NamedTypeReferenceType(Type):
- def __init__(self, handle, platform:'_platform.Platform'=None, confidence:int=core.max_confidence, ntr_handle=None):
+ def __init__(
+ self, handle, platform: '_platform.Platform' = None, confidence: int = core.max_confidence, ntr_handle=None
+ ):
assert handle is not None, "Attempting to create NamedTypeReferenceType handle which is None"
super(NamedTypeReferenceType, self).__init__(handle, platform, confidence)
if ntr_handle is None:
@@ -2175,14 +2332,18 @@ class NamedTypeReferenceType(Type):
def mutable_copy(self):
type_builder_handle = core.BNCreateTypeBuilderFromType(self._handle)
assert type_builder_handle is not None, "core.BNCreateTypeBuilderFromType returned None"
- ntr_builder_handle = core.BNCreateNamedTypeBuilder(self.named_type_class, self.type_id, self.name._to_core_struct())
+ ntr_builder_handle = core.BNCreateNamedTypeBuilder(
+ self.named_type_class, self.type_id, self.name._to_core_struct()
+ )
assert ntr_builder_handle is not None, "core.BNCreateNamedTypeBuilder returned None"
return NamedTypeReferenceBuilder(type_builder_handle, ntr_builder_handle, self.platform, self.confidence)
@classmethod
- def create(cls, named_type_class:NamedTypeReferenceClass, guid:Optional[str],
- name:QualifiedName, alignment:int=0, width:int=0, platform:'_platform.Platform'=None,
- confidence:int=core.max_confidence, const:BoolWithConfidenceType=False, volatile:BoolWithConfidenceType=False) -> 'NamedTypeReferenceType':
+ def create(
+ cls, named_type_class: NamedTypeReferenceClass, guid: Optional[str], name: QualifiedName, alignment: int = 0,
+ width: int = 0, platform: '_platform.Platform' = None, confidence: int = core.max_confidence,
+ const: BoolWithConfidenceType = False, volatile: BoolWithConfidenceType = False
+ ) -> 'NamedTypeReferenceType':
_guid = guid
if guid is None:
_guid = str(uuid.uuid4())
@@ -2198,8 +2359,10 @@ class NamedTypeReferenceType(Type):
return cls(core.BNNewTypeReference(core_type), platform, confidence)
@classmethod
- def create_from_type(cls, name:QualifiedName, type:Optional[Type], guid:Optional[str]=None,
- platform:'_platform.Platform'=None, confidence:int=core.max_confidence) -> 'NamedTypeReferenceType':
+ def create_from_type(
+ cls, name: QualifiedName, type: Optional[Type], guid: Optional[str] = None,
+ platform: '_platform.Platform' = None, confidence: int = core.max_confidence
+ ) -> 'NamedTypeReferenceType':
_guid = guid
if _guid is None:
_guid = str(uuid.uuid4())
@@ -2210,8 +2373,10 @@ class NamedTypeReferenceType(Type):
return type.generate_named_type_reference(_guid, name)
@classmethod
- def create_from_registered_type(cls, view:'binaryview.BinaryView', name:QualifiedName,
- platform:'_platform.Platform'=None, confidence:int=core.max_confidence) -> 'NamedTypeReferenceType':
+ def create_from_registered_type(
+ cls, view: 'binaryview.BinaryView', name: QualifiedName, platform: '_platform.Platform' = None,
+ confidence: int = core.max_confidence
+ ) -> 'NamedTypeReferenceType':
_name = QualifiedName(name)._to_core_struct()
core_type = core.BNCreateNamedTypeReferenceFromType(view.handle, _name)
assert core_type is not None, "core.BNCreateNamedTypeReferenceFromType returned None"
@@ -2262,16 +2427,16 @@ class NamedTypeReferenceType(Type):
return result
@staticmethod
- def generate_auto_type_ref(type_class:NamedTypeReferenceClass, source:str, name:QualifiedNameType):
+ def generate_auto_type_ref(type_class: NamedTypeReferenceClass, source: str, name: QualifiedNameType):
type_id = Type.generate_auto_type_id(source, name)
return NamedTypeReferenceType.create(type_class, type_id, name)
@staticmethod
- def generate_auto_demangled_type_ref(type_class:NamedTypeReferenceClass, name:QualifiedNameType):
+ def generate_auto_demangled_type_ref(type_class: NamedTypeReferenceClass, name: QualifiedNameType):
type_id = Type.generate_auto_demangled_type_id(name)
return NamedTypeReferenceType.create(type_class, type_id, name)
- def _target_helper(self, bv:'binaryview.BinaryView', type_ids=None) -> Optional[Type]:
+ def _target_helper(self, bv: 'binaryview.BinaryView', type_ids=None) -> Optional[Type]:
t = bv.get_type_by_id(self.type_id)
if t is None:
return None
@@ -2285,7 +2450,7 @@ class NamedTypeReferenceType(Type):
else:
return t
- def target(self, bv:'binaryview.BinaryView') -> Optional[Type]:
+ def target(self, bv: 'binaryview.BinaryView') -> Optional[Type]:
"""Returns the type pointed to by the current type
:param bv: The BinaryView in which this type is defined.
@@ -2298,8 +2463,10 @@ class NamedTypeReferenceType(Type):
class WideCharType(Type):
@classmethod
- def create(cls, width:int, alternate_name:str="", platform:'_platform.Platform'=None,
- confidence:int=core.max_confidence) -> 'WideCharType':
+ def create(
+ cls, width: int, alternate_name: str = "", platform: '_platform.Platform' = None,
+ confidence: int = core.max_confidence
+ ) -> 'WideCharType':
"""
``wide_char`` class method for creating wide char Types.
@@ -2310,24 +2477,20 @@ class WideCharType(Type):
assert core_type is not None, "core.BNCreateWideCharType returned None"
return cls(core.BNNewTypeReference(core_type), platform, confidence)
+
Types = {
- TypeClass.VoidTypeClass:VoidType,
- TypeClass.BoolTypeClass:BoolType,
- TypeClass.IntegerTypeClass:IntegerType,
- TypeClass.FloatTypeClass:FloatType,
- TypeClass.StructureTypeClass:StructureType,
- TypeClass.EnumerationTypeClass:EnumerationType,
- TypeClass.PointerTypeClass:PointerType,
- TypeClass.ArrayTypeClass:ArrayType,
- TypeClass.FunctionTypeClass:FunctionType,
- TypeClass.NamedTypeReferenceClass:NamedTypeReferenceType,
- TypeClass.WideCharTypeClass:WideCharType,
+ TypeClass.VoidTypeClass: VoidType, TypeClass.BoolTypeClass: BoolType, TypeClass.IntegerTypeClass: IntegerType,
+ TypeClass.FloatTypeClass: FloatType, TypeClass.StructureTypeClass: StructureType,
+ TypeClass.EnumerationTypeClass: EnumerationType, TypeClass.PointerTypeClass: PointerType,
+ TypeClass.ArrayTypeClass: ArrayType, TypeClass.FunctionTypeClass: FunctionType,
+ TypeClass.NamedTypeReferenceClass: NamedTypeReferenceType, TypeClass.WideCharTypeClass: WideCharType,
}
+
@dataclass(frozen=True)
class RegisterSet:
- regs:List['architecture.RegisterName']
- confidence:int=core.max_confidence
+ regs: List['architecture.RegisterName']
+ confidence: int = core.max_confidence
def __iter__(self) -> Generator['architecture.RegisterName', None, None]:
for reg in self.regs:
@@ -2345,15 +2508,16 @@ class RegisterSet:
@dataclass(frozen=True)
class TypeParserResult:
- types:Mapping[QualifiedName, Type]
- variables:Mapping[QualifiedName, Type]
- functions:Mapping[QualifiedName, Type]
+ types: Mapping[QualifiedName, Type]
+ variables: Mapping[QualifiedName, Type]
+ functions: Mapping[QualifiedName, Type]
def __repr__(self):
return f"<types: {self.types}, variables: {self.variables}, functions: {self.functions}>"
-def preprocess_source(source:str, filename:str=None, include_dirs:Optional[List[str]]=None) -> Tuple[Optional[str], str]:
+def preprocess_source(source: str, filename: str = None,
+ include_dirs: Optional[List[str]] = None) -> Tuple[Optional[str], str]:
"""
``preprocess_source`` run the C preprocessor on the given source or source filename.
@@ -2393,11 +2557,11 @@ def preprocess_source(source:str, filename:str=None, include_dirs:Optional[List[
@dataclass(frozen=True)
class TypeFieldReference:
- func:Optional['_function.Function']
- arch:Optional['architecture.Architecture']
- address:int
- size:int
- incomingType:Optional[Type]
+ func: Optional['_function.Function']
+ arch: Optional['architecture.Architecture']
+ address: int
+ size: int
+ incomingType: Optional[Type]
def __repr__(self):
if self.arch:
diff --git a/python/update.py b/python/update.py
index 1c91e700..db4d66ee 100644
--- a/python/update.py
+++ b/python/update.py
@@ -28,7 +28,6 @@ from .enums import UpdateResult
from .log import log_error
-
class _UpdateChannelMetaClass(type):
def __iter__(self):
binaryninja._init_plugins()
@@ -69,7 +68,8 @@ class _UpdateChannelMetaClass(type):
class UpdateProgressCallback:
def __init__(self, func):
- self.cb = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_ulonglong, ctypes.c_ulonglong)(self.callback)
+ self.cb = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_ulonglong,
+ ctypes.c_ulonglong)(self.callback)
self.func = func
def callback(self, ctxt, progress, total):
@@ -85,9 +85,10 @@ class UpdateProgressCallback:
return core.BNGetActiveUpdateChannel()
@active.setter
- def active(cls, value:str) -> None:
+ def active(cls, value: str) -> None:
return core.BNSetActiveUpdateChannel(value)
+
class UpdateChannel(metaclass=_UpdateChannelMetaClass):
def __init__(self, name, desc, ver):
self._name = name
@@ -153,7 +154,7 @@ class UpdateChannel(metaclass=_UpdateChannelMetaClass):
def __str__(self):
return self._name
- def update_to_latest(self, progress = None):
+ def update_to_latest(self, progress=None):
cb = UpdateProgressCallback(progress)
errors = ctypes.c_char_p()
result = core.BNUpdateToLatestVersion(self._name, errors, cb.cb, None)
@@ -201,7 +202,7 @@ class UpdateVersion:
def __str__(self):
return self._version
- def update(self, progress = None):
+ def update(self, progress=None):
cb = UpdateProgressCallback(progress)
errors = ctypes.c_char_p()
result = core.BNUpdateToVersion(self._channel.name, self._version, errors, cb.cb, None)
diff --git a/python/variable.py b/python/variable.py
index 67dc2cac..564281c6 100644
--- a/python/variable.py
+++ b/python/variable.py
@@ -28,17 +28,16 @@ from . import _binaryninjacore as core
from . import decorators
from .enums import RegisterValueType, VariableSourceType, DeadStoreElimination, FunctionGraphType
-FunctionOrILFunction = Union["binaryninja.function.Function",
- "binaryninja.lowlevelil.LowLevelILFunction",
+FunctionOrILFunction = Union["binaryninja.function.Function", "binaryninja.lowlevelil.LowLevelILFunction",
"binaryninja.mediumlevelil.MediumLevelILFunction",
"binaryninja.highlevelil.HighLevelILFunction"]
@dataclass(frozen=True)
class LookupTableEntry:
- from_values:List[int]
- to_value:int
- type:RegisterValueType = RegisterValueType.LookupTableValue
+ from_values: List[int]
+ to_value: int
+ type: RegisterValueType = RegisterValueType.LookupTableValue
def __repr__(self):
return f"[{', '.join([f'{i:#x}' for i in self.from_values])}] -> {self.to_value:#x}"
@@ -46,10 +45,10 @@ class LookupTableEntry:
@dataclass(frozen=True)
class RegisterValue:
- value:int
- offset:int
- type:RegisterValueType = RegisterValueType.UndeterminedValue
- confidence:int=core.max_confidence
+ value: int
+ offset: int
+ type: RegisterValueType = RegisterValueType.UndeterminedValue
+ confidence: int = core.max_confidence
def _to_core_struct(self) -> core.BNRegisterValue:
result = core.BNRegisterValue()
@@ -76,13 +75,15 @@ class RegisterValue:
elif isinstance(other, bool):
return bool(self) == other
elif isinstance(other, self.__class__):
- return (self.type, self.offset, self.type, self.confidence) == \
- (other.type, other.offset, other.type, other.confidence)
+ return (self.type, self.offset, self.type,
+ self.confidence) == (other.type, other.offset, other.type, other.confidence)
assert False, f"no comparison for types {repr(self)} and {repr(other)}"
@classmethod
- def from_BNRegisterValue(cls, reg_value:Union[core.BNRegisterValue, core.BNRegisterValueWithConfidence],
- arch:Optional['binaryninja.architecture.Architecture']=None) -> 'RegisterValue':
+ def from_BNRegisterValue(
+ cls, reg_value: Union[core.BNRegisterValue, core.BNRegisterValueWithConfidence],
+ arch: Optional['binaryninja.architecture.Architecture'] = None
+ ) -> 'RegisterValue':
confidence = core.max_confidence
if isinstance(reg_value, core.BNRegisterValueWithConfidence):
confidence = reg_value.confidence
@@ -111,9 +112,9 @@ class RegisterValue:
@dataclass(frozen=True, eq=False)
class Undetermined(RegisterValue):
- value:int = 0
- offset:int = 0
- type:RegisterValueType = RegisterValueType.UndeterminedValue
+ value: int = 0
+ offset: int = 0
+ type: RegisterValueType = RegisterValueType.UndeterminedValue
def __repr__(self):
return "<undetermined>"
@@ -121,8 +122,8 @@ class Undetermined(RegisterValue):
@dataclass(frozen=True, eq=False)
class ConstantRegisterValue(RegisterValue):
- offset:int = 0
- type:RegisterValueType = RegisterValueType.ConstantValue
+ offset: int = 0
+ type: RegisterValueType = RegisterValueType.ConstantValue
def __repr__(self):
return f"<const {self.value:#x}>"
@@ -130,8 +131,8 @@ class ConstantRegisterValue(RegisterValue):
@dataclass(frozen=True, eq=False)
class ConstantPointerRegisterValue(RegisterValue):
- offset:int = 0
- type:RegisterValueType = RegisterValueType.ConstantPointerValue
+ offset: int = 0
+ type: RegisterValueType = RegisterValueType.ConstantPointerValue
def __repr__(self):
return f"<const ptr {self.value:#x}>"
@@ -139,8 +140,8 @@ class ConstantPointerRegisterValue(RegisterValue):
@dataclass(frozen=True, eq=False)
class ImportedAddressRegisterValue(RegisterValue):
- offset:int = 0
- type:RegisterValueType = RegisterValueType.ImportedAddressValue
+ offset: int = 0
+ type: RegisterValueType = RegisterValueType.ImportedAddressValue
def __repr__(self):
return f"<imported address from entry {self.value:#x}>"
@@ -148,8 +149,8 @@ class ImportedAddressRegisterValue(RegisterValue):
@dataclass(frozen=True, eq=False)
class ReturnAddressRegisterValue(RegisterValue):
- offset:int = 0
- type:RegisterValueType = RegisterValueType.ReturnAddressValue
+ offset: int = 0
+ type: RegisterValueType = RegisterValueType.ReturnAddressValue
def __repr__(self):
return "<return address>"
@@ -157,10 +158,10 @@ class ReturnAddressRegisterValue(RegisterValue):
@dataclass(frozen=True, eq=False)
class EntryRegisterValue(RegisterValue):
- value:int = 0
- offset:int = 0
- type:RegisterValueType = RegisterValueType.EntryValue
- reg:Optional['binaryninja.architecture.RegisterName'] = None
+ value: int = 0
+ offset: int = 0
+ type: RegisterValueType = RegisterValueType.EntryValue
+ reg: Optional['binaryninja.architecture.RegisterName'] = None
def __repr__(self):
if self.reg is not None:
@@ -170,15 +171,16 @@ class EntryRegisterValue(RegisterValue):
@dataclass(frozen=True, eq=False)
class StackFrameOffsetRegisterValue(RegisterValue):
- offset:int = 0
- type:RegisterValueType = RegisterValueType.StackFrameOffset
+ offset: int = 0
+ type: RegisterValueType = RegisterValueType.StackFrameOffset
def __repr__(self):
return f"<stack frame offset {self.value:#x}>"
+
@dataclass(frozen=True, eq=False)
class ExternalPointerRegisterValue(RegisterValue):
- type:RegisterValueType = RegisterValueType.ExternalPointerValue
+ type: RegisterValueType = RegisterValueType.ExternalPointerValue
def __repr__(self):
return f"<external {self.value:#x} + offset {self.offset:#x}>"
@@ -186,9 +188,9 @@ class ExternalPointerRegisterValue(RegisterValue):
@dataclass(frozen=True)
class ValueRange:
- start:int
- end:int
- step:int
+ start: int
+ end: int
+ step: int
def __repr__(self):
if self.step == 1:
@@ -208,7 +210,7 @@ class PossibleValueSet:
that a variable can take. It contains methods to instantiate different
value sets such as Constant, Signed/Unsigned Ranges, etc.
"""
- def __init__(self, arch = None, value = None):
+ def __init__(self, arch=None, value=None):
if value is None:
self._type = RegisterValueType.UndeterminedValue
return
@@ -283,9 +285,11 @@ class PossibleValueSet:
return "<undetermined>"
def __contains__(self, other):
- if self.type in [RegisterValueType.ConstantValue, RegisterValueType.ConstantPointerValue] and isinstance(other, int):
+ if self.type in [RegisterValueType.ConstantValue, RegisterValueType.ConstantPointerValue
+ ] and isinstance(other, int):
return self.value == other
- if self.type in [RegisterValueType.ConstantValue, RegisterValueType.ConstantPointerValue] and hasattr(other, "value"):
+ if self.type in [RegisterValueType.ConstantValue, RegisterValueType.ConstantPointerValue
+ ] and hasattr(other, "value"):
return self.value == other.value
if not isinstance(other, int):
return NotImplemented
@@ -304,7 +308,8 @@ class PossibleValueSet:
return NotImplemented
def __eq__(self, other):
- if self.type in [RegisterValueType.ConstantValue, RegisterValueType.ConstantPointerValue] and isinstance(other, int):
+ if self.type in [RegisterValueType.ConstantValue, RegisterValueType.ConstantPointerValue
+ ] and isinstance(other, int):
return self.value == other
if not isinstance(other, self.__class__):
return NotImplemented
@@ -431,7 +436,7 @@ class PossibleValueSet:
return PossibleValueSet()
@staticmethod
- def constant(value:int) -> 'PossibleValueSet':
+ def constant(value: int) -> 'PossibleValueSet':
"""
Create a constant valued PossibleValueSet object.
@@ -444,7 +449,7 @@ class PossibleValueSet:
return result
@staticmethod
- def constant_ptr(value:int) -> 'PossibleValueSet':
+ def constant_ptr(value: int) -> 'PossibleValueSet':
"""
Create constant pointer valued PossibleValueSet object.
@@ -457,7 +462,7 @@ class PossibleValueSet:
return result
@staticmethod
- def stack_frame_offset(offset:int) -> 'PossibleValueSet':
+ def stack_frame_offset(offset: int) -> 'PossibleValueSet':
"""
Create a PossibleValueSet object for a stack frame offset.
@@ -470,7 +475,7 @@ class PossibleValueSet:
return result
@staticmethod
- def signed_range_value(ranges:List[ValueRange]) -> 'PossibleValueSet':
+ def signed_range_value(ranges: List[ValueRange]) -> 'PossibleValueSet':
"""
Create a PossibleValueSet object for a signed range of values.
@@ -491,7 +496,7 @@ class PossibleValueSet:
return result
@staticmethod
- def unsigned_range_value(ranges:List[ValueRange]) -> 'PossibleValueSet':
+ def unsigned_range_value(ranges: List[ValueRange]) -> 'PossibleValueSet':
"""
Create a PossibleValueSet object for a unsigned signed range of values.
@@ -512,7 +517,7 @@ class PossibleValueSet:
return result
@staticmethod
- def in_set_of_values(values:Union[List[int], Set[int]]) -> 'PossibleValueSet':
+ def in_set_of_values(values: Union[List[int], Set[int]]) -> 'PossibleValueSet':
"""
Create a PossibleValueSet object for a value in a set of values.
@@ -558,12 +563,12 @@ class PossibleValueSet:
@dataclass(frozen=True)
class StackVariableReference:
- _source_operand:Optional[int]
- type:'binaryninja.types.Type'
- name:str
- var:'Variable'
- referenced_offset:int
- size:int
+ _source_operand: Optional[int]
+ type: 'binaryninja.types.Type'
+ name: str
+ var: 'Variable'
+ referenced_offset: int
+ size: int
def __repr__(self):
if self.source_operand is None:
@@ -583,9 +588,9 @@ class StackVariableReference:
@dataclass(frozen=True, order=True)
class CoreVariable:
- _source_type:int
- index:int
- storage:int
+ _source_type: int
+ index: int
+ storage: int
@property
def identifier(self) -> int:
@@ -603,7 +608,7 @@ class CoreVariable:
return v
@classmethod
- def from_BNVariable(cls, var:core.BNVariable):
+ def from_BNVariable(cls, var: core.BNVariable):
return cls(var.type, var.index, var.storage)
@classmethod
@@ -614,8 +619,8 @@ class CoreVariable:
@dataclass(frozen=True, order=True)
class VariableNameAndType(CoreVariable):
- name:str
- type:'binaryninja.types.Type'
+ name: str
+ type: 'binaryninja.types.Type'
@classmethod
def from_identifier(cls, identifier, name, type):
@@ -628,7 +633,7 @@ class VariableNameAndType(CoreVariable):
class Variable(CoreVariable):
- def __init__(self, func:FunctionOrILFunction, source_type:VariableSourceType, index:int, storage:int):
+ def __init__(self, func: FunctionOrILFunction, source_type: VariableSourceType, index: int, storage: int):
super(Variable, self).__init__(int(source_type), index, storage)
if isinstance(func, binaryninja.function.Function):
self._function = func
@@ -638,19 +643,19 @@ class Variable(CoreVariable):
self._il_function = func
@classmethod
- def from_variable_name_and_type(cls, func:FunctionOrILFunction, var:VariableNameAndType):
+ def from_variable_name_and_type(cls, func: FunctionOrILFunction, var: VariableNameAndType):
return cls(func, VariableSourceType(var.type), var.index, var.storage)
@classmethod
- def from_core_variable(cls, func:FunctionOrILFunction, var:CoreVariable):
+ def from_core_variable(cls, func: FunctionOrILFunction, var: CoreVariable):
return cls(func, var.source_type, var.index, var.storage)
@classmethod
- def from_BNVariable(cls, func:FunctionOrILFunction, var:core.BNVariable):
+ def from_BNVariable(cls, func: FunctionOrILFunction, var: core.BNVariable):
return cls(func, var.type, var.index, var.storage)
@classmethod
- def from_identifier(cls, func:FunctionOrILFunction, identifier:int):
+ def from_identifier(cls, func: FunctionOrILFunction, identifier: int):
var = core.BNFromVariableIdentifier(identifier)
return cls(func, VariableSourceType(var.type), var.index, var.storage)
@@ -710,7 +715,7 @@ class Variable(CoreVariable):
return core.BNGetRealVariableName(self._function.handle, self._function.arch.handle, self.to_BNVariable())
@name.setter
- def name(self, name:Optional[str]) -> None:
+ def name(self, name: Optional[str]) -> None:
self.set_name_async(name)
self._function.view.update_analysis_and_wait()
@@ -724,7 +729,7 @@ class Variable(CoreVariable):
return None
@type.setter
- def type(self, new_type:'binaryninja.types.Type') -> None:
+ def type(self, new_type: 'binaryninja.types.Type') -> None:
self.set_type_async(new_type)
self._function.view.update_analysis_and_wait()
@@ -735,10 +740,18 @@ class Variable(CoreVariable):
raise NotImplementedError("No IL function associated with variable")
version_count = ctypes.c_ulonglong()
- if self._il_function.il_form in [FunctionGraphType.MediumLevelILFunctionGraph, FunctionGraphType.MediumLevelILSSAFormFunctionGraph]:
- versions = core.BNGetMediumLevelILVariableSSAVersions(self._il_function.handle, self.to_BNVariable(), version_count)
- elif self._il_function.il_form in [FunctionGraphType.HighLevelILFunctionGraph, FunctionGraphType.HighLevelILSSAFormFunctionGraph]:
- versions = core.BNGetHighLevelILVariableSSAVersions(self._il_function.handle, self.to_BNVariable(), version_count)
+ if self._il_function.il_form in [
+ FunctionGraphType.MediumLevelILFunctionGraph, FunctionGraphType.MediumLevelILSSAFormFunctionGraph
+ ]:
+ versions = core.BNGetMediumLevelILVariableSSAVersions(
+ self._il_function.handle, self.to_BNVariable(), version_count
+ )
+ elif self._il_function.il_form in [
+ FunctionGraphType.HighLevelILFunctionGraph, FunctionGraphType.HighLevelILSSAFormFunctionGraph
+ ]:
+ versions = core.BNGetHighLevelILVariableSSAVersions(
+ self._il_function.handle, self.to_BNVariable(), version_count
+ )
else:
raise NotImplementedError("Unsupported IL form")
@@ -753,7 +766,9 @@ class Variable(CoreVariable):
@property
def dead_store_elimination(self) -> DeadStoreElimination:
- return DeadStoreElimination(core.BNGetFunctionVariableDeadStoreElimination(self._function.handle, self.to_BNVariable()))
+ return DeadStoreElimination(
+ core.BNGetFunctionVariableDeadStoreElimination(self._function.handle, self.to_BNVariable())
+ )
@dead_store_elimination.setter
def dead_store_elimination(self, value):
@@ -764,7 +779,7 @@ class Variable(CoreVariable):
"""returns the source Function object which this variable belongs to"""
return self._function
- def set_name_async(self, name:Optional[str]) -> None:
+ def set_name_async(self, name: Optional[str]) -> None:
"""
``set_name_async`` provides a way to asynchronously set the name of a variable. This method should be used
when speed is of concern.
@@ -773,14 +788,14 @@ class Variable(CoreVariable):
name = ""
self._function.create_user_var(self, self.type, name)
- def set_type_async(self, new_type:'binaryninja.types.Type') -> None:
+ def set_type_async(self, new_type: 'binaryninja.types.Type') -> None:
"""
``set_type_async`` provides a way to asynchronously set the type of a variable. This method should be used
when speed is of concern.
"""
self._function.create_user_var(self, new_type, self.name)
- def set_name_and_type_async(self, name:Optional[str], new_type:'binaryninja.types.Type') -> None:
+ def set_name_and_type_async(self, name: Optional[str], new_type: 'binaryninja.types.Type') -> None:
"""
``set_name_and_type_async`` provides a way to asynchronously set both the name and type of a variable. This method should be used
when speed is of concern.
@@ -790,10 +805,10 @@ class Variable(CoreVariable):
@dataclass(frozen=True)
class ConstantReference:
- value:int
- size:int
- pointer:bool
- intermediate:bool
+ value: int
+ size: int
+ pointer: bool
+ intermediate: bool
def __repr__(self):
if self.pointer:
@@ -805,11 +820,11 @@ class ConstantReference:
@dataclass(frozen=True)
class IndirectBranchInfo:
- source_arch:'binaryninja.architecture.Architecture'
- source_addr:int
- dest_arch:'binaryninja.architecture.Architecture'
- dest_addr:int
- auto_defined:bool
+ source_arch: 'binaryninja.architecture.Architecture'
+ source_addr: int
+ dest_arch: 'binaryninja.architecture.Architecture'
+ dest_addr: int
+ auto_defined: bool
def __repr__(self):
return f"<branch {self.source_arch.name}:{self.source_addr:#x} -> {self.dest_arch.name}:{self.dest_addr:#x}>"
@@ -817,7 +832,10 @@ class IndirectBranchInfo:
@decorators.passive
class ParameterVariables:
- def __init__(self, var_list:List[Variable], confidence:int=core.max_confidence, func:Optional['binaryninja.function.Function']=None):
+ def __init__(
+ self, var_list: List[Variable], confidence: int = core.max_confidence,
+ func: Optional['binaryninja.function.Function'] = None
+ ):
self._vars = var_list
self._confidence = confidence
self._func = func
@@ -835,12 +853,12 @@ class ParameterVariables:
def __getitem__(self, idx) -> 'Variable':
return self._vars[idx]
- def __setitem__(self, idx:int, value:'Variable'):
+ def __setitem__(self, idx: int, value: 'Variable'):
self._vars[idx] = value
if self._func is not None:
self._func.parameter_vars = self
- def with_confidence(self, confidence:int) -> 'ParameterVariables':
+ def with_confidence(self, confidence: int) -> 'ParameterVariables':
return ParameterVariables(list(self._vars), confidence, self._func)
@property
@@ -858,11 +876,11 @@ class ParameterVariables:
@dataclass(frozen=True, order=True)
class AddressRange:
- start:int # Inclusive starting address
- end:int # Exclusive ending address
+ start: int # Inclusive starting address
+ end: int # Exclusive ending address
def __repr__(self):
return f"<{self.start:#x}-{self.end:#x}>"
- def __contains__(self, i:int):
- return self.start <= i < self.end \ No newline at end of file
+ def __contains__(self, i: int):
+ return self.start <= i < self.end
diff --git a/python/websocketprovider.py b/python/websocketprovider.py
index 3d5d194e..0a143562 100644
--- a/python/websocketprovider.py
+++ b/python/websocketprovider.py
@@ -18,7 +18,6 @@
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
-
import abc
import ctypes
from json import loads, dumps
@@ -37,7 +36,6 @@ import binaryninja
from .log import log_error
-
def nop(*args, **kwargs):
pass
@@ -53,7 +51,7 @@ def to_bytes(field):
class WebsocketClient(object):
_registered_clients = []
- def __init__(self, provider, handle = None):
+ def __init__(self, provider, handle=None):
if handle is None:
self._cb = core.BNWebsocketClientCallbacks()
self._cb.context = 0
@@ -179,7 +177,9 @@ class WebsocketClient(object):
self.io_callbacks = core.BNWebsocketClientOutputCallbacks()
self.io_callbacks.context = 0
self.io_callbacks.connectedCallback = self.io_callbacks.connectedCallback.__class__(self._connected_callback)
- self.io_callbacks.disconnectedCallback = self.io_callbacks.disconnectedCallback.__class__(self._disconnected_callback)
+ self.io_callbacks.disconnectedCallback = self.io_callbacks.disconnectedCallback.__class__(
+ self._disconnected_callback
+ )
self.io_callbacks.errorCallback = self.io_callbacks.errorCallback.__class__(self._error_callback)
self.io_callbacks.readCallback = self.io_callbacks.readCallback.__class__(self._read_callback)
@@ -188,7 +188,9 @@ class WebsocketClient(object):
self.on_error = on_error
self.on_data = on_data
- return core.BNConnectWebsocketClient(self.handle, url, len(headers), header_keys, header_values, self.io_callbacks)
+ return core.BNConnectWebsocketClient(
+ self.handle, url, len(headers), header_keys, header_values, self.io_callbacks
+ )
def write(self, data):
"""
@@ -198,7 +200,9 @@ class WebsocketClient(object):
:return: true if successful
:rtype: bool
"""
- return core.BNWriteWebsocketClientData(self.handle, (ctypes.c_ubyte * len(data)).from_buffer_copy(data), len(data))
+ return core.BNWriteWebsocketClientData(
+ self.handle, (ctypes.c_ubyte * len(data)).from_buffer_copy(data), len(data)
+ )
def disconnect(self):
"""
@@ -209,6 +213,7 @@ class WebsocketClient(object):
"""
return core.BNDisconnectWebsocketClient(self.handle)
+
class _WebsocketProviderMetaclass(type):
@property
def list(self):
@@ -251,7 +256,7 @@ class WebsocketProvider(metaclass=_WebsocketProviderMetaclass):
instance_class = None
_registered_providers = []
- def __init__(self, handle = None):
+ def __init__(self, handle=None):
if handle is not None:
self.handle = core.handle_of_type(handle, core.BNWebsocketProvider)
self.__dict__["name"] = core.BNGetWebsocketProviderName(handle)
diff --git a/python/workflow.py b/python/workflow.py
index b9c38e35..89e0f186 100644
--- a/python/workflow.py
+++ b/python/workflow.py
@@ -30,16 +30,23 @@ from .flowgraph import FlowGraph, CoreFlowGraph
ActivityType = Union['Activity', str]
+
class Activity(object):
"""
:class:`Activity`
"""
_action_callbacks = {}
- def __init__(self, name:str = "", handle:Optional[core.BNActivityHandle] = None, action:Optional[Callable[[Any], None]] = None):
+
+ def __init__(
+ self, name: str = "", handle: Optional[core.BNActivityHandle] = None, action: Optional[Callable[[Any],
+ None]] = None
+ ):
if handle is None:
#cls._notify(ac, callback)
- action_callback = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(core.BNAnalysisContext))(lambda ctxt, ac: self._action(ac))
+ action_callback = ctypes.CFUNCTYPE(None, ctypes.c_void_p,
+ ctypes.POINTER(core.BNAnalysisContext
+ ))(lambda ctxt, ac: self._action(ac))
_handle = core.BNCreateActivity(name, None, action_callback)
self.action = action
self.__class__._action_callbacks[len(self.__class__._action_callbacks)] = action_callback
@@ -49,7 +56,7 @@ class Activity(object):
self.handle = _handle
self._name = name
- def _action(self, ac:Any):
+ def _action(self, ac: Any):
try:
if self.action is not None:
self.action(ac)
@@ -100,7 +107,7 @@ class _WorkflowMetaclass(type):
for i in range(0, count.value):
handle = core.BNNewWorkflowReference(workflows[i])
assert handle is not None, "core.BNNewWorkflowReference returned None"
- result.append(Workflow(handle = handle))
+ result.append(Workflow(handle=handle))
return result
finally:
core.BNFreeWorkflowList(workflows, count.value)
@@ -114,14 +121,14 @@ class _WorkflowMetaclass(type):
for i in range(0, count.value):
handle = core.BNNewWorkflowReference(workflows[i])
assert handle is not None, "core.BNNewWorkflowReference returned None"
- yield Workflow(handle = handle)
+ yield Workflow(handle=handle)
finally:
core.BNFreeWorkflowList(workflows, count.value)
def __getitem__(self, value):
binaryninja._init_plugins()
workflow = core.BNWorkflowInstance(str(value))
- return Workflow(handle = workflow)
+ return Workflow(handle=workflow)
class Workflow(metaclass=_WorkflowMetaclass):
@@ -165,8 +172,7 @@ class Workflow(metaclass=_WorkflowMetaclass):
>>> Workflow().show_documentation()
"""
-
- def __init__(self, name:str = "", handle:core.BNWorkflowHandle = None, query_registry:bool = True):
+ def __init__(self, name: str = "", handle: core.BNWorkflowHandle = None, query_registry: bool = True):
if handle is None:
if query_registry:
_handle = core.BNWorkflowInstance(str(name))
@@ -211,7 +217,7 @@ class Workflow(metaclass=_WorkflowMetaclass):
def __hash__(self):
return hash(ctypes.addressof(self.handle.contents))
- def register(self, description:str = "") -> bool:
+ def register(self, description: str = "") -> bool:
"""
``register`` Register this Workflow, making it immutable and available for use.
@@ -221,7 +227,7 @@ class Workflow(metaclass=_WorkflowMetaclass):
"""
return core.BNRegisterWorkflow(self.handle, str(description))
- def clone(self, name:str, activity:ActivityType = "") -> "Workflow":
+ def clone(self, name: str, activity: ActivityType = "") -> "Workflow":
"""
``clone`` Clone a new Workflow, copying all Activities and the execution strategy.
@@ -231,9 +237,10 @@ class Workflow(metaclass=_WorkflowMetaclass):
:rtype: Workflow
"""
workflow = core.BNWorkflowClone(self.handle, str(name), str(activity))
- return Workflow(handle = workflow)
+ return Workflow(handle=workflow)
- def register_activity(self, activity:Activity, subactivities:List[ActivityType] = [], description:str = "") -> Optional[bool]:
+ def register_activity(self, activity: Activity, subactivities: List[ActivityType] = [],
+ description: str = "") -> Optional[bool]:
"""
``register_activity`` Register an Activity with this Workflow.
@@ -248,9 +255,11 @@ class Workflow(metaclass=_WorkflowMetaclass):
input_list = (ctypes.c_char_p * len(subactivities))()
for i in range(0, len(subactivities)):
input_list[i] = str(subactivities[i]).encode('charmap')
- return core.BNWorkflowRegisterActivity(self.handle, activity.handle, input_list, len(subactivities), str(description))
+ return core.BNWorkflowRegisterActivity(
+ self.handle, activity.handle, input_list, len(subactivities), str(description)
+ )
- def contains(self, activity:ActivityType) -> bool:
+ def contains(self, activity: ActivityType) -> bool:
"""
``contains`` Determine if an Activity exists in this Workflow.
@@ -260,7 +269,7 @@ class Workflow(metaclass=_WorkflowMetaclass):
"""
return core.BNWorkflowContains(self.handle, str(activity))
- def configuration(self, activity:ActivityType = "") -> str:
+ def configuration(self, activity: ActivityType = "") -> str:
"""
``configuration`` Retrieve the configuration as an adjacency list in JSON for the Workflow, or if specified just for the given ``activity``.
@@ -279,7 +288,7 @@ class Workflow(metaclass=_WorkflowMetaclass):
"""
return core.BNWorkflowIsRegistered(self.handle)
- def get_activity(self, activity:ActivityType) -> Optional[Activity]:
+ def get_activity(self, activity: ActivityType) -> Optional[Activity]:
"""
``get_activity`` Retrieve the Activity object for the specified ``activity``.
@@ -292,7 +301,7 @@ class Workflow(metaclass=_WorkflowMetaclass):
return None
return Activity(str(activity), handle)
- def activity_roots(self, activity:ActivityType = "") -> List[str]:
+ def activity_roots(self, activity: ActivityType = "") -> List[str]:
"""
``activity_roots`` Retrieve the list of activity roots for the Workflow, or if specified just for the given ``activity``.
@@ -311,7 +320,7 @@ class Workflow(metaclass=_WorkflowMetaclass):
finally:
core.BNFreeStringList(result, length.value)
- def subactivities(self, activity:ActivityType = "", immediate:bool = True) -> List[str]:
+ def subactivities(self, activity: ActivityType = "", immediate: bool = True) -> List[str]:
"""
``subactivities`` Retrieve the list of all activities, or optionally a filtered list.
@@ -331,7 +340,7 @@ class Workflow(metaclass=_WorkflowMetaclass):
finally:
core.BNFreeStringList(result, length.value)
- def assign_subactivities(self, activity:Activity, activities:List[str]) -> bool:
+ def assign_subactivities(self, activity: Activity, activities: List[str]) -> bool:
"""
``assign_subactivities`` Assign the list of ``activities`` as the new set of children for the specified ``activity``.
@@ -354,7 +363,7 @@ class Workflow(metaclass=_WorkflowMetaclass):
"""
return core.BNWorkflowClear(self.handle)
- def insert(self, activity:ActivityType, activities:List[str]) -> bool:
+ def insert(self, activity: ActivityType, activities: List[str]) -> bool:
"""
``insert`` Insert the list of ``activities`` before the specified ``activity`` and at the same level.
@@ -368,7 +377,7 @@ class Workflow(metaclass=_WorkflowMetaclass):
input_list[i] = str(activities[i]).encode('charmap')
return core.BNWorkflowInsert(self.handle, str(activity), input_list, len(activities))
- def remove(self, activity:ActivityType) -> bool:
+ def remove(self, activity: ActivityType) -> bool:
"""
``remove`` Remove the specified ``activity``.
@@ -378,7 +387,7 @@ class Workflow(metaclass=_WorkflowMetaclass):
"""
return core.BNWorkflowRemove(self.handle, str(activity))
- def replace(self, activity:ActivityType, new_activity:List[str]) -> bool:
+ def replace(self, activity: ActivityType, new_activity: List[str]) -> bool:
"""
``replace`` Replace the specified ``activity``.
@@ -389,7 +398,7 @@ class Workflow(metaclass=_WorkflowMetaclass):
"""
return core.BNWorkflowReplace(self.handle, str(activity), str(new_activity))
- def graph(self, activity:ActivityType = "", sequential:bool = False, show:bool = True) -> Optional[FlowGraph]:
+ def graph(self, activity: ActivityType = "", sequential: bool = False, show: bool = True) -> Optional[FlowGraph]:
"""
``graph`` Generate a FlowGraph object for the current Workflow and optionally show it in the UI.