#region ========================================================================= USING ===================================================================================== using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; #endregion namespace Nemera.Presentation.Api.IntegrationTests.Common.Setup; /// /// Reads an embedded resource from an assembly file without loading the assembly into the current process. /// /// /// The published bundled plugin manifest verification inspects publish folders of other architectures, where loading the assembly would fail. /// [ExcludeFromCodeCoverage] public static class PublishedAssemblyResourceReader { /// /// Reads an embedded resource from an assembly file without loading the assembly into the current process. /// /// The absolute path of the assembly file. /// The name of the embedded resource. /// The raw bytes of the embedded resource. public static byte[] ReadEmbeddedResource(string assemblyPath, string resourceName) { using (FileStream assemblyStream = File.OpenRead(assemblyPath)) { using (PEReader peReader = new(assemblyStream)) { // A publish folder without managed metadata means the wrong artifact was passed, so fail instead of reporting a missing resource. if (!peReader.HasMetadata) throw new InvalidOperationException($"The assembly '{assemblyPath}' does not contain managed metadata."); MetadataReader metadataReader = peReader.GetMetadataReader(); foreach (ManifestResourceHandle resourceHandle in metadataReader.ManifestResources) { ManifestResource resource = metadataReader.GetManifestResource(resourceHandle); // A resource with a non-null implementation is linked from another file, so its bytes are not stored in this resources directory. if (!metadataReader.StringComparer.Equals(resource.Name, resourceName) || !resource.Implementation.IsNil) continue; // The embedded payloads live in the PE resources directory, and every resource offset is relative to the start of that directory. PEMemoryBlock resourceDirectory = peReader.GetSectionData(peReader.PEHeaders.CorHeader!.ResourcesDirectory.RelativeVirtualAddress); BlobReader resourceReader = resourceDirectory.GetReader((int)resource.Offset, resourceDirectory.Length - (int)resource.Offset); // Every embedded resource is prefixed with a four-byte length before its payload. int resourceLength = resourceReader.ReadInt32(); return resourceReader.ReadBytes(resourceLength); } } } // Returning empty bytes would let the manifest verification compare against nothing, so a missing resource is treated as a broken artifact. throw new InvalidOperationException($"The embedded resource '{resourceName}' is missing from '{assemblyPath}'."); } }