Python dis.disassemble() Examples

The following are 19 code examples of dis.disassemble(). 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: ch12_ex1.py    From Functional-Python-Programming-Second-Edition with MIT License 6 votes vote down vote up
def performance():
    import dis
    dis.disassemble(some_function.__code__)
    size = len(some_function.__code__.co_code)
    print(f"size {size} bytes")

    import timeit
    t = timeit.timeit(
        """some_function(4)""",
        """from Chapter_12.ch12_ex1 import some_function"""
    )

    print(f"total time {t:.3f} sec. for 1,000,000 iterations")
    rate = 1_000_000*size/t
    print(f"rate {rate:,.0f} bytes/sec")
    print(f"rate {rate/1_000_000:,.1f} Mbytes/sec") 
Example #2
Source File: tb.py    From owasp-pysec with Apache License 2.0 5 votes vote down vote up
def reset_excepthook():
    sys.excepthook = sys.__excepthook__


# Utilities to format traceback

# inspired by dis.disassemble() in Python 2.7 
Example #3
Source File: test_dis.py    From android_universal with MIT License 5 votes vote down vote up
def jumpy():
    # This won't actually run (but that's OK, we only disassemble it)
    for i in range(10):
        print(i)
        if i < 4:
            continue
        if i > 6:
            break
    else:
        print("I can haz else clause?")
    while i:
        print(i)
        i -= 1
        if i > 6:
            continue
        if i < 4:
            break
    else:
        print("Who let lolcatz into this test suite?")
    try:
        1 / 0
    except ZeroDivisionError:
        print("Here we go, here we go, here we go...")
    else:
        with i as dodgy:
            print("Never reach this")
    finally:
        print("OK, now we're done")

# End fodder for opinfo generation tests 
Example #4
Source File: test_dis.py    From android_universal with MIT License 5 votes vote down vote up
def get_disassembly(self, func, lasti=-1, wrapper=True, **kwargs):
        output = io.StringIO()
        if wrapper:
            dis.dis(func, file=output, **kwargs)
        else:
            dis.disassemble(func, lasti, file=output, **kwargs)
        return output.getvalue() 
Example #5
Source File: test_dis.py    From android_universal with MIT License 5 votes vote down vote up
def get_disassembly(self, func, lasti=-1, wrapper=True, **kwargs):
        # 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, **kwargs)
            else:
                dis.disassemble(func, lasti, **kwargs)
        return output.getvalue() 
Example #6
Source File: test_dis.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def jumpy():
    # This won't actually run (but that's OK, we only disassemble it)
    for i in range(10):
        print(i)
        if i < 4:
            continue
        if i > 6:
            break
    else:
        print("I can haz else clause?")
    while i:
        print(i)
        i -= 1
        if i > 6:
            continue
        if i < 4:
            break
    else:
        print("Who let lolcatz into this test suite?")
    try:
        1 / 0
    except ZeroDivisionError:
        print("Here we go, here we go, here we go...")
    else:
        with i as dodgy:
            print("Never reach this")
    finally:
        print("OK, now we're done")

# End fodder for opinfo generation tests 
Example #7
Source File: test_dis.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.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 #8
Source File: test_dis.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.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 #9
Source File: tb.py    From owasp-pysec with Apache License 2.0 5 votes vote down vote up
def deep_tb(exc_type, exc_value, exc_tb):
    traceback = ['=== Traceback (most recent call last) ===']
    lvl = 0
    while exc_tb:
        path = os.path.abspath(exc_tb.tb_frame.f_code.co_filename)
        lineno = exc_tb.tb_lineno
        traceback.append('[%d]' % lvl)
        traceback.append('  File: %r' % path)
        traceback.append('  Function: %r' % exc_tb.tb_frame.f_code.co_name)
        with fd.File.open(path, fd.FO_READEX) as src:
            line = src.get_line(lineno - 1)
        traceback.append('  Line: (%d) %r' % (lineno, line.strip()))
        traceback.append('  Variables:')
        for token, where, val in linevars(line.strip(), exc_tb.tb_frame):
            if where is None:
                val = '<undefined>'
            else:
                val = '[%s] %r' % (erepr(getattr(type(val), '__name__', type(val))), val)
            traceback.append('    %r: %s' % (token, val))
        traceback.append('  Code:')
        for ist, lineno, label, op, arg in disassemble(exc_tb.tb_frame.f_code):
            prefix = '>> ' if ist == exc_tb.tb_lasti else '   '
            postfix = ' << %s' % exc_type.__name__ if ist == exc_tb.tb_lasti else ''
            if lineno == exc_tb.tb_lineno:
                if arg is NOVAL:
                    traceback.append('  %s%s%s' % (prefix, op, postfix))
                else:
                    traceback.append('  %s%s %r%s' % (prefix, op, arg, postfix))
        exc_tb = exc_tb.tb_next
        lvl += 1
    traceback.append('[ERROR]')
    traceback.append('%s: %r' % (exc_type.__name__, str(exc_value)))
    traceback.append('=========================================\n')
    return '\n'.join(traceback) 
Example #10
Source File: tb.py    From owasp-pysec with Apache License 2.0 5 votes vote down vote up
def disassemble(co):
    code = co.co_code
    labels = dis.findlabels(code)
    linestarts = dict(dis.findlinestarts(co))
    n = len(code)
    i = 0
    extended_arg = 0
    free = None
    lineno = None
    while i < n:
        c = code[i]
        op = ord(c)
        lineno = linestarts.get(i, lineno)
        is_label = i in labels
        ist = i
        i += 1
        if op >= opcode.HAVE_ARGUMENT:
            oparg = ord(code[i]) + ord(code[i + 1]) * 256 + extended_arg
            extended_arg = 0
            i += 2
            if op == opcode.EXTENDED_ARG:
                extended_arg = oparg * 65536L
            if op in opcode.hasconst:
                arg = co.co_consts[oparg]
            elif op in opcode.hasname:
                arg = co.co_names[oparg]
            elif op in opcode.hasjrel:
                arg = i + oparg
            elif op in opcode.haslocal:
                arg = co.co_varnames[oparg]
            elif op in opcode.hascompare:
                arg = opcode.cmp_op[oparg]
            elif op in opcode.hasfree:
                if free is None:
                    free = co.co_cellvars + co.co_freevars
                arg = free[oparg]
            else:
                arg = NOVAL
        else:
            arg = NOVAL
        yield ist, lineno, is_label, opcode.opname[op], arg 
Example #11
Source File: show_pyc.py    From coveragepy with Apache License 2.0 5 votes vote down vote up
def show_code(code, indent='', number=None):
    label = ""
    if number is not None:
        label = "%d: " % number
    print("%s%scode" % (indent, label))
    indent += '   '
    print("%sname %r" % (indent, code.co_name))
    print("%sargcount %d" % (indent, code.co_argcount))
    print("%snlocals %d" % (indent, code.co_nlocals))
    print("%sstacksize %d" % (indent, code.co_stacksize))
    print("%sflags %04x: %s" % (indent, code.co_flags, flag_words(code.co_flags, CO_FLAGS)))
    show_hex("code", code.co_code, indent=indent)
    dis.disassemble(code)
    print("%sconsts" % indent)
    for i, const in enumerate(code.co_consts):
        if type(const) == types.CodeType:
            show_code(const, indent+'   ', number=i)
        else:
            print("   %s%d: %r" % (indent, i, const))
    print("%snames %r" % (indent, code.co_names))
    print("%svarnames %r" % (indent, code.co_varnames))
    print("%sfreevars %r" % (indent, code.co_freevars))
    print("%scellvars %r" % (indent, code.co_cellvars))
    print("%sfilename %r" % (indent, code.co_filename))
    print("%sfirstlineno %d" % (indent, code.co_firstlineno))
    show_hex("lnotab", code.co_lnotab, indent=indent) 
Example #12
Source File: test_dis.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def jumpy():
    # This won't actually run (but that's OK, we only disassemble it)
    for i in range(10):
        print(i)
        if i < 4:
            continue
        if i > 6:
            break
    else:
        print("I can haz else clause?")
    while i:
        print(i)
        i -= 1
        if i > 6:
            continue
        if i < 4:
            break
    else:
        print("Who let lolcatz into this test suite?")
    try:
        1 / 0
    except ZeroDivisionError:
        print("Here we go, here we go, here we go...")
    else:
        with i as dodgy:
            print("Never reach this")
    finally:
        print("OK, now we're done")

# End fodder for opinfo generation tests 
Example #13
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 #14
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 #15
Source File: test_dis.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def jumpy():
    # This won't actually run (but that's OK, we only disassemble it)
    for i in range(10):
        print(i)
        if i < 4:
            continue
        if i > 6:
            break
    else:
        print("I can haz else clause?")
    while i:
        print(i)
        i -= 1
        if i > 6:
            continue
        if i < 4:
            break
    else:
        print("Who let lolcatz into this test suite?")
    try:
        1 / 0
    except ZeroDivisionError:
        print("Here we go, here we go, here we go...")
    else:
        with i as dodgy:
            print("Never reach this")
    finally:
        print("OK, now we're done")

# End fodder for opinfo generation tests 
Example #16
Source File: test_dis.py    From Fluid-Designer with GNU General Public License v3.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 #17
Source File: test_dis.py    From Fluid-Designer with GNU General Public License v3.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 #18
Source File: show_pyc.py    From coveragepy-bbmirror with Apache License 2.0 5 votes vote down vote up
def show_code(code, indent='', number=None):
    label = ""
    if number is not None:
        label = "%d: " % number
    print("%s%scode" % (indent, label))
    indent += '   '
    print("%sname %r" % (indent, code.co_name))
    print("%sargcount %d" % (indent, code.co_argcount))
    print("%snlocals %d" % (indent, code.co_nlocals))
    print("%sstacksize %d" % (indent, code.co_stacksize))
    print("%sflags %04x: %s" % (indent, code.co_flags, flag_words(code.co_flags, CO_FLAGS)))
    show_hex("code", code.co_code, indent=indent)
    dis.disassemble(code)
    print("%sconsts" % indent)
    for i, const in enumerate(code.co_consts):
        if type(const) == types.CodeType:
            show_code(const, indent+'   ', number=i)
        else:
            print("   %s%d: %r" % (indent, i, const))
    print("%snames %r" % (indent, code.co_names))
    print("%svarnames %r" % (indent, code.co_varnames))
    print("%sfreevars %r" % (indent, code.co_freevars))
    print("%scellvars %r" % (indent, code.co_cellvars))
    print("%sfilename %r" % (indent, code.co_filename))
    print("%sfirstlineno %d" % (indent, code.co_firstlineno))
    show_hex("lnotab", code.co_lnotab, indent=indent) 
Example #19
Source File: debug.py    From python-devtools with MIT License 4 votes vote down vote up
def _statement_range(call_frame: 'FrameType', func_name: str) -> 'Tuple[int, int]':  # noqa: C901
        """
        Try to find the start and end of a frame statement.
        """
        import dis

        # dis.disassemble(call_frame.f_code, call_frame.f_lasti)
        # pprint([i for i in dis.get_instructions(call_frame.f_code)])

        instructions = iter(dis.get_instructions(call_frame.f_code))
        first_line = None
        last_line = None

        for instr in instructions:  # pragma: no branch
            if instr.starts_line:
                if instr.opname in {'LOAD_GLOBAL', 'LOAD_NAME'} and instr.argval == func_name:
                    first_line = instr.starts_line
                elif instr.opname == 'LOAD_GLOBAL' and instr.argval == 'debug':
                    if next(instructions).argval == func_name:
                        first_line = instr.starts_line
            if instr.offset == call_frame.f_lasti:
                break

        if first_line is None:
            raise IntrospectionError('error parsing code, unable to find "{}" function statement'.format(func_name))

        for instr in instructions:
            if instr.starts_line:
                last_line = instr.starts_line - 1
                break

        if last_line is None:
            if sys.version_info >= (3, 8):
                # absolutely no reliable way of getting the last line of the statement, complete hack is to
                # get the last line of the last statement of the whole code block and go from there
                # this assumes (perhaps wrongly?) that the reason we couldn't find last_line is that the statement
                # in question was the last of the block
                last_line = max(i.starts_line for i in dis.get_instructions(call_frame.f_code) if i.starts_line)
            else:
                # in older version of python f_lineno is the end of the statement, not the beginning
                # so this is a reasonable guess
                last_line = call_frame.f_lineno

        return first_line, last_line