Ejemplo n.º 1
0
 public FieldAndOffset(FieldDesc field, int offset)
 {
     Field = field;
     Offset = offset;
 }
Ejemplo n.º 2
0
 private ISymbolNode CreateFieldHandleHelper(FieldDesc field, SignatureContext signatureContext)
 {
     return(new PrecodeHelperImport(
                _codegenNodeFactory,
                new FieldFixupSignature(ReadyToRunFixupKind.READYTORUN_FIXUP_FieldHandle, field, signatureContext)));
 }
 public PreInitFieldFixupInfo(int offset, FieldDesc field)
     : base(offset)
 {
     FieldFixup = field;
 }
Ejemplo n.º 4
0
        private string ComputeMangledFieldName(FieldDesc field)
        {
            string prependTypeName = null;

            if (!_compilation.IsCppCodeGen)
            {
                prependTypeName = GetMangledTypeName(field.OwningType);
            }

            if (field is EcmaField)
            {
                var deduplicator = new HashSet <string>();

                // Add consistent names for all fields of the type, independent on the order in which
                // they are compiled
                lock (this)
                {
                    foreach (var f in field.OwningType.GetFields())
                    {
                        string name = SanitizeName(f.Name);

                        if (deduplicator.Contains(name))
                        {
                            string nameWithIndex;
                            for (int index = 1; ; index++)
                            {
                                nameWithIndex = name + "_" + index.ToString(CultureInfo.InvariantCulture);
                                if (!deduplicator.Contains(nameWithIndex))
                                {
                                    break;
                                }
                            }
                            name = nameWithIndex;
                        }
                        deduplicator.Add(name);

                        if (prependTypeName != null)
                        {
                            name = prependTypeName + "__" + name;
                        }

                        _mangledFieldNames = _mangledFieldNames.Add(f, name);
                    }
                }

                return(_mangledFieldNames[field]);
            }


            string mangledName = SanitizeName(field.Name);

            if (prependTypeName != null)
            {
                mangledName = prependTypeName + "__" + mangledName;
            }

            lock (this)
            {
                _mangledFieldNames = _mangledFieldNames.Add(field, mangledName);
            }

            return(mangledName);
        }
Ejemplo n.º 5
0
 public FieldHandleGenericLookupResult(FieldDesc field)
 {
     Debug.Assert(field.OwningType.IsRuntimeDeterminedSubtype, "Concrete field in a generic dictionary?");
     _field = field;
 }
Ejemplo n.º 6
0
        public static bool TryGetDependenciesForReflectedField(ref DependencyList dependencies, NodeFactory factory, FieldDesc field, string reason)
        {
            FieldDesc typicalField = field.GetTypicalFieldDefinition();

            if (factory.MetadataManager.IsReflectionBlocked(typicalField))
            {
                return(false);
            }

            dependencies ??= new DependencyList();

            // If this is a field on generic type, make sure we at minimum have the metadata
            // for it. This hedges against the risk that we fail to figure out an instantiated base
            // for it below.
            if (typicalField.OwningType.HasInstantiation)
            {
                dependencies.Add(factory.ReflectableField(typicalField), reason);
            }

            // If there's any genericness involved, try to create a fitting instantiation that would be usable at runtime.
            // This is not a complete solution to the problem.
            // If we ever decide that MakeGenericType/MakeGenericMethod should simply be considered unsafe, this code can be deleted
            // and instantiations that are not fully closed can be ignored.
            if (field.OwningType.IsGenericDefinition || field.OwningType.ContainsSignatureVariables(treatGenericParameterLikeSignatureVariable: true))
            {
                TypeDesc      owningType = field.OwningType.GetTypeDefinition();
                Instantiation inst       = TypeExtensions.GetInstantiationThatMeetsConstraints(owningType.Instantiation, allowCanon: true);
                if (inst.IsNull)
                {
                    return(false);
                }

                field = field.Context.GetFieldForInstantiatedType(
                    field.GetTypicalFieldDefinition(),
                    ((MetadataType)owningType).MakeInstantiatedType(inst));
            }

            dependencies.Add(factory.ReflectableField(field), reason);

            return(true);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Generates IL for the IsSupported property that reads this information from a field initialized by the runtime
        /// at startup. Returns null for hardware intrinsics whose support level is known at compile time
        /// (i.e. they're known to be always supported or always unsupported).
        /// </summary>
        public static MethodIL EmitIsSupportedIL(MethodDesc method, FieldDesc isSupportedField)
        {
            Debug.Assert(IsIsSupportedMethod(method));
            Debug.Assert(isSupportedField.IsStatic && isSupportedField.FieldType.IsWellKnownType(WellKnownType.Int32));

            TargetDetails target     = method.Context.Target;
            MetadataType  owningType = (MetadataType)method.OwningType;

            // Check for case of nested "X64" types
            if (owningType.Name == "X64")
            {
                if (target.Architecture != TargetArchitecture.X64)
                {
                    return(null);
                }

                // Un-nest the type so that we can do a name match
                owningType = (MetadataType)owningType.ContainingType;
            }

            int flag;

            if ((target.Architecture == TargetArchitecture.X64 || target.Architecture == TargetArchitecture.X86) &&
                owningType.Namespace == "System.Runtime.Intrinsics.X86")
            {
                switch (owningType.Name)
                {
                case "Aes":
                    flag = XArchIntrinsicConstants.Aes;
                    break;

                case "Pclmulqdq":
                    flag = XArchIntrinsicConstants.Pclmulqdq;
                    break;

                case "Sse3":
                    flag = XArchIntrinsicConstants.Sse3;
                    break;

                case "Ssse3":
                    flag = XArchIntrinsicConstants.Ssse3;
                    break;

                case "Lzcnt":
                    flag = XArchIntrinsicConstants.Lzcnt;
                    break;

                // NOTE: this switch is complemented by IsKnownSupportedIntrinsicAtCompileTime
                // in the method below.
                default:
                    return(null);
                }
            }
            else
            {
                return(null);
            }

            var          emit       = new ILEmitter();
            ILCodeStream codeStream = emit.NewCodeStream();

            codeStream.Emit(ILOpcode.ldsfld, emit.NewToken(isSupportedField));
            codeStream.EmitLdc(flag);
            codeStream.Emit(ILOpcode.and);
            codeStream.EmitLdc(0);
            codeStream.Emit(ILOpcode.cgt_un);
            codeStream.Emit(ILOpcode.ret);

            return(emit.Link(method));
        }
Ejemplo n.º 8
0
 public RuntimeFieldHandleNode(FieldDesc targetField)
 {
     Debug.Assert(!targetField.OwningType.IsCanonicalSubtype(CanonicalFormKind.Any));
     Debug.Assert(!targetField.OwningType.IsRuntimeDeterminedSubtype);
     _targetField = targetField;
 }
Ejemplo n.º 9
0
 /// <summary>
 /// Given that a method is invokable, if it is inserted into the reflection invoke table
 /// will it use a field token to be referenced, or not?
 /// </summary>
 public abstract bool WillUseMetadataTokenToReferenceField(FieldDesc field);
Ejemplo n.º 10
0
        private Object ResolveMemberReference(MemberReferenceHandle handle)
        {
            MemberReference memberReference = _metadataReader.GetMemberReference(handle);

            Object parent = GetObject(memberReference.Parent);

            TypeDesc parentTypeDesc = parent as TypeDesc;

            if (parentTypeDesc != null)
            {
                BlobReader signatureReader = _metadataReader.GetBlobReader(memberReference.Signature);

                EcmaSignatureParser parser = new EcmaSignatureParser(this, signatureReader);

                string name = _metadataReader.GetString(memberReference.Name);

                if (parser.IsFieldSignature)
                {
                    FieldDesc field = parentTypeDesc.GetField(name);
                    if (field != null)
                    {
                        return(field);
                    }

                    // TODO: Better error message
                    throw new MissingMemberException("Field not found " + parent.ToString() + "." + name);
                }
                else
                {
                    MethodSignature sig = parser.ParseMethodSignature();
                    TypeDesc        typeDescToInspect = parentTypeDesc;

                    // Try to resolve the name and signature in the current type, or any of the base types.
                    do
                    {
                        // TODO: handle substitutions
                        MethodDesc method = typeDescToInspect.GetMethod(name, sig);
                        if (method != null)
                        {
                            // If this resolved to one of the base types, make sure it's not a constructor.
                            // Instance constructors are not inherited.
                            if (typeDescToInspect != parentTypeDesc && method.IsConstructor)
                            {
                                break;
                            }

                            return(method);
                        }
                        typeDescToInspect = typeDescToInspect.BaseType;
                    } while (typeDescToInspect != null);

                    // TODO: Better error message
                    throw new MissingMemberException("Method not found " + parent.ToString() + "." + name);
                }
            }
            else if (parent is MethodDesc)
            {
                throw new NotSupportedException("Vararg methods not supported in .NET Core.");
            }
            else if (parent is ModuleDesc)
            {
                throw new NotImplementedException("MemberRef to a global function or variable.");
            }

            throw new BadImageFormatException();
        }
Ejemplo n.º 11
0
 protected internal override int CompareToImpl(FieldDesc other, TypeSystemComparer comparer)
 {
     return(comparer.Compare(_managedField, ((NativeStructField)other)._managedField));
 }
Ejemplo n.º 12
0
 public BlobNode FieldRvaDataBlob(FieldDesc field)
 {
     // Use the typical field definition in case this is an instantiated generic type
     field = field.GetTypicalFieldDefinition();
     return(ReadOnlyDataBlob(NameMangler.GetMangledFieldName(field), ((EcmaField)field).GetFieldRvaData(), Target.PointerSize));
 }
Ejemplo n.º 13
0
 protected override int CompareToImpl(FieldDesc other, TypeSystemComparer comparer)
 {
     return(_symbolName.CompareTo(((ExternSymbolMappedField)other)._symbolName));
 }
Ejemplo n.º 14
0
 /// <summary>
 /// This method is an extension point that can provide additional metadata-based dependencies to generated RuntimeFieldHandles.
 /// </summary>
 public virtual void GetDependenciesDueToLdToken(ref DependencyList dependencies, NodeFactory factory, FieldDesc field)
 {
     // MetadataManagers can override this to provide additional dependencies caused by the presence of a
     // RuntimeFieldHandle data structure.
 }
 public GenericLookupResult FieldHandle(FieldDesc field)
 {
     return(_fieldHandles.GetOrAdd(field));
 }
Ejemplo n.º 16
0
 public bool CanGenerateMetadata(FieldDesc field)
 {
     Debug.Assert(field.IsTypicalFieldDefinition);
     return((GetMetadataCategory(field) & MetadataCategory.Description) != 0);
 }
Ejemplo n.º 17
0
 /// <summary>
 /// Gets an object representing the static data for RVA mapped fields from the PE image.
 /// </summary>
 public object GetFieldRvaData(FieldDesc field)
 {
     return(_nodeFactory.ReadOnlyDataBlob(NameMangler.GetMangledFieldName(field),
                                          ((EcmaField)field).GetFieldRvaData(), _typeSystemContext.Target.PointerSize));
 }
Ejemplo n.º 18
0
 protected abstract MetadataCategory GetMetadataCategory(FieldDesc field);
 public ISymbolNode GetFieldRvaData(FieldDesc field) => NodeFactory.CopiedFieldRva(field);
Ejemplo n.º 20
0
 public override bool IsBlocked(FieldDesc field)
 {
     Debug.Assert(field.IsTypicalFieldDefinition);
     // TODO: we might need to do something here if we keep this policy.
     return(false);
 }
Ejemplo n.º 21
0
 public static bool IsPrivate(this FieldDesc field)
 {
     return(field.GetTypicalFieldDefinition() is EcmaField ecmaField &&
            (ecmaField.Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Private);
 }
Ejemplo n.º 22
0
 public bool GeneratesMetadata(FieldDesc fieldDef) => false;
 public bool GeneratesMetadata(FieldDesc fieldDef)
 {
     return(true);
 }
Ejemplo n.º 24
0
        private void ReadRequiredTemplates(MethodIL methodIL, HashSet <TypeDesc> typeTemplates, HashSet <MethodDesc> methodTemplates, HashSet <FieldDesc> fieldTemplates)
        {
            ILStreamReader il = new ILStreamReader(methodIL);

            if (!_typeSystemContext.SupportsUniversalCanon)
            {
                return;
            }

            //
            // Types, methods and field tokens listed here are *open* generic definitions determined by the reducer as needing reflection.
            // Type tokens listed are tokens of generic type definitions that will need reflection support.
            // Method tokens listed are either tokens of generic method definitions, or non-generic methods on generic containing type definitions, and need reflection support.
            // Field tokens listed are for fields on generic type definitions that will need reflection support
            // The canonical form supported by the typesystem context will determine how to instantiate the types/methods/fields listed here, and templatize them for
            // reflection support at runtime (templates used by the dynamic TypeLoader component of the runtime).
            //

            // structure is
            // REPEAT N TIMES
            //ldtoken type
            //pop
            while (true)
            {
                if (il.TryReadRet()) // ret
                {
                    break;
                }

                TypeSystemEntity tse;
                il.TryReadLdtokenAsTypeSystemEntity(out tse);
                il.ReadPop();

                if (tse == null)
                {
                    throw new BadImageFormatException();
                }

                if (tse is MetadataType)
                {
                    MetadataType type = (MetadataType)tse;
                    Debug.Assert(type.IsGenericDefinition && type.HasInstantiation);

                    type = _typeSystemContext.GetInstantiatedType(type, GetUniversalCanonicalInstantiation(type.Instantiation.Length));

                    typeTemplates.Add(type);
                }
                else if (tse is MethodDesc)
                {
                    MethodDesc method         = (MethodDesc)tse;
                    TypeDesc   containingType = method.OwningType;

                    Debug.Assert(method.IsTypicalMethodDefinition);
                    Debug.Assert(method.HasInstantiation || method.OwningType.HasInstantiation);

                    if (containingType.HasInstantiation)
                    {
                        containingType = _typeSystemContext.GetInstantiatedType((MetadataType)containingType, GetUniversalCanonicalInstantiation(containingType.Instantiation.Length));
                        method         = containingType.GetMethod(method.Name, method.GetTypicalMethodDefinition().Signature);
                        typeTemplates.Add(containingType);
                    }

                    if (method.HasInstantiation)
                    {
                        method = _typeSystemContext.GetInstantiatedMethod(method, GetUniversalCanonicalInstantiation(method.Instantiation.Length));
                    }

                    methodTemplates.Add(method);
                }
                else if (tse is FieldDesc)
                {
                    FieldDesc field          = (FieldDesc)tse;
                    TypeDesc  containingType = field.OwningType;

                    Debug.Assert(containingType.HasInstantiation && containingType.IsGenericDefinition);

                    containingType = _typeSystemContext.GetInstantiatedType((MetadataType)containingType, GetUniversalCanonicalInstantiation(containingType.Instantiation.Length));
                    field          = containingType.GetField(field.Name);

                    typeTemplates.Add(containingType);
                    fieldTemplates.Add(field);
                }
            }
        }
Ejemplo n.º 25
0
        public override ISymbolNode GetTarget(NodeFactory factory, Instantiation typeInstantiation, Instantiation methodInstantiation, GenericDictionaryNode dictionary)
        {
            FieldDesc instantiatedField = _field.InstantiateSignature(typeInstantiation, methodInstantiation);

            return(factory.RuntimeFieldHandle(instantiatedField));
        }
Ejemplo n.º 26
0
 public override bool WillUseMetadataTokenToReferenceField(FieldDesc field)
 {
     return(_compilationModuleGroup.ContainsType(field.GetTypicalFieldDefinition().OwningType));
 }
        /// <summary>
        /// Extract preinitialize data as byte[] from a RVA field, and perform necessary validations.
        /// </summary>
        private static PreInitFieldInfo ConstructPreInitFieldInfo(FieldDesc field, FieldDesc dataField)
        {
            if (!dataField.HasRva)
            {
                throw new BadImageFormatException();
            }

            var ecmaDataField = dataField as EcmaField;

            if (ecmaDataField == null)
            {
                throw new NotSupportedException();
            }

            var      rvaData   = ecmaDataField.GetFieldRvaData();
            var      fieldType = field.FieldType;
            int      elementCount;
            int      realDataOffset;
            TypeDesc realDataType = null;

            //
            // Construct fixups
            //
            List <PreInitFixupInfo> fixups = null;

            var typeFixupAttrs = ecmaDataField.GetDecodedCustomAttributes("System.Runtime.CompilerServices", "TypeHandleFixupAttribute");

            foreach (var typeFixupAttr in typeFixupAttrs)
            {
                if (typeFixupAttr.FixedArguments[0].Type != field.Context.GetWellKnownType(WellKnownType.Int32))
                {
                    throw new BadImageFormatException();
                }

                int offset    = (int)typeFixupAttr.FixedArguments[0].Value;
                var typeArg   = typeFixupAttr.FixedArguments[1].Value;
                var fixupType = typeArg as TypeDesc;
                if (fixupType == null)
                {
                    if (typeArg is string fixupTypeName)
                    {
                        fixupType = CustomAttributeTypeNameParser.GetTypeByCustomAttributeTypeName(ecmaDataField.Module, fixupTypeName, throwIfNotFound: true);
                    }
                    else
                    {
                        throw new BadImageFormatException();
                    }
                }

                fixups = fixups ?? new List <PreInitFixupInfo>();

                if (offset == 0 && fieldType.IsSzArray)
                {
                    // For array field, offset 0 is the element type handle followed by the element count
                    realDataType = fixupType;
                }
                else
                {
                    fixups.Add(new PreInitTypeFixupInfo(offset, fixupType));
                }
            }

            var methodFixupAttrs = ecmaDataField.GetDecodedCustomAttributes("System.Runtime.CompilerServices", "MethodAddrFixupAttribute");

            foreach (var methodFixupAttr in methodFixupAttrs)
            {
                if (methodFixupAttr.FixedArguments[0].Type != field.Context.GetWellKnownType(WellKnownType.Int32))
                {
                    throw new BadImageFormatException();
                }

                int      offset    = (int)methodFixupAttr.FixedArguments[0].Value;
                TypeDesc fixupType = methodFixupAttr.FixedArguments[1].Value as TypeDesc;
                if (fixupType == null)
                {
                    throw new BadImageFormatException();
                }

                string methodName = methodFixupAttr.FixedArguments[2].Value as string;
                if (methodName == null)
                {
                    throw new BadImageFormatException();
                }

                var method = fixupType.GetMethod(methodName, signature: null);
                if (method == null)
                {
                    throw new BadImageFormatException();
                }

                fixups = fixups ?? new List <PreInitFixupInfo>();

                fixups.Add(new PreInitMethodFixupInfo(offset, method));
            }

            var fieldFixupAttrs = ecmaDataField.GetDecodedCustomAttributes("System.Runtime.CompilerServices", "FieldAddrFixupAttribute");

            foreach (var fieldFixupAttr in fieldFixupAttrs)
            {
                if (fieldFixupAttr.FixedArguments[0].Type != field.Context.GetWellKnownType(WellKnownType.Int32))
                {
                    throw new BadImageFormatException();
                }

                int      offset    = (int)fieldFixupAttr.FixedArguments[0].Value;
                TypeDesc fixupType = fieldFixupAttr.FixedArguments[1].Value as TypeDesc;
                if (fixupType == null)
                {
                    throw new BadImageFormatException();
                }

                string fieldName = fieldFixupAttr.FixedArguments[2].Value as string;
                if (fieldName == null)
                {
                    throw new BadImageFormatException();
                }

                var fixupField = fixupType.GetField(fieldName);
                if (fixupField == null)
                {
                    throw new BadImageFormatException();
                }

                if (!fixupField.IsStatic)
                {
                    throw new BadImageFormatException();
                }

                fixups = fixups ?? new List <PreInitFixupInfo>();

                fixups.Add(new PreInitFieldFixupInfo(offset, fixupField));
            }

            if (fieldType.IsValueType || fieldType.IsPointer)
            {
                elementCount   = -1;
                realDataOffset = 0;
                realDataType   = fieldType;
            }
            else if (fieldType.IsSzArray)
            {
                // Offset 0 is the element type handle fixup followed by the element count
                if (realDataType == null)
                {
                    throw new BadImageFormatException();
                }

                int ptrSize = fieldType.Context.Target.PointerSize;
                elementCount   = rvaData[ptrSize] | rvaData[ptrSize + 1] << 8 | rvaData[ptrSize + 2] << 16 | rvaData[ptrSize + 3] << 24;
                realDataOffset = ptrSize * 2;
                realDataType   = realDataType.MakeArrayType();
            }
            else
            {
                throw new NotSupportedException();
            }

            return(new PreInitFieldInfo(field, realDataType, rvaData, realDataOffset, elementCount, fixups));
        }
Ejemplo n.º 28
0
 protected override MetadataCategory GetMetadataCategory(FieldDesc field)
 {
     // Backwards compatible behavior. We might want to tweak this.
     return(MetadataCategory.RuntimeMapping);
 }
Ejemplo n.º 29
0
 public ISymbolNode GetFieldRvaData(FieldDesc field)
 {
     // Use the typical field definition in case this is an instantiated generic type
     field = field.GetTypicalFieldDefinition();
     throw new NotImplementedException();
 }
Ejemplo n.º 30
0
            protected internal override int CompareToImpl(FieldDesc other, TypeSystemComparer comparer)
            {
                var otherField = (InlineArrayField)other;

                return(comparer.CompareWithinClass(OwningType, otherField.OwningType));
            }
Ejemplo n.º 31
0
 public bool GetFieldDesc(string name, out int offset, out int tid)
 {
     FieldDesc fd = null;
     if(!fields.TryGetValue(name, out fd))
     {
         // loop over for search of desired property
         for(int i = 0; i < PropertyCount; i++)
         {
             string n = null;
             int _tid = 0;
             int _offset = 0;
             bool is_private = false;
             bool is_reference = false;
             GetProperty(i, ref n, ref _tid, ref is_private, ref _offset, ref is_reference);
             if(n == name)
             {
                 // if type is reference, denote it in type id
                 if(is_reference)
                     _tid = _tid | (int)asETypeIdFlags.asTYPEID_OBJHANDLE;
                 // memoize the result
                 fd = new FieldDesc(_offset, _tid);
                 fields[name] = fd;
                 break;
             }
         }
     }
     if(fd != null)
     {
         offset = fd.Offset;
         tid = fd.TypeId;
         return true;
     }
     else
     {
         offset = tid = 0;
         return false;
     }
 }
 public bool GeneratesMetadata(FieldDesc fieldDef)
 {
     return(_parent._typeDefinitionsGenerated.Contains((MetadataType)fieldDef.OwningType));
 }