private static ModuleMetadata GetModuleMetadata( TemporaryStorageService.TemporaryStreamStorage storage) { // For an unmanaged memory stream, ModuleMetadata can take ownership directly. var stream = storage.ReadStream(CancellationToken.None); unsafe { return(ModuleMetadata.CreateFromMetadata((IntPtr)stream.PositionPointer, (int)stream.Length, stream, disposeOwner: true)); } }
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()); }
public unsafe void CreateFromMetadata_Module_Stream() { var netModule = TestResources.MetadataTests.NetModule01.ModuleCS00; PEHeaders h = new PEHeaders(new MemoryStream(netModule)); fixed(byte *ptr = &netModule[h.MetadataStartOffset]) { var stream = new UnmanagedMemoryStream(ptr, h.MetadataSize); ModuleMetadata.CreateFromMetadata((IntPtr)stream.PositionPointer, (int)stream.Length, stream, disposeOwner: true); } }
public unsafe void CreateFromMetadata_Assembly() { var assembly = TestResources.Basic.Members; PEHeaders h = new PEHeaders(new MemoryStream(assembly)); fixed(byte *ptr = &assembly[h.MetadataStartOffset]) { var metadata = ModuleMetadata.CreateFromMetadata((IntPtr)ptr, h.MetadataSize); Assert.Equal(new AssemblyIdentity("Members"), metadata.Module.ReadAssemblyIdentityOrThrow()); } }
/// <summary> /// Verify the set of module metadata blocks /// contains all blocks referenced by the set. /// </summary> private static void VerifyAllModules(IEnumerable <ModuleInstance> modules) { var blocks = modules.Select(m => m.MetadataBlock).Select(b => ModuleMetadata.CreateFromMetadata(b.Pointer, b.Size)); var names = new HashSet <string>(blocks.Select(b => b.Name)); foreach (var block in blocks) { foreach (var name in block.GetModuleNames()) { Assert.True(names.Contains(name)); } } }
public unsafe void CreateFromMetadata_Errors() { Assert.Throws <ArgumentNullException>(() => ModuleMetadata.CreateFromMetadata(IntPtr.Zero, 0)); Assert.Throws <ArgumentOutOfRangeException>(() => { fixed(byte *ptr = new byte[] { 1, 2, 3 }) ModuleMetadata.CreateFromMetadata((IntPtr)ptr, 0); }); Assert.Throws <ArgumentOutOfRangeException>(() => { fixed(byte *ptr = new byte[] { 1, 2, 3 }) ModuleMetadata.CreateFromMetadata((IntPtr)ptr, -1); }); fixed(byte *ptr = new byte[] { 1, 2, 3 }) { var metadata = ModuleMetadata.CreateFromMetadata((IntPtr)ptr, 3); Assert.Throws <BadImageFormatException>(() => metadata.GetModuleNames()); } }
public unsafe void CreateFromMetadata_Assembly_Stream() { var assembly = TestResources.Basic.Members; PEHeaders h = new PEHeaders(new MemoryStream(assembly)); fixed(byte *ptr = &assembly[h.MetadataStartOffset]) { var stream = new UnmanagedMemoryStream(ptr, h.MetadataSize); var metadata = ModuleMetadata.CreateFromMetadata((IntPtr)stream.PositionPointer, (int)stream.Length, stream, disposeOwner: true); Assert.Equal(new AssemblyIdentity("Members"), metadata.Module.ReadAssemblyIdentityOrThrow()); } }
public void CreateInitialBaseline() { var provider = new LocalVariableNameProvider(_ => ImmutableArray.Create <string>()); var peModule = ModuleMetadata.CreateFromImage(TestResources.MetadataTests.Basic.Members); var peReader = peModule.Module.PEReaderOpt; var mdBytes = peReader.GetMetadata().GetContent(); var mdBytesHandle = PinnedImmutableArray.Create(mdBytes); var mdModule = ModuleMetadata.CreateFromMetadata(mdBytesHandle.Pointer, mdBytes.Length); Assert.Throws <ArgumentNullException>(() => EmitBaseline.CreateInitialBaseline(null, provider)); Assert.Throws <ArgumentNullException>(() => EmitBaseline.CreateInitialBaseline(peModule, null)); Assert.Throws <ArgumentException>(() => EmitBaseline.CreateInitialBaseline(mdModule, provider)); }
private ModuleMetadata CreateModuleMetadataFromTemporaryStorage(FileKey moduleFileKey, List <ITemporaryStreamStorage>?storages) { GetStorageInfoFromTemporaryStorage(moduleFileKey, out var storage, out var stream, out var pImage); var metadata = ModuleMetadata.CreateFromMetadata(pImage, (int)stream.Length); // first time, the metadata is created. tie lifetime. s_lifetimeMap.Add(metadata, stream); // hold onto storage if requested storages?.Add(storage); return(metadata); }
private ModuleMetadata GetModuleMetadata(ITemporaryStreamStorage storage) { var stream = storage.ReadStream(CancellationToken.None); // under VS host, direct access should be supported var directAccess = (ISupportDirectMemoryAccess)stream; var pImage = directAccess.GetPointer(); var metadata = ModuleMetadata.CreateFromMetadata(pImage, (int)stream.Length); // memory management. _lifetimeMap.Add(metadata, stream); return(metadata); }
public void CreateInitialBaseline() { var provider = new Func <MethodDefinitionHandle, EditAndContinueMethodDebugInformation>(_ => default(EditAndContinueMethodDebugInformation)); var peModule = ModuleMetadata.CreateFromImage(TestResources.MetadataTests.Basic.Members); var peReader = peModule.Module.PEReaderOpt; var mdBytes = peReader.GetMetadata().GetContent(); var mdBytesHandle = GCHandle.Alloc(mdBytes.DangerousGetUnderlyingArray(), GCHandleType.Pinned); var mdModule = ModuleMetadata.CreateFromMetadata(mdBytesHandle.AddrOfPinnedObject(), mdBytes.Length); Assert.Throws <ArgumentNullException>(() => EmitBaseline.CreateInitialBaseline(null, provider)); Assert.Throws <ArgumentNullException>(() => EmitBaseline.CreateInitialBaseline(peModule, null)); Assert.Throws <ArgumentException>(() => EmitBaseline.CreateInitialBaseline(mdModule, provider)); }
private static ModuleMetadata GetBaselineModuleMetadata(DkmClrModuleInstance module) { IntPtr metadataPtr; uint metadataSize; try { metadataPtr = module.GetBaselineMetaDataBytesPtr(out metadataSize); } catch (Exception e) when(DkmExceptionUtilities.IsBadOrMissingMetadataException(e)) { return(null); } return(ModuleMetadata.CreateFromMetadata(metadataPtr, (int)metadataSize)); }
private void GetMetadata(Stream stream, long length, out ModuleMetadata metadata, out object lifeTimeObject) { if (stream is ISupportDirectMemoryAccess directAccess) { metadata = ModuleMetadata.CreateFromMetadata(directAccess.GetPointer(), (int)length); lifeTimeObject = stream; return; } PinnedObject pinnedObject; if (stream is MemoryStream memory && memory.TryGetBuffer(out var buffer) && buffer.Offset == 0) { pinnedObject = new PinnedObject(buffer.Array, buffer.Count); }
public static unsafe ICollection <MetadataReference> AddReferencesFromAssemblyOf <TObject>(this ICollection <MetadataReference> references) { Assembly assembly = typeof(TObject).GetTypeInfo().Assembly; // See http://www.strathweb.com/2016/03/roslyn-scripting-on-coreclr-net-cli-and-dnx-and-in-memory-assemblies/ if (assembly.TryGetRawMetadata(out byte *b, out int length)) { var moduleMetadata = ModuleMetadata.CreateFromMetadata((IntPtr)b, length); var assemblyMetadata = AssemblyMetadata.Create(moduleMetadata); var result = assemblyMetadata.GetReference(); references.Add(result); return(references); } else { throw new Exception("Failed to get raw metadata for assembly: " + assembly.FullName); } }
private ModuleMetadata CreateModuleMetadataFromTemporaryStorage(FileKey moduleFileKey, List <ITemporaryStreamStorage> storages) { ITemporaryStreamStorage storage; Stream stream; IntPtr pImage; GetStorageInfoFromTemporaryStorage(moduleFileKey, out storage, out stream, out pImage); var metadata = ModuleMetadata.CreateFromMetadata(pImage, (int)stream.Length); // first time, the metadata is created. tie lifetime. s_lifetimeMap.Add(metadata, stream); // hold onto storage if requested if (storages != null) { storages.Add(storage); } return(metadata); }
public unsafe TConfig Create <TConfig>(TConfig config) { var code = File.ReadAllText(_rootPath + "/" + _scriptName); byte *b; int length; var assembly = typeof(TConfig).GetTypeInfo().Assembly; if (assembly.TryGetRawMetadata(out b, out length)) { var moduleMetadata = ModuleMetadata.CreateFromMetadata((IntPtr)b, length); var assemblyMetadata = AssemblyMetadata.Create(moduleMetadata); var reference = assemblyMetadata.GetReference(); var opts = ScriptOptions.Default.AddImports(_namespaces).AddReferences(_assemblies).AddReferences(reference); var script = CSharpScript.Create(code, opts, typeof(TConfig)); var result = script.RunAsync(config).Result; } return(config); }
/// <summary> /// 将模板内容编译并输出内存流 /// </summary> /// <param name="templateSource"></param> /// <param name="options"></param> /// <returns></returns> private static MemoryStream CreateAndCompileToStream(string templateSource, ViewEngineOptions options) { templateSource = WriteDirectives(templateSource, options); var engine = RazorProjectEngine.Create( RazorConfiguration.Default, RazorProjectFileSystem.Create(@"."), (builder) => { builder.SetNamespace(options.TemplateNamespace); }); var fileName = Path.GetRandomFileName(); var document = RazorSourceDocument.Create(templateSource, fileName); var codeDocument = engine.Process( document, null, new List <RazorSourceDocument>(), new List <TagHelperDescriptor>()); var razorCSharpDocument = codeDocument.GetCSharpDocument(); var syntaxTree = CSharpSyntaxTree.ParseText(razorCSharpDocument.GeneratedCode); var compilation = CSharpCompilation.Create( fileName, new[] { syntaxTree }, options.ReferencedAssemblies .Select(ass => { // MetadataReference.CreateFromFile(ass.Location) unsafe { ass.TryGetRawMetadata(out var blob, out var length); var moduleMetadata = ModuleMetadata.CreateFromMetadata((IntPtr)blob, length); var assemblyMetadata = AssemblyMetadata.Create(moduleMetadata); var metadataReference = assemblyMetadata.GetReference(); return(metadataReference); } }) .Concat(options.MetadataReferences) .ToList(), new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); var memoryStream = new MemoryStream(); var emitResult = compilation.Emit(memoryStream); if (!emitResult.Success) { var errors = emitResult.Diagnostics.ToList(); var exception = new ViewEngineTemplateException($"Unable to compile template: {errors.FirstOrDefault()}") { Errors = errors, GeneratedCode = razorCSharpDocument.GeneratedCode }; throw exception; } memoryStream.Position = 0; return(memoryStream); }
private MemoryStream CreateAndCompileToStream(string templateSource, RazorEngineCompilationOptions options) { templateSource = this.WriteDirectives(templateSource, options); RazorProjectEngine engine = RazorProjectEngine.Create( RazorConfiguration.Default, RazorProjectFileSystem.Create(@"."), (builder) => { builder.SetNamespace(options.TemplateNamespace); }); string fileName = Path.GetRandomFileName(); RazorSourceDocument document = RazorSourceDocument.Create(templateSource, fileName); RazorCodeDocument codeDocument = engine.Process( document, null, new List <RazorSourceDocument>(), new List <TagHelperDescriptor>()); RazorCSharpDocument razorCSharpDocument = codeDocument.GetCSharpDocument(); SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(razorCSharpDocument.GeneratedCode); CSharpCompilation compilation = CSharpCompilation.Create( fileName, new[] { syntaxTree }, options.ReferencedAssemblies .Select(ass => { #if NETSTANDARD2_0 return(MetadataReference.CreateFromFile(ass.Location)); #else unsafe { ass.TryGetRawMetadata(out byte *blob, out int length); ModuleMetadata moduleMetadata = ModuleMetadata.CreateFromMetadata((IntPtr)blob, length); AssemblyMetadata assemblyMetadata = AssemblyMetadata.Create(moduleMetadata); PortableExecutableReference metadataReference = assemblyMetadata.GetReference(); return(metadataReference); } #endif }) .Concat(options.MetadataReferences) .ToList(), new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); MemoryStream memoryStream = new MemoryStream(); EmitResult emitResult = compilation.Emit(memoryStream); if (!emitResult.Success) { RazorEngineCompilationException exception = new RazorEngineCompilationException() { Errors = emitResult.Diagnostics.ToList(), GeneratedCode = razorCSharpDocument.GeneratedCode }; throw exception; } memoryStream.Position = 0; return(memoryStream); }
/// <summary> /// Group module metadata into assemblies. /// </summary> internal static ImmutableArray <MetadataReference> MakeAssemblyReferences(this ImmutableArray <MetadataBlock> metadataBlocks) { // Get metadata for each module. var metadataBuilder = ArrayBuilder <ModuleMetadata> .GetInstance(); // Win8 applications contain a reference to Windows.winmd version >= 1.3 // and perhaps multiple application winmds. At runtime, Windows.winmd // is replaced by multiple Windows.*.winmd version >= 1.3. In the EE, we // need to map compile-time assembly references to the runtime assemblies // supplied by the debugger. To do so, we “merge” all winmds named // Windows.*.winmd into a single fake Windows.winmd at runtime. // All other (application) winmds are left as is. var runtimeWinMdBuilder = ArrayBuilder <ModuleMetadata> .GetInstance(); foreach (var block in metadataBlocks) { var metadata = ModuleMetadata.CreateFromMetadata(block.Pointer, block.Size, includeEmbeddedInteropTypes: true); try { if (IsWindowsComponent(metadata.MetadataReader, metadata.Name)) { runtimeWinMdBuilder.Add(metadata); } else { metadataBuilder.Add(metadata); } } catch (Exception e) when(IsBadMetadataException(e)) { // Ignore modules with "bad" metadata. } } // Index non-primary netmodules by name. Multiple modules may // have the same name but we do not have a way to differentiate // netmodules other than by name so if there are duplicates, the // dictionary value is set to null and references are dropped when // generating the containing assembly metadata. Dictionary <string, ModuleMetadata> modulesByName = null; foreach (var metadata in metadataBuilder) { if (IsPrimaryModule(metadata)) { // Primary module. No need to add to dictionary. continue; } if (modulesByName == null) { modulesByName = new Dictionary <string, ModuleMetadata>(); // Requires case-insensitive comparison? } var name = metadata.Name; modulesByName[name] = modulesByName.ContainsKey(name) ? null : metadata; } // Build assembly references from modules in primary module // manifests. There will be duplicate assemblies if the process has // multiple app domains and those duplicates need to be dropped. var referencesBuilder = ArrayBuilder <MetadataReference> .GetInstance(); var moduleIds = PooledHashSet <Guid> .GetInstance(); foreach (var metadata in metadataBuilder) { if (!IsPrimaryModule(metadata)) { continue; } var mvid = metadata.GetModuleVersionId(); if (moduleIds.Contains(mvid)) { continue; } moduleIds.Add(mvid); referencesBuilder.Add(MakeAssemblyMetadata(metadata, modulesByName)); } moduleIds.Free(); // Any runtime winmd modules were separated out initially. Now add // those to a placeholder for the missing compile time module since // each of the runtime winmds refer to the compile time module. if (runtimeWinMdBuilder.Any()) { referencesBuilder.Add(MakeCompileTimeWinMdAssemblyMetadata(runtimeWinMdBuilder)); } runtimeWinMdBuilder.Free(); metadataBuilder.Free(); return(referencesBuilder.ToImmutableAndFree()); }
/// <summary> /// Group module metadata into assemblies. /// If <paramref name="moduleVersionId"/> is set, the /// assemblies are limited to those referenced by that module. /// </summary> internal static ImmutableArray <MetadataReference> MakeAssemblyReferences( this ImmutableArray <MetadataBlock> metadataBlocks, Guid moduleVersionId, AssemblyIdentityComparer identityComparer) { Debug.Assert((identityComparer == null) || (moduleVersionId != default(Guid))); // Get metadata for each module. var metadataBuilder = ArrayBuilder <ModuleMetadata> .GetInstance(); // Win8 applications contain a reference to Windows.winmd version >= 1.3 // and perhaps multiple application winmds. At runtime, Windows.winmd // is replaced by multiple Windows.*.winmd version >= 1.3. In the EE, we // need to map compile-time assembly references to the runtime assemblies // supplied by the debugger. To do so, we "merge" all winmds named // Windows.*.winmd into a single fake Windows.winmd at runtime. // All other (application) winmds are left as is. var runtimeWinMdBuilder = ArrayBuilder <ModuleMetadata> .GetInstance(); foreach (var block in metadataBlocks) { var metadata = ModuleMetadata.CreateFromMetadata(block.Pointer, block.Size, includeEmbeddedInteropTypes: true); try { if (IsWindowsComponent(metadata.MetadataReader, metadata.Name)) { runtimeWinMdBuilder.Add(metadata); } else { metadataBuilder.Add(metadata); } } catch (Exception e) when(IsBadMetadataException(e)) { // Ignore modules with "bad" metadata. } } // Index non-primary netmodules by name. Multiple modules may // have the same name but we do not have a way to differentiate // netmodules other than by name so if there are duplicates, the // dictionary value is set to null and references are dropped when // generating the containing assembly metadata. Dictionary <string, ModuleMetadata> modulesByName = null; foreach (var metadata in metadataBuilder) { if (IsPrimaryModule(metadata)) { // Primary module. No need to add to dictionary. continue; } if (modulesByName == null) { modulesByName = new Dictionary <string, ModuleMetadata>(); // Requires case-insensitive comparison? } var name = metadata.Name; modulesByName[name] = modulesByName.ContainsKey(name) ? null : metadata; } // Build assembly references from modules in primary module manifests. var referencesBuilder = ArrayBuilder <MetadataReference> .GetInstance(); var identitiesBuilder = (identityComparer == null) ? null : ArrayBuilder <AssemblyIdentity> .GetInstance(); AssemblyIdentity corLibrary = null; AssemblyIdentity intrinsicsAssembly = null; foreach (var metadata in metadataBuilder) { if (!IsPrimaryModule(metadata)) { continue; } if (identitiesBuilder != null) { var reader = metadata.MetadataReader; var identity = reader.ReadAssemblyIdentityOrThrow(); identitiesBuilder.Add(identity); // If this assembly has no references, and declares // System.Object, assume it is the COR library. if ((corLibrary == null) && (reader.AssemblyReferences.Count == 0) && reader.DeclaresTheObjectClass()) { corLibrary = identity; } else if ((intrinsicsAssembly == null) && reader.DeclaresType((r, t) => r.IsPublicNonInterfaceType(t, ExpressionCompilerConstants.IntrinsicAssemblyNamespace, ExpressionCompilerConstants.IntrinsicAssemblyTypeName))) { intrinsicsAssembly = identity; } } var reference = MakeAssemblyMetadata(metadata, modulesByName); referencesBuilder.Add(reference); } if (identitiesBuilder != null) { // Remove assemblies not directly referenced by the target module. var module = metadataBuilder.FirstOrDefault(m => m.MetadataReader.GetModuleVersionIdOrThrow() == moduleVersionId); Debug.Assert(module != null); if (module != null) { var referencedModules = ArrayBuilder <AssemblyIdentity> .GetInstance(); referencedModules.Add(module.MetadataReader.ReadAssemblyIdentityOrThrow()); referencedModules.AddRange(module.MetadataReader.GetReferencedAssembliesOrThrow()); // Ensure COR library is included, otherwise any compilation will fail. // (Note, an equivalent assembly may have already been included from // GetReferencedAssembliesOrThrow above but RemoveUnreferencedModules // allows duplicates.) Debug.Assert(corLibrary != null); if (corLibrary != null) { referencedModules.Add(corLibrary); } // Ensure Debugger intrinsic methods assembly is included. if (intrinsicsAssembly != null) { referencedModules.Add(intrinsicsAssembly); } RemoveUnreferencedModules(referencesBuilder, identitiesBuilder, identityComparer, referencedModules); referencedModules.Free(); } identitiesBuilder.Free(); } metadataBuilder.Free(); // Any runtime winmd modules were separated out initially. Now add // those to a placeholder for the missing compile time module since // each of the runtime winmds refer to the compile time module. if (runtimeWinMdBuilder.Any()) { referencesBuilder.Add(MakeCompileTimeWinMdAssemblyMetadata(runtimeWinMdBuilder)); } runtimeWinMdBuilder.Free(); return(referencesBuilder.ToImmutableAndFree()); }
public unsafe static void DoMyDynamicCompile() { SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText( "using System.Collections.Generic; " + "using Microsoft.AspNet.Mvc; " + "using DynamicApi.Web.Models; " + "using DynamicApi.Web.Repositories; " + "namespace DynamicApi.Web.Controllers {" + "[Route(\"api /[controller]\")] " + "public class ValuesController : Controller<Values> { public ValuesController(IRepository<Values> repository) : base(repository) { }}}"); string assemblyName = Path.GetRandomFileName(); byte * b; int length; MetadataReference reference = null; var assembly = typeof(Controller <>).GetTypeInfo().Assembly; //let's grab the Controller in-memory assembly if (assembly.TryGetRawMetadata(out b, out length)) { var moduleMetadata = ModuleMetadata.CreateFromMetadata((IntPtr)b, length); var assemblyMetadata = AssemblyMetadata.Create(moduleMetadata); reference = assemblyMetadata.GetReference(); } MetadataReference[] references = new MetadataReference[] { MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location), MetadataReference.CreateFromFile(typeof(Attribute).GetTypeInfo().Assembly.Location), MetadataReference.CreateFromFile(typeof(Controller).GetTypeInfo().Assembly.Location), MetadataReference.CreateFromFile(typeof(RouteAttribute).GetTypeInfo().Assembly.Location), reference }; var compilation = CSharpCompilation.Create( assemblyName, syntaxTrees: new[] { syntaxTree }, references: references, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); using (var ms = new MemoryStream()) { EmitResult result = compilation.Emit(ms); if (!result.Success) { IEnumerable <Diagnostic> failures = result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error); foreach (Diagnostic diagnostic in failures) { Console.Error.WriteLine("{0}: {1}", diagnostic.Id, diagnostic.GetMessage()); } } else { ms.Seek(0, SeekOrigin.Begin); Assembly.Load(new AssemblyName(assemblyName)); //var myAssembly = Assembly.Load(ms.ToArray()); } } }
private static CSharpCompilation GenerateCode(string assemblyOrModuleName, string code, string[] assemblyRefs = null) { var options = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9); _logger.Info("Code Syntax Parse..."); SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(code, options); _logger.Info("Code Syntax Parse = OK"); if (assemblyRefs != null) { foreach (var assemblyName in assemblyRefs) { var dllname = assemblyName; _logger.Info($"Loading: {dllname}"); if (dllname.Contains("%ProgramFiles(x86)%")) { dllname = assemblyName.Replace("%ProgramFiles(x86)%", Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)); } if (dllname.Contains("%ProgramFiles%")) { dllname = assemblyName.Replace("%ProgramFiles%", Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)); } Assembly.LoadFrom(dllname).GetReferencedAssemblies(); } } var domainAssemblys = AppDomain.CurrentDomain.GetAssemblies(); var metadataReferenceList = new List <MetadataReference>(); foreach (var assembl in domainAssemblys) { _logger.Info($"Loading: {assembl.GetName()}"); //if (!assembl.Location.IsNull()) // _logger.Info($"Dll Location: {assembl.Location}"); //if (assembl.Location.IsNull()) // continue; unsafe { assembl.TryGetRawMetadata(out byte *blob, out int length); var moduleMetadata = ModuleMetadata.CreateFromMetadata((IntPtr)blob, length); var assemblyMetadata = AssemblyMetadata.Create(moduleMetadata); // Not work in Net 5.0 Self-Contained Single File, Cause 'Path' Exception //var assemblyMetadata = AssemblyMetadata.CreateFromFile(assembl.Location); var metadataReference = assemblyMetadata.GetReference(); metadataReferenceList.Add(metadataReference); } } unsafe { // Add extra refs typeof(Process).Assembly.TryGetRawMetadata(out byte *blob, out int length); typeof(FileSystemWatcher).Assembly.TryGetRawMetadata(out byte *blob2, out int length2); typeof(System.Drawing.Bitmap).Assembly.TryGetRawMetadata(out byte *blob3, out int length3); typeof(System.Reactive.Observer).Assembly.TryGetRawMetadata(out byte *blob4, out int length4); typeof(System.ComponentModel.Component).Assembly.TryGetRawMetadata(out byte *blob5, out int length5); typeof(System.Linq.Expressions.Expression).Assembly.TryGetRawMetadata(out byte *blob6, out int length6); typeof(System.Configuration.ConfigurationManager).Assembly.TryGetRawMetadata(out byte *blob7, out int length7); metadataReferenceList.Add(AssemblyMetadata.Create(ModuleMetadata.CreateFromMetadata((IntPtr)blob, length)).GetReference()); metadataReferenceList.Add(AssemblyMetadata.Create(ModuleMetadata.CreateFromMetadata((IntPtr)blob2, length2)).GetReference()); metadataReferenceList.Add(AssemblyMetadata.Create(ModuleMetadata.CreateFromMetadata((IntPtr)blob3, length3)).GetReference()); metadataReferenceList.Add(AssemblyMetadata.Create(ModuleMetadata.CreateFromMetadata((IntPtr)blob4, length4)).GetReference()); metadataReferenceList.Add(AssemblyMetadata.Create(ModuleMetadata.CreateFromMetadata((IntPtr)blob5, length5)).GetReference()); metadataReferenceList.Add(AssemblyMetadata.Create(ModuleMetadata.CreateFromMetadata((IntPtr)blob6, length6)).GetReference()); metadataReferenceList.Add(AssemblyMetadata.Create(ModuleMetadata.CreateFromMetadata((IntPtr)blob7, length7)).GetReference()); } // create and return the compilation CSharpCompilation compilation = CSharpCompilation.Create ( assemblyOrModuleName, new[] { syntaxTree }, options: new CSharpCompilationOptions(OutputKind.ConsoleApplication, optimizationLevel: OptimizationLevel.Release, assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default), references: metadataReferenceList ); return(compilation); }