Ejemplo n.º 1
0
        public void Test_Z3_MemWithArray_2()
        {
            #region Definitions
            uint    nBits = 8;
            Context ctx   = new Context();

            BitVecExpr bv_0  = ctx.MkBV(0, nBits);
            BitVecExpr bv_16 = ctx.MkBV(16, nBits);
            BitVecExpr bv_32 = ctx.MkBV(32, nBits);

            BitVecExpr rax = ctx.MkBVConst("RAX!0", nBits);
            BitVecExpr rbx = ctx.MkBVConst("RBX!0", nBits);
            BitVecExpr rcx = ctx.MkBVConst("RCX!0", nBits);
            BitVecExpr rdx = ctx.MkBVConst("RDX!0", nBits);

            ArrayExpr mem = ctx.MkArrayConst("mem", ctx.MkBitVecSort(nBits), ctx.MkBitVecSort(nBits));

            Goal state = ctx.MkGoal();
            #endregion

            // Test possible memory overwrite
            Console.WriteLine("mov qword ptr[16], 0 ; store at address=16 value=0");
            mem = ctx.MkStore(mem, bv_16, bv_0);
            Console.WriteLine("mov rax, qword ptr[16] ; load rax with the value at address=16");
            state.Assert(ctx.MkEq(rax, ctx.MkSelect(mem, bv_16)));
            Console.WriteLine("mov qword ptr[rcx], 32 ; store at unknown address rcx value 32, appreciate that address 16 could be overwritten");
            mem = ctx.MkStore(mem, rcx, bv_32);
            Console.WriteLine("mov rbx, qword ptr[16] ; load rbx with value at address 16, appreciate that rbx need not be equal to rax");
            state.Assert(ctx.MkEq(rbx, ctx.MkSelect(mem, bv_16)));

            if (true)
            {
                Console.WriteLine("cmp rcx, 16 ;");
                Console.WriteLine("jnz label1: ");
                state.Assert(ctx.MkEq(rcx, bv_16));
            }
            #region Write to console
            Console.WriteLine("mem=" + mem);

            Solver solver   = ctx.MkSolver();
            Solver solver_U = ctx.MkSolver();
            solver.Assert(state.Formulas);
            Console.WriteLine("state1=" + state);
            if (true)
            {
                Tactic tactic1 = ctx.MkTactic("propagate-values");
                Goal   state2  = tactic1.Apply(state).Subgoals[0];
                Console.WriteLine("state2=" + state2.ToString());
            }
            Console.WriteLine(string.Empty);
            Tv[] raxTV = ToolsZ3.GetTvArray(rax, (int)nBits, solver, solver_U, ctx);
            Console.WriteLine("rax = " + ToolsZ3.ToStringBin(raxTV) + " = " + ToolsZ3.ToStringHex(raxTV));
            Tv[] rbxTV = ToolsZ3.GetTvArray(rbx, (int)nBits, solver, solver_U, ctx);
            Console.WriteLine("rbx = " + ToolsZ3.ToStringBin(rbxTV) + " = " + ToolsZ3.ToStringHex(rbxTV));
            Tv[] rcxTV = ToolsZ3.GetTvArray(rcx, (int)nBits, solver, solver_U, ctx);
            Console.WriteLine("rcx = " + ToolsZ3.ToStringBin(rcxTV) + " = " + ToolsZ3.ToStringHex(rcxTV));
            // Tv5[] rdxTV = ToolsZ3.getTvArray(rdx, nBits, solver, ctx);
            // Console.WriteLine("rdx = " + ToolsZ3.toStringBin(rdxTV) + " = " + ToolsZ3.toStringHex(rdxTV));
            #endregion
        }
Ejemplo n.º 2
0
    public void Run()
    {
        using (Context ctx = new Context())
        {
            RealExpr x = ctx.MkRealConst("x");
            RealExpr y = ctx.MkRealConst("y");

            Goal g = ctx.MkGoal();
            g.Assert(ctx.MkGt(x, ctx.MkReal(10)), ctx.MkEq(y, ctx.MkAdd(x, ctx.MkReal(1))));
            g.Assert(ctx.MkGt(y, ctx.MkReal(1)));

            Tactic      t = ctx.MkTactic("simplify");
            ApplyResult r = t.Apply(g);

            Console.WriteLine(r);
            Console.WriteLine(g.Size);

            foreach (Goal s in r.Subgoals)
            {
                Console.WriteLine(s);
            }

            Console.WriteLine("Old goal: ");
            Console.WriteLine(g);

            t = ctx.Then(ctx.MkTactic("simplify"), ctx.MkTactic("solve-eqs"));
            r = t.Apply(g);

            Console.WriteLine(r);

            Solver solver = ctx.MkSolver();
            foreach (BoolExpr f in r.Subgoals[0].Formulas)
            {
                solver.Assert(f);
            }

            Console.WriteLine(solver);
            Console.WriteLine(solver.Check());
            Console.WriteLine(solver.Model);
            Console.WriteLine("applying model convert");
            Console.WriteLine(r.ConvertModel(0, solver.Model));
            Console.WriteLine("done");
        }
    }
Ejemplo n.º 3
0
        public void Test_Z3_MemWithImplies()
        {
            Context ctx = new Context();

            BitVecExpr bv_0  = ctx.MkBV(0, 64);
            BitVecExpr bv_10 = ctx.MkBV(10, 64);
            BitVecExpr bv_20 = ctx.MkBV(20, 64);

            BitVecExpr addr  = ctx.MkBVConst("ADDR", 64);
            BitVecExpr value = ctx.MkBVConst("VALUE", 64);

            BitVecExpr value1 = ctx.MkBVConst("value1", 64);
            BitVecExpr value2 = ctx.MkBVConst("value2", 64);

            BitVecExpr rax = ctx.MkBVConst("RAX!0-1955042C05A090D2", 64);
            BitVecExpr rbx = ctx.MkBVConst("RBX!1-5000C87A5EB2FB98", 64);
            BitVecExpr rcx = ctx.MkBVConst("RCX!1-68FC98BF6AFBF63E", 64);
            BitVecExpr rdx = ctx.MkBVConst("RDX!0-231D57E228F579AD", 64);

            Goal state = ctx.MkGoal();

            // mov qword ptr[0], 10
            state.Assert(ctx.MkImplies(ctx.MkEq(addr, bv_0), ctx.MkEq(value, bv_10)));
            // mov qword ptr[10], 20
            state.Assert(ctx.MkImplies(ctx.MkEq(addr, bv_10), ctx.MkEq(value, bv_20)));
            // mov rbx, qword ptr[rax]
            //state.Assert(ctx.MkEq(rbx, ctx.MkEq(addr, value1));
            // mov rcx, qword ptr[rbx]
            //state.Assert(ctx.MkEq(rcx, ctx.MkEq(addr, value2));
            // cmp rax, 10;
            // jnz label1:
            state.Assert(ctx.MkEq(rax, bv_0));


            Tactic tactic1 = ctx.MkTactic("propagate-values");

            Console.WriteLine("state1=" + state);
            Console.WriteLine("state2=" + tactic1.Apply(state).ToString());

            Solver solver   = ctx.MkSolver();
            Solver solver_U = ctx.MkSolver();

            solver.Assert(state.Formulas);
            Tv[] f = ToolsZ3.GetTvArray(value, 64, solver, solver_U, ctx);
            Console.WriteLine("Value = 0b" + ToolsZ3.ToStringBin(f) + " = 0x" + ToolsZ3.ToStringHex(f));
        }
Ejemplo n.º 4
0
    public void Run()
    {
        Dictionary <string, string> cfg = new Dictionary <string, string>()
        {
            { "AUTO_CONFIG", "true" }
        };

        using (Context ctx = new Context(cfg))
        {
            RealExpr x = ctx.MkRealConst("x");
            RealExpr y = ctx.MkRealConst("y");
            RealExpr z = ctx.MkRealConst("z");

            Goal g = ctx.MkGoal();
            g.Assert(ctx.MkGt(ctx.MkAdd(x, y, z), ctx.MkReal(0)));

            Probe p = ctx.MkProbe("num-consts");
            Console.WriteLine("num-consts: " + p.Apply(g));

            Tactic t = ctx.FailIf(ctx.Gt(p, ctx.Const(2)));

            try
            {
                t.Apply(g);
            }
            catch (Z3Exception ex)
            {
                Console.WriteLine("Tactic failed: " + ex.Message);
            }

            Console.WriteLine("trying again...");

            g = ctx.MkGoal();
            g.Assert(ctx.MkGt(ctx.MkAdd(x, y), ctx.MkReal(0)));

            Console.WriteLine(t[g]);
        }
    }
Ejemplo n.º 5
0
        /// <summary>
        /// Consolidate constraints. Remove all redundancies.
        /// Eg. (= rax, rbx-4443) and (= rbx-4443, 2) is replaced by (= rax, 2)
        /// </summary>
        public static void Consolidate(bool undef, Solver solver, Solver solver_U, Context ctx)
        {
            if (true)
            {
                #region Doc

                /*
                 *  tacticName ackermannize_bv: A tactic for performing full Ackermannization on bv instances.
                 *  tacticName subpaving: tactic for testing subpaving module.
                 *  tacticName horn: apply tactic for horn clauses.
                 *  tacticName horn-simplify: simplify horn clauses.
                 *  tacticName nlsat: (try to) solve goal using a nonlinear arithmetic solver.
                 *  tacticName qfnra-nlsat: builtin strategy for solving QF_NRA problems using only nlsat.
                 *  tacticName nlqsat: apply a NL-QSAT solver.
                 *  tacticName qe-light: apply light-weight quantifier elimination.
                 *  tacticName qe-sat: check satisfiability of quantified formulas using quantifier elimination.
                 *  tacticName qe: apply quantifier elimination.
                 *  tacticName qsat: apply a QSAT solver.
                 *  tacticName qe2: apply a QSAT based quantifier elimination.
                 *  tacticName qe_rec: apply a QSAT based quantifier elimination recursively.
                 *  tacticName vsubst: checks satsifiability of quantifier-free non-linear constraints using virtual substitution.
                 *  tacticName sat: (try to) solve goal using a SAT solver.
                 *  tacticName sat-preprocess: Apply SAT solver preprocessing procedures (bounded resolution, Boolean constant propagation, 2-SAT, subsumption, subsumption resolution).
                 *  tacticName ctx-solver-simplify: apply solver-based contextual simplification rules.
                 *  tacticName smt: apply a SAT based SMT solver.
                 *  tacticName unit-subsume-simplify: unit subsumption simplification.
                 *  tacticName aig: simplify Boolean structure using AIGs.
                 *  tacticName add-bounds: add bounds to unbounded variables (under approximation).
                 *  tacticName card2bv: convert pseudo-boolean constraints to bit-vectors.
                 *  tacticName degree-shift: try to reduce degree of polynomials (remark: :mul2power simplification is automatically applied).
                 *  tacticName diff-neq: specialized solver for integer arithmetic problems that contain only atoms of the form (<= k x) (<= x k) and (not (= (- x y) k)), where x and y are constants and k is a numeral, and all constants are bounded.
                 *  tacticName elim01: eliminate 0-1 integer variables, replace them by Booleans.
                 *  tacticName eq2bv: convert integer variables used as finite domain elements to bit-vectors.
                 *  tacticName factor: polynomial factorization.
                 *  tacticName fix-dl-var: if goal is in the difference logic fragment, then fix the variable with the most number of occurrences at 0.
                 *  tacticName fm: eliminate variables using fourier-motzkin elimination.
                 *  tacticName lia2card: introduce cardinality constraints from 0-1 integer.
                 *  tacticName lia2pb: convert bounded integer variables into a sequence of 0-1 variables.
                 *  tacticName nla2bv: convert a nonlinear arithmetic problem into a bit-vector problem, in most cases the resultant goal is an under approximation and is useul for finding models.
                 *  tacticName normalize-bounds: replace a variable x with lower bound k <= x with x' = x - k.
                 *  tacticName pb2bv: convert pseudo-boolean constraints to bit-vectors.
                 *  tacticName propagate-ineqs: propagate ineqs/bounds, remove subsumed inequalities.
                 *  tacticName purify-arith: eliminate unnecessary operators: -, /, div, mod, rem, is-int, to-int, ^, root-objects.
                 *  tacticName recover-01: recover 0-1 variables hidden as Boolean variables.
                 *  tacticName bit-blast: reduce bit-vector expressions into SAT.
                 *  tacticName bv1-blast: reduce bit-vector expressions into bit-vectors of size 1 (notes: only equality, extract and concat are supported).
                 *  tacticName bv_bound_chk: attempts to detect inconsistencies of bounds on bv expressions.
                 *  tacticName propagate-bv-bounds: propagate bit-vector bounds by simplifying implied or contradictory bounds.
                 *  tacticName reduce-bv-size: try to reduce bit-vector sizes using inequalities.
                 *  tacticName bvarray2uf: Rewrite bit-vector arrays into bit-vector (uninterpreted) functions.
                 *  tacticName dt2bv: eliminate finite domain data-types. Replace by bit-vectors.
                 *  tacticName elim-small-bv: eliminate small, quantified bit-vectors by expansion.
                 *  tacticName max-bv-sharing: use heuristics to maximize the sharing of bit-vector expressions such as adders and multipliers.
                 *  tacticName blast-term-ite: blast term if-then-else by hoisting them.
                 *  tacticName cofactor-term-ite: eliminate term if-the-else using cofactors.
                 *  tacticName collect-statistics: Collects various statistics.
                 *  tacticName ctx-simplify: apply contextual simplification rules.
                 *  tacticName der: destructive equality resolution.
                 *  tacticName distribute-forall: distribute forall over conjunctions.
                 *  tacticName elim-term-ite: eliminate term if-then-else by adding fresh auxiliary declarations.
                 *  tacticName elim-uncnstr: eliminate application containing unconstrained variables.
                 *  tacticName snf: put goal in skolem normal form.
                 *  tacticName nnf: put goal in negation normal form.
                 *  tacticName occf: put goal in one constraint per clause normal form (notes: fails if proof generation is enabled; only clauses are considered).
                 *  tacticName pb-preprocess: pre-process pseudo-Boolean constraints a la Davis Putnam.
                 *  tacticName propagate-values: propagate constants.
                 *  tacticName reduce-args: reduce the number of arguments of function applications, when for all occurrences of a function f the i-th is a value.
                 *  tacticName simplify: apply simplification rules.
                 *  tacticName elim-and: convert (and a b) into (not (or (not a) (not b))).
                 *  tacticName solve-eqs: eliminate variables by solving equations.
                 *  tacticName split-clause: split a clause in many subgoals.
                 *  tacticName symmetry-reduce: apply symmetry reduction.
                 *  tacticName tseitin-cnf: convert goal into CNF using tseitin-like encoding (note: quantifiers are ignored).
                 *  tacticName tseitin-cnf-core: convert goal into CNF using tseitin-like encoding (note: quantifiers are ignored). This tactic does not apply required simplifications to the input goal like the tseitin-cnf tactic.
                 *  tacticName fpa2bv: convert floating point numbers to bit-vectors.
                 *  tacticName qffp: (try to) solve goal using the tactic for QF_FP.
                 *  tacticName qffpbv: (try to) solve goal using the tactic for QF_FPBV (floats+bit-vectors).
                 *  tacticName nl-purify: Decompose goal into pure NL-sat formula and formula over other theories.
                 *  tacticName default: default strategy used when no logic is specified.
                 *  tacticName qfbv-sls: (try to) solve using stochastic local search for QF_BV.
                 *  tacticName nra: builtin strategy for solving NRA problems.
                 *  tacticName qfaufbv: builtin strategy for solving QF_AUFBV problems.
                 *  tacticName qfauflia: builtin strategy for solving QF_AUFLIA problems.
                 *  tacticName qfbv: builtin strategy for solving QF_BV problems.
                 *  tacticName qfidl: builtin strategy for solving QF_IDL problems.
                 *  tacticName qflia: builtin strategy for solving QF_LIA problems.
                 *  tacticName qflra: builtin strategy for solving QF_LRA problems.
                 *  tacticName qfnia: builtin strategy for solving QF_NIA problems.
                 *  tacticName qfnra: builtin strategy for solving QF_NRA problems.
                 *  tacticName qfuf: builtin strategy for solving QF_UF problems.
                 *  tacticName qfufbv: builtin strategy for solving QF_UFBV problems.
                 *  tacticName qfufbv_ackr: A tactic for solving QF_UFBV based on Ackermannization.
                 *  tacticName qfufnra: builtin strategy for solving QF_UNFRA problems.
                 *  tacticName ufnia: builtin strategy for solving UFNIA problems.
                 *  tacticName uflra: builtin strategy for solving UFLRA problems.
                 *  tacticName auflia: builtin strategy for solving AUFLIA problems.
                 *  tacticName auflira: builtin strategy for solving AUFLIRA problems.
                 *  tacticName aufnira: builtin strategy for solving AUFNIRA problems.
                 *  tacticName lra: builtin strategy for solving LRA problems.
                 *  tacticName lia: builtin strategy for solving LIA problems.
                 *  tacticName lira: builtin strategy for solving LIRA problems.
                 *  tacticName skip: do nothing tactic.
                 *  tacticName fail: always fail tactic.
                 *  tacticName fail-if-undecided: fail if goal is undecided.
                 *  tacticName macro-finder: Identifies and applies macros.
                 *  tacticName quasi-macros: Identifies and applies quasi-macros.
                 *  tacticName ufbv-rewriter: Applies UFBV-specific rewriting rules, mainly demodulation.
                 *  tacticName bv: builtin strategy for solving BV problems (with quantifiers).
                 *  tacticName ufbv: builtin strategy for solving UFBV problems (with quantifiers).
                 */
                #endregion
                {
                    //Tactic taY = ctx.MkTactic("default"); // does not work: all constraitns are lost
                    //Tactic taX = ctx.MkTactic("skip");
                    //Tactic ta0 = ctx.MkTactic("ctx-solver-simplify"); //VERY SLOW
                    Tactic ta1 = ctx.MkTactic("simplify");     // some minor rewrites
                    Tactic ta2 = ctx.MkTactic("ctx-simplify"); // no differences compared with SKIP
                    //Tactic ta3 = ctx.MkTactic("qfbv"); // does not work: all constraitns are lost
                    //Tactic ta3b = ctx.MkTactic("qfbv-sls");// does not work: all constraitns are lost
                    //Tactic ta4 = ctx.MkTactic("solve-eqs");// does not work: all constraitns are lost
                    Tactic ta5 = ctx.MkTactic("propagate-values"); // no differences compared with SKIP
                    //Tactic ta6 = ctx.MkTactic("sat"); // make much more constrains such that Flatten takes VERY LONG
                    //Tactic ta6b = ctx.MkTactic("sat-preprocess"); // does not work: some constrains are lost
                    //Tactic ta7 = ctx.MkTactic("smt"); // does not work: all constraitns are lost

                    using (Tactic tactic = ctx.AndThen(ta2, ctx.AndThen(ta1, ta5)))
                    //                    using (Tactic tactic = ctx.AndThen(ta2, ta1))
                    {
                        if (!undef)
                        {
                            using (Goal goal1 = ctx.MkGoal())
                            {
                                goal1.Assert(solver.Assertions);
                                using (ApplyResult ar = tactic.Apply(goal1))
                                {
                                    solver.Reset();
                                    solver.Assert(ar.Subgoals[0].Formulas);
                                }
                            }
                        }
                        else
                        {
                            using (Goal goal1 = ctx.MkGoal())
                            {
                                goal1.Assert(solver_U.Assertions);
                                using (ApplyResult ar = tactic.Apply(goal1))
                                {
                                    solver_U.Reset();
                                    solver_U.Assert(ar.Subgoals[0].Formulas);
                                }
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Compute post from pre
        /// </summary>
        /// <param name="pre"></param>
        /// <returns></returns>
        public Expr MakePost(Expr pre)
        {
            KeyValuePair <Transition, Expr> postKey = new KeyValuePair <Transition, Expr>(this, pre);

            if (Transition.CachePost.ContainsKey(postKey))
            {
                return(CachePost[postKey]);
            }

            Expr idx = Controller.Instance.Indices["i"];

            ConcreteLocation l = this.Parent;

            List <BoolExpr> resets = new List <BoolExpr>();

            resets.Add((BoolExpr)pre); // add prestate

            if (this.NextStates.Count > 0)
            {
                resets.Add((BoolExpr)this.ToTerm());       // discrete location post-state (e.g., loc'[i] = 2)
            }

            List <String> globalVariableResets         = new List <String>(); // global variables not reset
            List <String> indexVariableResets          = new List <String>(); // indexed variables of process moving that are not reset
            List <String> universalIndexVariableResets = new List <String>(); // universally quantified indexed variables that are reset

            if (this.Reset != null)
            {
                resets.Add((BoolExpr)this.Reset);

                globalVariableResets = Controller.Instance.Z3.findGlobalVariableResets(this.Reset);
                indexVariableResets  = Controller.Instance.Z3.findIndexedVariableResets(this.Reset);
            }
            else
            {
                // global variable was not mentioned since reset is null: add it to the identity global variables (g' = g)
                globalVariableResets = Controller.Instance.Z3.findGlobalVariableResets(null);
                indexVariableResets  = Controller.Instance.Z3.findIndexedVariableResets(null);
            }

            if (this.UGuard != null) // TODO: handle univerasl resets (assume none for now)
            {
                universalIndexVariableResets = Controller.Instance.Z3.findIndexedVariableResetsNeg(this.UGuard);
            }

            Expr resetAnd = null;

            // create conjunction of pre-state and post-state conditions
            if (resets.Count > 0)
            {
                resetAnd = Controller.Instance.Z3.MkAnd(resets.ToArray());
            }


            Expr identity;

            if (l == null)
            {
                // TODO NEXT: GLOBAL INDEXED VARIABLE COULD CAUSE RESETS / "be the process moving"
                int  i    = 0;
                Expr gidx = null;
                foreach (var v in Controller.Instance.GlobalVariables)
                {
                    if (Controller.Instance.Sys.Variables.Find(
                            delegate(Variable gv)
                    {
                        return(gv.Name == v.Key);
                    }).Type == Variable.VarType.index && Controller.Instance.Z3.findTerm(this.Reset, v.Value, true))
                    {
                        gidx = v.Value;
                        i++;
                    }
                    // TODO: need to refactor forall identity to allow multiple processes moving, for now throw exception if it happens
                    if (i > 1)
                    {
                        throw new Exception("Error: too many global index variables used.");
                    }
                }
                identity = Controller.Instance.Sys.forallIdentityPost(gidx, globalVariableResets, indexVariableResets, universalIndexVariableResets, this.UGuard, 0); // no process moves if no location
            }
            else
            {
                identity = Controller.Instance.Sys.forallIdentityPost(idx, globalVariableResets, indexVariableResets, universalIndexVariableResets, this.UGuard, 0);
            }

            resetAnd = Controller.Instance.Z3.MkAnd((BoolExpr)resetAnd, (BoolExpr)identity);
            resetAnd = Controller.Instance.Z3.copyExpr(resetAnd);

            // short circuit

            /*
             * if (this.Reset == null && Controller.Instance.Sys.Variables.Count == 0)
             * {
             *  return resetAnd;
             * }
             */

            // replace all function declarations with constants (e.g., (q i) => (qi), where qi is a constant, instead of a function)

            List <Expr> bound = new List <Expr>();

            // TODO: use this.Parent.Parent.Parent, etc to access hybrid automata, holism, etc (will make generalizing to compositions easier)
            foreach (var v in Controller.Instance.Sys.HybridAutomata[0].Variables)
            {
                Expr varConst     = Controller.Instance.Z3.MkConst(v.Name + "_" + "i", v.TypeSort);
                Expr varConstPost = Controller.Instance.Z3.MkConst(v.NamePrimed + "_" + "i", v.TypeSort);
                resetAnd = resetAnd.Substitute(Controller.Instance.Z3.MkApp(v.Value, idx), varConst);
                resetAnd = resetAnd.Substitute(Controller.Instance.Z3.MkApp(v.ValuePrimed, idx), varConstPost);
                bound.Add(varConst);
            }

            foreach (var v in Controller.Instance.GlobalVariables.Values)
            {
                bound.Add(v);
            }


            //Expr post = Controller.Instance.Z3.MkExists(new Expr[] { idx }, (BoolExpr)resetAnd);
            Expr post = Controller.Instance.Z3.MkExists(bound.ToArray(), (BoolExpr)resetAnd);


            // HACK: replace all location names with their values...
            foreach (var loc in Controller.Instance.Sys.HybridAutomata[0].Locations)
            {
                post = post.Substitute(loc.LabelExpr, loc.BitVectorExpr);
            }
            post = post.Substitute(Controller.Instance.IndexN, Controller.Instance.Z3.MkInt(Controller.Instance.IndexNValue));



            Tactic tqe = Controller.Instance.Z3.Repeat(Controller.Instance.Z3.MkTactic("qe"));
            Goal   g   = Controller.Instance.Z3.MkGoal();



            List <BoolExpr> remAss = Controller.Instance.Z3.Assumptions.FindAll(a => a.IsQuantifier); // todo: add type constraints to constant (q_i) instead of functions (q i)

            Controller.Instance.Z3.Assumptions.RemoveAll(a => a.IsQuantifier);                        // otherwise q.e. will fail
            g.Assert(Controller.Instance.Z3.Assumptions.ToArray());
            Controller.Instance.Z3.Assumptions.AddRange(remAss);                                      // add back
            g.Assert(Controller.Instance.Z3.AssumptionsUniversal.ToArray());



            g.Assert((BoolExpr)post);
            g = g.Simplify();
            ApplyResult ar = tqe.Apply(g);

            List <BoolExpr> postStates = new List <BoolExpr>();

            foreach (var sg in ar.Subgoals)
            {
                postStates.AddRange(sg.Formulas);
            }



            postStates.RemoveAll(fa => Controller.Instance.Z3.Assumptions.Contains(fa));
            postStates.RemoveAll(fa => Controller.Instance.Z3.AssumptionsUniversal.Contains(fa));



            post = Controller.Instance.Z3.MkAnd(postStates.ToArray());


            // HACK: replace all location values with their names...
            foreach (var loc in Controller.Instance.Sys.HybridAutomata[0].Locations)
            {
                post = post.Substitute(loc.BitVectorExpr, loc.LabelExpr);
            }

            // convert constants back to functions
            foreach (var v in Controller.Instance.Sys.HybridAutomata[0].Variables)
            {
                Expr varConst     = Controller.Instance.Z3.MkConst(v.Name + "_" + "i", v.TypeSort);
                Expr varConstPost = Controller.Instance.Z3.MkConst(v.NamePrimed + "_" + "i", v.TypeSort);
                post = post.Substitute(varConst, Controller.Instance.Z3.MkApp(v.Value, idx));
                post = post.Substitute(varConstPost, Controller.Instance.Z3.MkApp(v.ValuePrimed, idx));
            }

            Controller.Instance.Z3.unprimeAllVariables(ref post); // unprime

            System.Console.WriteLine("POST: " + post.ToString());

            // cache result
            CachePost.Add(postKey, post);

            return(post);
        }
Ejemplo n.º 7
0
        public void Test_Z3_GoalsAndProbes()
        {
            using (Context ctx = new Context())
            {
                Solver solver = ctx.MkSolver();

                #region Print all Probes
                if (false)
                {
                    for (int i = 0; i < ctx.ProbeNames.Length; ++i)
                    {
                        Console.WriteLine(i + ": probe " + ctx.ProbeNames[i] + "; " + ctx.ProbeDescription(ctx.ProbeNames[i]));
                    }

                    /*
                     * 0: probe is-quasi-pb; true if the goal is quasi-pb.
                     * 1: probe is-unbounded; true if the goal contains integer/real constants that do not have lower/upper bounds.
                     * 2: probe is-pb; true if the goal is a pseudo-boolean problem.
                     * 3: probe arith-max-deg; max polynomial total degree of an arithmetic atom.
                     * 4: probe arith-avg-deg; avg polynomial total degree of an arithmetic atom.
                     * 5: probe arith-max-bw; max coefficient bit width.
                     * 6: probe arith-avg-bw; avg coefficient bit width.
                     * 7: probe is-qflia; true if the goal is in QF_LIA.
                     * 8: probe is-qfauflia; true if the goal is in QF_AUFLIA.
                     * 9: probe is-qflra; true if the goal is in QF_LRA.
                     * 10: probe is-qflira; true if the goal is in QF_LIRA.
                     * 11: probe is-ilp; true if the goal is ILP.
                     * 12: probe is-qfnia; true if the goal is in QF_NIA (quantifier-free nonlinear integer arithmetic).
                     * 13: probe is-qfnra; true if the goal is in QF_NRA (quantifier-free nonlinear real arithmetic).
                     * 14: probe is-nia; true if the goal is in NIA (nonlinear integer arithmetic, formula may have quantifiers).
                     * 15: probe is-nra; true if the goal is in NRA (nonlinear real arithmetic, formula may have quantifiers).
                     * 16: probe is-nira; true if the goal is in NIRA (nonlinear integer and real arithmetic, formula may have quantifiers).
                     * 17: probe is-lia; true if the goal is in LIA (linear integer arithmetic, formula may have quantifiers).
                     * 18: probe is-lra; true if the goal is in LRA (linear real arithmetic, formula may have quantifiers).
                     * 19: probe is-lira; true if the goal is in LIRA (linear integer and real arithmetic, formula may have quantifiers).
                     * 20: probe is-qfufnra; true if the goal is QF_UFNRA (quantifier-free nonlinear real arithmetic with other theories).
                     * 21: probe memory; ammount of used memory in megabytes.
                     * 22: probe depth; depth of the input goal.
                     * 23: probe size; number of assertions in the given goal.
                     * 24: probe num-exprs; number of expressions/terms in the given goal.
                     * 25: probe num-consts; number of non Boolean constants in the given goal.
                     * 26: probe num-bool-consts; number of Boolean constants in the given goal.
                     * 27: probe num-arith-consts; number of arithmetic constants in the given goal.
                     * 28: probe num-bv-consts; number of bit-vector constants in the given goal.
                     * 29: probe produce-proofs; true if proof generation is enabled for the given goal.
                     * 30: probe produce-model; true if model generation is enabled for the given goal.
                     * 31: probe produce-unsat-cores; true if unsat-core generation is enabled for the given goal.
                     * 32: probe has-patterns; true if the goal contains quantifiers with patterns.
                     * 33: probe is-propositional; true if the goal is in propositional logic.
                     * 34: probe is-qfbv; true if the goal is in QF_BV.
                     * 35: probe is-qfaufbv; true if the goal is in QF_AUFBV.
                     * 36: probe is-qfbv-eq; true if the goal is in a fragment of QF_BV which uses only =, extract, concat.
                     * 37: probe is-qffp; true if the goal is in QF_FP (floats).
                     * 38: probe is-qffpbv; true if the goal is in QF_FPBV (floats+bit-vectors).
                     */
                }
                #endregion Print all Probes
                #region Print all Tactics
                if (false)
                {
                    for (int i = 0; i < ctx.TacticNames.Length; ++i)
                    {
                        Console.WriteLine(i + ": tactic " + ctx.TacticNames[i] + "; " + ctx.TacticDescription(ctx.TacticNames[i]));
                    }

                    /*
                     * 0: tactic qfbv; builtin strategy for solving QF_BV problems.
                     * 1: tactic qflia; builtin strategy for solving QF_LIA problems.
                     * 2: tactic qflra; builtin strategy for solving QF_LRA problems.
                     * 3: tactic qfnia; builtin strategy for solving QF_NIA problems.
                     * 4: tactic qfnra; builtin strategy for solving QF_NRA problems.
                     * 5: tactic qfufnra; builtin strategy for solving QF_UNFRA problems.
                     * 6: tactic add-bounds; add bounds to unbounded variables(under approximation).
                     * 7: tactic card2bv; convert pseudo-boolean constraints to bit - vectors.
                     * 8: tactic degree-shift; try to reduce degree of polynomials(remark: :mul2power simplification is automatically applied).
                     * 9: tactic diff-neq; specialized solver for integer arithmetic problems that contain only atoms of the form(<= k x)(<= x k) and(not(= (-x y) k)), where x and y are constants and k is a numberal, and all constants are bounded.
                     * 10: tactic elim01; eliminate 0 - 1 integer variables, replace them by Booleans.
                     * 11: tactic eq2bv; convert integer variables used as finite domain elements to bit-vectors.
                     * 12: tactic factor; polynomial factorization.
                     * 13: tactic fix-dl - var; if goal is in the difference logic fragment, then fix the variable with the most number of occurrences at 0.
                     * 14: tactic fm; eliminate variables using fourier - motzkin elimination.
                     * 15: tactic lia2card; introduce cardinality constraints from 0 - 1 integer.
                     * 16: tactic lia2pb; convert bounded integer variables into a sequence of 0 - 1 variables.
                     * 17: tactic nla2bv; convert a nonlinear arithmetic problem into a bit-vector problem, in most cases the resultant goal is an under approximation and is useul for finding models.
                     * 18: tactic normalize - bounds; replace a variable x with lower bound k <= x with x' = x - k.
                     * 19: tactic pb2bv; convert pseudo-boolean constraints to bit - vectors.
                     * 20: tactic propagate-ineqs; propagate ineqs/ bounds, remove subsumed inequalities.
                     * 21: tactic purify-arith; eliminate unnecessary operators: -, /, div, mod, rem, is- int, to - int, ^, root - objects.
                     * 22: tactic recover-01; recover 0 - 1 variables hidden as Boolean variables.
                     * 23: tactic blast-term-ite; blast term if-then -else by hoisting them.
                     * 24: tactic cofactor-term-ite; eliminate term if-the -else using cofactors.
                     * 25: tactic ctx-simplify; apply contextual simplification rules.
                     * 26: tactic der; destructive equality resolution.
                     * 27: tactic distribute-forall; distribute forall over conjunctions.
                     * 28: tactic elim-term-ite; eliminate term if-then -else by adding fresh auxiliary declarations.
                     * 29: tactic elim-uncnstr; eliminate application containing unconstrained variables.
                     * 30: tactic snf; put goal in skolem normal form.
                     * 31: tactic nnf; put goal in negation normal form.
                     * 32: tactic occf; put goal in one constraint per clause normal form (notes: fails if proof generation is enabled; only clauses are considered).
                     * 33: tactic pb-preprocess; pre - process pseudo - Boolean constraints a la Davis Putnam.
                     * 34: tactic propagate-values; propagate constants.
                     * 35: tactic reduce-args; reduce the number of arguments of function applications, when for all occurrences of a function f the i - th is a value.
                     * 36: tactic simplify; apply simplification rules.
                     * 37: tactic elim-and; convert(and a b) into(not(or(not a)(not b))).
                     * 38: tactic solve-eqs; eliminate variables by solving equations.
                     * 39: tactic split-clause; split a clause in many subgoals.
                     * 40: tactic symmetry-reduce; apply symmetry reduction.
                     * 41: tactic tseitin-cnf; convert goal into CNF using tseitin - like encoding(note: quantifiers are ignored).
                     * 42: tactic tseitin-cnf-core; convert goal into CNF using tseitin - like encoding(note: quantifiers are ignored).This tactic does not apply required simplifications to the input goal like the tseitin - cnf tactic.
                     * 43: tactic skip; do nothing tactic.
                     * 44: tactic fail; always fail tactic.
                     * 45: tactic fail-if-undecided; fail if goal is undecided.
                     * 46: tactic bit-blast; reduce bit-vector expressions into SAT.
                     * 47: tactic bv1-blast; reduce bit-vector expressions into bit - vectors of size 1(notes: only equality, extract and concat are supported).
                     * 48: tactic reduce-bv-size; try to reduce bit - vector sizes using inequalities.
                     * 49: tactic max-bv-sharing; use heuristics to maximize the sharing of bit-vector expressions such as adders and multipliers.
                     * 50: tactic nlsat; (try to) solve goal using a nonlinear arithmetic solver.
                     * 51: tactic qfnra-nlsat; builtin strategy for solving QF_NRA problems using only nlsat.
                     * 52: tactic sat; (try to) solve goal using a SAT solver.
                     * 53: tactic sat-preprocess; Apply SAT solver preprocessing procedures(bounded resolution, Boolean constant propagation, 2 - SAT, subsumption, subsumption resolution).
                     * 54: tactic ctx-solver-simplify; apply solver-based contextual simplification rules.
                     * 55: tactic smt; apply a SAT based SMT solver.
                     * 56: tactic unit-subsume-simplify; unit subsumption simplification.
                     * 57: tactic aig; simplify Boolean structure using AIGs.
                     * 58: tactic horn; apply tactic for horn clauses.
                     * 59: tactic horn-simplify; simplify horn clauses.
                     * 60: tactic qe-light; apply light-weight quantifier elimination.
                     * 61: tactic qe-sat; check satisfiability of quantified formulas using quantifier elimination.
                     * 62: tactic qe; apply quantifier elimination.
                     * 63: tactic vsubst; checks satsifiability of quantifier-free non - linear constraints using virtual substitution.
                     * 64: tactic nl-purify; Decompose goal into pure NL-sat formula and formula over other theories.
                     * 65: tactic macro-finder; Identifies and applies macros.
                     * 66: tactic quasi-macros; Identifies and applies quasi-macros.
                     * 67: tactic bv; builtin strategy for solving BV problems(with quantifiers).
                     * 68: tactic ufbv; builtin strategy for solving UFBV problems(with quantifiers).
                     * 69: tactic fpa2bv; convert floating point numbers to bit-vectors.
                     * 70: tactic qffp; (try to) solve goal using the tactic for QF_FP.
                     * 71: tactic qffpbv; (try to) solve goal using the tactic for QF_FPBV(floats+bit-vectors).
                     * 72: tactic qfbv-sls; (try to) solve using stochastic local search for QF_BV.
                     * 73: tactic subpaving; tactic for testing subpaving module.
                     */
                }
                #endregion Print all Tactics

                BitVecExpr rax = ctx.MkBVConst("rax", 64);
                BitVecExpr rbx = ctx.MkBVConst("rbx", 64);

                BoolExpr a1 = ctx.MkEq(rax, ctx.MkBV(0, 64));
                BoolExpr a2 = ctx.MkEq(rbx, rax);

                Goal goal1 = ctx.MkGoal(true, false, false);
                goal1.Assert(a1, a2);
                Console.WriteLine("goal1=" + goal1 + "; inconsistent=" + goal1.Inconsistent);

                Tactic tactic1 = ctx.MkTactic("simplify");
                // Console.WriteLine("tactic1=" + tactic1.ToString());
                ApplyResult applyResult = tactic1.Apply(goal1);

                Console.WriteLine("applyResult=" + applyResult.ToString() + "; nSubGoals=" + applyResult.NumSubgoals);

                // Console.WriteLine("AsBoolExpr=" + goal1.AsBoolExpr());

                #region Probe Tests
                if (false)
                {
                    Probe  probe1 = ctx.MkProbe("is-qfbv");
                    double d      = probe1.Apply(goal1);
                    Console.WriteLine("d=" + d);
                }
                #endregion Probe Tests
            }
        }
Ejemplo n.º 8
0
        public void Test_Z3_MemWithArray_4()
        {
            #region Definitions
            uint    nBits = 8;
            Context ctx   = new Context();

            BitVecExpr bv_0  = ctx.MkBV(0, nBits);
            BitVecExpr bv_16 = ctx.MkBV(16, nBits);
            BitVecExpr bv_32 = ctx.MkBV(32, nBits);

            BitVecExpr rax = ctx.MkBVConst("RAX!0", nBits);
            BitVecExpr rbx = ctx.MkBVConst("RBX!0", nBits);
            BitVecExpr rcx = ctx.MkBVConst("RCX!0", nBits);
            BitVecExpr rdx = ctx.MkBVConst("RDX!0", nBits);

            IList <(BitVecExpr, BitVecExpr)> writes = new List <(BitVecExpr, BitVecExpr)>();

            Goal      state = ctx.MkGoal();
            ArrayExpr mem   = ctx.MkArrayConst("mem", ctx.MkBitVecSort(nBits), ctx.MkBitVecSort(nBits));

            #endregion

            // Test if overwriting a address works

            Console.WriteLine("mov rbx, 16");
            state.Assert(ctx.MkEq(rbx, bv_16));
            Console.WriteLine("mov rcx, 32");
            state.Assert(ctx.MkEq(rcx, bv_32));
            // Console.WriteLine("mov rax, 0");
            // state.Assert(ctx.MkEq(rax, bv_0));
            Console.WriteLine("mov qword ptr[rax], rbx");
            mem = ctx.MkStore(mem, rax, rbx);
            Console.WriteLine("mov qword ptr[rax], rcx");
            mem = ctx.MkStore(mem, rax, rcx);
            Console.WriteLine("mov rdx, qword ptr[rax]");
            state.Assert(ctx.MkEq(rdx, ctx.MkSelect(mem, rax)));

            #region Write to console

            Solver solver   = ctx.MkSolver();
            Solver solver_U = ctx.MkSolver();

            solver.Assert(state.Formulas);
            Console.WriteLine(string.Empty);
            Console.WriteLine("state1=" + state);
            if (true)
            {
                Tactic tactic1 = ctx.MkTactic("propagate-values");
                Goal   state2  = tactic1.Apply(state).Subgoals[0];
                Console.WriteLine("state2=" + state2.ToString());
            }
            Console.WriteLine(string.Empty);
            Tv[] raxTV = ToolsZ3.GetTvArray(rax, (int)nBits, solver, solver_U, ctx);
            Console.WriteLine("rax = " + ToolsZ3.ToStringBin(raxTV) + " = " + ToolsZ3.ToStringHex(raxTV));
            Tv[] rbxTV = ToolsZ3.GetTvArray(rbx, (int)nBits, solver, solver_U, ctx);
            Console.WriteLine("rbx = " + ToolsZ3.ToStringBin(rbxTV) + " = " + ToolsZ3.ToStringHex(rbxTV));
            Tv[] rcxTV = ToolsZ3.GetTvArray(rcx, (int)nBits, solver, solver_U, ctx);
            Console.WriteLine("rcx = " + ToolsZ3.ToStringBin(rcxTV) + " = " + ToolsZ3.ToStringHex(rcxTV));
            Tv[] rdxTV = ToolsZ3.GetTvArray(rdx, (int)nBits, solver, solver_U, ctx);
            Console.WriteLine("rdx = " + ToolsZ3.ToStringBin(rdxTV) + " = " + ToolsZ3.ToStringHex(rdxTV));
            #endregion
        }