private NativeFormatRuntimeNamedTypeInfo(MetadataReader reader, TypeDefinitionHandle typeDefinitionHandle, RuntimeTypeHandle typeHandle) :
     base(typeHandle)
 {
     _reader = reader;
     _typeDefinitionHandle = typeDefinitionHandle;
     _typeDefinition = _typeDefinitionHandle.GetTypeDefinition(reader);
 }
 protected RuntimeMethodParameterInfo(MethodBase member, int position, MetadataReader reader, Handle typeHandle, TypeContext typeContext)
     : base(member, position)
 {
     Reader = reader;
     _typeHandle = typeHandle;
     _typeContext = typeContext;
 }
 private RuntimeFatMethodParameterInfo(MethodBase member, MethodHandle methodHandle, int position, ParameterHandle parameterHandle, MetadataReader reader, Handle typeHandle, TypeContext typeContext)
     : base(member, position, reader, typeHandle, typeContext)
 {
     _methodHandle = methodHandle;
     _parameterHandle = parameterHandle;
     _parameter = parameterHandle.GetParameter(reader);
 }
        private bool TryResolveNamespaceDefinitionCaseSensitive(MetadataReader reader, string[] namespaceParts, ScopeDefinitionHandle scopeDefinitionHandle, out NamespaceDefinition namespaceDefinition)
        {
            namespaceDefinition = scopeDefinitionHandle.GetScopeDefinition(reader).RootNamespaceDefinition.GetNamespaceDefinition(reader);
            IEnumerable<NamespaceDefinitionHandle> candidates = namespaceDefinition.NamespaceDefinitions;
            int idx = namespaceParts.Length;
            while (idx-- != 0)
            {
                // Each iteration finds a match for one segment of the namespace chain.
                String expected = namespaceParts[idx];
                bool foundMatch = false;
                foreach (NamespaceDefinitionHandle candidate in candidates)
                {
                    namespaceDefinition = candidate.GetNamespaceDefinition(reader);
                    if (namespaceDefinition.Name.StringOrNullEquals(expected, reader))
                    {
                        // Found a match for this segment of the namespace chain. Move on to the next level.
                        foundMatch = true;
                        candidates = namespaceDefinition.NamespaceDefinitions;
                        break;
                    }
                }

                if (!foundMatch)
                {
                    return false;
                }
            }

            return true;
        }
        // TODO
        // bool _hasModifiers;

        public NativeFormatSignatureParser(NativeFormatMetadataUnit metadataUnit, Handle signatureHandle, MetadataReader metadataReader)
        {
            _metadataUnit = metadataUnit;
            _signatureHandle = signatureHandle;
            _metadataReader = metadataReader;
            // _hasModifiers = false;
        }
 protected RuntimeGenericParameterTypeInfo(MetadataReader reader, GenericParameterHandle genericParameterHandle)
 {
     Reader = reader;
     GenericParameterHandle = genericParameterHandle;
     _genericParameter = genericParameterHandle.GetGenericParameter(reader);
     _position = _genericParameter.Number;
 }
        public unsafe bool TryGetMetadataForNamedType(RuntimeTypeHandle runtimeTypeHandle, out MetadataReader metadataReader, out TypeDefinitionHandle typeDefHandle)
        {
            // Iterate over all modules, starting with the module that defines the EEType
            foreach (IntPtr moduleHandle in ModuleList.Enumerate(RuntimeAugments.GetModuleFromTypeHandle(runtimeTypeHandle)))
            {
                MetadataTable mapTable = MetadataTable.CreateTypeMapTable(moduleHandle);
                foreach (var ptrEntry in mapTable)
                {
                    var pCurrentEntry = (TypeMapEntry*)ptrEntry;
                    RuntimeTypeHandle entryTypeHandle = RuntimeAugments.CreateRuntimeTypeHandle(pCurrentEntry->EEType);
                    Handle entryMetadataHandle = pCurrentEntry->TypeDefinitionHandle.AsHandle();
                    if (entryTypeHandle.Equals(runtimeTypeHandle) &&
                        entryMetadataHandle.HandleType == HandleType.TypeDefinition)
                    {
                        metadataReader = ModuleList.Instance.GetMetadataReaderForModule(moduleHandle);
                        typeDefHandle = entryMetadataHandle.ToTypeDefinitionHandle(metadataReader);
                        return true;
                    }
                }
            }

            metadataReader = null;
            typeDefHandle = default(TypeDefinitionHandle);

            return false;
        }
 protected NativeFormatRuntimeGenericParameterTypeInfo(MetadataReader reader, GenericParameterHandle genericParameterHandle, GenericParameter genericParameter)
     : base(genericParameter.Number)
 {
     Reader = reader;
     GenericParameterHandle = genericParameterHandle;
     _genericParameter = genericParameter;
 }
示例#9
0
 //
 // eventHandle    - the "tkEventDef" that identifies the event.
 // definingType   - the "tkTypeDef" that defined the field (this is where you get the metadata reader that created eventHandle.)
 // contextType    - the type that supplies the type context (i.e. substitutions for generic parameters.) Though you
 //                  get your raw information from "definingType", you report "contextType" as your DeclaringType property.
 //
 //  For example:
 //
 //       typeof(Foo<>).GetTypeInfo().DeclaredMembers
 //
 //           The definingType and contextType are both Foo<>
 //
 //       typeof(Foo<int,String>).GetTypeInfo().DeclaredMembers
 //
 //          The definingType is "Foo<,>"
 //          The contextType is "Foo<int,String>"
 //
 //  We don't report any DeclaredMembers for arrays or generic parameters so those don't apply.
 //
 private RuntimeEventInfo(EventHandle eventHandle, RuntimeNamedTypeInfo definingTypeInfo, RuntimeTypeInfo contextTypeInfo)
 {
     _eventHandle = eventHandle;
     _definingTypeInfo = definingTypeInfo;
     _contextTypeInfo = contextTypeInfo;
     _reader = definingTypeInfo.Reader;
     _event = eventHandle.GetEvent(_reader);
 }
示例#10
0
 //
 // methodHandle    - the "tkMethodDef" that identifies the method.
 // definingType   - the "tkTypeDef" that defined the method (this is where you get the metadata reader that created methodHandle.)
 // contextType    - the type that supplies the type context (i.e. substitutions for generic parameters.) Though you
 //                  get your raw information from "definingType", you report "contextType" as your DeclaringType property.
 //
 //  For example:
 //
 //       typeof(Foo<>).GetTypeInfo().DeclaredMembers
 //
 //           The definingType and contextType are both Foo<>
 //
 //       typeof(Foo<int,String>).GetTypeInfo().DeclaredMembers
 //
 //          The definingType is "Foo<,>"
 //          The contextType is "Foo<int,String>"
 //
 //  We don't report any DeclaredMembers for arrays or generic parameters so those don't apply.
 //
 public RuntimeMethodCommon(MethodHandle methodHandle, RuntimeNamedTypeInfo definingTypeInfo, RuntimeTypeInfo contextTypeInfo)
 {
     _definingTypeInfo = definingTypeInfo;
     _methodHandle = methodHandle;
     _contextTypeInfo = contextTypeInfo;
     _reader = definingTypeInfo.Reader;
     _method = methodHandle.GetMethod(_reader);
 }
示例#11
0
 //
 // fieldHandle    - the "tkFieldDef" that identifies the field.
 // definingType   - the "tkTypeDef" that defined the field (this is where you get the metadata reader that created fieldHandle.)
 // contextType    - the type that supplies the type context (i.e. substitutions for generic parameters.) Though you
 //                  get your raw information from "definingType", you report "contextType" as your DeclaringType property.
 //
 //  For example:
 //
 //       typeof(Foo<>).GetTypeInfo().DeclaredMembers
 //
 //           The definingType and contextType are both Foo<>
 //
 //       typeof(Foo<int,String>).GetTypeInfo().DeclaredMembers
 //
 //          The definingType is "Foo<,>"
 //          The contextType is "Foo<int,String>"
 //
 //  We don't report any DeclaredMembers for arrays or generic parameters so those don't apply.
 //
 private RuntimeFieldInfo(FieldHandle fieldHandle, RuntimeNamedTypeInfo definingTypeInfo, RuntimeTypeInfo contextTypeInfo)
 {
     _fieldHandle = fieldHandle;
     _definingTypeInfo = definingTypeInfo;
     _contextTypeInfo = contextTypeInfo;
     _reader = definingTypeInfo.Reader;
     _field = fieldHandle.GetField(_reader);
 }
 //
 // Main routine to resolve a typeDef/Ref/Spec.
 //
 internal static RuntimeTypeInfo Resolve(this Handle typeDefRefOrSpec, MetadataReader reader, TypeContext typeContext)
 {
     Exception exception = null;
     RuntimeTypeInfo runtimeType = typeDefRefOrSpec.TryResolve(reader, typeContext, ref exception);
     if (runtimeType == null)
         throw exception;
     return runtimeType;
 }
 public static bool StringOrNullEquals(this ConstantStringValueHandle handle, String valueOrNull, MetadataReader reader)
 {
     if (valueOrNull == null)
         return handle.IsNull(reader);
     if (handle.IsNull(reader))
         return false;
     return handle.StringEquals(valueOrNull, reader);
 }
示例#14
0
 //
 // propertyHandle - the "tkPropertyDef" that identifies the property.
 // definingType   - the "tkTypeDef" that defined the field (this is where you get the metadata reader that created propertyHandle.)
 // contextType    - the type that supplies the type context (i.e. substitutions for generic parameters.) Though you
 //                  get your raw information from "definingType", you report "contextType" as your DeclaringType property.
 //
 //  For example:
 //
 //       typeof(Foo<>).GetTypeInfo().DeclaredMembers
 //
 //           The definingType and contextType are both Foo<>
 //
 //       typeof(Foo<int,String>).GetTypeInfo().DeclaredMembers
 //
 //          The definingType is "Foo<,>"
 //          The contextType is "Foo<int,String>"
 //
 //  We don't report any DeclaredMembers for arrays or generic parameters so those don't apply.
 //
 private RuntimePropertyInfo(PropertyHandle propertyHandle, RuntimeNamedTypeInfo definingTypeInfo, RuntimeTypeInfo contextTypeInfo)
 {
     _propertyHandle = propertyHandle;
     _definingTypeInfo = definingTypeInfo;
     _contextTypeInfo = contextTypeInfo;
     _reader = definingTypeInfo.Reader;
     _property = propertyHandle.GetProperty(_reader);
 }
示例#15
0
        internal NamespaceChain(MetadataReader reader, NamespaceDefinitionHandle innerMostNamespaceHandle)
        {
            NamespaceDefinition currentNamespaceDefinition = innerMostNamespaceHandle.GetNamespaceDefinition(reader);
            ConstantStringValueHandle currentNameHandle = currentNamespaceDefinition.Name;
            Handle currentNamespaceHandle = innerMostNamespaceHandle.ToHandle(reader);
            LowLevelList<String> names = new LowLevelList<String>();
            for (;;)
            {
                String name = currentNameHandle.GetStringOrNull(reader);
                names.Add(name);
                currentNamespaceHandle = currentNamespaceDefinition.ParentScopeOrNamespace;
                HandleType handleType = currentNamespaceHandle.HandleType;
                if (handleType == HandleType.ScopeDefinition)
                    break;
                if (handleType == HandleType.NamespaceDefinition)
                {
                    NamespaceDefinitionHandle nsHandle = currentNamespaceHandle.ToNamespaceDefinitionHandle(reader);
                    currentNamespaceDefinition = nsHandle.GetNamespaceDefinition(reader);
                    currentNameHandle = currentNamespaceDefinition.Name;
                    continue;
                }

                throw new BadImageFormatException(SR.Bif_InvalidMetadata);
            }

            DefiningScope = currentNamespaceHandle.ToScopeDefinitionHandle(reader);

            int count = names.Count;
            if (count == 0)
            {
                // Every namespace chain has to start with the root namespace.
                throw new BadImageFormatException();
            }
            else if (count == 1)
            {
                // The root namespace. For compat with the desktop, TypeInfo.NameSpaces returns null in this case.
                NameSpace = null;
            }
            else
            {
                // Namespace has at least one non-root component.
                StringBuilder sb = new StringBuilder();
                int idx = count - 1;
                while (idx-- != 0)
                {
                    String name = names[idx];
                    if (name == null)
                        throw new BadImageFormatException(); // null namespace fragment found in middle.
                    sb.Append(name);
                    if (idx != 0)
                        sb.Append('.');
                }
                NameSpace = sb.ToString();
            }
        }
 public static bool TryGetMethodInvokeMetadata(
     MetadataReader metadataReader,
     RuntimeTypeHandle declaringTypeHandle,
     MethodHandle methodHandle,
     RuntimeTypeHandle[] genericMethodTypeArgumentHandles,
     ref MethodSignatureComparer methodSignatureComparer,
     CanonicalFormKind canonFormKind,
     out MethodInvokeMetadata methodInvokeMetadata)
 {
     throw new NotImplementedException();
 }
示例#17
0
        private static Handle GetAttributeTypeHandle(this CustomAttribute customAttribute, MetadataReader reader)
        {
            HandleType constructorHandleType = customAttribute.Constructor.HandleType;

            if (constructorHandleType == HandleType.QualifiedMethod)
                return customAttribute.Constructor.ToQualifiedMethodHandle(reader).GetQualifiedMethod(reader).EnclosingType;
            else if (constructorHandleType == HandleType.MemberReference)
                return customAttribute.Constructor.ToMemberReferenceHandle(reader).GetMemberReference(reader).Parent;
            else
                throw new BadImageFormatException();
        }
 internal static RuntimeTypeInfo TryResolve(this Handle typeDefRefOrSpec, MetadataReader reader, TypeContext typeContext, ref Exception exception)
 {
     HandleType handleType = typeDefRefOrSpec.HandleType;
     if (handleType == HandleType.TypeDefinition)
         return typeDefRefOrSpec.ToTypeDefinitionHandle(reader).ResolveTypeDefinition(reader);
     else if (handleType == HandleType.TypeReference)
         return typeDefRefOrSpec.ToTypeReferenceHandle(reader).TryResolveTypeReference(reader, ref exception);
     else if (handleType == HandleType.TypeSpecification)
         return typeDefRefOrSpec.ToTypeSpecificationHandle(reader).TryResolveTypeSignature(reader, typeContext, ref exception);
     else
         throw new BadImageFormatException();  // Expected TypeRef, Def or Spec.
 }
示例#19
0
        /// <summary>
        /// Initialize module info and construct per-module metadata reader.
        /// </summary>
        /// <param name="moduleHandle">Handle (address) of module to initialize</param>
        internal unsafe ModuleInfo(IntPtr moduleHandle, ModuleType moduleType)
        {
            Handle = moduleHandle;
            ModuleType = moduleType;
            DynamicModulePtr = null;

            byte* pBlob;
            uint cbBlob;

            if (RuntimeAugments.FindBlob(moduleHandle, (int)ReflectionMapBlob.EmbeddedMetadata, new IntPtr(&pBlob), new IntPtr(&cbBlob)))
            {
                MetadataReader = new MetadataReader((IntPtr)pBlob, (int)cbBlob);
            }
        }
        public static unsafe bool TryGetNamedTypeForTypeReference(MetadataReader metadataReader, TypeReferenceHandle typeRefHandle, out RuntimeTypeHandle runtimeTypeHandle)
        {
            IntPtr moduleHandle = ModuleList.Instance.GetModuleForMetadataReader(metadataReader);
            MetadataTable mapTable = MetadataTable.CreateTypeMapTable(moduleHandle);
            foreach (var ptrEntry in mapTable)
            {
                TypeMapEntry* pCurrentEntry = (TypeMapEntry*)ptrEntry;
                if (pCurrentEntry->TypeDefinitionHandle.AsHandle().Equals(typeRefHandle))
                {
                    runtimeTypeHandle = RuntimeAugments.CreateRuntimeTypeHandle(pCurrentEntry->EEType);
                    return true;
                }
            }

            runtimeTypeHandle = default(RuntimeTypeHandle);
            return false;
        }
        private static void AppendNamespaceHashCode(ref HashCodeBuilder builder, NamespaceReferenceHandle namespaceRefHandle, MetadataReader reader)
        {
            NamespaceReference namespaceReference = reader.GetNamespaceReference(namespaceRefHandle);

            Handle parentHandle = namespaceReference.ParentScopeOrNamespace;
            HandleType parentHandleType = parentHandle.HandleType;
            if (parentHandleType == HandleType.NamespaceReference)
            {
                AppendNamespaceHashCode(ref builder, parentHandle.ToNamespaceReferenceHandle(reader), reader);
                string namespaceNamePart = reader.GetString(namespaceReference.Name);
                builder.Append(namespaceNamePart);
                builder.Append(".");
            }
            else
            {
                Debug.Assert(parentHandleType == HandleType.ScopeReference);
                Debug.Assert(String.IsNullOrEmpty(reader.GetString(namespaceReference.Name)), "Root namespace with a name?");
            }
        }
        /// <summary>
        /// Try to look up field acccess info for given canon in metadata blobs for all available modules.
        /// </summary>
        /// <param name="metadataReader">Metadata reader for the declaring type</param>
        /// <param name="declaringTypeHandle">Declaring type for the method</param>
        /// <param name="fieldHandle">Field handle</param>
        /// <param name="canonFormKind">Canonical form to use</param>
        /// <param name="fieldAccessMetadata">Output - metadata information for field accessor construction</param>
        /// <returns>true when found, false otherwise</returns>
        public static bool TryGetFieldAccessMetadata(
            MetadataReader metadataReader,
            RuntimeTypeHandle runtimeTypeHandle,
            FieldHandle fieldHandle,
            out FieldAccessMetadata fieldAccessMetadata)
        {
            fieldAccessMetadata = default(FieldAccessMetadata);

            if (TryGetFieldAccessMetadataFromFieldAccessMap(
                metadataReader,
                runtimeTypeHandle,
                fieldHandle,
                CanonicalFormKind.Specific,
                ref fieldAccessMetadata))
            {
                return true;
            }

            if (TryGetFieldAccessMetadataFromFieldAccessMap(
                metadataReader,
                runtimeTypeHandle,
                fieldHandle,
                CanonicalFormKind.Universal,
                ref fieldAccessMetadata))
            {
                return true;
            }

            TypeSystemContext context = TypeSystemContextFactory.Create();

            bool success = TryGetFieldAccessMetadataFromNativeFormatMetadata(
                metadataReader,
                runtimeTypeHandle,
                fieldHandle,
                context,
                ref fieldAccessMetadata);

            TypeSystemContextFactory.Recycle(context);

            return success;
        }
示例#23
0
        public unsafe void TestDefinitionHashCodes()
        {
            var wr = new Writer.MetadataWriter();

            wr.ScopeDefinitions.Add(BuildSimpleTestDefinitionData());
            var ms = new MemoryStream();

            wr.Write(ms);

            fixed(byte *pBuffer = ms.ToArray())
            {
                var rd = new Reader.MetadataReader((IntPtr)pBuffer, (int)ms.Length);

                Reader.ScopeDefinitionHandle scopeHandle        = rd.ScopeDefinitions.Single();
                Reader.ScopeDefinition       systemRuntimeScope = scopeHandle.GetScopeDefinition(rd);

                // Validate root type hash code
                Reader.NamespaceDefinition  rootNamespace    = systemRuntimeScope.RootNamespaceDefinition.GetNamespaceDefinition(rd);
                Reader.TypeDefinitionHandle moduleTypeHandle = rootNamespace.TypeDefinitions.Single();
                Assert.Equal(TypeHashingAlgorithms.ComputeNameHashCode("<Module>"), MetadataTypeHashingAlgorithms.ComputeHashCode(moduleTypeHandle, rd));

                // Validate namespace type hashcode
                Reader.NamespaceDefinition  systemNamespace  = rootNamespace.NamespaceDefinitions.Single().GetNamespaceDefinition(rd);
                Reader.TypeDefinitionHandle objectTypeHandle = systemNamespace.TypeDefinitions.Single();
                int objectHashCode = TypeHashingAlgorithms.ComputeNameHashCode("System.Object");

                Assert.Equal(objectHashCode, MetadataTypeHashingAlgorithms.ComputeHashCode(objectTypeHandle, rd));

                // Validate nested type hashcode
                Reader.TypeDefinitionHandle nestedTypeHandle = objectTypeHandle.GetTypeDefinition(rd).NestedTypes.Single();
                int nestedHashCode = TypeHashingAlgorithms.ComputeNestedTypeHashCode(objectHashCode, TypeHashingAlgorithms.ComputeNameHashCode("Nested"));

                Assert.Equal(nestedHashCode, MetadataTypeHashingAlgorithms.ComputeHashCode(nestedTypeHandle, rd));

                // Validate really nested type hashcode
                Reader.TypeDefinitionHandle reallyNestedTypeHandle = nestedTypeHandle.GetTypeDefinition(rd).NestedTypes.Single();
                int reallyNestedHashCode = TypeHashingAlgorithms.ComputeNestedTypeHashCode(nestedHashCode, TypeHashingAlgorithms.ComputeNameHashCode("ReallyNested"));

                Assert.Equal(reallyNestedHashCode, MetadataTypeHashingAlgorithms.ComputeHashCode(reallyNestedTypeHandle, rd));
            }
        }
示例#24
0
        //
        // This is a port of the desktop CLR's RuntimeType.FormatTypeName() routine. This routine is used by various Reflection ToString() methods
        // to display the name of a type. Do not use for any other purpose as it inherits some pretty quirky desktop behavior.
        //
        // The Project N version takes a raw metadata handle rather than a completed type so that it remains robust in the face of missing metadata.
        //
        public static String FormatTypeName(this Handle typeDefRefOrSpecHandle, MetadataReader reader, TypeContext typeContext)
        {
            try
            {
                // Though we wrap this in a try-catch as a failsafe, this code must still strive to avoid triggering MissingMetadata exceptions
                // (non-error exceptions are very annoying when debugging.)

                Exception exception = null;
                RuntimeTypeInfo runtimeType = typeDefRefOrSpecHandle.TryResolve(reader, typeContext, ref exception);
                if (runtimeType == null)
                    return UnavailableType;

                // Because this runtimeType came from a successful TryResolve() call, it is safe to querying the TypeInfo's of the type and its component parts.
                // If we're wrong, we do have the safety net of a try-catch.
                return runtimeType.FormatTypeName();
            }
            catch (Exception)
            {
                return UnavailableType;
            }
        }
        public static int ComputeHashCode(this TypeDefinitionHandle typeDefHandle, MetadataReader reader)
        {
            HashCodeBuilder builder = new HashCodeBuilder("");

            TypeDefinition typeDef = reader.GetTypeDefinition(typeDefHandle);
            bool isNested = typeDef.Flags.IsNested();
            if (!isNested)
            {
                AppendNamespaceHashCode(ref builder, typeDef.NamespaceDefinition, reader);
            }

            string typeName = reader.GetString(typeDef.Name);
            builder.Append(typeName);

            if (isNested)
            {
                int enclosingTypeHashCode = typeDef.EnclosingType.ComputeHashCode(reader);
                return TypeHashingAlgorithms.ComputeNestedTypeHashCode(enclosingTypeHashCode, builder.ToHashCode());
            }

            return builder.ToHashCode();
        }
示例#26
0
        public unsafe static void TestCommonTailOptimization()
        {
            var wr = new Writer.MetadataWriter();

            wr.ScopeDefinitions.Add(BuildSimpleTestData());
            var ms = new MemoryStream();

            wr.Write(ms);

            fixed(byte *pBuffer = ms.ToArray())
            {
                var rd = new Reader.MetadataReader((IntPtr)pBuffer, (int)ms.Length);

                Reader.ScopeDefinitionHandle scopeHandle        = rd.ScopeDefinitions.Single();
                Reader.ScopeDefinition       systemRuntimeScope = scopeHandle.GetScopeDefinition(rd);
                Reader.NamespaceDefinition   rootNamespace      = systemRuntimeScope.RootNamespaceDefinition.GetNamespaceDefinition(rd);
                Reader.NamespaceDefinition   systemNamespace    =
                    rootNamespace.NamespaceDefinitions.Single(
                        ns => ns.GetNamespaceDefinition(rd).Name.StringEquals("System", rd)
                        ).GetNamespaceDefinition(rd);

                // This validates the common tail optimization.
                // Since both System.Object and System.String define a default constructor and the
                // records are structurally equivalent, there should only be one metadata record
                // representing a default .ctor in the blob.
                Reader.TypeDefinition objectType = systemNamespace.TypeDefinitions.Single(
                    t => t.GetTypeDefinition(rd).Name.StringEquals("Object", rd)
                    ).GetTypeDefinition(rd);
                Reader.TypeDefinition stringType = systemNamespace.TypeDefinitions.Single(
                    t => t.GetTypeDefinition(rd).Name.StringEquals("String", rd)
                    ).GetTypeDefinition(rd);

                Reader.MethodHandle objectCtor = objectType.Methods.Single();
                Reader.MethodHandle stringCtor = stringType.Methods.Single();

                Assert.True(objectCtor.Equals(stringCtor));
            }
        }
        public unsafe bool TryGetMetadataForNamedType(RuntimeTypeHandle runtimeTypeHandle, out MetadataReader metadataReader, out TypeDefinitionHandle typeDefHandle)
        {
            // Iterate over all modules, starting with the module that defines the EEType
            foreach (IntPtr moduleHandle in ModuleList.Enumerate(RuntimeAugments.GetModuleFromTypeHandle(runtimeTypeHandle)))
            {
                NativeReader typeMapReader;
                if (TryGetNativeReaderForBlob(moduleHandle, ReflectionMapBlob.TypeMap, out typeMapReader))
                {
                    NativeParser typeMapParser = new NativeParser(typeMapReader, 0);
                    NativeHashtable typeHashtable = new NativeHashtable(typeMapParser);

                    ExternalReferencesTable externalReferences = default(ExternalReferencesTable);
                    externalReferences.InitializeCommonFixupsTable(moduleHandle);

                    var lookup = typeHashtable.Lookup(runtimeTypeHandle.GetHashCode());
                    NativeParser entryParser;
                    while (!(entryParser = lookup.GetNext()).IsNull)
                    {
                        RuntimeTypeHandle foundType = externalReferences.GetRuntimeTypeHandleFromIndex(entryParser.GetUnsigned());
                        if (foundType.Equals(runtimeTypeHandle))
                        {
                            Handle entryMetadataHandle = entryParser.GetUnsigned().AsHandle();
                            if (entryMetadataHandle.HandleType == HandleType.TypeDefinition)
                            {
                                metadataReader = ModuleList.Instance.GetMetadataReaderForModule(moduleHandle);
                                typeDefHandle = entryMetadataHandle.ToTypeDefinitionHandle(metadataReader);
                                return true;
                            }
                        }
                    }
                }
            }

            metadataReader = null;
            typeDefHandle = default(TypeDefinitionHandle);

            return false;
        }
示例#28
0
        /// <summary>
        /// Initialize module info and construct per-module metadata reader.
        /// </summary>
        /// <param name="moduleHandle">Handle (address) of module to initialize</param>
        internal ModuleInfo(IntPtr moduleHandle, ModuleType moduleType)
        {
            Handle = moduleHandle;
            ModuleType = moduleType;

            byte* pBlob;
            uint cbBlob;

            if (RuntimeAugments.FindBlob(moduleHandle, (int)ReflectionMapBlob.EmbeddedMetadata, new IntPtr(&pBlob), new IntPtr(&cbBlob)))
            {
                MetadataReader = new MetadataReader((IntPtr)pBlob, (int)cbBlob);
            }

            DynamicModule* dynamicModulePtr = (DynamicModule*)MemoryHelpers.AllocateMemory(sizeof(DynamicModule));
            dynamicModulePtr->CbSize = DynamicModule.DynamicModuleSize;
            Debug.Assert(sizeof(DynamicModule) >= dynamicModulePtr->CbSize);

#if SUPPORTS_R2R_LOADING                
            if (moduleType == ModuleType.ReadyToRun)
            {
                // ReadyToRun modules utilize dynamic type resolution
                dynamicModulePtr->DynamicTypeSlotDispatchResolve = Intrinsics.AddrOf(
                    (Func<IntPtr, IntPtr, ushort, IntPtr>)ReadyToRunCallbacks.ResolveTypeSlotDispatch);
            }
            else
#endif
            {
                Debug.Assert(moduleType == ModuleType.Eager);
                // Pre-generated modules do not
                dynamicModulePtr->DynamicTypeSlotDispatchResolve = IntPtr.Zero;
            }

            dynamicModulePtr->GetRuntimeException = Intrinsics.AddrOf(
                (Func<ExceptionIDs, Exception>)RuntimeExceptionHelpers.GetRuntimeException);

            DynamicModulePtr = dynamicModulePtr;
        }
示例#29
0
        public unsafe void TestDefinitionHashCodes()
        {
            var wr = new Writer.MetadataWriter();
            wr.ScopeDefinitions.Add(BuildSimpleTestDefinitionData());
            var ms = new MemoryStream();
            wr.Write(ms);

            fixed (byte* pBuffer = ms.ToArray())
            {
                var rd = new Reader.MetadataReader((IntPtr)pBuffer, (int)ms.Length);

                Reader.ScopeDefinitionHandle scopeHandle = rd.ScopeDefinitions.Single();
                Reader.ScopeDefinition systemRuntimeScope = scopeHandle.GetScopeDefinition(rd);

                // Validate root type hash code
                Reader.NamespaceDefinition rootNamespace = systemRuntimeScope.RootNamespaceDefinition.GetNamespaceDefinition(rd);
                Reader.TypeDefinitionHandle moduleTypeHandle = rootNamespace.TypeDefinitions.Single();
                Assert.Equal(TypeHashingAlgorithms.ComputeNameHashCode("<Module>"), MetadataTypeHashingAlgorithms.ComputeHashCode(moduleTypeHandle, rd));

                // Validate namespace type hashcode
                Reader.NamespaceDefinition systemNamespace = rootNamespace.NamespaceDefinitions.Single().GetNamespaceDefinition(rd);
                Reader.TypeDefinitionHandle objectTypeHandle = systemNamespace.TypeDefinitions.Single();
                int objectHashCode = TypeHashingAlgorithms.ComputeNameHashCode("System.Object");
                Assert.Equal(objectHashCode, MetadataTypeHashingAlgorithms.ComputeHashCode(objectTypeHandle, rd));

                // Validate nested type hashcode
                Reader.TypeDefinitionHandle nestedTypeHandle = objectTypeHandle.GetTypeDefinition(rd).NestedTypes.Single();
                int nestedHashCode = TypeHashingAlgorithms.ComputeNestedTypeHashCode(objectHashCode, TypeHashingAlgorithms.ComputeNameHashCode("Nested"));
                Assert.Equal(nestedHashCode, MetadataTypeHashingAlgorithms.ComputeHashCode(nestedTypeHandle, rd));

                // Validate really nested type hashcode
                Reader.TypeDefinitionHandle reallyNestedTypeHandle = nestedTypeHandle.GetTypeDefinition(rd).NestedTypes.Single();
                int reallyNestedHashCode = TypeHashingAlgorithms.ComputeNestedTypeHashCode(nestedHashCode, TypeHashingAlgorithms.ComputeNameHashCode("ReallyNested"));
                Assert.Equal(reallyNestedHashCode, MetadataTypeHashingAlgorithms.ComputeHashCode(reallyNestedTypeHandle, rd));
            }
        }
        public static int ComputeHashCode(this TypeReferenceHandle typeRefHandle, MetadataReader reader)
        {
            HashCodeBuilder builder = new HashCodeBuilder("");

            TypeReference typeRef = reader.GetTypeReference(typeRefHandle);
            HandleType parentHandleType = typeRef.ParentNamespaceOrType.HandleType;
            bool isNested = parentHandleType == HandleType.TypeReference;
            if (!isNested)
            {
                Debug.Assert(parentHandleType == HandleType.NamespaceReference);
                AppendNamespaceHashCode(ref builder, typeRef.ParentNamespaceOrType.ToNamespaceReferenceHandle(reader), reader);
            }

            string typeName = reader.GetString(typeRef.TypeName);
            builder.Append(typeName);

            if (isNested)
            {
                int enclosingTypeHashCode = typeRef.ParentNamespaceOrType.ToTypeReferenceHandle(reader).ComputeHashCode(reader);
                return TypeHashingAlgorithms.ComputeNestedTypeHashCode(enclosingTypeHashCode, builder.ToHashCode());
            }

            return builder.ToHashCode();
        }
示例#31
0
        public static unsafe void TestCommonTailOptimization()
        {
            var wr = new Writer.MetadataWriter();
            wr.ScopeDefinitions.Add(BuildSimpleTestData());
            var ms = new MemoryStream();
            wr.Write(ms);

            fixed (byte* pBuffer = ms.ToArray())
            {
                var rd = new Reader.MetadataReader((IntPtr)pBuffer, (int)ms.Length);

                Reader.ScopeDefinitionHandle scopeHandle = rd.ScopeDefinitions.Single();
                Reader.ScopeDefinition systemRuntimeScope = scopeHandle.GetScopeDefinition(rd);
                Reader.NamespaceDefinition rootNamespace = systemRuntimeScope.RootNamespaceDefinition.GetNamespaceDefinition(rd);
                Reader.NamespaceDefinition systemNamespace =
                    rootNamespace.NamespaceDefinitions.Single(
                        ns => ns.GetNamespaceDefinition(rd).Name.StringEquals("System", rd)
                        ).GetNamespaceDefinition(rd);

                // This validates the common tail optimization.
                // Since both System.Object and System.String define a default constructor and the
                // records are structurally equivalent, there should only be one metadata record
                // representing a default .ctor in the blob.
                Reader.TypeDefinition objectType = systemNamespace.TypeDefinitions.Single(
                    t => t.GetTypeDefinition(rd).Name.StringEquals("Object", rd)
                    ).GetTypeDefinition(rd);
                Reader.TypeDefinition stringType = systemNamespace.TypeDefinitions.Single(
                    t => t.GetTypeDefinition(rd).Name.StringEquals("String", rd)
                    ).GetTypeDefinition(rd);

                Reader.MethodHandle objectCtor = objectType.Methods.Single();
                Reader.MethodHandle stringCtor = stringType.Methods.Single();

                Assert.True(objectCtor.Equals(stringCtor));
            }
        }
示例#32
0
        public unsafe static void TestSimpleRoundTripping()
        {
            var wr = new Writer.MetadataWriter();

            wr.ScopeDefinitions.Add(BuildSimpleTestData());
            var ms = new MemoryStream();

            wr.Write(ms);

            fixed(byte *pBuffer = ms.ToArray())
            {
                var rd = new Reader.MetadataReader((IntPtr)pBuffer, (int)ms.Length);

                // Validate the System.Runtime scope
                Reader.ScopeDefinitionHandle scopeHandle        = rd.ScopeDefinitions.Single();
                Reader.ScopeDefinition       systemRuntimeScope = scopeHandle.GetScopeDefinition(rd);
                Assert.Equal(4, systemRuntimeScope.MajorVersion);
                Assert.Equal("System.Runtime", systemRuntimeScope.Name.GetConstantStringValue(rd).Value);

                // Validate the root namespace and <Module> type
                Reader.NamespaceDefinition rootNamespace = systemRuntimeScope.RootNamespaceDefinition.GetNamespaceDefinition(rd);
                Assert.Equal(1, rootNamespace.TypeDefinitions.Count());
                Reader.TypeDefinition moduleType = rootNamespace.TypeDefinitions.Single().GetTypeDefinition(rd);
                Assert.Equal("<Module>", moduleType.Name.GetConstantStringValue(rd).Value);
                Assert.Equal(1, rootNamespace.NamespaceDefinitions.Count());

                // Validate the System namespace
                Reader.NamespaceDefinition systemNamespace = rootNamespace.NamespaceDefinitions.Single().GetNamespaceDefinition(rd);
                Assert.Equal(4, systemNamespace.TypeDefinitions.Count());
                foreach (var typeHandle in systemNamespace.TypeDefinitions)
                {
                    Reader.TypeDefinition type = typeHandle.GetTypeDefinition(rd);
                    string typeName            = type.Name.GetConstantStringValue(rd).Value;

                    string baseTypeName = null;
                    if (!type.BaseType.IsNull(rd))
                    {
                        baseTypeName = type.BaseType.ToTypeDefinitionHandle(rd).GetTypeDefinition(rd).Name.GetConstantStringValue(rd).Value;
                    }

                    switch (typeName)
                    {
                    case "Object":
                        Assert.Null(baseTypeName);
                        Assert.Equal(1, type.Methods.Count());
                        break;

                    case "Void":
                        Assert.Equal("ValueType", baseTypeName);
                        Assert.Equal(0, type.Methods.Count());
                        break;

                    case "String":
                        Assert.Equal("Object", baseTypeName);
                        Assert.Equal(1, type.Methods.Count());
                        break;

                    case "ValueType":
                        Assert.Equal("Object", baseTypeName);
                        Assert.Equal(0, type.Methods.Count());
                        break;

                    default:
                        throw new NotImplementedException();
                    }
                }
            }
        }
示例#33
0
 public bool IsNull(MetadataReader reader)
 {
     return(reader.IsNull(this));
 }
示例#34
0
 public static string GetString(this MetadataReader reader, ConstantStringValueHandle handle)
 {
     return(reader.GetConstantStringValue(handle).Value);
 }
示例#35
0
 public bool StringEquals(string value, MetadataReader reader)
 {
     return(reader.StringEquals(this, value));
 }
示例#36
0
        public unsafe void TestReferenceHashCodes()
        {
            var wr = new Writer.MetadataWriter();

            var systemRuntimeScopeRecord = new Writer.ScopeReference
            {
                Name         = (Writer.ConstantStringValue) "System.Runtime",
                MajorVersion = 4,
            };

            var rootNamespaceRecord = new Writer.NamespaceReference
            {
                Name = null,
                ParentScopeOrNamespace = systemRuntimeScopeRecord,
            };

            var fooTypeRecord = new Writer.TypeReference
            {
                ParentNamespaceOrType = rootNamespaceRecord,
                TypeName = (Writer.ConstantStringValue) "Foo",
            };

            var nestedTypeRecord = new Writer.TypeReference
            {
                ParentNamespaceOrType = fooTypeRecord,
                TypeName = (Writer.ConstantStringValue) "Nested",
            };

            var reallyNestedTypeRecord = new Writer.TypeReference
            {
                ParentNamespaceOrType = nestedTypeRecord,
                TypeName = (Writer.ConstantStringValue) "ReallyNested",
            };

            var systemNamespaceRecord = new Writer.NamespaceReference
            {
                Name = (Writer.ConstantStringValue) "System",
                ParentScopeOrNamespace = rootNamespaceRecord,
            };

            var objectTypeRecord = new Writer.TypeReference
            {
                ParentNamespaceOrType = systemNamespaceRecord,
                TypeName = (Writer.ConstantStringValue) "Object",
            };

            wr.AdditionalRootRecords.Add(objectTypeRecord);
            wr.AdditionalRootRecords.Add(fooTypeRecord);
            wr.AdditionalRootRecords.Add(nestedTypeRecord);
            wr.AdditionalRootRecords.Add(reallyNestedTypeRecord);
            var ms = new MemoryStream();

            wr.Write(ms);

            fixed(byte *pBuffer = ms.ToArray())
            {
                var rd = new Reader.MetadataReader((IntPtr)pBuffer, (int)ms.Length);

                var fooTypeHandle   = new Reader.TypeReferenceHandle(wr.GetRecordHandle(fooTypeRecord));
                var fooTypeHashCode = TypeHashingAlgorithms.ComputeNameHashCode("Foo");

                Assert.Equal(fooTypeHashCode, MetadataTypeHashingAlgorithms.ComputeHashCode(fooTypeHandle, rd));

                var objectTypeHandle = new Reader.TypeReferenceHandle(wr.GetRecordHandle(objectTypeRecord));

                Assert.Equal(TypeHashingAlgorithms.ComputeNameHashCode("System.Object"), MetadataTypeHashingAlgorithms.ComputeHashCode(objectTypeHandle, rd));

                var nestedTypeHandle   = new Reader.TypeReferenceHandle(wr.GetRecordHandle(nestedTypeRecord));
                var nestedTypeHashCode = TypeHashingAlgorithms.ComputeNestedTypeHashCode(fooTypeHashCode, TypeHashingAlgorithms.ComputeNameHashCode("Nested"));

                Assert.Equal(nestedTypeHashCode, MetadataTypeHashingAlgorithms.ComputeHashCode(nestedTypeHandle, rd));

                var reallyNestedTypeHandle   = new Reader.TypeReferenceHandle(wr.GetRecordHandle(reallyNestedTypeRecord));
                var reallyNestedTypeHashCode = TypeHashingAlgorithms.ComputeNestedTypeHashCode(nestedTypeHashCode, TypeHashingAlgorithms.ComputeNameHashCode("ReallyNested"));

                Assert.Equal(reallyNestedTypeHashCode, MetadataTypeHashingAlgorithms.ComputeHashCode(reallyNestedTypeHandle, rd));
            }
        }
示例#37
0
        public unsafe static void TestSimpleRoundTripping()
        {
            var wr = new Writer.MetadataWriter();
            wr.ScopeDefinitions.Add(BuildSimpleTestData());
            var ms = new MemoryStream();
            wr.Write(ms);
            
            fixed (byte* pBuffer = ms.ToArray())
            {
                var rd = new Reader.MetadataReader((IntPtr)pBuffer, (int)ms.Length);

                // Validate the System.Runtime scope
                Reader.ScopeDefinitionHandle scopeHandle = rd.ScopeDefinitions.Single();
                Reader.ScopeDefinition systemRuntimeScope = scopeHandle.GetScopeDefinition(rd);
                Assert.Equal(4, systemRuntimeScope.MajorVersion);
                Assert.Equal("System.Runtime", systemRuntimeScope.Name.GetConstantStringValue(rd).Value);

                // Validate the root namespace and <Module> type
                Reader.NamespaceDefinition rootNamespace = systemRuntimeScope.RootNamespaceDefinition.GetNamespaceDefinition(rd);
                Assert.Equal(1, rootNamespace.TypeDefinitions.Count());
                Reader.TypeDefinition moduleType = rootNamespace.TypeDefinitions.Single().GetTypeDefinition(rd);
                Assert.Equal("<Module>", moduleType.Name.GetConstantStringValue(rd).Value);
                Assert.Equal(1, rootNamespace.NamespaceDefinitions.Count());

                // Validate the System namespace
                Reader.NamespaceDefinition systemNamespace = rootNamespace.NamespaceDefinitions.Single().GetNamespaceDefinition(rd);
                Assert.Equal(4, systemNamespace.TypeDefinitions.Count());
                foreach (var typeHandle in systemNamespace.TypeDefinitions)
                {
                    Reader.TypeDefinition type = typeHandle.GetTypeDefinition(rd);
                    string typeName = type.Name.GetConstantStringValue(rd).Value;

                    string baseTypeName = null;
                    if (!type.BaseType.IsNull(rd))
                    {
                        baseTypeName = type.BaseType.ToTypeDefinitionHandle(rd).GetTypeDefinition(rd).Name.GetConstantStringValue(rd).Value;
                    }

                    switch (typeName)
                    {
                        case "Object":
                            Assert.Null(baseTypeName);
                            Assert.Equal(1, type.Methods.Count());
                            break;
                        case "Void":
                            Assert.Equal("ValueType", baseTypeName);
                            Assert.Equal(0, type.Methods.Count());
                            break;
                        case "String":
                            Assert.Equal("Object", baseTypeName);
                            Assert.Equal(1, type.Methods.Count());
                            break;
                        case "ValueType":
                            Assert.Equal("Object", baseTypeName);
                            Assert.Equal(0, type.Methods.Count());
                            break;
                        default:
                            throw new NotImplementedException();
                    }
                }
            }
        }
        private static void AppendNamespaceHashCode(ref HashCodeBuilder builder, NamespaceReferenceHandle namespaceRefHandle, MetadataReader reader)
        {
            NamespaceReference namespaceReference = reader.GetNamespaceReference(namespaceRefHandle);

            Handle     parentHandle     = namespaceReference.ParentScopeOrNamespace;
            HandleType parentHandleType = parentHandle.HandleType;

            if (parentHandleType == HandleType.NamespaceReference)
            {
                AppendNamespaceHashCode(ref builder, parentHandle.ToNamespaceReferenceHandle(reader), reader);
                string namespaceNamePart = reader.GetString(namespaceReference.Name);
                builder.Append(namespaceNamePart);
                builder.Append(".");
            }
            else
            {
                Debug.Assert(parentHandleType == HandleType.ScopeReference);
                Debug.Assert(string.IsNullOrEmpty(reader.GetString(namespaceReference.Name)), "Root namespace with a name?");
            }
        }