Esempio n. 1
0
def get_cti(s: Solver, candidate: Expr) -> Optional[Tuple[Diagram, Diagram]]:
    res = logic.check_two_state_implication_all_transitions(s, [candidate],
                                                            candidate,
                                                            minimize=True)
    if res is None:
        return None

    z3m: z3.ModelRef = res[0]
    mod = Trace.from_z3((KEY_OLD, KEY_NEW), z3m)
    return (mod.as_diagram(index=0), mod.as_diagram(index=1))
Esempio n. 2
0
File: updr.py Progetto: aatxe/mypyvy
        def edge_covering_checker(p: Phase) -> Optional[Tuple[Phase, Diagram]]:
            t = self.solver.get_translator(KEY_NEW, KEY_OLD)
            f = self.fs[-1]
            prog = syntax.the_program

            with self.solver:
                for c in f.summary_of(p):
                    self.solver.add(t.translate_expr(c, old=True))

                transitions_from_phase = self.automaton.transitions_from(p)

                for trans in prog.transitions():
                    edges_from_phase_matching_prog_trans = [
                        t for t in transitions_from_phase
                        if t.prog_transition_name() == trans.name
                    ]
                    if any(delta.precond is None
                           for delta in edges_from_phase_matching_prog_trans):
                        utils.logger.debug(
                            'transition %s is covered trivially by %s' %
                            (trans.name, p.name()))
                        continue

                    utils.logger.debug(
                        'checking transition %s is covered by %s' %
                        (trans.name, p.name()))

                    with self.solver:
                        self.solver.add(t.translate_transition(trans))
                        preconds = (
                            z3.Not(
                                t.translate_precond_of_transition(
                                    delta.precond(), trans))
                            for delta in edges_from_phase_matching_prog_trans)
                        self.solver.add(z3.And(*preconds))

                        if self.solver.check() != z3.unsat:
                            utils.logger.debug(
                                'phase %s cex to edge covering of transition %s'
                                % (p.name(), trans.name))
                            z3m: z3.ModelRef = self.solver.model()
                            mod = Trace.from_z3([KEY_OLD, KEY_NEW], z3m)
                            self.record_state(mod)
                            diag = mod.as_diagram(i=0)
                            return (p, diag)

                        utils.logger.debug(
                            'transition %s is covered non-trivially by %s' %
                            (trans.name, p.name()))
                        continue

                utils.logger.debug('all edges covered from phase %s' %
                                   p.name())
                return None
Esempio n. 3
0
File: updr.py Progetto: aatxe/mypyvy
        def safety_property_checker(
                p: Phase) -> Optional[Tuple[Phase, Diagram]]:
            res = logic.check_implication(self.solver, f.summary_of(p),
                                          (inv.expr
                                           for inv in phases.phase_safety(p)))

            if res is None:
                utils.logger.debug(
                    "Frontier frame phase %s implies safety, summary is %s" %
                    (p.name(), f.summary_of(p)))
                return None

            utils.logger.debug("Frontier frame phase %s cex to safety" %
                               p.name())
            z3m: z3.ModelRef = res
            mod = Trace.from_z3([KEY_ONE], z3m)
            self.record_state(mod)
            diag = mod.as_diagram()
            return (p, diag)
Esempio n. 4
0
    def find_predecessor(
        self, j: int, diag_or_expr: Union[Diagram, Expr]
    ) -> Tuple[z3.CheckSatResult, Union[Optional[MySet[int]], Tuple[
            DefinitionDecl, Trace]]]:
        pre_frame = self[j]
        prog = syntax.the_program
        solver = self.solver
        t = self.solver.get_translator((KEY_OLD, KEY_NEW))

        if utils.args.use_z3_unsat_cores:
            core: Optional[MySet[int]] = MySet()
        else:
            core = None

        def to_z3() -> z3.ExprRef:
            if isinstance(diag_or_expr, Diagram):
                return diag_or_expr.to_z3(t, state_index=1)
            else:
                return t.translate_expr(diag_or_expr, index=1)

        def trackers() -> List[z3.ExprRef]:
            if isinstance(diag_or_expr, Diagram):
                return diag_or_expr.trackers
            else:
                return []

        with solver.new_frame(), solver.mark_assumptions_necessary():
            for f in pre_frame.summary():
                solver.add(t.translate_expr(f, index=0))
            solver.add(to_z3())
            for ition in prog.transitions():
                with solver.new_frame():
                    solver.add(t.translate_transition(ition))
                    if (res := solver.check(trackers())) == z3.sat:
                        m = Trace.from_z3((KEY_OLD, KEY_NEW),
                                          solver.model(trackers()))
                        state = State(m, 0)
                        src = self.currently_blocking
                        assert src is not None
                        steps_from_cex = src.known_absent_until_frame + 1 - j + src.num_steps_to_bad
                        bstate = BackwardReachableState(
                            len(self.backwards_reachable_states), state,
                            steps_from_cex)
                        self.record_backwards_reachable_state(bstate)
                        return (z3.sat, (ition, m))
                    elif res == z3.unsat:
                        if utils.args.use_z3_unsat_cores and isinstance(
                                diag_or_expr, Diagram):
                            assert core is not None
                            # carefully retrieve the unsat core before calling check again
                            uc = solver.unsat_core()
                            res = solver.check(
                                [diag_or_expr.trackers[i] for i in core])
                            if res == z3.unsat:
                                continue
                            for x in sorted(uc, key=lambda y: y.decl().name()):
                                assert isinstance(x, z3.ExprRef)
                                core.add(int(x.decl().name()[1:]))
                    else:
                        for e in solver.assertions():
                            print(e)
                        assert False, ('z3 returned unknown', res)
Esempio n. 5
0
                                              minimize=False)
                if res is not None:
                    return bstate_min

            bstate_min.known_absent_until_frame += 1

        utils.logger.info(
            'no existing states to block. looking for a new state.')

        f = self.fs[-1]
        if len(self.safeties) == 0 or (res := logic.check_implication(
                self.solver, f.summary(), self.safeties)) is None:
            utils.logger.info('frontier is safe. nothing new to block either.')
            return None

        state = State(Trace.from_z3((KEY_ONE, ), res), 0)
        assert len(self) >= 2
        bstate = BackwardReachableState(len(self.backwards_reachable_states),
                                        state, 0)
        bstate.known_absent_until_frame = len(self) - 2
        self.record_backwards_reachable_state(bstate)
        return bstate

    def record_backwards_reachable_state(
            self, state: BackwardReachableState) -> None:
        utils.logger.info(
            f'discovered state #{len(self.backwards_reachable_states)}')
        utils.logger.info(str(state))
        self.backwards_reachable_states.append(state)

    def get_inductive_frame(self) -> Optional[Frame]:
Esempio n. 6
0
File: updr.py Progetto: aatxe/mypyvy
    def find_predecessor_from_src_phase(
        self, t: syntax.Z3Translator, pre_frame: Frame, src_phase: Phase,
        transitions: Sequence[PhaseTransition], diag: Diagram,
        core: Optional[MySet[int]]
    ) -> Tuple[z3.CheckSatResult, Optional[Tuple[PhaseTransition, Tuple[
            Phase, Diagram]]]]:

        prog = syntax.the_program
        solver = self.solver
        with solver:

            for f in pre_frame.summary_of(src_phase):
                solver.add(t.translate_expr(f, old=True))

            for phase_transition in transitions:
                delta = phase_transition.transition_decl()
                trans = prog.scope.get_definition(delta.transition)
                assert trans is not None
                precond = delta.precond

                with utils.LogTag(utils.logger,
                                  'find-pred',
                                  transition=delta.transition,
                                  weight=str(
                                      phase_transition.avg_time_traversing())):
                    with solver:
                        solver.add(
                            t.translate_transition(trans, precond=precond))
                        before_check = datetime.now()
                        res = solver.check(diag.trackers)
                        phase_transition.time_spent_traversing += (
                            datetime.now() - before_check).total_seconds()
                        phase_transition.count_traversed += 1

                        if res != z3.unsat:
                            utils.logger.debug('found predecessor via %s' %
                                               trans.name)
                            m = Trace.from_z3([KEY_OLD, KEY_NEW],
                                              solver.model(diag.trackers))
                            # if utils.logger.isEnabledFor(logging.DEBUG):
                            #     utils.logger.debug(str(m))
                            self.record_state(m)
                            return (res, (phase_transition,
                                          (src_phase, m.as_diagram(i=0))))
                        elif utils.args.use_z3_unsat_cores:
                            assert core is not None
                            uc = solver.unsat_core()
                            # if utils.logger.isEnabledFor(logging.DEBUG):
                            #     utils.logger.debug('uc')
                            #     utils.logger.debug(str(sorted(uc, key=lambda y: y.decl().name())))
                            #     utils.logger.debug('assertions')
                            #     utils.logger.debug(str(solver.assertions()))

                            res = solver.check(
                                [diag.trackers[i] for i in core])
                            if res == z3.unsat:
                                utils.logger.debug(
                                    'but existing core sufficient, skipping')
                                continue

                            for x in sorted(uc, key=lambda y: y.decl().name()):
                                assert isinstance(x, z3.ExprRef)
                                core.add(int(x.decl().name()[1:]))
                            if utils.logger.isEnabledFor(logging.DEBUG):
                                utils.logger.debug('new core')
                                utils.logger.debug(str(sorted(core)))

            return (z3.unsat, None)
Esempio n. 7
0
File: updr.py Progetto: aatxe/mypyvy
    def push_conjunct(self,
                      frame_no: int,
                      c: Expr,
                      p: Phase,
                      frame_old_count: Optional[int] = None) -> None:
        is_safety = c in phases.phase_safety(p)

        f = self.fs[frame_no]
        while True:
            with utils.LogTag(utils.logger,
                              'pushing-conjunct-attempt',
                              lvl=logging.DEBUG,
                              frame=str(frame_no),
                              conj=str(c)):
                utils.logger.debug('frame %s phase %s attempting to push %s' %
                                   (frame_no, p.name(), c))

                res = self.clause_implied_by_transitions_from_frame(
                    f, p, c, minimize=is_safety or utils.args.block_may_cexs)
                if res is None:
                    utils.logger.debug('frame %s phase %s managed to push %s' %
                                       (frame_no, p.name(), c))

                    if utils.args.smoke_test and utils.logger.isEnabledFor(
                            logging.DEBUG):
                        utils.logger.debug('smoke testing...')
                        # TODO: phases
                        logic.check_bmc(self.solver, c, frame_no + 1)

                    # assert self.clause_implied_by_transitions_from_frame(f, p, c) is None
                    self[frame_no + 1].strengthen(p, c)
                    self.debug_assert_inductive_trace()
                    break

                pre_phase, (m, t) = res
                mod = Trace.from_z3([KEY_OLD, KEY_NEW], m)
                self.record_state(mod)
                diag = mod.as_diagram(i=0)

                if utils.logger.isEnabledFor(logging.DEBUG):
                    utils.logger.debug(
                        'frame %s failed to immediately push %s due to '
                        'transition %s' % (frame_no, c, t.pp()))
                    # utils.logger.debug(str(mod))
                if is_safety:
                    utils.logger.debug(
                        'note: current clause is safety condition')
                    self.block(diag,
                               frame_no,
                               pre_phase, [(None, c), (t, diag)],
                               safety_goal=True)
                else:
                    if utils.args.block_may_cexs:
                        ans = self.block(diag,
                                         frame_no,
                                         pre_phase, [(None, c), (t, diag)],
                                         safety_goal=False)
                        if isinstance(ans, CexFound):
                            break
                    else:
                        break