Пример #1
0
        /////////////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Constructor.  Initialize a checker with the program and log file.
        /// Optionally, use prover context provided by parameter "ctx".
        /// </summary>
        public Checker(VC.ConditionGeneration vcgen, Program prog, string /*?*/ logFilePath, bool appendLogFile, int timeout, ProverContext ctx = null)
        {
            Contract.Requires(vcgen != null);
            Contract.Requires(prog != null);
            this.timeout = timeout;
            this.Program = prog;

            ProverOptions options = cce.NonNull(CommandLineOptions.Clo.TheProverFactory).BlankProverOptions();

            if (logFilePath != null)
            {
                options.LogFilename = logFilePath;
                if (appendLogFile)
                {
                    options.AppendLogFile = appendLogFile;
                }
            }

            if (timeout > 0)
            {
                options.TimeLimit = timeout * 1000;
            }

            options.Parse(CommandLineOptions.Clo.ProverOptions);

            ContextCacheKey key = new ContextCacheKey(prog);
            ProverInterface prover;

            if (vcgen.CheckerCommonState == null)
            {
                vcgen.CheckerCommonState = new Dictionary <ContextCacheKey, ProverContext>();
            }
            IDictionary <ContextCacheKey, ProverContext> /*!>!*/ cachedContexts = (IDictionary <ContextCacheKey, ProverContext /*!*/>)vcgen.CheckerCommonState;

            if (ctx == null && cachedContexts.TryGetValue(key, out ctx))
            {
                ctx    = (ProverContext)cce.NonNull(ctx).Clone();
                prover = (ProverInterface)
                         CommandLineOptions.Clo.TheProverFactory.SpawnProver(options, ctx);
            }
            else
            {
                if (ctx == null)
                {
                    ctx = (ProverContext)CommandLineOptions.Clo.TheProverFactory.NewProverContext(options);
                }

                Setup(prog, ctx);

                // we first generate the prover and then store a clone of the
                // context in the cache, so that the prover can setup stuff in
                // the context to be cached
                prover = (ProverInterface)
                         CommandLineOptions.Clo.TheProverFactory.SpawnProver(options, ctx);
                cachedContexts.Add(key, cce.NonNull((ProverContext)ctx.Clone()));
            }

            this.thmProver = prover;
            this.gen       = prover.VCExprGen;
        }
Пример #2
0
        public static VC.ConditionGeneration.Outcome MyVerifyImplementation(Implementation impl, Program prog)
        {
            VC.ConditionGeneration vcgen = BoogieVerify.InitializeVC(prog);
            List <Counterexample>  errs;
            var outcome = vcgen.VerifyImplementation(impl, out errs);

            vcgen.Close();
            return(outcome);
        }
Пример #3
0
        public static VC.ConditionGeneration InitializeVC(Program prog)
        {
            VC.ConditionGeneration vcgen = null;
            try
            {
                if (CommandLineOptions.Clo.vcVariety == CommandLineOptions.VCVariety.Doomed)
                {
                    throw new Exception("The doomed option is not supported in SymDiff");
                    //vcgen = new VC.DCGen(prog, CommandLineOptions.Clo.SimplifyLogFilePath, CommandLineOptions.Clo.SimplifyLogFileAppend);
                }
                else
                {
                    vcgen = new VC.VCGen(prog, CommandLineOptions.Clo.SimplifyLogFilePath, CommandLineOptions.Clo.SimplifyLogFileAppend, new List <Checker>());
                }
            }
            catch (ProverException)
            {
                Log.Out(Log.Error, "Fatal Error: ProverException: {0}");
                return(null);
            }

            return(vcgen);
        }
Пример #4
0
        static int Main(string[] args)
        {
            CommandLineOptions.Install(new CommandLineOptions());
            int argc = args.Length;

            if (argc < 4)
            {
                System.Console.WriteLine("Boogiewrapper.exe a.bpl EQ LEFT RIGHT [v1name] [v2name] [bvdfriendly]");
                System.Console.WriteLine("\t   EQ: name of the combined procedure to be verified");
                System.Console.WriteLine("\t   RIGHT: name of the right procedure");
                System.Console.WriteLine("\t   RIGHT: name of the right procedure");
                System.Console.WriteLine("\t   viname: optional prefix of the left/right procedure (when not checking EQ_v1.foo__xx__v2.foo)");
                System.Console.WriteLine("\t   bvdfriendly: optional instrument the input file to add some captureStates for bvd to display (no checking)");
                return(-1);
            }
            string fileName = args[0];
            string funcName = args[1];

            //TODO: Make it aware of the other Boogie options
            var boogieOptions = " -doModSetAnalysis -printInstrumented -z3multipleErrors -typeEncoding:m -timeLimit:" + Options.Timeout + " -removeEmptyBlocks:0 -printModel:1 -printModelToFile:model.dmp " + Options.BoogieUserOpts;

            SDiff.Boogie.Process.InitializeBoogie(boogieOptions);

            Program prog = BoogieUtils.ParseProgram(args[0]);

            if (prog == null)
            {
                Log.Out(Log.Verifier, "Parse Error!!! in   " + args[1]);
                return(-1);
            }
            if (BoogieUtils.ResolveAndTypeCheckThrow(prog, args[0]))
            {
                return(-1);
            }
            //code duplication

            //Not having "-printInstrumented" just prints the old version of hte program!!!!
            if (args.Length == 7 && args[6] == "/bvdfriendly")
            {
                //System.Diagnostics.Debugger.Break();
                var     bvdI  = new BvdInstrument();
                Program prog1 = bvdI.VisitProgram(prog);
                if (BoogieUtils.ResolveAndTypeCheckThrow(prog, fileName))
                {
                    return(-1);
                }
                Util.DumpBplAST(prog, "merged_bvd.bpl");
                return(-1);
            }

            var newProg = prog;

            VC.ConditionGeneration vcgen = BoogieVerify.InitializeVC(newProg);
            var newDict = SDiff.Boogie.Process.BuildProgramDictionary(newProg.TopLevelDeclarations.ToList());

            //RS: Uncomment this
            var newEq = (Implementation)newDict.Get(funcName + "$IMPL");
            SDiffCounterexamples SErrors;
            List <Model>         errModelList;

            var Result = BoogieVerify.VerifyImplementation(vcgen, newEq, newProg, out SErrors, out errModelList);

            switch (Result)
            {
            case VerificationResult.Error:
                Log.Out(Log.Verifier, "Result: Error");
                break;

            case VerificationResult.Verified:
                Log.Out(Log.Verifier, "Result: Verified");
                break;

            case VerificationResult.OutOfMemory:
                Log.Out(Log.Verifier, "Result: OutOfMemory");
                return(-2);

            //break;
            case VerificationResult.TimeOut:
                Log.Out(Log.Verifier, "Result: TimeOut");
                return(-3);

            // break;
            default:
                Log.Out(Log.Verifier, "Result: Unhandled");
                return(-4);
            }
            Implementation n1, n2;

            GetImplementations(newDict, funcName, out n1, out n2, args[2], args[3]);

            var outputVars = new List <Variable>();

            foreach (Variable v in n1.OutParams)
            {
                outputVars.Add(newDict.Get(v.Name + "$VAR") as Variable);
            }
            foreach (Variable v in n2.OutParams)
            {
                outputVars.Add(newDict.Get(v.Name + "$VAR") as Variable);
            }


            var globals = new List <Variable>();

            foreach (IdentifierExpr ie in newEq.Proc.Modifies)
            {
                globals.Add(ie.Decl);
            }


            if (SErrors != null)
            {
                //somewhat misnamed...
                if (Options.DumpBeforeVerifying)
                {
                    Log.Out(Log.SymEx, "Dumping procedure under verification");
                    newEq.Emit(Log.LogWriter, 0);
                }
                if (Options.DoSymEx)
                {
                    if (Options.PreciseDifferentialInline)
                    {
                        IEnumerable <Declaration> consts = prog.TopLevelDeclarations.Where(x => x is Constant);
                        if (args.Length < 6)
                        {
                            BoogieVerify.ProcessCounterexamplesWOSymbolicOut(SErrors, globals, newEq.LocVars, null, null, consts.ToList(), errModelList);
                        }
                        else
                        {
                            BoogieVerify.ProcessCounterexamplesWOSymbolicOut(SErrors, globals, newEq.LocVars, null, null, consts.ToList(), errModelList, args[4], args[5]);
                        }
                    }
                    else
                    {
                        BoogieVerify.ProcessCounterexamples(SErrors, globals, outputVars, newProg, null, null);
                    }
                }
            }

            return(SErrors == null ? 0 : SErrors.Count);
        }
Пример #5
0
        public static int RVTRunVerificationTask(SDiff.VerificationTask vt, VC.ConditionGeneration vcgen, Program prog,
                                                 HashSet <int> inlinedFns1, HashSet <int> inlinedFns2, out bool crashed)
        {
            Log.Out(Log.Verifier, "Verifying " + vt.Eq.Name);

            crashed = false;


            var attList = new List <Object>(1);

            attList.Add(Expr.Literal(1));

            //save attributes
            var sqkLeft   = vt.Left.Attributes;
            var sqkpLeft  = vt.Left.Proc.Attributes;
            var sqkRight  = vt.Right.Attributes;
            var sqkpRight = vt.Right.Proc.Attributes;

            //save postconditions
            var leftPosts  = vt.Left.Proc.Ensures;
            var rightPosts = vt.Right.Proc.Ensures;

            //Keep the postconditions correpsonding to the
            //free ensures (out == uf_Foo(inp))
            //vt.Left.Proc.Ensures = new List<Ensures>();
            //vt.Right.Proc.Ensures = new List<Ensures>();

            //inline procedures under analysis
            vt.Left.Attributes
                = Util.MkInlinedAttribute(attList);
            vt.Left.Proc.Attributes = vt.Left.Attributes;

            vt.Right.Attributes
                = Util.MkInlinedAttribute(attList);
            vt.Right.Proc.Attributes = vt.Right.Attributes;

            vt.Left.OriginalBlocks   = vt.Left.Blocks;
            vt.Left.OriginalLocVars  = vt.Left.LocVars;
            vt.Right.OriginalBlocks  = vt.Right.Blocks;
            vt.Right.OriginalLocVars = vt.Right.LocVars;


            IEnumerable <Declaration> procImplPIter = prog.TopLevelDeclarations.Where(x => x is Implementation);

            List <Implementation> inlinedImpls = new List <Implementation>();

            foreach (Implementation currentProcImpl in procImplPIter)
            {
                bool match = false;
                int  indx  = -1;
                if (fnNameToIndex1.ContainsKey(currentProcImpl.Proc.Name))
                {
                    match = true;
                    indx  = fnNameToIndex1[currentProcImpl.Proc.Name];
                }
                else if (fnNameToIndex2.ContainsKey(currentProcImpl.Proc.Name))
                {
                    match = true;
                    indx  = fnNameToIndex2[currentProcImpl.Proc.Name];
                }

                //Inline if present in
                if (match && (inlinedFns1.Contains(indx) || inlinedFns2.Contains(indx)))
                {
                    inlinedImpls.Add(currentProcImpl);
                    currentProcImpl.Attributes      = Util.MkInlinedAttribute(attList);
                    currentProcImpl.Proc.Attributes = Util.MkInlinedAttribute(attList);

                    //RUN INLINER OVER EQ FUNCTION
                    currentProcImpl.OriginalBlocks  = currentProcImpl.Blocks;
                    currentProcImpl.OriginalLocVars = currentProcImpl.LocVars;
                }
            }

            //RUN INLINER OVER EQ FUNCTION
            // prog = EQ program
            // vt.Eq = EQ_f_f' procedure with f, f' having {inline} tags
            Inliner.ProcessImplementation(prog, vt.Eq);

            if (Options.TraceVerify)
            {
                Log.Out(Log.Normal, "Ready to verify:");
                Log.LogEmit(Log.Normal, prog.Emit);
            }

            // To print the EQ files in

            Util.DumpBplAST(prog, vt.Eq.Name + "_out.bpl");
            // prog = SDiff.Boogie.Process.ParseProgram(vt.Eq.Name + "_out.bpl");

            if (BoogieUtils.ResolveAndTypeCheckThrow(prog, Options.MergedProgramOutputFile))
            {
                return(1);
            }

            Implementation newEq   = vt.Eq;
            var            newProg = prog;

            vcgen = BoogieVerify.InitializeVC(newProg);
            //SDiff.Boogie.Process.ResolveAndTypeCheck(newProg, "");
            var newDict = SDiff.Boogie.Process.BuildProgramDictionary(newProg.TopLevelDeclarations.ToList());
            //newEq = (Implementation)newDict.Get(vt.Eq.Name + "$IMPL");



            SDiffCounterexamples SErrors;
            List <Model>         errModelList;


            //Clear up the state since it might call the same procedure twice



            vt.Result = BoogieVerify.VerifyImplementation(vcgen, newEq, newProg, out SErrors, out errModelList);

            switch (vt.Result)
            {
            case SDiff.VerificationResult.Error:
                Log.Out(Log.Verifier, "Result: Error");
                break;

            case SDiff.VerificationResult.Verified:
                Log.Out(Log.Verifier, "Result: Verified");
                break;

            default:
                Log.Out(Log.Verifier, "Result: Unhandled");
                crashed = true;
                break;
            }

            //restore postconditions IN THE OLD IN-MEMORY PROGRAM
            vt.Left.Proc.Ensures  = leftPosts;
            vt.Right.Proc.Ensures = rightPosts;

            //remove the inline annotation IN THE OLD IN-MEMORY PROGRAM
            vt.Left.Attributes       = sqkLeft;
            vt.Left.Proc.Attributes  = sqkpLeft;
            vt.Right.Attributes      = sqkRight;
            vt.Right.Proc.Attributes = sqkpRight;

            //remove the inline annotation in the Inlined Procedures
            foreach (Implementation currentProcImpl in procImplPIter)
            {
                if (inlinedImpls.Contains(currentProcImpl))
                {
                    currentProcImpl.Attributes      = null;
                    currentProcImpl.Proc.Attributes = null;
                }
            }

            if (vt.Result == SDiff.VerificationResult.Verified)
            {
                return(1);
            }
            else
            {
                return(0);
            }
        }
Пример #6
0
        public void Run()
        {
            if (WhoopRaceCheckerCommandLineOptions.Get().MeasurePassExecutionTime)
            {
                Console.WriteLine(" |------ [{0} :: {1}]", this.EP1.Name, this.EP2.Name);
                Console.WriteLine(" |  |");
                this.Timer = new ExecutionTimer();
                this.Timer.Start();
            }

            this.AC.EliminateDeadVariables();
            this.AC.Inline();
            if (WhoopRaceCheckerCommandLineOptions.Get().LoopUnrollCount != -1)
            {
                this.AC.Program.UnrollLoops(WhoopRaceCheckerCommandLineOptions.Get().LoopUnrollCount,
                                            WhoopRaceCheckerCommandLineOptions.Get().SoundLoopUnrolling);
            }

            string         checkerName = "check$" + this.EP1.Name + "$" + this.EP2.Name;
            Implementation checker     = this.AC.TopLevelDeclarations.OfType <Implementation>().ToList().
                                         Find(val => val.Name.Equals(checkerName));

            Contract.Assert(checker != null);

            VC.ConditionGeneration vcgen = null;

            try
            {
                vcgen = new VC.VCGen(this.AC.Program, WhoopRaceCheckerCommandLineOptions.Get().SimplifyLogFilePath,
                                     WhoopRaceCheckerCommandLineOptions.Get().SimplifyLogFileAppend, new List <Checker>());
            }
            catch (ProverException e)
            {
                Whoop.IO.Reporter.ErrorWriteLine("Fatal Error: ProverException: {0}", e);
                Environment.Exit((int)Outcome.FatalError);
            }

            int prevAssertionCount = vcgen.CumulativeAssertionCount;

            List <Counterexample> errors;

            DateTime start = new DateTime();

            if (WhoopRaceCheckerCommandLineOptions.Get().Trace)
            {
                start = DateTime.UtcNow;
                if (WhoopRaceCheckerCommandLineOptions.Get().Trace)
                {
                    Console.WriteLine("");
                    Console.WriteLine("Verifying {0} ...", checker.Name.Substring(5));
                }
            }

            VC.VCGen.Outcome vcOutcome;
            try
            {
                vcOutcome = vcgen.VerifyImplementation(checker, out errors);
            }
            catch (VC.VCGenException e)
            {
                Whoop.IO.Reporter.ReportBplError(checker, String.Format("Error BP5010: {0}  Encountered in implementation {1}.",
                                                                        e.Message, checker.Name), true, true);
                errors    = null;
                vcOutcome = VC.VCGen.Outcome.Inconclusive;
            }
            catch (UnexpectedProverOutputException e)
            {
                Whoop.IO.Reporter.AdvisoryWriteLine("Advisory: {0} SKIPPED because of internal error: unexpected prover output: {1}",
                                                    checker.Name, e.Message);
                errors    = null;
                vcOutcome = VC.VCGen.Outcome.Inconclusive;
            }

            string   timeIndication = "";
            DateTime end            = DateTime.UtcNow;
            TimeSpan elapsed        = end - start;

            if (WhoopRaceCheckerCommandLineOptions.Get().Trace)
            {
                int poCount = vcgen.CumulativeAssertionCount - prevAssertionCount;
                timeIndication = string.Format("  [{0:F3} s, {1} proof obligation{2}]  ",
                                               elapsed.TotalSeconds, poCount, poCount == 1 ? "" : "s");
            }

            this.ProcessOutcome(checker, vcOutcome, errors, timeIndication, this.Stats);

            if (vcOutcome == VC.VCGen.Outcome.Errors || WhoopRaceCheckerCommandLineOptions.Get().Trace)
            {
                Console.Out.Flush();
            }

            WhoopRaceCheckerCommandLineOptions.Get().TheProverFactory.Close();
//      cce.NonNull(WhoopRaceCheckerCommandLineOptions.Get().TheProverFactory).Close();
            vcgen.Dispose();

            if (WhoopRaceCheckerCommandLineOptions.Get().MeasurePassExecutionTime)
            {
                this.Timer.Stop();
                Console.WriteLine(" |  |------ [StaticLocksetAnalyser] {0}", this.Timer.Result());
                Console.WriteLine(" |");
            }
        }
Пример #7
0
        private void CheckForRaces()
        {
            this.AC.EliminateDeadVariables();
            this.AC.Inline();
            if (ToolCommandLineOptions.Get().LoopUnrollCount != -1)
            {
                this.AC.BoogieProgram.UnrollLoops(ToolCommandLineOptions.Get().LoopUnrollCount,
                                                  ToolCommandLineOptions.Get().SoundLoopUnrolling);
            }

            VC.ConditionGeneration vcgen = null;

            try
            {
                vcgen = new VC.VCGen(this.AC.BoogieProgram, ToolCommandLineOptions.Get().SimplifyLogFilePath,
                                     ToolCommandLineOptions.Get().SimplifyLogFileAppend, new List <Checker>());
            }
            catch (ProverException e)
            {
                Lockpwn.IO.Reporter.ErrorWriteLine("Fatal Error: ProverException: {0}", e);
                Environment.Exit((int)Outcome.FatalError);
            }

            int prevAssertionCount = vcgen.CumulativeAssertionCount;

            List <Counterexample> errors;

            DateTime start = new DateTime();

            if (ToolCommandLineOptions.Get().Trace)
            {
                start = DateTime.UtcNow;
                if (ToolCommandLineOptions.Get().Trace)
                {
                    Output.PrintLine("");
                    Output.PrintLine("Verifying {0} ...", this.AC.EntryPoint.Name.Substring(5));
                }
            }

            GC.Collect();

            VC.VCGen.Outcome vcOutcome;
            try
            {
                vcOutcome = vcgen.VerifyImplementation(this.AC.EntryPoint, out errors);
            }
            catch (VC.VCGenException e)
            {
                Lockpwn.IO.Reporter.ReportBplError(this.AC.EntryPoint, String.Format("Error BP5010: {0}  Encountered in implementation {1}.",
                                                                                     e.Message, this.AC.EntryPoint.Name), true, true);
                errors = null;
                this.AC.GetErrorReporter().Result = ErrorReporter.Outcome.Inconclusive;
                vcOutcome = VC.VCGen.Outcome.Inconclusive;
                GC.Collect();
            }
            catch (UnexpectedProverOutputException e)
            {
                Lockpwn.IO.Reporter.WarningWriteLine("Warning: unexpected prover output: {0}", e.Message);
                errors = null;
                this.AC.GetErrorReporter().Result = ErrorReporter.Outcome.Inconclusive;
                vcOutcome = VC.VCGen.Outcome.Inconclusive;
                GC.Collect();
            }
            catch (OutOfMemoryException)
            {
                Lockpwn.IO.Reporter.WarningWriteLine("Warning: run out of memory during VC verification");
                errors = null;
                this.AC.GetErrorReporter().Result = ErrorReporter.Outcome.OutOfMemory;
                vcOutcome = VC.VCGen.Outcome.OutOfMemory;
                GC.Collect();
            }
            catch (Exception ex)
            {
                Lockpwn.IO.Reporter.WarningWriteLine("Warning: VC verification failed: " + ex.Message);
                errors = null;
                this.AC.GetErrorReporter().Result = ErrorReporter.Outcome.Inconclusive;
                vcOutcome = VC.VCGen.Outcome.Inconclusive;
                GC.Collect();
            }

            string   timeIndication = "";
            DateTime end            = DateTime.UtcNow;
            TimeSpan elapsed        = end - start;

            if (ToolCommandLineOptions.Get().Trace)
            {
                int poCount = vcgen.CumulativeAssertionCount - prevAssertionCount;
                timeIndication = string.Format("  [{0:F3} s, {1} proof obligation{2}]  ",
                                               elapsed.TotalSeconds, poCount, poCount == 1 ? "" : "s");
            }

            this.ProcessOutcome(this.AC.EntryPoint, vcOutcome, errors, timeIndication, this.Stats);

            if (vcOutcome == VC.VCGen.Outcome.Errors || ToolCommandLineOptions.Get().Trace)
            {
                Console.Out.Flush();
            }

            ToolCommandLineOptions.Get().TheProverFactory.Close();
            cce.NonNull(ToolCommandLineOptions.Get().TheProverFactory).Close();
            vcgen.Dispose();

            Lockpwn.IO.Reporter.WriteTrailer(this.Stats);
        }
Пример #8
0
        public static int RunVerificationTask(VerificationTask vt, VC.ConditionGeneration vcgen, Program prog, out bool crashed, bool wrapper = true)
        {
            crashed = false;

            var attList = new List <Object>(1);

            attList.Add(Expr.Literal(1));

            //save attributes
            var sqkLeft   = vt.Left.Attributes;
            var sqkpLeft  = vt.Left.Proc.Attributes;
            var sqkRight  = vt.Right.Attributes;
            var sqkpRight = vt.Right.Proc.Attributes;

            //save postconditions
            var leftPosts  = vt.Left.Proc.Ensures;
            var rightPosts = vt.Right.Proc.Ensures;

            //The ensures must have been removed at the time of stripContracts
            //The recursive case is handled by RVT option anyway.
            //vt.Left.Proc.Ensures = new List<Ensures>();
            //vt.Right.Proc.Ensures = new List<Ensures>();

            //inline procedures under analysis
            vt.Left.Attributes
                = Util.MkInlinedAttribute(attList);
            vt.Left.Proc.Attributes = vt.Left.Attributes;

            vt.Right.Attributes
                = Util.MkInlinedAttribute(attList);
            vt.Right.Proc.Attributes = vt.Right.Attributes;

            //RUN INLINER OVER EQ FUNCTION
            vt.Left.OriginalBlocks   = vt.Left.Blocks;
            vt.Left.OriginalLocVars  = vt.Left.LocVars;
            vt.Right.OriginalBlocks  = vt.Right.Blocks;
            vt.Right.OriginalLocVars = vt.Right.LocVars;

            // inline diff_inline procedures
            IEnumerable <Declaration> procImplPIter = prog.TopLevelDeclarations.Where(x => x is Implementation);

            foreach (Implementation currentProcImpl in procImplPIter)
            {
                if (currentProcImpl.Name.Contains("_Diff_Inline"))
                {
                    currentProcImpl.Attributes      = Util.MkInlinedAttribute(attList);
                    currentProcImpl.Proc.Attributes = Util.MkInlinedAttribute(attList);

                    //RUN INLINER OVER EQ FUNCTION
                    currentProcImpl.OriginalBlocks  = currentProcImpl.Blocks;
                    currentProcImpl.OriginalLocVars = currentProcImpl.LocVars;
                }
            }

            // prog = EQ program
            // vt.Eq = EQ_f_f' procedure with f, f' having {inline} tags
            Inliner.ProcessImplementation(prog, vt.Eq);

            SDiffCounterexamples SErrors      = null;
            List <Model>         errModelList = null;
            Implementation       newEq        = null;
            Program newProg = null;
            Dictionary <string, Declaration> newDict = null;


            Log.Out(Log.Verifier, "Verifying " + vt.Eq.Name);
            if (Options.TraceVerify)
            {
                Log.Out(Log.Normal, "Ready to verify:");
                Log.LogEmit(Log.Normal, prog.Emit);
            }

            // To print the EQ files in
            Util.DumpBplAST(prog, vt.Eq.Name + "_out.bpl");
            //RS: Uncomment this

            /*if (wrapper)
             * {
             *  prog.RemoveTopLevelDeclaration(vt.Eq);
             *  prog.RemoveTopLevelDeclaration(vt.Eq.Proc);
             * }*/
            prog = null;
            ReplaceInFile(vt.Eq.Name + "_out.bpl", "@", "_");
            if (!wrapper)
            {
                prog = BoogieUtils.ParseProgram("RS" + vt.Eq.Name + "_out.bpl");

                if (prog == null)
                {
                    Log.Out(Log.Verifier, "Parse Error!!! in   " + vt.Eq.Name);
                    return(1);
                }
                if (BoogieUtils.ResolveAndTypeCheckThrow(prog, Options.MergedProgramOutputFile))
                {
                    return(1);
                }

                newEq   = vt.Eq;
                newProg = prog;

                vcgen = InitializeVC(newProg);
                //SDiff.Boogie.Process.ResolveAndTypeCheck(newProg, "");
                newDict = SDiff.Boogie.Process.BuildProgramDictionary(newProg.TopLevelDeclarations.ToList());

                //RS: Uncomment this
                newEq = (Implementation)newDict.Get(vt.Eq.Name + "$IMPL");

                vt.Result = VerifyImplementation(vcgen, newEq, newProg, out SErrors, out errModelList);



                switch (vt.Result)
                {
                case VerificationResult.Error:
                    Log.Out(Log.Verifier, "Result: Error");
                    break;

                case VerificationResult.Verified:
                    Log.Out(Log.Verifier, "Result: Verified");
                    break;

                case VerificationResult.OutOfMemory:
                    Log.Out(Log.Verifier, "Result: OutOfMemory");
                    break;

                case VerificationResult.TimeOut:
                    Log.Out(Log.Verifier, "Result: TimeOut");
                    break;

                default:
                    Log.Out(Log.Verifier, "Result: Unhandled");
                    crashed = true;
                    break;
                }
                vcgen.Close();
            }
            //restore postconditions IN THE OLD IN-MEMORY PROGRAM
            vt.Left.Proc.Ensures  = leftPosts;
            vt.Right.Proc.Ensures = rightPosts;

            //remove the inline annotation IN THE OLD IN-MEMORY PROGRAM
            vt.Left.Attributes       = sqkLeft;
            vt.Left.Proc.Attributes  = sqkpLeft;
            vt.Right.Attributes      = sqkRight;
            vt.Right.Proc.Attributes = sqkpRight;

            //remove the inline annotation in the Diff_Inline Procedures
            foreach (Implementation currentProcImpl in procImplPIter)
            {
                if (currentProcImpl.Name.Contains("_Diff_Inline"))
                {
                    currentProcImpl.Attributes      = null;
                    currentProcImpl.Proc.Attributes = null;
                }
            }
            if (!wrapper)
            {
                if (vt.Result != VerificationResult.Error)
                {
                    return(0);                                       //even timeouts/unhandled, as we see timeouts with 1 error, 0 model
                }
                //process counterexamples OVER THE NEW IN-MEMORY PROGRAM
                var outputVars = new List <Variable>();
                foreach (var v in vt.DesiredOutputVars)
                {
                    outputVars.Add(newDict.Get(v.Name + "$VAR") as Variable);
                }

                var globals = new List <Variable>();
                foreach (IdentifierExpr ie in newEq.Proc.Modifies)
                {
                    globals.Add(ie.Decl);
                }


                if (SErrors != null &&
                    SErrors.Count > 0 &&
                    errModelList.Count == SErrors.Count) //change as now SErrors can be nonnull, yet Count == 0. Sometimes model.Count < SErrror!!
                {
                    //somewhat misnamed...
                    if (Options.DumpBeforeVerifying)
                    {
                        Log.Out(Log.SymEx, "Dumping procedure under verification");
                        newEq.Emit(Log.LogWriter, 0);
                    }
                    if (Options.DoSymEx)
                    {
                        var vtLeftProcImpl  = (Implementation)Util.getDeclarationByName(vt.Left.Name + "_Diff_Inline", procImplPIter);
                        var vtRightProcImpl = (Implementation)Util.getDeclarationByName(vt.Right.Name + "_Diff_Inline", procImplPIter);

                        if (Options.PreciseDifferentialInline)
                        {
                            List <Declaration> consts = prog.TopLevelDeclarations.Where(x => x is Constant).ToList();
                            ProcessCounterexamplesWOSymbolicOut(SErrors, globals, vt.Eq.LocVars, vtLeftProcImpl, vtRightProcImpl, consts, errModelList);
                        }
                        else
                        {
                            ProcessCounterexamples(SErrors, globals, outputVars, newProg, vtLeftProcImpl, vtRightProcImpl);
                        }
                    }
                }

                return(SErrors == null ? 0 : SErrors.Count);
            }
            return(0);
        }
Пример #9
0
        public static VerificationResult VerifyImplementation(VC.ConditionGeneration vcgen, Implementation impl, Program prog, out SDiffCounterexamples cex, out List <Model> errModelList)
        {
            VerifyImplCleanup vic;

            vic = new VerifyImplCleanup();
            vic.Visit(prog);


            cex          = null;
            errModelList = null;

            if (impl == null)
            {
                Log.Out(Log.Urgent, "VerifyImplementation saw null implementation");
                return(VerificationResult.Unknown);
            }

            //Log.Out(Log.Verifier, "Verifying implementation " + impl.Name);

            List <Counterexample> errors;
            List <Model>          errorsModel;
            VerificationResult    sdoutcome = VerificationResult.Unknown;

            VC.VCGen.Outcome outcome;

            //Log.Out(Log.Verifier, "Saving implementation before Boogie preprocessing");
            var duper            = new Duplicator();
            var imperativeBlocks = new Dictionary <string, Block>();

            foreach (Block b in impl.Blocks)
            {
                //new: to avoid repeated blocks (MYSTERY)
                if (!imperativeBlocks.ContainsKey(b.Label))
                {
                    imperativeBlocks.Add(b.Label, duper.VisitBlock(b));
                }
            }

            try
            {
                var start = DateTime.Now;

                //outcome = vcgen.VerifyImplementation(impl, prog, out errors);
                outcome      = vcgen.VerifyImplementation(impl, /*prog,*/ out errors, out errorsModel);
                errModelList = errorsModel;

                var end = DateTime.Now;

                TimeSpan elapsed = end - start;
                Console.WriteLine(string.Format("  [{0} s]  ", elapsed.TotalSeconds));
            }
            catch (VC.VCGenException e)
            {
                Log.Out(Log.Error, "Error BP5010: {0}  Encountered in implementation {1}: " + e.Message);
                errors  = null;
                outcome = VC.VCGen.Outcome.Inconclusive;
            }
            catch (UnexpectedProverOutputException upo)
            {
                Log.Out(Log.Error, "Advisory: {0} SKIPPED because of internal error: unexpected prover output: {1}" + upo.Message);
                errors  = null;
                outcome = VC.VCGen.Outcome.Inconclusive;
            }
            catch (Exception e)
            {
                Log.Out(Log.Error, "Unknown error somewhere in verification: ");
                Log.Out(Log.Error, e.ToString());
                return(VerificationResult.Unknown);
            }

            switch (outcome)
            {
            case VC.VCGen.Outcome.Correct:
                sdoutcome = VerificationResult.Verified;
                break;

            case VC.VCGen.Outcome.Errors:
                sdoutcome = VerificationResult.Error;
                break;

            case VC.VCGen.Outcome.Inconclusive:
                sdoutcome = VerificationResult.Inconclusive;
                break;

            case VC.VCGen.Outcome.OutOfMemory:
                sdoutcome = VerificationResult.OutOfMemory;
                break;

            case VC.VCGen.Outcome.TimedOut:
                sdoutcome = VerificationResult.TimeOut;
                break;
            }

            Log.Out(Log.Normal, outcome.ToString());

            var eqVarName = "";

            if (errors != null && errors.Count() == 1)
            {
                //eqVarName = errors[0];
            }

            Log.Out(Log.Verifier, (errors == null ? 0 : errors.Count) + " counterexamples...");

            if (errors != null)
            {
                cex = new SDiffCounterexamples();
                for (int i = 0; i < errors.Count; i++)
                {
                    if (Options.EnumerateAllPaths)
                    {
                        //just remove any time for this option
                        cex.Add(new SDiffCounterexample(errors[i], null, impl));
                        continue;
                    }

                    //reconstruct trace in terms of imperative blocks
                    var trace = ReconstructImperativeTrace(errors[i].Trace, imperativeBlocks);
                    if (SymEx.TraceValidator.Validate(trace))
                    {
                        Log.Out(Log.Cex, "Trace " + "[" + i + "]:");
                        Log.Out(Log.Cex, "Validating...");
                        Log.Out(Log.Cex, "Trace is not complete! Printing..");
                        SDiff.SymEx.CexDumper.PrintTrace(trace);
                        continue;
                    }
                    else
                    {
                        //Log.Out(Log.Cex, "Trace OK");
                        if (Options.DumpValidTraces)
                        {
                            SDiff.SymEx.CexDumper.PrintTrace(trace);
                        }
                    }

                    cex.Add(new SDiffCounterexample(errors[i], trace, impl));
                }
            }

            return(sdoutcome);
        }