Esempio n. 1
0
    public IntervalStruct(Decimal MinValue, Decimal MaxValue, Func<Decimal, BoxedExpression> ToBoxedExpression)
    {
      Contract.Requires(ToBoxedExpression != null);

      this.IsValid = true;
      this.MinValue = ToBoxedExpression(MinValue);
      this.MaxValue = ToBoxedExpression(MaxValue);
    }
 public List<uint> CausesFor(BoxedExpression expression)
 {
     if (this.preconditions == null || expression == null)
         return (List<uint>)null;
     List<ProofObligation> list;
     if (this.preconditions.TryGetValue (expression, out list))
         return Enumerable.ToList<uint> (Enumerable.Distinct<uint> ((IEnumerable<uint>)list.ConvertAll<uint> ((Converter<ProofObligation, uint>)(obl => obl.ID))));
     else
         return (List<uint>)null;
 }
 public bool TryLookUp(ProofObligation obligation, BoxedExpression expression, out ProofOutcome outcome)
 {
     string s = ((object)expression).ToString ();
     foreach (Tuple<BoxedExpression, string, ProofOutcome, List<ProofObligation>> item in this.inferred) {
         if (item.Item2 == s) {
             item.Item4.Add (obligation);
             outcome = item.Item4;
             return true;
         }
     }
     outcome = ProofOutcome.Top;
     return false;
 }
Esempio n. 4
0
    public List<uint> CausesFor(BoxedExpression exp)
    {
      if (this.preconditions == null || exp == null)
      {
        return null;
      }

      List<ProofObligation> causes;
      if (this.preconditions.TryGetValue(exp, out causes))
      {
        return causes.ConvertAll(obl => obl.ID).Distinct().ToList();
      }

      return null;
    }
                protected bool TryInferSegmentEquality(BoxedExpression index, BoxedExpression body,
                                                       ArrayState state,
                                                       out BoxedExpression leftArray, out BoxedExpression rightArray, out AbstractDomain meet)
                {
                    BinaryOperator bop;

                    BoxedExpression.ArrayIndexExpression <Type> left, right;
                    if (body.TryFindArrayExpBinOpArrayExp(index, out bop, out left, out right) && bop == BinaryOperator.Ceq)
                    {
                        // we know we have the expression "left == right"
                        leftArray  = left.Array;
                        rightArray = right.Array;
                    }

                    leftArray = rightArray = default(BoxedExpression);
                    meet      = default(AbstractDomain);
                    return(false);
                }
        public override BoxedVariable <Variable> UnderlyingVariable(BoxedExpression exp)
        {
            // F: HACK: should be changed
            var embedded = exp.UnderlyingVariable;

            if (embedded is Variable)
            {
                return(new BoxedVariable <Variable>((Variable)exp.UnderlyingVariable));
            }
            else if (exp.UnderlyingVariable is BoxedVariable <Variable> )
            {
                return((BoxedVariable <Variable>)embedded);
            }
            else
            {
                return(new BoxedVariable <Variable>(false));
            }
        }
 protected override BoxedExpression Constant(BoxedExpression original, object type, object value)
 {
     if (value is System.Single)
     {
         types[original]  = FloatType.Float32;
         this.ResultValue = string.Format("((_ asFloat {0}) {1} {2:0.0})", FLOAT32Bits, DEFAULTROUNDING, value);
     }
     else if (value is System.Double)
     {
         types[original]  = FloatType.Float64;
         this.ResultValue = string.Format("((_ asFloat {0}) {1} {2:0.0})", FLOAT64Bits, DEFAULTROUNDING, value);
     }
     else
     {
         this.ResultValue = value.ToString();
     }
     return(original);
 }
                /// <summary>
                /// Given a constraint it returns the InternalExpression representing the given constraints (i.e. key-constr>0)
                /// </summary>
                public static BoxedExpression MakeCondition(BoxedExpression key, AtMostTwoExpressions <BoxedExpression> constr, IDecodeMetaData <Local, Parameter, Method, Field, Property, Type, Attribute, Assembly> mdDecoder)
                {
                    BoxedExpression cons = BoxedExpression.Const(constr.N, mdDecoder.System_Int32, mdDecoder);
                    BoxedExpression vars = constr.Exp1;

                    if (constr.Exp2 != null)
                    {
                        vars = BoxedExpression.Binary(BinaryOperator.Add, vars, constr.Exp2);
                    }

                    BoxedExpression constant = BoxedExpression.Const(constr.Constant, mdDecoder.System_Int32, mdDecoder);
                    BoxedExpression right    = BoxedExpression.Binary(BinaryOperator.Mul, cons, vars);

                    right = BoxedExpression.Binary(BinaryOperator.Add, right, constant);
                    BoxedExpression toBeChecked = BoxedExpression.Binary(BinaryOperator.Cgt, key, right);

                    return(toBeChecked);
                }
        private BoxedExpression DeclareVariable(BoxedExpression original, string type)
        {
            var tmp = original.ToString().Replace(' ', '_');

            this.Info.AddDeclaration(string.Format("(declare-fun {0} () {1})", tmp, type));
            this.ResultValue = tmp;

            if (type == FLOAT32)
            {
                this.types[original] = FloatType.Float32;
            }
            else if (type == FLOAT64)
            {
                this.types[original] = FloatType.Float64;
            }

            return(original);
        }
            public bool TryLookUp(BoxedExpression exp, out ProofOutcome outcome)
            {
                Contract.Requires(exp != null);

                var expStr = exp.ToString();

                foreach (var triple in this.inferred)
                {
                    if (triple.Item2 == expStr)
                    {
                        outcome = triple.Item3;
                        return(true);
                    }
                }
                outcome = ProofOutcome.Top;

                return(false);
            }
Esempio n. 11
0
                public override ArrayState Assume(APC pc, string tag, Variable source, object provenance, ArrayState data)
                {
                    var md   = this.MethodDriver;
                    var cond = BoxedExpression.Convert(md.Context.ExpressionContext.Refine(pc, source), md.ExpressionDecoder).Simplify(md.MetaDataDecoder);

                    Type     type;
                    Variable var;

                    if (cond != null)
                    {
                        // normalize assume(false) !(...)
                        if (tag == "false" && cond.IsUnary && cond.UnaryOp == UnaryOperator.Not)
                        {
                            cond = cond.UnaryArgument;
                        }

                        if (cond.IsAssumeIsAType(out var, out type))
                        {
                            return(data.UpdatePluginAt(this.Id, Select(data).Update(var, type)));
                        }

                        Variable left, right;
                        if (cond.IsBinary && cond.BinaryOp == BinaryOperator.Cobjeq & cond.BinaryLeft.TryGetFrameworkVariable(out left) && cond.BinaryRight.TryGetFrameworkVariable(out right))
                        {
                            var  runtimeTypes = Select(data);
                            var  boxedLeft    = new BoxedVariable <Variable>(left);
                            var  boxedRight   = new BoxedVariable <Variable>(right);
                            Type t;
                            if (runtimeTypes.TryGetValue(left, out t))
                            {
                                runtimeTypes[boxedRight] = t;
                            }
                            if (runtimeTypes.TryGetValue(right, out t))
                            {
                                runtimeTypes[boxedLeft] = t;
                            }

                            return(data.UpdatePluginAt(this.Id, runtimeTypes));
                        }
                    }

                    return(base.Assume(pc, tag, source, provenance, data));
                }
        private bool TryMovingExpressionsAroundComparison(BinaryOperator bop, BoxedExpression left, BoxedExpression c, BoxedExpression original)
        {
            if (bop.IsComparisonBinaryOperator())
            {
                BinaryOperator  bopLeft;
                BoxedExpression a, b;
                if (left.IsBinaryExpression(out bopLeft, out a, out b) && (bopLeft == BinaryOperator.Add || bopLeft == BinaryOperator.Add_Ovf || bopLeft == BinaryOperator.Add_Ovf_Un))
                {
                    var aAddbSubc = BoxedExpression.Binary(BinaryOperator.Sub, left, c);
                    aAddbSubc.Dispatch(this);
                    if (this.PartialResult != null)
                    {
                        return(NotifyOkAndSetResult(BoxedExpression.Binary(bop, aAddbSubc, ZeroExp.Value)));
                    }
                }
            }

            return(NotifyNotOk(original));
        }
Esempio n. 13
0
    public bool TryLookUp(ProofObligation obl, BoxedExpression exp, out ProofOutcome outcome)
    {
      Contract.Requires(obl != null);
      Contract.Requires(exp != null);

      var expStr = exp.ToString();
      foreach (var quad in this.inferred)
      {
        if (quad.Item2 == expStr)
        {
          quad.Item4.Add(obl);
          outcome = quad.Item3;
          return true;
        }
      }
      outcome = ProofOutcome.Top;

      return false;
    }
Esempio n. 14
0
        protected override BoxedExpression Variable(BoxedExpression original, object var, PathElement[] path)
        {
            if (var is Variabl && path != null && path.Length > 0)
            {
                var varAsV      = (Variabl)var;
                var pathAsFList = path.ToFList();

                if (this.MethodDriver.Context.ValueContext.IsRootedInParameter(pathAsFList) && path[0].AssumeNotNull().ToString() == "this")
                {
                    return(BoxedExpression.VarCast(var, path, default(Type), this.castTo));
                }
                else
                {
                    return(original);
                }
            }

            return(null);
        }
                public override DisjunctiveRefinement Assume(APC pc, string tag, Variable source, object provenance, DisjunctiveRefinement data)
                {
                    Contract.Assume(data != null);
                    this.InferExceptionHandlers(pc);

                    var refinedExp = new LazyEval <BoxedExpression>(
                        () => BoxedExpression.Convert(this.Context.ExpressionContext.Refine(pc, source), this.MethodDriver.ExpressionDecoder, MAXDEPTH));

                    if (tag != "false")
                    {
                        var toRefine = source;

                        // in clousot1 we refine "assume refinedExp".
                        // in clousot2 we refinedExp may be exp != 0 and in this case we refine "assume exp"
                        if (!this.MethodDriver.SyntacticComplexity.TooManyJoinsForBackwardsChecking &&
                            refinedExp.Value != null && CanRefineAVariableTruthValue(refinedExp.Value, ref toRefine))
                        {
                            Log("Trying to refine the variable {0} to one containing logical connectives", refinedExp.Value.UnderlyingVariable.ToString);

                            BoxedExpression refinedExpWithConnectives;
                            if (TryToBoxedExpressionWithBooleanConnectives(pc, tag, toRefine, false,
                                                                           TopNumericalDomain <BoxedVariable <Variable>, BoxedExpression> .Singleton, out refinedExpWithConnectives))
                            {
                                Log("Succeeded. Got {0}", refinedExpWithConnectives.ToString);

                                data[new BoxedVariable <Variable>(source)] = new SetOfConstraints <BoxedExpression>(refinedExpWithConnectives);
                            }
                        }
                    }

                    APC pcForExpression;

                    if (!this.FirstViewAt.TryGetValue(source, out pcForExpression))
                    {
                        pcForExpression = pc;
                    }

                    this.Tests.Add(new SyntacticTest(SyntacticTest.Polarity.Assume, pcForExpression, tag, refinedExp));

                    // We do not call the base Assume as it performs too many things not needed here
                    return(data);
                }
Esempio n. 16
0
        public bool TryLookUp(ProofObligation obl, BoxedExpression exp, out ProofOutcome outcome)
        {
            Contract.Requires(obl != null);
            Contract.Requires(exp != null);

            var expStr = exp.ToString();

            foreach (var quad in this.inferred)
            {
                if (quad.Item2 == expStr)
                {
                    quad.Item4.Add(obl);
                    outcome = quad.Item3;
                    return(true);
                }
            }
            outcome = ProofOutcome.Top;

            return(false);
        }
        private Witness MakeUpAWitness(APC pc, WarningType type, BoxedExpression precondition, KeyValuePair <BoxedExpression, IEnumerable <MinimalProofObligation> > pair)
        {
            uint?id;
            var  provenance = pair.Value;

            if (provenance != null && provenance.Any())
            {
                id = provenance.First().ID;
            }
            else
            {
                id = null;
            }

            var md             = this.mdriver;
            var warningContext = WarningContextFetcher.InferContext(pc, precondition, md.Context, md.MetaDataDecoder.IsBoolean)
                                 .Where(wc => wc.Type != WarningContext.ContextType.ViaParameterUnmodified); // very likely we will have unmodified parameters, and we do not want them to count in the score

            return(new Witness(id, type, ProofOutcome.Top, pc, warningContext));
        }
        private bool TryDividingByConstnatDoNotOverflow(BinaryOperator bop, BoxedExpression left, BoxedExpression right, BoxedExpression original)
        {
            if (bop == BinaryOperator.Div || bop == BinaryOperator.Div_Un || bop == BinaryOperator.Rem || bop == BinaryOperator.Rem_Un)
            {
                int value;
                if (right.IsConstantInt(out value) && value != 0)
                {
                    BoxedExpression newLeft;
                    left.Dispatch(this);
                    if ((newLeft = this.PartialResult) != null)
                    {
                        this.NotifyOkAndSetResult(BoxedExpression.Binary(bop, newLeft, right, original.UnderlyingVariable));
                        return(true);
                    }
                }
            }

            this.PartialResult = null;
            return(false);
        }
Esempio n. 19
0
                                static bool TryEvaluateToConstant (APC pc, BoxedExpression e, out long result)
                                {
                                        int res;
                                        if (e.IsConstantIntOrNull (out res))
                                                return true.With (res, out result);

                                        long argValue;
                                        if (e.IsUnary && TryEvaluateToConstant (pc, e.UnaryArgument, out argValue)) {
                                                switch (e.UnaryOperator) {
                                                case UnaryOperator.Neg:
                                                        return true.With (-argValue, out result);
                                                case UnaryOperator.Not:
                                                        return true.With (argValue != 0 ? 0L : 1L, out result);
                                                default:
                                                        throw new ArgumentOutOfRangeException ();
                                                }
                                        }

                                        return false.Without (out result);
                                }
        public void ArrayIndex <Type>(Type type, BoxedExpression array, BoxedExpression index, BoxedExpression original)
        {
            BoxedExpression newArray, newIndex;

            array.Dispatch(this);
            if (this.PartialResult != null)
            {
                newArray = this.PartialResult;
                index.Dispatch(this);
                if (this.PartialResult != null)
                {
                    newIndex = this.PartialResult;
                    NotifyOkAndSetResult(new BoxedExpression.ArrayIndexExpression <Type>(newArray, newIndex, type));

                    return;
                }
            }

            NotifyNotOk(original);
        }
        private bool TrySemiSumRewriting(BinaryOperator bop, BoxedExpression left, BoxedExpression right, BoxedExpression original)
        {
            // TODO: case when bop is negative
            if (bop == BinaryOperator.Div || bop == BinaryOperator.Div_Un)
            {
                BinaryOperator  bopLeft;
                BoxedExpression a, b;
                int             value;
                // match (leftleft + leftRight) / 2
                // TODO: make it for even numbers
                if (left.IsBinaryExpression(out bopLeft, out a, out b) &&
                    (bopLeft == BinaryOperator.Add || bopLeft == BinaryOperator.Add_Ovf || bopLeft == BinaryOperator.Add_Ovf_Un) &&
                    right.IsConstantInt(out value) && value == 2
                    )
                {
                    BoxedExpression aPrime, bPrime;
                    a.Dispatch(this);
                    if ((aPrime = this.PartialResult) != null)
                    {
                        b.Dispatch(this);
                        if ((bPrime = this.PartialResult) != null)
                        {
                            a = null; b = null;
                            var RightSubLeft = BoxedExpression.Binary(BinaryOperator.Sub, bPrime, aPrime);
                            if (!this.OverflowOracle.CanUnderflow(this.PC, RightSubLeft))
                            {
                                return(NotifyOkAndSetResult(BoxedExpression.Binary(BinaryOperator.Add, aPrime, BoxedExpression.Binary(bop, RightSubLeft, right))));
                            }

                            var LeftSubRight = BoxedExpression.Binary(BinaryOperator.Sub, aPrime, bPrime);
                            if (!this.OverflowOracle.CanUnderflow(this.PC, LeftSubRight))
                            {
                                return(NotifyOkAndSetResult(BoxedExpression.Binary(BinaryOperator.Add, bPrime, BoxedExpression.Binary(bop, LeftSubRight, right))));
                            }
                        }
                    }
                }
            }

            return(NotifyNotOk(original));
        }
Esempio n. 22
0
            public bool TryCollectWitnesses(out bool mayReturnNull)
            {
                Trace("Try to collect a witness for the return value");

                mayReturnNull = false;
                if (this.timeout.HasAlreadyTimeOut)
                {
                    return(false);
                }

                try
                {
                    this.timeout.Start();
                    Variable retVar;

                    if (this.Mdriver.Context.ValueContext.TryResultValue(this.pcCondition, out retVar))
                    {
                        var initialState = new Witness(BoxedExpression.Var(retVar));
                        Visit(this.pcCondition, initialState, 0);
                        if (this.Found)
                        {
                            mayReturnNull = this.Result.State == Witness.Kind.ReturnNull || this.Result.State == Witness.Kind.ReturnNullIndirectly;
                            return(true);
                        }
                    }
                }
                catch (TimeoutExceptionFixpointComputation)
                {
                    return(false);
                }
                catch (AccessViolationException)
                {
                    Console.WriteLine("Internal error in CLR: memory is corrupted? -- Continuing as we where simply searching for a witness");
                }
                finally
                {
                    this.timeout.Stop();
                }

                return(false);
            }
        public override bool IsNaN(BoxedExpression exp)
        {
            if (!exp.IsConstant)
            {
                return(false);
            }

            object constant = exp.Constant;

            if (constant is float)
            {
                return(((float)constant).Equals(float.NaN));
            }

            if (constant is double)
            {
                return(((double)constant).Equals(double.NaN));
            }

            return(false);
        }
 private static bool CanMergeTogether(BoxedExpression condition, BoxedExpression premise, out BoxedExpression joined)
 {
     BinaryOperator binaryOp_1, binaryOp_2;
     BoxedExpression left_1, left_2, right_1, right_2;
     if (condition.IsBinaryExpression(out binaryOp_1, out left_1, out right_1) && premise.IsBinaryExpression(out binaryOp_2, out left_2, out right_2))
     {
         condition = premise = (BoxedExpression) null;
         BoxedExpression left_3 = BoxedExpressionExtensions.StripIfCastOfArrayLength(left_1);
         BoxedExpression right_3 = BoxedExpressionExtensions.StripIfCastOfArrayLength(right_1);
         BoxedExpression boxedExpression_1 = BoxedExpressionExtensions.StripIfCastOfArrayLength(left_2);
         BoxedExpression boxedExpression_2 = BoxedExpressionExtensions.StripIfCastOfArrayLength(right_2);
         if (binaryOp_1 == BinaryOperator.Clt && binaryOp_2 == BinaryOperator.Ceq || binaryOp_1 == BinaryOperator.Ceq && binaryOp_2 == BinaryOperator.Clt)
         {
           	if (left_3.Equals((object) boxedExpression_1) && right_3.Equals((object) boxedExpression_2))
           	{
                 joined = BoxedExpression.Binary(BinaryOperator.Cle, left_3, right_3, (object) null);
                 return true;
           	}
           	else if (left_3.Equals((object) boxedExpression_2) && right_3.Equals((object) boxedExpression_1))
           	{
                 joined = BoxedExpression.Binary(binaryOp_1 == BinaryOperator.Ceq ? BinaryOperator.Cge : BinaryOperator.Cle, left_3, right_3, (object) null);
                 return true;
           	}
         }
         if (binaryOp_1 == BinaryOperator.Cgt && binaryOp_2 == BinaryOperator.Ceq || binaryOp_1 == BinaryOperator.Ceq && binaryOp_2 == BinaryOperator.Cgt)
         {
           if (left_3.Equals((object) boxedExpression_1) && right_3.Equals((object) boxedExpression_2))
           {
             joined = BoxedExpression.Binary(BinaryOperator.Cge, left_3, right_3, (object) null);
             return true;
           }
           else if (left_3.Equals((object) boxedExpression_2) && right_3.Equals((object) boxedExpression_1))
           {
             joined = BoxedExpression.Binary(binaryOp_1 == BinaryOperator.Ceq ? BinaryOperator.Cle : BinaryOperator.Cge, left_3, right_3, (object) null);
             return true;
           }
         }
     }
     return false;
 }
        private bool TryComparisonDoNotOverflow(BinaryOperator bop, BoxedExpression left, BoxedExpression right, BoxedExpression original)
        {
            BoxedExpression newLeft, newRight;

            if (bop.IsComparisonBinaryOperator())
            {
                left.Dispatch(this);
                if ((newLeft = this.PartialResult) != null)
                {
                    right.Dispatch(this);
                    if ((newRight = this.PartialResult) != null)
                    {
                        // ok no overflow!
                        NotifyOkAndSetResult(BoxedExpression.Binary(bop, newLeft, newRight, original.UnderlyingVariable));
                        return(true);
                    }
                }
            }

            this.PartialResult = null;
            return(false);
        }
Esempio n. 26
0
 private BoxedExpression SubstituteThis(BoxedExpression be, Parameter from, Parameter to)
 {
     return(be.Substitute <object>((_, variableExpression) =>
     {
         var accessPath = SubstituteThis(variableExpression.AccessPath, from, to);
         if (accessPath == variableExpression.AccessPath)
         {
             return variableExpression;
         }
         BoxedExpression writableBytes;
         object type;
         if (!variableExpression.TryGetType(out type))
         {
             type = null;
         }
         if (variableExpression.TryGetAssociatedInfo(AssociatedInfo.WritableBytes, out writableBytes))
         {
             return new BoxedExpression.VariableExpression(variableExpression.UnderlyingVariable, accessPath, writableBytes, type);
         }
         return new BoxedExpression.VariableExpression(variableExpression.UnderlyingVariable, accessPath, type);
     }));
 }
Esempio n. 27
0
            // F: not the most efficient way of doing it - should replace with a lookup table
            private bool IsExpressionCheckedAt(APC pc, BoxedExpression exp)
            {
                Contract.Requires(exp != null);

                var obligationsAtPC = new List <ProofObligationBase <BoxedExpression, Variable> >();

                foreach (var obl in obligations)
                {
                    if (obl.PCWithProofObligations(pc, obligationsAtPC))
                    {
                        foreach (var particularObl in obligationsAtPC)
                        {
                            if (exp.Equals(particularObl.Condition))
                            {
                                return(true);
                            }
                        }
                    }
                }

                return(false);
            }
        private bool TryRemovingAddInComparison(BinaryOperator bop, BoxedExpression left, BoxedExpression c, BoxedExpression original)
        {
            if (bop.IsComparisonBinaryOperator())
            {
                BinaryOperator  bopLeft;
                BoxedExpression a, b;
                // match a + b
                if (left.IsBinaryExpression(out bopLeft, out a, out b) && (bopLeft == BinaryOperator.Add || bopLeft == BinaryOperator.Add_Ovf || bopLeft == BinaryOperator.Add_Ovf_Un))
                {
                    BoxedExpression aPrime, bPrime, cPrime;
                    a.Dispatch(this);
                    if ((aPrime = this.PartialResult) != null)
                    {
                        b.Dispatch(this);
                        if ((bPrime = this.PartialResult) != null)
                        {
                            c.Dispatch(this);
                            if ((cPrime = this.PartialResult) != null)
                            {
                                a = null; b = null; c = null;
                                var RightSubB = BoxedExpression.Binary(BinaryOperator.Sub, cPrime, bPrime);
                                if (!this.OverflowOracle.CanUnderflow(this.PC, RightSubB))
                                {
                                    return(NotifyOkAndSetResult(BoxedExpression.Binary(bop, aPrime, RightSubB)));
                                }

                                var RightSubA = BoxedExpression.Binary(BinaryOperator.Sub, cPrime, aPrime);
                                if (!this.OverflowOracle.CanUnderflow(this.PC, RightSubA))
                                {
                                    return(NotifyOkAndSetResult(BoxedExpression.Binary(bop, bPrime, RightSubA)));
                                }
                            }
                        }
                    }
                }
            }

            return(NotifyNotOk(original));
        }
        protected virtual BoxedExpression Binary(BoxedExpression original, BinaryOperator binaryOperator, BoxedExpression left, BoxedExpression right)
        {
            Contract.Requires(original != null);
            Contract.Requires(left != null);
            Contract.Requires(right != null);

            var recLeft = this.Visit(left);

            if (recLeft == null)
            {
                return(recLeft);
            }

            var recRight = this.Visit(right);

            if (recRight == null)
            {
                return(recRight);
            }

            return(BoxedExpression.Binary(binaryOperator, recLeft, recRight, original.UnderlyingVariable));
        }
Esempio n. 30
0
            public bool CheckPreconditionAdmissibility(BoxedExpression candidate)
            {
                Contract.Requires(candidate != null);

                var closure = this.MethodDriver.HybridLayer.CreateForward(this, new DFAOptions()
                {
                    Trace = MethodDriver.Options.TraceDFA
                }, null);

                closure(new AbstractValue(candidate));

                AbstractValue exitValue;

                var result = !FoundLoop                                                                                          // No loop with an unchecked condition was found
                             &&
                             (!this.fixpointInfo.PreState(this.MethodDriver.Context.MethodContext.CFG.NormalExit, out exitValue) // The method exit is unreachable
                              ||
                              exitValue.IsChecked                                                                                // or, if it is reachable it is checked at the end
                             );

                return(result);
            }
        private static bool BothWithNegativeSigns(BoxedExpression left, BoxedExpression right, out BoxedExpression minusLeft, out BoxedExpression minusRight, ConstFor GetConst)
        {
            if (left.IsUnary && left.UnaryOp == UnaryOperator.Neg)
            {
                // case -left, -right
                if (right.IsUnary && right.UnaryOp == UnaryOperator.Neg)
                {
                    minusLeft  = left.UnaryArgument;
                    minusRight = right.UnaryArgument;

                    return(true);
                }

                Int32 value;
                // case -left, constant
                if (right.IsConstant && TryInt32Constant(right.Constant, out value))
                {
                    minusLeft  = left.UnaryArgument;
                    minusRight = GetConst(-value);

                    return(true);
                }
            }
            else if (right.IsUnary && right.UnaryOp == UnaryOperator.Neg)
            {
                Int32 value;
                // case constant, -right
                if (left.IsConstant && TryInt32Constant(left.Constant, out value))
                {
                    minusLeft  = GetConst(-value);
                    minusRight = right.UnaryArgument;

                    return(true);
                }
            }

            minusLeft = minusRight = null;
            return(false);
        }
                /// <summary>
                /// It checks for each dropped constraints if it can be validated by the intervals domain state
                /// </summary>
                private void addConstraints(IntervalsForUnsafeCode intervalsPrev, StripeForUnsafeCode thiscloned, StripeForUnsafeCode result)
                {
                    StripeForUnsafeCode dropped = (StripeForUnsafeCode)this.Factory();

                    ExtractDroppedConstraints(thiscloned, result, dropped);

                    foreach (BoxedExpression key in dropped.Keys)
                    {
                        foreach (AtMostTwoExpressions <BoxedExpression> constr in dropped[key].EmbeddedValues_Unsafe)
                        {
                            if (!constr.IsTop && !constr.IsBottom)
                            {
                                BoxedExpression           toBeChecked = StripeWithIntervalsForUnsafeCode.MakeCondition(key, constr, this.mdDecoder);
                                FlatAbstractDomain <bool> test        = intervalsPrev.CheckIfHolds(toBeChecked);
                                if (!test.IsBottom && !test.IsTop && test.BoxedElement == true)
                                {
                                    result.AddConstraint(key, constr);
                                }
                            }
                        }
                    }
                }
        protected virtual BoxedExpression ArrayIndex <Typ>(BoxedExpression original, Typ type, BoxedExpression array, BoxedExpression index)
        {
            Contract.Requires(original != null);
            Contract.Requires(array != null);
            Contract.Requires(index != null);

            var arrayRec = this.Visit(array);

            if (arrayRec == null)
            {
                return(null);
            }

            var indexRec = this.Visit(index);

            if (indexRec == null)
            {
                return(null);
            }

            return(BoxedExpression.ArrayIndex(arrayRec, indexRec, (Typ)type));
        }
                private BoxedExpression RemoveKnownFacts(BoxedExpression original, Predicate <BoxedExpression> isKnown)
                {
                    if (isKnown == null)
                    {
                        return(original);
                    }

                    var             splitted = original.SplitConjunctions();
                    BoxedExpression result   = null;

                    foreach (var exp in splitted)
                    {
                        if (exp == null || isKnown(exp))
                        {
                            continue;
                        }

                        result = result == null ? exp : BoxedExpression.Binary(BinaryOperator.LogicalAnd, result, exp);
                    }

                    return(result);
                }
Esempio n. 35
0
                    private BoxedExpression ToBoxedExpressionTime(APC pc, Variable var)
                    {
                        Contract.Requires(this.fullMap != null);

                        Contract.Ensures(Contract.Result <BoxedExpression>() != null);

                        BoxedExpression result;

                        var key = new Pair <APC, Variable>(pc, var);

                        if (this.fullMap.TryGetValue(key, out result))
                        {
                            Contract.Assume(result != null);
                            return(result);
                        }
                        else
                        {
                            result            = BoxedExpression.For(this.context.Refine(pc, var), this.outdecoder);
                            this.fullMap[key] = result;
                        }

                        return(result);
                    }
Esempio n. 36
0
                    private BoxedExpression ToBoxedExpressionMem(APC pc, Variable var)
                    {
                        Contract.Requires(this.weakrefMap != null);
                        Contract.Ensures(Contract.Result <BoxedExpression>() != null);

                        BoxedExpression result;
                        WeakReference   wr;

                        var key = new Pair <APC, Variable>(pc, var);

                        if (this.weakrefMap.TryGetValue(key, out wr) && wr != null && wr.IsAlive)
                        {
                            result = wr.Target as BoxedExpression;
                            Contract.Assume(result != null);
                        }
                        else
                        {
                            result = BoxedExpression.For(this.context.Refine(pc, var), this.outdecoder);
                            this.weakrefMap[key] = new WeakReference(result);
                        }

                        return(result);
                    }
 public void Add(ProofObligation obligation, BoxedExpression expression, ProofOutcome outcome)
 {
     this.inferred.Add (new Tuple<BoxedExpression, string, ProofOutcome, List<ProofObligation>> (expression, ((object)expression).ToString (), outcome, new List<ProofObligation> (){obligation}));
     this.preconditions = (Dictionary<BoxedExpression, List<ProofObligation>>)null;
 }
 public override void Unary(UnaryOperator unaryOperator, BoxedExpression argument, BoxedExpression parent)
 {
     argument.Dispatch ((IBoxedExpressionController)this);
 }
 private PreconditionDB.ComparisonOutputType SyntacticComparison(BoxedExpression left, BoxedExpression right)
 {
     if (left.Equals ((object)right)) {
         return PreconditionDB.ComparisonOutputType.Equal;
     }
     int num1, num2;
     if (BoxedExpressionExtensions.IsConstantInt (left, out num1) && BoxedExpressionExtensions.IsConstantInt (right, out num2)) {
         if (num1 == num2)
             return PreconditionDB.ComparisonOutputType.Equal;
         if (num1 < num2)
             return PreconditionDB.ComparisonOutputType.LessEqual;
         if (num1 > num2)
             return PreconditionDB.ComparisonOutputType.GreaterEqual;
     }
     BinaryOperator binaryOp_1, binaryOp_2;
     BoxedExpression left_1, left_2, right_1, right_2;
     bool flag_1 = left.IsBinaryExpression (out binaryOp_1, out left_1, out right_1);
     bool flag_2 = right.IsBinaryExpression (out binaryOp_2, out left_2, out right_2);
     if (flag_1 && flag_2 && binaryOp_1 == binaryOp_2) {
         if (binaryOp_1 == BinaryOperator.Add)
             return this.Join (this.SyntacticComparison (left_1, left_2), this.SyntacticComparison (right_1, right_2));
         else
             return PreconditionDB.ComparisonOutputType.Top;
     } else if (flag_1 && left_1.Equals ((object)right)) {
         if (binaryOp_1 == BinaryOperator.Add && BoxedExpressionExtensions.IsConstantInt (right_1, out num1)) {
             if (num1 == 0)
                 return PreconditionDB.ComparisonOutputType.Equal;
             if (num1 > 0)
                 return PreconditionDB.ComparisonOutputType.GreaterEqual;
             if (num1 < 0)
                 return PreconditionDB.ComparisonOutputType.LessEqual;
         }
         return PreconditionDB.ComparisonOutputType.Top;
     } else {
         if (!flag_2 || !left_2.Equals ((object)left) || (binaryOp_2 != BinaryOperator.Add || !BoxedExpressionExtensions.IsConstantInt (right_2, out num2)))
             return PreconditionDB.ComparisonOutputType.Top;
         if (num2 == 0)
             return PreconditionDB.ComparisonOutputType.Equal;
         if (num2 > 0)
             return PreconditionDB.ComparisonOutputType.GreaterEqual;
         return num2 < 0 ? PreconditionDB.ComparisonOutputType.LessEqual : PreconditionDB.ComparisonOutputType.Top;
     }
     return PreconditionDB.ComparisonOutputType.Top;
 }
Esempio n. 40
0
 public PC(BoxedExpression expr, int index)
 {
     this.Node = expr;
         this.Index = index;
 }
 public IntervalStruct(Decimal MinValue, Decimal MaxValue, Func<Decimal, BoxedExpression> ToBoxedExpression)
 {
     this.IsValid = true;
       this.MinValue = ToBoxedExpression(MinValue);
       this.MaxValue = ToBoxedExpression(MaxValue);
 }
 public SimpleInferredPrecondition(BoxedExpression expr, ExpressionInPreStateKind kind, bool isSufficient)
 {
     this.expr = expr;
       this.kind = kind;
       this.IsSufficientForTheWarning = isSufficient;
 }
 public MinimalProofObligation(APC pc, BoxedExpression condition, string obligationName, object provenance)
     : base(pc, provenance)
 {
     this.condition = condition;
       		this.obligationName = obligationName;
 }
Esempio n. 44
0
    private SyntacticComparisonOutcome SyntacticComparison(BoxedExpression left, BoxedExpression right)
    {
      Contract.Requires(left != null);
      Contract.Requires(right != null);

      if (left.Equals(right))
      {
        return SyntacticComparisonOutcome.Equal;
      }

      int leftK, rightK;
      if (left.IsConstantInt(out leftK) && right.IsConstantInt(out rightK))
      {
        if (leftK == rightK)
          return SyntacticComparisonOutcome.Equal;
        if (leftK < rightK)
          return SyntacticComparisonOutcome.LessEqual;
        if (leftK > rightK)
          return SyntacticComparisonOutcome.GreaterEqual;
      }

      BinaryOperator bopLeft, bopRight;
      BoxedExpression bLeftLeft, bLeftRight, bRightLeft, bRightRight;

      var isLeftBin = left.IsBinaryExpression(out bopLeft, out bLeftLeft, out bLeftRight);
      var isRightBin = right.IsBinaryExpression(out bopRight, out bRightLeft, out bRightRight);

      // case "a + b" compared with "a' + b'"
      if (isLeftBin && isRightBin && bopLeft == bopRight)
      {
        switch (bopLeft)
        {
          case BinaryOperator.Add:
            {
              var compareLeft = SyntacticComparison(bLeftLeft, bRightLeft);
              var compareRight = SyntacticComparison(bLeftRight, bRightRight);

              return Join(compareLeft, compareRight);
            }

          // TODO: other cases?
        }
        return SyntacticComparisonOutcome.Top;
      }

      // case "a + b" compared with "a"
      if (isLeftBin && bLeftLeft.Equals(right))
      {
        switch (bopLeft)
        {
          case BinaryOperator.Add:
            {
              if (bLeftRight.IsConstantInt(out leftK))
              {
                if (leftK == 0)
                  return SyntacticComparisonOutcome.Equal;
                if (leftK > 0)
                  return SyntacticComparisonOutcome.GreaterEqual;
                if (leftK < 0)
                  return SyntacticComparisonOutcome.LessEqual;
              }
              break;
            }
        }
        return SyntacticComparisonOutcome.Top;
      }

      // case "a" compared with "a+b"
      if (isRightBin && bRightLeft.Equals(left))
      {
        switch (bopRight)
        {
          case BinaryOperator.Add:
            {
              if (bRightRight.IsConstantInt(out rightK))
              {
                if (rightK == 0)
                  return SyntacticComparisonOutcome.Equal;
                if (rightK > 0)
                  return SyntacticComparisonOutcome.GreaterEqual;
                if (rightK < 0)
                  return SyntacticComparisonOutcome.LessEqual;
              }
              break;
            }
        }
        return SyntacticComparisonOutcome.Top;
      }



      return SyntacticComparisonOutcome.Top;
    }
Esempio n. 45
0
    private void Add(
      Dictionary<Tuple<BinaryOperator, BoxedExpression>, List<Tuple<BoxedExpression, BoxedExpression, List<ProofObligation>>>> where,
      Tuple<BinaryOperator, BoxedExpression> key, BoxedExpression value, BoxedExpression precondition, List<ProofObligation> obl)
    {
      Contract.Requires(where != null);
      Contract.Requires(key != null);
      Contract.Requires(value != null);
      Contract.Requires(precondition != null);
      Contract.Requires(obl != null);

      List<Tuple<BoxedExpression, BoxedExpression, List<ProofObligation>>> values;
      var triplet = new Tuple<BoxedExpression, BoxedExpression, List<ProofObligation>>(value, precondition, obl);
      if (where.TryGetValue(key, out values))
      {
        Contract.Assume(values != null);
        // use aliasing here to save one lookup
        values.Add(triplet);
      }
      else
      {
        values = new List<Tuple<BoxedExpression, BoxedExpression, List<ProofObligation>>>() { triplet };
        where[key] = values;
      }
    }
Esempio n. 46
0
      /// <summary>
      ///  left ==> right ?
      /// </summary>
    static private bool Implies(BoxedExpression left, BoxedExpression right)
    {
      Contract.Requires(left != null);
      Contract.Requires(right != null);

      BinaryOperator leftOp, rightOp;
      BoxedExpression leftLeft, leftRight, rightLeft, rightRight;

      if (left.IsBinaryExpression(out leftOp, out leftLeft, out leftRight) && right.IsBinaryExpression(out rightOp, out rightLeft, out rightRight))
      {
        #region Equality
        switch (rightOp)
        {
          case BinaryOperator.Ceq:
            {
              if ((leftLeft.Equals(rightLeft) && leftRight.Equals(rightRight)) || (leftLeft.Equals(rightRight) && leftRight.Equals(rightLeft)))
              {
                return new BinaryOperator[] { BinaryOperator.Ceq, BinaryOperator.Cge, BinaryOperator.Cge_Un, BinaryOperator.Cle, BinaryOperator.Cle_Un }.Contains(leftOp);
              }

              return false;
            }

          default:
            {
              break;
            }
        }
        #endregion

        #region Other cases

        // k1 op1 exp and k2 op2 exp
        int k1, k2;
        if (leftRight.Equals(rightRight) && leftLeft.IsConstantInt(out k1) && rightLeft.IsConstantInt(out k2))
        {
          // k1 <= exp and k2 < exp
          if (leftOp == BinaryOperator.Cle && rightOp == BinaryOperator.Clt)
          {
            return k1 < k2;
          }
        }

        // todo: other cases

        #endregion

      }

      return false;
    }
Esempio n. 47
0
    static private bool PremiseIsImpliedByOtherPreconditions(BoxedExpression premises, BoxedExpression condition, IEnumerable<BoxedExpression> knownPreconditions, out BoxedExpression newPrecondition)
    {
      Contract.Requires(premises != null);
      Contract.Requires(knownPreconditions != null);
      Contract.Requires(condition != null);

      Contract.Ensures(!Contract.Result<bool>() || Contract.ValueAtReturn(out newPrecondition) != null);

      if(!knownPreconditions.Any())
      {
        newPrecondition = null;
        return false;
      }

      var oldPremises = premises.SplitDisjunctions();
      var newPremises = new List<BoxedExpression>();

      foreach (var disjunct in oldPremises)
      {
        if (knownPreconditions.Contains(disjunct.Negate()))
        {
          continue;
        }
        else
        {
          newPremises.Add(disjunct);
        }
      }

      if (oldPremises.Count == newPremises.Count)
      {
        newPrecondition = null;
        return false;
      }
      else
      {
        if (newPremises.Count == 0)
        {
          newPrecondition = condition;
        }
        else
        {
          var newPremisesAsExp = newPremises.ToDisjunction();
          if (newPremisesAsExp != null)
          {
            newPrecondition = BoxedExpression.Binary(BinaryOperator.LogicalOr, newPremisesAsExp, condition);
          }
          else
          {
            newPrecondition = condition;
          }
        }
        return true;
      }
    }
Esempio n. 48
0
    static private bool CanMergeTogether(BoxedExpression condition, BoxedExpression premise, out BoxedExpression joined)
    {
      Contract.Requires(condition != null);
      Contract.Requires(premise != null);
      Contract.Ensures(!Contract.Result<bool>() || Contract.ValueAtReturn(out joined) != null);

      BinaryOperator bopCondition, bopPremise;
      BoxedExpression condition1, condition2, premise1, premise2;
      if (condition.IsBinaryExpression(out bopCondition, out condition1, out condition2) && premise.IsBinaryExpression(out bopPremise, out premise1, out premise2))
      {
        condition = premise = null; // kill the parameters, just to make sure we do not do errors afterwards

        // remove the (int)a.Length, if any
        condition1 = condition1.StripIfCastOfArrayLength();
        condition2 = condition2.StripIfCastOfArrayLength();
        premise1 = premise1.StripIfCastOfArrayLength();
        premise2 = premise2.StripIfCastOfArrayLength();

        // (< || ==) or ( == || <)
        if ((bopCondition == BinaryOperator.Clt && bopPremise == BinaryOperator.Ceq) 
          ||(bopCondition == BinaryOperator.Ceq && bopPremise == BinaryOperator.Clt))
        {
          if (condition1.Equals(premise1) && condition2.Equals(premise2))
          {
            joined = BoxedExpression.Binary(BinaryOperator.Cle, condition1, condition2);
            return true;
          }

          if (condition1.Equals(premise2) && condition2.Equals(premise1))
          {
            joined = BoxedExpression.Binary(
              bopCondition == BinaryOperator.Ceq
              ? BinaryOperator.Cge   // a == b || b < a   ==> a >= b
              : BinaryOperator.Cle,  // a < b  || b == a  ==> a <= b
              condition1, condition2);
            
            return true;
          }

        }

        // (> || ==) or ( == || >)
        if ((bopCondition == BinaryOperator.Cgt && bopPremise == BinaryOperator.Ceq)
          || (bopCondition == BinaryOperator.Ceq && bopPremise == BinaryOperator.Cgt))
        {
          if (condition1.Equals(premise1) && condition2.Equals(premise2))
          {
            joined = BoxedExpression.Binary(BinaryOperator.Cge, condition1, condition2);
            return true;
          }

          if (condition1.Equals(premise2) && condition2.Equals(premise1))
          {
            joined = BoxedExpression.Binary(
              bopCondition == BinaryOperator.Ceq
              ? BinaryOperator.Cle   // a == b || b > a   ==> a <= b
              : BinaryOperator.Cge,  // a > b  || b == a  ==> a >= b
              condition1, condition2);

            return true;
          }
        }

        // a  < b ||  b < a -- > a != b 
        if(bopCondition == BinaryOperator.Clt && bopPremise == BinaryOperator.Clt)
        {
          // a  < b ||  b < a -- > a != b 
          if(condition1.Equals(premise2) && condition2.Equals(premise1))
          {
            joined = BoxedExpression.Binary(BinaryOperator.Cne_Un, condition1, condition2);
            return true;
          }
        }

      }

      joined = null;
      return false;
    }
Esempio n. 49
0
    public void Add(ProofObligation obl, BoxedExpression exp, ProofOutcome outcome)
    {
      Contract.Requires(obl != null);
      Contract.Requires(exp != null);

      this.inferred.Add(new Tuple<BoxedExpression, string, ProofOutcome, List<ProofObligation>>(exp, exp.ToString(), outcome, new List<ProofObligation>() { obl }));

      // we added a new condition, let us discare the previous ones
      this.preconditions = null; 
    }
 public override void Binary(BinaryOperator binaryOp, BoxedExpression left, BoxedExpression right, BoxedExpression parent)
 {
     left.Dispatch ((IBoxedExpressionController)this);
     if (this.Overflow)
         return;
     right.Dispatch ((IBoxedExpressionController)this);
     if (this.Overflow)
         return;
     switch (binaryOp) {
     case BinaryOperator.Add:
     case BinaryOperator.Add_Ovf:
     case BinaryOperator.Add_Ovf_Un:
         int sign1;
         int sign2;
         if (IFactQueryExtensions.TrySign<BoxedExpression, Variable> (
             this.facts,
             this.pc,
             left,
             out sign1
         ) && IFactQueryExtensions.TrySign<BoxedExpression, Variable> (
             this.facts,
             this.pc,
             right,
             out sign2
         ) && (sign1 >= 0 || sign2 >= 0)) {
             this.Overflow = false;
             break;
         } else {
             this.Overflow = true;
             break;
         }
     case BinaryOperator.And:
     case BinaryOperator.Ceq:
     case BinaryOperator.Cobjeq:
     case BinaryOperator.Cne_Un:
     case BinaryOperator.Cge:
     case BinaryOperator.Cge_Un:
     case BinaryOperator.Cgt:
     case BinaryOperator.Cgt_Un:
     case BinaryOperator.Cle:
     case BinaryOperator.Cle_Un:
     case BinaryOperator.Clt:
     case BinaryOperator.Clt_Un:
     case BinaryOperator.LogicalAnd:
     case BinaryOperator.LogicalOr:
     case BinaryOperator.Or:
     case BinaryOperator.Shl:
     case BinaryOperator.Shr:
     case BinaryOperator.Shr_Un:
     case BinaryOperator.Xor:
         this.Overflow = false;
         break;
     case BinaryOperator.Div:
     case BinaryOperator.Div_Un:
     case BinaryOperator.Rem:
     case BinaryOperator.Rem_Un:
         if (this.facts.IsNonZero (this.pc, right) == ProofOutcome.True)
             this.Overflow = false;
         this.Overflow = true;
         break;
     case BinaryOperator.Mul:
     case BinaryOperator.Mul_Ovf:
     case BinaryOperator.Mul_Ovf_Un:
         this.Overflow = true;
         break;
     case BinaryOperator.Sub:
     case BinaryOperator.Sub_Ovf:
     case BinaryOperator.Sub_Ovf_Un:
         int sign3;
         int sign4;
         if (IFactQueryExtensions.TrySign<BoxedExpression, Variable> (
             this.facts,
             this.pc,
             left,
             out sign3
         ) && IFactQueryExtensions.TrySign<BoxedExpression, Variable> (
             this.facts,
             this.pc,
             right,
             out sign4
         ) && (sign3 >= 0 || sign4 <= 0)) {
             this.Overflow = false;
             break;
         } else {
             this.Overflow = true;
             break;
         }
     default:
         this.Overflow = true;
         break;
     }
 }
 private static bool Implies(BoxedExpression condition, BoxedExpression premise)
 {
     BinaryOperator binaryOp_1, binaryOp_2;
     BoxedExpression left_1, left_2, right_1, right_2;
     if (!condition.IsBinaryExpression (out binaryOp_1, out left_1, out right_1) ||
         !premise.IsBinaryExpression (out binaryOp_2, out left_2, out right_2) ||
         binaryOp_2 != BinaryOperator.Ceq ||
         (!left_1.Equals ((object)left_2)) ||
         !right_1.Equals ((object)right_2) &&
         (!left_1.Equals ((object)right_2) || !right_1.Equals ((object)left_2))) {
         return false;
     }
     return ArrayExtensions.Contains<BinaryOperator> (new BinaryOperator[5]
       	{
         BinaryOperator.Ceq,
         BinaryOperator.Cge,
         BinaryOperator.Cge_Un,
         BinaryOperator.Cle,
         BinaryOperator.Cle_Un
       	}, binaryOp_1);
 }