private static async Task <SourceFile> createSourceFileAsync(string filePath, Configuration configuration, Project project)
        {
            try
            {
                await Instance.JoinableTaskFactory.SwitchToMainThreadAsync();

                Debug.Assert(isVisualCppProjectKind(project.Kind));

                VCProject       vcProject = project.Object as VCProject;
                VCConfiguration vcconfig  = vcProject.ActiveConfiguration;

                string toolSetName = ((dynamic)vcconfig).PlatformToolsetFriendlyName;

                string     projectDirectory  = vcProject.ProjectDirectory;
                string     projectName       = project.Name;
                SourceFile sourceForAnalysis = null;
                dynamic    toolsCollection   = vcconfig.Tools;
                foreach (var tool in toolsCollection)
                {
                    // Project-specific includes
                    if (implementsInterface(tool, "Microsoft.VisualStudio.VCProjectEngine.VCCLCompilerTool"))
                    {
                        if (sourceForAnalysis == null)
                        {
                            sourceForAnalysis = new SourceFile(filePath, projectDirectory, projectName, toolSetName);
                        }

                        string includes         = tool.FullIncludePath;
                        string definitions      = tool.PreprocessorDefinitions;
                        string macrosToUndefine = tool.UndefinePreprocessorDefinitions;

                        string[] includePaths = includes.Split(';');
                        for (int i = 0; i < includePaths.Length; ++i)
                        {
                            includePaths[i] = Environment.ExpandEnvironmentVariables(vcconfig.Evaluate(includePaths[i]));
                        }
                        ;

                        sourceForAnalysis.addIncludePaths(includePaths);
                        sourceForAnalysis.addMacros(definitions.Split(';'));
                        sourceForAnalysis.addMacrosToUndefine(macrosToUndefine.Split(';'));
                    }
                }

                return(sourceForAnalysis);
            }
            catch (Exception ex)
            {
                DebugTracer.Trace(ex);
                return(null);
            }
        }
Пример #2
0
        private static async Task <SourceFile> createSourceFileAsync(string filePath, Configuration targetConfig, dynamic project)
        {
            // TODO:
            //Debug.Assert(isVisualCppProject((object)project));
            try
            {
                await Instance.JoinableTaskFactory.SwitchToMainThreadAsync();

                var     configurationName = targetConfig.ConfigurationName;
                dynamic config            = project.Configurations.Item(configurationName);
                String  toolSetName       = config.PlatformToolsetShortName;
                if (String.IsNullOrEmpty(toolSetName))
                {
                    toolSetName = config.PlatformToolsetFriendlyName;
                }
                String     projectDirectory  = project.ProjectDirectory;
                String     projectName       = project.Name;
                SourceFile sourceForAnalysis = new SourceFile(filePath, projectDirectory, projectName, toolSetName);
                dynamic    toolsCollection   = config.Tools;
                foreach (var tool in toolsCollection)
                {
                    // Project-specific includes
                    if (implementsInterface(tool, "Microsoft.VisualStudio.VCProjectEngine.VCCLCompilerTool"))
                    {
                        String includes         = tool.FullIncludePath;
                        String definitions      = tool.PreprocessorDefinitions;
                        String macrosToUndefine = tool.UndefinePreprocessorDefinitions;

                        String[] includePaths = includes.Split(';');
                        for (int i = 0; i < includePaths.Length; ++i)
                        {
                            includePaths[i] = Environment.ExpandEnvironmentVariables(config.Evaluate(includePaths[i]));
                        }
                        ;

                        sourceForAnalysis.addIncludePaths(includePaths);
                        sourceForAnalysis.addMacros(definitions.Split(';'));
                        sourceForAnalysis.addMacrosToUndefine(macrosToUndefine.Split(';'));
                        break;
                    }
                }

                return(sourceForAnalysis);
            }
            catch (Exception ex)
            {
                DebugTracer.Trace(ex);
                return(null);
            }
        }
Пример #3
0
 public void abortThreadIfAny()
 {
     if (_thread != null)
     {
         try
         {
             _terminateThread = true;
             _thread.Join();
         }
         catch (Exception ex)
         {
             DebugTracer.Trace(ex);
         }
         _thread = null;
     }
 }
Пример #4
0
        SourceFile createSourceFile(string filePath, Configuration targetConfig, dynamic project)
        {
            Debug.Assert(isVisualCppProject((object)project));
            try
            {
                var     configurationName = targetConfig.ConfigurationName;
                dynamic config            = project.Configurations.Item(configurationName);
                String  toolSetName       = config.PlatformToolsetShortName;
                if (String.IsNullOrEmpty(toolSetName))
                {
                    toolSetName = config.PlatformToolsetFriendlyName;
                }
                String     projectDirectory  = project.ProjectDirectory;
                String     projectName       = project.Name;
                SourceFile sourceForAnalysis = new SourceFile(filePath, projectDirectory, projectName, toolSetName);
                dynamic    toolsCollection   = config.Tools;
                foreach (var tool in toolsCollection)
                {
                    // Project-specific includes
                    Type toolType = tool.GetType();
                    var  compilerToolInterface = toolType.GetInterface("Microsoft.VisualStudio.VCProjectEngine.VCCLCompilerTool");
                    if (compilerToolInterface != null)
                    {
                        String   includes         = tool.FullIncludePath;
                        String   definitions      = tool.PreprocessorDefinitions;
                        String   macrosToUndefine = tool.UndefinePreprocessorDefinitions;
                        String[] includePaths     = includes.Split(';');
                        for (int i = 0; i < includePaths.Length; ++i)
                        {
                            includePaths[i] = config.Evaluate(includePaths[i]);
                        }

                        sourceForAnalysis.addIncludePaths(includePaths);
                        sourceForAnalysis.addMacros(definitions.Split(';'));
                        sourceForAnalysis.addMacrosToUndefine(macrosToUndefine.Split(';'));
                        break;
                    }
                }
                return(sourceForAnalysis);
            }
            catch (System.Exception ex)
            {
                DebugTracer.Trace(ex);
                return(null);
            }
        }
Пример #5
0
        private void startAnalyzerProcess(string analyzerExePath, string arguments)
        {
            System.Diagnostics.Process process = null;

            try
            {
                Debug.Assert(!String.IsNullOrEmpty(analyzerExePath));
                Debug.Assert(!String.IsNullOrEmpty(arguments));

                process = new System.Diagnostics.Process();
                process.StartInfo.FileName         = analyzerExePath;
                process.StartInfo.WorkingDirectory = Path.GetDirectoryName(analyzerExePath);
                process.StartInfo.Arguments        = arguments;
                process.StartInfo.CreateNoWindow   = true;

                // Set UseShellExecute to false for output redirection.
                process.StartInfo.UseShellExecute = false;

                // Redirect the standard output of the command.
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError  = true;

                // Set our event handler to asynchronously read the sort output.
                process.OutputDataReceived += new DataReceivedEventHandler(this.analyzerOutputHandler);
                process.ErrorDataReceived  += new DataReceivedEventHandler(this.analyzerOutputHandler);

                _ = CPPCheckPluginPackage.AddTextToOutputWindowAsync("Starting analyzer with arguments: " + arguments + "\n");

                var timer = Stopwatch.StartNew();
                // Start the process.
                process.Start();

                try
                {
                    process.PriorityClass = ProcessPriorityClass.Idle;
                }
                catch (System.InvalidOperationException)
                {
                }

                onProgressUpdated(0);

                // Start the asynchronous read of the sort output stream.
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                // Wait for analysis completion
                while (!process.WaitForExit(500))
                {
                    if (_terminateThread)
                    {
                        // finally block will run anyway and do the cleanup
                        return;
                    }
                }
                timer.Stop();
                analysisFinished(arguments);
                if (process.ExitCode != 0)
                {
                    _ = CPPCheckPluginPackage.AddTextToOutputWindowAsync(analyzerExePath + " has exited with code " + process.ExitCode.ToString() + "\n");
                }
                else
                {
                    double timeElapsed = Math.Round(timer.Elapsed.TotalSeconds, 3);
                    _ = CPPCheckPluginPackage.AddTextToOutputWindowAsync("Analysis completed in " + timeElapsed.ToString() + " seconds\n");
                }
                process.Close();
                process = null;
            }
            catch (Exception ex)
            {
                DebugTracer.Trace(ex);
            }
            finally
            {
                onProgressUpdated(100);
                if (process != null)
                {
                    try
                    {
                        process.Kill();
                    }
                    catch (Exception ex)
                    {
                        DebugTracer.Trace(ex);
                    }

                    process.Dispose();
                }
            }
        }
Пример #6
0
        private void documentSaved(Document document)
        {
            if (document == null || document.Language != "C/C++")
            {
                return;
            }

            if (Properties.Settings.Default.CheckSavedFilesHasValue && Properties.Settings.Default.CheckSavedFiles == false)
            {
                return;
            }

            if (document.ActiveWindow == null)
            {
                // We get here when new files are being created and added to the project and
                // then trying to obtain document.ProjectItem yields an exception. Will just skip this.
                return;
            }
            try
            {
                dynamic project = document.ProjectItem.ContainingProject.Object;
                if (!isVisualCppProject(project))
                {
                    return;
                }

                Configuration currentConfig = null;
                try { currentConfig = document.ProjectItem.ConfigurationManager.ActiveConfiguration; }
                catch (Exception) { currentConfig = null; }
                if (currentConfig == null)
                {
                    MessageBox.Show("Cannot perform check - no valid configuration selected", "Cppcheck error");
                    return;
                }

                SourceFile sourceForAnalysis = createSourceFile(document.FullName, currentConfig, project);
                if (sourceForAnalysis == null)
                {
                    return;
                }

                if (!Properties.Settings.Default.CheckSavedFilesHasValue)
                {
                    askCheckSavedFiles();

                    if (!Properties.Settings.Default.CheckSavedFiles)
                    {
                        return;
                    }
                }

                MainToolWindow.Instance.showIfWindowNotCreated();
                MainToolWindow.Instance.ContentsType = ICodeAnalyzer.AnalysisType.DocumentSavedAnalysis;
                runSavedFileAnalysis(sourceForAnalysis, currentConfig, _outputPane);
            }
            catch (System.Exception ex)
            {
                if (_outputPane != null)
                {
                    _outputPane.Clear();
                    _outputPane.OutputString("Exception occurred in cppcheck add-in: " + ex.Message);
                }
                DebugTracer.Trace(ex);
            }
        }
        private void documentSavedSync(Document document)
        {
            JoinableTaskFactory.Run(async() =>
            {
                await JoinableTaskFactory.SwitchToMainThreadAsync();

                if (document == null || document.Language != "C/C++")
                {
                    return;
                }

                if (Settings.Default.CheckSavedFilesHasValue && Settings.Default.CheckSavedFiles == false)
                {
                    return;
                }

                if (document.ActiveWindow == null)
                {
                    // We get here when new files are being created and added to the project and
                    // then trying to obtain document.ProjectItem yields an exception. Will just skip this.
                    return;
                }
                try
                {
                    var kind = document.ProjectItem.ContainingProject.Kind;
                    if (!isVisualCppProjectKind(document.ProjectItem.ContainingProject.Kind))
                    {
                        return;
                    }

                    Configuration currentConfig = null;
                    try { currentConfig = document.ProjectItem.ConfigurationManager.ActiveConfiguration; }
                    catch (Exception) { currentConfig = null; }
                    if (currentConfig == null)
                    {
                        MessageBox.Show("Cannot perform check - no valid configuration selected", "Cppcheck error");
                        return;
                    }

                    //dynamic project = document.ProjectItem.ContainingProject.Object;
                    Project project = document.ProjectItem.ContainingProject;
                    SourceFile sourceForAnalysis = await createSourceFileAsync(document.FullName, currentConfig, project);
                    if (sourceForAnalysis == null)
                    {
                        return;
                    }

                    if (!Settings.Default.CheckSavedFilesHasValue)
                    {
                        askCheckSavedFiles();

                        if (!Settings.Default.CheckSavedFiles)
                        {
                            return;
                        }
                    }

                    MainToolWindow.Instance.showIfWindowNotCreated();
                    MainToolWindow.Instance.ContentsType = ICodeAnalyzer.AnalysisType.DocumentSavedAnalysis;
                    runSavedFileAnalysis(sourceForAnalysis, currentConfig);
                }
                catch (Exception ex)
                {
                    if (_outputPane != null)
                    {
                        _outputPane.Clear();
                        _ = AddTextToOutputWindowAsync("Exception occurred in cppcheck add-in: " + ex.Message);
                    }
                    DebugTracer.Trace(ex);
                }
            });
        }
        private static async Task <SourceFile> createSourceFileAsync(ProjectItem item)
        {
            try
            {
                await Instance.JoinableTaskFactory.SwitchToMainThreadAsync();

                Debug.Assert(isVisualCppProjectKind(item.ContainingProject.Kind));

                VCFile              vcFile     = item.Object as VCFile;
                VCProject           vcProject  = item.ContainingProject.Object as VCProject;
                VCConfiguration     vcconfig   = vcProject.ActiveConfiguration;
                VCFileConfiguration fileConfig = vcFile.FileConfigurations.Item(vcconfig.Name);

                string toolSetName = ((dynamic)vcconfig).PlatformToolsetFriendlyName;

                string     projectDirectory  = vcProject.ProjectDirectory;
                string     projectName       = vcProject.Name;
                SourceFile sourceForAnalysis = null;

                if (item.FileCount > 0)
                {
                    bool     bInheritDefs = true, bInheritUndefs = true;
                    string[] includePaths = { };

                    // Do the file-level first in case it disables inheritance. Include files don't have file-level config.
                    if (implementsInterface(fileConfig.Tool, "Microsoft.VisualStudio.VCProjectEngine.VCCLCompilerTool"))
                    {
                        sourceForAnalysis = new SourceFile(item.FileNames[1], projectDirectory, projectName, toolSetName);
                        includePaths      = fileConfig.Tool.FullIncludePath.Split(';');

                        // Other details may be gathered from the file, project or any inherited property sheets.
                        recursiveAddToolDetails(sourceForAnalysis, vcconfig, fileConfig.Tool, null, ref bInheritDefs, ref bInheritUndefs);
                    }

                    // Now get the full include path
                    VCCLCompilerTool projectTool = (VCCLCompilerTool)vcconfig.Tools.Item("VCCLCompilerTool");
                    if (projectTool != null && implementsInterface(projectTool, "Microsoft.VisualStudio.VCProjectEngine.VCCLCompilerTool"))
                    {
                        if (sourceForAnalysis == null)
                        {
                            sourceForAnalysis = new SourceFile(item.FileNames[1], projectDirectory, projectName, toolSetName);
                            includePaths      = projectTool.FullIncludePath.Split(';');
                        }

                        // Take the full include path from file level, which is already fully resolved.
                        for (int i = 0; i < includePaths.Length; ++i)
                        {
                            includePaths[i] = Environment.ExpandEnvironmentVariables(vcconfig.Evaluate(includePaths[i]));
                        }
                        sourceForAnalysis.addIncludePaths(includePaths);

                        recursiveAddToolDetails(sourceForAnalysis, vcconfig, projectTool, vcconfig.PropertySheets, ref bInheritDefs, ref bInheritUndefs);
                    }
                }

                return(sourceForAnalysis);
            }
            catch (Exception ex)
            {
                DebugTracer.Trace(ex);
                return(null);
            }
        }