summaryrefslogtreecommitdiff
path: root/python
diff options
context:
space:
mode:
Diffstat (limited to 'python')
-rw-r--r--python/__init__.py51
-rw-r--r--python/architecture.py54
-rw-r--r--python/basicblock.py33
-rw-r--r--python/binaryview.py92
-rw-r--r--python/demangle.py6
-rw-r--r--python/examples/angr_plugin.py25
-rw-r--r--python/examples/bin_info.py15
-rw-r--r--python/examples/breakpoint.py28
-rwxr-xr-xpython/examples/export_svg.py84
-rw-r--r--python/examples/jump_table.py8
-rw-r--r--python/examples/nds.py225
-rw-r--r--python/examples/nes.py430
-rw-r--r--python/examples/nsf.py86
-rw-r--r--python/examples/print_syscalls.py55
-rw-r--r--python/examples/version_switcher.py15
-rw-r--r--python/function.py98
-rw-r--r--python/generator.cpp88
-rw-r--r--python/highlight.py47
-rw-r--r--python/interaction.py45
-rw-r--r--python/log.py10
-rw-r--r--python/lowlevelil.py275
-rw-r--r--python/platform.py33
-rw-r--r--python/plugin.py19
-rw-r--r--python/scriptingprovider.py35
-rw-r--r--python/startup.py4
-rw-r--r--python/transform.py7
-rw-r--r--python/types.py (renamed from python/bntype.py)9
-rw-r--r--python/undoaction.py3
-rw-r--r--python/update.py5
29 files changed, 996 insertions, 889 deletions
diff --git a/python/__init__.py b/python/__init__.py
index 2a1139f9..a1ea02f5 100644
--- a/python/__init__.py
+++ b/python/__init__.py
@@ -18,30 +18,37 @@
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
+
# Binary Ninja components
import _binaryninjacore as core
-from databuffer import *
-from filemetadata import *
-from fileaccessor import *
-from binaryview import *
-from transform import *
-from architecture import *
-from basicblock import *
-from function import *
-from log import *
-from lowlevelil import *
-from bntype import *
-from functionrecognizer import *
-from update import *
-from plugin import *
-from callingconvention import *
-from platform import *
-from demangle import *
-from mainthread import *
-from interaction import *
-from lineardisassembly import *
-from undoaction import *
-from highlight import *
+from .enums import *
+from .databuffer import *
+from .filemetadata import *
+from .fileaccessor import *
+from .binaryview import *
+from .transform import *
+from .architecture import *
+from .basicblock import *
+from .function import *
+from .log import *
+from .lowlevelil import *
+from .types import *
+from .functionrecognizer import *
+from .update import *
+from .plugin import *
+from .callingconvention import *
+from .platform import *
+from .demangle import *
+from .mainthread import *
+from .interaction import *
+from .lineardisassembly import *
+from .undoaction import *
+from .highlight import *
+from .scriptingprovider import *
+
+
+def shutdown():
+ core.BNShutdown()
class _DestructionCallbackHandler(object):
diff --git a/python/architecture.py b/python/architecture.py
index 5162e58a..5d42ec35 100644
--- a/python/architecture.py
+++ b/python/architecture.py
@@ -24,8 +24,8 @@ import abc
# Binary Ninja components
import _binaryninjacore as core
-from _binaryninjacore import BNEndianness
-
+from enums import (Endianness, ImplicitRegisterExtend, BranchType,
+ InstructionTextTokenType, LowLevelILFlagCondition, FlagRole)
import startup
import function
import lowlevelil
@@ -33,7 +33,7 @@ import callingconvention
import platform
import log
import databuffer
-import bntype
+import types
class _ArchitectureMetaClass(type):
@@ -108,7 +108,7 @@ class Architecture(object):
>>> arch = Architecture['x86']
"""
name = None
- endianness = BNEndianness.LittleEndian
+ endianness = Endianness.LittleEndian
address_size = 8
default_int_size = 4
max_instr_length = 16
@@ -128,7 +128,7 @@ class Architecture(object):
if handle is not None:
self.handle = core.handle_of_type(handle, core.BNArchitecture)
self.__dict__["name"] = core.BNGetArchitectureName(self.handle)
- self.__dict__["endianness"] = core.BNEndianness(core.BNGetArchitectureEndianness(self.handle)).name
+ self.__dict__["endianness"] = Endianness(core.BNGetArchitectureEndianness(self.handle)).name
self.__dict__["address_size"] = core.BNGetArchitectureAddressSize(self.handle)
self.__dict__["default_int_size"] = core.BNGetArchitectureDefaultIntegerSize(self.handle)
self.__dict__["max_instr_length"] = core.BNGetArchitectureMaxInstructionLength(self.handle)
@@ -146,7 +146,7 @@ class Architecture(object):
info = core.BNGetArchitectureRegisterInfo(self.handle, regs[i])
full_width_reg = core.BNGetArchitectureRegisterName(self.handle, info.fullWidthRegister)
self.regs[name] = function.RegisterInfo(full_width_reg, info.size, info.offset,
- core.BNImplicitRegisterExtend(info.extend).name, regs[i])
+ ImplicitRegisterExtend(info.extend).name, regs[i])
core.BNFreeRegisterList(regs)
count = ctypes.c_ulonglong()
@@ -182,7 +182,7 @@ class Architecture(object):
self._flags_required_for_flag_condition = {}
self.__dict__["flags_required_for_flag_condition"] = {}
- for cond in core.BNLowLevelILFlagCondition:
+ for cond in LowLevelILFlagCondition:
count = ctypes.c_ulonglong()
flags = core.BNGetArchitectureFlagsRequiredForFlagCondition(self.handle, cond, count)
flag_indexes = []
@@ -311,7 +311,7 @@ class Architecture(object):
for flag in self.__class__.flag_roles:
role = self.__class__.flag_roles[flag]
if isinstance(role, str):
- role = core.BNFlagRole[role]
+ role = FlagRole[role]
self._flag_roles[self._flags[flag]] = role
self._flags_required_for_flag_condition = {}
@@ -383,7 +383,7 @@ class Architecture(object):
return self.__class__.endianness
except:
log.log_error(traceback.format_exc())
- return core.BNEndianness.LittleEndian
+ return Endianness.LittleEndian
def _get_address_size(self, ctxt):
try:
@@ -434,7 +434,7 @@ class Architecture(object):
result[0].branchCount = len(info.branches)
for i in xrange(0, len(info.branches)):
if isinstance(info.branches[i].type, str):
- result[0].branchType[i] = core.BNBranchType[info.branches[i].type]
+ result[0].branchType[i] = BranchType[info.branches[i].type]
else:
result[0].branchType[i] = info.branches[i].type
result[0].branchTarget[i] = info.branches[i].target
@@ -460,7 +460,7 @@ class Architecture(object):
token_buf = (core.BNInstructionTextToken * len(tokens))()
for i in xrange(0, len(tokens)):
if isinstance(tokens[i].type, str):
- token_buf[i].type = core.BNInstructionTextTokenType[tokens[i].type]
+ token_buf[i].type = InstructionTextTokenType[tokens[i].type]
else:
token_buf[i].type = tokens[i].type
token_buf[i].text = tokens[i].text
@@ -589,7 +589,7 @@ class Architecture(object):
try:
if flag in self._flag_roles:
return self._flag_roles[flag]
- return core.BNFlagRole.SpecialFlagRole
+ return FlagRole.SpecialFlagRole
except KeyError:
log.log_error(traceback.format_exc())
return None
@@ -673,14 +673,14 @@ class Architecture(object):
result[0].fullWidthRegister = 0
result[0].offset = 0
result[0].size = 0
- result[0].extend = core.BNImplicitRegisterExtend.NoExtend
+ result[0].extend = ImplicitRegisterExtend.NoExtend
return
info = self.__class__.regs[self._regs_by_index[reg]]
result[0].fullWidthRegister = self._all_regs[info.full_width_reg]
result[0].offset = info.offset
result[0].size = info.size
if isinstance(info.extend, str):
- result[0].extend = core.BNImplicitRegisterExtend[info.extend]
+ result[0].extend = ImplicitRegisterExtend[info.extend]
else:
result[0].extend = info.extend
except KeyError:
@@ -688,7 +688,7 @@ class Architecture(object):
result[0].fullWidthRegister = 0
result[0].offset = 0
result[0].size = 0
- result[0].extend = core.BNImplicitRegisterExtend.NoExtend
+ result[0].extend = ImplicitRegisterExtend.NoExtend
def _get_stack_pointer_register(self, ctxt):
try:
@@ -1113,7 +1113,7 @@ class Architecture(object):
result.length = info.length
result.branch_delay = info.branchDelay
for i in xrange(0, info.branchCount):
- branch_type = core.BNBranchType(info.branchType[i]).name
+ branch_type = BranchType(info.branchType[i]).name
target = info.branchTarget[i]
if info.branchArch[i]:
arch = Architecture(info.branchArch[i])
@@ -1143,7 +1143,7 @@ class Architecture(object):
return None, 0
result = []
for i in xrange(0, count.value):
- token_type = core.BNInstructionTextTokenType(tokens[i].type).name
+ token_type = InstructionTextTokenType(tokens[i].type).name
text = tokens[i].text
value = tokens[i].value
size = tokens[i].size
@@ -1611,17 +1611,17 @@ class Architecture(object):
core.BNFreeString(ctypes.cast(errors, ctypes.POINTER(ctypes.c_byte)))
if not result:
return (None, error_str)
- types = {}
+ type_dict = {}
variables = {}
functions = {}
for i in xrange(0, parse.typeCount):
- types[parse.types[i].name] = bntype.Type(core.BNNewTypeReference(parse.types[i].type))
+ types[parse.types[i].name] = types.Type(core.BNNewTypeReference(parse.types[i].type))
for i in xrange(0, parse.variableCount):
- variables[parse.variables[i].name] = bntype.Type(core.BNNewTypeReference(parse.variables[i].type))
+ variables[parse.variables[i].name] = types.Type(core.BNNewTypeReference(parse.variables[i].type))
for i in xrange(0, parse.functionCount):
- functions[parse.functions[i].name] = bntype.Type(core.BNNewTypeReference(parse.functions[i].type))
+ functions[parse.functions[i].name] = types.Type(core.BNNewTypeReference(parse.functions[i].type))
core.BNFreeTypeParserResult(parse)
- return (bntype.TypeParserResult(types, variables, functions), error_str)
+ return (types.TypeParserResult(type_dict, variables, functions), error_str)
def parse_types_from_source_file(self, filename, include_dirs=[]):
"""
@@ -1652,17 +1652,17 @@ class Architecture(object):
core.BNFreeString(ctypes.cast(errors, ctypes.POINTER(ctypes.c_byte)))
if not result:
return (None, error_str)
- types = {}
+ type_dict = {}
variables = {}
functions = {}
for i in xrange(0, parse.typeCount):
- types[parse.types[i].name] = bntype.Type(core.BNNewTypeReference(parse.types[i].type))
+ type_dict[parse.types[i].name] = types.Type(core.BNNewTypeReference(parse.types[i].type))
for i in xrange(0, parse.variableCount):
- variables[parse.variables[i].name] = bntype.Type(core.BNNewTypeReference(parse.variables[i].type))
+ variables[parse.variables[i].name] = types.Type(core.BNNewTypeReference(parse.variables[i].type))
for i in xrange(0, parse.functionCount):
- functions[parse.functions[i].name] = bntype.Type(core.BNNewTypeReference(parse.functions[i].type))
+ functions[parse.functions[i].name] = types.Type(core.BNNewTypeReference(parse.functions[i].type))
core.BNFreeTypeParserResult(parse)
- return (bntype.TypeParserResult(types, variables, functions), error_str)
+ return (types.TypeParserResult(type_dict, variables, functions), error_str)
def register_calling_convention(self, cc):
"""
diff --git a/python/basicblock.py b/python/basicblock.py
index d728cb8d..ae9889fc 100644
--- a/python/basicblock.py
+++ b/python/basicblock.py
@@ -22,6 +22,7 @@ import ctypes
# Binary Ninja components
import _binaryninjacore as core
+from enums import BranchType, HighlightColorStyle, HighlightStandardColor, InstructionTextTokenType
import architecture
import highlight
import function
@@ -30,13 +31,13 @@ import function
class BasicBlockEdge(object):
def __init__(self, branch_type, target, arch):
self.type = branch_type
- if self.type != core.BNBranchType.UnresolvedBranch:
+ if self.type != BranchType.UnresolvedBranch:
self.target = target
self.arch = arch
def __repr__(self):
- if self.type == core.BNBranchType.UnresolvedBranch:
- return "<%s>" % core.BNBranchType(self.type).name
+ if self.type == BranchType.UnresolvedBranch:
+ return "<%s>" % BranchType(self.type).name
elif self.arch:
return "<%s: %s@%#x>" % (self.type, self.arch.name, self.target)
else:
@@ -126,18 +127,18 @@ class BasicBlock(object):
:Example:
- >>> current_basic_block.highlight = core.BNHighlightStandardColor.BlueHighlightColor
+ >>> current_basic_block.highlight = HighlightStandardColor.BlueHighlightColor
>>> current_basic_block.highlight
<color: blue>
"""
color = core.BNGetBasicBlockHighlight(self.handle)
- if color.style == core.BNHighlightColorStyle.StandardHighlightColor:
+ if color.style == HighlightColorStyle.StandardHighlightColor:
return highlight.HighlightColor(color=color.color, alpha=color.alpha)
- elif color.style == core.BNHighlightColorStyle.MixedHighlightColor:
+ elif color.style == HighlightColorStyle.MixedHighlightColor:
return highlight.HighlightColor(color=color.color, mix_color=color.mixColor, mix=color.mix, alpha=color.alpha)
- elif color.style == core.BNHighlightColorStyle.CustomHighlightColor:
+ elif color.style == HighlightColorStyle.CustomHighlightColor:
return highlight.HighlightColor(red=color.r, green=color.g, blue=color.b, alpha=color.alpha)
- return highlight.HighlightColor(color=core.BNHighlightStandardColor.NoHighlightColor)
+ return highlight.HighlightColor(color=HighlightStandardColor.NoHighlightColor)
@highlight.setter
def highlight(self, value):
@@ -194,7 +195,7 @@ class BasicBlock(object):
addr = lines[i].addr
tokens = []
for j in xrange(0, lines[i].count):
- token_type = core.BNInstructionTextTokenType(lines[i].tokens[j].type)
+ token_type = InstructionTextTokenType(lines[i].tokens[j].type)
text = lines[i].tokens[j].text
value = lines[i].tokens[j].value
size = lines[i].tokens[j].size
@@ -210,22 +211,22 @@ class BasicBlock(object):
.warning:: Use only in analysis plugins. Do not use in regular plugins, as colors won't be saved to the database.
- :param core.BNHighlightStandardColor or highlight.HighlightColor color: Color value to use for highlighting
+ :param HighlightStandardColor or highlight.HighlightColor color: Color value to use for highlighting
"""
- if not isinstance(color, core.BNHighlightStandardColor) and not isinstance(color, highlight.HighlightColor):
- raise ValueError("Specified color is not one of core.BNHighlightStandardColor, highlight.HighlightColor")
+ if not isinstance(color, HighlightStandardColor) and not isinstance(color, highlight.HighlightColor):
+ raise ValueError("Specified color is not one of HighlightStandardColor, highlight.HighlightColor")
core.BNSetAutoBasicBlockHighlight(self.handle, color._get_core_struct())
def set_user_highlight(self, color):
"""
``set_user_highlight`` highlights the current BasicBlock with the supplied color
- :param core.BNHighlightStandardColor or highlight.HighlightColor color: Color value to use for highlighting
+ :param HighlightStandardColor or highlight.HighlightColor color: Color value to use for highlighting
:Example:
>>> current_basic_block.set_user_highlight(highlight.HighlightColor(red=0xff, blue=0xff, green=0))
- >>> current_basic_block.set_user_highlight(core.BNHighlightStandardColor.BlueHighlightColor)
+ >>> current_basic_block.set_user_highlight(HighlightStandardColor.BlueHighlightColor)
"""
- if not isinstance(color, core.BNHighlightStandardColor) and not isinstance(color, highlight.HighlightColor):
- raise ValueError("Specified color is not one of core.BNHighlightStandardColor, highlight.HighlightColor")
+ if not isinstance(color, HighlightStandardColor) and not isinstance(color, highlight.HighlightColor):
+ raise ValueError("Specified color is not one of HighlightStandardColor, highlight.HighlightColor")
core.BNSetUserBasicBlockHighlight(self.handle, color._get_core_struct())
diff --git a/python/binaryview.py b/python/binaryview.py
index b4be159c..41702dc8 100644
--- a/python/binaryview.py
+++ b/python/binaryview.py
@@ -26,6 +26,7 @@ import threading
# Binary Ninja components
import _binaryninjacore as core
+from enums import AnalysisState, SymbolType, InstructionTextTokenType, Endianness, ModificationStatus, StringType, SegmentFlag
import function
import startup
import architecture
@@ -36,7 +37,7 @@ import filemetadata
import log
import databuffer
import basicblock
-import bntype
+import types
import lineardisassembly
@@ -116,9 +117,9 @@ class AnalysisProgress(object):
self.total = total
def __str__(self):
- if self.state == core.BNAnalysisState.DisassembleState:
+ if self.state == AnalysisState.DisassembleState:
return "Disassembling (%d/%d)" % (self.count, self.total)
- if self.state == core.BNAnalysisState.AnalyzeState:
+ if self.state == AnalysisState.AnalyzeState:
return "Analyzing (%d/%d)" % (self.count, self.total)
return "Idle"
@@ -199,7 +200,7 @@ class BinaryDataNotificationCallbacks(object):
def _data_var_added(self, ctxt, view, var):
try:
address = var.address
- var_type = bntype.Type(core.BNNewTypeReference(var.type))
+ var_type = types.Type(core.BNNewTypeReference(var.type))
auto_discovered = var.autoDiscovered
self.notify.data_var_added(self.view, DataVariable(address, var_type, auto_discovered))
except:
@@ -208,7 +209,7 @@ class BinaryDataNotificationCallbacks(object):
def _data_var_removed(self, ctxt, view, var):
try:
address = var.address
- var_type = bntype.Type(core.BNNewTypeReference(var.type))
+ var_type = types.Type(core.BNNewTypeReference(var.type))
auto_discovered = var.autoDiscovered
self.notify.data_var_removed(self.view, DataVariable(address, var_type, auto_discovered))
except:
@@ -217,7 +218,7 @@ class BinaryDataNotificationCallbacks(object):
def _data_var_updated(self, ctxt, view, var):
try:
address = var.address
- var_type = bntype.Type(core.BNNewTypeReference(var.type))
+ var_type = types.Type(core.BNNewTypeReference(var.type))
auto_discovered = var.autoDiscovered
self.notify.data_var_updated(self.view, DataVariable(address, var_type, auto_discovered))
except:
@@ -225,13 +226,13 @@ class BinaryDataNotificationCallbacks(object):
def _string_found(self, ctxt, view, string_type, offset, length):
try:
- self.notify.string_found(self.view, core.BNStringType(string_type), offset, length)
+ self.notify.string_found(self.view, StringType(string_type), offset, length)
except:
log.log_error(traceback.format_exc())
def _string_removed(self, ctxt, view, string_type, offset, length):
try:
- self.notify.string_removed(self.view, core.BNStringType(string_type), offset, length)
+ self.notify.string_removed(self.view, StringType(string_type), offset, length)
except:
log.log_error(traceback.format_exc())
@@ -370,9 +371,9 @@ class Segment(object):
def __repr__(self):
return "<segment: %#x-%#x, %s%s%s>" % (self.start, self.end,
- "r" if (self.flags & core.BNSegmentFlag.SegmentReadable) != 0 else "-",
- "w" if (self.flags & core.BNSegmentFlag.SegmentWritable) != 0 else "-",
- "x" if (self.flags & core.BNSegmentFlag.SegmentExecutable) != 0 else "-")
+ "r" if (self.flags & SegmentFlag.SegmentReadable) != 0 else "-",
+ "w" if (self.flags & SegmentFlag.SegmentWritable) != 0 else "-",
+ "x" if (self.flags & SegmentFlag.SegmentExecutable) != 0 else "-")
class Section(object):
@@ -804,7 +805,7 @@ class BinaryView(object):
result = {}
for i in xrange(0, count.value):
addr = var_list[i].address
- var_type = bntype.Type(core.BNNewTypeReference(var_list[i].type))
+ var_type = types.Type(core.BNNewTypeReference(var_list[i].type))
auto_discovered = var_list[i].autoDiscovered
result[addr] = DataVariable(addr, var_type, auto_discovered)
core.BNFreeDataVariables(var_list, count.value)
@@ -817,7 +818,7 @@ class BinaryView(object):
type_list = core.BNGetAnalysisTypeList(self.handle, count)
result = {}
for i in xrange(0, count.value):
- result[type_list[i].name] = bntype.Type(core.BNNewTypeReference(type_list[i].type))
+ result[type_list[i].name] = types.Type(core.BNNewTypeReference(type_list[i].type))
core.BNFreeTypeList(type_list, count.value)
return result
@@ -993,7 +994,7 @@ class BinaryView(object):
return self.perform_get_modification(offset)
except:
log.log_error(traceback.format_exc())
- return core.BNModificationStatus.Original
+ return ModificationStatus.Original
def _is_valid_offset(self, ctxt, offset):
try:
@@ -1063,7 +1064,7 @@ class BinaryView(object):
return self.perform_get_default_endianness()
except:
log.log_error(traceback.format_exc())
- return core.BNEndianness.LittleEndian
+ return Endianness.LittleEndian
def _get_address_size(self, ctxt):
try:
@@ -1229,9 +1230,9 @@ class BinaryView(object):
:param int addr: a virtual address to be checked
:return: One of the following: Original = 0, Changed = 1, Inserted = 2
- :rtype: BNModificationStatus
+ :rtype: ModificationStatus
"""
- return core.BNModificationStatus.Original
+ return ModificationStatus.Original
def perform_is_valid_offset(self, addr):
"""
@@ -1352,10 +1353,10 @@ class BinaryView(object):
.. note:: This method **may** be implemented for custom BinaryViews that are not LittleEndian.
.. warning:: This method **must not** be called directly.
- :return: either ``core.BNEndianness.LittleEndian`` or ``core.BNEndianness.BigEndian``
- :rtype: BNEndianness
+ :return: either ``Endianness.LittleEndian`` or ``Endianness.BigEndian``
+ :rtype: Endianness
"""
- return core.BNEndianness.LittleEndian
+ return Endianness.LittleEndian
def create_database(self, filename, progress_func=None):
"""
@@ -1568,16 +1569,16 @@ class BinaryView(object):
def get_modification(self, addr, length=None):
"""
``get_modification`` returns the modified bytes of up to ``length`` bytes from virtual address ``addr``, or if
- ``length`` is None returns the core.BNModificationStatus.
+ ``length`` is None returns the ModificationStatus.
:param int addr: virtual address to get modification from
:param int length: optional length of modification
- :return: Either core.BNModificationStatus of the byte at ``addr``, or string of modified bytes at ``addr``
- :rtype: core.BNModificationStatus or str
+ :return: Either ModificationStatus of the byte at ``addr``, or string of modified bytes at ``addr``
+ :rtype: ModificationStatus or str
"""
if length is None:
return core.BNGetModification(self.handle, addr)
- data = (core.BNModificationStatus * length)()
+ data = (ModificationStatus * length)()
length = core.BNGetModificationArray(self.handle, addr, data, length)
return data[0:length]
@@ -1991,7 +1992,7 @@ class BinaryView(object):
sym = core.BNGetSymbolByAddress(self.handle, addr)
if sym is None:
return None
- return bntype.Symbol(None, None, None, handle = sym)
+ return types.Symbol(None, None, None, handle = sym)
def get_symbol_by_raw_name(self, name):
"""
@@ -2009,7 +2010,7 @@ class BinaryView(object):
sym = core.BNGetSymbolByRawName(self.handle, name)
if sym is None:
return None
- return bntype.Symbol(None, None, None, handle = sym)
+ return types.Symbol(None, None, None, handle = sym)
def get_symbols_by_name(self, name):
"""
@@ -2028,7 +2029,7 @@ class BinaryView(object):
syms = core.BNGetSymbolsByName(self.handle, name, count)
result = []
for i in xrange(0, count.value):
- result.append(bntype.Symbol(None, None, None, handle = core.BNNewSymbolReference(syms[i])))
+ result.append(types.Symbol(None, None, None, handle = core.BNNewSymbolReference(syms[i])))
core.BNFreeSymbolList(syms, count.value)
return result
@@ -2053,7 +2054,7 @@ class BinaryView(object):
syms = core.BNGetSymbolsInRange(self.handle, start, length, count)
result = []
for i in xrange(0, count.value):
- result.append(bntype.Symbol(None, None, None, handle = core.BNNewSymbolReference(syms[i])))
+ result.append(types.Symbol(None, None, None, handle = core.BNNewSymbolReference(syms[i])))
core.BNFreeSymbolList(syms, count.value)
return result
@@ -2069,12 +2070,12 @@ class BinaryView(object):
:rtype: list(Symbol)
:Example:
- >>> bv.get_symbols_of_type(core.BNSymbolType.ImportAddressSymbol, 0x10002028, 1)
+ >>> bv.get_symbols_of_type(SymbolType.ImportAddressSymbol, 0x10002028, 1)
[<ImportAddressSymbol: "KERNEL32!GetCurrentThreadId@IAT" @ 0x10002028>]
>>>
"""
if isinstance(sym_type, str):
- sym_type = core.BNSymbolType[sym_type]
+ sym_type = SymbolType[sym_type]
count = ctypes.c_ulonglong(0)
if start is None:
syms = core.BNGetSymbolsOfType(self.handle, sym_type, count)
@@ -2082,7 +2083,7 @@ class BinaryView(object):
syms = core.BNGetSymbolsOfTypeInRange(self.handle, sym_type, start, length, count)
result = []
for i in xrange(0, count.value):
- result.append(bntype.Symbol(None, None, None, handle = core.BNNewSymbolReference(syms[i])))
+ result.append(types.Symbol(None, None, None, handle = core.BNNewSymbolReference(syms[i])))
core.BNFreeSymbolList(syms, count.value)
return result
@@ -2095,6 +2096,21 @@ class BinaryView(object):
"""
core.BNDefineAutoSymbol(self.handle, sym.handle)
+ def define_auto_symbol_and_var_or_function(self, sym, sym_type, platform = None):
+ """
+ ``define_auto_symbol`` adds a symbol to the internal list of automatically discovered Symbol objects.
+
+ :param Symbol sym: the symbol to define
+ :rtype: None
+ """
+ if platform is None:
+ platform = self.platform
+ if platform is not None:
+ platform = platform.handle
+ if sym_type is not None:
+ sym_type = sym_type.handle
+ core.BNDefineAutoSymbolAndVariableOrFunction(self.handle, platform, sym.handle, sym_type)
+
def undefine_auto_symbol(self, sym):
"""
``undefine_auto_symbol`` removes a symbol from the internal list of automatically discovered Symbol objects.
@@ -2456,7 +2472,7 @@ class BinaryView(object):
strings = core.BNGetStringsInRange(self.handle, start, length, count)
result = []
for i in xrange(0, count.value):
- result.append(StringReference(core.BNStringType(strings[i].type), strings[i].start, strings[i].length))
+ result.append(StringReference(StringType(strings[i].type), strings[i].start, strings[i].length))
core.BNFreeStringReferenceList(strings)
return result
@@ -2697,7 +2713,7 @@ class BinaryView(object):
addr = lines[i].contents.addr
tokens = []
for j in xrange(0, lines[i].contents.count):
- token_type = core.BNInstructionTextTokenType(lines[i].contents.tokens[j].type)
+ token_type = InstructionTextTokenType(lines[i].contents.tokens[j].type)
text = lines[i].contents.tokens[j].text
value = lines[i].contents.tokens[j].value
size = lines[i].contents.tokens[j].size
@@ -2816,7 +2832,7 @@ class BinaryView(object):
error_str = errors.value
core.BNFreeString(ctypes.cast(errors, ctypes.POINTER(ctypes.c_byte)))
raise SyntaxError(error_str)
- type_obj = bntype.Type(core.BNNewTypeReference(result.type))
+ type_obj = types.Type(core.BNNewTypeReference(result.type))
name = result.name
core.BNFreeNameAndType(result)
return type_obj, name
@@ -2839,7 +2855,7 @@ class BinaryView(object):
obj = core.BNGetAnalysisTypeByName(self.handle, name)
if not obj:
return None
- return bntype.Type(obj)
+ return types.Type(obj)
def is_type_auto_defined(self, name):
"""
@@ -3066,7 +3082,7 @@ class BinaryReader(object):
Or using the optional endian parameter ::
>>> from binaryninja import *
- >>> br = BinaryReader(bv, core.BNEndianness.BigEndian)
+ >>> br = BinaryReader(bv, Endianness.BigEndian)
>>> hex(br.read32())
'0xcffaedfeL'
>>>
@@ -3374,8 +3390,8 @@ class BinaryWriter(object):
Or using the optional endian parameter ::
>>> from binaryninja import *
- >>> br = BinaryReader(bv, core.BNEndianness.BigEndian)
- >>> bw = BinaryWriter(bv, core.BNEndianness.BigEndian)
+ >>> br = BinaryReader(bv, Endianness.BigEndian)
+ >>> bw = BinaryWriter(bv, Endianness.BigEndian)
>>>
"""
def __init__(self, view, endian = None):
diff --git a/python/demangle.py b/python/demangle.py
index 75c63f40..520cfbaf 100644
--- a/python/demangle.py
+++ b/python/demangle.py
@@ -22,7 +22,7 @@ import ctypes
# Binary Ninja components
import _binaryninjacore as core
-import bntype
+import types
def get_qualified_name(names):
@@ -64,7 +64,7 @@ def demangle_ms(arch, mangled_name):
for i in xrange(outSize.value):
names.append(outName[i])
core.BNFreeDemangledName(outName.value, outSize.value)
- return (bntype.Type(handle), names)
+ return (types.Type(handle), names)
return (None, mangled_name)
@@ -79,5 +79,5 @@ def demangle_gnu3(arch, mangled_name):
core.BNFreeDemangledName(outName.value, outSize.value)
if not handle:
return (None, names)
- return (bntype.Type(handle), names)
+ return (types.Type(handle), names)
return (None, mangled_name)
diff --git a/python/examples/angr_plugin.py b/python/examples/angr_plugin.py
index 852eff65..9c91d970 100644
--- a/python/examples/angr_plugin.py
+++ b/python/examples/angr_plugin.py
@@ -30,14 +30,20 @@
# virtual environment. A later update may allow for a manual override to link to the required version
# of Python.
-__name__ = "__console__" # angr looks for this, it won't load from within a UI without it
-import angr
-from binaryninja import *
-
import tempfile
import logging
import os
+__name__ = "__console__" # angr looks for this, it won't load from within a UI without it
+
+import angr
+# For the lazy instead you can just import everything 'from binaryninja import *''
+from binaryninja.binaryview import BinaryView
+from binaryninja.plugin import BackgroundTaskThread, PluginCommand
+from binaryninja.interaction import show_plain_text_report, show_message_box
+from binaryninja.highlight import HighlightColor
+from binaryninja.enums import HighlightStandardColor, MessageBoxButtonSet
+
# Disable warning logs as they show up as errors in the UI
logging.disable(logging.WARNING)
@@ -109,8 +115,8 @@ 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(core.BNHighlightStandardColor.GreenHighlightColor, alpha = 128))
- block.function.set_auto_instr_highlight(block.arch, addr, core.BNHighlightStandardColor.GreenHighlightColor)
+ block.set_auto_highlight(HighlightColor(HighlightStandardColor.GreenHighlightColor, alpha = 128))
+ block.function.set_auto_instr_highlight(block.arch, addr, HighlightStandardColor.GreenHighlightColor)
# Add the instruction to the list associated with the current view
bv.session_data.angr_find.add(addr)
@@ -120,8 +126,8 @@ 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(core.BNHighlightStandardColor.RedHighlightColor, alpha = 128))
- block.function.set_auto_instr_highlight(block.arch, addr, core.BNHighlightStandardColor.RedHighlightColor)
+ block.set_auto_highlight(HighlightColor(HighlightStandardColor.RedHighlightColor, alpha = 128))
+ block.function.set_auto_instr_highlight(block.arch, addr, HighlightStandardColor.RedHighlightColor)
# Add the instruction to the list associated with the current view
bv.session_data.angr_avoid.add(addr)
@@ -131,13 +137,14 @@ 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.", core.BNMessageBoxButtonSet.OKButtonSet, core.BNMessageBoxButtonSet.ErrorIcon)
+ "continue.", MessageBoxButtonSet.OKButtonSet, MessageBoxButtonSet.ErrorIcon)
return
# Start a solver thread for the path associated with the view
s = Solver(bv.session_data.angr_find, bv.session_data.angr_avoid, bv)
s.start()
+
# 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)
diff --git a/python/examples/bin_info.py b/python/examples/bin_info.py
index c574a530..4c4ab8fd 100644
--- a/python/examples/bin_info.py
+++ b/python/examples/bin_info.py
@@ -21,12 +21,12 @@
import sys
import binaryninja.log as log
-import binaryninja.binaryview as view
+from binaryninja.binaryview import BinaryViewType
import binaryninja.interaction as interaction
from binaryninja.plugin import PluginCommand
-def bininfo(bv):
+def get_bininfo(bv):
if bv is None:
filename = ""
if len(sys.argv) > 1:
@@ -37,7 +37,7 @@ def bininfo(bv):
log.log_warn("No file specified")
sys.exit(1)
- bv = view.BinaryViewType.get_view_of_file(filename)
+ bv = BinaryViewType.get_view_of_file(filename)
log.redirect_output_to_log()
log.log_to_stdout(True)
@@ -60,11 +60,14 @@ def bininfo(bv):
length = bv.strings[i].length
string = bv.read(start, length)
contents += "| 0x%x |%d | %s |\n" % (start, length, string)
+ return contents
- interaction.show_markdown_report("Binary Info Report", contents)
+
+def display_bininfo(bv):
+ interaction.show_markdown_report("Binary Info Report", get_bininfo(bv))
if __name__ == "__main__":
- bininfo(None)
+ print get_bininfo(None)
else:
- PluginCommand.register("Binary Info", "Display basic info about the binary", bininfo)
+ PluginCommand.register("Binary Info", "Display basic info about the binary", display_bininfo)
diff --git a/python/examples/breakpoint.py b/python/examples/breakpoint.py
index 2426e6a1..e694329b 100644
--- a/python/examples/breakpoint.py
+++ b/python/examples/breakpoint.py
@@ -18,7 +18,11 @@
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
-from binaryninja import *
+
+from binaryninja.plugin import PluginCommand
+from binaryninja.log import log_error
+from binaryninja.architecture import Architecture
+
def write_breakpoint(view, start, length):
"""Sample function to show registering a plugin menu item for a range of bytes. Also possible:
@@ -26,11 +30,21 @@ def write_breakpoint(view, start, length):
register_for_address
register_for_function
"""
- if view.arch.name.startswith("x86"):
- view.write(start, "\xcc" * length)
- elif view.arch.name == "armv7":
- view.write(start, "\x7a\x00\x20\xe1" * (length/4))
- else:
- log_error("No support for breakpoint on %s" % view.arch.name)
+ 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)
+ return
+ bkpt, err = Architecture[view.arch.name].assemble(bkpt_str[view.arch.name])
+ if bkpt is None:
+ log_error(err)
+ return
+ view.write(start, bkpt * length / len(bkpt))
+
PluginCommand.register_for_range("Convert to breakpoint", "Fill region with breakpoint instructions.", write_breakpoint)
diff --git a/python/examples/export_svg.py b/python/examples/export_svg.py
index 5a4d2982..bab00f5d 100755
--- a/python/examples/export_svg.py
+++ b/python/examples/export_svg.py
@@ -1,11 +1,14 @@
-from binaryninja import *
+# from binaryninja import *
import os
import webbrowser
try:
- from urllib import pathname2url # Python 2.x
+ from urllib import pathname2url # Python 2.x
except:
- from urllib.request import pathname2url # Python 3.x
+ from urllib.request import pathname2url # Python 3.x
+from binaryninja.interaction import get_save_filename_input, show_message_box
+from binaryninja.enums import MessageBoxButtonSet
+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]}
@@ -17,40 +20,46 @@ escape_table = {
' ': "&#160;"
}
-def escape(string):
- string=string.decode('utf-8').encode('ascii','xmlcharrefreplace') #handle extended unicode
- return ''.join(escape_table.get(i,i) for i in string) #still escape the basics
-def save_svg(bv,function):
- address = hex(function.start).replace('L','')
+def escape(toescape):
+ toescape = toescape.decode('utf-8').encode('ascii', 'xmlcharrefreplace') # handle extended unicode
+ return ''.join(escape_table.get(i, i) for i in toescape) # still escape the basics
+
+
+def save_svg(bv, function):
+ address = hex(function.start).replace('L', '')
path = os.path.dirname(bv.file.filename)
origname = os.path.basename(bv.file.filename)
- filename = os.path.join(path,'binaryninja-{filename}-{function}.html'.format(filename=origname,function=address))
+ filename = os.path.join(path, 'binaryninja-{filename}-{function}.html'.format(filename=origname, function=address))
outputfile = get_save_filename_input('File name for export_svg', 'HTML files (*.html)', filename)
if outputfile is None:
return
content = render_svg(function)
- output = open(outputfile,'w')
+ output = open(outputfile, 'w')
output.write(content)
output.close()
- if show_message_box("Open SVG", "Would you like to view the exported SVG?", buttons = core.YesNoButtonSet, icon = core.QuestionIcon) == core.YesButton:
+ result = show_message_box("Open SVG", "Would you like to view the exported SVG?",
+ buttons = MessageBoxButtonSet.YesNoButtonSet, icon = MessageBoxButtonSet.QuestionIcon)
+ if result == MessageBoxButtonSet.YesButton:
url = 'file:{}'.format(pathname2url(outputfile))
webbrowser.open(url)
-def instruction_data_flow(function,address):
+
+def instruction_data_flow(function, address):
''' TODO: Extract data flow information '''
- length = function.view.get_instruction_length(function.arch,address)
+ length = function.view.get_instruction_length(function.arch, address)
bytes = function.view.read(address, length)
hex = bytes.encode('hex')
- padded = ' '.join([hex[i:i+2] for i in range(0, len(hex), 2)])
+ padded = ' '.join([hex[i:i + 2] for i in range(0, len(hex), 2)])
return 'Opcode: {bytes}'.format(bytes=padded)
+
def render_svg(function):
graph = function.create_graph()
graph.layout_and_wait()
heightconst = 15
ratio = 0.48
- widthconst = heightconst*ratio
+ widthconst = heightconst * ratio
output = '''<html>
<head>
@@ -135,63 +144,64 @@ def render_svg(function):
<path d="M 0 0 L 10 5 L 0 10 z" />
</marker>
</defs>
- '''.format(width=graph.width*widthconst + 20, height=graph.height*heightconst + 20)
+ '''.format(width=graph.width * widthconst + 20, height=graph.height * heightconst + 20)
output += ''' <g id="functiongraph0" class="functiongraph">
<title>Function Graph 0</title>
'''
edges = ''
- for i,block in enumerate(graph.blocks):
+ for i, block in enumerate(graph.blocks):
- #Calculate basic block location and coordinates
+ # Calculate basic block location and coordinates
x = ((block.x) * widthconst)
y = ((block.y) * heightconst)
width = ((block.width) * widthconst)
height = ((block.height) * heightconst)
- #Render block
+ # Render block
output += ' <g id="basicblock{i}">\n'.format(i=i)
output += ' <title>Basic Block {i}</title>\n'.format(i=i)
- rgb=colors['none']
+ rgb = colors['none']
try:
bb = block.basic_block
color_code = bb.highlight.color
color_str = bb.highlight._standard_color_to_str(color_code)
if color_str in colors:
- rgb=colors[color_str]
+ rgb = colors[color_str]
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])
+ 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])
+ 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=token.type)
+ output += '<tspan class="{tokentype}">{text}</tspan>'.format(text=escape(token.text), tokentype=token.type)
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) + " "
- edges += ' <polyline class="edge {type}" points="{points}" marker-end="url(#arrow-{type})"/>\n'.format(type=edge.type,points=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) + " "
+ edges += ' <polyline class="edge {type}" points="{points}" marker-end="url(#arrow-{type})"/>\n'.format(type=edge.type, points=points)
output += ' ' + edges + '\n'
output += ' </g>\n'
output += '</svg></html>'
return output
+
PluginCommand.register_for_function("Export to SVG", "Exports an SVG of the current function", save_svg)
diff --git a/python/examples/jump_table.py b/python/examples/jump_table.py
index 0fd0dbab..f24eea12 100644
--- a/python/examples/jump_table.py
+++ b/python/examples/jump_table.py
@@ -20,7 +20,8 @@
# This plugin will attempt to resolve simple jump tables (an array of code pointers) and add the destinations
# as indirect branch targets so that the flow graph reflects the jump table's control flow.
-import binaryninja
+from binaryninja.plugin import PluginCommand
+from binaryninja.enum import InstructionTextTokenType
import struct
@@ -49,7 +50,7 @@ def find_jump_table(bv, addr):
# Collect the branch targets for any tables referenced by the clicked instruction
branches = []
for token in tokens:
- if token.type == core.BNInstructionTextTokenType.PossibleAddressToken: # Table addresses will be a "possible address" token
+ if 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
@@ -79,6 +80,7 @@ def find_jump_table(bv, addr):
# Set the indirect branch targets on the jump instruction to be the list of targets discovered
func.set_user_indirect_branches(jump_addr, branches)
+
# Create a plugin command so that the user can right click on an instruction referencing a jump table and
# invoke the command
-binaryninja.PluginCommand.register_for_address("Process jump table", "Look for jump table destinations", find_jump_table)
+PluginCommand.register_for_address("Process jump table", "Look for jump table destinations", find_jump_table)
diff --git a/python/examples/nds.py b/python/examples/nds.py
index 302bbc0d..ff137b4b 100644
--- a/python/examples/nds.py
+++ b/python/examples/nds.py
@@ -1,108 +1,117 @@
-# Copyright (c) 2015-2016 Vector 35 LLC
-#
-# 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
-# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
-# sell copies of the Software, and to permit persons to whom the Software is
-# furnished to do so, subject to the following conditions:
-#
-# The above copyright notice and this permission notice shall be included in
-# all copies or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
-# IN THE SOFTWARE.
-
-from binaryninja import *
-import struct
-import traceback
-import os
-
-def crc16(data):
- crc = 0xffff
- for ch in data:
- crc ^= ord(ch)
- for bit in xrange(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
-
- @classmethod
- def is_valid_for_data(self, 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
- 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,
- core.BNSegmentFlag.SegmentReadable | core.BNSegmentFlag.SegmentExecutable)
- self.add_entry_point(Architecture['armv7'].standalone_platform, self.arm_entry_addr)
- 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,
- core.BNSegmentFlag.SegmentReadable | core.BNSegmentFlag.SegmentExecutable)
- self.add_entry_point(Architecture['armv7'].standalone_platform, self.arm_entry_addr)
- return True
- except:
- log_error(traceback.format_exc())
- return False
-
- def perform_is_executable(self):
- return True
-
- def perform_get_entry_point(self):
- return self.arm_entry_addr
-
-class DSARM9View(DSView):
- name = "DSARM9"
- long_name = "DS ARM9 ROM"
-
- def init(self):
- return self.init_arm9()
-
-class DSARM7View(DSView):
- name = "DSARM7"
- long_name = "DS ARM7 ROM"
-
- def init(self):
- return self.init_arm7()
-
-DSARM9View.register()
-DSARM7View.register()
+# Copyright (c) 2015-2016 Vector 35 LLC
+#
+# 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
+# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+# sell copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+# IN THE SOFTWARE.
+
+# from binaryninja import *
+from binaryninja.binaryview import BinaryView
+from binaryninja.architecture import Architecture
+from binaryninja.enums import SegmentFlag
+from binaryninja.log import log_error
+
+import struct
+import traceback
+
+
+def crc16(data):
+ crc = 0xffff
+ for ch in data:
+ crc ^= ord(ch)
+ for bit in xrange(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
+
+ @classmethod
+ def is_valid_for_data(self, 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
+ 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)
+ 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)
+ return True
+ except:
+ log_error(traceback.format_exc())
+ return False
+
+ def perform_is_executable(self):
+ return True
+
+ def perform_get_entry_point(self):
+ return self.arm_entry_addr
+
+
+class DSARM9View(DSView):
+ name = "DSARM9"
+ long_name = "DS ARM9 ROM"
+
+ def init(self):
+ return self.init_arm9()
+
+
+class DSARM7View(DSView):
+ name = "DSARM7"
+ long_name = "DS ARM7 ROM"
+
+ def init(self):
+ return self.init_arm7()
+
+
+DSARM9View.register()
+DSARM7View.register()
diff --git a/python/examples/nes.py b/python/examples/nes.py
index 6a05539c..a1410398 100644
--- a/python/examples/nes.py
+++ b/python/examples/nes.py
@@ -22,43 +22,48 @@ import struct
import traceback
import os
-
-from binaryninja import *
-
+from binaryninja.architecture import Architecture
+from binaryninja.lowlevelil import LowLevelILLabel, LLIL_TEMP
+from binaryninja.function import RegisterInfo, InstructionInfo
+from binaryninja.binaryview import BinaryView
+from binaryninja.types import Symbol
+from binaryninja.log import log_error
+from enums import (BranchType, InstructionTextToken, 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
@@ -84,103 +89,103 @@ 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, # ZREO_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, # ZREO_DEST
+ 1, # ZERO_X
+ 1, # ZERO_X_DEST
+ 1, # ZERO_Y
+ 1 # ZERO_Y_DEST
]
OperandTokens = [
- lambda value: [], # NONE
- lambda value: [InstructionTextToken(core.core.BNInstructionTextTokenType.PossibleAddressToken, "$%.4x" % value, value)], # ABS
- lambda value: [InstructionTextToken(core.core.BNInstructionTextTokenType.PossibleAddressToken, "$%.4x" % value, value)], # ABS_DEST
- lambda value: [InstructionTextToken(core.core.BNInstructionTextTokenType.PossibleAddressToken, "$%.4x" % value, value),
- InstructionTextToken(core.core.BNInstructionTextTokenType.TextToken, ", "), InstructionTextToken(core.core.BNInstructionTextTokenType.RegisterToken, "x")], # ABS_X
- lambda value: [InstructionTextToken(core.core.BNInstructionTextTokenType.PossibleAddressToken, "$%.4x" % value, value),
- InstructionTextToken(core.core.BNInstructionTextTokenType.TextToken, ", "), InstructionTextToken(core.core.BNInstructionTextTokenType.RegisterToken, "x")], # ABS_X_DEST
- lambda value: [InstructionTextToken(core.core.BNInstructionTextTokenType.PossibleAddressToken, "$%.4x" % value, value),
- InstructionTextToken(core.core.BNInstructionTextTokenType.TextToken, ", "), InstructionTextToken(core.core.BNInstructionTextTokenType.RegisterToken, "y")], # ABS_Y
- lambda value: [InstructionTextToken(core.core.BNInstructionTextTokenType.PossibleAddressToken, "$%.4x" % value, value),
- InstructionTextToken(core.BNInstructionTextTokenType.TextToken, ", "), InstructionTextToken(core.BNInstructionTextTokenType.RegisterToken, "y")], # ABS_Y_DEST
- lambda value: [InstructionTextToken(core.BNInstructionTextTokenType.RegisterToken, "a")], # ACCUM
- lambda value: [InstructionTextToken(core.BNInstructionTextTokenType.PossibleAddressToken, "$%.4x" % value, value)], # ADDR
- lambda value: [InstructionTextToken(core.BNInstructionTextTokenType.TextToken, "#"), InstructionTextToken(core.BNInstructionTextTokenType.IntegerToken, "$%.2x" % value, value)], # IMMED
- lambda value: [InstructionTextToken(core.BNInstructionTextTokenType.TextToken, "["), InstructionTextToken(core.BNInstructionTextTokenType.PossibleAddressToken, "$%.4x" % value, value),
- InstructionTextToken(core.BNInstructionTextTokenType.TextToken, "]")], # IND
- lambda value: [InstructionTextToken(core.BNInstructionTextTokenType.TextToken, "["), InstructionTextToken(core.BNInstructionTextTokenType.PossibleAddressToken, "$%.2x" % value, value),
- InstructionTextToken(core.BNInstructionTextTokenType.TextToken, ", "), InstructionTextToken(core.BNInstructionTextTokenType.RegisterToken, "x"),
- InstructionTextToken(core.BNInstructionTextTokenType.TextToken, "]")], # IND_X
- lambda value: [InstructionTextToken(core.BNInstructionTextTokenType.TextToken, "["), InstructionTextToken(core.BNInstructionTextTokenType.PossibleAddressToken, "$%.2x" % value, value),
- InstructionTextToken(core.BNInstructionTextTokenType.TextToken, ", "), InstructionTextToken(core.BNInstructionTextTokenType.RegisterToken, "x"),
- InstructionTextToken(core.BNInstructionTextTokenType.TextToken, "]")], # IND_X_DEST
- lambda value: [InstructionTextToken(core.BNInstructionTextTokenType.TextToken, "["), InstructionTextToken(core.BNInstructionTextTokenType.PossibleAddressToken, "$%.2x" % value, value),
- InstructionTextToken(core.BNInstructionTextTokenType.TextToken, "], "), InstructionTextToken(core.BNInstructionTextTokenType.RegisterToken, "y")], # IND_Y
- lambda value: [InstructionTextToken(core.BNInstructionTextTokenType.TextToken, "["), InstructionTextToken(core.BNInstructionTextTokenType.PossibleAddressToken, "$%.2x" % value, value),
- InstructionTextToken(core.BNInstructionTextTokenType.TextToken, "], "), InstructionTextToken(core.BNInstructionTextTokenType.RegisterToken, "y")], # IND_Y_DEST
- lambda value: [InstructionTextToken(core.BNInstructionTextTokenType.PossibleAddressToken, "$%.4x" % value, value)], # REL
- lambda value: [InstructionTextToken(core.BNInstructionTextTokenType.PossibleAddressToken, "$%.2x" % value, value)], # ZERO
- lambda value: [InstructionTextToken(core.BNInstructionTextTokenType.PossibleAddressToken, "$%.2x" % value, value)], # ZERO_DEST
- lambda value: [InstructionTextToken(core.BNInstructionTextTokenType.PossibleAddressToken, "$%.2x" % value, value),
- InstructionTextToken(core.BNInstructionTextTokenType.TextToken, ", "), InstructionTextToken(core.BNInstructionTextTokenType.RegisterToken, "x")], # ZERO_X
- lambda value: [InstructionTextToken(core.BNInstructionTextTokenType.PossibleAddressToken, "$%.2x" % value, value),
- InstructionTextToken(core.BNInstructionTextTokenType.TextToken, ", "), InstructionTextToken(core.BNInstructionTextTokenType.RegisterToken, "x")], # ZERO_X_DEST
- lambda value: [InstructionTextToken(core.BNInstructionTextTokenType.PossibleAddressToken, "$%.2x" % value, value),
- InstructionTextToken(core.BNInstructionTextTokenType.TextToken, ", "), InstructionTextToken(core.BNInstructionTextTokenType.RegisterToken, "y")], # ZERO_Y
- lambda value: [InstructionTextToken(core.BNInstructionTextTokenType.PossibleAddressToken, "$%.2x" % value, value),
- InstructionTextToken(core.BNInstructionTextTokenType.TextToken, ", "), InstructionTextToken(core.BNInstructionTextTokenType.RegisterToken, "y")] # ZERO_Y_DEST
+ 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
]
@@ -195,7 +200,7 @@ def indirect_load(il, value):
def load_zero_page_16(il, value):
- if il[value].operation == core.BNLowLevelILOperation.LLIL_CONST:
+ if il[value].operation == LowLevelILOperation.LLIL_CONST:
if il[value].value == 0xff:
lo = il.zero_extend(2, il.load(1, il.const(2, 0xff)))
hi = il.shift_left(2, il.zero_extend(2, il.load(1, il.const(2, 0)), il.const(2, 8)))
@@ -209,35 +214,36 @@ def load_zero_page_16(il, value):
hi = il.shift_left(2, il.zero_extend(2, il.load(1, hi_addr)), il.const(2, 8))
return il.or_expr(2, lo, hi)
+
OperandIL = [
- lambda il, value: None, # NONE
- lambda il, value: il.load(1, il.const(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(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(2, value), # REL
- lambda il, value: il.load(1, il.const(2, value)), # ZERO
- lambda il, value: il.const(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(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(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(2, value), # REL
+ lambda il, value: il.load(1, il.const(2, value)), # ZERO
+ lambda il, value: il.const(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
]
def cond_branch(il, cond, dest):
t = None
- if il[dest].operation == core.BNLowLevelILOperation.LLIL_CONST:
+ if il[dest].operation == LowLevelILOperation.LLIL_CONST:
t = il.get_label_for_address(Architecture['6502'], il[dest].value)
if t is None:
t = LowLevelILLabel()
@@ -255,7 +261,7 @@ def cond_branch(il, cond, dest):
def jump(il, dest):
label = None
- if il[dest].operation == core.BNLowLevelILOperation.LLIL_CONST:
+ if il[dest].operation == LowLevelILOperation.LLIL_CONST:
label = il.get_label_for_address(Architecture['6502'], il[dest].value)
if label is None:
il.append(il.jump(dest))
@@ -292,18 +298,19 @@ def rti(il):
set_p_value(il, il.pop(1))
return il.ret(il.pop(2))
+
InstructionIL = {
"adc": lambda il, operand: il.set_reg(1, "a", il.add_carry(1, il.reg(1, "a"), operand, 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(core.BNLowLevelILFlagCondition.LLFC_UGE), operand),
- "bcs": lambda il, operand: cond_branch(il, il.flag_condition(core.BNLowLevelILFlagCondition.LLFC_ULT), operand),
- "beq": lambda il, operand: cond_branch(il, il.flag_condition(core.BNLowLevelILFlagCondition.LLFC_E), operand),
+ "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(core.BNLowLevelILFlagCondition.LLFC_NEG), operand),
- "bne": lambda il, operand: cond_branch(il, il.flag_condition(core.BNLowLevelILFlagCondition.LLFC_NE), operand),
- "bpl": lambda il, operand: cond_branch(il, il.flag_condition(core.BNLowLevelILFlagCondition.LLFC_POS), operand),
+ "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),
@@ -371,18 +378,18 @@ class M6502(Architecture):
flags = ["c", "z", "i", "d", "b", "v", "s"]
flag_write_types = ["*", "czs", "zvs", "zs"]
flag_roles = {
- "c": core.BNFlagRole.SpecialFlagRole, # Not a normal carry flag, subtract result is inverted
- "z": core.BNFlagRole.ZeroFlagRole,
- "v": core.BNFlagRole.OverflowFlagRole,
- "s": core.BNFlagRole.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 = {
- core.BNLowLevelILFlagCondition.LLFC_UGE: ["c"],
- core.BNLowLevelILFlagCondition.LLFC_ULT: ["c"],
- core.BNLowLevelILFlagCondition.LLFC_E: ["z"],
- core.BNLowLevelILFlagCondition.LLFC_NE: ["z"],
- core.BNLowLevelILFlagCondition.LLFC_NEG: ["s"],
- core.BNLowLevelILFlagCondition.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"],
@@ -424,17 +431,17 @@ class M6502(Architecture):
result.length = length
if instr == "jmp":
if operand == ADDR:
- result.add_branch(core.BNBranchType.UnconditionalBranch, struct.unpack("<H", data[1:3])[0])
+ result.add_branch(BranchType.UnconditionalBranch, struct.unpack("<H", data[1:3])[0])
else:
- result.add_branch(core.BNBranchType.UnresolvedBranch)
+ result.add_branch(BranchType.UnresolvedBranch)
elif instr == "jsr":
- result.add_branch(core.BNBranchType.CallDestination, struct.unpack("<H", data[1:3])[0])
+ result.add_branch(BranchType.CallDestination, struct.unpack("<H", data[1:3])[0])
elif instr in ["rti", "rts"]:
- result.add_branch(core.BNBranchType.FunctionReturn)
+ result.add_branch(BranchType.FunctionReturn)
if instr in ["bcc", "bcs", "beq", "bmi", "bne", "bpl", "bvc", "bvs"]:
dest = (addr + 2 + struct.unpack("b", data[1])[0]) & 0xffff
- result.add_branch(core.BNBranchType.TrueBranch, dest)
- result.add_branch(core.BNBranchType.FalseBranch, addr + 2)
+ result.add_branch(BranchType.TrueBranch, dest)
+ result.add_branch(BranchType.FalseBranch, addr + 2)
return result
def perform_get_instruction_text(self, data, addr):
@@ -443,7 +450,7 @@ class M6502(Architecture):
return None
tokens = []
- tokens.append(InstructionTextToken(core.BNInstructionTextTokenType.TextToken, "%-7s " % instr.replace("@", "")))
+ tokens.append(InstructionTextToken(InstructionTextTokenType.TextToken, "%-7s " % instr.replace("@", "")))
tokens += OperandTokens[operand](value)
return tokens, length
@@ -533,55 +540,55 @@ 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, core.BNSegmentFlag.SegmentReadable | core.BNSegmentFlag.SegmentWritable | core.BNSegmentFlag.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 + (self.__class__.bank * 0x4000), 0x4000,
- core.BNSegmentFlag.SegmentReadable | core.BNSegmentFlag.SegmentExecutable)
+ SegmentFlag.SegmentReadable | SegmentFlag.SegmentExecutable)
self.add_auto_segment(0xc000, 0x4000, self.rom_offset + self.rom_length - 0x4000, 0x4000,
- core.BNSegmentFlag.SegmentReadable | core.BNSegmentFlag.SegmentExecutable)
+ SegmentFlag.SegmentReadable | SegmentFlag.SegmentExecutable)
nmi = struct.unpack("<H", self.read(0xfffa, 2))[0]
start = struct.unpack("<H", self.read(0xfffc, 2))[0]
irq = struct.unpack("<H", self.read(0xfffe, 2))[0]
- self.define_auto_symbol(Symbol(core.BNSymbolType.FunctionSymbol, nmi, "_nmi"))
- self.define_auto_symbol(Symbol(core.BNSymbolType.FunctionSymbol, start, "_start"))
- self.define_auto_symbol(Symbol(core.BNSymbolType.FunctionSymbol, irq, "_irq"))
+ self.define_auto_symbol(Symbol(SymbolType.FunctionSymbol, nmi, "_nmi"))
+ self.define_auto_symbol(Symbol(SymbolType.FunctionSymbol, start, "_start"))
+ self.define_auto_symbol(Symbol(SymbolType.FunctionSymbol, irq, "_irq"))
self.add_function(Architecture['6502'].standalone_platform, nmi)
self.add_function(Architecture['6502'].standalone_platform, irq)
self.add_entry_point(Architecture['6502'].standalone_platform, start)
# Hardware registers
- self.define_auto_symbol(Symbol(core.BNSymbolType.DataSymbol, 0x2000, "PPUCTRL"))
- self.define_auto_symbol(Symbol(core.BNSymbolType.DataSymbol, 0x2001, "PPUMASK"))
- self.define_auto_symbol(Symbol(core.BNSymbolType.DataSymbol, 0x2002, "PPUSTATUS"))
- self.define_auto_symbol(Symbol(core.BNSymbolType.DataSymbol, 0x2003, "OAMADDR"))
- self.define_auto_symbol(Symbol(core.BNSymbolType.DataSymbol, 0x2004, "OAMDATA"))
- self.define_auto_symbol(Symbol(core.BNSymbolType.DataSymbol, 0x2005, "PPUSCROLL"))
- self.define_auto_symbol(Symbol(core.BNSymbolType.DataSymbol, 0x2006, "PPUADDR"))
- self.define_auto_symbol(Symbol(core.BNSymbolType.DataSymbol, 0x2007, "PPUDATA"))
- self.define_auto_symbol(Symbol(core.BNSymbolType.DataSymbol, 0x4000, "SQ1_VOL"))
- self.define_auto_symbol(Symbol(core.BNSymbolType.DataSymbol, 0x4001, "SQ1_SWEEP"))
- self.define_auto_symbol(Symbol(core.BNSymbolType.DataSymbol, 0x4002, "SQ1_LO"))
- self.define_auto_symbol(Symbol(core.BNSymbolType.DataSymbol, 0x4003, "SQ1_HI"))
- self.define_auto_symbol(Symbol(core.BNSymbolType.DataSymbol, 0x4004, "SQ2_VOL"))
- self.define_auto_symbol(Symbol(core.BNSymbolType.DataSymbol, 0x4005, "SQ2_SWEEP"))
- self.define_auto_symbol(Symbol(core.BNSymbolType.DataSymbol, 0x4006, "SQ2_LO"))
- self.define_auto_symbol(Symbol(core.BNSymbolType.DataSymbol, 0x4007, "SQ2_HI"))
- self.define_auto_symbol(Symbol(core.BNSymbolType.DataSymbol, 0x4008, "TRI_LINEAR"))
- self.define_auto_symbol(Symbol(core.BNSymbolType.DataSymbol, 0x400a, "TRI_LO"))
- self.define_auto_symbol(Symbol(core.BNSymbolType.DataSymbol, 0x400b, "TRI_HI"))
- self.define_auto_symbol(Symbol(core.BNSymbolType.DataSymbol, 0x400c, "NOISE_VOL"))
- self.define_auto_symbol(Symbol(core.BNSymbolType.DataSymbol, 0x400e, "NOISE_LO"))
- self.define_auto_symbol(Symbol(core.BNSymbolType.DataSymbol, 0x400f, "NOISE_HI"))
- self.define_auto_symbol(Symbol(core.BNSymbolType.DataSymbol, 0x4010, "DMC_FREQ"))
- self.define_auto_symbol(Symbol(core.BNSymbolType.DataSymbol, 0x4011, "DMC_RAW"))
- self.define_auto_symbol(Symbol(core.BNSymbolType.DataSymbol, 0x4012, "DMC_START"))
- self.define_auto_symbol(Symbol(core.BNSymbolType.DataSymbol, 0x4013, "DMC_LEN"))
- self.define_auto_symbol(Symbol(core.BNSymbolType.DataSymbol, 0x4014, "OAMDMA"))
- self.define_auto_symbol(Symbol(core.BNSymbolType.DataSymbol, 0x4015, "SND_CHN"))
- self.define_auto_symbol(Symbol(core.BNSymbolType.DataSymbol, 0x4016, "JOY1"))
- self.define_auto_symbol(Symbol(core.BNSymbolType.DataSymbol, 0x4017, "JOY2"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x2000, "PPUCTRL"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x2001, "PPUMASK"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x2002, "PPUSTATUS"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x2003, "OAMADDR"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x2004, "OAMDATA"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x2005, "PPUSCROLL"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x2006, "PPUADDR"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x2007, "PPUDATA"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4000, "SQ1_VOL"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4001, "SQ1_SWEEP"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4002, "SQ1_LO"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4003, "SQ1_HI"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4004, "SQ2_VOL"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4005, "SQ2_SWEEP"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4006, "SQ2_LO"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4007, "SQ2_HI"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4008, "TRI_LINEAR"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x400a, "TRI_LO"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x400b, "TRI_HI"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x400c, "NOISE_VOL"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x400e, "NOISE_LO"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x400f, "NOISE_HI"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4010, "DMC_FREQ"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4011, "DMC_RAW"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4012, "DMC_START"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4013, "DMC_LEN"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4014, "OAMDMA"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4015, "SND_CHN"))
+ 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",
@@ -596,7 +603,7 @@ class NESView(BinaryView):
break
addr = int(sym[0][1:], 16)
name = sym[1]
- self.define_auto_symbol(Symbol(core.BNSymbolType.FunctionSymbol, addr, name))
+ self.define_auto_symbol(Symbol(SymbolType.FunctionSymbol, addr, name))
if addr >= 0x8000:
self.add_function(Architecture['6502'].standalone_platform, addr)
@@ -611,6 +618,7 @@ class NESView(BinaryView):
def perform_get_entry_point(self):
return struct.unpack("<H", str(self.perform_read(0xfffc, 2)))[0]
+
banks = []
for i in xrange(0, 32):
class NESViewBank(NESView):
diff --git a/python/examples/nsf.py b/python/examples/nsf.py
index 9d4ebd5c..de775d34 100644
--- a/python/examples/nsf.py
+++ b/python/examples/nsf.py
@@ -23,17 +23,22 @@
# https://scarybeastsecurity.blogspot.com/2016/11/0day-exploit-compromising-linux-desktop.html
#
-from binaryninja import *
+from binaryninja.binaryview import BinaryView
+from binaryninja.architecture import Architecture
+from binaryninja.log import log_error, log_info
+from binaryninja.types import Symbol
+from binaryninja.enums import SymbolType, SegmentFlag
+
import struct
import traceback
-import os
+
class NSFView(BinaryView):
name = "NSF"
long_name = "Nintendo Sound Format"
def __init__(self, data):
- BinaryView.__init__(self, parent_view = data, file_metadata = data.file)
+ BinaryView.__init__(self, parent_view=data, file_metadata=data.file)
@classmethod
def is_valid_for_data(self, data):
@@ -71,58 +76,58 @@ class NSFView(BinaryView):
self.ntsc = True
self.extra_sound_bits = struct.unpack("B", hdr[123])[0]
- if self.bank_switching == "\0"*8:
- #no bank switching
+ if self.bank_switching == "\0" * 8:
+ # no bank switching
self.load_address & 0xFFF
self.rom_offset = 128
else:
- #bank switching not implemented
+ # bank switching not implemented
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, SegmentReadable | SegmentWritable | 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,
- SegmentReadable | SegmentExecutable)
+ SegmentFlag.SegmentReadable | SegmentFlag.SegmentExecutable)
- self.define_auto_symbol(Symbol(FunctionSymbol, self.play_address, "_play"))
- self.define_auto_symbol(Symbol(FunctionSymbol, self.init_address, "_init"))
+ self.define_auto_symbol(Symbol(SymbolType.FunctionSymbol, self.play_address, "_play"))
+ self.define_auto_symbol(Symbol(SymbolType.FunctionSymbol, self.init_address, "_init"))
self.add_entry_point(Architecture['6502'].standalone_platform, self.init_address)
self.add_function(Architecture['6502'].standalone_platform, self.play_address)
# Hardware registers
- self.define_auto_symbol(Symbol(DataSymbol, 0x2000, "PPUCTRL"))
- self.define_auto_symbol(Symbol(DataSymbol, 0x2001, "PPUMASK"))
- self.define_auto_symbol(Symbol(DataSymbol, 0x2002, "PPUSTATUS"))
- self.define_auto_symbol(Symbol(DataSymbol, 0x2003, "OAMADDR"))
- self.define_auto_symbol(Symbol(DataSymbol, 0x2004, "OAMDATA"))
- self.define_auto_symbol(Symbol(DataSymbol, 0x2005, "PPUSCROLL"))
- self.define_auto_symbol(Symbol(DataSymbol, 0x2006, "PPUADDR"))
- self.define_auto_symbol(Symbol(DataSymbol, 0x2007, "PPUDATA"))
- self.define_auto_symbol(Symbol(DataSymbol, 0x4000, "SQ1_VOL"))
- self.define_auto_symbol(Symbol(DataSymbol, 0x4001, "SQ1_SWEEP"))
- self.define_auto_symbol(Symbol(DataSymbol, 0x4002, "SQ1_LO"))
- self.define_auto_symbol(Symbol(DataSymbol, 0x4003, "SQ1_HI"))
- self.define_auto_symbol(Symbol(DataSymbol, 0x4004, "SQ2_VOL"))
- self.define_auto_symbol(Symbol(DataSymbol, 0x4005, "SQ2_SWEEP"))
- self.define_auto_symbol(Symbol(DataSymbol, 0x4006, "SQ2_LO"))
- self.define_auto_symbol(Symbol(DataSymbol, 0x4007, "SQ2_HI"))
- self.define_auto_symbol(Symbol(DataSymbol, 0x4008, "TRI_LINEAR"))
- self.define_auto_symbol(Symbol(DataSymbol, 0x400a, "TRI_LO"))
- self.define_auto_symbol(Symbol(DataSymbol, 0x400b, "TRI_HI"))
- self.define_auto_symbol(Symbol(DataSymbol, 0x400c, "NOISE_VOL"))
- self.define_auto_symbol(Symbol(DataSymbol, 0x400e, "NOISE_LO"))
- self.define_auto_symbol(Symbol(DataSymbol, 0x400f, "NOISE_HI"))
- self.define_auto_symbol(Symbol(DataSymbol, 0x4010, "DMC_FREQ"))
- self.define_auto_symbol(Symbol(DataSymbol, 0x4011, "DMC_RAW"))
- self.define_auto_symbol(Symbol(DataSymbol, 0x4012, "DMC_START"))
- self.define_auto_symbol(Symbol(DataSymbol, 0x4013, "DMC_LEN"))
- self.define_auto_symbol(Symbol(DataSymbol, 0x4014, "OAMDMA"))
- self.define_auto_symbol(Symbol(DataSymbol, 0x4015, "SND_CHN"))
- self.define_auto_symbol(Symbol(DataSymbol, 0x4016, "JOY1"))
- self.define_auto_symbol(Symbol(DataSymbol, 0x4017, "JOY2"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x2000, "PPUCTRL"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x2001, "PPUMASK"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x2002, "PPUSTATUS"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x2003, "OAMADDR"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x2004, "OAMDATA"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x2005, "PPUSCROLL"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x2006, "PPUADDR"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x2007, "PPUDATA"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4000, "SQ1_VOL"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4001, "SQ1_SWEEP"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4002, "SQ1_LO"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4003, "SQ1_HI"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4004, "SQ2_VOL"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4005, "SQ2_SWEEP"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4006, "SQ2_LO"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4007, "SQ2_HI"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4008, "TRI_LINEAR"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x400a, "TRI_LO"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x400b, "TRI_HI"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x400c, "NOISE_VOL"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x400e, "NOISE_LO"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x400f, "NOISE_HI"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4010, "DMC_FREQ"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4011, "DMC_RAW"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4012, "DMC_START"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4013, "DMC_LEN"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4014, "OAMDMA"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4015, "SND_CHN"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4016, "JOY1"))
+ self.define_auto_symbol(Symbol(SymbolType.DataSymbol, 0x4017, "JOY2"))
return True
except:
@@ -135,4 +140,5 @@ class NSFView(BinaryView):
def perform_get_entry_point(self):
return struct.unpack("<H", str(self.perform_read(0x0a, 2)))[0]
+
NSFView.register()
diff --git a/python/examples/print_syscalls.py b/python/examples/print_syscalls.py
index 003b388e..2af4d38d 100644
--- a/python/examples/print_syscalls.py
+++ b/python/examples/print_syscalls.py
@@ -26,45 +26,30 @@
import sys
from itertools import chain
-from binaryninja import BinaryView, core
+from binaryninja.binaryview import BinaryViewType
+from binaryninja.enums import LowLevelILOperation
-def print_syscalls(bv):
- """ Print Syscall numbers for a provided binaryview """
+def print_syscalls(fileName):
+ """ Print Syscall numbers for a provided file """
+ bv = BinaryViewType.get_view_of_file(fileName)
+ calling_convention = bv.platform.system_call_convention
+ if calling_convention is None:
+ print('Error: No syscall convention available for {:s}'.format(bv.platform))
+ return
- calling_convention = bv.platform.system_call_convention
- if not calling_convention:
- print('Error: No syscall convention available for {:s}'.format(bv.platform))
- return
+ register = calling_convention.int_arg_regs[0]
- 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 == core.BNLowLevelILOperation.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))
-
-
-def main():
- if len(sys.argv) != 2:
- print('Usage: {} <file>'.format(sys.argv[0]))
- return -1
-
- target = sys.argv[1]
-
- bv = BinaryView.open(target)
- view_type = next(bvt for bvt in bv.available_view_types if bvt.name != 'Raw')
- if not view_type:
- print('Error: Unable to get any other view type besides Raw')
- return -1
-
- bv = bv.file.get_view_of_type(view_type.name)
- bv.update_analysis_and_wait()
-
- print_syscalls(bv)
+ for func in bv.functions:
+ 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))
if __name__ == "__main__":
- sys.exit(main())
+ if len(sys.argv) != 2:
+ print('Usage: {} <file>'.format(sys.argv[0]))
+ else:
+ print_syscalls(sys.argv[1])
diff --git a/python/examples/version_switcher.py b/python/examples/version_switcher.py
index e8f8814d..bc4f576c 100644
--- a/python/examples/version_switcher.py
+++ b/python/examples/version_switcher.py
@@ -27,10 +27,11 @@ chandefault = binaryninja.UpdateChannel.list[0].name
channel = None
versions = []
+
def load_channel(newchannel):
global channel
global versions
- if (channel != None and newchannel == channel.name):
+ if (channel is None and newchannel == channel.name):
print "Same channel, not updating."
else:
try:
@@ -42,6 +43,7 @@ def load_channel(newchannel):
print "%s is not a valid channel name. Defaulting to " % chandefault
channel = binaryninja.UpdateChannel[chandefault]
+
def select(version):
done = False
date = datetime.datetime.fromtimestamp(version.time).strftime('%c')
@@ -74,34 +76,37 @@ def select(version):
print "binaryninja.core_version %s" % binaryninja.core_version
print "Updating..."
print version.update()
- #forward updating won't work without reloading
+ # forward updating won't work without reloading
sys.exit()
else:
print "Invalid selection"
+
def list_channels():
done = False
print "\tSelect channel:\n"
while not done:
channel_list = binaryninja.UpdateChannel.list
for index, item in enumerate(channel_list):
- print "\t%d)\t%s" % (index+1, item.name)
- print "\t%d)\t%s" % (len(channel_list)+1, "Main Menu")
+ print "\t%d)\t%s" % (index + 1, item.name)
+ print "\t%d)\t%s" % (len(channel_list) + 1, "Main Menu")
selection = raw_input('Choice: ')
if selection.isdigit():
selection = int(selection)
else:
selection = 0
- if (selection <= 0 or selection > len(channel_list)+1):
+ if (selection <= 0 or selection > len(channel_list) + 1):
print "%s is an invalid choice." % selection
else:
done = True
if (selection != len(channel_list) + 1):
load_channel(channel_list[selection - 1].name)
+
def toggle_updates():
binaryninja.set_auto_updates_enabled(not binaryninja.are_auto_updates_enabled())
+
def main():
global channel
done = False
diff --git a/python/function.py b/python/function.py
index 16357c3f..e3c79312 100644
--- a/python/function.py
+++ b/python/function.py
@@ -24,10 +24,12 @@ import ctypes
# Binary Ninja components
import _binaryninjacore as core
+from enums import (FunctionGraphType, BranchType, SymbolType, InstructionTextTokenType,
+ HighlightStandardColor, RegisterValueType, ImplicitRegisterExtend, DisassemblyOption, IntegerDisplayType)
import architecture
import highlight
import associateddatastore
-import bntype
+import types
import basicblock
import lowlevelil
import binaryview
@@ -46,16 +48,16 @@ class LookupTableEntry(object):
class RegisterValue(object):
def __init__(self, arch, value):
self.type = value.state
- if value.state == core.BNRegisterValueType.EntryValue:
+ if value.state == RegisterValueType.EntryValue:
self.reg = arch.get_reg_name(value.reg)
- elif value.state == core.BNRegisterValueType.OffsetFromEntryValue:
+ elif value.state == RegisterValueType.OffsetFromEntryValue:
self.reg = arch.get_reg_name(value.reg)
self.offset = value.value
- elif value.state == core.BNRegisterValueType.ConstantValue:
+ elif value.state == RegisterValueType.ConstantValue:
self.value = value.value
- elif value.state == core.BNRegisterValueType.StackFrameOffset:
+ elif value.state == RegisterValueType.StackFrameOffset:
self.offset = value.value
- elif value.state == core.BNRegisterValueType.SignedRangeValue:
+ elif value.state == RegisterValueType.SignedRangeValue:
self.offset = value.value
self.start = value.rangeStart
self.end = value.rangeEnd
@@ -64,12 +66,12 @@ class RegisterValue(object):
self.start |= ~((1 << 63) - 1)
if self.end & (1 << 63):
self.end |= ~((1 << 63) - 1)
- elif value.state == core.BNRegisterValueType.UnsignedRangeValue:
+ elif value.state == RegisterValueType.UnsignedRangeValue:
self.offset = value.value
self.start = value.rangeStart
self.end = value.rangeEnd
self.step = value.rangeStep
- elif value.state == core.BNRegisterValueType.LookupTableValue:
+ elif value.state == RegisterValueType.LookupTableValue:
self.table = []
self.mapping = {}
for i in xrange(0, value.rangeEnd):
@@ -78,25 +80,25 @@ class RegisterValue(object):
from_list.append(value.table[i].fromValues[j])
self.mapping[value.table[i].fromValues[j]] = value.table[i].toValue
self.table.append(LookupTableEntry(from_list, value.table[i].toValue))
- elif value.state == core.BNRegisterValueType.OffsetFromUndeterminedValue:
+ elif value.state == RegisterValueType.OffsetFromUndeterminedValue:
self.offset = value.value
def __repr__(self):
- if self.type == core.BNRegisterValueType.EntryValue:
+ if self.type == RegisterValueType.EntryValue:
return "<entry %s>" % self.reg
- if self.type == core.BNRegisterValueType.OffsetFromEntryValue:
+ if self.type == RegisterValueType.OffsetFromEntryValue:
return "<entry %s + %#x>" % (self.reg, self.offset)
- if self.type == core.BNRegisterValueType.ConstantValue:
+ if self.type == RegisterValueType.ConstantValue:
return "<const %#x>" % self.value
- if self.type == core.BNRegisterValueType.StackFrameOffset:
+ if self.type == RegisterValueType.StackFrameOffset:
return "<stack frame offset %#x>" % self.offset
- if (self.type == core.BNRegisterValueType.SignedRangeValue) or (self.type == core.BNRegisterValueType.UnsignedRangeValue):
+ if (self.type == RegisterValueType.SignedRangeValue) or (self.type == RegisterValueType.UnsignedRangeValue):
if self.step == 1:
return "<range: %#x to %#x>" % (self.start, self.end)
return "<range: %#x to %#x, step %#x>" % (self.start, self.end, self.step)
- if self.type == core.BNRegisterValueType.LookupTableValue:
+ if self.type == RegisterValueType.LookupTableValue:
return "<table: %s>" % ', '.join([repr(i) for i in self.table])
- if self.type == core.BNRegisterValueType.OffsetFromUndeterminedValue:
+ if self.type == RegisterValueType.OffsetFromUndeterminedValue:
return "<undetermined with offset %#x>" % self.offset
return "<undetermined>"
@@ -195,7 +197,7 @@ class Function(object):
if self.symbol is not None:
self.view.undefine_user_symbol(self.symbol)
else:
- symbol = bntype.Symbol(core.BNSymbolType.FunctionSymbol, self.start, value)
+ symbol = types.Symbol(SymbolType.FunctionSymbol, self.start, value)
self.view.define_user_symbol(symbol)
@property
@@ -230,7 +232,7 @@ class Function(object):
sym = core.BNGetFunctionSymbol(self.handle)
if sym is None:
return None
- return bntype.Symbol(None, None, None, handle = sym)
+ return types.Symbol(None, None, None, handle = sym)
@property
def auto(self):
@@ -287,7 +289,7 @@ class Function(object):
@property
def function_type(self):
"""Function type object"""
- return bntype.Type(core.BNGetFunctionType(self.handle))
+ return types.Type(core.BNGetFunctionType(self.handle))
@function_type.setter
def function_type(self, value):
@@ -300,7 +302,7 @@ class Function(object):
v = core.BNGetStackLayout(self.handle, count)
result = []
for i in xrange(0, count.value):
- result.append(StackVariable(v[i].offset, v[i].name, bntype.Type(handle = core.BNNewTypeReference(v[i].type))))
+ result.append(StackVariable(v[i].offset, v[i].name, types.Type(handle = core.BNNewTypeReference(v[i].type))))
result.sort(key = lambda x: x.offset)
core.BNFreeStackLayout(v, count.value)
return result
@@ -553,7 +555,7 @@ class Function(object):
refs = core.BNGetStackVariablesReferencedByInstruction(self.handle, arch.handle, addr, count)
result = []
for i in xrange(0, count.value):
- result.append(StackVariableReference(refs[i].sourceOperand, bntype.Type(core.BNNewTypeReference(refs[i].type)),
+ result.append(StackVariableReference(refs[i].sourceOperand, types.Type(core.BNNewTypeReference(refs[i].type)),
refs[i].name, refs[i].startingOffset, refs[i].referencedOffset))
core.BNFreeStackVariableReferenceList(refs, count.value)
return result
@@ -661,7 +663,7 @@ class Function(object):
for i in xrange(0, count.value):
tokens = []
for j in xrange(0, lines[i].count):
- token_type = core.BNInstructionTextTokenType(lines[i].tokens[j].type)
+ token_type = InstructionTextTokenType(lines[i].tokens[j].type)
text = lines[i].tokens[j].text
value = lines[i].tokens[j].value
size = lines[i].tokens[j].size
@@ -688,13 +690,13 @@ class Function(object):
:param int instr_addr:
:param int value:
:param int operand:
- :param BNIntegerDisplayTypeEnum display_type:
+ :param IntegerDisplayTypeEnum display_type:
:param Architecture arch: (optional)
"""
if arch is None:
arch = self.arch
if isinstance(display_type, str):
- display_type = core.BNIntegerDisplayType[display_type]
+ display_type = IntegerDisplayType[display_type]
core.BNSetIntegerConstantDisplayType(self.handle, arch.handle, instr_addr, value, operand, display_type)
def reanalyze(self):
@@ -741,13 +743,13 @@ class Function(object):
if arch is None:
arch = self.arch
color = core.BNGetInstructionHighlight(self.handle, arch.handle, addr)
- if color.style == core.BNHighlightColorStyle.StandardHighlightColor:
+ if color.style == HighlightColorStyle.StandardHighlightColor:
return highlight.HighlightColor(color = color.color, alpha = color.alpha)
- elif color.style == core.BNHighlightColorStyle.MixedHighlightColor:
+ elif color.style == HighlightColorStyle.MixedHighlightColor:
return highlight.HighlightColor(color = color.color, mix_color = color.mixColor, mix = color.mix, alpha = color.alpha)
- elif color.style == core.BNHighlightColorStyle.CustomHighlightColor:
+ elif color.style == HighlightColorStyle.CustomHighlightColor:
return highlight.HighlightColor(red = color.r, green = color.g, blue = color.b, alpha = color.alpha)
- return highlight.HighlightColor(color = core.BNHighlightStandardColor.NoHighlightColor)
+ return highlight.HighlightColor(color = HighlightStandardColor.NoHighlightColor)
def set_auto_instr_highlight(self, addr, color, arch=None):
"""
@@ -756,7 +758,7 @@ class Function(object):
.warning:: Use only in analysis plugins. Do not use in regular plugins, as colors won't be saved to the database.
:param int addr: virtual address of the instruction to be highlighted
- :param core.BNHighlightStandardColor or highlight.HighlightColor color: Color value to use for highlighting
+ :param HighlightStandardColor or highlight.HighlightColor color: Color value to use for highlighting
:param Architecture arch: (optional) Architecture of the instruction if different from self.arch
"""
if arch is None:
@@ -770,17 +772,17 @@ class Function(object):
``set_user_instr_highlight`` highlights the instruction at the specified address with the supplied color
:param int addr: virtual address of the instruction to be highlighted
- :param core.BNHighlightStandardColor or highlight.HighlightColor color: Color value to use for highlighting
+ :param HighlightStandardColor or highlight.HighlightColor color: Color value to use for highlighting
:param Architecture arch: (optional) Architecture of the instruction if different from self.arch
:Example:
- >>> current_function.set_user_instr_highlight(here, core.BNHighlightStandardColor.BlueHighlightColor)
+ >>> current_function.set_user_instr_highlight(here, HighlightStandardColor.BlueHighlightColor)
>>> current_function.set_user_instr_highlight(here, highlight.HighlightColor(red=0xff, blue=0xff, green=0))
"""
if arch is None:
arch = self.arch
- if not isinstance(color, core.BNHighlightStandardColor) and not isinstance(color, highlight.HighlightColor):
- raise ValueError("Specified color is not one of core.BNHighlightStandardColor, highlight.HighlightColor")
+ if not isinstance(color, HighlightStandardColor) and not isinstance(color, highlight.HighlightColor):
+ raise ValueError("Specified color is not one of HighlightStandardColor, highlight.HighlightColor")
core.BNSetUserInstructionHighlight(self.handle, arch.handle, addr, color._get_core_struct())
@@ -908,7 +910,7 @@ class FunctionGraphBlock(object):
addr = lines[i].addr
tokens = []
for j in xrange(0, lines[i].count):
- token_type = core.BNInstructionTextTokenType(lines[i].tokens[j].type)
+ token_type = InstructionTextTokenType(lines[i].tokens[j].type)
text = lines[i].tokens[j].text
value = lines[i].tokens[j].value
size = lines[i].tokens[j].size
@@ -925,7 +927,7 @@ class FunctionGraphBlock(object):
edges = core.BNGetFunctionGraphBlockOutgoingEdges(self.handle, count)
result = []
for i in xrange(0, count.value):
- branch_type = core.BNBranchType(edges[i].type)
+ branch_type = BranchType(edges[i].type)
target = edges[i].target
arch = None
if edges[i].arch is not None:
@@ -958,7 +960,7 @@ class FunctionGraphBlock(object):
addr = lines[i].addr
tokens = []
for j in xrange(0, lines[i].count):
- token_type = core.BNInstructionTextTokenType(lines[i].tokens[j].type)
+ token_type = InstructionTextTokenType(lines[i].tokens[j].type)
text = lines[i].tokens[j].text
value = lines[i].tokens[j].value
size = lines[i].tokens[j].size
@@ -997,12 +999,12 @@ class DisassemblySettings(object):
def is_option_set(self, option):
if isinstance(option, str):
- option = core.BNDisassemblyOption[option]
+ option = DisassemblyOption[option]
return core.BNIsDisassemblySettingsOptionSet(self.handle, option)
def set_option(self, option, state = True):
if isinstance(option, str):
- option = core.BNDisassemblyOption[option]
+ option = DisassemblyOption[option]
core.BNSetDisassemblySettingsOption(self.handle, option, state)
@@ -1033,7 +1035,7 @@ class FunctionGraph(object):
@property
def type(self):
"""Function graph type (read-only)"""
- return core.BNFunctionGraphType(core.BNGetFunctionGraphType(self.handle))
+ return FunctionGraphType(core.BNGetFunctionGraphType(self.handle))
@property
def blocks(self):
@@ -1101,9 +1103,9 @@ class FunctionGraph(object):
except:
log.log_error(traceback.format_exc())
- def layout(self, graph_type = core.BNFunctionGraphType.NormalFunctionGraph):
+ def layout(self, graph_type = FunctionGraphType.NormalFunctionGraph):
if isinstance(graph_type, str):
- graph_type = core.BNFunctionGraphType[graph_type]
+ graph_type = FunctionGraphType[graph_type]
core.BNStartFunctionGraphLayout(self.handle, graph_type)
def _wait_complete(self):
@@ -1111,7 +1113,7 @@ class FunctionGraph(object):
self._wait_cond.notify()
self._wait_cond.release()
- def layout_and_wait(self, graph_type = core.BNFunctionGraphType.NormalFunctionGraph):
+ def layout_and_wait(self, graph_type=FunctionGraphType.NormalFunctionGraph):
self._wait_cond = threading.Condition()
self.on_complete(self._wait_complete)
self.layout(graph_type)
@@ -1139,17 +1141,17 @@ class FunctionGraph(object):
def is_option_set(self, option):
if isinstance(option, str):
- option = core.BNDisassemblyOption[option]
+ option = DisassemblyOption[option]
return core.BNIsFunctionGraphOptionSet(self.handle, option)
def set_option(self, option, state = True):
if isinstance(option, str):
- option = core.BNDisassemblyOption[option]
+ option = DisassemblyOption[option]
core.BNSetFunctionGraphOption(self.handle, option, state)
class RegisterInfo(object):
- def __init__(self, full_width_reg, size, offset = 0, extend = core.BNImplicitRegisterExtend.NoExtend, index = None):
+ def __init__(self, full_width_reg, size, offset=0, extend=ImplicitRegisterExtend.NoExtend, index=None):
self.full_width_reg = full_width_reg
self.offset = offset
self.size = size
@@ -1157,9 +1159,9 @@ class RegisterInfo(object):
self.index = index
def __repr__(self):
- if self.extend == core.BNImplicitRegisterExtend.ZeroExtendToFullWidth:
+ if self.extend == ImplicitRegisterExtend.ZeroExtendToFullWidth:
extend = ", zero extend"
- elif self.extend == core.BNImplicitRegisterExtend.SignExtendToFullWidth:
+ elif self.extend == ImplicitRegisterExtend.SignExtendToFullWidth:
extend = ", sign extend"
else:
extend = ""
@@ -1200,7 +1202,7 @@ class InstructionTextToken(object):
``class InstructionTextToken`` is used to tell the core about the various components in the disassembly views.
========================== ============================================
- BNInstructionTextTokenType Description
+ InstructionTextTokenType Description
========================== ============================================
TextToken Text that doesn't fit into the other tokens
InstructionToken The instruction mnemonic
diff --git a/python/generator.cpp b/python/generator.cpp
index 730b317c..d3725b6d 100644
--- a/python/generator.cpp
+++ b/python/generator.cpp
@@ -101,8 +101,13 @@ void OutputType(FILE* out, Type* type, bool isReturnType = false, bool isCallbac
fprintf(out, "%s", type->GetQualifiedName(type->GetStructure()->GetName()).c_str());
break;
case EnumerationTypeClass:
- fprintf(out, "%sEnum", type->GetQualifiedName(type->GetEnumeration()->GetName()).c_str());
+ {
+ string name = type->GetQualifiedName(type->GetEnumeration()->GetName());
+ if (name.size() > 2 && name.substr(0, 2) == "BN")
+ name = name.substr(2);
+ fprintf(out, "%sEnum", name.c_str());
break;
+ }
case PointerTypeClass:
if (isCallback || (type->GetChildType()->GetClass() == VoidTypeClass))
{
@@ -147,9 +152,9 @@ void OutputType(FILE* out, Type* type, bool isReturnType = false, bool isCallbac
int main(int argc, char* argv[])
{
- if (argc < 3)
+ if (argc < 4)
{
- fprintf(stderr, "Usage: generator <header> <output>\n");
+ fprintf(stderr, "Usage: generator <header> <output> <output_enum>\n");
return 1;
}
@@ -164,23 +169,27 @@ int main(int argc, char* argv[])
return 1;
FILE* out = fopen(argv[2], "w");
+ FILE* enums = fopen(argv[3], "w");
- fprintf(out, "import ctypes, os, enum\n\n");
+ fprintf(out, "from __future__ import absolute_import\n");
+ fprintf(out, "import ctypes, os\n\n");
+ fprintf(enums, "import enum");
fprintf(out, "# Load core module\n");
-#if defined(__APPLE__)
- fprintf(out, "_base_path = os.path.join(os.path.dirname(__file__), \"..\", \"..\", \"..\", \"MacOS\")\n");
-#else
- fprintf(out, "_base_path = os.path.join(os.path.dirname(__file__), \"..\", \"..\")\n");
-#endif
-
-#ifdef WIN32
- fprintf(out, "core = ctypes.CDLL(os.path.join(_base_path, \"binaryninjacore.dll\"))\n\n");
-#elif defined(__APPLE__)
- fprintf(out, "core = ctypes.CDLL(os.path.join(_base_path, \"libbinaryninjacore.dylib\"))\n\n");
-#else
- fprintf(out, "core = ctypes.CDLL(os.path.join(_base_path, \"libbinaryninjacore.so.1\"))\n\n");
-#endif
+ fprintf(out, "import platform\n");
+ fprintf(out, "core = None\n");
+ fprintf(out, "_base_path = None\n");
+ fprintf(out, "if platform.system() == \"Darwin\":\n");
+ fprintf(out, "\t_base_path = os.path.join(os.path.dirname(__file__), \"..\", \"..\", \"..\", \"MacOS\")\n");
+ fprintf(out, "\tcore = ctypes.CDLL(os.path.join(_base_path, \"libbinaryninjacore.dylib\"))\n\n");
+ fprintf(out, "elif platform.system() == \"Linux\":\n");
+ fprintf(out, "\t_base_path = os.path.join(os.path.dirname(__file__), \"..\", \"..\")\n");
+ fprintf(out, "\tcore = ctypes.CDLL(os.path.join(_base_path, \"libbinaryninjacore.so.1\"))\n\n");
+ fprintf(out, "elif platform.system() == \"Windows\":\n");
+ fprintf(out, "\t_base_path = os.path.join(os.path.dirname(__file__), \"..\", \"..\")\n");
+ fprintf(out, "\tcore = ctypes.CDLL(os.path.join(_base_path, \"binaryninjacore.dll\"))\n");
+ fprintf(out, "else:\n");
+ fprintf(out, "\traise Exception(\"OS not supported\")\n\n");
// Create type objects
fprintf(out, "# Type definitions\n");
@@ -189,17 +198,21 @@ int main(int argc, char* argv[])
if (i.second->GetClass() == StructureTypeClass)
{
fprintf(out, "class %s(ctypes.Structure):\n", i.first.c_str());
- fprintf(out, " pass\n");
+ fprintf(out, "\tpass\n");
}
else if (i.second->GetClass() == EnumerationTypeClass)
{
- fprintf(out, "%sEnum = ctypes.c_int\n", i.first.c_str());
- fprintf(out, "class %s(enum.IntEnum):\n", i.first.c_str());
+ string name = i.first;
+ if (name.size() > 2 && name.substr(0, 2) == "BN")
+ name = name.substr(2);
+
+ fprintf(out, "%sEnum = ctypes.c_int\n", name.c_str());
+
+ fprintf(enums, "\n\nclass %s(enum.IntEnum):\n", name.c_str());
for (auto& j : i.second->GetEnumeration()->GetMembers())
{
- fprintf(out, " %s = %" PRId64 "\n", j.name.c_str(), j.value);
+ 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))
@@ -219,11 +232,11 @@ int main(int argc, char* argv[])
fprintf(out, "%s._fields_ = [\n", i.first.c_str());
for (auto& j : i.second->GetStructure()->GetMembers())
{
- fprintf(out, " (\"%s\", ", j.name.c_str());
+ fprintf(out, "\t\t(\"%s\", ", j.name.c_str());
OutputType(out, j.type);
fprintf(out, "),\n");
}
- fprintf(out, " ]\n");
+ fprintf(out, "\t]\n");
}
}
@@ -260,7 +273,7 @@ int main(int argc, char* argv[])
fprintf(out, "%s.argtypes = [\n", funcName.c_str());
for (auto& j : i.second->GetParameters())
{
- fprintf(out, " ");
+ fprintf(out, "\t\t");
if (i.first == "BNFreeString")
{
// BNFreeString expects a pointer to a string allocated by the core, so do not use
@@ -274,38 +287,39 @@ int main(int argc, char* argv[])
}
fprintf(out, ",\n");
}
- fprintf(out, " ]\n");
+ fprintf(out, "\t]\n");
}
if (stringResult)
{
// Emit wrapper to get Python string and free native memory
fprintf(out, "def %s(*args):\n", i.first.c_str());
- fprintf(out, " result = %s(*args)\n", funcName.c_str());
- fprintf(out, " string = ctypes.cast(result, ctypes.c_char_p).value\n");
- fprintf(out, " BNFreeString(result)\n");
- fprintf(out, " return string\n");
+ fprintf(out, "\tresult = %s(*args)\n", funcName.c_str());
+ fprintf(out, "\tstring = ctypes.cast(result, ctypes.c_char_p).value\n");
+ fprintf(out, "\tBNFreeString(result)\n");
+ fprintf(out, "\treturn string\n");
}
else if (pointerResult)
{
// Emit wrapper to return None on null pointer
fprintf(out, "def %s(*args):\n", i.first.c_str());
- fprintf(out, " result = %s(*args)\n", funcName.c_str());
- fprintf(out, " if not result:\n");
- fprintf(out, " return None\n");
- fprintf(out, " return result\n");
+ fprintf(out, "\tresult = %s(*args)\n", funcName.c_str());
+ fprintf(out, "\tif not result:\n");
+ fprintf(out, "\t\treturn None\n");
+ fprintf(out, "\treturn result\n");
}
}
fprintf(out, "\n# Helper functions\n");
fprintf(out, "def handle_of_type(value, handle_type):\n");
- fprintf(out, " if isinstance(value, ctypes.POINTER(handle_type)) or isinstance(value, ctypes.c_void_p):\n");
- fprintf(out, " return ctypes.cast(value, ctypes.POINTER(handle_type))\n");
- fprintf(out, " raise ValueError, 'expected pointer to %%s' %% str(handle_type)\n");
+ fprintf(out, "\tif isinstance(value, ctypes.POINTER(handle_type)) or isinstance(value, ctypes.c_void_p):\n");
+ fprintf(out, "\t\treturn ctypes.cast(value, ctypes.POINTER(handle_type))\n");
+ fprintf(out, "\traise ValueError, 'expected pointer to %%s' %% str(handle_type)\n");
fprintf(out, "\n# Set path for core plugins\n");
fprintf(out, "BNSetBundledPluginDirectory(os.path.join(_base_path, \"plugins\"))\n");
fclose(out);
+ fclose(enums);
return 0;
}
diff --git a/python/highlight.py b/python/highlight.py
index 98735166..6af1cf95 100644
--- a/python/highlight.py
+++ b/python/highlight.py
@@ -21,66 +21,67 @@
# Binary Ninja components
import _binaryninjacore as core
+from enums import HighlightColorStyle, HighlightStandardColor
class HighlightColor(object):
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 = core.BNHighlightColorStyle.CustomHighlightColor
+ self.style = HighlightColorStyle.CustomHighlightColor
self.red = red
self.green = green
self.blue = blue
elif (mix_color is not None) and (mix is not None):
- self.style = core.BNHighlightColorStyle.MixedHighlightColor
+ self.style = HighlightColorStyle.MixedHighlightColor
if color is None:
- self.color = core.BNHighlightStandardColor.NoHighlightColor
+ self.color = HighlightStandardColor.NoHighlightColor
else:
self.color = color
self.mix_color = mix_color
self.mix = mix
else:
- self.style = core.BNHighlightColorStyle.StandardHighlightColor
+ self.style = HighlightColorStyle.StandardHighlightColor
if color is None:
- self.color = core.BNHighlightStandardColor.NoHighlightColor
+ self.color = HighlightStandardColor.NoHighlightColor
else:
self.color = color
self.alpha = alpha
def _standard_color_to_str(self, color):
- if color == core.BNHighlightStandardColor.NoHighlightColor:
+ if color == HighlightStandardColor.NoHighlightColor:
return "none"
- if color == core.BNHighlightStandardColor.BlueHighlightColor:
+ if color == HighlightStandardColor.BlueHighlightColor:
return "blue"
- if color == core.BNHighlightStandardColor.GreenHighlightColor:
+ if color == HighlightStandardColor.GreenHighlightColor:
return "green"
- if color == core.BNHighlightStandardColor.CyanHighlightColor:
+ if color == HighlightStandardColor.CyanHighlightColor:
return "cyan"
- if color == core.BNHighlightStandardColor.RedHighlightColor:
+ if color == HighlightStandardColor.RedHighlightColor:
return "red"
- if color == core.BNHighlightStandardColor.MagentaHighlightColor:
+ if color == HighlightStandardColor.MagentaHighlightColor:
return "magenta"
- if color == core.BNHighlightStandardColor.YellowHighlightColor:
+ if color == HighlightStandardColor.YellowHighlightColor:
return "yellow"
- if color == core.BNHighlightStandardColor.OrangeHighlightColor:
+ if color == HighlightStandardColor.OrangeHighlightColor:
return "orange"
- if color == core.BNHighlightStandardColor.WhiteHighlightColor:
+ if color == HighlightStandardColor.WhiteHighlightColor:
return "white"
- if color == core.BNHighlightStandardColor.BlackHighlightColor:
+ if color == HighlightStandardColor.BlackHighlightColor:
return "black"
return "%d" % color
def __repr__(self):
- if self.style == core.BNHighlightColorStyle.StandardHighlightColor:
+ if self.style == HighlightColorStyle.StandardHighlightColor:
if self.alpha == 255:
return "<color: %s>" % self._standard_color_to_str(self.color)
return "<color: %s, alpha %d>" % (self._standard_color_to_str(self.color), self.alpha)
- if self.style == core.BNHighlightColorStyle.MixedHighlightColor:
+ 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)
- if self.style == core.BNHighlightColorStyle.CustomHighlightColor:
+ if self.style == HighlightColorStyle.CustomHighlightColor:
if self.alpha == 255:
return "<color: #%.2x%.2x%.2x>" % (self.red, self.green, self.blue)
return "<color: #%.2x%.2x%.2x, alpha %d>" % (self.red, self.green, self.blue, self.alpha)
@@ -89,21 +90,21 @@ class HighlightColor(object):
def _get_core_struct(self):
result = core.BNHighlightColor()
result.style = self.style
- result.color = core.BNHighlightStandardColor.NoHighlightColor
- result.mix_color = core.BNHighlightStandardColor.NoHighlightColor
+ result.color = HighlightStandardColor.NoHighlightColor
+ result.mix_color = HighlightStandardColor.NoHighlightColor
result.mix = 0
result.r = 0
result.g = 0
result.b = 0
result.alpha = self.alpha
- if self.style == core.BNHighlightColorStyle.StandardHighlightColor:
+ if self.style == HighlightColorStyle.StandardHighlightColor:
result.color = self.color
- elif self.style == core.BNHighlightColorStyle.MixedHighlightColor:
+ elif self.style == HighlightColorStyle.MixedHighlightColor:
result.color = self.color
result.mixColor = self.mix_color
result.mix = self.mix
- elif self.style == core.BNHighlightColorStyle.CustomHighlightColor:
+ elif self.style == HighlightColorStyle.CustomHighlightColor:
result.r = self.red
result.g = self.green
result.b = self.blue
diff --git a/python/interaction.py b/python/interaction.py
index 1899b7aa..6d640d17 100644
--- a/python/interaction.py
+++ b/python/interaction.py
@@ -23,6 +23,7 @@ import traceback
# Binary Ninja components
import _binaryninjacore as core
+from enums import FormInputFieldType, MessageBoxIcon, MessageBoxButtonResult
import binaryview
import log
@@ -32,7 +33,7 @@ class LabelField(object):
self.text = text
def _fill_core_struct(self, value):
- value.type = core.BNFormInputFieldType.LabelFormField
+ value.type = FormInputFieldType.LabelFormField
value.prompt = self.text
def _fill_core_result(self, value):
@@ -44,7 +45,7 @@ class LabelField(object):
class SeparatorField(object):
def _fill_core_struct(self, value):
- value.type = core.BNFormInputFieldType.SeparatorFormField
+ value.type = FormInputFieldType.SeparatorFormField
def _fill_core_result(self, value):
pass
@@ -59,7 +60,7 @@ class TextLineField(object):
self.result = None
def _fill_core_struct(self, value):
- value.type = core.BNFormInputFieldType.TextLineFormField
+ value.type = FormInputFieldType.TextLineFormField
value.prompt = self.prompt
def _fill_core_result(self, value):
@@ -75,7 +76,7 @@ class MultilineTextField(object):
self.result = None
def _fill_core_struct(self, value):
- value.type = core.BNFormInputFieldType.MultilineTextFormField
+ value.type = FormInputFieldType.MultilineTextFormField
value.prompt = self.prompt
def _fill_core_result(self, value):
@@ -91,7 +92,7 @@ class IntegerField(object):
self.result = None
def _fill_core_struct(self, value):
- value.type = core.BNFormInputFieldType.IntegerFormField
+ value.type = FormInputFieldType.IntegerFormField
value.prompt = self.prompt
def _fill_core_result(self, value):
@@ -109,7 +110,7 @@ class AddressField(object):
self.result = None
def _fill_core_struct(self, value):
- value.type = core.BNFormInputFieldType.AddressFormField
+ value.type = FormInputFieldType.AddressFormField
value.prompt = self.prompt
value.view = None
if self.view is not None:
@@ -130,7 +131,7 @@ class ChoiceField(object):
self.result = None
def _fill_core_struct(self, value):
- value.type = core.BNFormInputFieldType.ChoiceFormField
+ value.type = FormInputFieldType.ChoiceFormField
value.prompt = self.prompt
choice_buf = (ctypes.c_char_p * len(self.choices))()
for i in xrange(0, len(self.choices)):
@@ -152,7 +153,7 @@ class OpenFileNameField(object):
self.result = None
def _fill_core_struct(self, value):
- value.type = core.BNFormInputFieldType.OpenFileNameFormField
+ value.type = FormInputFieldType.OpenFileNameFormField
value.prompt = self.prompt
value.ext = self.ext
@@ -171,7 +172,7 @@ class SaveFileNameField(object):
self.result = None
def _fill_core_struct(self, value):
- value.type = core.BNFormInputFieldType.SaveFileNameFormField
+ value.type = FormInputFieldType.SaveFileNameFormField
value.prompt = self.prompt
value.ext = self.ext
value.defaultName = self.default_name
@@ -190,7 +191,7 @@ class DirectoryNameField(object):
self.result = None
def _fill_core_struct(self, value):
- value.type = core.DirectoryNameField
+ value.type = DirectoryNameField
value.prompt = self.prompt
value.defaultName = self.default_name
@@ -335,31 +336,31 @@ class InteractionHandler(object):
try:
field_objs = []
for i in xrange(0, count):
- if fields[i].type == core.BNFormInputFieldType.LabelFormField:
+ if fields[i].type == FormInputFieldType.LabelFormField:
field_objs.append(LabelField(fields[i].prompt))
- elif fields[i].type == core.BNFormInputFieldType.SeparatorFormField:
+ elif fields[i].type == FormInputFieldType.SeparatorFormField:
field_objs.append(SeparatorField())
- elif fields[i].type == core.BNFormInputFieldType.TextLineFormField:
+ elif fields[i].type == FormInputFieldType.TextLineFormField:
field_objs.append(TextLineField(fields[i].prompt))
- elif fields[i].type == core.BNFormInputFieldType.MultilineTextFormField:
+ elif fields[i].type == FormInputFieldType.MultilineTextFormField:
field_objs.append(MultilineTextField(fields[i].prompt))
- elif fields[i].type == core.BNFormInputFieldType.IntegerFormField:
+ elif fields[i].type == FormInputFieldType.IntegerFormField:
field_objs.append(IntegerField(fields[i].prompt))
- elif fields[i].type == core.BNFormInputFieldType.AddressFormField:
+ 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))
- elif fields[i].type == core.BNFormInputFieldType.ChoiceFormField:
+ elif fields[i].type == FormInputFieldType.ChoiceFormField:
choices = []
for i in xrange(0, fields[i].count):
choices.append(fields[i].choices[i])
field_objs.append(ChoiceField(fields[i].prompt, choices))
- elif fields[i].type == core.BNFormInputFieldType.OpenFileNameFormField:
+ elif fields[i].type == FormInputFieldType.OpenFileNameFormField:
field_objs.append(OpenFileNameField(fields[i].prompt, fields[i].ext))
- elif fields[i].type == core.BNFormInputFieldType.SaveFileNameFormField:
+ elif fields[i].type == FormInputFieldType.SaveFileNameFormField:
field_objs.append(SaveFileNameField(fields[i].prompt, fields[i].ext, fields[i].defaultName))
- elif fields[i].type == core.DirectoryNameField:
+ elif fields[i].type == DirectoryNameField:
field_objs.append(DirectoryNameField(fields[i].prompt, fields[i].defaultName))
else:
field_objs.append(LabelField(fields[i].prompt))
@@ -419,7 +420,7 @@ class InteractionHandler(object):
return False
def show_message_box(self, title, text, buttons, icon):
- return core.BNMessageBoxButtonResult.CancelButton
+ return MessageBoxButtonResult.CancelButton
def markdown_to_html(contents):
@@ -516,5 +517,5 @@ def get_form_input(fields, title):
return True
-def show_message_box(title, text, buttons = core.BNMessageBoxButtonResult.OKButton, icon = core.BNMessageBoxIcon.InformationIcon):
+def show_message_box(title, text, buttons = MessageBoxButtonResult.OKButton, icon = MessageBoxIcon.InformationIcon):
return core.BNShowMessageBox(title, text, buttons, icon)
diff --git a/python/log.py b/python/log.py
index 932c739d..45adb4aa 100644
--- a/python/log.py
+++ b/python/log.py
@@ -57,7 +57,7 @@ def log_debug(text):
:rtype: None
:Example:
- >>> log_to_stdout(core.BNLogLevel.DebugLog)
+ >>> log_to_stdout(LogLevel.DebugLog)
>>> log_debug("Hotdogs!")
Hotdogs!
"""
@@ -87,7 +87,7 @@ def log_warn(text):
:rtype: None
:Example:
- >>> log_to_stdout(core.BNLogLevel.DebugLog)
+ >>> log_to_stdout(LogLevel.DebugLog)
>>> log_info("Chilidogs!")
Chilidogs!
>>>
@@ -103,7 +103,7 @@ def log_error(text):
:rtype: None
:Example:
- >>> log_to_stdout(core.BNLogLevel.DebugLog)
+ >>> log_to_stdout(LogLevel.DebugLog)
>>> log_error("Spanferkel!")
Spanferkel!
>>>
@@ -119,7 +119,7 @@ def log_alert(text):
:rtype: None
:Example:
- >>> log_to_stdout(core.BNLogLevel.DebugLog)
+ >>> log_to_stdout(LogLevel.DebugLog)
>>> log_alert("Kielbasa!")
Kielbasa!
>>>
@@ -136,7 +136,7 @@ def log_to_stdout(min_level):
:Example:
>>> log_debug("Hotdogs!")
- >>> log_to_stdout(core.BNLogLevel.DebugLog)
+ >>> log_to_stdout(LogLevel.DebugLog)
>>> log_debug("Hotdogs!")
Hotdogs!
>>>
diff --git a/python/lowlevelil.py b/python/lowlevelil.py
index 7025a7c1..4564bf13 100644
--- a/python/lowlevelil.py
+++ b/python/lowlevelil.py
@@ -22,6 +22,7 @@ import ctypes
# Binary Ninja components
import _binaryninjacore as core
+from .enums import LowLevelILOperation, LowLevelILFlagCondition, InstructionTextTokenType
import function
import basicblock
@@ -43,73 +44,73 @@ class LowLevelILInstruction(object):
"""
ILOperations = {
- core.BNLowLevelILOperation.LLIL_NOP: [],
- core.BNLowLevelILOperation.LLIL_SET_REG: [("dest", "reg"), ("src", "expr")],
- core.BNLowLevelILOperation.LLIL_SET_REG_SPLIT: [("hi", "reg"), ("lo", "reg"), ("src", "expr")],
- core.BNLowLevelILOperation.LLIL_SET_FLAG: [("dest", "flag"), ("src", "expr")],
- core.BNLowLevelILOperation.LLIL_LOAD: [("src", "expr")],
- core.BNLowLevelILOperation.LLIL_STORE: [("dest", "expr"), ("src", "expr")],
- core.BNLowLevelILOperation.LLIL_PUSH: [("src", "expr")],
- core.BNLowLevelILOperation.LLIL_POP: [],
- core.BNLowLevelILOperation.LLIL_REG: [("src", "reg")],
- core.BNLowLevelILOperation.LLIL_CONST: [("value", "int")],
- core.BNLowLevelILOperation.LLIL_FLAG: [("src", "flag")],
- core.BNLowLevelILOperation.LLIL_FLAG_BIT: [("src", "flag"), ("bit", "int")],
- core.BNLowLevelILOperation.LLIL_ADD: [("left", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_ADC: [("left", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_SUB: [("left", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_SBB: [("left", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_AND: [("left", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_OR: [("left", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_XOR: [("left", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_LSL: [("left", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_LSR: [("left", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_ASR: [("left", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_ROL: [("left", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_RLC: [("left", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_ROR: [("left", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_RRC: [("left", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_MUL: [("left", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_MULU_DP: [("left", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_MULS_DP: [("left", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_DIVU: [("left", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_DIVU_DP: [("hi", "expr"), ("lo", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_DIVS: [("left", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_DIVS_DP: [("hi", "expr"), ("lo", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_MODU: [("left", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_MODU_DP: [("hi", "expr"), ("lo", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_MODS: [("left", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_MODS_DP: [("hi", "expr"), ("lo", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_NEG: [("src", "expr")],
- core.BNLowLevelILOperation.LLIL_NOT: [("src", "expr")],
- core.BNLowLevelILOperation.LLIL_SX: [("src", "expr")],
- core.BNLowLevelILOperation.LLIL_ZX: [("src", "expr")],
- core.BNLowLevelILOperation.LLIL_JUMP: [("dest", "expr")],
- core.BNLowLevelILOperation.LLIL_JUMP_TO: [("dest", "expr"), ("targets", "int_list")],
- core.BNLowLevelILOperation.LLIL_CALL: [("dest", "expr")],
- core.BNLowLevelILOperation.LLIL_RET: [("dest", "expr")],
- core.BNLowLevelILOperation.LLIL_NORET: [],
- core.BNLowLevelILOperation.LLIL_IF: [("condition", "expr"), ("true", "int"), ("false", "int")],
- core.BNLowLevelILOperation.LLIL_GOTO: [("dest", "int")],
- core.BNLowLevelILOperation.LLIL_FLAG_COND: [("condition", "cond")],
- core.BNLowLevelILOperation.LLIL_CMP_E: [("left", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_CMP_NE: [("left", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_CMP_SLT: [("left", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_CMP_ULT: [("left", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_CMP_SLE: [("left", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_CMP_ULE: [("left", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_CMP_SGE: [("left", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_CMP_UGE: [("left", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_CMP_SGT: [("left", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_CMP_UGT: [("left", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_TEST_BIT: [("left", "expr"), ("right", "expr")],
- core.BNLowLevelILOperation.LLIL_BOOL_TO_INT: [("src", "expr")],
- core.BNLowLevelILOperation.LLIL_SYSCALL: [],
- core.BNLowLevelILOperation.LLIL_BP: [],
- core.BNLowLevelILOperation.LLIL_TRAP: [("value", "int")],
- core.BNLowLevelILOperation.LLIL_UNDEF: [],
- core.BNLowLevelILOperation.LLIL_UNIMPL: [],
- core.BNLowLevelILOperation.LLIL_UNIMPL_MEM: [("src", "expr")]
+ 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_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_CONST: [("value", "int")],
+ 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")],
+ LowLevelILOperation.LLIL_SUB: [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_SBB: [("left", "expr"), ("right", "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")],
+ LowLevelILOperation.LLIL_ROR: [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_RRC: [("left", "expr"), ("right", "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: [("hi", "expr"), ("lo", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_DIVS: [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_DIVS_DP: [("hi", "expr"), ("lo", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_MODU: [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_MODU_DP: [("hi", "expr"), ("lo", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_MODS: [("left", "expr"), ("right", "expr")],
+ LowLevelILOperation.LLIL_MODS_DP: [("hi", "expr"), ("lo", "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_JUMP: [("dest", "expr")],
+ LowLevelILOperation.LLIL_JUMP_TO: [("dest", "expr"), ("targets", "int_list")],
+ LowLevelILOperation.LLIL_CALL: [("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")],
+ 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_SYSCALL: [],
+ LowLevelILOperation.LLIL_BP: [],
+ LowLevelILOperation.LLIL_TRAP: [("value", "int")],
+ LowLevelILOperation.LLIL_UNDEF: [],
+ LowLevelILOperation.LLIL_UNIMPL: [],
+ LowLevelILOperation.LLIL_UNIMPL_MEM: [("src", "expr")]
}
def __init__(self, func, expr_index, instr_index=None):
@@ -118,7 +119,7 @@ class LowLevelILInstruction(object):
self.expr_index = expr_index
self.instr_index = instr_index
self.operation = instr.operation
- self.operation_name = core.BNLowLevelILOperation(instr.operation)
+ self.operation_name = LowLevelILOperation(instr.operation)
self.size = instr.size
self.address = instr.address
self.source_operand = instr.sourceOperand
@@ -144,7 +145,7 @@ class LowLevelILInstruction(object):
elif operand_type == "flag":
value = func.arch.get_flag_name(instr.operands[i])
elif operand_type == "cond":
- value = core.BNLowLevelILFlagCondition(instr.operands[i])
+ value = LowLevelILFlagCondition(instr.operands[i])
elif operand_type == "int_list":
count = ctypes.c_ulonglong()
operands = core.BNLowLevelILGetOperandList(func.handle, self.expr_index, i, count)
@@ -182,7 +183,7 @@ class LowLevelILInstruction(object):
return None
result = []
for i in xrange(0, count.value):
- token_type = core.BNInstructionTextTokenType(tokens[i].type)
+ token_type = InstructionTextTokenType(tokens[i].type)
text = tokens[i].text
value = tokens[i].value
size = tokens[i].size
@@ -329,8 +330,8 @@ class LowLevelILFunction(object):
def expr(self, operation, a = 0, b = 0, c = 0, d = 0, size = 0, flags = None):
if isinstance(operation, str):
- operation = core.BNLowLevelILOperation[operation]
- elif isinstance(operation, core.BNLowLevelILOperation):
+ operation = LowLevelILOperation[operation]
+ elif isinstance(operation, LowLevelILOperation):
operation = operation.value
if isinstance(flags, str):
flags = self.arch.get_flag_write_type_by_name(flags)
@@ -355,7 +356,7 @@ class LowLevelILFunction(object):
:return: The no operation expression
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_NOP)
+ return self.expr(LowLevelILOperation.LLIL_NOP)
def set_reg(self, size, reg, value, flags = 0):
"""
@@ -370,7 +371,7 @@ class LowLevelILFunction(object):
"""
if isinstance(reg, str):
reg = self.arch.regs[reg].index
- return self.expr(core.BNLowLevelILOperation.LLIL_SET_REG, reg, value.index, size = size, flags = flags)
+ return self.expr(LowLevelILOperation.LLIL_SET_REG, reg, value.index, size = size, flags = flags)
def set_reg_split(self, size, hi, lo, value, flags = 0):
"""
@@ -389,7 +390,7 @@ class LowLevelILFunction(object):
hi = self.arch.regs[hi].index
if isinstance(lo, str):
lo = self.arch.regs[lo].index
- return self.expr(core.BNLowLevelILOperation.LLIL_SET_REG_SPLIT, hi, lo, value.index, size = size, flags = flags)
+ return self.expr(LowLevelILOperation.LLIL_SET_REG_SPLIT, hi, lo, value.index, size = size, flags = flags)
def set_flag(self, flag, value):
"""
@@ -400,7 +401,7 @@ class LowLevelILFunction(object):
:return: The expression FLAG.flag = value
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_SET_FLAG, self.arch.get_flag_by_name(flag), value.index)
+ return self.expr(LowLevelILOperation.LLIL_SET_FLAG, self.arch.get_flag_by_name(flag), value.index)
def load(self, size, addr):
"""
@@ -411,7 +412,7 @@ class LowLevelILFunction(object):
:return: The expression ``[addr].size``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_LOAD, addr.index, size=size)
+ return self.expr(LowLevelILOperation.LLIL_LOAD, addr.index, size=size)
def store(self, size, addr, value):
"""
@@ -423,7 +424,7 @@ class LowLevelILFunction(object):
:return: The expression ``[addr].size = value``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_STORE, addr.index, value.index, size=size)
+ return self.expr(LowLevelILOperation.LLIL_STORE, addr.index, value.index, size=size)
def push(self, size, value):
"""
@@ -434,7 +435,7 @@ class LowLevelILFunction(object):
:return: The expression push(value)
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_PUSH, value.index, size=size)
+ return self.expr(LowLevelILOperation.LLIL_PUSH, value.index, size=size)
def pop(self, size):
"""
@@ -444,7 +445,7 @@ class LowLevelILFunction(object):
:return: The expression ``pop``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_POP, size=size)
+ return self.expr(LowLevelILOperation.LLIL_POP, size=size)
def reg(self, size, reg):
"""
@@ -457,7 +458,7 @@ class LowLevelILFunction(object):
"""
if isinstance(reg, str):
reg = self.arch.regs[reg].index
- return self.expr(core.BNLowLevelILOperation.LLIL_REG, reg, size=size)
+ return self.expr(LowLevelILOperation.LLIL_REG, reg, size=size)
def const(self, size, value):
"""
@@ -468,7 +469,7 @@ class LowLevelILFunction(object):
:return: A constant expression of given value and size
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_CONST, value, size=size)
+ return self.expr(LowLevelILOperation.LLIL_CONST, value, size=size)
def flag(self, reg):
"""
@@ -478,7 +479,7 @@ class LowLevelILFunction(object):
:return: A flag expression of given flag name
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_FLAG, self.arch.get_flag_by_name(reg))
+ return self.expr(LowLevelILOperation.LLIL_FLAG, self.arch.get_flag_by_name(reg))
def flag_bit(self, size, reg, bit):
"""
@@ -490,7 +491,7 @@ class LowLevelILFunction(object):
:return: A constant expression of given value and size ``FLAG.reg = bit``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_FLAG_BIT, self.arch.get_flag_by_name(reg), bit, size=size)
+ return self.expr(LowLevelILOperation.LLIL_FLAG_BIT, self.arch.get_flag_by_name(reg), bit, size=size)
def add(self, size, a, b, flags=None):
"""
@@ -504,7 +505,7 @@ class LowLevelILFunction(object):
:return: The expression ``add.<size>{<flags>}(a, b)``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_ADD, a.index, b.index, size=size, flags=flags)
+ return self.expr(LowLevelILOperation.LLIL_ADD, a.index, b.index, size=size, flags=flags)
def add_carry(self, size, a, b, flags=None):
"""
@@ -518,7 +519,7 @@ class LowLevelILFunction(object):
:return: The expression ``adc.<size>{<flags>}(a, b)``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_ADC, a.index, b.index, size=size, flags=flags)
+ return self.expr(LowLevelILOperation.LLIL_ADC, a.index, b.index, size=size, flags=flags)
def sub(self, size, a, b, flags=None):
"""
@@ -532,7 +533,7 @@ class LowLevelILFunction(object):
:return: The expression ``sub.<size>{<flags>}(a, b)``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_SUB, a.index, b.index, size=size, flags=flags)
+ return self.expr(LowLevelILOperation.LLIL_SUB, a.index, b.index, size=size, flags=flags)
def sub_borrow(self, size, a, b, flags=None):
"""
@@ -546,7 +547,7 @@ class LowLevelILFunction(object):
:return: The expression ``sbc.<size>{<flags>}(a, b)``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_SBB, a.index, b.index, size=size, flags=flags)
+ return self.expr(LowLevelILOperation.LLIL_SBB, a.index, b.index, size=size, flags=flags)
def and_expr(self, size, a, b, flags=None):
"""
@@ -560,7 +561,7 @@ class LowLevelILFunction(object):
:return: The expression ``and.<size>{<flags>}(a, b)``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_AND, a.index, b.index, size=size, flags=flags)
+ return self.expr(LowLevelILOperation.LLIL_AND, a.index, b.index, size=size, flags=flags)
def or_expr(self, size, a, b, flags=None):
"""
@@ -574,7 +575,7 @@ class LowLevelILFunction(object):
:return: The expression ``or.<size>{<flags>}(a, b)``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_OR, a.index, b.index, size=size, flags=flags)
+ return self.expr(LowLevelILOperation.LLIL_OR, a.index, b.index, size=size, flags=flags)
def xor_expr(self, size, a, b, flags=None):
"""
@@ -588,7 +589,7 @@ class LowLevelILFunction(object):
:return: The expression ``xor.<size>{<flags>}(a, b)``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_XOR, a.index, b.index, size=size, flags=flags)
+ return self.expr(LowLevelILOperation.LLIL_XOR, a.index, b.index, size=size, flags=flags)
def shift_left(self, size, a, b, flags=None):
"""
@@ -602,7 +603,7 @@ class LowLevelILFunction(object):
:return: The expression ``lsl.<size>{<flags>}(a, b)``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_LSL, a.index, b.index, size=size, flags=flags)
+ return self.expr(LowLevelILOperation.LLIL_LSL, a.index, b.index, size=size, flags=flags)
def logical_shift_right(self, size, a, b, flags=None):
"""
@@ -616,7 +617,7 @@ class LowLevelILFunction(object):
:return: The expression ``lsr.<size>{<flags>}(a, b)``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_LSR, a.index, b.index, size=size, flags=flags)
+ return self.expr(LowLevelILOperation.LLIL_LSR, a.index, b.index, size=size, flags=flags)
def arith_shift_right(self, size, a, b, flags=None):
"""
@@ -630,7 +631,7 @@ class LowLevelILFunction(object):
:return: The expression ``asr.<size>{<flags>}(a, b)``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_ASR, a.index, b.index, size=size, flags=flags)
+ return self.expr(LowLevelILOperation.LLIL_ASR, a.index, b.index, size=size, flags=flags)
def rotate_left(self, size, a, b, flags=None):
"""
@@ -644,7 +645,7 @@ class LowLevelILFunction(object):
:return: The expression ``rol.<size>{<flags>}(a, b)``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_ROL, a.index, b.index, size=size, flags=flags)
+ return self.expr(LowLevelILOperation.LLIL_ROL, a.index, b.index, size=size, flags=flags)
def rotate_left_carry(self, size, a, b, flags=None):
"""
@@ -658,7 +659,7 @@ class LowLevelILFunction(object):
:return: The expression ``rcl.<size>{<flags>}(a, b)``
:rtype: LowLevelILExpr
"""
- return self.expr(core.LLIL_RLC, a.index, b.index, size=size, flags=flags)
+ return self.expr(LowLevelILOperation.LLIL_RLC, a.index, b.index, size=size, flags=flags)
def rotate_right(self, size, a, b, flags=None):
"""
@@ -672,7 +673,7 @@ class LowLevelILFunction(object):
:return: The expression ``ror.<size>{<flags>}(a, b)``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_ROR, a.index, b.index, size=size, flags=flags)
+ return self.expr(LowLevelILOperation.LLIL_ROR, a.index, b.index, size=size, flags=flags)
def rotate_right_carry(self, size, a, b, flags=None):
"""
@@ -686,7 +687,7 @@ class LowLevelILFunction(object):
:return: The expression ``rcr.<size>{<flags>}(a, b)``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_RRC, a.index, b.index, size=size, flags=flags)
+ return self.expr(LowLevelILOperation.LLIL_RRC, a.index, b.index, size=size, flags=flags)
def mult(self, size, a, b, flags=None):
"""
@@ -700,7 +701,7 @@ class LowLevelILFunction(object):
:return: The expression ``sbc.<size>{<flags>}(a, b)``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_MUL, a.index, b.index, size=size, flags=flags)
+ return self.expr(LowLevelILOperation.LLIL_MUL, a.index, b.index, size=size, flags=flags)
def mult_double_prec_signed(self, size, a, b, flags=None):
"""
@@ -714,7 +715,7 @@ class LowLevelILFunction(object):
:return: The expression ``muls.dp.<size>{<flags>}(a, b)``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_MULS_DP, a.index, b.index, size=size, flags=flags)
+ return self.expr(LowLevelILOperation.LLIL_MULS_DP, a.index, b.index, size=size, flags=flags)
def mult_double_prec_unsigned(self, size, a, b, flags=None):
"""
@@ -728,7 +729,7 @@ class LowLevelILFunction(object):
:return: The expression ``muls.dp.<size>{<flags>}(a, b)``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_MULU_DP, a.index, b.index, size=size, flags=flags)
+ return self.expr(LowLevelILOperation.LLIL_MULU_DP, a.index, b.index, size=size, flags=flags)
def div_signed(self, size, a, b, flags=None):
"""
@@ -742,7 +743,7 @@ class LowLevelILFunction(object):
:return: The expression ``divs.<size>{<flags>}(a, b)``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_DIVS, a.index, b.index, size=size, flags=flags)
+ return self.expr(LowLevelILOperation.LLIL_DIVS, a.index, b.index, size=size, flags=flags)
def div_double_prec_signed(self, size, hi, lo, b, flags=None):
"""
@@ -758,7 +759,7 @@ class LowLevelILFunction(object):
:return: The expression ``divs.dp.<size>{<flags>}(hi:lo, b)``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_DIVS_DP, hi.index, lo.index, b.index, size=size, flags=flags)
+ return self.expr(LowLevelILOperation.LLIL_DIVS_DP, hi.index, lo.index, b.index, size=size, flags=flags)
def div_unsigned(self, size, a, b, flags=None):
"""
@@ -772,7 +773,7 @@ class LowLevelILFunction(object):
:return: The expression ``divs.<size>{<flags>}(a, b)``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_DIVS, a.index, b.index, size=size, flags=flags)
+ return self.expr(LowLevelILOperation.LLIL_DIVS, a.index, b.index, size=size, flags=flags)
def div_double_prec_unsigned(self, size, hi, lo, b, flags=None):
"""
@@ -788,7 +789,7 @@ class LowLevelILFunction(object):
:return: The expression ``divs.dp.<size>{<flags>}(hi:lo, b)``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_DIVS_DP, hi.index, lo.index, b.index, size=size, flags=flags)
+ return self.expr(LowLevelILOperation.LLIL_DIVS_DP, hi.index, lo.index, b.index, size=size, flags=flags)
def mod_signed(self, size, a, b, flags=None):
"""
@@ -802,7 +803,7 @@ class LowLevelILFunction(object):
:return: The expression ``mods.<size>{<flags>}(a, b)``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_MODS, a.index, b.index, size=size, flags=flags)
+ return self.expr(LowLevelILOperation.LLIL_MODS, a.index, b.index, size=size, flags=flags)
def mod_double_prec_signed(self, size, hi, lo, b, flags=None):
"""
@@ -818,7 +819,7 @@ class LowLevelILFunction(object):
:return: The expression ``mods.dp.<size>{<flags>}(hi:lo, b)``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_MODS_DP, hi.index, lo.index, b.index, size=size, flags=flags)
+ return self.expr(LowLevelILOperation.LLIL_MODS_DP, hi.index, lo.index, b.index, size=size, flags=flags)
def mod_unsigned(self, size, a, b, flags=None):
"""
@@ -832,7 +833,7 @@ class LowLevelILFunction(object):
:return: The expression ``modu.<size>{<flags>}(a, b)``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_MODS, a.index, b.index, size=size, flags=flags)
+ return self.expr(LowLevelILOperation.LLIL_MODS, a.index, b.index, size=size, flags=flags)
def mod_double_prec_unsigned(self, size, hi, lo, b, flags=None):
"""
@@ -848,7 +849,7 @@ class LowLevelILFunction(object):
:return: The expression ``modu.dp.<size>{<flags>}(hi:lo, b)``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_MODS_DP, hi.index, lo.index, b.index, size=size, flags=flags)
+ return self.expr(LowLevelILOperation.LLIL_MODS_DP, hi.index, lo.index, b.index, size=size, flags=flags)
def neg_expr(self, size, value, flags=None):
"""
@@ -860,7 +861,7 @@ class LowLevelILFunction(object):
:return: The expression ``neg.<size>{<flags>}(value)``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_NEG, value.index, size=size, flags=flags)
+ return self.expr(LowLevelILOperation.LLIL_NEG, value.index, size=size, flags=flags)
def not_expr(self, size, value, flags=None):
"""
@@ -872,7 +873,7 @@ class LowLevelILFunction(object):
:return: The expression ``not.<size>{<flags>}(value)``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_NOT, value.index, size=size, flags=flags)
+ return self.expr(LowLevelILOperation.LLIL_NOT, value.index, size=size, flags=flags)
def sign_extend(self, size, value, flags=None):
"""
@@ -884,7 +885,7 @@ class LowLevelILFunction(object):
:return: The expression ``sx.<size>(value)``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_SX, value.index, size=size, flags=flags)
+ return self.expr(LowLevelILOperation.LLIL_SX, value.index, size=size, flags=flags)
def zero_extend(self, size, value):
"""
@@ -895,7 +896,7 @@ class LowLevelILFunction(object):
:return: The expression ``sx.<size>(value)``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_ZX, value.index, size=size)
+ return self.expr(LowLevelILOperation.LLIL_ZX, value.index, size=size)
def jump(self, dest):
"""
@@ -905,7 +906,7 @@ class LowLevelILFunction(object):
:return: The expression ``jump(dest)``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_JUMP, dest.index)
+ return self.expr(LowLevelILOperation.LLIL_JUMP, dest.index)
def call(self, dest):
"""
@@ -916,7 +917,7 @@ class LowLevelILFunction(object):
:return: The expression ``call(dest)``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_CALL, dest.index)
+ return self.expr(LowLevelILOperation.LLIL_CALL, dest.index)
def ret(self, dest):
"""
@@ -927,7 +928,7 @@ class LowLevelILFunction(object):
:return: The expression ``jump(dest)``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_RET, dest.index)
+ return self.expr(LowLevelILOperation.LLIL_RET, dest.index)
def no_ret(self):
"""
@@ -936,7 +937,7 @@ class LowLevelILFunction(object):
:return: The expression ``noreturn``
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_NORET)
+ return self.expr(LowLevelILOperation.LLIL_NORET)
def flag_condition(self, cond):
"""
@@ -947,10 +948,10 @@ class LowLevelILFunction(object):
:rtype: LowLevelILExpr
"""
if isinstance(cond, str):
- cond = core.BNLowLevelILFlagCondition[cond]
- elif isinstance(cond, core.BNLowLevelILFlagCondition):
+ cond = LowLevelILFlagCondition[cond]
+ elif isinstance(cond, LowLevelILFlagCondition):
cond = cond.value
- return self.expr(core.BNLowLevelILOperation.LLIL_FLAG_COND, cond)
+ return self.expr(LowLevelILOperation.LLIL_FLAG_COND, cond)
def compare_equal(self, size, a, b):
"""
@@ -963,7 +964,7 @@ class LowLevelILFunction(object):
:return: a comparison expression.
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_CMP_E, a.index, b.index, size = size)
+ return self.expr(LowLevelILOperation.LLIL_CMP_E, a.index, b.index, size = size)
def compare_not_equal(self, size, a, b):
"""
@@ -976,7 +977,7 @@ class LowLevelILFunction(object):
:return: a comparison expression.
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_CMP_NE, a.index, b.index, size = size)
+ return self.expr(LowLevelILOperation.LLIL_CMP_NE, a.index, b.index, size = size)
def compare_signed_less_than(self, size, a, b):
"""
@@ -989,7 +990,7 @@ class LowLevelILFunction(object):
:return: a comparison expression.
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_CMP_SLT, a.index, b.index, size = size)
+ return self.expr(LowLevelILOperation.LLIL_CMP_SLT, a.index, b.index, size = size)
def compare_unsigned_less_than(self, size, a, b):
"""
@@ -1002,7 +1003,7 @@ class LowLevelILFunction(object):
:return: a comparison expression.
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_CMP_ULT, a.index, b.index, size = size)
+ return self.expr(LowLevelILOperation.LLIL_CMP_ULT, a.index, b.index, size = size)
def compare_signed_less_equal(self, size, a, b):
"""
@@ -1015,7 +1016,7 @@ class LowLevelILFunction(object):
:return: a comparison expression.
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_CMP_SLE, a.index, b.index, size = size)
+ return self.expr(LowLevelILOperation.LLIL_CMP_SLE, a.index, b.index, size = size)
def compare_unsigned_less_equal(self, size, a, b):
"""
@@ -1028,7 +1029,7 @@ class LowLevelILFunction(object):
:return: a comparison expression.
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_CMP_ULE, a.index, b.index, size = size)
+ return self.expr(LowLevelILOperation.LLIL_CMP_ULE, a.index, b.index, size = size)
def compare_signed_greater_equal(self, size, a, b):
"""
@@ -1041,7 +1042,7 @@ class LowLevelILFunction(object):
:return: a comparison expression.
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_CMP_SGE, a.index, b.index, size = size)
+ return self.expr(LowLevelILOperation.LLIL_CMP_SGE, a.index, b.index, size = size)
def compare_unsigned_greater_equal(self, size, a, b):
"""
@@ -1054,7 +1055,7 @@ class LowLevelILFunction(object):
:return: a comparison expression.
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_CMP_UGE, a.index, b.index, size = size)
+ return self.expr(LowLevelILOperation.LLIL_CMP_UGE, a.index, b.index, size = size)
def compare_signed_greater_than(self, size, a, b):
"""
@@ -1067,7 +1068,7 @@ class LowLevelILFunction(object):
:return: a comparison expression.
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_CMP_SGT, a.index, b.index, size = size)
+ return self.expr(LowLevelILOperation.LLIL_CMP_SGT, a.index, b.index, size = size)
def compare_unsigned_greater_than(self, size, a, b):
"""
@@ -1080,10 +1081,10 @@ class LowLevelILFunction(object):
:return: a comparison expression.
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_CMP_UGT, a.index, b.index, size = size)
+ return self.expr(LowLevelILOperation.LLIL_CMP_UGT, a.index, b.index, size = size)
def test_bit(self, size, a, b):
- return self.expr(core.BNLowLevelILOperation.LLIL_TEST_BIT, a.index, b.index, size = size)
+ return self.expr(LowLevelILOperation.LLIL_TEST_BIT, a.index, b.index, size = size)
def system_call(self):
"""
@@ -1092,7 +1093,7 @@ class LowLevelILFunction(object):
:return: a system call expression.
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_SYSCALL)
+ return self.expr(LowLevelILOperation.LLIL_SYSCALL)
def breakpoint(self):
"""
@@ -1101,7 +1102,7 @@ class LowLevelILFunction(object):
:return: a breakpoint expression.
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_BP)
+ return self.expr(LowLevelILOperation.LLIL_BP)
def trap(self, value):
"""
@@ -1111,7 +1112,7 @@ class LowLevelILFunction(object):
:return: a trap expression.
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_TRAP, value)
+ return self.expr(LowLevelILOperation.LLIL_TRAP, value)
def undefined(self):
"""
@@ -1121,7 +1122,7 @@ class LowLevelILFunction(object):
:return: the unimplemented expression.
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_UNDEF)
+ return self.expr(LowLevelILOperation.LLIL_UNDEF)
def unimplemented(self):
"""
@@ -1131,7 +1132,7 @@ class LowLevelILFunction(object):
:return: the unimplemented expression.
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_UNIMPL)
+ return self.expr(LowLevelILOperation.LLIL_UNIMPL)
def unimplemented_memory_ref(self, size, addr):
"""
@@ -1142,7 +1143,7 @@ class LowLevelILFunction(object):
:return: the unimplemented memory reference expression.
:rtype: LowLevelILExpr
"""
- return self.expr(core.BNLowLevelILOperation.LLIL_UNIMPL_MEM, addr.index, size = size)
+ return self.expr(LowLevelILOperation.LLIL_UNIMPL_MEM, addr.index, size = size)
def goto(self, label):
"""
diff --git a/python/platform.py b/python/platform.py
index 6c3eefea..04dce587 100644
--- a/python/platform.py
+++ b/python/platform.py
@@ -20,10 +20,12 @@
import ctypes
-#Binary Ninja components
+# Binary Ninja components
import _binaryninjacore as core
import startup
import architecture
+import callingconvention
+
class _PlatformMetaClass(type):
@property
@@ -60,15 +62,15 @@ class _PlatformMetaClass(type):
def __setattr__(self, name, value):
try:
- type.__setattr__(self,name,value)
+ type.__setattr__(self, name, value)
except AttributeError:
- raise AttributeError, "attribute '%s' is read only" % name
+ raise AttributeError("attribute '%s' is read only" % name)
def __getitem__(cls, value):
startup._init_plugins()
platform = core.BNGetPlatformByName(str(value))
if platform is None:
- raise KeyError, "'%s' is not a valid platform" % str(value)
+ raise KeyError("'%s' is not a valid platform" % str(value))
return Platform(None, platform)
def get_list(cls, os = None, arch = None):
@@ -86,6 +88,7 @@ class _PlatformMetaClass(type):
core.BNFreePlatformList(platforms, count.value)
return result
+
class Platform(object):
"""
``class Platform`` contains all information releated to the execution environment of the binary, mainly the
@@ -118,7 +121,7 @@ class Platform(object):
result = core.BNGetPlatformDefaultCallingConvention(self.handle)
if result is None:
return None
- return CallingConvention(None, result)
+ return callingconvention.CallingConvention(None, result)
@default_calling_convention.setter
def default_calling_convention(self, value):
@@ -136,7 +139,7 @@ class Platform(object):
result = core.BNGetPlatformCdeclCallingConvention(self.handle)
if result is None:
return None
- return CallingConvention(None, result)
+ return callingconvention.CallingConvention(None, result)
@cdecl_calling_convention.setter
def cdecl_calling_convention(self, value):
@@ -154,7 +157,7 @@ class Platform(object):
result = core.BNGetPlatformStdcallCallingConvention(self.handle)
if result is None:
return None
- return CallingConvention(None, result)
+ return callingconvention.CallingConvention(None, result)
@stdcall_calling_convention.setter
def stdcall_calling_convention(self, value):
@@ -172,7 +175,7 @@ class Platform(object):
result = core.BNGetPlatformFastcallCallingConvention(self.handle)
if result is None:
return None
- return CallingConvention(None, result)
+ return callingconvention.CallingConvention(None, result)
@fastcall_calling_convention.setter
def fastcall_calling_convention(self, value):
@@ -190,7 +193,7 @@ class Platform(object):
result = core.BNGetPlatformSystemCallConvention(self.handle)
if result is None:
return None
- return CallingConvention(None, result)
+ return callingconvention.CallingConvention(None, result)
@system_call_convention.setter
def system_call_convention(self, value):
@@ -208,15 +211,15 @@ class Platform(object):
cc = core.BNGetPlatformCallingConventions(self.handle, count)
result = []
for i in xrange(0, count.value):
- result.append(CallingConvention(None, core.BNNewCallingConventionReference(cc[i])))
+ result.append(callingconvention.CallingConvention(None, core.BNNewCallingConventionReference(cc[i])))
core.BNFreeCallingConventionList(cc, count.value)
return result
def __setattr__(self, name, value):
try:
- object.__setattr__(self,name,value)
+ object.__setattr__(self, name, value)
except AttributeError:
- raise AttributeError, "attribute '%s' is read only" % name
+ raise AttributeError("attribute '%s' is read only" % name)
def __repr__(self):
return "<platform: %s>" % self.name
@@ -250,3 +253,9 @@ class Platform(object):
def add_related_platform(self, arch, platform):
core.BNAddRelatedPlatform(self.handle, arch.handle, platform.handle)
+
+ def get_associated_platform_by_address(self, addr):
+ new_addr = ctypes.c_ulonglong()
+ new_addr.value = addr
+ result = core.BNGetAssociatedPlatformByAddress(self.handle, new_addr)
+ return Platform(None, handle = result), new_addr.value
diff --git a/python/plugin.py b/python/plugin.py
index b6faef7f..9a4da487 100644
--- a/python/plugin.py
+++ b/python/plugin.py
@@ -24,6 +24,7 @@ import threading
# Binary Ninja components
import _binaryninjacore as core
+from enums import LowLevelILOperation
import startup
import filemetadata
import binaryview
@@ -77,7 +78,7 @@ class PluginCommand(object):
ctypes.memmove(ctypes.byref(self.command), ctypes.byref(cmd), ctypes.sizeof(core.BNPluginCommand))
self.name = str(cmd.name)
self.description = str(cmd.description)
- self.type = core.BNPluginCommandType(cmd.type)
+ self.type = LowLevelILOperation(cmd.type)
@classmethod
def _default_action(cls, view, action):
@@ -209,21 +210,21 @@ class PluginCommand(object):
def is_valid(self, context):
if context.view is None:
return False
- if self.command.type == core.BNPluginCommandType.DefaultPluginCommand:
+ if self.command.type == LowLevelILOperation.DefaultPluginCommand:
if not self.command.defaultIsValid:
return True
return self.command.defaultIsValid(self.command.context, context.view.handle)
- elif self.command.type == core.BNPluginCommandType.AddressPluginCommand:
+ elif self.command.type == LowLevelILOperation.AddressPluginCommand:
if not self.command.addressIsValid:
return True
return self.command.addressIsValid(self.command.context, context.view.handle, context.address)
- elif self.command.type == core.BNPluginCommandType.RangePluginCommand:
+ elif self.command.type == LowLevelILOperation.RangePluginCommand:
if context.length == 0:
return False
if not self.command.rangeIsValid:
return True
return self.command.rangeIsValid(self.command.context, context.view.handle, context.address, context.length)
- elif self.command.type == core.BNPluginCommandType.FunctionPluginCommand:
+ elif self.command.type == LowLevelILOperation.FunctionPluginCommand:
if context.function is None:
return False
if not self.command.functionIsValid:
@@ -234,13 +235,13 @@ class PluginCommand(object):
def execute(self, context):
if not self.is_valid(context):
return
- if self.command.type == core.BNPluginCommandType.DefaultPluginCommand:
+ if self.command.type == LowLevelILOperation.DefaultPluginCommand:
self.command.defaultCommand(self.command.context, context.view.handle)
- elif self.command.type == core.BNPluginCommandType.AddressPluginCommand:
+ elif self.command.type == LowLevelILOperation.AddressPluginCommand:
self.command.addressCommand(self.command.context, context.view.handle, context.address)
- elif self.command.type == core.BNPluginCommandType.RangePluginCommand:
+ elif self.command.type == LowLevelILOperation.RangePluginCommand:
self.command.rangeCommand(self.command.context, context.view.handle, context.address, context.length)
- elif self.command.type == core.BNPluginCommandType.FunctionPluginCommand:
+ elif self.command.type == LowLevelILOperation.FunctionPluginCommand:
self.command.functionCommand(self.command.context, context.view.handle, context.function.handle)
def __repr__(self):
diff --git a/python/scriptingprovider.py b/python/scriptingprovider.py
index 079b47cd..71402b1b 100644
--- a/python/scriptingprovider.py
+++ b/python/scriptingprovider.py
@@ -28,6 +28,7 @@ import sys
# Binary Ninja Components
import _binaryninjacore as core
+from enums import ScriptingProviderExecuteResult, ScriptingProviderInputReadyState
import binaryview
import function
import basicblock
@@ -131,7 +132,7 @@ class ScriptingInstance(object):
return self.perform_execute_script_input(text)
except:
log.log_error(traceback.format_exc())
- return core.BNScriptingProviderExecuteResult.InvalidScriptInput
+ return ScriptingProviderExecuteResult.InvalidScriptInput
def _set_current_binary_view(self, ctxt, view):
try:
@@ -186,7 +187,7 @@ class ScriptingInstance(object):
@abc.abstractmethod
def perform_execute_script_input(self, text):
- return core.BNScriptingProviderExecuteResult.InvalidScriptInput
+ return ScriptingProviderExecuteResult.InvalidScriptInput
@abc.abstractmethod
def perform_set_current_binary_view(self, view):
@@ -506,7 +507,7 @@ class PythonScriptingInstance(ScriptingInstance):
result = self.input
self.input = ""
return result
- self.instance.input_ready_state = core.BNScriptingProviderInputReadyState.ReadyForScriptProgramInput
+ self.instance.input_ready_state = ScriptingProviderInputReadyState.ReadyForScriptProgramInput
self.event.wait()
self.event.clear()
return ""
@@ -518,7 +519,7 @@ class PythonScriptingInstance(ScriptingInstance):
if self.exit:
break
if self.code is not None:
- self.instance.input_ready_state = core.BNScriptingProviderInputReadyState.NotReadyForInput
+ self.instance.input_ready_state = ScriptingProviderInputReadyState.NotReadyForInput
code = self.code
self.code = None
@@ -551,7 +552,7 @@ class PythonScriptingInstance(ScriptingInstance):
traceback.print_exc()
finally:
PythonScriptingInstance._interpreter.value = None
- self.instance.input_ready_state = core.BNScriptingProviderInputReadyState.ReadyForScriptExecution
+ self.instance.input_ready_state = ScriptingProviderInputReadyState.ReadyForScriptExecution
def get_selected_data(self):
if self.active_view is None:
@@ -575,7 +576,7 @@ class PythonScriptingInstance(ScriptingInstance):
self.interpreter = PythonScriptingInstance.InterpreterThread(self)
self.interpreter.start()
self.queued_input = ""
- self.input_ready_state = core.BNScriptingProviderInputReadyState.ReadyForScriptExecution
+ self.input_ready_state = ScriptingProviderInputReadyState.ReadyForScriptExecution
@abc.abstractmethod
def perform_destroy_instance(self):
@@ -583,15 +584,15 @@ class PythonScriptingInstance(ScriptingInstance):
@abc.abstractmethod
def perform_execute_script_input(self, text):
- if self.input_ready_state == core.BNScriptingProviderInputReadyState.NotReadyForInput:
- return core.BNScriptingProviderExecuteResult.InvalidScriptInput
+ if self.input_ready_state == ScriptingProviderInputReadyState.NotReadyForInput:
+ return ScriptingProviderExecuteResult.InvalidScriptInput
- if self.input_ready_state == core.BNScriptingProviderInputReadyState.ReadyForScriptProgramInput:
+ if self.input_ready_state == ScriptingProviderInputReadyState.ReadyForScriptProgramInput:
if len(text) == 0:
- return core.BNScriptingProviderExecuteResult.SuccessfulScriptExecution
- self.input_ready_state = core.BNScriptingProviderInputReadyState.NotReadyForInput
+ return ScriptingProviderExecuteResult.SuccessfulScriptExecution
+ self.input_ready_state = ScriptingProviderInputReadyState.NotReadyForInput
self.interpreter.add_input(text)
- return core.BNScriptingProviderExecuteResult.SuccessfulScriptExecution
+ return ScriptingProviderExecuteResult.SuccessfulScriptExecution
try:
result = code.compile_command(text)
@@ -600,11 +601,11 @@ class PythonScriptingInstance(ScriptingInstance):
if result is None:
# Command is not complete, ask for more input
- return core.BNScriptingProviderExecuteResult.IncompleteScriptInput
+ return ScriptingProviderExecuteResult.IncompleteScriptInput
- self.input_ready_state = core.BNScriptingProviderInputReadyState.NotReadyForInput
+ self.input_ready_state = ScriptingProviderInputReadyState.NotReadyForInput
self.interpreter.execute(text)
- return core.BNScriptingProviderExecuteResult.SuccessfulScriptExecution
+ return ScriptingProviderExecuteResult.SuccessfulScriptExecution
@abc.abstractmethod
def perform_set_current_binary_view(self, view):
@@ -635,6 +636,10 @@ class PythonScriptingProvider(ScriptingProvider):
PythonScriptingProvider().register()
# Wrap stdin/stdout/stderr for Python scripting provider implementation
+original_stdin = sys.stdin
+original_stdout = sys.stdout
+original_stderr = sys.stderr
+
sys.stdin = _PythonScriptingInstanceInput(sys.stdin)
sys.stdout = _PythonScriptingInstanceOutput(sys.stdout, False)
sys.stderr = _PythonScriptingInstanceOutput(sys.stderr, True)
diff --git a/python/startup.py b/python/startup.py
index c9d6792e..809f185b 100644
--- a/python/startup.py
+++ b/python/startup.py
@@ -32,7 +32,3 @@ def _init_plugins():
core.BNInitUserPlugins()
if not core.BNIsLicenseValidated():
raise RuntimeError("License is not valid. Please supply a valid license.")
-
-
-def shutdown():
- core.BNShutdown()
diff --git a/python/transform.py b/python/transform.py
index 0bbffc8f..0c003738 100644
--- a/python/transform.py
+++ b/python/transform.py
@@ -24,6 +24,7 @@ import abc
# Binary Ninja components
import _binaryninjacore as core
+from enums import TransformType
import startup
import log
import databuffer
@@ -109,14 +110,14 @@ class Transform(object):
self._pending_param_lists = {}
self.type = self.__class__.transform_type
if not isinstance(self.type, str):
- self.type = core.BNTransformType(self.type)
+ self.type = TransformType(self.type)
self.name = self.__class__.name
self.long_name = self.__class__.long_name
self.group = self.__class__.group
self.parameters = self.__class__.parameters
else:
self.handle = handle
- self.type = core.BNTransformType(core.BNGetTransformType(self.handle))
+ self.type = TransformType(core.BNGetTransformType(self.handle))
self.name = core.BNGetTransformName(self.handle)
self.long_name = core.BNGetTransformLongName(self.handle)
self.group = core.BNGetTransformGroup(self.handle)
@@ -191,7 +192,7 @@ class Transform(object):
@abc.abstractmethod
def perform_decode(self, data, params):
- if self.type == core.BNTransformType.InvertingTransform:
+ if self.type == TransformType.InvertingTransform:
return self.perform_encode(data, params)
return None
diff --git a/python/bntype.py b/python/types.py
index 1822c5df..8582e4e0 100644
--- a/python/bntype.py
+++ b/python/types.py
@@ -22,6 +22,7 @@ import ctypes
# Binary Ninja components
import _binaryninjacore as core
+from enums import SymbolType, TypeClass
import callingconvention
import demangle
@@ -31,7 +32,7 @@ class Symbol(object):
Symbols are defined as one of the following types:
=========================== ==============================================================
- BNSymbolType Description
+ SymbolType Description
=========================== ==============================================================
FunctionSymbol Symbol for Function that exists in the current binary
ImportAddressSymbol Symbol defined in the Import Address Table
@@ -45,7 +46,7 @@ class Symbol(object):
self.handle = core.handle_of_type(handle, core.BNSymbol)
else:
if isinstance(sym_type, str):
- sym_type = core.BNSymbolType[sym_type]
+ sym_type = SymbolType[sym_type]
if full_name is None:
full_name = short_name
if raw_name is None:
@@ -58,7 +59,7 @@ class Symbol(object):
@property
def type(self):
"""Symbol type (read-only)"""
- return core.BNSymbolType(core.BNGetSymbolType(self.handle))
+ return SymbolType(core.BNGetSymbolType(self.handle))
@property
def name(self):
@@ -113,7 +114,7 @@ class Type(object):
@property
def type_class(self):
"""Type class (read-only)"""
- return core.BNTypeClass(core.BNGetTypeClass(self.handle))
+ return TypeClass(core.BNGetTypeClass(self.handle))
@property
def width(self):
diff --git a/python/undoaction.py b/python/undoaction.py
index 850d37fd..9f742e00 100644
--- a/python/undoaction.py
+++ b/python/undoaction.py
@@ -24,6 +24,7 @@ import ctypes
# Binary Ninja components
import _binaryninjacore as core
+from enums import ActionType
import startup
import log
@@ -40,7 +41,7 @@ class UndoAction(object):
raise TypeError("undo action type not registered")
action_type = self.__class__.action_type
if isinstance(action_type, str):
- self._cb.type = core.BNActionType[action_type]
+ self._cb.type = ActionType[action_type]
else:
self._cb.type = action_type
self._cb.context = 0
diff --git a/python/update.py b/python/update.py
index 38d68683..7e2bd4ef 100644
--- a/python/update.py
+++ b/python/update.py
@@ -23,6 +23,7 @@ import ctypes
# Binary Ninja components
import _binaryninjacore as core
+from enums import UpdateResult
import startup
import log
@@ -180,7 +181,7 @@ class UpdateChannel(object):
error_str = errors.value
core.BNFreeString(ctypes.cast(errors, ctypes.POINTER(ctypes.c_byte)))
raise IOError(error_str)
- return core.BNUpdateResult(result)
+ return UpdateResult(result)
class UpdateVersion(object):
@@ -204,7 +205,7 @@ class UpdateVersion(object):
error_str = errors.value
core.BNFreeString(ctypes.cast(errors, ctypes.POINTER(ctypes.c_byte)))
raise IOError(error_str)
- return core.BNUpdateResult(result)
+ return UpdateResult(result)
def are_auto_updates_enabled():