Ejemplo n.º 1
0
    public static void  RuntimeTypeHandleTest()
    {
        RuntimeTypeHandle h = typeof(int).TypeHandle;

        Assert.NotEqual(h, typeof(uint).TypeHandle);

        Assert.True(h.Value != IntPtr.Zero);

        Assert.Equal(h.GetHashCode(), h.GetHashCode());
        Assert.Equal(default(RuntimeTypeHandle).GetHashCode(), default(RuntimeTypeHandle).GetHashCode());

        Assert.True(h.Equals(h));
        Assert.False(h.Equals(default(RuntimeTypeHandle)));
        Assert.False(default(RuntimeTypeHandle).Equals(h));
        Assert.True(default(RuntimeTypeHandle).Equals(default(RuntimeTypeHandle)));

        Assert.True(h.Equals((object)h));
        Assert.False(h.Equals(typeof(int)));
        Assert.False(h.Equals(new object()));
        Assert.False(h.Equals(null));

        Assert.False(h == null);
        Assert.False(null == h);
        Assert.True(h != null);
        Assert.True(null != h);
    }
Ejemplo n.º 2
0
    public static void  RuntimeTypeHandleTest()
    {
        RuntimeTypeHandle h = typeof(int).TypeHandle;

        Assert.NotEqual(h, typeof(uint).TypeHandle);

        Assert.True(h.Value != IntPtr.Zero);

        Assert.Equal(h.GetHashCode(), h.GetHashCode());
        Assert.Equal(default(RuntimeTypeHandle).GetHashCode(), default(RuntimeTypeHandle).GetHashCode());

        Assert.True(h.Equals(h));
        Assert.False(h.Equals(default(RuntimeTypeHandle)));
        Assert.False(default(RuntimeTypeHandle).Equals(h));
        Assert.True(default(RuntimeTypeHandle).Equals(default(RuntimeTypeHandle)));

        Assert.True(h.Equals((object)h));
        Assert.True(((IEquatable <RuntimeTypeHandle>)h).Equals(h));
        Assert.False(h.Equals(typeof(int)));
        Assert.False(h.Equals(new object()));
        Assert.False(h.Equals(null));

        Assert.False(h == null);
        Assert.False(null == h);
        Assert.True(h != null);
        Assert.True(null != h);

        IntPtr            hPtr = RuntimeTypeHandle.ToIntPtr(h);
        RuntimeTypeHandle hNew = RuntimeTypeHandle.FromIntPtr(hPtr);

        Assert.True(h.Equals(hNew));
        Assert.True(hNew.Equals(h));
    }
        internal virtual void InternalSerialize(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
#endif
        {
            if (writeXsiType)
            {
                Type declaredType = Globals.TypeOfObject;
                SerializeWithXsiType(xmlWriter, obj, obj.GetType().TypeHandle, null /*type*/, -1, declaredType.TypeHandle, declaredType);
            }
            else if (isDeclaredType)
            {
                DataContract contract = GetDataContract(declaredTypeID, declaredTypeHandle);
                SerializeWithoutXsiType(contract, xmlWriter, obj, declaredTypeHandle);
            }
            else
            {
                RuntimeTypeHandle objTypeHandle = obj.GetType().TypeHandle;
                if (declaredTypeHandle.GetHashCode() == objTypeHandle.GetHashCode()) // semantically the same as Value == Value; Value is not available in SL
                {
                    DataContract dataContract = (declaredTypeID >= 0)
                        ? GetDataContract(declaredTypeID, declaredTypeHandle)
                        : GetDataContract(declaredTypeHandle, null /*type*/);
                    SerializeWithoutXsiType(dataContract, xmlWriter, obj, declaredTypeHandle);
                }
                else
                {
                    SerializeWithXsiType(xmlWriter, obj, objTypeHandle, null /*type*/, declaredTypeID, declaredTypeHandle, Type.GetTypeFromHandle(declaredTypeHandle));
                }
            }
        }
Ejemplo n.º 4
0
 /// <summary>
 ///  Setter for RuntimeTypeHandle. Seperate from normal property as all uses should be done with great care.
 ///  Must not be set with partially constructed type handles
 /// </summary>
 public void SetRuntimeTypeHandleUnsafe(RuntimeTypeHandle runtimeTypeHandle)
 {
     Debug.Assert(!runtimeTypeHandle.IsNull());
     Debug.Assert(_runtimeTypeHandle.IsNull() || runtimeTypeHandle.Equals(_runtimeTypeHandle));
     Debug.Assert(runtimeTypeHandle.GetHashCode() == GetHashCode());
     _runtimeTypeHandle = runtimeTypeHandle;
 }
        private unsafe bool TryGetStructData(RuntimeTypeHandle structTypeHandle, out ExternalReferencesTable externalReferences, out NativeParser entryParser)
        {
            int structHashcode = structTypeHandle.GetHashCode();

            externalReferences = default(ExternalReferencesTable);
            entryParser        = default(NativeParser);
            foreach (NativeFormatModuleInfo module in ModuleList.EnumerateModules())
            {
                NativeReader structMapReader;
                if (TryGetNativeReaderForBlob(module, ReflectionMapBlob.StructMarshallingStubMap, out structMapReader))
                {
                    NativeParser    structMapParser = new NativeParser(structMapReader, 0);
                    NativeHashtable structHashtable = new NativeHashtable(structMapParser);

                    externalReferences.InitializeCommonFixupsTable(module);

                    var lookup = structHashtable.Lookup(structHashcode);
                    while (!(entryParser = lookup.GetNext()).IsNull)
                    {
                        RuntimeTypeHandle foundStructType = externalReferences.GetRuntimeTypeHandleFromIndex(entryParser.GetUnsigned());
                        if (foundStructType.Equals(structTypeHandle))
                        {
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
        public bool TryLookupExactMethodPointerForComponents(RuntimeTypeHandle declaringType, MethodNameAndSignature nameAndSignature, RuntimeTypeHandle[] genericMethodArgumentHandles, out IntPtr result)
        {
            int lookupHashcode = declaringType.GetHashCode();

            NativeHashtable         hashtable;
            ExternalReferencesTable externalReferencesLookup;

            HandleBasedGenericMethodLookup lookupData = new HandleBasedGenericMethodLookup(declaringType, nameAndSignature, genericMethodArgumentHandles);

            foreach (NativeFormatModuleInfo module in ModuleList.EnumerateModules())
            {
                if (!GetHashtableFromBlob(module, ReflectionMapBlob.ExactMethodInstantiationsHashtable, out hashtable, out externalReferencesLookup))
                {
                    continue;
                }

                var enumerator = hashtable.Lookup(lookupHashcode);

                NativeParser entryParser;
                while (!(entryParser = enumerator.GetNext()).IsNull)
                {
                    if (!lookupData.MatchParsedEntry(ref entryParser, ref externalReferencesLookup, module.Handle))
                    {
                        continue;
                    }

                    // We found a match
                    result = externalReferencesLookup.GetIntPtrFromIndex(entryParser.GetUnsigned());
                    return(true);
                }
            }

            result = IntPtr.Zero;
            return(false);
        }
Ejemplo n.º 7
0
        public unsafe IntPtr TryGetMarshallerForDelegate(RuntimeTypeHandle delegateTypeHandle)
        {
            int delegateHashcode = delegateTypeHandle.GetHashCode();

            foreach (NativeFormatModuleInfo module in ModuleList.EnumerateModules())
            {
                NativeReader delegateMapReader;
                if (TryGetNativeReaderForBlob(module, ReflectionMapBlob.DelegateMarshallingStubMap, out delegateMapReader))
                {
                    NativeParser    delegateMapParser = new NativeParser(delegateMapReader, 0);
                    NativeHashtable delegateHashtable = new NativeHashtable(delegateMapParser);

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

                    var          lookup = delegateHashtable.Lookup(delegateHashcode);
                    NativeParser entryParser;
                    while (!(entryParser = lookup.GetNext()).IsNull)
                    {
                        RuntimeTypeHandle foundDelegateType = externalReferences.GetRuntimeTypeHandleFromIndex(entryParser.GetUnsigned());
                        if (foundDelegateType.Equals(delegateTypeHandle))
                        {
                            byte *pByte = (byte *)externalReferences.GetIntPtrFromIndex(entryParser.GetUnsigned());
                            return((IntPtr)pByte);
                        }
                    }
                }
            }

            return(IntPtr.Zero);
        }
Ejemplo n.º 8
0
        private NativeParser GetStaticInfo(RuntimeTypeHandle instantiatedType, out ExternalReferencesTable staticsInfoLookup)
        {
            TypeManagerHandle       moduleHandle = RuntimeAugments.GetModuleFromTypeHandle(instantiatedType);
            NativeFormatModuleInfo  module       = ModuleList.Instance.GetModuleInfoByHandle(moduleHandle);
            NativeHashtable         staticsInfoHashtable;
            ExternalReferencesTable externalReferencesLookup;

            if (!GetStaticsInfoHashtable(module, out staticsInfoHashtable, out externalReferencesLookup, out staticsInfoLookup))
            {
                return(new NativeParser());
            }

            int lookupHashcode = instantiatedType.GetHashCode();
            var enumerator     = staticsInfoHashtable.Lookup(lookupHashcode);

            NativeParser entryParser;

            while (!(entryParser = enumerator.GetNext()).IsNull)
            {
                RuntimeTypeHandle parsedInstantiatedType = externalReferencesLookup.GetRuntimeTypeHandleFromIndex(entryParser.GetUnsigned());

                if (!parsedInstantiatedType.Equals(instantiatedType))
                {
                    continue;
                }

                return(entryParser);
            }

            return(new NativeParser());
        }
Ejemplo n.º 9
0
 public override int GetHashCode()
 {
     if (!_hashCode.HasValue)
     {
         _hashCode = _declaringTypeHandle.GetHashCode() ^ TypeHashingAlgorithms.ComputeGenericInstanceHashCode(TypeHashingAlgorithms.ComputeNameHashCode(_methodNameAndSignature.Name), _genericMethodArgumentHandles);
     }
     return(_hashCode.Value);
 }
Ejemplo n.º 10
0
 public override int GetHashCode()
 {
     if (!_hashCode.HasValue)
     {
         _hashCode = TypeHashingAlgorithms.ComputeGenericInstanceHashCode(_genericTypeDefinitionHandle.GetHashCode(), _genericTypeArgumentHandles);
     }
     return(_hashCode.Value);
 }
            public RuntimeMethodHandleKey(RuntimeTypeHandle declaringType, string methodName, RuntimeSignature signature, RuntimeTypeHandle[] genericArgs)
            {
                Debug.Assert(genericArgs != null);

                _declaringType = declaringType;
                _methodName    = methodName;
                _signature     = signature;
                _genericArgs   = genericArgs;
                int methodNameHashCode = methodName == null ? 0 : methodName.GetHashCode();

                _hashcode = TypeHashingAlgorithms.ComputeGenericInstanceHashCode(declaringType.GetHashCode(), genericArgs) ^ methodNameHashCode ^ signature.GetHashCode();
            }
Ejemplo n.º 12
0
        public unsafe static IntPtr TryGetStaticClassConstructionContext(RuntimeTypeHandle typeHandle)
        {
            if (RuntimeAugments.HasCctor(typeHandle))
            {
                if (RuntimeAugments.IsDynamicType(typeHandle))
                {
                    // For dynamic types, its always possible to get the non-gc static data section directly.
                    byte *ptr = (byte *)*(IntPtr *)RuntimeAugments.GetNonGcStaticFieldData(typeHandle);

                    // what we have now is the base address of the non-gc statics of the type
                    // what we need is the cctor context, which is just before that
                    ptr = ptr - sizeof(System.Runtime.CompilerServices.StaticClassConstructionContext);

                    return((IntPtr)ptr);
                }
                else
                {
                    // Non-dynamic types do not provide a way to directly get at the non-gc static region.
                    // Use the CctorContextMap instead.

                    var moduleHandle = RuntimeAugments.GetModuleFromTypeHandle(typeHandle);
                    Debug.Assert(moduleHandle != IntPtr.Zero);

                    NativeReader typeMapReader;
                    if (TryGetNativeReaderForBlob(moduleHandle, ReflectionMapBlob.CCtorContextMap, out typeMapReader))
                    {
                        NativeParser    typeMapParser = new NativeParser(typeMapReader, 0);
                        NativeHashtable typeHashtable = new NativeHashtable(typeMapParser);

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

                        var          lookup = typeHashtable.Lookup(typeHandle.GetHashCode());
                        NativeParser entryParser;
                        while (!(entryParser = lookup.GetNext()).IsNull)
                        {
                            RuntimeTypeHandle foundType = externalReferences.GetRuntimeTypeHandleFromIndex(entryParser.GetUnsigned());
                            if (foundType.Equals(typeHandle))
                            {
                                byte *pNonGcStaticBase = (byte *)externalReferences.GetIntPtrFromIndex(entryParser.GetUnsigned());

                                // cctor context is located before the non-GC static base
                                return((IntPtr)(pNonGcStaticBase - sizeof(System.Runtime.CompilerServices.StaticClassConstructionContext)));
                            }
                        }
                    }
                }
            }

            return(IntPtr.Zero);
        }
Ejemplo n.º 13
0
    private bool VerifyHashCode(Object o)
    {
        bool retVal = true;
        RuntimeTypeHandle handle = o.GetType().TypeHandle;
        int value1 = handle.GetHashCode();
        int value2 = handle.GetHashCode();

        m_ErrorNo++;
        if (value1 == 0)
        {
            TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "RuntimeTypeHandle.GetHashCode returns 0");
            retVal = false;
        }

        m_ErrorNo++;
        if (value1 != value2)
        {
            TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Call RuntimeTypeHandle.GetHashCode twice returns wrong hash code");
            retVal = false;
        }

        return(retVal);
    }
Ejemplo n.º 14
0
        internal RuntimeTypeHandleMap(int size, Func <int, RuntimeTypeHandle> getHandle) : base(size)
        {
            m_getHandle = getHandle;

            for (int i = 0; i < size; i++)
            {
                RuntimeTypeHandle handle = getHandle(i);

                if (!handle.Equals(McgModule.s_DependencyReductionTypeRemovedTypeHandle))
                {
                    Add(handle.GetHashCode(), i);
                }
            }
        }
Ejemplo n.º 15
0
        internal int Lookup(RuntimeTypeHandle handle)
        {
            for (int slot = GetFirst(handle.GetHashCode()); slot >= 0; slot = GetNext(slot))
            {
                int index = GetIndex(slot);

                if (handle.Equals(m_getHandle(index)))
                {
                    return(index);
                }
            }

            return(-1);
        }
            public override int GetHashCode()
            {
                unchecked
                {
                    int hash = Type.GetHashCode();

                    if (AdditionalImplementedTypes != null)
                    {
                        foreach (var h in AdditionalImplementedTypes)
                        {
                            hash = 37 * hash + h.GetHashCode();
                        }
                    }

                    return(hash);
                }
            }
Ejemplo n.º 17
0
    private bool VerifyHashCode(Object o1, Object o2, bool desiredValue)
    {
        bool retVal = true;
        RuntimeTypeHandle handle1 = o1.GetType().TypeHandle;
        RuntimeTypeHandle handle2 = o2.GetType().TypeHandle;
        int value1 = handle1.GetHashCode();
        int value2 = handle2.GetHashCode();

        bool actualValue = value1 == value2;

        m_ErrorNo++;
        if (actualValue != desiredValue)
        {
            TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Compare the hash code for handle1 with handle2 returns ACTUAL: " + actualValue.ToString() + ", DESIRED: " + desiredValue.ToString());
            retVal = false;
        }

        return(retVal);
    }
Ejemplo n.º 18
0
        private unsafe bool TryGetMarshallersForDelegate(RuntimeTypeHandle delegateTypeHandle, out IntPtr openStub, out IntPtr closedStub, out IntPtr delegateCreationStub)
        {
            int delegateHashcode = delegateTypeHandle.GetHashCode();

            openStub             = IntPtr.Zero;
            closedStub           = IntPtr.Zero;
            delegateCreationStub = IntPtr.Zero;

            foreach (NativeFormatModuleInfo module in ModuleList.EnumerateModules())
            {
                NativeReader delegateMapReader;
                if (TryGetNativeReaderForBlob(module, ReflectionMapBlob.DelegateMarshallingStubMap, out delegateMapReader))
                {
                    NativeParser    delegateMapParser = new NativeParser(delegateMapReader, 0);
                    NativeHashtable delegateHashtable = new NativeHashtable(delegateMapParser);

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

                    var          lookup = delegateHashtable.Lookup(delegateHashcode);
                    NativeParser entryParser;
                    while (!(entryParser = lookup.GetNext()).IsNull)
                    {
                        RuntimeTypeHandle foundDelegateType = externalReferences.GetRuntimeTypeHandleFromIndex(entryParser.GetUnsigned());
                        if (foundDelegateType.Equals(delegateTypeHandle))
                        {
                            byte *pOpen             = (byte *)externalReferences.GetIntPtrFromIndex(entryParser.GetUnsigned());
                            byte *pClose            = (byte *)externalReferences.GetIntPtrFromIndex(entryParser.GetUnsigned());
                            byte *pDelegateCreation = (byte *)externalReferences.GetIntPtrFromIndex(entryParser.GetUnsigned());
                            openStub             = (IntPtr)pOpen;
                            closedStub           = (IntPtr)pClose;
                            delegateCreationStub = (IntPtr)pDelegateCreation;
                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
Ejemplo n.º 19
0
        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);
        }
Ejemplo n.º 20
0
            public RuntimeMethodHandleKey(RuntimeTypeHandle declaringType, string methodName, RuntimeSignature signature, RuntimeTypeHandle[] genericArgs)
            {
                // genericArgs will be null if this is a (typical or not) method definition
                // genericArgs are non-null only for instantiated generic methods.
                Debug.Assert(genericArgs == null || genericArgs.Length > 0);

                _declaringType = declaringType;
                _methodName    = methodName;
                _signature     = signature;
                _genericArgs   = genericArgs;
                int methodNameHashCode = methodName == null ? 0 : methodName.GetHashCode();

                _hashcode = methodNameHashCode ^ signature.GetHashCode();

                if (genericArgs != null)
                {
                    _hashcode ^= TypeHashingAlgorithms.ComputeGenericInstanceHashCode(declaringType.GetHashCode(), genericArgs);
                }
                else
                {
                    _hashcode ^= declaringType.GetHashCode();
                }
            }
Ejemplo n.º 21
0
        private static unsafe bool GetMarshallersForDelegate(RuntimeTypeHandle delegateTypeHandle, out IntPtr openStub, out IntPtr closedStub, out IntPtr delegateCreationStub)
        {
            int delegateHashcode = delegateTypeHandle.GetHashCode();

            openStub             = IntPtr.Zero;
            closedStub           = IntPtr.Zero;
            delegateCreationStub = IntPtr.Zero;

            foreach (TypeManagerHandle module in RuntimeAugments.GetLoadedModules())
            {
                NativeReader delegateMapReader;
                if (TryGetNativeReaderForBlob(module, ReflectionMapBlob.DelegateMarshallingStubMap, out delegateMapReader))
                {
                    NativeParser    delegateMapParser = new NativeParser(delegateMapReader, 0);
                    NativeHashtable delegateHashtable = new NativeHashtable(delegateMapParser);

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

                    var          lookup = delegateHashtable.Lookup(delegateHashcode);
                    NativeParser entryParser;
                    while (!(entryParser = lookup.GetNext()).IsNull)
                    {
                        RuntimeTypeHandle foundDelegateType = externalReferences.GetRuntimeTypeHandleFromIndex(entryParser.GetUnsigned());
                        if (foundDelegateType.Equals(delegateTypeHandle))
                        {
                            openStub             = externalReferences.GetIntPtrFromIndex(entryParser.GetUnsigned());
                            closedStub           = externalReferences.GetIntPtrFromIndex(entryParser.GetUnsigned());
                            delegateCreationStub = externalReferences.GetIntPtrFromIndex(entryParser.GetUnsigned());
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
Ejemplo n.º 22
0
 public override int GetHashCode()
 {
     return(m_handle.GetHashCode());
 }
Ejemplo n.º 23
0
 internal override int LookupHashCode()
 {
     return(_typeToLookup != null?_typeToLookup.GetHashCode() : TypeHashingAlgorithms.ComputeGenericInstanceHashCode(_genericTypeDefinitionHandle.GetHashCode(), _genericTypeArgumentHandles));
 }
Ejemplo n.º 24
0
        private bool ResolveInterfaceGenericVirtualMethodSlot_Static(RuntimeTypeHandle targetTypeHandle, ref RuntimeTypeHandle declaringType, ref MethodNameAndSignature methodNameAndSignature)
        {
            // Get the open type definition of the containing type of the generic virtual method being resolved
            RuntimeTypeHandle openCallingTypeHandle = GetTypeDefinition(declaringType);

            // Get the open type definition of the current type of the object instance on which the GVM is being resolved
            RuntimeTypeHandle openTargetTypeHandle;

            RuntimeTypeHandle[] targetTypeInstantiation;
            openTargetTypeHandle = GetOpenTypeDefinition(targetTypeHandle, out targetTypeInstantiation);

#if REFLECTION_EXECUTION_TRACE
            ReflectionExecutionLogger.WriteLine("INTERFACE GVM call = " + GetTypeNameDebug(declaringType) + "." + methodNameAndSignature.Name);
#endif

            foreach (NativeFormatModuleInfo module in ModuleList.EnumerateModules(RuntimeAugments.GetModuleFromTypeHandle(openTargetTypeHandle)))
            {
                NativeReader gvmTableReader;
                if (!TryGetNativeReaderForBlob(module, ReflectionMapBlob.InterfaceGenericVirtualMethodTable, out gvmTableReader))
                {
                    continue;
                }

                NativeReader nativeLayoutReader;
                if (!TryGetNativeReaderForBlob(module, ReflectionMapBlob.NativeLayoutInfo, out nativeLayoutReader))
                {
                    continue;
                }

                NativeParser    gvmTableParser = new NativeParser(gvmTableReader, 0);
                NativeHashtable gvmHashtable   = new NativeHashtable(gvmTableParser);

                ExternalReferencesTable extRefs = default(ExternalReferencesTable);
                extRefs.InitializeCommonFixupsTable(module);

                var lookup = gvmHashtable.Lookup(openCallingTypeHandle.GetHashCode());

                NativeParser entryParser;
                while (!(entryParser = lookup.GetNext()).IsNull)
                {
                    RuntimeTypeHandle interfaceTypeHandle = extRefs.GetRuntimeTypeHandleFromIndex(entryParser.GetUnsigned());
                    if (!openCallingTypeHandle.Equals(interfaceTypeHandle))
                    {
                        continue;
                    }

                    uint nameAndSigToken = extRefs.GetExternalNativeLayoutOffset(entryParser.GetUnsigned());
                    MethodNameAndSignature interfaceMethodNameAndSignature = GetMethodNameAndSignatureFromNativeReader(nativeLayoutReader, module.Handle, nameAndSigToken);

                    if (!interfaceMethodNameAndSignature.Equals(methodNameAndSignature))
                    {
                        continue;
                    }

                    // For each of the possible GVM slot targets for the current interface call, we will do the following:
                    //
                    //  Step 1: Scan the types that currently provide implementations for the current GVM slot target, and look
                    //          for ones that match the target object's type.
                    //
                    //  Step 2: For each type that we find in step #1, get a list of all the interfaces that the current GVM target
                    //          provides an implementation for
                    //
                    //  Step 3: For each interface in the list in step #2, parse the signature of that interface, do the generic argument
                    //          substitution (in case of a generic interface), and check if this interface signature is assignable from the
                    //          calling interface signature (from the name and sig input). if there is an exact match based on
                    //          interface type, then we've found the right slot. Otherwise, re-scan the entry again and see if some interface
                    //          type is compatible with the initial slots interface by means of variance.
                    //          This is done by calling the TypeLoaderEnvironment helper function.
                    //
                    // Example:
                    //      public interface IFoo<out T, out U>
                    //      {
                    //          string M1<V>();
                    //      }
                    //      public class Foo1<T, U> : IFoo<T, U>, IFoo<Kvp<T, string>, U>
                    //      {
                    //          string IFoo<T, U>.M1<V>() { ... }
                    //          public virtual string M1<V>() { ... }
                    //      }
                    //      public class Foo2<T, U> : Foo1<object, U>, IFoo<U, T>
                    //      {
                    //          string IFoo<U, T>.M1<V>() { ... }
                    //      }
                    //
                    //  GVM Table layout for IFoo<T, U>.M1<V>:
                    //  {
                    //      InterfaceTypeHandle = IFoo<T, U>
                    //      InterfaceMethodNameAndSignature = { "M1", SigOf(string M1) }
                    //      GVMTargetSlots[] =
                    //      {
                    //          {
                    //              TargetMethodNameAndSignature = { "M1", SigOf(M1) }
                    //              TargetTypeHandle = Foo1<T, U>
                    //              ImplementingTypes[] = {
                    //                  ImplementingTypeHandle = Foo1<T, U>
                    //                  ImplementedInterfacesSignatures[] = { SigOf(IFoo<!0, !1>) }
                    //              }
                    //          },
                    //
                    //          {
                    //              TargetMethodNameAndSignature = { "M1", SigOf(M1) }
                    //              TargetTypeHandle = Foo1<T, U>
                    //              ImplementingTypes[] = {
                    //                  ImplementingTypeHandle = Foo1<T, U>
                    //                  ImplementedInterfacesSignatures[] = { SigOf(IFoo<Kvp<!0, string>, !1>) }
                    //              }
                    //          },
                    //
                    //          {
                    //              TargetMethodNameAndSignature = { "M1", SigOf(M1) }
                    //              TargetTypeHandle = Foo2<T, U>
                    //              ImplementingTypes = {
                    //                  ImplementingTypeHandle = Foo2<T, U>
                    //                  ImplementedInterfacesSignatures[] = { SigOf(IFoo<!1, !0>) }
                    //              }
                    //          },
                    //      }
                    //  }
                    //

                    uint currentOffset = entryParser.Offset;

                    // Non-variant dispatch of a variant generic interface generic virtual method.
                    if (FindMatchingInterfaceSlot(module, nativeLayoutReader, ref entryParser, ref extRefs, ref declaringType, ref methodNameAndSignature, openTargetTypeHandle, targetTypeInstantiation, false))
                    {
                        return(true);
                    }

                    entryParser.Offset = currentOffset;

                    // Variant dispatch of a variant generic interface generic virtual method.
                    if (FindMatchingInterfaceSlot(module, nativeLayoutReader, ref entryParser, ref extRefs, ref declaringType, ref methodNameAndSignature, openTargetTypeHandle, targetTypeInstantiation, true))
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Construct McgModule
        /// </summary>
        public unsafe McgModule(
            int mcgDataModulePriority,
            McgInterfaceData[] interfaceData,
            CCWTemplateData[] ccwTemplateData,
            FixupRuntimeTypeHandle[] supportedInterfaceList,
            McgClassData[] classData,
            McgBoxingData[] boxingData,
            McgAdditionalClassData[] additionalClassData,
            McgCollectionData[] collectionData,
            McgPInvokeDelegateData[] pinvokeDelegateData,
            McgCCWFactoryInfoEntry[] ccwFactories,
            McgStructMarshalData[] structMarshalData,
            McgUnsafeStructFieldOffsetData[] unsafeStructFieldOffsetData,
            McgGenericArgumentMarshalInfo[] genericArgumentMarshalInfo,
            McgHashcodeVerifyEntry[] hashcodeVerifyData)
        {
            m_mcgDataModulePriority      = mcgDataModulePriority;
            m_interfaceData              = interfaceData;
            m_classData                  = classData;
            m_boxingData                 = boxingData;
            m_collectionData             = collectionData;
            m_pinvokeDelegateData        = pinvokeDelegateData;
            m_additionalClassData        = additionalClassData;
            m_ccwFactories               = ccwFactories;
            m_structMarshalData          = structMarshalData;
            m_unsafeStructOffsetData     = unsafeStructFieldOffsetData;
            m_genericArgumentMarshalInfo = genericArgumentMarshalInfo;

            m_ccwTemplateData = ccwTemplateData;

            // Following code is disabled due to lazy static constructor dependency from McgModule which is
            // static eager constructor. Undo this when McgCurrentModule is using ModuleConstructorAttribute
            // -- Today McgCurrentModule cannot use ModuleConstructor attribute. Module constructors are called
            // after ReflectionExecution has been initialized but ReflectionExecution.Initialize requires
            // McgCurrentModule to have already been initialized because the assembly binder needs MCG support
            // for assembly (scope) name enumeration while registering the new module for reflection.
#if EAGER_CTOR_WORKAROUND
            Debug.Assert(m_interfaceTypeInfo != null);
#endif
            if (supportedInterfaceList != null)
            {
                m_supportedInterfaceList = new RuntimeTypeHandle[supportedInterfaceList.Length];
                for (int i = 0; i < supportedInterfaceList.Length; i++)
                {
                    m_supportedInterfaceList[i] = supportedInterfaceList[i].RuntimeTypeHandle;
                }
            }
            else
            {
                m_supportedInterfaceList = null;
            }

            m_hashcodeVerifyData = hashcodeVerifyData;

#if DEBUG
            // Check no duplicate RuntimeTypeHandle in hashtable
            if (m_interfaceData != null)
            {
                System.Collections.Generic.Internal.HashSet <EquatableRuntimeTypeHandle> intfHashSet =
                    new System.Collections.Generic.Internal.HashSet <EquatableRuntimeTypeHandle>(m_interfaceData.Length);
                foreach (McgInterfaceData item in m_interfaceData)
                {
                    RuntimeTypeHandle typeHnd = item.ItfType;
                    if (!typeHnd.Equals(s_DependencyReductionTypeRemovedTypeHandle) && !typeHnd.Equals(default(RuntimeTypeHandle)))
                    {
                        if (intfHashSet.Add(new EquatableRuntimeTypeHandle(typeHnd), typeHnd.GetHashCode()))
                        {
                            Debug.Fail("Duplicate RuntimeTypeHandle found in m_interfaceData");
                        }
                    }
                }
            }

            if (m_classData != null)
            {
                System.Collections.Generic.Internal.HashSet <EquatableRuntimeTypeHandle> classHashSet =
                    new System.Collections.Generic.Internal.HashSet <EquatableRuntimeTypeHandle>(m_classData.Length);
                foreach (McgClassData item in m_classData)
                {
                    RuntimeTypeHandle typeHnd = item.ClassType;
                    if (!typeHnd.Equals(s_DependencyReductionTypeRemovedTypeHandle) && !typeHnd.Equals(default(RuntimeTypeHandle)))
                    {
                        if (classHashSet.Add(new EquatableRuntimeTypeHandle(typeHnd), typeHnd.GetHashCode()))
                        {
                            Debug.Fail("Duplicate RuntimeTypeHandle found in m_classData");
                        }
                    }
                }
            }

            Debug.Assert(this.VerifyHashCodes());
#endif
        }
Ejemplo n.º 26
0
        private unsafe bool ResolveGenericVirtualMethodTarget_Static(RuntimeTypeHandle targetTypeHandle, RuntimeTypeHandle declaringType, RuntimeTypeHandle[] genericArguments, MethodNameAndSignature callingMethodNameAndSignature, out IntPtr methodPointer, out IntPtr dictionaryPointer)
        {
            methodPointer = dictionaryPointer = IntPtr.Zero;

            // Get the open type definition of the containing type of the generic virtual method being resolved
            RuntimeTypeHandle openCallingTypeHandle = GetTypeDefinition(declaringType);

            // Get the open type definition of the current type of the object instance on which the GVM is being resolved
            RuntimeTypeHandle openTargetTypeHandle = GetTypeDefinition(targetTypeHandle);

            int hashCode = openCallingTypeHandle.GetHashCode();

            hashCode = ((hashCode << 13) ^ hashCode) ^ openTargetTypeHandle.GetHashCode();

#if REFLECTION_EXECUTION_TRACE
            ReflectionExecutionLogger.WriteLine("GVM Target Resolution = " + GetTypeNameDebug(targetTypeHandle) + "." + callingMethodNameAndSignature.Name);
#endif

            foreach (NativeFormatModuleInfo module in ModuleList.EnumerateModules(RuntimeAugments.GetModuleFromTypeHandle(openTargetTypeHandle)))
            {
                NativeReader gvmTableReader;
                if (!TryGetNativeReaderForBlob(module, ReflectionMapBlob.GenericVirtualMethodTable, out gvmTableReader))
                {
                    continue;
                }

                NativeReader nativeLayoutReader;
                if (!TryGetNativeReaderForBlob(module, ReflectionMapBlob.NativeLayoutInfo, out nativeLayoutReader))
                {
                    continue;
                }

                NativeParser            gvmTableParser = new NativeParser(gvmTableReader, 0);
                NativeHashtable         gvmHashtable   = new NativeHashtable(gvmTableParser);
                ExternalReferencesTable extRefs        = default(ExternalReferencesTable);
                extRefs.InitializeCommonFixupsTable(module);

                var lookup = gvmHashtable.Lookup(hashCode);

                NativeParser entryParser;
                while (!(entryParser = lookup.GetNext()).IsNull)
                {
                    RuntimeTypeHandle parsedCallingTypeHandle = extRefs.GetRuntimeTypeHandleFromIndex(entryParser.GetUnsigned());
                    if (!parsedCallingTypeHandle.Equals(openCallingTypeHandle))
                    {
                        continue;
                    }

                    RuntimeTypeHandle parsedTargetTypeHandle = extRefs.GetRuntimeTypeHandleFromIndex(entryParser.GetUnsigned());
                    if (!parsedTargetTypeHandle.Equals(openTargetTypeHandle))
                    {
                        continue;
                    }

                    uint parsedCallingNameAndSigToken = extRefs.GetExternalNativeLayoutOffset(entryParser.GetUnsigned());
                    MethodNameAndSignature parsedCallingNameAndSignature = GetMethodNameAndSignatureFromNativeReader(nativeLayoutReader, module.Handle, parsedCallingNameAndSigToken);

                    if (!parsedCallingNameAndSignature.Equals(callingMethodNameAndSignature))
                    {
                        continue;
                    }

                    uint parsedTargetMethodNameAndSigToken = extRefs.GetExternalNativeLayoutOffset(entryParser.GetUnsigned());
                    MethodNameAndSignature targetMethodNameAndSignature = GetMethodNameAndSignatureFromNativeReader(nativeLayoutReader, module.Handle, parsedTargetMethodNameAndSigToken);

                    Debug.Assert(targetMethodNameAndSignature != null);

                    if (!TryGetGenericVirtualMethodPointer(targetTypeHandle, targetMethodNameAndSignature, genericArguments, out methodPointer, out dictionaryPointer))
                    {
                        Environment.FailFast("GVM method pointer lookup failure");
                    }

                    return(true);
                }
            }

            return(false);
        }
Ejemplo n.º 27
0
 public RuntimeFieldHandleKey(RuntimeTypeHandle declaringType, string fieldName)
 {
     _declaringType = declaringType;
     _fieldName     = fieldName;
     _hashcode      = declaringType.GetHashCode() ^ fieldName.GetHashCode();
 }
Ejemplo n.º 28
0
 internal override int LookupHashCode()
 {
     // Todo: Signatures in the hash code.
     return(_methodToLookup != null?_methodToLookup.GetHashCode() : (_declaringType.GetHashCode() ^ TypeHashingAlgorithms.ComputeGenericInstanceHashCode(TypeHashingAlgorithms.ComputeNameHashCode(_nameAndSignature.Name), _genericMethodArgumentHandles)));
 }
Ejemplo n.º 29
0
 public override int GetHashCode()
 {
     return(CalcHashCode(_resolveType, _handle, _methodHandleOrSlotOrCodePointer.GetHashCode(), _declaringType.GetHashCode()));
 }
Ejemplo n.º 30
0
        public TypeDesc ResolveRuntimeTypeHandle(RuntimeTypeHandle rtth)
        {
            TypeDesc returnedType;

            if (_runtimeTypeHandleResolutionCache.TryGetValue(rtth, out returnedType))
            {
                return(returnedType);
            }

            if (rtth.Equals(CanonType.RuntimeTypeHandle))
            {
                returnedType = CanonType;
            }
            else if (rtth.Equals(UniversalCanonType.RuntimeTypeHandle))
            {
                returnedType = UniversalCanonType;
            }
            else if (RuntimeAugments.IsGenericTypeDefinition(rtth))
            {
                returnedType = TryGetMetadataBasedTypeFromRuntimeTypeHandle_Uncached(rtth);
                if (returnedType == null)
                {
                    unsafe
                    {
                        TypeDesc[] genericParameters = new TypeDesc[rtth.ToEETypePtr()->GenericArgumentCount];
                        for (int i = 0; i < genericParameters.Length; i++)
                        {
                            genericParameters[i] = GetSignatureVariable(i, false);
                        }

                        returnedType = new NoMetadataType(this, rtth, null, new Instantiation(genericParameters), rtth.GetHashCode());
                    }
                }
            }
            else if (RuntimeAugments.IsGenericType(rtth))
            {
                RuntimeTypeHandle   typeDefRuntimeTypeHandle;
                RuntimeTypeHandle[] genericArgRuntimeTypeHandles;
                typeDefRuntimeTypeHandle = RuntimeAugments.GetGenericInstantiation(rtth, out genericArgRuntimeTypeHandles);

                DefType       typeDef     = (DefType)ResolveRuntimeTypeHandle(typeDefRuntimeTypeHandle);
                Instantiation genericArgs = ResolveRuntimeTypeHandles(genericArgRuntimeTypeHandles);
                returnedType = ResolveGenericInstantiation(typeDef, genericArgs);
            }
            else if (RuntimeAugments.IsArrayType(rtth))
            {
                RuntimeTypeHandle elementTypeHandle = RuntimeAugments.GetRelatedParameterTypeHandle(rtth);
                TypeDesc          elementType       = ResolveRuntimeTypeHandle(elementTypeHandle);
                unsafe
                {
                    if (rtth.ToEETypePtr()->IsSzArray)
                    {
                        returnedType = GetArrayType(elementType);
                    }
                    else
                    {
                        returnedType = GetArrayType(elementType, rtth.ToEETypePtr()->ArrayRank);
                    }
                }
            }
            else if (RuntimeAugments.IsUnmanagedPointerType(rtth))
            {
                RuntimeTypeHandle targetTypeHandle = RuntimeAugments.GetRelatedParameterTypeHandle(rtth);
                TypeDesc          targetType       = ResolveRuntimeTypeHandle(targetTypeHandle);
                returnedType = GetPointerType(targetType);
            }
            else if (RuntimeAugments.IsByRefType(rtth))
            {
                RuntimeTypeHandle targetTypeHandle = RuntimeAugments.GetRelatedParameterTypeHandle(rtth);
                TypeDesc          targetType       = ResolveRuntimeTypeHandle(targetTypeHandle);
                returnedType = GetByRefType(targetType);
            }
            else
            {
                returnedType = TryGetMetadataBasedTypeFromRuntimeTypeHandle_Uncached(rtth);
                if (returnedType == null)
                {
                    returnedType = new NoMetadataType(this, rtth, null, Instantiation.Empty, rtth.GetHashCode());
                }
            }

            // We either retrieved an existing DefType that is already registered with the runtime
            // or one that is not associated with an MethodTable yet. If it's not associated, associate it.
            if (returnedType.RuntimeTypeHandle.IsNull())
            {
                TypeBuilderState state = returnedType.GetTypeBuilderStateIfExist();
                bool             skipStoringRuntimeTypeHandle = false;

                // If we've already attempted to lookup and failed to retrieve this type handle, we
                // may have already decided to create a new one. In that case, do not attempt to abort
                // that creation process as it may have already begun the process of type creation
                if (state != null && state.AttemptedAndFailedToRetrieveTypeHandle)
                {
                    skipStoringRuntimeTypeHandle = true;
                }

                if (!skipStoringRuntimeTypeHandle)
                {
                    returnedType.SetRuntimeTypeHandleUnsafe(rtth);
                }
            }

            _runtimeTypeHandleResolutionCache.Add(rtth, returnedType);

            return(returnedType.WithDebugName());
        }