private Mapping <ConstantHandle> MapConstantImpl(ConstantHandle handle)
        {
            Constant         constant = _sourceMetadata.GetConstant(handle);
            Mapping <Handle> parent   = MapHandle(constant.Parent);

            if (parent.Target.IsNil)
            {
                return(new Mapping <ConstantHandle>());
            }

            ConstantHandle targetHandle;

            switch (parent.Target.Kind)
            {
            case HandleKind.Parameter:
                Parameter targetParameter = _targetMetadata.GetParameter((ParameterHandle)parent.Target);
                targetHandle = targetParameter.GetDefaultValue();
                break;

            case HandleKind.FieldDefinition:
                FieldDefinition targetFieldDefinition = _targetMetadata.GetFieldDefinition((FieldDefinitionHandle)parent.Target);
                targetHandle = targetFieldDefinition.GetDefaultValue();
                break;

            case HandleKind.PropertyDefinition:
                PropertyDefinition targetPropertyDefinition = _targetMetadata.GetPropertyDefinition((PropertyDefinitionHandle)parent.Target);
                targetHandle = targetPropertyDefinition.GetDefaultValue();
                break;

            default:
                throw new InvalidOperationException();
            }

            if (targetHandle.IsNil)
            {
                return(new Mapping <ConstantHandle>());
            }

            Constant targetConstant = _targetMetadata.GetConstant(targetHandle);

            if (constant.TypeCode != targetConstant.TypeCode)
            {
                var candidateTargets = ImmutableArray.Create(targetHandle);
                var candidateReasons = ImmutableArray.Create("Mapped constant has a different type.");
                return(new Mapping <ConstantHandle>(candidateTargets, candidateReasons));
            }

            ImmutableArray <byte> sourceContent = _sourceMetadata.GetBlobContent(constant.Value);
            ImmutableArray <byte> targetContent = _targetMetadata.GetBlobContent(targetConstant.Value);

            if (!sourceContent.SequenceEqual(targetContent))
            {
                var candidateTargets = ImmutableArray.Create(targetHandle);
                var candidateReasons = ImmutableArray.Create("Mapped constant has a different value.");
                return(new Mapping <ConstantHandle>(candidateTargets, candidateReasons));
            }

            return(new Mapping <ConstantHandle>(targetHandle));
        }
Example #2
0
        private MetadataFieldInfo ResolveFieldImpl(
            int metadataToken,
            Type[] genericTypeArguments,
            Type[] genericMethodArguments,
            bool shouldThrow = true)
        {
            var entity = MetadataTokens.EntityHandle(metadataToken);

            if (entity.IsNil || entity.Kind != HandleKind.FieldDefinition)
            {
                if (!shouldThrow)
                {
                    return(null);
                }

                throw NewTokenOutOfRangeException(metadataToken, nameof(metadataToken));
            }

            var field = _metadata.GetFieldDefinition((FieldDefinitionHandle)entity);
            var type  = ResolveTypeImpl(
                MetadataTokens.GetToken(_metadata, field.GetDeclaringType()),
                genericTypeArguments,
                genericMethodArguments);

            return(type.GetMetadataField(MetadataTokens.GetToken(_metadata, entity)));
        }
Example #3
0
        public static TypeDefinitionHandle GetDeclaringType(this EntityHandle entity, MetadataReader metadata)
        {
            switch (entity.Kind)
            {
            case HandleKind.TypeDefinition:
                var td = metadata.GetTypeDefinition((TypeDefinitionHandle)entity);
                return(td.GetDeclaringType());

            case HandleKind.FieldDefinition:
                var fd = metadata.GetFieldDefinition((FieldDefinitionHandle)entity);
                return(fd.GetDeclaringType());

            case HandleKind.MethodDefinition:
                var md = metadata.GetMethodDefinition((MethodDefinitionHandle)entity);
                return(md.GetDeclaringType());

            case HandleKind.EventDefinition:
                var ed = metadata.GetEventDefinition((EventDefinitionHandle)entity);
                return(metadata.GetMethodDefinition(ed.GetAccessors().GetAny()).GetDeclaringType());

            case HandleKind.PropertyDefinition:
                var pd = metadata.GetPropertyDefinition((PropertyDefinitionHandle)entity);
                return(metadata.GetMethodDefinition(pd.GetAccessors().GetAny()).GetDeclaringType());

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
        void ParseEnum(TypeDefinition enumTypeDef)
        {
            // TODO: verify that int32 is the enums storage type for constant read below

            InspectorEnum ienum = new InspectorEnum();

            ienum.Name = metaReader.GetString(enumTypeDef.Name);

            InspectorEnums [ienum.Name] = ienum;

            var fields = enumTypeDef.GetFields();

            foreach (var fieldHandle in fields)
            {
                var inspectorField = new InspectorField();

                var fieldDef = metaReader.GetFieldDefinition(fieldHandle);

                if ((fieldDef.Attributes & FieldAttributes.HasDefault) != 0)
                {
                    var constantHandle = fieldDef.GetDefaultValue();
                    var constant       = metaReader.GetConstant(constantHandle);

                    BlobReader constantReader = metaReader.GetBlobReader(constant.Value);

                    ienum.Values [metaReader.GetString(fieldDef.Name)] = constantReader.ReadInt32();
                }
            }

            return;
        }
Example #5
0
        private static void ProcessFieldDef(FieldDefinitionHandle fieldDefHandle, MetadataReader dllReader, MetadataReader pdbReader, HashSet <DocumentHandle> docList)
        {
            var fieldDef      = dllReader.GetFieldDefinition(fieldDefHandle);
            var typeDefHandle = fieldDef.GetDeclaringType();

            ProcessTypeDef(typeDefHandle, dllReader, pdbReader, docList);
        }
Example #6
0
        public static bool IsEnum(this TypeDefinition typeDefinition, MetadataReader reader,
                                  out PrimitiveTypeCode underlyingType)
        {
            underlyingType = 0;
            EntityHandle baseType = typeDefinition.GetBaseTypeOrNil();

            if (baseType.IsNil)
            {
                return(false);
            }
            if (!baseType.IsKnownType(reader, KnownTypeCode.Enum))
            {
                return(false);
            }
            foreach (var handle in typeDefinition.GetFields())
            {
                var field = reader.GetFieldDefinition(handle);
                if ((field.Attributes & FieldAttributes.Static) != 0)
                {
                    continue;
                }
                var blob = reader.GetBlobReader(field.Signature);
                if (blob.ReadSignatureHeader().Kind != SignatureKind.Field)
                {
                    return(false);
                }
                underlyingType = (PrimitiveTypeCode)blob.ReadByte();
                return(true);
            }
            return(false);
        }
Example #7
0
        public TypeHandle LoadType(MetadataReader reader, TypeDefinition type)
        {
            string namespaceName = reader.GetString(type.Namespace);
            string typeName      = reader.GetString(type.Name);

            int size = 0;

            Dictionary <string, int> offsets = new();

            foreach (FieldDefinitionHandle fieldHandle in type.GetFields())
            {
                FieldDefinition field = reader.GetFieldDefinition(fieldHandle);

                TypeHandle fieldType = field.DecodeSignature(this, null !);

                offsets[reader.GetString(field.Name)] = size;

                size += fieldType.Size;
            }

            return(this.types.GetOrAdd($"{namespaceName}.{typeName}", new TypeHandle(this)
            {
                Size = size,

                Offsets = offsets,
            }));
        }
        protected sealed override KeyValuePair <String, ulong>[] ReadNamesAndValues()
        {
            LowLevelList <KeyValuePair <String, ulong> > namesAndUnboxedValues = new LowLevelList <KeyValuePair <String, ulong> >();
            MetadataReader reader = _reader;

            foreach (FieldDefinitionHandle fieldHandle in _typeDefinition.GetFields())
            {
                FieldDefinition field = reader.GetFieldDefinition(fieldHandle);
                if (0 != (field.Attributes & FieldAttributes.Static))
                {
                    String name = reader.GetString(field.Name);

                    if ((field.Attributes & FieldAttributes.HasDefault) != FieldAttributes.HasDefault)
                    {
                        throw new BadImageFormatException();
                    }

                    ConstantHandle valueHandle = field.GetDefaultValue();

                    ulong ulValue = ReadUnboxedEnumValue(reader, valueHandle);
                    namesAndUnboxedValues.Add(new KeyValuePair <String, ulong>(name, ulValue));
                }
            }

            return(namesAndUnboxedValues.ToArray());
        }
Example #9
0
        /// <summary>
        /// This should produce a string representation of the entity for search to match search strings against.
        /// </summary>
        public virtual string GetEntityName(PEFile module, EntityHandle handle, bool fullName)
        {
            MetadataReader metadata = module.Metadata;

            switch (handle.Kind)
            {
            case HandleKind.TypeDefinition:
                if (fullName)
                {
                    return(((TypeDefinitionHandle)handle).GetFullTypeName(metadata).ToILNameString());
                }
                var td = metadata.GetTypeDefinition((TypeDefinitionHandle)handle);
                return(metadata.GetString(td.Name));

            case HandleKind.FieldDefinition:
                var fd            = metadata.GetFieldDefinition((FieldDefinitionHandle)handle);
                var declaringType = fd.GetDeclaringType();
                if (fullName)
                {
                    return(fd.GetDeclaringType().GetFullTypeName(metadata).ToILNameString() + "." + metadata.GetString(fd.Name));
                }
                return(metadata.GetString(fd.Name));

            case HandleKind.MethodDefinition:
                var md = metadata.GetMethodDefinition((MethodDefinitionHandle)handle);
                declaringType = md.GetDeclaringType();
                string methodName        = metadata.GetString(md.Name);
                int    genericParamCount = md.GetGenericParameters().Count;
                if (genericParamCount > 0)
                {
                    methodName += "``" + genericParamCount;
                }
                if (fullName)
                {
                    return(md.GetDeclaringType().GetFullTypeName(metadata).ToILNameString() + "." + methodName);
                }
                return(methodName);

            case HandleKind.EventDefinition:
                var ed = metadata.GetEventDefinition((EventDefinitionHandle)handle);
                declaringType = metadata.GetMethodDefinition(ed.GetAccessors().GetAny()).GetDeclaringType();
                if (fullName)
                {
                    return(declaringType.GetFullTypeName(metadata).ToILNameString() + "." + metadata.GetString(ed.Name));
                }
                return(metadata.GetString(ed.Name));

            case HandleKind.PropertyDefinition:
                var pd = metadata.GetPropertyDefinition((PropertyDefinitionHandle)handle);
                declaringType = metadata.GetMethodDefinition(pd.GetAccessors().GetAny()).GetDeclaringType();
                if (fullName)
                {
                    return(declaringType.GetFullTypeName(metadata).ToILNameString() + "." + metadata.GetString(pd.Name));
                }
                return(metadata.GetString(pd.Name));

            default:
                return(null);
            }
        }
Example #10
0
 public FieldDefEntry(PEFile module, FieldDefinitionHandle handle)
 {
     this.metadataOffset = module.Reader.PEHeaders.MetadataStartOffset;
     this.module         = module;
     this.metadata       = module.Metadata;
     this.handle         = handle;
     this.fieldDef       = metadata.GetFieldDefinition(handle);
 }
        internal sealed override IEnumerable <FieldInfo> CoreGetDeclaredFields(NameFilter optionalNameFilter, RuntimeTypeInfo reflectedType, RuntimeTypeInfo contextTypeInfo)
        {
            MetadataReader reader = Reader;

            foreach (FieldDefinitionHandle fieldHandle in DeclaredFieldHandles)
            {
                if (optionalNameFilter == null || optionalNameFilter.Matches(reader.GetFieldDefinition(fieldHandle).Name, reader))
                {
                    yield return(EcmaFormatRuntimeFieldInfo.GetRuntimeFieldInfo(fieldHandle, this, contextTypeInfo, reflectedType));
                }
            }
        }
Example #12
0
        public override ClassLayoutMetadata GetClassLayout()
        {
            TypeLayout layout = _typeDefinition.GetLayout();

            ClassLayoutMetadata result;

            result.PackingSize = layout.PackingSize;
            result.Size        = layout.Size;

            // Skip reading field offsets if this is not explicit layout
            if (IsExplicitLayout)
            {
                var fieldDefinitionHandles = _typeDefinition.GetFields();
                var numInstanceFields      = 0;

                foreach (var handle in fieldDefinitionHandles)
                {
                    var fieldDefinition = MetadataReader.GetFieldDefinition(handle);
                    if ((fieldDefinition.Attributes & FieldAttributes.Static) != 0)
                    {
                        continue;
                    }

                    numInstanceFields++;
                }

                result.Offsets = new FieldAndOffset[numInstanceFields];

                int index = 0;
                foreach (var handle in fieldDefinitionHandles)
                {
                    var fieldDefinition = MetadataReader.GetFieldDefinition(handle);
                    if ((fieldDefinition.Attributes & FieldAttributes.Static) != 0)
                    {
                        continue;
                    }

                    // Note: GetOffset() returns -1 when offset was not set in the metadata which maps nicely
                    //       to FieldAndOffset.InvalidOffset.
                    Debug.Assert(FieldAndOffset.InvalidOffset == -1);
                    result.Offsets[index] =
                        new FieldAndOffset((FieldDesc)_module.GetObject(handle), fieldDefinition.GetOffset());

                    index++;
                }
            }
            else
            {
                result.Offsets = null;
            }

            return(result);
        }
Example #13
0
        /// <summary>
        /// Get the information for a field.
        /// </summary>
        /// <param name="reader">The metadata reader.</param>
        /// <param name="handle">The field definition to read.</param>
        /// <returns>The field's information.</returns>
        public static FieldInfo GetFieldInfo(this MetadataReader reader, FieldDefinitionHandle handle)
        {
            var fieldDefinition = reader.GetFieldDefinition(handle);

            return(new FieldInfo
            {
                Name = reader.GetString(fieldDefinition.Name),
                Type = fieldDefinition.DecodeSignature(new SignatureTypeProvider(reader), null),

                Attributes = fieldDefinition.Attributes,
            });
        }
Example #14
0
        private static void Main(string[] args)
        {
            string assemblyPath = args[0];

            using (PEReader peReader = new PEReader(File.OpenRead(assemblyPath), PEStreamOptions.PrefetchMetadata))
            {
                ISet <AssemblyName> exposedDependencies = new HashSet <AssemblyName>(new AssemblyNameEqualityComparer());

                MetadataReader metadataReader = peReader.GetMetadataReader();
                foreach (var type in metadataReader.TypeDefinitions)
                {
                    TypeDefinition typeDefinition = metadataReader.GetTypeDefinition(type);
                    if (!IsExposedType(metadataReader, typeDefinition))
                    {
                        continue;
                    }

                    Console.WriteLine("Exposed type: {0}", GetFullName(metadataReader, typeDefinition));

                    CheckType(metadataReader, typeDefinition, exposedDependencies);

                    foreach (var eventDefinitionHandle in typeDefinition.GetEvents())
                    {
                        CheckEvent(metadataReader, metadataReader.GetEventDefinition(eventDefinitionHandle), exposedDependencies);
                    }

                    foreach (var methodDefinitionHandle in typeDefinition.GetMethods())
                    {
                        CheckMethod(metadataReader, metadataReader.GetMethodDefinition(methodDefinitionHandle), exposedDependencies);
                    }

                    foreach (var propertyDefinitionHandle in typeDefinition.GetProperties())
                    {
                        CheckProperty(metadataReader, metadataReader.GetPropertyDefinition(propertyDefinitionHandle), exposedDependencies);
                    }

                    foreach (var fieldDefinitionHandle in typeDefinition.GetFields())
                    {
                        CheckField(metadataReader, metadataReader.GetFieldDefinition(fieldDefinitionHandle), exposedDependencies);
                    }
                }

                Console.WriteLine();
                Console.WriteLine("Exposed Dependencies ({0}):", Path.GetFileName(args[0]));
                foreach (AssemblyName dependency in exposedDependencies.OrderBy(i => i.FullName, StringComparer.OrdinalIgnoreCase))
                {
                    Console.WriteLine("  {0}", dependency.FullName);
                }
            }
        }
Example #15
0
        private static string GetFieldInformation(MetadataReader metadataReader, int intOperand, CilTypeProvider provider)
        {
            if (IsMemberReference(intOperand))
            {
                return(GetMemberRef(metadataReader, intOperand, provider));
            }
            var handle        = MetadataTokens.FieldDefinitionHandle(intOperand);
            var definition    = metadataReader.GetFieldDefinition(handle);
            var typeHandle    = definition.GetDeclaringType();
            var typeSignature = SignatureDecoder.DecodeType(typeHandle, provider, null);
            var signature     = SignatureDecoder.DecodeFieldSignature(definition.Signature, provider);

            return(String.Format("{0} {1}::{2}", signature.ToString(), typeSignature.ToString(false), GetString(metadataReader, definition.Name)));
        }
Example #16
0
        public override MarshalAsDescriptor GetMarshalAsDescriptor()
        {
            MetadataReader  reader     = MetadataReader;
            FieldDefinition definition = reader.GetFieldDefinition(_handle);

            if ((definition.Attributes & FieldAttributes.HasFieldMarshal) != 0)
            {
                BlobReader          marshalAsReader = reader.GetBlobReader(definition.GetMarshallingDescriptor());
                EcmaSignatureParser parser          = new EcmaSignatureParser(_type.EcmaModule, marshalAsReader, NotFoundBehavior.Throw);
                return(parser.ParseMarshalAsDescriptor());
            }

            return(null);
        }
Example #17
0
        private void WalkField(MetadataReader mdReader, FieldDefinitionHandle handle, MutableSymbol parent)
        {
            FieldDefinition field = mdReader.GetFieldDefinition(handle);

            MutableSymbol result = new MutableSymbol(mdReader.GetString(field.Name), SymbolType.Field);

            AddModifiers(field.Attributes, result);
            AddLocation(handle, result);

            if (IsExcluded(result))
            {
                return;
            }
            parent.AddChild(result);
        }
Example #18
0
        private ulong GetEnumRecordValue(FieldDesc field)
        {
            var ecmaField = field as EcmaField;

            if (ecmaField != null)
            {
                MetadataReader  reader             = ecmaField.MetadataReader;
                FieldDefinition fieldDef           = reader.GetFieldDefinition(ecmaField.Handle);
                ConstantHandle  defaultValueHandle = fieldDef.GetDefaultValue();
                if (!defaultValueHandle.IsNil)
                {
                    return(HandleConstant(ecmaField.Module, defaultValueHandle));
                }
            }
            return(0);
        }
Example #19
0
        public override MarshalAsDescriptor[] GetFieldMarshalAsDescriptors()
        {
            var fieldDefinitionHandles = _typeDefinition.GetFields();

            MarshalAsDescriptor[] marshalAsDescriptors = new MarshalAsDescriptor[fieldDefinitionHandles.Count];
            int index = 0;

            foreach (var handle in fieldDefinitionHandles)
            {
                var fieldDefinition = MetadataReader.GetFieldDefinition(handle);
                MarshalAsDescriptor marshalAsDescriptor = GetMarshalAsDescriptor(fieldDefinition);
                marshalAsDescriptors[index++] = marshalAsDescriptor;
            }

            return(marshalAsDescriptors);
        }
        private ModuleToken GetTypeToken(ModuleToken token)
        {
            if (token.IsNull)
            {
                return(token);
            }
            MetadataReader mdReader = token.MetadataReader;
            EntityHandle   handle   = (EntityHandle)MetadataTokens.Handle((int)token.Token);
            ModuleToken    typeToken;

            switch (token.TokenType)
            {
            case CorTokenType.mdtTypeRef:
            case CorTokenType.mdtTypeDef:
                typeToken = token;
                break;

            case CorTokenType.mdtMemberRef:
            {
                MemberReferenceHandle memberRefHandle = (MemberReferenceHandle)handle;
                MemberReference       memberRef       = mdReader.GetMemberReference(memberRefHandle);
                typeToken = new ModuleToken(token.Module, (mdToken)MetadataTokens.GetToken(memberRef.Parent));
            }
            break;

            case CorTokenType.mdtFieldDef:
            {
                FieldDefinitionHandle fieldDefHandle = (FieldDefinitionHandle)handle;
                FieldDefinition       fieldDef       = mdReader.GetFieldDefinition(fieldDefHandle);
                typeToken = new ModuleToken(token.Module, (mdToken)MetadataTokens.GetToken(fieldDef.GetDeclaringType()));
            }
            break;

            case CorTokenType.mdtMethodDef:
            {
                MethodDefinitionHandle methodDefHandle = (MethodDefinitionHandle)handle;
                MethodDefinition       methodDef       = mdReader.GetMethodDefinition(methodDefHandle);
                typeToken = new ModuleToken(token.Module, (mdToken)MetadataTokens.GetToken(methodDef.GetDeclaringType()));
            }
            break;

            default:
                throw new NotImplementedException();
            }

            return(typeToken);
        }
Example #21
0
        public override ClassLayoutMetadata GetClassLayout()
        {
            TypeLayout layout = _typeDefinition.GetLayout();

            ClassLayoutMetadata result;
            result.PackingSize = layout.PackingSize;
            result.Size = layout.Size;

            // Skip reading field offsets if this is not explicit layout
            if (IsExplicitLayout)
            {
                var fieldDefinitionHandles = _typeDefinition.GetFields();
                var numInstanceFields = 0;

                foreach (var handle in fieldDefinitionHandles)
                {
                    var fieldDefinition = MetadataReader.GetFieldDefinition(handle);
                    if ((fieldDefinition.Attributes & FieldAttributes.Static) != 0)
                        continue;

                    numInstanceFields++;
                }

                result.Offsets = new FieldAndOffset[numInstanceFields];

                int index = 0;
                foreach (var handle in fieldDefinitionHandles)
                {
                    var fieldDefinition = MetadataReader.GetFieldDefinition(handle);
                    if ((fieldDefinition.Attributes & FieldAttributes.Static) != 0)
                        continue;

                    // Note: GetOffset() returns -1 when offset was not set in the metadata
                    int specifiedOffset = fieldDefinition.GetOffset();
                    result.Offsets[index] =
                        new FieldAndOffset((EcmaField)_module.GetObject(handle), specifiedOffset == -1 ? FieldAndOffset.InvalidOffset : new LayoutInt(specifiedOffset));

                    index++;
                }
            }
            else
                result.Offsets = null;

            return result;
        }
        public void WrongSignatureType()
        {
            using (FileStream stream = File.OpenRead(AssemblyPathHelper.GetAssemblyLocation(typeof(VarArgsToDecode).GetTypeInfo().Assembly)))
                using (var peReader = new PEReader(stream))
                {
                    MetadataReader reader   = peReader.GetMetadataReader();
                    var            provider = new DisassemblingTypeProvider();
                    var            decoder  = new SignatureDecoder <string, DisassemblingGenericContext>(provider, reader, genericContext: null);

                    BlobReader fieldSignature    = reader.GetBlobReader(reader.GetFieldDefinition(MetadataTokens.FieldDefinitionHandle(1)).Signature);
                    BlobReader methodSignature   = reader.GetBlobReader(reader.GetMethodDefinition(MetadataTokens.MethodDefinitionHandle(1)).Signature);
                    BlobReader propertySignature = reader.GetBlobReader(reader.GetPropertyDefinition(MetadataTokens.PropertyDefinitionHandle(1)).Signature);

                    Assert.Throws <BadImageFormatException>(() => decoder.DecodeMethodSignature(ref fieldSignature));
                    Assert.Throws <BadImageFormatException>(() => decoder.DecodeFieldSignature(ref methodSignature));
                    Assert.Throws <BadImageFormatException>(() => decoder.DecodeLocalSignature(ref propertySignature));
                }
        }
        private Mapping <FieldDefinitionHandle> MapFieldDefinitionImpl(FieldDefinitionHandle handle)
        {
            FieldDefinition fieldDefinition = _sourceMetadata.GetFieldDefinition(handle);

            // Map the parent
            Mapping <TypeDefinitionHandle> declaringTypeMapping = MapTypeDefinition(fieldDefinition.GetDeclaringType());

            if (declaringTypeMapping.Target.IsNil)
            {
                return(new Mapping <FieldDefinitionHandle>());
            }

            string fieldName = _sourceMetadata.GetString(fieldDefinition.Name);

            TypeDefinition targetDeclaringType = _targetMetadata.GetTypeDefinition(declaringTypeMapping.Target);

            foreach (var targetHandle in targetDeclaringType.GetFields())
            {
                var targetField = _targetMetadata.GetFieldDefinition(targetHandle);
                if (!_targetMetadata.StringComparer.Equals(targetField.Name, fieldName))
                {
                    continue;
                }

                // The name matches. If the signature matches, return in Target; otherwise, return in CandidateTargets.
                FieldSignature sourceSignature = _sourceMetadata.GetSignature(fieldDefinition);
                FieldSignature targetSignature = _targetMetadata.GetSignature(targetField);
                string         candidateReason = CompareFieldSignatures(sourceSignature, targetSignature);
                if (candidateReason == null)
                {
                    return(new Mapping <FieldDefinitionHandle>(targetHandle));
                }

                var candidateTargets = ImmutableArray.Create(targetHandle);
                var candidateReasons = ImmutableArray.Create(candidateReason);
                return(new Mapping <FieldDefinitionHandle>(candidateTargets, candidateReasons));
            }

            // No field with this name was located.
            return(new Mapping <FieldDefinitionHandle>());
        }
Example #24
0
        public static bool IsEnum(this TypeDefinition typeDefinition, MetadataReader reader, out PrimitiveTypeCode underlyingType)
        {
            underlyingType = 0;
            if (typeDefinition.BaseType.IsNil)
            {
                return(false);
            }
            if (!typeDefinition.BaseType.IsKnownType(reader, KnownTypeCode.Enum))
            {
                return(false);
            }
            var field = reader.GetFieldDefinition(typeDefinition.GetFields().First());
            var blob  = reader.GetBlobReader(field.Signature);

            if (blob.ReadSignatureHeader().Kind != SignatureKind.Field)
            {
                return(false);
            }
            underlyingType = (PrimitiveTypeCode)blob.ReadByte();
            return(true);
        }
Example #25
0
        public static EnumInfo Create(RuntimeTypeHandle typeHandle, MetadataReader reader, TypeDefinitionHandle typeDefHandle)
        {
            TypeDefinition typeDef = reader.GetTypeDefinition(typeDefHandle);

            // Per the spec, Enums are required to have one instance field. The rest are statics.
            int staticFieldCount = typeDef.GetFields().Count - 1;

            string[] names  = new string[staticFieldCount];
            object[] values = new object[staticFieldCount];

            int i = 0;

            foreach (FieldDefinitionHandle fieldHandle in typeDef.GetFields())
            {
                FieldDefinition field = reader.GetFieldDefinition(fieldHandle);
                if (0 != (field.Attributes & FieldAttributes.Static))
                {
                    if (i >= staticFieldCount || (field.Attributes & FieldAttributes.HasDefault) != FieldAttributes.HasDefault)
                    {
                        throw new BadImageFormatException();
                    }

                    names[i]  = reader.GetString(field.Name);
                    values[i] = field.GetDefaultValue().ParseConstantValue(reader);
                    i++;
                }
            }

            bool isFlags = false;

            foreach (CustomAttributeHandle cah in typeDef.GetCustomAttributes())
            {
                if (cah.IsCustomAttributeOfType(reader, "System", "FlagsAttribute"))
                {
                    isFlags = true;
                }
            }

            return(new EnumInfo(RuntimeAugments.GetEnumUnderlyingType(typeHandle), values, names, isFlags));
        }
Example #26
0
        void CreateImportFor(string declaringTypeFullName, TypeDefinition type, CodeMemberMethod method, MetadataReader reader)
        {
            var typeName    = reader.GetString(type.Name);
            var srcClassRef = new CodeTypeReferenceExpression(
                new CodeTypeReference($"{primary_name}.{typeName}", CodeTypeReferenceOptions.GlobalReference));
            var dstClassRef = new CodeTypeReferenceExpression(
                new CodeTypeReference($"{declaringTypeFullName}.{typeName}", CodeTypeReferenceOptions.GlobalReference));

            foreach (var handle in type.GetFields())
            {
                var fieldName       = reader.GetString(reader.GetFieldDefinition(handle).Name);
                var dstField        = new CodeFieldReferenceExpression(dstClassRef, fieldName);
                var srcField        = new CodeFieldReferenceExpression(srcClassRef, fieldName);
                var fieldIdentifier = CreateIdentifier(typeName, fieldName);
                if (!resourceFields.Contains(fieldIdentifier))
                {
                    Log.LogDebugMessage($"Value not found for {fieldIdentifier}, skipping...");
                    continue;
                }
                // This simply assigns field regardless of whether it is int or int[].
                method.Statements.Add(new CodeAssignStatement(dstField, srcField));
            }
        }
        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($"[{CollectionsAssemblyName}]System.Collections.Generic.List`1<!T>", provider.GetTypeFromHandle(reader, genericTypeContext, handle: type.BaseType));
                }
        }
Example #28
0
        /// <summary>
        /// Field Table Columns:
        ///     Name (offset to #String)
        ///     Flags (2 byte unsigned)
        ///     Signature (offset to #blob)
        /// </summary>
        private void ValidateFieldDef(MetadataReader reader, uint startIndex, uint count, bool isMod = false)
        {
            if (count == 0)
            {
                return;
            }

            // APPCS
            var expNames = new string[] { "AppField01", "AppField02" };
            var expFlags = new FieldAttributes[]
            {
                /*0x11*/
                         FieldAttributes.Private | FieldAttributes.Static,
                /*0x01*/ FieldAttributes.Private,
                };
            var expSigs = new byte[][] { new byte[] { 0x06, 0x12, 0x11 }, new byte[] { 0x06, 0x12, 0x25 }, };

            // =====================================================================================================
            // VB Module - 8
            var modNames = new string[] { "ConstString", "ArrayField", "AnEventEvent", "value__", "None", "Red", "Yellow", "Blue", };
            var modFlags = new FieldAttributes[]
            {
                /* 0x8053 */
                             FieldAttributes.HasDefault | FieldAttributes.Literal | FieldAttributes.Static | FieldAttributes.FamANDAssem | FieldAttributes.Private,
                /* 0x0016 */ FieldAttributes.Static | FieldAttributes.Family | FieldAttributes.FamANDAssem,
                /* 0x0001 */ FieldAttributes.Private,
                /* 0x0606 */ FieldAttributes.RTSpecialName | FieldAttributes.SpecialName | FieldAttributes.Family | FieldAttributes.FamANDAssem,
                /* 0x8056 */ FieldAttributes.HasDefault | FieldAttributes.Literal | FieldAttributes.Static | FieldAttributes.Family | FieldAttributes.FamANDAssem,
                /* 0x8056 */ FieldAttributes.HasDefault | FieldAttributes.Literal | FieldAttributes.Static | FieldAttributes.Family | FieldAttributes.FamANDAssem,
                /* 0x8056 */ FieldAttributes.HasDefault | FieldAttributes.Literal | FieldAttributes.Static | FieldAttributes.Family | FieldAttributes.FamANDAssem,
                /* 0x8056 */ FieldAttributes.HasDefault | FieldAttributes.Literal | FieldAttributes.Static | FieldAttributes.Family | FieldAttributes.FamANDAssem,
                };
            var modSigs = new byte[][]
            {
                new byte[] { 0x06, 0x0e }, new byte[] { 0x06, 0x14, 0x11, 0x14, 02, 00, 02, 00, 00 },
                new byte[] { 0x06, 0x12, 0x18 }, new byte[] { 0x06, 0x08 },
                new byte[] { 0x06, 0x11, 0x10 }, new byte[] { 0x06, 0x11, 0x10 },
                new byte[] { 0x06, 0x11, 0x10 }, new byte[] { 0x06, 0x11, 0x10 },
            };

            if (startIndex > reader.FieldTable.NumberOfRows)
            {
                return;
            }

            uint zeroBased = startIndex - 1;
            uint delta = count;

            // Last one
            if (0xF0000000 == count)
            {
                delta = (uint)reader.FieldTable.NumberOfRows - zeroBased;
                if (0 == delta)
                {
                    return;
                }
            }

            Assert.InRange((uint)reader.FieldTable.NumberOfRows, zeroBased + delta, uint.MaxValue); // 1 based
            for (uint i = zeroBased; i < zeroBased + delta; i++)
            {
                var handle = FieldDefinitionHandle.FromRowId((int)(i + 1));
                var row = reader.GetFieldDefinition(handle);

                if (isMod)
                {
                    Assert.Equal(modNames[i], reader.GetString(row.Name));
                    Assert.Equal(modFlags[i], row.Attributes);
                }
                else
                {
                    Assert.Equal(expNames[i], reader.GetString(row.Name));
                    Assert.Equal(expFlags[i], row.Attributes);
                }

                var sig = reader.GetBlobBytes(row.Signature);

                // calling convention, always 6 for field
                Assert.Equal(sig[0], 6);
                int len = 0;
                if (isMod)
                {
                    len = modSigs[i].Length;
                }
                else
                {
                    len = expSigs[i].Length;
                }

                for (int j = 1; j < len; j++)
                {
                    if (isMod)
                    {
                        Assert.Equal(modSigs[i][j], sig[j]);
                    }
                    else
                    {
                        Assert.Equal(expSigs[i][j], sig[j]);
                    }
                }
            }
        }
Example #29
0
 public override bool HasCustomAttribute(string attributeNamespace, string attributeName)
 {
     return(MetadataReader.HasCustomAttribute(MetadataReader.GetFieldDefinition(_handle).GetCustomAttributes(),
                                              attributeNamespace, attributeName));
 }
Example #30
0
 public static StringHandle[] GetFieldDefNames(this MetadataReader reader)
 {
     return(reader.FieldDefinitions.Select(handle => reader.GetFieldDefinition(handle).Name).ToArray());
 }
Example #31
0
        public override string GetEntityName(PEFile module, EntityHandle handle, bool fullName)
        {
            MetadataReader metadata = module.Metadata;

            switch (handle.Kind)
            {
            case HandleKind.TypeDefinition:
                return(ToCSharpString(metadata, (TypeDefinitionHandle)handle, fullName));

            case HandleKind.FieldDefinition:
                var fd            = metadata.GetFieldDefinition((FieldDefinitionHandle)handle);
                var declaringType = fd.GetDeclaringType();
                if (fullName)
                {
                    return(ToCSharpString(metadata, declaringType, fullName) + "." + metadata.GetString(fd.Name));
                }
                return(metadata.GetString(fd.Name));

            case HandleKind.MethodDefinition:
                var md = metadata.GetMethodDefinition((MethodDefinitionHandle)handle);
                declaringType = md.GetDeclaringType();
                string methodName = metadata.GetString(md.Name);
                switch (methodName)
                {
                case ".ctor":
                case ".cctor":
                    var td = metadata.GetTypeDefinition(declaringType);
                    methodName = ReflectionHelper.SplitTypeParameterCountFromReflectionName(metadata.GetString(td.Name));
                    break;

                case "Finalize":
                    const MethodAttributes finalizerAttributes = (MethodAttributes.Virtual | MethodAttributes.Family | MethodAttributes.HideBySig);
                    if ((md.Attributes & finalizerAttributes) != finalizerAttributes)
                    {
                        goto default;
                    }
                    MethodSignature <IType> methodSignature = md.DecodeSignature(MetadataExtensions.MinimalSignatureTypeProvider, default);
                    if (methodSignature.GenericParameterCount != 0 || methodSignature.ParameterTypes.Length != 0)
                    {
                        goto default;
                    }
                    td         = metadata.GetTypeDefinition(declaringType);
                    methodName = "~" + ReflectionHelper.SplitTypeParameterCountFromReflectionName(metadata.GetString(td.Name));
                    break;

                default:
                    var genericParams = md.GetGenericParameters();
                    if (genericParams.Count > 0)
                    {
                        methodName += "<";
                        int i = 0;
                        foreach (var h in genericParams)
                        {
                            if (i > 0)
                            {
                                methodName += ",";
                            }
                            var gp = metadata.GetGenericParameter(h);
                            methodName += metadata.GetString(gp.Name);
                        }
                        methodName += ">";
                    }
                    break;
                }
                if (fullName)
                {
                    return(ToCSharpString(metadata, declaringType, fullName) + "." + methodName);
                }
                return(methodName);

            case HandleKind.EventDefinition:
                var ed = metadata.GetEventDefinition((EventDefinitionHandle)handle);
                declaringType = metadata.GetMethodDefinition(ed.GetAccessors().GetAny()).GetDeclaringType();
                if (fullName)
                {
                    return(ToCSharpString(metadata, declaringType, fullName) + "." + metadata.GetString(ed.Name));
                }
                return(metadata.GetString(ed.Name));

            case HandleKind.PropertyDefinition:
                var pd = metadata.GetPropertyDefinition((PropertyDefinitionHandle)handle);
                declaringType = metadata.GetMethodDefinition(pd.GetAccessors().GetAny()).GetDeclaringType();
                if (fullName)
                {
                    return(ToCSharpString(metadata, declaringType, fullName) + "." + metadata.GetString(pd.Name));
                }
                return(metadata.GetString(pd.Name));

            default:
                return(null);
            }
        }
Example #32
0
 private static string GetFieldInformation(MetadataReader metadataReader, int intOperand, CilTypeProvider provider)
 {
     if(IsMemberReference(intOperand))
     {
         return GetMemberRef(metadataReader, intOperand, provider);
     }
     var handle = MetadataTokens.FieldDefinitionHandle(intOperand);
     var definition = metadataReader.GetFieldDefinition(handle);
     var typeHandle = definition.GetDeclaringType();
     var typeSignature = SignatureDecoder.DecodeType(typeHandle, provider, null);
     var signature = SignatureDecoder.DecodeFieldSignature(definition.Signature, provider);
     return String.Format("{0} {1}::{2}", signature.ToString(), typeSignature.ToString(false), GetString(metadataReader, definition.Name));
 }