示例#1
0
        /// <summary>
        /// Open a given reference assembly (relative to this ECMA metadata file).
        /// </summary>
        /// <param name="refAsmIndex">Reference assembly index</param>
        /// <returns>EcmaMetadataReader instance representing the reference assembly</returns>
        public EcmaMetadataReader OpenReferenceAssembly(int refAsmIndex)
        {
            if (refAsmIndex == 0)
            {
                return(this);
            }

            int    assemblyRefCount = MetadataReader.GetTableRowCount(TableIndex.AssemblyRef);
            string name;

            if (refAsmIndex <= assemblyRefCount)
            {
                AssemblyReference asmRef = MetadataReader.GetAssemblyReference(MetadataTokens.AssemblyReferenceHandle(refAsmIndex));
                name = MetadataReader.GetString(asmRef.Name);
            }
            else
            {
                name = ManifestReferenceAssemblies[refAsmIndex - assemblyRefCount - 2];
            }

            EcmaMetadataReader ecmaReader;

            if (!_assemblyCache.TryGetValue(name, out ecmaReader))
            {
                string assemblyPath = _assemblyResolver.FindAssembly(name, Filename);
                if (assemblyPath == null)
                {
                    throw new Exception($"Missing reference assembly: {name}");
                }
                ecmaReader = new EcmaMetadataReader(_assemblyResolver, assemblyPath, ManifestReferenceAssemblies);
                _assemblyCache.Add(name, ecmaReader);
            }
            return(ecmaReader);
        }
示例#2
0
        public void HasCustomAttribute()
        {
            Assert.Equal(0, CodedIndex.HasCustomAttribute(default(MethodDefinitionHandle)));
            Assert.Equal((0xffffff << 5) | 21, CodedIndex.HasCustomAttribute(MetadataTokens.MethodSpecificationHandle(0xffffff)));

            Assert.Equal(0x20 | 0, CodedIndex.HasCustomAttribute(MetadataTokens.MethodDefinitionHandle(1)));
            Assert.Equal(0x20 | 1, CodedIndex.HasCustomAttribute(MetadataTokens.FieldDefinitionHandle(1)));
            Assert.Equal(0x20 | 2, CodedIndex.HasCustomAttribute(MetadataTokens.TypeReferenceHandle(1)));
            Assert.Equal(0x20 | 3, CodedIndex.HasCustomAttribute(MetadataTokens.TypeDefinitionHandle(1)));
            Assert.Equal(0x20 | 4, CodedIndex.HasCustomAttribute(MetadataTokens.ParameterHandle(1)));
            Assert.Equal(0x20 | 5, CodedIndex.HasCustomAttribute(MetadataTokens.InterfaceImplementationHandle(1)));
            Assert.Equal(0x20 | 6, CodedIndex.HasCustomAttribute(MetadataTokens.MemberReferenceHandle(1)));
            Assert.Equal(0x20 | 7, CodedIndex.HasCustomAttribute(EntityHandle.ModuleDefinition));
            Assert.Equal(0x20 | 8, CodedIndex.HasCustomAttribute(MetadataTokens.DeclarativeSecurityAttributeHandle(1)));
            Assert.Equal(0x20 | 9, CodedIndex.HasCustomAttribute(MetadataTokens.PropertyDefinitionHandle(1)));
            Assert.Equal(0x20 | 10, CodedIndex.HasCustomAttribute(MetadataTokens.EventDefinitionHandle(1)));
            Assert.Equal(0x20 | 11, CodedIndex.HasCustomAttribute(MetadataTokens.StandaloneSignatureHandle(1)));
            Assert.Equal(0x20 | 12, CodedIndex.HasCustomAttribute(MetadataTokens.ModuleReferenceHandle(1)));
            Assert.Equal(0x20 | 13, CodedIndex.HasCustomAttribute(MetadataTokens.TypeSpecificationHandle(1)));
            Assert.Equal(0x20 | 14, CodedIndex.HasCustomAttribute(EntityHandle.AssemblyDefinition));
            Assert.Equal(0x20 | 15, CodedIndex.HasCustomAttribute(MetadataTokens.AssemblyReferenceHandle(1)));
            Assert.Equal(0x20 | 16, CodedIndex.HasCustomAttribute(MetadataTokens.AssemblyFileHandle(1)));
            Assert.Equal(0x20 | 17, CodedIndex.HasCustomAttribute(MetadataTokens.ExportedTypeHandle(1)));
            Assert.Equal(0x20 | 18, CodedIndex.HasCustomAttribute(MetadataTokens.ManifestResourceHandle(1)));
            Assert.Equal(0x20 | 19, CodedIndex.HasCustomAttribute(MetadataTokens.GenericParameterHandle(1)));
            Assert.Equal(0x20 | 20, CodedIndex.HasCustomAttribute(MetadataTokens.GenericParameterConstraintHandle(1)));
            Assert.Equal(0x20 | 21, CodedIndex.HasCustomAttribute(MetadataTokens.MethodSpecificationHandle(1)));
        }
示例#3
0
 protected override AssemblyReferenceHandle GetOrAddAssemblyReferenceHandle(
     IAssemblyReference reference
     )
 {
     return(MetadataTokens.AssemblyReferenceHandle(
                _assemblyRefIndex.GetOrAdd(reference.Identity)
                ));
 }
示例#4
0
        public void Implementation()
        {
            Assert.Equal(0, CodedIndex.Implementation(default(AssemblyFileHandle)));
            Assert.Equal((0xffffff << 2) | 2, CodedIndex.Implementation(MetadataTokens.ExportedTypeHandle(0xffffff)));

            Assert.Equal(0x04 | 0, CodedIndex.Implementation(MetadataTokens.AssemblyFileHandle(1)));
            Assert.Equal(0x04 | 1, CodedIndex.Implementation(MetadataTokens.AssemblyReferenceHandle(1)));
            Assert.Equal(0x04 | 2, CodedIndex.Implementation(MetadataTokens.ExportedTypeHandle(1)));
        }
示例#5
0
        public void ResolutionScope()
        {
            Assert.Equal(0, CodedIndex.ResolutionScope(default(ModuleDefinitionHandle)));
            Assert.Equal((0xffffff << 2) | 3, CodedIndex.ResolutionScope(MetadataTokens.TypeReferenceHandle(0xffffff)));

            Assert.Equal(0x04 | 0, CodedIndex.ResolutionScope(EntityHandle.ModuleDefinition));
            Assert.Equal(0x04 | 1, CodedIndex.ResolutionScope(MetadataTokens.ModuleReferenceHandle(1)));
            Assert.Equal(0x04 | 2, CodedIndex.ResolutionScope(MetadataTokens.AssemblyReferenceHandle(1)));
            Assert.Equal(0x04 | 3, CodedIndex.ResolutionScope(MetadataTokens.TypeReferenceHandle(1)));
        }
示例#6
0
            private static AssemblyReference[] GetAssemblyReferences(MetadataReader reader)
            {
                var count      = reader.GetTableRowCount(TableIndex.AssemblyRef);
                var references = new AssemblyReference[count];

                for (int i = 0; i < count; i++)
                {
                    var reference = reader.GetAssemblyReference(MetadataTokens.AssemblyReferenceHandle(i + 1));
                    references[i] = new AssemblyReference(reader.GetString(reference.Name), reference.Version);
                }

                return(references.ToArray());
            }
示例#7
0
        public AssemblyName[] GetAssemblyReferences()
        {
            var count      = _metaReader.GetTableRowCount(TableIndex.AssemblyRef);
            var references = new AssemblyName[count];

            for (int i = 0; i < count; i++)
            {
                var assemblyRef     = _metaReader.GetAssemblyReference(MetadataTokens.AssemblyReferenceHandle(i + 1));
                var assemblyRefName = _metaReader.GetString(assemblyRef.Name);
                var cultureName     = assemblyRef.Culture.IsNil ? "neutral" : _metaReader.GetString(assemblyRef.Culture);
                var pubKeyTok       = AssemblyHelpers.FormatPublicKeyToken(_metaReader, assemblyRef.PublicKeyOrToken);

                references[i] = new AssemblyName(string.Format("{0}, Version={1}, Culture={2}, PublicKeyToken={3}", assemblyRefName, assemblyRef.Version, cultureName, pubKeyTok));
            }

            return(references);
        }
        public ManifestMetadataTableNode(NodeFactory nodeFactory)
            : base(nodeFactory.Target)
        {
            _assemblyRefToModuleIdMap  = new Dictionary <string, int>();
            _moduleIdToAssemblyNameMap = new Dictionary <int, AssemblyName>();
            _manifestAssemblyMvids     = new List <Guid>();
            _signatureEmitters         = new List <ISignatureEmitter>();
            _nodeFactory  = nodeFactory;
            _nextModuleId = 1;

            if (!_nodeFactory.CompilationModuleGroup.IsCompositeBuildMode)
            {
                MetadataReader mdReader = _nodeFactory.CompilationModuleGroup.CompilationModuleSet.Single().MetadataReader;
                _assemblyRefCount = mdReader.GetTableRowCount(TableIndex.AssemblyRef) + 1;

                if (!_nodeFactory.CompilationModuleGroup.IsInputBubble)
                {
                    for (int assemblyRefIndex = 1; assemblyRefIndex < _assemblyRefCount; assemblyRefIndex++)
                    {
                        AssemblyReferenceHandle assemblyRefHandle = MetadataTokens.AssemblyReferenceHandle(assemblyRefIndex);
                        AssemblyReference       assemblyRef       = mdReader.GetAssemblyReference(assemblyRefHandle);
                        string assemblyName = mdReader.GetString(assemblyRef.Name);
                        _assemblyRefToModuleIdMap[assemblyName] = assemblyRefIndex;
                    }
                }

                // AssemblyRefCount + 1 corresponds to ROWID 0 in the manifest metadata
                _nextModuleId += _assemblyRefCount;
            }

            if (_nodeFactory.CompilationModuleGroup.IsCompositeBuildMode)
            {
                // Fill in entries for all input modules right away to make sure they have parallel indices
                int nextExpectedId = 1;
                foreach (EcmaModule inputModule in _nodeFactory.CompilationModuleGroup.CompilationModuleSet)
                {
                    int acquiredId = ModuleToIndexInternal(inputModule);
                    if (acquiredId != nextExpectedId)
                    {
                        throw new InternalCompilerErrorException($"Manifest metadata consistency error - acquired ID {acquiredId}, expected {nextExpectedId}");
                    }
                    nextExpectedId++;
                }
            }
        }
示例#9
0
        private AssemblyReferenceHandle GetAssemblyAtIndex(int refAsmIndex, out MetadataReader metadataReader)
        {
            Debug.Assert(refAsmIndex != 0);

            int assemblyRefCount = (_composite ? 0 : _assemblyCache[0].GetTableRowCount(TableIndex.AssemblyRef) + 1);
            AssemblyReferenceHandle assemblyReferenceHandle;

            if (refAsmIndex < assemblyRefCount)
            {
                metadataReader          = _assemblyCache[0];
                assemblyReferenceHandle = MetadataTokens.AssemblyReferenceHandle(refAsmIndex);
            }
            else
            {
                metadataReader          = ManifestReader;
                assemblyReferenceHandle = ManifestReferences[refAsmIndex - assemblyRefCount - 1];
            }

            return(assemblyReferenceHandle);
        }
示例#10
0
        private AssemblyReferenceHandle GetAssemblyAtIndex(int refAsmIndex, out MetadataReader metadataReader)
        {
            Debug.Assert(refAsmIndex != 0);

            int assemblyRefCount = MetadataReader.GetTableRowCount(TableIndex.AssemblyRef);
            AssemblyReferenceHandle assemblyReferenceHandle;

            if (refAsmIndex <= assemblyRefCount)
            {
                metadataReader          = MetadataReader;
                assemblyReferenceHandle = MetadataTokens.AssemblyReferenceHandle(refAsmIndex);
            }
            else
            {
                metadataReader          = ManifestReader;
                assemblyReferenceHandle = ManifestReferences[refAsmIndex - assemblyRefCount - 2];
            }

            return(assemblyReferenceHandle);
        }
示例#11
0
        private unsafe void EnsureManifestReferences()
        {
            if (_manifestReferences != null)
            {
                return;
            }
            _manifestReferences = new List <AssemblyReferenceHandle>();
            if (ReadyToRunHeader.Sections.TryGetValue(ReadyToRunSectionType.ManifestMetadata, out ReadyToRunSection manifestMetadata))
            {
                fixed(byte *image = Image)
                {
                    _manifestReader = new MetadataReader(image + GetOffset(manifestMetadata.RelativeVirtualAddress), manifestMetadata.Size);
                    int assemblyRefCount = _manifestReader.GetTableRowCount(TableIndex.AssemblyRef);

                    for (int assemblyRefIndex = 1; assemblyRefIndex <= assemblyRefCount; assemblyRefIndex++)
                    {
                        AssemblyReferenceHandle asmRefHandle = MetadataTokens.AssemblyReferenceHandle(assemblyRefIndex);
                        _manifestReferences.Add(asmRefHandle);
                    }
                }
            }
        }
示例#12
0
        public ManifestMetadataTableNode(EcmaModule inputModule, NodeFactory nodeFactory)
            : base(inputModule.Context.Target)
        {
            _assemblyRefToModuleIdMap  = new Dictionary <string, int>();
            _moduleIdToAssemblyNameMap = new Dictionary <int, AssemblyName>();
            _signatureEmitters         = new List <ISignatureEmitter>();
            _nodeFactory = nodeFactory;

            _inputModuleName = inputModule.Assembly.GetName().Name;

            _assemblyRefCount = inputModule.MetadataReader.GetTableRowCount(TableIndex.AssemblyRef);
            for (int assemblyRefIndex = 1; assemblyRefIndex <= _assemblyRefCount; assemblyRefIndex++)
            {
                AssemblyReferenceHandle assemblyRefHandle = MetadataTokens.AssemblyReferenceHandle(assemblyRefIndex);
                AssemblyReference       assemblyRef       = inputModule.MetadataReader.GetAssemblyReference(assemblyRefHandle);
                string assemblyName = inputModule.MetadataReader.GetString(assemblyRef.Name);
                _assemblyRefToModuleIdMap[assemblyName] = assemblyRefIndex;
            }

            // AssemblyRefCount + 1 corresponds to ROWID 0 in the manifest metadata
            _nextModuleId = _assemblyRefCount + 2;
        }
示例#13
0
 public void SpecificHandleFactories()
 {
     Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.MethodDefinitionHandle(1)));
     Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.MethodImplementationHandle(1)));
     Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.MethodSpecificationHandle(1)));
     Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.TypeDefinitionHandle(1)));
     Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.ExportedTypeHandle(1)));
     Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.TypeReferenceHandle(1)));
     Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.TypeSpecificationHandle(1)));
     Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.InterfaceImplementationHandle(1)));
     Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.MemberReferenceHandle(1)));
     Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.FieldDefinitionHandle(1)));
     Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.EventDefinitionHandle(1)));
     Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.PropertyDefinitionHandle(1)));
     Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.StandaloneSignatureHandle(1)));
     Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.ParameterHandle(1)));
     Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.GenericParameterHandle(1)));
     Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.GenericParameterConstraintHandle(1)));
     Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.ModuleReferenceHandle(1)));
     Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.AssemblyReferenceHandle(1)));
     Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.CustomAttributeHandle(1)));
     Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.DeclarativeSecurityAttributeHandle(1)));
     Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.ConstantHandle(1)));
     Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.ManifestResourceHandle(1)));
     Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.AssemblyFileHandle(1)));
     Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.DocumentHandle(1)));
     Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.MethodDebugInformationHandle(1)));
     Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.LocalScopeHandle(1)));
     Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.LocalVariableHandle(1)));
     Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.LocalConstantHandle(1)));
     Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.ImportScopeHandle(1)));
     Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.CustomDebugInformationHandle(1)));
     Assert.Equal(1, MetadataTokens.GetHeapOffset(MetadataTokens.UserStringHandle(1)));
     Assert.Equal(1, MetadataTokens.GetHeapOffset(MetadataTokens.StringHandle(1)));
     Assert.Equal(1, MetadataTokens.GetHeapOffset(MetadataTokens.BlobHandle(1)));
     Assert.Equal(1, MetadataTokens.GetHeapOffset(MetadataTokens.GuidHandle(1)));
     Assert.Equal(1, MetadataTokens.GetHeapOffset((BlobHandle)MetadataTokens.DocumentNameBlobHandle(1)));
 }
示例#14
0
        private unsafe void EnsureManifestReferences()
        {
            if (_manifestReferences != null)
            {
                return;
            }
            _manifestReferences = new List <AssemblyReferenceHandle>();
            if (ReadyToRunHeader.Sections.ContainsKey(ReadyToRunSection.SectionType.READYTORUN_SECTION_MANIFEST_METADATA))
            {
                ReadyToRunSection manifestMetadata = ReadyToRunHeader.Sections[ReadyToRunSection.SectionType.READYTORUN_SECTION_MANIFEST_METADATA];
                fixed(byte *image = Image)
                {
                    _manifestReader = new MetadataReader(image + GetOffset(manifestMetadata.RelativeVirtualAddress), manifestMetadata.Size);
                    int assemblyRefCount = _manifestReader.GetTableRowCount(TableIndex.AssemblyRef);

                    for (int assemblyRefIndex = 1; assemblyRefIndex <= assemblyRefCount; assemblyRefIndex++)
                    {
                        AssemblyReferenceHandle asmRefHandle = MetadataTokens.AssemblyReferenceHandle(assemblyRefIndex);
                        _manifestReferences.Add(asmRefHandle);
                    }
                }
            }
        }
示例#15
0
        /// <summary>
        /// Open a given reference assembly (relative to this ECMA metadata file).
        /// </summary>
        /// <param name="refAsmIndex">Reference assembly index</param>
        /// <returns>MetadataReader instance representing the reference assembly</returns>
        internal MetadataReader OpenReferenceAssembly(int refAsmIndex)
        {
            if (refAsmIndex == 0)
            {
                return(this.MetadataReader);
            }

            int                     assemblyRefCount = MetadataReader.GetTableRowCount(TableIndex.AssemblyRef);
            MetadataReader          metadataReader;
            AssemblyReferenceHandle assemblyReferenceHandle;

            if (refAsmIndex <= assemblyRefCount)
            {
                metadataReader          = MetadataReader;
                assemblyReferenceHandle = MetadataTokens.AssemblyReferenceHandle(refAsmIndex);
            }
            else
            {
                metadataReader          = _manifestReader;
                assemblyReferenceHandle = _manifestReferences[refAsmIndex - assemblyRefCount - 2];
            }


            MetadataReader result;

            if (!_assemblyCache.TryGetValue(refAsmIndex, out result))
            {
                result = _assemblyResolver.FindAssembly(metadataReader, assemblyReferenceHandle, Filename);
                if (result == null)
                {
                    string name = metadataReader.GetString(metadataReader.GetAssemblyReference(assemblyReferenceHandle).Name);
                    throw new Exception($"Missing reference assembly: {name}");
                }
                _assemblyCache.Add(refAsmIndex, result);
            }
            return(result);
        }
示例#16
0
        private static IEnumerable <string> GetReferencesFromDll(MetadataReader reader)
        {
            var typeReferenceHandles = reader.TypeReferences;
            var dictionary           = new Dictionary <int, string>(100);

            foreach (var typeReferenceHandle in typeReferenceHandles)
            {
                var typeReference   = reader.GetTypeReference(typeReferenceHandle);
                var resolutionScope = typeReference.ResolutionScope;
                if (resolutionScope.Kind == HandleKind.AssemblyReference)
                {
                    var rowNumber = reader.GetToken(resolutionScope);

                    if (!dictionary.TryGetValue(rowNumber, out var assemblyName))
                    {
                        var assemblyReference = reader.GetAssemblyReference(MetadataTokens.AssemblyReferenceHandle(rowNumber));
                        assemblyName = reader.GetString(assemblyReference.Name);
                        dictionary.Add(rowNumber, assemblyName);
                    }
                }
            }

            return(dictionary.Values);
        }
示例#17
0
        private unsafe void Initialize()
        {
            _assemblyCache           = new Dictionary <int, MetadataReader>();
            this._manifestReferences = new List <AssemblyReferenceHandle>();

            if (MetadataReader == null)
            {
                byte[] image = File.ReadAllBytes(Filename);
                Image = image;

                PEReader = new PEReader(Unsafe.As <byte[], ImmutableArray <byte> >(ref image));

                if (!PEReader.HasMetadata)
                {
                    throw new Exception($"ECMA metadata not found in file '{Filename}'");
                }

                MetadataReader = PEReader.GetMetadataReader();
            }
            else
            {
                ImmutableArray <byte> content = PEReader.GetEntireImage().GetContent();
                Image = Unsafe.As <ImmutableArray <byte>, byte[]>(ref content);
            }

            if ((PEReader.PEHeaders.CorHeader.Flags & CorFlags.ILLibrary) == 0)
            {
                throw new BadImageFormatException("The file is not a ReadyToRun image");
            }

            // This is a work in progress toward lazy initialization.
            // Ideally, here should be the end of the Initialize() method

            EnsureHeader();

            EnsureRuntimeFunctionToDebugInfo();

            if (ReadyToRunHeader.Sections.ContainsKey(ReadyToRunSection.SectionType.READYTORUN_SECTION_MANIFEST_METADATA))
            {
                ReadyToRunSection manifestMetadata = ReadyToRunHeader.Sections[ReadyToRunSection.SectionType.READYTORUN_SECTION_MANIFEST_METADATA];
                fixed(byte *image = Image)
                {
                    _manifestReader = new MetadataReader(image + GetOffset(manifestMetadata.RelativeVirtualAddress), manifestMetadata.Size);
                    int assemblyRefCount = _manifestReader.GetTableRowCount(TableIndex.AssemblyRef);

                    for (int assemblyRefIndex = 1; assemblyRefIndex <= assemblyRefCount; assemblyRefIndex++)
                    {
                        AssemblyReferenceHandle asmRefHandle = MetadataTokens.AssemblyReferenceHandle(assemblyRefIndex);
                        _manifestReferences.Add(asmRefHandle);
                    }
                }
            }

            if (ReadyToRunHeader.Sections.ContainsKey(ReadyToRunSection.SectionType.READYTORUN_SECTION_EXCEPTION_INFO))
            {
                ReadyToRunSection exceptionInfoSection = ReadyToRunHeader.Sections[ReadyToRunSection.SectionType.READYTORUN_SECTION_EXCEPTION_INFO];
                EHLookupTable = new EHLookupTable(Image, GetOffset(exceptionInfoSection.RelativeVirtualAddress), exceptionInfoSection.Size);
            }

            ImportSections  = new List <ReadyToRunImportSection>();
            ImportCellNames = new Dictionary <int, string>();
            ParseImportSections();

            R2RMethods      = new List <ReadyToRunMethod>();
            InstanceMethods = new List <InstanceMethod>();

            if (ReadyToRunHeader.Sections.ContainsKey(ReadyToRunSection.SectionType.READYTORUN_SECTION_RUNTIME_FUNCTIONS))
            {
                int runtimeFunctionSize = CalculateRuntimeFunctionSize();
                ReadyToRunSection runtimeFunctionSection = ReadyToRunHeader.Sections[ReadyToRunSection.SectionType.READYTORUN_SECTION_RUNTIME_FUNCTIONS];

                uint   nRuntimeFunctions     = (uint)(runtimeFunctionSection.Size / runtimeFunctionSize);
                int    runtimeFunctionOffset = GetOffset(runtimeFunctionSection.RelativeVirtualAddress);
                bool[] isEntryPoint          = new bool[nRuntimeFunctions];

                // initialize R2RMethods
                ParseMethodDefEntrypoints(isEntryPoint);
                ParseInstanceMethodEntrypoints(isEntryPoint);
                ParseRuntimeFunctions(isEntryPoint, runtimeFunctionOffset, runtimeFunctionSize);
            }

            AvailableTypes = new List <string>();
            ParseAvailableTypes();

            CompilerIdentifier = ParseCompilerIdentifier();
        }
示例#18
0
        public ManifestMetadataTableNode(NodeFactory nodeFactory)
            : base(nodeFactory.Target)
        {
            _assemblyRefToModuleIdMap  = new Dictionary <string, int>();
            _moduleIdToAssemblyNameMap = new Dictionary <int, AssemblyName>();
            _manifestAssemblyMvids     = new List <Guid>();
            _signatureEmitters         = new List <ISignatureEmitter>();
            _nodeFactory  = nodeFactory;
            _nextModuleId = 2;

            AssemblyHashAlgorithm hashAlgorithm = AssemblyHashAlgorithm.None;

            byte[]        publicKeyBlob           = null;
            AssemblyFlags manifestAssemblyFlags   = default(AssemblyFlags);
            Version       manifestAssemblyVersion = new Version(0, 0, 0, 0);

            if ((nodeFactory.CompositeImageSettings != null) && nodeFactory.CompilationModuleGroup.IsCompositeBuildMode)
            {
                if (nodeFactory.CompositeImageSettings.PublicKey != null)
                {
                    hashAlgorithm          = AssemblyHashAlgorithm.Sha1;
                    publicKeyBlob          = nodeFactory.CompositeImageSettings.PublicKey.ToArray();
                    manifestAssemblyFlags |= AssemblyFlags.PublicKey;
                }

                if (nodeFactory.CompositeImageSettings.AssemblyVersion != null)
                {
                    manifestAssemblyVersion = nodeFactory.CompositeImageSettings.AssemblyVersion;
                }
            }

            _mutableModule = new MutableModule(nodeFactory.TypeSystemContext,
                                               "ManifestMetadata",
                                               manifestAssemblyFlags,
                                               publicKeyBlob,
                                               manifestAssemblyVersion,
                                               hashAlgorithm,
                                               ModuleToIndexSingleThreadedAndSorted,
                                               nodeFactory.CompilationModuleGroup);

            if (!_nodeFactory.CompilationModuleGroup.IsCompositeBuildMode)
            {
                MetadataReader mdReader = _nodeFactory.CompilationModuleGroup.CompilationModuleSet.Single().MetadataReader;
                _assemblyRefCount = mdReader.GetTableRowCount(TableIndex.AssemblyRef);

                if (!_nodeFactory.CompilationModuleGroup.IsInputBubble)
                {
                    for (int assemblyRefIndex = 1; assemblyRefIndex < _assemblyRefCount; assemblyRefIndex++)
                    {
                        AssemblyReferenceHandle assemblyRefHandle = MetadataTokens.AssemblyReferenceHandle(assemblyRefIndex);
                        AssemblyReference       assemblyRef       = mdReader.GetAssemblyReference(assemblyRefHandle);
                        string assemblyName = mdReader.GetString(assemblyRef.Name);
                        _assemblyRefToModuleIdMap[assemblyName] = assemblyRefIndex;
                    }
                }

                // AssemblyRefCount + 1 corresponds to rid 0 in the manifest metadata which indicates to use the manifest metadata itself
                // AssemblyRefCount + 2 corresponds to ROWID 1 in the manifest metadata
                _nextModuleId += _assemblyRefCount;
            }

            if (_nodeFactory.CompilationModuleGroup.IsCompositeBuildMode)
            {
                // Fill in entries for all input modules right away to make sure they have parallel indices
                int nextExpectedId = 2;
                foreach (EcmaModule inputModule in _nodeFactory.CompilationModuleGroup.CompilationModuleSet)
                {
                    int acquiredId = ModuleToIndexInternal(inputModule);
                    if (acquiredId != nextExpectedId)
                    {
                        throw new InternalCompilerErrorException($"Manifest metadata consistency error - acquired ID {acquiredId}, expected {nextExpectedId}");
                    }
                    nextExpectedId++;
                }
            }
        }
        public void HandleConversionGivesCorrectKind()
        {
            var expectedKinds = new SortedSet <HandleKind>((HandleKind[])Enum.GetValues(typeof(HandleKind)));

            Action <Handle, HandleKind> assert = (handle, expectedKind) =>
            {
                Assert.False(expectedKinds.Count == 0, "Repeat handle in tests below.");
                Assert.Equal(expectedKind, handle.Kind);
                expectedKinds.Remove(expectedKind);
            };

            assert(default(ModuleDefinitionHandle), HandleKind.ModuleDefinition);
            assert(default(AssemblyDefinitionHandle), HandleKind.AssemblyDefinition);
            assert(default(InterfaceImplementationHandle), HandleKind.InterfaceImplementation);
            assert(default(MethodDefinitionHandle), HandleKind.MethodDefinition);
            assert(default(MethodSpecificationHandle), HandleKind.MethodSpecification);
            assert(default(TypeDefinitionHandle), HandleKind.TypeDefinition);
            assert(default(ExportedTypeHandle), HandleKind.ExportedType);
            assert(default(TypeReferenceHandle), HandleKind.TypeReference);
            assert(default(TypeSpecificationHandle), HandleKind.TypeSpecification);
            assert(default(MemberReferenceHandle), HandleKind.MemberReference);
            assert(default(FieldDefinitionHandle), HandleKind.FieldDefinition);
            assert(default(EventDefinitionHandle), HandleKind.EventDefinition);
            assert(default(PropertyDefinitionHandle), HandleKind.PropertyDefinition);
            assert(default(StandaloneSignatureHandle), HandleKind.StandaloneSignature);
            assert(default(MemberReferenceHandle), HandleKind.MemberReference);
            assert(default(FieldDefinitionHandle), HandleKind.FieldDefinition);
            assert(default(EventDefinitionHandle), HandleKind.EventDefinition);
            assert(default(PropertyDefinitionHandle), HandleKind.PropertyDefinition);
            assert(default(StandaloneSignatureHandle), HandleKind.StandaloneSignature);
            assert(default(ParameterHandle), HandleKind.Parameter);
            assert(default(GenericParameterHandle), HandleKind.GenericParameter);
            assert(default(GenericParameterConstraintHandle), HandleKind.GenericParameterConstraint);
            assert(default(ModuleReferenceHandle), HandleKind.ModuleReference);
            assert(default(CustomAttributeHandle), HandleKind.CustomAttribute);
            assert(default(DeclarativeSecurityAttributeHandle), HandleKind.DeclarativeSecurityAttribute);
            assert(default(ManifestResourceHandle), HandleKind.ManifestResource);
            assert(default(ConstantHandle), HandleKind.Constant);
            assert(default(ManifestResourceHandle), HandleKind.ManifestResource);
            assert(default(AssemblyFileHandle), HandleKind.AssemblyFile);

            assert(default(MethodImplementationHandle), HandleKind.MethodImplementation);
            assert(default(AssemblyFileHandle), HandleKind.AssemblyFile);

            // Bug #: DevDiv: Bug 1048345: [System.Reflection.Metada] For select handles, default(THandle) does not preserve type.
            // Not changing this immediately, because it has been this way for a long time so need to check Roslyn compat.
            //
            //assertEqual(default(StringHandle), HandleKind.String);
            //assertEqual(default(AssemblyReferenceHandle), HandleKind.AssemblyReference);
            //assertEqual(default(UserStringHandle), HandleKind.UserString);
            //assertEqual(default(GuidHandle), HandleKind.Guid);
            //assertEqual(default(BlobHandle), HandleKind.Blob);
            //assertEqual(default(NamespaceDefinitionHandle), HandleKind.NamespaceDefinition);

            // In the meantime, check using initialized handles behave as expected
            assert(MetadataTokens.StringHandle(1), HandleKind.String);
            assert(MetadataTokens.AssemblyReferenceHandle(1), HandleKind.AssemblyReference);
            assert(MetadataTokens.UserStringHandle(1), HandleKind.UserString);
            assert(MetadataTokens.GuidHandle(1), HandleKind.Guid);
            assert(MetadataTokens.BlobHandle(1), HandleKind.Blob);
            assert(NamespaceDefinitionHandle.FromIndexOfFullName(1), HandleKind.NamespaceDefinition);

            Assert.True(expectedKinds.Count == 0, "Some handles are missing from this test: " + String.Join(",\r\n", expectedKinds));
        }
示例#20
0
        /// <summary>
        /// Initializes the fields of the R2RHeader and R2RMethods
        /// </summary>
        /// <param name="filename">PE image</param>
        /// <exception cref="BadImageFormatException">The Cor header flag must be ILLibrary</exception>
        public unsafe R2RReader(IAssemblyResolver assemblyResolver, string filename)
            : base(assemblyResolver, filename, new List <string>())
        {
            IsR2R = ((PEReader.PEHeaders.CorHeader.Flags & CorFlags.ILLibrary) != 0);
            if (!IsR2R)
            {
                throw new BadImageFormatException("The file is not a ReadyToRun image");
            }

            uint machine = (uint)PEReader.PEHeaders.CoffHeader.Machine;

            OS = OperatingSystem.Unknown;
            foreach (OperatingSystem os in Enum.GetValues(typeof(OperatingSystem)))
            {
                Machine = (Machine)(machine ^ (uint)os);
                if (Enum.IsDefined(typeof(Machine), Machine))
                {
                    OS = os;
                    break;
                }
            }
            if (OS == OperatingSystem.Unknown)
            {
                throw new BadImageFormatException($"Invalid Machine: {machine}");
            }

            switch (Machine)
            {
            case Machine.I386:
                Architecture = Architecture.X86;
                PointerSize  = 4;
                break;

            case Machine.Amd64:
                Architecture = Architecture.X64;
                PointerSize  = 8;
                break;

            case Machine.Arm:
            case Machine.Thumb:
            case Machine.ArmThumb2:
                Architecture = Architecture.Arm;
                PointerSize  = 4;
                break;

            case Machine.Arm64:
                Architecture = Architecture.Arm64;
                PointerSize  = 8;
                break;

            default:
                throw new NotImplementedException(Machine.ToString());
            }


            ImageBase = PEReader.PEHeaders.PEHeader.ImageBase;

            // initialize R2RHeader
            DirectoryEntry r2rHeaderDirectory = PEReader.PEHeaders.CorHeader.ManagedNativeHeaderDirectory;
            int            r2rHeaderOffset    = GetOffset(r2rHeaderDirectory.RelativeVirtualAddress);

            R2RHeader = new R2RHeader(Image, r2rHeaderDirectory.RelativeVirtualAddress, r2rHeaderOffset);
            if (r2rHeaderDirectory.Size != R2RHeader.Size)
            {
                throw new BadImageFormatException("The calculated size of the R2RHeader doesn't match the size saved in the ManagedNativeHeaderDirectory");
            }

            ParseDebugInfo();

            if (R2RHeader.Sections.ContainsKey(R2RSection.SectionType.READYTORUN_SECTION_MANIFEST_METADATA))
            {
                R2RSection manifestMetadata = R2RHeader.Sections[R2RSection.SectionType.READYTORUN_SECTION_MANIFEST_METADATA];
                fixed(byte *image = Image)
                {
                    MetadataReader manifestReader   = new MetadataReader(image + GetOffset(manifestMetadata.RelativeVirtualAddress), manifestMetadata.Size);
                    int            assemblyRefCount = manifestReader.GetTableRowCount(TableIndex.AssemblyRef);

                    for (int assemblyRefIndex = 1; assemblyRefIndex <= assemblyRefCount; assemblyRefIndex++)
                    {
                        AssemblyReferenceHandle asmRefHandle = MetadataTokens.AssemblyReferenceHandle(assemblyRefIndex);
                        AssemblyReference       asmRef       = manifestReader.GetAssemblyReference(asmRefHandle);
                        string asmRefName = manifestReader.GetString(asmRef.Name);
                        ManifestReferenceAssemblies.Add(asmRefName);
                    }
                }
            }

            if (R2RHeader.Sections.ContainsKey(R2RSection.SectionType.READYTORUN_SECTION_EXCEPTION_INFO))
            {
                R2RSection exceptionInfoSection = R2RHeader.Sections[R2RSection.SectionType.READYTORUN_SECTION_EXCEPTION_INFO];
                EHLookupTable = new EHLookupTable(Image, GetOffset(exceptionInfoSection.RelativeVirtualAddress), exceptionInfoSection.Size);
            }

            ImportSections  = new List <R2RImportSection>();
            ImportCellNames = new Dictionary <int, string>();
            ParseImportSections();

            R2RMethods      = new List <R2RMethod>();
            InstanceMethods = new List <InstanceMethod>();

            if (R2RHeader.Sections.ContainsKey(R2RSection.SectionType.READYTORUN_SECTION_RUNTIME_FUNCTIONS))
            {
                int        runtimeFunctionSize    = CalculateRuntimeFunctionSize();
                R2RSection runtimeFunctionSection = R2RHeader.Sections[R2RSection.SectionType.READYTORUN_SECTION_RUNTIME_FUNCTIONS];

                uint   nRuntimeFunctions     = (uint)(runtimeFunctionSection.Size / runtimeFunctionSize);
                int    runtimeFunctionOffset = GetOffset(runtimeFunctionSection.RelativeVirtualAddress);
                bool[] isEntryPoint          = new bool[nRuntimeFunctions];

                // initialize R2RMethods
                ParseMethodDefEntrypoints(isEntryPoint);
                ParseInstanceMethodEntrypoints(isEntryPoint);
                ParseRuntimeFunctions(isEntryPoint, runtimeFunctionOffset, runtimeFunctionSize);
            }

            AvailableTypes = new List <string>();
            ParseAvailableTypes();

            CompilerIdentifier = ParseCompilerIdentifier();
        }
示例#21
0
        internal override void DumpSectionContents(ReadyToRunSection section)
        {
            switch (section.Type)
            {
            case ReadyToRunSection.SectionType.READYTORUN_SECTION_AVAILABLE_TYPES:
                if (!_options.Naked)
                {
                    uint            availableTypesSectionOffset = (uint)_r2r.GetOffset(section.RelativeVirtualAddress);
                    NativeParser    availableTypesParser        = new NativeParser(_r2r.Image, availableTypesSectionOffset);
                    NativeHashtable availableTypes = new NativeHashtable(_r2r.Image, availableTypesParser, (uint)(availableTypesSectionOffset + section.Size));
                    _writer.WriteLine(availableTypes.ToString());
                }

                foreach (string name in _r2r.AvailableTypes)
                {
                    _writer.WriteLine(name);
                }
                break;

            case ReadyToRunSection.SectionType.READYTORUN_SECTION_METHODDEF_ENTRYPOINTS:
                if (!_options.Naked)
                {
                    NativeArray methodEntryPoints = new NativeArray(_r2r.Image, (uint)_r2r.GetOffset(section.RelativeVirtualAddress));
                    _writer.Write(methodEntryPoints.ToString());
                }
                break;

            case ReadyToRunSection.SectionType.READYTORUN_SECTION_INSTANCE_METHOD_ENTRYPOINTS:
                if (!_options.Naked)
                {
                    uint            instanceSectionOffset = (uint)_r2r.GetOffset(section.RelativeVirtualAddress);
                    NativeParser    instanceParser        = new NativeParser(_r2r.Image, instanceSectionOffset);
                    NativeHashtable instMethodEntryPoints = new NativeHashtable(_r2r.Image, instanceParser, (uint)(instanceSectionOffset + section.Size));
                    _writer.Write(instMethodEntryPoints.ToString());
                    _writer.WriteLine();
                }
                foreach (InstanceMethod instanceMethod in _r2r.InstanceMethods)
                {
                    _writer.WriteLine($@"0x{instanceMethod.Bucket:X2} -> {instanceMethod.Method.SignatureString}");
                }
                break;

            case ReadyToRunSection.SectionType.READYTORUN_SECTION_RUNTIME_FUNCTIONS:
                int rtfOffset    = _r2r.GetOffset(section.RelativeVirtualAddress);
                int rtfEndOffset = rtfOffset + section.Size;
                int rtfIndex     = 0;
                while (rtfOffset < rtfEndOffset)
                {
                    int startRva = NativeReader.ReadInt32(_r2r.Image, ref rtfOffset);
                    int endRva   = -1;
                    if (_r2r.Machine == Machine.Amd64)
                    {
                        endRva = NativeReader.ReadInt32(_r2r.Image, ref rtfOffset);
                    }
                    int unwindRva = NativeReader.ReadInt32(_r2r.Image, ref rtfOffset);
                    _writer.WriteLine($"Index: {rtfIndex}");
                    _writer.WriteLine($"\tStartRva: 0x{startRva:X8}");
                    if (endRva != -1)
                    {
                        _writer.WriteLine($"\tEndRva: 0x{endRva:X8}");
                    }
                    _writer.WriteLine($"\tUnwindRva: 0x{unwindRva:X8}");
                    rtfIndex++;
                }
                break;

            case ReadyToRunSection.SectionType.READYTORUN_SECTION_COMPILER_IDENTIFIER:
                _writer.WriteLine(_r2r.CompilerIdentifier);
                break;

            case ReadyToRunSection.SectionType.READYTORUN_SECTION_IMPORT_SECTIONS:
                if (_options.Naked)
                {
                    DumpNakedImportSections();
                }
                else
                {
                    foreach (ReadyToRunImportSection importSection in _r2r.ImportSections)
                    {
                        importSection.WriteTo(_writer);
                        if (_options.Raw && importSection.Entries.Count != 0)
                        {
                            if (importSection.SectionRVA != 0)
                            {
                                _writer.WriteLine("Section Bytes:");
                                DumpBytes(importSection.SectionRVA, (uint)importSection.SectionSize);
                            }
                            if (importSection.SignatureRVA != 0)
                            {
                                _writer.WriteLine("Signature Bytes:");
                                DumpBytes(importSection.SignatureRVA, (uint)importSection.Entries.Count * sizeof(int));
                            }
                            if (importSection.AuxiliaryDataRVA != 0 && importSection.AuxiliaryDataSize != 0)
                            {
                                _writer.WriteLine("AuxiliaryData Bytes:");
                                DumpBytes(importSection.AuxiliaryDataRVA, (uint)importSection.AuxiliaryDataSize);
                            }
                        }
                        foreach (ReadyToRunImportSection.ImportSectionEntry entry in importSection.Entries)
                        {
                            entry.WriteTo(_writer, _options);
                            _writer.WriteLine();
                        }
                        _writer.WriteLine();
                    }
                }
                break;

            case ReadyToRunSection.SectionType.READYTORUN_SECTION_MANIFEST_METADATA:
                int assemblyRefCount = _r2r.MetadataReader.GetTableRowCount(TableIndex.AssemblyRef);
                _writer.WriteLine($"MSIL AssemblyRef's ({assemblyRefCount} entries):");
                for (int assemblyRefIndex = 1; assemblyRefIndex <= assemblyRefCount; assemblyRefIndex++)
                {
                    AssemblyReference assemblyRef     = _r2r.MetadataReader.GetAssemblyReference(MetadataTokens.AssemblyReferenceHandle(assemblyRefIndex));
                    string            assemblyRefName = _r2r.MetadataReader.GetString(assemblyRef.Name);
                    _writer.WriteLine($"[ID 0x{assemblyRefIndex:X2}]: {assemblyRefName}");
                }

                _writer.WriteLine($"Manifest metadata AssemblyRef's ({_r2r.ManifestReferenceAssemblies.Count()} entries):");
                int manifestAsmIndex = 0;
                foreach (string manifestReferenceAssembly in _r2r.ManifestReferenceAssemblies)
                {
                    _writer.WriteLine($"[ID 0x{manifestAsmIndex + assemblyRefCount + 2:X2}]: {manifestReferenceAssembly}");
                    manifestAsmIndex++;
                }
                break;

            case ReadyToRunSection.SectionType.READYTORUN_SECTION_ATTRIBUTEPRESENCE:
                int attributesStartOffset     = _r2r.GetOffset(section.RelativeVirtualAddress);
                int attributesEndOffset       = attributesStartOffset + section.Size;
                NativeCuckooFilter attributes = new NativeCuckooFilter(_r2r.Image, attributesStartOffset, attributesEndOffset);
                _writer.WriteLine("Attribute presence filter");
                _writer.WriteLine(attributes.ToString());
                break;
            }
        }
示例#22
0
        internal override void DumpSectionContents(ReadyToRunSection section)
        {
            switch (section.Type)
            {
            case ReadyToRunSectionType.AvailableTypes:
                if (!_options.Naked)
                {
                    uint            availableTypesSectionOffset = (uint)_r2r.GetOffset(section.RelativeVirtualAddress);
                    NativeParser    availableTypesParser        = new NativeParser(_r2r.Image, availableTypesSectionOffset);
                    NativeHashtable availableTypes = new NativeHashtable(_r2r.Image, availableTypesParser, (uint)(availableTypesSectionOffset + section.Size));
                    _writer.WriteLine(availableTypes.ToString());
                }

                if (_r2r.AvailableTypes.TryGetValue(section, out List <string> sectionTypes))
                {
                    _writer.WriteLine();
                    foreach (string name in sectionTypes)
                    {
                        _writer.WriteLine(name);
                    }
                }
                break;

            case ReadyToRunSectionType.MethodDefEntryPoints:
                if (!_options.Naked)
                {
                    NativeArray methodEntryPoints = new NativeArray(_r2r.Image, (uint)_r2r.GetOffset(section.RelativeVirtualAddress));
                    _writer.Write(methodEntryPoints.ToString());
                }

                if (_r2r.Methods.TryGetValue(section, out List <ReadyToRunMethod> sectionMethods))
                {
                    _writer.WriteLine();
                    foreach (ReadyToRunMethod method in sectionMethods)
                    {
                        _writer.WriteLine($@"{MetadataTokens.GetToken(method.MethodHandle):X8}: {method.SignatureString}");
                    }
                }
                break;

            case ReadyToRunSectionType.InstanceMethodEntryPoints:
                if (!_options.Naked)
                {
                    uint            instanceSectionOffset = (uint)_r2r.GetOffset(section.RelativeVirtualAddress);
                    NativeParser    instanceParser        = new NativeParser(_r2r.Image, instanceSectionOffset);
                    NativeHashtable instMethodEntryPoints = new NativeHashtable(_r2r.Image, instanceParser, (uint)(instanceSectionOffset + section.Size));
                    _writer.Write(instMethodEntryPoints.ToString());
                    _writer.WriteLine();
                }
                foreach (InstanceMethod instanceMethod in _r2r.InstanceMethods)
                {
                    _writer.WriteLine($@"0x{instanceMethod.Bucket:X2} -> {instanceMethod.Method.SignatureString}");
                }
                break;

            case ReadyToRunSectionType.RuntimeFunctions:
                int rtfOffset    = _r2r.GetOffset(section.RelativeVirtualAddress);
                int rtfEndOffset = rtfOffset + section.Size;
                int rtfIndex     = 0;
                while (rtfOffset < rtfEndOffset)
                {
                    int startRva = NativeReader.ReadInt32(_r2r.Image, ref rtfOffset);
                    int endRva   = -1;
                    if (_r2r.Machine == Machine.Amd64)
                    {
                        endRva = NativeReader.ReadInt32(_r2r.Image, ref rtfOffset);
                    }
                    int unwindRva = NativeReader.ReadInt32(_r2r.Image, ref rtfOffset);
                    _writer.WriteLine($"Index: {rtfIndex}");
                    _writer.WriteLine($"        StartRva: 0x{startRva:X8}");
                    if (endRva != -1)
                    {
                        _writer.WriteLine($"        EndRva: 0x{endRva:X8}");
                    }
                    _writer.WriteLine($"        UnwindRva: 0x{unwindRva:X8}");
                    rtfIndex++;
                }
                break;

            case ReadyToRunSectionType.CompilerIdentifier:
                _writer.WriteLine(_r2r.CompilerIdentifier);
                break;

            case ReadyToRunSectionType.ImportSections:
                if (_options.Naked)
                {
                    DumpNakedImportSections();
                }
                else
                {
                    foreach (ReadyToRunImportSection importSection in _r2r.ImportSections)
                    {
                        importSection.WriteTo(_writer);
                        if (_options.Raw && importSection.Entries.Count != 0)
                        {
                            if (importSection.SectionRVA != 0)
                            {
                                _writer.WriteLine("Section Bytes:");
                                DumpBytes(importSection.SectionRVA, (uint)importSection.SectionSize);
                            }
                            if (importSection.SignatureRVA != 0)
                            {
                                _writer.WriteLine("Signature Bytes:");
                                DumpBytes(importSection.SignatureRVA, (uint)importSection.Entries.Count * sizeof(int));
                            }
                            if (importSection.AuxiliaryDataRVA != 0 && importSection.AuxiliaryDataSize != 0)
                            {
                                _writer.WriteLine("AuxiliaryData Bytes:");
                                DumpBytes(importSection.AuxiliaryDataRVA, (uint)importSection.AuxiliaryDataSize);
                            }
                        }
                        foreach (ReadyToRunImportSection.ImportSectionEntry entry in importSection.Entries)
                        {
                            entry.WriteTo(_writer, _options);
                            _writer.WriteLine();
                        }
                        _writer.WriteLine();
                    }
                }
                break;

            case ReadyToRunSectionType.ManifestMetadata:
                int assemblyRefCount = 0;
                if (!_r2r.Composite)
                {
                    MetadataReader globalReader = _r2r.GetGlobalMetadataReader();
                    assemblyRefCount = globalReader.GetTableRowCount(TableIndex.AssemblyRef) + 1;
                    _writer.WriteLine($"MSIL AssemblyRef's ({assemblyRefCount} entries):");
                    for (int assemblyRefIndex = 1; assemblyRefIndex < assemblyRefCount; assemblyRefIndex++)
                    {
                        AssemblyReference assemblyRef     = globalReader.GetAssemblyReference(MetadataTokens.AssemblyReferenceHandle(assemblyRefIndex));
                        string            assemblyRefName = globalReader.GetString(assemblyRef.Name);
                        _writer.WriteLine($"[ID 0x{assemblyRefIndex:X2}]: {assemblyRefName}");
                    }
                }

                _writer.WriteLine($"Manifest metadata AssemblyRef's ({_r2r.ManifestReferenceAssemblies.Count} entries):");
                int manifestAsmIndex = 0;
                foreach (string manifestReferenceAssembly in _r2r.ManifestReferenceAssemblies.OrderBy(kvp => kvp.Value).Select(kvp => kvp.Key))
                {
                    _writer.WriteLine($"[ID 0x{manifestAsmIndex + assemblyRefCount + 1:X2}]: {manifestReferenceAssembly}");
                    manifestAsmIndex++;
                }
                break;

            case ReadyToRunSectionType.AttributePresence:
                int attributesStartOffset     = _r2r.GetOffset(section.RelativeVirtualAddress);
                int attributesEndOffset       = attributesStartOffset + section.Size;
                NativeCuckooFilter attributes = new NativeCuckooFilter(_r2r.Image, attributesStartOffset, attributesEndOffset);
                _writer.WriteLine("Attribute presence filter");
                _writer.WriteLine(attributes.ToString());
                break;

            case ReadyToRunSectionType.InliningInfo:
                int iiOffset    = _r2r.GetOffset(section.RelativeVirtualAddress);
                int iiEndOffset = iiOffset + section.Size;
                InliningInfoSection inliningInfoSection = new InliningInfoSection(_r2r, iiOffset, iiEndOffset);
                _writer.WriteLine(inliningInfoSection.ToString());
                break;

            case ReadyToRunSectionType.InliningInfo2:
                int ii2Offset    = _r2r.GetOffset(section.RelativeVirtualAddress);
                int ii2EndOffset = ii2Offset + section.Size;
                InliningInfoSection2 inliningInfoSection2 = new InliningInfoSection2(_r2r, ii2Offset, ii2EndOffset);
                _writer.WriteLine(inliningInfoSection2.ToString());
                break;

            case ReadyToRunSectionType.OwnerCompositeExecutable:
                int oceOffset = _r2r.GetOffset(section.RelativeVirtualAddress);
                if (_r2r.Image[oceOffset + section.Size - 1] != 0)
                {
                    R2RDump.WriteWarning("String is not zero-terminated");
                }
                string ownerCompositeExecutable = Encoding.UTF8.GetString(_r2r.Image, oceOffset, section.Size - 1);     // exclude the zero terminator
                _writer.WriteLine("Composite executable: {0}", ownerCompositeExecutable.ToEscapedString());
                break;
            }
        }
            /// <exception cref="BadImageFormatException">Invalid blob format.</exception>
            public bool MoveNext()
            {
                if (_reader.RemainingBytes == 0)
                {
                    return(false);
                }

                var kind = (ImportDefinitionKind)_reader.ReadByte();

                switch (kind)
                {
                case ImportDefinitionKind.ImportType:
                    _current = new ImportDefinition(
                        kind,
                        typeOrNamespace: _reader.ReadTypeHandle());

                    break;

                case ImportDefinitionKind.ImportNamespace:
                    _current = new ImportDefinition(
                        kind,
                        typeOrNamespace: MetadataTokens.BlobHandle(_reader.ReadCompressedInteger()));

                    break;

                case ImportDefinitionKind.ImportAssemblyNamespace:
                    _current = new ImportDefinition(
                        kind,
                        assembly: MetadataTokens.AssemblyReferenceHandle(_reader.ReadCompressedInteger()),
                        typeOrNamespace: MetadataTokens.BlobHandle(_reader.ReadCompressedInteger()));

                    break;

                case ImportDefinitionKind.ImportAssemblyReferenceAlias:
                    _current = new ImportDefinition(
                        kind,
                        alias: MetadataTokens.BlobHandle(_reader.ReadCompressedInteger()));

                    break;

                case ImportDefinitionKind.AliasAssemblyReference:
                    _current = new ImportDefinition(
                        kind,
                        alias: MetadataTokens.BlobHandle(_reader.ReadCompressedInteger()),
                        assembly: MetadataTokens.AssemblyReferenceHandle(_reader.ReadCompressedInteger()));

                    break;

                case ImportDefinitionKind.AliasType:
                    _current = new ImportDefinition(
                        kind,
                        alias: MetadataTokens.BlobHandle(_reader.ReadCompressedInteger()),
                        typeOrNamespace: _reader.ReadTypeHandle());

                    break;

                case ImportDefinitionKind.ImportXmlNamespace:
                case ImportDefinitionKind.AliasNamespace:
                    _current = new ImportDefinition(
                        kind,
                        alias: MetadataTokens.BlobHandle(_reader.ReadCompressedInteger()),
                        typeOrNamespace: MetadataTokens.BlobHandle(_reader.ReadCompressedInteger()));

                    break;

                case ImportDefinitionKind.AliasAssemblyNamespace:
                    _current = new ImportDefinition(
                        kind,
                        alias: MetadataTokens.BlobHandle(_reader.ReadCompressedInteger()),
                        assembly: MetadataTokens.AssemblyReferenceHandle(_reader.ReadCompressedInteger()),
                        typeOrNamespace: MetadataTokens.BlobHandle(_reader.ReadCompressedInteger()));

                    break;

                default:
                    throw new BadImageFormatException(SR.Format(SR.InvalidImportDefinitionKind, kind));
                }

                return(true);
            }
示例#24
0
        private unsafe void Initialize()
        {
            _assemblyCache           = new Dictionary <int, MetadataReader>();
            this._manifestReferences = new List <AssemblyReferenceHandle>();

            if (MetadataReader == null)
            {
                Image = File.ReadAllBytes(Filename);

                fixed(byte *p = Image)
                {
                    IntPtr ptr = (IntPtr)p;

                    PEReader = new PEReader(p, Image.Length);

                    if (!PEReader.HasMetadata)
                    {
                        throw new Exception($"ECMA metadata not found in file '{Filename}'");
                    }

                    MetadataReader = PEReader.GetMetadataReader();
                }
            }
            else
            {
                ImmutableArray <byte> content = PEReader.GetEntireImage().GetContent();
                // TODO: Avoid copying
                Image = new byte[content.Length];
                content.CopyTo(Image);
            }

            ParseHeader();

            ParseDebugInfo();

            if (R2RHeader.Sections.ContainsKey(R2RSection.SectionType.READYTORUN_SECTION_MANIFEST_METADATA))
            {
                R2RSection manifestMetadata = R2RHeader.Sections[R2RSection.SectionType.READYTORUN_SECTION_MANIFEST_METADATA];
                fixed(byte *image = Image)
                {
                    _manifestReader = new MetadataReader(image + GetOffset(manifestMetadata.RelativeVirtualAddress), manifestMetadata.Size);
                    int assemblyRefCount = _manifestReader.GetTableRowCount(TableIndex.AssemblyRef);

                    for (int assemblyRefIndex = 1; assemblyRefIndex <= assemblyRefCount; assemblyRefIndex++)
                    {
                        AssemblyReferenceHandle asmRefHandle = MetadataTokens.AssemblyReferenceHandle(assemblyRefIndex);
                        _manifestReferences.Add(asmRefHandle);
                    }
                }
            }

            if (R2RHeader.Sections.ContainsKey(R2RSection.SectionType.READYTORUN_SECTION_EXCEPTION_INFO))
            {
                R2RSection exceptionInfoSection = R2RHeader.Sections[R2RSection.SectionType.READYTORUN_SECTION_EXCEPTION_INFO];
                EHLookupTable = new EHLookupTable(Image, GetOffset(exceptionInfoSection.RelativeVirtualAddress), exceptionInfoSection.Size);
            }

            ImportSections  = new List <R2RImportSection>();
            ImportCellNames = new Dictionary <int, string>();
            ParseImportSections();

            R2RMethods      = new List <R2RMethod>();
            InstanceMethods = new List <InstanceMethod>();

            if (R2RHeader.Sections.ContainsKey(R2RSection.SectionType.READYTORUN_SECTION_RUNTIME_FUNCTIONS))
            {
                int        runtimeFunctionSize    = CalculateRuntimeFunctionSize();
                R2RSection runtimeFunctionSection = R2RHeader.Sections[R2RSection.SectionType.READYTORUN_SECTION_RUNTIME_FUNCTIONS];

                uint   nRuntimeFunctions     = (uint)(runtimeFunctionSection.Size / runtimeFunctionSize);
                int    runtimeFunctionOffset = GetOffset(runtimeFunctionSection.RelativeVirtualAddress);
                bool[] isEntryPoint          = new bool[nRuntimeFunctions];

                // initialize R2RMethods
                ParseMethodDefEntrypoints(isEntryPoint);
                ParseInstanceMethodEntrypoints(isEntryPoint);
                ParseRuntimeFunctions(isEntryPoint, runtimeFunctionOffset, runtimeFunctionSize);
            }

            AvailableTypes = new List <string>();
            ParseAvailableTypes();

            CompilerIdentifier = ParseCompilerIdentifier();
        }