Пример #1
0
        public static bool CompareTypeReferenceToDefinition(TypeReferenceHandle tr1, MetadataReader mr1, TypeDefinitionHandle td2, MetadataReader mr2)
        {
            // TODO! The correct implementation here is probably to call into the assembly binder, but that's not available due to layering.
            // For now, just implement comparison, which will be equivalent in all cases until we support loading multiple copies of the same assembly

            TypeReference trData1 = mr1.GetTypeReference(tr1);
            TypeDefinition tdData2 = mr2.GetTypeDefinition(td2);

            if (!trData1.TypeName.StringEquals(tdData2.Name.GetConstantStringValue(mr2).Value, mr1))
                return false;

            switch (trData1.ParentNamespaceOrType.HandleType)
            {
                case HandleType.TypeReference:
                    if (tdData2.EnclosingType.IsNull(mr2))
                        return false;

                    return CompareTypeReferenceToDefinition(trData1.ParentNamespaceOrType.ToTypeReferenceHandle(mr1), mr1, tdData2.EnclosingType, mr2);

                case HandleType.NamespaceReference:
                    return CompareNamespaceReferenceToDefinition(trData1.ParentNamespaceOrType.ToNamespaceReferenceHandle(mr1), mr1, tdData2.NamespaceDefinition, mr2);

                default:
                    Debug.Assert(false);
                    throw new BadImageFormatException();
            }
        }
Пример #2
0
        private TypeDefTreatment GetWellKnownTypeDefinitionTreatment(TypeDefinitionHandle typeDef)
        {
            InitializeProjectedTypes();

            StringHandle name = TypeDefTable.GetName(typeDef);

            int index = StringStream.BinarySearchRaw(s_projectedTypeNames, name);
            if (index < 0)
            {
                return TypeDefTreatment.None;
            }

            StringHandle namespaceName = TypeDefTable.GetNamespace(typeDef);
            if (StringStream.EqualsRaw(namespaceName, StringStream.GetVirtualValue(s_projectionInfos[index].ClrNamespace)))
            {
                return s_projectionInfos[index].Treatment;
            }

            // TODO: we can avoid this comparison if info.DotNetNamespace == info.WinRtNamespace 
            if (StringStream.EqualsRaw(namespaceName, s_projectionInfos[index].WinRTNamespace))
            {
                return s_projectionInfos[index].Treatment | TypeDefTreatment.MarkInternalFlag;
            }

            return TypeDefTreatment.None;
        }
Пример #3
0
        internal static ClassLayoutRow GetTypeLayout(this MetadataReader reader, TypeDefinitionHandle typeDef)
        {
            uint rowId = reader.ClassLayoutTable.FindRow(typeDef);
            if (rowId == 0)
            {
                return default(ClassLayoutRow);
            }

            return GetTypeLayout(reader, rowId);
        }
Пример #4
0
        internal EcmaType(EcmaModule module, TypeDefinitionHandle handle)
        {
            _module = module;
            _handle = handle;

            _typeDefinition = module.MetadataReader.GetTypeDefinition(handle);

            _baseType = this; // Not yet initialized flag

#if DEBUG
            // Initialize name eagerly in debug builds for convenience
            this.ToString();
#endif
        }
        protected RuntimeInspectionOnlyNamedType(MetadataReader reader, TypeDefinitionHandle typeDefinitionHandle)
            : base()
        {
#if DEBUG
            if (!(this.InternalViolatesTypeIdentityRules))
            {
                RuntimeTypeHandle runtimeTypeHandle;
                if (ReflectionCoreExecution.ExecutionEnvironment.TryGetNamedTypeForMetadata(reader, typeDefinitionHandle, out runtimeTypeHandle))
                    Debug.Assert(false, "Type identity violation: You must use a RuntimeEENamedType to represent this type as RH has generated an EEType for it.");
            }
#endif
            _reader = reader;
            _typeDefinitionHandle = typeDefinitionHandle;
            _typeDefinition = _typeDefinitionHandle.GetTypeDefinition(_reader);
        }
Пример #6
0
        /// <summary>
        /// Returns true if the nested type should be imported. 
        /// </summary>
        public static bool ShouldImportNestedType(this PEModule module, TypeDefinitionHandle typeDef)
        {
            // Currently, it appears that we must import ALL types, even private ones,
            // in order to maintain language semantics. This is because a class may implement
            // private interfaces, and we use the interfaces (even if inaccessible) to determine
            // conversions. For example:
            //
            // public class A: IEnumerable<A.X>
            // { 
            //    private class X: ICloneable {}
            // }
            //
            // Code compiling against A can convert A to IEnumerable<ICloneable>. Knowing this requires
            // importing the type A.X.

            return true;
        }
Пример #7
0
        internal uint CalculateTypeDefTreatmentAndRowId(TypeDefinitionHandle handle)
        {
            Debug.Assert(_metadataKind != MetadataKind.Ecma335);

            TypeDefTreatment treatment;

            TypeAttributes flags   = TypeDefTable.GetFlags(handle);
            Handle         extends = TypeDefTable.GetExtends(handle);

            if ((flags & TypeAttributes.WindowsRuntime) != 0)
            {
                if (_metadataKind == MetadataKind.WindowsMetadata)
                {
                    treatment = GetWellKnownTypeDefinitionTreatment(handle);
                    if (treatment != TypeDefTreatment.None)
                    {
                        return(TreatmentAndRowId((byte)treatment, handle.RowId));
                    }

                    // Is this an attribute?
                    if (extends.Kind == HandleKind.TypeReference && IsSystemAttribute((TypeReferenceHandle)extends))
                    {
                        treatment = TypeDefTreatment.NormalAttribute;
                    }
                    else
                    {
                        treatment = TypeDefTreatment.NormalNonAttribute;
                    }
                }
                else if (_metadataKind == MetadataKind.ManagedWindowsMetadata && NeedsWinRTPrefix(flags, extends))
                {
                    // WinMDExp emits two versions of RuntimeClasses and Enums:
                    //
                    //    public class Foo {}            // the WinRT reference class
                    //    internal class <CLR>Foo {}     // the implementation class that we want WinRT consumers to ignore
                    //
                    // The adapter's job is to undo WinMDExp's transformations. I.e. turn the above into:
                    //
                    //    internal class <WinRT>Foo {}   // the WinRT reference class that we want CLR consumers to ignore
                    //    public class Foo {}            // the implementation class
                    //
                    // We only add the <WinRT> prefix here since the WinRT view is the only view that is marked WindowsRuntime
                    // De-mangling the CLR name is done below.


                    // tomat: The CLR adapter implements a back-compat quirk: Enums exported with an older WinMDExp have only one version
                    // not marked with tdSpecialName. These enums should *not* be mangled and flipped to private.
                    // We don't implement this flag since the WinMDs producted by the older WinMDExp are not used in the wild.

                    treatment = TypeDefTreatment.PrefixWinRTName;
                }
                else
                {
                    treatment = TypeDefTreatment.None;
                }

                // Scan through Custom Attributes on type, looking for interesting bits. We only
                // need to do this for RuntimeClasses
                if ((treatment == TypeDefTreatment.PrefixWinRTName || treatment == TypeDefTreatment.NormalNonAttribute))
                {
                    if ((flags & TypeAttributes.Interface) == 0 &&
                        HasAttribute(handle, "Windows.UI.Xaml", "TreatAsAbstractComposableClassAttribute"))
                    {
                        treatment |= TypeDefTreatment.MarkAbstractFlag;
                    }
                }
            }
            else if (_metadataKind == MetadataKind.ManagedWindowsMetadata && IsClrImplementationType(handle))
            {
                // <CLR> implementation classes are not marked WindowsRuntime, but still need to be modified
                // by the adapter.
                treatment = TypeDefTreatment.UnmangleWinRTName;
            }
            else
            {
                treatment = TypeDefTreatment.None;
            }

            return(TreatmentAndRowId((byte)treatment, handle.RowId));
        }
Пример #8
0
 internal void GetMethodRange(TypeDefinitionHandle typeDef, out int firstMethodRowId, out int lastMethodRowId)
 {
     uint typeDefRowId = typeDef.RowId;
     firstMethodRowId = (int)this.TypeDefTable.GetMethodStart(typeDefRowId);
     if (firstMethodRowId == 0)
     {
         firstMethodRowId = 1;
         lastMethodRowId = 0;
     }
     else if (typeDefRowId == this.TypeDefTable.NumberOfRows)
     {
         lastMethodRowId = (int)(this.UseMethodPtrTable ? this.MethodPtrTable.NumberOfRows : this.MethodDefTable.NumberOfRows);
     }
     else
     {
         lastMethodRowId = (int)this.TypeDefTable.GetMethodStart(typeDefRowId + 1) - 1;
     }
 }
Пример #9
0
        private bool IsClrImplementationType(TypeDefinitionHandle typeDef)
        {
            var attrs = TypeDefTable.GetFlags(typeDef);

            if ((attrs & (TypeAttributes.VisibilityMask | TypeAttributes.SpecialName)) != TypeAttributes.SpecialName)
            {
                return false;
            }

            return StringStream.StartsWithRaw(TypeDefTable.GetName(typeDef), ClrPrefix);
        }
Пример #10
0
 public void AddPropertyMap(TypeDefinitionHandle declaringType, PropertyDefinitionHandle propertyList)
 {
     _propertyMapTable.Add(new PropertyMapRow
     {
         Parent = (uint)MetadataTokens.GetRowNumber(declaringType),
         PropertyList = (uint)MetadataTokens.GetRowNumber(propertyList)
     });
 }
Пример #11
0
 private static PENamedTypeSymbol GetType(PEModuleSymbol module, TypeDefinitionHandle typeHandle)
 {
     var metadataDecoder = new MetadataDecoder(module);
     return (PENamedTypeSymbol)metadataDecoder.GetTypeOfToken(typeHandle);
 }
Пример #12
0
        internal void GetInterfaceImplRange(
            TypeDefinitionHandle typeDef,
            out int firstImplRowId,
            out int lastImplRowId)
        {
            int typeDefRid = typeDef.RowId;

            int startRowNumber, endRowNumber;
            this.Block.BinarySearchReferenceRange(
                this.NumberOfRows,
                this.RowSize,
                _ClassOffset,
                (uint)typeDefRid,
                _IsTypeDefTableRowRefSizeSmall,
                out startRowNumber,
                out endRowNumber);

            if (startRowNumber == -1)
            {
                firstImplRowId = 1;
                lastImplRowId = 0;
            }
            else
            {
                firstImplRowId = startRowNumber + 1;
                lastImplRowId = endRowNumber + 1;
            }
        }
        public sealed override IEnumerable <CustomAttributeData> GetPsuedoCustomAttributes(MetadataReader reader, MethodHandle methodHandle, TypeDefinitionHandle declaringTypeHandle)
        {
            MethodImplAttributes implAttributes = methodHandle.GetMethod(reader).ImplFlags;

            if (0 != (implAttributes & MethodImplAttributes.PreserveSig))
            {
                yield return(ReflectionCoreExecution.ExecutionDomain.GetCustomAttributeData(typeof(PreserveSigAttribute), null, null));
            }
        }
        public sealed override IEnumerable <CustomAttributeData> GetPsuedoCustomAttributes(MetadataReader reader, TypeDefinitionHandle typeDefinitionHandle)
        {
            TypeAttributes attributes = typeDefinitionHandle.GetTypeDefinition(reader).Flags;

            if (0 != (attributes & TypeAttributes.Import))
            {
                yield return(ReflectionCoreExecution.ExecutionDomain.GetCustomAttributeData(typeof(ComImportAttribute), null, null));
            }
        }
Пример #15
0
 public GenericContext(TypeDefinitionHandle declaringType, PEFile module)
 {
     this.module        = module;
     this.declaringType = declaringType;
 }
Пример #16
0
 public GenericContext(MethodDefinitionHandle method, PEFile module)
 {
     this.module        = module;
     this.method        = method;
     this.declaringType = module.Metadata.GetMethodDefinition(method).GetDeclaringType();
 }
Пример #17
0
 ITypeSignature ISimpleTypeProvider <ITypeSignature> .GetTypeFromDefinition(MetadataReader reader, TypeDefinitionHandle handle, byte rawTypeKind)
 {
     return(new TypeDefinition(handle));
 }
Пример #18
0
 public TypeDefinition(TypeDefinitionHandle handle)
 {
     this.handle = handle;
 }
Пример #19
0
        internal TypeDefinitionHandle FindEnclosingType(TypeDefinitionHandle nestedTypeDef)
        {
            int rowNumber =
              this.Block.BinarySearchReference(
                this.NumberOfRows,
                this.RowSize,
                _NestedClassOffset,
                (uint)nestedTypeDef.RowId,
                _IsTypeDefTableRowRefSizeSmall);

            if (rowNumber == -1)
            {
                return default(TypeDefinitionHandle);
            }

            return TypeDefinitionHandle.FromRowId(this.Block.PeekReference(rowNumber * this.RowSize + _EnclosingClassOffset, _IsTypeDefTableRowRefSizeSmall));
        }
        public sealed override IEnumerable <CustomAttributeData> GetPsuedoCustomAttributes(MetadataReader reader, FieldHandle fieldHandle, TypeDefinitionHandle declaringTypeHandle)
        {
            TypeAttributes layoutKind = declaringTypeHandle.GetTypeDefinition(reader).Flags & TypeAttributes.LayoutMask;

            if (layoutKind == TypeAttributes.ExplicitLayout)
            {
                int offset = (int)(fieldHandle.GetField(reader).Offset);
                CustomAttributeTypedArgument offsetArgument = ExtensibleCustomAttributeData.CreateCustomAttributeTypedArgument(typeof(Int32), offset);
                yield return(ReflectionCoreExecution.ExecutionDomain.GetCustomAttributeData(typeof(FieldOffsetAttribute), new CustomAttributeTypedArgument[] { offsetArgument }, null));
            }
        }
Пример #21
0
        internal void GetFieldRange(TypeDefinitionHandle typeDef, out int firstFieldRowId, out int lastFieldRowId)
        {
            int typeDefRowId = typeDef.RowId;

            firstFieldRowId = this.TypeDefTable.GetFieldStart(typeDefRowId);
            if (firstFieldRowId == 0)
            {
                firstFieldRowId = 1;
                lastFieldRowId = 0;
            }
            else if (typeDefRowId == this.TypeDefTable.NumberOfRows)
            {
                lastFieldRowId = (this.UseFieldPtrTable) ? this.FieldPtrTable.NumberOfRows : this.FieldTable.NumberOfRows;
            }
            else
            {
                lastFieldRowId = this.TypeDefTable.GetFieldStart(typeDefRowId + 1) - 1;
            }
        }
 public sealed override IEnumerable <CustomAttributeData> GetPsuedoCustomAttributes(MetadataReader reader, EventHandle eventHandle, TypeDefinitionHandle declaringTypeHandle)
 {
     return(Empty <CustomAttributeData> .Enumerable);
 }
Пример #23
0
 public void AddInterfaceImplementation(
     TypeDefinitionHandle type,
     EntityHandle implementedInterface)
 {
     _interfaceImplTable.Add(new InterfaceImplRow
     {
         Class = (uint)MetadataTokens.GetRowNumber(type),
         Interface = (uint)CodedIndex.ToTypeDefOrRef(implementedInterface)
     });
 }
Пример #24
0
            protected override IEntityHandleObject CreateValueFromKey(EntityHandle handle)
            {
                object item;

                switch (handle.Kind)
                {
                case HandleKind.TypeDefinition:
                    item = new EcmaType(_module, (TypeDefinitionHandle)handle);
                    break;

                case HandleKind.MethodDefinition:
                {
                    MethodDefinitionHandle methodDefinitionHandle = (MethodDefinitionHandle)handle;
                    TypeDefinitionHandle   typeDefinitionHandle   = _module._metadataReader.GetMethodDefinition(methodDefinitionHandle).GetDeclaringType();
                    EcmaType type = (EcmaType)_module.GetObject(typeDefinitionHandle);
                    item = new EcmaMethod(type, methodDefinitionHandle);
                }
                break;

                case HandleKind.FieldDefinition:
                {
                    FieldDefinitionHandle fieldDefinitionHandle = (FieldDefinitionHandle)handle;
                    TypeDefinitionHandle  typeDefinitionHandle  = _module._metadataReader.GetFieldDefinition(fieldDefinitionHandle).GetDeclaringType();
                    EcmaType type = (EcmaType)_module.GetObject(typeDefinitionHandle);
                    item = new EcmaField(type, fieldDefinitionHandle);
                }
                break;

                case HandleKind.TypeReference:
                    item = _module.ResolveTypeReference((TypeReferenceHandle)handle);
                    break;

                case HandleKind.MemberReference:
                    item = _module.ResolveMemberReference((MemberReferenceHandle)handle);
                    break;

                case HandleKind.AssemblyReference:
                    item = _module.ResolveAssemblyReference((AssemblyReferenceHandle)handle);
                    break;

                case HandleKind.TypeSpecification:
                    item = _module.ResolveTypeSpecification((TypeSpecificationHandle)handle);
                    break;

                case HandleKind.MethodSpecification:
                    item = _module.ResolveMethodSpecification((MethodSpecificationHandle)handle);
                    break;

                case HandleKind.ExportedType:
                    item = _module.ResolveExportedType((ExportedTypeHandle)handle);
                    break;

                case HandleKind.StandaloneSignature:
                    item = _module.ResolveStandaloneSignature((StandaloneSignatureHandle)handle);
                    break;

                case HandleKind.ModuleDefinition:
                    // ECMA-335 Partition 2 II.22.38 1d: This should not occur in a CLI ("compressed metadata") module,
                    // but resolves to "current module".
                    item = _module;
                    break;

                case HandleKind.ModuleReference:
                    item = _module.ResolveModuleReference((ModuleReferenceHandle)handle);
                    break;

                default:
                    throw new BadImageFormatException("Unknown metadata token type: " + handle.Kind);
                }

                switch (handle.Kind)
                {
                case HandleKind.TypeDefinition:
                case HandleKind.MethodDefinition:
                case HandleKind.FieldDefinition:
                    // type/method/field definitions directly correspond to their target item.
                    return((IEntityHandleObject)item);

                default:
                    // Everything else is some form of reference which cannot be self-describing
                    return(new EcmaObjectLookupWrapper(handle, item));
                }
            }
Пример #25
0
 public void AddMethodImplementation(
     TypeDefinitionHandle type,
     EntityHandle methodBody,
     EntityHandle methodDeclaration)
 {
     _methodImplTable.Add(new MethodImplRow
     {
         Class = (uint)MetadataTokens.GetRowNumber(type),
         MethodBody = (uint)CodedIndex.ToMethodDefOrRef(methodBody),
         MethodDecl = (uint)CodedIndex.ToMethodDefOrRef(methodDeclaration)
     });
 }
Пример #26
0
 //==============================================================================================
 // Reflection Mapping Tables
 //==============================================================================================
 public abstract bool TryGetMetadataForNamedType(RuntimeTypeHandle runtimeTypeHandle, out MetadataReader metadataReader, out TypeDefinitionHandle typeDefHandle);
Пример #27
0
 public Type GetTypeFromDefinition(MetadataReader reader, TypeDefinitionHandle handle, byte rawTypeKind) =>
 (Type)cx.Create(handle);
Пример #28
0
 public abstract bool TryGetNamedTypeForMetadata(MetadataReader metadataReader, TypeDefinitionHandle typeDefHandle, out RuntimeTypeHandle runtimeTypeHandle);
Пример #29
0
        internal void GetPropertyRange(TypeDefinitionHandle typeDef, out int firstPropertyRowId, out int lastPropertyRowId)
        {
            uint propertyMapRowId = this.PropertyMapTable.FindPropertyMapRowIdFor(typeDef);
            if (propertyMapRowId == 0)
            {
                firstPropertyRowId = 1;
                lastPropertyRowId = 0;
                return;
            }

            firstPropertyRowId = (int)this.PropertyMapTable.GetPropertyListStartFor(propertyMapRowId);
            if (propertyMapRowId == this.PropertyMapTable.NumberOfRows)
            {
                lastPropertyRowId = (int)(this.UsePropertyPtrTable ? this.PropertyPtrTable.NumberOfRows : this.PropertyTable.NumberOfRows);
            }
            else
            {
                lastPropertyRowId = (int)this.PropertyMapTable.GetPropertyListStartFor(propertyMapRowId + 1) - 1;
            }
        }
Пример #30
0
 public abstract IEnumerable <CustomAttributeData> GetPsuedoCustomAttributes(MetadataReader reader, TypeDefinitionHandle typeDefinitionHandle);
Пример #31
0
        private uint CalculateMethodDefTreatmentAndRowId(MethodDefinitionHandle methodDef)
        {
            MethodDefTreatment treatment = MethodDefTreatment.Implementation;

            TypeDefinitionHandle parentTypeDef = GetDeclaringType(methodDef);
            TypeAttributes       parentFlags   = TypeDefTable.GetFlags(parentTypeDef);

            if ((parentFlags & TypeAttributes.WindowsRuntime) != 0)
            {
                if (IsClrImplementationType(parentTypeDef))
                {
                    treatment = MethodDefTreatment.Implementation;
                }
                else if (parentFlags.IsNested())
                {
                    treatment = MethodDefTreatment.Implementation;
                }
                else if ((parentFlags & TypeAttributes.Interface) != 0)
                {
                    treatment = MethodDefTreatment.InterfaceMethod;
                }
                else if (_metadataKind == MetadataKind.ManagedWindowsMetadata && (parentFlags & TypeAttributes.Public) == 0)
                {
                    treatment = MethodDefTreatment.Implementation;
                }
                else
                {
                    treatment = MethodDefTreatment.Other;

                    var parentBaseType = TypeDefTable.GetExtends(parentTypeDef);
                    if (parentBaseType.Kind == HandleKind.TypeReference)
                    {
                        switch (GetSpecialTypeRefTreatment((TypeReferenceHandle)parentBaseType))
                        {
                        case TypeRefTreatment.SystemAttribute:
                            treatment = MethodDefTreatment.AttributeMethod;
                            break;

                        case TypeRefTreatment.SystemDelegate:
                            treatment = MethodDefTreatment.DelegateMethod | MethodDefTreatment.MarkPublicFlag;
                            break;
                        }
                    }
                }
            }

            if (treatment == MethodDefTreatment.Other)
            {
                // we want to hide the method if it implements
                // only redirected interfaces
                // We also want to check if the methodImpl is IClosable.Close,
                // so we can change the name
                bool seenRedirectedInterfaces    = false;
                bool seenNonRedirectedInterfaces = false;

                bool isIClosableClose = false;

                foreach (var methodImplHandle in new MethodImplementationHandleCollection(this, parentTypeDef))
                {
                    MethodImplementation methodImpl = GetMethodImplementation(methodImplHandle);
                    if (methodImpl.MethodBody == methodDef)
                    {
                        Handle declaration = methodImpl.MethodDeclaration;

                        // See if this MethodImpl implements a redirected interface
                        // In WinMD, MethodImpl will always use MemberRef and TypeRefs to refer to redirected interfaces,
                        // even if they are in the same module.
                        if (declaration.Kind == HandleKind.MemberReference &&
                            ImplementsRedirectedInterface((MemberReferenceHandle)declaration, out isIClosableClose))
                        {
                            seenRedirectedInterfaces = true;
                            if (isIClosableClose)
                            {
                                // This method implements IClosable.Close
                                // Let's rename to IDisposable later
                                // Once we know this implements IClosable.Close, we are done
                                // looking
                                break;
                            }
                        }
                        else
                        {
                            // Now we know this implements a non-redirected interface
                            // But we need to keep looking, just in case we got a methodimpl that
                            // implements the IClosable.Close method and needs to be renamed
                            seenNonRedirectedInterfaces = true;
                        }
                    }
                }

                if (isIClosableClose)
                {
                    treatment = MethodDefTreatment.DisposeMethod;
                }
                else if (seenRedirectedInterfaces && !seenNonRedirectedInterfaces)
                {
                    // Only hide if all the interfaces implemented are redirected
                    treatment = MethodDefTreatment.HiddenInterfaceImplementation;
                }
            }

            // If treatment is other, then this is a non-managed WinRT runtime class definition
            // Find out about various bits that we apply via attributes and name parsing
            if (treatment == MethodDefTreatment.Other)
            {
                treatment |= GetMethodTreatmentFromCustomAttributes(methodDef);
            }

            return(TreatmentAndRowId((byte)treatment, methodDef.RowId));
        }
Пример #32
0
 public abstract IEnumerable <CustomAttributeData> GetPsuedoCustomAttributes(MetadataReader reader, EventHandle eventHandle, TypeDefinitionHandle declaringTypeHandle);
Пример #33
0
        public void SimpleSignatureProviderCoverage()
        {
            using (FileStream stream = File.OpenRead(AssemblyPathHelper.GetAssemblyLocation(typeof(SignaturesToDecode <>).GetTypeInfo().Assembly)))
                using (var peReader = new PEReader(stream))
                {
                    MetadataReader       reader     = peReader.GetMetadataReader();
                    var                  provider   = new DisassemblingTypeProvider();
                    TypeDefinitionHandle typeHandle = TestMetadataResolver.FindTestType(reader, typeof(SignaturesToDecode <>));
                    Assert.Equal("System.Reflection.Metadata.Decoding.Tests.SignatureDecoderTests/SignaturesToDecode`1", provider.GetTypeFromHandle(reader, genericContext: null, handle: typeHandle));

                    TypeDefinition type = reader.GetTypeDefinition(typeHandle);
                    Dictionary <string, string> expectedFields        = GetExpectedFieldSignatures();
                    ImmutableArray <string>     genericTypeParameters = type.GetGenericParameters().Select(h => reader.GetString(reader.GetGenericParameter(h).Name)).ToImmutableArray();

                    var genericTypeContext = new DisassemblingGenericContext(genericTypeParameters, ImmutableArray <string> .Empty);

                    foreach (var fieldHandle in type.GetFields())
                    {
                        FieldDefinition field     = reader.GetFieldDefinition(fieldHandle);
                        string          fieldName = reader.GetString(field.Name);
                        string          expected;
                        Assert.True(expectedFields.TryGetValue(fieldName, out expected), "Unexpected field: " + fieldName);
                        Assert.Equal(expected, field.DecodeSignature(provider, genericTypeContext));
                    }

                    Dictionary <string, string> expectedMethods = GetExpectedMethodSignatures();
                    foreach (var methodHandle in type.GetMethods())
                    {
                        MethodDefinition method = reader.GetMethodDefinition(methodHandle);

                        ImmutableArray <string> genericMethodParameters = method.GetGenericParameters().Select(h => reader.GetString(reader.GetGenericParameter(h).Name)).ToImmutableArray();
                        var genericMethodContext = new DisassemblingGenericContext(genericTypeParameters, genericMethodParameters);

                        string methodName = reader.GetString(method.Name);
                        string expected;
                        Assert.True(expectedMethods.TryGetValue(methodName, out expected), "Unexpected method: " + methodName);
                        MethodSignature <string> signature = method.DecodeSignature(provider, genericMethodContext);
                        Assert.True(signature.Header.Kind == SignatureKind.Method);

                        if (methodName.StartsWith("Generic"))
                        {
                            Assert.Equal(1, signature.GenericParameterCount);
                        }
                        else
                        {
                            Assert.Equal(0, signature.GenericParameterCount);
                        }

                        Assert.True(signature.GenericParameterCount <= 1 && (methodName != "GenericMethodParameter" || signature.GenericParameterCount == 1));
                        Assert.Equal(expected, provider.GetFunctionPointerType(signature));
                    }

                    Dictionary <string, string> expectedProperties = GetExpectedPropertySignatures();
                    foreach (var propertyHandle in type.GetProperties())
                    {
                        PropertyDefinition property     = reader.GetPropertyDefinition(propertyHandle);
                        string             propertyName = reader.GetString(property.Name);
                        string             expected;
                        Assert.True(expectedProperties.TryGetValue(propertyName, out expected), "Unexpected property: " + propertyName);
                        MethodSignature <string> signature = property.DecodeSignature(provider, genericTypeContext);
                        Assert.True(signature.Header.Kind == SignatureKind.Property);
                        Assert.Equal(expected, provider.GetFunctionPointerType(signature));
                    }

                    Dictionary <string, string> expectedEvents = GetExpectedEventSignatures();
                    foreach (var eventHandle in type.GetEvents())
                    {
                        EventDefinition @event    = reader.GetEventDefinition(eventHandle);
                        string          eventName = reader.GetString(@event.Name);
                        string          expected;
                        Assert.True(expectedEvents.TryGetValue(eventName, out expected), "Unexpected event: " + eventName);

                        Assert.Equal(expected, provider.GetTypeFromHandle(reader, genericTypeContext, @event.Type));
                    }

                    Assert.Equal($"[{MetadataReaderTestHelpers.CollectionsAssemblyName}]System.Collections.Generic.List`1<!T>", provider.GetTypeFromHandle(reader, genericTypeContext, handle: type.BaseType));
                }
        }
Пример #34
0
        /// <inheritdoc cref="ISimpleTypeProvider{TType}" />
        public TypeDescriptor GetTypeFromDefinition(MetadataReader reader, TypeDefinitionHandle handle, byte rawTypeKind)
        {
            var definition = reader.GetTypeDefinition(handle);

            return(reader.ToTypeDescriptor(definition));
        }
Пример #35
0
 internal EntityHandle GetExtends(TypeDefinitionHandle handle)
 {
     int rowOffset = (handle.RowId - 1) * this.RowSize;
     return TypeDefOrRefTag.ConvertToHandle(this.Block.PeekTaggedReference(rowOffset + _ExtendsOffset, _IsTypeDefOrRefRefSizeSmall));
 }
        public IHandleTypeNamedWrapper GetTypeFromDefinition(MetadataReader reader, TypeDefinitionHandle handle, byte rawTypeKind)
        {
            var assemblyMetadata = MetadataRepository.GetAssemblyMetadataForReader(reader);

            return(TypeWrapper.Create(handle, assemblyMetadata));
        }
Пример #37
0
        internal GenericParameterHandleCollection FindGenericParametersForType(TypeDefinitionHandle typeDef)
        {
            ushort count = 0;
            uint searchCodedTag = TypeOrMethodDefTag.ConvertTypeDefRowIdToTag(typeDef);
            int startRid = (int)this.BinarySearchTag(searchCodedTag, ref count);

            return new GenericParameterHandleCollection(startRid, count);
        }
 public TypeDesc GetTypeFromDefinition(MetadataReader reader, TypeDefinitionHandle handle, SignatureTypeHandleCode code)
 {
     Debug.Assert(reader == _module.MetadataReader);
     return(_module.GetType(handle));
 }
Пример #39
0
 //
 // Main routine to resolve a typeDefinition.
 //
 internal static RuntimeType ResolveTypeDefinition(this ReflectionDomain reflectionDomain, MetadataReader reader, TypeDefinitionHandle typeDefinitionHandle)
 {
     return RuntimeTypeUnifierEx.GetNamedType(reader, typeDefinitionHandle);
 }
Пример #40
0
 public static DiscoveredType FromDefinedType(MetadataReader reader, TypeDefinitionHandle handle)
 => new DiscoveredType(reader, handle);
Пример #41
0
        private static String GetTypeFullNameFromTypeDef(TypeDefinitionHandle typeDefinitionHandle, MetadataReader reader, List<int> genericParameterOffsets)
        {
            String s = "";

            TypeDefinition typeDefinition = typeDefinitionHandle.GetTypeDefinition(reader);
            s = typeDefinition.Name.GetString(reader);

            TypeDefinitionHandle enclosingTypeDefHandle = typeDefinition.EnclosingType;
            if (!enclosingTypeDefHandle.IsNull(reader))
            {
                String containingTypeName = GetTypeFullNameFromTypeDef(enclosingTypeDefHandle, reader, genericParameterOffsets);
                s = containingTypeName + "." + s;
            }
            else
            {
                NamespaceDefinitionHandle namespaceHandle = typeDefinition.NamespaceDefinition;
                for (; ;)
                {
                    NamespaceDefinition namespaceDefinition = namespaceHandle.GetNamespaceDefinition(reader);
                    String namespacePart = namespaceDefinition.Name.GetStringOrNull(reader);
                    if (namespacePart == null)
                        break; // Reached the root namespace.
                    s = namespacePart + "." + s;
                    if (namespaceDefinition.ParentScopeOrNamespace.HandleType != HandleType.NamespaceDefinition)
                        break; // Should have reached the root namespace first but this helper is for ToString() - better to
                    // return partial information than crash.
                    namespaceHandle = namespaceDefinition.ParentScopeOrNamespace.ToNamespaceDefinitionHandle(reader);
                }
            }
            return ConvertBackTickNameToNameWithReducerInputFormat(s, genericParameterOffsets);
        }
Пример #42
0
 public object GetTypeFromDefinition(MetadataReader reader, TypeDefinitionHandle handle, byte rawTypeKind) => null;
Пример #43
0
 public void AddTypeLayout(
     TypeDefinitionHandle type,
     ushort packingSize,
     uint size)
 {
     _classLayoutTable.Add(new ClassLayoutRow
     {
         Parent = (uint)MetadataTokens.GetRowNumber(type),
         PackingSize = packingSize,
         ClassSize = size
     });
 }
Пример #44
0
        public void TestCustomAttributeDecoder()
        {
            using (FileStream stream = File.OpenRead(typeof(HasAttributes).GetTypeInfo().Assembly.Location))
                using (var peReader = new PEReader(stream))
                {
                    MetadataReader       reader        = peReader.GetMetadataReader();
                    var                  provider      = new CustomAttributeTypeProvider();
                    TypeDefinitionHandle typeDefHandle = TestMetadataResolver.FindTestType(reader, typeof(HasAttributes));


                    int i = 0;
                    foreach (CustomAttributeHandle attributeHandle in reader.GetCustomAttributes(typeDefHandle))
                    {
                        CustomAttribute attribute           = reader.GetCustomAttribute(attributeHandle);
                        CustomAttributeValue <string> value = attribute.DecodeValue(provider);

                        switch (i++)
                        {
                        case 0:
                            Assert.Empty(value.FixedArguments);
                            Assert.Empty(value.NamedArguments);
                            break;

                        case 1:
                            Assert.Equal(3, value.FixedArguments.Length);

                            Assert.Equal("string", value.FixedArguments[0].Type);
                            Assert.Equal("0", value.FixedArguments[0].Value);

                            Assert.Equal("int32", value.FixedArguments[1].Type);
                            Assert.Equal(1, value.FixedArguments[1].Value);

                            Assert.Equal("float64", value.FixedArguments[2].Type);
                            Assert.Equal(2.0, value.FixedArguments[2].Value);

                            Assert.Empty(value.NamedArguments);
                            break;

                        case 2:
                            Assert.Equal(3, value.NamedArguments.Length);

                            Assert.Equal(CustomAttributeNamedArgumentKind.Field, value.NamedArguments[0].Kind);
                            Assert.Equal("StringField", value.NamedArguments[0].Name);
                            Assert.Equal("string", value.NamedArguments[0].Type);
                            Assert.Equal("0", value.NamedArguments[0].Value);

                            Assert.Equal(CustomAttributeNamedArgumentKind.Field, value.NamedArguments[1].Kind);
                            Assert.Equal("Int32Field", value.NamedArguments[1].Name);
                            Assert.Equal("int32", value.NamedArguments[1].Type);
                            Assert.Equal(1, value.NamedArguments[1].Value);

                            Assert.Equal(CustomAttributeNamedArgumentKind.Property, value.NamedArguments[2].Kind);
                            Assert.Equal("SByteEnumArrayProperty", value.NamedArguments[2].Name);
                            Assert.Equal(typeof(SByteEnum).FullName + "[]", value.NamedArguments[2].Type);

                            var array = (ImmutableArray <CustomAttributeTypedArgument <string> >)(value.NamedArguments[2].Value);
                            Assert.Equal(1, array.Length);
                            Assert.Equal(typeof(SByteEnum).FullName, array[0].Type);
                            Assert.Equal((sbyte)SByteEnum.Value, array[0].Value);
                            break;

                        default:
                            // TODO: https://github.com/dotnet/runtime/issues/16552
                            // The other cases are missing corresponding assertions. This needs some refactoring to
                            // be data-driven. A better approach would probably be to generically compare reflection
                            // CustomAttributeData to S.R.M CustomAttributeValue for every test attribute applied.
                            break;
                        }
                    }
                }
        }
Пример #45
0
 public void AddNestedType(
     TypeDefinitionHandle type,
     TypeDefinitionHandle enclosingType)
 {
     _nestedClassTable.Add(new NestedClassRow
     {
         NestedClass = (uint)MetadataTokens.GetRowNumber(type),
         EnclosingClass = (uint)MetadataTokens.GetRowNumber(enclosingType)
     });
 }
 //
 // Q: Why is the type handle part of the unification key when it doesn't participate in the Equals/HashCode computations?
 // A: It's a passenger.
 //
 //    The typeHandle argument is "redundant" in that it can be computed from the rest of the key. However, we have callers (Type.GetTypeFromHandle()) that
 //    already have the typeHandle so to avoid an unnecessary round-trip computation, we require the caller to pass it in separately.
 //    We allow it to ride along in the key object because the ConcurrentUnifier classes we use don't support passing "extra" parameters to
 //    their Factory methods.
 //
 public UnificationKey(MetadataReader reader, TypeDefinitionHandle typeDefinitionHandle, RuntimeTypeHandle typeHandle)
 {
     Reader = reader;
     TypeDefinitionHandle = typeDefinitionHandle;
     TypeHandle           = typeHandle;
 }
Пример #47
0
 public void AddEventMap(TypeDefinitionHandle declaringType, EventDefinitionHandle eventList)
 {
     _eventMapTable.Add(new EventMapRow
     {
         Parent = (uint)MetadataTokens.GetRowNumber(declaringType),
         EventList = (uint)MetadataTokens.GetRowNumber(eventList)
     });
 }
Пример #48
0
        /// <summary>
        /// NestedClass Table Columns:
        ///     NestedClass (RID to TypeDef) nestee
        ///     EnclosingClass (RID to TypeDef)
        /// </summary>
        private void ValidateNestedClass(MetadataReader reader, TypeDefinitionHandle typeDef, bool isMod = false)
        {
            // var expNC = new uint[] { 4, 5, 6 };
            var expClasses = new int[][] { new int[] { 4, 5, 6 }, new int[] { 3, 3, 5 } };
            var modClasses = new int[][] { new int[] { 4, 5, 6, 7 }, new int[] { 2, 3, 3, 5 } };

            int rid = reader.NestedClassTable.FindEnclosingType(typeDef).RowId;
            int[][] classes = expClasses;

            if (isMod)
            {
                classes = modClasses;
            }

            Assert.Equal(rid, classes[1].Where((x, index) => classes[0][index] == typeDef.RowId).First());
        }
Пример #49
0
        internal uint CalculateTypeDefTreatmentAndRowId(TypeDefinitionHandle handle)
        {
            Debug.Assert(_metadataKind != MetadataKind.Ecma335);

            TypeDefTreatment treatment;

            TypeAttributes flags = TypeDefTable.GetFlags(handle);
            EntityHandle extends = TypeDefTable.GetExtends(handle);

            if ((flags & TypeAttributes.WindowsRuntime) != 0)
            {
                if (_metadataKind == MetadataKind.WindowsMetadata)
                {
                    treatment = GetWellKnownTypeDefinitionTreatment(handle);
                    if (treatment != TypeDefTreatment.None)
                    {
                        return TreatmentAndRowId((byte)treatment, handle.RowId);
                    }

                    // Is this an attribute?
                    if (extends.Kind == HandleKind.TypeReference && IsSystemAttribute((TypeReferenceHandle)extends))
                    {
                        treatment = TypeDefTreatment.NormalAttribute;
                    }
                    else
                    {
                        treatment = TypeDefTreatment.NormalNonAttribute;
                    }
                }
                else if (_metadataKind == MetadataKind.ManagedWindowsMetadata && NeedsWinRTPrefix(flags, extends))
                {
                    // WinMDExp emits two versions of RuntimeClasses and Enums:
                    //
                    //    public class Foo {}            // the WinRT reference class
                    //    internal class <CLR>Foo {}     // the implementation class that we want WinRT consumers to ignore
                    //
                    // The adapter's job is to undo WinMDExp's transformations. I.e. turn the above into:
                    //
                    //    internal class <WinRT>Foo {}   // the WinRT reference class that we want CLR consumers to ignore
                    //    public class Foo {}            // the implementation class
                    //
                    // We only add the <WinRT> prefix here since the WinRT view is the only view that is marked WindowsRuntime
                    // De-mangling the CLR name is done below.


                    // tomat: The CLR adapter implements a back-compat quirk: Enums exported with an older WinMDExp have only one version
                    // not marked with tdSpecialName. These enums should *not* be mangled and flipped to private.
                    // We don't implement this flag since the WinMDs producted by the older WinMDExp are not used in the wild.

                    treatment = TypeDefTreatment.PrefixWinRTName;
                }
                else
                {
                    treatment = TypeDefTreatment.None;
                }

                // Scan through Custom Attributes on type, looking for interesting bits. We only
                // need to do this for RuntimeClasses
                if ((treatment == TypeDefTreatment.PrefixWinRTName || treatment == TypeDefTreatment.NormalNonAttribute))
                {
                    if ((flags & TypeAttributes.Interface) == 0
                        && HasAttribute(handle, "Windows.UI.Xaml", "TreatAsAbstractComposableClassAttribute"))
                    {
                        treatment |= TypeDefTreatment.MarkAbstractFlag;
                    }
                }
            }
            else if (_metadataKind == MetadataKind.ManagedWindowsMetadata && IsClrImplementationType(handle))
            {
                // <CLR> implementation classes are not marked WindowsRuntime, but still need to be modified
                // by the adapter. 
                treatment = TypeDefTreatment.UnmangleWinRTName;
            }
            else
            {
                treatment = TypeDefTreatment.None;
            }

            return TreatmentAndRowId((byte)treatment, handle.RowId);
        }
Пример #50
0
 public TypeDefinition GetTypeDefinition(TypeDefinitionHandle handle)
 {
     // PERF: This code pattern is JIT friendly and results in very efficient code.
     return new TypeDefinition(this, GetTypeDefTreatmentAndRowId(handle));
 }
 public override int GetHashCode()
 {
     return(TypeDefinitionHandle.GetHashCode());
 }
Пример #52
0
 private MrType(TypeDefinitionHandle typeDefinitionHandle, MrAssembly assembly)
 {
     TypeDefinitionHandle = typeDefinitionHandle;
     Assembly             = assembly;
     TypeDefinition       = Assembly.Reader.GetTypeDefinition(typeDefinitionHandle);
 }
Пример #53
0
 internal abstract bool TryGetTypeHandle(Cci.ITypeDefinition def, out TypeDefinitionHandle handle);
Пример #54
0
 internal abstract bool TryGetTypeHandle(Cci.ITypeDefinition def, out TypeDefinitionHandle handle);
Пример #55
0
        internal void GetEventRange(TypeDefinitionHandle typeDef, out int firstEventRowId, out int lastEventRowId)
        {
            uint eventMapRowId = this.EventMapTable.FindEventMapRowIdFor(typeDef);
            if (eventMapRowId == 0)
            {
                firstEventRowId = 1;
                lastEventRowId = 0;
                return;
            }

            firstEventRowId = (int)this.EventMapTable.GetEventListStartFor(eventMapRowId);
            if (eventMapRowId == this.EventMapTable.NumberOfRows)
            {
                lastEventRowId = (int)(this.UseEventPtrTable ? this.EventPtrTable.NumberOfRows : this.EventTable.NumberOfRows);
            }
            else
            {
                lastEventRowId = (int)this.EventMapTable.GetEventListStartFor(eventMapRowId + 1) - 1;
            }
        }
Пример #56
0
        protected virtual bool IncludeTypeWhenDecompilingProject(Metadata.PEFile module, TypeDefinitionHandle type)
        {
            var metadata = module.Metadata;
            var typeDef  = metadata.GetTypeDefinition(type);

            if (metadata.GetString(typeDef.Name) == "<Module>" || CSharpDecompiler.MemberIsHidden(module, type, settings))
            {
                return(false);
            }
            if (metadata.GetString(typeDef.Namespace) == "XamlGeneratedNamespace" && metadata.GetString(typeDef.Name) == "GeneratedInternalTypeHelper")
            {
                return(false);
            }
            return(true);
        }
Пример #57
0
        /// <summary>
        /// Returns an array of types nested in the specified type.
        /// </summary>
        internal ImmutableArray<TypeDefinitionHandle> GetNestedTypes(TypeDefinitionHandle typeDef)
        {
            if (this.lazyNestedTypesMap == null)
            {
                InitializeNestedTypesMap();
            }

            ImmutableArray<TypeDefinitionHandle> nestedTypes;
            if (this.lazyNestedTypesMap.TryGetValue(typeDef, out nestedTypes))
            {
                return nestedTypes;
            }

            return ImmutableArray<TypeDefinitionHandle>.Empty;
        }
 public UnificationKey(MetadataReader reader, TypeDefinitionHandle typeDefinitionHandle, GenericParameterHandle genericParameterHandle)
 {
     _reader = reader;
     _typeDefinitionHandle   = typeDefinitionHandle;
     _genericParameterHandle = genericParameterHandle;
 }
Пример #59
0
        private uint GetTypeDefTreatmentAndRowId(TypeDefinitionHandle handle)
        {
            // PERF: This code pattern is JIT friendly and results in very efficient code.
            if (this.metadataKind == MetadataKind.Ecma335)
            {
                return handle.RowId;
            }

            return CalculateTypeDefTreatmentAndRowId(handle);
        }
Пример #60
0
        public static bool TryGetMethodMetadataFromStartAddress(IntPtr methodStartAddress, out MetadataReader reader, out TypeDefinitionHandle typeHandle, out MethodHandle methodHandle)
        {
            reader       = null;
            typeHandle   = default(TypeDefinitionHandle);
            methodHandle = default(MethodHandle);

            RuntimeTypeHandle declaringTypeHandle = default(RuntimeTypeHandle);

            if (!ExecutionEnvironment.TryGetMethodForOriginalLdFtnResult(methodStartAddress,
                                                                         ref declaringTypeHandle, out QMethodDefinition qMethodDefinition, out _))
            {
                return(false);
            }

            if (!qMethodDefinition.IsNativeFormatMetadataBased)
            {
                return(false);
            }

            if (RuntimeAugments.IsGenericType(declaringTypeHandle))
            {
                declaringTypeHandle = RuntimeAugments.GetGenericDefinition(declaringTypeHandle);
            }

            if (!ExecutionEnvironment.TryGetMetadataForNamedType(declaringTypeHandle, out QTypeDefinition qTypeDefinition))
            {
                return(false);
            }

            Debug.Assert(qTypeDefinition.IsNativeFormatMetadataBased);
            Debug.Assert(qTypeDefinition.NativeFormatReader == qMethodDefinition.NativeFormatReader);

            reader       = qTypeDefinition.NativeFormatReader;
            typeHandle   = qTypeDefinition.NativeFormatHandle;
            methodHandle = qMethodDefinition.NativeFormatHandle;

            return(true);
        }