Пример #1
0
        public static void AddProjectReferencesPathsIntoHost(References references, MetadataReaderHost host)
        {
            Contract.Requires(host != null);

            if (references == null)
            {
                return;
            }

            for (int i = 1; i <= references.Count; i++)
            {
                var tempRef = references.Item(i);
                if (tempRef == null)
                {
                    continue;
                }

                var refPath = tempRef.Path;
                if (!String.IsNullOrEmpty(refPath))
                {
                    var refDir = Path.GetDirectoryName(refPath);
                    if (refDir != null)
                    {
                        host.AddLibPath(refDir);
                        var referenceAssemblyPath = Path.Combine(refDir, "CodeContracts");
                        if (System.IO.Directory.Exists(referenceAssemblyPath))
                        {
                            host.AddLibPath(referenceAssemblyPath);
                        }
                    }
                }
            }
        }
Пример #2
0
        public WholeProgram(IEnumerable <IAssembly> rootAssemblies, MetadataReaderHost host)
        {
            this.rootAssemblies = new HashSet <IAssembly>(rootAssemblies);

            this.allAssemblies = GarbageCollectHelper.CloseAndResolveOverReferencedAssemblies(rootAssemblies);

            this.host = host;
        }
Пример #3
0
        public MyLoader(MetadataReaderHost host, string directory)
        {
            this.cciHost              = host;
            this.myRuntimeLoader      = new RuntimeLoader.RuntimeLoader(host);
            sourceProviderForAssembly = new Dictionary <IAssembly, ISourceLocationProvider>();
            if (PlatformTypes == null)
            {
                PlatformTypes = host.PlatformType;
            }

            this.failedAssemblies = new HashSet <IAssemblyReference>();
            //LoadCoreAssembly();

            LoadRuntimeTypes(directory);
        }
Пример #4
0
        public bool Load(string location)
        {
            IModule module = MetadataReaderHost.LoadUnitFrom(location) as IModule;

            if (module == null || module is Dummy)
            {
                return(false);
            }
            else
            {
                PrimaryModule   = module;
                PrimaryAssembly = module as IAssembly;
                Environment.Message("Loaded primary assembly {0} with {1} assembly references.", PrimaryAssembly.Name.Value, PrimaryAssembly.AssemblyReferences.Count());
                return(true);
            }
        }
Пример #5
0
        private static void RewriteBinary(
            Assembly copy,
            AssemblyReport assemblyReport,
            MetadataReaderHost host,
            string outputPath,
            MethodRemoval methodRemoval,
            StubMethodBodyEmitter stubEmitter)
        {
            /* This is an attempt to decouple the MethodRemoval commandline options
             * from the tree shaker, but it doesn't really seem to be working.
             * Might be better to just pass the method removal directly to
             * the rewriter.
             */

            bool removeMethods  = (methodRemoval == MethodRemoval.Remove);
            bool fullDebugStubs = (methodRemoval == MethodRemoval.Debug);
            bool dryRun         = (methodRemoval == MethodRemoval.None);

            PdbReader /*?*/ pdbReader = null;
            string          pdbFile   = Path.ChangeExtension(copy.Location, "pdb");

            if (File.Exists(pdbFile))
            {
                using (var pdbStream = File.OpenRead(pdbFile)) {
                    pdbReader = new PdbReader(pdbStream, host);
                }
            }
            else
            {
                Console.WriteLine("Could not load the PDB file for '" + copy.Name.Value + "' . Proceeding anyway.");
            }

            using (pdbReader) {
                var localScopeProvider = pdbReader == null ? null : new ILGenerator.LocalScopeProvider(pdbReader);
                var pdbPath            = Path.ChangeExtension(outputPath, ".pdb");
                var outputFileName     = Path.GetFileNameWithoutExtension(outputPath);
                using (var peStream = File.Create(outputPath)) {
                    using (var pdbWriter = new PdbWriter(pdbPath, pdbReader)) {
                        var       rewriter      = new TreeShakingRewriter(host, assemblyReport, dryRun, removeMethods, fullDebugStubs, stubEmitter);
                        IAssembly rewrittenCopy = rewriter.Rewrite(copy);

                        PeWriter.WritePeToStream(rewrittenCopy, host, peStream, pdbReader, localScopeProvider, pdbWriter);
                    }
                }
            }
        }
Пример #6
0
        public PdbReader LoadPdb(string file, MetadataReaderHost host)
        {
            PdbReader symbol = null;

            try
            {
                string symbolFile = Path.ChangeExtension(file, ".pdb");
                if (File.Exists(symbolFile))
                {
                    symbol = new PdbReader(File.Open(symbolFile, FileMode.Open, FileAccess.Read), host);
                }
            }
            catch (Exception)
            {
                // yum yum, i feel dirty writing this.
                symbol = null;
            }
            return(symbol);
        }
Пример #7
0
        public PhoneNavigationCodeTraverser(MetadataReaderHost host, IEnumerable <IAssemblyReference> assemblies) : base()
        {
            this.host = host;
            List <IAssembly> assembliesTraversed = new List <IAssembly>();

            foreach (IAssemblyReference asmRef in assemblies)
            {
                assembliesTraversed.Add(asmRef.ResolvedAssembly);
            }

            Microsoft.Cci.Immutable.PlatformType platform = host.PlatformType as Microsoft.Cci.Immutable.PlatformType;

            // TODO obtain version, culture and signature data dynamically
            IAssemblyReference assembly = PhoneTypeHelper.getPhoneAssemblyReference(host);

            // TODO determine the needed types dynamically
            navigationSvcType = platform.CreateReference(assembly, "System", "Windows", "Navigation", "NavigationService");

            assembly            = PhoneTypeHelper.getSystemAssemblyReference(host);
            cancelEventArgsType = platform.CreateReference(assembly, "System", "ComponentModel", "CancelEventArgs");
            navigationCallers   = new HashSet <IMethodReference>();
        }
Пример #8
0
        public static AssemblyIdentity GetAssemblyIdentity(EnvDTE.Project project, MetadataReaderHost host)
        {
            Contract.Requires(project != null);
            Contract.Requires(host != null);

            if (!ProjectIsAvailable(project))
            {
                return(null);
            }

            VSServiceProvider.Current.Logger.WriteToLog("Getting the assembly identity for project: " + project.Name);

            string           location_RootDir             = null;
            string           location_RelativeAssemblyDir = null;
            string           location_FileName            = null;
            string           location = null;
            IName            iName    = null;
            string           culture  = "";//TODO: Find out where to get culture information.
            Version          version  = new Version();
            AssemblyIdentity result   = null;

            try {
                var activePropCount =
                    project.ConfigurationManager != null && project.ConfigurationManager.ActiveConfiguration != null && project.ConfigurationManager.ActiveConfiguration.Properties != null ?
                    project.ConfigurationManager.ActiveConfiguration.Properties.Count : 0;
                for (int i = activePropCount; 1 <= i; i--)
                {
                    var prop = project.ConfigurationManager.ActiveConfiguration.Properties.Item(i);
                    if (prop == null)
                    {
                        continue;
                    }
                    if (prop.Name == "OutputPath")
                    {
                        location_RelativeAssemblyDir = prop.Value as string;
                        break;
                    }
                }
                var propCount = project.Properties != null ? project.Properties.Count : 0;
                for (int i = propCount; 1 <= i; i--)
                {
                    var prop = project.Properties.Item(i);
                    if (prop == null)
                    {
                        continue;
                    }
                    switch (prop.Name)
                    {
                    case "AssemblyName":
                        iName = host.NameTable.GetNameFor(prop.Value as string);
                        break;

                    case "AssemblyVersion":
                        var stringVersion = prop.Value as string;
                        if (!Version.TryParse(stringVersion, out version))
                        {
                            version = new Version();
                        }
                        Contract.Assume(version != null);
                        break;

                    case "FullPath":
                        location_RootDir = prop.Value as string;
                        break;

                    case "OutputFileName":
                        location_FileName = prop.Value as string;
                        break;

                    default:
                        break;
                    }
                }
            } catch (COMException comEx) {
                VSServiceProvider.Current.Logger.WriteToLog("COM Exception while trying to access project's properties.");
                VSServiceProvider.Current.Logger.WriteToLog("Message: " + comEx.Message);
                if (comEx.Message.Contains(COMExceptionMessage_ProjectUnavailable))
                {
                    VSServiceProvider.Current.Logger.WriteToLog("Returning null.");
                    return(null);
                }
                else if (((uint)comEx.ErrorCode) == 0x80020009)
                {
                    VSServiceProvider.Current.Logger.WriteToLog("Returning null.");
                    return(null);
                }
                else
                {
                    throw comEx;
                }
            }

            //Check if we got enough information from VS to build the location
            if (location_FileName == null ||
                location_RelativeAssemblyDir == null ||
                location_RootDir == null)
            {
                VSServiceProvider.Current.Logger.WriteToLog("Couldn't find path to the project's output assembly.");
                return(null);
            }

            //Set the location of the output assembly
            location = Path.Combine(location_RootDir, location_RelativeAssemblyDir, location_FileName);

            //Check that the output assembly exists
            if (!File.Exists(location))
            {
                VSServiceProvider.Current.Logger.WriteToLog("Project output assembly could not be found at the location given by Visual Studio: " + location);
            }

            //Check our other information from VS
            if (iName == null ||
                string.IsNullOrEmpty(location))
            {
                VSServiceProvider.Current.Logger.WriteToLog("Couldn't gather sufficient information from the project to construct an assembly identity.");
                return(null);
            }

            //Success
            Contract.Assert(version != null);
            Contract.Assert(culture != null);
            result = new AssemblyIdentity(iName, culture, version, Enumerable <byte> .Empty, location);
            host.AddLibPath(Path.Combine(location_RootDir, location_RelativeAssemblyDir, "CodeContracts"));
            host.AddLibPath(Path.Combine(location_RootDir, location_RelativeAssemblyDir, @"..\Debug\CodeContracts"));

            return(result);
        }
        // this function applies analysis-net analyses on the method defined in our assembly (methodDefinition)
        // the result is a typed stackless three address code representation of the orignal method definition body
        // you can 'out' the control flow graph because it can be reused for another analysis
        public static MethodBody ThreeAddressCode(IMethodDefinition methodDefinition, MetadataReaderHost host, out ControlFlowGraph cfg)
        {
            if (methodDefinition.IsAbstract || methodDefinition.IsExternal)
            {
                cfg = null;
                return(null);
            }

            var disassembler = new Disassembler(host, methodDefinition, null);
            var methodBody   = disassembler.Execute();

            var cfAnalysis = new ControlFlowAnalysis(methodBody);

            //var cfg = cfAnalysis.GenerateNormalControlFlow();
            cfg = cfAnalysis.GenerateExceptionalControlFlow();

            var splitter = new WebAnalysis(cfg, methodDefinition);

            splitter.Analyze();
            splitter.Transform();

            methodBody.UpdateVariables();

            var typeAnalysis = new TypeInferenceAnalysis(cfg, methodDefinition.Type);

            typeAnalysis.Analyze();

            methodBody.UpdateVariables();

            return(methodBody);
        }
Пример #10
0
 public void Dispose()
 {
     _mutableAssembly = null;
     _host.Dispose();
     _host = null;
 }
Пример #11
0
        public override bool Execute()
        {
            ReswFileList            = null;
            UnprocessedAssemblyList = null;

            List <ITaskItem> unprocessedAssemblyList = new List <ITaskItem>();
            List <ITaskItem> reswList = new List <ITaskItem>();

            _state = ReadStateFile(StateFile);
            if (_state == null)
            {
                _state = new ResourceHandlingState();
            }
            _state.SetLogger(Log);

            using (_host = new PeReader.DefaultHost())
            {
                try
                {
                    // Separate main assemblies and satellite assemblies so main assemblies get processed first
                    _mainAssemblies      = new List <ITaskItem>();
                    _satelliteAssemblies = new List <ITaskItem>();
                    _processedAssemblies = new HashSet <String>(StringComparer.OrdinalIgnoreCase);

                    foreach (ITaskItem item in AssemblyList)
                    {
                        if (_processedAssemblies.Contains(item.ItemSpec))
                        {
                            continue;
                        }
                        _processedAssemblies.Add(item.ItemSpec);

                        if (item.ItemSpec.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
                        {
                            if (item.ItemSpec.EndsWith(".resources.dll", StringComparison.OrdinalIgnoreCase))
                            {
                                _satelliteAssemblies.Add(item);
                            }
                            else
                            {
                                _mainAssemblies.Add(item);
                            }
                        }
                    }

                    foreach (ITaskItem assemblyFilePath in _mainAssemblies.Concat(_satelliteAssemblies))
                    {
                        List <ResWInfo> resWInfoList = null;
                        bool            containsFrameworkResources = false;
                        if (!_state.IsUpToDate(assemblyFilePath.ItemSpec, out containsFrameworkResources, out resWInfoList))
                        {
                            resWInfoList = ExtractAssemblyResWList(assemblyFilePath.ItemSpec, out containsFrameworkResources);

                            if (resWInfoList != null)
                            {
                                FileInfo fiAssembly = new FileInfo(assemblyFilePath.ItemSpec);
                                _state.Save(assemblyFilePath.ItemSpec, fiAssembly.LastWriteTimeUtc, containsFrameworkResources, resWInfoList);
                            }
                        }

                        if (resWInfoList != null)
                        {
                            foreach (ResWInfo reswInfo in resWInfoList)
                            {
                                TaskItem newTaskItem = new TaskItem(reswInfo.ResWPath);
                                newTaskItem.SetMetadata("ResourceIndexName", reswInfo.ResourceIndexName);
                                if (!String.IsNullOrEmpty(reswInfo.NeutralResourceLanguage))
                                {
                                    newTaskItem.SetMetadata("NeutralResourceLanguage", reswInfo.NeutralResourceLanguage);
                                }

                                if (!containsFrameworkResources)
                                {
                                    newTaskItem.SetMetadata("OriginalItemSpec", reswInfo.ResWPath); // Original GenerateResource behavior creates this additional metadata item on processed non-framework assemblies
                                    reswList.Add(newTaskItem);
                                }
                                else if (!SkipFrameworkResources)
                                {
                                    reswList.Add(newTaskItem);
                                }
                            }
                        }
                    }

                    UnprocessedAssemblyList = unprocessedAssemblyList.ToArray(); // For now this list will always be empty
                    ReswFileList            = reswList.ToArray();
                    WriteStateFile(StateFile, _state);
                }
                catch (Exception e)
                {
                    Log.LogError(Resources.Error_ResourceExtractionFailed, e.Message);
                    return(false);
                }
            }

            return(true);
        }
Пример #12
0
 public PhoneInitializationMetadataTraverser(MetadataReaderHost host)
     : base()
 {
     this.host = host;
 }
Пример #13
0
 public void Dispose()
 {
     this.cciHost.Dispose();
     this.cciHost = null;
     GC.SuppressFinalize(this);
 }
Пример #14
0
 public CciModuleSource(MetadataReaderHost host, List <ModuleInfo> moduleInfoList) : this(host)
 {
     _moduleInfoList = moduleInfoList;
 }
Пример #15
0
 public CciModuleSource(MetadataReaderHost host = null)
 {
     pdbReaders      = new Dictionary <string, PdbReader>(StringComparer.OrdinalIgnoreCase);
     _host           = host ?? new PeReader.DefaultHost();
     _moduleInfoList = new List <ModuleInfo>();
 }
Пример #16
0
        public override bool Execute()
        {
            ReswFileList            = null;
            UnprocessedAssemblyList = null;

            List <ITaskItem> unprocessedAssemblyList = new List <ITaskItem>();
            List <ITaskItem> reswList = new List <ITaskItem>();

            _state = ReadStateFile(StateFile);
            if (_state == null)
            {
                _state = new ResourceHandlingState();
            }
            _state.SetLogger(Log);

            using (_host = new PeReader.DefaultHost())
            {
                try
                {
                    ITaskItem firstNonFrameworkAssembly = null;
                    foreach (ITaskItem assemblyFilePath in AssemblyList)
                    {
                        string reswPath          = null;
                        bool   containsResources = false;
                        if (!_state.IsUpToDate(assemblyFilePath.ItemSpec, out reswPath) ||
                            !IsAtOutputFolder(reswPath))
                        {
                            reswPath = ExtractFrameworkAssemblyResW(assemblyFilePath.ItemSpec, out containsResources);
                            if (reswPath != null)
                            {
                                FileInfo fiAssembly = new FileInfo(assemblyFilePath.ItemSpec);
                                FileInfo fiResW     = new FileInfo(reswPath);
                                _state.Save(assemblyFilePath.ItemSpec, reswPath, fiAssembly.LastWriteTimeUtc, fiResW.LastWriteTimeUtc);
                            }
                        }

                        if (reswPath == null)
                        {
                            if (containsResources)
                            {
                                unprocessedAssemblyList.Add(assemblyFilePath);
                            }

                            if (unprocessedAssemblyList.Count == 0)
                            {
                                firstNonFrameworkAssembly = assemblyFilePath;
                            }
                        }
                        else
                        {
                            TaskItem newTaskItem = new TaskItem(reswPath);
                            newTaskItem.SetMetadata("NeutralResourceLanguage", "en-US");
                            newTaskItem.SetMetadata("ResourceIndexName", Path.GetFileNameWithoutExtension(reswPath));
                            reswList.Add(newTaskItem);
                        }
                    }

                    UnprocessedAssemblyList = unprocessedAssemblyList.ToArray();

                    if (!SkipFrameworkResources)
                    {
                        ReswFileList = reswList.ToArray();
                    }

                    // we make sure unprocessedAssemblyList has at least one item if ReswFileList is empty to avoid having _GeneratePrisForPortableLibraries
                    // repopulate the assembly list and reprocess them
                    if ((ReswFileList == null || ReswFileList.Length == 0) &&
                        UnprocessedAssemblyList.Length == 0 &&
                        firstNonFrameworkAssembly != null)
                    {
                        UnprocessedAssemblyList = new ITaskItem[1] {
                            firstNonFrameworkAssembly
                        };
                    }

                    WriteStateFile(StateFile, _state);
                }
                catch (Exception e)
                {
                    Log.LogError(Resources.Error_ResourceExtractionFailed, e.Message);
                    return(false);
                }
            }

            return(true);
        }
Пример #17
0
 public PhoneNavigationMetadataTraverser(MetadataReaderHost host)
     : base()
 {
     this.host = host;
 }
Пример #18
0
 static Inspector()
 {
     host = new PeReader.DefaultHost();
 }
Пример #19
0
 private CciModuleSource(MetadataReaderHost host, IAssembly module) : this(host)
 {
     _moduleInfoList.Add(new ModuleInfo(module));
 }
Пример #20
0
 public PhoneInitializationCodeTraverser(MetadataReaderHost host, IMethodDefinition traversedMethod) : base()
 {
     this.methodBeingTraversed = traversedMethod;
     this.host = host;
     InitializeTraverser();
 }