public MetadataReference GetMetadataReference(string path) { var cacheKey = _cacheKeyPrefix + path.ToLowerInvariant(); var metadata = _cache.Get <AssemblyMetadata>(cacheKey); if (metadata == null) { _logger.LogDebug(string.Format("Cache miss {0}", path)); using (var stream = File.OpenRead(path)) { var moduleMetadata = ModuleMetadata.CreateFromStream(stream, PEStreamOptions.PrefetchMetadata); metadata = AssemblyMetadata.Create(moduleMetadata); var options = new MemoryCacheEntryOptions(); options.ExpirationTokens.Add(new FileWriteTimeTrigger(path)); _cache.Set(cacheKey, metadata, options); } } var documentationFile = Path.ChangeExtension(path, ".xml"); if (File.Exists(documentationFile)) { return(metadata.GetReference(new XmlDocumentationProvider(documentationFile))); } return(metadata.GetReference()); }
private AssemblyMetadata CreateAssemblyMetadata( FileKey fileKey, ModuleMetadata manifestModule, List <ITemporaryStreamStorage>?storages, Func <FileKey, List <ITemporaryStreamStorage>?, ModuleMetadata> moduleMetadataFactory) { var moduleBuilder = ArrayBuilder <ModuleMetadata> .GetInstance(); string?assemblyDir = null; foreach (var moduleName in manifestModule.GetModuleNames()) { if (assemblyDir is null) { moduleBuilder.Add(manifestModule); assemblyDir = Path.GetDirectoryName(fileKey.FullPath); } // Suppression should be removed or addressed https://github.com/dotnet/roslyn/issues/41636 var moduleFileKey = FileKey.Create(PathUtilities.CombineAbsoluteAndRelativePaths(assemblyDir, moduleName) !); var metadata = moduleMetadataFactory(moduleFileKey, storages); moduleBuilder.Add(metadata); } if (moduleBuilder.Count == 0) { moduleBuilder.Add(manifestModule); } return(AssemblyMetadata.Create( moduleBuilder.ToImmutableAndFree())); }
internal Metadata GetMetadata() { if (EmittedAssemblyData == null) { throw new InvalidOperationException("You must call Emit before calling GetAllModuleMetadata."); } if (_compilation.Options.OutputKind.IsNetModule()) { var metadata = ModuleMetadata.CreateFromImage(EmittedAssemblyData); metadata.Module.PretendThereArentNoPiaLocalTypes(); return(metadata); } else { var images = new List <ImmutableArray <byte> > { EmittedAssemblyData }; if (_allModuleData != null) { images.AddRange(_allModuleData.Where(m => m.Kind == OutputKind.NetModule).Select(m => m.Image)); } return(AssemblyMetadata.Create(images.Select(image => { var metadata = ModuleMetadata.CreateFromImage(image); metadata.Module.PretendThereArentNoPiaLocalTypes(); return metadata; }))); } }
public void Ctor_Errors() { Assert.Throws <ArgumentNullException>(() => AssemblyMetadata.CreateFromImage(default(ImmutableArray <byte>))); IEnumerable <byte> enumerableImage = null; Assert.Throws <ArgumentNullException>(() => AssemblyMetadata.CreateFromImage(enumerableImage)); byte[] arrayImage = null; Assert.Throws <ArgumentNullException>(() => AssemblyMetadata.CreateFromImage(arrayImage)); Assert.Throws <ArgumentNullException>(() => AssemblyMetadata.Create((ModuleMetadata)null)); Assert.Throws <ArgumentException>(() => AssemblyMetadata.Create(default(ImmutableArray <ModuleMetadata>))); Assert.Throws <ArgumentException>(() => AssemblyMetadata.Create(ImmutableArray.Create <ModuleMetadata>())); var m1 = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.MultiModule.MultiModuleDll); var m2 = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.MultiModule.mod2); var m3 = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.MultiModule.mod3); Assert.Throws <ArgumentException>(() => AssemblyMetadata.Create(m1, m2.Copy(), m3)); Assert.Throws <ArgumentException>(() => AssemblyMetadata.Create(new List <ModuleMetadata>(new ModuleMetadata[] { m1.Copy(), m2.Copy(), m3.Copy() }))); Assert.Throws <ArgumentNullException>(() => AssemblyMetadata.Create(ImmutableArray.Create(m1, m2, null))); Assert.Throws <ArgumentNullException>(() => AssemblyMetadata.Create(ImmutableArray.Create((ModuleMetadata)null))); Assert.Throws <ArgumentNullException>(() => AssemblyMetadata.CreateFromFile((string)null)); }
internal IReadOnlyList <MetadataReference> Resolve(DependencyContext dependencyContext) { var libraryPaths = new HashSet <string>(StringComparer.OrdinalIgnoreCase); var references = dependencyContext.CompileLibraries.SelectMany(library => library.ResolveReferencePaths()); if (!references.Any()) { throw new RazorLightException("Can't load metadata reference from the entry assembly. " + "Make sure PreserveCompilationContext is set to true in *.csproj file"); } var metadataRerefences = new List <MetadataReference>(); foreach (var reference in references) { if (libraryPaths.Add(reference)) { using (var stream = File.OpenRead(reference)) { var moduleMetadata = ModuleMetadata.CreateFromStream(stream, PEStreamOptions.PrefetchMetadata); var assemblyMetadata = AssemblyMetadata.Create(moduleMetadata); metadataRerefences.Add(assemblyMetadata.GetReference(filePath: reference)); } } } if (AdditionalMetadataReferences.Any()) { metadataRerefences.AddRange(AdditionalMetadataReferences); } return(metadataRerefences); }
public MetadataReference GetMetadataReference(string path) { var cacheKey = _cacheKeyPrefix + path.ToLowerInvariant(); var metadata = _cache.GetOrSet(cacheKey, ctx => { _logger.WriteVerbose(string.Format("Cache miss {0}", path)); ctx.AddExpirationTrigger(new FileWriteTimeTrigger(path)); using (var stream = File.OpenRead(path)) { var moduleMetadata = ModuleMetadata.CreateFromStream(stream, PEStreamOptions.PrefetchMetadata); return(AssemblyMetadata.Create(moduleMetadata)); } }); var documentationFile = Path.ChangeExtension(path, ".xml"); if (File.Exists(documentationFile)) { return(metadata.GetReference(new XmlDocumentationProvider(documentationFile))); } return(metadata.GetReference()); }
/// <exception cref="IOException"/> /// <exception cref="BadImageFormatException" /> private AssemblyMetadata CreateAssemblyMetadata( FileKey fileKey, ModuleMetadata manifestModule, List <ITemporaryStreamStorage> storages, Func <FileKey, List <ITemporaryStreamStorage>, ModuleMetadata> moduleMetadataGetter) { ImmutableArray <ModuleMetadata> .Builder moduleBuilder = null; string assemblyDir = null; foreach (string moduleName in manifestModule.GetModuleNames()) { if (moduleBuilder == null) { moduleBuilder = ImmutableArray.CreateBuilder <ModuleMetadata>(); moduleBuilder.Add(manifestModule); assemblyDir = Path.GetDirectoryName(fileKey.FullPath); } var moduleFileKey = FileKey.Create(PathUtilities.CombineAbsoluteAndRelativePaths(assemblyDir, moduleName)); var metadata = moduleMetadataGetter(moduleFileKey, storages); moduleBuilder.Add(metadata); } var modules = (moduleBuilder != null) ? moduleBuilder.ToImmutable() : ImmutableArray.Create(manifestModule); return(AssemblyMetadata.Create(modules)); }
/// <summary> /// 运行时编译服务 /// </summary> /// <param name="pluginDllFullPaths">提供引用依赖插件模块等路径</param> public static void InitReference(params string[] pluginDllFullPaths) { if (pluginDllFullPaths == null || pluginDllFullPaths.Length == 0) { return; } var hashSet = new HashSet <MetadataReference>(globalMetadataReferences); var newList = new List <MetadataReference>(); foreach (var filePath in pluginDllFullPaths) { var dllFullPath = Utils.MapPath(filePath); var assembly = AssemblyLoader.Load(dllFullPath); if (assembly == null) { continue; } using (var stream = File.OpenRead(dllFullPath)) { var moduleMetadata = ModuleMetadata.CreateFromStream(stream, PEStreamOptions.PrefetchMetadata); var assemblyMetadata = AssemblyMetadata.Create(moduleMetadata); var referenceMetadata = assemblyMetadata.GetReference(filePath: dllFullPath); if (hashSet.Add(referenceMetadata)) { newList.Add(referenceMetadata); } } } lock (((ICollection)globalMetadataReferences).SyncRoot) { globalMetadataReferences.AddRange(newList); } }
public MetadataReference GetMetadataReference(string filePath) { var cacheKey = _cacheKeyPrefix + filePath.ToLowerInvariant(); var assemblyMetadata = _cache.Get <AssemblyMetadata>(cacheKey); if (assemblyMetadata == null) { _logger.LogDebug(string.Format("Cache miss {0}", filePath)); using (var stream = File.OpenRead(filePath)) { var moduleMetadata = ModuleMetadata.CreateFromStream(stream, PEStreamOptions.PrefetchMetadata); assemblyMetadata = AssemblyMetadata.Create(moduleMetadata); var options = new MemoryCacheEntryOptions(); options.ExpirationTokens.Add(new FileWriteTimeTrigger(filePath)); _cache.Set(cacheKey, assemblyMetadata, options); } } var displayText = assemblyMetadata.GetModules().FirstOrDefault()?.Name; var documentationFile = Path.ChangeExtension(filePath, ".xml"); var documentationProvider = File.Exists(documentationFile) ? XmlDocumentationProvider.CreateFromFile(documentationFile) : null; return(assemblyMetadata.GetReference( documentationProvider, filePath: filePath, display: displayText)); }
private (Metadata metadata, ImmutableArray <ITemporaryStreamStorage> storages)? TryReadMetadataFrom( ObjectReader reader, SerializationKinds kind, CancellationToken cancellationToken) { var imageKind = reader.ReadInt32(); if (imageKind == MetadataFailed) { // error case return(null); } var metadataKind = (MetadataImageKind)imageKind; if (_storageService == null) { if (metadataKind == MetadataImageKind.Assembly) { using var pooledMetadata = Creator.CreateList <ModuleMetadata>(); var count = reader.ReadInt32(); for (var i = 0; i < count; i++) { metadataKind = (MetadataImageKind)reader.ReadInt32(); Contract.ThrowIfFalse(metadataKind == MetadataImageKind.Module); pooledMetadata.Object.Add(ReadModuleMetadataFrom(reader, kind)); } return(AssemblyMetadata.Create(pooledMetadata.Object), storages : default);
/// <exception cref="IOException"/> /// <exception cref="BadImageFormatException" /> private AssemblyMetadata CreateAssemblyMetadata( FileKey fileKey, ModuleMetadata manifestModule, List <ITemporaryStreamStorage> storages, Func <FileKey, List <ITemporaryStreamStorage>, ModuleMetadata> moduleMetadataFactory) { var moduleBuilder = ArrayBuilder <ModuleMetadata> .GetInstance(); string assemblyDir = null; foreach (string moduleName in manifestModule.GetModuleNames()) { if (moduleBuilder.Count == 0) { moduleBuilder.Add(manifestModule); assemblyDir = Path.GetDirectoryName(fileKey.FullPath); } var moduleFileKey = FileKey.Create(PathUtilities.CombineAbsoluteAndRelativePaths(assemblyDir, moduleName)); var metadata = moduleMetadataFactory(moduleFileKey, storages); moduleBuilder.Add(metadata); } if (moduleBuilder.Count == 0) { moduleBuilder.Add(manifestModule); } return(AssemblyMetadata.Create( moduleBuilder.ToImmutableAndFree())); }
internal Metadata GetMetadata(string fullPath, MetadataReferenceProperties properties) { // Check if we have an entry in the dictionary. FileKey?fileKey = GetUniqueFileKey(fullPath); Metadata metadata; if (fileKey.HasValue && _metadataCache.TryGetValue(fileKey.Value, out metadata) && metadata != null) { return(metadata); } if (properties.Kind == MetadataImageKind.Module) { var result = CreateModuleMetadata(fullPath, prefetchEntireImage: true); //?? never add modules to cache? return(result); } else { var primaryModule = CreateModuleMetadata(fullPath, prefetchEntireImage: false); // Get all the modules, and load them. Create an assembly metadata. var allModules = GetAllModules(primaryModule, Path.GetDirectoryName(fullPath)); Metadata result = AssemblyMetadata.Create(allModules); result = _metadataCache.GetOrAdd(fileKey.Value, result); return(result); } }
private MetadataReference GetMetadataReference(string assetPath) { var extension = Path.GetExtension(assetPath); string path = assetPath; if (string.IsNullOrEmpty(extension) || !ValidExtensions.Any(e => e.Equals(extension, StringComparison.OrdinalIgnoreCase))) { foreach (var ext in ValidExtensions) { path = assetPath + ext; if (File.Exists(path)) { break; } } } AssemblyMetadata assemblyMetadata = null; if (!_cache.TryGetValue(path, out assemblyMetadata)) { if (File.Exists(path)) { using (var stream = File.OpenRead(path)) { var moduleMetadata = ModuleMetadata.CreateFromStream(stream, PEStreamOptions.PrefetchMetadata); assemblyMetadata = AssemblyMetadata.Create(moduleMetadata); _cache[path] = assemblyMetadata; } } } return(assemblyMetadata?.GetReference()); }
public static IEnumerable <MetadataReference> GetMetadataReference(this ResolvedReference reference, bool throwOnError = true) { var references = new List <MetadataReference>(); AssemblyMetadata assemblyMetadata; try { using (var stream = File.OpenRead(reference.ResolvedPath)) { var moduleMetadata = ModuleMetadata.CreateFromStream(stream, PEStreamOptions.PrefetchMetadata); assemblyMetadata = AssemblyMetadata.Create(moduleMetadata); references.Add(assemblyMetadata.GetReference()); } } catch (Exception ex) when(ex is NotSupportedException || ex is ArgumentException || ex is BadImageFormatException || ex is IOException) { // TODO: Log this if (throwOnError) { throw ex; } } return(references); }
private static unsafe MetadataReference GetMetadataReferenceInSingleFileApp(Assembly assembly) { assembly.TryGetRawMetadata(out byte *blob, out int length); var moduleMetadata = ModuleMetadata.CreateFromMetadata((IntPtr)blob, length); var assemblyMetadata = AssemblyMetadata.Create(moduleMetadata); return(assemblyMetadata.GetReference()); }
private static MetadataReference CreateMetadataReference(string path) { var stream = File.OpenRead(path); var moduleMetadata = ModuleMetadata.CreateFromStream(stream, PEStreamOptions.PrefetchMetadata); var assemblyMetadata = AssemblyMetadata.Create(moduleMetadata); return(assemblyMetadata.GetReference(filePath: path)); }
private unsafe static MetadataReference CreateMetadataReferenceFromAssembly(Assembly assembly) { assembly.TryGetRawMetadata(out var blob, out var length); var moduleMetadata = ModuleMetadata.CreateFromMetadata((IntPtr)blob, length); var assemblyMetadata = AssemblyMetadata.Create(moduleMetadata); return(assemblyMetadata.GetReference()); }
/// <summary> /// Creates a <see cref="AssemblyMetadata"/> for the assembly specified by <paramref name="fileReference"/>. /// </summary> /// <param name="fileReference">The <see cref="IMetadataFileReference"/>.</param> /// <returns>An <see cref="AssemblyMetadata"/>.</returns> public static AssemblyMetadata CreateAssemblyMetadata(this IMetadataFileReference fileReference) { using (var stream = File.OpenRead(fileReference.Path)) { var moduleMetadata = ModuleMetadata.CreateFromStream(stream, PEStreamOptions.PrefetchMetadata); return(AssemblyMetadata.Create(moduleMetadata)); } }
private AssemblyMetadata CreateAssemblyMetadata(FileStream manifestModuleCopyStream, string originalPath, string shadowCopyPath) { // We don't need to use the global metadata cache here since the shadow copy // won't change and is private to us - only users of the same shadow copy provider see it. ImmutableArray <ModuleMetadata> .Builder moduleBuilder = null; bool fault = true; ModuleMetadata manifestModule = null; try { manifestModule = CreateModuleMetadata(manifestModuleCopyStream); string originalDirectory = null, shadowCopyDirectory = null; foreach (string moduleName in manifestModule.GetModuleNames()) { if (moduleBuilder == null) { moduleBuilder = ImmutableArray.CreateBuilder <ModuleMetadata>(); moduleBuilder.Add(manifestModule); originalDirectory = Path.GetDirectoryName(originalPath); shadowCopyDirectory = Path.GetDirectoryName(shadowCopyPath); } FileStream moduleCopyStream = CopyFile( originalPath: Path.Combine(originalDirectory, moduleName), shadowCopyPath: Path.Combine(shadowCopyDirectory, moduleName)); moduleBuilder.Add(CreateModuleMetadata(moduleCopyStream)); } var modules = (moduleBuilder != null) ? moduleBuilder.ToImmutable() : ImmutableArray.Create(manifestModule); fault = false; return(AssemblyMetadata.Create(modules)); } finally { if (fault) { if (manifestModule != null) { manifestModule.Dispose(); } if (moduleBuilder != null) { for (int i = 1; i < moduleBuilder.Count; i++) { moduleBuilder[i].Dispose(); } } } } }
private static MetadataReference CreateMetadataReference(string path) { using (var stream = File.OpenRead(path)) { var moduleMetadata = ModuleMetadata.CreateFromStream(stream, System.Reflection.PortableExecutable.PEStreamOptions.PrefetchMetadata); var assemblyMetadata = AssemblyMetadata.Create(moduleMetadata); return(assemblyMetadata.GetReference(filePath: path)); } }
public void ImageOwnership() { ModuleMetadata m1, m2, m3; var a = AssemblyMetadata.Create( m1 = ModuleMetadata.CreateFromImage( TestResources.SymbolsTests.MultiModule.MultiModuleDll ), m2 = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.MultiModule.mod2), m3 = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.MultiModule.mod3) ); Assert.True(a.IsImageOwner, "Assembly should own the image"); Assert.True(m1.IsImageOwner, "Module should own the image"); Assert.True(m2.IsImageOwner, "Module should own the image"); Assert.True(m3.IsImageOwner, "Module should own the image"); var copy1 = a.Copy(); Assert.False(copy1.IsImageOwner, "Assembly should not own the image"); Assert.False(copy1.GetModules()[0].IsImageOwner, "Module should not own the image"); Assert.False(copy1.GetModules()[1].IsImageOwner, "Module should not own the image"); Assert.False(copy1.GetModules()[2].IsImageOwner, "Module should not own the image"); Assert.Equal(m1.Module, copy1.GetModules()[0].Module); Assert.Equal(m2.Module, copy1.GetModules()[1].Module); Assert.Equal(m3.Module, copy1.GetModules()[2].Module); var copy2 = copy1.Copy(); Assert.False(copy2.IsImageOwner, "Assembly should not own the image"); Assert.False(copy2.GetModules()[0].IsImageOwner, "Module should not own the image"); Assert.False(copy2.GetModules()[1].IsImageOwner, "Module should not own the image"); Assert.False(copy2.GetModules()[2].IsImageOwner, "Module should not own the image"); Assert.Equal(m1.Module, copy2.GetModules()[0].Module); Assert.Equal(m2.Module, copy2.GetModules()[1].Module); Assert.Equal(m3.Module, copy2.GetModules()[2].Module); copy1.Dispose(); Assert.Throws <ObjectDisposedException>(() => copy1.GetModules()[0].Module); Assert.Throws <ObjectDisposedException>(() => copy1.GetModules()[1].Module); Assert.Throws <ObjectDisposedException>(() => copy1.GetModules()[2].Module); Assert.NotNull(a.GetModules()[0].Module); Assert.NotNull(a.GetModules()[1].Module); Assert.NotNull(a.GetModules()[2].Module); a.Dispose(); Assert.Throws <ObjectDisposedException>(() => a.GetModules()[0].Module); Assert.Throws <ObjectDisposedException>(() => a.GetModules()[1].Module); Assert.Throws <ObjectDisposedException>(() => a.GetModules()[2].Module); }
private static PortableExecutableReference MakeCompileTimeWinMdAssemblyMetadata(ArrayBuilder <ModuleMetadata> runtimeModules) { var metadata = ModuleMetadata.CreateFromImage(GetWindowsProxyBytes()); var builder = ArrayBuilder <ModuleMetadata> .GetInstance(); builder.Add(metadata); builder.AddRange(runtimeModules); var assemblyMetadata = AssemblyMetadata.Create(builder.ToImmutableAndFree()); return(assemblyMetadata.GetReference(embedInteropTypes: false, display: metadata.Name)); }
private MetadataReference CreateMetadataFileReference(string path) { var metadata = _metadataFileCache.GetOrAdd(path, _ => { using (var stream = File.OpenRead(path)) { var moduleMetadata = ModuleMetadata.CreateFromStream(stream, PEStreamOptions.PrefetchMetadata); return(AssemblyMetadata.Create(moduleMetadata)); } }); return(metadata.GetReference()); }
unsafe static MetadataReference GetReference(Assembly assembly) { if (!assembly.TryGetRawMetadata(out var blob, out var length)) { throw new NotSupportedException(); } var moduleMetadata = ModuleMetadata.CreateFromMetadata((IntPtr)blob, length); var assemblyMetadata = AssemblyMetadata.Create(moduleMetadata); return(assemblyMetadata.GetReference()); }
internal IReadOnlyList <MetadataReference> Resolve(Assembly assembly, DependencyContext dependencyContext) { var libraryPaths = new HashSet <string>(StringComparer.OrdinalIgnoreCase); IEnumerable <string> references; if (dependencyContext == null) { var context = new HashSet <string>(); var x = GetReferencedAssemblies(assembly, ExcludedAssemblies, context).Union(new[] { assembly }).ToArray(); references = x.Select(p => _directoryFormatter.GetAssemblyDirectory(p)).ToList(); } else { var excluded = ExcludedAssemblies; var compiledLibraries = dependencyContext.CompileLibraries.Select(x => x.Name); var paths = dependencyContext.CompileLibraries.SelectMany(x => x.ResolveReferencePaths()).ToList(); references = dependencyContext.CompileLibraries.Where(x => !ExcludedAssemblies.Contains(x.Name)).SelectMany(library => library.ResolveReferencePaths()).ToList(); if (!references.Any()) { throw new RazorLightException( "Can't load metadata reference from the entry assembly. " + "Make sure PreserveCompilationContext is set to true in *.csproj file"); } } var metadataReferences = new List <MetadataReference>(); foreach (var reference in references) { if (!libraryPaths.Add(reference)) { continue; } using (var stream = File.OpenRead(reference)) { var moduleMetadata = ModuleMetadata.CreateFromStream(stream, PEStreamOptions.PrefetchMetadata); var assemblyMetadata = AssemblyMetadata.Create(moduleMetadata); metadataReferences.Add(assemblyMetadata.GetReference(filePath: reference)); } } if (AdditionalMetadataReferences.Any()) { metadataReferences.AddRange(AdditionalMetadataReferences); } return(metadataReferences); }
private MetadataReference GetMetadataReference(string path) { var metadata = _cache.Get <AssemblyMetadata>(path, ctx => { ctx.Monitor(new FileWriteTimeCacheDependency(path)); using (var stream = File.OpenRead(path)) { var moduleMetadata = ModuleMetadata.CreateFromStream(stream, PEStreamOptions.PrefetchMetadata); return(AssemblyMetadata.Create(moduleMetadata)); } }); return(metadata.GetReference()); }
public void Disposal() { ModuleMetadata m1, m2, m3; var md = AssemblyMetadata.Create( m1 = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.MultiModule.MultiModuleDll), m2 = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.MultiModule.mod2), m3 = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.MultiModule.mod3)); md.Dispose(); Assert.Throws <ObjectDisposedException>(() => m1.Module); Assert.Throws <ObjectDisposedException>(() => m2.Module); Assert.Throws <ObjectDisposedException>(() => m3.Module); md.Dispose(); }
private MetadataReference GetMetadataReference(string path) { AssemblyMetadata assemblyMetadata; if (!_cache.TryGetValue(path, out assemblyMetadata)) { using (var stream = File.OpenRead(path)) { var moduleMetadata = ModuleMetadata.CreateFromStream(stream, PEStreamOptions.PrefetchMetadata); assemblyMetadata = AssemblyMetadata.Create(moduleMetadata); _cache[path] = assemblyMetadata; } } return(assemblyMetadata.GetReference()); }
private MetadataReference GetMetadataReference(string path) { try { using (var stream = File.OpenRead(path)) { var moduleMetadata = ModuleMetadata.CreateFromStream(stream, PEStreamOptions.PrefetchMetadata); var assemblyMetadata = AssemblyMetadata.Create(moduleMetadata); return(assemblyMetadata.GetReference()); } } catch { return(null); } }
private static PortableExecutableReference MakeAssemblyMetadata(ModuleMetadata metadata, Dictionary <string, ModuleMetadata> modulesByName) { Debug.Assert(metadata.Module.IsManifestModule); var builder = ArrayBuilder <ModuleMetadata> .GetInstance(); builder.Add(metadata); // Include any associated netmodules from the manifest. if (modulesByName != null) { try { var reader = metadata.MetadataReader; foreach (var handle in reader.AssemblyFiles) { var assemblyFile = reader.GetAssemblyFile(handle); if (assemblyFile.ContainsMetadata) { var name = reader.GetString(assemblyFile.Name); // Find the assembly file in the set of netmodules with that name. // The file may be missing if the file is not a module (say a resource) // or if the module has not been loaded yet. The value will be null // if the name was ambiguous. ModuleMetadata module; if (!modulesByName.TryGetValue(name, out module)) { // AssemblyFile names may contain file information (".dll", etc). modulesByName.TryGetValue(GetFileNameWithoutExtension(name), out module); } if (module != null) { builder.Add(module); } } } } catch (Exception e) when(IsBadMetadataException(e)) { // Ignore modules with "bad" metadata. } } var assemblyMetadata = AssemblyMetadata.Create(builder.ToImmutableAndFree()); return(assemblyMetadata.GetReference(embedInteropTypes: false, display: metadata.Name)); }