Esempio n. 1
0
        static void Main(string[] args)
        {
            if (args.Length == 0 || new[] {"/?", "-?", "-h", "--help"}.Any(x => string.Equals(args[0], x, StringComparison.OrdinalIgnoreCase)))
            {
                PrintUsage();
                return;
            }

            foreach (var fileName in args)
            {
                Console.WriteLine(fileName);
                Console.WriteLine(new string('*', 80));

                try
                {
                    using (var stream = File.OpenRead(fileName))
                    using (var peFile = new PEReader(stream))
                    {
                        var metadataReader = peFile.GetMetadataReader();
                        var visualizer = new MetadataVisualizer(metadataReader, Console.Out);
                        visualizer.Visualize();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);                    
                }
            }
        }
Esempio n. 2
0
        public PE(string fileName)
        {
            FileName = Path.GetFullPath(fileName);
            Uri = new Uri(FileName);
            IsPEFile = false;
            try
            {
                _fs = File.OpenRead(FileName);

                byte byteRead = (byte)_fs.ReadByte();
                if (byteRead != 'M') { return; }

                byteRead = (byte)_fs.ReadByte();
                if (byteRead != 'Z') { return; }
                _fs.Seek(0, SeekOrigin.Begin);

                _peReader = new PEReader(_fs);
                PEHeaders = _peReader.PEHeaders;
                IsPEFile = true;
            }
            catch (IOException e) { LoadException = e; }
            catch (BadImageFormatException e) { LoadException = e; }
            catch (UnauthorizedAccessException e) { LoadException = e; }

            if (IsPEFile)
            {
                m_pImage = new SafePointer(_peReader.GetEntireImage().GetContent().ToBuilder().ToArray());

                if (IsManaged)
                {
                    _metadataReader = _peReader.GetMetadataReader();
                }
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Returns true if the PE file meets all of the pre-conditions to be Open Source Signed.
        /// Returns false and logs msbuild errors otherwise.
        /// </summary>
        private static bool Validate(PEReader peReader)
        {
            if (!peReader.HasMetadata)
            {
                Console.Error.WriteLine("PE file is not a managed module.");
                return false;
            }

            var mdReader = peReader.GetMetadataReader();
            if (!mdReader.IsAssembly)
            {
                Console.Error.WriteLine("PE file is not an assembly.");
                return false;
            }

            CorHeader header = peReader.PEHeaders.CorHeader;
            if ((header.Flags & CorFlags.StrongNameSigned) == CorFlags.StrongNameSigned)
            {
                Console.Error.WriteLine("PE file is already strong-name signed.");
                return false;
            }

            if ((header.StrongNameSignatureDirectory.Size <= 0) || mdReader.GetAssemblyDefinition().PublicKey.IsNil)
            {
                Console.Error.WriteLine("PE file is not a delay-signed assembly.");
                return false;
            }

            return true;
        }
 public InspectableAssembly(string filename, ParseContext context)
 {
     Stream = File.OpenRead(filename);
     Pe = new PEReader(Stream);
     Reader = Pe.GetMetadataReader();
     Context = context;
 }
Esempio n. 5
0
        public static AssemblyIdentity TryGetAssemblyIdentity(string filePath)
        {
            try
            {
                using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete))
                using (var peReader = new PEReader(stream))
                {
                    var metadataReader = peReader.GetMetadataReader();

                    AssemblyDefinition assemblyDefinition = metadataReader.GetAssemblyDefinition();

                    string name = metadataReader.GetString(assemblyDefinition.Name);
                    Version version = assemblyDefinition.Version;

                    StringHandle cultureHandle = assemblyDefinition.Culture;
                    string cultureName = (!cultureHandle.IsNil) ? metadataReader.GetString(cultureHandle) : null;
                    AssemblyFlags flags = assemblyDefinition.Flags;

                    bool hasPublicKey = (flags & AssemblyFlags.PublicKey) != 0;
                    BlobHandle publicKeyHandle = assemblyDefinition.PublicKey;
                    ImmutableArray<byte> publicKeyOrToken = !publicKeyHandle.IsNil
                        ? metadataReader.GetBlobBytes(publicKeyHandle).AsImmutableOrNull()
                        : default(ImmutableArray<byte>);
                    return new AssemblyIdentity(name, version, cultureName, publicKeyOrToken, hasPublicKey);
                }
            }
            catch { }

            return null;
        }
Esempio n. 6
0
 public void OpenNativeImage()
 {
     using (var reader = new PEReader(File.OpenRead(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "kernel32.dll"))))
     {
         Assert.False(reader.HasMetadata);
         Assert.True(reader.PEHeaders.IsDll);
         Assert.False(reader.PEHeaders.IsExe);
         Assert.Throws<InvalidOperationException>(() => reader.GetMetadataReader());
     }
 }
        public override bool Execute()
        {
            if (Assemblies == null || Assemblies.Length == 0)
                return true;

            List<ITaskItem> references = new List<ITaskItem>();
            List<ITaskItem> nativeLibs = new List<ITaskItem>();

            foreach (var assemblyItem in Assemblies)
            {
                try
                {
                    if (!File.Exists(assemblyItem.ItemSpec))
                    {
                        Log.LogError($"File {assemblyItem.ItemSpec} does not exist, ensure you have built libraries before building the package.");
                        continue;
                    }

                    using (PEReader peReader = new PEReader(new FileStream(assemblyItem.ItemSpec, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.Read)))
                    {
                        MetadataReader reader = peReader.GetMetadataReader();
                        foreach (var handle in reader.AssemblyReferences)
                        {
                            AssemblyReference reference = reader.GetAssemblyReference(handle);
                            TaskItem referenceItem = new TaskItem(reader.GetString(reference.Name));
                            assemblyItem.CopyMetadataTo(referenceItem);
                            referenceItem.SetMetadata("Version", reference.Version.ToString());
                            referenceItem.SetMetadata("AssemblyVersion", reference.Version.ToString());
                            references.Add(referenceItem);
                        }

                        for (int i = 1, count = reader.GetTableRowCount(TableIndex.ModuleRef); i <= count; i++)
                        {
                            var moduleRef = reader.GetModuleReference(MetadataTokens.ModuleReferenceHandle(i));
                            var moduleName = reader.GetString(moduleRef.Name);

                            TaskItem nativeLib = new TaskItem(moduleName);
                            assemblyItem.CopyMetadataTo(nativeLib);
                            nativeLibs.Add(nativeLib);
                        }
                    }
                }
                catch (InvalidOperationException)
                {
                    // Ignore invalid assemblies
                }
            }

            ReferencedAssemblies = references.ToArray();
            ReferencedNativeLibraries = nativeLibs.ToArray();

            return true;
        }
 public static ISymUnmanagedReader CreateReader(Stream pdbStream, Stream peStreamOpt = null)
 {
     if (peStreamOpt != null)
     {
         var peReader = new PEReader(peStreamOpt);
         return CreateReader(pdbStream, peReader.GetMetadataReader(), peReader);
     }
     else
     {
         return CreateReader(pdbStream, null, null);
     }
 }
Esempio n. 9
0
        public void IL_LazyLoad()
        {
            var peStream = new MemoryStream(TestResources.Misc.Members);
            using (var reader = new PEReader(peStream, PEStreamOptions.LeaveOpen))
            {
                var md = reader.GetMetadataReader();
                var il = reader.GetMethodBody(md.GetMethodDefinition(MetadataTokens.MethodDefinitionHandle(1)).RelativeVirtualAddress);

                Assert.Equal(new byte[] { 0, 42 }, il.GetILBytes());
                Assert.Equal(8, il.MaxStack);
            }
        }
        public static AssemblyInfo GetAssemblyInfo(string path)
        {
            using (var peReader = new PEReader(new FileStream(path, FileMode.Open, FileAccess.Read)))
            {
                var contractReader = peReader.GetMetadataReader();
                var assembly = contractReader.GetAssemblyDefinition();

                var name = contractReader.GetString(assembly.Name);
                var version = assembly.Version;
                var references = GetAssemblyReferences(contractReader);

                return new AssemblyInfo(path, name, version, references);
            }
        }
        public override bool Execute()
        {
            Log.LogMessage(MessageImportance.High, "About to inspect {0} test assemblies.", TestBinaries.Length);
            var perfTests = new List<ITaskItem>();

            foreach (var testBinary in TestBinaries)
            {
                Log.LogMessage(MessageImportance.Low, "Inspecting assembly {0}.", testBinary.ItemSpec);

                using (var stream = File.OpenRead(testBinary.ItemSpec))
                {
                    using (var peFile = new PEReader(stream))
                    {
                        if(!peFile.HasMetadata){
                            continue;
                        }
                        var mdReader = peFile.GetMetadataReader();

                        foreach (var asmRefHandle in mdReader.AssemblyReferences)
                        {
                            var asmRef = mdReader.GetAssemblyReference(asmRefHandle);
                            var asmRefName = mdReader.GetString(asmRef.Name);

                            // if an assembly contains a reference to xunit.performance.core
                            // then it contains at least one performance test.

                            if (string.Compare(asmRefName, "xunit.performance.core", StringComparison.OrdinalIgnoreCase) == 0)
                            {
                                var fileName = (GetFullPaths) ? Path.GetFullPath(testBinary.ItemSpec) : Path.GetFileNameWithoutExtension(testBinary.ItemSpec);
                                perfTests.Add(new TaskItem(fileName));
                                Log.LogMessage("+ Assembly {0} contains one or more performance tests.", fileName);
                                break;
                            }
                        }
                    }
                }
            }

            if (perfTests.Count > 0)
            {
                PerfTestAssemblies = perfTests.ToArray();
                Log.LogMessage(MessageImportance.High, "Found {0} assemblies containing performance tests.", perfTests.Count);
            }
            else
            {
                Log.LogWarning("Didn't find any performance tests.");
            }

            return true;
        }
Esempio n. 12
0
        public void BasicValidation()
        {
            using (var peStream = new MemoryStream())
            {
                var ilBuilder = new BlobBuilder();
                var metadataBuilder = new MetadataBuilder();
                var entryPoint = BasicValidationEmit(metadataBuilder, ilBuilder);
                WritePEImage(peStream, metadataBuilder, ilBuilder, entryPoint);

                peStream.Position = 0;
                var r = new PEReader(peStream);
                var h = r.PEHeaders;
                var mdReader = r.GetMetadataReader();
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Returns true if the PE file meets all of the pre-conditions to be Open Source Signed.
        /// Returns false and logs msbuild errors otherwise.
        /// </summary>
        private static bool IsPublicSigned(PEReader peReader)
        {
            if (!peReader.HasMetadata)
            {
                return false;
            }

            var mdReader = peReader.GetMetadataReader();
            if (!mdReader.IsAssembly)
            {
                return false;
            }

            CorHeader header = peReader.PEHeaders.CorHeader;
            return (header.Flags & CorFlags.StrongNameSigned) == CorFlags.StrongNameSigned;
        }
Esempio n. 14
0
        /// <remarks>
        /// Based on https://gist.github.com/nguerrera/72444715c7ea0b40addb
        /// </remarks>
        public static byte[] GetILBytes(this MethodInfo methodInfo)
        {
#if NET45
            return methodInfo.GetMethodBody().GetILAsByteArray();
#else
            var metadataToken = methodInfo.GetMetadataToken();
            
            using (var stream = File.OpenRead(methodInfo.DeclaringType.GetTypeInfo().Assembly.Location))
            using (var peReader = new PEReader(stream))
            {
                var metadataReader = peReader.GetMetadataReader();
                var methodHandle = MetadataTokens.MethodDefinitionHandle(metadataToken);
                var methodDefinition = metadataReader.GetMethodDefinition(methodHandle);
                var methodBody = peReader.GetMethodBody(methodDefinition.RelativeVirtualAddress);
                return methodBody.GetILBytes();
            }
#endif
        }
Esempio n. 15
0
        public static string GetAssemblyAttributeValue(string assemblyPath, string attributeName)
        {
            if (!File.Exists(assemblyPath))
            {
                return null;
            }

            using (var stream = File.OpenRead(assemblyPath))
            using (var peReader = new PEReader(stream))
            {
                if (!peReader.HasMetadata)
                {
                    return null;
                }

                var mdReader = peReader.GetMetadataReader();
                var attrs = mdReader.GetAssemblyDefinition().GetCustomAttributes()
                    .Select(ah => mdReader.GetCustomAttribute(ah));

                foreach (var attr in attrs)
                {
                    var ctorHandle = attr.Constructor;
                    if (ctorHandle.Kind != HandleKind.MemberReference)
                    {
                        continue;
                    }

                    var container = mdReader.GetMemberReference((MemberReferenceHandle)ctorHandle).Parent;
                    var name = mdReader.GetTypeReference((TypeReferenceHandle)container).Name;
                    if (!string.Equals(mdReader.GetString(name), attributeName))
                    {
                        continue;
                    }

                    var arguments = GetFixedStringArguments(mdReader, attr);
                    if (arguments.Count == 1)
                    {
                        return arguments[0];
                    }
                }
            }

            return null;
        }
Esempio n. 16
0
        /// <summary>
        /// Given a path to an assembly, identifies files in the same directory
        /// that could satisfy the assembly's dependencies. May throw.
        /// </summary>
        /// <remarks>
        /// Dependencies are identified by simply checking the name of an assembly
        /// reference against a file name; if they match the file is considered a
        /// dependency. Other factors, such as version, culture, public key, etc., 
        /// are not considered, and so the returned collection may include items that
        /// cannot in fact satisfy the original assembly's dependencies.
        /// </remarks>
        /// <exception cref="IOException">If the file at <paramref name="filePath"/> does not exist or cannot be accessed.</exception>
        /// <exception cref="BadImageFormatException">If the file is not an assembly or is somehow corrupted.</exception>
        public static ImmutableArray<string> FindAssemblySet(string filePath)
        {
            Debug.Assert(filePath != null);
            Debug.Assert(PathUtilities.IsAbsolute(filePath));

            Queue<string> workList = new Queue<string>();
            HashSet<string> assemblySet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

            workList.Enqueue(filePath);

            while (workList.Count > 0)
            {
                string assemblyPath = workList.Dequeue();

                if (!assemblySet.Add(assemblyPath))
                {
                    continue;
                }

                var directory = Path.GetDirectoryName(assemblyPath);

                using (var reader = new PEReader(FileUtilities.OpenRead(assemblyPath)))
                {
                    var metadataReader = reader.GetMetadataReader();
                    var assemblyReferenceHandles = metadataReader.AssemblyReferences;

                    foreach (var handle in assemblyReferenceHandles)
                    {
                        var reference = metadataReader.GetAssemblyReference(handle);
                        var referenceName = metadataReader.GetString(reference.Name);

                        string referencePath = Path.Combine(directory, referenceName + ".dll");

                        if (!assemblySet.Contains(referencePath) &&
                            File.Exists(referencePath))
                        {
                            workList.Enqueue(referencePath);
                        }
                    }
                }
            }

            return ImmutableArray.CreateRange(assemblySet);
        }
Esempio n. 17
0
        public static IList<IMetadataEmbeddedReference> GetEmbeddedReferences(this PEReader reader)
        {
            var items = new List<IMetadataEmbeddedReference>();

            var mdReader = reader.GetMetadataReader();
            foreach (var resourceHandle in mdReader.ManifestResources)
            {
                var resource = mdReader.GetManifestResource(resourceHandle);
                var resourceName = mdReader.GetString(resource.Name);

                if (resourceName.StartsWith("AssemblyNeutral/") &&
                    resourceName.EndsWith(".dll"))
                {
                    var buffer = GetEmbeddedResourceContents(reader, resource);

                    using (var nestedPeReader = new PEReader(new MemoryStream(buffer)))
                    {
                        try
                        {
                            // Skip dlls that aren't managed
                            if (!nestedPeReader.HasMetadata)
                            {
                                continue;
                            }
                        }
                        catch (BadImageFormatException)
                        {
                            continue;
                        }

                        var nestedMdReader = nestedPeReader.GetMetadataReader();
                        var assemblyDef = nestedMdReader.GetAssemblyDefinition();

                        var assemblyName = nestedMdReader.GetString(assemblyDef.Name);

                        items.Add(new EmbeddedMetadataReference(assemblyName, buffer));
                    }
                }
            }

            return items;
        }
Esempio n. 18
0
        private static IList<string> GetReferences(byte[] buffer)
        {
            var references = new List<string>();

            using (var stream = new MemoryStream(buffer))
            using (var peReader = new PEReader(stream))
            {
                var reader = peReader.GetMetadataReader();

                foreach (var a in reader.AssemblyReferences)
                {
                    var reference = reader.GetAssemblyReference(a);
                    var referenceName = reader.GetString(reference.Name);

                    references.Add(referenceName);
                }

                return references;
            }
        }
Esempio n. 19
0
        public static Version GetAssemblyVersion(string assemblyPath)
        {
            Version result = null;
            try
            {
                using (PEReader peReader = new PEReader(new FileStream(assemblyPath, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.Read)))
                {
                    if (peReader.HasMetadata)
                    {
                        MetadataReader reader = peReader.GetMetadataReader();
                        result = reader.GetAssemblyDefinition().Version;
                    }
                }
            }
            catch (BadImageFormatException)
            {
                // not a PE
            }

            return result;
        }
Esempio n. 20
0
        // -----------------------------
        // ---- PAL layer ends here ----
        // -----------------------------

        /// <summary>Attempt to load our fields from the metadata of the file, if it's a managed assembly.</summary>
        /// <returns>true if the file is a managed assembly; otherwise, false.</returns>
        private bool TryLoadManagedAssemblyMetadata()
        {
            try
            {
                // Try to load the file using the managed metadata reader
                using (FileStream assemblyStream = File.OpenRead(_fileName))
                using (PEReader peReader = new PEReader(assemblyStream))
                {
                    if (peReader.HasMetadata)
                    {
                        MetadataReader metadataReader = peReader.GetMetadataReader();
                        if (metadataReader.IsAssembly)
                        {
                            LoadManagedAssemblyMetadata(metadataReader);
                            return true;
                        }
                    }
                }
            }
            catch (BadImageFormatException) { }
            return false;
        }
        // -----------------------------
        // ---- PAL layer ends here ----
        // -----------------------------

        /// <summary>Attempt to load our fields from the metadata of the file, if it's a managed assembly.</summary>
        /// <returns>true if the file is a managed assembly; otherwise, false.</returns>
        private bool TryLoadManagedAssemblyMetadata()
        {
            try
            {
                // Try to load the file using the managed metadata reader
                using (FileStream assemblyStream = new FileStream(_fileName, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 0x1000, useAsync: false))
                using (PEReader peReader = new PEReader(assemblyStream))
                {
                    if (peReader.HasMetadata)
                    {
                        MetadataReader metadataReader = peReader.GetMetadataReader();
                        if (metadataReader.IsAssembly)
                        {
                            LoadManagedAssemblyMetadata(metadataReader);
                            return true;
                        }
                    }
                }
            }
            catch (BadImageFormatException) { }
            return false;
        }
Esempio n. 22
0
        public static Version GetAssemblyVersion(Stream assemblyStream)
        {
            Version result = null;
            try
            {
                using (PEReader peReader = new PEReader(assemblyStream, PEStreamOptions.LeaveOpen))
                {
                    if (peReader.HasMetadata)
                    {
                        MetadataReader reader = peReader.GetMetadataReader();
                        if (reader.IsAssembly)
                        {
                            result = reader.GetAssemblyDefinition().Version;
                        }
                    }
                }
            }
            catch (BadImageFormatException)
            {
                // not a PE
            }

            return result;
        }
Esempio n. 23
0
        internal static bool IsAssemblyServiceable(string assemblyPath)
        {
            if (!File.Exists(assemblyPath))
            {
                return false;
            }

            using (var stream = File.OpenRead(assemblyPath))
            using (var peReader = new PEReader(stream))
            {
                if (!peReader.HasMetadata)
                {
                    return false;
                }

                var mdReader = peReader.GetMetadataReader();
                var attrs = mdReader.GetAssemblyDefinition().GetCustomAttributes()
                    .Select(ah => mdReader.GetCustomAttribute(ah));

                foreach (var attr in attrs)
                {
                    var ctorHandle = attr.Constructor;
                    if (ctorHandle.Kind != HandleKind.MemberReference)
                    {
                        continue;
                    }

                    var container = mdReader.GetMemberReference((MemberReferenceHandle)ctorHandle).Parent;
                    var name = mdReader.GetTypeReference((TypeReferenceHandle)container).Name;
                    if (!string.Equals(mdReader.GetString(name), "AssemblyMetadataAttribute"))
                    {
                        continue;
                    }

                    var arguments = GetFixedStringArguments(mdReader, attr);
                    if (arguments.Count == 2 &&
                        string.Equals(arguments[0], "Serviceable", StringComparison.OrdinalIgnoreCase) &&
                        string.Equals(arguments[1], "True", StringComparison.OrdinalIgnoreCase))
                    {
                        return true;
                    }
                }
            }

            return false;
        }
 /// <summary>
 /// Given a path get the CLR runtime version of the file
 /// </summary>
 /// <param name="path">path to the file</param>
 /// <returns>The CLR runtime version or empty if the path does not exist.</returns>
 private static string TryGetRuntimeVersion(string path)
 {
     try
     {
         using (FileStream stream = File.OpenRead(path))
         using (PEReader peReader = new PEReader(stream))
         {
             return peReader.GetMetadataReader().MetadataVersion;
         }
     }
     catch (Exception)
     {
         return string.Empty;
     }
 }
Esempio n. 25
0
        public void CustomDebugEntryPoint_EXE()
        {
            var source = @"class M { static void Main() { } } class C { static void F<S>() { } }";

            var c = CreateCompilationWithMscorlib(source, options: TestOptions.DebugExe);
            var f = c.GetMember<MethodSymbol>("C.F");

            c.VerifyPdb(@"
<symbols>
  <entryPoint declaringType=""C"" methodName=""F"" />
  <methods/>
</symbols>", debugEntryPoint: f, options: PdbToXmlOptions.ExcludeScopes | PdbToXmlOptions.ExcludeSequencePoints | PdbToXmlOptions.ExcludeCustomDebugInformation);

            var peReader = new PEReader(c.EmitToArray(debugEntryPoint: f));
            int peEntryPointToken = peReader.PEHeaders.CorHeader.EntryPointTokenOrRelativeVirtualAddress;

            var mdReader = peReader.GetMetadataReader();
            var methodDef = mdReader.GetMethodDefinition((MethodDefinitionHandle)MetadataTokens.Handle(peEntryPointToken));
            Assert.Equal("Main", mdReader.GetString(methodDef.Name));
        }
Esempio n. 26
0
        public void CanReadFromSameMemoryMappedPEReaderInParallel()
        {
            // See http://roslyn.codeplex.com/workitem/299
            //
            // This simulates the use case where something is holding on
            // to a PEReader and prepared to produce a MetadataReader
            // on demand for callers on different threads.
            //
            using (var stream = GetTemporaryAssemblyLargeEnoughToBeMemoryMapped())
            {
                Assert.InRange(stream.Length, StreamMemoryBlockProvider.MemoryMapThreshold + 1, int.MaxValue);

                for (int i = 0; i < 1000; i++)
                {
                    stream.Position = 0;

                    using (var peReader = new PEReader(stream, PEStreamOptions.LeaveOpen))
                    {
                        Parallel.For(0, 4, _ => { peReader.GetMetadataReader(); });
                    }
                }
            }
        }
Esempio n. 27
0
        public void Metadata_LazyLoad()
        {
            var peStream = new MemoryStream(TestResources.Misc.Members);
            using (var reader = new PEReader(peStream, PEStreamOptions.LeaveOpen))
            {
                var md = reader.GetMetadataReader();
                var method = md.GetMethodDefinition(MetadataTokens.MethodDefinitionHandle(1));

                Assert.Equal("MC1", md.GetString(method.Name));
            }
        }
Esempio n. 28
0
 private static List<TypeInfo> GetTypeInfoList(string assemblyPath)
 {
     using (var stream = File.OpenRead(assemblyPath))
     using (var peReader = new PEReader(stream))
     {
         var metadataReader = peReader.GetMetadataReader();
         return GetTypeInfoList(metadataReader);
     }
 }
Esempio n. 29
0
        public void Metadata_EagerLoad()
        {
            var peStream = new MemoryStream(TestResources.Misc.Members);
            using (var reader = new PEReader(peStream, PEStreamOptions.LeaveOpen | PEStreamOptions.PrefetchMetadata))
            {
                var md = reader.GetMetadataReader();
                var method = md.GetMethodDefinition(MetadataTokens.MethodDefinitionHandle(1));
                Assert.Equal("MC1", md.GetString(method.Name));

                Assert.Throws<InvalidOperationException>(() => reader.GetEntireImage());
                Assert.Throws<InvalidOperationException>(() => reader.GetMethodBody(method.RelativeVirtualAddress));
            }
        }
Esempio n. 30
0
            private AssemblyName GetAssemblyName(string fullPath)
            {
                using (var stream = PortableShim.File.OpenRead(fullPath))
                {
                    using (var peReader = new PEReader(stream))
                    {
                        var reader = peReader.GetMetadataReader();
                        var assemblyDef = reader.GetAssemblyDefinition();

                        var name = reader.GetString(assemblyDef.Name);

                        var cultureName = assemblyDef.Culture.IsNil
                            ? null
                            : reader.GetString(assemblyDef.Culture);

                        var publicKeyOrToken = reader.GetBlobContent(assemblyDef.PublicKey);
                        var hasPublicKey = !publicKeyOrToken.IsEmpty;

                        if (publicKeyOrToken.IsEmpty)
                        {
                            publicKeyOrToken = default(ImmutableArray<byte>);
                        }

                        var identity = new AssemblyIdentity(
                            name: name,
                            version: assemblyDef.Version,
                            cultureName: cultureName,
                            publicKeyOrToken: publicKeyOrToken,
                            hasPublicKey: hasPublicKey,
                            isRetargetable: (assemblyDef.Flags & AssemblyFlags.Retargetable) != 0,
                            contentType: (AssemblyContentType)((int)(assemblyDef.Flags & AssemblyFlags.ContentTypeMask) >> 9));

                        return new AssemblyName(identity.GetDisplayName());
                    }
                }
            }