Inheritance: IDisposable, IAnalysisLogger
        internal AggregatingLogger InitializeLogger(AnalyzeOptionsBase analyzeOptions)
        {
            _tool = Tool.CreateFromAssemblyData();

            var logger = new AggregatingLogger();

            if (!analyzeOptions.Quiet)
            {
                _consoleLogger = new ConsoleLogger(analyzeOptions.Verbose, _tool.Driver.Name)
                {
                    CaptureOutput = _captureConsoleOutput
                };
                logger.Loggers.Add(_consoleLogger);
            }

            if (analyzeOptions.ComputeFileHashes)
            {
                _resultsCachingLogger = new ResultsCachingLogger(analyzeOptions.Verbose);
                logger.Loggers.Add(_resultsCachingLogger);
            }

            if (analyzeOptions.Statistics)
            {
                logger.Loggers.Add(new StatisticsLogger());
            }

            return(logger);
        }
Ejemplo n.º 2
0
        private void InitializeOutputFile(TOptions analyzeOptions, TContext context, HashSet <string> targets)
        {
            string            filePath          = analyzeOptions.OutputFilePath;
            AggregatingLogger aggregatingLogger = (AggregatingLogger)context.Logger;

            if (!string.IsNullOrEmpty(filePath))
            {
                InvokeCatchingRelevantIOExceptions
                (
                    () =>
                {
                    LoggingOptions loggingOptions;
                    loggingOptions = analyzeOptions.ConvertToLoggingOptions();

                    var sarifLogger = new SarifLogger(
                        analyzeOptions.OutputFilePath,
                        loggingOptions,
                        null,
                        null,
                        targets,
                        Prerelease,
                        invocationTokensToRedact: GenerateSensitiveTokensList(),
                        invocationPropertiesToLog: analyzeOptions.InvocationPropertiesToLog);
                    sarifLogger.AnalysisStarted();
                    aggregatingLogger.Loggers.Add(sarifLogger);
                },
                    (ex) =>
                {
                    Errors.LogExceptionCreatingLogFile(context, filePath, ex);
                    ThrowExitApplicationException(context, ExitReason.ExceptionCreatingLogFile, ex);
                }
                );
            }
        }
        private void InitializeOutputFile(TOptions analyzeOptions, TContext context, ISet <string> targets)
        {
            string            filePath          = analyzeOptions.OutputFilePath;
            AggregatingLogger aggregatingLogger = (AggregatingLogger)context.Logger;

            if (!string.IsNullOrEmpty(filePath))
            {
                InvokeCatchingRelevantIOExceptions
                (
                    () =>
                {
                    LogFilePersistenceOptions logFilePersistenceOptions = analyzeOptions.ConvertToLogFilePersistenceOptions();

                    OptionallyEmittedData dataToInsert = analyzeOptions.DataToInsert.ToFlags();
                    OptionallyEmittedData dataToRemove = analyzeOptions.DataToRemove.ToFlags();

                    SarifLogger sarifLogger;

                    if (analyzeOptions.SarifOutputVersion != SarifVersion.OneZeroZero)
                    {
                        sarifLogger = new SarifLogger(
                            analyzeOptions.OutputFilePath,
                            logFilePersistenceOptions,
                            dataToInsert,
                            dataToRemove,
                            tool: _tool,
                            run: null,
                            analysisTargets: targets,
                            invocationTokensToRedact: GenerateSensitiveTokensList(),
                            invocationPropertiesToLog: analyzeOptions.InvocationPropertiesToLog,
                            levels: analyzeOptions.Level,
                            kinds: analyzeOptions.Kind);
                    }
                    else
                    {
                        sarifLogger = new SarifOneZeroZeroLogger(
                            analyzeOptions.OutputFilePath,
                            logFilePersistenceOptions,
                            dataToInsert,
                            dataToRemove,
                            tool: _tool,
                            run: null,
                            analysisTargets: targets,
                            invocationTokensToRedact: GenerateSensitiveTokensList(),
                            invocationPropertiesToLog: analyzeOptions.InvocationPropertiesToLog,
                            levels: analyzeOptions.Level,
                            kinds: analyzeOptions.Kind);
                    }
                    _pathToHashDataMap = sarifLogger.AnalysisTargetToHashDataMap;
                    sarifLogger.AnalysisStarted();
                    aggregatingLogger.Loggers.Add(sarifLogger);
                },
                    (ex) =>
                {
                    Errors.LogExceptionCreatingLogFile(context, filePath, ex);
                    ThrowExitApplicationException(context, ExitReason.ExceptionCreatingLogFile, ex);
                }
                );
            }
        }
        public override int Run(TOptions options)
        {
            //  To correctly initialize the logger, we must first add Hashes to dataToInsert
#pragma warning disable CS0618 // Type or member is obsolete
            if (options.ComputeFileHashes)
#pragma warning restore CS0618
            {
                OptionallyEmittedData dataToInsert = options.DataToInsert.ToFlags();
                dataToInsert |= OptionallyEmittedData.Hashes;

                options.DataToInsert = Enum.GetValues(typeof(OptionallyEmittedData)).Cast <OptionallyEmittedData>()
                                       .Where(oed => dataToInsert.HasFlag(oed)).ToList();
            }

            // 0. Initialize an common logger that drives all outputs. This
            //    object drives logging for console, statistics, etc.
            using (AggregatingLogger logger = InitializeLogger(options))
            {
                //  Once the logger has been correctly initialized, we can raise a warning
                _rootContext = CreateContext(options, logger, RuntimeErrors);
#pragma warning disable CS0618 // Type or member is obsolete
                if (options.ComputeFileHashes)
#pragma warning restore CS0618
                {
                    Warnings.LogObsoleteOption(_rootContext, "--hashes", SdkResources.ComputeFileHashes_ReplaceInsertHashes);
                }

                try
                {
                    Analyze(options, logger);
                }
                catch (ExitApplicationException <ExitReason> ex)
                {
                    // These exceptions have already been logged
                    ExecutionException = ex;
                    return(FAILURE);
                }
                catch (Exception ex)
                {
                    // These exceptions escaped our net and must be logged here
                    RuntimeErrors     |= Errors.LogUnhandledEngineException(_rootContext, ex);
                    ExecutionException = ex;
                    return(FAILURE);
                }
                finally
                {
                    logger.AnalysisStopped(RuntimeErrors);
                }
            }

            bool succeeded = (RuntimeErrors & ~RuntimeConditions.Nonfatal) == RuntimeConditions.None;

            if (options.RichReturnCode)
            {
                return((int)RuntimeErrors);
            }

            return(succeeded ? SUCCESS : FAILURE);
        }
Ejemplo n.º 5
0
        private void Analyze(TOptions analyzeOptions, AggregatingLogger logger)
        {
            // 0. Log analysis initiation
            logger.AnalysisStarted();

            // 1. Create context object to pass to skimmers. The logger
            //    and configuration objects are common to all context
            //    instances and will be passed on again for analysis.
            this.rootContext = CreateContext(analyzeOptions, logger, RuntimeErrors);

            // 2. Perform any command line argument validation beyond what
            //    the command line parser library is capable of.
            ValidateOptions(this.rootContext, analyzeOptions);

            // 3. Create our configuration property bag, which will be
            //    shared with all rules during analysis
            //ConfigureFromOptions(this.rootContext, analyzeOptions);

            // 4. Produce a comprehensive set of analysis targets
            HashSet <string> targets = CreateTargetsSet(analyzeOptions);

            // 5. Proactively validate that we can locate and
            //    access all analysis targets. Helper will return
            //    a list that potentially filters out files which
            //    did not exist, could not be accessed, etc.
            targets = ValidateTargetsExist(this.rootContext, targets);

            // 6. Initialize report file, if configured.
            InitializeOutputFile(analyzeOptions, this.rootContext, targets);

            // 7. Instantiate skimmers.
            HashSet <ISkimmer <TContext> > skimmers = CreateSkimmers(this.rootContext);

            // 8. Initialize configuration. This step must be done after initializing
            //    the skimmers, as rules define their specific context objects and
            //    so those assemblies must be loaded.
            InitializeConfiguration(analyzeOptions, this.rootContext);

            // 9. Initialize skimmers. Initialize occurs a single time only. This
            //    step needs to occurs after initializing configuration in order
            //    to allow command-line override of rule settings
            skimmers = InitializeSkimmers(skimmers, this.rootContext);

            // 10. Run all analysis
            AnalyzeTargets(analyzeOptions, skimmers, this.rootContext, targets);

            // 11. For test purposes, raise an unhandled exception if indicated
            if (RaiseUnhandledExceptionInDriverCode)
            {
                throw new InvalidOperationException(this.GetType().Name);
            }
        }
Ejemplo n.º 6
0
        private void InitializeOutputFile(TOptions analyzeOptions, TContext context, HashSet <string> targets)
        {
            string            filePath          = analyzeOptions.OutputFilePath;
            AggregatingLogger aggregatingLogger = (AggregatingLogger)context.Logger;

            if (!string.IsNullOrEmpty(filePath))
            {
                InvokeCatchingRelevantIOExceptions
                (
                    () =>
                {
                    LoggingOptions loggingOptions;
                    loggingOptions = analyzeOptions.ConvertToLoggingOptions();

                    OptionallyEmittedData dataToInsert = OptionallyEmittedData.None;
                    if (analyzeOptions.DataToInsert != null)
                    {
                        Array.ForEach(analyzeOptions.DataToInsert, data => dataToInsert |= data);
                    }

                    // This code is required in order to support the obsoleted ComputeFileHashes argument
                    // on the analyze command-line;
                    if (analyzeOptions.ComputeFileHashes)
                    {
                        dataToInsert |= OptionallyEmittedData.Hashes;
                    }

                    var sarifLogger = new SarifLogger(
                        analyzeOptions.OutputFilePath,
                        loggingOptions,
                        dataToInsert,
                        null,
                        null,
                        targets,
                        Prerelease,
                        invocationTokensToRedact: GenerateSensitiveTokensList(),
                        invocationPropertiesToLog: analyzeOptions.InvocationPropertiesToLog);
                    sarifLogger.AnalysisStarted();
                    aggregatingLogger.Loggers.Add(sarifLogger);
                },
                    (ex) =>
                {
                    Errors.LogExceptionCreatingLogFile(context, filePath, ex);
                    ThrowExitApplicationException(context, ExitReason.ExceptionCreatingLogFile, ex);
                }
                );
            }
        }
Ejemplo n.º 7
0
        internal AggregatingLogger InitializeLogger(AnalyzeOptionsBase analyzeOptions)
        {
            var logger = new AggregatingLogger();

            if (!analyzeOptions.Quiet)
            {
                logger.Loggers.Add(new ConsoleLogger(analyzeOptions.Verbose));
            }

            if (analyzeOptions.Statistics)
            {
                logger.Loggers.Add(new StatisticsLogger());
            }

            return(logger);
        }
        internal AggregatingLogger InitializeLogger(AnalyzeOptionsBase analyzeOptions)
        {
            _tool = Tool.CreateFromAssemblyData();

            var logger = new AggregatingLogger();

            if (!analyzeOptions.Quiet)
            {
                _consoleLogger = new ConsoleLogger(analyzeOptions.Quiet, _tool.Driver.Name, analyzeOptions.Level, analyzeOptions.Kind)
                {
                    CaptureOutput = _captureConsoleOutput
                };
                logger.Loggers.Add(_consoleLogger);
            }

            return(logger);
        }
        public override int Run(TOptions options)
        {
            // Initialize an common logger that drives all outputs. This
            // object drives logging for console, statistics, etc.
            using (AggregatingLogger logger = InitializeLogger(options))
            {
                try
                {
                    Analyze(options, logger);
                }
                catch (ExitApplicationException <ExitReason> ex)
                {
                    // These exceptions have already been logged
                    ExecutionException = ex;
                    return(FAILURE);
                }
                catch (Exception ex)
                {
                    ex = ex.InnerException ?? ex;

                    if (!(ex is ExitApplicationException <ExitReason>))
                    {
                        // These exceptions escaped our net and must be logged here
                        RuntimeErrors |= Errors.LogUnhandledEngineException(_rootContext, ex);
                    }
                    ExecutionException = ex;
                    return(FAILURE);
                }
                finally
                {
                    logger.AnalysisStopped(RuntimeErrors);
                }
            }

            bool succeeded = (RuntimeErrors & ~RuntimeConditions.Nonfatal) == RuntimeConditions.None;

            if (options.RichReturnCode)
            {
                return((int)RuntimeErrors);
            }

            return(succeeded ? SUCCESS : FAILURE);
        }
        private void Analyze(TOptions analyzeOptions, AggregatingLogger logger)
        {
            // 0. Log analysis initiation
            logger.AnalysisStarted();

            // 1. Create context object to pass to skimmers. The logger
            //    and configuration objects are common to all context
            //    instances and will be passed on again for analysis.
            _rootContext = CreateContext(analyzeOptions, logger, RuntimeErrors);

            // 2. Perform any command line argument validation beyond what
            //    the command line parser library is capable of.
            ValidateOptions(analyzeOptions, _rootContext);

            // 5. Initialize report file, if configured.
            InitializeOutputFile(analyzeOptions, _rootContext);

            // 6. Instantiate skimmers.
            ISet <Skimmer <TContext> > skimmers = CreateSkimmers(analyzeOptions, _rootContext);

            // 7. Initialize configuration. This step must be done after initializing
            //    the skimmers, as rules define their specific context objects and
            //    so those assemblies must be loaded.
            InitializeConfiguration(analyzeOptions, _rootContext);

            // 8. Initialize skimmers. Initialize occurs a single time only. This
            //    step needs to occurs after initializing configuration in order
            //    to allow command-line override of rule settings
            skimmers = InitializeSkimmers(skimmers, _rootContext);

            // 9. Run all multi-threaded analysis operations.
            AnalyzeTargets(analyzeOptions, _rootContext, skimmers);

            // 10. For test purposes, raise an unhandled exception if indicated
            if (RaiseUnhandledExceptionInDriverCode)
            {
                throw new InvalidOperationException(GetType().Name);
            }
        }
Ejemplo n.º 11
0
        internal AggregatingLogger InitializeLogger(AnalyzeOptionsBase analyzeOptions)
        {
            _tool = Tool.CreateFromAssemblyData();

            var logger = new AggregatingLogger();

            if (!analyzeOptions.Quiet)
            {
                _consoleLogger = new ConsoleLogger(analyzeOptions.Verbose, _tool.Driver.Name)
                {
                    CaptureOutput = _captureConsoleOutput
                };
                logger.Loggers.Add(_consoleLogger);
            }

            if ((analyzeOptions.DataToInsert.ToFlags() & OptionallyEmittedData.Hashes) != 0)
            {
                _cacheByFileHashLogger = new CacheByFileHashLogger(analyzeOptions.Verbose);
                logger.Loggers.Add(_cacheByFileHashLogger);
            }

            return(logger);
        }
        private void InitializeOutputFile(TOptions analyzeOptions, TContext context, HashSet <string> targets)
        {
            string            filePath          = analyzeOptions.OutputFilePath;
            AggregatingLogger aggregatingLogger = (AggregatingLogger)context.Logger;

            if (!string.IsNullOrEmpty(filePath))
            {
                InvokeCatchingRelevantIOExceptions
                (
                    () =>
                {
                    LoggingOptions loggingOptions;
                    loggingOptions = analyzeOptions.ConvertToLoggingOptions();

                    OptionallyEmittedData dataToInsert = analyzeOptions.DataToInsert.ToFlags();
                    OptionallyEmittedData dataToRemove = analyzeOptions.DataToRemove.ToFlags();

                    // This code is required in order to support the obsolete ComputeFileHashes argument
                    // on the analyze command-line.
                    if (analyzeOptions.ComputeFileHashes)
                    {
                        dataToInsert |= OptionallyEmittedData.Hashes;
                    }

                    SarifLogger sarifLogger;

                    if (analyzeOptions.SarifOutputVersion != SarifVersion.OneZeroZero)
                    {
                        sarifLogger = new SarifLogger(
                            analyzeOptions.OutputFilePath,
                            loggingOptions,
                            dataToInsert,
                            dataToRemove,
                            tool: _tool,
                            run: null,
                            analysisTargets: targets,
                            invocationTokensToRedact: GenerateSensitiveTokensList(),
                            invocationPropertiesToLog: analyzeOptions.InvocationPropertiesToLog);
                    }
                    else
                    {
                        sarifLogger = new SarifOneZeroZeroLogger(
                            analyzeOptions.OutputFilePath,
                            loggingOptions,
                            dataToInsert,
                            dataToRemove,
                            tool: _tool,
                            run: null,
                            analysisTargets: targets,
                            invocationTokensToRedact: GenerateSensitiveTokensList(),
                            invocationPropertiesToLog: analyzeOptions.InvocationPropertiesToLog);
                    }
                    _pathToHashDataMap = sarifLogger.AnalysisTargetToHashDataMap;
                    sarifLogger.AnalysisStarted();
                    aggregatingLogger.Loggers.Add(sarifLogger);
                },
                    (ex) =>
                {
                    Errors.LogExceptionCreatingLogFile(context, filePath, ex);
                    ThrowExitApplicationException(context, ExitReason.ExceptionCreatingLogFile, ex);
                }
                );
            }
        }