示例#1
0
    def process_actions(self):
        if ivy_compiler.isolate.get():
            st = ivy_compiler.isolate.get().split('.')[0]
        else:
            st = ''
        st = [st, 'timeout', 'handle', 'recv']
        for name in self.mod.public_actions:
            print >> sys.stderr, "action:\t", name
            if not (ivy_compiler.isolate.get() == None or any(s in name
                                                              for s in st)):
                continue
            action = ia.env_action(name)
            #             print ("action2: ", ia.action_def_to_str(name, action))
            ag = ivy_art.AnalysisGraph()
            pre = itp.State()
            pre.clauses = lut.true_clauses()
            #             print(pre.to_formula())
            with itp.EvalContext(check=False):
                post = ag.execute(action, pre)
            history = ag.get_history(post)
            clauses = lut.and_clauses(history.post)
            f = self.get_formula(clauses)
            conjuncts = clauses.fmlas
            defn = lut.close_epr(lg.And(*conjuncts))
            #             print(defn)
            #             assert(0)

            update = action.update(pre.domain, pre.in_scope)
            sf = self.standardize_action(f, update[0], name)
            self.add_new_constants(sf, 'action')

            actname = "action_" + name
            self.actions.add(actname)
            res = (sf, actname, "action", name)
            self.vmt[actname] = res
示例#2
0
    def process_actions(self):
        for name, action in self.mod.actions.iteritems():
            #             print(type(action))
            #             print ("action2: ", ia.action_def_to_str(name, action))
            ag = ivy_art.AnalysisGraph()
            pre = itp.State()
            pre.clauses = lut.true_clauses()
            #             print(pre.to_formula())
            post = ag.execute(action, pre)
            history = ag.get_history(post)
            clauses = lut.and_clauses(history.post)
            f = self.get_formula(clauses)
            conjuncts = clauses.fmlas
            defn = lut.close_epr(lg.And(*conjuncts))
            #             print(defn)
            #             assert(0)

            update = action.update(pre.domain, pre.in_scope)
            sf = self.standardize_action(f, update[0], name)
            self.add_new_constants(sf)

            actname = "action_" + name
            self.actions.add(actname)
            res = (sf, actname, "action", name)
            self.vmt[actname] = res
示例#3
0
文件: ivy_check.py 项目: xornand/ivy
def main():
    ivy.read_params()
    if len(sys.argv) != 2 or not sys.argv[1].endswith('ivy'):
        usage()
    with im.Module():
        isolate = ivy_compiler.isolate.get()
        ivy.source_file(sys.argv[1],
                        ivy.open_read(sys.argv[1]),
                        create_isolate=False)

        # If user specifies an isolate, check it. Else, if any isolates
        # are specificied in the file, check all, else check globally.

        if isolate != None:
            isolates = [isolate]
        else:
            isolates = sorted(list(im.module.isolates))
            if len(isolates) == 0:
                isolates = [None]

        for isolate in isolates:
            if len(im.module.isolates[isolate].verified()) == 0:
                continue  # skip if nothing to verify
            with im.module.copy():
                ivy_isolate.create_isolate(isolate, ext='ext')
                ag = ivy_art.AnalysisGraph(initializer=ivy_alpha.alpha)
                with utl.ErrorPrinter():
                    with ivy_interp.EvalContext(check=False):
                        ag.execute_action('ext')
                        cex = ag.check_bounded_safety(ag.states[-1])
                        if cex is not None:
                            display_cex("safety failed", cex)
    print "OK"
def check_isolate(n_steps):
    
    step_action = ia.env_action(None)

    conjectures = im.module.conjs
    conj = ilu.and_clauses(*conjectures)

    used_names = frozenset(x.name for x in il.sig.symbols.values())
    def witness(v):
        c = lg.Const('@' + v.name, v.sort)
        assert c.name not in used_names
        return c
    clauses = ilu.dual_clauses(conj, witness)

    ag = art.AnalysisGraph()
    with ag.context as ac:
#                post = ac.new_state(ag.init_cond)
        ag.add_initial_state(ag.init_cond)
        post = ag.states[0]
    if 'initialize' in im.module.actions:
        init_action = im.module.actions['initialize']
        post = ag.execute(init_action, None, None, 'initialize')

    for n in range(n_steps + 1):
        print 'Checking invariants at depth {}...'.format(n)
        res = ivy_trace.check_final_cond(ag,post,clauses,[],True)
        if res is not None:
            print 'BMC with bound {} found a counter-example...'.format(n)
            print
            print res
            exit(0)
        post = ag.execute(step_action)
            
示例#5
0
def isInvInductive(mod):
    # returns the max size of the universe for each sort taken over actions
    checked_actions = get_checked_actions()
    res = lI.Universe({})
    isInvInd = True
    print "\n    The following set of external actions must preserve the invariant:"
    for actname in sorted(checked_actions):
        action = mod.actions[actname]
        print "        {}{}".format(pretty_lineno(action), actname)
        if not opt_summary.get() or opt_learn.get():
            ag = ivy_art.AnalysisGraph()
            pre = itp.State()
            pre.clauses = get_conjs(
                mod)  # comment it to have only action clauses
            # print "<bhavya> pre", type(pre)
            # print "<bhavya> pre.clauses", type(pre.clauses), pre.clauses
            with itp.EvalContext(check=False):  # don't check safety
                post = ag.execute(action, pre, None,
                                  actname)  # action clauses are added
                # print "<bhavya> post clauses", type(post), post.clauses
            dic = check_conjs_in_state(mod, ag, post, indent=12)
            # print "<bhavya> in isInvInductive, dic ret:", dic
            if dic:
                for key, value in dic.unv.iteritems(
                ):  # <TODO> verify if it shouldn't be min
                    res.unv[key] = res.unv[key] if res.sizeof(
                        key) >= dic.sizeof(key) else dic.unv[key]
                isInvInd = False
    return res, isInvInd
示例#6
0
文件: ivy_check.py 项目: hannesm/ivy
def show_counterexample(ag, state, bmc_res):
    universe, path = bmc_res
    other_art = ivy_art.AnalysisGraph()
    ag.copy_path(state, other_art, None)
    for state, value in zip(other_art.states[-len(path):], path):
        state.value = value
        state.universe = universe
    gui_art(other_art)
示例#7
0
def check_isolate():
    temporals = [p for p in im.module.labeled_props if p.temporal]
    mod = im.module
    if temporals:
        if len(temporals) > 1:
            raise IvyError(None,'multiple temporal properties in an isolate not supported yet')
        from ivy_l2s import l2s
        l2s(mod, temporals[0])
        mod.concept_spaces = []
        mod.update_conjs()
    ifc.check_fragment()
    with im.module.theory_context():
        summarize_isolate(mod)
        return
        check_properties()
        some_temporals = any(p.temporal for p in im.module.labeled_props)
        check_temporals()
        ag = ivy_art.AnalysisGraph(initializer=ivy_alpha.alpha)
        if im.module.initializers:
            cex = ag.check_bounded_safety(ag.states[0])
            if cex is not None:
                display_cex("safety failed in initializer",cex)
        with ivy_interp.EvalContext(check=False):
            initiation_checked = False
            if not some_temporals:
                check_conjectures('Initiation','These conjectures are false initially.',ag,ag.states[0])
                initiation_checked = True
            for actname in get_checked_actions():
                old_checked_assert = act.checked_assert.get()
                assertions = find_assertions(actname)
                if assertions and not initiation_checked:
                    check_conjectures('Initiation','These conjectures are false initially.',ag,ag.states[0])
                    initiation_checked = True
                print "trying {}...".format(actname)
                if act.checked_assert.get():
                    assertions = [a for a in assertions if a.lineno == act.checked_assert.get()]
                tried = set()
                for asn in assertions:
                    if asn.lineno not in tried:
                        tried.add(asn.lineno)
                        act.checked_assert.value = asn.lineno
                        print '{}: {}'.format(asn.lineno,asn)
                        ag.execute_action(actname,prestate=ag.states[0])
                        cex = ag.check_bounded_safety(ag.states[-1],bound=1)
                        if cex is not None:
                            display_cex("safety failed",cex)
                if initiation_checked:
                    print "checking consecution..."
                    ag.execute_action(actname,prestate=ag.states[0],abstractor=ivy_alpha.alpha)
                    check_conjectures('Consecution','These conjectures are not inductive.',ag,ag.states[-1])
                act.checked_assert.value = old_checked_assert
示例#8
0
 def process_init(self):
     init_cl = []
     for name, action in self.mod.initializers:
         #             print ("init: ", str(action))
         ag = ivy_art.AnalysisGraph(initializer=lambda x: None)
         history = ag.get_history(ag.states[0])
         post = lut.and_clauses(history.post)
         init_cl.append(post)
     clauses = lut.and_clauses(*init_cl)
     f = self.get_formula(clauses)
     pref = lgu.substitute(f, self.nex2pre)
     self.add_new_constants(pref)
     res = (pref, "init", "init", "true")
     self.vmt["$init"] = res
示例#9
0
def show_counterexample(ag,state,bmc_res):
    universe,path = bmc_res
    other_art = ivy_art.AnalysisGraph()
    ag.copy_path(state,other_art,None)
    for state,value in zip(other_art.states[-len(path):],path):
        state.value = value
        state.universe = universe

    import tk_ui as ui
    iu.set_parameters({'mode':'induction'})
    gui = ui.new_ui()
    agui = gui.add(other_art)
    gui.tk.update_idletasks() # so that dialog is on top of main window
    gui.tk.mainloop()
    exit(1)
示例#10
0
文件: ivy_trace.py 项目: hannesm/ivy
def make_check_art(act_name=None, precond=[]):
    action = act.env_action(act_name)

    ag = art.AnalysisGraph()

    pre = itp.State()
    pre.clauses = lut.and_clauses(*precond)
    pre.clauses.annot = act.EmptyAnnotation()

    with itp.EvalContext(check=False):  # don't check safety
        post = ag.execute(action, pre)
        post.clauses = lut.true_clauses()

    fail = itp.State(expr=itp.fail_expr(post.expr))

    return ag, post, fail
示例#11
0
def check_module():
    # If user specifies an isolate, check it. Else, if any isolates
    # are specificied in the file, check all, else check globally.

    missing = []

    isolate = ivy_compiler.isolate.get()
    if isolate != None:
        isolates = [isolate]
    else:
        isolates = sorted(list(im.module.isolates))
        if len(isolates) == 0:
            isolates = [None]
        else:
            if coverage.get():
                missing = ivy_isolate.check_isolate_completeness()

    if missing:
        raise iu.IvyError(None, "Some assertions are not checked")

    for isolate in isolates:
        if isolate != None and len(
                im.module.isolates[isolate].verified()) == 0:
            continue  # skip if nothing to verify
        if isolate:
            print "Checking isolate {}...".format(isolate)
        with im.module.copy():
            ivy_isolate.create_isolate(isolate)  # ,ext='ext'
            check_properties()
            ag = ivy_art.AnalysisGraph(initializer=ivy_alpha.alpha)
            if im.module.initializers:
                cex = ag.check_bounded_safety(ag.states[0])
                if cex is not None:
                    display_cex("safety failed in initializer", cex)
            with ivy_interp.EvalContext(check=False):
                check_conjectures('Initiation',
                                  'These conjectures are false initially.', ag,
                                  ag.states[0])
                for a in sorted(im.module.public_actions):
                    print "trying {}...".format(a)
                    ag.execute_action(a, prestate=ag.states[0])
                    cex = ag.check_bounded_safety(ag.states[-1])
                    if cex is not None:
                        display_cex("safety failed", cex)
                    check_conjectures('Consecution',
                                      'These conjectures are not inductive.',
                                      ag, ag.states[-1])
示例#12
0
def sampleUtil(mod, preclause, fcs, actname):
    '''
	a sample created by using z3 which satsfies preclauses and final condition(fcs) where transtion 
	function is obtained from action corresponding to actname
	'''
    action = mod.actions[actname]
    ag = ivy_art.AnalysisGraph()
    pre = itp.State()
    pre.clauses = preclause
    with itp.EvalContext(check=False):  # don't check safety
        post = ag.execute(
            action, pre, None, actname
        )  # action clauses are added to preclause here (transition function and preclause)
        history = ag.get_history(post)
        gmc = lambda cls, final_cond: itr.small_model_clauses(
            cls, final_cond, shrink=True
        )  #shrink=True gives smallest possible sample
        axioms = mod.background_theory()
        return history.satisfy(axioms, gmc, fcs)
示例#13
0
文件: ivy_trace.py 项目: odedp/ivy
def make_vc(action, precond=[], postcond=[], check_asserts=True):

    ag = art.AnalysisGraph()

    pre = itp.State()
    pre.clauses = lut.Clauses([lf.formula for lf in precond])
    pre.clauses.annot = act.EmptyAnnotation()

    with itp.EvalContext(check=False):  # don't check safety
        post = ag.execute(action, pre)
        post.clauses = lut.true_clauses()

    fail = itp.State(expr=itp.fail_expr(post.expr))

    history = ag.get_history(post)
    axioms = im.module.background_theory()
    clauses = history.post

    #Tricky: fix the annotation so it matches the original action
    stack = []
    while isinstance(clauses.annot, act.RenameAnnotation):
        stack.append(clauses.annot.map)
        clauses.annot = clauses.annot.arg
    clauses.annot = clauses.annot.args[1]
    while stack:
        clauses.annot = act.RenameAnnotation(clauses.annot, stack.pop())

    clauses = lut.and_clauses(clauses, axioms)
    fc = lut.Clauses([lf.formula for lf in postcond])
    fc.annot = act.EmptyAnnotation()
    used_names = frozenset(x.name for x in lg.sig.symbols.values())

    def witness(v):
        c = lg.Symbol('@' + v.name, v.sort)
        assert c.name not in used_names
        return c

    fcc = lut.dual_clauses(fc, witness)
    clauses = lut.and_clauses(clauses, fcc)

    return clauses
示例#14
0
def checkInitialCond(mod):
    print "\nChecking if Initialization establishes the learned invariants"
    print "\n    Invariants are: "
    for lc in mod.labeled_conjs:
        print "    {}".format(Clauses([lc.formula]))
    print ''
    with itp.EvalContext(check=False):
        ag = ivy_art.AnalysisGraph(initializer=lambda x: None)
        lcs = mod.labeled_conjs
        fcs = [icheck.ConjChecker(c) for c in lcs]
        history = ag.get_history(ag.states[0])
        gmc = lambda cls, final_cond: itr.small_model_clauses(
            cls, final_cond, shrink=True)
        axioms = mod.background_theory()
        model = history.satisfy(axioms, gmc, fcs)
        smpl = Sample(model, '-1')  # this sample has no post state
        if hasattr(smpl, 'interp'):  # smpl is not None
            print "<plearn> + sample interpretation : ", smpl.interp, "\n"  # for detailed information
            smpl.displaySample()  # for displaying the sample
            print "\nInitialization establishes the learned Invariant: FAIL"
        else:
            print "\nInitialization establishes the learned Invariant: PASS"
示例#15
0
def check_module():
    # If user specifies an isolate, check it. Else, if any isolates
    # are specificied in the file, check all, else check globally.

    missing = []

    isolate = ivy_compiler.isolate.get()
    if isolate != None:
        isolates = [isolate]
    else:
        isolates = sorted(list(im.module.isolates))
        if len(isolates) == 0:
            isolates = [None]
        else:
            if coverage.get():
                missing = ivy_isolate.check_isolate_completeness()

    if missing:
        raise iu.IvyError(None, "Some assertions are not checked")

    for isolate in isolates:
        if isolate != None and isolate in im.module.isolates:
            idef = im.module.isolates[isolate]
            if len(idef.verified()) == 0 or isinstance(
                    idef, ivy_ast.TrustedIsolateDef):
                continue  # skip if nothing to verify
        if isolate:
            print "Checking isolate {}...".format(isolate)
        with im.module.copy():
            ivy_isolate.create_isolate(isolate)  # ,ext='ext'
            if opt_trusted.get():
                continue
            with im.module.theory_context():
                check_properties()
                ag = ivy_art.AnalysisGraph(initializer=ivy_alpha.alpha)
                if im.module.initializers:
                    cex = ag.check_bounded_safety(ag.states[0])
                    if cex is not None:
                        display_cex("safety failed in initializer", cex)
                with ivy_interp.EvalContext(check=False):
                    check_conjectures(
                        'Initiation', 'These conjectures are false initially.',
                        ag, ag.states[0])
                    #                    show_assertions()
                    for actname in get_checked_actions():
                        old_checked_assert = act.checked_assert.get()
                        print "trying {}...".format(actname)
                        assertions = find_assertions(actname)
                        if act.checked_assert.get():
                            assertions = [
                                a for a in assertions
                                if a.lineno == act.checked_assert.get()
                            ]
                        tried = set()
                        for asn in assertions:
                            if asn.lineno not in tried:
                                tried.add(asn.lineno)
                                act.checked_assert.value = asn.lineno
                                print '{}: {}'.format(asn.lineno, asn)
                                ag.execute_action(actname,
                                                  prestate=ag.states[0])
                                cex = ag.check_bounded_safety(ag.states[-1],
                                                              bound=1)
                                if cex is not None:
                                    display_cex("safety failed", cex)
                        print "checking consecution..."
                        ag.execute_action(actname,
                                          prestate=ag.states[0],
                                          abstractor=ivy_alpha.alpha)
                        check_conjectures(
                            'Consecution',
                            'These conjectures are not inductive.', ag,
                            ag.states[-1])
                        act.checked_assert.value = old_checked_assert
示例#16
0
文件: ivy_check.py 项目: hannesm/ivy
def summarize_isolate(mod):

    global check_lineno
    check_lineno = act.checked_assert.get()
    if check_lineno == "":
        check_lineno = None


#    print 'check_lineno: {}'.format(check_lineno)
    check = not opt_summary.get()
    subgoalmap = dict((x.id, y) for x, y in im.module.subgoals)
    axioms = [m for m in mod.labeled_axioms if m.id not in subgoalmap]
    schema_instances = [m for m in mod.labeled_axioms if m.id in subgoalmap]
    if axioms:
        print "\n    The following properties are assumed as axioms:"
        for lf in axioms:
            print pretty_lf(lf)

    if mod.definitions:
        print "\n    The following definitions are used:"
        for lf in mod.definitions:
            print pretty_lf(lf)

    if (mod.labeled_props or schema_instances) and not checked_action.get():
        print "\n    The following properties are to be checked:"
        if check:
            for lf in schema_instances:
                print pretty_lf(lf) + " [proved by axiom schema]"
            ag = ivy_art.AnalysisGraph()
            clauses1 = lut.true_clauses(annot=act.EmptyAnnotation())
            pre = itp.State(value=clauses1)
            props = [x for x in im.module.labeled_props if not x.temporal]
            fcs = ([
                (ConjAssumer if prop.id in subgoalmap else ConjChecker)(prop)
                for prop in props
            ])
            check_fcs_in_state(mod, ag, pre, fcs)
        else:
            for lf in schema_instances + mod.labeled_props:
                print pretty_lf(lf)

    # after checking properties, make them axioms
    im.module.labeled_axioms.extend(im.module.labeled_props)
    im.module.update_theory()

    if mod.labeled_inits:
        print "\n    The following properties are assumed initially:"
        for lf in mod.labeled_inits:
            print pretty_lf(lf)
    if mod.labeled_conjs:
        print "\n    The inductive invariant consists of the following conjectures:"
        for lf in mod.labeled_conjs:
            print pretty_lf(lf)

    apply_conj_proofs(mod)

    if mod.isolate_info.implementations:
        print "\n    The following action implementations are present:"
        for mixer, mixee, action in sorted(mod.isolate_info.implementations,
                                           key=lambda x: x[0]):
            print "        {}implementation of {}".format(
                pretty_lineno(action), mixee)

    if mod.isolate_info.monitors:
        print "\n    The following action monitors are present:"
        for mixer, mixee, action in sorted(mod.isolate_info.monitors,
                                           key=lambda x: x[0]):
            print "        {}monitor of {}".format(pretty_lineno(action),
                                                   mixee)

    # if mod.actions:
    #     print "\n    The following actions are present:"
    #     for actname,action in sorted(mod.actions.iteritems()):
    #         print "        {}{}".format(pretty_lineno(action),actname)

    if mod.initializers:
        print "\n    The following initializers are present:"
        for actname, action in sorted(mod.initializers, key=lambda x: x[0]):
            print "        {}{}".format(pretty_lineno(action), actname)

    if mod.labeled_conjs and not checked_action.get():
        print "\n    Initialization must establish the invariant"
        if check:
            with itp.EvalContext(check=False):
                ag = ivy_art.AnalysisGraph(initializer=lambda x: None)
                check_conjs_in_state(mod, ag, ag.states[0])
        else:
            print ''

    if mod.initializers:
        print "\n    Any assertions in initializers must be checked",
        if check:
            ag = ivy_art.AnalysisGraph(initializer=lambda x: None)
            fail = itp.State(expr=itp.fail_expr(ag.states[0].expr))
            check_safety_in_state(mod, ag, fail)

    checked_actions = get_checked_actions()

    if checked_actions and mod.labeled_conjs:
        print "\n    The following set of external actions must preserve the invariant:"
        for actname in sorted(checked_actions):
            action = act.env_action(actname)
            print "        {}{}".format(pretty_lineno(action), actname)
            if check:
                ag = ivy_art.AnalysisGraph()
                pre = itp.State()
                pre.clauses = get_conjs(mod)
                with itp.EvalContext(check=False):  # don't check safety
                    #                    post = ag.execute(action, pre, None, actname)
                    post = ag.execute(action, pre)
                check_conjs_in_state(mod, ag, post, indent=12)
            else:
                print ''

    callgraph = defaultdict(list)
    for actname, action in mod.actions.iteritems():
        for called_name in action.iter_calls():
            callgraph[called_name].append(actname)

    some_assumps = False
    for actname, action in mod.actions.iteritems():
        assumptions = [
            sub for sub in action.iter_subactions()
            if isinstance(sub, act.AssumeAction)
        ]
        if assumptions:
            if not some_assumps:
                print "\n    The following program assertions are treated as assumptions:"
                some_assumps = True
            callers = callgraph[actname]
            if actname in mod.public_actions:
                callers.append("the environment")
            prettyname = actname[4:] if actname.startswith('ext:') else actname
            prettycallers = [
                c[4:] if c.startswith('ext:') else c for c in callers
            ]
            print "        in action {} when called from {}:".format(
                prettyname, ','.join(prettycallers))
            for sub in assumptions:
                print "            {}assumption".format(pretty_lineno(sub))

    tried = set()
    some_guarants = False
    for actname, action in mod.actions.iteritems():
        guarantees = [
            sub for sub in action.iter_subactions()
            if isinstance(sub, (act.AssertAction, act.Ranking))
        ]
        if check_lineno is not None:
            guarantees = [
                sub for sub in guarantees if sub.lineno == check_lineno
            ]
        if guarantees:
            if not some_guarants:
                print "\n    The following program assertions are treated as guarantees:"
                some_guarants = True
            callers = callgraph[actname]
            if actname in mod.public_actions:
                callers.append("the environment")
            prettyname = actname[4:] if actname.startswith('ext:') else actname
            prettycallers = [
                c[4:] if c.startswith('ext:') else c for c in callers
            ]
            print "        in action {} when called from {}:".format(
                prettyname, ','.join(prettycallers))
            roots = set(iu.reachable([actname], lambda x: callgraph[x]))
            for sub in guarantees:
                print "            {}guarantee".format(pretty_lineno(sub)),
                if check and any(r in roots and (r, sub.lineno) not in tried
                                 for r in checked_actions):
                    print_dots()
                    old_checked_assert = act.checked_assert.get()
                    act.checked_assert.value = sub.lineno
                    some_failed = False
                    for root in checked_actions:
                        if root in roots:
                            tried.add((root, sub.lineno))
                            action = act.env_action(root)
                            ag = ivy_art.AnalysisGraph()
                            pre = itp.State()
                            pre.clauses = get_conjs(mod)
                            with itp.EvalContext(check=False):
                                post = ag.execute(action, prestate=pre)
                            fail = itp.State(expr=itp.fail_expr(post.expr))
                            if not check_safety_in_state(
                                    mod, ag, fail, report_pass=False):
                                some_failed = True
                                break
                    if not some_failed:
                        print 'PASS'
                    act.checked_assert.value = old_checked_assert
                else:
                    print ""