Exemplo n.º 1
0
 public MethodSymbols(MetadataToken methodToken)
 {
     this.method_token = methodToken;
 }
Exemplo n.º 2
0
 internal object GetDefaultValue(MetadataToken token) {
     ElementType type;
     int constantRid = ConstantTable.GetConstantRowId(token);
     if (constantRid == 0) {
         return Missing.Value;
     }
     uint blob = ConstantTable.GetValue(constantRid, out type);
     return GetBlobValue(blob, type);
 }
Exemplo n.º 3
0
        [System.Security.SecuritySafeCritical]  // auto-generated
        public override FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
        {
            MetadataToken tk = new MetadataToken(metadataToken);

            if (!MetadataImport.IsValidToken(tk))
                throw new ArgumentOutOfRangeException(nameof(metadataToken),
                    Environment.GetResourceString("Argument_InvalidToken", tk, this));

            RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
            RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments);

            try 
            {
                IRuntimeFieldInfo fieldHandle = null;
            
                if (!tk.IsFieldDef)
                {
                    if (!tk.IsMemberRef)
                        throw new ArgumentException(Environment.GetResourceString("Argument_ResolveField", tk, this),
                            nameof(metadataToken));

                    unsafe 
                    {
                        ConstArray sig = MetadataImport.GetMemberRefProps(tk);
                        
                        if (*(MdSigCallingConvention*)sig.Signature.ToPointer() != MdSigCallingConvention.Field)
                            throw new ArgumentException(Environment.GetResourceString("Argument_ResolveField", tk, this),
                                nameof(metadataToken));                            
                    }

                    fieldHandle = ModuleHandle.ResolveFieldHandleInternal(GetNativeHandle(), tk, typeArgs, methodArgs);
                }

                fieldHandle = ModuleHandle.ResolveFieldHandleInternal(GetNativeHandle(), metadataToken, typeArgs, methodArgs);
                RuntimeType declaringType = RuntimeFieldHandle.GetApproxDeclaringType(fieldHandle.Value);
                
                if (declaringType.IsGenericType || declaringType.IsArray)
                {
                    int tkDeclaringType = ModuleHandle.GetMetadataImport(GetNativeHandle()).GetParentToken(metadataToken);
                    declaringType = (RuntimeType)ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments);
                }

                return System.RuntimeType.GetFieldInfo(declaringType, fieldHandle);
            }
            catch(MissingFieldException)
            {
                return ResolveLiteralField(tk, genericTypeArguments, genericMethodArguments);
            }
            catch (BadImageFormatException e) 
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_BadImageFormatExceptionResolve"), e);
            }           
        }
Exemplo n.º 4
0
        [System.Security.SecuritySafeCritical]  // auto-generated
        public override MemberInfo ResolveMember(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
        {
            MetadataToken tk = new MetadataToken(metadataToken);

            if (tk.IsProperty)
                throw new ArgumentException(Environment.GetResourceString("InvalidOperation_PropertyInfoNotAvailable"));

            if (tk.IsEvent)
                throw new ArgumentException(Environment.GetResourceString("InvalidOperation_EventInfoNotAvailable"));

            if (tk.IsMethodSpec || tk.IsMethodDef)
                return ResolveMethod(metadataToken, genericTypeArguments, genericMethodArguments);

            if (tk.IsFieldDef)
                return ResolveField(metadataToken, genericTypeArguments, genericMethodArguments);

            if (tk.IsTypeRef || tk.IsTypeDef || tk.IsTypeSpec)
                return ResolveType(metadataToken, genericTypeArguments, genericMethodArguments);

            if (tk.IsMemberRef)
            {
                if (!MetadataImport.IsValidToken(tk))
                    throw new ArgumentOutOfRangeException(nameof(metadataToken),
                        Environment.GetResourceString("Argument_InvalidToken", tk, this));

                ConstArray sig = MetadataImport.GetMemberRefProps(tk);

                unsafe 
                {
                    if (*(MdSigCallingConvention*)sig.Signature.ToPointer() == MdSigCallingConvention.Field)
                    {
                        return ResolveField(tk, genericTypeArguments, genericMethodArguments);
                    }
                    else
                    {
                        return ResolveMethod(tk, genericTypeArguments, genericMethodArguments);
                    }
                }                
            }

            throw new ArgumentException(Environment.GetResourceString("Argument_ResolveMember", tk, this),
                nameof(metadataToken));
        }
Exemplo n.º 5
0
        [System.Security.SecurityCritical]  // auto-generated
        private unsafe static bool FilterCustomAttributeRecord(
            CustomAttributeRecord caRecord,
            MetadataImport scope,
            ref Assembly lastAptcaOkAssembly, 
            RuntimeModule decoratedModule,
            MetadataToken decoratedToken,
            RuntimeType attributeFilterType,
            bool mustBeInheritable,
            object[] attributes,
            IList derivedAttributes,
            out RuntimeType attributeType,
            out IRuntimeMethodInfo ctor,
            out bool ctorHasParameters,
            out bool isVarArg)
        {
            ctor = null;
            attributeType = null;
            ctorHasParameters = false;
            isVarArg = false;
            
            IntPtr blobStart = caRecord.blob.Signature;
            IntPtr blobEnd = (IntPtr)((byte*)blobStart + caRecord.blob.Length);

#if FEATURE_LEGACYNETCF
            if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
                try
                {
                    // Resolve attribute type from ctor parent token found in decorated decoratedModule scope
                    attributeType = decoratedModule.ResolveType(scope.GetParentToken(caRecord.tkCtor), null, null) as RuntimeType;
                }
                catch(Exception)
                {
                    return false;
                }
            }
            else
#endif
            // Resolve attribute type from ctor parent token found in decorated decoratedModule scope
            attributeType = decoratedModule.ResolveType(scope.GetParentToken(caRecord.tkCtor), null, null) as RuntimeType;


            // Test attribute type against user provided attribute type filter
            if (!(attributeFilterType.IsAssignableFrom(attributeType)))
                return false;

            // Ensure if attribute type must be inheritable that it is inhertiable
            // Ensure that to consider a duplicate attribute type AllowMultiple is true
            if (!AttributeUsageCheck(attributeType, mustBeInheritable, attributes, derivedAttributes))
                return false;

            // Windows Runtime attributes aren't real types - they exist to be read as metadata only, and as such
            // should be filtered out of the GetCustomAttributes path.
            if ((attributeType.Attributes & TypeAttributes.WindowsRuntime) == TypeAttributes.WindowsRuntime)
            {
                return false;
            }

#if FEATURE_APTCA
            // APTCA checks
            RuntimeAssembly attributeAssembly = (RuntimeAssembly)attributeType.Assembly;
            RuntimeAssembly decoratedModuleAssembly = (RuntimeAssembly)decoratedModule.Assembly;

            if (attributeAssembly != lastAptcaOkAssembly && 
                !RuntimeAssembly.AptcaCheck(attributeAssembly, decoratedModuleAssembly))
                return false;

            // Cache last successful APTCA check (optimization)
            lastAptcaOkAssembly = decoratedModuleAssembly;
#endif // FEATURE_APTCA

            // Resolve the attribute ctor
            ConstArray ctorSig = scope.GetMethodSignature(caRecord.tkCtor);
            isVarArg = (ctorSig[0] & 0x05) != 0;
            ctorHasParameters = ctorSig[1] != 0;

            if (ctorHasParameters)
            {
                // Resolve method ctor token found in decorated decoratedModule scope
                ctor = ModuleHandle.ResolveMethodHandleInternal(decoratedModule.GetNativeHandle(), caRecord.tkCtor);
            }
            else
            {
                // Resolve method ctor token from decorated decoratedModule scope
                ctor = attributeType.GetTypeHandleInternal().GetDefaultConstructor();

                if (ctor == null && !attributeType.IsValueType)
                    throw new MissingMethodException(".ctor");
            }

            // Visibility checks
            MetadataToken tkParent = new MetadataToken();
                
            if (decoratedToken.IsParamDef)
            {
                tkParent = new MetadataToken(scope.GetParentToken(decoratedToken));
                tkParent = new MetadataToken(scope.GetParentToken(tkParent));
            }               
            else if (decoratedToken.IsMethodDef || decoratedToken.IsProperty || decoratedToken.IsEvent || decoratedToken.IsFieldDef) 
            {
                tkParent = new MetadataToken(scope.GetParentToken(decoratedToken));
            }
            else if (decoratedToken.IsTypeDef)
            {
                tkParent = decoratedToken;
            }
            else if (decoratedToken.IsGenericPar)
            {
                tkParent = new MetadataToken(scope.GetParentToken(decoratedToken));

                // decoratedToken is a generic parameter on a method. Get the declaring Type of the method.
                if (tkParent.IsMethodDef)
                    tkParent = new MetadataToken(scope.GetParentToken(tkParent));
            }
            else
            {
                // We need to relax this when we add support for other types of decorated tokens.
                Contract.Assert(decoratedToken.IsModule || decoratedToken.IsAssembly, 
                                "The decoratedToken must be either an assembly, a module, a type, or a member.");
            }

            // If the attribute is on a type, member, or parameter we check access against the (declaring) type,
            // otherwise we check access against the module.
            RuntimeTypeHandle parentTypeHandle = tkParent.IsTypeDef ?
                                                    decoratedModule.ModuleHandle.ResolveTypeHandle(tkParent) :
                                                    new RuntimeTypeHandle();

            return RuntimeMethodHandle.IsCAVisibleFromDecoratedType(attributeType.TypeHandle, ctor, parentTypeHandle, decoratedModule);
        }
Exemplo n.º 6
0
        [System.Security.SecuritySafeCritical]  // auto-generated
        public override MethodBase ResolveMethod(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
        {
            MetadataToken tk = new MetadataToken(metadataToken);

            if (!MetadataImport.IsValidToken(tk))
                throw new ArgumentOutOfRangeException(nameof(metadataToken),
                    Environment.GetResourceString("Argument_InvalidToken", tk, this));

            RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
            RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments);

            try 
            {
                if (!tk.IsMethodDef && !tk.IsMethodSpec)
                {
                    if (!tk.IsMemberRef)
                        throw new ArgumentException(Environment.GetResourceString("Argument_ResolveMethod", tk, this),
                            nameof(metadataToken));

                    unsafe
                    {
                        ConstArray sig = MetadataImport.GetMemberRefProps(tk);
                        
                        if (*(MdSigCallingConvention*)sig.Signature.ToPointer() == MdSigCallingConvention.Field)
                            throw new ArgumentException(Environment.GetResourceString("Argument_ResolveMethod", tk, this),
                                nameof(metadataToken));
                    }
                }

                IRuntimeMethodInfo methodHandle = ModuleHandle.ResolveMethodHandleInternal(GetNativeHandle(), tk, typeArgs, methodArgs);
                Type declaringType = RuntimeMethodHandle.GetDeclaringType(methodHandle);
    
                if (declaringType.IsGenericType || declaringType.IsArray)
                {
                    MetadataToken tkDeclaringType = new MetadataToken(MetadataImport.GetParentToken(tk));
                
                    if (tk.IsMethodSpec)
                        tkDeclaringType = new MetadataToken(MetadataImport.GetParentToken(tkDeclaringType));
                
                    declaringType = ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments);
                }

                return System.RuntimeType.GetMethodBase(declaringType as RuntimeType, methodHandle);    
            } 
            catch (BadImageFormatException e) 
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_BadImageFormatExceptionResolve"), e);
            }
        }
Exemplo n.º 7
0
        public override void GetTypeRefProps(
            TypeReferenceHandle typeRef,
            out string name,
            out string @namespace,
            out MetadataToken resolutionScope)
        {
            base.GetTypeRefProps(typeRef, out name, out @namespace, out resolutionScope);

// TODO (tomat): disable the warning temporarily until we move this code to the metadata reader
#pragma warning disable 618 // obsolete warning reported when RowIds are used
            uint assemblyRefOffset;
            string clrName, clrNamespace;
            if (WinRTProjectedTypes.ResolveWinRTTypeReference(name, @namespace, out clrName, out clrNamespace, out assemblyRefOffset))
            {
                name = clrName;
                @namespace = clrNamespace;
                uint assemblyRefRid = this.winMdStartIndex + assemblyRefOffset + 1;
                resolutionScope = AssemblyReferenceHandle.FromRowId(assemblyRefRid);
            }
            else if (GetTypeRefTreatment(typeRef) != TypeRefTreatment.None)
            {
                uint assemblyRefRid = this.winMdStartIndex + (uint)WinMdAssembliesOffsets.SystemRuntime + 1;
                resolutionScope = AssemblyReferenceHandle.FromRowId(assemblyRefRid);
            }
#pragma warning restore 618 // obsolete warning reported when RowIds are used
        }
Exemplo n.º 8
0
 public ConstArray GetMethodSignature(MetadataToken token)
 {
     if (token.IsMemberRef)
     {
         return this.GetMemberRefProps((int) token);
     }
     return this.GetSigOfMethodDef((int) token);
 }
Exemplo n.º 9
0
        private TypeDefTreatment GetTypeDefTreatment(
            TypeHandle typeDef,
            TypeAttributes flags,
            string name,
            string namespaceName,
            MetadataToken extends)
        {
            TypeDefTreatment treatment;

            // Does the type def have the WindowsRuntime bit set?
            if (flags.IsWindowsRuntime())
            {
                if (scenario == WinMDScenario.NormalWinMD)
                {
                    treatment = WinRTProjectedTypes.GetTypeDefinitionTreatment(name, namespaceName);
                    if (treatment != TypeDefTreatment.None)
                    {
                        return treatment;
                    }

                    // Is this an attribute?
                    if (extends.HandleType == HandleType.TypeReference && GetTypeRefTreatment((TypeReferenceHandle)extends) == TypeRefTreatment.SystemAttribute)
                    {
                        treatment = TypeDefTreatment.NormalAttribute;
                    }
                    else
                    {
                        treatment = TypeDefTreatment.NormalNonAttribute;
                    }
                }
                else if (scenario == WinMDScenario.WinMDExp && !flags.IsNested() && flags.IsPublic() && flags.IsSpecialName())
                {
                    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.IsInterface() && HasAttribute(typeDef, "Windows.UI.Xaml", "TreatAsAbstractComposableClassAttribute"))
                    {
                        treatment |= TypeDefTreatment.MarkAbstractFlag;
                    }
                }
            }
            else if (this.scenario == WinMDScenario.WinMDExp && IsClrImplementationType(name, flags))
            {
                treatment = TypeDefTreatment.UnmangleWinRTName;
            }
            else
            {
                treatment = TypeDefTreatment.None;
            }

            return treatment;
        }
Exemplo n.º 10
0
        // TODO (tomat): disable the warning temporarily until we move this code to the metadata reader
#pragma warning disable 618
        private bool HasAttribute(MetadataToken token, string namespaceName, string typeName)
        {
            foreach (var caHandle in peFileReader.GetCustomAttributes(token))
            {
                StringHandle namespaceHandle, nameHandle;
                if (peFileReader.GetCustomAttribute(caHandle).GetFullTypeName(out namespaceHandle, out nameHandle) &&
                    peFileReader.StringStream.CheckForText(namespaceHandle, namespaceName) &&
                    peFileReader.StringStream.CheckForText(nameHandle, typeName))
                {
                    return true;
                }
            }

            return false;
        }
Exemplo n.º 11
0
        private static RuntimeMethodInfo?AssignAssociates(
            int tkMethod,
            RuntimeType declaredType,
            RuntimeType reflectedType)
        {
            if (MetadataToken.IsNullToken(tkMethod))
            {
                return(null);
            }

            Debug.Assert(declaredType != null);
            Debug.Assert(reflectedType != null);

            bool isInherited = declaredType != reflectedType;

            IntPtr[]? genericArgumentHandles = null;
            int genericArgumentCount = 0;

            RuntimeType[] genericArguments = declaredType.GetTypeHandleInternal().GetInstantiationInternal();
            if (genericArguments != null)
            {
                genericArgumentCount   = genericArguments.Length;
                genericArgumentHandles = new IntPtr[genericArguments.Length];
                for (int i = 0; i < genericArguments.Length; i++)
                {
                    genericArgumentHandles[i] = genericArguments[i].GetTypeHandleInternal().Value;
                }
            }

            RuntimeMethodHandleInternal associateMethodHandle = ModuleHandle.ResolveMethodHandleInternal(RuntimeTypeHandle.GetModule(declaredType), tkMethod, genericArgumentHandles, genericArgumentCount, null, 0);

            Debug.Assert(!associateMethodHandle.IsNullHandle(), "Failed to resolve associateRecord methodDef token");

            if (isInherited)
            {
                MethodAttributes methAttr = RuntimeMethodHandle.GetAttributes(associateMethodHandle);

                // ECMA MethodSemantics: "All methods for a given Property or Event shall have the same accessibility
                // (ie the MemberAccessMask subfield of their Flags row) and cannot be CompilerControlled  [CLS]"
                // Consequently, a property may be composed of public and private methods. If the declared type !=
                // the reflected type, the private methods should not be exposed. Note that this implies that the
                // identity of a property includes it's reflected type.

                if ((methAttr & MethodAttributes.MemberAccessMask) == MethodAttributes.Private)
                {
                    return(null);
                }

                // Note this is the first time the property was encountered walking from the most derived class
                // towards the base class. It would seem to follow that any associated methods would not
                // be overriden -- but this is not necessarily true. A more derived class may have overriden a
                // virtual method associated with a property in a base class without associating the override with
                // the same or any property in the derived class.
                if ((methAttr & MethodAttributes.Virtual) != 0)
                {
                    bool declaringTypeIsClass =
                        (RuntimeTypeHandle.GetAttributes(declaredType) & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Class;

                    // It makes no sense to search for a virtual override of a method declared on an interface.
                    if (declaringTypeIsClass)
                    {
                        int slot = RuntimeMethodHandle.GetSlot(associateMethodHandle);

                        // Find the override visible from the reflected type
                        associateMethodHandle = RuntimeTypeHandle.GetMethodAt(reflectedType, slot);
                    }
                }
            }

            RuntimeMethodInfo?associateMethod =
                RuntimeType.GetMethodBase(reflectedType, associateMethodHandle) as RuntimeMethodInfo;

            // suppose a property was mapped to a method not in the derivation hierarchy of the reflectedTypeHandle
            return(associateMethod ?? reflectedType.Module.ResolveMethod(tkMethod, null, null) as RuntimeMethodInfo);
        }
Exemplo n.º 12
0
        public override FieldInfo?ResolveField(int metadataToken, Type[]?genericTypeArguments, Type[]?genericMethodArguments)
        {
            try
            {
                MetadataToken tk = new MetadataToken(metadataToken);

                if (!MetadataImport.IsValidToken(tk))
                {
                    throw new ArgumentOutOfRangeException(nameof(metadataToken),
                                                          SR.Format(SR.Argument_InvalidToken, tk, this));
                }

                RuntimeTypeHandle[]? typeArgs   = null;
                RuntimeTypeHandle[]? methodArgs = null;
                if (genericTypeArguments?.Length > 0)
                {
                    typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
                }
                if (genericMethodArguments?.Length > 0)
                {
                    methodArgs = ConvertToTypeHandleArray(genericMethodArguments);
                }

                ModuleHandle moduleHandle = new ModuleHandle(this);
                if (!tk.IsFieldDef)
                {
                    if (!tk.IsMemberRef)
                    {
                        throw new ArgumentException(SR.Format(SR.Argument_ResolveField, tk, this),
                                                    nameof(metadataToken));
                    }

                    unsafe
                    {
                        ConstArray sig = MetadataImport.GetMemberRefProps(tk);

                        if (*(MdSigCallingConvention *)sig.Signature != MdSigCallingConvention.Field)
                        {
                            throw new ArgumentException(SR.Format(SR.Argument_ResolveField, tk, this),
                                                        nameof(metadataToken));
                        }
                    }
                }

                IRuntimeFieldInfo fieldHandle = moduleHandle.ResolveFieldHandle(metadataToken, typeArgs, methodArgs).GetRuntimeFieldInfo();

                RuntimeType declaringType = RuntimeFieldHandle.GetApproxDeclaringType(fieldHandle.Value);

                if (declaringType.IsGenericType || declaringType.IsArray)
                {
                    int tkDeclaringType = ModuleHandle.GetMetadataImport(this).GetParentToken(metadataToken);
                    declaringType = (RuntimeType)ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments);
                }

                return(RuntimeType.GetFieldInfo(declaringType, fieldHandle));
            }
            catch (MissingFieldException)
            {
                return(ResolveLiteralField(metadataToken, genericTypeArguments, genericMethodArguments));
            }
            catch (BadImageFormatException e)
            {
                throw new ArgumentException(SR.Argument_BadImageFormatExceptionResolve, e);
            }
        }
Exemplo n.º 13
0
 private static partial void GetForwardedType(QCallAssembly assembly, MetadataToken mdtExternalType, ObjectHandleOnStack type);
Exemplo n.º 14
0
        public override MemberInfo?ResolveMember(
            int metadataToken,
            Type[]?genericTypeArguments,
            Type[]?genericMethodArguments
            )
        {
            MetadataToken tk = new MetadataToken(metadataToken);

            if (tk.IsProperty)
            {
                throw new ArgumentException(SR.InvalidOperation_PropertyInfoNotAvailable);
            }

            if (tk.IsEvent)
            {
                throw new ArgumentException(SR.InvalidOperation_EventInfoNotAvailable);
            }

            if (tk.IsMethodSpec || tk.IsMethodDef)
            {
                return(ResolveMethod(metadataToken, genericTypeArguments, genericMethodArguments));
            }

            if (tk.IsFieldDef)
            {
                return(ResolveField(metadataToken, genericTypeArguments, genericMethodArguments));
            }

            if (tk.IsTypeRef || tk.IsTypeDef || tk.IsTypeSpec)
            {
                return(ResolveType(metadataToken, genericTypeArguments, genericMethodArguments));
            }

            if (tk.IsMemberRef)
            {
                if (!MetadataImport.IsValidToken(tk))
                {
                    throw new ArgumentOutOfRangeException(
                              nameof(metadataToken),
                              SR.Format(SR.Argument_InvalidToken, tk, this)
                              );
                }

                ConstArray sig = MetadataImport.GetMemberRefProps(tk);
                unsafe
                {
                    if (*(MdSigCallingConvention *)sig.Signature == MdSigCallingConvention.Field)
                    {
                        return(ResolveField(tk, genericTypeArguments, genericMethodArguments));
                    }
                    else
                    {
                        return(ResolveMethod(tk, genericTypeArguments, genericMethodArguments));
                    }
                }
            }

            throw new ArgumentException(
                      SR.Format(SR.Argument_ResolveMember, tk, this),
                      nameof(metadataToken)
                      );
        }
Exemplo n.º 15
0
        public override void GetTypeDefProps(
            TypeHandle typeDef,
            out string name,
            out string namespaceName,
            out TypeAttributes flags,
            out MetadataToken extends)
        {
            base.GetTypeDefProps(typeDef,
                                 out name,
                                 out namespaceName,
                                 out flags,
                                 out extends);

            TypeDefTreatment treatment =
                GetTypeDefTreatment(typeDef, flags, name, namespaceName, extends);

            switch (treatment & TypeDefTreatment.TreatmentMask)
            {
                case TypeDefTreatment.None:
                    break;

                case TypeDefTreatment.NormalNonAttribute:
                    flags |= TypeAttributes.WindowsRuntime | TypeAttributes.Import;
                    break;

                case TypeDefTreatment.NormalAttribute:
                    flags |= TypeAttributes.WindowsRuntime | TypeAttributes.Sealed;
                    break;

                case TypeDefTreatment.UnmangleWinRTName:
                    name = name.Substring(clrPrefix.Length);
                    flags |= TypeAttributes.Public;
                    break;

                case TypeDefTreatment.PrefixWinRTName:
                    name = winRtPrefix + name;
                    flags &= TypeAttributes.Public;
                    flags |= TypeAttributes.Import;
                    break;

                case TypeDefTreatment.RedirectedToCLRType:
                    flags &= ~TypeAttributes.Public;
                    flags |= TypeAttributes.Import;
                    break;

                case TypeDefTreatment.RedirectedToCLRAttribute:
                    flags &= ~TypeAttributes.Public;
                    break;
            }

            if (treatment.HasFlag(TypeDefTreatment.MarkAbstractFlag))
            {
                flags |= TypeAttributes.Abstract;
            }

            if (treatment.HasFlag(TypeDefTreatment.MarkInternalFlag))
            {
                flags &= ~TypeAttributes.Public;
            }
        }
Exemplo n.º 16
0
        public FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
        {
            MetadataToken tk = new MetadataToken(metadataToken);

            if (!MetadataImport.IsValidToken(tk))
                throw new ArgumentOutOfRangeException("metadataToken",
                    String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_InvalidToken", tk, this)));

            RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
            RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments);

            try 
            {
                RuntimeFieldHandle fieldHandle = new RuntimeFieldHandle();
            
                if (!tk.IsFieldDef)
                {
                    if (!tk.IsMemberRef)
                        throw new ArgumentException("metadataToken",
                            String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_ResolveField"), tk, this));

                    unsafe 
                    {
                        ConstArray sig = MetadataImport.GetMemberRefProps(tk);
                        
                        if (*(CorCallingConvention*)sig.Signature.ToPointer() != CorCallingConvention.Field)
                            throw new ArgumentException("metadataToken",
                                String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_ResolveField"), tk, this));                            
                    }

                    fieldHandle = GetModuleHandle().ResolveFieldHandle(tk, typeArgs, methodArgs);
                }

                fieldHandle = GetModuleHandle().ResolveFieldHandle(metadataToken, typeArgs, methodArgs);
                Type declaringType = fieldHandle.GetApproxDeclaringType().GetRuntimeType();
                
                if (declaringType.IsGenericType || declaringType.IsArray)
                {
                    int tkDeclaringType = GetModuleHandle().GetMetadataImport().GetParentToken(metadataToken);
                    declaringType = ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments);
                }

                return System.RuntimeType.GetFieldInfo(declaringType.GetTypeHandleInternal(), fieldHandle);
            }
            catch(MissingFieldException)
            {
                return ResolveLiteralField(tk, genericTypeArguments, genericMethodArguments);
            }
            catch (BadImageFormatException e) 
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_BadImageFormatExceptionResolve"), e);
            }           
        }
Exemplo n.º 17
0
 public bool IsValidToken(MetadataToken token)
 {
     return m_import.IsValidToken(token);
 }
Exemplo n.º 18
0
 [System.Security.SecurityCritical]  // auto-generated
 public ConstArray GetMethodSignature(MetadataToken token)
 {
     if (token.IsMemberRef)
         return GetMemberRefProps(token);
         
     return GetSigOfMethodDef(token);
 }
Exemplo n.º 19
0
 internal int GetFieldMarshalRowId(MetadataToken token)
 {
     int foundRowNumber = Table.BinarySearchReference(
         NumberOfRows,
         RowSize,
         ParentOffset,
         HasFieldMarshalTag.ConvertToTag(token),
         IsHasFieldMarshalRefSizeSmall
     );
     return foundRowNumber + 1;
 }
Exemplo n.º 20
0
        [System.Security.SecuritySafeCritical]  // auto-generated
        public override byte[] ResolveSignature(int metadataToken)
        {
            MetadataToken tk = new MetadataToken(metadataToken);

            if (!MetadataImport.IsValidToken(tk))
                throw new ArgumentOutOfRangeException(nameof(metadataToken),
                    Environment.GetResourceString("Argument_InvalidToken", tk, this));

            if (!tk.IsMemberRef && !tk.IsMethodDef && !tk.IsTypeSpec && !tk.IsSignature && !tk.IsFieldDef)
                throw new ArgumentException(Environment.GetResourceString("Argument_InvalidToken", tk, this),
                                            nameof(metadataToken));

            ConstArray signature;
            if (tk.IsMemberRef)
                signature = MetadataImport.GetMemberRefProps(metadataToken);
            else
                signature = MetadataImport.GetSignatureFromToken(metadataToken);

            byte[] sig = new byte[signature.Length];

            for (int i = 0; i < signature.Length; i++)
                sig[i] = signature[i];

            return sig;
        }
Exemplo n.º 21
0
 internal int GetConstantRowId(MetadataToken parentToken)
 {
     int foundRowNumber = Table.BinarySearchReference(
         NumberOfRows,
         RowSize,
         ParentOffset,
         HasConstantTag.ConvertToTag(parentToken),
         IsHasConstantRefSizeSmall
     );
     return foundRowNumber + 1;
 }
Exemplo n.º 22
0
        [System.Security.SecurityCritical]  // auto-generated
        private FieldInfo ResolveLiteralField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
        {
            MetadataToken tk = new MetadataToken(metadataToken);

            if (!MetadataImport.IsValidToken(tk) || !tk.IsFieldDef)
                throw new ArgumentOutOfRangeException(nameof(metadataToken),
                    String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_InvalidToken", tk, this)));

            int tkDeclaringType;
            string fieldName;

            fieldName = MetadataImport.GetName(tk).ToString();
            tkDeclaringType = MetadataImport.GetParentToken(tk);

            Type declaringType = ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments);

            declaringType.GetFields();

            try
            {
                return declaringType.GetField(fieldName, 
                    BindingFlags.Static | BindingFlags.Instance | 
                    BindingFlags.Public | BindingFlags.NonPublic | 
                    BindingFlags.DeclaredOnly);
            }
            catch
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_ResolveField", tk, this), nameof(metadataToken));
            }
        }
Exemplo n.º 23
0
 internal int FindCustomAttributesForToken(MetadataToken token, out int customAttributeCount)
 {
     return BinarySearchTag(HasCustomAttributeTag.ConvertToTag(token), out customAttributeCount);
 }
Exemplo n.º 24
0
        [System.Security.SecuritySafeCritical]  // auto-generated
        public override Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
        {
            MetadataToken tk = new MetadataToken(metadataToken);

            if (tk.IsGlobalTypeDefToken)
                throw new ArgumentException(Environment.GetResourceString("Argument_ResolveModuleType", tk), nameof(metadataToken));
            
            if (!MetadataImport.IsValidToken(tk))
                throw new ArgumentOutOfRangeException(nameof(metadataToken),
                    Environment.GetResourceString("Argument_InvalidToken", tk, this));

            if (!tk.IsTypeDef && !tk.IsTypeSpec && !tk.IsTypeRef)
                throw new ArgumentException(Environment.GetResourceString("Argument_ResolveType", tk, this), nameof(metadataToken));

            RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
            RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments);

            try 
            {
                Type t = GetModuleHandle().ResolveTypeHandle(metadataToken, typeArgs, methodArgs).GetRuntimeType();
                    
                if (t == null)
                    throw new ArgumentException(Environment.GetResourceString("Argument_ResolveType", tk, this), nameof(metadataToken));

                return t;
            } 
            catch (BadImageFormatException e) 
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_BadImageFormatExceptionResolve"), e);
            }
        }
Exemplo n.º 25
0
 internal int FindSecurityAttributesForToken(MetadataToken token, out int securityAttributeCount)
 {
     uint searchCodedTag = HasDeclSecurityTag.ConvertToTag(token);
     return BinarySearchTag(searchCodedTag, out securityAttributeCount);
 }
Exemplo n.º 26
0
        [System.Security.SecuritySafeCritical]  // auto-generated
        public override string ResolveString(int metadataToken)
        {
            MetadataToken tk = new MetadataToken(metadataToken);
            if (!tk.IsString)
                throw new ArgumentException(
                    String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_ResolveString"), metadataToken, ToString()));

            if (!MetadataImport.IsValidToken(tk))
                throw new ArgumentOutOfRangeException(nameof(metadataToken),
                    String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_InvalidToken", tk, this)));

            string str = MetadataImport.GetUserString(metadataToken);
            
            if (str == null)                
                throw new ArgumentException(
                    String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_ResolveString"), metadataToken, ToString()));

            return str;
        }
        internal unsafe static bool FilterCustomAttributeRecord(
            CustomAttributeRecord caRecord, MetadataImport scope, ref Assembly lastAptcaOkAssembly, 
            Module decoratedModule, MetadataToken decoratedToken, RuntimeType attributeFilterType, bool mustBeInheritable,
            object[] attributes, IList derivedAttributes,
            out RuntimeType attributeType, out RuntimeMethodHandle ctor, out bool ctorHasParameters, out bool isVarArg)
        {
            ctor = new RuntimeMethodHandle();
            attributeType = null;
            ctorHasParameters = false;
            isVarArg = false;
            
            IntPtr blobStart = caRecord.blob.Signature;
            IntPtr blobEnd = (IntPtr)((byte*)blobStart + caRecord.blob.Length);

            // Resolve attribute type from ctor parent token found in decorated decoratedModule scope
            attributeType = decoratedModule.ResolveType(scope.GetParentToken(caRecord.tkCtor), null, null) as RuntimeType;

            // Test attribute type against user provided attribute type filter
            if (!(attributeFilterType.IsAssignableFrom(attributeType)))
                return false;

            if (!AttributeUsageCheck(attributeType, mustBeInheritable, attributes, derivedAttributes))
                return false;

            // APTCA checks
            if (attributeType.Assembly != lastAptcaOkAssembly && 
                !attributeType.Assembly.AptcaCheck(decoratedModule.Assembly))
                return false;

            // Cache last successful APTCA check (optimization)
            lastAptcaOkAssembly = decoratedModule.Assembly;

            // Resolve the attribute ctor
            ConstArray ctorSig = scope.GetMethodSignature(caRecord.tkCtor);
            isVarArg = (ctorSig[0] & 0x05) != 0;
            ctorHasParameters = ctorSig[1] != 0;

            if (ctorHasParameters)
            {
                // Resolve method ctor token found in decorated decoratedModule scope
                ctor = decoratedModule.ModuleHandle.ResolveMethodHandle(caRecord.tkCtor);
            }
            else
            {
                // Resolve method ctor token from decorated decoratedModule scope
                ctor = attributeType.GetTypeHandleInternal().GetDefaultConstructor();

                if (ctor.IsNullHandle() && !attributeType.IsValueType)
                    throw new MissingMethodException(".ctor");
            }

            // Visibility checks
            if (ctor.IsNullHandle())
            {
                if (!attributeType.IsVisible && !attributeType.TypeHandle.IsVisibleFromModule(decoratedModule.ModuleHandle))
                    return false;            
                
                return true;
            }
            
            if (ctor.IsVisibleFromModule(decoratedModule))
                return true;
            
            MetadataToken tkParent = new MetadataToken();
                
            if (decoratedToken.IsParamDef)
            {
                tkParent = new MetadataToken(scope.GetParentToken(decoratedToken));
                tkParent = new MetadataToken(scope.GetParentToken(tkParent));
            }               
            else if (decoratedToken.IsMethodDef || decoratedToken.IsProperty || decoratedToken.IsEvent || decoratedToken.IsFieldDef) 
            {
                tkParent = new MetadataToken(scope.GetParentToken(decoratedToken));
            }
            else if (decoratedToken.IsTypeDef)
            {
                tkParent = decoratedToken;
            }
            
            if (tkParent.IsTypeDef)
                return ctor.IsVisibleFromType(decoratedModule.ModuleHandle.ResolveTypeHandle(tkParent));
            
            return false;
        }
Exemplo n.º 28
0
 internal bool IsValidToken(MetadataToken token) {
     int tableIndex = (int)token.RecordType;
     if (tableIndex < _tableRowCounts.Length) {
         return token.Rid <= _tableRowCounts[tableIndex];
     }
     switch (tableIndex) {
         case (int)MetadataTokenType.String >> 24: return token.Rid < _stringStream.Length;
         case (int)MetadataTokenType.Name >> 24: return _userStringStream != null && token.Rid < _userStringStream.Length;
     }
     return false;
 }
Exemplo n.º 29
0
 internal static unsafe bool FilterCustomAttributeRecord(CustomAttributeRecord caRecord, MetadataImport scope, ref Assembly lastAptcaOkAssembly, Module decoratedModule, MetadataToken decoratedToken, RuntimeType attributeFilterType, bool mustBeInheritable, object[] attributes, IList derivedAttributes, out RuntimeType attributeType, out RuntimeMethodHandle ctor, out bool ctorHasParameters, out bool isVarArg)
 {
     ctor = new RuntimeMethodHandle();
     attributeType = null;
     ctorHasParameters = false;
     isVarArg = false;
     IntPtr ptr1 = (IntPtr) (((void*) caRecord.blob.Signature) + caRecord.blob.Length);
     attributeType = decoratedModule.ResolveType(scope.GetParentToken((int) caRecord.tkCtor), null, null) as RuntimeType;
     if (!attributeFilterType.IsAssignableFrom(attributeType))
     {
         return false;
     }
     if (!AttributeUsageCheck(attributeType, mustBeInheritable, attributes, derivedAttributes))
     {
         return false;
     }
     if ((attributeType.Assembly != lastAptcaOkAssembly) && !attributeType.Assembly.AptcaCheck(decoratedModule.Assembly))
     {
         return false;
     }
     lastAptcaOkAssembly = decoratedModule.Assembly;
     ConstArray methodSignature = scope.GetMethodSignature(caRecord.tkCtor);
     isVarArg = (methodSignature[0] & 5) != 0;
     ctorHasParameters = methodSignature[1] != 0;
     if (ctorHasParameters)
     {
         ctor = decoratedModule.ModuleHandle.ResolveMethodHandle((int) caRecord.tkCtor);
     }
     else
     {
         ctor = attributeType.GetTypeHandleInternal().GetDefaultConstructor();
         if (ctor.IsNullHandle() && !attributeType.IsValueType)
         {
             throw new MissingMethodException(".ctor");
         }
     }
     if (ctor.IsNullHandle())
     {
         if (!attributeType.IsVisible && !attributeType.TypeHandle.IsVisibleFromModule(decoratedModule.ModuleHandle))
         {
             return false;
         }
         return true;
     }
     if (ctor.IsVisibleFromModule(decoratedModule))
     {
         return true;
     }
     MetadataToken token = new MetadataToken();
     if (decoratedToken.IsParamDef)
     {
         token = new MetadataToken(scope.GetParentToken((int) decoratedToken));
         token = new MetadataToken(scope.GetParentToken((int) token));
     }
     else if ((decoratedToken.IsMethodDef || decoratedToken.IsProperty) || (decoratedToken.IsEvent || decoratedToken.IsFieldDef))
     {
         token = new MetadataToken(scope.GetParentToken((int) decoratedToken));
     }
     else if (decoratedToken.IsTypeDef)
     {
         token = decoratedToken;
     }
     return (token.IsTypeDef && ctor.IsVisibleFromType(decoratedModule.ModuleHandle.ResolveTypeHandle((int) token)));
 }
Exemplo n.º 30
0
        internal EnumerationIndirection GetEnumeratorRange(MetadataTokenType type, MetadataToken parent, out int startRid, out int count) {
            Debug.Assert(IsValidToken(parent));

            switch (type) {
                case MetadataTokenType.MethodDef:
                    if (parent.IsNull) {
                        count = MethodTable.NumberOfRows;
                        startRid = 1;
                    } else {
                        Debug.Assert(parent.IsTypeDef);
                        startRid = GetMethodRange(parent.Rid, out count);
                    }
                    return UseParamPtrTable ? EnumerationIndirection.Method : EnumerationIndirection.None;

                case MetadataTokenType.Property:
                    if (parent.IsNull) {
                        count = PropertyTable.NumberOfRows;
                        startRid = 1;
                    } else {
                        Debug.Assert(parent.IsTypeDef);
                        startRid = GetPropertyRange(parent.Rid, out count);
                    }
                    return UsePropertyPtrTable ? EnumerationIndirection.Property : EnumerationIndirection.None;

                case MetadataTokenType.Event:
                    if (parent.IsNull) {
                        count = EventTable.NumberOfRows;
                        startRid = 1;
                    } else {
                        Debug.Assert(parent.IsTypeDef);
                        startRid = GetEventRange(parent.Rid, out count);
                    }
                    return UseEventPtrTable ? EnumerationIndirection.Event : EnumerationIndirection.None;

                case MetadataTokenType.FieldDef:
                    if (parent.IsNull) {
                        count = FieldTable.NumberOfRows;
                        startRid = 1;
                    } else {
                        Debug.Assert(parent.IsTypeDef);
                        startRid = GetFieldRange(parent.Rid, out count);
                    }
                    return UseFieldPtrTable ? EnumerationIndirection.Field : EnumerationIndirection.None;

                case MetadataTokenType.ParamDef:
                    if (parent.IsNull) {
                        count = ParamTable.NumberOfRows;
                        startRid = 1;
                    } else {
                        Debug.Assert(parent.IsMethodDef);
                        startRid = GetParamRange(parent.Rid, out count);
                    }
                    return UseParamPtrTable ? EnumerationIndirection.Param : EnumerationIndirection.None;

                case MetadataTokenType.CustomAttribute:
                    if (parent.IsNull) {
                        count = CustomAttributeTable.NumberOfRows;
                        startRid = 1;
                    } else {
                        startRid = CustomAttributeTable.FindCustomAttributesForToken(parent, out count);
                    }
                    return EnumerationIndirection.None;

                case MetadataTokenType.InterfaceImpl:
                    if (parent.IsNull) {
                        count = InterfaceImplTable.NumberOfRows;
                        startRid = 1;
                    } else {
                        Debug.Assert(parent.IsTypeDef);
                        startRid = InterfaceImplTable.FindInterfaceImplForType(parent.Rid, out count);
                    }
                    return EnumerationIndirection.None;

                case MetadataTokenType.GenericPar:
                    if (parent.IsNull) {
                        count = GenericParamTable.NumberOfRows;
                        startRid = 1;
                    } else if (parent.IsTypeDef) {
                        startRid = GenericParamTable.FindGenericParametersForType(parent.Rid, out count);
                    } else {
                        Debug.Assert(parent.IsMethodDef);
                        startRid = GenericParamTable.FindGenericParametersForMethod(parent.Rid, out count);
                    }
                    return EnumerationIndirection.None;

                case MetadataTokenType.GenericParamConstraint:
                    if (parent.IsNull) {
                        count = GenericParamConstraintTable.NumberOfRows;
                        startRid = 1;
                    } else {
                        Debug.Assert(parent.IsGenericParam);
                        startRid = GenericParamConstraintTable.FindConstraintForGenericParam(parent.Rid, out count);
                    }
                    return EnumerationIndirection.None;

                case MetadataTokenType.AssemblyRef:
                case MetadataTokenType.ModuleRef:
                case MetadataTokenType.File:
                case MetadataTokenType.TypeDef:
                case MetadataTokenType.TypeSpec:
                case MetadataTokenType.TypeRef:
                case MetadataTokenType.NestedClass:
                case MetadataTokenType.ExportedType:
                case MetadataTokenType.MethodSpec:
                case MetadataTokenType.MemberRef:
                case MetadataTokenType.Signature:
                case MetadataTokenType.ManifestResource:
                    Debug.Assert(parent.IsNull);
                    count = _tableRowCounts[(int)type >> 24];
                    startRid = 1;
                    return EnumerationIndirection.None;

                default:
                    Debug.Assert(false);
                    throw new InvalidOperationException();
            }
        }
Exemplo n.º 31
0
        public override MethodBase?ResolveMethod(
            int metadataToken,
            Type[]?genericTypeArguments,
            Type[]?genericMethodArguments
            )
        {
            try
            {
                MetadataToken tk = new MetadataToken(metadataToken);
                if (!tk.IsMethodDef && !tk.IsMethodSpec)
                {
                    if (!tk.IsMemberRef)
                    {
                        throw new ArgumentException(
                                  SR.Format(SR.Argument_ResolveMethod, tk, this),
                                  nameof(metadataToken)
                                  );
                    }
                    unsafe
                    {
                        ConstArray sig = MetadataImport.GetMemberRefProps(tk);

                        if (*(MdSigCallingConvention *)sig.Signature == MdSigCallingConvention.Field)
                        {
                            throw new ArgumentException(
                                      SR.Format(SR.Argument_ResolveMethod, tk, this),
                                      nameof(metadataToken)
                                      );
                        }
                    }
                }

                RuntimeTypeHandle[]? typeArgs   = null;
                RuntimeTypeHandle[]? methodArgs = null;
                if (genericTypeArguments?.Length > 0)
                {
                    typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
                }
                if (genericMethodArguments?.Length > 0)
                {
                    methodArgs = ConvertToTypeHandleArray(genericMethodArguments);
                }

                ModuleHandle       moduleHandle = new ModuleHandle(this);
                IRuntimeMethodInfo methodHandle = moduleHandle
                                                  .ResolveMethodHandle(tk, typeArgs, methodArgs)
                                                  .GetMethodInfo();

                Type declaringType = RuntimeMethodHandle.GetDeclaringType(methodHandle);

                if (declaringType.IsGenericType || declaringType.IsArray)
                {
                    MetadataToken tkDeclaringType = new MetadataToken(
                        MetadataImport.GetParentToken(tk)
                        );

                    if (tk.IsMethodSpec)
                    {
                        tkDeclaringType = new MetadataToken(
                            MetadataImport.GetParentToken(tkDeclaringType)
                            );
                    }

                    declaringType = ResolveType(
                        tkDeclaringType,
                        genericTypeArguments,
                        genericMethodArguments
                        );
                }

                return(RuntimeType.GetMethodBase(declaringType as RuntimeType, methodHandle));
            }
            catch (BadImageFormatException e)
            {
                throw new ArgumentException(SR.Argument_BadImageFormatExceptionResolve, e);
            }
        }