コード例 #1
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);
        }
コード例 #2
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, CecilWeaverConfiguration configuration)
        {
            ServiceContainer serviceContainer = new ServiceContainer();

            serviceContainer.AddService(typeof(IEntitiesAccessor), languageModel);
            serviceContainer.AddService(typeof(CecilWeaverConfiguration), configuration);
            serviceContainer.AddService(typeof(IBuilderConfigurator <BuilderStage>), new ILWeaverBuilderConfigurator());

            return(serviceContainer);
        }
コード例 #3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="T:CecilILAnalyzer"/> class.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="languageModelAccessor">The language model accessor.</param>
        public CecilILAnalyzer(CecilAnalyzerConfiguration configuration, IEntitiesAccessor entitiesAccessor)
        {
            #region Check for null values

            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            #endregion

            _configuration = configuration;
        }
コード例 #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);
        }
コード例 #5
0
        public void Start()
        {
            if (!File.Exists(_config))
            {
                throw new SigExpanderException("Configuration file '" + _config + "' does not exist");
            }

            IEntitiesAccessor      accessor = EntitiesAccessor.Instance;
            ConfigurationContainer config   = accessor.LoadConfiguration(_config);

            foreach (AssemblyConfig ac in config.Assemblies)
            {
                if (ac.ExpansionSpecificationFile != null)
                {
                    ExpandedAssembly ea = LoadExpandedAssembly(ac.ExpansionSpecificationFile);
                    ExpandAssembly(ea, ac.FileName);
                }
            }
        }
コード例 #6
0
        /// <summary>
        /// When overridden in a derived class, executes the task.
        /// </summary>
        /// <returns>
        /// true if the task successfully executed; otherwise, false.
        /// </returns>
        public override bool Execute()
        {
            base.Execute();
            List <string> refTypes = new List <string>();
            Stopwatch     sw       = Stopwatch.StartNew();

            try
            {
                // Open DB
                Log.LogMessageFromResources(MessageImportance.Low, "OpenDatabase", _repositoryFileName);
                IEntitiesAccessor      entitiesAccessor = EntitiesAccessor.Instance;
                ConfigurationContainer configContainer  = entitiesAccessor.LoadConfiguration(_repositoryFileName);

                // Create a list with the new concerns
                List <ConcernElement> concernsToAdd = new List <ConcernElement>();

                // Parse all concern files and add to the database
                foreach (ITaskItem item in _concernFiles)
                {
                    string concernFile = item.ToString();
                    bool   newConcern;

                    ConcernElement ce = FindConcernElement(configContainer, concernFile, out newConcern);

                    // Do a time check, if new or change, run the parser and store the data
                    if (newConcern || File.GetLastWriteTime(concernFile).Ticks > ce.Timestamp)
                    {
                        Log.LogMessageFromResources("ParsingConcernFile", concernFile);

                        // File is changed, we might not have the correct data
                        ICpsParser parser = new CpsFileParserEx(concernFile);

                        // Parse the concern file
                        parser.Parse();

                        // Indicate if there are any outputfilters
                        ce.HasOutputFilters = parser.HasOutputFilters;

                        // Store the embedded code (if any)
                        ce.EmbeddedFileName = StoreEmbeddedCode(concernFile, parser.EmbeddedCode);

                        // Add the referenced types
                        ce.ReferencedTypes.AddRange(parser.ReferencedTypes);

                        // Update timestamp
                        ce.Timestamp = File.GetLastWriteTime(concernFile).Ticks;

                        // Indicate that the concerns are most likely dirty
                        _concernsDirty = true;
                    }
                    else
                    {
                        Log.LogMessageFromResources("AddingConcernFile", concernFile);
                    }

                    if (!string.IsNullOrEmpty(ce.EmbeddedFileName))
                    {
                        _extraSources.Add(new TaskItem(ce.EmbeddedFileName));
                    }

                    _hasOutputFilters |= ce.HasOutputFilters;

                    refTypes.AddRange(ce.ReferencedTypes);

                    concernsToAdd.Add(ce);
                }

                sw.Stop();

                Log.LogMessageFromResources("FoundReferenceType", refTypes.Count, _concernFiles.Length, sw.Elapsed.TotalSeconds);

                // Pass all the referenced types back to msbuild
                if (refTypes != null && refTypes.Count > 0)
                {
                    int index = 0;
                    _referencedTypes = new ITaskItem[refTypes.Count];
                    foreach (String type in refTypes)
                    {
                        _referencedTypes[index] = new TaskItem(type);
                        index++;
                    }
                }

                // Save the configContainer
                configContainer.Concerns = concernsToAdd;
                entitiesAccessor.SaveConfiguration(_repositoryFileName, configContainer);
            }
            catch (CpsParserException ex)
            {
                Log.LogErrorFromException(ex, false);
            }
            catch (FileNotFoundException ex)
            {
                Log.LogErrorFromException(ex, false);
            }

            return(!Log.HasLoggedErrors);
        }
コード例 #7
0
        /// <summary>
        /// When overridden in a derived class, executes the task.
        /// </summary>
        /// <returns>
        /// true if the task successfully executed; otherwise, false.
        /// </returns>
        public override bool Execute()
        {
            base.Execute();
            Log.LogMessageFromResources("WeavingStartText");

            // Get the configuration container
            IEntitiesAccessor      entitiesAccessor = EntitiesAccessor.Instance;
            ConfigurationContainer configContainer  = entitiesAccessor.LoadConfiguration(RepositoryFileName);

            // Set the weave debug level
            CecilWeaverConfiguration.WeaveDebug weaveDebugLevel;
            if (string.IsNullOrEmpty(_weaveDebug))
            {
                weaveDebugLevel = CecilWeaverConfiguration.WeaveDebug.None;
            }
            else
            {
                try
                {
                    weaveDebugLevel = (CecilWeaverConfiguration.WeaveDebug)CecilWeaverConfiguration.WeaveDebug.Parse(typeof(CecilWeaverConfiguration.WeaveDebug), _weaveDebug, true);
                }
                catch (ArgumentException)
                {
                    Log.LogErrorFromResources("CouldNotParseWeaveDebugLevel", _weaveDebug);
                    return(false);
                }
            }

            // For each assembly in the config
            foreach (AssemblyConfig assembly in configContainer.Assemblies)
            {
                // Exclude StarLight ContextInfo assembly from the weaving process
                if (assembly.FileName.EndsWith(ContextInfoFileName))
                {
                    continue;
                }

                // Exclude references
                if (assembly.IsReference)
                {
                    continue;
                }

                // If there is no weaving spec file, then skip
                if (string.IsNullOrEmpty(assembly.WeaveSpecificationFile))
                {
                    Log.LogMessageFromResources("SkippedWeavingFile", assembly.FileName);
                    continue;
                }

                // Check for modification
                if (!ConcernsDirty && File.GetLastWriteTime(assembly.FileName).Ticks <= assembly.Timestamp)
                {
                    // we beter copy the backuped file
                    string backupWeavefile = string.Concat(assembly.FileName, ".weaved");
                    if (File.Exists(backupWeavefile))
                    {
                        File.Copy(backupWeavefile, assembly.FileName, true);
                        Log.LogMessageFromResources("UsingBackupWeaveFile", assembly.FileName);
                        continue;
                    }
                }

                Log.LogMessageFromResources("WeavingFile", assembly.FileName);

                // Preparing config
                CecilWeaverConfiguration configuration = new CecilWeaverConfiguration(assembly, configContainer, weaveDebugLevel);

                if (!String.IsNullOrEmpty(BinFolder))
                {
                    configuration.BinFolder = BinFolder;
                }

                try
                {
                    // Retrieve a weaver instance from the ObjectManager
                    using (IILWeaver weaver = DIHelper.CreateObject <CecilILWeaver>(CreateContainer(entitiesAccessor, configuration)))
                    {
                        // Perform weaving
                        IWeaveResults weaveResults = weaver.DoWeave();

                        // Output the logitems
                        foreach (LogItem item in weaveResults.Log.LogItems)
                        {
                            Log.LogMessageFromText(item.ToString(), MessageImportance.Normal);
                        }

                        // Show information about weaving
                        Log.LogMessageFromResources("WeavingCompleted", weaveResults.WeaveStatistics.TotalWeaveTime.TotalSeconds);
                        switch (configuration.WeaveDebugLevel)
                        {
                        case CecilWeaverConfiguration.WeaveDebug.None:
                            break;

                        case CecilWeaverConfiguration.WeaveDebug.Statistics:
                            ShowWeavingStats(assembly, weaveResults.WeaveStatistics);
                            break;

                        case CecilWeaverConfiguration.WeaveDebug.Detailed:
                            ShowWeavingStats(assembly, weaveResults.WeaveStatistics);

                            // Save instruction log
                            string logFilename    = assembly.FileName + ".weavelog.txt";
                            string timingFilename = assembly.FileName + ".weavetiming.txt";

                            weaveResults.WeaveStatistics.SaveInstructionsLog(logFilename);
                            weaveResults.WeaveStatistics.SaveTimingLog(timingFilename);

                            Log.LogMessageFromResources("WeavingInstructionsLogSaved", logFilename);
                            Log.LogMessageFromResources("WeavingTimingLogSaved", timingFilename);
                            break;

                        default:
                            break;
                        }
                    }
                }
                catch (ILWeaverException ex)
                {
                    //Log.LogErrorFromException(ex, true);
                    string errorMessage = ex.Message;
                    string stackTrace   = ex.StackTrace;

                    Exception innerException = ex.InnerException;
                    while (innerException != null)
                    {
                        errorMessage   = string.Concat(errorMessage, "; ", innerException.Message);
                        stackTrace     = string.Concat(innerException.StackTrace, stackTrace);
                        innerException = innerException.InnerException;
                    }
                    Log.LogErrorFromResources("WeaverException", errorMessage);

                    // Only show stacktrace when debugging is enabled
                    if (weaveDebugLevel != CecilWeaverConfiguration.WeaveDebug.None)
                    {
                        Log.LogErrorFromResources("WeaverExceptionStackTrace", stackTrace);
                    }
                }
                catch (ArgumentException ex)
                {
                    Log.LogErrorFromException(ex, true);
                }
                catch (BadImageFormatException ex)
                {
                    Log.LogErrorFromException(ex, false);
                }
            }

            return(!Log.HasLoggedErrors);
        }
コード例 #8
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);
        }
コード例 #9
0
        /// <summary>
        /// When overridden in a derived class, executes the task.
        /// </summary>
        /// <returns>
        /// true if the task successfully executed; otherwise, false.
        /// </returns>
        public override bool Execute()
        {
            base.Execute();
            Stopwatch sw = Stopwatch.StartNew();

            // Open DB
            Log.LogMessageFromResources(MessageImportance.Low, "OpenDatabase", _repositoryFileName);
            IEntitiesAccessor entitiesAccessor = EntitiesAccessor.Instance;

            ConfigurationContainer configContainer = entitiesAccessor.LoadConfiguration(_repositoryFileName);

            if (configContainer.Concerns.Count == 0)
            {
                Log.LogMessageFromResources("MasterSkipNoConcerns");
                return(!Log.HasLoggedErrors);
            }

            Log.LogMessageFromResources("MasterStartText");

            // Place debuglevel
            Log.LogMessageFromResources("StoreDebugLevel", _debugLevel);

            // Set the Common Configuration
            string debugLevelValue = "";

            if (!string.IsNullOrEmpty(_debugLevel))
            {
                try
                {
                    CurrentDebugMode = (DebugLevel)Enum.Parse(typeof(DebugLevel), _debugLevel);
                    debugLevelValue  = DebugLevelToLog4j(CurrentDebugMode);
                }
                catch (ArgumentException)
                {
                    Log.LogErrorFromResources("CouldNotConvertDebugLevel", _debugLevel);
                    return(false);
                }
            }

            if (!String.IsNullOrEmpty(debugLevelValue))
            {
                configContainer.AddSetting("buildDebugLevel", debugLevelValue);
            }
            configContainer.AddSetting("IntermediateOutputPath", _intermediateOutputPath);
            configContainer.AddSetting("InstallFolder", StarLightSettings.Instance.StarLightInstallFolder);

            //michielh: disabled for now, not used in FILTH
            //configContainer.AddSetting("FILTH.outputEnabled", _filthOutput.ToString(CultureInfo.InvariantCulture));

            if (!String.IsNullOrEmpty(_bookKeepingMode))
            {
                configContainer.AddSetting("INLINE.bookkeeping", _bookKeepingMode);
            }

            // Save common config
            entitiesAccessor.SaveConfiguration(_repositoryFileName, configContainer);

            // Create a process to execute the StarLight Master.
            Process process = new Process();

            process.StartInfo.CreateNoWindow         = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardError  = true;

            // Determine filename
            if (!string.IsNullOrEmpty(StarLightSettings.Instance.JavaLocation))
            {
                process.StartInfo.FileName = Path.Combine(StarLightSettings.Instance.JavaLocation, JavaExecutable);
            }
            else
            {
                process.StartInfo.FileName = JavaExecutable;                 // In path
            }
            // Create command line
            string jarFile = Path.Combine(StarLightSettings.Instance.StarLightInstallFolder, StarLightJar);

            IList <string> args = new List <string>();

            args.Add(StarLightSettings.Instance.JavaOptions);
            args.Add("-jar " + Quote(jarFile));
            args.Add(Quote(_repositoryFileName));

            process.StartInfo.Arguments = Join(args, " ");
            Log.LogMessageFromResources("JavaStartMessage", process.StartInfo.Arguments);

            // Start the process
            try
            {
                process.Start();

                using (StreamReader outputReader = process.StandardOutput)
                {
                    while (!outputReader.EndOfStream)
                    {
                        ParseMasterOutput(outputReader.ReadLine());
                    }
                }

                process.WaitForExit();
                if (process.ExitCode == 0)
                {
                    sw.Stop();
                    Log.LogMessageFromResources("MasterCompleted", sw.Elapsed.TotalSeconds);
                    return(!Log.HasLoggedErrors);
                }
                else
                {
                    Log.LogMessagesFromStream(process.StandardError, MessageImportance.High);
                    Log.LogErrorFromResources("MasterRunFailed", process.ExitCode);
                    return(false);
                }
            }
            catch (Win32Exception e)
            {
                if (e.NativeErrorCode == ErrorFileNotFound)
                {
                    Log.LogErrorFromResources("JavaExecutableNotFound", process.StartInfo.FileName);
                }
                else if (e.NativeErrorCode == ErrorAccessDenied)
                {
                    Log.LogErrorFromResources("JavaExecutableAccessDenied", process.StartInfo.FileName);
                }
                else
                {
                    Log.LogErrorFromResources("ExecutionException", e.ToString());
                }
                return(false);
            }
            finally
            {
                if (sw.IsRunning)
                {
                    sw.Stop();
                }
            }
        }
コード例 #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);
        }
コード例 #11
0
        /// <summary>
        /// When overridden in a derived class, executes the task.
        /// </summary>
        /// <returns>
        /// true if the task successfully executed; otherwise, false.
        /// </returns>
        public override bool Execute()
        {
            base.Execute();
            Stopwatch sw = Stopwatch.StartNew();

            // Get the location of PEVerify
            string PEVerifyLocation = ToolLocationHelper.GetPathToDotNetFrameworkSdkFile(PEVerifyExecutable, TargetDotNetFrameworkVersion.Version20);

            if (String.IsNullOrEmpty(PEVerifyLocation) || !File.Exists(PEVerifyLocation))
            {
                Log.LogWarningFromResources("PEVerifyExecutableNotFound", "PEVerify.exe");
                return(true);
            }

            // Setup process
            Process process = new Process();

            // Determine filename
            process.StartInfo.FileName = PEVerifyLocation;

            process.StartInfo.CreateNoWindow         = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardError  = true;

            IEntitiesAccessor entitiesAccessor = EntitiesAccessor.Instance;

            ConfigurationContainer configContainer = entitiesAccessor.LoadConfiguration(RepositoryFileName);

            ushort filesVerified = 0;

            // Execute PEVerify for each file
            foreach (AssemblyConfig assembly in configContainer.Assemblies)
            {
                try
                {
                    // Only verify files we weaved on. Skip the rest.
                    if (assembly.IsReference || String.IsNullOrEmpty(assembly.WeaveSpecificationFile))
                    {
                        continue;
                    }

                    Log.LogMessageFromResources("VerifyingAssembly", assembly.FileName);

                    string arguments = String.Format(CultureInfo.InvariantCulture, "{0} /IL /MD /NOLOGO", assembly.FileName);
                    process.StartInfo.Arguments = arguments;
                    process.Start();

                    process.WaitForExit(8000);
                    if (process.ExitCode == 0)
                    {
                        Log.LogMessageFromResources("VerifySuccess", assembly.FileName);
                    }
                    else
                    {
                        while (!process.StandardOutput.EndOfStream)
                        {
                            ParseOutput(process.StandardOutput.ReadLine(), assembly.FileName);
                        }
                        while (!process.StandardError.EndOfStream)
                        {
                            ParseOutput(process.StandardError.ReadLine(), assembly.FileName);
                        }
                    }
                    filesVerified++;
                }
                catch (Win32Exception exception)
                {
                    if (exception.NativeErrorCode == ErrorFileNotFound)
                    {
                        Log.LogWarningFromResources("PEVerifyExecutableNotFound", process.StartInfo.FileName);
                        return(true);
                    }
                    else if (exception.NativeErrorCode == ErrorAccessDenied)
                    {
                        Log.LogWarningFromResources("PEVerifyExecutableAccessDenied", process.StartInfo.FileName);
                        return(true);
                    }
                    else
                    {
                        Log.LogErrorFromResources("PEVerifyExecutionException", exception.ToString());
                        return(false);
                    }
                }
                catch (InvalidOperationException ex)
                {
                    Log.LogErrorFromException(ex, true);
                }
                catch (ArgumentException ex)
                {
                    Log.LogErrorFromException(ex, true);
                }
            }

            sw.Stop();

            Log.LogMessageFromResources("VerificationCompleted", filesVerified, sw.Elapsed.TotalSeconds);

            return(!Log.HasLoggedErrors);
        }