예제 #1
0
        public void InitializeThrowsBadImageExceptionOnInvalidInputImage()
        {
            CecilAnalyzerConfiguration configuration     = CecilAnalyzerConfiguration.CreateDefaultConfiguration(string.Empty);
            ILanguageModelAccessor     langModelAccessor = new LanguageModelAccessorMock();

            AssemblyElement ae = ((IILAnalyzer) new CecilILAnalyzer(configuration, langModelAccessor)).ExtractAllTypes(CreateFullPath("InvalidImage.exe"));
        }
예제 #2
0
        public void AnalyzerThrowsExceptionIfFileDoesntExists()
        {
            CecilAnalyzerConfiguration configuration     = CecilAnalyzerConfiguration.CreateDefaultConfiguration(string.Empty);
            ILanguageModelAccessor     langModelAccessor = new LanguageModelAccessorMock();

            AssemblyElement ae = ((IILAnalyzer) new CecilILAnalyzer(configuration, langModelAccessor)).ExtractAllTypes("c:\\this_file_doesnt_exist");
        }
예제 #3
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);
        }
예제 #4
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()
예제 #5
0
        /// <summary>
        /// Creates the test container.
        /// </summary>
        /// <param name="languageModel">The language model.</param>
        /// <param name="configuration">The configuration.</param>
        /// <returns></returns>
        internal IServiceProvider CreateTestContainer(LanguageModelAccessorMock languageModel, CecilAnalyzerConfiguration configuration)
        {
            ServiceContainer serviceContainer = new ServiceContainer();

            serviceContainer.AddService(typeof(IEntitiesAccessor), languageModel == null ? new LanguageModelAccessorMock() : languageModel);
            serviceContainer.AddService(typeof(CecilAnalyzerConfiguration), configuration == null ? CecilAnalyzerConfiguration.CreateDefaultConfiguration(CreateFullPath("test.yap")) : configuration);
            serviceContainer.AddService(typeof(IBuilderConfigurator <BuilderStage>), new ILAnalyzerTestBuilderConfigurator());

            return(serviceContainer);
        }
예제 #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);
        }
예제 #7
0
        /// <summary>
        /// Creates the services container.
        /// </summary>
        /// <param name="languageModel">The language model.</param>
        /// <param name="configuration">The configuration.</param>
        /// <returns></returns>
        internal static IServiceProvider CreateContainer(IEntitiesAccessor languageModel, CecilAnalyzerConfiguration configuration)
        {
            ServiceContainer serviceContainer = new ServiceContainer();

            serviceContainer.AddService(typeof(IEntitiesAccessor), languageModel);
            serviceContainer.AddService(typeof(CecilAnalyzerConfiguration), configuration);

            return(serviceContainer);
        }
예제 #8
0
 public void TestInitialize()
 {
     svcContainer.AddService(typeof(IBuilderConfigurator <BuilderStage>), new ILAnalyzerTestBuilderConfigurator());
     svcContainer.AddService(typeof(CecilAnalyzerConfiguration), CecilAnalyzerConfiguration.CreateDefaultConfiguration(CreateFullPath("TestTarget.exe")));
     svcContainer.AddService(typeof(ILanguageModelAccessor), new LanguageModelAccessorMock());
 }
예제 #9
0
 public virtual void GlobalSetUp()
 {
     config = CecilAnalyzerConfiguration.CreateDefaultConfiguration("test.yap");
 }
예제 #10
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);
        }