Exemplo n.º 1
0
def define_sizeof_modifier_type(t):
    # setup the toplevel call
    if t.get_typename():
        argument_ast = t.get_reference()("storage")
    else:
        argument_ast = t.define("storage")
    prefix = "fffc_get_sizeof_"
    desired_name = CGenerator().visit(argument_ast)
    suffix = encode_hash(desired_name)
    function_name = prefix + suffix

    # build the underlying function call
    underlying_call = get_sizeof_pointer_to_type(t.underlying_type,
                                                 c_ast.ID("storage"))

    # build this just as above, except with the call in place of the sizeof
    storage_tdecl = c_ast.Decl("storage", [], [], [],
                               c_ast.PtrDecl([], argument_ast), None, None)
    func_tdecl = c_ast.TypeDecl(
        function_name, [], c_ast.IdentifierType(["long", "long", "unsigned"]))
    funcdecl = c_ast.FuncDecl(c_ast.ParamList([storage_tdecl]), func_tdecl)
    funcdef = c_ast.FuncDef(
        c_ast.Decl(function_name, [], [], [], funcdecl, None, None),
        None,
        c_ast.Compound([c_ast.Return(underlying_call)]),
    )
    comment = "/* " + desired_name + "*/\n"
    kr_funcdecl = c_ast.FuncDecl(c_ast.ParamList([]), func_tdecl)
    return comment, kr_funcdecl, funcdef
Exemplo n.º 2
0
    def createMain(self):
        #Main Function
        #Declaration
        z1 = c_ast.TypeDecl('args',[],c_ast.IdentifierType(['int']))
        args = c_ast.Decl('args',[],[],[],z1,None,None)
        z2= c_ast.PtrDecl([],c_ast.TypeDecl('argv',[],c_ast.IdentifierType(['char'])))
        z3=c_ast.ArrayDecl(z2,None,[])
        argv = c_ast.Decl('argv',[],[],[],z3,None,None)
        params=c_ast.ParamList([args,argv])
        mainDec=c_ast.FuncDecl(params,c_ast.TypeDecl('main',[],c_ast.IdentifierType(['int'])))
#        insertTest(functionName,varVals,varTypes)
        #Body
        ##Signal
        sigalrm=c_ast.ID(name="14")
        funcCast=c_ast.TypeDecl(declname = None,quals=[],type=c_ast.IdentifierType(['void']))
        paramCast=c_ast.ParamList([c_ast.Typename(name=None,quals=[],type=c_ast.TypeDecl(declname = None,quals=[],type=c_ast.IdentifierType(['int'])))])
        typeFunc=c_ast.PtrDecl(type=c_ast.FuncDecl(paramCast,funcCast),quals=[])        
        kchild=c_ast.Cast(to_type=c_ast.Typename(name=None, quals=[],type=typeFunc),expr=c_ast.ID(name="kill_child"))
        expressList = [sigalrm,kchild]
        signalStmt=c_ast.FuncCall(c_ast.ID(name="signal"),c_ast.ExprList(expressList))

        ##Return
        returnStmt=c_ast.Return(c_ast.Constant(type="int",value="0"))
        comp=c_ast.Compound([signalStmt,returnStmt])
        return c_ast.FuncDef(mainDec,None,comp)
Exemplo n.º 3
0
def make_mutator_decl_from_arg_type(arg_type,
                                    generator=CGenerator(),
                                    seen={},
                                    point=True,
                                    change_name=False):
    # memoize
    if arg_type in seen:
        return seen[arg_type]
    mut_name = "fffc_mutator_for_target_type"
    # change the type declname
    if change_name:
        change_declname(arg_type, "storage")
    # first, wrap the type in a pointer to match the necessary mutator semantics
    if point:
        arg_type_ptr = c_ast.PtrDecl([], arg_type)
    else:
        arg_type_ptr = arg_type
    # next, wrap that in a decl with the right name
    arg_decl = c_ast.ParamList(
        [c_ast.Decl("storage", [], [], [], arg_type_ptr, None, None)])
    # next, generate the desired decl
    ret_type = c_ast.IdentifierType(["int"])
    ret_decl = c_ast.TypeDecl(mut_name, [], ret_type)
    desired_decl = c_ast.FuncDecl(arg_decl, ret_decl)
    # now build the mangled name
    desired_name = generator.visit(desired_decl)
    suffix = encode_hash(desired_name)
    actual_name = "_Z_fffc_mutator_" + suffix
    desired_decl.type.declname = actual_name
    # build the output
    out = c_ast.Decl(actual_name, [], [], [], desired_decl, None, None)
    # save the result
    seen[arg_type] = (desired_name, out)
    # and go home
    return desired_name, out
Exemplo n.º 4
0
def _build_handle_function(functions):
    """ Wraps the switch statement in a function definition

    """
    case_statement = _build_case(functions)
    available_check = c_ast.If(
        c_ast.BinaryOp(
            '<', c_ast.FuncCall(
                c_ast.ID('mailbox_available'),
                c_ast.ExprList([c_ast.Constant('int', '2')])
            ),
            c_ast.Constant('int', '4')
        ),
        c_ast.Return(None),
        None
    )
    handle_decl = c_ast.FuncDecl(
        None, c_ast.TypeDecl('_handle_events', [],
                             c_ast.IdentifierType(['void'])),
    )
    command_decl = c_ast.Decl('command', [], [], [],
                              c_ast.TypeDecl('command', [],
                                             c_ast.IdentifierType(['int'])),
                              [], [])
    command_read = _generate_read('command')
    body = c_ast.Compound([available_check,
                           command_decl,
                           command_read,
                           case_statement])
    return c_ast.FuncDef(handle_decl, [], body)
Exemplo n.º 5
0
def define_sizeof_type_from_ast(argument_ast):
    prefix = "fffc_get_sizeof_"
    desired_name = CGenerator().visit(argument_ast)
    suffix = encode_hash(desired_name)
    function_name = prefix + suffix
    storage_tdecl = c_ast.Decl("storage", [], [], [],
                               c_ast.PtrDecl([], argument_ast), None, None)
    func_tdecl = c_ast.TypeDecl(
        function_name, [], c_ast.IdentifierType(["long", "long", "unsigned"]))
    funcdecl = c_ast.FuncDecl(c_ast.ParamList([storage_tdecl]), func_tdecl)
    funcdef = c_ast.FuncDef(
        c_ast.Decl(function_name, [], [], [], funcdecl, None, None),
        None,
        c_ast.Compound([
            c_ast.Return(
                c_ast.UnaryOp("sizeof", c_ast.UnaryOp("*",
                                                      c_ast.ID("storage"))))
        ]),
    )
    comment = "/* " + desired_name + "*/\n"
    kr_funcdecl = c_ast.FuncDecl(c_ast.ParamList([]), func_tdecl)
    return comment, kr_funcdecl, funcdef
Exemplo n.º 6
0
def MakePrintfStyleDecl(name: str, type_names: List[str], is_pointer=False):
    parameter_fd = c_ast.Decl("fd", [], [], [],
                              MakeSimpleTypeDecl("fd", ["int"]), None, None)

    parameter_value = c_ast.Decl("value", [], [], [],
                                 MakeSimpleTypeDecl("value", type_names), None,
                                 None)
    if is_pointer:
        parameter_value.type = c_ast.PtrDecl([], parameter_value.type)

    fun_result = MakeSimpleTypeDecl(name, ["int"])
    return c_ast.Decl(
        name, [], [], [],
        c_ast.FuncDecl(c_ast.ParamList([parameter_fd, parameter_value]),
                       fun_result), None, None)
Exemplo n.º 7
0
def createTest(block,functionName,varVals,varTypes):
   #Main Function
   #Declaration
   z1 = c_ast.TypeDecl('args',[],c_ast.IdentifierType(['int']))
   args = c_ast.Decl('args',[],[],[],z1,None,None)
   z2= c_ast.PtrDecl([],c_ast.TypeDecl('argv',[],c_ast.IdentifierType(['char'])))
   z3=c_ast.ArrayDecl(z2,None,[])
   argv = c_ast.Decl('argv',[],[],[],z3,None,None)
   params=c_ast.ParamList([args,argv])
   mainDec=c_ast.FuncDecl(params,c_ast.TypeDecl('main',[],c_ast.IdentifierType(['int'])))
   insertTest(functionName,varVals,varTypes)
   #Body
   returnStmt=c_ast.Return(c_ast.Constant(type="int",value="0"))
   comp=c_ast.Compound([returnStmt])
   main= c_ast.FuncDef(mainDec,None,comp)
   insertTest(main,"func",['1','2'],['int','int'])
Exemplo n.º 8
0
def type_from_global_decl(decl: ca.Decl) -> CType:
    """Get the CType of a global Decl, stripping names of function parameters."""
    tp = decl.type
    if not isinstance(tp, ca.FuncDecl) or not tp.args:
        return tp

    def anonymize_param(param: ca.Decl) -> ca.Typename:
        param = copy.deepcopy(param)
        param.name = None
        set_decl_name(param)
        return ca.Typename(name=None, quals=param.quals, type=param.type)

    new_params: List[Union[ca.Decl, ca.ID, ca.Typename, ca.EllipsisParam]] = [
        anonymize_param(param) if isinstance(param, ca.Decl) else param
        for param in tp.args.params
    ]
    return ca.FuncDecl(args=ca.ParamList(new_params), type=tp.type)
Exemplo n.º 9
0
def make_internal_fn_decl(name):
    '''str -> c_ast'''
    # don't you wish python had a macro system?
    return c_ast.Decl(
        name, [], [], [],
        c_ast.FuncDecl(
            c_ast.ParamList([
                c_ast.Decl(
                    utils.args_tag, [], [], [],
                    c_ast.PtrDecl([],
                                  c_ast.TypeDecl(
                                      utils.args_tag, [],
                                      c_ast.IdentifierType([
                                          '%s%s' %
                                          (utils.decomp_tag, utils.args_tag)
                                      ]))), None, None)
            ]), c_ast.TypeDecl(name, [], c_ast.IdentifierType(['void']))),
        None, None)
Exemplo n.º 10
0
    def create_svcomp_function_declaration(self, name: str):
        """
		Creates a declaration for the given SV comp function name, e.g. "__VERIFIER_nondet_int".
		:param name: The SV comp function name.
		:return: c_ast.Decl
		"""
        return_type = self.get_c_type(name.replace("__VERIFIER_nondet_", ""))
        # Need to handle pointers separately.
        if "*" in return_type:
            return_type.remove("*")
            return_code = c_ast.PtrDecl(
                [],
                c_ast.TypeDecl(name, [],
                               c_ast.IdentifierType(list(return_type))))
        else:
            return_code = c_ast.TypeDecl(name, [],
                                         c_ast.IdentifierType(return_type))
        return c_ast.Decl(name, [], ["extern"], [],
                          c_ast.FuncDecl(None, return_code), None, None)
def addTestFunction(ast, expectedOutput, testFxn, initVars, initList):
    varList = []
    exprList = []
    fxnName = ''
    inFxn = False
    listi = 0
    for i in range(len(initVars)):
        v = initVars[i]
        if inFxn:
            exprList.append(c_ast.Constant('int', initList[listi]))
            listi += 1
            if (')' in v):
                inFxn = False
                newVar = c_ast.FuncCall(c_ast.ID(fxnName), c_ast.ExprList(exprList))
                varList.append(newVar)
                exprList = []
        else:
            if ('(' in v):
                fxnName = v[:v.index('(')]
                if (v[v.index('(')+1] != ')'):
                    inFxn = True
                    exprList.append(c_ast.Constant('int', initList[listi]))
                    listi += 1
                else:
                    newVar = c_ast.FuncCall(c_ast.ID(fxnName), c_ast.ExprList([]))
                    varList.append(newVar)
            else:
                newVar = c_ast.Assignment('=', c_ast.ID(v), c_ast.Constant('int', initList[listi]))
                listi += 1
                varList.append(newVar)
    fxnDecl = c_ast.FuncDecl(None, c_ast.TypeDecl('klee_test_entry', [], c_ast.IdentifierType(['void'])))
    fxnCall = c_ast.FuncCall(c_ast.ID(testFxn), c_ast.ExprList([]))
    binaryOp = c_ast.BinaryOp('==', fxnCall, c_ast.Constant('int', expectedOutput))
    ifFalse = c_ast.Compound([c_ast.FuncCall(c_ast.ID('klee_silent_exit'), c_ast.ExprList([c_ast.Constant('int', '0')]))])
    ifTrue = c_ast.Compound([])
    blockItems = []
    for v in varList:
        blockItems.append(v)
    blockItems.append(c_ast.If(binaryOp, ifTrue, ifFalse))
    fxnBody = c_ast.Compound(blockItems)
    fxnNode = c_ast.FuncDef(fxnDecl, None, fxnBody)
    ast.ext.append(fxnNode)
Exemplo n.º 12
0
def fndecl(name, inargs, outargs, code):
    ptroutargs = [deepcopy(arg) for arg in outargs]
    rename = RenameVisitor("out")
    for arg in ptroutargs:
        rename.visit(arg)
        arg.type = c_ast.PtrDecl([], arg.type)
        arg.init = None

    fdecl = c_ast.FuncDecl(
        c_ast.ParamList(inargs + ptroutargs),
        c_ast.TypeDecl(name, [], c_ast.IdentifierType(['void'])))
    decl = c_ast.Decl(name, [], [], [], fdecl, None, None)
    assign = []
    for ptr, var in zip(ptroutargs, outargs):
        assign.append(
            c_ast.Assignment('=', c_ast.UnaryOp('*', c_ast.ID(ptr.name)),
                             c_ast.ID(var.name)))

    comp = c_ast.Compound(code + assign)
    return c_ast.FuncDef(decl, None, comp)
Exemplo n.º 13
0
    def _get_assume_definition(self):
        param_name = '__cond'
        int_type = a.TypeDecl(param_name, [], a.IdentifierType(['int']))
        param_list = a.ParamList(
            [a.Decl(param_name, [], [], [], int_type, None, None)])
        assume_type = a.TypeDecl('__VERIFIER_assume', [],
                                 a.IdentifierType(['void']))
        assume_func_decl = a.FuncDecl(param_list, assume_type)
        assume_decl = a.Decl('__VERIFIER_assume', list(), list(), list(),
                             assume_func_decl, None, None)

        exit_code = a.ExprList([a.Constant('int', '0')])
        true_branch = a.Compound([a.FuncCall(a.ID('exit'), exit_code)])
        false_branch = None
        if_statement = a.If(a.UnaryOp('!', a.ID(param_name)), true_branch,
                            false_branch)

        return_statement = a.Return(None)

        body_items = [if_statement, return_statement]
        assume_body = a.Compound(body_items)
        return a.FuncDef(assume_decl, None, assume_body)
Exemplo n.º 14
0
def simisrt(ast, isrdict):
    isrnum = len(isrdict)
    identi = c_ast.IdentifierType(['void'])
    fundetyde = c_ast.TypeDecl('simulate', [], identi)
    simdecl = c_ast.Decl('simulate', [], [], [],
                         c_ast.FuncDecl(None, fundetyde), None, None, None)
    simu = c_ast.FuncDef(simdecl, None, c_ast.Compound([]))

    for i in range(0, isrnum):  #isr[0] = &isr_1;
        simassiisr = astAssiIsr(i)
        simu.body.block_items.append(simassiisr)
    for isr in isrdict:  #deferral[0] = &deferral_1;
        if isrdict[isr] == isr:
            simdef = astAssiDef(isr)
            simu.body.block_items.append(simdef)
    #int rand = __VERIFIER_nondet() % N;
    simveri = astVeriNon()
    simu.body.block_items.append(simveri)
    simpri = astAssiPri()
    simu.body.block_items.append(simpri)
    simfuncisr = astFuncIsr()
    simu.body.block_items.append(simfuncisr)
    simu.show()
    ast.ext.append(simu)
Exemplo n.º 15
0
                                 None)
    if is_pointer:
        parameter_value.type = c_ast.PtrDecl([], parameter_value.type)

    fun_result = MakeSimpleTypeDecl(name, ["int"])
    return c_ast.Decl(
        name, [], [], [],
        c_ast.FuncDecl(c_ast.ParamList([parameter_format, parameter_value]),
                       fun_result), None, None)


PUTS = c_ast.Decl(
    "print", [], [], [],
    c_ast.FuncDecl(
        c_ast.ParamList([
            c_ast.Decl("s", [], [], [],
                       c_ast.PtrDecl([], MakeSimpleTypeDecl("s", ["char"])),
                       None, None)
        ]), MakeSimpleTypeDecl("print", ["int"])), None, None)

PRINTF_PROTOTYPES = {
    "printf_u": MakePrintfStyleDecl("printf_u", ["int", "unsigned"]),
    "printf_d": MakePrintfStyleDecl("printf_d", ["int"]),
    "printf_lu": MakePrintfStyleDecl("printf_lu",
                                     ["long", "long", "unsigned"]),
    "printf_ld": MakePrintfStyleDecl("printf_ld", ["long", "long"]),
    "printf_f": MakePrintfStyleDecl("printf_f", ["double"]),
    "printf_c": MakePrintfStyleDecl("printf_c", ["char"]),
    "printf_p": MakePrintfStyleDecl("printf_p", ["void"], True),
    "printf_s": MakePrintfStyleDecl("printf_s", ["char"], True)
}
Exemplo n.º 16
0
    def __init__(self, function, has_implementation, real_variadic_function,
                 generator):
        self.function = function
        self.func_name = function.name
        self.real_variadic_function = real_variadic_function
        self.struct_names = generator.struct_names
        self.struct_typedef_names = generator.struct_typedef_names

        self.wrapped_func = f'__wrap_{self.func_name}'
        self.real_func = f'__real_{self.func_name}'

        self.state_name = f'nala_mock_{self.func_name}'

        self.generator = generator
        self.func_decl = self.function.declaration.type
        self.func_params = self.func_decl.args.params if self.func_decl.args else []
        self.assign_names_to_unnamed_params(self.func_params)
        self.is_variadic_func = False
        self.params = []

        for param in self.func_params:
            if is_ellipsis(param):
                self.is_variadic_func = True
                break

            if param.name is None:
                break

            expanded_param = deepcopy(param)
            expanded_param.type = self.generator.parser.expand_type(
                expanded_param.type)
            self.params.append((param, expanded_param))

        if has_implementation is not None:
            self.has_implementation = has_implementation
        elif self.is_variadic_func:
            if real_variadic_function:
                self.has_implementation = True
            else:
                self.has_implementation = False
        else:
            self.has_implementation = True

        self.params_struct = []

        for param, expanded_param in self.params:
            if is_array(expanded_param.type):
                param = deepcopy(expanded_param)
                param.type = self.convert_array_to_pointer(param.type)
                param = self.rename_param(param, param.name)

            if 'const' in param.type.quals:
                param = deepcopy(param)
                param.type.quals = [
                    qual for qual in param.type.quals if qual != 'const'
                ]

            self.params_struct.append(param)

        self.forward_args = ', '.join(param.name
                                      for param in self.params_struct)

        if self.is_variadic_func:
            self.params_struct.append(
                decl(
                    None,
                    c_ast.PtrDecl([],
                                  c_ast.TypeDecl(
                                      'vafmt_p', ['const'],
                                      c_ast.IdentifierType(['char'])))))
            self.forward_args += ', nala_vl'

        # -Wpedantic warns on empty structs.
        if not self.params_struct:
            self.params_struct = [
                decl(
                    'dummy',
                    c_ast.TypeDecl('dummy', [], c_ast.IdentifierType(['int'])))
            ]

        return_type = self.func_decl.type
        self.return_value = (
            None if isinstance(return_type, c_ast.TypeDecl)
            and isinstance(return_type.type, c_ast.IdentifierType)
            and return_type.type.names[0] == 'void' else 'return_value')

        if self.is_variadic_func:
            self.va_list_start_arg_name = self.func_params[-2].name
        else:
            self.va_list_start_arg_name = None

        self.return_value_decl = decl(
            self.return_value,
            rename_return_type(return_type, self.return_value))
        mock_params = self.create_mock_params()
        self.implementation_decl = function_ptr_decl(
            'implementation', rename_return_type(return_type,
                                                 'implementation'),
            create_implementation_params(self.func_params))
        self.mock_func = self.void_function_decl(f'{self.func_name}_mock',
                                                 mock_params)
        self.mock_once_func = self.int_function_decl(
            f'{self.func_name}_mock_once', mock_params)
        self.set_errno_func = self.void_function_decl(
            f'{self.func_name}_mock_set_errno', [
                decl(
                    'errno_value',
                    c_ast.TypeDecl('errno_value', [],
                                   c_ast.IdentifierType(['int'])),
                )
            ])
        self.callback_decl = function_ptr_decl(
            'callback', void_type('callback'),
            create_implementation_params(self.func_params))
        self.variadic_func_real_wrapper_decl = c_ast.FuncDecl(
            c_ast.ParamList(create_implementation_params(self.func_params)),
            c_ast.TypeDecl(f'{self.func_name}_mock_va_arg_real', [],
                           return_type))
        self.default_variadic_func_real_wrapper_decl = c_ast.FuncDecl(
            c_ast.ParamList(create_implementation_params(self.func_params)),
            c_ast.TypeDecl(f'nala_v{self.func_name}', [], return_type))
        self.real_decl = self.rename_function(self.real_func)
        self.wrapped_decl = self.rename_function(self.wrapped_func)
        self.instance_members = []
        self.set_params = []
        self.char_pointer_params = []
        self.pointer_params = []
        self.non_pointer_params = []
        self.ignore_params = []

        for param, expanded_param in self.params:
            if is_struct_or_union(expanded_param.type):
                continue
            elif is_va_list(expanded_param.type):
                continue

            self.instance_members.append(bool_param(f'ignore_{param.name}_in'))

            if is_pointer_or_array(expanded_param.type):
                if is_char_pointer(expanded_param.type):
                    self.char_pointer_params.append(param)
                    self.ignore_params.append((param.name, True))
                else:
                    self.pointer_params.append(param)
            else:
                self.non_pointer_params.append(param)
                self.ignore_params.append((param.name, False))
                continue

            param_buf = self.rename_param(param, 'buf_p')
            param_actual = self.rename_param(param, 'actual_p')
            param_expected = self.rename_param(param, 'expected_p')
            param_dst = self.rename_param(param, 'dst_p')
            param_src = self.rename_param(param, 'src_p')
            self.instance_members.append(set_member(f'{param.name}_in'))
            self.instance_members.append(
                in_assert_member(param.name, param_actual, param_expected))
            self.instance_members.append(set_member(f'{param.name}_out'))
            self.instance_members.append(
                out_copy_member(param.name, param_dst, param_src))
            self.set_params.append(
                (param, param_buf, param_actual, param_expected, param_dst,
                 param_src, self.find_check_function(param, expanded_param)))
Exemplo n.º 17
0
def function_ptr_decl(name, return_type, parameters):
    return decl(
        name,
        node.PtrDecl([], node.FuncDecl(node.ParamList(parameters),
                                       return_type)))
Exemplo n.º 18
0
 def rename_function(self, name):
     return decl(
         name,
         node.FuncDecl(self.func_decl.args,
                       rename_return_type(self.func_decl.type, name)),
     )
Exemplo n.º 19
0
def function_ptr_decl(name, return_type, parameters):
    return decl(
        name,
        c_ast.PtrDecl([],
                      c_ast.FuncDecl(c_ast.ParamList(parameters),
                                     return_type)))
Exemplo n.º 20
0
    def int_function_decl(self, name, parameters):
        if not parameters:
            parameters = [void_type('')]

        return c_ast.FuncDecl(c_ast.ParamList(parameters), int_type(name))
Exemplo n.º 21
0
 def eliminateParams(self):
     self.params=c_ast.ParamList([])
     mainDec=c_ast.Decl(name='mainFake',quals=[],init=None,bitsize=None,storage=[],funcspec=[],type=c_ast.FuncDecl(self.params,c_ast.TypeDecl('mainFake',[],c_ast.IdentifierType(['int']))))
     self.main = c_ast.FuncDef(mainDec,None,self.main.body)
     for i,func in enumerate(self.ast.ext):
         if(isinstance(func,c_ast.FuncDef)): 
             if func.decl.name == 'main':
                 self.ast.ext[i]=self.main