public void variableCache()
        {
            var prog = SymbooglixLibTests.SymbooglixTest.LoadProgramFrom(@"
            procedure main()
            {
                var x:int;
                var y:int;
                return;
            }
            ", "test.bpl");

            // The Program needs to be annotated with ProgramLocations for this test to work
            var PM = new Symbooglix.Transform.PassManager();

            PM.Add(new Symbooglix.Annotation.ProgramLocationAnnotater());
            PM.Run(prog);

            var pool = new CachingSymbolicPool();

            // Get the Variables we will request SymbolicVariables for
            var mainImpl = prog.TopLevelDeclarations.OfType <Implementation>().Where(i => i.Name == "main").First();
            var xVar     = mainImpl.LocVars[0];
            var yVar     = mainImpl.LocVars[1];

            // Make a few ExecutionStates. We don't need to do anything with them, we are effectively using
            // them as a key into our data structure
            var state0 = MkExecutionState();
            var state1 = state0.Clone(xVar.GetProgramLocation()); // HACK: Just use any old program location
            var state2 = state1.Clone(xVar.GetProgramLocation());

            var xSyms = new List <SymbolicVariable>();
            var ySyms = new List <SymbolicVariable>();

            xSyms.Add(pool.GetFreshSymbolic(xVar, state0));
            ySyms.Add(pool.GetFreshSymbolic(yVar, state0));

            xSyms.Add(pool.GetFreshSymbolic(xVar, state1));
            xSyms.Add(pool.GetFreshSymbolic(xVar, state2));
            ySyms.Add(pool.GetFreshSymbolic(yVar, state1));
            ySyms.Add(pool.GetFreshSymbolic(yVar, state2));

            // Now check we only ever got two instances

            foreach (var sym in xSyms)
            {
                Assert.IsNotNull(sym);
                Assert.AreSame(xSyms[0], sym);
            }

            foreach (var sym in ySyms)
            {
                Assert.IsNotNull(sym);
                Assert.AreSame(ySyms[0], sym);
            }

            // Now State1 will ask for a new symbolic so it should get something new
            var xSymFirst = xSyms[0];

            xSyms.Clear();
            xSyms.Add(pool.GetFreshSymbolic(xVar, state1));
            xSyms.Add(pool.GetFreshSymbolic(xVar, state0));
            xSyms.Add(pool.GetFreshSymbolic(xVar, state2));

            Assert.AreNotSame(xSymFirst, xSyms[0]);

            foreach (var sym in xSyms)
            {
                Assert.IsNotNull(sym);
                Assert.AreSame(xSyms[0], sym);
            }

            // Create a new state it should not get xSymFirst because even though it has never asked for a symbolic before
            // the cache should be aware it is a child of state 1 which has already been given "xSymFirst".
            var state3        = state1.Clone(xVar.GetProgramLocation());
            var state3Request = pool.GetFreshSymbolic(xVar, state3);

            Assert.AreNotSame(xSymFirst, state3Request);
        }
Exemple #2
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.
        }
        public void ModsetCache()
        {
            var prog = SymbooglixLibTests.SymbooglixTest.LoadProgramFrom(@"
            var g:int;
            var h:int;
            procedure main()
            modifies g, h;
            {
                g := 0;
                return;
            }
            ", "test.bpl");

            // The Program needs to be annotated with ProgramLocations for this test to work
            var PM = new Symbooglix.Transform.PassManager();

            PM.Add(new Symbooglix.Annotation.ProgramLocationAnnotater());
            PM.Run(prog);

            var pool = new CachingSymbolicPool();

            var proc = prog.TopLevelDeclarations.OfType <Procedure>().Where(p => p.Name == "main").First();

            // Make a few ExecutionStates. We don't need to do anything with them, we are effectively using
            // them as a key into our data structure
            var state0 = MkExecutionState();
            var state1 = state0.Clone(proc.GetModSetProgramLocation()); // HACK: Just use any old program location
            var state2 = state1.Clone(proc.GetModSetProgramLocation());


            var gVars = new List <SymbolicVariable>();
            var hVars = new List <SymbolicVariable>();

            gVars.Add(pool.GetFreshSymbolic(proc, 0, state0));
            gVars.Add(pool.GetFreshSymbolic(proc, 0, state1));
            gVars.Add(pool.GetFreshSymbolic(proc, 0, state2));

            hVars.Add(pool.GetFreshSymbolic(proc, 1, state0));
            hVars.Add(pool.GetFreshSymbolic(proc, 1, state1));
            hVars.Add(pool.GetFreshSymbolic(proc, 1, state2));

            foreach (var sym in gVars)
            {
                Assert.IsNotNull(sym);
                Assert.AreSame(gVars[0], sym);
            }

            foreach (var sym in hVars)
            {
                Assert.IsNotNull(sym);
                Assert.AreSame(hVars[0], sym);
            }

            // Now State1 will ask for a new symbolic so it should get something new
            var gSymFirst = gVars[0];

            gVars.Clear();
            gVars.Add(pool.GetFreshSymbolic(proc, 0, state1));
            gVars.Add(pool.GetFreshSymbolic(proc, 0, state0));
            gVars.Add(pool.GetFreshSymbolic(proc, 0, state2));

            Assert.AreNotSame(gSymFirst, gVars[0]);

            foreach (var sym in gVars)
            {
                Assert.IsNotNull(sym);
                Assert.AreSame(gVars[0], sym);
            }

            // Create a new state it should not get gSymFirst because even though it has never asked for a symbolic before
            // the cache should be aware it is a child of state 1 which has already been given "xSymFirst".
            var state3        = state1.Clone(proc.GetModSetProgramLocation()); // HACK: Use any old program location
            var state3Request = pool.GetFreshSymbolic(proc, 0, state3);

            Assert.AreNotSame(gSymFirst, state3Request);
        }