public void TestGenericMethodInterfaceMethodImplOverride()
        {
            //
            // Ensure MethodImpl based overriding works for MethodSpecs
            //

            MetadataType interfaceType   = _testModule.GetType("VirtualFunctionOverride", "IIFaceWithGenericMethod");
            MethodDesc   interfaceMethod = null;

            foreach (MethodDesc m in interfaceType.GetMethods())
            {
                if (m.Name == "GenMethod")
                {
                    interfaceMethod = m;
                    break;
                }
            }
            Assert.NotNull(interfaceMethod);

            MetadataType objectType            = _testModule.GetType("VirtualFunctionOverride", "HasMethodInterfaceOverrideOfGenericMethod");
            MethodDesc   expectedVirtualMethod = null;

            foreach (MethodDesc m in objectType.GetMethods())
            {
                if (m.Name.Contains("GenMethod"))
                {
                    expectedVirtualMethod = m;
                    break;
                }
            }
            Assert.NotNull(expectedVirtualMethod);

            Assert.Equal(expectedVirtualMethod, objectType.ResolveInterfaceMethodToVirtualMethodOnType(interfaceMethod));
        }
Beispiel #2
0
        public void TestSignatureMatches2ModOptsAtStartOfSig()
        {
            MetadataType    modOptTester = _testModule.GetType("", "ModOptTester");
            MethodSignature methodWith2ModOptsAtStartOfSig = modOptTester.GetMethods().Single(m => string.Equals(m.Name, "Method")).Signature;

            // All modopts that are at the very beginning of the signature are given index 0.1.1.1
            // Both the index and the order in the modopt array are significant for signature comparison
            Assert.Equal(MethodSignature.IndexOfCustomModifiersOnReturnType, methodWith2ModOptsAtStartOfSig.GetEmbeddedSignatureData()[0].index);
            Assert.Equal(MethodSignature.IndexOfCustomModifiersOnReturnType, methodWith2ModOptsAtStartOfSig.GetEmbeddedSignatureData()[1].index);
            Assert.NotEqual(MethodSignature.IndexOfCustomModifiersOnReturnType, methodWith2ModOptsAtStartOfSig.GetEmbeddedSignatureData()[2].index);
            Assert.Equal("OptionalCustomModifier0.1.1.1CharOptionalCustomModifier0.1.1.1VoidOptionalCustomModifier0.1.2.1FooModifier", GetModOptMethodSignatureInfo(methodWith2ModOptsAtStartOfSig));
        }
Beispiel #3
0
        public void TestNonGenericTypes()
        {
            DefType      systemArrayType = _context.GetWellKnownType(WellKnownType.Array);
            MetadataType nonNestedType   = (MetadataType)_testModule.GetType("Hashcode", "NonNestedType");
            TypeDesc     nestedType      = nonNestedType.GetNestedType("NestedType");

            int expectedNonNestedTypeHashcode  = TypeHashingAlgorithms.ComputeNameHashCode("Hashcode.NonNestedType");
            int expectedNestedTypeNameHashcode = TypeHashingAlgorithms.ComputeNameHashCode("NestedType");
            int expectedNestedTypeHashcode     = TypeHashingAlgorithms.ComputeNestedTypeHashCode(expectedNonNestedTypeHashcode, expectedNestedTypeNameHashcode);

            Assert.Equal(expectedNonNestedTypeHashcode, nonNestedType.GetHashCode());
            Assert.Equal(expectedNestedTypeHashcode, nestedType.GetHashCode());
        }
Beispiel #4
0
        public void TestNoPointers()
        {
            MetadataType t = _testModule.GetType("StaticFieldLayout", "NoPointers");

            foreach (var field in t.GetFields())
            {
                if (!field.IsStatic)
                {
                    continue;
                }

                switch (field.Name)
                {
                case "int1":
                    Assert.Equal(0, field.Offset);
                    break;

                case "byte1":
                    Assert.Equal(4, field.Offset);
                    break;

                case "char1":
                    Assert.Equal(6, field.Offset);
                    break;

                default:
                    throw new Exception(field.Name);
                }
            }
        }
Beispiel #5
0
        public void TestDevirtualizeSimple()
        {
            MetadataType            testType   = _testModule.GetType("Devirtualization", "DevirtualizeSimple");
            DevirtualizationManager scanDevirt = GetDevirtualizationManagerFromScan(testType.GetMethod("Run", null));

            MethodDesc implMethod = testType.GetNestedType("Derived").GetMethod("Virtual", null);

            // The impl method should be treated as sealed
            Assert.True(scanDevirt.IsEffectivelySealed(implMethod));

            // Even though the metadata based algorithm would say it isn't
            var devirt = new DevirtualizationManager();

            Assert.False(devirt.IsEffectivelySealed(implMethod));
        }
Beispiel #6
0
        public void TestInstanceMap()
        {
            MetadataType classWithArrayFields = _testModule.GetType("GCPointerMap", "ClassWithArrayFields");
            MetadataType classWithStringField = _testModule.GetType("GCPointerMap", "ClassWithStringField");
            MetadataType mixedStruct          = _testModule.GetType("GCPointerMap", "MixedStruct");
            MetadataType structWithSameGCLayoutAsMixedStruct = _testModule.GetType("GCPointerMap", "StructWithSameGCLayoutAsMixedStruct");
            MetadataType doubleMixedStructLayout             = _testModule.GetType("GCPointerMap", "DoubleMixedStructLayout");
            MetadataType explicitlyFarPointer = _testModule.GetType("GCPointerMap", "ExplicitlyFarPointer");
            MetadataType struct32GcPointers   = _testModule.GetType("GCPointerMap", "Struct32GcPointers");

            {
                var map = GCPointerMap.FromInstanceLayout(classWithArrayFields);
                Assert.Equal(map.Size, 3);
                Assert.Equal("011", map.ToString());
            }

            {
                var map = GCPointerMap.FromInstanceLayout(classWithStringField);
                Assert.Equal(map.Size, 4);
                Assert.Equal("0010", map.ToString());
            }

            {
                var map = GCPointerMap.FromInstanceLayout(mixedStruct);
                Assert.Equal(map.Size, 5);
                Assert.Equal("01001", map.ToString());
            }

            {
                var map1 = GCPointerMap.FromInstanceLayout(mixedStruct);
                var map2 = GCPointerMap.FromInstanceLayout(structWithSameGCLayoutAsMixedStruct);
                Assert.Equal(map1.Size, map2.Size);
                Assert.Equal(map1.ToString(), map2.ToString());
            }

            {
                var map = GCPointerMap.FromInstanceLayout(doubleMixedStructLayout);
                Assert.Equal(map.Size, 10);
                Assert.Equal("0100101001", map.ToString());
            }

            {
                var map = GCPointerMap.FromInstanceLayout(explicitlyFarPointer);
                Assert.Equal(map.Size, 117);
                Assert.Equal("100000000000000000000000000000000000000000000000000000000000000010000000000000001000000000000000000000000000000001001", map.ToString());
            }

            {
                var map = GCPointerMap.FromInstanceLayout(struct32GcPointers);
                Assert.Equal(map.Size, 32);
                Assert.Equal("11111111111111111111111111111111", map.ToString());
            }
        }
        private void CommonClassLayoutTestBits(ModuleDesc testModule,
                                               TypeSystemContext context,
                                               LayoutInt expectedIndeterminateByteAlignment,
                                               out InstantiatedType genOfIU,
                                               out InstantiatedType genOfLU,
                                               out InstantiatedType genOfUU,
                                               out InstantiatedType genOfUI,
                                               out InstantiatedType genOfUL)
        {
            MetadataType tDerivedGen = testModule.GetType("GenericTypes", "GenDerivedClass`2");

            genOfIU = tDerivedGen.MakeInstantiatedType(context.GetWellKnownType(WellKnownType.Int32), context.UniversalCanonType);
            genOfLU = tDerivedGen.MakeInstantiatedType(context.GetWellKnownType(WellKnownType.Int64), context.UniversalCanonType);
            genOfUU = tDerivedGen.MakeInstantiatedType(context.UniversalCanonType, context.UniversalCanonType);

            genOfUI = tDerivedGen.MakeInstantiatedType(context.UniversalCanonType, context.GetWellKnownType(WellKnownType.Int32));
            genOfUL = tDerivedGen.MakeInstantiatedType(context.UniversalCanonType, context.GetWellKnownType(WellKnownType.Int64));

            // Assert that the class as a whole is known to be of undefined size
            AssertClassIndeterminateSize(context, genOfIU, expectedIndeterminateByteAlignment);
            AssertClassIndeterminateSize(context, genOfLU, expectedIndeterminateByteAlignment);
            AssertClassIndeterminateSize(context, genOfUU, expectedIndeterminateByteAlignment);
            AssertClassIndeterminateSize(context, genOfUI, expectedIndeterminateByteAlignment);
            AssertClassIndeterminateSize(context, genOfUL, expectedIndeterminateByteAlignment);
        }
        private void TestIndeterminatedNestedStructFieldPerContext(TypeSystemContext context, ModuleDesc testModule, out InstantiatedType genOfIntNestedInt, out InstantiatedType genOfLongNestedInt)
        {
            // Given a struct with all field universal, what is the layout?
            MetadataType     tGen     = testModule.GetType("GenericTypes", "GenStruct`3");
            InstantiatedType genOfUUU = tGen.MakeInstantiatedType(context.UniversalCanonType, context.UniversalCanonType, context.UniversalCanonType);

            genOfIntNestedInt  = tGen.MakeInstantiatedType(context.GetWellKnownType(WellKnownType.Int32), genOfUUU, context.GetWellKnownType(WellKnownType.Int32));
            genOfLongNestedInt = tGen.MakeInstantiatedType(context.GetWellKnownType(WellKnownType.Int64), genOfUUU, context.GetWellKnownType(WellKnownType.Int32));

            Assert.Equal(LayoutInt.Indeterminate, genOfIntNestedInt.InstanceFieldAlignment);
            Assert.Equal(LayoutInt.Indeterminate, genOfIntNestedInt.InstanceFieldSize);
            Assert.Equal(LayoutInt.Indeterminate, genOfIntNestedInt.InstanceByteCount);
            Assert.Equal(LayoutInt.Indeterminate, genOfIntNestedInt.InstanceByteCountUnaligned);
            Assert.Equal(0, genOfIntNestedInt.GetFields().First().Offset.AsInt);
            Assert.Equal(LayoutInt.Indeterminate, genOfIntNestedInt.GetFields().ElementAt(1).Offset);
            Assert.Equal(LayoutInt.Indeterminate, genOfIntNestedInt.GetFields().ElementAt(2).Offset);

            Assert.Equal(LayoutInt.Indeterminate, genOfLongNestedInt.InstanceFieldAlignment);
            Assert.Equal(LayoutInt.Indeterminate, genOfLongNestedInt.InstanceFieldSize);
            Assert.Equal(LayoutInt.Indeterminate, genOfLongNestedInt.InstanceByteCount);
            Assert.Equal(LayoutInt.Indeterminate, genOfLongNestedInt.InstanceByteCountUnaligned);
            Assert.Equal(0, genOfLongNestedInt.GetFields().First().Offset.AsInt);
            if (context.Target.MaximumAlignment <= 8)
            {
                Assert.Equal(8, genOfLongNestedInt.GetFields().ElementAt(1).Offset.AsInt);
            }
            else
            {
                Assert.Equal(LayoutInt.Indeterminate, genOfLongNestedInt.GetFields().ElementAt(1).Offset);
            }
            Assert.Equal(LayoutInt.Indeterminate, genOfLongNestedInt.GetFields().ElementAt(2).Offset);
        }
        private DefType ResolveTypeReference(TypeReferenceHandle handle)
        {
            TypeReference typeReference = _metadataReader.GetTypeReference(handle);

            if (typeReference.ParentNamespaceOrType.HandleType == HandleType.TypeReference)
            {
                // Nested type case
                MetadataType containingType = (MetadataType)ResolveTypeReference(typeReference.ParentNamespaceOrType.ToTypeReferenceHandle(_metadataReader));

                return(containingType.GetNestedType(_metadataReader.GetString(typeReference.TypeName)));
            }
            else
            {
                // Cross-assembly reference
                // Get remote module, and then lookup by namespace/name
                ScopeReferenceHandle     scopeReferenceHandle            = default(ScopeReferenceHandle);
                NamespaceReferenceHandle initialNamespaceReferenceHandle = typeReference.ParentNamespaceOrType.ToNamespaceReferenceHandle(_metadataReader);
                NamespaceReferenceHandle namespaceReferenceHandle        = initialNamespaceReferenceHandle;
                do
                {
                    NamespaceReference namespaceReference = _metadataReader.GetNamespaceReference(namespaceReferenceHandle);
                    if (namespaceReference.ParentScopeOrNamespace.HandleType == HandleType.ScopeReference)
                    {
                        scopeReferenceHandle = namespaceReference.ParentScopeOrNamespace.ToScopeReferenceHandle(_metadataReader);
                    }
                    else
                    {
                        namespaceReferenceHandle = namespaceReference.ParentScopeOrNamespace.ToNamespaceReferenceHandle(_metadataReader);
                    }
                } while (scopeReferenceHandle.IsNull(_metadataReader));

                ModuleDesc remoteModule = GetModule(scopeReferenceHandle);

                string namespaceName = _metadataReader.GetNamespaceName(initialNamespaceReferenceHandle);
                string typeName      = _metadataReader.GetString(typeReference.TypeName);

                MetadataType resolvedType = remoteModule.GetType(namespaceName, typeName, throwIfNotFound: false);
                if (resolvedType != null)
                {
                    return(resolvedType);
                }

                // Special handling for the magic __Canon types cannot be currently put into
                // NativeFormatModule because GetType returns a MetadataType.
                if (remoteModule == _context.SystemModule)
                {
                    string qualifiedTypeName = namespaceName + "." + typeName;
                    if (qualifiedTypeName == CanonType.FullName)
                    {
                        return(_context.CanonType);
                    }
                    if (qualifiedTypeName == UniversalCanonType.FullName)
                    {
                        return(_context.UniversalCanonType);
                    }
                }

                throw new NotImplementedException();
            }
        }
        public void TestInvalidByRefLikeTypes()
        {
            {
                DefType type = _ilTestModule.GetType("IsByRefLike", "InvalidClass1");
                Assert.Throws <TypeSystemException.TypeLoadException>(() => type.ComputeInstanceLayout(InstanceLayoutKind.TypeAndFields));
            }

            {
                DefType type = _ilTestModule.GetType("IsByRefLike", "InvalidClass2");
                Assert.Throws <TypeSystemException.TypeLoadException>(() => type.ComputeInstanceLayout(InstanceLayoutKind.TypeAndFields));
            }

            {
                DefType type = _ilTestModule.GetType("IsByRefLike", "InvalidStruct");
                Assert.Throws <TypeSystemException.TypeLoadException>(() => type.ComputeInstanceLayout(InstanceLayoutKind.TypeAndFields));
            }
        }
        public void TestSimpleHfa()
        {
            var simpleHfaFloatStruct = _testModule.GetType("ValueTypeShapeCharacteristics", "SimpleHfaFloatStruct");

            Assert.True(simpleHfaFloatStruct.IsHfa);
            Assert.Equal(_singleType, simpleHfaFloatStruct.HfaElementType);

            var simpleHfaFloatStructWithManyFields = _testModule.GetType("ValueTypeShapeCharacteristics", "SimpleHfaFloatStructWithManyFields");

            Assert.True(simpleHfaFloatStructWithManyFields.IsHfa);
            Assert.Equal(_singleType, simpleHfaFloatStructWithManyFields.HfaElementType);

            var simpleHfaDoubleStruct = _testModule.GetType("ValueTypeShapeCharacteristics", "SimpleHfaDoubleStruct");

            Assert.True(simpleHfaDoubleStruct.IsHfa);
            Assert.Equal(_doubleType, simpleHfaDoubleStruct.HfaElementType);
        }
        public void TestSimpleHfa()
        {
            var simpleHfaFloatStruct = _testModule.GetType("ValueTypeShapeCharacteristics", "SimpleHfaFloatStruct");

            Assert.True(simpleHfaFloatStruct.IsHomogeneousAggregate);
            Assert.Equal(Float32Aggregate, simpleHfaFloatStruct.ValueTypeShapeCharacteristics);

            var simpleHfaFloatStructWithManyFields = _testModule.GetType("ValueTypeShapeCharacteristics", "SimpleHfaFloatStructWithManyFields");

            Assert.True(simpleHfaFloatStructWithManyFields.IsHomogeneousAggregate);
            Assert.Equal(Float32Aggregate, simpleHfaFloatStructWithManyFields.ValueTypeShapeCharacteristics);

            var simpleHfaDoubleStruct = _testModule.GetType("ValueTypeShapeCharacteristics", "SimpleHfaDoubleStruct");

            Assert.True(simpleHfaDoubleStruct.IsHomogeneousAggregate);
            Assert.Equal(Float64Aggregate, simpleHfaDoubleStruct.ValueTypeShapeCharacteristics);
        }
        public void TestInstantiation()
        {
            MetadataType t = _testModule.GetType("GenericTypes", "GenericClass`1");

            // Verify that we get just type definitions.
            Assert.NotNull(t);
            Assert.True(t.IsTypeDefinition);
            Assert.NotNull(t.Instantiation);
            Assert.Equal(t.Instantiation.Length, 1);
            Assert.True(t.Instantiation[0].IsTypeDefinition);

            // Verify that we got a method definition
            MethodDesc fooMethod = t.GetMethods().First(m => m.Name == "Foo");

            Assert.True(fooMethod.IsTypicalMethodDefinition);

            // Verify that instantiating a method definition has no effect
            MethodDesc instantiatedMethod = fooMethod.InstantiateSignature(new Instantiation(_context.GetWellKnownType(WellKnownType.Int32)), Instantiation.Empty);

            Assert.Same(fooMethod, instantiatedMethod);

            MetadataType instantiatedType = t.MakeInstantiatedType(_context.GetWellKnownType(WellKnownType.Int32));

            // Verify properties of the instantiated type
            Assert.NotNull(instantiatedType);
            Assert.False(instantiatedType.IsTypeDefinition);
            Assert.NotNull(instantiatedType.Instantiation);
            Assert.Equal(instantiatedType.Instantiation.Length, 1);
            Assert.Equal(instantiatedType.Instantiation[0], _context.GetWellKnownType(WellKnownType.Int32));

            // Verify that we get an instantiated method with the proper signature
            MethodDesc fooInstantiatedMethod = instantiatedType.GetMethods().First(m => m.Name == "Foo");

            Assert.False(fooInstantiatedMethod.IsTypicalMethodDefinition);
            Assert.Equal(fooInstantiatedMethod.Signature.ReturnType, _context.GetWellKnownType(WellKnownType.Int32));
            Assert.Same(fooInstantiatedMethod.GetTypicalMethodDefinition(), fooMethod);
            // This is not a generic method, so they should be the same
            Assert.Same(fooInstantiatedMethod.GetMethodDefinition(), fooInstantiatedMethod);

            // Verify that instantiating a type definition has no effect
            TypeDesc newType = t.InstantiateSignature(new Instantiation(_context.GetWellKnownType(WellKnownType.Int32)), Instantiation.Empty);

            Assert.NotNull(newType);
            Assert.Same(newType, t);
        }
        public void TestInstanceLayoutDoubleBool()
        {
            MetadataType tX64 = _testModuleX64.GetType("Sequential", "ClassDoubleBool");
            MetadataType tX86 = _testModuleX86.GetType("Sequential", "ClassDoubleBool");
            MetadataType tARM = _testModuleARM.GetType("Sequential", "ClassDoubleBool");

            Assert.Equal(0x8, tX64.InstanceByteAlignment.AsInt);
            Assert.Equal(0x8, tARM.InstanceByteAlignment.AsInt);
            Assert.Equal(0x4, tX86.InstanceByteAlignment.AsInt);

            Assert.Equal(0x11, tX64.InstanceByteCountUnaligned.AsInt);
            Assert.Equal(0x11, tARM.InstanceByteCountUnaligned.AsInt);
            Assert.Equal(0x11, tX86.InstanceByteCountUnaligned.AsInt);

            Assert.Equal(0x18, tX64.InstanceByteCount.AsInt);
            Assert.Equal(0x18, tARM.InstanceByteCount.AsInt);
            Assert.Equal(0x14, tX86.InstanceByteCount.AsInt);
        }
Beispiel #15
0
        private TypeDesc FindType(CompilerTypeSystemContext context, string typeName)
        {
            ModuleDesc systemModule = context.SystemModule;

            TypeDesc foundType = systemModule.GetTypeByCustomAttributeTypeName(typeName);

            if (foundType == null)
            {
                throw new CommandLineException($"Type '{typeName}' not found");
            }

            TypeDesc classLibCanon    = systemModule.GetType("System", "__Canon", false);
            TypeDesc classLibUniCanon = systemModule.GetType("System", "__UniversalCanon", false);

            return(foundType.ReplaceTypesInConstructionOfType(
                       new TypeDesc[] { classLibCanon, classLibUniCanon },
                       new TypeDesc[] { context.CanonType, context.UniversalCanonType }));
        }
Beispiel #16
0
        static void GetMatchingTypes(ModuleDesc module, TypeDesc declaringType, string name, int arity, List <TypeSystemEntity> results)
        {
            Debug.Assert(module != null);

            if (declaringType == null)
            {
                int    indexOfLastDot = name.LastIndexOf('.');
                string namespacepart;
                string namepart;
                if (indexOfLastDot > 0 && indexOfLastDot < name.Length - 1)
                {
                    namespacepart = name.Substring(indexOfLastDot - 1);
                    namepart      = name.Substring(indexOfLastDot + 1, name.Length - indexOfLastDot - 1);
                }
                else
                {
                    namespacepart = "";
                    namepart      = name;
                }

                var type = module.GetType(namespacepart, namepart, throwIfNotFound: false);
                if (type != null)
                {
                    results.Add(type);
                }
                return;
            }

            if (declaringType is not MetadataType mdDeclaringType)
            {
                return;
            }

            foreach (var nestedType in mdDeclaringType.GetNestedTypes())
            {
                Debug.Assert(String.IsNullOrEmpty(nestedType.Namespace));
                if (nestedType.Name != name)
                {
                    continue;
                }

                // Compute arity counting only the newly-introduced generic parameters
                var declaringArity  = declaringType.Instantiation.Length;
                int totalArity      = nestedType.Instantiation.Length;
                var nestedTypeArity = totalArity - declaringArity;
                if (nestedTypeArity != arity)
                {
                    continue;
                }

                results.Add(nestedType);
                return;
            }
        }
        public void TestDevirtualizeWithUnallocatedType()
        {
            MetadataType            testType   = _testModule.GetType("Devirtualization", "DevirtualizeWithUnallocatedType");
            DevirtualizationManager scanDevirt = GetDevirtualizationManagerFromScan(testType.GetMethod("Run", null));

            MethodDesc   decl = testType.GetNestedType("Base").GetMethod("Unreachable", null);
            MetadataType impl = testType.GetNestedType("Derived");

            // Base::Unreachable should resolve into Derived::Unreachable on Derived.
            MethodDesc resolvedMethod = scanDevirt.ResolveVirtualMethod(decl, impl);

            Assert.Same(impl.GetMethod("Unreachable", null), resolvedMethod);

            // The resolved method should not be treated as sealed
            Assert.False(scanDevirt.IsEffectivelySealed(resolvedMethod));

            // Even though the metadata based algorithm would say it's sealed
            var devirt = new DevirtualizationManager();

            Assert.True(devirt.IsEffectivelySealed(resolvedMethod));
        }
Beispiel #18
0
        public VirtualMethodEnumerationAlgorithmTests()
        {
            _context = new TestTypeSystemContext(TargetArchitecture.Unknown);
            var systemModule = _context.CreateModuleForSimpleName("CoreTestAssembly");

            _context.SetSystemModule(systemModule);

            _testModule = systemModule;

            _testType = _testModule.GetType("VirtualFunctionOverride", "SimpleGeneric`1")
                        .MakeInstantiatedType(_context.GetWellKnownType(WellKnownType.Object));
        }
        public TypeNameParsingTests()
        {
            _context = new TestTypeSystemContext(TargetArchitecture.X64);

            // TODO-NICE: split test types into a separate, non-core, module
            _testModule = _context.CreateModuleForSimpleName("CoreTestAssembly");
            _context.SetSystemModule(_testModule);

            _simpleType      = _testModule.GetType("TypeNameParsing", "Simple");
            _nestedType      = _simpleType.GetNestedType("Nested");
            _nestedTwiceType = _nestedType.GetNestedType("NestedTwice");

            _genericType          = _testModule.GetType("TypeNameParsing", "Generic`1");
            _nestedGenericType    = _genericType.GetNestedType("NestedGeneric`1");
            _nestedNongenericType = _genericType.GetNestedType("NestedNongeneric");

            _veryGenericType = _testModule.GetType("TypeNameParsing", "VeryGeneric`3");

            _structType = _testModule.GetType("TypeNameParsing", "Struct");

            _coreAssemblyQualifier = ((IAssemblyDesc)_testModule).GetName().FullName;
        }
        public SimpleArrayOfTRuntimeInterfacesAlgorithm(ModuleDesc systemModule)
        {
            _systemModule = systemModule;

            // initialize interfaces
            _arrayRuntimeInterfaces = _systemModule.GetType("System", "Array")?.RuntimeInterfaces
                                      ?? Array.Empty <DefType>();

            _genericRuntimeInterfaces = new MetadataType[s_genericRuntimeInterfacesNames.Length];
            int count = 0;

            for (int i = 0; i < s_genericRuntimeInterfacesNames.Length; ++i)
            {
                MetadataType runtimeInterface = _systemModule.GetType("System.Collections.Generic", s_genericRuntimeInterfacesNames[i], false);
                if (runtimeInterface != null)
                {
                    _genericRuntimeInterfaces[count++] = runtimeInterface;
                }
            }
            ;
            Array.Resize(ref _genericRuntimeInterfaces, count);
        }
Beispiel #21
0
        public void TestSignatureMatches()
        {
            MetadataType atomType    = _testModule.GetType("", "Atom");
            MetadataType aType       = _testModule.GetType("", "A`1");
            MetadataType aOfAtomType = aType.MakeInstantiatedType(new Instantiation(atomType));


            MetadataType           baseClassType            = _testModule.GetType("", "BaseClass`2");
            MethodDesc             baseClassMethod          = baseClassType.GetMethods().Single(m => string.Equals(m.Name, "Method"));
            MethodSignature        baseClassMethodSignature = baseClassMethod.Signature;
            MethodSignatureBuilder matchingSignatureBuilder = new MethodSignatureBuilder(baseClassMethodSignature);

            matchingSignatureBuilder[0] = aOfAtomType;
            matchingSignatureBuilder[1] = atomType;
            MethodSignature matchingSignature = matchingSignatureBuilder.ToSignature();

            MetadataType             derivedClassType    = _testModule.GetType("", "DerivedClass");
            IEnumerable <MethodDesc> derivedClassMethods = derivedClassType.GetMethods().Where(m => string.Equals(m.Name, "Method"));
            IEnumerable <bool>       matches             = derivedClassMethods.Select(m => matchingSignature.Equals(m.Signature));
            int matchCount = matches.Select(b => b ? 1 : 0).Sum();

            Assert.Equal(1, matchCount);
        }
Beispiel #22
0
        public void AddCompilationRoots(IRootingServiceProvider rootProvider)
        {
            ModuleDesc systemModule = ((MetadataType)_context.GetWellKnownType(WellKnownType.Object)).Module;

            MetadataType equalityComparerType = systemModule.GetType("Internal.IntrinsicSupport", "EqualityComparerHelpers", false) as MetadataType;

            if (equalityComparerType != null)
            {
                AddCanonInstantiationsForMethod(rootProvider, equalityComparerType, "GetKnownGenericEquatableComparer", true);
                AddCanonInstantiationsForMethod(rootProvider, equalityComparerType, "GetKnownObjectEquatableComparer", true);
                AddCanonInstantiationsForMethod(rootProvider, equalityComparerType, "GetKnownNullableEquatableComparer", false);
                AddCanonInstantiationsForMethod(rootProvider, equalityComparerType, "GetKnownEnumEquatableComparer", false);
            }

            MetadataType comparerType = systemModule.GetType("Internal.IntrinsicSupport", "ComparerHelpers", false) as MetadataType;

            if (comparerType != null)
            {
                AddCanonInstantiationsForMethod(rootProvider, comparerType, "GetKnownGenericComparer", true);
                AddCanonInstantiationsForMethod(rootProvider, comparerType, "GetKnownObjectComparer", true);
                AddCanonInstantiationsForMethod(rootProvider, comparerType, "GetKnownNullableComparer", false);
            }
        }
Beispiel #23
0
        /// <summary>
        /// Retrieves a namespace type in <paramref name= "module" /> that is well known to the compiler.
        /// Throws an exception if the type doesn't exist.
        /// </summary>
        public static MetadataType GetKnownType(this ModuleDesc module, string @namespace, string name, bool throwIfNotFound = true)
        {
            MetadataType type = module.GetType(@namespace, name, false);

            if (type == null && throwIfNotFound)
            {
                throw new InvalidOperationException(
                          String.Format("Expected type '{0}' not found in module '{1}'",
                                        @namespace.Length > 0 ? String.Concat(@namespace, ".", name) : name,
                                        module));
            }

            return(type);
        }
        public void SetSystemModule(ModuleDesc systemModule)
        {
            _systemModule = systemModule;

            // Sanity check the name table
            Debug.Assert(s_wellKnownTypeNames[(int)WellKnownType.MulticastDelegate - 1] == "MulticastDelegate");

            // Initialize all well known types - it will save us from checking the name for each loaded type
            for (int typeIndex = 0; typeIndex < _wellKnownTypes.Length; typeIndex++)
            {
                MetadataType type = _systemModule.GetType("System", s_wellKnownTypeNames[typeIndex]);
                type.SetWellKnownType((WellKnownType)(typeIndex + 1));
                _wellKnownTypes[typeIndex] = type;
            }
        }
        public RuntimeDeterminedTypesTests()
        {
            _context = new TestTypeSystemContext(TargetArchitecture.Unknown);
            var systemModule = _context.CreateModuleForSimpleName("CoreTestAssembly");

            _context.SetSystemModule(systemModule);

            _testModule = systemModule;

            _referenceType        = _testModule.GetType("Canonicalization", "ReferenceType");
            _otherReferenceType   = _testModule.GetType("Canonicalization", "OtherReferenceType");
            _structType           = _testModule.GetType("Canonicalization", "StructType");
            _otherStructType      = _testModule.GetType("Canonicalization", "OtherStructType");
            _genericReferenceType = _testModule.GetType("Canonicalization", "GenericReferenceType`1");
            _genericStructType    = _testModule.GetType("Canonicalization", "GenericStructType`1");
            _genericReferenceTypeWithThreeParams = _testModule.GetType("Canonicalization", "GenericReferenceTypeWithThreeParams`3");
            _genericStructTypeWithThreeParams    = _testModule.GetType("Canonicalization", "GenericStructTypeWithThreeParams`3");
        }
Beispiel #26
0
        public void TestGenericNameFormatting()
        {
            MetadataType testClass  = _testModule.GetType("ILDisassembler", "TestGenericClass`1");
            EcmaMethod   testMethod = (EcmaMethod)testClass.GetMethod("TestMethod", null);
            EcmaMethodIL methodIL   = EcmaMethodIL.Create(testMethod);

            Dictionary <int, string> interestingLines = new Dictionary <int, string>
            {
                { 4, "IL_0003:  ldstr       \"Hello \\\"World\\\"!\\n\"" },
                { 9, "IL_000D:  call        instance void class ILDisassembler.TestGenericClass`1<!TClassParam>::VoidGenericMethod<string, valuetype ILDisassembler.TestStruct>(!!0, int32, native int, class ILDisassembler.TestClass&)" },
                { 14, "IL_0017:  initobj     !TClassParam" },
                { 16, "IL_001E:  call        !!0 class ILDisassembler.TestGenericClass`1<!TClassParam>::MethodParamGenericMethod<class ILDisassembler.TestClass>(class ILDisassembler.TestGenericClass`1<!!0>, class ILDisassembler.TestGenericClass`1/Nested<!0>, valuetype ILDisassembler.TestStruct*[], !0)" },
                { 24, "IL_0030:  call        !!0 class ILDisassembler.TestGenericClass`1<!TClassParam>::MethodParamGenericMethod<!0>(class ILDisassembler.TestGenericClass`1<!!0>, class ILDisassembler.TestGenericClass`1/Nested<!0>, valuetype ILDisassembler.TestStruct*[], !0)" },
                { 26, "IL_0036:  ldtoken     !TClassParam" },
                { 28, "IL_003C:  ldtoken     valuetype [CoreTestAssembly]System.Nullable`1<int32>" },
                { 31, "IL_0043:  ldc.r8      3.14" },
                { 32, "IL_004C:  ldc.r4      1.68" },
                { 34, "IL_0053:  call        instance valuetype ILDisassembler.TestStruct class ILDisassembler.TestGenericClass`1<!TClassParam>::NonGenericMethod(float64, float32, int16)" },
                { 37, "IL_005A:  ldflda      !0 class ILDisassembler.TestGenericClass`1<!TClassParam>::somefield" },
                { 41, "IL_0067:  stfld       class ILDisassembler.TestClass class ILDisassembler.TestGenericClass`1<!TClassParam>::otherfield" },
                { 44, "IL_006E:  stfld       class ILDisassembler.TestGenericClass`1<class ILDisassembler.TestGenericClass`1<class ILDisassembler.TestClass>> class ILDisassembler.TestGenericClass`1<!TClassParam>::genericfield" },
                { 47, "IL_0075:  stfld       !0[] class ILDisassembler.TestGenericClass`1<!TClassParam>::arrayfield" },
                { 48, "IL_007A:  call        void ILDisassembler.TestClass::NonGenericMethod()" },
                { 49, "IL_007F:  ldsflda     valuetype ILDisassembler.TestStruct ILDisassembler.TestClass::somefield" },
                { 50, "IL_0084:  initobj     ILDisassembler.TestStruct" }
            };

            ILDisassembler disasm = new ILDisassembler(methodIL);

            int numLines = 1;

            while (disasm.HasNextInstruction)
            {
                string line = disasm.GetNextInstruction();
                string expectedLine;
                if (interestingLines.TryGetValue(numLines, out expectedLine))
                {
                    Assert.Equal(expectedLine, line);
                }
                numLines++;
            }

            Assert.Equal(52, numLines);
        }
        public override MetadataType GetType(string nameSpace, string name, bool throwIfNotFound = true)
        {
            QualifiedNamespaceDefinition[] namespaceDefinitions = GetNamespaceDefinitionsFromString(nameSpace);

            foreach (QualifiedNamespaceDefinition namespaceDefinition in namespaceDefinitions)
            {
                // At least the namespace was found.
                MetadataReader metadataReader = namespaceDefinition.MetadataReader;

                // Now scan the type definitions on this namespace
                foreach (var typeDefinitionHandle in namespaceDefinition.Definition.TypeDefinitions)
                {
                    var typeDefinition = metadataReader.GetTypeDefinition(typeDefinitionHandle);
                    if (typeDefinition.Name.StringEquals(name, metadataReader))
                    {
                        return((MetadataType)namespaceDefinition.MetadataUnit.GetType((Handle)typeDefinitionHandle));
                    }
                }
            }

            foreach (QualifiedNamespaceDefinition namespaceDefinition in namespaceDefinitions)
            {
                // At least the namespace was found.
                MetadataReader metadataReader = namespaceDefinition.MetadataReader;

                // Now scan the type forwarders on this namespace
                foreach (var typeForwarderHandle in namespaceDefinition.Definition.TypeForwarders)
                {
                    var typeForwarder = metadataReader.GetTypeForwarder(typeForwarderHandle);
                    if (typeForwarder.Name.StringEquals(name, metadataReader))
                    {
                        ModuleDesc forwardTargetModule = namespaceDefinition.MetadataUnit.GetModule(typeForwarder.Scope);
                        return(forwardTargetModule.GetType(nameSpace, name, throwIfNotFound));
                    }
                }
            }

            if (throwIfNotFound)
            {
                throw CreateTypeLoadException(nameSpace + "." + name);
            }

            return(null);
        }
Beispiel #28
0
        // Returns null if no matching type is found
        private static TypeDesc GetMatchingType(ModuleDesc module, TypeDesc type)
        {
            var metadataType   = (MetadataType)type;
            var containingType = metadataType.ContainingType;

            if (containingType != null)
            {
                var matchingContainingType = (MetadataType)GetMatchingType(module, containingType);
                if (matchingContainingType == null)
                {
                    return(null);
                }
                return(matchingContainingType.GetNestedType(metadataType.Name));
            }
            else
            {
                return(module.GetType(metadataType.Namespace, metadataType.Name, false));
            }
        }
        private void InitLibraryInitializers()
        {
            Debug.Assert(_libraryInitializerMethods == null);

            _libraryInitializerMethods = new List <MethodDesc>();

            foreach (var entry in s_assembliesWithLibraryInitializers)
            {
                if (_isCppCodeGen && !entry.UseWithCppCodeGen)
                {
                    continue;
                }

                ModuleDesc assembly = entry.Assembly == ClassLibraryPlaceHolderString
                    ? _context.SystemModule
                    : _context.ResolveAssembly(new AssemblyName(entry.Assembly), false);

                if (assembly == null)
                {
                    continue;
                }

                TypeDesc containingType = assembly.GetType(LibraryInitializerContainerNamespaceName, LibraryInitializerContainerTypeName, false);
                if (containingType == null)
                {
                    continue;
                }

                MethodDesc initializerMethod = containingType.GetMethod(LibraryInitializerMethodName, null);
                if (initializerMethod == null)
                {
                    continue;
                }

                _libraryInitializerMethods.Add(initializerMethod);
            }
        }
Beispiel #30
0
 public override void SetSystemModule(ModuleDesc systemModule)
 {
     base.SetSystemModule(systemModule);
     _supportsLazyCctors = systemModule.GetType("System.Runtime.CompilerServices", "ClassConstructorRunner", false) != null;
 }