Python dis.dis() Examples

The following are 30 code examples of dis.dis(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module dis , or try the search function .
Example #1
Source File: method.py    From neo-boa with MIT License 8 votes vote down vote up
def __init__(self, module, block, module_name, extra):
        self.module = module
        self.block = block
        self.module_name = module_name
        self._extra = extra

        method_block_index = self.get_code_block_index(self.block)
        if method_block_index is None:
            raise Exception('Block of code of a method from %s module was not found', self.module_name)

        self.name = self.block[method_block_index + 1].arg
        self._id = uuid3(UUID('{baa187e0-2c51-4ef6-aa42-b3421c22d5e1}'), self.full_name)
        self.start_line_no = self.block[method_block_index].lineno
        self.code_object = self.block[method_block_index].arg

#        dis.dis(code_object)
        self.code, self.dictionary_defs = preprocess_method_body(self.code_object)

        self.bytecode = Bytecode.from_code(self.code)

        self.evaluate_annotations(method_block_index)
        self.setup() 
Example #2
Source File: test_dis.py    From gcblue with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def do_disassembly_test(self, func, expected):
        s = StringIO.StringIO()
        save_stdout = sys.stdout
        sys.stdout = s
        dis.dis(func)
        sys.stdout = save_stdout
        got = s.getvalue()
        # Trim trailing blanks (if any).
        lines = got.split('\n')
        lines = [line.rstrip() for line in lines]
        expected = expected.split("\n")
        import difflib
        if expected != lines:
            self.fail(
                "events did not match expectation:\n" +
                "\n".join(difflib.ndiff(expected,
                                        lines))) 
Example #3
Source File: stacks.py    From networking with GNU General Public License v3.0 6 votes vote down vote up
def func_bytes(fl):
	import console, dis
	"""
	This function reads a script and
	prints it's memory address.
	"""
	f = open(fl).readlines()
	for line in f:
		try:
			co = compile(line,"<none>","exec")
			t = str(str(co).split("at ")[1]).split(",")[0]
			print t, co.consts
		except:
			pass
	console.set_font("Menlo",10)
	f = open(fl).readlines()
	for line in f:
		try:
			dis.dis(line)
		except:
			pass
	console.set_font() 
Example #4
Source File: pydevd_modify_bytecode.py    From PyDev.Debugger with Eclipse Public License 1.0 6 votes vote down vote up
def _unpack_opargs(code, inserted_code_list, current_index):
    """
    Modified version of `_unpack_opargs` function from module `dis`.
    We have to use it, because sometimes code can be in an inconsistent state: if EXTENDED_ARG
    operator was introduced into the code, but it hasn't been inserted into `code_list` yet.
    In this case we can't use standard `_unpack_opargs` and we should check whether there are
    some new operators in `inserted_code_list`.
    """
    extended_arg = 0
    for i in range(0, len(code), 2):
        op = code[i]
        if op >= HAVE_ARGUMENT:
            if not extended_arg:
                # in case if we added EXTENDED_ARG, but haven't inserted it to the source code yet.
                for code_index in range(current_index, len(inserted_code_list)):
                    inserted_offset, inserted_code = inserted_code_list[code_index]
                    if inserted_offset == i and inserted_code[0] == EXTENDED_ARG:
                        extended_arg = inserted_code[1] << 8
            arg = code[i + 1] | extended_arg
            extended_arg = (arg << 8) if op == EXTENDED_ARG else 0
        else:
            arg = None
        yield (i, op, arg) 
Example #5
Source File: test_dis.py    From oss-ftp with MIT License 6 votes vote down vote up
def do_disassembly_test(self, func, expected):
        s = StringIO.StringIO()
        save_stdout = sys.stdout
        sys.stdout = s
        dis.dis(func)
        sys.stdout = save_stdout
        got = s.getvalue()
        # Trim trailing blanks (if any).
        lines = got.split('\n')
        lines = [line.rstrip() for line in lines]
        expected = expected.split("\n")
        import difflib
        if expected != lines:
            self.fail(
                "events did not match expectation:\n" +
                "\n".join(difflib.ndiff(expected,
                                        lines))) 
Example #6
Source File: test_dis.py    From BinderFilter with MIT License 6 votes vote down vote up
def do_disassembly_test(self, func, expected):
        s = StringIO.StringIO()
        save_stdout = sys.stdout
        sys.stdout = s
        dis.dis(func)
        sys.stdout = save_stdout
        got = s.getvalue()
        # Trim trailing blanks (if any).
        lines = got.split('\n')
        lines = [line.rstrip() for line in lines]
        expected = expected.split("\n")
        import difflib
        if expected != lines:
            self.fail(
                "events did not match expectation:\n" +
                "\n".join(difflib.ndiff(expected,
                                        lines))) 
Example #7
Source File: easy_debug.py    From YAPyPy with MIT License 6 votes vote down vote up
def easy_debug(code: str, should_exec=False, ctx=None):
    res = to_tagged_ast(parse(code).result)
    c = py_compile(res)
    print("-----------code")
    print(code)
    print("-----------Python")
    print(dis.dis(code))
    print("-----------YaPyPy")
    print(dis.dis(c))
    print("-----------astpretty")
    astpretty.pprint(ast.parse(code))
    print("----------- Python exec result")
    exec(code, ctx or {})
    print("-----------YaPyPy exec result")
    if should_exec:
        exec(c, ctx or {})
    else:
        print("\t(skip)") 
Example #8
Source File: test_dis.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def do_disassembly_test(self, func, expected):
        s = StringIO.StringIO()
        save_stdout = sys.stdout
        sys.stdout = s
        dis.dis(func)
        sys.stdout = save_stdout
        got = s.getvalue()
        # Trim trailing blanks (if any).
        lines = got.split('\n')
        lines = [line.rstrip() for line in lines]
        expected = expected.split("\n")
        import difflib
        if expected != lines:
            self.fail(
                "events did not match expectation:\n" +
                "\n".join(difflib.ndiff(expected,
                                        lines))) 
Example #9
Source File: test_dis.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_boundaries(self):
        self.assertEqual(dis.opmap["EXTENDED_ARG"], dis.EXTENDED_ARG)
        self.assertEqual(dis.opmap["STORE_NAME"], dis.HAVE_ARGUMENT) 
Example #10
Source File: function_manager.py    From ray with Apache License 2.0 5 votes vote down vote up
def compute_collision_identifier(self, function_or_class):
        """The identifier is used to detect excessive duplicate exports.

        The identifier is used to determine when the same function or class is
        exported many times. This can yield false positives.

        Args:
            function_or_class: The function or class to compute an identifier
                for.

        Returns:
            The identifier. Note that different functions or classes can give
                rise to same identifier. However, the same function should
                hopefully always give rise to the same identifier. TODO(rkn):
                verify if this is actually the case. Note that if the
                identifier is incorrect in any way, then we may give warnings
                unnecessarily or fail to give warnings, but the application's
                behavior won't change.
        """
        import io
        string_file = io.StringIO()
        if sys.version_info[1] >= 7:
            dis.dis(function_or_class, file=string_file, depth=2)
        else:
            dis.dis(function_or_class, file=string_file)
        collision_identifier = (
            function_or_class.__name__ + ":" + string_file.getvalue())

        # Return a hash of the identifier in case it is too large.
        return hashlib.sha1(collision_identifier.encode("ascii")).digest() 
Example #11
Source File: test_dis.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_dis_none(self):
        try:
            del sys.last_traceback
        except AttributeError:
            pass
        self.assertRaises(RuntimeError, dis.dis, None) 
Example #12
Source File: test_dis.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def get_disassembly(self, func, lasti=-1, wrapper=True):
        output = io.StringIO()
        if wrapper:
            dis.dis(func, file=output)
        else:
            dis.disassemble(func, lasti, file=output)
        return output.getvalue() 
Example #13
Source File: test_dis.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_code_info(self):
        self.maxDiff = 1000
        for x, expected in self.test_pairs:
            self.assertRegex(dis.code_info(x), expected) 
Example #14
Source File: test_dis.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_show_code(self):
        self.maxDiff = 1000
        for x, expected in self.test_pairs:
            with captured_stdout() as output:
                dis.show_code(x)
            self.assertRegex(output.getvalue(), expected+"\n")
            output = io.StringIO()
            dis.show_code(x, file=output)
            self.assertRegex(output.getvalue(), expected) 
Example #15
Source File: test_dis.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_code_info_object(self):
        self.assertRaises(TypeError, dis.code_info, object()) 
Example #16
Source File: test_dis.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_pretty_flags_no_flags(self):
        self.assertEqual(dis.pretty_flags(0), '0x0')


# Fodder for instruction introspection tests
#   Editing any of these may require recalculating the expected output 
Example #17
Source File: bytecode_helper.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def get_disassembly_as_string(self, co):
        s = io.StringIO()
        dis.dis(co, file=s)
        return s.getvalue() 
Example #18
Source File: bytecode_helper.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def assertNotInBytecode(self, x, opname, argval=_UNSPECIFIED):
        """Throws AssertionError if op is found"""
        for instr in dis.get_instructions(x):
            if instr.opname == opname:
                disassembly = self.get_disassembly_as_string(co)
                if opargval is _UNSPECIFIED:
                    msg = '%s occurs in bytecode:\n%s' % (opname, disassembly)
                elif instr.argval == argval:
                    msg = '(%s,%r) occurs in bytecode:\n%s'
                    msg = msg % (opname, argval, disassembly)
                self.fail(msg) 
Example #19
Source File: bytecode_helper.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def assertInBytecode(self, x, opname, argval=_UNSPECIFIED):
        """Returns instr if op is found, otherwise throws AssertionError"""
        for instr in dis.get_instructions(x):
            if instr.opname == opname:
                if argval is _UNSPECIFIED or instr.argval == argval:
                    return instr
        disassembly = self.get_disassembly_as_string(x)
        if argval is _UNSPECIFIED:
            msg = '%s not found in bytecode:\n%s' % (opname, disassembly)
        else:
            msg = '(%s,%r) not found in bytecode:\n%s'
            msg = msg % (opname, argval, disassembly)
        self.fail(msg) 
Example #20
Source File: test_dis.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_opname(self):
        self.assertEqual(dis.opname[dis.opmap["LOAD_FAST"]], "LOAD_FAST") 
Example #21
Source File: test_dis.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_opmap(self):
        self.assertEqual(dis.opmap["NOP"], 9)
        self.assertIn(dis.opmap["LOAD_CONST"], dis.hasconst)
        self.assertIn(dis.opmap["STORE_NAME"], dis.hasname) 
Example #22
Source File: test_dis.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def get_disassembly(self, func, lasti=-1, wrapper=True):
        # We want to test the default printing behaviour, not the file arg
        output = io.StringIO()
        with contextlib.redirect_stdout(output):
            if wrapper:
                dis.dis(func)
            else:
                dis.disassemble(func, lasti)
        return output.getvalue() 
Example #23
Source File: demodis.py    From ubelt with Apache License 2.0 5 votes vote down vote up
def demo():
    import dis

    def func1(x):
        return x + 1

    def func2(x):
        if True:
            return x + 1
        else:
            return x + 2

    import io
    file = io.StringIO()
    print('--- DIS1 ---')
    dis.dis(func1, file=file)
    file.seek(0)
    dis1 = file.read()
    print('--- DIS2 ---')
    file = io.StringIO()
    dis.dis(func2, file=file)
    file.seek(0)
    dis2 = file.read()
    print('dis1 =\n{}'.format(dis1))
    print('dis2 =\n{}'.format(dis2))
    print('dis1 == dis2 = {}'.format(dis1 == dis2))
    print('repr(dis1) ~= repr(dis2) = {}'.format(repr(dis1)[10:] == repr(dis2)[10:])) 
Example #24
Source File: bytecode_helper.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def assertNotInBytecode(self, x, opname, argval=_UNSPECIFIED):
        """Throws AssertionError if op is found"""
        for instr in dis.get_instructions(x):
            if instr.opname == opname:
                disassembly = self.get_disassembly_as_string(co)
                if opargval is _UNSPECIFIED:
                    msg = '%s occurs in bytecode:\n%s' % (opname, disassembly)
                elif instr.argval == argval:
                    msg = '(%s,%r) occurs in bytecode:\n%s'
                    msg = msg % (opname, argval, disassembly)
                self.fail(msg) 
Example #25
Source File: bytecode_helper.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def assertInBytecode(self, x, opname, argval=_UNSPECIFIED):
        """Returns instr if op is found, otherwise throws AssertionError"""
        for instr in dis.get_instructions(x):
            if instr.opname == opname:
                if argval is _UNSPECIFIED or instr.argval == argval:
                    return instr
        disassembly = self.get_disassembly_as_string(x)
        if argval is _UNSPECIFIED:
            msg = '%s not found in bytecode:\n%s' % (opname, disassembly)
        else:
            msg = '(%s,%r) not found in bytecode:\n%s'
            msg = msg % (opname, argval, disassembly)
        self.fail(msg) 
Example #26
Source File: bytecode_helper.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def get_disassembly_as_string(self, co):
        s = io.StringIO()
        dis.dis(co, file=s)
        return s.getvalue() 
Example #27
Source File: test_dis.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_from_traceback_dis(self):
        tb = get_tb()
        b = dis.Bytecode.from_traceback(tb)
        self.assertEqual(b.dis(), dis_traceback) 
Example #28
Source File: test_dis.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_disassembled(self):
        actual = dis.Bytecode(_f).dis()
        self.assertEqual(actual, dis_f) 
Example #29
Source File: test_dis.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_info(self):
        self.maxDiff = 1000
        for x, expected in CodeInfoTests.test_pairs:
            b = dis.Bytecode(x)
            self.assertRegex(b.info(), expected) 
Example #30
Source File: test_dis.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_outer(self):
        actual = dis.get_instructions(outer, first_line=expected_outer_line)
        self.assertEqual(list(actual), expected_opinfo_outer)