示例#1
0
 def to_smtlib(self):
     """Return a SMT_LIB string representation of the formula."""
     sc.reset_env()
     i_f = sc.And(*[bv2pysmt(a) for a in self.inner_problem.assertions])
     o_f = sc.And(*[bv2pysmt(a) for a in self.outer_problem.assertions])
     pysmt_formula = sc.And(i_f, o_f)
     return sc.to_smtlib(pysmt_formula, daggify=False)
示例#2
0
def execute_script_fname(smtfile, logic, expected_result):
    """Read and call a Solver to solve the instance"""

    reset_env()
    Solver = get_env().factory.Solver
    parser = SmtLibParser()
    script = parser.get_script_fname(smtfile)
    try:
        solver = Solver(logic=logic, incremental=False, generate_models=False)
        if logic == QF_UF and type(solver).__name__ == 'CVC4Solver':
            warnings.warn(
                "Test (%s, %s) skipped because CVC4 can't handle QF_UF." %
                (logic, smtfile))
            return
        if logic == QF_UF and type(solver).__name__ == 'BoolectorSolver':
            warnings.warn(
                "Test (%s, %s) skipped because Boolector can't handle QF_UF." %
                (logic, smtfile))
            return
        log = script.evaluate(solver)
    except NoSolverAvailableError:
        raise SkipTest("No solver for logic %s." % logic)
    except SolverReturnedUnknownResultError:
        if not logic.quantifier_free:
            warnings.warn(
                "Test (%s, %s) could not be solved due to quantifiers." %
                (logic, smtfile))
            return
        raise

    res = check_sat_filter(log)
    assert expected_result == res
示例#3
0
    def to_smtlib(self):
        """Return a SMT_LIB string representation of the formula.

            >>> from arxpy.bitvector.function import Function
            >>> from arxpy.diffcrypt.difference import XorDiff, DiffVar
            >>> from arxpy.diffcrypt.characteristic import Characteristic
            >>> from arxpy.diffcrypt.smt import SmtProblem
            >>> class MyFunction(Function):
            ...     input_widths = [8, 8, 8]
            ...     output_widths = [8, 8]
            ...     @classmethod
            ...     def eval(cls, x, y, k):
            ...         return (y + k, (y + k) ^ x)
            >>> x, y, k = DiffVar("x", 8), DiffVar("y", 8), DiffVar("k", 8)
            >>> ch = Characteristic(MyFunction, XorDiff, [x, y, k])
            >>> smt_problem = SmtProblem(ch, 0)
            >>> print(smt_problem.to_smtlib())  # doctest:+ELLIPSIS
            (and (not (= #b000000000000000000000000 (concat (concat x y) k))) ...

        Note that a more human-readable from can be obtained by
        printing the SmtProblem directly (print(smt_problem)).
        """
        sc.reset_env()
        pysmt_formula = sc.And(*[bv2pysmt(a) for a in self.assertions])
        return sc.to_smtlib(pysmt_formula, daggify=False)
示例#4
0
 def parse(self, file_id):
     fname = SMTLIB_FILE_PATTERN % file_id
     reset_env()
     parser = SmtLibParser()
     script = parser.get_script_fname(fname)
     self.assertIsNotNone(script)
     return script
示例#5
0
def scan(full_dir, root_dir):
    matches = []

    for root, dir_names, file_names in os.walk(full_dir):
        for filename in fnmatch.filter(file_names, '*.smt2'):
            full_path = os.path.abspath(os.path.join(root, filename))
            matches.append(re.match("{r}{s}(.*)".format(s=os.path.sep, r=root_dir), full_path).group(1))

    for match in matches:
        print(match)

    flat = load()
    problems = flat["files"]
    counter = 0
    for match in matches:
        if match not in problems:
            print("Importing {}".format(match))
            smt_file = os.path.join(root_dir, match)
            if os.path.getsize(smt_file) / 1024 <= 100:
                imported_problem = import_problem(match, smt_file)
                problems[match] = {
                    "loaded": True,
                    "var_count": len(imported_problem.domain.variables),
                    "file_size": os.path.getsize(match)
                }
                smt.reset_env()
            else:
                problems[match] = {"loaded": False, "reason": "size", "file_size": os.path.getsize(match)}
            counter += 1
            if counter >= 1:
                dump(flat)
                counter = 0

    if counter != 0:
        dump(flat)
示例#6
0
def execute_script_fname(smtfile, logic, expected_result):
    """Read and call a Solver to solve the instance"""

    reset_env()
    Solver = get_env().factory.Solver
    parser = SmtLibParser()
    script = parser.get_script_fname(smtfile)
    try:
        log = script.evaluate(
            Solver(logic=logic, incremental=False, generate_models=False))
    except NoSolverAvailableError:
        raise SkipTest("No solver for logic %s." % logic)
    except SolverReturnedUnknownResultError:
        if not logic.quantifier_free:
            warnings.warn(
                "Test (%s, %s) could not be solver due to quantifiers." %
                (logic, smtfile))
            return
        raise

    res = check_sat_filter(log)
    if res:
        assert expected_result == "sat"
    else:
        assert expected_result == "unsat"
示例#7
0
 def parse(self, file_id):
     fname = SMTLIB_FILE_PATTERN % file_id
     reset_env()
     parser = SmtLibParser()
     script = parser.get_script_fname(fname)
     self.assertIsNotNone(script)
     return script
示例#8
0
def run_translation(path):
    reset_env()

    status = True

    if "-boolean" in path:
        boolean = True
    else:
        boolean = False

    models = list([x for x in list(os.walk(path))
                   if COSADIR not in x[0]])[-1][-1]

    j_files = [
        "%s/%s" % (path, f) for f in models if f.split(".")[1] == "json"
    ]
    s_files = [
        "%s/%s" % (path, f) for f in models
        if f.split(".")[1] in ["sts", "ets"]
    ]
    v_files = [
        "%s/%s[%s]" % (path, f, f.split(".")[0]) for f in models
        if f.split(".")[1] in ["v"]
    ]

    if os.path.isfile("%s/assumptions.txt" % path):
        assumptions = "%s/assumptions.txt" % path
    else:
        assumptions = None

    if os.path.isfile("%s/properties.txt" % path):
        properties = "%s/properties.txt" % path
    else:
        properties = None

    if os.path.isfile("%s/lemmas.txt" % path):
        lemmas = "%s/lemmas.txt" % path
    else:
        lemmas = None

    problems_manager = cosa_option_manager.get_default_problem_manager(
        verbosity=3,
        boolean=boolean,
        translate=path + GENERATED,
        printer='SMV',
        model_files=",".join(j_files + s_files + v_files))

    problems_manager.add_problem(
        solver_name='msat',
        verification='safety' if properties is not None else "simulation",
        prove=True if properties is not None else False,
        assumptions=assumptions,
        properties=properties,
        lemmas=lemmas)
    run_problems(problems_manager)

    # status = files_eq(path+EXPECTED, path+GENERATED)
    # assert status
    return status
示例#9
0
    def pysmt_formula_size(self):
        """The size of the underlying bit-vector formula according to pySMT."""
        sc.reset_env()
        i_f = sc.And(*[bv2pysmt(a) for a in self.inner_problem.assertions])
        o_f = sc.And(*[bv2pysmt(a) for a in self.outer_problem.assertions])
        pysmt_formula = sc.And(i_f, o_f)

        return sc.get_formula_size(pysmt_formula)
示例#10
0
def execute_script_fname(smtfile):
    """Read and call a Solver to solve the instance"""
    print(smtfile)
    reset_env()
    assert os.path.exists(smtfile)
    start = time.clock()
    read_smtlib(smtfile)
    end = time.clock()
    return ( (end - start), smtfile)
示例#11
0
def execute_script_fname(smtfile):
    """Read and call a Solver to solve the instance"""
    print(smtfile)
    reset_env()
    assert os.path.exists(smtfile)
    start = time.clock()
    read_smtlib(smtfile)
    end = time.clock()
    return ((end - start), smtfile)
示例#12
0
def run_translation(path):
    reset_env()

    config = Config()
    status = True

    config.verbosity = 3
    config.solver_name = "msat"
    config.prove = True
    config.translate = path + GENERATED
    config.printer = "SMV"
    config.deterministic = True

    if "-boolean" in path:
        config.boolean = True

    if os.path.isfile("%s/assumptions.txt" % path):
        config.assumptions = "%s/assumptions.txt" % path

    if os.path.isfile("%s/properties.txt" % path):
        config.properties = "%s/properties.txt" % path

    if os.path.isfile("%s/lemmas.txt" % path):
        config.lemmas = "%s/lemmas.txt" % path

    models = list(os.walk(path))[-1][-1]
    j_files = [
        "%s/%s" % (path, f) for f in models if f.split(".")[1] == "json"
    ]
    s_files = [
        "%s/%s" % (path, f) for f in models
        if f.split(".")[1] in ["sts", "ets"]
    ]

    config.strfiles = ",".join(j_files + s_files)

    parsing_defs = [config.properties, config.lemmas, config.assumptions]
    for i in range(len(parsing_defs)):
        if parsing_defs[i] is not None:
            if os.path.isfile(parsing_defs[i]):
                with open(parsing_defs[i]) as f:
                    parsing_defs[i] = [
                        p.strip() for p in f.read().strip().split("\n")
                    ]
            else:
                parsing_defs[i] = [
                    p.strip() for p in parsing_defs[i].split(",")
                ]

    [config.properties, config.lemmas, config.assumptions] = parsing_defs

    run_verification(config)

    # status = files_eq(path+EXPECTED, path+GENERATED)
    # assert status
    return status
示例#13
0
def formulas_from_smtlib_test_set(logics=None):
    """Returns a generator over the test-set of SMT-LIB files.

    Note: This resets the Environment at each call.
    """
    for (logic, fname, expected_result) in SMTLIB_TEST_FILES:
        if logics is not None and logic not in logics:
            continue
        reset_env()
        smtfile = os.path.join(SMTLIB_DIR, fname)
        formula = get_formula_fname(smtfile)
        yield (logic, fname, formula, expected_result)
示例#14
0
def formulas_from_smtlib_test_set(logics=None):
    """Returns a generator over the test-set of SMT-LIB files.

    Note: This resets the Environment at each call.
    """
    for (logic, fname, expected_result) in SMTLIB_TEST_FILES:
        if logics is not None and logic not in logics:
            continue
        reset_env()
        smtfile = os.path.join(SMTLIB_DIR, fname)
        formula = get_formula_fname(smtfile)
        yield (logic, fname, formula, expected_result)
示例#15
0
def execute_script_fname(smtfile):
    """Read and print the formula in HR Format."""
    reset_env()
    assert os.path.exists(smtfile)
    smtlib_start = time.clock()
    f = read_smtlib(smtfile)
    smtlib_end = time.clock()
    start = time.clock()
    s = f.serialize()
    end = time.clock()
    assert s is not None
    #print(smtfile, (smtlib_end-smtlib_start), (end-start))
    return (smtfile, (end - start))
示例#16
0
    def solve(self, solver_name=None, get_assignment=False):
        """Solve the SMT problem.

        Return whether the decision problem is satisfiable. If get_assignment
        is set to True, solve() returns an assignment of the variables
        that makes the SMT problem satisfiable (if the problem is
        unsatisfiable, None is returned).

        This assignment is returned as a dictionary with the following entries:

        - differences: an ordered dictionary containing the sequence of
          differences.
        - weight: the weight of the characteristic.
        - op_weights: the weights of each operation with non-deterministic
          propagation.

            >>> from arxpy.bitvector.function import Function
            >>> from arxpy.diffcrypt.difference import XorDiff, DiffVar
            >>> from arxpy.diffcrypt.characteristic import Characteristic
            >>> from arxpy.diffcrypt.smt import SmtProblem
            >>> class MyFunction(Function):
            ...     input_widths = [8, 8, 8]
            ...     output_widths = [8, 8]
            ...     @classmethod
            ...     def eval(cls, x, y, k):
            ...         return (y + k, (y + k) ^ x)
            >>> x, y, k = DiffVar("x", 8), DiffVar("y", 8), DiffVar("k", 8)
            >>> ch = Characteristic(MyFunction, XorDiff, [x, y, k])
            >>> smt_problem = SmtProblem(ch, 0)
            >>> smt_problem.solve()
            True
            >>> smt_problem.solve(get_assignment=True)  # doctest:+NORMALIZE_WHITESPACE
            {'differences': OrderedDict([(x, 0x80), (y, 0x00), (k, 0x80),
            (d0, 0x80), (d1, 0x00)]), 'weight': 0,
            'op_weights': OrderedDict([(w_ky_d0, 0)])}

        """
        sc.reset_env()
        pysmt_formula = sc.And(*[bv2pysmt(a) for a in self.assertions])

        if not get_assignment:
            return sc.is_sat(pysmt_formula, solver_name, logic=logics.QF_BV)
        else:
            model = sc.get_model(pysmt_formula,
                                 solver_name,
                                 logic=logics.QF_BV)

            if model is None:
                return None
            else:
                return self._get_assignment(model)
示例#17
0
    def _smtlib_cnf(self, filename, logic, res_is_sat):
        reset_env()
        conv = CNFizer()
        smtfile = os.path.join(SMTLIB_DIR, filename)
        assert os.path.exists(smtfile)

        expr = get_formula_fname(smtfile)
        if not logic.quantifier_free:
            with self.assertRaises(NotImplementedError):
                conv.convert_as_formula(expr)
            return
        cnf = conv.convert_as_formula(expr)
        self.assertValid(Implies(cnf, expr), logic=logic)

        res = is_sat(cnf, logic=logic)
        self.assertEqual(res, res_is_sat)
示例#18
0
    def _smtlib_cnf(self, filename, logic, res_is_sat):
        reset_env()
        conv = CNFizer()
        smtfile = os.path.join(SMTLIB_DIR, filename)
        assert os.path.exists(smtfile)

        expr = get_formula_fname(smtfile)
        if not logic.quantifier_free:
            with self.assertRaises(NotImplementedError):
                conv.convert_as_formula(expr)
            return
        cnf = conv.convert_as_formula(expr)
        self.assertValid(Implies(cnf, expr), logic=logic)

        res = is_sat(cnf, logic=logic)
        self.assertEqual(res, res_is_sat)
示例#19
0
    def test_smtlib_multi_msat(self):
        from pysmt.test.smtlib.parser_utils import SMTLIB_TEST_FILES, SMTLIB_DIR

        # On some platforms (Windows x64) the internal pickling process requires
        # quite a lot of recursion...
        old_recursion_limit = sys.getrecursionlimit()
        sys.setrecursionlimit(999999)

        for (logic, f, expected_result) in SMTLIB_TEST_FILES:
            smtfile = os.path.join(SMTLIB_DIR, f)
            if logic <= QF_UFLIRA:
                env = reset_env()
                formula = get_formula_fname(smtfile, env)
                # Simplifying the formula to reduce its depth to avoid errors on some
                # platforms until issue #455 for details.
                formula = formula.simplify()
                with Portfolio([("msat", {
                        "random_seed": 1
                }), ("msat", {
                        "random_seed": 17
                }), ("msat", {
                        "random_seed": 42
                })],
                               logic=logic,
                               environment=env,
                               incremental=False,
                               generate_models=False) as s:
                    res = s.is_sat(formula)
                    self.assertEqual(expected_result, res, smtfile)

        #reset recursion limit
        sys.setrecursionlimit(old_recursion_limit)
示例#20
0
def runtest(example):
    reset_env()

    config = Config()

    config.safety = True
    config.verbosity = 3
    config.solver_name = "msat"
    config.prove = True
    config.vcd = True
    config.force_expected = True

    status = run_problems("%s/problem.txt" % example, config)

    assert status == 0
    return status
示例#21
0
    def test_smtlib_multi_msat(self):
        from pysmt.test.smtlib.parser_utils import SMTLIB_TEST_FILES, SMTLIB_DIR

        # On some platforms (Windows x64) the internal pickling process requires
        # quite a lot of recursion...
        old_recursion_limit = sys.getrecursionlimit()
        sys.setrecursionlimit(999999)
        
        for (logic, f, expected_result) in SMTLIB_TEST_FILES:
            smtfile = os.path.join(SMTLIB_DIR, f)
            if logic <= QF_UFLIRA:
                env = reset_env()
                formula = get_formula_fname(smtfile, env)
                # Simplifying the formula to reduce its depth to avoid errors on some
                # platforms until issue #455 for details.
                formula = formula.simplify()
                with Portfolio([("msat", {"random_seed": 1}),
                                ("msat", {"random_seed": 17}),
                                ("msat", {"random_seed": 42})],
                               logic=logic,
                               environment=env,
                               incremental=False,
                               generate_models=False) as s:
                    res = s.is_sat(formula)
                    self.assertEqual(expected_result, res, smtfile)

        #reset recursion limit
        sys.setrecursionlimit(old_recursion_limit)
示例#22
0
def execute_script_fname(smtfile):
    """Read and call a Solver to solve the instance"""
    print(smtfile)
    reset_env()
    assert os.path.exists(smtfile)
    parser = SmtLibParser()
    solver = NoopSolver(get_env())

    start = time.clock()
    script = parser.get_script_fname(smtfile)
    end = time.clock()

    script.evaluate(solver)
    res = solver.get_asserted_formula()
    assert res is not None

    return (smtfile, (end - start))
示例#23
0
def execute_script_fname(smtfile, logic, expected_result):
    """Read and call a Solver to solve the instance"""

    reset_env()
    assert os.path.exists(smtfile), smtfile
    parser = SmtLibParser()
    script = parser.get_script_fname(smtfile)
    try:
        log = script.evaluate(Solver(logic=logic))
    except NoSolverAvailableError:
        raise unittest.SkipTest("No solver for logic %s." % logic)

    res = check_sat_filter(log)
    if res:
        assert expected_result == "sat"
    else:
        assert expected_result == "unsat"
示例#24
0
def execute_script_fname(smtfile, logic, expected_result):
    """Read and call a Solver to solve the instance"""

    reset_env()
    assert os.path.exists(smtfile), smtfile
    parser = SmtLibParser()
    script = parser.get_script_fname(smtfile)
    try:
        log = script.evaluate(Solver(logic=logic))
    except NoSolverAvailableError:
        raise SkipTest("No solver for logic %s." % logic)

    res = check_sat_filter(log)
    if res:
        assert expected_result == "sat"
    else:
        assert expected_result == "unsat"
示例#25
0
 def run_smtlib(self, smtfile, logic, expected_result):
     env = reset_env()
     formula = get_formula_fname(smtfile, env)
     with Portfolio(["cvc4", "msat", "yices"],
                    logic=logic,
                    environment=env,
                    incremental=False,
                    generate_models=False) as s:
         res = s.is_sat(formula)
         self.assertEqual(expected_result, res, smtfile)
示例#26
0
 def run_smtlib(self, smtfile, logic, expected_result):
     env = reset_env()
     formula = get_formula_fname(smtfile, env)
     with Portfolio(["cvc4", "msat", "yices"],
                    logic=logic,
                    environment=env,
                    incremental=False,
                    generate_models=False) as s:
         res = s.is_sat(formula)
         self.assertEqual(expected_result, res, smtfile)
示例#27
0
def execute_script_fname(smtfile, logic, expected_result):
    """Read and call a Solver to solve the instance"""

    reset_env()
    Solver = get_env().factory.Solver
    parser = SmtLibParser()
    script = parser.get_script_fname(smtfile)
    try:
        log = script.evaluate(Solver(logic=logic, incremental=False,
                                     generate_models=False))
    except NoSolverAvailableError:
        raise SkipTest("No solver for logic %s." % logic)
    except SolverReturnedUnknownResultError:
        if not logic.quantifier_free:
            warnings.warn("Test (%s, %s) could not be solver due to quantifiers." % (logic, smtfile))
            return
        raise

    res = check_sat_filter(log)
    assert expected_result == res
示例#28
0
文件: shell.py 项目: danny-boby/CoSA
def run_problems(problems, config):
    reset_env()
    Logger.verbosity = config.verbosity
    pbms = Problems()
    psol = ProblemSolver()
    pbms.load_problems(problems)
    psol.solve_problems(pbms, config)

    global_status = 0

    Logger.log("\n*** SUMMARY ***", 0)

    for pbm in pbms.problems:
        unk_k = "" if pbm.status != VerificationStatus.UNK else "\nBMC depth: %s" % pbm.bmc_length
        Logger.log("\n** Problem %s **" % (pbm.name), 0)
        Logger.log("Description: %s" % (pbm.description), 0)
        Logger.log("Result: %s%s" % (pbm.status, unk_k), 0)
        if (pbm.expected is not None):
            expected = VerificationStatus.convert(pbm.expected) == pbm.status
            Logger.log("Expected: %s" % ("OK" if expected else "WRONG"), 0)
            if not expected:
                global_status = 1

        assert not (config.force_expected and (pbm.expected is None))

        prefix = config.prefix if config.prefix is not None else pbm.trace_prefix

        if (pbm.verification != VerificationType.SIMULATION) and (
                pbm.status == VerificationStatus.FALSE):
            print_trace("Counterexample", pbm.trace, pbm.name, prefix)

        if (pbm.verification == VerificationType.SIMULATION) and (
                pbm.status == VerificationStatus.TRUE):
            print_trace("Execution", pbm.trace, pbm.name, prefix)

        if pbm.time:
            Logger.log("Time: %.2f sec" % (pbm.time), 0)

    return global_status
示例#29
0
    def test_vmt(self):
        reset_env()
        parser = SmtLibParser()
        fname = os.path.join(SMTLIB_DIR, "small_set/vmt/c432_0f.vmt")
        script = parser.get_script_fname(fname)

        ann = script.annotations

        self.assertIn("A_1__AT0 ->", str(ann))

        a1 = Symbol("A_1__AT0")

        self.assertIn(a1, ann)
        self.assertTrue(ann.has_annotation(a1, "next"))
        self.assertFalse(ann.has_annotation(a1, "non-existent"))
        self.assertTrue(ann.has_annotation(a1, "next", "A_1__AT1"))
        self.assertFalse(ann.has_annotation(a1, "next", "non-existent"))

        self.assertIn("A_1__AT1", ann.annotations(a1)["next"])

        curr_a1 = ann.all_annotated_formulae("next", "A_1__AT1")
        self.assertEqual(curr_a1, set([a1]))
示例#30
0
    def test_vmt(self):
        reset_env()
        parser = SmtLibParser()
        fname = os.path.join(SMTLIB_DIR, "small_set/vmt/c432_0f.vmt")
        script = parser.get_script_fname(fname)

        ann = script.annotations

        self.assertIn("A_1__AT0 ->", str(ann))

        a1 = Symbol("A_1__AT0")

        self.assertIn(a1, ann)
        self.assertTrue(ann.has_annotation(a1, "next"))
        self.assertFalse(ann.has_annotation(a1, "non-existent"))
        self.assertTrue(ann.has_annotation(a1, "next", "A_1__AT1"))
        self.assertFalse(ann.has_annotation(a1, "next", "non-existent"))

        self.assertIn("A_1__AT1", ann.annotations(a1)["next"])
        self.assertIn("A_1__AT1", ann[a1]["next"])

        curr_a1 = ann.all_annotated_formulae("next", "A_1__AT1")
        self.assertEqual(curr_a1, set([a1]))
示例#31
0
    def test_smtlib_multi_msat(self):
        from pysmt.test.smtlib.parser_utils import SMTLIB_TEST_FILES, SMTLIB_DIR

        for (logic, f, expected_result) in SMTLIB_TEST_FILES:
            smtfile = os.path.join(SMTLIB_DIR, f)
            if logic <= QF_UFLIRA:
                env = reset_env()
                formula = get_formula_fname(smtfile, env)
                with Portfolio([("msat", {"random_seed": 1}),
                                ("msat", {"random_seed": 17}),
                                ("msat", {"random_seed": 42})],
                               logic=logic,
                               environment=env,
                               incremental=False,
                               generate_models=False) as s:
                    res = s.is_sat(formula)
                    result = "sat" if res else "unsat"
                    self.assertEqual(expected_result, result, smtfile)
示例#32
0
    def test_smtlib_multi_msat(self):
        from pysmt.test.smtlib.parser_utils import SMTLIB_TEST_FILES, SMTLIB_DIR

        for (logic, f, expected_result) in SMTLIB_TEST_FILES:
            smtfile = os.path.join(SMTLIB_DIR, f)
            if logic <= QF_UFLIRA:
                env = reset_env()
                formula = get_formula_fname(smtfile, env)
                with Portfolio([("msat", {
                        "random_seed": 1
                }), ("msat", {
                        "random_seed": 17
                }), ("msat", {
                        "random_seed": 42
                })],
                               logic=logic,
                               environment=env,
                               incremental=False,
                               generate_models=False) as s:
                    res = s.is_sat(formula)
                    self.assertEqual(expected_result, res, smtfile)
示例#33
0
    def pysmt_formula_size(self):
        """The size of the underlying bit-vector formula according to pySMT."""
        sc.reset_env()
        pysmt_formula = sc.And(*[bv2pysmt(a) for a in self.assertions])

        return sc.get_formula_size(pysmt_formula)
示例#34
0
    def test_new_node_type(self):
        old = list(all_types())
        idx = new_node_type(node_str="xor")
        self.assertIsNotNone(idx)
        self.assertNotIn(idx, old)
        with self.assertRaises(AssertionError):
            new_node_type(idx)
        XOR = idx

        # Ad-hoc method to handle printing of the new node
        def hrprinter_walk_xor(self, formula):
            self.stream.write("(")
            yield formula.arg(0)
            self.stream.write(" *+* ")
            yield formula.arg(1)
            self.stream.write(")")

        SimpleTypeChecker.walk_xor = SimpleTypeChecker.walk_bool_to_bool
        HRPrinter.walk_xor = hrprinter_walk_xor

        # Reset the env to recreate the TypeChecker and HRPrinter
        reset_env()

        # Shortcuts for function in env
        create_node = get_env().formula_manager.create_node
        # Create a test node (This implicitly calls the Type-checker)
        x = Symbol("x")
        f1 = create_node(node_type=XOR, args=(x,x))
        self.assertIsNotNone(f1)

        # String conversion should use the function defined above.
        s_f1 = str(f1)
        self.assertEqual(s_f1, "(x *+* x)")

        # We did not define an implementation for the Simplifier
        with self.assertRaises(UnsupportedOperatorError):
            f1.simplify()

        # Clean-up
        del SimpleTypeChecker.walk_xor
        del HRPrinter.walk_xor

        class MySimpleTypeChecker(SimpleTypeChecker):
            walk_xor = SimpleTypeChecker.walk_bool_to_bool

        class MyHRPrinter(HRPrinter):
            def walk_xor(self, formula):
                return self.walk_nary(formula, " *+* ")

        class MyHRSerializer(HRSerializer):
            PrinterClass = MyHRPrinter

        class MyEnv(Environment):
            TypeCheckerClass = MySimpleTypeChecker
            HRSerializerClass = MyHRSerializer

        with MyEnv() as myenv:
            create_node = myenv.formula_manager.create_node
            # Create a test node (This implicitly calls the Type-checker)
            x = Symbol("x")
            f1 = create_node(node_type=XOR, args=(x,x))
            self.assertIsNotNone(f1)

            # String conversion should use the function defined above.
            s_f1 = str(f1)
            self.assertEqual(s_f1, "(x *+* x)")

            # We did not define an implementation for the Simplifier
            with self.assertRaises(UnsupportedOperatorError):
                f1.simplify()

        return
示例#35
0
文件: __init__.py 项目: shadown/pysmt
 def setUp(self):
     self.env = reset_env()
示例#36
0
 def parse(self, fname):
     reset_env()
     parser = SmtLibParser()
     script = parser.get_script_fname(fname)
     self.assertIsNotNone(script)
     return script
示例#37
0
文件: shell.py 项目: danny-boby/CoSA
def run_verification(config):
    reset_env()
    Logger.verbosity = config.verbosity

    coreir_parser = None
    ets_parser = None
    sts_parser = None

    if config.ltl:
        ltl_reset_env()

    hts = HTS("Top level")

    if config.strfiles[0][-4:] != ".pkl":
        ps = ProblemSolver()
        (hts, invar_props,
         ltl_props) = ps.parse_model("./",
                                     config.strfiles,
                                     config.abstract_clock,
                                     config.symbolic_init,
                                     deterministic=config.deterministic,
                                     boolean=config.boolean,
                                     no_clock=config.no_clock)
        config.parser = ps.parser

        if config.pickle_file:
            Logger.msg("Pickling model to %s\n" % (config.pickle_file), 1)
            sys.setrecursionlimit(50000)
            with open(config.pickle_file, "wb") as f:
                pickle.dump(hts, f)
    else:
        if config.pickle_file:
            raise RuntimeError("Don't need to re-pickle the input file %s" %
                               (config.strfile))

        Logger.msg("Loading pickle file %s\n" % (config.strfile), 0)
        with open(config.pickle_file, "rb") as f:
            hts = pickle.load(f)
        Logger.log("DONE", 0)

    printsmv = True

    mc_config = MCConfig()

    sparser = StringParser()
    sparser.remap_or2an = config.parser.remap_or2an
    ltlparser = LTLParser()

    # if equivalence checking wait to add assumptions to combined system
    if config.assumptions is not None and config.equivalence is None:
        Logger.log("Adding %d assumptions... " % len(config.assumptions), 1)
        assumps = [t[1] for t in sparser.parse_formulae(config.assumptions)]
        hts.assumptions = assumps

    lemmas = None
    if config.lemmas is not None:
        Logger.log("Adding %d lemmas... " % len(config.lemmas), 1)
        parsed_formulae = sparser.parse_formulae(config.lemmas)
        if list(set([t[2] for t in parsed_formulae]))[0][0] != False:
            Logger.error("Lemmas do not support \"next\" operators")
        lemmas = [t[1] for t in parsed_formulae]
        hts.lemmas = lemmas

    mc_config.smt2file = config.smt2file

    mc_config.full_trace = config.full_trace
    mc_config.trace_vars_change = config.trace_vars_change
    mc_config.trace_all_vars = config.trace_all_vars
    mc_config.prefix = config.prefix
    mc_config.strategy = config.strategy
    mc_config.skip_solving = config.skip_solving
    mc_config.map_function = config.parser.remap_an2or
    mc_config.solver_name = config.solver_name
    mc_config.vcd_trace = config.vcd
    mc_config.prove = config.prove
    mc_config.incremental = config.incremental

    if config.ltl:
        bmc_ltl = BMCLTL(hts, mc_config)
    else:
        bmc_safety = BMCSafety(hts, mc_config)

    if config.translate:
        Logger.log("Writing system to \"%s\"" % (config.translate), 0)
        printer = PrintersFactory.printer_by_name(config.printer)

        props = []
        if config.ltl:
            props += ltlparser.parse_formulae(config.properties)
            props += [(str(p), p, None) for p in ltl_props]
        else:
            props += sparser.parse_formulae(config.properties)
            props += [(str(p), p, None) for p in invar_props]

        with open(config.translate, "w") as f:
            f.write(printer.print_hts(hts, props))

    if config.simulate:
        count = 0
        if config.properties is None:
            props = [("True", TRUE(), None)]
        else:
            props = sparser.parse_formulae(config.properties)
        for (strprop, prop, _) in props:
            Logger.log("Simulation for property \"%s\":" % (strprop), 0)
            res, trace = bmc_safety.simulate(prop, config.bmc_length)
            if res == VerificationStatus.TRUE:
                count += 1
                print_trace("Execution", trace, count, config.prefix)
            else:
                Logger.log("No execution found", 0)

    if config.safety:
        count = 0
        props = sparser.parse_formulae(config.properties)
        props += [(str(p), p, None) for p in invar_props]
        if len(props) == 0:
            Logger.warning("Safety verification requires at least a property")

        for (strprop, prop, _) in props:
            Logger.log("Safety verification for property \"%s\":" % (strprop),
                       0)
            res, trace, t = bmc_safety.safety(prop, config.bmc_length,
                                              config.bmc_length_min)
            Logger.log("\nProperty is %s" % res, 0)
            if res == VerificationStatus.FALSE:
                count += 1
                print_trace("Counterexample", trace, count, config.prefix)

        return 0

    if config.equivalence or config.fsm_check:

        if config.equivalence:
            parser2 = CoreIRParser(config.abstract_clock, config.symbolic_init,
                                   config.run_passes)

            Logger.msg("Parsing file \"%s\"... " % (config.equivalence), 0)
            hts2 = parser2.parse_file(config.equivalence)
            Logger.log("DONE", 0)

            symb = " (symbolic init)" if config.symbolic_init else ""
            Logger.log(
                "Equivalence checking%s with k=%s:" %
                (symb, config.bmc_length), 0)

            if Logger.level(1):
                print(hts2.print_statistics("System 2", Logger.level(2)))
        else:
            hts2 = hts

        # TODO: Make incremental solving optional
        htseq, miter_out = Miter.combine_systems(hts, hts2, config.bmc_length,
                                                 config.symbolic_init,
                                                 config.properties, True)

        if config.assumptions is not None:
            Logger.log(
                "Adding %d assumptions to combined system... " %
                len(config.assumptions), 1)
            assumps = [
                t[1] for t in sparser.parse_formulae(config.assumptions)
            ]
            htseq.assumptions = assumps

        # create bmc object for combined system
        bmcseq = BMC(htseq, mc_config)
        res, trace, t = bmcseq.safety(miter_out, config.bmc_length,
                                      config.bmc_length_min)

        msg = "Systems are %s equivalent" if config.equivalence else "System is%s deterministic"

        if res == VerificationStatus.FALSE:
            Logger.log(msg % (" not"), 0)
            print_trace("Counterexample", trace, 1, config.prefix)
        elif res == VerificationStatus.UNK:
            if config.symbolic_init:
                # strong equivalence with symbolic initial state
                Logger.log(msg % (""), 0)
            else:
                Logger.log(msg % ("") + " up to k=%i" % t, 0)
        else:
            Logger.log(msg % ("") + " up to k=%i" % t, 0)

    if config.ltl:
        count = 0
        props = ltlparser.parse_formulae(config.properties)
        props += [(str(p), p, None) for p in ltl_props]
        if len(props) == 0:
            Logger.warning("LTL verification requires at least a property")

        for (strprop, prop, _) in props:
            Logger.log("LTL verification for property \"%s\":" % (strprop), 0)
            res, trace, t = bmc_ltl.ltl(prop, config.bmc_length,
                                        config.bmc_length_min)
            Logger.log("\nProperty is %s" % res, 0)
            if res == VerificationStatus.FALSE:
                count += 1
                print_trace("Counterexample", trace, count, config.prefix)

        return 0
示例#38
0
    def solve(self, solver_name=None, get_assignment=False):
        """Solve the pair of SMT problems simultaneously.

        Return whether the pair of decision problems are satisfiable.
        If get_assignment is set to True, solve() returns an assignment of
        the variables that makes the pair of SMT problems satisfiable
        (if one of the problems is unsatisfiable, None is returned).

        This assignment is returned as a pair of dictionaries, where
        the first dictionary is the assignment of the inner SMT problem
        and the second dictionary is the assignment of the outer SMT problem.

            >>> from arxpy.bitvector.operation import RotateLeft
            >>> from arxpy.bitvector.function import Function, CompositeFunction
            >>> from arxpy.diffcrypt.difference import XorDiff, DiffVar
            >>> from arxpy.diffcrypt.characteristic import Characteristic, CompositeCh
            >>> class MyInner(Function):
            ...     input_widths = [8]
            ...     output_widths = [8, 8]
            ...     @classmethod
            ...     def eval(cls, k):
            ...         return (k, RotateLeft(k, 1))
            >>> class MyOuter(Function):
            ...     input_widths = [8, 8, 8, 8]
            ...     output_widths = [8, 8]
            ...     @classmethod
            ...     def eval(cls, x, y, k0, k1):
            ...         for ki in [k0, k1]:
            ...             x, y = y + ki, (y + ki) ^ x
            ...         return x, y
            >>> class MyComposite(CompositeFunction):
            ...     input_widths = [8, 8, 8]
            ...     output_widths = [8, 8]
            ...     inner_func = MyInner
            ...     outer_func = MyOuter
            >>> x, y, k = DiffVar("x", 8), DiffVar("y", 8), DiffVar("k", 8)
            >>> ch = CompositeCh(MyComposite, XorDiff, [x, y, k])
            >>> smt_problem = CompositeSmtProblem(ch, [1, 1])
            >>> smt_problem.solve()
            True
            >>> inner_assig, outer_assig = smt_problem.solve(get_assignment=True)
            >>> inner_assig  # doctest:+NORMALIZE_WHITESPACE
            {'differences': OrderedDict([(k, 0x40), (i0, 0x80)]),
            'weight': 0, 'op_weights': OrderedDict()}
            >>> outer_assig  # doctest:+NORMALIZE_WHITESPACE
            {'differences': OrderedDict([(x, 0x40), (y, 0x00), (k, 0x40),
            (i0, 0x80), (o0, 0x40), (o1, 0x00), (o2, 0x80), (o3, 0xc0)]),
            'weight': 1, 'op_weights': OrderedDict([(w_ky_o0, 1),
            (w_i0o1_o2, 0)])}

        """
        sc.reset_env()
        i_f = sc.And(*[bv2pysmt(a) for a in self.inner_problem.assertions])
        o_f = sc.And(*[bv2pysmt(a) for a in self.outer_problem.assertions])
        pysmt_formula = sc.And(i_f, o_f)

        if not get_assignment:
            return sc.is_sat(pysmt_formula, solver_name, logic=logics.QF_BV)
        else:
            model = sc.get_model(pysmt_formula,
                                 solver_name,
                                 logic=logics.QF_BV)

            if model is None:
                return None
            else:
                inner_assig = self.inner_problem._get_assignment(model)
                outer_assig = self.outer_problem._get_assignment(model)
                return inner_assig, outer_assig
示例#39
0
 def parse(self, fname):
     reset_env()
     parser = SmtLibParser()
     script = parser.get_script_fname(fname)
     self.assertIsNotNone(script)