Ejemplo n.º 1
0
        /// <summary>
        /// Stores the assemblies to the configuration container and, when needed, to assemblyElements on disk.
        /// </summary>
        /// <param name="analyzer">The analyzer.</param>
        /// <param name="assemblies">The assemblies.</param>
        private void StoreAssemblies(IILAnalyzer analyzer)
        {
            if (_assembliesToStore.Count == 0 || Log.HasLoggedErrors)
            {
                return;
            }

            Log.LogMessageFromResources("StoreInDatabase", _assembliesToStore.Count);
            Stopwatch sw = Stopwatch.StartNew();

            // Check if we have to save the assembly data
            foreach (AssemblyConfig assembly in _assembliesToStore)
            {
                // save each assembly if needed (there must be an assemblyElement)
                if (assembly.Assembly != null)
                {
                    EntitiesAccessor.Instance.SaveAssemblyElement(assembly.TypeSpecificationFile, assembly.Assembly);
                }
            }

            // Set the assemblies to store
            _configContainer.Assemblies = _assembliesToStore;

            // Add the filtertypes and actions
            _configContainer.FilterTypes   = _filterTypes;
            _configContainer.FilterActions = _filterActions;

            // Save the config
            EntitiesAccessor.Instance.SaveConfiguration(_repositoryFileName, _configContainer);

            sw.Stop();
            Log.LogMessageFromResources("StoreInDatabaseCompleted", _assembliesToStore.Count, analyzer.ResolvedAssemblies.Count, sw.Elapsed.TotalSeconds);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Analyzes all assemblies in output folder.
        /// </summary>
        /// <param name="analyzer">The analyzer.</param>
        /// <param name="assemblyFileList">The assembly file list.</param>
        /// <param name="assemblies">The assemblies.</param>
        private void AnalyzeWeavableAssemblies(IILAnalyzer analyzer, List <ITaskItem> weavableAssemblies, List <AssemblyElement> assemblies)
        {
            foreach (ITaskItem item in weavableAssemblies)
            {
                try
                {
                    AssemblyElement assembly = AnalyzeAssembly(analyzer, item);

                    if (assembly != null)
                    {
                        assemblies.Add(assembly);
                    }
                }
                catch (ILAnalyzerException ex)
                {
                    Log.LogErrorFromException(ex, true);
                }
                catch (ArgumentException ex)
                {
                    Log.LogErrorFromException(ex, true);
                }
                catch (FileNotFoundException ex)
                {
                    Log.LogErrorFromException(ex, true);
                }
                catch (BadImageFormatException ex)
                {
                    Log.LogErrorFromException(ex, false);
                }
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Adds all unresolved types from the concern files to the analyzer.
        /// </summary>
        /// <param name="analyzer">The analyzer.</param>
        private void AddUnresolvedTypes(IILAnalyzer analyzer)
        {
            if (_referencedTypes.Length == 0)
            {
                return;
            }

            Log.LogMessageFromResources(MessageImportance.Low, "NumberOfReferencesToResolve", _referencedTypes.Length);
            foreach (ITaskItem item in _referencedTypes)
            {
                analyzer.UnresolvedTypes.Add(item.ToString());
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Executes the ILAnalyser task.
        /// </summary>
        /// <returns>
        ///	<c>true</c> if the task successfully executed; otherwise, <c>false</c>.
        /// </returns>
        public override bool Execute()
        {
            base.Execute();
            Log.LogMessageFromResources("AnalyzerStartText");

            //
            // Setup of configuration and lists
            //
            IEntitiesAccessor          entitiesAccessor = EntitiesAccessor.Instance;
            CecilAnalyzerConfiguration configuration    = new CecilAnalyzerConfiguration(_repositoryFileName);

            configuration.BinFolder            = _binFolder;
            configuration.DoMethodCallAnalysis = _doMethodCallAnalysis;

            // Initialize instance variables
            _configContainer = entitiesAccessor.LoadConfiguration(_repositoryFileName);
            _filterActions   = _configContainer.FilterActions;
            _filterTypes     = _configContainer.FilterTypes;
            _resources       = _configContainer.Resources;
            _conflictRules   = _configContainer.ConflictRules;

            _assembliesInConfig = _configContainer.Assemblies;
            _assembliesToStore  = new List <AssemblyConfig>();

            // Create the analyzer using the object builder
            using (IILAnalyzer analyzer = DIHelper.CreateObject <CecilILAnalyzer>(CreateContainer(entitiesAccessor, configuration)))
            {
                // Find the assemblies to analyze
                List <ITaskItem> weavableAssemblies = FindAssembliesToAnalyze();
                List <ITaskItem> refAssemblies      = FindReferencedAssemblies();

                // Add all the unresolved types (used in the concern files) to the analyser
                AddUnresolvedTypes(analyzer);

                // Create a list to store information about analyzed assemblies in
                List <AssemblyElement> assemblies = new List <AssemblyElement>();

                // Analyze the assemblies in the output folder
                AnalyzeWeavableAssemblies(analyzer, weavableAssemblies, assemblies);

                // Analyze the assemblies referenced to this project or subprojects
                AnalyzeReferencedAssemblies(analyzer, refAssemblies, assemblies);

                // Store the found assemblies in the configuration container
                StoreAssemblies(analyzer);
            }

            return(!Log.HasLoggedErrors);
        }
Ejemplo n.º 5
0
        public void TestTargetMustReturnCorrectAssembly()
        {
            // set up model
            LanguageModelAccessorMock model = new LanguageModelAccessorMock();

            // create configuration
            CecilAnalyzerConfiguration configuration = CecilAnalyzerConfiguration.CreateDefaultConfiguration(string.Empty);

            // do weaving
            IILAnalyzer     analyzer = DIHelper.CreateObject <CecilILAnalyzer>(CreateTestContainer(model, configuration));
            AssemblyElement ae       = analyzer.ExtractAllTypes(CreateFullPath("TestTarget.exe"));

            Assert.IsNotNull(ae, "Could not create an AssemblyElement.");
            Assert.IsFalse(string.IsNullOrEmpty(ae.FileName), "Filename is not set.");
            Assert.IsFalse(string.IsNullOrEmpty(ae.Name), "Assembly name is not set.");
            Assert.IsFalse(ae.Timestamp == 0, "Timestamp is not set.");

            Assert.IsTrue(ae.TypeElements.Length > 0, "TypeElements were not retrieved.");
            Assert.IsTrue(ae.TypeElements.Length == 1, "Found {0} TypeElements, expecting 1.", ae.TypeElements.Length);

            TypeElement te = ae.TypeElements[0];

            Assert.IsNotNull(te, "Could not set the TypeElement.");

            Assert.IsFalse(string.IsNullOrEmpty(te.BaseType), "BaseType has not been stored.");
            Assert.IsFalse(string.IsNullOrEmpty(te.FullName), "FullName has not been stored.");
            Assert.IsFalse(string.IsNullOrEmpty(te.Name), "Name has not been stored.");
            Assert.IsFalse(string.IsNullOrEmpty(te.Namespace), "Namespace has not been stored.");

            Assert.IsTrue(te.MethodElements.Length == 2, "Methods not stored in the TypeElement. {0} methods found", te.MethodElements.Length);

            MethodElement me = te.MethodElements[0];

            Assert.IsNotNull(me, "Could not set the methodElement");

            Assert.IsFalse(string.IsNullOrEmpty(me.Name), "Name has not been stored.");
            Assert.IsFalse(string.IsNullOrEmpty(me.ReturnType), "Returntype has not been stored.");
            Assert.IsFalse(string.IsNullOrEmpty(me.Signature), "Signature has not been stored.");
        } // TestTargetMustReturnAssembly()
Ejemplo n.º 6
0
        private AssemblyInfo AnalyzeFile(String file)
        {
            AssemblyInfo result = new AssemblyInfo();

            IEntitiesAccessor entitiesAccessor = null;

            try
            {
                entitiesAccessor = EntitiesAccessor.Instance;
                CecilAnalyzerConfiguration configuration = new CecilAnalyzerConfiguration(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "starlight.yap"));

                NameValueCollection config = new NameValueCollection();
                config.Add("ProcessMethodBody", "true");

                analyzer = DIHelper.CreateObject <CecilILAnalyzer>(CreateContainer(entitiesAccessor, configuration));

                System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
                sw.Start();

                AssemblyElement assembly = analyzer.ExtractAllTypes(file);

                sw.Stop();

                // Create statistics
                int fields      = 0;
                int methods     = 0;
                int parameters  = 0;
                int methodcalls = 0;
                int attributes  = 0;
                foreach (TypeElement te in assembly.Types)
                {
                    fields  += te.Fields.Count;
                    methods += te.Methods.Count;
                    foreach (MethodElement me in te.Methods)
                    {
                        parameters += me.Parameters.Count;

                        if (me.HasMethodBody && me.Body.Calls != null)
                        {
                            methodcalls += me.Body.Calls.Count;
                        }
                    }
                }

                result.TypeCount       = assembly.Types.Count;
                result.FieldCount      = fields;
                result.MethodCount     = methods;
                result.ParameterCount  = parameters;
                result.MethodCallCount = methodcalls;
                result.ElapsedTime     = sw.Elapsed.TotalMilliseconds;
                result.UnresolvedTypes = analyzer.UnresolvedTypes.Count;

                sw.Reset();

                List <AssemblyElement> assemblies = new List <AssemblyElement>();
                assemblies.Add(assembly);

                if (analyzer.UnresolvedTypes.Count > 0 && resolve)
                {
//                    Console.WriteLine("Processing {0} unresolved types...", analyzer.UnresolvedTypes.Count);
                    foreach (String ut in analyzer.UnresolvedTypes)
                    {
                        Console.WriteLine("  {0}", ut);
                    }

                    if (analyzer.UnresolvedTypes.Count > 0)
                    {
                        foreach (String ut in analyzer.UnresolvedTypes)
                        {
                            Console.WriteLine("  {0}", ut);
                        }
                    }
                }
            }
            finally
            {
                analyzer.Dispose();
            }

            return(result);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Analyzes the referenced assemblies.
        /// </summary>
        /// <param name="analyzer">The analyzer.</param>
        /// <param name="refAssemblies">The referenced assemblies.</param>
        /// <param name="assemblies">The list to put the information about the analyzed assemblies in.</param>
        private void AnalyzeReferencedAssemblies(IILAnalyzer analyzer, List <ITaskItem> refAssemblies, List <AssemblyElement> assemblies)
        {
            // Only if we have unresolved types
            if (analyzer.UnresolvedTypes.Count == 0)
            {
                return;
            }

            Log.LogMessageFromResources("NumberOfReferencesToResolve", analyzer.UnresolvedTypes.Count);

            // The previous step could introduce new assemblies, so add those to the list.
            List <string> assemblyFiles = new List <string>();

            assemblyFiles.AddRange(analyzer.ResolveAssemblyLocations());

            // Create analyzer new config
            CecilAnalyzerConfiguration configuration = new CecilAnalyzerConfiguration(_repositoryFileName);

            configuration.DoFieldAnalysis       = false;
            configuration.DoMethodCallAnalysis  = false;
            configuration.ExtractUnresolvedOnly = true;
            configuration.BinFolder             = _binFolder;

            // Store before reset
            IList <string> tempUnresolvedTypes = analyzer.UnresolvedTypes;

            // Create a new analyzer using the object builder
            IEntitiesAccessor entitiesAccessor = EntitiesAccessor.Instance;

            analyzer = DIHelper.CreateObject <CecilILAnalyzer>(CreateContainer(entitiesAccessor, configuration));

            // Set the unresolved types (because we have reset the analyzer)
            foreach (string type in tempUnresolvedTypes)
            {
                analyzer.UnresolvedTypes.Add(type);
            }

            // Add the assemblies to analyze.
            foreach (ITaskItem item in refAssemblies)
            {
                string filename = item.ToString();
                if (!assemblyFiles.Contains(filename))
                {
                    assemblyFiles.Add(filename);
                }
            }

            // Try to resolve all the references.
            do
            {
                // Loop through all the referenced assemblies.
                foreach (string filename in assemblyFiles)
                {
                    try
                    {
                        // See if we already have this assembly in the list
                        AssemblyConfig asmConfig = _assembliesInConfig.Find(delegate(AssemblyConfig ac)
                        {
                            return(ac.FileName.Equals(filename));
                        });

                        // If a source assembly has changed, then new unresolved types can be introduced.
                        // So we must rescan the library based on the value of assemblyChanged.
                        // TODO: can this be optimized?
                        if (!_assembliesDirty && asmConfig != null && File.Exists(asmConfig.TypeSpecificationFile))
                        {
                            // Already in the config. Check the last modification date.
                            if (asmConfig.Timestamp == File.GetLastWriteTime(filename).Ticks)
                            {
                                // Assembly has not been modified, skipping analysis
                                Log.LogMessageFromResources("AssemblyNotModified", asmConfig.Name);

                                _assembliesToStore.Add(asmConfig);
                                continue;
                            }
                        }

                        // Either we could not find the assembly in the config or it was changed.

                        Log.LogMessageFromResources("AnalyzingFile", filename);
                        Stopwatch sw = Stopwatch.StartNew();

                        IAnalyzerResults results = analyzer.ExtractAllTypes(filename);
                        ShowLogItems(results.Log.LogItems);

                        // Store the filters
                        StoreFilters(results);

                        // Create a new AssemblyConfig object
                        AssemblyElement assembly = results.Assembly;
                        if (assembly != null)
                        {
                            asmConfig = new AssemblyConfig();

                            asmConfig.FileName    = filename;
                            asmConfig.Name        = assembly.Name;
                            asmConfig.Timestamp   = File.GetLastWriteTime(filename).Ticks;
                            asmConfig.Assembly    = assembly;
                            asmConfig.IsReference = true;

                            // Generate a unique filename
                            asmConfig.GenerateTypeSpecificationFileName(_intermediateOutputPath);

                            _assembliesToStore.Add(asmConfig);
                            assemblies.Add(assembly);
                        }

                        sw.Stop();
                        Log.LogMessageFromResources("AssemblyAnalyzed", assembly.Types.Count, analyzer.UnresolvedAssemblies.Count, sw.Elapsed.TotalSeconds);
                    }
                    catch (ILAnalyzerException ex)
                    {
                        Log.LogErrorFromException(ex, true);
                    }
                    catch (ArgumentException ex)
                    {
                        Log.LogErrorFromException(ex, true);
                    }
                    catch (FileNotFoundException ex)
                    {
                        Log.LogErrorFromException(ex, true);
                    }
                    catch (BadImageFormatException ex)
                    {
                        Log.LogErrorFromException(ex, false);
                    }
                }

                // Clear the already analyzed assemblies
                assemblyFiles.Clear();

                // Get the unresolved
                assemblyFiles.AddRange(analyzer.ResolveAssemblyLocations());
            }while (analyzer.UnresolvedTypes.Count > 0 && assemblyFiles.Count > 0);
        }
Ejemplo n.º 8
0
        private AssemblyElement AnalyzeAssembly(IILAnalyzer analyzer, ITaskItem item)
        {
            string filename = item.ToString();

            // See if we already have this assembly in the list
            AssemblyConfig asmConfig = _assembliesInConfig.Find(delegate(AssemblyConfig ac)
            {
                return(ac.FileName.Equals(filename));
            });

            if (asmConfig != null && File.Exists(asmConfig.TypeSpecificationFile))
            {
                // Already in the config. Check the last modification date.
                if (asmConfig.Timestamp == File.GetLastWriteTime(filename).Ticks)
                {
                    // Assembly has not been modified, skipping analysis
                    Log.LogMessageFromResources("AssemblyNotModified", asmConfig.Name);

                    // We still have to store this assembly, but we do not analyze it
                    _assembliesToStore.Add(asmConfig);
                    return(null);
                }
            }

            // Either we could not find the assembly in the config or it was changed.
            Log.LogMessageFromResources("AnalyzingFile", filename);
            Stopwatch sw = Stopwatch.StartNew();

            IAnalyzerResults results = analyzer.ExtractAllTypes(filename);

            ShowLogItems(results.Log.LogItems);

            // Store the filters
            StoreFilters(results);

            // Get the assembly from the results.
            AssemblyElement assembly = results.Assembly;

            if (assembly == null || IsFilterFile(Path.GetFileName(filename)))
            {
                Log.LogMessageFromResources("AssemblyAnalyzedSkipped");
                return(null);
            }

            // Create a new AssemblyConfig object
            asmConfig             = new AssemblyConfig();
            asmConfig.FileName    = filename;
            asmConfig.Name        = assembly.Name;
            asmConfig.Timestamp   = File.GetLastWriteTime(filename).Ticks;
            asmConfig.Assembly    = assembly;
            asmConfig.IsReference = false;

            // Generate a unique filename
            asmConfig.GenerateTypeSpecificationFileName(_intermediateOutputPath);

            _assembliesToStore.Add(asmConfig);
            _assembliesDirty = true;

            sw.Stop();
            Log.LogMessageFromResources("AssemblyAnalyzed", assembly.Types.Count, analyzer.UnresolvedAssemblies.Count, sw.Elapsed.TotalSeconds);

            return(assembly);
        }