From 5e4cca1f1796bec109adacdb049d9e34c17656eb Mon Sep 17 00:00:00 2001 From: plafosse Date: Fri, 28 Oct 2016 20:16:37 -0400 Subject: Refactor python api into separate files and add Enumeration support. Also fixed bugs found with pyflakes --- python/examples/angr_plugin.py | 17 ++- python/examples/bin_info.py | 48 ++++++-- python/examples/export_svg.py | 86 ++++++++----- python/examples/instruction_iterator.py | 33 +++-- python/examples/jump_table.py | 27 +++- python/examples/nds.py | 24 +++- python/examples/nes.py | 212 +++++++++++++++++--------------- python/examples/print_syscalls.py | 32 ++++- python/examples/version_switcher.py | 20 +++ 9 files changed, 329 insertions(+), 170 deletions(-) (limited to 'python/examples') diff --git a/python/examples/angr_plugin.py b/python/examples/angr_plugin.py index c6e6f87d..675cc5f6 100644 --- a/python/examples/angr_plugin.py +++ b/python/examples/angr_plugin.py @@ -12,8 +12,8 @@ __name__ = "__console__" # angr looks for this, it won't load from within a UI without it import angr from binaryninja import * + import tempfile -import threading import logging import os @@ -24,9 +24,11 @@ logging.disable(logging.WARNING) BinaryView.set_default_session_data("angr_find", set()) BinaryView.set_default_session_data("angr_avoid", set()) + def escaped_output(str): return '\n'.join([s.encode("string_escape") for s in str.split('\n')]) + # Define a background thread object for solving in the background class Solver(BackgroundTaskThread): def __init__(self, find, avoid, view): @@ -81,31 +83,34 @@ class Solver(BackgroundTaskThread): else: show_plain_text_report("Results from angr", text_report) + 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(GreenHighlightColor, alpha = 128)) - block.function.set_auto_instr_highlight(block.arch, addr, GreenHighlightColor) + block.set_auto_highlight(HighlightColor(core.BNHighlightStandardColor.GreenHighlightColor, alpha = 128)) + block.function.set_auto_instr_highlight(block.arch, addr, core.BNHighlightStandardColor.GreenHighlightColor) # Add the instruction to the list associated with the current view bv.session_data.angr_find.add(addr) + 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(RedHighlightColor, alpha = 128)) - block.function.set_auto_instr_highlight(block.arch, addr, RedHighlightColor) + block.set_auto_highlight(HighlightColor(core.BNHighlightStandardColor.RedHighlightColor, alpha = 128)) + block.function.set_auto_instr_highlight(block.arch, addr, core.BNHighlightStandardColor.RedHighlightColor) # Add the instruction to the list associated with the current view bv.session_data.angr_avoid.add(addr) + def solve(bv): if len(bv.session_data.angr_find) == 0: show_message_box("Angr Solve", "You have not specified a goal instruction.\n\n" + "Please right click on the goal instruction and select \"Find Path to This Instruction\" to " + - "continue.", OKButtonSet, ErrorIcon) + "continue.", core.BNMessageBoxButtonSet.OKButtonSet, core.BNMessageBoxButtonSet.ErrorIcon) return # Start a solver thread for the path associated with the view diff --git a/python/examples/bin_info.py b/python/examples/bin_info.py index 48073894..ab963e4e 100644 --- a/python/examples/bin_info.py +++ b/python/examples/bin_info.py @@ -1,11 +1,33 @@ #!/usr/bin/env python -import sys, binaryninja, time +# 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. + +import sys +import binaryninja + if sys.platform.lower().startswith("linux"): - bintype="ELF" + bintype = "ELF" elif sys.platform.lower() == "darwin": - bintype="Mach-O" + bintype = "Mach-O" else: - raise Exception, "%s is not supported on this plugin" % sys.platform + raise Exception("%s is not supported on this plugin" % sys.platform) if len(sys.argv) > 1: target = sys.argv[1] @@ -15,20 +37,20 @@ else: bv = binaryninja.BinaryViewType[bintype].open(target) bv.update_analysis_and_wait() -print "-------- %s --------" % target -print "START: 0x%x" % bv.start -print "ENTRY: 0x%x" % bv.entry_point -print "ARCH: %s" % bv.arch.name -print "\n-------- Function List --------" +print("-------- %s --------" % target) +print("START: 0x%x" % bv.start) +print("ENTRY: 0x%x" % bv.entry_point) +print("ARCH: %s" % bv.arch.name) +print("\n-------- Function List --------") for func in bv.functions: - print func.symbol.name + print(func.symbol.name) -print "\n-------- First 10 strings --------" +print("\n-------- First 10 strings --------") for i in xrange(10): start = bv.strings[i].start length = bv.strings[i].length - string = bv.read(start,length) - print "0x%x (%d):\t%s" % (start, length, string) + string = bv.read(start, length) + print("0x%x (%d):\t%s" % (start, length, string)) diff --git a/python/examples/export_svg.py b/python/examples/export_svg.py index a54dc879..843b17a5 100755 --- a/python/examples/export_svg.py +++ b/python/examples/export_svg.py @@ -1,10 +1,30 @@ +# 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 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 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 +37,44 @@ escape_table = { ' ': " " } + 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 + 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 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: + if show_message_box("Open SVG", "Would you like to view the exported SVG?", buttons=core.BNMessageBoxButtonSet.YesNoButtonSet, icon = core.BNMessageBoxIcon.QuestionIcon) == core.BNMessageBoxButtonResult.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 = ''' @@ -130,56 +154,56 @@ def render_svg(function): - '''.format(width=graph.width*widthconst, height=graph.height*heightconst) + '''.format(width=graph.width * widthconst, height=graph.height * heightconst) output += ''' Function Graph 0 ''' 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 += ' \n'.format(i=i) output += ' Basic Block {i}\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 += ' \n'.format(x=x,y=y,width=width,height=height,r=rgb[0],g=rgb[1],b=rgb[2]) + output += ' \n'.format(x=x, y=y, width=width, height=height, 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 += ' \n'.format(x=x,y=y + (i + 1) * heightconst) - for i,line in enumerate(block.lines): - output += ' '.format(x=x,y=y + (i + 0.7) * heightconst,address=hex(line.address)[:-1]) + output += ' \n'.format(x=x, y=y + (i + 1) * heightconst) + for i, line in enumerate(block.lines): + output += ' '.format(x=x, y=y + (i + 0.7) * heightconst, address=hex(line.address)[:-1]) hover = instruction_data_flow(function, line.address) output += '{hover}'.format(hover=hover) for token in line.tokens: # TODO: add hover for hex, function, and reg tokens - output+='{text}'.format(text=escape(token.text),tokentype=token.type) + output += '{text}'.format(text=escape(token.text), tokentype=token.type.name) output += '\n' output += ' \n' output += ' \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 = "" - for x,y in edge.points: - points += str(x*widthconst)+","+str(y*heightconst) + " " - edges += ' \n'.format(type=edge.type,points=points) + for x, y in edge.points: + points += str(x * widthconst) + "," + str(y * heightconst) + " " + edges += ' \n'.format(type=edge.type.name, points=points) output += ' ' + edges + '\n' output += ' \n' output += '' diff --git a/python/examples/instruction_iterator.py b/python/examples/instruction_iterator.py index 43bc000e..6c9d9653 100644 --- a/python/examples/instruction_iterator.py +++ b/python/examples/instruction_iterator.py @@ -1,19 +1,34 @@ #!/usr/bin/env python +# 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. import sys -try: - import binaryninja -except ImportError: - sys.path.append("/Applications/Binary Ninja.app/Contents/Resources/python/") - import binaryninja -import time +import binaryninja + if sys.platform.lower().startswith("linux"): - bintype="ELF" + bintype = "ELF" elif sys.platform.lower() == "darwin": - bintype="Mach-O" + bintype = "Mach-O" else: - raise Exception, "%s is not supported on this plugin" % sys.platform + raise Exception("%s is not supported on this plugin" % sys.platform) if len(sys.argv) > 1: target = sys.argv[1] diff --git a/python/examples/jump_table.py b/python/examples/jump_table.py index 39fed1a5..23531de0 100644 --- a/python/examples/jump_table.py +++ b/python/examples/jump_table.py @@ -1,8 +1,29 @@ +# 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. + # 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. -from binaryninja import * +import binaryninja import struct + def find_jump_table(bv, addr): for block in bv.get_basic_blocks_at(addr): func = block.function @@ -28,7 +49,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 == "PossibleAddressToken": # Table addresses will be a "possible address" token + if token.type == core.BNInstructionTextTokenType.PossibleAddressToken: # Table addresses will be a "possible address" token tbl = token.value print "Found possible table at 0x%x" % tbl i = 0 @@ -60,4 +81,4 @@ def find_jump_table(bv, addr): # Create a plugin command so that the user can right click on an instruction referencing a jump table and # invoke the command -PluginCommand.register_for_address("Process jump table", "Look for jump table destinations", find_jump_table) +binaryninja.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 5300018c..302bbc0d 100644 --- a/python/examples/nds.py +++ b/python/examples/nds.py @@ -1,3 +1,23 @@ +# 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 @@ -42,7 +62,7 @@ class DSView(BinaryView): self.arm9_load_addr = struct.unpack("= 0x8000: self.add_function(Architecture['6502'].standalone_platform, addr) diff --git a/python/examples/print_syscalls.py b/python/examples/print_syscalls.py index 7e93356c..c3b47a8d 100644 --- a/python/examples/print_syscalls.py +++ b/python/examples/print_syscalls.py @@ -1,8 +1,28 @@ #!/usr/bin/env python -""" - Thanks to @theqlabs from arm.ninja for the nice writeup and idea for this plugin: - http://arm.ninja/2016/03/08/intro-to-binary-ninja-api/ -""" +# 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. + + +# Thanks to @theqlabs from arm.ninja for the nice writeup and idea for this plugin: +# http://arm.ninja/2016/03/08/intro-to-binary-ninja-api/ + import sys from itertools import chain @@ -21,7 +41,7 @@ def print_syscalls(bv): for func in bv.functions: syscalls = (il for il in chain.from_iterable(func.low_level_il) - if il.operation == core.LLIL_SYSCALL) + if il.operation == core.BNLowLevelILOperation.LLIL_SYSCALL) for il in syscalls: value = func.get_reg_value_at(bv.arch, il.address, register).value print("System call address: {:#x} - {:d}".format(il.address, value)) @@ -35,7 +55,7 @@ def main(): target = sys.argv[1] bv = BinaryView.open(target) - view_type = next(bvt for bvt in bv.available_view_types if bvt.name != 'Raw') + 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 diff --git a/python/examples/version_switcher.py b/python/examples/version_switcher.py index 6199c578..e8f8814d 100644 --- a/python/examples/version_switcher.py +++ b/python/examples/version_switcher.py @@ -1,4 +1,24 @@ #!/usr/bin/env python +# 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. + import sys import binaryninja import datetime -- cgit v1.3.1 From a6842fc4209ed0bc160222ee61b2e6d9741dc9ef Mon Sep 17 00:00:00 2001 From: plafosse Date: Mon, 31 Oct 2016 16:06:34 -0400 Subject: Refactoring and other improvements of the python api --- python/__init__.py | 55 ++- python/architecture.py | 6 + python/binaryview.py | 35 +- python/enum/LICENSE | 32 ++ python/enum/README | 3 + python/enum/__init__.py | 837 ++++++++++++++++++++++++++++++++ python/examples/bin_info.py | 66 ++- python/examples/instruction_iterator.py | 28 +- python/platform.py | 9 + 9 files changed, 994 insertions(+), 77 deletions(-) create mode 100644 python/enum/LICENSE create mode 100644 python/enum/README create mode 100644 python/enum/__init__.py (limited to 'python/examples') diff --git a/python/__init__.py b/python/__init__.py index 402c8526..f38395c8 100644 --- a/python/__init__.py +++ b/python/__init__.py @@ -19,31 +19,38 @@ # 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 * +import sys + +# Binary Ninja components +try: + 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 * +except: + x = open("/Users/peterl/path", "w") + x.write(str(sys.exc_info())) + x.close() class _DestructionCallbackHandler(object): def __init__(self): diff --git a/python/architecture.py b/python/architecture.py index a8aa391b..0cdba6e5 100644 --- a/python/architecture.py +++ b/python/architecture.py @@ -1084,6 +1084,12 @@ class Architecture(object): """ return None + def get_associated_arch_by_address(self, addr): + new_addr = ctypes.c_ulonglong() + new_addr.value = addr + result = core.BNGetAssociatedArchitectureByAddress(self.handle, new_addr) + return Architecture(handle = result), new_addr.value + def get_instruction_info(self, data, addr): """ ``get_instruction_info`` returns an InstructionInfo object for the instruction at the given virtual address diff --git a/python/binaryview.py b/python/binaryview.py index 76def834..e6e0ff61 100644 --- a/python/binaryview.py +++ b/python/binaryview.py @@ -266,12 +266,6 @@ class _BinaryViewTypeMetaclass(type): raise KeyError("'%s' is not a valid view type" % str(value)) return BinaryViewType(view_type) - def __setattr__(self, name, value): - try: - type.__setattr__(self, name, value) - except AttributeError: - raise AttributeError("attribute '%s' is read only" % name) - class BinaryViewType(object): __metaclass__ = _BinaryViewTypeMetaclass @@ -304,6 +298,27 @@ class BinaryViewType(object): return None return self.create(data) + @classmethod + def get_view_of_file(cls, filename, update_analysis=True): + """ + ``get_view_of_file`` returns the first available, non-Raw `BinaryView` available. + + :param str filename: Path to filename + :param bool update_analysis: defaults to True. Pass False to not run update_analysis_and_wait. + :return: returns a BinaryView object for the given filename. + :rtype: BinaryView or None + """ + view = BinaryView.open(filename) + if view is None: + return None + for available in view.available_view_types: + if available.name != "Raw": + bv = cls[available.name].open(filename) + if update_analysis: + bv.update_analysis_and_wait() + return bv + return None + def is_valid_for_data(self, data): return core.BNIsBinaryViewTypeValidForData(self.handle, data.handle) @@ -328,12 +343,6 @@ class BinaryViewType(object): return None return platform.Platform(None, plat) - def __setattr__(self, name, value): - try: - object.__setattr__(self, name, value) - except AttributeError: - raise AttributeError("attribute '%s' is read only" % name) - class Segment(object): def __init__(self, start, length, data_offset, data_length, flags): @@ -467,7 +476,7 @@ class BinaryView(object): if file_metadata is None: file_metadata = filemetadata.FileMetadata() self.handle = core.BNCreateBinaryDataView(file_metadata.handle) - self.file = filemetadata.FileMetadata(handle=core.BNNewFileReference(file_metadata)) + self.file = filemetadata.FileMetadata(handle=core.BNNewFileReference(file_metadata.handle)) else: startup._init_plugins() if not self.__class__._registered: diff --git a/python/enum/LICENSE b/python/enum/LICENSE new file mode 100644 index 00000000..9003b885 --- /dev/null +++ b/python/enum/LICENSE @@ -0,0 +1,32 @@ +Copyright (c) 2013, Ethan Furman. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + Redistributions of source code must retain the above + copyright notice, this list of conditions and the + following disclaimer. + + Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + Neither the name Ethan Furman nor the names of any + contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. diff --git a/python/enum/README b/python/enum/README new file mode 100644 index 00000000..aa2333d8 --- /dev/null +++ b/python/enum/README @@ -0,0 +1,3 @@ +enum34 is the new Python stdlib enum module available in Python 3.4 +backported for previous versions of Python from 2.4 to 3.3. +tested on 2.6, 2.7, and 3.3+ diff --git a/python/enum/__init__.py b/python/enum/__init__.py new file mode 100644 index 00000000..d6ffb3a4 --- /dev/null +++ b/python/enum/__init__.py @@ -0,0 +1,837 @@ +"""Python Enumerations""" + +import sys as _sys + +__all__ = ['Enum', 'IntEnum', 'unique'] + +version = 1, 1, 6 + +pyver = float('%s.%s' % _sys.version_info[:2]) + +try: + any +except NameError: + def any(iterable): + for element in iterable: + if element: + return True + return False + +try: + from collections import OrderedDict +except ImportError: + OrderedDict = None + +try: + basestring +except NameError: + # In Python 2 basestring is the ancestor of both str and unicode + # in Python 3 it's just str, but was missing in 3.1 + basestring = str + +try: + unicode +except NameError: + # In Python 3 unicode no longer exists (it's just str) + unicode = str + +class _RouteClassAttributeToGetattr(object): + """Route attribute access on a class to __getattr__. + + This is a descriptor, used to define attributes that act differently when + accessed through an instance and through a class. Instance access remains + normal, but access to an attribute through a class will be routed to the + class's __getattr__ method; this is done by raising AttributeError. + + """ + def __init__(self, fget=None): + self.fget = fget + + def __get__(self, instance, ownerclass=None): + if instance is None: + raise AttributeError() + return self.fget(instance) + + def __set__(self, instance, value): + raise AttributeError("can't set attribute") + + def __delete__(self, instance): + raise AttributeError("can't delete attribute") + + +def _is_descriptor(obj): + """Returns True if obj is a descriptor, False otherwise.""" + return ( + hasattr(obj, '__get__') or + hasattr(obj, '__set__') or + hasattr(obj, '__delete__')) + + +def _is_dunder(name): + """Returns True if a __dunder__ name, False otherwise.""" + return (name[:2] == name[-2:] == '__' and + name[2:3] != '_' and + name[-3:-2] != '_' and + len(name) > 4) + + +def _is_sunder(name): + """Returns True if a _sunder_ name, False otherwise.""" + return (name[0] == name[-1] == '_' and + name[1:2] != '_' and + name[-2:-1] != '_' and + len(name) > 2) + + +def _make_class_unpicklable(cls): + """Make the given class un-picklable.""" + def _break_on_call_reduce(self, protocol=None): + raise TypeError('%r cannot be pickled' % self) + cls.__reduce_ex__ = _break_on_call_reduce + cls.__module__ = '' + + +class _EnumDict(dict): + """Track enum member order and ensure member names are not reused. + + EnumMeta will use the names found in self._member_names as the + enumeration member names. + + """ + def __init__(self): + super(_EnumDict, self).__init__() + self._member_names = [] + + def __setitem__(self, key, value): + """Changes anything not dundered or not a descriptor. + + If a descriptor is added with the same name as an enum member, the name + is removed from _member_names (this may leave a hole in the numerical + sequence of values). + + If an enum member name is used twice, an error is raised; duplicate + values are not checked for. + + Single underscore (sunder) names are reserved. + + Note: in 3.x __order__ is simply discarded as a not necessary piece + leftover from 2.x + + """ + if pyver >= 3.0 and key in ('_order_', '__order__'): + return + elif key == '__order__': + key = '_order_' + if _is_sunder(key): + if key != '_order_': + raise ValueError('_names_ are reserved for future Enum use') + elif _is_dunder(key): + pass + elif key in self._member_names: + # descriptor overwriting an enum? + raise TypeError('Attempted to reuse key: %r' % key) + elif not _is_descriptor(value): + if key in self: + # enum overwriting a descriptor? + raise TypeError('Key already defined as: %r' % self[key]) + self._member_names.append(key) + super(_EnumDict, self).__setitem__(key, value) + + +# Dummy value for Enum as EnumMeta explicity checks for it, but of course until +# EnumMeta finishes running the first time the Enum class doesn't exist. This +# is also why there are checks in EnumMeta like `if Enum is not None` +Enum = None + + +class EnumMeta(type): + """Metaclass for Enum""" + @classmethod + def __prepare__(metacls, cls, bases): + return _EnumDict() + + def __new__(metacls, cls, bases, classdict): + # an Enum class is final once enumeration items have been defined; it + # cannot be mixed with other types (int, float, etc.) if it has an + # inherited __new__ unless a new __new__ is defined (or the resulting + # class will fail). + if type(classdict) is dict: + original_dict = classdict + classdict = _EnumDict() + for k, v in original_dict.items(): + classdict[k] = v + + member_type, first_enum = metacls._get_mixins_(bases) + __new__, save_new, use_args = metacls._find_new_(classdict, member_type, + first_enum) + # save enum items into separate mapping so they don't get baked into + # the new class + members = dict((k, classdict[k]) for k in classdict._member_names) + for name in classdict._member_names: + del classdict[name] + + # py2 support for definition order + _order_ = classdict.get('_order_') + if _order_ is None: + if pyver < 3.0: + try: + _order_ = [name for (name, value) in sorted(members.items(), key=lambda item: item[1])] + except TypeError: + _order_ = [name for name in sorted(members.keys())] + else: + _order_ = classdict._member_names + else: + del classdict['_order_'] + if pyver < 3.0: + _order_ = _order_.replace(',', ' ').split() + aliases = [name for name in members if name not in _order_] + _order_ += aliases + + # check for illegal enum names (any others?) + invalid_names = set(members) & set(['mro']) + if invalid_names: + raise ValueError('Invalid enum member name(s): %s' % ( + ', '.join(invalid_names), )) + + # save attributes from super classes so we know if we can take + # the shortcut of storing members in the class dict + base_attributes = set([a for b in bases for a in b.__dict__]) + # create our new Enum type + enum_class = super(EnumMeta, metacls).__new__(metacls, cls, bases, classdict) + enum_class._member_names_ = [] # names in random order + if OrderedDict is not None: + enum_class._member_map_ = OrderedDict() + else: + enum_class._member_map_ = {} # name->value map + enum_class._member_type_ = member_type + + # Reverse value->name map for hashable values. + enum_class._value2member_map_ = {} + + # instantiate them, checking for duplicates as we go + # we instantiate first instead of checking for duplicates first in case + # a custom __new__ is doing something funky with the values -- such as + # auto-numbering ;) + if __new__ is None: + __new__ = enum_class.__new__ + for member_name in _order_: + value = members[member_name] + if not isinstance(value, tuple): + args = (value, ) + else: + args = value + if member_type is tuple: # special case for tuple enums + args = (args, ) # wrap it one more time + if not use_args or not args: + enum_member = __new__(enum_class) + if not hasattr(enum_member, '_value_'): + enum_member._value_ = value + else: + enum_member = __new__(enum_class, *args) + if not hasattr(enum_member, '_value_'): + enum_member._value_ = member_type(*args) + value = enum_member._value_ + enum_member._name_ = member_name + enum_member.__objclass__ = enum_class + enum_member.__init__(*args) + # If another member with the same value was already defined, the + # new member becomes an alias to the existing one. + for name, canonical_member in enum_class._member_map_.items(): + if canonical_member.value == enum_member._value_: + enum_member = canonical_member + break + else: + # Aliases don't appear in member names (only in __members__). + enum_class._member_names_.append(member_name) + # performance boost for any member that would not shadow + # a DynamicClassAttribute (aka _RouteClassAttributeToGetattr) + if member_name not in base_attributes: + setattr(enum_class, member_name, enum_member) + # now add to _member_map_ + enum_class._member_map_[member_name] = enum_member + try: + # This may fail if value is not hashable. We can't add the value + # to the map, and by-value lookups for this value will be + # linear. + enum_class._value2member_map_[value] = enum_member + except TypeError: + pass + + + # If a custom type is mixed into the Enum, and it does not know how + # to pickle itself, pickle.dumps will succeed but pickle.loads will + # fail. Rather than have the error show up later and possibly far + # from the source, sabotage the pickle protocol for this class so + # that pickle.dumps also fails. + # + # However, if the new class implements its own __reduce_ex__, do not + # sabotage -- it's on them to make sure it works correctly. We use + # __reduce_ex__ instead of any of the others as it is preferred by + # pickle over __reduce__, and it handles all pickle protocols. + unpicklable = False + if '__reduce_ex__' not in classdict: + if member_type is not object: + methods = ('__getnewargs_ex__', '__getnewargs__', + '__reduce_ex__', '__reduce__') + if not any(m in member_type.__dict__ for m in methods): + _make_class_unpicklable(enum_class) + unpicklable = True + + + # double check that repr and friends are not the mixin's or various + # things break (such as pickle) + for name in ('__repr__', '__str__', '__format__', '__reduce_ex__'): + class_method = getattr(enum_class, name) + obj_method = getattr(member_type, name, None) + enum_method = getattr(first_enum, name, None) + if name not in classdict and class_method is not enum_method: + if name == '__reduce_ex__' and unpicklable: + continue + setattr(enum_class, name, enum_method) + + # method resolution and int's are not playing nice + # Python's less than 2.6 use __cmp__ + + if pyver < 2.6: + + if issubclass(enum_class, int): + setattr(enum_class, '__cmp__', getattr(int, '__cmp__')) + + elif pyver < 3.0: + + if issubclass(enum_class, int): + for method in ( + '__le__', + '__lt__', + '__gt__', + '__ge__', + '__eq__', + '__ne__', + '__hash__', + ): + setattr(enum_class, method, getattr(int, method)) + + # replace any other __new__ with our own (as long as Enum is not None, + # anyway) -- again, this is to support pickle + if Enum is not None: + # if the user defined their own __new__, save it before it gets + # clobbered in case they subclass later + if save_new: + setattr(enum_class, '__member_new__', enum_class.__dict__['__new__']) + setattr(enum_class, '__new__', Enum.__dict__['__new__']) + return enum_class + + def __bool__(cls): + """ + classes/types should always be True. + """ + return True + + def __call__(cls, value, names=None, module=None, type=None, start=1): + """Either returns an existing member, or creates a new enum class. + + This method is used both when an enum class is given a value to match + to an enumeration member (i.e. Color(3)) and for the functional API + (i.e. Color = Enum('Color', names='red green blue')). + + When used for the functional API: `module`, if set, will be stored in + the new class' __module__ attribute; `type`, if set, will be mixed in + as the first base class. + + Note: if `module` is not set this routine will attempt to discover the + calling module by walking the frame stack; if this is unsuccessful + the resulting class will not be pickleable. + + """ + if names is None: # simple value lookup + return cls.__new__(cls, value) + # otherwise, functional API: we're creating a new Enum type + return cls._create_(value, names, module=module, type=type, start=start) + + def __contains__(cls, member): + return isinstance(member, cls) and member.name in cls._member_map_ + + def __delattr__(cls, attr): + # nicer error message when someone tries to delete an attribute + # (see issue19025). + if attr in cls._member_map_: + raise AttributeError( + "%s: cannot delete Enum member." % cls.__name__) + super(EnumMeta, cls).__delattr__(attr) + + def __dir__(self): + return (['__class__', '__doc__', '__members__', '__module__'] + + self._member_names_) + + @property + def __members__(cls): + """Returns a mapping of member name->value. + + This mapping lists all enum members, including aliases. Note that this + is a copy of the internal mapping. + + """ + return cls._member_map_.copy() + + def __getattr__(cls, name): + """Return the enum member matching `name` + + We use __getattr__ instead of descriptors or inserting into the enum + class' __dict__ in order to support `name` and `value` being both + properties for enum members (which live in the class' __dict__) and + enum members themselves. + + """ + if _is_dunder(name): + raise AttributeError(name) + try: + return cls._member_map_[name] + except KeyError: + raise AttributeError(name) + + def __getitem__(cls, name): + return cls._member_map_[name] + + def __iter__(cls): + return (cls._member_map_[name] for name in cls._member_names_) + + def __reversed__(cls): + return (cls._member_map_[name] for name in reversed(cls._member_names_)) + + def __len__(cls): + return len(cls._member_names_) + + __nonzero__ = __bool__ + + def __repr__(cls): + return "" % cls.__name__ + + def __setattr__(cls, name, value): + """Block attempts to reassign Enum members. + + A simple assignment to the class namespace only changes one of the + several possible ways to get an Enum member from the Enum class, + resulting in an inconsistent Enumeration. + + """ + member_map = cls.__dict__.get('_member_map_', {}) + if name in member_map: + raise AttributeError('Cannot reassign members.') + super(EnumMeta, cls).__setattr__(name, value) + + def _create_(cls, class_name, names=None, module=None, type=None, start=1): + """Convenience method to create a new Enum class. + + `names` can be: + + * A string containing member names, separated either with spaces or + commas. Values are auto-numbered from 1. + * An iterable of member names. Values are auto-numbered from 1. + * An iterable of (member name, value) pairs. + * A mapping of member name -> value. + + """ + if pyver < 3.0: + # if class_name is unicode, attempt a conversion to ASCII + if isinstance(class_name, unicode): + try: + class_name = class_name.encode('ascii') + except UnicodeEncodeError: + raise TypeError('%r is not representable in ASCII' % class_name) + metacls = cls.__class__ + if type is None: + bases = (cls, ) + else: + bases = (type, cls) + classdict = metacls.__prepare__(class_name, bases) + _order_ = [] + + # special processing needed for names? + if isinstance(names, basestring): + names = names.replace(',', ' ').split() + if isinstance(names, (tuple, list)) and isinstance(names[0], basestring): + names = [(e, i+start) for (i, e) in enumerate(names)] + + # Here, names is either an iterable of (name, value) or a mapping. + item = None # in case names is empty + for item in names: + if isinstance(item, basestring): + member_name, member_value = item, names[item] + else: + member_name, member_value = item + classdict[member_name] = member_value + _order_.append(member_name) + # only set _order_ in classdict if name/value was not from a mapping + if not isinstance(item, basestring): + classdict['_order_'] = ' '.join(_order_) + enum_class = metacls.__new__(metacls, class_name, bases, classdict) + + # TODO: replace the frame hack if a blessed way to know the calling + # module is ever developed + if module is None: + try: + module = _sys._getframe(2).f_globals['__name__'] + except (AttributeError, ValueError): + pass + if module is None: + _make_class_unpicklable(enum_class) + else: + enum_class.__module__ = module + + return enum_class + + @staticmethod + def _get_mixins_(bases): + """Returns the type for creating enum members, and the first inherited + enum class. + + bases: the tuple of bases that was given to __new__ + + """ + if not bases or Enum is None: + return object, Enum + + + # double check that we are not subclassing a class with existing + # enumeration members; while we're at it, see if any other data + # type has been mixed in so we can use the correct __new__ + member_type = first_enum = None + for base in bases: + if (base is not Enum and + issubclass(base, Enum) and + base._member_names_): + raise TypeError("Cannot extend enumerations") + # base is now the last base in bases + if not issubclass(base, Enum): + raise TypeError("new enumerations must be created as " + "`ClassName([mixin_type,] enum_type)`") + + # get correct mix-in type (either mix-in type of Enum subclass, or + # first base if last base is Enum) + if not issubclass(bases[0], Enum): + member_type = bases[0] # first data type + first_enum = bases[-1] # enum type + else: + for base in bases[0].__mro__: + # most common: (IntEnum, int, Enum, object) + # possible: (, , + # , , + # ) + if issubclass(base, Enum): + if first_enum is None: + first_enum = base + else: + if member_type is None: + member_type = base + + return member_type, first_enum + + if pyver < 3.0: + @staticmethod + def _find_new_(classdict, member_type, first_enum): + """Returns the __new__ to be used for creating the enum members. + + classdict: the class dictionary given to __new__ + member_type: the data type whose __new__ will be used by default + first_enum: enumeration to check for an overriding __new__ + + """ + # now find the correct __new__, checking to see of one was defined + # by the user; also check earlier enum classes in case a __new__ was + # saved as __member_new__ + __new__ = classdict.get('__new__', None) + if __new__: + return None, True, True # __new__, save_new, use_args + + N__new__ = getattr(None, '__new__') + O__new__ = getattr(object, '__new__') + if Enum is None: + E__new__ = N__new__ + else: + E__new__ = Enum.__dict__['__new__'] + # check all possibles for __member_new__ before falling back to + # __new__ + for method in ('__member_new__', '__new__'): + for possible in (member_type, first_enum): + try: + target = possible.__dict__[method] + except (AttributeError, KeyError): + target = getattr(possible, method, None) + if target not in [ + None, + N__new__, + O__new__, + E__new__, + ]: + if method == '__member_new__': + classdict['__new__'] = target + return None, False, True + if isinstance(target, staticmethod): + target = target.__get__(member_type) + __new__ = target + break + if __new__ is not None: + break + else: + __new__ = object.__new__ + + # if a non-object.__new__ is used then whatever value/tuple was + # assigned to the enum member name will be passed to __new__ and to the + # new enum member's __init__ + if __new__ is object.__new__: + use_args = False + else: + use_args = True + + return __new__, False, use_args + else: + @staticmethod + def _find_new_(classdict, member_type, first_enum): + """Returns the __new__ to be used for creating the enum members. + + classdict: the class dictionary given to __new__ + member_type: the data type whose __new__ will be used by default + first_enum: enumeration to check for an overriding __new__ + + """ + # now find the correct __new__, checking to see of one was defined + # by the user; also check earlier enum classes in case a __new__ was + # saved as __member_new__ + __new__ = classdict.get('__new__', None) + + # should __new__ be saved as __member_new__ later? + save_new = __new__ is not None + + if __new__ is None: + # check all possibles for __member_new__ before falling back to + # __new__ + for method in ('__member_new__', '__new__'): + for possible in (member_type, first_enum): + target = getattr(possible, method, None) + if target not in ( + None, + None.__new__, + object.__new__, + Enum.__new__, + ): + __new__ = target + break + if __new__ is not None: + break + else: + __new__ = object.__new__ + + # if a non-object.__new__ is used then whatever value/tuple was + # assigned to the enum member name will be passed to __new__ and to the + # new enum member's __init__ + if __new__ is object.__new__: + use_args = False + else: + use_args = True + + return __new__, save_new, use_args + + +######################################################## +# In order to support Python 2 and 3 with a single +# codebase we have to create the Enum methods separately +# and then use the `type(name, bases, dict)` method to +# create the class. +######################################################## +temp_enum_dict = {} +temp_enum_dict['__doc__'] = "Generic enumeration.\n\n Derive from this class to define new enumerations.\n\n" + +def __new__(cls, value): + # all enum instances are actually created during class construction + # without calling this method; this method is called by the metaclass' + # __call__ (i.e. Color(3) ), and by pickle + if type(value) is cls: + # For lookups like Color(Color.red) + value = value.value + #return value + # by-value search for a matching enum member + # see if it's in the reverse mapping (for hashable values) + try: + if value in cls._value2member_map_: + return cls._value2member_map_[value] + except TypeError: + # not there, now do long search -- O(n) behavior + for member in cls._member_map_.values(): + if member.value == value: + return member + raise ValueError("%s is not a valid %s" % (value, cls.__name__)) +temp_enum_dict['__new__'] = __new__ +del __new__ + +def __repr__(self): + return "<%s.%s: %r>" % ( + self.__class__.__name__, self._name_, self._value_) +temp_enum_dict['__repr__'] = __repr__ +del __repr__ + +def __str__(self): + return "%s.%s" % (self.__class__.__name__, self._name_) +temp_enum_dict['__str__'] = __str__ +del __str__ + +if pyver >= 3.0: + def __dir__(self): + added_behavior = [ + m + for cls in self.__class__.mro() + for m in cls.__dict__ + if m[0] != '_' and m not in self._member_map_ + ] + return (['__class__', '__doc__', '__module__', ] + added_behavior) + temp_enum_dict['__dir__'] = __dir__ + del __dir__ + +def __format__(self, format_spec): + # mixed-in Enums should use the mixed-in type's __format__, otherwise + # we can get strange results with the Enum name showing up instead of + # the value + + # pure Enum branch + if self._member_type_ is object: + cls = str + val = str(self) + # mix-in branch + else: + cls = self._member_type_ + val = self.value + return cls.__format__(val, format_spec) +temp_enum_dict['__format__'] = __format__ +del __format__ + + +#################################### +# Python's less than 2.6 use __cmp__ + +if pyver < 2.6: + + def __cmp__(self, other): + if type(other) is self.__class__: + if self is other: + return 0 + return -1 + return NotImplemented + raise TypeError("unorderable types: %s() and %s()" % (self.__class__.__name__, other.__class__.__name__)) + temp_enum_dict['__cmp__'] = __cmp__ + del __cmp__ + +else: + + def __le__(self, other): + raise TypeError("unorderable types: %s() <= %s()" % (self.__class__.__name__, other.__class__.__name__)) + temp_enum_dict['__le__'] = __le__ + del __le__ + + def __lt__(self, other): + raise TypeError("unorderable types: %s() < %s()" % (self.__class__.__name__, other.__class__.__name__)) + temp_enum_dict['__lt__'] = __lt__ + del __lt__ + + def __ge__(self, other): + raise TypeError("unorderable types: %s() >= %s()" % (self.__class__.__name__, other.__class__.__name__)) + temp_enum_dict['__ge__'] = __ge__ + del __ge__ + + def __gt__(self, other): + raise TypeError("unorderable types: %s() > %s()" % (self.__class__.__name__, other.__class__.__name__)) + temp_enum_dict['__gt__'] = __gt__ + del __gt__ + + +def __eq__(self, other): + if type(other) is self.__class__: + return self is other + return NotImplemented +temp_enum_dict['__eq__'] = __eq__ +del __eq__ + +def __ne__(self, other): + if type(other) is self.__class__: + return self is not other + return NotImplemented +temp_enum_dict['__ne__'] = __ne__ +del __ne__ + +def __hash__(self): + return hash(self._name_) +temp_enum_dict['__hash__'] = __hash__ +del __hash__ + +def __reduce_ex__(self, proto): + return self.__class__, (self._value_, ) +temp_enum_dict['__reduce_ex__'] = __reduce_ex__ +del __reduce_ex__ + +# _RouteClassAttributeToGetattr is used to provide access to the `name` +# and `value` properties of enum members while keeping some measure of +# protection from modification, while still allowing for an enumeration +# to have members named `name` and `value`. This works because enumeration +# members are not set directly on the enum class -- __getattr__ is +# used to look them up. + +@_RouteClassAttributeToGetattr +def name(self): + return self._name_ +temp_enum_dict['name'] = name +del name + +@_RouteClassAttributeToGetattr +def value(self): + return self._value_ +temp_enum_dict['value'] = value +del value + +@classmethod +def _convert(cls, name, module, filter, source=None): + """ + Create a new Enum subclass that replaces a collection of global constants + """ + # convert all constants from source (or module) that pass filter() to + # a new Enum called name, and export the enum and its members back to + # module; + # also, replace the __reduce_ex__ method so unpickling works in + # previous Python versions + module_globals = vars(_sys.modules[module]) + if source: + source = vars(source) + else: + source = module_globals + members = dict((name, value) for name, value in source.items() if filter(name)) + cls = cls(name, members, module=module) + cls.__reduce_ex__ = _reduce_ex_by_name + module_globals.update(cls.__members__) + module_globals[name] = cls + return cls +temp_enum_dict['_convert'] = _convert +del _convert + +Enum = EnumMeta('Enum', (object, ), temp_enum_dict) +del temp_enum_dict + +# Enum has now been created +########################### + +class IntEnum(int, Enum): + """Enum where members are also (and must be) ints""" + +def _reduce_ex_by_name(self, proto): + return self.name + +def unique(enumeration): + """Class decorator that ensures only unique members exist in an enumeration.""" + duplicates = [] + for name, member in enumeration.__members__.items(): + if name != member.name: + duplicates.append((name, member.name)) + if duplicates: + duplicate_names = ', '.join( + ["%s -> %s" % (alias, name) for (alias, name) in duplicates] + ) + raise ValueError('duplicate names found in %r: %s' % + (enumeration, duplicate_names) + ) + return enumeration diff --git a/python/examples/bin_info.py b/python/examples/bin_info.py index a472495a..c574a530 100644 --- a/python/examples/bin_info.py +++ b/python/examples/bin_info.py @@ -20,37 +20,51 @@ # IN THE SOFTWARE. import sys -import binaryninja +import binaryninja.log as log +import binaryninja.binaryview as view +import binaryninja.interaction as interaction +from binaryninja.plugin import PluginCommand -if sys.platform.lower().startswith("linux"): - bintype = "ELF" -elif sys.platform.lower() == "darwin": - bintype = "Mach-O" -else: - raise Exception("%s is not supported on this plugin" % sys.platform) -if len(sys.argv) > 1: - target = sys.argv[1] -else: - target = "/bin/ls" +def bininfo(bv): + if bv is None: + filename = "" + if len(sys.argv) > 1: + filename = sys.argv[1] + else: + filename = interaction.get_open_filename_input("Filename:") + if filename is None: + log.log_warn("No file specified") + sys.exit(1) -bv = binaryninja.BinaryViewType[bintype].open(target) -bv.update_analysis_and_wait() + bv = view.BinaryViewType.get_view_of_file(filename) + log.redirect_output_to_log() + log.log_to_stdout(True) -log.log_info("-------- %s --------" % target) -log.log_info("START: 0x%x" % bv.start) -log.log_info("ENTRY: 0x%x" % bv.entry_point) -log.log_info("ARCH: %s" % bv.arch.name) -log.log_info("\n-------- Function List --------") + contents = "## %s ##\n" % bv.file.filename + contents += "- START: 0x%x\n\n" % bv.start + contents += "- ENTRY: 0x%x\n\n" % bv.entry_point + contents += "- ARCH: %s\n\n" % bv.arch.name + contents += "### First 10 Functions ###\n" -for func in bv.functions: - log.log_info(func.symbol.name) + contents += "| Start | Name |\n" + contents += "|------:|:-------|\n" + for i in xrange(min(10, len(bv.functions))): + contents += "| 0x%x | %s |\n" % (bv.functions[i].start, bv.functions[i].symbol.full_name) + contents += "### First 10 Strings ###\n" + contents += "| Start | Length | String |\n" + contents += "|------:|-------:|:-------|\n" + for i in xrange(min(10, len(bv.strings))): + start = bv.strings[i].start + length = bv.strings[i].length + string = bv.read(start, length) + contents += "| 0x%x |%d | %s |\n" % (start, length, string) -log.log_info("\n-------- First 10 strings --------") + interaction.show_markdown_report("Binary Info Report", contents) -for i in xrange(10): - start = bv.strings[i].start - length = bv.strings[i].length - string = bv.read(start, length) - log.log_info("0x%x (%d):\t%s" % (start, length, string)) + +if __name__ == "__main__": + bininfo(None) +else: + PluginCommand.register("Binary Info", "Display basic info about the binary", bininfo) diff --git a/python/examples/instruction_iterator.py b/python/examples/instruction_iterator.py index 6c9d9653..47717aa0 100644 --- a/python/examples/instruction_iterator.py +++ b/python/examples/instruction_iterator.py @@ -20,7 +20,7 @@ # IN THE SOFTWARE. import sys -import binaryninja +import binaryninja as binja if sys.platform.lower().startswith("linux"): @@ -35,30 +35,30 @@ if len(sys.argv) > 1: else: target = "/bin/ls" -bv = binaryninja.BinaryViewType[bintype].open(target) +bv = binja.BinaryViewType[bintype].open(target) bv.update_analysis_and_wait() - -print "-------- %s --------" % target -print "START: 0x%x" % bv.start -print "ENTRY: 0x%x" % bv.entry_point -print "ARCH: %s" % bv.arch.name -print "\n-------- Function List --------" +binja.log_to_stdout(True) +binja.log_info("-------- %s --------" % target) +binja.log_info("START: 0x%x" % bv.start) +binja.log_info("ENTRY: 0x%x" % bv.entry_point) +binja.log_info("ARCH: %s" % bv.arch.name) +binja.log_info("\n-------- Function List --------") """ print all the functions, their basic blocks, and their il instructions """ for func in bv.functions: - print repr(func) + binja.log_info(repr(func)) for block in func.low_level_il: - print "\t{0}".format(block) + binja.log_info("\t{0}".format(block)) for insn in block: - print "\t\t{0}".format(insn) + binja.log_info("\t\t{0}".format(insn)) """ print all the functions, their basic blocks, and their mc instructions """ for func in bv.functions: - print repr(func) + binja.log_info(repr(func)) for block in func: - print "\t{0}".format(block) + binja.log_info("\t{0}".format(block)) for insn in block: - print "\t\t{0}".format(insn) + binja.log_info("\t\t{0}".format(insn)) diff --git a/python/platform.py b/python/platform.py index d69c38d1..6c3eefea 100644 --- a/python/platform.py +++ b/python/platform.py @@ -241,3 +241,12 @@ class Platform(object): :rtype: None """ core.BNRegisterPlatformCallingConvention(self.handle, cc.handle) + + def get_related_platform(self, arch): + result = core.BNGetRelatedPlatform(self.handle, arch.handle) + if not result: + return None + return Platform(None, handle = result) + + def add_related_platform(self, arch, platform): + core.BNAddRelatedPlatform(self.handle, arch.handle, platform.handle) -- cgit v1.3.1 From 842aba557f24ca9ab63f05cec6aa0c0efebd51b4 Mon Sep 17 00:00:00 2001 From: Peter LaFosse Date: Mon, 2 Jan 2017 15:19:47 -0500 Subject: Making platform and architecture optional parameters where possible --- python/architecture.py | 6 ++ python/basicblock.py | 47 +++++++++-- python/binaryview.py | 153 +++++++++++++++++++++-------------- python/examples/jump_table.py | 2 +- python/examples/print_syscalls.py | 2 +- python/filemetadata.py | 8 +- python/function.py | 162 ++++++++++++++++++++++++++++++++------ python/scriptingprovider.py | 43 ++++++++++ 8 files changed, 330 insertions(+), 93 deletions(-) (limited to 'python/examples') diff --git a/python/architecture.py b/python/architecture.py index 0cdba6e5..5162e58a 100644 --- a/python/architecture.py +++ b/python/architecture.py @@ -1152,6 +1152,12 @@ class Architecture(object): core.BNFreeInstructionText(tokens, count.value) return result, length.value + def get_instruction_low_level_il_instruction(self, bv, addr): + il = lowlevelil.LowLevelILFunction(self) + data = bv.read(addr, self.max_instr_length) + self.get_instruction_low_level_il(data, addr, il) + return il[0] + def get_instruction_low_level_il(self, data, addr, il): """ ``get_instruction_low_level_il`` appends LowLevelILExpr objects for the instruction at the given virtual diff --git a/python/basicblock.py b/python/basicblock.py index 7abfdc94..d728cb8d 100644 --- a/python/basicblock.py +++ b/python/basicblock.py @@ -111,11 +111,25 @@ class BasicBlock(object): @property def disassembly_text(self): + """ + ``disassembly_text`` property which returns a list of function.DisassemblyTextLine objects for the current basic block. + :Example: + + >>> current_basic_block.disassembly_text + [<0x100000f30: _main:>, ...] + """ return self.get_disassembly_text() @property def highlight(self): - """Highlight color for basic block""" + """Gets or sets the highlight color for basic block + + :Example: + + >>> current_basic_block.highlight = core.BNHighlightStandardColor.BlueHighlightColor + >>> current_basic_block.highlight + + """ color = core.BNGetBasicBlockHighlight(self.handle) if color.style == core.BNHighlightColorStyle.StandardHighlightColor: return highlight.HighlightColor(color=color.color, alpha=color.alpha) @@ -162,6 +176,13 @@ class BasicBlock(object): core.BNMarkBasicBlockAsRecentlyUsed(self.handle) def get_disassembly_text(self, settings=None): + """ + ``get_disassembly_text`` returns a list of function.DisassemblyTextLine objects for the current basic block. + :Example: + + >>>current_basic_block.get_disassembly_text() + [<0x100000f30: _main:>, <0x100000f30: push rbp>, ... ] + """ settings_obj = None if settings: settings_obj = settings.handle @@ -184,11 +205,27 @@ class BasicBlock(object): return result def set_auto_highlight(self, color): - if not isinstance(color, highlight.HighlightColor): - color = highlight.HighlightColor(color=color) + """ + ``set_auto_highlight`` highlights the current BasicBlock with the supplied color. + + .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 + """ + if not isinstance(color, core.BNHighlightStandardColor) and not isinstance(color, highlight.HighlightColor): + raise ValueError("Specified color is not one of core.BNHighlightStandardColor, highlight.HighlightColor") core.BNSetAutoBasicBlockHighlight(self.handle, color._get_core_struct()) def set_user_highlight(self, color): - if not isinstance(color, highlight.HighlightColor): - color = highlight.HighlightColor(color=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 + :Example: + + >>> current_basic_block.set_user_highlight(highlight.HighlightColor(red=0xff, blue=0xff, green=0)) + >>> current_basic_block.set_user_highlight(core.BNHighlightStandardColor.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") core.BNSetUserBasicBlockHighlight(self.handle, color._get_core_struct()) diff --git a/python/binaryview.py b/python/binaryview.py index e6e0ff61..7c85cd52 100644 --- a/python/binaryview.py +++ b/python/binaryview.py @@ -275,7 +275,7 @@ class BinaryViewType(object): @property def name(self): - """Binary View name (read-only)""" + """BinaryView name (read-only)""" return core.BNGetBinaryViewTypeName(self.handle) @property @@ -303,12 +303,21 @@ class BinaryViewType(object): """ ``get_view_of_file`` returns the first available, non-Raw `BinaryView` available. - :param str filename: Path to filename + :param str filename: Path to filename or bndb :param bool update_analysis: defaults to True. Pass False to not run update_analysis_and_wait. :return: returns a BinaryView object for the given filename. :rtype: BinaryView or None """ - view = BinaryView.open(filename) + sqlite = "SQLite format 3" + if filename.endswith(".bndb"): + f = open(filename, 'r') + if f is None or f.read(len(sqlite)) != sqlite: + return None + f.close() + view = filemetadata.FileMetadata().open_existing_database(filename) + else: + view = BinaryView.open(filename) + if view is None: return None for available in view.available_view_types: @@ -1381,7 +1390,7 @@ class BinaryView(object): >>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>> bv.begin_undo_actions() - >>> bv.convert_to_nop(bv.arch, 0x100012f1) + >>> bv.convert_to_nop(0x100012f1) True >>> bv.commit_undo_actions() >>> bv.get_disassembly(0x100012f1) @@ -1406,7 +1415,7 @@ class BinaryView(object): >>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>> bv.begin_undo_actions() - >>> bv.convert_to_nop(bv.arch, 0x100012f1) + >>> bv.convert_to_nop(0x100012f1) True >>> bv.commit_undo_actions() >>> bv.get_disassembly(0x100012f1) @@ -1428,7 +1437,7 @@ class BinaryView(object): >>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>> bv.begin_undo_actions() - >>> bv.convert_to_nop(bv.arch, 0x100012f1) + >>> bv.convert_to_nop(0x100012f1) True >>> bv.commit_undo_actions() >>> bv.get_disassembly(0x100012f1) @@ -1453,7 +1462,7 @@ class BinaryView(object): >>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>> bv.begin_undo_actions() - >>> bv.convert_to_nop(bv.arch, 0x100012f1) + >>> bv.convert_to_nop(0x100012f1) True >>> bv.commit_undo_actions() >>> bv.get_disassembly(0x100012f1) @@ -1624,33 +1633,37 @@ class BinaryView(object): self.notifications[notify]._unregister() del self.notifications[notify] - def add_function(self, plat, addr): + def add_function(self, addr, plat=None): """ ``add_function`` add a new function of the given ``plat`` at the virtual address ``addr`` - :param Platform plat: Platform for the function to be added :param int addr: virtual address of the function to be added + :param Platform plat: Platform for the function to be added :rtype: None :Example: - >>> bv.add_function(bv.plat, 1) + >>> bv.add_function(1) >>> bv.functions [] """ + if plat is None: + plat = self.platform core.BNAddFunctionForAnalysis(self.handle, plat.handle, addr) - def add_entry_point(self, plat, addr): + def add_entry_point(self, addr, plat=None): """ ``add_entry_point`` adds an virtual address to start analysis from for a given plat. - :param Platform plat: Platform for the entry point analysis :param int addr: virtual address to start analysis from + :param Platform plat: Platform for the entry point analysis :rtype: None :Example: - >>> bv.add_entry_point(bv.plat, 0xdeadbeef) + >>> bv.add_entry_point(0xdeadbeef) >>> """ + if plat is None: + plat = self.platform core.BNAddEntryPointForAnalysis(self.handle, plat.handle, addr) def remove_function(self, func): @@ -1669,20 +1682,22 @@ class BinaryView(object): """ core.BNRemoveAnalysisFunction(self.handle, func.handle) - def create_user_function(self, plat, addr): + def create_user_function(self, addr, plat=None): """ ``create_user_function`` add a new *user* function of the given ``plat`` at the virtual address ``addr`` - :param Platform plat: Platform for the function to be added :param int addr: virtual address of the *user* function to be added + :param Platform plat: Platform for the function to be added :rtype: None :Example: - >>> bv.create_user_function(bv.plat, 1) + >>> bv.create_user_function(1) >>> bv.functions [] """ + if plat is None: + plat = self.platform core.BNCreateUserFunction(self.handle, plat.handle, addr) def remove_user_function(self, func): @@ -1832,20 +1847,22 @@ class BinaryView(object): return None return DataVariable(var.address, type.Type(var.type), var.autoDiscovered) - def get_function_at(self, plat, addr): + def get_function_at(self, addr, plat=None): """ ``get_function_at`` gets a binaryninja.Function object for the function at the virtual address ``addr``: - :param binaryninja.Platform plat: plat of the desired function :param int addr: virtual address of the desired function + :param Platform plat: plat of the desired function :return: returns a Function object or None for the function at the virtual address provided :rtype: Function :Example: - >>> bv.get_function_at(bv.plat, bv.entry_point) + >>> bv.get_function_at(bv.entry_point) >>> """ + if plat is None: + plat = self.platform func = core.BNGetAnalysisFunction(self.handle, plat.handle, addr) if func is None: return None @@ -2092,144 +2109,154 @@ class BinaryView(object): """ core.BNDefineImportedFunction(self.handle, import_addr_sym.handle, func.handle) - def is_never_branch_patch_available(self, arch, addr): + def is_never_branch_patch_available(self, addr, arch=None): """ ``is_never_branch_patch_available`` queries the architecture plugin to determine if the instruction at the instruction at ``addr`` can be made to **never branch**. The actual logic of which is implemented in the ``perform_is_never_branch_patch_available`` in the corresponding architecture. - :param Architecture arch: the architecture for the current view :param int addr: the virtual address of the instruction to be patched + :param Architecture arch: (optional) the architecture of the instructions if different from the default :return: True if the instruction can be patched, False otherwise :rtype: bool :Example: >>> bv.get_disassembly(0x100012ed) 'test eax, eax' - >>> bv.is_never_branch_patch_available(bv.arch, 0x100012ed) + >>> bv.is_never_branch_patch_available(0x100012ed) False >>> bv.get_disassembly(0x100012ef) 'jg 0x100012f5' - >>> bv.is_never_branch_patch_available(bv.arch, 0x100012ef) + >>> bv.is_never_branch_patch_available(0x100012ef) True >>> """ + if arch is None: + arch = self.arch return core.BNIsNeverBranchPatchAvailable(self.handle, arch.handle, addr) - def is_always_branch_patch_available(self, arch, addr): + def is_always_branch_patch_available(self, addr, arch=None): """ ``is_always_branch_patch_available`` queries the architecture plugin to determine if the instruction at ``addr`` can be made to **always branch**. The actual logic of which is implemented in the ``perform_is_always_branch_patch_available`` in the corresponding architecture. - :param Architecture arch: the architecture for the current view :param int addr: the virtual address of the instruction to be patched + :param Architecture arch: (optional) the architecture for the current view :return: True if the instruction can be patched, False otherwise :rtype: bool :Example: >>> bv.get_disassembly(0x100012ed) 'test eax, eax' - >>> bv.is_always_branch_patch_available(bv.arch, 0x100012ed) + >>> bv.is_always_branch_patch_available(0x100012ed) False >>> bv.get_disassembly(0x100012ef) 'jg 0x100012f5' - >>> bv.is_always_branch_patch_available(bv.arch, 0x100012ef) + >>> bv.is_always_branch_patch_available(0x100012ef) True >>> """ + if arch is None: + arch = self.arch return core.BNIsAlwaysBranchPatchAvailable(self.handle, arch.handle, addr) - def is_invert_branch_patch_available(self, arch, addr): + def is_invert_branch_patch_available(self, addr, arch=None): """ ``is_invert_branch_patch_available`` queries the architecture plugin to determine if the instruction at ``addr`` is a branch that can be inverted. The actual logic of which is implemented in the ``perform_is_invert_branch_patch_available`` in the corresponding architecture. - :param Architecture arch: the architecture for the current view :param int addr: the virtual address of the instruction to be patched + :param Architecture arch: (optional) the architecture of the instructions if different from the default :return: True if the instruction can be patched, False otherwise :rtype: bool :Example: >>> bv.get_disassembly(0x100012ed) 'test eax, eax' - >>> bv.is_invert_branch_patch_available(bv.arch, 0x100012ed) + >>> bv.is_invert_branch_patch_available(0x100012ed) False >>> bv.get_disassembly(0x100012ef) 'jg 0x100012f5' - >>> bv.is_invert_branch_patch_available(bv.arch, 0x100012ef) + >>> bv.is_invert_branch_patch_available(0x100012ef) True >>> """ + if arch is None: + arch = self.arch return core.BNIsInvertBranchPatchAvailable(self.handle, arch.handle, addr) - def is_skip_and_return_zero_patch_available(self, arch, addr): + def is_skip_and_return_zero_patch_available(self, addr, arch=None): """ ``is_skip_and_return_zero_patch_available`` queries the architecture plugin to determine if the instruction at ``addr`` is similar to an x86 "call" instruction which can be made to return zero. The actual logic of which is implemented in the ``perform_is_skip_and_return_zero_patch_available`` in the corresponding architecture. - :param Architecture arch: the architecture for the current view :param int addr: the virtual address of the instruction to be patched + :param Architecture arch: (optional) the architecture of the instructions if different from the default :return: True if the instruction can be patched, False otherwise :rtype: bool :Example: >>> bv.get_disassembly(0x100012f6) 'mov dword [0x10003020], eax' - >>> bv.is_skip_and_return_zero_patch_available(bv.arch, 0x100012f6) + >>> bv.is_skip_and_return_zero_patch_available(0x100012f6) False >>> bv.get_disassembly(0x100012fb) 'call 0x10001629' - >>> bv.is_skip_and_return_zero_patch_available(bv.arch, 0x100012fb) + >>> bv.is_skip_and_return_zero_patch_available(0x100012fb) True >>> """ + if arch is None: + arch = self.arch return core.BNIsSkipAndReturnZeroPatchAvailable(self.handle, arch.handle, addr) - def is_skip_and_return_value_patch_available(self, arch, addr): + def is_skip_and_return_value_patch_available(self, addr, arch=None): """ ``is_skip_and_return_value_patch_available`` queries the architecture plugin to determine if the instruction at ``addr`` is similar to an x86 "call" instruction which can be made to return a value. The actual logic of which is implemented in the ``perform_is_skip_and_return_value_patch_available`` in the corresponding architecture. - :param Architecture arch: the architecture for the current view :param int addr: the virtual address of the instruction to be patched + :param Architecture arch: (optional) the architecture of the instructions if different from the default :return: True if the instruction can be patched, False otherwise :rtype: bool :Example: >>> bv.get_disassembly(0x100012f6) 'mov dword [0x10003020], eax' - >>> bv.is_skip_and_return_value_patch_available(bv.arch, 0x100012f6) + >>> bv.is_skip_and_return_value_patch_available(0x100012f6) False >>> bv.get_disassembly(0x100012fb) 'call 0x10001629' - >>> bv.is_skip_and_return_value_patch_available(bv.arch, 0x100012fb) + >>> bv.is_skip_and_return_value_patch_available(0x100012fb) True >>> """ + if arch is None: + arch = self.arch return core.BNIsSkipAndReturnValuePatchAvailable(self.handle, arch.handle, addr) - def convert_to_nop(self, arch, addr): + def convert_to_nop(self, addr, arch=None): """ ``convert_to_nop`` converts the instruction at virtual address ``addr`` to a nop of the provided architecture. .. note:: This API performs a binary patch, analysis may need to be updated afterward. Additionally the binary\ file must be saved in order to preserve the changes made. - :param Architecture arch: architecture of the current BinaryView :param int addr: virtual address of the instruction to conver to nops + :param Architecture arch: (optional) the architecture of the instructions if different from the default :return: True on success, False on falure. :rtype: bool :Example: >>> bv.get_disassembly(0x100012fb) 'call 0x10001629' - >>> bv.convert_to_nop(bv.arch, 0x100012fb) + >>> bv.convert_to_nop(0x100012fb) True >>> #The above 'call' instruction is 5 bytes, a nop in x86 is 1 byte, >>> # thus 5 nops are used: @@ -2246,9 +2273,11 @@ class BinaryView(object): >>> bv.get_next_disassembly() 'mov byte [ebp-0x1c], al' """ + if arch is None: + arch = self.arch return core.BNConvertToNop(self.handle, arch.handle, addr) - def always_branch(self, arch, addr): + def always_branch(self, addr, arch=None): """ ``always_branch`` convert the instruction of architecture ``arch`` at the virtual address ``addr`` to an unconditional branch. @@ -2256,23 +2285,25 @@ class BinaryView(object): .. note:: This API performs a binary patch, analysis may need to be updated afterward. Additionally the binary\ file must be saved in order to preserve the changes made. - :param Architecture arch: architecture of the current binary view :param int addr: virtual address of the instruction to be modified + :param Architecture arch: (optional) the architecture of the instructions if different from the default :return: True on success, False on falure. :rtype: bool :Example: >>> bv.get_disassembly(0x100012ef) 'jg 0x100012f5' - >>> bv.always_branch(bv.arch, 0x100012ef) + >>> bv.always_branch(0x100012ef) True >>> bv.get_disassembly(0x100012ef) 'jmp 0x100012f5' >>> """ + if arch is None: + arch = self.arch return core.BNAlwaysBranch(self.handle, arch.handle, addr) - def never_branch(self, arch, addr): + def never_branch(self, addr, arch=None): """ ``never_branch`` convert the branch instruction of architecture ``arch`` at the virtual address ``addr`` to a fall through. @@ -2280,23 +2311,25 @@ class BinaryView(object): .. note:: This API performs a binary patch, analysis may need to be updated afterward. Additionally the binary\ file must be saved in order to preserve the changes made. - :param Architecture arch: architecture of the current binary view :param int addr: virtual address of the instruction to be modified + :param Architecture arch: (optional) the architecture of the instructions if different from the default :return: True on success, False on falure. :rtype: bool :Example: >>> bv.get_disassembly(0x1000130e) 'jne 0x10001317' - >>> bv.never_branch(bv.arch, 0x1000130e) + >>> bv.never_branch(0x1000130e) True >>> bv.get_disassembly(0x1000130e) 'nop' >>> """ + if arch is None: + arch = self.arch return core.BNConvertToNop(self.handle, arch.handle, addr) - def invert_branch(self, arch, addr): + def invert_branch(self, addr, arch=None): """ ``invert_branch`` convert the branch instruction of architecture ``arch`` at the virtual address ``addr`` to the inverse branch. @@ -2304,63 +2337,69 @@ class BinaryView(object): .. note:: This API performs a binary patch, analysis may need to be updated afterward. Additionally the binary file must be saved in order to preserve the changes made. - :param Architecture arch: architecture of the current binary view :param int addr: virtual address of the instruction to be modified + :param Architecture arch: (optional) the architecture of the instructions if different from the default :return: True on success, False on falure. :rtype: bool :Example: >>> bv.get_disassembly(0x1000130e) 'je 0x10001317' - >>> bv.invert_branch(bv.arch, 0x1000130e) + >>> bv.invert_branch(0x1000130e) True >>> >>> bv.get_disassembly(0x1000130e) 'jne 0x10001317' >>> """ + if arch is None: + arch = self.arch return core.BNInvertBranch(self.handle, arch.handle, addr) - def skip_and_return_value(self, arch, addr, value): + def skip_and_return_value(self, addr, value, arch=None): """ ``skip_and_return_value`` convert the ``call`` instruction of architecture ``arch`` at the virtual address ``addr`` to the equivilent of returning a value. - :param Architecture arch: architecture of the current binary view :param int addr: virtual address of the instruction to be modified :param int value: value to make the instruction *return* + :param Architecture arch: (optional) the architecture of the instructions if different from the default :return: True on success, False on falure. :rtype: bool :Example: >>> bv.get_disassembly(0x1000132a) 'call 0x1000134a' - >>> bv.skip_and_return_value(bv.arch, 0x1000132a, 42) + >>> bv.skip_and_return_value(0x1000132a, 42) True >>> #The return value from x86 functions is stored in eax thus: >>> bv.get_disassembly(0x1000132a) 'mov eax, 0x2a' >>> """ + if arch is None: + arch = self.arch return core.BNSkipAndReturnValue(self.handle, arch.handle, addr, value) - def get_instruction_length(self, arch, addr): + def get_instruction_length(self, addr, arch=None): """ ``get_instruction_length`` returns the number of bytes in the instruction of Architecture ``arch`` at the virtual address ``addr`` - :param Architecture arch: architecture of the current binary view :param int addr: virtual address of the instruction query + :param Architecture arch: (optional) the architecture of the instructions if different from the default :return: Number of bytes in instruction :rtype: int :Example: >>> bv.get_disassembly(0x100012f1) 'xor eax, eax' - >>> bv.get_instruction_length(bv.arch, 0x100012f1) + >>> bv.get_instruction_length(0x100012f1) 2L >>> """ + if arch is None: + arch = self.arch return core.BNGetInstructionLength(self.handle, arch.handle, addr) def notify_data_written(self, offset, length): diff --git a/python/examples/jump_table.py b/python/examples/jump_table.py index 23531de0..0fd0dbab 100644 --- a/python/examples/jump_table.py +++ b/python/examples/jump_table.py @@ -77,7 +77,7 @@ def find_jump_table(bv, addr): i += 1 # Set the indirect branch targets on the jump instruction to be the list of targets discovered - func.set_user_indirect_branches(arch, jump_addr, branches) + 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 diff --git a/python/examples/print_syscalls.py b/python/examples/print_syscalls.py index c3b47a8d..003b388e 100644 --- a/python/examples/print_syscalls.py +++ b/python/examples/print_syscalls.py @@ -43,7 +43,7 @@ def print_syscalls(bv): 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(bv.arch, il.address, register).value + value = func.get_reg_value_at(il.address, register).value print("System call address: {:#x} - {:d}".format(il.address, value)) diff --git a/python/filemetadata.py b/python/filemetadata.py index 846c9f94..f6593405 100644 --- a/python/filemetadata.py +++ b/python/filemetadata.py @@ -208,7 +208,7 @@ class FileMetadata(object): >>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>> bv.begin_undo_actions() - >>> bv.convert_to_nop(bv.arch, 0x100012f1) + >>> bv.convert_to_nop(0x100012f1) True >>> bv.commit_undo_actions() >>> bv.get_disassembly(0x100012f1) @@ -230,7 +230,7 @@ class FileMetadata(object): >>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>> bv.begin_undo_actions() - >>> bv.convert_to_nop(bv.arch, 0x100012f1) + >>> bv.convert_to_nop(0x100012f1) True >>> bv.commit_undo_actions() >>> bv.get_disassembly(0x100012f1) @@ -252,7 +252,7 @@ class FileMetadata(object): >>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>> bv.begin_undo_actions() - >>> bv.convert_to_nop(bv.arch, 0x100012f1) + >>> bv.convert_to_nop(0x100012f1) True >>> bv.commit_undo_actions() >>> bv.get_disassembly(0x100012f1) @@ -277,7 +277,7 @@ class FileMetadata(object): >>> bv.get_disassembly(0x100012f1) 'xor eax, eax' >>> bv.begin_undo_actions() - >>> bv.convert_to_nop(bv.arch, 0x100012f1) + >>> bv.convert_to_nop(0x100012f1) True >>> bv.commit_undo_actions() >>> bv.get_disassembly(0x100012f1) diff --git a/python/function.py b/python/function.py index 2910d283..7253f264 100644 --- a/python/function.py +++ b/python/function.py @@ -286,7 +286,7 @@ class Function(object): @property def function_type(self): - """Function type""" + """Function type object""" return bntype.Type(core.BNGetFunctionType(self.handle)) @function_type.setter @@ -358,10 +358,26 @@ class Function(object): def set_comment(self, addr, comment): core.BNSetCommentForAddress(self.handle, addr, comment) - def get_low_level_il_at(self, arch, addr): + def get_low_level_il_at(self, addr, arch=None): + """ + ``get_low_level_il_at`` gets the LowLevelIL instruction address corresponding to the given virtual address + + :param int addr: virtual address of the function to be queried + :param Architecture arch: (optional) Architecture for the given function + :rtype: int + :Example: + + >>> func = bv.functions[0] + >>> func.get_low_level_il_at(func.start) + 0L + """ + if arch is None: + arch = self.arch return core.BNGetLowLevelILForInstruction(self.handle, arch.handle, addr) - def get_low_level_il_exits_at(self, arch, addr): + def get_low_level_il_exits_at(self, addr, arch=None): + if arch is None: + arch = self.arch count = ctypes.c_ulonglong() exits = core.BNGetLowLevelILExitsForInstruction(self.handle, arch.handle, addr, count) result = [] @@ -370,7 +386,21 @@ class Function(object): core.BNFreeLowLevelILInstructionList(exits) return result - def get_reg_value_at(self, arch, addr, reg): + def get_reg_value_at(self, addr, reg, arch=None): + """ + ``get_reg_value_at`` gets the value the provided string register address corresponding to the given virtual address + + :param int addr: virtual address of the instruction to query + :param str reg: string value of native register to query + :param Architecture arch: (optional) Architecture for the given function + :rtype: function.RegisterValue + :Example: + + >>> func.get_reg_value_at(0x400dbe, 'rdi') + + """ + if arch is None: + arch = self.arch if isinstance(reg, str): reg = arch.regs[reg].index value = core.BNGetRegisterValueAtInstruction(self.handle, arch.handle, addr, reg) @@ -378,7 +408,21 @@ class Function(object): core.BNFreeRegisterValue(value) return result - def get_reg_value_after(self, arch, addr, reg): + def get_reg_value_after(self, addr, reg, arch=None): + """ + ``get_reg_value_after`` gets the value instruction address corresponding to the given virtual address + + :param int addr: virtual address of the instruction to query + :param str reg: string value of native register to query + :param Architecture arch: (optional) Architecture for the given function + :rtype: function.RegisterValue + :Example: + + >>> func.get_reg_value_after(0x400dbe, 'rdi') + + """ + if arch is None: + arch = self.arch if isinstance(reg, str): reg = arch.regs[reg].index value = core.BNGetRegisterValueAfterInstruction(self.handle, arch.handle, addr, reg) @@ -386,11 +430,25 @@ class Function(object): core.BNFreeRegisterValue(value) return result - def get_reg_value_at_low_level_il_instruction(self, i, reg): + def get_reg_value_at_low_level_il_instruction(self, i, reg, arch=None): + """ + ``get_reg_value_at_low_level_il_instruction`` returns the value of the specified register ``reg`` at the il address + i + + :param int i: il address of instruction to query + :param Architecture arch: (optional) Architecture for the given function + :rtype: function.RegisterValue + :Example: + + >>> func.get_reg_value_at_low_level_il_instruction(15, 'rdi') + + """ + if arch is None: + arch = self.arch if isinstance(reg, str): reg = self.arch.regs[reg].index value = core.BNGetRegisterValueAtLowLevelILInstruction(self.handle, i, reg) - result = RegisterValue(self.arch, value) + result = RegisterValue(arch, value) core.BNFreeRegisterValue(value) return result @@ -402,13 +460,35 @@ class Function(object): core.BNFreeRegisterValue(value) return result - def get_stack_contents_at(self, arch, addr, offset, size): + def get_stack_contents_at(self, addr, offset, size, arch=None): + """ + ``get_stack_contents_at`` returns the RegisterValue for the item on the stack in the current function at the + given virtual address ``addr``, stack offset ``offset`` and size of ``size``. Optionally specifying the architecture. + + :param int addr: virtual address of the instruction to query + :param int offset: stack offset base of stack + :param int size: size of memory to query + :param Architecture arch: (optional) Architecture for the given function + :rtype: function.RegisterValue + + .. note:: Stack base is zero on entry into the function unless the architecture places the return address on the + stack as in (x86/x86_64) where the stack base will start at address_size + + :Example: + + >>> func.get_stack_contents_at(0x400fad, -16, 4) + + """ + if arch is None: + arch = self.arch value = core.BNGetStackContentsAtInstruction(self.handle, arch.handle, addr, offset, size) result = RegisterValue(arch, value) core.BNFreeRegisterValue(value) return result - def get_stack_contents_after(self, arch, addr, offset, size): + def get_stack_contents_after(self, addr, offset, size, arch=None): + if arch is None: + arch = self.arch value = core.BNGetStackContentsAfterInstruction(self.handle, arch.handle, addr, offset, size) result = RegisterValue(arch, value) core.BNFreeRegisterValue(value) @@ -426,7 +506,9 @@ class Function(object): core.BNFreeRegisterValue(value) return result - def get_parameter_at(self, arch, addr, func_type, i): + def get_parameter_at(self, addr, func_type, i, arch=None): + if arch is None: + arch = self.arch if func_type is not None: func_type = func_type.handle value = core.BNGetParameterValueAtInstruction(self.handle, arch.handle, addr, func_type, i) @@ -442,7 +524,9 @@ class Function(object): core.BNFreeRegisterValue(value) return result - def get_regs_read_by(self, arch, addr): + def get_regs_read_by(self, addr, arch=None): + if arch is None: + arch = self.arch count = ctypes.c_ulonglong() regs = core.BNGetRegistersReadByInstruction(self.handle, arch.handle, addr, count) result = [] @@ -451,7 +535,9 @@ class Function(object): core.BNFreeRegisterList(regs) return result - def get_regs_written_by(self, arch, addr): + def get_regs_written_by(self, addr, arch=None): + if arch is None: + arch = self.arch count = ctypes.c_ulonglong() regs = core.BNGetRegistersWrittenByInstruction(self.handle, arch.handle, addr, count) result = [] @@ -460,7 +546,9 @@ class Function(object): core.BNFreeRegisterList(regs) return result - def get_stack_vars_referenced_by(self, arch, addr): + def get_stack_vars_referenced_by(self, addr, arch=None): + if arch is None: + arch = self.arch count = ctypes.c_ulonglong() refs = core.BNGetStackVariablesReferencedByInstruction(self.handle, arch.handle, addr, count) result = [] @@ -470,7 +558,9 @@ class Function(object): core.BNFreeStackVariableReferenceList(refs, count.value) return result - def get_constants_referenced_by(self, arch, addr): + def get_constants_referenced_by(self, addr, arch=None): + if arch is None: + arch = self.arch count = ctypes.c_ulonglong() refs = core.BNGetConstantsReferencedByInstruction(self.handle, arch.handle, addr, count) result = [] @@ -479,7 +569,9 @@ class Function(object): core.BNFreeConstantReferenceList(refs) return result - def get_lifted_il_at(self, arch, addr): + def get_lifted_il_at(self, addr, arch=None): + if arch is None: + arch = self.arch return core.BNGetLiftedILForInstruction(self.handle, arch.handle, addr) def get_lifted_il_flag_uses_for_definition(self, i, flag): @@ -531,21 +623,27 @@ class Function(object): def apply_auto_discovered_type(self, func_type): core.BNApplyAutoDiscoveredFunctionType(self.handle, func_type.handle) - def set_auto_indirect_branches(self, source_arch, source, branches): + def set_auto_indirect_branches(self, source, branches, source_arch=None): + if source_arch is None: + source_arch = self.arch branch_list = (core.BNArchitectureAndAddress * len(branches))() for i in xrange(len(branches)): branch_list[i].arch = branches[i][0].handle branch_list[i].address = branches[i][1] core.BNSetAutoIndirectBranches(self.handle, source_arch.handle, source, branch_list, len(branches)) - def set_user_indirect_branches(self, source_arch, source, branches): + def set_user_indirect_branches(self, source, branches, source_arch=None): + if source_arch is None: + source_arch = self.arch branch_list = (core.BNArchitectureAndAddress * len(branches))() for i in xrange(len(branches)): branch_list[i].arch = branches[i][0].handle branch_list[i].address = branches[i][1] core.BNSetUserIndirectBranches(self.handle, source_arch.handle, source, branch_list, len(branches)) - def get_indirect_branches_at(self, arch, addr): + def get_indirect_branches_at(self, addr, arch=None): + if arch is None: + arch = self.arch count = ctypes.c_ulonglong() branches = core.BNGetIndirectBranchesAt(self.handle, arch.handle, addr, count) result = [] @@ -554,7 +652,9 @@ class Function(object): core.BNFreeIndirectBranchList(branches) return result - def get_block_annotations(self, arch, addr): + def get_block_annotations(self, addr, arch=None): + if arch is None: + arch = self.arch count = ctypes.c_ulonglong(0) lines = core.BNGetFunctionBlockAnnotations(self.handle, arch.handle, addr, count) result = [] @@ -577,10 +677,14 @@ class Function(object): def set_user_type(self, value): core.BNSetFunctionUserType(self.handle, value.handle) - def get_int_display_type(self, arch, instr_addr, value, operand): + def get_int_display_type(self, instr_addr, value, operand, arch=None): + if arch is None: + arch = self.arch return core.BNGetIntegerConstantDisplayType(self.handle, arch.handle, instr_addr, value, operand) - def set_int_display_type(self, arch, instr_addr, value, operand, display_type): + def set_int_display_type(self, instr_addr, value, operand, display_type, arch=None): + if arch is None: + arch = self.arch if isinstance(display_type, str): display_type = core.BNIntegerDisplayType[display_type] core.BNSetIntegerConstantDisplayType(self.handle, arch.handle, instr_addr, value, operand, display_type) @@ -601,13 +705,17 @@ class Function(object): core.BNReleaseAdvancedFunctionAnalysisData(self.handle) self._advanced_analysis_requests -= 1 - def get_basic_block_at(self, arch, addr): + def get_basic_block_at(self, addr, arch=None): + if arch is None: + arch = self.arch block = core.BNGetFunctionBasicBlockAtAddress(self.handle, arch.handle, addr) if not block: return None return basicblock.BasicBlock(self._view, handle = block) - def get_instr_highlight(self, arch, addr): + def get_instr_highlight(self, addr, arch=None): + if arch is None: + arch = self.arch color = core.BNGetInstructionHighlight(self.handle, arch.handle, addr) if color.style == core.BNHighlightColorStyle.StandardHighlightColor: return highlight.HighlightColor(color = color.color, alpha = color.alpha) @@ -617,12 +725,16 @@ class Function(object): return highlight.HighlightColor(red = color.r, green = color.g, blue = color.b, alpha = color.alpha) return highlight.HighlightColor(color = core.BNHighlightStandardColor.NoHighlightColor) - def set_auto_instr_highlight(self, arch, addr, color): + def set_auto_instr_highlight(self, addr, color, arch=None): + if arch is None: + arch = self.arch if not isinstance(color, highlight.HighlightColor): color = highlight.HighlightColor(color = color) core.BNSetAutoInstructionHighlight(self.handle, arch.handle, addr, color._get_core_struct()) - def set_user_instr_highlight(self, arch, addr, color): + def set_user_instr_highlight(self, addr, color, arch=None): + if arch is None: + arch = self.arch if not isinstance(color, highlight.HighlightColor): color = highlight.HighlightColor(color = color) core.BNSetUserInstructionHighlight(self.handle, arch.handle, addr, color._get_core_struct()) diff --git a/python/scriptingprovider.py b/python/scriptingprovider.py index 3ccf9560..cbd9696d 100644 --- a/python/scriptingprovider.py +++ b/python/scriptingprovider.py @@ -334,6 +334,48 @@ class _PythonScriptingInstanceOutput(object): self.orig = orig self.is_error = is_error self.buffer = "" + self.encoding = 'UTF-8' + self.errors = None + self.isatty = False + self.mode = 'w' + self.name = 'PythonScriptingInstanceOutput' + self.newlines = None + + def close(self): + pass + + def closed(self): + return False + + def flush(self): + pass + + def next(self): + raise IOError("File not open for reading") + + def read(self): + raise IOError("File not open for reading") + + def readinto(self): + raise IOError("File not open for reading") + + def readlines(self): + raise IOError("File not open for reading") + + def seek(self): + pass + + def sofspace(self): + return 0 + + def truncate(self): + pass + + def tell(self): + return self.orig.tell() + + def writelines(self, lines): + return self.write('\n'.join(lines)) def write(self, data): global _output_to_log @@ -590,6 +632,7 @@ class PythonScriptingProvider(ScriptingProvider): name = "Python" instance_class = PythonScriptingInstance + PythonScriptingProvider().register() # Wrap stdin/stdout/stderr for Python scripting provider implementation -- cgit v1.3.1 From 1ff75ac9611c4f8cbde195460dfc18e139fee696 Mon Sep 17 00:00:00 2001 From: Peter LaFosse Date: Mon, 2 Jan 2017 15:34:57 -0500 Subject: merging svg export changes --- python/examples/export_svg.py | 95 ++++++++++++++++++------------------------- 1 file changed, 40 insertions(+), 55 deletions(-) (limited to 'python/examples') diff --git a/python/examples/export_svg.py b/python/examples/export_svg.py index 843b17a5..5a4d2982 100755 --- a/python/examples/export_svg.py +++ b/python/examples/export_svg.py @@ -1,30 +1,10 @@ -# 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 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 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]} @@ -37,51 +17,52 @@ escape_table = { ' ': " " } - 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 + 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 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.BNMessageBoxButtonSet.YesNoButtonSet, icon = core.BNMessageBoxIcon.QuestionIcon) == core.BNMessageBoxButtonResult.YesButton: + if show_message_box("Open SVG", "Would you like to view the exported SVG?", buttons = core.YesNoButtonSet, icon = core.QuestionIcon) == core.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 = '''