private WorkflowSymbol GetWorkflowSymbol(string fileName, object deserializedObject, Dictionary <object, SourceLocation> sourceLocations)
        {
            if (deserializedObject != null)
            {
                Activity deserializedRootElement = GetRootWorkflowElement(deserializedObject);
                if (deserializedRootElement != null)
                {
                    try
                    {
                        deserializedRootElement = GetRootElementForSymbol(deserializedObject, deserializedRootElement);
                        return(new WorkflowSymbol
                        {
                            FileName = fileName,
                            Symbols = SourceLocationProvider.GetSymbols(deserializedRootElement, sourceLocations)
                        });
                    }
                    catch (Exception ex)
                    {
                        if (SharedFx.IsFatal(ex))
                        {
                            throw;
                        }

                        // This happens when the workflow is invalid so GetSymbols fails.
                        // ---- exception here.
                    }
                }
            }

            return(null);
        }
        private Dictionary <object, SourceLocation> UpdateSourceLocationMappingInDebuggerService(Activity root)
        {
            var rootInstance                  = GetRootInstance();
            var sourceLocationMapping         = new Dictionary <object, SourceLocation>();
            var designerSourceLocationMapping = new Dictionary <object, SourceLocation>();

            if (rootInstance != null)
            {
                var documentRootElement = GetRootWorkflowElement(rootInstance);

                SourceLocationProvider.CollectMapping(
                    GetDebuggableActivity(root),
                    documentRootElement,
                    sourceLocationMapping,
                    WorkflowDesigner.Context.Items.GetValue <WorkflowFileItem>().LoadedFile);

                SourceLocationProvider.CollectMapping(
                    documentRootElement,
                    documentRootElement,
                    designerSourceLocationMapping,
                    WorkflowDesigner.Context.Items.GetValue <WorkflowFileItem>().LoadedFile);
            }

            ((DebuggerService)WorkflowDesigner.DebugManagerView).UpdateSourceLocations(designerSourceLocationMapping);

            return(sourceLocationMapping);
        }
        Dictionary <object, SourceLocation> UpdateSourceLocationMappingInDebuggerService()
        {
            object rootInstance = GetRootInstance();
            Dictionary <object, SourceLocation> sourceLocationMapping         = new Dictionary <object, SourceLocation>();
            Dictionary <object, SourceLocation> designerSourceLocationMapping = new Dictionary <object, SourceLocation>();

            if (rootInstance != null)
            {
                Activity documentRootElement = GetRootWorkflowElement(rootInstance);
                SourceLocationProvider.CollectMapping(GetRootRuntimeWorkflowElement(), documentRootElement, sourceLocationMapping,
                                                      _designer.Context.Items.GetValue <WorkflowFileItem>().LoadedFile);
                SourceLocationProvider.CollectMapping(documentRootElement, documentRootElement, designerSourceLocationMapping,
                                                      _designer.Context.Items.GetValue <WorkflowFileItem>().LoadedFile);
            }

            // Notify the DebuggerService of the new sourceLocationMapping.
            // When rootInstance == null, it'll just reset the mapping.
            //DebuggerService debuggerService = debuggerService as DebuggerService;
            var debugService = _designer.DebugManagerView;

            if (debugService != null)
            {
                ((DebuggerService)debugService).UpdateSourceLocations(designerSourceLocationMapping);
            }

            return(sourceLocationMapping);
        }
        private Dictionary <object, SourceLocation> UpdateSourceLocationMappingInDebuggerService(Activity root)
        {
            object rootInstance = this.GetRootInstance();
            Dictionary <object, SourceLocation> sourceLocationMapping         = new Dictionary <object, SourceLocation>();
            Dictionary <object, SourceLocation> designerSourceLocationMapping = new Dictionary <object, SourceLocation>();

            if (rootInstance != null)
            {
                Activity documentRootElement = this.GetRootWorkflowElement(rootInstance);
                SourceLocationProvider.CollectMapping(
                    this.GetRootRuntimeWorkflowElement(root),
                    documentRootElement,
                    sourceLocationMapping,
                    this.workflowDesigner.Context.Items.GetValue <WorkflowFileItem>().LoadedFile);
                SourceLocationProvider.CollectMapping(
                    documentRootElement,
                    documentRootElement,
                    designerSourceLocationMapping,
                    this.workflowDesigner.Context.Items.GetValue <WorkflowFileItem>().LoadedFile);
            }

            // Notify the DebuggerService of the new sourceLocationMapping.
            // When rootInstance == null, it'll just reset the mapping.
            if (this.debuggerService != null)
            {
                ((DebuggerService)this.debuggerService).UpdateSourceLocations(designerSourceLocationMapping);
            }

            return(sourceLocationMapping);
        }
        Dictionary <object, SourceLocation> UpdateSourceLocationMappingInDebuggerService()
        {
            object rootInstance = GetRootInstance();
            Dictionary <object, SourceLocation> sourceLocationMapping = new Dictionary <object, SourceLocation>();


            if (rootInstance != null)
            {
                Activity documentRootElement = GetRootWorkflowElement(rootInstance);

                SourceLocationProvider.CollectMapping(GetRootRuntimeWorkflowElement(), documentRootElement, sourceLocationMapping,
                                                      this.WorkflowDesigner.Context.Items.GetValue <WorkflowFileItem>().LoadedFile);

                //Collect the mapping between the Model Item tree and its underlying source location
                SourceLocationProvider.CollectMapping(documentRootElement, documentRootElement, designerSourceLocationMapping,
                                                      this.WorkflowDesigner.Context.Items.GetValue <WorkflowFileItem>().LoadedFile);
            }

            // Notify the DebuggerService of the new sourceLocationMapping.
            // When rootInstance == null, it'll just reset the mapping.
            //DebuggerService debuggerService = debuggerService as DebuggerService;
            if (this.DebuggerService != null)
            {
                ((DebuggerService)this.DebuggerService).UpdateSourceLocations(designerSourceLocationMapping);
            }

            return(sourceLocationMapping);
        }
        static void AssertNoLineNumber(string className, string methodName)
        {
            var sourceLocationProvider = new SourceLocationProvider(TestAssemblyPath);

            var success = sourceLocationProvider.TryGetSourceLocation(className, methodName, out var location);

            success.ShouldBe(false);
            location.ShouldBe(null);
        }
        Dictionary <object, SourceLocation> GetErrorInformation(Activity activity)
        {
            Dictionary <object, SourceLocation> sourceLocations = null;

            Activity implementationRoot     = null;
            IEnumerable <Activity> children = WorkflowInspectionServices.GetActivities(activity);

            foreach (Activity child in children)
            {
                // Check if the child is the root of the activity's implementation
                // When an activity is an implementation child of another activity, the IDSpace for
                // the implementation child is different than it's parent activity and parent's public
                // children. The IDs for activities in the root activity's IDSpace are 1, 2
                // etc and for the root implementation child it is 1.1 and for its implementation
                // child it is 1.1.1 and so on.
                // As the activity can have just one implementation root, we just check
                // for '.' to identify the root of the implementation.
                if (child.Id.Contains("."))
                {
                    implementationRoot = child;
                    break;
                }
            }

            if (implementationRoot == null)
            {
                return(sourceLocations);
            }

            // We use the workflow debug symbol to get the line and column number information for a
            // erroneous activity.
            // We do not rely on the workflow debug symbol to get the file name. This is to enable cases
            // where the xaml was hand written outside of the workflow designer. The hand written xaml
            // file will not have the workflow debug symbol unless it was saved in the workflow designer.
            string symbolString = DebugSymbol.GetSymbol(implementationRoot) as String;

            if (!string.IsNullOrEmpty(symbolString))
            {
                try
                {
                    WorkflowSymbol wfSymbol = WorkflowSymbol.Decode(symbolString);
                    if (wfSymbol != null)
                    {
                        sourceLocations = SourceLocationProvider.GetSourceLocations(activity, wfSymbol);
                    }
                }
                catch (Exception e)
                {
                    if (Fx.IsFatal(e))
                    {
                        throw;
                    }
                    // Ignore invalid symbol.
                }
            }
            return(sourceLocations);
        }
Exemple #8
0
        static void AssertNoLineNumber(string className, string methodName)
        {
            var sourceLocationProvider = new SourceLocationProvider(TestAssemblyPath);

            SourceLocation location;
            var            success = sourceLocationProvider.TryGetSourceLocation(new MethodGroup(className + "." + methodName), out location);

            success.ShouldBeFalse();
            location.ShouldBeNull();
        }
        static void AssertLineNumber(string className, string methodName, int expectedLine)
        {
            var sourceLocationProvider = new SourceLocationProvider(TestAssemblyPath);

            var success = sourceLocationProvider.TryGetSourceLocation(className, methodName, out var location);

            success.ShouldBe(true);
            location.CodeFilePath.EndsWith("SourceLocationSamples.cs").ShouldBe(true);

            location.LineNumber.ShouldBe(expectedLine);
        }
        private Dictionary <object, SourceLocation> GetSourceLocationMap()
        {
            var runtimeDebug     = new Dictionary <object, SourceLocation>();
            var debugDebug       = new Dictionary <object, SourceLocation>();
            var fileItem         = _workflowDesigner.Context.Items.GetValue(typeof(WorkflowFileItem)) as WorkflowFileItem;
            var debugActivity    = GetDebugActivity();
            var runtTimeActivity = GetRuntimeActivity();

            SourceLocationProvider.CollectMapping(runtTimeActivity, debugActivity, runtimeDebug, fileItem.LoadedFile);
            SourceLocationProvider.CollectMapping(debugActivity, debugActivity, debugDebug, fileItem.LoadedFile);
            _debuggerService.UpdateSourceLocations(debugDebug);
            return(runtimeDebug);
        }
Exemple #11
0
        public static void ConvertRoslynToCCI(
            IMetadataHost host,
            SyntaxTree tree,
            SemanticModel semanticModel,
            out IModule module,
            out ISourceLocationProvider sourceLocationProvider)
        {
            sourceLocationProvider = new SourceLocationProvider();

            var transformer = new NodeVisitor(host, semanticModel, sourceLocationProvider);
            var assembly    = (IModule)transformer.Visit(tree.GetRoot());

            module = assembly;
        }
    public static void ConvertRoslynToCCI(
      IMetadataHost host,
      Microsoft.CodeAnalysis.CSharp.SyntaxTree tree,
      Microsoft.CodeAnalysis.CSharp.Semantics.SemanticModel semanticModel,
      out IModule module,
      out ISourceLocationProvider sourceLocationProvider) {

      sourceLocationProvider = new SourceLocationProvider();

      var transformer = new NodeVisitor(host, semanticModel, sourceLocationProvider);
      var assembly = (Module)transformer.Visit(tree.GetRoot());
      assembly.Location = Path.GetFullPath(tree.FilePath);
      module = assembly;
    }
Exemple #13
0
        static void AssertLineNumber(string className, string methodName, int debugLine, int releaseLine)
        {
            var sourceLocationProvider = new SourceLocationProvider(TestAssemblyPath);

            SourceLocation location;
            var            success = sourceLocationProvider.TryGetSourceLocation(new MethodGroup(className + "." + methodName), out location);

            location.CodeFilePath.EndsWith("SourceLocationSamples.cs").ShouldBeTrue();

#if DEBUG
            location.LineNumber.ShouldEqual(debugLine);
#else
            location.LineNumber.ShouldEqual(releaseLine);
#endif
        }
Exemple #14
0
        Dictionary <object, SourceLocation> UpdateSourceLocationMappingInDebuggerService(Activity activityExecute)
        {
            object rootInstance = GetRootInstance();
            Dictionary <object, SourceLocation> sourceLocationMapping = new Dictionary <object, SourceLocation>();

            // Dictionary<object, SourceLocation> designerSourceLocationMapping = new Dictionary<object, SourceLocation>();
            designerSourceLocationMapping = new Dictionary <object, SourceLocation>();
            try
            {
                if (rootInstance != null)
                {
                    Activity documentRootElement = GetRootWorkflowElement(rootInstance);
                    SourceLocationProvider.CollectMapping(GetRootRuntimeWorkflowElement(activityExecute), documentRootElement, sourceLocationMapping,
                                                          SelectHelper._wfDesigner.Context.Items.GetValue <WorkflowFileItem>().LoadedFile);
                    try
                    {
                        SourceLocationProvider.CollectMapping(documentRootElement, documentRootElement, designerSourceLocationMapping,
                                                              SelectHelper._wfDesigner.Context.Items.GetValue <WorkflowFileItem>().LoadedFile);
                    }
                    catch (Exception)
                    {
                    }
                }

                // Notify the DebuggerService of the new sourceLocationMapping.
                // When rootInstance == null, it'll just reset the mapping.
                //DebuggerService debuggerService = debuggerService as DebuggerService;
                if (DebuggerService == null)
                {
                    DebuggerService = SelectHelper._wfDesigner.DebugManagerView;
                }
                if (DebuggerService != null)
                {
                    ((DebuggerService)DebuggerService).UpdateSourceLocations(designerSourceLocationMapping);
                }
            }
            catch (Exception ex)
            {
                Log.Logger.LogData(ex.Message, LogLevel.Error);
            }

            //  return sourceLocationMapping;
            return(designerSourceLocationMapping);
        }
Exemple #15
0
        public IEnumerable <Tuple <string, TextSpan> > AnalyzeMeAUnit(
            Microsoft.CodeAnalysis.Document document,
            CompilationUnitSyntax compilationUnitDeclaration,
            CancellationToken cancellationToken)
        {
            var semanticModel = document.GetSemanticModel(cancellationToken);
            var semanticNode  = semanticModel.GetDeclaredSymbol(compilationUnitDeclaration);

            this.sourceLocationProvider = new SourceLocationProvider();
            string             exceptionMessage = null;
            IAssemblyReference ar = null;

            try {
                // Constructs a full metadata model for the assembly the semantic model is from
                var transformer = new NodeVisitor(this.host, semanticModel, sourceLocationProvider);

                // Constructs the method bodies all of the methods in the compilation unit
                var tree  = document.GetSyntaxTree(cancellationToken);
                var tree2 = transformer.Visit(compilationUnitDeclaration);
                ar = tree2 as IAssemblyReference;
            } catch (ConverterException e) {
                exceptionMessage = e.Message;
            }
            if (exceptionMessage != null)
            {
                yield return(Tuple.Create(exceptionMessage, compilationUnitDeclaration.GetFirstToken().Span));

                yield break;
            }
            var unit = ar;

            this.host.RegisterUnit(unit.ResolvedUnit);
            this.cciProvider.MetaDataDecoder.RegisterSourceLocationProvider(unit, sourceLocationProvider);

            this.methodAnalyzer.AnalyzeAssembly(ar);

            foreach (var result in this.analysisResults)
            {
                yield return(result);
            }
        }
Exemple #16
0
        public IEnumerable <Tuple <string, TextSpan> > AnalyzeMeAMethod(
            Microsoft.CodeAnalysis.Document document,
            MethodDeclarationSyntax methodDeclaration,
            CancellationToken cancellationToken)
        {
            var semanticModel = document.GetSemanticModel(cancellationToken);
            var semanticNode  = semanticModel.GetDeclaredSymbol(methodDeclaration);

            Microsoft.Cci.IMethodReference cciMethod = null;
            this.sourceLocationProvider = new SourceLocationProvider();
            string exceptionMessage = null;

            try {
                // Constructs a full metadata model for the assembly the semantic model is from
                var transformer = new NodeVisitor(this.host, semanticModel, sourceLocationProvider);

                // Constructs the method body for just this one method
                cciMethod = transformer.Visit(methodDeclaration) as Microsoft.Cci.IMethodReference;
            } catch (ConverterException e) {
                exceptionMessage = e.Message;
            }
            if (exceptionMessage != null)
            {
                yield return(Tuple.Create(exceptionMessage, methodDeclaration.Span));

                yield break;
            }
            var unit = TypeHelper.GetDefiningUnitReference(cciMethod.ContainingType);

            this.host.RegisterUnit(unit.ResolvedUnit);
            this.cciProvider.MetaDataDecoder.RegisterSourceLocationProvider(unit, sourceLocationProvider);

            this.methodAnalyzer.Analyze(MethodReferenceAdaptor.AdaptorOf(cciMethod));

            foreach (var result in this.analysisResults)
            {
                yield return(result);
            }
        }
Exemple #17
0
        /// <summary>
        /// Checks the <paramref name="compilationUnitDeclaration"/> for syntax and semantic
        /// errors and returns an empty enumerable if any are found.
        /// </summary>
        public IEnumerable <ClousotOutput> AnalyzeMeAUnit(
            Microsoft.CodeAnalysis.Document document,
            CompilationUnitSyntax compilationUnitDeclaration,
            CancellationToken cancellationToken,
            ClousotOptions options,
            string[] extraOptions,
            bool showOnlyAnswersToAskClousot = false
            )
        {
            if (options == null)
            {
                options = new ClousotOptions();
            }

            // Don't do anything if there are syntactic errors.
            if (compilationUnitDeclaration.ContainsDiagnostics)
            {
                yield break;
            }

            var semanticModel = document.GetSemanticModel(cancellationToken);

            // Don't do anything if there are semantic errors.
            var diagnostics = semanticModel.GetDiagnostics(cancellationToken);

            if (diagnostics.Any(d => d.Info.Severity == DiagnosticSeverity.Error || d.Info.IsWarningAsError))
            {
                yield break;
            }

            this.host = new ClousotGlueHost((document.Project).MetadataReferences);

            this.sourceLocationProvider = new SourceLocationProvider();
            string             exceptionMessage = null;
            IAssemblyReference ar = null;

            try {
                // Constructs a full metadata model for the assembly the semantic model is from
                var transformer = new NodeVisitor(this.host, semanticModel, sourceLocationProvider);

                // Constructs the method bodies all of the methods in the compilation unit
                // var tree = document.GetSyntaxTree(cancellationToken);
                var tree2 = transformer.Visit(compilationUnitDeclaration);
                ar = tree2 as IAssemblyReference;
            } catch (ConverterException e) {
                exceptionMessage = e.Message;
            } catch (OperationCanceledException) {
                // just return nothing
                yield break;
            }
            if (exceptionMessage != null)
            {
                yield return(new ClousotOutput(null, exceptionMessage, compilationUnitDeclaration.GetFirstToken().Span, null, (ICodeAction)null, ClousotOutput.ExtraInfo.None));

                yield break;
            }

            var spanToMethodMap = MethodSpanFinder.GetMethodSpans(compilationUnitDeclaration);

            lock (this) { // Clousot is single-threaded
                var cciProvider = Microsoft.Cci.Analysis.CciILCodeProvider.CreateCodeProvider(host);
                var unit        = ar;
                this.host.RegisterUnit(unit.ResolvedUnit);
                cciProvider.MetaDataDecoder.RegisterSourceLocationProvider(unit, sourceLocationProvider);
                var metadataDecoder = cciProvider.MetaDataDecoder;
                var contractDecoder = cciProvider.ContractDecoder;

                var defaultargs = new string[] {
                    "-nonnull",
                    "-bounds",
                    "-arithmetic",
                    "-sortwarns:-",
                    //"-arrays",
                    "-cache",
                    //"-suggest=methodensures",
                    "-suggest=propertyensures",
                    "-suggest=objectinvariants",
                    //"-infer=requires",
                    //"-infer=objectinvariants",
                    //"-clearcache",
                    //"-prefrompost"
                };
                var codefixesargs = new string[] {
                    "-nonnull",
                    "-bounds",
                    "-arithmetic",
                    "-suggest=codefixes",
                    "-cache",
                    "-libpaths:\"c:\\program files (x86)\\Microsoft\\Contracts\\Contracts\\.NetFramework\\v4.0\"",
                    //"-suggest=methodensures",
                    "-suggest=objectinvariants",
                    "-infer=objectinvariants",
                    "-suggest=assumes",
                    "-premode=backwards",
                };
                var args = codefixesargs;
                if (extraOptions != null)
                {
                    args = args.Concat(extraOptions).ToArray();
                }

                var w = (options == null || String.IsNullOrWhiteSpace(options.WarningLevel))
          ? "low"
          : options.WarningLevel;

                var warninglevel = String.Format("-warninglevel={0}", w);
                var x            = new string[] { warninglevel, };
                args = args.Concat(x).ToArray();

                if (options != null)
                {
                    var otherOptions = options.OtherOptions;
                    if (!String.IsNullOrWhiteSpace(otherOptions))
                    {
                        var otherOpts = otherOptions.Split(' ');
                        args = args.Concat(otherOpts).ToArray();
                    }
                }

                this.analysisResults = new List <ClousotOutput>();
                var output         = new RoslynOutput(showOnlyAnswersToAskClousot, this.analysisResults, document, spanToMethodMap, null);
                var methodAnalyzer = Clousot.GetIndividualMethodAnalyzer(metadataDecoder, contractDecoder, args, output,
                                                                         new[] { this.cacheFactory });
                foreach (var path in methodAnalyzer.Options.libPaths)
                {
                    host.AddLibPath(path);
                }
                methodAnalyzer.AnalyzeAssembly(ar);
            }

            foreach (var result in this.analysisResults)
            {
                yield return(result);
            }
        }