Ejemplo n.º 1
0
    def disassembleSource(self):
        import dis
        try:
            code = compile(self.data, self.filename, 'exec')
        except:
            oldOut = sys.stdout
            sys.stdout = Utils.PseudoFileOutStore()
            try:
                print _(
                    "''' Code does not compile\n\n    Disassembly of Traceback:\n'''"
                )
                try:
                    dis.distb(sys.exc_info()[2])
                except:
                    print _("''' Could not disassemble traceback '''\n")
                return sys.stdout.read()
            finally:
                sys.stdout = oldOut

        oldOut = sys.stdout
        sys.stdout = Utils.PseudoFileOutStore()
        try:
            try:
                dis.disco(code)
            except:
                raise
            return sys.stdout.read()
        finally:
            sys.stdout = oldOut

        return 'Invisible code'
    def disassembleSource(self):
        import dis
        try:
            code = compile(self.data, self.filename, 'exec')
        except:
            oldOut = sys.stdout
            sys.stdout = Utils.PseudoFileOutStore()
            try:
                print _("''' Code does not compile\n\n    Disassembly of Traceback:\n'''")
                try:
                    dis.distb(sys.exc_info()[2])
                except:
                    print _("''' Could not disassemble traceback '''\n")
                return sys.stdout.read()
            finally:
                sys.stdout = oldOut

        oldOut = sys.stdout
        sys.stdout = Utils.PseudoFileOutStore()
        try:
            try:
                dis.disco(code)
            except:
                raise
            return sys.stdout.read()
        finally:
            sys.stdout = oldOut

        return 'Invisible code'
Ejemplo n.º 3
0
def test_code_unoptimized():
    code = get_code()
    stream = io.StringIO()
    dis.disco(code, file=stream)
    stream.seek(0)
    buf = stream.read()
    assert "0 LOAD_CONST               1 (1)" in buf
    assert "3 LOAD_CONST               2 (2)" in buf
Ejemplo n.º 4
0
def dis(c):
    if type(c) == types.StringType:
	c = compile(c,'hacking','exec')
    elif type(c) == types.FunctionType:
	c = c.func_code
    elif type(c) == types.MethodType or type(c) == types.UnboundMethodType:
	c = c.im_func.func_code
    import dis
    dis.disco(c)
Ejemplo n.º 5
0
def dis(c):
    """ dis(c) -- disassemble c; can be a code-string, -object a function
        or a method
    """
    if type(c) == types.StringType:
        c = compile(c, 'hacking', 'exec')
    elif type(c) == types.FunctionType:
        c = c.func_code
    elif type(c) == types.MethodType or type(c) == types.UnboundMethodType:
        c = c.im_func.func_code
    import dis
    dis.disco(c)
Ejemplo n.º 6
0
def dis(c):

    """ dis(c) -- disassemble c; can be a code-string, -object a function
        or a method
    """
    if type(c) == types.StringType:
        c = compile(c,'hacking','exec')
    elif type(c) == types.FunctionType:
        c = c.func_code
    elif type(c) == types.MethodType or type(c) == types.UnboundMethodType:
        c = c.im_func.func_code
    import dis
    dis.disco(c)
Ejemplo n.º 7
0
def my_trace(frame, event, args):
    frame.f_trace_opcodes = True
    stack = traceback.extract_stack(frame)
    pad = "   " * len(stack) + "|"
    if event == 'opcode':
        with io.StringIO() as out:
            dis.disco(frame.f_code, frame.f_lasti, file=out)
            lines = out.getvalue().split('\\n')
            [print(f"{pad}{l}") for l in lines]
    elif event == 'call':
        print(f"{pad}Calling {frame.f_code}")
    elif event == 'return':
        print(f"{pad}Returning {args}")
    elif event == 'line':
        print(f"{pad}Changing line to {frame.f_lineno}")
    else:
        print(f"{pad}{frame} ({event} - {args})")
    print(f"{pad}----------------------------------")
    return my_trace
Ejemplo n.º 8
0
	def _get_data(self):
		count = 0
		frame = inspect.currentframe().f_back
		print '#', frame.f_code
		dis.disco(frame.f_code, frame.f_lasti)
		last_op = None
		try:
			co = frame.f_code
			code = co.co_code
			i = 0
			n = min(len(code), frame.f_lasti + 1)
			extended_arg = 0
			while i < n:
				op = ord(code[i])
				print opcode.opname[op].ljust(20),
				i = i+1
				if op >= opcode.HAVE_ARGUMENT:
					oparg = ord(code[i]) + ord(code[i+1])*256 + extended_arg
					i = i+2
					if op == opcode.EXTENDED_ARG:
						extended_arg = oparg*65536L
					if op in opcode.hasname:
						name = co.co_names[oparg]
						print name,
						if op == LOAD_ATTR and name == 'data':
							count += 1
							if i >= frame.f_lasti and count > infinity:
								print '#', count
								return self._infinidata
						elif op == opcode.opmap['LOAD_NAME']:
							count = 0
				if (
					op == opcode.opmap['LOAD_FAST']
					and last_op != opcode.opmap['STORE_FAST']
				):
					count = 0
				last_op = op
				print '#', count
		finally:
			del frame
			del co
			del code
		return self
Ejemplo n.º 9
0
 def _get_data(self):
     count = 0
     frame = inspect.currentframe().f_back
     print '#', frame.f_code
     dis.disco(frame.f_code, frame.f_lasti)
     last_op = None
     try:
         co = frame.f_code
         code = co.co_code
         i = 0
         n = min(len(code), frame.f_lasti + 1)
         extended_arg = 0
         while i < n:
             op = ord(code[i])
             print opcode.opname[op].ljust(20),
             i = i + 1
             if op >= opcode.HAVE_ARGUMENT:
                 oparg = ord(
                     code[i]) + ord(code[i + 1]) * 256 + extended_arg
                 i = i + 2
                 if op == opcode.EXTENDED_ARG:
                     extended_arg = oparg * 65536L
                 if op in opcode.hasname:
                     name = co.co_names[oparg]
                     print name,
                     if op == LOAD_ATTR and name == 'data':
                         count += 1
                         if i >= frame.f_lasti and count > infinity:
                             print '#', count
                             return self._infinidata
                     elif op == opcode.opmap['LOAD_NAME']:
                         count = 0
             if (op == opcode.opmap['LOAD_FAST']
                     and last_op != opcode.opmap['STORE_FAST']):
                 count = 0
             last_op = op
             print '#', count
     finally:
         del frame
         del co
         del code
     return self
Ejemplo n.º 10
0
def mm_debug(*args):
    # replace standard stdout with a StringIO object
    buf = StringIO.StringIO()
    old_stdout = sys.stdout
    sys.stdout = buf

    # call dis.disco to get bytecodes
    f = sys._getframe(1)
    dis.disco(f.f_code, f.f_lasti)

    # restore standard stdout
    sys.stdout = old_stdout

    # process bytecode
    var_names = __parse_bytecodes(buf.getvalue())
    buf.close()

    #print var name and var value
    for i, var_name in enumerate(var_names):
        print '%s = %s' % (var_name, args[i])
Ejemplo n.º 11
0
def trace(
    frame: Frame,
    event: Event,
    arg: Union[None, Value, Tuple[Type[BaseException], BaseException,
                                  Traceback]],
):
    if verbose:
        header()
        dis.disco(frame.f_code, frame.f_lasti)
    if event == "call":
        trace_call(frame)
    elif event == "line":
        trace_line(frame)
    elif event == "return":
        arg = cast(Value, arg)
        trace_return(frame, arg)
    elif event == "exception":
        arg = cast(Tuple[Type[BaseException], BaseException, Traceback], arg)
        trace_exception(frame, arg)
    else:
        raise Exception(f"Unhandled event type {event!r}")
    return trace
Ejemplo n.º 12
0
        return update_wrapper(self, func)
        
lulu = 101
nlv = nonlocal_var()
bnlv = Block(nlv)
print bnlv
print bnlv()

import dis
print '----'
def lu(f):
    lulu = 3
    f()
    print lulu
print lu(bnlv)
dis.disco(bnlv.code)
dis.dis(lu)

# <codecell>

from opcode import *

def find_or_append(lst, val):
    try:
        return lst.index(val)
    except ValueError:
        lst.append(val)
        return len(lst)-1

def make_block_code(co, co_name=None):
    from types import CodeType
Ejemplo n.º 13
0
# -*- coding: utf-8 -*-
"""
just mucking about with dis module - newly discovered.
"""

import dis

counter = 0
li = [0,1,2,3,4,5,6,7,8,9,None]


def returnValue():
    global counter
    counter += 1
    return li[counter]

def useForLoop():
    for i in iter(returnValue, None):
        print i
        
def useWhileLoop():
    myCounter = 0    
    while 1:
        if li[myCounter] is None:
            break

print "====== with For ====="
dis.disco(useForLoop.__code__)
print "===== with While ====="
dis.disco(useWhileLoop.__code__)
Ejemplo n.º 14
0
# This will disamble a certain function and let you know how it works in C level.
import dis


def func():
    for i in xrange(100000):
        print i


dis.disco(func.__code__)
Ejemplo n.º 15
0
import dis


def simple():
    print('Hello')
    yield 42
    print('Good bye')
    yield 43


if __name__ == '__main__':
    print('Newly created generator')
    g = simple()

    print(f'Instruction pointer: {g.gi_frame.f_lasti}')
    dis.disco(g.gi_code, g.gi_frame.f_lasti)

    print('First next() call')
    next(g)

    print(f'Instruction pointer: {g.gi_frame.f_lasti}')
    dis.disco(g.gi_code, g.gi_frame.f_lasti)

    print('Second next() call')
    next(g)

    print(f'Instruction pointer: {g.gi_frame.f_lasti}')
    dis.disco(g.gi_code, g.gi_frame.f_lasti)

    try:
        next(g)
Ejemplo n.º 16
0
 def update_event(self, inp=-1):
     self.set_output_val(0, dis.disco(self.input(0), self.input(1)))