Example #1
0
def python_segfault(self):
    import time
    time.sleep(0.5)
    from types import CodeType as code
    #Guaranteed segfault https://wiki.python.org/moin/CrashingPython
    exec code(0, 5, 8, 0, "hello moshe", (), (), (), "", "", 0, "")
    return -111
Example #2
0
def python_segfault(self):
  import time
  time.sleep(0.5)
  from types import CodeType as code
  #Guaranteed segfault https://wiki.python.org/moin/CrashingPython
  exec code(0, 5, 8, 0, "hello moshe", (), (), (), "", "", 0, "")
  return -111
Example #3
0
def recompile(source, filename, mode, flags=0, firstlineno=1, privateprefix=None):
    """ recompile output of uncompile back to a code object. source may also be preparsed AST """
    if isinstance(source, ast.AST):
        a = source
    else:
        a = parse_snippet(source, filename, mode, flags, firstlineno)
    node = a.body[0]
    if not isinstance(node, ast.FunctionDef):
        raise Error('Expecting function AST node')

    c0 = compile(a, filename, mode, flags, True)

    # This code object defines the function. Find the function's actual body code:
    for c in c0.co_consts:
        if not isinstance(c, code):
            continue
        if c.co_name == node.name and c.co_firstlineno == node.lineno:
            break
    else:
        raise Error('Function body code not found')

    # Re-mangle private names:
    if privateprefix is not None:

        def fixnames(names):
            isprivate = re.compile('^__.*(?<!__)$').match
            return tuple(privateprefix + name if isprivate(name) else name for name in names)

        c = code(c.co_argcount, c.co_nlocals, c.co_stacksize, c.co_flags, c.co_code, c.co_consts,
                fixnames(c.co_names), fixnames(c.co_varnames), c.co_filename, c.co_name,
                c.co_firstlineno, c.co_lnotab, c.co_freevars, c.co_cellvars)
    return c
Example #4
0
def copycode(template, changes):
    names = [
        "argcount", "nlocals", "stacksize", "flags", "code", "consts", "names",
        "varnames", "filename", "name", "firstlineno", "lnotab", "freevars",
        "cellvars"
    ]
    if hasattr(code, "co_kwonlyargcount"):
        names.insert(1, "kwonlyargcount")
    values = [
        changes.get(name, getattr(template, "co_" + name)) for name in names
    ]
    return code(*values)
def copycode(template, changes):
    names = [
        "argcount", "nlocals", "stacksize", "flags", "code", "consts",
        "names", "varnames", "filename", "name", "firstlineno", "lnotab",
        "freevars", "cellvars"
    ]
    if str is not bytes:
        names.insert(1, "kwonlyargcount")
    values = [
        changes.get(name, getattr(template, "co_" + name))
        for name in names
    ]
    return code(*values)
Example #6
0
def recompile(source,
              filename,
              mode,
              flags=0,
              firstlineno=1,
              privateprefix=None):
    """Recompile output of uncompile back to a code object. source may also be preparsed AST."""
    if isinstance(source, ast.AST):
        a = source
    else:
        a = parse_snippet(source, filename, mode, flags, firstlineno)
    node = a.body[0]
    if not isinstance(node, ast.FunctionDef):
        raise Error("Expecting function AST node")

    c0 = compile(a, filename, mode, flags, True)

    # This code object defines the function. Find the function's actual body code:
    for c in c0.co_consts:
        if not isinstance(c, code):
            continue
        if c.co_name == node.name and c.co_firstlineno == node.lineno:
            break
    else:
        raise Error("Function body code not found")

    # Re-mangle private names:
    if privateprefix is not None:

        def fixnames(names):
            isprivate = re.compile("^__.*(?<!__)$").match
            return tuple(privateprefix + name if isprivate(name) else name
                         for name in names)

        c = code(
            c.co_argcount,  # pylint: disable=undefined-loop-variable
            c.co_nlocals,  # pylint: disable=undefined-loop-variable
            c.co_stacksize,  # pylint: disable=undefined-loop-variable
            c.co_flags,  # pylint: disable=undefined-loop-variable
            c.co_code,  # pylint: disable=undefined-loop-variable
            c.co_consts,  # pylint: disable=undefined-loop-variable
            fixnames(c.co_names),  # pylint: disable=undefined-loop-variable
            fixnames(c.co_varnames),  # pylint: disable=undefined-loop-variable
            c.co_filename,  # pylint: disable=undefined-loop-variable
            c.co_name,  # pylint: disable=undefined-loop-variable
            c.co_firstlineno,  # pylint: disable=undefined-loop-variable
            c.co_lnotab,  # pylint: disable=undefined-loop-variable
            c.co_freevars,  # pylint: disable=undefined-loop-variable
            c.co_cellvars,  # pylint: disable=undefined-loop-variable
        )
    return c
Example #7
0
def _load_function(pickled_func, globals):
    """recreates a serialized function"""
    code_info, func_info, doc = pickle.loads(pickled_func)
    func = function(code(*code_info), globals, *func_info)
    func.func_doc = doc
    return func
from random import random, getrandbits
from types import CodeType as code

import faulthandler
faulthandler.enable()

print "I'll exhibit random runtime failures..."
n = 1
while 0 < n:
    print "\r" + str(n)
    if random() < 0.001:
	# Generate some non-functioning code.
        exec code(0, 0, 0, 0, "hello thw", (), (), (), "", "", 0, "") 
        n = -1000
    n += 1

Example #9
0
def write_code(obj, env=None, p=None):
    tmp = analyze(obj, env, p)
    if not tmp:
        return False
    argcount, nlocals, flags, constants, names, varnames, filename, name, firstlineno, varargs = tmp
    if None in constants:
        constants.remove(None)
    stackptr = StackPointer()
    constants=(None,lookup_value,isaProcedure,scheme.processer.processer)+tuple(constants)
    names=("pushStack",)+tuple(names)
    varnames=list(varnames)
    c = iter(obj.ast[1:])
    bytecode = Bytecode(lineno=obj.lineno or 0)
    loader = Loader(constants, varnames, names, obj.env, bytecode, stackptr)
    def write_nested_code(statement):
        if not isinstance(statement, list):
            if isinstance(statement, Symbol):
                bytecode.nextLine(statement.line)
            stackptr + 1
            loader.loadItem(statement)
            return True
        func = statement[0]
        while isinstance(func, Symbol):
            bytecode.nextLine(func.line)
            if func.isBound(obj.env):
                func = func.toObject(obj.env)
            else:
                break
        if func in basic_ops.keys():
            isp = stackptr.ptr
            for l in statement[1:]:
                if isinstance(l, list):
                    if not write_nested_code(l):
                        return False
                    continue
                stackptr + 1
                loader.loadItem(l)
            while stackptr > isp + 1:
                stackptr - 1
                bytecode.append(basic_ops[func])
            return True
        elif func in compare_ops:
            isp = stackptr.ptr
            istatement = iter(statement[1:])
            lidx = labelidx.next()
            for l in istatement:
                if isinstance(l, list):
                    if not write_nested_code(l):
                        return False
                else:
                    stackptr + 1
                    loader.loadItem(l)
                if stackptr > isp + 1:
                    stackptr + 1
                    if istatement.__length_hint__():
                        bytecode.append(DUP_TOP)
                        bytecode.append(ROT_THREE)
                    bytecode.append(COMPARE_OP)
                    stackptr - 1
                    bytecode.append(compare_ops.index(func))
                    bytecode.append(0)
                    if istatement.__length_hint__():
                        bytecode.append(JUMP_IF_FALSE_OR_POP)
                        bytecode.append(goto('false%i'%lidx))
                        stackptr - 1
                    else:
                        bytecode.append(JUMP_ABSOLUTE)
                        bytecode.append(goto('false%i'%lidx))
            bytecode.append(label('false%i'%lidx))
            bytecode.append(ROT_TWO)
            bytecode.append(POP_TOP)
            stackptr - 1
            bytecode.append(label('false%i'%lidx))
            return True
        elif isinstance(func, (BuiltinFunctionType, function, type)):
            isp = stackptr.ptr
            istatement = iter(statement[1:])
            loader.loadItem(statement[0])
            for l in statement[1:]:
                if isinstance(l, list):
                    if not write_nested_code(l):
                        return False
                    continue
                stackptr + 1
                loader.loadItem(l)
            bytecode.add(CALL_FUNCTION, len(statement[1:]), 0)
            return True
        elif isinstance(func, scheme.define.define):
            var = statement[1]
            if isinstance(var, list):
                return False
            val = statement[2]
            if isinstance(val, list):
                if not write_nested_code(val):
                    return False
            else:
                loader.loadItem(val)
                stackptr +1
            bytecode.add(DUP_TOP)
            bytecode.add(DUP_TOP)
            loader.storeItem(var)
            loader.loadItem(obj.env)
            loader.loadExtraConstant(var)
            bytecode.add(ROT_THREE,ROT_THREE,ROT_TWO)
            bytecode.add(STORE_MAP)
            bytecode.add(POP_TOP)
            return True
        elif isinstance(func, scheme.IF.IF):
            lidx = labelidx.next()
            if not write_nested_code(statement[1]):
                return False
            bytecode.add(JUMP_IF_FALSE_OR_POP, goto('iffalse%i'%lidx))
            if not write_nested_code(statement[2]):
                return False
            bytecode.add(JUMP_ABSOLUTE, goto('end%i'%lidx))
            bytecode.add(label('iffalse%i'%lidx))
            if len(statement)==4:
                bytecode.add(POP_TOP)
                if not write_nested_code(statement[3]):
                    return False
            bytecode.add(label('end%i'%lidx))
            return True
        elif isinstance(func, scheme.begin.begin):
            c = iter(statement[1:])
            isp = stackptr.ptr
            for statement in c:
                while stackptr > isp:
                    bytecode.append(POP_TOP)
                    stackptr-1
                if not isinstance(statement, list):
                    if isinstance(statement, Symbol):
                        bytecode.nextLine(statement.line)
                    stackptr + 1
                    loader.loadItem(statement)
                    if c.__length_hint__() > 0:
                        bytecode.append(POP_TOP)
                        stackptr - 1
                    continue
                if not write_nested_code(statement):
                    return False
            return True
        elif isaProcedure(func):
            ls = len(statement)-1
            loader.loadItem(func)
            if func is not obj:
                loader.loadItem(scheme.processer.processer)
                bytecode.add(DUP_TOP)
                bytecode.add(LOAD_ATTR,names.index("pushStack")%256,names.index("pushStack")//256)
                loader.loadItem([None])
                bytecode.add(CALL_FUNCTION,1,0)
                bytecode.add(POP_TOP)
            for arg in statement[1:]:
                if not write_nested_code(arg):
                    return False
            if func is not obj:
                bytecode.add(BUILD_LIST, ls%256,ls//256)
                bytecode.add(CALL_FUNCTION, 2, 0)
            else:
                bytecode.add(CALL_FUNCTION, ls, 0)
            stackptr-(ls-1)
            return True
        elif isinstance(func, Symbol):
            #not currently resolvable, so we calculate it's value at runtime.  If it's a Procedure or special form, we'll apply it.  Only use these if unstable optimizations enabled
            gidx=labelidx.next()
            if unstable_enabled:
                ls = len(statement)-1
                loader.loadItem(isaProcedure)
                stackptr+1
                loader.loadItem(func)
                stackptr+1
                bytecode.add(DUP_TOP,ROT_THREE,CALL_FUNCTION,1,0)
                bytecode.add(POP_JUMP_IF_TRUE)
                bytecode.add(goto("applyProcedure%i"%gidx))
                #it's a function
                for arg in statement[1:]:
                    if not write_nested_code(arg):
                        return False
                bytecode.add(CALL_FUNCTION, ls, 0)
                stackptr-(ls-1)
                bytecode.add(JUMP_ABSOLUTE, goto("end%i"%gidx))
                bytecode.add(label("applyProcedure%i"%gidx))
                loader.loadItem(scheme.processer.processer)
                for arg in statement[1:]:
                    if not write_nested_code(arg):
                        return False
                bytecode.add(BUILD_LIST,ls%256,ls//256)
                stackptr-(ls-1)
                bytecode.add(CALL_FUNCTION,2,0)
                stackptr-3
                bytecode.add(label('end%i'%gidx))
                
                
                return True
            else:
                return False
        elif isinstance(func, list):
            if not write_nested_code(func):
                return False
            for arg in statement[1:]:
                if not write_nested_code(arg):
                    return False
            bytecode.add(CALL_FUNCTION, len(statement)-1, 0)
            stackptr - (len(statement)-2)
            return True
        elif isinstance(func, scheme.Lambda.Lambda):
            if unstable_enabled and lambdas_enabled:
                p = scheme.processer.processer
                p.pushStackN()
                p.cenv=Environment(p.cenv)
                print 470, 'statically compiling and linking lambda'
                f = func(p, statement[1:]).toObject({})
                try:
                    if isinstance(f, SimpleProcedure):
                        f = makeFunction(f)
                finally:
                    p.popStackN()
                loader.loadExtraConstant(f)
                return True
            return False
        else:
            print type(func)
            return False
    if varargs:
        for vararg in varargs:
            loader.loadItem('list-type')
            loader.loadItem(vararg)
            bytecode.append(CALL_FUNCTION)
            bytecode.append(1)
            bytecode.append(0)
            loader.storeItem(vararg)
    for statement in c:
        while stackptr > 0:
            bytecode.append(POP_TOP)
            stackptr-=1
        if not isinstance(statement, list):
            if isinstance(statement, Symbol):
                bytecode.nextLine(statement.line)
            stackptr + 1
            loader.loadItem(statement)
            if c.__length_hint__() > 0:
                bytecode.append(POP_TOP)
                stackptr -= 1
            continue
        if not write_nested_code(statement):
            return False
    if not bytecode:
        loader.loadItem(None)
    bytecode.append(RETURN_VALUE)
    c = code(argcount, nlocals, stackptr.maxptr, flags, bytecode.flatten(), constants+tuple(loader.nonlocals), tuple(str(i) for i in names), tuple(str(i) for i in varnames), filename, name, firstlineno, bytecode.get_lnotab())
    if scheme.debug.debug_settings['jit']:
        print stackptr
    return c
from random import random, getrandbits
from types import CodeType as code

import faulthandler
faulthandler.enable()

print "I'll exhibit random runtime failures..."
n = 1
while 0 < n:
    print "\r" + str(n)
    if random() < 0.001:
        # Generate some non-functioning code.
        exec code(0, 0, 0, 0, "hello thw", (), (), (), "", "", 0, "")
        n = -1000
    n += 1