Пример #1
0
 public LimitLoopBoundScheduler(IStateScheduler underlyingScheduler, BigInteger loopBound)
 {
     this.UnderlyingScheduler = underlyingScheduler;
     this.LoopBound           = loopBound;
     if (this.LoopBound < 0)
     {
         throw new ArgumentException("Invalid loop bound");
     }
     this.StateToCurrentLoops = new Dictionary <ExecutionState, ExecutionStateNestedLoopInfo>();
     this.ProgramLoopInfo     = null; // Set elsewhere
     this.Executor            = null; // Set elsewhere
 }
Пример #2
0
        private void ExploreOrderInit(IStateScheduler scheduler, out Implementation main, out Block entryBlock, out List <Block> l)
        {
            p = LoadProgramFrom("programs/StateScheduleTest.bpl");
            e = GetExecutor(p, scheduler, GetSolver());

            main       = p.TopLevelDeclarations.OfType <Implementation>().Where(i => i.Name == "main").First();
            entryBlock = main.Blocks[0];
            Assert.AreEqual("entry", entryBlock.Label);

            // Collect "l<N>" blocks
            l = new List <Block>();
            for (int index = 0; index <= 5; ++index)
            {
                l.Add(main.Blocks[index + 1]);
                Assert.AreEqual("l" + index, l[index].Label);
            }
        }
Пример #3
0
        public static IStateScheduler GetScheduler(CmdLineOpts options)
        {
            IStateScheduler scheduler = null;

            switch (options.scheduler)
            {
            case CmdLineOpts.Scheduler.DFS:
                scheduler = new DFSStateScheduler();
                break;

            case CmdLineOpts.Scheduler.BFS:
                scheduler = new BFSStateScheduler();
                break;

            case CmdLineOpts.Scheduler.UntilEndBFS:
                scheduler = new UntilTerminationBFSStateScheduler();
                break;

            case CmdLineOpts.Scheduler.AltBFS:
                scheduler = new AlternativeBFSStateScheduler();
                break;

            default:
                throw new ArgumentException("Unsupported scheduler");
            }

            if (options.PreferLoopEscapingPaths > 0)
            {
                scheduler = new LoopEscapingScheduler(scheduler);
            }

            if (options.MaxLoopDepth > 0)
            {
                scheduler = new LimitLoopBoundScheduler(scheduler, options.MaxLoopDepth);
            }

            return(scheduler);
        }
Пример #4
0
        public static Executor GetExecutor(Program p, IStateScheduler scheduler = null, ISolver solver = null, bool useConstantFolding = false)
        {
            if (scheduler == null)
            {
                scheduler = new DFSStateScheduler();
            }

            if (solver == null)
            {
                solver = new SimpleSolver(new DummySolver());
            }

            IExprBuilder builder = new SimpleExprBuilder(/*immutable=*/ true);

            if (useConstantFolding)
            {
                builder = new ConstantFoldingExprBuilder(new ConstantCachingExprBuilder(builder));
            }

            Executor e = new Executor(p, scheduler, solver, builder, new SimpleSymbolicPool());

            return(e);
        }
Пример #5
0
 public LimitExplicitDepthScheduler(IStateScheduler underlyingScheduler, int maxDepth)
 {
     this.UnderlyingStateScheduler = underlyingScheduler;
     this.MaxDepth = maxDepth;
 }
Пример #6
0
        private void SimpleLoop(IStateScheduler scheduler)
        {
            p = LoadProgramFrom("programs/SimpleLoop.bpl");
            e = GetExecutor(p, scheduler, GetSolver(), /*useConstantFolding=*/ true);

            var main = p.TopLevelDeclarations.OfType <Implementation>().Where(i => i.Name == "main").First();

            var boundsVar = main.InParams[0];

            var entryBlock = main.Blocks[0];

            Assert.AreEqual("entry", entryBlock.Label);

            var loopHead = main.Blocks[1];

            Assert.AreEqual("loopHead", loopHead.Label);

            var loopBody = main.Blocks[2];

            Assert.AreEqual("loopBody", loopBody.Label);
            var loopBodyAssume = loopBody.Cmds[0] as AssumeCmd;

            Assert.IsNotNull(loopBodyAssume);

            var loopExit = main.Blocks[3];

            Assert.AreEqual("loopDone", loopExit.Label);
            var loopExitAssume = loopExit.Cmds[0] as AssumeCmd;

            Assert.IsNotNull(loopExitAssume);

            var exitBlock = main.Blocks[4];

            Assert.AreEqual("exit", exitBlock.Label);

            var tc = new TerminationCounter();

            tc.Connect(e);

            int change             = 1;
            int contextChangeCount = 0;

            e.ContextChanged += delegate(object sender, Executor.ContextChangeEventArgs eventArgs)
            {
                ++contextChangeCount;

                // FIXME:
                //var symbolicForBound = eventArgs.Previous.Symbolics.Where( s => s.Origin.IsVariable && s.Origin.AsVariable == boundsVar).First();
                SymbolicVariable symbolicForBound = null; // Just so we can compile

                if (change == 1)
                {
                    // FIXME: The Executor shouldn't pop the last stack frame so we can check where we terminated successfully
                    Assert.IsTrue(eventArgs.Previous.TerminationType.ExitLocation.IsTransferCmd);
                    Assert.IsTrue(eventArgs.Previous.TerminationType.ExitLocation.AsTransferCmd is ReturnCmd);
                    Assert.IsTrue(eventArgs.Previous.Finished());
                    Assert.AreEqual(3, eventArgs.Previous.Constraints.Count);
                    var exitConstraint = eventArgs.Previous.Constraints.Constraints.Where(c => c.Origin.IsCmd && c.Origin.AsCmd == loopExitAssume);
                    Assert.AreEqual(1, exitConstraint.Count());
                    Assert.AreEqual(symbolicForBound.Name + " <= 0", exitConstraint.First().Condition.ToString());

                    Assert.AreSame(loopBody, eventArgs.Next.GetCurrentBlock());
                    Assert.AreEqual(2, eventArgs.Next.Constraints.Count);
                    var bodyConstraint = eventArgs.Next.Constraints.Constraints.Where(c => c.Origin.IsCmd && c.Origin.AsCmd == loopBodyAssume);
                    Assert.AreEqual(1, bodyConstraint.Count());
                    Assert.AreEqual("0 < " + symbolicForBound.Name, bodyConstraint.First().Condition.ToString());
                }
                else if (change == 2)
                {
                    Assert.IsTrue(eventArgs.Previous.Finished());
                    Assert.AreSame(loopBody, eventArgs.Next.GetCurrentBlock());
                    Assert.AreEqual(4, eventArgs.Previous.Constraints.Count);

                    var exitConstraint = eventArgs.Previous.Constraints.Constraints.Where(c => c.Origin.IsCmd && c.Origin.AsCmd == loopExitAssume);
                    Assert.AreEqual(1, exitConstraint.Count());
                    Assert.AreEqual(symbolicForBound.Name + " <= 1", exitConstraint.First().Condition.ToString());

                    Assert.AreSame(loopBody, eventArgs.Next.GetCurrentBlock());
                    Assert.AreEqual(3, eventArgs.Next.Constraints.Count);
                    var bodyConstraints = eventArgs.Next.Constraints.Constraints.Where(c => c.Origin.IsCmd && c.Origin.AsCmd == loopBodyAssume).ToList();
                    Assert.AreEqual(2, bodyConstraints.Count());
                    Assert.AreEqual("0 < " + symbolicForBound.Name, bodyConstraints[0].Condition.ToString());
                    Assert.AreEqual("1 < " + symbolicForBound.Name, bodyConstraints[1].Condition.ToString());
                }


                ++change;
            };

            e.Run(main);
            Assert.AreEqual(3, tc.NumberOfTerminatedStates);
            Assert.AreEqual(3, tc.Sucesses);
            Assert.AreEqual(2, contextChangeCount);
        }
Пример #7
0
        public static int RealMain(String[] args)
        {
            // Debug log output goes to standard error.
            Debug.Listeners.Add(new ExceptionThrowingTextWritierTraceListener(Console.Error));

            // FIXME: Urgh... we are forced to use Boogie's command line
            // parser becaue the Boogie program resolver/type checker
            // is dependent on the parser being used...EURGH!
            CommandLineOptions.Install(new Microsoft.Boogie.CommandLineOptions());


            var options = new CmdLineOpts();

            if (!CommandLine.Parser.Default.ParseArguments(args, options))
            {
                Console.WriteLine("Failed to parse args");
                ExitWith(ExitCode.COMMAND_LINE_ERROR);
            }

            if (options.boogieProgramPath == null)
            {
                Console.WriteLine("A boogie program must be specified. See --help");
                ExitWith(ExitCode.COMMAND_LINE_ERROR);
            }

            if (!File.Exists(options.boogieProgramPath))
            {
                Console.WriteLine("Boogie program \"" + options.boogieProgramPath + "\" does not exist");
                ExitWith(ExitCode.COMMAND_LINE_ERROR);
            }


            Program program = null;

            if (options.Defines != null)
            {
                foreach (var define in options.Defines)
                {
                    Console.WriteLine("Adding define \"" + define + "\" to Boogie parser");
                }
            }

            int errors = Microsoft.Boogie.Parser.Parse(options.boogieProgramPath, options.Defines, out program);

            if (errors != 0)
            {
                Console.WriteLine("Failed to parse");
                ExitWith(ExitCode.PARSE_ERROR);
            }

            errors = program.Resolve();

            if (errors != 0)
            {
                Console.WriteLine("Failed to resolve.");
                ExitWith(ExitCode.RESOLVE_ERROR);
            }

            if (options.useModSetTransform > 0)
            {
                // This is useful for Boogie Programs produced by the GPUVerify tool that
                // have had instrumentation added that invalidates the modset attached to
                // procedures. By running the analysis we may modify the modsets attached to
                // procedures in the program to be correct so that Boogie's Type checker doesn't
                // produce an error.
                var modsetAnalyser = new ModSetCollector();
                modsetAnalyser.DoModSetAnalysis(program);
            }

            errors = program.Typecheck();

            if (errors != 0)
            {
                Console.WriteLine("Failed to Typecheck.");
                ExitWith(ExitCode.TYPECHECK_ERROR);
            }


            IStateScheduler scheduler = GetScheduler(options);

            // Limit Depth if necessary
            if (options.MaxDepth >= 0)
            {
                scheduler = new LimitExplicitDepthScheduler(scheduler, options.MaxDepth);
                Console.WriteLine("Using Depth limit:{0}", options.MaxDepth);
            }

            if (options.FailureLimit < 0)
            {
                Console.Error.WriteLine("FailureLimit must be >= 0");
                ExitWith(ExitCode.COMMAND_LINE_ERROR);
            }


            Console.WriteLine("Using Scheduler: {0}", scheduler.ToString());

            var           nonSpeculativeterminationCounter = new TerminationCounter(TerminationCounter.CountType.ONLY_NON_SPECULATIVE);
            var           speculativeTerminationCounter    = new TerminationCounter(TerminationCounter.CountType.ONLY_SPECULATIVE);
            IExprBuilder  builder      = new SimpleExprBuilder(/*immutable=*/ true);
            ISymbolicPool symbolicPool = null;

            if (options.useSymbolicPoolCache > 0)
            {
                throw new Exception("DON'T USE THIS. IT'S BROKEN");
                symbolicPool = new CachingSymbolicPool();
            }
            else
            {
                symbolicPool = new SimpleSymbolicPool();
            }

            Console.WriteLine("Using Symbolic Pool: {0}", symbolicPool.ToString());

            if (options.useConstantFolding > 0)
            {
                if (options.ConstantCaching > 0)
                {
                    Console.WriteLine("Using ConstantCachingExprBuilder");
                    builder = new ConstantCachingExprBuilder(builder);
                }

                builder = new ConstantFoldingExprBuilder(builder);
            }

            // Destroy the solver when we stop using it
            using (var solver = BuildSolverChain(options))
            {
                Executor executor = new Executor(program, scheduler, solver, builder, symbolicPool);

                executor.ExecutorTimeoutReached += delegate(object sender, Executor.ExecutorTimeoutReachedArgs eventArgs)
                {
                    TimeoutHit = true; // Record so we can set the exitcode appropriately later
                    Console.Error.WriteLine("Timeout hit. Trying to kill Executor (may wait for solver)");
                };

                // Check all implementations exist and build list of entry points to execute
                var entryPoints = new List <Implementation>();

                // This is specific to GPUVerify
                if (options.gpuverifyEntryPoints)
                {
                    var kernels = program.TopLevelDeclarations.OfType <Implementation>().Where(impl => QKeyValue.FindBoolAttribute(impl.Attributes, "kernel"));
                    foreach (var kernel in kernels)
                    {
                        entryPoints.Add(kernel);
                    }

                    if (entryPoints.Count() == 0)
                    {
                        Console.WriteLine("Could not find any kernel entry points");
                        ExitWith(ExitCode.ENTRY_POINT_NOT_FOUND_ERROR);
                    }
                }
                else
                {
                    // Set main as default.
                    if (options.entryPoints == null)
                    {
                        options.entryPoints = new List <string>()
                        {
                            "main"
                        }
                    }
                    ;

                    foreach (var implString in options.entryPoints)
                    {
                        Implementation entry = program.TopLevelDeclarations.OfType <Implementation>().Where(i => i.Name == implString).FirstOrDefault();
                        if (entry == null)
                        {
                            Console.WriteLine("Could not find implementation \"" + implString + "\" to use as entry point");
                            ExitWith(ExitCode.ENTRY_POINT_NOT_FOUND_ERROR);
                        }
                        entryPoints.Add(entry);
                    }
                }

                if (options.useInstructionPrinter)
                {
                    Console.WriteLine("Installing instruction printer");
                    var instrPrinter = new InstructionPrinter(Console.Out);
                    instrPrinter.Connect(executor);
                }

                if (options.useCallSequencePrinter)
                {
                    Console.WriteLine("Installing call sequence printer");
                    var callPrinter = new CallPrinter(Console.Out);
                    callPrinter.Connect(executor);
                }

                if (options.gotoAssumeLookAhead > 0)
                {
                    executor.UseGotoLookAhead = true;
                }
                else
                {
                    executor.UseGotoLookAhead = false;
                }

                if (options.ForkAtPredicatedAssign)
                {
                    executor.UseForkAtPredicatedAssign = true;
                }

                if (options.CheckEntryRequires > 0)
                {
                    executor.CheckEntryRequires = true;
                }
                else
                {
                    Console.WriteLine("Warning: Requires at the entry point are not being checked");
                    executor.CheckEntryRequires = false;
                }

                if (options.CheckEntryAxioms > 0)
                {
                    executor.CheckEntryAxioms = true;
                }
                else
                {
                    Console.WriteLine("Warning: Axioms are not being checked");
                    executor.CheckEntryAxioms = false;
                }

                if (options.CheckUniqueVariableDecls > 0)
                {
                    executor.CheckUniqueVariableDecls = true;
                }
                else
                {
                    Console.WriteLine("Warning: Unique variables are not being checked");
                    executor.CheckUniqueVariableDecls = false;
                }

                if (options.GlobalDDE > 0)
                {
                    executor.UseGlobalDDE = true;
                    Console.WriteLine("WARNING: Using GlobalDDE. This may remove unsatisfiable axioms");
                }
                else
                {
                    executor.UseGlobalDDE = false;
                }

                // Just print a message about break points for now.
                executor.BreakPointReached += BreakPointPrinter.handleBreakPoint;

                // Write to the console about context changes
                var contextChangeReporter = new ContextChangedReporter();
                contextChangeReporter.Connect(executor);

                var stateHandler = new TerminationConsoleReporter();
                stateHandler.Connect(executor);

                nonSpeculativeterminationCounter.Connect(executor);
                speculativeTerminationCounter.Connect(executor);

                if (options.FileLogging > 0)
                {
                    SetupFileLoggers(options, executor, solver);
                }

                SetupTerminationCatchers(executor);
                ApplyFilters(executor, options);

                if (options.FailureLimit > 0)
                {
                    var failureLimiter = new FailureLimiter(options.FailureLimit);
                    failureLimiter.Connect(executor);
                    Console.WriteLine("Using failure limit of {0}", options.FailureLimit);
                }

                try
                {
                    // Supply our own PassManager for preparation so we can hook into its events
                    executor.PreparationPassManager = GetPassManager(options);

                    foreach (var entryPoint in entryPoints)
                    {
                        Console.ForegroundColor = ConsoleColor.Cyan;
                        Console.WriteLine("Entering Implementation " + entryPoint.Name + " as entry point");
                        Console.ResetColor();
                        executor.Run(entryPoint, options.timeout);
                    }
                }
                catch (InitialStateTerminated)
                {
                    if (options.CatchExceptions == 0)
                    {
                        throw;
                    }
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Error.WriteLine("The initial state terminated. Execution cannot continue");
                    Console.ResetColor();
                    ExitWith(ExitCode.INITIAL_STATE_TERMINATED);
                }
                catch (RecursiveFunctionDetectedException rfdException)
                {
                    if (options.CatchExceptions == 0)
                    {
                        throw;
                    }
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Error.WriteLine("Detected the following recursive functions");
                    foreach (var function in rfdException.Functions)
                    {
                        Console.Error.Write(function.Name + ": ");
                        if (function.Body != null)
                        {
                            Console.Error.WriteLine(function.Body.ToString());
                        }

                        if (function.DefinitionAxiom != null)
                        {
                            Console.Error.WriteLine(function.DefinitionAxiom.Expr.ToString());
                        }
                    }
                    Console.ResetColor();
                    ExitWith(ExitCode.RECURSIVE_FUNCTIONS_FOUND_ERROR);
                }
                catch (OutOfMemoryException e)
                {
                    if (options.CatchExceptions == 0)
                    {
                        throw;
                    }
                    Console.Error.WriteLine("Ran out of memory!");
                    Console.Error.WriteLine(e.ToString());
                    ExitWith(ExitCode.OUT_OF_MEMORY);
                }
                catch (NotImplementedException e)
                {
                    if (options.CatchExceptions == 0)
                    {
                        throw;
                    }
                    Console.Error.WriteLine("Feature not implemented!");
                    Console.Error.WriteLine(e.ToString());
                    ExitWith(ExitCode.NOT_IMPLEMENTED_EXCEPTION);
                }
                catch (NotSupportedException e)
                {
                    if (options.CatchExceptions == 0)
                    {
                        throw;
                    }
                    Console.Error.WriteLine("Feature not supported!");
                    Console.Error.WriteLine(e.ToString());
                    ExitWith(ExitCode.NOT_SUPPORTED_EXCEPTION);
                }


                Console.WriteLine("Finished executing");
                DumpStats(executor, solver, nonSpeculativeterminationCounter, speculativeTerminationCounter);
            }

            if (TimeoutHit)
            {
                ExitWith(nonSpeculativeterminationCounter.NumberOfFailures > 0 ? ExitCode.ERRORS_TIMEOUT : ExitCode.NO_ERRORS_TIMEOUT);
                throw new InvalidOperationException("Unreachable");
            }

            var exitCode = nonSpeculativeterminationCounter.NumberOfFailures > 0 ? ExitCode.ERRORS_NO_TIMEOUT : ExitCode.NO_ERRORS_NO_TIMEOUT;

            if (exitCode == ExitCode.NO_ERRORS_NO_TIMEOUT)
            {
                // If no errors were found we may need to pick a different exit code
                // because path exploration may not have been exhaustive due to speculative paths
                // or hitting a bound. This isn't perfect because we may hit a bound and have speculative
                // paths so we could use either exit code in this case.
                if (nonSpeculativeterminationCounter.DisallowedSpeculativePaths > 0 || speculativeTerminationCounter.NumberOfTerminatedStates > 0)
                {
                    exitCode = ExitCode.NO_ERRORS_NO_TIMEOUT_BUT_FOUND_SPECULATIVE_PATHS;
                    Console.WriteLine("NOTE: Bugs may have been missed!");
                }
                else if (nonSpeculativeterminationCounter.DisallowedPathDepths > 0)
                {
                    exitCode = ExitCode.NO_ERRORS_NO_TIMEOUT_BUT_HIT_BOUND;
                    Console.WriteLine("NOTE: Bugs may have been missed!");
                }
            }
            ExitWith(exitCode);
            return((int)exitCode); // This is required to keep the compiler happy.
        }
Пример #8
0
 public LoopEscapingScheduler(IStateScheduler underlyingScheduler)
 {
     this.UnderlyingScheduler = underlyingScheduler;
     this.LoopEscapingStates  = new Stack <ExecutionState>();
     // Deliberately do not initialise EscapingBlocks here
 }