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

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

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

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

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

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

                default:
                    Debug.Assert(false);
                    throw new BadImageFormatException();
            }
        }
 private RuntimeFatMethodParameterInfo(MethodBase member, MethodHandle methodHandle, int position, ParameterHandle parameterHandle, ReflectionDomain reflectionDomain, MetadataReader reader, Handle typeHandle, TypeContext typeContext)
     : base(member, position, reflectionDomain, reader, typeHandle, typeContext)
 {
     _methodHandle = methodHandle;
     _parameterHandle = parameterHandle;
     _parameter = parameterHandle.GetParameter(reader);
 }
Example #3
0
        public static TypeDefinitionHandle FindTestType(MetadataReader reader, Type type)
        {
            if (type.DeclaringType == null)
            {
                foreach (TypeDefinitionHandle handle in reader.TypeDefinitions)
                {
                    TypeDefinition definition = reader.GetTypeDefinition(handle);
                    if (reader.StringComparer.Equals(definition.Namespace, type.Namespace) &&
                        reader.StringComparer.Equals(definition.Name, type.Name))
                    {
                        return handle;
                    }
                }
            }
            else
            {
                TypeDefinitionHandle declaringHandle = FindTestType(reader, type.DeclaringType);
                TypeDefinition declaringDefinition = reader.GetTypeDefinition(declaringHandle);
                foreach (TypeDefinitionHandle handle in declaringDefinition.GetNestedTypes())
                {
                    TypeDefinition definition = reader.GetTypeDefinition(handle);
                    if (reader.StringComparer.Equals(definition.Name, type.Name))
                    {
                        return handle;
                    }
                }
            }

            Assert.True(false, "Cannot find test type:" + type);
            return default(TypeDefinitionHandle);
        }
        public static string GetFullName(this Handle handle, MetadataReader reader)
        {
            switch (handle.HandleType)
            {
                case HandleType.TypeDefinition:
                    return handle.ToTypeDefinitionHandle(reader).GetFullName(reader);
                case HandleType.TypeReference:
                    return handle.ToTypeReferenceHandle(reader).GetFullName(reader);

                case HandleType.NamespaceDefinition:
                    return handle.ToNamespaceDefinitionHandle(reader).GetFullName(reader);
                case HandleType.NamespaceReference:
                    return handle.ToNamespaceReferenceHandle(reader).GetFullName(reader);

                case HandleType.TypeSpecification:
                    return handle.ToTypeSpecificationHandle(reader).GetFullName(reader);
                case HandleType.TypeInstantiationSignature:
                    return handle.ToTypeInstantiationSignatureHandle(reader).GetFullName(reader);

                case HandleType.ArraySignature:
                    return handle.ToArraySignatureHandle(reader).GetFullName(reader);
                case HandleType.SZArraySignature:
                    return handle.ToSZArraySignatureHandle(reader).GetFullName(reader);

                case HandleType.PointerSignature:
                    return handle.ToPointerSignatureHandle(reader).GetFullName(reader);
                case HandleType.ByReferenceSignature:
                    return handle.ToByReferenceSignatureHandle(reader).GetFullName(reader);
            }
            return null;
        }
Example #5
0
 public CodeReader(Section section, MetadataReader reader, Dictionary<uint, DumpedMethod> dumpedMethods = null)
     : base(section.Data)
 {
     this.code_section = section;
     this.reader = reader;
     this.dumpedMethods = dumpedMethods;
 }
Example #6
0
		public CodeReader (MethodDefinition method, MetadataReader reader)
			: base (reader.image.Stream)
		{
			this.reader = reader;
			this.reader.context = method;
			this.Position = (int) reader.image.ResolveVirtualAddress ((uint) method.RVA);
		}
 internal RuntimeGenericParameterType(MetadataReader reader, GenericParameterHandle genericParameterHandle)
 {
     _reader = reader;
     _genericParameterHandle = genericParameterHandle;
     _genericParameter = _genericParameterHandle.GetGenericParameter(_reader);
     _position = _genericParameter.Number;
 }
 public static bool IsTypeDefRefOrSpecHandle(this Handle handle, MetadataReader reader)
 {
     HandleType handleType = handle.HandleType;
     return handleType == HandleType.TypeDefinition ||
         handleType == HandleType.TypeReference ||
         handleType == HandleType.TypeSpecification;
 }
 //wicky.patch.start: add support to read directly from bytes, contributed by HaRpy
 public CodeReader(MethodDefinition method, byte[] bytes):base(bytes)
 {
     this.method = method;
     this.reader = method.DeclaringType.Module.reader;
     this.code_section = null;  //code_section could be null for obfuscated assembly
     this.isReadFromBytes = true;
 }
        private static RuntimeAssemblyName CreateRuntimeAssemblyNameFromMetadata(
            MetadataReader reader,
            ConstantStringValueHandle name,
            ushort majorVersion,
            ushort minorVersion,
            ushort buildNumber,
            ushort revisionNumber,
            ConstantStringValueHandle culture,
            IEnumerable<byte> publicKeyOrToken,
            AssemblyFlags assemblyFlags)
        {
            AssemblyNameFlags assemblyNameFlags = AssemblyNameFlags.None;
            if (0 != (assemblyFlags & AssemblyFlags.PublicKey))
                assemblyNameFlags |= AssemblyNameFlags.PublicKey;
            if (0 != (assemblyFlags & AssemblyFlags.Retargetable))
                assemblyNameFlags |= AssemblyNameFlags.Retargetable;
            int contentType = ((int)assemblyFlags) & 0x00000E00;
            assemblyNameFlags |= (AssemblyNameFlags)contentType;

            ArrayBuilder<byte> keyOrTokenArrayBuilder = new ArrayBuilder<byte>();
            foreach (byte b in publicKeyOrToken)
                keyOrTokenArrayBuilder.Add(b);

            return new RuntimeAssemblyName(
                name.GetString(reader),
                new Version(majorVersion, minorVersion, buildNumber, revisionNumber),
                culture.GetStringOrNull(reader),
                assemblyNameFlags,
                keyOrTokenArrayBuilder.ToArray()
                );
        }
Example #11
0
 public static string GetFullName(this ArraySignatureHandle handle, MetadataReader reader)
 {
     ArraySignature array = handle.GetArraySignature(reader);
     var result = array.ElementType.GetFullName(reader);
     if (result == null) return null;
     return result + "[" + (new string(',', array.Rank - 1)) + "]";
 }
Example #12
0
        public static bool GetDefaultValueIfAny(MemberType memberType, MetadataReader reader, Handle constantHandle, Type declaredType, IEnumerable<CustomAttributeData> customAttributes, out Object defaultValue)
        {
            if (!(constantHandle.IsNull(reader)))
            {
                defaultValue = ParseMetadataConstant(reader, constantHandle);
                if (declaredType.GetTypeInfo().IsEnum)
                    defaultValue = Enum.ToObject(declaredType, defaultValue);
                return true;
            }

            if (memberType != MemberType.Property)  // the attributes in question cannot be applied to properties.
            {
                // Legacy: If there are multiple default value attribute, the desktop picks one at random (and so do we...)
                foreach (CustomAttributeData cad in customAttributes)
                {
                    Type attributeType = cad.AttributeType;
                    TypeInfo attributeTypeInfo = attributeType.GetTypeInfo();
                    if (attributeTypeInfo.IsSubclassOf(typeof(CustomConstantAttribute)))
                    {
                        CustomConstantAttribute customConstantAttribute = (CustomConstantAttribute)(cad.Instantiate());
                        defaultValue = customConstantAttribute.Value;
                        return true;
                    }
                    if (attributeType.Equals(typeof(DecimalConstantAttribute)))
                    {
                        DecimalConstantAttribute decimalConstantAttribute = (DecimalConstantAttribute)(cad.Instantiate());
                        defaultValue = decimalConstantAttribute.Value;
                        return true;
                    }
                }
            }

            defaultValue = null;
            return false;
        }
 public static bool StringOrNullEquals(this ConstantStringValueHandle handle, String valueOrNull, MetadataReader reader)
 {
     if (valueOrNull == null)
         return handle.IsNull(reader);
     if (handle.IsNull(reader))
         return false;
     return handle.StringEquals(valueOrNull, reader);
 }
 protected RuntimeMethodParameterInfo(MethodBase member, int position, ReflectionDomain reflectionDomain, MetadataReader reader, Handle typeHandle, TypeContext typeContext)
     : base(member, position)
 {
     _reflectionDomain = reflectionDomain;
     Reader = reader;
     _typeHandle = typeHandle;
     _typeContext = typeContext;
 }
Example #15
0
 //
 // Main routine to resolve a typeDef/Ref/Spec.
 //
 internal static RuntimeType Resolve(this ReflectionDomain reflectionDomain, MetadataReader reader, Handle typeDefRefOrSpec, TypeContext typeContext)
 {
     Exception exception = null;
     RuntimeType runtimeType = reflectionDomain.TryResolve(reader, typeDefRefOrSpec, typeContext, ref exception);
     if (runtimeType == null)
         throw exception;
     return runtimeType;
 }
Example #16
0
		public static MethodBody ReadMethodBody (MethodDefinition method, MetadataReader metadata)
		{
			var reader = new CodeReader (method, metadata);
			reader.body = new MethodBody (method);

			reader.ReadMethodBody ();

			return reader.body;
		}
Example #17
0
        public static string GetFullName(this TypeSpecificationHandle typeSpecHandle, MetadataReader reader)
        {
            var typeSpec = typeSpecHandle.GetTypeSpecification(reader);

            if (typeSpec.Signature.IsNull(reader))
                return null;

            return typeSpec.Signature.GetFullName(reader);
        }
Example #18
0
        private List<CustomAttributeHandle> GetCustomAttributes(MetadataReader reader, int token)
        {
            var attributes = new List<CustomAttributeHandle>();
            foreach (var caHandle in reader.GetCustomAttributes(new EntityHandle((uint)token)))
            {
                attributes.Add(caHandle);
            }

            return attributes;
        }
Example #19
0
        internal NamespaceChain(MetadataReader reader, NamespaceDefinitionHandle innerMostNamespaceHandle)
        {
            NamespaceDefinition currentNamespaceDefinition = innerMostNamespaceHandle.GetNamespaceDefinition(reader);
            ConstantStringValueHandle currentNameHandle = currentNamespaceDefinition.Name;
            Handle currentNamespaceHandle = innerMostNamespaceHandle.ToHandle(reader);
            LowLevelList<String> names = new LowLevelList<String>();
            for (; ;)
            {
                String name = currentNameHandle.GetStringOrNull(reader);
                names.Add(name);
                currentNamespaceHandle = currentNamespaceDefinition.ParentScopeOrNamespace;
                HandleType handleType = currentNamespaceHandle.HandleType;
                if (handleType == HandleType.ScopeDefinition)
                    break;
                if (handleType == HandleType.NamespaceDefinition)
                {
                    NamespaceDefinitionHandle nsHandle = currentNamespaceHandle.ToNamespaceDefinitionHandle(reader);
                    currentNamespaceDefinition = nsHandle.GetNamespaceDefinition(reader);
                    currentNameHandle = currentNamespaceDefinition.Name;
                    continue;
                }

                throw new BadImageFormatException(SR.Bif_InvalidMetadata);
            }

            DefiningScope = currentNamespaceHandle.ToScopeDefinitionHandle(reader);

            int count = names.Count;
            if (count == 0)
            {
                // Every namespace chain has to start with the root namespace.
                throw new BadImageFormatException();
            }
            else if (count == 1)
            {
                // The root namespace. For compat with the desktop, TypeInfo.NameSpaces returns null in this case.
                NameSpace = null;
            }
            else
            {
                // Namespace has at least one non-root component.
                StringBuilder sb = new StringBuilder();
                int idx = count - 1;
                while (idx-- != 0)
                {
                    String name = names[idx];
                    if (name == null)
                        throw new BadImageFormatException(); // null namespace fragment found in middle.
                    sb.Append(name);
                    if (idx != 0)
                        sb.Append('.');
                }
                NameSpace = sb.ToString();
            }
        }
 //
 // Creates the appropriate flavor of Invoker depending on the calling convention "shape" (static, instance or virtual.)
 //
 internal static MethodInvoker CreateMethodInvoker(MetadataReader reader, RuntimeTypeHandle declaringTypeHandle, MethodHandle methodHandle, MethodInvokeInfo methodInvokeInfo)
 {
     Method method = methodHandle.GetMethod(reader);
     MethodAttributes methodAttributes = method.Flags;
     if (0 != (methodAttributes & MethodAttributes.Static))
         return new StaticMethodInvoker(methodInvokeInfo);
     else if (methodInvokeInfo.VirtualResolveData != IntPtr.Zero)
         return new VirtualMethodInvoker(methodInvokeInfo, declaringTypeHandle);
     else
         return new InstanceMethodInvoker(methodInvokeInfo, declaringTypeHandle);
 }
        /// <summary>
        /// Locate reflection blob in a given module and construct its metadata reader.
        /// </summary>
        /// <param name="moduleHandle">Module handle to register</param>
        unsafe void CreateMetadataReader(IntPtr moduleHandle)
        {
            uint* pBlob;
            uint cbBlob;

            if (RuntimeAugments.FindBlob(moduleHandle, (int)ReflectionMapBlob.EmbeddedMetadata, (IntPtr)(&pBlob), (IntPtr)(&cbBlob)))
            {
                MetadataReader reader = new MetadataReader((IntPtr)pBlob, (int)cbBlob);
                _moduleToMetadataReader.Add(moduleHandle, reader);
            }
        }
Example #22
0
 internal static RuntimeType TryResolve(this ReflectionDomain reflectionDomain, MetadataReader reader, Handle typeDefRefOrSpec, TypeContext typeContext, ref Exception exception)
 {
     HandleType handleType = typeDefRefOrSpec.HandleType;
     if (handleType == HandleType.TypeDefinition)
         return reflectionDomain.ResolveTypeDefinition(reader, typeDefRefOrSpec.ToTypeDefinitionHandle(reader));
     else if (handleType == HandleType.TypeReference)
         return reflectionDomain.TryResolveTypeReference(reader, typeDefRefOrSpec.ToTypeReferenceHandle(reader), ref exception);
     else if (handleType == HandleType.TypeSpecification)
         return reflectionDomain.TryResolveTypeSignature(reader, typeDefRefOrSpec.ToTypeSpecificationHandle(reader), typeContext, ref exception);
     else
         throw new BadImageFormatException();  // Expected TypeRef, Def or Spec.
 }
        public NullableInstanceMethodInvoker(MetadataReader reader, MethodHandle methodHandle, RuntimeTypeHandle nullableTypeHandle, MethodInvokeInfo methodInvokeInfo)
        {
            _id = NullableMethodId.None;
            _nullableTypeHandle = nullableTypeHandle;
            Method method = methodHandle.GetMethod(reader);
            if (MethodAttributes.Public == (method.Flags & MethodAttributes.MemberAccessMask))
            {
                // Note: Since we control the definition of Nullable<>, we're not checking signatures here.
                String name = method.Name.GetConstantStringValue(reader).Value;
                switch (name)
                {
                    case "GetType":
                        _id = NullableMethodId.GetType;
                        break;

                    case "ToString":
                        _id = NullableMethodId.ToString;
                        break;

                    case "Equals":
                        _id = NullableMethodId.Equals;
                        break;

                    case "GetHashCode":
                        _id = NullableMethodId.GetHashCode;
                        break;

                    case ".ctor":
                        _id = NullableMethodId.Ctor;
                        break;

                    case "get_HasValue":
                        _id = NullableMethodId.get_HasValue;
                        break;

                    case "get_Value":
                        _id = NullableMethodId.get_Value;
                        break;

                    case "GetValueOrDefault":
                        IEnumerator<ParameterTypeSignatureHandle> parameters = method.Signature.GetMethodSignature(reader).Parameters.GetEnumerator();
                        if (parameters.MoveNext())
                            _id = NullableMethodId.GetValueOrDefault_1;
                        else
                            _id = NullableMethodId.GetValueOrDefault_0;
                        break;

                    default:
                        break;
                }
            }
        }
Example #24
0
        private static Object ParseMetadataConstant(MetadataReader reader, Handle handle)
        {
            switch (handle.HandleType)
            {
                case HandleType.ConstantBooleanValue:
                    return handle.ToConstantBooleanValueHandle(reader).GetConstantBooleanValue(reader).Value;

                case HandleType.ConstantStringValue:
                    return handle.ToConstantStringValueHandle(reader).GetConstantStringValue(reader).Value;

                case HandleType.ConstantCharValue:
                    return handle.ToConstantCharValueHandle(reader).GetConstantCharValue(reader).Value;

                case HandleType.ConstantByteValue:
                    return handle.ToConstantByteValueHandle(reader).GetConstantByteValue(reader).Value;

                case HandleType.ConstantSByteValue:
                    return handle.ToConstantSByteValueHandle(reader).GetConstantSByteValue(reader).Value;

                case HandleType.ConstantInt16Value:
                    return handle.ToConstantInt16ValueHandle(reader).GetConstantInt16Value(reader).Value;

                case HandleType.ConstantUInt16Value:
                    return handle.ToConstantUInt16ValueHandle(reader).GetConstantUInt16Value(reader).Value;

                case HandleType.ConstantInt32Value:
                    return handle.ToConstantInt32ValueHandle(reader).GetConstantInt32Value(reader).Value;

                case HandleType.ConstantUInt32Value:
                    return handle.ToConstantUInt32ValueHandle(reader).GetConstantUInt32Value(reader).Value;

                case HandleType.ConstantInt64Value:
                    return handle.ToConstantInt64ValueHandle(reader).GetConstantInt64Value(reader).Value;

                case HandleType.ConstantUInt64Value:
                    return handle.ToConstantUInt64ValueHandle(reader).GetConstantUInt64Value(reader).Value;

                case HandleType.ConstantSingleValue:
                    return handle.ToConstantSingleValueHandle(reader).GetConstantSingleValue(reader).Value;

                case HandleType.ConstantDoubleValue:
                    return handle.ToConstantDoubleValueHandle(reader).GetConstantDoubleValue(reader).Value;

                case HandleType.ConstantReferenceValue:
                    return null;

                default:
                    throw new BadImageFormatException();
            }
        }
 public static RuntimeAssemblyName ToRuntimeAssemblyName(this ScopeDefinitionHandle scopeDefinitionHandle, MetadataReader reader)
 {
     ScopeDefinition scopeDefinition = scopeDefinitionHandle.GetScopeDefinition(reader);
     return CreateRuntimeAssemblyNameFromMetadata(
         reader,
         scopeDefinition.Name,
         scopeDefinition.MajorVersion,
         scopeDefinition.MinorVersion,
         scopeDefinition.BuildNumber,
         scopeDefinition.RevisionNumber,
         scopeDefinition.Culture,
         scopeDefinition.PublicKey,
         scopeDefinition.Flags
         );
 }
Example #26
0
        public static bool CompareTypeReferenceAcrossModules(TypeReferenceHandle tr1, MetadataReader mr1, TypeReferenceHandle tr2, MetadataReader mr2)
        {
            TypeReference trData1 = mr1.GetTypeReference(tr1);
            TypeReference trData2 = mr2.GetTypeReference(tr2);
            if (!trData1.TypeName.StringEquals(trData2.TypeName.GetConstantStringValue(mr2).Value, mr1))
                return false;

            if (trData1.ParentNamespaceOrType.HandleType != trData2.ParentNamespaceOrType.HandleType)
                return false;

            if (trData1.ParentNamespaceOrType.HandleType == HandleType.TypeReference)
                return CompareTypeReferenceAcrossModules(trData1.ParentNamespaceOrType.ToTypeReferenceHandle(mr1), mr1, trData2.ParentNamespaceOrType.ToTypeReferenceHandle(mr2), mr2);

            return CompareNamespaceReferenceAcrossModules(trData1.ParentNamespaceOrType.ToNamespaceReferenceHandle(mr1), mr1, trData2.ParentNamespaceOrType.ToNamespaceReferenceHandle(mr2), mr2);
        }
        /// <summary>
        /// Construct a comparer between NativeFormat metadata methods and native layouts
        /// </summary>
        /// <param name="metadataReader">Metadata reader for the method declaring type</param>
        /// <param name="methodHandle">Handle of method to compare</param>
        public MethodSignatureComparer(
            MetadataReader metadataReader,
            MethodHandle methodHandle)
        {
            _metadataReader = metadataReader;
            _methodHandle = methodHandle;

            _method = methodHandle.GetMethod(metadataReader);

            _methodSignature = _method.Signature.GetMethodSignature(_metadataReader);
            _isGeneric = (_methodSignature.GenericParameterCount != 0);

            // Precalculate initial method attributes used in signature queries
            _isStatic = (_method.Flags & MethodAttributes.Static) != 0;
        }
        protected RuntimeInspectionOnlyNamedType(MetadataReader reader, TypeDefinitionHandle typeDefinitionHandle)
            : base()
        {
#if DEBUG
            if (!(this.InternalViolatesTypeIdentityRules))
            {
                RuntimeTypeHandle runtimeTypeHandle;
                if (ReflectionCoreExecution.ExecutionEnvironment.TryGetNamedTypeForMetadata(reader, typeDefinitionHandle, out runtimeTypeHandle))
                    Debug.Assert(false, "Type identity violation: You must use a RuntimeEENamedType to represent this type as RH has generated an EEType for it.");
            }
#endif
            _reader = reader;
            _typeDefinitionHandle = typeDefinitionHandle;
            _typeDefinition = _typeDefinitionHandle.GetTypeDefinition(_reader);
        }
Example #29
0
        private static int MapVirtualHandleRowId(MetadataReader reader, Handle handle)
        {
            switch (handle.Kind)
            {
                case HandleKind.AssemblyReference:
                    // pretend that virtual rows immediately follow real rows:
                    return reader.AssemblyRefTable.NumberOfNonVirtualRows + 1 + handle.RowId;

                case HandleKind.String:
                case HandleKind.Blob:
                    // We could precalculate offsets for virtual strings and blobs as we are creating them
                    // if we wanted to implement this.
                    throw new NotSupportedException(SR.CantGetOffsetForVirtualHeapHandle);

                default:
                    throw new ArgumentException(SR.InvalidHandle, "handle");
            }
        }
Example #30
0
        // 
        // This is a port of the desktop CLR's RuntimeType.FormatTypeName() routine. This routine is used by various Reflection ToString() methods
        // to display the name of a type. Do not use for any other purpose as it inherits some pretty quirky desktop behavior.
        //
        // The Project N version takes a raw metadata handle rather than a completed type so that it remains robust in the face of missing metadata.
        //
        public static String FormatTypeName(this Handle typeDefRefOrSpecHandle, MetadataReader reader, TypeContext typeContext, ReflectionDomain reflectionDomain)
        {
            try
            {
                // Though we wrap this in a try-catch as a failsafe, this code must still strive to avoid triggering MissingMetadata exceptions
                // (non-error exceptions are very annoying when debugging.)

                Exception exception = null;
                RuntimeType runtimeType = reflectionDomain.TryResolve(reader, typeDefRefOrSpecHandle, typeContext, ref exception);
                if (runtimeType == null)
                    return UnavailableType;

                // Because this runtimeType came from a successful TryResolve() call, it is safe to querying the TypeInfo's of the type and its component parts.
                // If we're wrong, we do have the safety net of a try-catch.
                return runtimeType.FormatTypeName();
            }
            catch (Exception)
            {
                return UnavailableType;
            }
        }