internal int SuggestNonNullFieldsForConstructors(APC pc, Type t, IOutputResults output)
        {
            Contract.Ensures(Contract.Result <int>() >= 0);

            var md    = this.metadataDecoder;
            var count = 0;

            // No suggestions for structs
            if (md.IsStruct(t))
            {
                return(count);
            }

            var result = GenerateObjectInvariantsForType(t);

            if (result.Any())
            {
                foreach (var f in result)
                {
                    var contract  = string.Format("Contract.Invariant({0} != null);", md.Name(f.Item1));
                    var extraInfo = new ClousotSuggestion.ExtraSuggestionInfo()
                    {
                        SuggestedCode = contract, TypeDocumentId = md.DocumentationId(t)
                    };
                    var str = String.Format("Consider adding an object invariant {0} to the type {1}", contract, md.Name(t));
                    output.Suggestion(ClousotSuggestion.Kind.ObjectInvariant, ClousotSuggestion.Kind.ObjectInvariant.ToString(), pc, str, null, extraInfo);
                    count++;
                }
            }

            this.typesWeSuggestedNonNullFields.Add(t);
            return(count);
        }
    public static ClousotAnalysisResults EmitStats(this AnalysisStatistics @this, int swallowedTop, int swallowedBottom, int swallowedFalse, string assemblyName, IOutputResults output)
    {
      Contract.Requires(swallowedTop >= 0);
      Contract.Requires(swallowedBottom >= 0);
      Contract.Requires(swallowedFalse >= 0);
      Contract.Requires(assemblyName != null);
      Contract.Ensures(Contract.Result<ClousotAnalysisResults>() != null);

      var result = new ClousotAnalysisResults();

      if (@this.Total > 0)
      {
        var True = @this.True;
        var Top = Math.Max(@this.Top - swallowedTop, 0);
        var Bottom = Math.Max(@this.Bottom - swallowedBottom, 0);
        var False = Math.Max(@this.False - swallowedFalse, 0);

        var Total = True + Top + Bottom + False;

        var masked = swallowedTop + swallowedFalse + swallowedBottom;

        Contract.Assert(masked >= 0);

        Contract.Assert(Top >= 0);
        Contract.Assert(Bottom >= 0);
        Contract.Assert(False >= 0);

        var stats = String.Format("Checked {0} assertion{1}: {2}{3}{4}{5}{6}",
          @this.Total.ToString(),
          @this.Total > 1 ? "s" : "",
          True > 0 ? True + " correct " : "",
          Top > 0 ? Top + " unknown " : "",
          Bottom > 0 ? Bottom + " unreached " : "",
          False > 0 ? False + " false" : "",
          masked > 0 ? "(" + masked + " masked)" : "");

        output.FinalStatistic(assemblyName,stats);

        double precision = Total != 0 ? True / (double)Total : 1.0;
        output.Statistic("Validated: {0,6:P1}", precision);

        // for scripts parsing msbuild output
        output.WriteLine(stats);

        // Update the result
        result.Total = @this.Total;
        result.True = True;
        result.False = False;
        result.Bottom = Bottom;
        result.Top = Top;
        result.Masked = masked;
      }
      else
      {
        output.FinalStatistic(assemblyName, "Checked 0 assertions.");
      }

      return result;
    }
Beispiel #3
0
        public double Validate(IOutputResults output, ContractInferenceManager inferenceManager, IFactQuery <HighLevelExpression, Variable> query)
        {
            Contract.Requires(output != null);
            Contract.Requires(inferenceManager != null);
            Contract.Requires(query != null);

            throw new NotImplementedException();
        }
        public SimpleObjectInvariantDispatcher(
            IMethodDriver <Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions> mdriver,
            IOutputResults output, bool allowDisjunctivePreconditions)
            : base(mdriver, output, allowDisjunctivePreconditions)
        {
            Contract.Requires(mdriver != null);
            Contract.Requires(output != null);

            this.objectInvariants = new InferenceDB(exp => exp.Simplify(mdriver.MetaDataDecoder), exp => true);
        }
        protected SimpleDispatcherBase(IMethodDriver <Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions> mdriver,
                                       IOutputResults output, bool allowDisjunctivePreconditions)
        {
            Contract.Requires(mdriver != null);
            Contract.Requires(output != null);

            this.mdriver = mdriver;
            this.output  = output;
            this.allowDisjunctivePreconditions = allowDisjunctivePreconditions;
        }
        public double Validate(IOutputResults output, ContractInferenceManager inferenceManager, IFactQuery <HighLevelExpression, Variable> query)
        {
            var result = 0.0; // is this used?

            foreach (var obl in this.underlying)
            {
                obl.Validate(output, inferenceManager, query);
            }
            return(result);
        }
        public SimplePreconditionDispatcher(
            IMethodDriver <Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions> mdriver,
            IOutputResults output)
        {
            Contract.Requires(mdriver != null);

            this.mdriver       = mdriver;
            this.output        = output;
            this.preconditions = new InferredPreconditionDB();
        }
        /// <param name="extraFilter"> extraFilter(e) == true if e should not be suggested</param>
        public SimplePreconditionDispatcher(
            IMethodDriver <Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions> mdriver,
            IOutputResults output, bool allowDisjunctivePreconditions,
            Func <BoxedExpression, bool> extraFilter = null)
            : base(mdriver, output, allowDisjunctivePreconditions)
        {
            Contract.Requires(mdriver != null);
            Contract.Requires(output != null);

            this.preconditions = new InferenceDB(exp => exp.Simplify(mdriver.MetaDataDecoder), this.IsSuitableInRequires);
            this.shouldFilter  = extraFilter;
        }
        public override void EmitOutcome(ProofOutcome outcome, IOutputResults output)
        {
            // For some reason the EmitOutcome for the other assertions is done externally
            if (this.IsConditionCheck)
            {
                this.PopulateWarningContextInternal(outcome);
                var witness = this.GetWitness(outcome);

                // new Witness(this.ID, WarningType.TestAlwaysEvaluatingToAConstant, ProofOutcome.Bottom, this.PC)
                output.EmitOutcome(witness, MessageString(), this.condition.ToString());
            }
        }
        public SimpleAssumeDispatcher(
            IMethodDriver <Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions> mdriver,
            IOutputResults output, bool allowDisjunctivePreconditions, bool aggressiveInference)
            : base(mdriver, output, allowDisjunctivePreconditions)
        {
            Contract.Requires(mdriver != null);
            Contract.Requires(output != null);

            this.entryAssumptions     = new InferenceDB(exp => exp.Simplify(mdriver.MetaDataDecoder), _ => true);
            this.calleeAssumptions    = new Dictionary <Method, InferenceDB>();
            this.calleeAssumptionsPCs = new Dictionary <Method, List <APC> >();
            this.AggressiveInferece   = aggressiveInference;
        }
                //This code should be moved in the inference helper
#if false
                private bool CanAssumeLowerBoundPrecondition(IOutputResults output, BoxedExpression index)
                {
                    bool            hasVariables, hasAccessPath;
                    BoxedExpression indexInPreState = PreconditionSuggestion.ExpressionInPreState(index, this.Context, this.DecoderForMetaData, out hasVariables, out hasAccessPath, this.PC);

                    if (indexInPreState == null || !hasVariables)
                    {
                        return(false);
                    }

                    this.warningContext.Add(new WarningContext(WarningContext.ContextType.PreconditionCanDischarge));

                    BoxedExpression suggestedPre = BoxedExpression.Binary(
                        BinaryOperator.Cle, BoxedExpression.Const(0, this.DecoderForMetaData.System_Int32, this.DecoderForMetaData), indexInPreState);

                    return(InferenceHelper.TryAssumePreCondition(this.PC, suggestedPre, MethodDriver, SuggestedCodeFixes.WARNING_ARRAY_BOUND, "array lower bound", output));
                }
        public double Validate(IOutputResults output, ContractInferenceManager inferenceManager, IFactQuery <HighLevelExpression, Variable> query)
        {
            var options           = output.LogOptions;
            var total_obligations = 0;
            var validated         = 0;

            var outcomes = new List <Pair <ProofObligation, ProofOutcome> >();

            foreach (var obl in obligations)
            {
                if (obl.IsAlreadyValidated)
                {
                    continue;
                }

                var outcome = obl.Validate(query, inferenceManager, output);

                // Discard unreached implicit obligations in contracts
                if (outcome == ProofOutcome.Bottom && obl.PC.InsideContract)
                {
                    continue;
                }

                total_obligations++;

                if (outcome == ProofOutcome.True)
                {
                    validated++;
                }

                this.stats.Add(outcome);

                outcomes.Add(new Pair <ProofObligation, ProofOutcome>(obl, outcome));
            }

            foreach (var pair in outcomes)
            {
                if (options.PrintOutcome(pair.Two))
                {
                    pair.One.EmitOutcome(pair.Two, output);
                }
            }

            return(total_obligations != 0 ? ((double)validated) / total_obligations : 1.0);
        }
                    public override void EmitOutcome(ProofOutcome outcome, IOutputResults output)
                    {
                        Contract.Assume(output != null, "Should be a precondition");

                        var index = (int)outcome;

                        if (index < 0 || index >= fixedMessagesWrite.Length)
                        {
                            return;
                        }

                        if (this.isWrite)
                        {
                            output.EmitOutcome(GetWitness(outcome), AddHintsForTheUser(outcome, "{0}"), fixedMessagesWrite[index]);
                        }
                        else
                        {
                            output.EmitOutcome(GetWitness(outcome), AddHintsForTheUser(outcome, "{0}"), fixedMessagesRead[index]);
                        }
                    }
Beispiel #14
0
                protected override ProofOutcome ValidateInternalSpecific(IFactQuery <BoxedExpression, Variable> query, ContractInferenceManager inferenceManager, IOutputResults output)
                {
                    // We check the condition
                    var condition = this.Condition;

                    if (condition == null)
                    {
                        return(ProofOutcome.Top);
                    }

                    return(query.IsTrue(this.PC, condition));
                }
Beispiel #15
0
                protected override ProofOutcome ValidateInternalSpecific(IFactQuery <BoxedExpression, Variable> query, ContractInferenceManager inferenceManager, IOutputResults output)
                {
                    object minValue;

                    if (!this.DecoderForMetaData.TryGetMinValueForType(this.TypeOp1, out minValue))
                    {
                        return(ProofOutcome.Top);
                    }

                    // first, we check that Op1 != MinValue
                    var condition1 = BoxedExpression.Binary(BinaryOperator.Cne_Un, this.Op1, BoxedExpression.Const(minValue, this.TypeOp1, this.DecoderForMetaData));
                    var resultOp1  = query.IsTrue(this.PC, condition1);

                    // second, we check Op2 != -1
                    var condition2 = BoxedExpression.Binary(BinaryOperator.Cne_Un, this.Op2, BoxedExpression.Const(-1, this.DecoderForMetaData.System_Int32, this.DecoderForMetaData));
                    var resultOp2  = query.IsTrue(this.PC, condition2);

                    // One of the two conditions is true, so it is ok!
                    if (resultOp1 == ProofOutcome.True || resultOp2 == ProofOutcome.True)
                    {
                        return(ProofOutcome.True);
                    }

                    // Both conditions are false, so division is definitely an overflow
                    if (resultOp1 == ProofOutcome.False && resultOp2 == ProofOutcome.False)
                    {
                        return(ProofOutcome.False);
                    }

                    return(ProofOutcome.Top);
                }
Beispiel #16
0
 protected override ProofOutcome ValidateInternalSpecific(IFactQuery <BoxedExpression, Variable> query, ContractInferenceManager inferenceManager, IOutputResults output)
 {
     return(query.IsNonZero(this.PC, this.denominator));
 }
Beispiel #17
0
 public override void EmitOutcome(ProofOutcome outcome, IOutputResults output)
 {
     output.EmitOutcome(GetWitness(outcome), this.AddHintsForTheUser(outcome, "{0}"), fixedMessages[(int)outcome]);
 }
 /// <summary>
 /// Try to validate the embodied proof obligation and return the outcome.
 /// The IFactQuery interface is for future logic based implementation of fact querying.
 /// The validation can make queries or use internal state to answer the outcome.
 /// </summary>
 protected abstract ProofOutcome ValidateInternal(IFactQuery <Expression, Variable> query, ContractInferenceManager inferenceManager, IOutputResults output);
Beispiel #19
0
 public override void EmitOutcome(ProofOutcome outcome, IOutputResults output)
 {
     output.EmitOutcome(GetWitness(outcome), AddHintsForTheUser(outcome, "{0} of type {1}"), fixedMessages[(int)outcome], nameOfTypeOfArg);
 }
        public ProofOutcome Validate(IFactQuery <Expression, Variable> query, ContractInferenceManager inferenceManager, IOutputResults output)
        {
            ProofOutcome outcome;

            if (query.IsUnreachable(this.PCForValidation))
            {
                outcome = ProofOutcome.Bottom;
            }
            else
            {
                outcome = ValidateInternal(query, inferenceManager, output);

                if (outcome == ProofOutcome.Top || outcome == ProofOutcome.False)
                {
                    if (this.Condition != null && this.TryInferPrecondition && !output.IsMasked(this.GetWitness(outcome)))
                    {
                        InferredConditions inferredPreConditions;

                        var inferencer = inferenceManager.PreCondition.Inference;
                        if (inferencer.TryInferConditions(this, inferenceManager.CodeFixesManager, out inferredPreConditions))
                        {
                            var context = inferredPreConditions.PushToContractManager(inferenceManager, inferencer.ShouldAddAssumeFalse, this, ref outcome, output.LogOptions);

                            this.HasASufficientAndNecessaryCondition = inferredPreConditions.HasASufficientCondition;
                            this.AdditionalInformationOnTheWarning.AddRange(context);
                        }
                        else if (inferencer.ShouldAddAssumeFalse)
                        {
                            inferenceManager.Assumptions.AddEntryAssumes(this, new BoxedExpression[] { BoxedExpression.ConstFalse });
                        }
                    }
                }
            }

            this.Outcome = outcome;

            return(outcome);
        }
 protected override ProofOutcome ValidateInternal(IFactQuery <BoxedExpression, Variable> query, ContractInferenceManager inferenceManager, IOutputResults output)
 {
     return(query.IsTrue(this.PC, this.condition));
 }
 public override void EmitOutcome(ProofOutcome outcome, IOutputResults output)
 {
     throw new NotImplementedException();
 }
        protected override ProofOutcome ValidateInternal(IFactQuery <Exp, Var> query, ContractInferenceManager inferenceManager, IOutputResults output)
        {
            Contract.Requires(query != null);
            Contract.Requires(inferenceManager != null);

            throw new NotImplementedException();
        }
 /// <summary>
 /// Prints out the outcome of the embodied proof obligation on the given output.
 /// Note, the code should not make decisions about when to print, as this is done
 /// by the context.
 /// </summary>
 public abstract void EmitOutcome(ProofOutcome outcome, IOutputResults output);
Beispiel #25
0
 public override void EmitOutcome(ProofOutcome outcome, IOutputResults output)
 {
     output.EmitOutcome(GetWitness(outcome), AddHintsForTheUser(outcome, "{0}"), FixedMessages(outcome));
 }
Beispiel #26
0
                protected override ProofOutcome ValidateInternalSpecific(IFactQuery <BoxedExpression, Variable> query, ContractInferenceManager inferenceManager, IOutputResults output)
                {
                    // If it is a variable or a constant, then there is nothing to do, and we return true.

                    if (this.exp.IsConstant || this.exp.IsVariable)
                    {
                        return(ProofOutcome.True);
                    }

                    return(base.ValidateInternalSpecific(query, inferenceManager, output));
                }
        public static ClousotAnalysisResults EmitStats(this AnalysisStatistics @this, int swallowedTop, int swallowedBottom, int swallowedFalse, string assemblyName, IOutputResults output)
        {
            Contract.Requires(swallowedTop >= 0);
            Contract.Requires(swallowedBottom >= 0);
            Contract.Requires(swallowedFalse >= 0);
            Contract.Requires(assemblyName != null);
            Contract.Ensures(Contract.Result <ClousotAnalysisResults>() != null);

            var result = new ClousotAnalysisResults();

            if (@this.Total > 0)
            {
                var True   = @this.True;
                var Top    = Math.Max(@this.Top - swallowedTop, 0);
                var Bottom = Math.Max(@this.Bottom - swallowedBottom, 0);
                var False  = Math.Max(@this.False - swallowedFalse, 0);

                var Total = True + Top + Bottom + False;

                var masked = swallowedTop + swallowedFalse + swallowedBottom;

                Contract.Assert(masked >= 0);

                Contract.Assert(Top >= 0);
                Contract.Assert(Bottom >= 0);
                Contract.Assert(False >= 0);

                var stats = String.Format("Checked {0} assertion{1}: {2}{3}{4}{5}{6}",
                                          @this.Total.ToString(),
                                          @this.Total > 1 ? "s" : "",
                                          True > 0 ? True + " correct " : "",
                                          Top > 0 ? Top + " unknown " : "",
                                          Bottom > 0 ? Bottom + " unreached " : "",
                                          False > 0 ? False + " false" : "",
                                          masked > 0 ? "(" + masked + " masked)" : "");

                output.FinalStatistic(assemblyName, stats);

                double precision = Total != 0 ? True / (double)Total : 1.0;
                output.Statistic("Validated: {0,6:P1}", precision);

                // for scripts parsing msbuild output
                output.WriteLine(stats);

                // Update the result
                result.Total  = @this.Total;
                result.True   = True;
                result.False  = False;
                result.Bottom = Bottom;
                result.Top    = Top;
                result.Masked = masked;
            }
            else
            {
                output.FinalStatistic(assemblyName, "Checked 0 assertions.");
            }

            return(result);
        }
Beispiel #28
0
                protected override ProofOutcome ValidateInternalSpecific(IFactQuery <BoxedExpression, Variable> query, ContractInferenceManager inferenceManager, IOutputResults output)
                {
                    // First, we check if arg != MinValue

                    object value;

                    if (!this.DecoderForMetaData.TryGetMinValueForType(this.typeOfArg, out value))
                    {
                        return(ProofOutcome.Top);
                    }

                    var condition = this.Condition;

                    if (condition != null) // this.Condition may return null
                    {
                        var result = query.IsTrue(this.PC, condition);

                        if (result != ProofOutcome.Top)
                        {
                            return(result);
                        }
                    }
                    // We check a sufficient condition: if arg is >= 0, then it is not the negation of a negative "extreme"
                    var greaterThanZero = query.IsGreaterEqualToZero(this.PC, this.arg);

                    return((greaterThanZero == ProofOutcome.True || greaterThanZero == ProofOutcome.Bottom)
            ? greaterThanZero : ProofOutcome.Top);
                }
Beispiel #29
0
                /// <summary>
                /// If we cannot validate the precision of the operands, we try to suggest an explicit cast
                /// </summary>
                protected override ProofOutcome ValidateInternalSpecific(IFactQuery <BoxedExpression, Variable> query, ContractInferenceManager inferenceManager, IOutputResults output)
                {
                    var outcome = query.HaveSameFloatType(PC, this.left, this.right);

                    switch (outcome)
                    {
                    case ProofOutcome.Top:
                    {
                        ConcreteFloat leftType, rightType;

                        if (query.TryGetFloatType(this.PC, this.left, out leftType) && query.TryGetFloatType(this.PC, this.right, out rightType))
                        {
                            APC conditionPC;
                            if (!this.MethodDriver.AdditionalSyntacticInformation.VariableDefinitions.TryGetValue(this.var, out conditionPC))
                            {
                                conditionPC = this.PC;
                            }

                            if (inferenceManager.CodeFixesManager.TrySuggestFloatingPointComparisonFix(this, conditionPC, this.left, this.right, leftType, rightType))
                            {
                                // do something? Returning true seems a bad idea
                            }
                        }

                        return(outcome);
                    }

                    default:
                    {
                        return(outcome);
                    }
                    }
                }
 public override void ValidateImplicitAssertions(IOutputResults output)
 {
     throw new Exception("not implemented");
 }
Beispiel #31
0
 public override void EmitOutcome(ProofOutcome outcome, IOutputResults output)
 {
     output.EmitOutcome(GetWitness(outcome), fixedMessages[(int)outcome]);
 }