From 566b15e5af8835a7e0f75017d03dcf4957b5b2c6 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Tue, 28 May 2024 01:26:45 +0800 Subject: [PATCH 01/51] Implement IsSimpleCopy and CanAssignArrayType in managed code --- .../src/System/Array.CoreCLR.cs | 116 ++++++++++++++++-- .../Runtime/CompilerServices/CastHelpers.cs | 14 +++ .../RuntimeHelpers.CoreCLR.cs | 39 ++++++ .../CompilerServices/RuntimeHelpers.cs | 25 ++++ 4 files changed, 187 insertions(+), 7 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs index 74e0739848168..50989229ef8c3 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs @@ -89,8 +89,58 @@ private static unsafe void CopyImpl(Array sourceArray, int sourceIndex, Array de CopySlow(sourceArray, sourceIndex, destinationArray, destinationIndex, length); } - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern bool IsSimpleCopy(Array sourceArray, Array destinationArray); + private static unsafe bool IsSimpleCopy(Array sourceArray, Array destinationArray) + { + TypeHandle srcTH = RuntimeHelpers.GetMethodTable(sourceArray)->GetArrayElementTypeHandle(); + TypeHandle destTH = RuntimeHelpers.GetMethodTable(destinationArray)->GetArrayElementTypeHandle(); + if (TypeHandle.AreSameType(srcTH, destTH)) // This check kicks for different array kind or dimensions + return true; + + if (srcTH.IsValueType) + { + // Value class boxing + if (!destTH.IsValueType) + return false; + + CorElementType srcElType = sourceArray.GetCorElementTypeOfElementType(); + CorElementType destElType = destinationArray.GetCorElementTypeOfElementType(); + + // Copying primitives from one type to another + if (srcElType.IsPrimitiveType() && destElType.IsPrimitiveType()) + { + if (GetNormalizedIntegralArrayElementType(srcElType) == GetNormalizedIntegralArrayElementType(destElType)) + return true; + } + } + else + { + // Value class unboxing + if (destTH.IsValueType) + return false; + } + + return srcTH.CanCastTo(destTH); + } + + private static CorElementType GetNormalizedIntegralArrayElementType(CorElementType elementType) + { + Debug.Assert(elementType.IsPrimitiveType()); + + // Array Primitive types such as E_T_I4 and E_T_U4 are interchangeable + // Enums with interchangeable underlying types are interchangeable + // BOOL is NOT interchangeable with I1/U1, neither CHAR -- with I2/U2 + switch (elementType) + { + case CorElementType.ELEMENT_TYPE_U1: + case CorElementType.ELEMENT_TYPE_U2: + case CorElementType.ELEMENT_TYPE_U4: + case CorElementType.ELEMENT_TYPE_U8: + case CorElementType.ELEMENT_TYPE_U: + return elementType - 1; // normalize to signed type + default: + return elementType; + } + } // Reliability-wise, this method will either possibly corrupt your // instance & might fail when called from within a CER, or if the @@ -100,9 +150,7 @@ private static unsafe void CopySlow(Array sourceArray, int sourceIndex, Array de { Debug.Assert(sourceArray.Rank == destinationArray.Rank); - void* srcTH = RuntimeHelpers.GetMethodTable(sourceArray)->ElementType; - void* destTH = RuntimeHelpers.GetMethodTable(destinationArray)->ElementType; - AssignArrayEnum r = CanAssignArrayType(srcTH, destTH); + AssignArrayEnum r = CanAssignArrayType(sourceArray, destinationArray); if (r == AssignArrayEnum.AssignWrongType) ThrowHelper.ThrowArrayTypeMismatchException_CantAssignType(); @@ -144,8 +192,62 @@ private enum AssignArrayEnum AssignPrimitiveWiden, } - [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "Array_CanAssignArrayType")] - private static unsafe partial AssignArrayEnum CanAssignArrayType(void* srcTH, void* dstTH); + private static unsafe AssignArrayEnum CanAssignArrayType(Array sourceArray, Array destinationArray) + { + TypeHandle srcTH = RuntimeHelpers.GetMethodTable(sourceArray)->GetArrayElementTypeHandle(); + TypeHandle destTH = RuntimeHelpers.GetMethodTable(destinationArray)->GetArrayElementTypeHandle(); + Debug.Assert(!TypeHandle.AreSameType(srcTH, destTH)); // Handled by fast path + + // Value class boxing + if (srcTH.IsValueType && !destTH.IsValueType) + { + if (srcTH.CanCastTo(destTH)) + return AssignArrayEnum.AssignBoxValueClassOrPrimitive; + else + return AssignArrayEnum.AssignWrongType; + } + + // Value class unboxing. + if (!srcTH.IsValueType && destTH.IsValueType) + { + if (srcTH.CanCastTo(destTH)) + return AssignArrayEnum.AssignUnboxValueClass; + else if (destTH.CanCastTo(srcTH)) // V extends IV. Copying from IV to V, or Object to V. + return AssignArrayEnum.AssignUnboxValueClass; + else + return AssignArrayEnum.AssignWrongType; + } + + CorElementType srcElType = sourceArray.GetCorElementTypeOfElementType(); + CorElementType destElType = destinationArray.GetCorElementTypeOfElementType(); + + // Copying primitives from one type to another + if (srcElType.IsPrimitiveType() && destElType.IsPrimitiveType()) + { + Debug.Assert(srcElType != destElType); // Handled by fast path + if (RuntimeHelpers.CanPrimitiveWiden(srcElType, destElType)) + return AssignArrayEnum.AssignPrimitiveWiden; + else + return AssignArrayEnum.AssignWrongType; + } + + // dest Object extends src + Debug.Assert(!srcTH.CanCastTo(destTH)); // Handled by fast path + + // src Object extends dest + if (destTH.CanCastTo(srcTH)) + return AssignArrayEnum.AssignMustCast; + + // class X extends/implements src and implements dest. + if (!destTH.IsInterface && srcElType != CorElementType.ELEMENT_TYPE_VALUETYPE) + return AssignArrayEnum.AssignMustCast; + + // class X implements src and extends/implements dest + if (!srcTH.IsInterface && srcElType != CorElementType.ELEMENT_TYPE_VALUETYPE) + return AssignArrayEnum.AssignMustCast; + + return AssignArrayEnum.AssignWrongType; + } // Unboxes from an Object[] into a value class or primitive array. private static unsafe void CopyImplUnBoxEachElement(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/CastHelpers.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/CastHelpers.cs index 0c640dd1c2f0a..452b98e977149 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/CastHelpers.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/CastHelpers.cs @@ -25,6 +25,20 @@ internal static unsafe class CastHelpers [MethodImpl(MethodImplOptions.InternalCall)] private static extern void WriteBarrier(ref object? dst, object? obj); + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool CanCastTo_NoCacheLookup(void* fromTypeHnd, void* toTypeHnd); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static bool CanCastTo(void* fromTypeHnd, void* toTypeHnd) + { + CastResult result = CastCache.TryGet(s_table!, (nuint)fromTypeHnd, (nuint)toTypeHnd); + + if (result != CastResult.MaybeCast) + return result == CastResult.CanCast; + + return CanCastTo_NoCacheLookup(fromTypeHnd, toTypeHnd); + } + // IsInstanceOf test used for unusual cases (naked type parameters, variant generic types) // Unlike the IsInstanceOfInterface and IsInstanceOfClass functions, // this test must deal with all kinds of type tests diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs index 43ddbfecf006f..3d5773e9978f2 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs @@ -784,11 +784,50 @@ public bool IsTypeDesc return (MethodTable*)m_asTAddr; } + /// + /// Gets the pointer wrapped by the current instance. + /// + /// This is only safe to call if returned . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public TypeDesc* AsTypeDesc() + { + Debug.Assert(IsTypeDesc); + + return (TypeDesc*)((nint)m_asTAddr - 2); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static TypeHandle TypeHandleOf() { return new TypeHandle((void*)RuntimeTypeHandle.ToIntPtr(typeof(T).TypeHandle)); } + + public static bool AreSameType(TypeHandle left, TypeHandle right) => left.m_asTAddr == right.m_asTAddr; + + public bool CanCastTo(TypeHandle destTH) => CastHelpers.CanCastTo(m_asTAddr, destTH.m_asTAddr); + + public bool IsValueType + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + return IsTypeDesc + ? AsTypeDesc()->GetInternalCorElementType() == CorElementType.ELEMENT_TYPE_VALUETYPE + : AsMethodTable()->IsValueType; + } + } + + public bool IsInterface => !IsTypeDesc && AsMethodTable()->IsInterface; + } + + internal unsafe struct TypeDesc + { + private readonly int m_typeAndFlags; + + // This is the ELEMENT_TYPE* that would be used in the type sig for this type + // For enums this is the underlying type + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public CorElementType GetInternalCorElementType() => (CorElementType)(m_typeAndFlags & 0xFF); } // Helper structs used for tail calls via helper. diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs index 63471d9f91967..938cdeb566833 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; @@ -109,6 +110,30 @@ internal static bool IsPrimitiveType(this CorElementType et) // COR_ELEMENT_TYPE_I1,I2,I4,I8,U1,U2,U4,U8,R4,R8,I,U,CHAR,BOOLEAN => ((1 << (int)et) & 0b_0011_0000_0000_0011_1111_1111_1100) != 0; + private static ReadOnlySpan PrimitiveWidenTable => + [ + 0x00, // ELEMENT_TYPE_END + 0x00, // ELEMENT_TYPE_VOID + 0x0004, // ELEMENT_TYPE_BOOLEAN + 0x3F88, // ELEMENT_TYPE_CHAR (W = U2, CHAR, I4, U4, I8, U8, R4, R8) (U2 == Char) + 0x3550, // ELEMENT_TYPE_I1 (W = I1, I2, I4, I8, R4, R8) + 0x3FE8, // ELEMENT_TYPE_U1 (W = CHAR, U1, I2, U2, I4, U4, I8, U8, R4, R8) + 0x3540, // ELEMENT_TYPE_I2 (W = I2, I4, I8, R4, R8) + 0x3F88, // ELEMENT_TYPE_U2 (W = U2, CHAR, I4, U4, I8, U8, R4, R8) + 0x3500, // ELEMENT_TYPE_I4 (W = I4, I8, R4, R8) + 0x3E00, // ELEMENT_TYPE_U4 (W = U4, I8, R4, R8) + 0x3400, // ELEMENT_TYPE_I8 (W = I8, R4, R8) + 0x3800, // ELEMENT_TYPE_U8 (W = U8, R4, R8) + 0x3000, // ELEMENT_TYPE_R4 (W = R4, R8) + 0x2000, // ELEMENT_TYPE_R8 (W = R8) + ]; + + internal static bool CanPrimitiveWiden(CorElementType srcET, CorElementType dstET) + { + Debug.Assert(srcET.IsPrimitiveType() && dstET.IsPrimitiveType()); + return (PrimitiveWidenTable[(int)srcET] & (1 << (int)dstET)) != 0; + } + /// Provide a fast way to access constant data stored in a module as a ReadOnlySpan{T} /// A field handle that specifies the location of the data to be referred to by the ReadOnlySpan{T}. The Rva of the field must be aligned on a natural boundary of type T /// A ReadOnlySpan{T} of the data stored in the field From 8a592b9d7fbef2c387d91c7c3d2fc74cb7a7c997 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Tue, 28 May 2024 01:57:22 +0800 Subject: [PATCH 02/51] Fold IsSimpleCopy back to CanAssignArrayType --- .../src/System/Array.CoreCLR.cs | 61 ++++++------------- 1 file changed, 17 insertions(+), 44 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs index 50989229ef8c3..3f0733d09285b 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs @@ -62,7 +62,10 @@ private static unsafe void CopyImpl(Array sourceArray, int sourceIndex, Array de if ((uint)(destinationIndex + length) > destinationArray.NativeLength) throw new ArgumentException(SR.Arg_LongerThanDestArray, nameof(destinationArray)); - if (sourceArray.GetType() == destinationArray.GetType() || IsSimpleCopy(sourceArray, destinationArray)) + AssignArrayEnum assignType = AssignArrayEnum.AssignWrongType; + + if (sourceArray.GetType() == destinationArray.GetType() + || (assignType = CanAssignArrayType(sourceArray, destinationArray)) == AssignArrayEnum.AssignSimpleCopy) { MethodTable* pMT = RuntimeHelpers.GetMethodTable(sourceArray); @@ -86,40 +89,7 @@ private static unsafe void CopyImpl(Array sourceArray, int sourceIndex, Array de throw new ArrayTypeMismatchException(SR.ArrayTypeMismatch_ConstrainedCopy); // Rare - CopySlow(sourceArray, sourceIndex, destinationArray, destinationIndex, length); - } - - private static unsafe bool IsSimpleCopy(Array sourceArray, Array destinationArray) - { - TypeHandle srcTH = RuntimeHelpers.GetMethodTable(sourceArray)->GetArrayElementTypeHandle(); - TypeHandle destTH = RuntimeHelpers.GetMethodTable(destinationArray)->GetArrayElementTypeHandle(); - if (TypeHandle.AreSameType(srcTH, destTH)) // This check kicks for different array kind or dimensions - return true; - - if (srcTH.IsValueType) - { - // Value class boxing - if (!destTH.IsValueType) - return false; - - CorElementType srcElType = sourceArray.GetCorElementTypeOfElementType(); - CorElementType destElType = destinationArray.GetCorElementTypeOfElementType(); - - // Copying primitives from one type to another - if (srcElType.IsPrimitiveType() && destElType.IsPrimitiveType()) - { - if (GetNormalizedIntegralArrayElementType(srcElType) == GetNormalizedIntegralArrayElementType(destElType)) - return true; - } - } - else - { - // Value class unboxing - if (destTH.IsValueType) - return false; - } - - return srcTH.CanCastTo(destTH); + CopySlow(sourceArray, sourceIndex, destinationArray, destinationIndex, length, assignType); } private static CorElementType GetNormalizedIntegralArrayElementType(CorElementType elementType) @@ -146,18 +116,16 @@ private static CorElementType GetNormalizedIntegralArrayElementType(CorElementTy // instance & might fail when called from within a CER, or if the // reliable flag is true, it will either always succeed or always // throw an exception with no side effects. - private static unsafe void CopySlow(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length) + private static unsafe void CopySlow(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length, AssignArrayEnum assignType) { Debug.Assert(sourceArray.Rank == destinationArray.Rank); - AssignArrayEnum r = CanAssignArrayType(sourceArray, destinationArray); - - if (r == AssignArrayEnum.AssignWrongType) + if (assignType == AssignArrayEnum.AssignWrongType) ThrowHelper.ThrowArrayTypeMismatchException_CantAssignType(); if (length > 0) { - switch (r) + switch (assignType) { case AssignArrayEnum.AssignUnboxValueClass: CopyImplUnBoxEachElement(sourceArray, sourceIndex, destinationArray, destinationIndex, length); @@ -185,6 +153,7 @@ private static unsafe void CopySlow(Array sourceArray, int sourceIndex, Array de // Must match the definition in arraynative.cpp private enum AssignArrayEnum { + AssignSimpleCopy, AssignWrongType, AssignMustCast, AssignBoxValueClassOrPrimitive, @@ -196,7 +165,9 @@ private static unsafe AssignArrayEnum CanAssignArrayType(Array sourceArray, Arra { TypeHandle srcTH = RuntimeHelpers.GetMethodTable(sourceArray)->GetArrayElementTypeHandle(); TypeHandle destTH = RuntimeHelpers.GetMethodTable(destinationArray)->GetArrayElementTypeHandle(); - Debug.Assert(!TypeHandle.AreSameType(srcTH, destTH)); // Handled by fast path + + if (TypeHandle.AreSameType(srcTH, destTH)) // This check kicks for different array kind or dimensions + return AssignArrayEnum.AssignSimpleCopy; // Value class boxing if (srcTH.IsValueType && !destTH.IsValueType) @@ -224,15 +195,17 @@ private static unsafe AssignArrayEnum CanAssignArrayType(Array sourceArray, Arra // Copying primitives from one type to another if (srcElType.IsPrimitiveType() && destElType.IsPrimitiveType()) { - Debug.Assert(srcElType != destElType); // Handled by fast path - if (RuntimeHelpers.CanPrimitiveWiden(srcElType, destElType)) + if (GetNormalizedIntegralArrayElementType(srcElType) == GetNormalizedIntegralArrayElementType(destElType)) + return AssignArrayEnum.AssignSimpleCopy; + else if (RuntimeHelpers.CanPrimitiveWiden(srcElType, destElType)) return AssignArrayEnum.AssignPrimitiveWiden; else return AssignArrayEnum.AssignWrongType; } // dest Object extends src - Debug.Assert(!srcTH.CanCastTo(destTH)); // Handled by fast path + if (srcTH.CanCastTo(destTH)) + return AssignArrayEnum.AssignSimpleCopy; // src Object extends dest if (destTH.CanCastTo(srcTH)) From 0dce3d4e7edf68d1c2bf9058824c70ebb7dbf7b9 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Tue, 28 May 2024 01:59:02 +0800 Subject: [PATCH 03/51] Delete FCall and QCall definitions for copy --- .../classlibnative/bcltype/arraynative.cpp | 159 ------------------ .../classlibnative/bcltype/arraynative.h | 3 - src/coreclr/vm/ecalllist.h | 1 - src/coreclr/vm/qcallentrypoints.cpp | 1 - 4 files changed, 164 deletions(-) diff --git a/src/coreclr/classlibnative/bcltype/arraynative.cpp b/src/coreclr/classlibnative/bcltype/arraynative.cpp index 02ff0360ac4b7..00a1eeda6f6c7 100644 --- a/src/coreclr/classlibnative/bcltype/arraynative.cpp +++ b/src/coreclr/classlibnative/bcltype/arraynative.cpp @@ -47,165 +47,6 @@ extern "C" PCODE QCALLTYPE Array_GetElementConstructorEntrypoint(QCall::TypeHand return ctorEntrypoint; } - // Returns whether you can directly copy an array of srcType into destType. -FCIMPL2(FC_BOOL_RET, ArrayNative::IsSimpleCopy, ArrayBase* pSrc, ArrayBase* pDst) -{ - FCALL_CONTRACT; - - _ASSERTE(pSrc != NULL); - _ASSERTE(pDst != NULL); - - // This case is expected to be handled by the fast path - _ASSERTE(pSrc->GetMethodTable() != pDst->GetMethodTable()); - - TypeHandle srcTH = pSrc->GetMethodTable()->GetArrayElementTypeHandle(); - TypeHandle destTH = pDst->GetMethodTable()->GetArrayElementTypeHandle(); - if (srcTH == destTH) // This check kicks for different array kind or dimensions - FC_RETURN_BOOL(true); - - if (srcTH.IsValueType()) - { - // Value class boxing - if (!destTH.IsValueType()) - FC_RETURN_BOOL(false); - - const CorElementType srcElType = srcTH.GetVerifierCorElementType(); - const CorElementType destElType = destTH.GetVerifierCorElementType(); - _ASSERTE(srcElType < ELEMENT_TYPE_MAX); - _ASSERTE(destElType < ELEMENT_TYPE_MAX); - - // Copying primitives from one type to another - if (CorTypeInfo::IsPrimitiveType_NoThrow(srcElType) && CorTypeInfo::IsPrimitiveType_NoThrow(destElType)) - { - if (GetNormalizedIntegralArrayElementType(srcElType) == GetNormalizedIntegralArrayElementType(destElType)) - FC_RETURN_BOOL(true); - } - } - else - { - // Value class unboxing - if (destTH.IsValueType()) - FC_RETURN_BOOL(false); - } - - TypeHandle::CastResult r = srcTH.CanCastToCached(destTH); - if (r != TypeHandle::MaybeCast) - { - FC_RETURN_BOOL(r); - } - - struct - { - OBJECTREF src; - OBJECTREF dst; - } gc; - - gc.src = ObjectToOBJECTREF(pSrc); - gc.dst = ObjectToOBJECTREF(pDst); - - BOOL iRetVal = FALSE; - - HELPER_METHOD_FRAME_BEGIN_RET_PROTECT(gc); - iRetVal = srcTH.CanCastTo(destTH); - HELPER_METHOD_FRAME_END(); - - FC_RETURN_BOOL(iRetVal); -} -FCIMPLEND - - -// Return values for CanAssignArrayType -enum AssignArrayEnum -{ - AssignWrongType, - AssignMustCast, - AssignBoxValueClassOrPrimitive, - AssignUnboxValueClass, - AssignPrimitiveWiden, -}; - -// Returns an enum saying whether you can copy an array of srcType into destType. -static AssignArrayEnum CanAssignArrayType(const TypeHandle srcTH, const TypeHandle destTH) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - PRECONDITION(!srcTH.IsNull()); - PRECONDITION(!destTH.IsNull()); - } - CONTRACTL_END; - - _ASSERTE(srcTH != destTH); // Handled by fast path - - // Value class boxing - if (srcTH.IsValueType() && !destTH.IsValueType()) - { - if (srcTH.CanCastTo(destTH)) - return AssignBoxValueClassOrPrimitive; - else - return AssignWrongType; - } - - // Value class unboxing. - if (!srcTH.IsValueType() && destTH.IsValueType()) - { - if (srcTH.CanCastTo(destTH)) - return AssignUnboxValueClass; - else if (destTH.CanCastTo(srcTH)) // V extends IV. Copying from IV to V, or Object to V. - return AssignUnboxValueClass; - else - return AssignWrongType; - } - - const CorElementType srcElType = srcTH.GetVerifierCorElementType(); - const CorElementType destElType = destTH.GetVerifierCorElementType(); - _ASSERTE(srcElType < ELEMENT_TYPE_MAX); - _ASSERTE(destElType < ELEMENT_TYPE_MAX); - - // Copying primitives from one type to another - if (CorTypeInfo::IsPrimitiveType_NoThrow(srcElType) && CorTypeInfo::IsPrimitiveType_NoThrow(destElType)) - { - _ASSERTE(srcElType != destElType); // Handled by fast path - if (InvokeUtil::CanPrimitiveWiden(destElType, srcElType)) - return AssignPrimitiveWiden; - else - return AssignWrongType; - } - - // dest Object extends src - _ASSERTE(!srcTH.CanCastTo(destTH)); // Handled by fast path - - // src Object extends dest - if (destTH.CanCastTo(srcTH)) - return AssignMustCast; - - // class X extends/implements src and implements dest. - if (destTH.IsInterface() && srcElType != ELEMENT_TYPE_VALUETYPE) - return AssignMustCast; - - // class X implements src and extends/implements dest - if (srcTH.IsInterface() && destElType != ELEMENT_TYPE_VALUETYPE) - return AssignMustCast; - - return AssignWrongType; -} - -extern "C" int QCALLTYPE Array_CanAssignArrayType(void* srcTH, void* destTH) -{ - QCALL_CONTRACT; - - INT32 ret = 0; - - BEGIN_QCALL; - - ret = CanAssignArrayType(TypeHandle::FromPtr(srcTH), TypeHandle::FromPtr(destTH)); - - END_QCALL; - - return ret; -} - // // This is a GC safe variant of the memmove intrinsic. It sets the cards, and guarantees that the object references in the GC heap are diff --git a/src/coreclr/classlibnative/bcltype/arraynative.h b/src/coreclr/classlibnative/bcltype/arraynative.h index aeb264a9b28ce..c6d0473bb4f65 100644 --- a/src/coreclr/classlibnative/bcltype/arraynative.h +++ b/src/coreclr/classlibnative/bcltype/arraynative.h @@ -27,8 +27,6 @@ class ArrayNative public: static FCDECL1(INT32, GetCorElementTypeOfElementType, ArrayBase* arrayUNSAFE); - static FCDECL2(FC_BOOL_RET, IsSimpleCopy, ArrayBase* pSrc, ArrayBase* pDst); - // This set of methods will set a value in an array static FCDECL3(void, SetValue, ArrayBase* refThisUNSAFE, Object* objUNSAFE, INT_PTR flattenedIndex); @@ -43,6 +41,5 @@ class ArrayNative extern "C" void QCALLTYPE Array_CreateInstance(QCall::TypeHandle pTypeHnd, INT32 rank, INT32* pLengths, INT32* pBounds, BOOL createFromArrayType, QCall::ObjectHandleOnStack retArray); extern "C" PCODE QCALLTYPE Array_GetElementConstructorEntrypoint(QCall::TypeHandle pArrayTypeHnd); -extern "C" INT32 QCALLTYPE Array_CanAssignArrayType(void* srcTH, void* destTH); #endif // _ARRAYNATIVE_H_ diff --git a/src/coreclr/vm/ecalllist.h b/src/coreclr/vm/ecalllist.h index 98a38b8603419..05908387de320 100644 --- a/src/coreclr/vm/ecalllist.h +++ b/src/coreclr/vm/ecalllist.h @@ -361,7 +361,6 @@ FCFuncEnd() FCFuncStart(gArrayFuncs) FCFuncElement("GetCorElementTypeOfElementType", ArrayNative::GetCorElementTypeOfElementType) - FCFuncElement("IsSimpleCopy", ArrayNative::IsSimpleCopy) FCFuncElement("InternalSetValue", ArrayNative::SetValue) FCFuncEnd() diff --git a/src/coreclr/vm/qcallentrypoints.cpp b/src/coreclr/vm/qcallentrypoints.cpp index e038db62831d9..0f919f9ed9131 100644 --- a/src/coreclr/vm/qcallentrypoints.cpp +++ b/src/coreclr/vm/qcallentrypoints.cpp @@ -171,7 +171,6 @@ static const Entry s_QCall[] = DllImportEntry(MdUtf8String_EqualsCaseInsensitive) DllImportEntry(Array_CreateInstance) DllImportEntry(Array_GetElementConstructorEntrypoint) - DllImportEntry(Array_CanAssignArrayType) DllImportEntry(AssemblyName_InitializeAssemblySpec) DllImportEntry(AssemblyNative_GetFullName) DllImportEntry(AssemblyNative_GetLocation) From d29e5d84dac961d00a7cf4e494f883a1bf21c969 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Tue, 28 May 2024 12:29:49 +0800 Subject: [PATCH 04/51] Convert InternalSetValue to managed --- .../src/System/Array.CoreCLR.cs | 358 +++++++++++------- .../Runtime/CompilerServices/CastHelpers.cs | 2 +- .../RuntimeHelpers.CoreCLR.cs | 8 + .../classlibnative/bcltype/arraynative.cpp | 87 ----- .../classlibnative/bcltype/arraynative.h | 3 - src/coreclr/vm/ecalllist.h | 1 - .../src/System/ThrowHelper.cs | 9 + 7 files changed, 238 insertions(+), 230 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs index 3f0733d09285b..44bba8389c500 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs @@ -324,147 +324,152 @@ private static unsafe void CopyImplPrimitiveWiden(Array sourceArray, int sourceI ref byte srcElement = ref Unsafe.Add(ref srcData, (nuint)i * srcElSize); ref byte destElement = ref Unsafe.Add(ref data, (nuint)i * destElSize); - switch (srcElType) - { - case CorElementType.ELEMENT_TYPE_U1: - switch (destElType) - { - case CorElementType.ELEMENT_TYPE_CHAR: - case CorElementType.ELEMENT_TYPE_I2: - case CorElementType.ELEMENT_TYPE_U2: - Unsafe.As(ref destElement) = srcElement; break; - case CorElementType.ELEMENT_TYPE_I4: - case CorElementType.ELEMENT_TYPE_U4: - Unsafe.As(ref destElement) = srcElement; break; - case CorElementType.ELEMENT_TYPE_I8: - case CorElementType.ELEMENT_TYPE_U8: - Unsafe.As(ref destElement) = srcElement; break; - case CorElementType.ELEMENT_TYPE_R4: - Unsafe.As(ref destElement) = srcElement; break; - case CorElementType.ELEMENT_TYPE_R8: - Unsafe.As(ref destElement) = srcElement; break; - default: - Debug.Fail("Array.Copy from U1 to another type hit unsupported widening conversion"); break; - } - break; - - case CorElementType.ELEMENT_TYPE_I1: - switch (destElType) - { - case CorElementType.ELEMENT_TYPE_I2: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_I4: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_I8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R4: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - default: - Debug.Fail("Array.Copy from I1 to another type hit unsupported widening conversion"); break; - } - break; - - case CorElementType.ELEMENT_TYPE_U2: - case CorElementType.ELEMENT_TYPE_CHAR: - switch (destElType) - { - case CorElementType.ELEMENT_TYPE_U2: - case CorElementType.ELEMENT_TYPE_CHAR: - // U2 and CHAR are identical in conversion - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_I4: - case CorElementType.ELEMENT_TYPE_U4: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_I8: - case CorElementType.ELEMENT_TYPE_U8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R4: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - default: - Debug.Fail("Array.Copy from U2 to another type hit unsupported widening conversion"); break; - } - break; - - case CorElementType.ELEMENT_TYPE_I2: - switch (destElType) - { - case CorElementType.ELEMENT_TYPE_I4: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_I8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R4: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - default: - Debug.Fail("Array.Copy from I2 to another type hit unsupported widening conversion"); break; - } - break; - - case CorElementType.ELEMENT_TYPE_U4: - switch (destElType) - { - case CorElementType.ELEMENT_TYPE_I8: - case CorElementType.ELEMENT_TYPE_U8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R4: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - default: - Debug.Fail("Array.Copy from U4 to another type hit unsupported widening conversion"); break; - } - break; + PrimitiveWiden(ref srcElement, ref destElement, srcElType, destElType); + } + } - case CorElementType.ELEMENT_TYPE_I4: - switch (destElType) - { - case CorElementType.ELEMENT_TYPE_I8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R4: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - default: - Debug.Fail("Array.Copy from I4 to another type hit unsupported widening conversion"); break; - } - break; + private static void PrimitiveWiden(ref byte srcElement, ref byte destElement, CorElementType srcElType, CorElementType destElType) + { + switch (srcElType) + { + case CorElementType.ELEMENT_TYPE_U1: + switch (destElType) + { + case CorElementType.ELEMENT_TYPE_CHAR: + case CorElementType.ELEMENT_TYPE_I2: + case CorElementType.ELEMENT_TYPE_U2: + Unsafe.As(ref destElement) = srcElement; break; + case CorElementType.ELEMENT_TYPE_I4: + case CorElementType.ELEMENT_TYPE_U4: + Unsafe.As(ref destElement) = srcElement; break; + case CorElementType.ELEMENT_TYPE_I8: + case CorElementType.ELEMENT_TYPE_U8: + Unsafe.As(ref destElement) = srcElement; break; + case CorElementType.ELEMENT_TYPE_R4: + Unsafe.As(ref destElement) = srcElement; break; + case CorElementType.ELEMENT_TYPE_R8: + Unsafe.As(ref destElement) = srcElement; break; + default: + Debug.Fail("Array.Copy from U1 to another type hit unsupported widening conversion"); break; + } + break; + + case CorElementType.ELEMENT_TYPE_I1: + switch (destElType) + { + case CorElementType.ELEMENT_TYPE_I2: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_I4: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_I8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R4: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + default: + Debug.Fail("Array.Copy from I1 to another type hit unsupported widening conversion"); break; + } + break; - case CorElementType.ELEMENT_TYPE_U8: - switch (destElType) - { - case CorElementType.ELEMENT_TYPE_R4: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - default: - Debug.Fail("Array.Copy from U8 to another type hit unsupported widening conversion"); break; - } - break; + case CorElementType.ELEMENT_TYPE_U2: + case CorElementType.ELEMENT_TYPE_CHAR: + switch (destElType) + { + case CorElementType.ELEMENT_TYPE_U2: + case CorElementType.ELEMENT_TYPE_CHAR: + // U2 and CHAR are identical in conversion + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_I4: + case CorElementType.ELEMENT_TYPE_U4: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_I8: + case CorElementType.ELEMENT_TYPE_U8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R4: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + default: + Debug.Fail("Array.Copy from U2 to another type hit unsupported widening conversion"); break; + } + break; + + case CorElementType.ELEMENT_TYPE_I2: + switch (destElType) + { + case CorElementType.ELEMENT_TYPE_I4: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_I8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R4: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + default: + Debug.Fail("Array.Copy from I2 to another type hit unsupported widening conversion"); break; + } + break; - case CorElementType.ELEMENT_TYPE_I8: - switch (destElType) - { - case CorElementType.ELEMENT_TYPE_R4: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - default: - Debug.Fail("Array.Copy from I8 to another type hit unsupported widening conversion"); break; - } - break; + case CorElementType.ELEMENT_TYPE_U4: + switch (destElType) + { + case CorElementType.ELEMENT_TYPE_I8: + case CorElementType.ELEMENT_TYPE_U8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R4: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + default: + Debug.Fail("Array.Copy from U4 to another type hit unsupported widening conversion"); break; + } + break; + + case CorElementType.ELEMENT_TYPE_I4: + switch (destElType) + { + case CorElementType.ELEMENT_TYPE_I8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R4: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + default: + Debug.Fail("Array.Copy from I4 to another type hit unsupported widening conversion"); break; + } + break; - case CorElementType.ELEMENT_TYPE_R4: - Debug.Assert(destElType == CorElementType.ELEMENT_TYPE_R8); - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_U8: + switch (destElType) + { + case CorElementType.ELEMENT_TYPE_R4: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + default: + Debug.Fail("Array.Copy from U8 to another type hit unsupported widening conversion"); break; + } + break; + + case CorElementType.ELEMENT_TYPE_I8: + switch (destElType) + { + case CorElementType.ELEMENT_TYPE_R4: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + default: + Debug.Fail("Array.Copy from I8 to another type hit unsupported widening conversion"); break; + } + break; + + case CorElementType.ELEMENT_TYPE_R4: + Debug.Assert(destElType == CorElementType.ELEMENT_TYPE_R8); + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - default: - Debug.Fail("Fell through outer switch in PrimitiveWiden! Unknown primitive type for source array!"); break; - } + default: + Debug.Fail("Fell through outer switch in PrimitiveWiden! Unknown primitive type for source array!"); break; } } @@ -629,8 +634,85 @@ private unsafe nint GetFlattenedIndex(ReadOnlySpan indices) return result; } - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void InternalSetValue(object? value, nint flattenedIndex); + private unsafe void InternalSetValue(object? value, nint flattenedIndex) + { + MethodTable* pMethodTable = RuntimeHelpers.GetMethodTable(this); + + TypeHandle arrayElementTypeHandle = pMethodTable->GetArrayElementTypeHandle(); + + // Legacy behavior (this handles pointers and function pointers) + if (arrayElementTypeHandle.IsTypeDesc) + { + ThrowHelper.ThrowNotSupportedException(ExceptionResource.Arg_TypeNotSupported); + } + + Debug.Assert((nuint)flattenedIndex < NativeLength); + + ref byte arrayDataRef = ref MemoryMarshal.GetArrayDataReference(this); + + MethodTable* pElementMethodTable = arrayElementTypeHandle.AsMethodTable(); + + if (value == null) + { + // Null is the universal zero... + if (pElementMethodTable->IsValueType) + { + ref byte offsetDataRef = ref Unsafe.Add(ref arrayDataRef, flattenedIndex * pMethodTable->ComponentSize); + if (pElementMethodTable->ContainsGCPointers) + SpanHelpers.ClearWithReferences(ref Unsafe.As(ref offsetDataRef), pElementMethodTable->GetNumInstanceFieldBytes()); + else + SpanHelpers.ClearWithoutReferences(ref offsetDataRef, pElementMethodTable->GetNumInstanceFieldBytes()); + } + else + { + ref object? elementRef = ref Unsafe.As(ref arrayDataRef); + ref object? offsetElementRef = ref Unsafe.Add(ref elementRef, (nuint)flattenedIndex); + offsetElementRef = null; + } + } + else if (TypeHandle.AreSameType(arrayElementTypeHandle, TypeHandle.TypeHandleOf())) + { + // Everything is compatible with Object + ref object? elementRef = ref Unsafe.As(ref arrayDataRef); + ref object? offsetElementRef = ref Unsafe.Add(ref elementRef, (nuint)flattenedIndex); + offsetElementRef = value; + } + else if (!pElementMethodTable->IsValueType) + { + if (CastHelpers.IsInstanceOfAny(pElementMethodTable, value) == null) + { + ThrowHelper.ThrowInvalidCastException_StoreArrayElement(); + } + + ref object? elementRef = ref Unsafe.As(ref arrayDataRef); + ref object? offsetElementRef = ref Unsafe.Add(ref elementRef, (nuint)flattenedIndex); + offsetElementRef = value; + } + else + { + // value class or primitive type + + ref byte offsetDataRef = ref Unsafe.Add(ref arrayDataRef, flattenedIndex * pMethodTable->ComponentSize); + if (!RuntimeHelpers.TryUnboxInto(ref offsetDataRef, pElementMethodTable, value)) + { + // Allow enum -> primitive conversion, disallow primitive -> enum conversion + MethodTable* thSrc = RuntimeHelpers.GetMethodTable(value); + CorElementType srcType = thSrc->GetVerifierCorElementType(); + CorElementType targetType = pElementMethodTable->GetVerifierCorElementType(); + + if (!srcType.IsPrimitiveType() || !targetType.IsPrimitiveType() || !pElementMethodTable->IsTruePrimitive) + ThrowHelper.ThrowInvalidCastException_StoreArrayElement(); + + // Get a properly widened type + if (!RuntimeHelpers.CanPrimitiveWiden(srcType, targetType)) + ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_PrimitiveWiden); + + PrimitiveWiden(ref Unsafe.Unbox(value), ref offsetDataRef, srcType, targetType); + } + } + + GC.KeepAlive(this); // Keep the method table alive + } public int Length => checked((int)Unsafe.As(this).Length); diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/CastHelpers.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/CastHelpers.cs index 452b98e977149..a1a1a9c661e6e 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/CastHelpers.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/CastHelpers.cs @@ -43,7 +43,7 @@ internal static bool CanCastTo(void* fromTypeHnd, void* toTypeHnd) // Unlike the IsInstanceOfInterface and IsInstanceOfClass functions, // this test must deal with all kinds of type tests [DebuggerHidden] - private static object? IsInstanceOfAny(void* toTypeHnd, object? obj) + internal static object? IsInstanceOfAny(void* toTypeHnd, object? obj) { if (obj != null) { diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs index 3d5773e9978f2..e032de7b0620f 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs @@ -323,6 +323,9 @@ internal static unsafe bool ObjectHasComponentSize(object obj) [MethodImpl(MethodImplOptions.InternalCall)] internal static extern unsafe void Unbox_Nullable(ref byte destination, MethodTable* toTypeHnd, object? obj); + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern unsafe bool TryUnboxInto(ref byte destination, MethodTable* toTypeHnd, object obj); + // Given an object reference, returns its MethodTable*. // // WARNING: The caller has to ensure that MethodTable* does not get unloaded. The most robust way @@ -686,6 +689,8 @@ public int MultiDimensionalArrayRank // Warning! UNLIKE the similarly named Reflection api, this method also returns "true" for Enums. public bool IsPrimitive => (Flags & enum_flag_Category_Mask) is enum_flag_Category_PrimitiveValueType or enum_flag_Category_TruePrimitive; + public bool IsTruePrimitive => (Flags & enum_flag_Category_Mask) is enum_flag_Category_TruePrimitive; + public bool HasInstantiation => (Flags & enum_flag_HasComponentSize) == 0 && (Flags & enum_flag_GenericsMask) != enum_flag_GenericsMask_NonGeneric; public bool IsGenericTypeDefinition => (Flags & (enum_flag_HasComponentSize | enum_flag_GenericsMask)) == enum_flag_GenericsMask_TypicalInst; @@ -715,6 +720,9 @@ public TypeHandle GetArrayElementTypeHandle() [MethodImpl(MethodImplOptions.InternalCall)] public extern uint GetNumInstanceFieldBytes(); + + [MethodImpl(MethodImplOptions.InternalCall)] + public extern CorElementType GetVerifierCorElementType(); } // Subset of src\vm\methodtable.h diff --git a/src/coreclr/classlibnative/bcltype/arraynative.cpp b/src/coreclr/classlibnative/bcltype/arraynative.cpp index 00a1eeda6f6c7..a53b68e064fa8 100644 --- a/src/coreclr/classlibnative/bcltype/arraynative.cpp +++ b/src/coreclr/classlibnative/bcltype/arraynative.cpp @@ -207,93 +207,6 @@ Done: ; END_QCALL; } -FCIMPL3(void, ArrayNative::SetValue, ArrayBase* refThisUNSAFE, Object* objUNSAFE, INT_PTR flattenedIndex) -{ - FCALL_CONTRACT; - - BASEARRAYREF refThis(refThisUNSAFE); - OBJECTREF obj(objUNSAFE); - - TypeHandle arrayElementType = refThis->GetArrayElementTypeHandle(); - - // Legacy behavior (this handles pointers and function pointers) - if (arrayElementType.IsTypeDesc()) - { - FCThrowResVoid(kNotSupportedException, W("NotSupported_Type")); - } - - _ASSERTE((SIZE_T)flattenedIndex < refThis->GetNumComponents()); - - MethodTable* pElementTypeMT = arrayElementType.GetMethodTable(); - PREFIX_ASSUME(NULL != pElementTypeMT); - - void* pData = refThis->GetDataPtr() + flattenedIndex * refThis->GetComponentSize(); - - if (obj == NULL) - { - // Null is the universal zero... - if (pElementTypeMT->IsValueType()) - InitValueClass(pData,pElementTypeMT); - else - ClearObjectReference((OBJECTREF*)pData); - } - else - if (arrayElementType == TypeHandle(g_pObjectClass)) - { - // Everything is compatible with Object - SetObjectReference((OBJECTREF*)pData,(OBJECTREF)obj); - } - else - if (!pElementTypeMT->IsValueType()) - { - if (ObjIsInstanceOfCached(OBJECTREFToObject(obj), arrayElementType) != TypeHandle::CanCast) - { - HELPER_METHOD_FRAME_BEGIN_2(refThis, obj); - - if (!ObjIsInstanceOf(OBJECTREFToObject(obj), arrayElementType)) - COMPlusThrow(kInvalidCastException,W("InvalidCast_StoreArrayElement")); - - HELPER_METHOD_FRAME_END(); - - // Refresh pData in case GC moved objects around - pData = refThis->GetDataPtr() + flattenedIndex * refThis->GetComponentSize(); - } - - SetObjectReference((OBJECTREF*)pData,obj); - } - else - { - // value class or primitive type - - if (!pElementTypeMT->UnBoxInto(pData, obj)) - { - HELPER_METHOD_FRAME_BEGIN_2(refThis, obj); - - ARG_SLOT value = 0; - - // Allow enum -> primitive conversion, disallow primitive -> enum conversion - TypeHandle thSrc = obj->GetTypeHandle(); - CorElementType srcType = thSrc.GetVerifierCorElementType(); - CorElementType targetType = arrayElementType.GetSignatureCorElementType(); - - if (!InvokeUtil::IsPrimitiveType(srcType) || !InvokeUtil::IsPrimitiveType(targetType)) - COMPlusThrow(kInvalidCastException, W("InvalidCast_StoreArrayElement")); - - // Get a properly widened type - InvokeUtil::CreatePrimitiveValue(targetType,srcType,obj,&value); - - // Refresh pData in case GC moved objects around - pData = refThis->GetDataPtr() + flattenedIndex * refThis->GetComponentSize(); - - UINT cbSize = CorTypeInfo::Size(targetType); - memcpyNoGCRefs(pData, ArgSlotEndiannessFixup(&value, cbSize), cbSize); - - HELPER_METHOD_FRAME_END(); - } - } -} -FCIMPLEND - // This method will initialize an array from a TypeHandle to a field. FCIMPL2_IV(void, ArrayNative::InitializeArray, ArrayBase* pArrayRef, FCALLRuntimeFieldHandle structField) diff --git a/src/coreclr/classlibnative/bcltype/arraynative.h b/src/coreclr/classlibnative/bcltype/arraynative.h index c6d0473bb4f65..f5901311463d3 100644 --- a/src/coreclr/classlibnative/bcltype/arraynative.h +++ b/src/coreclr/classlibnative/bcltype/arraynative.h @@ -27,9 +27,6 @@ class ArrayNative public: static FCDECL1(INT32, GetCorElementTypeOfElementType, ArrayBase* arrayUNSAFE); - // This set of methods will set a value in an array - static FCDECL3(void, SetValue, ArrayBase* refThisUNSAFE, Object* objUNSAFE, INT_PTR flattenedIndex); - // This method will initialize an array from a TypeHandle // to a field. static FCDECL2_IV(void, InitializeArray, ArrayBase* vArrayRef, FCALLRuntimeFieldHandle structField); diff --git a/src/coreclr/vm/ecalllist.h b/src/coreclr/vm/ecalllist.h index 05908387de320..82f807a012e2b 100644 --- a/src/coreclr/vm/ecalllist.h +++ b/src/coreclr/vm/ecalllist.h @@ -361,7 +361,6 @@ FCFuncEnd() FCFuncStart(gArrayFuncs) FCFuncElement("GetCorElementTypeOfElementType", ArrayNative::GetCorElementTypeOfElementType) - FCFuncElement("InternalSetValue", ArrayNative::SetValue) FCFuncEnd() FCFuncStart(gBufferFuncs) diff --git a/src/libraries/System.Private.CoreLib/src/System/ThrowHelper.cs b/src/libraries/System.Private.CoreLib/src/System/ThrowHelper.cs index eb9b5b7eb0261..f49c16c51ef42 100644 --- a/src/libraries/System.Private.CoreLib/src/System/ThrowHelper.cs +++ b/src/libraries/System.Private.CoreLib/src/System/ThrowHelper.cs @@ -83,6 +83,12 @@ internal static void ThrowInvalidCastException_DownCastArrayElement() throw new InvalidCastException(SR.InvalidCast_DownCastArrayElement); } + [DoesNotReturn] + internal static void ThrowInvalidCastException_StoreArrayElement() + { + throw new InvalidCastException(SR.InvalidCast_StoreArrayElement); + } + [DoesNotReturn] internal static void ThrowInvalidTypeWithPointersNotSupported(Type targetType) { @@ -1244,6 +1250,8 @@ private static string GetResourceString(ExceptionResource resource) return SR.Format_ExpectedAsciiDigit; case ExceptionResource.Argument_HasToBeArrayClass: return SR.Argument_HasToBeArrayClass; + case ExceptionResource.Arg_PrimitiveWiden: + return SR.Arg_PrimWiden; default: Debug.Fail("The enum value is not defined, please check the ExceptionResource Enum."); return ""; @@ -1440,5 +1448,6 @@ internal enum ExceptionResource Format_UnclosedFormatItem, Format_ExpectedAsciiDigit, Argument_HasToBeArrayClass, + Arg_PrimitiveWiden, } } From 5dd0e3c8a4693092095f16115a5aa7cdcf74bbc7 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Tue, 28 May 2024 12:53:09 +0800 Subject: [PATCH 05/51] Setup FCalls --- .../Runtime/CompilerServices/CastHelpers.cs | 14 -------------- .../CompilerServices/RuntimeHelpers.CoreCLR.cs | 17 +++++++++++++++-- src/coreclr/vm/comutilnative.cpp | 14 ++++++++++++++ src/coreclr/vm/comutilnative.h | 2 ++ src/coreclr/vm/ecalllist.h | 3 +++ 5 files changed, 34 insertions(+), 16 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/CastHelpers.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/CastHelpers.cs index a1a1a9c661e6e..14c8a959cda5b 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/CastHelpers.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/CastHelpers.cs @@ -25,20 +25,6 @@ internal static unsafe class CastHelpers [MethodImpl(MethodImplOptions.InternalCall)] private static extern void WriteBarrier(ref object? dst, object? obj); - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern bool CanCastTo_NoCacheLookup(void* fromTypeHnd, void* toTypeHnd); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal static bool CanCastTo(void* fromTypeHnd, void* toTypeHnd) - { - CastResult result = CastCache.TryGet(s_table!, (nuint)fromTypeHnd, (nuint)toTypeHnd); - - if (result != CastResult.MaybeCast) - return result == CastResult.CanCast; - - return CanCastTo_NoCacheLookup(fromTypeHnd, toTypeHnd); - } - // IsInstanceOf test used for unusual cases (naked type parameters, variant generic types) // Unlike the IsInstanceOfInterface and IsInstanceOfClass functions, // this test must deal with all kinds of type tests diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs index e032de7b0620f..b18bb96059579 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs @@ -723,6 +723,10 @@ public TypeHandle GetArrayElementTypeHandle() [MethodImpl(MethodImplOptions.InternalCall)] public extern CorElementType GetVerifierCorElementType(); + + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool CanCastTo_NoCacheLookup(void* fromTypeHnd, void* toTypeHnd); + } // Subset of src\vm\methodtable.h @@ -750,7 +754,7 @@ public bool CanCompareBitsOrUseFastGetHashCode /// /// A type handle, which can wrap either a pointer to a TypeDesc or to a . /// - internal unsafe struct TypeHandle + internal readonly unsafe struct TypeHandle { // Subset of src\vm\typehandle.h @@ -812,7 +816,16 @@ public static TypeHandle TypeHandleOf() public static bool AreSameType(TypeHandle left, TypeHandle right) => left.m_asTAddr == right.m_asTAddr; - public bool CanCastTo(TypeHandle destTH) => CastHelpers.CanCastTo(m_asTAddr, destTH.m_asTAddr); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool CanCastTo(TypeHandle destTH) + { + CastResult result = CastCache.TryGet(CastHelpers.s_table!, (nuint)m_asTAddr, (nuint)destTH.m_asTAddr); + + if (result != CastResult.MaybeCast) + return result == CastResult.CanCast; + + return MethodTable.CanCastTo_NoCacheLookup(m_asTAddr, destTH.m_asTAddr); + } public bool IsValueType { diff --git a/src/coreclr/vm/comutilnative.cpp b/src/coreclr/vm/comutilnative.cpp index a3c9d0a848cdf..f1c3209c86a51 100644 --- a/src/coreclr/vm/comutilnative.cpp +++ b/src/coreclr/vm/comutilnative.cpp @@ -1787,6 +1787,20 @@ FCIMPL1(UINT32, MethodTableNative::GetNumInstanceFieldBytes, MethodTable* mt) } FCIMPLEND +FCIMPL1(CorElementType, MethodTableNative::GetVerifierCorElementType, MethodTable* mt) +{ + FCALL_CONTRACT; + return mt->GetVerifierCorElementType(); +} +FCIMPLEND + +FCIMPL2(FC_BOOL_RET, MethodTableNative::CanCastTo, void* fromType, void* toType) +{ + FCALL_CONTRACT; + FC_RETURN_BOOL(TypeHandle::FromPtr(fromType).CanCastTo(TypeHandle::FromPtr(toType))); +} +FCIMPLEND + extern "C" BOOL QCALLTYPE MethodTable_AreTypesEquivalent(MethodTable* mta, MethodTable* mtb) { QCALL_CONTRACT; diff --git a/src/coreclr/vm/comutilnative.h b/src/coreclr/vm/comutilnative.h index 3e64207564c84..91c0a4b5815d9 100644 --- a/src/coreclr/vm/comutilnative.h +++ b/src/coreclr/vm/comutilnative.h @@ -244,6 +244,8 @@ extern "C" void QCALLTYPE Interlocked_MemoryBarrierProcessWide(); class MethodTableNative { public: static FCDECL1(UINT32, GetNumInstanceFieldBytes, MethodTable* mt); + static FCDECL1(CorElementType, GetVerifierCorElementType, MethodTable* mt); + static FCDECL2(FC_BOOL_RET, CanCastTo, MethodTable* fromType, MethodTable* toType); }; extern "C" BOOL QCALLTYPE MethodTable_AreTypesEquivalent(MethodTable* mta, MethodTable* mtb); diff --git a/src/coreclr/vm/ecalllist.h b/src/coreclr/vm/ecalllist.h index 82f807a012e2b..ca928c2f09635 100644 --- a/src/coreclr/vm/ecalllist.h +++ b/src/coreclr/vm/ecalllist.h @@ -353,6 +353,7 @@ FCFuncEnd() #endif // FEATURE_COMINTEROP FCFuncStart(gCastHelpers) + FCFuncElement("CanCastTo_NoCacheLookup", ::IsInstanceOfAny_NoCacheLookup) FCFuncElement("IsInstanceOfAny_NoCacheLookup", ::IsInstanceOfAny_NoCacheLookup) FCFuncElement("ChkCastAny_NoCacheLookup", ::ChkCastAny_NoCacheLookup) FCFuncElement("Unbox_Helper", ::Unbox_Helper) @@ -454,6 +455,8 @@ FCFuncEnd() FCFuncStart(gMethodTableFuncs) FCFuncElement("GetNumInstanceFieldBytes", MethodTableNative::GetNumInstanceFieldBytes) + FCFuncElement("GetVerifierCorElementType", MethodTableNative::GetVerifierCorElementType) + FCFuncElement("CanCastTo_NoCacheLookup", MethodTableNative::CanCastTo) FCFuncEnd() FCFuncStart(gStubHelperFuncs) From 527021c76290a1ba111f2fc2c5a8631185f6248d Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Tue, 28 May 2024 13:13:03 +0800 Subject: [PATCH 06/51] Remove FCall for GetCorElementTypeOfElementType --- .../src/System/Array.CoreCLR.cs | 13 +++++++++---- .../CompilerServices/RuntimeHelpers.CoreCLR.cs | 6 +++++- src/coreclr/classlibnative/bcltype/arraynative.cpp | 11 ----------- src/coreclr/classlibnative/bcltype/arraynative.h | 2 -- src/coreclr/vm/ecalllist.h | 5 ----- 5 files changed, 14 insertions(+), 23 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs index 44bba8389c500..8f548951eb913 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs @@ -189,8 +189,8 @@ private static unsafe AssignArrayEnum CanAssignArrayType(Array sourceArray, Arra return AssignArrayEnum.AssignWrongType; } - CorElementType srcElType = sourceArray.GetCorElementTypeOfElementType(); - CorElementType destElType = destinationArray.GetCorElementTypeOfElementType(); + CorElementType srcElType = srcTH.GetVerifierCorElementType(); + CorElementType destElType = destTH.GetVerifierCorElementType(); // Copying primitives from one type to another if (srcElType.IsPrimitiveType() && destElType.IsPrimitiveType()) @@ -770,8 +770,13 @@ public unsafe int GetLowerBound(int dimension) return Unsafe.Add(ref RuntimeHelpers.GetMultiDimensionalArrayBounds(this), rank + dimension); } - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern CorElementType GetCorElementTypeOfElementType(); + internal unsafe CorElementType GetCorElementTypeOfElementType() + { + MethodTable* pMT = RuntimeHelpers.GetMethodTable(this); + CorElementType et = pMT->GetArrayElementTypeHandle().GetVerifierCorElementType(); + GC.KeepAlive(this); + return et; + } private unsafe bool IsValueOfElementType(object value) { diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs index b18bb96059579..58276a9a11de2 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs @@ -752,7 +752,7 @@ public bool CanCompareBitsOrUseFastGetHashCode } /// - /// A type handle, which can wrap either a pointer to a TypeDesc or to a . + /// A type handle, which can wrap either a pointer to a or to a . /// internal readonly unsafe struct TypeHandle { @@ -839,6 +839,10 @@ public bool IsValueType } public bool IsInterface => !IsTypeDesc && AsMethodTable()->IsInterface; + + public CorElementType GetVerifierCorElementType() => IsTypeDesc + ? AsTypeDesc()->GetInternalCorElementType() + : AsMethodTable()->GetVerifierCorElementType(); } internal unsafe struct TypeDesc diff --git a/src/coreclr/classlibnative/bcltype/arraynative.cpp b/src/coreclr/classlibnative/bcltype/arraynative.cpp index a53b68e064fa8..aa675eb29633a 100644 --- a/src/coreclr/classlibnative/bcltype/arraynative.cpp +++ b/src/coreclr/classlibnative/bcltype/arraynative.cpp @@ -17,17 +17,6 @@ #include "arraynative.inl" -// Returns a bool to indicate if the array is of primitive types or not. -FCIMPL1(INT32, ArrayNative::GetCorElementTypeOfElementType, ArrayBase* arrayUNSAFE) -{ - FCALL_CONTRACT; - - _ASSERTE(arrayUNSAFE != NULL); - - return arrayUNSAFE->GetArrayElementTypeHandle().GetVerifierCorElementType(); -} -FCIMPLEND - extern "C" PCODE QCALLTYPE Array_GetElementConstructorEntrypoint(QCall::TypeHandle pArrayTypeHnd) { QCALL_CONTRACT; diff --git a/src/coreclr/classlibnative/bcltype/arraynative.h b/src/coreclr/classlibnative/bcltype/arraynative.h index f5901311463d3..6f130c2215b40 100644 --- a/src/coreclr/classlibnative/bcltype/arraynative.h +++ b/src/coreclr/classlibnative/bcltype/arraynative.h @@ -25,8 +25,6 @@ struct FCALLRuntimeFieldHandle class ArrayNative { public: - static FCDECL1(INT32, GetCorElementTypeOfElementType, ArrayBase* arrayUNSAFE); - // This method will initialize an array from a TypeHandle // to a field. static FCDECL2_IV(void, InitializeArray, ArrayBase* vArrayRef, FCALLRuntimeFieldHandle structField); diff --git a/src/coreclr/vm/ecalllist.h b/src/coreclr/vm/ecalllist.h index ca928c2f09635..8014210f110bc 100644 --- a/src/coreclr/vm/ecalllist.h +++ b/src/coreclr/vm/ecalllist.h @@ -360,10 +360,6 @@ FCFuncStart(gCastHelpers) FCFuncElement("WriteBarrier", ::WriteBarrier_Helper) FCFuncEnd() -FCFuncStart(gArrayFuncs) - FCFuncElement("GetCorElementTypeOfElementType", ArrayNative::GetCorElementTypeOfElementType) -FCFuncEnd() - FCFuncStart(gBufferFuncs) FCFuncElement("__BulkMoveWithWriteBarrier", Buffer::BulkMoveWithWriteBarrier) FCFuncEnd() @@ -539,7 +535,6 @@ FCFuncEnd() // Note these have to remain sorted by name:namespace pair (Assert will wack you if you don't) // The sorting is case-sensitive -FCClassElement("Array", "System", gArrayFuncs) FCClassElement("AssemblyLoadContext", "System.Runtime.Loader", gAssemblyLoadContextFuncs) FCClassElement("Buffer", "System", gBufferFuncs) FCClassElement("CastHelpers", "System.Runtime.CompilerServices", gCastHelpers) From e7d843a0e00447858134db1661c53de957d25e10 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Tue, 28 May 2024 13:31:30 +0800 Subject: [PATCH 07/51] Complete TryUnBox --- .../src/System/Array.CoreCLR.cs | 19 +++++++++++++++++-- .../RuntimeHelpers.CoreCLR.cs | 3 --- src/coreclr/vm/ecalllist.h | 1 - 3 files changed, 17 insertions(+), 6 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs index 8f548951eb913..8d165315e9e2b 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs @@ -693,7 +693,22 @@ private unsafe void InternalSetValue(object? value, nint flattenedIndex) // value class or primitive type ref byte offsetDataRef = ref Unsafe.Add(ref arrayDataRef, flattenedIndex * pMethodTable->ComponentSize); - if (!RuntimeHelpers.TryUnboxInto(ref offsetDataRef, pElementMethodTable, value)) + if (CastHelpers.IsInstanceOfAny(pElementMethodTable, value) != null) + { + if (pElementMethodTable->IsNullable) + { + RuntimeHelpers.Unbox_Nullable(ref offsetDataRef, pElementMethodTable, value); + } + else if (pElementMethodTable->ContainsGCPointers) + { + Buffer.BulkMoveWithWriteBarrier(ref offsetDataRef, ref value.GetRawData(), pElementMethodTable->GetNumInstanceFieldBytes()); + } + else + { + SpanHelpers.Memmove(ref offsetDataRef, ref value.GetRawData(), pElementMethodTable->GetNumInstanceFieldBytes()); + } + } + else { // Allow enum -> primitive conversion, disallow primitive -> enum conversion MethodTable* thSrc = RuntimeHelpers.GetMethodTable(value); @@ -707,7 +722,7 @@ private unsafe void InternalSetValue(object? value, nint flattenedIndex) if (!RuntimeHelpers.CanPrimitiveWiden(srcType, targetType)) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_PrimitiveWiden); - PrimitiveWiden(ref Unsafe.Unbox(value), ref offsetDataRef, srcType, targetType); + PrimitiveWiden(ref value.GetRawData(), ref offsetDataRef, srcType, targetType); } } diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs index 58276a9a11de2..921af0d7967ae 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs @@ -323,9 +323,6 @@ internal static unsafe bool ObjectHasComponentSize(object obj) [MethodImpl(MethodImplOptions.InternalCall)] internal static extern unsafe void Unbox_Nullable(ref byte destination, MethodTable* toTypeHnd, object? obj); - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern unsafe bool TryUnboxInto(ref byte destination, MethodTable* toTypeHnd, object obj); - // Given an object reference, returns its MethodTable*. // // WARNING: The caller has to ensure that MethodTable* does not get unloaded. The most robust way diff --git a/src/coreclr/vm/ecalllist.h b/src/coreclr/vm/ecalllist.h index 8014210f110bc..7a18572cc46a8 100644 --- a/src/coreclr/vm/ecalllist.h +++ b/src/coreclr/vm/ecalllist.h @@ -353,7 +353,6 @@ FCFuncEnd() #endif // FEATURE_COMINTEROP FCFuncStart(gCastHelpers) - FCFuncElement("CanCastTo_NoCacheLookup", ::IsInstanceOfAny_NoCacheLookup) FCFuncElement("IsInstanceOfAny_NoCacheLookup", ::IsInstanceOfAny_NoCacheLookup) FCFuncElement("ChkCastAny_NoCacheLookup", ::ChkCastAny_NoCacheLookup) FCFuncElement("Unbox_Helper", ::Unbox_Helper) From 2bb5fe78f1d1ab73237ab33c73116b08b3390bce Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Tue, 28 May 2024 16:01:38 +0800 Subject: [PATCH 08/51] Fix FCall definition --- src/coreclr/vm/comutilnative.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/coreclr/vm/comutilnative.h b/src/coreclr/vm/comutilnative.h index 91c0a4b5815d9..ad51908267489 100644 --- a/src/coreclr/vm/comutilnative.h +++ b/src/coreclr/vm/comutilnative.h @@ -245,7 +245,7 @@ class MethodTableNative { public: static FCDECL1(UINT32, GetNumInstanceFieldBytes, MethodTable* mt); static FCDECL1(CorElementType, GetVerifierCorElementType, MethodTable* mt); - static FCDECL2(FC_BOOL_RET, CanCastTo, MethodTable* fromType, MethodTable* toType); + static FCDECL2(FC_BOOL_RET, CanCastTo, void* fromType, void* toType); }; extern "C" BOOL QCALLTYPE MethodTable_AreTypesEquivalent(MethodTable* mta, MethodTable* mtb); From f7da1728f3250505b71170b322ae4796f5813f99 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Tue, 28 May 2024 15:34:46 +0800 Subject: [PATCH 09/51] Implement InitializeArray in managed --- .../RuntimeHelpers.CoreCLR.cs | 69 +++++++++++++++++-- .../src/Resources/Strings.resx | 8 ++- .../src/System/ThrowHelper.cs | 6 ++ 3 files changed, 78 insertions(+), 5 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs index 921af0d7967ae..ab36b1cf50c1a 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs @@ -1,22 +1,83 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Buffers.Binary; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; -using System.Threading; namespace System.Runtime.CompilerServices { public static partial class RuntimeHelpers { [Intrinsic] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void InitializeArray(Array array, RuntimeFieldHandle fldHandle); + public static unsafe void InitializeArray(Array array, RuntimeFieldHandle fldHandle) + { + RtFieldInfo fldInfo = (RtFieldInfo)FieldInfo.GetFieldFromHandle(fldHandle); + + if (array is null) + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); + + if ((fldInfo.Attributes & FieldAttributes.HasFieldRVA) != 0) + ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_BadFieldForInitializeArray); + + // Note that we do not check that the field is actually in the PE file that is initializing + // the array. Basically the data being published is can be accessed by anyone with the proper + // permissions (C# marks these as assembly visibility, and thus are protected from outside + // snooping) + + if (!array.GetCorElementTypeOfElementType().IsPrimitiveType()) // Enum is included + ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_MustBePrimitiveArray); + + MethodTable* pMT = GetMethodTable(array); + nuint totalSize = pMT->ComponentSize * array.NativeLength; + + uint size = ((MethodTable*)((RuntimeType)fldInfo.FieldType).TypeHandle.Value)->GetNumInstanceFieldBytes(); + + // make certain you don't go off the end of the rva static + if (totalSize > size) + ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_BadFieldForInitializeArray); + + void* src = (void*)RuntimeFieldHandle.GetStaticFieldAddress(fldInfo); + ref byte dst = ref MemoryMarshal.GetArrayDataReference(array); + + Debug.Assert(!pMT->GetArrayElementTypeHandle().AsMethodTable()->ContainsGCPointers); + + if (BitConverter.IsLittleEndian) + { + SpanHelpers.Memmove(ref dst, ref *(byte*)src, totalSize); + } + else + { + switch (pMT->ComponentSize) + { + case 1: + SpanHelpers.Memmove(ref dst, ref *(byte*)src, totalSize); + break; + case 2: + BinaryPrimitives.ReverseEndianness( + new ReadOnlySpan(src, array.Length), + new Span(ref Unsafe.As(ref dst), array.Length)); + break; + case 4: + BinaryPrimitives.ReverseEndianness( + new ReadOnlySpan(src, array.Length), + new Span(ref Unsafe.As(ref dst), array.Length)); + break; + case 8: + BinaryPrimitives.ReverseEndianness( + new ReadOnlySpan(src, array.Length), + new Span(ref Unsafe.As(ref dst), array.Length)); + break; + default: + Debug.Fail("Incorrect primitive type size!"); + break; + } + } + } [MethodImpl(MethodImplOptions.InternalCall)] private static extern unsafe void* GetSpanDataFrom( diff --git a/src/libraries/System.Private.CoreLib/src/Resources/Strings.resx b/src/libraries/System.Private.CoreLib/src/Resources/Strings.resx index c4504f140527a..4a27078217114 100644 --- a/src/libraries/System.Private.CoreLib/src/Resources/Strings.resx +++ b/src/libraries/System.Private.CoreLib/src/Resources/Strings.resx @@ -4319,4 +4319,10 @@ Emitting debug info is not supported for this member. - + + The field is invalid for initializing array or span. + + + The array must be array of primitive or enum type. + + \ No newline at end of file diff --git a/src/libraries/System.Private.CoreLib/src/System/ThrowHelper.cs b/src/libraries/System.Private.CoreLib/src/System/ThrowHelper.cs index f49c16c51ef42..3997d47191fb8 100644 --- a/src/libraries/System.Private.CoreLib/src/System/ThrowHelper.cs +++ b/src/libraries/System.Private.CoreLib/src/System/ThrowHelper.cs @@ -1252,6 +1252,10 @@ private static string GetResourceString(ExceptionResource resource) return SR.Argument_HasToBeArrayClass; case ExceptionResource.Arg_PrimitiveWiden: return SR.Arg_PrimWiden; + case ExceptionResource.Argument_MustBePrimitiveArray: + return SR.Argument_MustBePrimitiveArray; + case ExceptionResource.Argument_BadFieldForInitializeArray: + return SR.Argument_BadFieldForInitializeArray; default: Debug.Fail("The enum value is not defined, please check the ExceptionResource Enum."); return ""; @@ -1449,5 +1453,7 @@ internal enum ExceptionResource Format_ExpectedAsciiDigit, Argument_HasToBeArrayClass, Arg_PrimitiveWiden, + Argument_MustBePrimitiveArray, + Argument_BadFieldForInitializeArray, } } From 0924555cccbae35e698fbe5310586c6e1877ed3c Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Tue, 28 May 2024 15:45:21 +0800 Subject: [PATCH 10/51] Implement GetSpanDataFrom in managed --- .../RuntimeHelpers.CoreCLR.cs | 32 +++++++++++++++++-- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs index ab36b1cf50c1a..7e16c52e6dbbd 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs @@ -79,11 +79,37 @@ public static unsafe void InitializeArray(Array array, RuntimeFieldHandle fldHan } } - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern unsafe void* GetSpanDataFrom( + private static unsafe void* GetSpanDataFrom( RuntimeFieldHandle fldHandle, RuntimeTypeHandle targetTypeHandle, - out int count); + out int count) + { + RtFieldInfo fldInfo = (RtFieldInfo)FieldInfo.GetFieldFromHandle(fldHandle); + + if ((fldInfo.Attributes & FieldAttributes.HasFieldRVA) != 0) + ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_BadFieldForInitializeArray); + + TypeHandle th = new TypeHandle((void*)targetTypeHandle.Value); + Debug.Assert(!th.IsTypeDesc); // TypeDesc can't be used as generic parameter + + if (!th.GetVerifierCorElementType().IsPrimitiveType()) // Enum is included + ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_MustBePrimitiveArray); + + uint totalSize = ((MethodTable*)((RuntimeType)fldInfo.FieldType).TypeHandle.Value)->GetNumInstanceFieldBytes(); + uint targetTypeSize = th.AsMethodTable()->GetNumInstanceFieldBytes(); + + IntPtr data = RuntimeFieldHandle.GetStaticFieldAddress(fldInfo); + if (data % targetTypeSize != 0) + ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_BadFieldForInitializeArray); + + if (!BitConverter.IsLittleEndian) + { + throw new PlatformNotSupportedException(); + } + + count = (int)(totalSize / targetTypeSize); + return (void*)data; + } // GetObjectValue is intended to allow value classes to be manipulated as 'Object' // but have aliasing behavior of a value class. The intent is that you would use From dc85381096f9e18f6ae60b4b42a124b0ccdda4cb Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Tue, 28 May 2024 15:48:10 +0800 Subject: [PATCH 11/51] Remove FCall definition --- .../classlibnative/bcltype/arraynative.cpp | 113 ------------------ .../classlibnative/bcltype/arraynative.h | 21 +--- src/coreclr/vm/ecalllist.h | 2 - 3 files changed, 1 insertion(+), 135 deletions(-) diff --git a/src/coreclr/classlibnative/bcltype/arraynative.cpp b/src/coreclr/classlibnative/bcltype/arraynative.cpp index aa675eb29633a..246c539827607 100644 --- a/src/coreclr/classlibnative/bcltype/arraynative.cpp +++ b/src/coreclr/classlibnative/bcltype/arraynative.cpp @@ -195,116 +195,3 @@ void QCALLTYPE Array_CreateInstance(QCall::TypeHandle pTypeHnd, INT32 rank, INT3 Done: ; END_QCALL; } - -// This method will initialize an array from a TypeHandle to a field. - -FCIMPL2_IV(void, ArrayNative::InitializeArray, ArrayBase* pArrayRef, FCALLRuntimeFieldHandle structField) -{ - FCALL_CONTRACT; - - BASEARRAYREF arr = BASEARRAYREF(pArrayRef); - REFLECTFIELDREF refField = (REFLECTFIELDREF)ObjectToOBJECTREF(FCALL_RFH_TO_REFLECTFIELD(structField)); - HELPER_METHOD_FRAME_BEGIN_2(arr, refField); - - if ((arr == 0) || (refField == NULL)) - COMPlusThrow(kArgumentNullException); - - FieldDesc* pField = (FieldDesc*) refField->GetField(); - - if (!pField->IsRVA()) - COMPlusThrow(kArgumentException); - - // Note that we do not check that the field is actually in the PE file that is initializing - // the array. Basically the data being published is can be accessed by anyone with the proper - // permissions (C# marks these as assembly visibility, and thus are protected from outside - // snooping) - - if (!CorTypeInfo::IsPrimitiveType(arr->GetArrayElementType()) && !arr->GetArrayElementTypeHandle().IsEnum()) - COMPlusThrow(kArgumentException); - - SIZE_T dwCompSize = arr->GetComponentSize(); - SIZE_T dwElemCnt = arr->GetNumComponents(); - SIZE_T dwTotalSize = dwCompSize * dwElemCnt; - - DWORD size = pField->LoadSize(); - - // make certain you don't go off the end of the rva static - if (dwTotalSize > size) - COMPlusThrow(kArgumentException); - - void *src = pField->GetStaticAddressHandle(NULL); - void *dest = arr->GetDataPtr(); - -#if BIGENDIAN - DWORD i; - switch (dwCompSize) { - case 1: - memcpyNoGCRefs(dest, src, dwElemCnt); - break; - case 2: - for (i = 0; i < dwElemCnt; i++) - *((UINT16*)dest + i) = GET_UNALIGNED_VAL16((UINT16*)src + i); - break; - case 4: - for (i = 0; i < dwElemCnt; i++) - *((UINT32*)dest + i) = GET_UNALIGNED_VAL32((UINT32*)src + i); - break; - case 8: - for (i = 0; i < dwElemCnt; i++) - *((UINT64*)dest + i) = GET_UNALIGNED_VAL64((UINT64*)src + i); - break; - default: - // should not reach here. - UNREACHABLE_MSG("Incorrect primitive type size!"); - break; - } -#else - memcpyNoGCRefs(dest, src, dwTotalSize); -#endif - - HELPER_METHOD_FRAME_END(); -} -FCIMPLEND - -FCIMPL3_VVI(void*, ArrayNative::GetSpanDataFrom, FCALLRuntimeFieldHandle structField, FCALLRuntimeTypeHandle targetTypeUnsafe, INT32* count) -{ - FCALL_CONTRACT; - struct - { - REFLECTFIELDREF refField; - REFLECTCLASSBASEREF refClass; - } gc; - gc.refField = (REFLECTFIELDREF)ObjectToOBJECTREF(FCALL_RFH_TO_REFLECTFIELD(structField)); - gc.refClass = (REFLECTCLASSBASEREF)ObjectToOBJECTREF(FCALL_RTH_TO_REFLECTCLASS(targetTypeUnsafe)); - void* data = NULL; - HELPER_METHOD_FRAME_BEGIN_RET_PROTECT(gc); - - FieldDesc* pField = (FieldDesc*)gc.refField->GetField(); - - if (!pField->IsRVA()) - COMPlusThrow(kArgumentException); - - TypeHandle targetTypeHandle = gc.refClass->GetType(); - if (!CorTypeInfo::IsPrimitiveType(targetTypeHandle.GetSignatureCorElementType()) && !targetTypeHandle.IsEnum()) - COMPlusThrow(kArgumentException); - - DWORD totalSize = pField->LoadSize(); - DWORD targetTypeSize = targetTypeHandle.GetSize(); - - data = pField->GetStaticAddressHandle(NULL); - _ASSERTE(data != NULL); - _ASSERTE(count != NULL); - - if (AlignUp((UINT_PTR)data, targetTypeSize) != (UINT_PTR)data) - COMPlusThrow(kArgumentException); - - *count = (INT32)totalSize / targetTypeSize; - -#if BIGENDIAN - COMPlusThrow(kPlatformNotSupportedException); -#endif - - HELPER_METHOD_FRAME_END(); - return data; -} -FCIMPLEND diff --git a/src/coreclr/classlibnative/bcltype/arraynative.h b/src/coreclr/classlibnative/bcltype/arraynative.h index 6f130c2215b40..5dd3570ce5cbb 100644 --- a/src/coreclr/classlibnative/bcltype/arraynative.h +++ b/src/coreclr/classlibnative/bcltype/arraynative.h @@ -13,26 +13,7 @@ #ifndef _ARRAYNATIVE_H_ #define _ARRAYNATIVE_H_ -#include "fcall.h" -#include "runtimehandles.h" - -struct FCALLRuntimeFieldHandle -{ - ReflectFieldObject *pFieldDONOTUSEDIRECTLY; -}; -#define FCALL_RFH_TO_REFLECTFIELD(x) (x).pFieldDONOTUSEDIRECTLY - -class ArrayNative -{ -public: - // This method will initialize an array from a TypeHandle - // to a field. - static FCDECL2_IV(void, InitializeArray, ArrayBase* vArrayRef, FCALLRuntimeFieldHandle structField); - - // This method will acquire data to create a span from a TypeHandle - // to a field. - static FCDECL3_VVI(void*, GetSpanDataFrom, FCALLRuntimeFieldHandle structField, FCALLRuntimeTypeHandle targetTypeUnsafe, INT32* count); -}; +#include "qcall.h" extern "C" void QCALLTYPE Array_CreateInstance(QCall::TypeHandle pTypeHnd, INT32 rank, INT32* pLengths, INT32* pBounds, BOOL createFromArrayType, QCall::ObjectHandleOnStack retArray); extern "C" PCODE QCALLTYPE Array_GetElementConstructorEntrypoint(QCall::TypeHandle pArrayTypeHnd); diff --git a/src/coreclr/vm/ecalllist.h b/src/coreclr/vm/ecalllist.h index 7a18572cc46a8..b33ad43eae218 100644 --- a/src/coreclr/vm/ecalllist.h +++ b/src/coreclr/vm/ecalllist.h @@ -434,8 +434,6 @@ FCFuncStart(gMonitorFuncs) FCFuncEnd() FCFuncStart(gRuntimeHelpers) - FCFuncElement("InitializeArray", ArrayNative::InitializeArray) - FCFuncElement("GetSpanDataFrom", ArrayNative::GetSpanDataFrom) FCFuncElement("PrepareDelegate", ReflectionInvocation::PrepareDelegate) FCFuncElement("GetHashCode", ObjectNative::GetHashCode) FCFuncElement("TryGetHashCode", ObjectNative::TryGetHashCode) From f99c553d9964b2d93e741af3ca139e3008640384 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Tue, 28 May 2024 22:48:13 +0800 Subject: [PATCH 12/51] Fix RVA field address --- src/coreclr/vm/reflectioninvocation.cpp | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/coreclr/vm/reflectioninvocation.cpp b/src/coreclr/vm/reflectioninvocation.cpp index f57e21801253a..e4ca976f2fd6c 100644 --- a/src/coreclr/vm/reflectioninvocation.cpp +++ b/src/coreclr/vm/reflectioninvocation.cpp @@ -1246,14 +1246,16 @@ FCIMPL1(void*, RuntimeFieldHandle::GetStaticFieldAddress, ReflectFieldObject *pF // IsFastPathSupported needs to checked before calling this method. _ASSERTE(IsFastPathSupportedHelper(pFieldDesc)); - PTR_BYTE base = 0; - if (!pFieldDesc->IsRVA()) + if (pFieldDesc->IsRVA()) { - // For RVA the base is ignored and offset is used. - base = pFieldDesc->GetBase(); + Module* pModule = pFieldDesc->GetModule(); + return pModule->GetRvaField(pFieldDesc->GetOffset()); + } + else + { + PTR_BYTE base = pFieldDesc->GetBase(); + return PTR_VOID(base + pFieldDesc->GetOffset()); } - - return PTR_VOID(base + pFieldDesc->GetOffset()); } FCIMPLEND From c5e6cc4fd8d1d876ff67d966531f9e6d3c8e01ab Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Tue, 28 May 2024 22:53:31 +0800 Subject: [PATCH 13/51] Fix RVA assert --- .../System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs index 7e16c52e6dbbd..124e27f332808 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs @@ -21,7 +21,7 @@ public static unsafe void InitializeArray(Array array, RuntimeFieldHandle fldHan if (array is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - if ((fldInfo.Attributes & FieldAttributes.HasFieldRVA) != 0) + if ((fldInfo.Attributes & FieldAttributes.HasFieldRVA) == 0) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_BadFieldForInitializeArray); // Note that we do not check that the field is actually in the PE file that is initializing @@ -86,7 +86,7 @@ public static unsafe void InitializeArray(Array array, RuntimeFieldHandle fldHan { RtFieldInfo fldInfo = (RtFieldInfo)FieldInfo.GetFieldFromHandle(fldHandle); - if ((fldInfo.Attributes & FieldAttributes.HasFieldRVA) != 0) + if ((fldInfo.Attributes & FieldAttributes.HasFieldRVA) == 0) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_BadFieldForInitializeArray); TypeHandle th = new TypeHandle((void*)targetTypeHandle.Value); From 470b86fcce282dfb5cdd2c74da205aa8cf694d4a Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Wed, 29 May 2024 00:36:47 +0800 Subject: [PATCH 14/51] Do not use hydrated RtFieldInfo --- .../CompilerServices/RuntimeHelpers.CoreCLR.cs | 12 ++++++------ .../src/System/RuntimeHandles.cs | 12 +++++++++++- src/coreclr/vm/ecalllist.h | 1 + src/coreclr/vm/runtimehandles.cpp | 13 +++++++++++++ src/coreclr/vm/runtimehandles.h | 1 + 5 files changed, 32 insertions(+), 7 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs index 124e27f332808..ec0a606c769a5 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs @@ -16,12 +16,12 @@ public static partial class RuntimeHelpers [Intrinsic] public static unsafe void InitializeArray(Array array, RuntimeFieldHandle fldHandle) { - RtFieldInfo fldInfo = (RtFieldInfo)FieldInfo.GetFieldFromHandle(fldHandle); + IRuntimeFieldInfo fldInfo = fldHandle.GetRuntimeFieldInfo(); if (array is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - if ((fldInfo.Attributes & FieldAttributes.HasFieldRVA) == 0) + if ((RuntimeFieldHandle.GetAttributes(fldInfo.Value) & FieldAttributes.HasFieldRVA) == 0) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_BadFieldForInitializeArray); // Note that we do not check that the field is actually in the PE file that is initializing @@ -35,7 +35,7 @@ public static unsafe void InitializeArray(Array array, RuntimeFieldHandle fldHan MethodTable* pMT = GetMethodTable(array); nuint totalSize = pMT->ComponentSize * array.NativeLength; - uint size = ((MethodTable*)((RuntimeType)fldInfo.FieldType).TypeHandle.Value)->GetNumInstanceFieldBytes(); + uint size = ((MethodTable*)RuntimeFieldHandle.GetApproxFieldType(fldInfo))->GetNumInstanceFieldBytes(); // make certain you don't go off the end of the rva static if (totalSize > size) @@ -84,9 +84,9 @@ public static unsafe void InitializeArray(Array array, RuntimeFieldHandle fldHan RuntimeTypeHandle targetTypeHandle, out int count) { - RtFieldInfo fldInfo = (RtFieldInfo)FieldInfo.GetFieldFromHandle(fldHandle); + IRuntimeFieldInfo fldInfo = fldHandle.GetRuntimeFieldInfo(); - if ((fldInfo.Attributes & FieldAttributes.HasFieldRVA) == 0) + if ((RuntimeFieldHandle.GetAttributes(fldInfo.Value) & FieldAttributes.HasFieldRVA) == 0) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_BadFieldForInitializeArray); TypeHandle th = new TypeHandle((void*)targetTypeHandle.Value); @@ -95,7 +95,7 @@ public static unsafe void InitializeArray(Array array, RuntimeFieldHandle fldHan if (!th.GetVerifierCorElementType().IsPrimitiveType()) // Enum is included ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_MustBePrimitiveArray); - uint totalSize = ((MethodTable*)((RuntimeType)fldInfo.FieldType).TypeHandle.Value)->GetNumInstanceFieldBytes(); + uint totalSize = ((MethodTable*)RuntimeFieldHandle.GetApproxFieldType(fldInfo))->GetNumInstanceFieldBytes(); uint targetTypeSize = th.AsMethodTable()->GetNumInstanceFieldBytes(); IntPtr data = RuntimeFieldHandle.GetStaticFieldAddress(fldInfo); diff --git a/src/coreclr/System.Private.CoreLib/src/System/RuntimeHandles.cs b/src/coreclr/System.Private.CoreLib/src/System/RuntimeHandles.cs index 380981993451e..7ba90efac8042 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/RuntimeHandles.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/RuntimeHandles.cs @@ -1180,6 +1180,16 @@ internal static RuntimeType GetApproxDeclaringType(IRuntimeFieldInfo field) return type; } + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern IntPtr GetApproxFieldType(RuntimeFieldHandleInternal field); + + internal static IntPtr GetApproxFieldType(IRuntimeFieldInfo field) + { + IntPtr th = GetApproxFieldType(field.Value); + GC.KeepAlive(field); + return th; + } + [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool IsFastPathSupported(RtFieldInfo field); @@ -1187,7 +1197,7 @@ internal static RuntimeType GetApproxDeclaringType(IRuntimeFieldInfo field) internal static extern int GetInstanceFieldOffset(RtFieldInfo field); [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern IntPtr GetStaticFieldAddress(RtFieldInfo field); + internal static extern IntPtr GetStaticFieldAddress(IRuntimeFieldInfo field); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern int GetToken(RtFieldInfo field); diff --git a/src/coreclr/vm/ecalllist.h b/src/coreclr/vm/ecalllist.h index b33ad43eae218..e5231f43e6410 100644 --- a/src/coreclr/vm/ecalllist.h +++ b/src/coreclr/vm/ecalllist.h @@ -224,6 +224,7 @@ FCFuncStart(gCOMFieldHandleNewFuncs) FCFuncElement("_GetUtf8Name", RuntimeFieldHandle::GetUtf8Name) FCFuncElement("GetAttributes", RuntimeFieldHandle::GetAttributes) FCFuncElement("GetApproxDeclaringType", RuntimeFieldHandle::GetApproxDeclaringType) + FCFuncElement("GetApproxFieldType", RuntimeFieldHandle::GetApproxFieldType) FCFuncElement("GetToken", RuntimeFieldHandle::GetToken) FCFuncElement("GetStaticFieldForGenericType", RuntimeFieldHandle::GetStaticFieldForGenericType) FCFuncElement("AcquiresContextFromThis", RuntimeFieldHandle::AcquiresContextFromThis) diff --git a/src/coreclr/vm/runtimehandles.cpp b/src/coreclr/vm/runtimehandles.cpp index c660763f11577..2817ef5a76ece 100644 --- a/src/coreclr/vm/runtimehandles.cpp +++ b/src/coreclr/vm/runtimehandles.cpp @@ -2622,6 +2622,19 @@ FCIMPL1(ReflectClassBaseObject*, RuntimeFieldHandle::GetApproxDeclaringType, Fie } FCIMPLEND +FCIMPL1(void*, RuntimeFieldHandle::GetApproxFieldType, FieldDesc *pField) { + CONTRACTL { + FCALL_CHECK; + } + CONTRACTL_END; + + if (!pField) + FCThrowRes(kArgumentNullException, W("Arg_InvalidHandle")); + + return pField->GetApproxFieldTypeHandleThrowing().GetMethodTable(); +} +FCIMPLEND + FCIMPL1(INT32, RuntimeFieldHandle::GetToken, ReflectFieldObject *pFieldUNSAFE) { CONTRACTL { FCALL_CHECK; diff --git a/src/coreclr/vm/runtimehandles.h b/src/coreclr/vm/runtimehandles.h index 56bb2df245f9f..a763e33dbc2c6 100644 --- a/src/coreclr/vm/runtimehandles.h +++ b/src/coreclr/vm/runtimehandles.h @@ -303,6 +303,7 @@ class RuntimeFieldHandle { static FCDECL1(INT32, GetAttributes, FieldDesc *pField); static FCDECL1(ReflectClassBaseObject*, GetApproxDeclaringType, FieldDesc *pField); + static FCDECL1(void*, GetApproxFieldType, FieldDesc *pField); static FCDECL1(INT32, GetToken, ReflectFieldObject *pFieldUNSAFE); static FCDECL2(FieldDesc*, GetStaticFieldForGenericType, FieldDesc *pField, ReflectClassBaseObject *pDeclaringType); static FCDECL1(FC_BOOL_RET, AcquiresContextFromThis, FieldDesc *pField); From c7821e6a6dcb3b97dce556da8722947a5bfe5a88 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Wed, 29 May 2024 20:19:36 +0800 Subject: [PATCH 15/51] Use QCall for LoadSize --- .../CompilerServices/RuntimeHelpers.CoreCLR.cs | 4 ++-- .../src/System/RuntimeHandles.cs | 15 ++++----------- src/coreclr/vm/ecalllist.h | 1 - src/coreclr/vm/qcall.h | 18 ++++++++++++++++++ src/coreclr/vm/qcallentrypoints.cpp | 1 + src/coreclr/vm/reflectioninvocation.cpp | 13 +++++++++++++ src/coreclr/vm/runtimehandles.cpp | 13 ------------- src/coreclr/vm/runtimehandles.h | 2 +- .../Runtime/CompilerServices/QCallHandles.cs | 13 +++++++++++++ 9 files changed, 52 insertions(+), 28 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs index ec0a606c769a5..313e4da564c9a 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs @@ -35,7 +35,7 @@ public static unsafe void InitializeArray(Array array, RuntimeFieldHandle fldHan MethodTable* pMT = GetMethodTable(array); nuint totalSize = pMT->ComponentSize * array.NativeLength; - uint size = ((MethodTable*)RuntimeFieldHandle.GetApproxFieldType(fldInfo))->GetNumInstanceFieldBytes(); + uint size = RuntimeFieldHandle.GetFieldSize(new QCallFieldHandle(ref fldInfo)); // make certain you don't go off the end of the rva static if (totalSize > size) @@ -95,7 +95,7 @@ public static unsafe void InitializeArray(Array array, RuntimeFieldHandle fldHan if (!th.GetVerifierCorElementType().IsPrimitiveType()) // Enum is included ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_MustBePrimitiveArray); - uint totalSize = ((MethodTable*)RuntimeFieldHandle.GetApproxFieldType(fldInfo))->GetNumInstanceFieldBytes(); + uint totalSize = RuntimeFieldHandle.GetFieldSize(new QCallFieldHandle(ref fldInfo)); uint targetTypeSize = th.AsMethodTable()->GetNumInstanceFieldBytes(); IntPtr data = RuntimeFieldHandle.GetStaticFieldAddress(fldInfo); diff --git a/src/coreclr/System.Private.CoreLib/src/System/RuntimeHandles.cs b/src/coreclr/System.Private.CoreLib/src/System/RuntimeHandles.cs index 7ba90efac8042..472f4f6318a3d 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/RuntimeHandles.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/RuntimeHandles.cs @@ -1085,7 +1085,7 @@ public RuntimeFieldInfoStub(RuntimeFieldHandleInternal fieldHandle, object keepa } [NonVersionable] - public unsafe struct RuntimeFieldHandle : IEquatable, ISerializable + public unsafe partial struct RuntimeFieldHandle : IEquatable, ISerializable { // Returns handle for interop with EE. The handle is guaranteed to be non-null. internal RuntimeFieldHandle GetNativeHandle() @@ -1180,16 +1180,6 @@ internal static RuntimeType GetApproxDeclaringType(IRuntimeFieldInfo field) return type; } - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern IntPtr GetApproxFieldType(RuntimeFieldHandleInternal field); - - internal static IntPtr GetApproxFieldType(IRuntimeFieldInfo field) - { - IntPtr th = GetApproxFieldType(field.Value); - GC.KeepAlive(field); - return th; - } - [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool IsFastPathSupported(RtFieldInfo field); @@ -1199,6 +1189,9 @@ internal static IntPtr GetApproxFieldType(IRuntimeFieldInfo field) [MethodImpl(MethodImplOptions.InternalCall)] internal static extern IntPtr GetStaticFieldAddress(IRuntimeFieldInfo field); + [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "RuntimeFieldHandle_GetFieldSize")] + internal static partial uint GetFieldSize(QCallFieldHandle field); + [MethodImpl(MethodImplOptions.InternalCall)] internal static extern int GetToken(RtFieldInfo field); diff --git a/src/coreclr/vm/ecalllist.h b/src/coreclr/vm/ecalllist.h index e5231f43e6410..b33ad43eae218 100644 --- a/src/coreclr/vm/ecalllist.h +++ b/src/coreclr/vm/ecalllist.h @@ -224,7 +224,6 @@ FCFuncStart(gCOMFieldHandleNewFuncs) FCFuncElement("_GetUtf8Name", RuntimeFieldHandle::GetUtf8Name) FCFuncElement("GetAttributes", RuntimeFieldHandle::GetAttributes) FCFuncElement("GetApproxDeclaringType", RuntimeFieldHandle::GetApproxDeclaringType) - FCFuncElement("GetApproxFieldType", RuntimeFieldHandle::GetApproxFieldType) FCFuncElement("GetToken", RuntimeFieldHandle::GetToken) FCFuncElement("GetStaticFieldForGenericType", RuntimeFieldHandle::GetStaticFieldForGenericType) FCFuncElement("AcquiresContextFromThis", RuntimeFieldHandle::AcquiresContextFromThis) diff --git a/src/coreclr/vm/qcall.h b/src/coreclr/vm/qcall.h index e3154c7b1334c..b63d2ffa7beac 100644 --- a/src/coreclr/vm/qcall.h +++ b/src/coreclr/vm/qcall.h @@ -293,6 +293,24 @@ class QCall } }; + struct FieldHandle + { + Object ** m_ppObject; + FieldDesc * m_pField; + + operator FieldDesc * () + { + LIMITED_METHOD_CONTRACT; + return m_pField; + } + + FieldDesc * operator -> () + { + LIMITED_METHOD_CONTRACT; + return m_pField; + } + }; + struct LoaderAllocatorHandle { LoaderAllocator * m_pLoaderAllocator; diff --git a/src/coreclr/vm/qcallentrypoints.cpp b/src/coreclr/vm/qcallentrypoints.cpp index 0f919f9ed9131..a2c96af36b6a2 100644 --- a/src/coreclr/vm/qcallentrypoints.cpp +++ b/src/coreclr/vm/qcallentrypoints.cpp @@ -132,6 +132,7 @@ static const Entry s_QCall[] = DllImportEntry(RuntimeModule_GetScopeName) DllImportEntry(RuntimeModule_GetFullyQualifiedName) DllImportEntry(RuntimeModule_GetTypes) + DllImportEntry(RuntimeFieldHandle_GetFieldSize) DllImportEntry(StackFrame_GetMethodDescFromNativeIP) DllImportEntry(ModuleBuilder_GetStringConstant) DllImportEntry(ModuleBuilder_GetTypeRef) diff --git a/src/coreclr/vm/reflectioninvocation.cpp b/src/coreclr/vm/reflectioninvocation.cpp index e4ca976f2fd6c..65192d5a68738 100644 --- a/src/coreclr/vm/reflectioninvocation.cpp +++ b/src/coreclr/vm/reflectioninvocation.cpp @@ -1259,6 +1259,19 @@ FCIMPL1(void*, RuntimeFieldHandle::GetStaticFieldAddress, ReflectFieldObject *pF } FCIMPLEND +extern "C" UINT QCALLTYPE RuntimeFieldHandle_GetFieldSize(QCall::FieldHandle pField) +{ + QCALL_CONTRACT; + + UINT ret = 0; + + BEGIN_QCALL; + ret = pField->LoadSize(); + END_QCALL; + + return ret; +} + extern "C" void QCALLTYPE ReflectionInvocation_CompileMethod(MethodDesc * pMD) { QCALL_CONTRACT; diff --git a/src/coreclr/vm/runtimehandles.cpp b/src/coreclr/vm/runtimehandles.cpp index 2817ef5a76ece..c660763f11577 100644 --- a/src/coreclr/vm/runtimehandles.cpp +++ b/src/coreclr/vm/runtimehandles.cpp @@ -2622,19 +2622,6 @@ FCIMPL1(ReflectClassBaseObject*, RuntimeFieldHandle::GetApproxDeclaringType, Fie } FCIMPLEND -FCIMPL1(void*, RuntimeFieldHandle::GetApproxFieldType, FieldDesc *pField) { - CONTRACTL { - FCALL_CHECK; - } - CONTRACTL_END; - - if (!pField) - FCThrowRes(kArgumentNullException, W("Arg_InvalidHandle")); - - return pField->GetApproxFieldTypeHandleThrowing().GetMethodTable(); -} -FCIMPLEND - FCIMPL1(INT32, RuntimeFieldHandle::GetToken, ReflectFieldObject *pFieldUNSAFE) { CONTRACTL { FCALL_CHECK; diff --git a/src/coreclr/vm/runtimehandles.h b/src/coreclr/vm/runtimehandles.h index a763e33dbc2c6..e0504d952880d 100644 --- a/src/coreclr/vm/runtimehandles.h +++ b/src/coreclr/vm/runtimehandles.h @@ -303,12 +303,12 @@ class RuntimeFieldHandle { static FCDECL1(INT32, GetAttributes, FieldDesc *pField); static FCDECL1(ReflectClassBaseObject*, GetApproxDeclaringType, FieldDesc *pField); - static FCDECL1(void*, GetApproxFieldType, FieldDesc *pField); static FCDECL1(INT32, GetToken, ReflectFieldObject *pFieldUNSAFE); static FCDECL2(FieldDesc*, GetStaticFieldForGenericType, FieldDesc *pField, ReflectClassBaseObject *pDeclaringType); static FCDECL1(FC_BOOL_RET, AcquiresContextFromThis, FieldDesc *pField); static FCDECL1(Object*, GetLoaderAllocator, FieldDesc *pField); }; +extern "C" UINT QCALLTYPE RuntimeFieldHandle_GetFieldSize(QCall::FieldHandle pField); class ModuleHandle { diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/QCallHandles.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/QCallHandles.cs index 240e9932bf624..698fb50375b85 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/QCallHandles.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/QCallHandles.cs @@ -95,4 +95,17 @@ internal QCallTypeHandle(ref RuntimeTypeHandle rth) _handle = rth.Value; } } + + // Wraps IRuntimeFieldInfo into a handle. Used to pass IRuntimeFieldInfo to native code without letting it be collected + internal unsafe ref struct QCallFieldHandle + { + private void* _ptr; + private IntPtr _handle; + + internal QCallFieldHandle(ref IRuntimeFieldInfo field) + { + _ptr = Unsafe.AsPointer(ref field); + _handle = field.Value.Value; + } + } } From 522520381b4962809fe36221faaa38dcd70de461 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Wed, 29 May 2024 20:20:21 +0800 Subject: [PATCH 16/51] Fix CanAssignArrayType condition --- .../System.Private.CoreLib/src/System/Array.CoreCLR.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs index 8d165315e9e2b..bbc882f0286de 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs @@ -203,20 +203,20 @@ private static unsafe AssignArrayEnum CanAssignArrayType(Array sourceArray, Arra return AssignArrayEnum.AssignWrongType; } - // dest Object extends src + // src Object extends dest if (srcTH.CanCastTo(destTH)) return AssignArrayEnum.AssignSimpleCopy; - // src Object extends dest + // dest Object extends src if (destTH.CanCastTo(srcTH)) return AssignArrayEnum.AssignMustCast; // class X extends/implements src and implements dest. - if (!destTH.IsInterface && srcElType != CorElementType.ELEMENT_TYPE_VALUETYPE) + if (destTH.IsInterface && srcElType != CorElementType.ELEMENT_TYPE_VALUETYPE) return AssignArrayEnum.AssignMustCast; // class X implements src and extends/implements dest - if (!srcTH.IsInterface && srcElType != CorElementType.ELEMENT_TYPE_VALUETYPE) + if (srcTH.IsInterface && srcElType != CorElementType.ELEMENT_TYPE_VALUETYPE) return AssignArrayEnum.AssignMustCast; return AssignArrayEnum.AssignWrongType; From 07293e3a331c9274f6536683e12ed0728cafb5bb Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Wed, 29 May 2024 21:03:23 +0800 Subject: [PATCH 17/51] Fix compilation --- .../src/System/Runtime/CompilerServices/QCallHandles.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/QCallHandles.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/QCallHandles.cs index 698fb50375b85..e6ab54d12e5d7 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/QCallHandles.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/QCallHandles.cs @@ -102,10 +102,18 @@ internal unsafe ref struct QCallFieldHandle private void* _ptr; private IntPtr _handle; +#if CORECLR internal QCallFieldHandle(ref IRuntimeFieldInfo field) { _ptr = Unsafe.AsPointer(ref field); _handle = field.Value.Value; } +#endif + + internal QCallFieldHandle(ref RuntimeFieldHandle rth) + { + _ptr = Unsafe.AsPointer(ref rth); + _handle = rth.Value; + } } } From 5da88c33ad549c4e2d2f9f0e959652786c5edf5a Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Wed, 29 May 2024 23:17:12 +0800 Subject: [PATCH 18/51] Simplify AssignType enum --- .../src/System/Array.CoreCLR.cs | 61 +++++++++---------- 1 file changed, 30 insertions(+), 31 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs index bbc882f0286de..f8200f16d1887 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs @@ -62,10 +62,10 @@ private static unsafe void CopyImpl(Array sourceArray, int sourceIndex, Array de if ((uint)(destinationIndex + length) > destinationArray.NativeLength) throw new ArgumentException(SR.Arg_LongerThanDestArray, nameof(destinationArray)); - AssignArrayEnum assignType = AssignArrayEnum.AssignWrongType; + ArrayAssignType assignType = ArrayAssignType.WrongType; if (sourceArray.GetType() == destinationArray.GetType() - || (assignType = CanAssignArrayType(sourceArray, destinationArray)) == AssignArrayEnum.AssignSimpleCopy) + || (assignType = CanAssignArrayType(sourceArray, destinationArray)) == ArrayAssignType.SimpleCopy) { MethodTable* pMT = RuntimeHelpers.GetMethodTable(sourceArray); @@ -116,30 +116,30 @@ private static CorElementType GetNormalizedIntegralArrayElementType(CorElementTy // instance & might fail when called from within a CER, or if the // reliable flag is true, it will either always succeed or always // throw an exception with no side effects. - private static unsafe void CopySlow(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length, AssignArrayEnum assignType) + private static unsafe void CopySlow(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length, ArrayAssignType assignType) { Debug.Assert(sourceArray.Rank == destinationArray.Rank); - if (assignType == AssignArrayEnum.AssignWrongType) + if (assignType == ArrayAssignType.WrongType) ThrowHelper.ThrowArrayTypeMismatchException_CantAssignType(); if (length > 0) { switch (assignType) { - case AssignArrayEnum.AssignUnboxValueClass: + case ArrayAssignType.UnboxValueClass: CopyImplUnBoxEachElement(sourceArray, sourceIndex, destinationArray, destinationIndex, length); break; - case AssignArrayEnum.AssignBoxValueClassOrPrimitive: + case ArrayAssignType.BoxValueClassOrPrimitive: CopyImplBoxEachElement(sourceArray, sourceIndex, destinationArray, destinationIndex, length); break; - case AssignArrayEnum.AssignMustCast: + case ArrayAssignType.MustCast: CopyImplCastCheckEachElement(sourceArray, sourceIndex, destinationArray, destinationIndex, length); break; - case AssignArrayEnum.AssignPrimitiveWiden: + case ArrayAssignType.PrimitiveWiden: CopyImplPrimitiveWiden(sourceArray, sourceIndex, destinationArray, destinationIndex, length); break; @@ -150,43 +150,42 @@ private static unsafe void CopySlow(Array sourceArray, int sourceIndex, Array de } } - // Must match the definition in arraynative.cpp - private enum AssignArrayEnum + private enum ArrayAssignType { - AssignSimpleCopy, - AssignWrongType, - AssignMustCast, - AssignBoxValueClassOrPrimitive, - AssignUnboxValueClass, - AssignPrimitiveWiden, + SimpleCopy, + WrongType, + MustCast, + BoxValueClassOrPrimitive, + UnboxValueClass, + PrimitiveWiden, } - private static unsafe AssignArrayEnum CanAssignArrayType(Array sourceArray, Array destinationArray) + private static unsafe ArrayAssignType CanAssignArrayType(Array sourceArray, Array destinationArray) { TypeHandle srcTH = RuntimeHelpers.GetMethodTable(sourceArray)->GetArrayElementTypeHandle(); TypeHandle destTH = RuntimeHelpers.GetMethodTable(destinationArray)->GetArrayElementTypeHandle(); if (TypeHandle.AreSameType(srcTH, destTH)) // This check kicks for different array kind or dimensions - return AssignArrayEnum.AssignSimpleCopy; + return ArrayAssignType.SimpleCopy; // Value class boxing if (srcTH.IsValueType && !destTH.IsValueType) { if (srcTH.CanCastTo(destTH)) - return AssignArrayEnum.AssignBoxValueClassOrPrimitive; + return ArrayAssignType.BoxValueClassOrPrimitive; else - return AssignArrayEnum.AssignWrongType; + return ArrayAssignType.WrongType; } // Value class unboxing. if (!srcTH.IsValueType && destTH.IsValueType) { if (srcTH.CanCastTo(destTH)) - return AssignArrayEnum.AssignUnboxValueClass; + return ArrayAssignType.UnboxValueClass; else if (destTH.CanCastTo(srcTH)) // V extends IV. Copying from IV to V, or Object to V. - return AssignArrayEnum.AssignUnboxValueClass; + return ArrayAssignType.UnboxValueClass; else - return AssignArrayEnum.AssignWrongType; + return ArrayAssignType.WrongType; } CorElementType srcElType = srcTH.GetVerifierCorElementType(); @@ -196,30 +195,30 @@ private static unsafe AssignArrayEnum CanAssignArrayType(Array sourceArray, Arra if (srcElType.IsPrimitiveType() && destElType.IsPrimitiveType()) { if (GetNormalizedIntegralArrayElementType(srcElType) == GetNormalizedIntegralArrayElementType(destElType)) - return AssignArrayEnum.AssignSimpleCopy; + return ArrayAssignType.SimpleCopy; else if (RuntimeHelpers.CanPrimitiveWiden(srcElType, destElType)) - return AssignArrayEnum.AssignPrimitiveWiden; + return ArrayAssignType.PrimitiveWiden; else - return AssignArrayEnum.AssignWrongType; + return ArrayAssignType.WrongType; } // src Object extends dest if (srcTH.CanCastTo(destTH)) - return AssignArrayEnum.AssignSimpleCopy; + return ArrayAssignType.SimpleCopy; // dest Object extends src if (destTH.CanCastTo(srcTH)) - return AssignArrayEnum.AssignMustCast; + return ArrayAssignType.MustCast; // class X extends/implements src and implements dest. if (destTH.IsInterface && srcElType != CorElementType.ELEMENT_TYPE_VALUETYPE) - return AssignArrayEnum.AssignMustCast; + return ArrayAssignType.MustCast; // class X implements src and extends/implements dest if (srcTH.IsInterface && srcElType != CorElementType.ELEMENT_TYPE_VALUETYPE) - return AssignArrayEnum.AssignMustCast; + return ArrayAssignType.MustCast; - return AssignArrayEnum.AssignWrongType; + return ArrayAssignType.WrongType; } // Unboxes from an Object[] into a value class or primitive array. From 5222bcaeea5f7f654641c2704a3d0cbe71b8112c Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Wed, 29 May 2024 23:27:44 +0800 Subject: [PATCH 19/51] Fix I and U in CanPrimitiveWiden --- .../src/System/Runtime/CompilerServices/RuntimeHelpers.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs index 938cdeb566833..3715e6df74a11 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs @@ -131,6 +131,11 @@ internal static bool IsPrimitiveType(this CorElementType et) internal static bool CanPrimitiveWiden(CorElementType srcET, CorElementType dstET) { Debug.Assert(srcET.IsPrimitiveType() && dstET.IsPrimitiveType()); + if ((int)srcET >= PrimitiveWidenTable.Length) + { + // I or U + return srcET == dstET; + } return (PrimitiveWidenTable[(int)srcET] & (1 << (int)dstET)) != 0; } From 335b2fb81588f052dc6b8767d9686ed6cba9c050 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Thu, 30 May 2024 18:33:25 +0800 Subject: [PATCH 20/51] CanCastTo should be QCall --- .../RuntimeHelpers.CoreCLR.cs | 12 +++++----- src/coreclr/vm/comutilnative.cpp | 22 +++++++++++++------ src/coreclr/vm/comutilnative.h | 2 +- src/coreclr/vm/ecalllist.h | 1 - src/coreclr/vm/qcallentrypoints.cpp | 1 + 5 files changed, 23 insertions(+), 15 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs index 313e4da564c9a..cd1dc4dc6472f 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs @@ -807,10 +807,6 @@ public TypeHandle GetArrayElementTypeHandle() [MethodImpl(MethodImplOptions.InternalCall)] public extern CorElementType GetVerifierCorElementType(); - - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern bool CanCastTo_NoCacheLookup(void* fromTypeHnd, void* toTypeHnd); - } // Subset of src\vm\methodtable.h @@ -838,7 +834,7 @@ public bool CanCompareBitsOrUseFastGetHashCode /// /// A type handle, which can wrap either a pointer to a or to a . /// - internal readonly unsafe struct TypeHandle + internal readonly unsafe partial struct TypeHandle { // Subset of src\vm\typehandle.h @@ -908,9 +904,13 @@ public bool CanCastTo(TypeHandle destTH) if (result != CastResult.MaybeCast) return result == CastResult.CanCast; - return MethodTable.CanCastTo_NoCacheLookup(m_asTAddr, destTH.m_asTAddr); + return CanCastTo_NoCacheLookup(m_asTAddr, destTH.m_asTAddr); } + [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "TypeHandle_CanCastTo")] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool CanCastTo_NoCacheLookup(void* fromTypeHnd, void* toTypeHnd); + public bool IsValueType { [MethodImpl(MethodImplOptions.AggressiveInlining)] diff --git a/src/coreclr/vm/comutilnative.cpp b/src/coreclr/vm/comutilnative.cpp index f1c3209c86a51..1823ffa2c07ac 100644 --- a/src/coreclr/vm/comutilnative.cpp +++ b/src/coreclr/vm/comutilnative.cpp @@ -1794,13 +1794,6 @@ FCIMPL1(CorElementType, MethodTableNative::GetVerifierCorElementType, MethodTabl } FCIMPLEND -FCIMPL2(FC_BOOL_RET, MethodTableNative::CanCastTo, void* fromType, void* toType) -{ - FCALL_CONTRACT; - FC_RETURN_BOOL(TypeHandle::FromPtr(fromType).CanCastTo(TypeHandle::FromPtr(toType))); -} -FCIMPLEND - extern "C" BOOL QCALLTYPE MethodTable_AreTypesEquivalent(MethodTable* mta, MethodTable* mtb) { QCALL_CONTRACT; @@ -1816,6 +1809,21 @@ extern "C" BOOL QCALLTYPE MethodTable_AreTypesEquivalent(MethodTable* mta, Metho return bResult; } +extern "C" BOOL QCALLTYPE TypeHandle_CanCastTo(void* fromTypeHnd, void* toTypeHnd) +{ + QCALL_CONTRACT; + + BOOL ret = false; + + BEGIN_QCALL; + + ret = TypeHandle::FromPtr(fromTypeHnd).CanCastTo(TypeHandle::FromPtr(toTypeHnd)); + + END_QCALL; + + return ret; +} + static MethodTable * g_pStreamMT; static WORD g_slotBeginRead, g_slotEndRead; static WORD g_slotBeginWrite, g_slotEndWrite; diff --git a/src/coreclr/vm/comutilnative.h b/src/coreclr/vm/comutilnative.h index ad51908267489..fb1038d7f3f5d 100644 --- a/src/coreclr/vm/comutilnative.h +++ b/src/coreclr/vm/comutilnative.h @@ -245,11 +245,11 @@ class MethodTableNative { public: static FCDECL1(UINT32, GetNumInstanceFieldBytes, MethodTable* mt); static FCDECL1(CorElementType, GetVerifierCorElementType, MethodTable* mt); - static FCDECL2(FC_BOOL_RET, CanCastTo, void* fromType, void* toType); }; extern "C" BOOL QCALLTYPE MethodTable_AreTypesEquivalent(MethodTable* mta, MethodTable* mtb); extern "C" BOOL QCALLTYPE MethodTable_CanCompareBitsOrUseFastGetHashCode(MethodTable* mt); +extern "C" BOOL QCALLTYPE TypeHandle_CanCastTo(void* fromTypeHnd, void* toTypeHnd); extern "C" INT32 QCALLTYPE ValueType_GetHashCodeStrategy(MethodTable* mt, QCall::ObjectHandleOnStack objHandle, UINT32* fieldOffset, UINT32* fieldSize, MethodTable** fieldMT); class StreamNative { diff --git a/src/coreclr/vm/ecalllist.h b/src/coreclr/vm/ecalllist.h index b33ad43eae218..3ad62b22824ac 100644 --- a/src/coreclr/vm/ecalllist.h +++ b/src/coreclr/vm/ecalllist.h @@ -449,7 +449,6 @@ FCFuncEnd() FCFuncStart(gMethodTableFuncs) FCFuncElement("GetNumInstanceFieldBytes", MethodTableNative::GetNumInstanceFieldBytes) FCFuncElement("GetVerifierCorElementType", MethodTableNative::GetVerifierCorElementType) - FCFuncElement("CanCastTo_NoCacheLookup", MethodTableNative::CanCastTo) FCFuncEnd() FCFuncStart(gStubHelperFuncs) diff --git a/src/coreclr/vm/qcallentrypoints.cpp b/src/coreclr/vm/qcallentrypoints.cpp index a2c96af36b6a2..05a62c15df1eb 100644 --- a/src/coreclr/vm/qcallentrypoints.cpp +++ b/src/coreclr/vm/qcallentrypoints.cpp @@ -103,6 +103,7 @@ static const Entry s_QCall[] = DllImportEntry(QCall_FreeGCHandleForTypeHandle) DllImportEntry(MethodTable_AreTypesEquivalent) DllImportEntry(MethodTable_CanCompareBitsOrUseFastGetHashCode) + DllImportEntry(TypeHandle_CanCastTo) DllImportEntry(ValueType_GetHashCodeStrategy) DllImportEntry(RuntimeTypeHandle_MakePointer) DllImportEntry(RuntimeTypeHandle_MakeByRef) From 93ec9d8477c471c1a90634d04768676b1d40d574 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Fri, 31 May 2024 20:48:06 +0800 Subject: [PATCH 21/51] Remove ThrowHelper usages that not in hot path --- .../src/System/Array.CoreCLR.cs | 12 ++++----- .../RuntimeHelpers.CoreCLR.cs | 12 ++++----- .../src/System/ThrowHelper.cs | 27 ------------------- 3 files changed, 11 insertions(+), 40 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs index f8200f16d1887..7c3cad7d86637 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs @@ -121,7 +121,7 @@ private static unsafe void CopySlow(Array sourceArray, int sourceIndex, Array de Debug.Assert(sourceArray.Rank == destinationArray.Rank); if (assignType == ArrayAssignType.WrongType) - ThrowHelper.ThrowArrayTypeMismatchException_CantAssignType(); + throw new ArrayTypeMismatchException(SR.ArrayTypeMismatch_CantAssignType); if (length > 0) { @@ -250,7 +250,7 @@ private static unsafe void CopyImplUnBoxEachElement(Array sourceArray, int sourc } else if (obj is null || RuntimeHelpers.GetMethodTable(obj) != pDestMT) { - ThrowHelper.ThrowInvalidCastException_DownCastArrayElement(); + throw new InvalidCastException(SR.InvalidCast_DownCastArrayElement); } else if (pDestMT->ContainsGCPointers) { @@ -679,9 +679,7 @@ private unsafe void InternalSetValue(object? value, nint flattenedIndex) else if (!pElementMethodTable->IsValueType) { if (CastHelpers.IsInstanceOfAny(pElementMethodTable, value) == null) - { - ThrowHelper.ThrowInvalidCastException_StoreArrayElement(); - } + throw new InvalidCastException(SR.InvalidCast_StoreArrayElement); ref object? elementRef = ref Unsafe.As(ref arrayDataRef); ref object? offsetElementRef = ref Unsafe.Add(ref elementRef, (nuint)flattenedIndex); @@ -715,11 +713,11 @@ private unsafe void InternalSetValue(object? value, nint flattenedIndex) CorElementType targetType = pElementMethodTable->GetVerifierCorElementType(); if (!srcType.IsPrimitiveType() || !targetType.IsPrimitiveType() || !pElementMethodTable->IsTruePrimitive) - ThrowHelper.ThrowInvalidCastException_StoreArrayElement(); + throw new InvalidCastException(SR.InvalidCast_StoreArrayElement); // Get a properly widened type if (!RuntimeHelpers.CanPrimitiveWiden(srcType, targetType)) - ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_PrimitiveWiden); + throw new ArgumentException(SR.Arg_PrimWiden); PrimitiveWiden(ref value.GetRawData(), ref offsetDataRef, srcType, targetType); } diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs index cd1dc4dc6472f..51c60b74f4168 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs @@ -22,7 +22,7 @@ public static unsafe void InitializeArray(Array array, RuntimeFieldHandle fldHan ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if ((RuntimeFieldHandle.GetAttributes(fldInfo.Value) & FieldAttributes.HasFieldRVA) == 0) - ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_BadFieldForInitializeArray); + throw new ArgumentException(SR.Argument_BadFieldForInitializeArray); // Note that we do not check that the field is actually in the PE file that is initializing // the array. Basically the data being published is can be accessed by anyone with the proper @@ -30,7 +30,7 @@ public static unsafe void InitializeArray(Array array, RuntimeFieldHandle fldHan // snooping) if (!array.GetCorElementTypeOfElementType().IsPrimitiveType()) // Enum is included - ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_MustBePrimitiveArray); + throw new ArgumentException(SR.Argument_MustBePrimitiveArray); MethodTable* pMT = GetMethodTable(array); nuint totalSize = pMT->ComponentSize * array.NativeLength; @@ -39,7 +39,7 @@ public static unsafe void InitializeArray(Array array, RuntimeFieldHandle fldHan // make certain you don't go off the end of the rva static if (totalSize > size) - ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_BadFieldForInitializeArray); + throw new ArgumentException(SR.Argument_BadFieldForInitializeArray); void* src = (void*)RuntimeFieldHandle.GetStaticFieldAddress(fldInfo); ref byte dst = ref MemoryMarshal.GetArrayDataReference(array); @@ -87,20 +87,20 @@ public static unsafe void InitializeArray(Array array, RuntimeFieldHandle fldHan IRuntimeFieldInfo fldInfo = fldHandle.GetRuntimeFieldInfo(); if ((RuntimeFieldHandle.GetAttributes(fldInfo.Value) & FieldAttributes.HasFieldRVA) == 0) - ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_BadFieldForInitializeArray); + throw new ArgumentException(SR.Argument_BadFieldForInitializeArray); TypeHandle th = new TypeHandle((void*)targetTypeHandle.Value); Debug.Assert(!th.IsTypeDesc); // TypeDesc can't be used as generic parameter if (!th.GetVerifierCorElementType().IsPrimitiveType()) // Enum is included - ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_MustBePrimitiveArray); + throw new ArgumentException(SR.Argument_MustBePrimitiveArray); uint totalSize = RuntimeFieldHandle.GetFieldSize(new QCallFieldHandle(ref fldInfo)); uint targetTypeSize = th.AsMethodTable()->GetNumInstanceFieldBytes(); IntPtr data = RuntimeFieldHandle.GetStaticFieldAddress(fldInfo); if (data % targetTypeSize != 0) - ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_BadFieldForInitializeArray); + throw new ArgumentException(SR.Argument_BadFieldForInitializeArray); if (!BitConverter.IsLittleEndian) { diff --git a/src/libraries/System.Private.CoreLib/src/System/ThrowHelper.cs b/src/libraries/System.Private.CoreLib/src/System/ThrowHelper.cs index 3997d47191fb8..f742fe7a77e1c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/ThrowHelper.cs +++ b/src/libraries/System.Private.CoreLib/src/System/ThrowHelper.cs @@ -71,24 +71,6 @@ internal static void ThrowArrayTypeMismatchException() throw new ArrayTypeMismatchException(); } - [DoesNotReturn] - internal static void ThrowArrayTypeMismatchException_CantAssignType() - { - throw new ArrayTypeMismatchException(SR.ArrayTypeMismatch_CantAssignType); - } - - [DoesNotReturn] - internal static void ThrowInvalidCastException_DownCastArrayElement() - { - throw new InvalidCastException(SR.InvalidCast_DownCastArrayElement); - } - - [DoesNotReturn] - internal static void ThrowInvalidCastException_StoreArrayElement() - { - throw new InvalidCastException(SR.InvalidCast_StoreArrayElement); - } - [DoesNotReturn] internal static void ThrowInvalidTypeWithPointersNotSupported(Type targetType) { @@ -1250,12 +1232,6 @@ private static string GetResourceString(ExceptionResource resource) return SR.Format_ExpectedAsciiDigit; case ExceptionResource.Argument_HasToBeArrayClass: return SR.Argument_HasToBeArrayClass; - case ExceptionResource.Arg_PrimitiveWiden: - return SR.Arg_PrimWiden; - case ExceptionResource.Argument_MustBePrimitiveArray: - return SR.Argument_MustBePrimitiveArray; - case ExceptionResource.Argument_BadFieldForInitializeArray: - return SR.Argument_BadFieldForInitializeArray; default: Debug.Fail("The enum value is not defined, please check the ExceptionResource Enum."); return ""; @@ -1452,8 +1428,5 @@ internal enum ExceptionResource Format_UnclosedFormatItem, Format_ExpectedAsciiDigit, Argument_HasToBeArrayClass, - Arg_PrimitiveWiden, - Argument_MustBePrimitiveArray, - Argument_BadFieldForInitializeArray, } } From 481e4d47d1000ff3e418b5c145316ff3c891f9ff Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Thu, 6 Jun 2024 20:42:50 +0800 Subject: [PATCH 22/51] Revert the known broken InternalSetValue --- .../src/System/Array.CoreCLR.cs | 94 +------------------ .../Runtime/CompilerServices/CastHelpers.cs | 2 +- .../classlibnative/bcltype/arraynative.cpp | 87 +++++++++++++++++ .../classlibnative/bcltype/arraynative.h | 9 +- src/coreclr/vm/ecalllist.h | 5 + 5 files changed, 103 insertions(+), 94 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs index b84c9aec7d68f..c3cf411bc87cc 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs @@ -633,98 +633,8 @@ private unsafe nint GetFlattenedIndex(ReadOnlySpan indices) return result; } - private unsafe void InternalSetValue(object? value, nint flattenedIndex) - { - MethodTable* pMethodTable = RuntimeHelpers.GetMethodTable(this); - - TypeHandle arrayElementTypeHandle = pMethodTable->GetArrayElementTypeHandle(); - - // Legacy behavior (this handles pointers and function pointers) - if (arrayElementTypeHandle.IsTypeDesc) - { - ThrowHelper.ThrowNotSupportedException(ExceptionResource.Arg_TypeNotSupported); - } - - Debug.Assert((nuint)flattenedIndex < NativeLength); - - ref byte arrayDataRef = ref MemoryMarshal.GetArrayDataReference(this); - - MethodTable* pElementMethodTable = arrayElementTypeHandle.AsMethodTable(); - - if (value == null) - { - // Null is the universal zero... - if (pElementMethodTable->IsValueType) - { - ref byte offsetDataRef = ref Unsafe.Add(ref arrayDataRef, flattenedIndex * pMethodTable->ComponentSize); - if (pElementMethodTable->ContainsGCPointers) - SpanHelpers.ClearWithReferences(ref Unsafe.As(ref offsetDataRef), pElementMethodTable->GetNumInstanceFieldBytes()); - else - SpanHelpers.ClearWithoutReferences(ref offsetDataRef, pElementMethodTable->GetNumInstanceFieldBytes()); - } - else - { - ref object? elementRef = ref Unsafe.As(ref arrayDataRef); - ref object? offsetElementRef = ref Unsafe.Add(ref elementRef, (nuint)flattenedIndex); - offsetElementRef = null; - } - } - else if (TypeHandle.AreSameType(arrayElementTypeHandle, TypeHandle.TypeHandleOf())) - { - // Everything is compatible with Object - ref object? elementRef = ref Unsafe.As(ref arrayDataRef); - ref object? offsetElementRef = ref Unsafe.Add(ref elementRef, (nuint)flattenedIndex); - offsetElementRef = value; - } - else if (!pElementMethodTable->IsValueType) - { - if (CastHelpers.IsInstanceOfAny(pElementMethodTable, value) == null) - throw new InvalidCastException(SR.InvalidCast_StoreArrayElement); - - ref object? elementRef = ref Unsafe.As(ref arrayDataRef); - ref object? offsetElementRef = ref Unsafe.Add(ref elementRef, (nuint)flattenedIndex); - offsetElementRef = value; - } - else - { - // value class or primitive type - - ref byte offsetDataRef = ref Unsafe.Add(ref arrayDataRef, flattenedIndex * pMethodTable->ComponentSize); - if (CastHelpers.IsInstanceOfAny(pElementMethodTable, value) != null) - { - if (pElementMethodTable->IsNullable) - { - RuntimeHelpers.Unbox_Nullable(ref offsetDataRef, pElementMethodTable, value); - } - else if (pElementMethodTable->ContainsGCPointers) - { - Buffer.BulkMoveWithWriteBarrier(ref offsetDataRef, ref value.GetRawData(), pElementMethodTable->GetNumInstanceFieldBytes()); - } - else - { - SpanHelpers.Memmove(ref offsetDataRef, ref value.GetRawData(), pElementMethodTable->GetNumInstanceFieldBytes()); - } - } - else - { - // Allow enum -> primitive conversion, disallow primitive -> enum conversion - MethodTable* thSrc = RuntimeHelpers.GetMethodTable(value); - CorElementType srcType = thSrc->GetVerifierCorElementType(); - CorElementType targetType = pElementMethodTable->GetVerifierCorElementType(); - - if (!srcType.IsPrimitiveType() || !targetType.IsPrimitiveType() || !pElementMethodTable->IsTruePrimitive) - throw new InvalidCastException(SR.InvalidCast_StoreArrayElement); - - // Get a properly widened type - if (!RuntimeHelpers.CanPrimitiveWiden(srcType, targetType)) - throw new ArgumentException(SR.Arg_PrimWiden); - - PrimitiveWiden(ref value.GetRawData(), ref offsetDataRef, srcType, targetType); - } - } - - GC.KeepAlive(this); // Keep the method table alive - } + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void InternalSetValue(object? value, nint flattenedIndex); public int Length => checked((int)Unsafe.As(this).Length); diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/CastHelpers.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/CastHelpers.cs index 14c8a959cda5b..0c640dd1c2f0a 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/CastHelpers.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/CastHelpers.cs @@ -29,7 +29,7 @@ internal static unsafe class CastHelpers // Unlike the IsInstanceOfInterface and IsInstanceOfClass functions, // this test must deal with all kinds of type tests [DebuggerHidden] - internal static object? IsInstanceOfAny(void* toTypeHnd, object? obj) + private static object? IsInstanceOfAny(void* toTypeHnd, object? obj) { if (obj != null) { diff --git a/src/coreclr/classlibnative/bcltype/arraynative.cpp b/src/coreclr/classlibnative/bcltype/arraynative.cpp index 246c539827607..f44560b17a72d 100644 --- a/src/coreclr/classlibnative/bcltype/arraynative.cpp +++ b/src/coreclr/classlibnative/bcltype/arraynative.cpp @@ -195,3 +195,90 @@ void QCALLTYPE Array_CreateInstance(QCall::TypeHandle pTypeHnd, INT32 rank, INT3 Done: ; END_QCALL; } + +FCIMPL3(void, ArrayNative::SetValue, ArrayBase* refThisUNSAFE, Object* objUNSAFE, INT_PTR flattenedIndex) +{ + FCALL_CONTRACT; + + BASEARRAYREF refThis(refThisUNSAFE); + OBJECTREF obj(objUNSAFE); + + TypeHandle arrayElementType = refThis->GetArrayElementTypeHandle(); + + // Legacy behavior (this handles pointers and function pointers) + if (arrayElementType.IsTypeDesc()) + { + FCThrowResVoid(kNotSupportedException, W("NotSupported_Type")); + } + + _ASSERTE((SIZE_T)flattenedIndex < refThis->GetNumComponents()); + + MethodTable* pElementTypeMT = arrayElementType.GetMethodTable(); + PREFIX_ASSUME(NULL != pElementTypeMT); + + void* pData = refThis->GetDataPtr() + flattenedIndex * refThis->GetComponentSize(); + + if (obj == NULL) + { + // Null is the universal zero... + if (pElementTypeMT->IsValueType()) + InitValueClass(pData,pElementTypeMT); + else + ClearObjectReference((OBJECTREF*)pData); + } + else + if (arrayElementType == TypeHandle(g_pObjectClass)) + { + // Everything is compatible with Object + SetObjectReference((OBJECTREF*)pData,(OBJECTREF)obj); + } + else + if (!pElementTypeMT->IsValueType()) + { + if (ObjIsInstanceOfCached(OBJECTREFToObject(obj), arrayElementType) != TypeHandle::CanCast) + { + HELPER_METHOD_FRAME_BEGIN_2(refThis, obj); + + if (!ObjIsInstanceOf(OBJECTREFToObject(obj), arrayElementType)) + COMPlusThrow(kInvalidCastException,W("InvalidCast_StoreArrayElement")); + + HELPER_METHOD_FRAME_END(); + + // Refresh pData in case GC moved objects around + pData = refThis->GetDataPtr() + flattenedIndex * refThis->GetComponentSize(); + } + + SetObjectReference((OBJECTREF*)pData,obj); + } + else + { + // value class or primitive type + + if (!pElementTypeMT->UnBoxInto(pData, obj)) + { + HELPER_METHOD_FRAME_BEGIN_2(refThis, obj); + + ARG_SLOT value = 0; + + // Allow enum -> primitive conversion, disallow primitive -> enum conversion + TypeHandle thSrc = obj->GetTypeHandle(); + CorElementType srcType = thSrc.GetVerifierCorElementType(); + CorElementType targetType = arrayElementType.GetSignatureCorElementType(); + + if (!InvokeUtil::IsPrimitiveType(srcType) || !InvokeUtil::IsPrimitiveType(targetType)) + COMPlusThrow(kInvalidCastException, W("InvalidCast_StoreArrayElement")); + + // Get a properly widened type + InvokeUtil::CreatePrimitiveValue(targetType,srcType,obj,&value); + + // Refresh pData in case GC moved objects around + pData = refThis->GetDataPtr() + flattenedIndex * refThis->GetComponentSize(); + + UINT cbSize = CorTypeInfo::Size(targetType); + memcpyNoGCRefs(pData, ArgSlotEndiannessFixup(&value, cbSize), cbSize); + + HELPER_METHOD_FRAME_END(); + } + } +} +FCIMPLEND diff --git a/src/coreclr/classlibnative/bcltype/arraynative.h b/src/coreclr/classlibnative/bcltype/arraynative.h index 5dd3570ce5cbb..0c03df1c2841c 100644 --- a/src/coreclr/classlibnative/bcltype/arraynative.h +++ b/src/coreclr/classlibnative/bcltype/arraynative.h @@ -13,7 +13,14 @@ #ifndef _ARRAYNATIVE_H_ #define _ARRAYNATIVE_H_ -#include "qcall.h" +#include "fcall.h" + +class ArrayNative +{ +public: + // This set of methods will set a value in an array + static FCDECL3(void, SetValue, ArrayBase* refThisUNSAFE, Object* objUNSAFE, INT_PTR flattenedIndex); +}; extern "C" void QCALLTYPE Array_CreateInstance(QCall::TypeHandle pTypeHnd, INT32 rank, INT32* pLengths, INT32* pBounds, BOOL createFromArrayType, QCall::ObjectHandleOnStack retArray); extern "C" PCODE QCALLTYPE Array_GetElementConstructorEntrypoint(QCall::TypeHandle pArrayTypeHnd); diff --git a/src/coreclr/vm/ecalllist.h b/src/coreclr/vm/ecalllist.h index 3ad62b22824ac..1172101b374a9 100644 --- a/src/coreclr/vm/ecalllist.h +++ b/src/coreclr/vm/ecalllist.h @@ -359,6 +359,10 @@ FCFuncStart(gCastHelpers) FCFuncElement("WriteBarrier", ::WriteBarrier_Helper) FCFuncEnd() +FCFuncStart(gArrayFuncs) + FCFuncElement("InternalSetValue", ArrayNative::SetValue) +FCFuncEnd() + FCFuncStart(gBufferFuncs) FCFuncElement("__BulkMoveWithWriteBarrier", Buffer::BulkMoveWithWriteBarrier) FCFuncEnd() @@ -531,6 +535,7 @@ FCFuncEnd() // Note these have to remain sorted by name:namespace pair (Assert will wack you if you don't) // The sorting is case-sensitive +FCClassElement("Array", "System", gArrayFuncs) FCClassElement("AssemblyLoadContext", "System.Runtime.Loader", gAssemblyLoadContextFuncs) FCClassElement("Buffer", "System", gBufferFuncs) FCClassElement("CastHelpers", "System.Runtime.CompilerServices", gCastHelpers) From a266a30ba7606bc0fcbf44a019b1e4acde81dfca Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Thu, 6 Jun 2024 20:53:19 +0800 Subject: [PATCH 23/51] Revert "Revert the known broken InternalSetValue" This reverts commit 481e4d47d1000ff3e418b5c145316ff3c891f9ff. --- .../src/System/Array.CoreCLR.cs | 94 ++++++++++++++++++- .../Runtime/CompilerServices/CastHelpers.cs | 2 +- .../classlibnative/bcltype/arraynative.cpp | 87 ----------------- .../classlibnative/bcltype/arraynative.h | 9 +- src/coreclr/vm/ecalllist.h | 5 - 5 files changed, 94 insertions(+), 103 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs index c3cf411bc87cc..b84c9aec7d68f 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs @@ -633,8 +633,98 @@ private unsafe nint GetFlattenedIndex(ReadOnlySpan indices) return result; } - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void InternalSetValue(object? value, nint flattenedIndex); + private unsafe void InternalSetValue(object? value, nint flattenedIndex) + { + MethodTable* pMethodTable = RuntimeHelpers.GetMethodTable(this); + + TypeHandle arrayElementTypeHandle = pMethodTable->GetArrayElementTypeHandle(); + + // Legacy behavior (this handles pointers and function pointers) + if (arrayElementTypeHandle.IsTypeDesc) + { + ThrowHelper.ThrowNotSupportedException(ExceptionResource.Arg_TypeNotSupported); + } + + Debug.Assert((nuint)flattenedIndex < NativeLength); + + ref byte arrayDataRef = ref MemoryMarshal.GetArrayDataReference(this); + + MethodTable* pElementMethodTable = arrayElementTypeHandle.AsMethodTable(); + + if (value == null) + { + // Null is the universal zero... + if (pElementMethodTable->IsValueType) + { + ref byte offsetDataRef = ref Unsafe.Add(ref arrayDataRef, flattenedIndex * pMethodTable->ComponentSize); + if (pElementMethodTable->ContainsGCPointers) + SpanHelpers.ClearWithReferences(ref Unsafe.As(ref offsetDataRef), pElementMethodTable->GetNumInstanceFieldBytes()); + else + SpanHelpers.ClearWithoutReferences(ref offsetDataRef, pElementMethodTable->GetNumInstanceFieldBytes()); + } + else + { + ref object? elementRef = ref Unsafe.As(ref arrayDataRef); + ref object? offsetElementRef = ref Unsafe.Add(ref elementRef, (nuint)flattenedIndex); + offsetElementRef = null; + } + } + else if (TypeHandle.AreSameType(arrayElementTypeHandle, TypeHandle.TypeHandleOf())) + { + // Everything is compatible with Object + ref object? elementRef = ref Unsafe.As(ref arrayDataRef); + ref object? offsetElementRef = ref Unsafe.Add(ref elementRef, (nuint)flattenedIndex); + offsetElementRef = value; + } + else if (!pElementMethodTable->IsValueType) + { + if (CastHelpers.IsInstanceOfAny(pElementMethodTable, value) == null) + throw new InvalidCastException(SR.InvalidCast_StoreArrayElement); + + ref object? elementRef = ref Unsafe.As(ref arrayDataRef); + ref object? offsetElementRef = ref Unsafe.Add(ref elementRef, (nuint)flattenedIndex); + offsetElementRef = value; + } + else + { + // value class or primitive type + + ref byte offsetDataRef = ref Unsafe.Add(ref arrayDataRef, flattenedIndex * pMethodTable->ComponentSize); + if (CastHelpers.IsInstanceOfAny(pElementMethodTable, value) != null) + { + if (pElementMethodTable->IsNullable) + { + RuntimeHelpers.Unbox_Nullable(ref offsetDataRef, pElementMethodTable, value); + } + else if (pElementMethodTable->ContainsGCPointers) + { + Buffer.BulkMoveWithWriteBarrier(ref offsetDataRef, ref value.GetRawData(), pElementMethodTable->GetNumInstanceFieldBytes()); + } + else + { + SpanHelpers.Memmove(ref offsetDataRef, ref value.GetRawData(), pElementMethodTable->GetNumInstanceFieldBytes()); + } + } + else + { + // Allow enum -> primitive conversion, disallow primitive -> enum conversion + MethodTable* thSrc = RuntimeHelpers.GetMethodTable(value); + CorElementType srcType = thSrc->GetVerifierCorElementType(); + CorElementType targetType = pElementMethodTable->GetVerifierCorElementType(); + + if (!srcType.IsPrimitiveType() || !targetType.IsPrimitiveType() || !pElementMethodTable->IsTruePrimitive) + throw new InvalidCastException(SR.InvalidCast_StoreArrayElement); + + // Get a properly widened type + if (!RuntimeHelpers.CanPrimitiveWiden(srcType, targetType)) + throw new ArgumentException(SR.Arg_PrimWiden); + + PrimitiveWiden(ref value.GetRawData(), ref offsetDataRef, srcType, targetType); + } + } + + GC.KeepAlive(this); // Keep the method table alive + } public int Length => checked((int)Unsafe.As(this).Length); diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/CastHelpers.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/CastHelpers.cs index 0c640dd1c2f0a..14c8a959cda5b 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/CastHelpers.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/CastHelpers.cs @@ -29,7 +29,7 @@ internal static unsafe class CastHelpers // Unlike the IsInstanceOfInterface and IsInstanceOfClass functions, // this test must deal with all kinds of type tests [DebuggerHidden] - private static object? IsInstanceOfAny(void* toTypeHnd, object? obj) + internal static object? IsInstanceOfAny(void* toTypeHnd, object? obj) { if (obj != null) { diff --git a/src/coreclr/classlibnative/bcltype/arraynative.cpp b/src/coreclr/classlibnative/bcltype/arraynative.cpp index f44560b17a72d..246c539827607 100644 --- a/src/coreclr/classlibnative/bcltype/arraynative.cpp +++ b/src/coreclr/classlibnative/bcltype/arraynative.cpp @@ -195,90 +195,3 @@ void QCALLTYPE Array_CreateInstance(QCall::TypeHandle pTypeHnd, INT32 rank, INT3 Done: ; END_QCALL; } - -FCIMPL3(void, ArrayNative::SetValue, ArrayBase* refThisUNSAFE, Object* objUNSAFE, INT_PTR flattenedIndex) -{ - FCALL_CONTRACT; - - BASEARRAYREF refThis(refThisUNSAFE); - OBJECTREF obj(objUNSAFE); - - TypeHandle arrayElementType = refThis->GetArrayElementTypeHandle(); - - // Legacy behavior (this handles pointers and function pointers) - if (arrayElementType.IsTypeDesc()) - { - FCThrowResVoid(kNotSupportedException, W("NotSupported_Type")); - } - - _ASSERTE((SIZE_T)flattenedIndex < refThis->GetNumComponents()); - - MethodTable* pElementTypeMT = arrayElementType.GetMethodTable(); - PREFIX_ASSUME(NULL != pElementTypeMT); - - void* pData = refThis->GetDataPtr() + flattenedIndex * refThis->GetComponentSize(); - - if (obj == NULL) - { - // Null is the universal zero... - if (pElementTypeMT->IsValueType()) - InitValueClass(pData,pElementTypeMT); - else - ClearObjectReference((OBJECTREF*)pData); - } - else - if (arrayElementType == TypeHandle(g_pObjectClass)) - { - // Everything is compatible with Object - SetObjectReference((OBJECTREF*)pData,(OBJECTREF)obj); - } - else - if (!pElementTypeMT->IsValueType()) - { - if (ObjIsInstanceOfCached(OBJECTREFToObject(obj), arrayElementType) != TypeHandle::CanCast) - { - HELPER_METHOD_FRAME_BEGIN_2(refThis, obj); - - if (!ObjIsInstanceOf(OBJECTREFToObject(obj), arrayElementType)) - COMPlusThrow(kInvalidCastException,W("InvalidCast_StoreArrayElement")); - - HELPER_METHOD_FRAME_END(); - - // Refresh pData in case GC moved objects around - pData = refThis->GetDataPtr() + flattenedIndex * refThis->GetComponentSize(); - } - - SetObjectReference((OBJECTREF*)pData,obj); - } - else - { - // value class or primitive type - - if (!pElementTypeMT->UnBoxInto(pData, obj)) - { - HELPER_METHOD_FRAME_BEGIN_2(refThis, obj); - - ARG_SLOT value = 0; - - // Allow enum -> primitive conversion, disallow primitive -> enum conversion - TypeHandle thSrc = obj->GetTypeHandle(); - CorElementType srcType = thSrc.GetVerifierCorElementType(); - CorElementType targetType = arrayElementType.GetSignatureCorElementType(); - - if (!InvokeUtil::IsPrimitiveType(srcType) || !InvokeUtil::IsPrimitiveType(targetType)) - COMPlusThrow(kInvalidCastException, W("InvalidCast_StoreArrayElement")); - - // Get a properly widened type - InvokeUtil::CreatePrimitiveValue(targetType,srcType,obj,&value); - - // Refresh pData in case GC moved objects around - pData = refThis->GetDataPtr() + flattenedIndex * refThis->GetComponentSize(); - - UINT cbSize = CorTypeInfo::Size(targetType); - memcpyNoGCRefs(pData, ArgSlotEndiannessFixup(&value, cbSize), cbSize); - - HELPER_METHOD_FRAME_END(); - } - } -} -FCIMPLEND diff --git a/src/coreclr/classlibnative/bcltype/arraynative.h b/src/coreclr/classlibnative/bcltype/arraynative.h index 0c03df1c2841c..5dd3570ce5cbb 100644 --- a/src/coreclr/classlibnative/bcltype/arraynative.h +++ b/src/coreclr/classlibnative/bcltype/arraynative.h @@ -13,14 +13,7 @@ #ifndef _ARRAYNATIVE_H_ #define _ARRAYNATIVE_H_ -#include "fcall.h" - -class ArrayNative -{ -public: - // This set of methods will set a value in an array - static FCDECL3(void, SetValue, ArrayBase* refThisUNSAFE, Object* objUNSAFE, INT_PTR flattenedIndex); -}; +#include "qcall.h" extern "C" void QCALLTYPE Array_CreateInstance(QCall::TypeHandle pTypeHnd, INT32 rank, INT32* pLengths, INT32* pBounds, BOOL createFromArrayType, QCall::ObjectHandleOnStack retArray); extern "C" PCODE QCALLTYPE Array_GetElementConstructorEntrypoint(QCall::TypeHandle pArrayTypeHnd); diff --git a/src/coreclr/vm/ecalllist.h b/src/coreclr/vm/ecalllist.h index 1172101b374a9..3ad62b22824ac 100644 --- a/src/coreclr/vm/ecalllist.h +++ b/src/coreclr/vm/ecalllist.h @@ -359,10 +359,6 @@ FCFuncStart(gCastHelpers) FCFuncElement("WriteBarrier", ::WriteBarrier_Helper) FCFuncEnd() -FCFuncStart(gArrayFuncs) - FCFuncElement("InternalSetValue", ArrayNative::SetValue) -FCFuncEnd() - FCFuncStart(gBufferFuncs) FCFuncElement("__BulkMoveWithWriteBarrier", Buffer::BulkMoveWithWriteBarrier) FCFuncEnd() @@ -535,7 +531,6 @@ FCFuncEnd() // Note these have to remain sorted by name:namespace pair (Assert will wack you if you don't) // The sorting is case-sensitive -FCClassElement("Array", "System", gArrayFuncs) FCClassElement("AssemblyLoadContext", "System.Runtime.Loader", gAssemblyLoadContextFuncs) FCClassElement("Buffer", "System", gBufferFuncs) FCClassElement("CastHelpers", "System.Runtime.CompilerServices", gCastHelpers) From b8e4584024f328eb4d4d3c9af3acf7a611c95042 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Sat, 8 Jun 2024 02:08:03 +0800 Subject: [PATCH 24/51] Fix heap overwrite --- src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs index b84c9aec7d68f..d72672e7238be 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs @@ -658,7 +658,7 @@ private unsafe void InternalSetValue(object? value, nint flattenedIndex) { ref byte offsetDataRef = ref Unsafe.Add(ref arrayDataRef, flattenedIndex * pMethodTable->ComponentSize); if (pElementMethodTable->ContainsGCPointers) - SpanHelpers.ClearWithReferences(ref Unsafe.As(ref offsetDataRef), pElementMethodTable->GetNumInstanceFieldBytes()); + SpanHelpers.ClearWithReferences(ref Unsafe.As(ref offsetDataRef), pElementMethodTable->GetNumInstanceFieldBytes() / (nuint)sizeof(IntPtr)); else SpanHelpers.ClearWithoutReferences(ref offsetDataRef, pElementMethodTable->GetNumInstanceFieldBytes()); } From 5465a97b2d1b70ffcad87aea7785a5a42794bd1a Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Sun, 9 Jun 2024 17:52:31 +0800 Subject: [PATCH 25/51] Add disabled test for RVA field reflection --- .../System.Reflection.Tests/FieldInfoTests.cs | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/src/libraries/System.Runtime/tests/System.Reflection.Tests/FieldInfoTests.cs b/src/libraries/System.Runtime/tests/System.Reflection.Tests/FieldInfoTests.cs index d854e19c71ade..fbc97e4f17dad 100644 --- a/src/libraries/System.Runtime/tests/System.Reflection.Tests/FieldInfoTests.cs +++ b/src/libraries/System.Runtime/tests/System.Reflection.Tests/FieldInfoTests.cs @@ -5,6 +5,8 @@ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; using Xunit; #pragma warning disable 0414 @@ -121,6 +123,30 @@ public void GetValueWithFunctionPointers(Type type, string name, object obj, obj Assert.Equal(expected, fieldInfo.GetValue(obj)); } + [Fact] + [ActiveIssue("https://github.com/dotnet/runtime/issues/103207")] + public void GetValueFromRvaField() + { + byte[] valueArray = new byte[] { 1, 2, 3, 4, 5 }; + + // Roslyn uses SHA256 of raw data as data field name + FieldInfo fieldInfo = GetField( + typeof(FieldInfoTests).Assembly.GetType(""), + "74F81FE167D99B4CB41D6D0CCDA82278CAEE9F3E2F25D5E5A3936FF3DCEC60D0"); + Assert.NotNull(fieldInfo); + Assert.True(fieldInfo.IsStatic); + Assert.True((fieldInfo.Attributes & FieldAttributes.HasFieldRVA) != 0); + + for (int i = 0; i < 5; i++) + { + // FieldAccessor uses slow path until the class is initialized. + // Make sure subsequent invocations also succeed. + + object value = fieldInfo.GetValue(null); + Assert.Equal(valueArray, MemoryMarshal.CreateReadOnlySpan(ref Unsafe.As(ref value).Data, valueArray.Length)); + } + } + [Fact] public void GetAndSetValueTypeFromStatic() { @@ -839,5 +865,10 @@ public static class SettingsForMyTypeThatThrowsInClassInitializer { public static bool s_shouldThrow = true; } + + private class RawData + { + public byte Data; + } } } From 4ce4f5118c20f438c1e33a5a73d626f1180c86d5 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Tue, 11 Jun 2024 01:14:42 +0800 Subject: [PATCH 26/51] Push back changes around IsSimpleCopy and CanAssignArrayType --- .../src/System/Array.CoreCLR.cs | 122 +++----------- .../RuntimeHelpers.CoreCLR.cs | 28 --- .../classlibnative/bcltype/arraynative.cpp | 159 ++++++++++++++++++ .../classlibnative/bcltype/arraynative.h | 8 + src/coreclr/vm/comutilnative.cpp | 15 -- src/coreclr/vm/comutilnative.h | 1 - src/coreclr/vm/ecalllist.h | 5 + src/coreclr/vm/qcallentrypoints.cpp | 2 +- 8 files changed, 197 insertions(+), 143 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs index d72672e7238be..78b3f7dd0b731 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs @@ -62,10 +62,7 @@ private static unsafe void CopyImpl(Array sourceArray, int sourceIndex, Array de if ((uint)(destinationIndex + length) > destinationArray.NativeLength) throw new ArgumentException(SR.Arg_LongerThanDestArray, nameof(destinationArray)); - ArrayAssignType assignType = ArrayAssignType.WrongType; - - if (sourceArray.GetType() == destinationArray.GetType() - || (assignType = CanAssignArrayType(sourceArray, destinationArray)) == ArrayAssignType.SimpleCopy) + if (sourceArray.GetType() == destinationArray.GetType() || IsSimpleCopy(sourceArray, destinationArray)) { MethodTable* pMT = RuntimeHelpers.GetMethodTable(sourceArray); @@ -89,57 +86,44 @@ private static unsafe void CopyImpl(Array sourceArray, int sourceIndex, Array de throw new ArrayTypeMismatchException(SR.ArrayTypeMismatch_ConstrainedCopy); // Rare - CopySlow(sourceArray, sourceIndex, destinationArray, destinationIndex, length, assignType); + CopySlow(sourceArray, sourceIndex, destinationArray, destinationIndex, length); } - private static CorElementType GetNormalizedIntegralArrayElementType(CorElementType elementType) - { - Debug.Assert(elementType.IsPrimitiveType()); - - // Array Primitive types such as E_T_I4 and E_T_U4 are interchangeable - // Enums with interchangeable underlying types are interchangeable - // BOOL is NOT interchangeable with I1/U1, neither CHAR -- with I2/U2 - switch (elementType) - { - case CorElementType.ELEMENT_TYPE_U1: - case CorElementType.ELEMENT_TYPE_U2: - case CorElementType.ELEMENT_TYPE_U4: - case CorElementType.ELEMENT_TYPE_U8: - case CorElementType.ELEMENT_TYPE_U: - return elementType - 1; // normalize to signed type - default: - return elementType; - } - } + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool IsSimpleCopy(Array sourceArray, Array destinationArray); // Reliability-wise, this method will either possibly corrupt your // instance & might fail when called from within a CER, or if the // reliable flag is true, it will either always succeed or always // throw an exception with no side effects. - private static unsafe void CopySlow(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length, ArrayAssignType assignType) + private static unsafe void CopySlow(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length) { Debug.Assert(sourceArray.Rank == destinationArray.Rank); - if (assignType == ArrayAssignType.WrongType) + void* srcTH = RuntimeHelpers.GetMethodTable(sourceArray)->ElementType; + void* destTH = RuntimeHelpers.GetMethodTable(destinationArray)->ElementType; + AssignArrayEnum r = CanAssignArrayType(srcTH, destTH); + + if (r == AssignArrayEnum.AssignWrongType) throw new ArrayTypeMismatchException(SR.ArrayTypeMismatch_CantAssignType); if (length > 0) { - switch (assignType) + switch (r) { - case ArrayAssignType.UnboxValueClass: + case AssignArrayEnum.AssignUnboxValueClass: CopyImplUnBoxEachElement(sourceArray, sourceIndex, destinationArray, destinationIndex, length); break; - case ArrayAssignType.BoxValueClassOrPrimitive: + case AssignArrayEnum.AssignBoxValueClassOrPrimitive: CopyImplBoxEachElement(sourceArray, sourceIndex, destinationArray, destinationIndex, length); break; - case ArrayAssignType.MustCast: + case AssignArrayEnum.AssignMustCast: CopyImplCastCheckEachElement(sourceArray, sourceIndex, destinationArray, destinationIndex, length); break; - case ArrayAssignType.PrimitiveWiden: + case AssignArrayEnum.AssignPrimitiveWiden: CopyImplPrimitiveWiden(sourceArray, sourceIndex, destinationArray, destinationIndex, length); break; @@ -150,76 +134,18 @@ private static unsafe void CopySlow(Array sourceArray, int sourceIndex, Array de } } - private enum ArrayAssignType + // Must match the definition in arraynative.cpp + private enum AssignArrayEnum { - SimpleCopy, - WrongType, - MustCast, - BoxValueClassOrPrimitive, - UnboxValueClass, - PrimitiveWiden, + AssignWrongType, + AssignMustCast, + AssignBoxValueClassOrPrimitive, + AssignUnboxValueClass, + AssignPrimitiveWiden, } - private static unsafe ArrayAssignType CanAssignArrayType(Array sourceArray, Array destinationArray) - { - TypeHandle srcTH = RuntimeHelpers.GetMethodTable(sourceArray)->GetArrayElementTypeHandle(); - TypeHandle destTH = RuntimeHelpers.GetMethodTable(destinationArray)->GetArrayElementTypeHandle(); - - if (TypeHandle.AreSameType(srcTH, destTH)) // This check kicks for different array kind or dimensions - return ArrayAssignType.SimpleCopy; - - // Value class boxing - if (srcTH.IsValueType && !destTH.IsValueType) - { - if (srcTH.CanCastTo(destTH)) - return ArrayAssignType.BoxValueClassOrPrimitive; - else - return ArrayAssignType.WrongType; - } - - // Value class unboxing. - if (!srcTH.IsValueType && destTH.IsValueType) - { - if (srcTH.CanCastTo(destTH)) - return ArrayAssignType.UnboxValueClass; - else if (destTH.CanCastTo(srcTH)) // V extends IV. Copying from IV to V, or Object to V. - return ArrayAssignType.UnboxValueClass; - else - return ArrayAssignType.WrongType; - } - - CorElementType srcElType = srcTH.GetVerifierCorElementType(); - CorElementType destElType = destTH.GetVerifierCorElementType(); - - // Copying primitives from one type to another - if (srcElType.IsPrimitiveType() && destElType.IsPrimitiveType()) - { - if (GetNormalizedIntegralArrayElementType(srcElType) == GetNormalizedIntegralArrayElementType(destElType)) - return ArrayAssignType.SimpleCopy; - else if (RuntimeHelpers.CanPrimitiveWiden(srcElType, destElType)) - return ArrayAssignType.PrimitiveWiden; - else - return ArrayAssignType.WrongType; - } - - // src Object extends dest - if (srcTH.CanCastTo(destTH)) - return ArrayAssignType.SimpleCopy; - - // dest Object extends src - if (destTH.CanCastTo(srcTH)) - return ArrayAssignType.MustCast; - - // class X extends/implements src and implements dest. - if (destTH.IsInterface && srcElType != CorElementType.ELEMENT_TYPE_VALUETYPE) - return ArrayAssignType.MustCast; - - // class X implements src and extends/implements dest - if (srcTH.IsInterface && srcElType != CorElementType.ELEMENT_TYPE_VALUETYPE) - return ArrayAssignType.MustCast; - - return ArrayAssignType.WrongType; - } + [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "Array_CanAssignArrayType")] + private static unsafe partial AssignArrayEnum CanAssignArrayType(void* srcTH, void* dstTH); // Unboxes from an Object[] into a value class or primitive array. private static unsafe void CopyImplUnBoxEachElement(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs index 461922f7f017b..95de0fcc1863b 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs @@ -862,34 +862,6 @@ public static TypeHandle TypeHandleOf() public static bool AreSameType(TypeHandle left, TypeHandle right) => left.m_asTAddr == right.m_asTAddr; - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool CanCastTo(TypeHandle destTH) - { - CastResult result = CastCache.TryGet(CastHelpers.s_table!, (nuint)m_asTAddr, (nuint)destTH.m_asTAddr); - - if (result != CastResult.MaybeCast) - return result == CastResult.CanCast; - - return CanCastTo_NoCacheLookup(m_asTAddr, destTH.m_asTAddr); - } - - [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "TypeHandle_CanCastTo")] - [return: MarshalAs(UnmanagedType.Bool)] - private static partial bool CanCastTo_NoCacheLookup(void* fromTypeHnd, void* toTypeHnd); - - public bool IsValueType - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get - { - return IsTypeDesc - ? AsTypeDesc()->GetInternalCorElementType() == CorElementType.ELEMENT_TYPE_VALUETYPE - : AsMethodTable()->IsValueType; - } - } - - public bool IsInterface => !IsTypeDesc && AsMethodTable()->IsInterface; - public CorElementType GetVerifierCorElementType() => IsTypeDesc ? AsTypeDesc()->GetInternalCorElementType() : AsMethodTable()->GetVerifierCorElementType(); diff --git a/src/coreclr/classlibnative/bcltype/arraynative.cpp b/src/coreclr/classlibnative/bcltype/arraynative.cpp index 246c539827607..2e8a41a827910 100644 --- a/src/coreclr/classlibnative/bcltype/arraynative.cpp +++ b/src/coreclr/classlibnative/bcltype/arraynative.cpp @@ -36,6 +36,165 @@ extern "C" PCODE QCALLTYPE Array_GetElementConstructorEntrypoint(QCall::TypeHand return ctorEntrypoint; } + // Returns whether you can directly copy an array of srcType into destType. +FCIMPL2(FC_BOOL_RET, ArrayNative::IsSimpleCopy, ArrayBase* pSrc, ArrayBase* pDst) +{ + FCALL_CONTRACT; + + _ASSERTE(pSrc != NULL); + _ASSERTE(pDst != NULL); + + // This case is expected to be handled by the fast path + _ASSERTE(pSrc->GetMethodTable() != pDst->GetMethodTable()); + + TypeHandle srcTH = pSrc->GetMethodTable()->GetArrayElementTypeHandle(); + TypeHandle destTH = pDst->GetMethodTable()->GetArrayElementTypeHandle(); + if (srcTH == destTH) // This check kicks for different array kind or dimensions + FC_RETURN_BOOL(true); + + if (srcTH.IsValueType()) + { + // Value class boxing + if (!destTH.IsValueType()) + FC_RETURN_BOOL(false); + + const CorElementType srcElType = srcTH.GetVerifierCorElementType(); + const CorElementType destElType = destTH.GetVerifierCorElementType(); + _ASSERTE(srcElType < ELEMENT_TYPE_MAX); + _ASSERTE(destElType < ELEMENT_TYPE_MAX); + + // Copying primitives from one type to another + if (CorTypeInfo::IsPrimitiveType_NoThrow(srcElType) && CorTypeInfo::IsPrimitiveType_NoThrow(destElType)) + { + if (GetNormalizedIntegralArrayElementType(srcElType) == GetNormalizedIntegralArrayElementType(destElType)) + FC_RETURN_BOOL(true); + } + } + else + { + // Value class unboxing + if (destTH.IsValueType()) + FC_RETURN_BOOL(false); + } + + TypeHandle::CastResult r = srcTH.CanCastToCached(destTH); + if (r != TypeHandle::MaybeCast) + { + FC_RETURN_BOOL(r); + } + + struct + { + OBJECTREF src; + OBJECTREF dst; + } gc; + + gc.src = ObjectToOBJECTREF(pSrc); + gc.dst = ObjectToOBJECTREF(pDst); + + BOOL iRetVal = FALSE; + + HELPER_METHOD_FRAME_BEGIN_RET_PROTECT(gc); + iRetVal = srcTH.CanCastTo(destTH); + HELPER_METHOD_FRAME_END(); + + FC_RETURN_BOOL(iRetVal); +} +FCIMPLEND + + +// Return values for CanAssignArrayType +enum AssignArrayEnum +{ + AssignWrongType, + AssignMustCast, + AssignBoxValueClassOrPrimitive, + AssignUnboxValueClass, + AssignPrimitiveWiden, +}; + +// Returns an enum saying whether you can copy an array of srcType into destType. +static AssignArrayEnum CanAssignArrayType(const TypeHandle srcTH, const TypeHandle destTH) +{ + CONTRACTL + { + THROWS; + GC_TRIGGERS; + PRECONDITION(!srcTH.IsNull()); + PRECONDITION(!destTH.IsNull()); + } + CONTRACTL_END; + + _ASSERTE(srcTH != destTH); // Handled by fast path + + // Value class boxing + if (srcTH.IsValueType() && !destTH.IsValueType()) + { + if (srcTH.CanCastTo(destTH)) + return AssignBoxValueClassOrPrimitive; + else + return AssignWrongType; + } + + // Value class unboxing. + if (!srcTH.IsValueType() && destTH.IsValueType()) + { + if (srcTH.CanCastTo(destTH)) + return AssignUnboxValueClass; + else if (destTH.CanCastTo(srcTH)) // V extends IV. Copying from IV to V, or Object to V. + return AssignUnboxValueClass; + else + return AssignWrongType; + } + + const CorElementType srcElType = srcTH.GetVerifierCorElementType(); + const CorElementType destElType = destTH.GetVerifierCorElementType(); + _ASSERTE(srcElType < ELEMENT_TYPE_MAX); + _ASSERTE(destElType < ELEMENT_TYPE_MAX); + + // Copying primitives from one type to another + if (CorTypeInfo::IsPrimitiveType_NoThrow(srcElType) && CorTypeInfo::IsPrimitiveType_NoThrow(destElType)) + { + _ASSERTE(srcElType != destElType); // Handled by fast path + if (InvokeUtil::CanPrimitiveWiden(destElType, srcElType)) + return AssignPrimitiveWiden; + else + return AssignWrongType; + } + + // dest Object extends src + _ASSERTE(!srcTH.CanCastTo(destTH)); // Handled by fast path + + // src Object extends dest + if (destTH.CanCastTo(srcTH)) + return AssignMustCast; + + // class X extends/implements src and implements dest. + if (destTH.IsInterface() && srcElType != ELEMENT_TYPE_VALUETYPE) + return AssignMustCast; + + // class X implements src and extends/implements dest + if (srcTH.IsInterface() && destElType != ELEMENT_TYPE_VALUETYPE) + return AssignMustCast; + + return AssignWrongType; +} + +extern "C" int QCALLTYPE Array_CanAssignArrayType(void* srcTH, void* destTH) +{ + QCALL_CONTRACT; + + INT32 ret = 0; + + BEGIN_QCALL; + + ret = CanAssignArrayType(TypeHandle::FromPtr(srcTH), TypeHandle::FromPtr(destTH)); + + END_QCALL; + + return ret; +} + // // This is a GC safe variant of the memmove intrinsic. It sets the cards, and guarantees that the object references in the GC heap are diff --git a/src/coreclr/classlibnative/bcltype/arraynative.h b/src/coreclr/classlibnative/bcltype/arraynative.h index 5dd3570ce5cbb..c7ce27eb5c91b 100644 --- a/src/coreclr/classlibnative/bcltype/arraynative.h +++ b/src/coreclr/classlibnative/bcltype/arraynative.h @@ -13,9 +13,17 @@ #ifndef _ARRAYNATIVE_H_ #define _ARRAYNATIVE_H_ +#include "fcall.h" #include "qcall.h" +class ArrayNative +{ +public: + static FCDECL2(FC_BOOL_RET, IsSimpleCopy, ArrayBase* pSrc, ArrayBase* pDst); +}; + extern "C" void QCALLTYPE Array_CreateInstance(QCall::TypeHandle pTypeHnd, INT32 rank, INT32* pLengths, INT32* pBounds, BOOL createFromArrayType, QCall::ObjectHandleOnStack retArray); extern "C" PCODE QCALLTYPE Array_GetElementConstructorEntrypoint(QCall::TypeHandle pArrayTypeHnd); +extern "C" INT32 QCALLTYPE Array_CanAssignArrayType(void* srcTH, void* destTH); #endif // _ARRAYNATIVE_H_ diff --git a/src/coreclr/vm/comutilnative.cpp b/src/coreclr/vm/comutilnative.cpp index 1823ffa2c07ac..b569143bbaa51 100644 --- a/src/coreclr/vm/comutilnative.cpp +++ b/src/coreclr/vm/comutilnative.cpp @@ -1809,21 +1809,6 @@ extern "C" BOOL QCALLTYPE MethodTable_AreTypesEquivalent(MethodTable* mta, Metho return bResult; } -extern "C" BOOL QCALLTYPE TypeHandle_CanCastTo(void* fromTypeHnd, void* toTypeHnd) -{ - QCALL_CONTRACT; - - BOOL ret = false; - - BEGIN_QCALL; - - ret = TypeHandle::FromPtr(fromTypeHnd).CanCastTo(TypeHandle::FromPtr(toTypeHnd)); - - END_QCALL; - - return ret; -} - static MethodTable * g_pStreamMT; static WORD g_slotBeginRead, g_slotEndRead; static WORD g_slotBeginWrite, g_slotEndWrite; diff --git a/src/coreclr/vm/comutilnative.h b/src/coreclr/vm/comutilnative.h index fb1038d7f3f5d..74f0c7967e745 100644 --- a/src/coreclr/vm/comutilnative.h +++ b/src/coreclr/vm/comutilnative.h @@ -249,7 +249,6 @@ class MethodTableNative { extern "C" BOOL QCALLTYPE MethodTable_AreTypesEquivalent(MethodTable* mta, MethodTable* mtb); extern "C" BOOL QCALLTYPE MethodTable_CanCompareBitsOrUseFastGetHashCode(MethodTable* mt); -extern "C" BOOL QCALLTYPE TypeHandle_CanCastTo(void* fromTypeHnd, void* toTypeHnd); extern "C" INT32 QCALLTYPE ValueType_GetHashCodeStrategy(MethodTable* mt, QCall::ObjectHandleOnStack objHandle, UINT32* fieldOffset, UINT32* fieldSize, MethodTable** fieldMT); class StreamNative { diff --git a/src/coreclr/vm/ecalllist.h b/src/coreclr/vm/ecalllist.h index 3ad62b22824ac..7b866bf9bd242 100644 --- a/src/coreclr/vm/ecalllist.h +++ b/src/coreclr/vm/ecalllist.h @@ -359,6 +359,10 @@ FCFuncStart(gCastHelpers) FCFuncElement("WriteBarrier", ::WriteBarrier_Helper) FCFuncEnd() +FCFuncStart(gArrayFuncs) + FCFuncElement("IsSimpleCopy", ArrayNative::IsSimpleCopy) +FCFuncEnd() + FCFuncStart(gBufferFuncs) FCFuncElement("__BulkMoveWithWriteBarrier", Buffer::BulkMoveWithWriteBarrier) FCFuncEnd() @@ -531,6 +535,7 @@ FCFuncEnd() // Note these have to remain sorted by name:namespace pair (Assert will wack you if you don't) // The sorting is case-sensitive +FCClassElement("Array", "System", gArrayFuncs) FCClassElement("AssemblyLoadContext", "System.Runtime.Loader", gAssemblyLoadContextFuncs) FCClassElement("Buffer", "System", gBufferFuncs) FCClassElement("CastHelpers", "System.Runtime.CompilerServices", gCastHelpers) diff --git a/src/coreclr/vm/qcallentrypoints.cpp b/src/coreclr/vm/qcallentrypoints.cpp index 2ece683380ef5..7d28f0864d4cc 100644 --- a/src/coreclr/vm/qcallentrypoints.cpp +++ b/src/coreclr/vm/qcallentrypoints.cpp @@ -103,7 +103,6 @@ static const Entry s_QCall[] = DllImportEntry(QCall_FreeGCHandleForTypeHandle) DllImportEntry(MethodTable_AreTypesEquivalent) DllImportEntry(MethodTable_CanCompareBitsOrUseFastGetHashCode) - DllImportEntry(TypeHandle_CanCastTo) DllImportEntry(ValueType_GetHashCodeStrategy) DllImportEntry(RuntimeTypeHandle_MakePointer) DllImportEntry(RuntimeTypeHandle_MakeByRef) @@ -173,6 +172,7 @@ static const Entry s_QCall[] = DllImportEntry(MdUtf8String_EqualsCaseInsensitive) DllImportEntry(Array_CreateInstance) DllImportEntry(Array_GetElementConstructorEntrypoint) + DllImportEntry(Array_CanAssignArrayType) DllImportEntry(AssemblyName_InitializeAssemblySpec) DllImportEntry(AssemblyNative_GetFullName) DllImportEntry(AssemblyNative_GetLocation) From 30b7d8f6beef8abb330d4eb313d499a401fc8bb8 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Wed, 12 Jun 2024 15:29:13 +0800 Subject: [PATCH 27/51] Move PrimitiveWiden to InvokeUtils --- .../System.Private.CoreLib.csproj | 1 + .../src/System/Array.CoreCLR.cs | 156 +-------------- .../src/System/InvokeUtils.cs | 188 ++++++++++++++++++ 3 files changed, 194 insertions(+), 151 deletions(-) create mode 100644 src/coreclr/System.Private.CoreLib/src/System/InvokeUtils.cs diff --git a/src/coreclr/System.Private.CoreLib/System.Private.CoreLib.csproj b/src/coreclr/System.Private.CoreLib/System.Private.CoreLib.csproj index 1586ba4132120..fc3fccf07f71c 100644 --- a/src/coreclr/System.Private.CoreLib/System.Private.CoreLib.csproj +++ b/src/coreclr/System.Private.CoreLib/System.Private.CoreLib.csproj @@ -237,6 +237,7 @@ Common\System\Collections\Generic\ArrayBuilder.cs + diff --git a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs index 78b3f7dd0b731..c1c049bfaf0b1 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs @@ -246,155 +246,9 @@ private static unsafe void CopyImplPrimitiveWiden(Array sourceArray, int sourceI for (int i = 0; i < length; i++) { - ref byte srcElement = ref Unsafe.Add(ref srcData, (nuint)i * srcElSize); - ref byte destElement = ref Unsafe.Add(ref data, (nuint)i * destElSize); - - PrimitiveWiden(ref srcElement, ref destElement, srcElType, destElType); - } - } - - private static void PrimitiveWiden(ref byte srcElement, ref byte destElement, CorElementType srcElType, CorElementType destElType) - { - switch (srcElType) - { - case CorElementType.ELEMENT_TYPE_U1: - switch (destElType) - { - case CorElementType.ELEMENT_TYPE_CHAR: - case CorElementType.ELEMENT_TYPE_I2: - case CorElementType.ELEMENT_TYPE_U2: - Unsafe.As(ref destElement) = srcElement; break; - case CorElementType.ELEMENT_TYPE_I4: - case CorElementType.ELEMENT_TYPE_U4: - Unsafe.As(ref destElement) = srcElement; break; - case CorElementType.ELEMENT_TYPE_I8: - case CorElementType.ELEMENT_TYPE_U8: - Unsafe.As(ref destElement) = srcElement; break; - case CorElementType.ELEMENT_TYPE_R4: - Unsafe.As(ref destElement) = srcElement; break; - case CorElementType.ELEMENT_TYPE_R8: - Unsafe.As(ref destElement) = srcElement; break; - default: - Debug.Fail("Array.Copy from U1 to another type hit unsupported widening conversion"); break; - } - break; - - case CorElementType.ELEMENT_TYPE_I1: - switch (destElType) - { - case CorElementType.ELEMENT_TYPE_I2: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_I4: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_I8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R4: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - default: - Debug.Fail("Array.Copy from I1 to another type hit unsupported widening conversion"); break; - } - break; - - case CorElementType.ELEMENT_TYPE_U2: - case CorElementType.ELEMENT_TYPE_CHAR: - switch (destElType) - { - case CorElementType.ELEMENT_TYPE_U2: - case CorElementType.ELEMENT_TYPE_CHAR: - // U2 and CHAR are identical in conversion - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_I4: - case CorElementType.ELEMENT_TYPE_U4: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_I8: - case CorElementType.ELEMENT_TYPE_U8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R4: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - default: - Debug.Fail("Array.Copy from U2 to another type hit unsupported widening conversion"); break; - } - break; - - case CorElementType.ELEMENT_TYPE_I2: - switch (destElType) - { - case CorElementType.ELEMENT_TYPE_I4: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_I8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R4: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - default: - Debug.Fail("Array.Copy from I2 to another type hit unsupported widening conversion"); break; - } - break; - - case CorElementType.ELEMENT_TYPE_U4: - switch (destElType) - { - case CorElementType.ELEMENT_TYPE_I8: - case CorElementType.ELEMENT_TYPE_U8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R4: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - default: - Debug.Fail("Array.Copy from U4 to another type hit unsupported widening conversion"); break; - } - break; - - case CorElementType.ELEMENT_TYPE_I4: - switch (destElType) - { - case CorElementType.ELEMENT_TYPE_I8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R4: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - default: - Debug.Fail("Array.Copy from I4 to another type hit unsupported widening conversion"); break; - } - break; - - case CorElementType.ELEMENT_TYPE_U8: - switch (destElType) - { - case CorElementType.ELEMENT_TYPE_R4: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - default: - Debug.Fail("Array.Copy from U8 to another type hit unsupported widening conversion"); break; - } - break; - - case CorElementType.ELEMENT_TYPE_I8: - switch (destElType) - { - case CorElementType.ELEMENT_TYPE_R4: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - default: - Debug.Fail("Array.Copy from I8 to another type hit unsupported widening conversion"); break; - } - break; - - case CorElementType.ELEMENT_TYPE_R4: - Debug.Assert(destElType == CorElementType.ELEMENT_TYPE_R8); - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - - default: - Debug.Fail("Fell through outer switch in PrimitiveWiden! Unknown primitive type for source array!"); break; + InvokeUtils.PrimitiveWiden(ref srcData, ref data, srcElType, destElType); + srcData = ref Unsafe.AddByteOffset(ref srcData, srcElSize); + data = ref Unsafe.AddByteOffset(ref data, destElSize); } } @@ -642,10 +496,10 @@ private unsafe void InternalSetValue(object? value, nint flattenedIndex) throw new InvalidCastException(SR.InvalidCast_StoreArrayElement); // Get a properly widened type - if (!RuntimeHelpers.CanPrimitiveWiden(srcType, targetType)) + if (!InvokeUtils.CanPrimitiveWiden(srcType, targetType)) throw new ArgumentException(SR.Arg_PrimWiden); - PrimitiveWiden(ref value.GetRawData(), ref offsetDataRef, srcType, targetType); + InvokeUtils.PrimitiveWiden(ref value.GetRawData(), ref offsetDataRef, srcType, targetType); } } diff --git a/src/coreclr/System.Private.CoreLib/src/System/InvokeUtils.cs b/src/coreclr/System.Private.CoreLib/src/System/InvokeUtils.cs new file mode 100644 index 0000000000000..35f5dee28f3c0 --- /dev/null +++ b/src/coreclr/System.Private.CoreLib/src/System/InvokeUtils.cs @@ -0,0 +1,188 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace System +{ + internal static class InvokeUtils + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void PrimitiveWiden(ref byte srcElement, ref byte destElement, CorElementType srcElType, CorElementType destElType) + { + switch (srcElType) + { + case CorElementType.ELEMENT_TYPE_U1: + switch (destElType) + { + case CorElementType.ELEMENT_TYPE_CHAR: + case CorElementType.ELEMENT_TYPE_I2: + case CorElementType.ELEMENT_TYPE_U2: + Unsafe.As(ref destElement) = srcElement; break; + case CorElementType.ELEMENT_TYPE_I4: + case CorElementType.ELEMENT_TYPE_U4: + Unsafe.As(ref destElement) = srcElement; break; + case CorElementType.ELEMENT_TYPE_I8: + case CorElementType.ELEMENT_TYPE_U8: + Unsafe.As(ref destElement) = srcElement; break; + case CorElementType.ELEMENT_TYPE_R4: + Unsafe.As(ref destElement) = srcElement; break; + case CorElementType.ELEMENT_TYPE_R8: + Unsafe.As(ref destElement) = srcElement; break; + default: + Debug.Fail("Array.Copy from U1 to another type hit unsupported widening conversion"); break; + } + break; + + case CorElementType.ELEMENT_TYPE_I1: + switch (destElType) + { + case CorElementType.ELEMENT_TYPE_I2: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_I4: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_I8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R4: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + default: + Debug.Fail("Array.Copy from I1 to another type hit unsupported widening conversion"); break; + } + break; + + case CorElementType.ELEMENT_TYPE_U2: + case CorElementType.ELEMENT_TYPE_CHAR: + switch (destElType) + { + case CorElementType.ELEMENT_TYPE_U2: + case CorElementType.ELEMENT_TYPE_CHAR: + // U2 and CHAR are identical in conversion + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_I4: + case CorElementType.ELEMENT_TYPE_U4: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_I8: + case CorElementType.ELEMENT_TYPE_U8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R4: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + default: + Debug.Fail("Array.Copy from U2 to another type hit unsupported widening conversion"); break; + } + break; + + case CorElementType.ELEMENT_TYPE_I2: + switch (destElType) + { + case CorElementType.ELEMENT_TYPE_I4: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_I8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R4: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + default: + Debug.Fail("Array.Copy from I2 to another type hit unsupported widening conversion"); break; + } + break; + + case CorElementType.ELEMENT_TYPE_U4: + switch (destElType) + { + case CorElementType.ELEMENT_TYPE_I8: + case CorElementType.ELEMENT_TYPE_U8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R4: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + default: + Debug.Fail("Array.Copy from U4 to another type hit unsupported widening conversion"); break; + } + break; + + case CorElementType.ELEMENT_TYPE_I4: + switch (destElType) + { + case CorElementType.ELEMENT_TYPE_I8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R4: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + default: + Debug.Fail("Array.Copy from I4 to another type hit unsupported widening conversion"); break; + } + break; + + case CorElementType.ELEMENT_TYPE_U8: + switch (destElType) + { + case CorElementType.ELEMENT_TYPE_R4: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + default: + Debug.Fail("Array.Copy from U8 to another type hit unsupported widening conversion"); break; + } + break; + + case CorElementType.ELEMENT_TYPE_I8: + switch (destElType) + { + case CorElementType.ELEMENT_TYPE_R4: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + default: + Debug.Fail("Array.Copy from I8 to another type hit unsupported widening conversion"); break; + } + break; + + case CorElementType.ELEMENT_TYPE_R4: + Debug.Assert(destElType == CorElementType.ELEMENT_TYPE_R8); + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + + default: + Debug.Fail("Fell through outer switch in PrimitiveWiden! Unknown primitive type for source array!"); break; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool CanPrimitiveWiden(CorElementType srcET, CorElementType dstET) + { + ReadOnlySpan primitiveAttributes = + [ + 0x00, // ELEMENT_TYPE_END + 0x00, // ELEMENT_TYPE_VOID + 0x0004, // ELEMENT_TYPE_BOOLEAN + 0x3F88, // ELEMENT_TYPE_CHAR (W = U2, CHAR, I4, U4, I8, U8, R4, R8) (U2 == Char) + 0x3550, // ELEMENT_TYPE_I1 (W = I1, I2, I4, I8, R4, R8) + 0x3FE8, // ELEMENT_TYPE_U1 (W = CHAR, U1, I2, U2, I4, U4, I8, U8, R4, R8) + 0x3540, // ELEMENT_TYPE_I2 (W = I2, I4, I8, R4, R8) + 0x3F88, // ELEMENT_TYPE_U2 (W = U2, CHAR, I4, U4, I8, U8, R4, R8) + 0x3500, // ELEMENT_TYPE_I4 (W = I4, I8, R4, R8) + 0x3E00, // ELEMENT_TYPE_U4 (W = U4, I8, R4, R8) + 0x3400, // ELEMENT_TYPE_I8 (W = I8, R4, R8) + 0x3800, // ELEMENT_TYPE_U8 (W = U8, R4, R8) + 0x3000, // ELEMENT_TYPE_R4 (W = R4, R8) + 0x2000, // ELEMENT_TYPE_R8 (W = R8) + ]; + + Debug.Assert(srcET.IsPrimitiveType() && dstET.IsPrimitiveType()); + if ((int)srcET >= primitiveAttributes.Length) + { + // I or U + return srcET == dstET; + } + return (primitiveAttributes[(int)srcET] & (1 << (int)dstET)) != 0; + } + } +} From 8a9c5bc1288fe29e6596da63dff6e982fdc7ed5c Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Wed, 12 Jun 2024 15:44:29 +0800 Subject: [PATCH 28/51] Merge coreclr specific InvokeUtils --- .../src/System/InvokeUtils.cs | 115 ++++++++++++++++ .../System.Private.CoreLib.Shared.projitems | 1 - .../src/System/Reflection/InvokeUtils.cs | 127 ------------------ 3 files changed, 115 insertions(+), 128 deletions(-) delete mode 100644 src/libraries/System.Private.CoreLib/src/System/Reflection/InvokeUtils.cs diff --git a/src/coreclr/System.Private.CoreLib/src/System/InvokeUtils.cs b/src/coreclr/System.Private.CoreLib/src/System/InvokeUtils.cs index 35f5dee28f3c0..a514c2e0991b3 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/InvokeUtils.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/InvokeUtils.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Runtime.CompilerServices; @@ -184,5 +185,119 @@ public static bool CanPrimitiveWiden(CorElementType srcET, CorElementType dstET) } return (primitiveAttributes[(int)srcET] & (1 << (int)dstET)) != 0; } + + // This method is similar to the NativeAot method ConvertOrWidenPrimitivesEnumsAndPointersIfPossible(). + public static object ConvertOrWiden(RuntimeType srcType, object srcObject, RuntimeType dstType, CorElementType dstElementType) + { + object dstObject; + + if (dstType.IsPointer || dstType.IsFunctionPointer) + { + if (TryConvertPointer(srcObject, out object? dstPtr)) + { + return dstPtr; + } + + Debug.Fail($"Unexpected CorElementType: {dstElementType}. Not a valid widening target."); + throw new NotSupportedException(); + } + + switch (dstElementType) + { + case CorElementType.ELEMENT_TYPE_BOOLEAN: + dstObject = Convert.ToBoolean(srcObject); + break; + + case CorElementType.ELEMENT_TYPE_CHAR: + char charValue = Convert.ToChar(srcObject); + dstObject = dstType.IsEnum ? Enum.ToObject(dstType, charValue) : charValue; + break; + + case CorElementType.ELEMENT_TYPE_I1: + sbyte sbyteValue = Convert.ToSByte(srcObject); + dstObject = dstType.IsEnum ? Enum.ToObject(dstType, sbyteValue) : sbyteValue; + break; + + case CorElementType.ELEMENT_TYPE_I2: + short shortValue = Convert.ToInt16(srcObject); + dstObject = dstType.IsEnum ? Enum.ToObject(dstType, shortValue) : shortValue; + break; + + case CorElementType.ELEMENT_TYPE_I4: + int intValue = Convert.ToInt32(srcObject); + dstObject = dstType.IsEnum ? Enum.ToObject(dstType, intValue) : intValue; + break; + + case CorElementType.ELEMENT_TYPE_I8: + long longValue = Convert.ToInt64(srcObject); + dstObject = dstType.IsEnum ? Enum.ToObject(dstType, longValue) : longValue; + break; + + case CorElementType.ELEMENT_TYPE_U1: + byte byteValue = Convert.ToByte(srcObject); + dstObject = dstType.IsEnum ? Enum.ToObject(dstType, byteValue) : byteValue; + break; + + case CorElementType.ELEMENT_TYPE_U2: + ushort ushortValue = Convert.ToUInt16(srcObject); + dstObject = dstType.IsEnum ? Enum.ToObject(dstType, ushortValue) : ushortValue; + break; + + case CorElementType.ELEMENT_TYPE_U4: + uint uintValue = Convert.ToUInt32(srcObject); + dstObject = dstType.IsEnum ? Enum.ToObject(dstType, uintValue) : uintValue; + break; + + case CorElementType.ELEMENT_TYPE_U8: + ulong ulongValue = Convert.ToUInt64(srcObject); + dstObject = dstType.IsEnum ? Enum.ToObject(dstType, (long)ulongValue) : ulongValue; + break; + + case CorElementType.ELEMENT_TYPE_R4: + if (srcType == typeof(char)) + { + dstObject = (float)(char)srcObject; + } + else + { + dstObject = Convert.ToSingle(srcObject); + } + break; + + case CorElementType.ELEMENT_TYPE_R8: + if (srcType == typeof(char)) + { + dstObject = (double)(char)srcObject; + } + else + { + dstObject = Convert.ToDouble(srcObject); + } + break; + + default: + Debug.Fail($"Unexpected CorElementType: {dstElementType}. Not a valid widening target."); + throw new NotSupportedException(); + } + + Debug.Assert(dstObject != null); + Debug.Assert(dstObject.GetType() == dstType); + return dstObject; + } + + private static bool TryConvertPointer(object srcObject, [NotNullWhen(true)] out object? dstPtr) + { + if (srcObject is IntPtr or UIntPtr) + { + dstPtr = srcObject; + return true; + } + + // The source pointer should already have been converted to an IntPtr. + Debug.Assert(srcObject is not Pointer); + + dstPtr = null; + return false; + } } } diff --git a/src/libraries/System.Private.CoreLib/src/System.Private.CoreLib.Shared.projitems b/src/libraries/System.Private.CoreLib/src/System.Private.CoreLib.Shared.projitems index ea91a44b9fcec..8179f33de72ea 100644 --- a/src/libraries/System.Private.CoreLib/src/System.Private.CoreLib.Shared.projitems +++ b/src/libraries/System.Private.CoreLib/src/System.Private.CoreLib.Shared.projitems @@ -714,7 +714,6 @@ - diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/InvokeUtils.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/InvokeUtils.cs deleted file mode 100644 index 5ad0b2729646b..0000000000000 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/InvokeUtils.cs +++ /dev/null @@ -1,127 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Runtime; -using System.Runtime.CompilerServices; - -namespace System.Reflection -{ - internal static class InvokeUtils - { - // This method is similar to the NativeAot method ConvertOrWidenPrimitivesEnumsAndPointersIfPossible(). - public static object ConvertOrWiden(RuntimeType srcType, object srcObject, RuntimeType dstType, CorElementType dstElementType) - { - object dstObject; - - if (dstType.IsPointer || dstType.IsFunctionPointer) - { - if (TryConvertPointer(srcObject, out object? dstPtr)) - { - return dstPtr; - } - - Debug.Fail($"Unexpected CorElementType: {dstElementType}. Not a valid widening target."); - throw new NotSupportedException(); - } - - switch (dstElementType) - { - case CorElementType.ELEMENT_TYPE_BOOLEAN: - dstObject = Convert.ToBoolean(srcObject); - break; - - case CorElementType.ELEMENT_TYPE_CHAR: - char charValue = Convert.ToChar(srcObject); - dstObject = dstType.IsEnum ? Enum.ToObject(dstType, charValue) : charValue; - break; - - case CorElementType.ELEMENT_TYPE_I1: - sbyte sbyteValue = Convert.ToSByte(srcObject); - dstObject = dstType.IsEnum ? Enum.ToObject(dstType, sbyteValue) : sbyteValue; - break; - - case CorElementType.ELEMENT_TYPE_I2: - short shortValue = Convert.ToInt16(srcObject); - dstObject = dstType.IsEnum ? Enum.ToObject(dstType, shortValue) : shortValue; - break; - - case CorElementType.ELEMENT_TYPE_I4: - int intValue = Convert.ToInt32(srcObject); - dstObject = dstType.IsEnum ? Enum.ToObject(dstType, intValue) : intValue; - break; - - case CorElementType.ELEMENT_TYPE_I8: - long longValue = Convert.ToInt64(srcObject); - dstObject = dstType.IsEnum ? Enum.ToObject(dstType, longValue) : longValue; - break; - - case CorElementType.ELEMENT_TYPE_U1: - byte byteValue = Convert.ToByte(srcObject); - dstObject = dstType.IsEnum ? Enum.ToObject(dstType, byteValue) : byteValue; - break; - - case CorElementType.ELEMENT_TYPE_U2: - ushort ushortValue = Convert.ToUInt16(srcObject); - dstObject = dstType.IsEnum ? Enum.ToObject(dstType, ushortValue) : ushortValue; - break; - - case CorElementType.ELEMENT_TYPE_U4: - uint uintValue = Convert.ToUInt32(srcObject); - dstObject = dstType.IsEnum ? Enum.ToObject(dstType, uintValue) : uintValue; - break; - - case CorElementType.ELEMENT_TYPE_U8: - ulong ulongValue = Convert.ToUInt64(srcObject); - dstObject = dstType.IsEnum ? Enum.ToObject(dstType, (long)ulongValue) : ulongValue; - break; - - case CorElementType.ELEMENT_TYPE_R4: - if (srcType == typeof(char)) - { - dstObject = (float)(char)srcObject; - } - else - { - dstObject = Convert.ToSingle(srcObject); - } - break; - - case CorElementType.ELEMENT_TYPE_R8: - if (srcType == typeof(char)) - { - dstObject = (double)(char)srcObject; - } - else - { - dstObject = Convert.ToDouble(srcObject); - } - break; - - default: - Debug.Fail($"Unexpected CorElementType: {dstElementType}. Not a valid widening target."); - throw new NotSupportedException(); - } - - Debug.Assert(dstObject != null); - Debug.Assert(dstObject.GetType() == dstType); - return dstObject; - } - - private static bool TryConvertPointer(object srcObject, [NotNullWhen(true)] out object? dstPtr) - { - if (srcObject is IntPtr or UIntPtr) - { - dstPtr = srcObject; - return true; - } - - // The source pointer should already have been converted to an IntPtr. - Debug.Assert(srcObject is not Pointer); - - dstPtr = null; - return false; - } - } -} From f95fa34c4b1f2f2d2493c44528e0d7cc21ce06da Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Thu, 13 Jun 2024 18:47:00 +0800 Subject: [PATCH 29/51] Revert "Merge coreclr specific InvokeUtils" This reverts commit 8a9c5bc1288fe29e6596da63dff6e982fdc7ed5c. --- .../src/System/InvokeUtils.cs | 115 ---------------- .../System.Private.CoreLib.Shared.projitems | 1 + .../src/System/Reflection/InvokeUtils.cs | 127 ++++++++++++++++++ 3 files changed, 128 insertions(+), 115 deletions(-) create mode 100644 src/libraries/System.Private.CoreLib/src/System/Reflection/InvokeUtils.cs diff --git a/src/coreclr/System.Private.CoreLib/src/System/InvokeUtils.cs b/src/coreclr/System.Private.CoreLib/src/System/InvokeUtils.cs index a514c2e0991b3..35f5dee28f3c0 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/InvokeUtils.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/InvokeUtils.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Runtime.CompilerServices; @@ -185,119 +184,5 @@ public static bool CanPrimitiveWiden(CorElementType srcET, CorElementType dstET) } return (primitiveAttributes[(int)srcET] & (1 << (int)dstET)) != 0; } - - // This method is similar to the NativeAot method ConvertOrWidenPrimitivesEnumsAndPointersIfPossible(). - public static object ConvertOrWiden(RuntimeType srcType, object srcObject, RuntimeType dstType, CorElementType dstElementType) - { - object dstObject; - - if (dstType.IsPointer || dstType.IsFunctionPointer) - { - if (TryConvertPointer(srcObject, out object? dstPtr)) - { - return dstPtr; - } - - Debug.Fail($"Unexpected CorElementType: {dstElementType}. Not a valid widening target."); - throw new NotSupportedException(); - } - - switch (dstElementType) - { - case CorElementType.ELEMENT_TYPE_BOOLEAN: - dstObject = Convert.ToBoolean(srcObject); - break; - - case CorElementType.ELEMENT_TYPE_CHAR: - char charValue = Convert.ToChar(srcObject); - dstObject = dstType.IsEnum ? Enum.ToObject(dstType, charValue) : charValue; - break; - - case CorElementType.ELEMENT_TYPE_I1: - sbyte sbyteValue = Convert.ToSByte(srcObject); - dstObject = dstType.IsEnum ? Enum.ToObject(dstType, sbyteValue) : sbyteValue; - break; - - case CorElementType.ELEMENT_TYPE_I2: - short shortValue = Convert.ToInt16(srcObject); - dstObject = dstType.IsEnum ? Enum.ToObject(dstType, shortValue) : shortValue; - break; - - case CorElementType.ELEMENT_TYPE_I4: - int intValue = Convert.ToInt32(srcObject); - dstObject = dstType.IsEnum ? Enum.ToObject(dstType, intValue) : intValue; - break; - - case CorElementType.ELEMENT_TYPE_I8: - long longValue = Convert.ToInt64(srcObject); - dstObject = dstType.IsEnum ? Enum.ToObject(dstType, longValue) : longValue; - break; - - case CorElementType.ELEMENT_TYPE_U1: - byte byteValue = Convert.ToByte(srcObject); - dstObject = dstType.IsEnum ? Enum.ToObject(dstType, byteValue) : byteValue; - break; - - case CorElementType.ELEMENT_TYPE_U2: - ushort ushortValue = Convert.ToUInt16(srcObject); - dstObject = dstType.IsEnum ? Enum.ToObject(dstType, ushortValue) : ushortValue; - break; - - case CorElementType.ELEMENT_TYPE_U4: - uint uintValue = Convert.ToUInt32(srcObject); - dstObject = dstType.IsEnum ? Enum.ToObject(dstType, uintValue) : uintValue; - break; - - case CorElementType.ELEMENT_TYPE_U8: - ulong ulongValue = Convert.ToUInt64(srcObject); - dstObject = dstType.IsEnum ? Enum.ToObject(dstType, (long)ulongValue) : ulongValue; - break; - - case CorElementType.ELEMENT_TYPE_R4: - if (srcType == typeof(char)) - { - dstObject = (float)(char)srcObject; - } - else - { - dstObject = Convert.ToSingle(srcObject); - } - break; - - case CorElementType.ELEMENT_TYPE_R8: - if (srcType == typeof(char)) - { - dstObject = (double)(char)srcObject; - } - else - { - dstObject = Convert.ToDouble(srcObject); - } - break; - - default: - Debug.Fail($"Unexpected CorElementType: {dstElementType}. Not a valid widening target."); - throw new NotSupportedException(); - } - - Debug.Assert(dstObject != null); - Debug.Assert(dstObject.GetType() == dstType); - return dstObject; - } - - private static bool TryConvertPointer(object srcObject, [NotNullWhen(true)] out object? dstPtr) - { - if (srcObject is IntPtr or UIntPtr) - { - dstPtr = srcObject; - return true; - } - - // The source pointer should already have been converted to an IntPtr. - Debug.Assert(srcObject is not Pointer); - - dstPtr = null; - return false; - } } } diff --git a/src/libraries/System.Private.CoreLib/src/System.Private.CoreLib.Shared.projitems b/src/libraries/System.Private.CoreLib/src/System.Private.CoreLib.Shared.projitems index 8179f33de72ea..ea91a44b9fcec 100644 --- a/src/libraries/System.Private.CoreLib/src/System.Private.CoreLib.Shared.projitems +++ b/src/libraries/System.Private.CoreLib/src/System.Private.CoreLib.Shared.projitems @@ -714,6 +714,7 @@ + diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/InvokeUtils.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/InvokeUtils.cs new file mode 100644 index 0000000000000..5ad0b2729646b --- /dev/null +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/InvokeUtils.cs @@ -0,0 +1,127 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Runtime; +using System.Runtime.CompilerServices; + +namespace System.Reflection +{ + internal static class InvokeUtils + { + // This method is similar to the NativeAot method ConvertOrWidenPrimitivesEnumsAndPointersIfPossible(). + public static object ConvertOrWiden(RuntimeType srcType, object srcObject, RuntimeType dstType, CorElementType dstElementType) + { + object dstObject; + + if (dstType.IsPointer || dstType.IsFunctionPointer) + { + if (TryConvertPointer(srcObject, out object? dstPtr)) + { + return dstPtr; + } + + Debug.Fail($"Unexpected CorElementType: {dstElementType}. Not a valid widening target."); + throw new NotSupportedException(); + } + + switch (dstElementType) + { + case CorElementType.ELEMENT_TYPE_BOOLEAN: + dstObject = Convert.ToBoolean(srcObject); + break; + + case CorElementType.ELEMENT_TYPE_CHAR: + char charValue = Convert.ToChar(srcObject); + dstObject = dstType.IsEnum ? Enum.ToObject(dstType, charValue) : charValue; + break; + + case CorElementType.ELEMENT_TYPE_I1: + sbyte sbyteValue = Convert.ToSByte(srcObject); + dstObject = dstType.IsEnum ? Enum.ToObject(dstType, sbyteValue) : sbyteValue; + break; + + case CorElementType.ELEMENT_TYPE_I2: + short shortValue = Convert.ToInt16(srcObject); + dstObject = dstType.IsEnum ? Enum.ToObject(dstType, shortValue) : shortValue; + break; + + case CorElementType.ELEMENT_TYPE_I4: + int intValue = Convert.ToInt32(srcObject); + dstObject = dstType.IsEnum ? Enum.ToObject(dstType, intValue) : intValue; + break; + + case CorElementType.ELEMENT_TYPE_I8: + long longValue = Convert.ToInt64(srcObject); + dstObject = dstType.IsEnum ? Enum.ToObject(dstType, longValue) : longValue; + break; + + case CorElementType.ELEMENT_TYPE_U1: + byte byteValue = Convert.ToByte(srcObject); + dstObject = dstType.IsEnum ? Enum.ToObject(dstType, byteValue) : byteValue; + break; + + case CorElementType.ELEMENT_TYPE_U2: + ushort ushortValue = Convert.ToUInt16(srcObject); + dstObject = dstType.IsEnum ? Enum.ToObject(dstType, ushortValue) : ushortValue; + break; + + case CorElementType.ELEMENT_TYPE_U4: + uint uintValue = Convert.ToUInt32(srcObject); + dstObject = dstType.IsEnum ? Enum.ToObject(dstType, uintValue) : uintValue; + break; + + case CorElementType.ELEMENT_TYPE_U8: + ulong ulongValue = Convert.ToUInt64(srcObject); + dstObject = dstType.IsEnum ? Enum.ToObject(dstType, (long)ulongValue) : ulongValue; + break; + + case CorElementType.ELEMENT_TYPE_R4: + if (srcType == typeof(char)) + { + dstObject = (float)(char)srcObject; + } + else + { + dstObject = Convert.ToSingle(srcObject); + } + break; + + case CorElementType.ELEMENT_TYPE_R8: + if (srcType == typeof(char)) + { + dstObject = (double)(char)srcObject; + } + else + { + dstObject = Convert.ToDouble(srcObject); + } + break; + + default: + Debug.Fail($"Unexpected CorElementType: {dstElementType}. Not a valid widening target."); + throw new NotSupportedException(); + } + + Debug.Assert(dstObject != null); + Debug.Assert(dstObject.GetType() == dstType); + return dstObject; + } + + private static bool TryConvertPointer(object srcObject, [NotNullWhen(true)] out object? dstPtr) + { + if (srcObject is IntPtr or UIntPtr) + { + dstPtr = srcObject; + return true; + } + + // The source pointer should already have been converted to an IntPtr. + Debug.Assert(srcObject is not Pointer); + + dstPtr = null; + return false; + } + } +} From ebfd2242292b7a4b027ad95165338b4a0accb0e2 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Thu, 13 Jun 2024 18:50:12 +0800 Subject: [PATCH 30/51] Move InvokeUtils to shared --- .../System.Private.CoreLib.csproj | 1 - .../src/System/InvokeUtils.cs | 188 ------------------ .../src/System/Reflection/InvokeUtils.cs | 176 ++++++++++++++++ 3 files changed, 176 insertions(+), 189 deletions(-) delete mode 100644 src/coreclr/System.Private.CoreLib/src/System/InvokeUtils.cs diff --git a/src/coreclr/System.Private.CoreLib/System.Private.CoreLib.csproj b/src/coreclr/System.Private.CoreLib/System.Private.CoreLib.csproj index fc3fccf07f71c..1586ba4132120 100644 --- a/src/coreclr/System.Private.CoreLib/System.Private.CoreLib.csproj +++ b/src/coreclr/System.Private.CoreLib/System.Private.CoreLib.csproj @@ -237,7 +237,6 @@ Common\System\Collections\Generic\ArrayBuilder.cs - diff --git a/src/coreclr/System.Private.CoreLib/src/System/InvokeUtils.cs b/src/coreclr/System.Private.CoreLib/src/System/InvokeUtils.cs deleted file mode 100644 index 35f5dee28f3c0..0000000000000 --- a/src/coreclr/System.Private.CoreLib/src/System/InvokeUtils.cs +++ /dev/null @@ -1,188 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using System.Diagnostics; -using System.Reflection; -using System.Runtime.CompilerServices; - -namespace System -{ - internal static class InvokeUtils - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void PrimitiveWiden(ref byte srcElement, ref byte destElement, CorElementType srcElType, CorElementType destElType) - { - switch (srcElType) - { - case CorElementType.ELEMENT_TYPE_U1: - switch (destElType) - { - case CorElementType.ELEMENT_TYPE_CHAR: - case CorElementType.ELEMENT_TYPE_I2: - case CorElementType.ELEMENT_TYPE_U2: - Unsafe.As(ref destElement) = srcElement; break; - case CorElementType.ELEMENT_TYPE_I4: - case CorElementType.ELEMENT_TYPE_U4: - Unsafe.As(ref destElement) = srcElement; break; - case CorElementType.ELEMENT_TYPE_I8: - case CorElementType.ELEMENT_TYPE_U8: - Unsafe.As(ref destElement) = srcElement; break; - case CorElementType.ELEMENT_TYPE_R4: - Unsafe.As(ref destElement) = srcElement; break; - case CorElementType.ELEMENT_TYPE_R8: - Unsafe.As(ref destElement) = srcElement; break; - default: - Debug.Fail("Array.Copy from U1 to another type hit unsupported widening conversion"); break; - } - break; - - case CorElementType.ELEMENT_TYPE_I1: - switch (destElType) - { - case CorElementType.ELEMENT_TYPE_I2: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_I4: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_I8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R4: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - default: - Debug.Fail("Array.Copy from I1 to another type hit unsupported widening conversion"); break; - } - break; - - case CorElementType.ELEMENT_TYPE_U2: - case CorElementType.ELEMENT_TYPE_CHAR: - switch (destElType) - { - case CorElementType.ELEMENT_TYPE_U2: - case CorElementType.ELEMENT_TYPE_CHAR: - // U2 and CHAR are identical in conversion - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_I4: - case CorElementType.ELEMENT_TYPE_U4: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_I8: - case CorElementType.ELEMENT_TYPE_U8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R4: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - default: - Debug.Fail("Array.Copy from U2 to another type hit unsupported widening conversion"); break; - } - break; - - case CorElementType.ELEMENT_TYPE_I2: - switch (destElType) - { - case CorElementType.ELEMENT_TYPE_I4: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_I8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R4: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - default: - Debug.Fail("Array.Copy from I2 to another type hit unsupported widening conversion"); break; - } - break; - - case CorElementType.ELEMENT_TYPE_U4: - switch (destElType) - { - case CorElementType.ELEMENT_TYPE_I8: - case CorElementType.ELEMENT_TYPE_U8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R4: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - default: - Debug.Fail("Array.Copy from U4 to another type hit unsupported widening conversion"); break; - } - break; - - case CorElementType.ELEMENT_TYPE_I4: - switch (destElType) - { - case CorElementType.ELEMENT_TYPE_I8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R4: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - default: - Debug.Fail("Array.Copy from I4 to another type hit unsupported widening conversion"); break; - } - break; - - case CorElementType.ELEMENT_TYPE_U8: - switch (destElType) - { - case CorElementType.ELEMENT_TYPE_R4: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - default: - Debug.Fail("Array.Copy from U8 to another type hit unsupported widening conversion"); break; - } - break; - - case CorElementType.ELEMENT_TYPE_I8: - switch (destElType) - { - case CorElementType.ELEMENT_TYPE_R4: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - case CorElementType.ELEMENT_TYPE_R8: - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - default: - Debug.Fail("Array.Copy from I8 to another type hit unsupported widening conversion"); break; - } - break; - - case CorElementType.ELEMENT_TYPE_R4: - Debug.Assert(destElType == CorElementType.ELEMENT_TYPE_R8); - Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; - - default: - Debug.Fail("Fell through outer switch in PrimitiveWiden! Unknown primitive type for source array!"); break; - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool CanPrimitiveWiden(CorElementType srcET, CorElementType dstET) - { - ReadOnlySpan primitiveAttributes = - [ - 0x00, // ELEMENT_TYPE_END - 0x00, // ELEMENT_TYPE_VOID - 0x0004, // ELEMENT_TYPE_BOOLEAN - 0x3F88, // ELEMENT_TYPE_CHAR (W = U2, CHAR, I4, U4, I8, U8, R4, R8) (U2 == Char) - 0x3550, // ELEMENT_TYPE_I1 (W = I1, I2, I4, I8, R4, R8) - 0x3FE8, // ELEMENT_TYPE_U1 (W = CHAR, U1, I2, U2, I4, U4, I8, U8, R4, R8) - 0x3540, // ELEMENT_TYPE_I2 (W = I2, I4, I8, R4, R8) - 0x3F88, // ELEMENT_TYPE_U2 (W = U2, CHAR, I4, U4, I8, U8, R4, R8) - 0x3500, // ELEMENT_TYPE_I4 (W = I4, I8, R4, R8) - 0x3E00, // ELEMENT_TYPE_U4 (W = U4, I8, R4, R8) - 0x3400, // ELEMENT_TYPE_I8 (W = I8, R4, R8) - 0x3800, // ELEMENT_TYPE_U8 (W = U8, R4, R8) - 0x3000, // ELEMENT_TYPE_R4 (W = R4, R8) - 0x2000, // ELEMENT_TYPE_R8 (W = R8) - ]; - - Debug.Assert(srcET.IsPrimitiveType() && dstET.IsPrimitiveType()); - if ((int)srcET >= primitiveAttributes.Length) - { - // I or U - return srcET == dstET; - } - return (primitiveAttributes[(int)srcET] & (1 << (int)dstET)) != 0; - } - } -} diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/InvokeUtils.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/InvokeUtils.cs index 5ad0b2729646b..86e962ed1ae58 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/InvokeUtils.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/InvokeUtils.cs @@ -123,5 +123,181 @@ private static bool TryConvertPointer(object srcObject, [NotNullWhen(true)] out dstPtr = null; return false; } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void PrimitiveWiden(ref byte srcElement, ref byte destElement, CorElementType srcElType, CorElementType destElType) + { + switch (srcElType) + { + case CorElementType.ELEMENT_TYPE_U1: + switch (destElType) + { + case CorElementType.ELEMENT_TYPE_CHAR: + case CorElementType.ELEMENT_TYPE_I2: + case CorElementType.ELEMENT_TYPE_U2: + Unsafe.As(ref destElement) = srcElement; break; + case CorElementType.ELEMENT_TYPE_I4: + case CorElementType.ELEMENT_TYPE_U4: + Unsafe.As(ref destElement) = srcElement; break; + case CorElementType.ELEMENT_TYPE_I8: + case CorElementType.ELEMENT_TYPE_U8: + Unsafe.As(ref destElement) = srcElement; break; + case CorElementType.ELEMENT_TYPE_R4: + Unsafe.As(ref destElement) = srcElement; break; + case CorElementType.ELEMENT_TYPE_R8: + Unsafe.As(ref destElement) = srcElement; break; + default: + Debug.Fail("Array.Copy from U1 to another type hit unsupported widening conversion"); break; + } + break; + + case CorElementType.ELEMENT_TYPE_I1: + switch (destElType) + { + case CorElementType.ELEMENT_TYPE_I2: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_I4: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_I8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R4: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + default: + Debug.Fail("Array.Copy from I1 to another type hit unsupported widening conversion"); break; + } + break; + + case CorElementType.ELEMENT_TYPE_U2: + case CorElementType.ELEMENT_TYPE_CHAR: + switch (destElType) + { + case CorElementType.ELEMENT_TYPE_U2: + case CorElementType.ELEMENT_TYPE_CHAR: + // U2 and CHAR are identical in conversion + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_I4: + case CorElementType.ELEMENT_TYPE_U4: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_I8: + case CorElementType.ELEMENT_TYPE_U8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R4: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + default: + Debug.Fail("Array.Copy from U2 to another type hit unsupported widening conversion"); break; + } + break; + + case CorElementType.ELEMENT_TYPE_I2: + switch (destElType) + { + case CorElementType.ELEMENT_TYPE_I4: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_I8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R4: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + default: + Debug.Fail("Array.Copy from I2 to another type hit unsupported widening conversion"); break; + } + break; + + case CorElementType.ELEMENT_TYPE_U4: + switch (destElType) + { + case CorElementType.ELEMENT_TYPE_I8: + case CorElementType.ELEMENT_TYPE_U8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R4: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + default: + Debug.Fail("Array.Copy from U4 to another type hit unsupported widening conversion"); break; + } + break; + + case CorElementType.ELEMENT_TYPE_I4: + switch (destElType) + { + case CorElementType.ELEMENT_TYPE_I8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R4: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + default: + Debug.Fail("Array.Copy from I4 to another type hit unsupported widening conversion"); break; + } + break; + + case CorElementType.ELEMENT_TYPE_U8: + switch (destElType) + { + case CorElementType.ELEMENT_TYPE_R4: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + default: + Debug.Fail("Array.Copy from U8 to another type hit unsupported widening conversion"); break; + } + break; + + case CorElementType.ELEMENT_TYPE_I8: + switch (destElType) + { + case CorElementType.ELEMENT_TYPE_R4: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + case CorElementType.ELEMENT_TYPE_R8: + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + default: + Debug.Fail("Array.Copy from I8 to another type hit unsupported widening conversion"); break; + } + break; + + case CorElementType.ELEMENT_TYPE_R4: + Debug.Assert(destElType == CorElementType.ELEMENT_TYPE_R8); + Unsafe.As(ref destElement) = Unsafe.As(ref srcElement); break; + + default: + Debug.Fail("Fell through outer switch in PrimitiveWiden! Unknown primitive type for source array!"); break; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool CanPrimitiveWiden(CorElementType srcET, CorElementType dstET) + { + ReadOnlySpan primitiveAttributes = + [ + 0x00, // ELEMENT_TYPE_END + 0x00, // ELEMENT_TYPE_VOID + 0x0004, // ELEMENT_TYPE_BOOLEAN + 0x3F88, // ELEMENT_TYPE_CHAR (W = U2, CHAR, I4, U4, I8, U8, R4, R8) (U2 == Char) + 0x3550, // ELEMENT_TYPE_I1 (W = I1, I2, I4, I8, R4, R8) + 0x3FE8, // ELEMENT_TYPE_U1 (W = CHAR, U1, I2, U2, I4, U4, I8, U8, R4, R8) + 0x3540, // ELEMENT_TYPE_I2 (W = I2, I4, I8, R4, R8) + 0x3F88, // ELEMENT_TYPE_U2 (W = U2, CHAR, I4, U4, I8, U8, R4, R8) + 0x3500, // ELEMENT_TYPE_I4 (W = I4, I8, R4, R8) + 0x3E00, // ELEMENT_TYPE_U4 (W = U4, I8, R4, R8) + 0x3400, // ELEMENT_TYPE_I8 (W = I8, R4, R8) + 0x3800, // ELEMENT_TYPE_U8 (W = U8, R4, R8) + 0x3000, // ELEMENT_TYPE_R4 (W = R4, R8) + 0x2000, // ELEMENT_TYPE_R8 (W = R8) + ]; + + Debug.Assert(srcET.IsPrimitiveType() && dstET.IsPrimitiveType()); + if ((int)srcET >= primitiveAttributes.Length) + { + // I or U + return srcET == dstET; + } + return (primitiveAttributes[(int)srcET] & (1 << (int)dstET)) != 0; + } } } From d9205c6ffae6c66c9f3987d7cc2f9058abbbc901 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Tue, 18 Jun 2024 11:35:22 +0800 Subject: [PATCH 31/51] Apply suggestions from code review Co-authored-by: Jan Kotas --- .../src/System/Array.CoreCLR.cs | 44 +++++++++---------- .../RuntimeHelpers.CoreCLR.cs | 2 +- 2 files changed, 21 insertions(+), 25 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs index c1c049bfaf0b1..0a210321681fe 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs @@ -437,33 +437,24 @@ private unsafe void InternalSetValue(object? value, nint flattenedIndex) if (pElementMethodTable->IsValueType) { ref byte offsetDataRef = ref Unsafe.Add(ref arrayDataRef, flattenedIndex * pMethodTable->ComponentSize); + nuint elementSize = pElementMethodTable->GetNumInstanceFieldBytes(); if (pElementMethodTable->ContainsGCPointers) - SpanHelpers.ClearWithReferences(ref Unsafe.As(ref offsetDataRef), pElementMethodTable->GetNumInstanceFieldBytes() / (nuint)sizeof(IntPtr)); + SpanHelpers.ClearWithReferences(ref Unsafe.As(ref offsetDataRef), elementSize / (nuint)sizeof(IntPtr)); else - SpanHelpers.ClearWithoutReferences(ref offsetDataRef, pElementMethodTable->GetNumInstanceFieldBytes()); + SpanHelpers.ClearWithoutReferences(ref offsetDataRef, elementSize); } else { - ref object? elementRef = ref Unsafe.As(ref arrayDataRef); - ref object? offsetElementRef = ref Unsafe.Add(ref elementRef, (nuint)flattenedIndex); - offsetElementRef = null; + Unsafe.Add(ref Unsafe.As(ref arrayDataRef), (nuint)flattenedIndex) = null; } } - else if (TypeHandle.AreSameType(arrayElementTypeHandle, TypeHandle.TypeHandleOf())) - { - // Everything is compatible with Object - ref object? elementRef = ref Unsafe.As(ref arrayDataRef); - ref object? offsetElementRef = ref Unsafe.Add(ref elementRef, (nuint)flattenedIndex); - offsetElementRef = value; - } else if (!pElementMethodTable->IsValueType) { - if (CastHelpers.IsInstanceOfAny(pElementMethodTable, value) == null) + if (pElementMethodTable != TypeHandle.TypeHandleOf().AsMethodTable() // Everything is compatible with Object + && CastHelpers.IsInstanceOfAny(pElementMethodTable, value) == null) throw new InvalidCastException(SR.InvalidCast_StoreArrayElement); - ref object? elementRef = ref Unsafe.As(ref arrayDataRef); - ref object? offsetElementRef = ref Unsafe.Add(ref elementRef, (nuint)flattenedIndex); - offsetElementRef = value; + Unsafe.Add(ref Unsafe.As(ref arrayDataRef), (nuint)flattenedIndex) = value; } else { @@ -476,23 +467,28 @@ private unsafe void InternalSetValue(object? value, nint flattenedIndex) { RuntimeHelpers.Unbox_Nullable(ref offsetDataRef, pElementMethodTable, value); } - else if (pElementMethodTable->ContainsGCPointers) - { - Buffer.BulkMoveWithWriteBarrier(ref offsetDataRef, ref value.GetRawData(), pElementMethodTable->GetNumInstanceFieldBytes()); - } else { - SpanHelpers.Memmove(ref offsetDataRef, ref value.GetRawData(), pElementMethodTable->GetNumInstanceFieldBytes()); + nuint elementSize = pElementMethodTable->GetNumInstanceFieldBytes(); + if (pElementMethodTable->ContainsGCPointers) + { + Buffer.BulkMoveWithWriteBarrier(ref offsetDataRef, ref value.GetRawData(), elementSize); + } + else + { + SpanHelpers.Memmove(ref offsetDataRef, ref value.GetRawData(), elementSize); + } } } else { // Allow enum -> primitive conversion, disallow primitive -> enum conversion - MethodTable* thSrc = RuntimeHelpers.GetMethodTable(value); - CorElementType srcType = thSrc->GetVerifierCorElementType(); + MethodTable* pValueMethodTable = RuntimeHelpers.GetMethodTable(value); + CorElementType srcType = pValueMethodTable->GetVerifierCorElementType(); CorElementType targetType = pElementMethodTable->GetVerifierCorElementType(); - if (!srcType.IsPrimitiveType() || !targetType.IsPrimitiveType() || !pElementMethodTable->IsTruePrimitive) + // Array.SetValue() does *not* permit conversion from a primitive to an Enum. + if (!pValueMethodTable->IsPrimitive || !pElementMethodTable->IsTruePrimitive) throw new InvalidCastException(SR.InvalidCast_StoreArrayElement); // Get a properly widened type diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs index 95de0fcc1863b..48edaa4b1064e 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs @@ -25,7 +25,7 @@ public static unsafe void InitializeArray(Array array, RuntimeFieldHandle fldHan throw new ArgumentException(SR.Argument_BadFieldForInitializeArray); // Note that we do not check that the field is actually in the PE file that is initializing - // the array. Basically the data being published is can be accessed by anyone with the proper + // the array. Basically, the data being published can be accessed by anyone with the proper // permissions (C# marks these as assembly visibility, and thus are protected from outside // snooping) From 8cfb58f45aa4d325286357dfb340d3182992dc08 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Tue, 18 Jun 2024 13:26:54 +0800 Subject: [PATCH 32/51] Fix trailing whitespace --- src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs index 6f8f535841865..1b95851cae205 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs @@ -487,7 +487,7 @@ private unsafe void InternalSetValue(object? value, nint flattenedIndex) CorElementType srcType = pValueMethodTable->GetVerifierCorElementType(); CorElementType targetType = pElementMethodTable->GetVerifierCorElementType(); - // Array.SetValue() does *not* permit conversion from a primitive to an Enum. + // Array.SetValue() does *not* permit conversion from a primitive to an Enum. if (!pValueMethodTable->IsPrimitive || !pElementMethodTable->IsTruePrimitive) throw new InvalidCastException(SR.InvalidCast_StoreArrayElement); From fbb9d71b6c1aec3bdd68ca538b43c801201516ff Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Tue, 18 Jun 2024 14:21:23 +0800 Subject: [PATCH 33/51] Reduce QCalls --- .../RuntimeHelpers.CoreCLR.cs | 10 +++------- .../src/System/RuntimeHandles.cs | 7 ++++--- src/coreclr/vm/qcallentrypoints.cpp | 2 +- src/coreclr/vm/reflectioninvocation.cpp | 20 +++++++++++++++---- src/coreclr/vm/runtimehandles.h | 2 +- 5 files changed, 25 insertions(+), 16 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs index 5574ed6ce5677..937e920ed6f97 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs @@ -21,7 +21,7 @@ public static unsafe void InitializeArray(Array array, RuntimeFieldHandle fldHan if (array is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - if ((RuntimeFieldHandle.GetAttributes(fldInfo.Value) & FieldAttributes.HasFieldRVA) == 0) + if (!RuntimeFieldHandle.GetRVAFieldInfo(new QCallFieldHandle(ref fldInfo), out IntPtr address, out uint size)) throw new ArgumentException(SR.Argument_BadFieldForInitializeArray); // Note that we do not check that the field is actually in the PE file that is initializing @@ -35,13 +35,11 @@ public static unsafe void InitializeArray(Array array, RuntimeFieldHandle fldHan MethodTable* pMT = GetMethodTable(array); nuint totalSize = pMT->ComponentSize * array.NativeLength; - uint size = RuntimeFieldHandle.GetFieldSize(new QCallFieldHandle(ref fldInfo)); - // make certain you don't go off the end of the rva static if (totalSize > size) throw new ArgumentException(SR.Argument_BadFieldForInitializeArray); - void* src = (void*)RuntimeFieldHandle.GetStaticFieldAddress(fldInfo); + void* src = (void*)address; ref byte dst = ref MemoryMarshal.GetArrayDataReference(array); Debug.Assert(!pMT->GetArrayElementTypeHandle().AsMethodTable()->ContainsGCPointers); @@ -86,7 +84,7 @@ public static unsafe void InitializeArray(Array array, RuntimeFieldHandle fldHan { IRuntimeFieldInfo fldInfo = fldHandle.GetRuntimeFieldInfo(); - if ((RuntimeFieldHandle.GetAttributes(fldInfo.Value) & FieldAttributes.HasFieldRVA) == 0) + if (!RuntimeFieldHandle.GetRVAFieldInfo(new QCallFieldHandle(ref fldInfo), out IntPtr data, out uint totalSize)) throw new ArgumentException(SR.Argument_BadFieldForInitializeArray); TypeHandle th = new TypeHandle((void*)targetTypeHandle.Value); @@ -95,10 +93,8 @@ public static unsafe void InitializeArray(Array array, RuntimeFieldHandle fldHan if (!th.GetVerifierCorElementType().IsPrimitiveType()) // Enum is included throw new ArgumentException(SR.Argument_MustBePrimitiveArray); - uint totalSize = RuntimeFieldHandle.GetFieldSize(new QCallFieldHandle(ref fldInfo)); uint targetTypeSize = th.AsMethodTable()->GetNumInstanceFieldBytes(); - IntPtr data = RuntimeFieldHandle.GetStaticFieldAddress(fldInfo); if (data % targetTypeSize != 0) throw new ArgumentException(SR.Argument_BadFieldForInitializeArray); diff --git a/src/coreclr/System.Private.CoreLib/src/System/RuntimeHandles.cs b/src/coreclr/System.Private.CoreLib/src/System/RuntimeHandles.cs index 7eddc635ef76b..6c4bc1bac538e 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/RuntimeHandles.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/RuntimeHandles.cs @@ -1191,10 +1191,11 @@ internal static RuntimeType GetApproxDeclaringType(IRuntimeFieldInfo field) internal static extern int GetInstanceFieldOffset(RtFieldInfo field); [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern IntPtr GetStaticFieldAddress(IRuntimeFieldInfo field); + internal static extern IntPtr GetStaticFieldAddress(RtFieldInfo field); - [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "RuntimeFieldHandle_GetFieldSize")] - internal static partial uint GetFieldSize(QCallFieldHandle field); + [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "RuntimeFieldHandle_GetRVAFieldInfo")] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool GetRVAFieldInfo(QCallFieldHandle field, out IntPtr address, out uint size); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern int GetToken(RtFieldInfo field); diff --git a/src/coreclr/vm/qcallentrypoints.cpp b/src/coreclr/vm/qcallentrypoints.cpp index 3aae3d7ae753a..329989cde6db4 100644 --- a/src/coreclr/vm/qcallentrypoints.cpp +++ b/src/coreclr/vm/qcallentrypoints.cpp @@ -132,7 +132,7 @@ static const Entry s_QCall[] = DllImportEntry(RuntimeModule_GetScopeName) DllImportEntry(RuntimeModule_GetFullyQualifiedName) DllImportEntry(RuntimeModule_GetTypes) - DllImportEntry(RuntimeFieldHandle_GetFieldSize) + DllImportEntry(RuntimeFieldHandle_GetRVAFieldInfo) DllImportEntry(StackFrame_GetMethodDescFromNativeIP) DllImportEntry(ModuleBuilder_GetStringConstant) DllImportEntry(ModuleBuilder_GetTypeRef) diff --git a/src/coreclr/vm/reflectioninvocation.cpp b/src/coreclr/vm/reflectioninvocation.cpp index 52c211fe74c8d..6277111bef59e 100644 --- a/src/coreclr/vm/reflectioninvocation.cpp +++ b/src/coreclr/vm/reflectioninvocation.cpp @@ -1259,14 +1259,26 @@ FCIMPL1(void*, RuntimeFieldHandle::GetStaticFieldAddress, ReflectFieldObject *pF } FCIMPLEND -extern "C" UINT QCALLTYPE RuntimeFieldHandle_GetFieldSize(QCall::FieldHandle pField) +extern "C" BOOL QCALLTYPE RuntimeFieldHandle_GetRVAFieldInfo(QCall::FieldHandle pField, void** address, UINT* size) { QCALL_CONTRACT; - UINT ret = 0; + BOOL ret = FALSE; BEGIN_QCALL; - ret = pField->LoadSize(); + + FieldDesc* pFieldDesc = pField.m_pField; + + if (pFieldDesc != NULL && pFieldDesc->IsRVA()) + { + ret = TRUE; + + Module* pModule = pFieldDesc->GetModule(); + *address = pModule->GetRvaField(pFieldDesc->GetOffset()); + + *size = pFieldDesc->LoadSize(); + } + END_QCALL; return ret; @@ -2129,4 +2141,4 @@ extern "C" void QCALLTYPE ReflectionInvocation_GetBoxInfo( pMT->EnsureInstanceActive(); END_QCALL; -} \ No newline at end of file +} diff --git a/src/coreclr/vm/runtimehandles.h b/src/coreclr/vm/runtimehandles.h index a444636618bc1..93deb865b8bcb 100644 --- a/src/coreclr/vm/runtimehandles.h +++ b/src/coreclr/vm/runtimehandles.h @@ -309,7 +309,7 @@ class RuntimeFieldHandle { static FCDECL1(FC_BOOL_RET, AcquiresContextFromThis, FieldDesc *pField); static FCDECL1(Object*, GetLoaderAllocator, FieldDesc *pField); }; -extern "C" UINT QCALLTYPE RuntimeFieldHandle_GetFieldSize(QCall::FieldHandle pField); +extern "C" BOOL QCALLTYPE RuntimeFieldHandle_GetRVAFieldInfo(QCall::FieldHandle pField, void** address, UINT* size); class ModuleHandle { From 324df7696499b463953deae2e67e476eda641415 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Tue, 18 Jun 2024 15:59:04 +0800 Subject: [PATCH 34/51] Reduce CorElementType overhead --- .../Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs index 937e920ed6f97..7a9ecb249f7a1 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs @@ -87,13 +87,14 @@ public static unsafe void InitializeArray(Array array, RuntimeFieldHandle fldHan if (!RuntimeFieldHandle.GetRVAFieldInfo(new QCallFieldHandle(ref fldInfo), out IntPtr data, out uint totalSize)) throw new ArgumentException(SR.Argument_BadFieldForInitializeArray); - TypeHandle th = new TypeHandle((void*)targetTypeHandle.Value); + TypeHandle th = targetTypeHandle.GetNativeTypeHandle(); Debug.Assert(!th.IsTypeDesc); // TypeDesc can't be used as generic parameter + MethodTable* targetMT = th.AsMethodTable(); - if (!th.GetVerifierCorElementType().IsPrimitiveType()) // Enum is included + if (!targetMT->IsPrimitive) // Enum is included throw new ArgumentException(SR.Argument_MustBePrimitiveArray); - uint targetTypeSize = th.AsMethodTable()->GetNumInstanceFieldBytes(); + uint targetTypeSize = targetMT->GetNumInstanceFieldBytes(); if (data % targetTypeSize != 0) throw new ArgumentException(SR.Argument_BadFieldForInitializeArray); From 089ae127d131790998eac0ffbb815a9a6577f9e2 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Wed, 19 Jun 2024 19:58:56 +0800 Subject: [PATCH 35/51] Separate RVA reflection change out --- src/coreclr/vm/reflectioninvocation.cpp | 14 ++++----- .../System.Reflection.Tests/FieldInfoTests.cs | 31 ------------------- 2 files changed, 6 insertions(+), 39 deletions(-) diff --git a/src/coreclr/vm/reflectioninvocation.cpp b/src/coreclr/vm/reflectioninvocation.cpp index 6277111bef59e..3ca340c19af34 100644 --- a/src/coreclr/vm/reflectioninvocation.cpp +++ b/src/coreclr/vm/reflectioninvocation.cpp @@ -1246,16 +1246,14 @@ FCIMPL1(void*, RuntimeFieldHandle::GetStaticFieldAddress, ReflectFieldObject *pF // IsFastPathSupported needs to checked before calling this method. _ASSERTE(IsFastPathSupportedHelper(pFieldDesc)); - if (pFieldDesc->IsRVA()) + PTR_BYTE base = 0; + if (!pFieldDesc->IsRVA()) { - Module* pModule = pFieldDesc->GetModule(); - return pModule->GetRvaField(pFieldDesc->GetOffset()); - } - else - { - PTR_BYTE base = pFieldDesc->GetBase(); - return PTR_VOID(base + pFieldDesc->GetOffset()); + // For RVA the base is ignored and offset is used. + base = pFieldDesc->GetBase(); } + + return PTR_VOID(base + pFieldDesc->GetOffset()); } FCIMPLEND diff --git a/src/libraries/System.Runtime/tests/System.Reflection.Tests/FieldInfoTests.cs b/src/libraries/System.Runtime/tests/System.Reflection.Tests/FieldInfoTests.cs index fbc97e4f17dad..d854e19c71ade 100644 --- a/src/libraries/System.Runtime/tests/System.Reflection.Tests/FieldInfoTests.cs +++ b/src/libraries/System.Runtime/tests/System.Reflection.Tests/FieldInfoTests.cs @@ -5,8 +5,6 @@ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; using Xunit; #pragma warning disable 0414 @@ -123,30 +121,6 @@ public void GetValueWithFunctionPointers(Type type, string name, object obj, obj Assert.Equal(expected, fieldInfo.GetValue(obj)); } - [Fact] - [ActiveIssue("https://github.com/dotnet/runtime/issues/103207")] - public void GetValueFromRvaField() - { - byte[] valueArray = new byte[] { 1, 2, 3, 4, 5 }; - - // Roslyn uses SHA256 of raw data as data field name - FieldInfo fieldInfo = GetField( - typeof(FieldInfoTests).Assembly.GetType(""), - "74F81FE167D99B4CB41D6D0CCDA82278CAEE9F3E2F25D5E5A3936FF3DCEC60D0"); - Assert.NotNull(fieldInfo); - Assert.True(fieldInfo.IsStatic); - Assert.True((fieldInfo.Attributes & FieldAttributes.HasFieldRVA) != 0); - - for (int i = 0; i < 5; i++) - { - // FieldAccessor uses slow path until the class is initialized. - // Make sure subsequent invocations also succeed. - - object value = fieldInfo.GetValue(null); - Assert.Equal(valueArray, MemoryMarshal.CreateReadOnlySpan(ref Unsafe.As(ref value).Data, valueArray.Length)); - } - } - [Fact] public void GetAndSetValueTypeFromStatic() { @@ -865,10 +839,5 @@ public static class SettingsForMyTypeThatThrowsInClassInitializer { public static bool s_shouldThrow = true; } - - private class RawData - { - public byte Data; - } } } From a5e7441fade3f7833404d6aed3fce96a6e27ba05 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Wed, 19 Jun 2024 20:06:33 +0800 Subject: [PATCH 36/51] Revert GetCorElementTypeOfElementType --- .../src/System/Array.CoreCLR.cs | 9 ++---- .../RuntimeHelpers.CoreCLR.cs | 28 +------------------ .../classlibnative/bcltype/arraynative.cpp | 11 ++++++++ .../classlibnative/bcltype/arraynative.h | 2 ++ src/coreclr/vm/ecalllist.h | 1 + 5 files changed, 17 insertions(+), 34 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs index 1b95851cae205..fee0a7222510f 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs @@ -558,13 +558,8 @@ public unsafe int GetLowerBound(int dimension) return Unsafe.Add(ref RuntimeHelpers.GetMultiDimensionalArrayBounds(this), rank + dimension); } - internal unsafe CorElementType GetCorElementTypeOfElementType() - { - MethodTable* pMT = RuntimeHelpers.GetMethodTable(this); - CorElementType et = pMT->GetArrayElementTypeHandle().GetVerifierCorElementType(); - GC.KeepAlive(this); - return et; - } + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern CorElementType GetCorElementTypeOfElementType(); private unsafe bool IsValueOfElementType(object value) { diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs index 7a9ecb249f7a1..27160afea2fb7 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs @@ -798,7 +798,7 @@ public bool CanCompareBitsOrUseFastGetHashCode } /// - /// A type handle, which can wrap either a pointer to a or to a . + /// A type handle, which can wrap either a pointer to a TypeDesc or to a . /// internal readonly unsafe partial struct TypeHandle { @@ -842,18 +842,6 @@ public bool IsTypeDesc return (MethodTable*)m_asTAddr; } - /// - /// Gets the pointer wrapped by the current instance. - /// - /// This is only safe to call if returned . - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public TypeDesc* AsTypeDesc() - { - Debug.Assert(IsTypeDesc); - - return (TypeDesc*)((nint)m_asTAddr - 2); - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] public static TypeHandle TypeHandleOf() { @@ -861,20 +849,6 @@ public static TypeHandle TypeHandleOf() } public static bool AreSameType(TypeHandle left, TypeHandle right) => left.m_asTAddr == right.m_asTAddr; - - public CorElementType GetVerifierCorElementType() => IsTypeDesc - ? AsTypeDesc()->GetInternalCorElementType() - : AsMethodTable()->GetVerifierCorElementType(); - } - - internal unsafe struct TypeDesc - { - private readonly int m_typeAndFlags; - - // This is the ELEMENT_TYPE* that would be used in the type sig for this type - // For enums this is the underlying type - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public CorElementType GetInternalCorElementType() => (CorElementType)(m_typeAndFlags & 0xFF); } // Helper structs used for tail calls via helper. diff --git a/src/coreclr/classlibnative/bcltype/arraynative.cpp b/src/coreclr/classlibnative/bcltype/arraynative.cpp index 2e8a41a827910..7a42245f76888 100644 --- a/src/coreclr/classlibnative/bcltype/arraynative.cpp +++ b/src/coreclr/classlibnative/bcltype/arraynative.cpp @@ -17,6 +17,17 @@ #include "arraynative.inl" +// Returns a bool to indicate if the array is of primitive types or not. +FCIMPL1(INT32, ArrayNative::GetCorElementTypeOfElementType, ArrayBase* arrayUNSAFE) +{ + FCALL_CONTRACT; + + _ASSERTE(arrayUNSAFE != NULL); + + return arrayUNSAFE->GetArrayElementTypeHandle().GetVerifierCorElementType(); +} +FCIMPLEND + extern "C" PCODE QCALLTYPE Array_GetElementConstructorEntrypoint(QCall::TypeHandle pArrayTypeHnd) { QCALL_CONTRACT; diff --git a/src/coreclr/classlibnative/bcltype/arraynative.h b/src/coreclr/classlibnative/bcltype/arraynative.h index c7ce27eb5c91b..5d8248bf172a6 100644 --- a/src/coreclr/classlibnative/bcltype/arraynative.h +++ b/src/coreclr/classlibnative/bcltype/arraynative.h @@ -19,6 +19,8 @@ class ArrayNative { public: + static FCDECL1(INT32, GetCorElementTypeOfElementType, ArrayBase* arrayUNSAFE); + static FCDECL2(FC_BOOL_RET, IsSimpleCopy, ArrayBase* pSrc, ArrayBase* pDst); }; diff --git a/src/coreclr/vm/ecalllist.h b/src/coreclr/vm/ecalllist.h index 713ad70f1a7c8..f9b0e2ac6f10a 100644 --- a/src/coreclr/vm/ecalllist.h +++ b/src/coreclr/vm/ecalllist.h @@ -360,6 +360,7 @@ FCFuncStart(gCastHelpers) FCFuncEnd() FCFuncStart(gArrayFuncs) + FCFuncElement("GetCorElementTypeOfElementType", ArrayNative::GetCorElementTypeOfElementType) FCFuncElement("IsSimpleCopy", ArrayNative::IsSimpleCopy) FCFuncEnd() From 5552d633f35729d9efe1e4c5aeef36f0c0f2332c Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Wed, 19 Jun 2024 20:33:49 +0800 Subject: [PATCH 37/51] Change the MethodTable FCall to be optimal for primitive and share with enum --- .../src/System/Array.CoreCLR.cs | 5 +++-- .../src/System/Enum.CoreCLR.cs | 6 +++--- .../RuntimeHelpers.CoreCLR.cs | 12 +++++++++--- src/coreclr/vm/comutilnative.cpp | 4 +++- src/coreclr/vm/ecalllist.h | 5 ----- src/coreclr/vm/reflectioninvocation.cpp | 19 ------------------- src/coreclr/vm/reflectioninvocation.h | 5 ----- 7 files changed, 18 insertions(+), 38 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs index fee0a7222510f..8f29eb4d4fb55 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs @@ -484,13 +484,14 @@ private unsafe void InternalSetValue(object? value, nint flattenedIndex) { // Allow enum -> primitive conversion, disallow primitive -> enum conversion MethodTable* pValueMethodTable = RuntimeHelpers.GetMethodTable(value); - CorElementType srcType = pValueMethodTable->GetVerifierCorElementType(); - CorElementType targetType = pElementMethodTable->GetVerifierCorElementType(); // Array.SetValue() does *not* permit conversion from a primitive to an Enum. if (!pValueMethodTable->IsPrimitive || !pElementMethodTable->IsTruePrimitive) throw new InvalidCastException(SR.InvalidCast_StoreArrayElement); + CorElementType srcType = pValueMethodTable->GetVerifierCorElementType(); + CorElementType targetType = pElementMethodTable->GetVerifierCorElementType(); + // Get a properly widened type if (!InvokeUtils.CanPrimitiveWiden(srcType, targetType)) throw new ArgumentException(SR.Arg_PrimWiden); diff --git a/src/coreclr/System.Private.CoreLib/src/System/Enum.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Enum.CoreCLR.cs index 9c92874f8ec27..3f2eed3f20770 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Enum.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Enum.CoreCLR.cs @@ -21,7 +21,7 @@ public abstract partial class Enum private static unsafe CorElementType InternalGetCorElementType(RuntimeType rt) { Debug.Assert(rt.IsActualEnum); - CorElementType elementType = InternalGetCorElementType((MethodTable*)rt.GetUnderlyingNativeHandle()); + CorElementType elementType = rt.GetNativeTypeHandle().AsMethodTable()->GetVerifierCorElementType(); GC.KeepAlive(rt); return elementType; } @@ -29,7 +29,7 @@ private static unsafe CorElementType InternalGetCorElementType(RuntimeType rt) [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe CorElementType InternalGetCorElementType() { - CorElementType elementType = InternalGetCorElementType(RuntimeHelpers.GetMethodTable(this)); + CorElementType elementType = RuntimeHelpers.GetMethodTable(this)->GetVerifierCorElementType(); GC.KeepAlive(this); return elementType; } @@ -71,7 +71,7 @@ internal static unsafe RuntimeType InternalGetUnderlyingType(RuntimeType enumTyp // Sanity check the last element in the table Debug.Assert(s_underlyingTypes[(int)CorElementType.ELEMENT_TYPE_U] == typeof(nuint)); - RuntimeType? underlyingType = s_underlyingTypes[(int)InternalGetCorElementType((MethodTable*)enumType.GetUnderlyingNativeHandle())]; + RuntimeType? underlyingType = s_underlyingTypes[(int)enumType.GetNativeTypeHandle().AsMethodTable()->GetVerifierCorElementType()]; GC.KeepAlive(enumType); Debug.Assert(underlyingType != null); diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs index 27160afea2fb7..8228fded96246 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs @@ -29,10 +29,12 @@ public static unsafe void InitializeArray(Array array, RuntimeFieldHandle fldHan // permissions (C# marks these as assembly visibility, and thus are protected from outside // snooping) - if (!array.GetCorElementTypeOfElementType().IsPrimitiveType()) // Enum is included + MethodTable* pMT = GetMethodTable(array); + TypeHandle elementTH = pMT->GetArrayElementTypeHandle(); + + if (elementTH.IsTypeDesc || !elementTH.AsMethodTable()->IsPrimitive) // Enum is included throw new ArgumentException(SR.Argument_MustBePrimitiveArray); - MethodTable* pMT = GetMethodTable(array); nuint totalSize = pMT->ComponentSize * array.NativeLength; // make certain you don't go off the end of the rva static @@ -42,7 +44,7 @@ public static unsafe void InitializeArray(Array array, RuntimeFieldHandle fldHan void* src = (void*)address; ref byte dst = ref MemoryMarshal.GetArrayDataReference(array); - Debug.Assert(!pMT->GetArrayElementTypeHandle().AsMethodTable()->ContainsGCPointers); + Debug.Assert(!elementTH.AsMethodTable()->ContainsGCPointers); if (BitConverter.IsLittleEndian) { @@ -771,6 +773,10 @@ public TypeHandle GetArrayElementTypeHandle() [MethodImpl(MethodImplOptions.InternalCall)] public extern uint GetNumInstanceFieldBytes(); + /// + /// Get the representing this type. Enums are represented by underlying type. + /// + /// This method is optimized in favor of primitive types and enums. [MethodImpl(MethodImplOptions.InternalCall)] public extern CorElementType GetVerifierCorElementType(); } diff --git a/src/coreclr/vm/comutilnative.cpp b/src/coreclr/vm/comutilnative.cpp index 8891c719044b8..8f9c5667824ac 100644 --- a/src/coreclr/vm/comutilnative.cpp +++ b/src/coreclr/vm/comutilnative.cpp @@ -1818,7 +1818,9 @@ FCIMPLEND FCIMPL1(CorElementType, MethodTableNative::GetVerifierCorElementType, MethodTable* mt) { FCALL_CONTRACT; - return mt->GetVerifierCorElementType(); + // MethodTable::GetInternalCorElementType has unnecessary overhead for primitives and enums + // Call EEClass::GetInternalCorElementType directly to avoid it + return mt->GetClass()->GetInternalCorElementType(); } FCIMPLEND diff --git a/src/coreclr/vm/ecalllist.h b/src/coreclr/vm/ecalllist.h index f9b0e2ac6f10a..f23cab2ee5d52 100644 --- a/src/coreclr/vm/ecalllist.h +++ b/src/coreclr/vm/ecalllist.h @@ -54,10 +54,6 @@ FCFuncStart(gDependentHandleFuncs) FCFuncElement("InternalFree", DependentHandle::InternalFree) FCFuncEnd() -FCFuncStart(gEnumFuncs) - FCFuncElement("InternalGetCorElementType", ReflectionEnum::InternalGetCorElementType) -FCFuncEnd() - FCFuncStart(gObjectFuncs) FCFuncElement("GetType", ObjectNative::GetClass) FCFuncEnd() @@ -540,7 +536,6 @@ FCClassElement("ComAwareWeakReference", "System", gComAwareWeakReferenceFuncs) FCClassElement("Debugger", "System.Diagnostics", gDiagnosticsDebugger) FCClassElement("Delegate", "System", gDelegateFuncs) FCClassElement("DependentHandle", "System.Runtime", gDependentHandleFuncs) -FCClassElement("Enum", "System", gEnumFuncs) FCClassElement("Environment", "System", gEnvironmentFuncs) FCClassElement("Exception", "System", gExceptionFuncs) FCClassElement("GC", "System", gGCInterfaceFuncs) diff --git a/src/coreclr/vm/reflectioninvocation.cpp b/src/coreclr/vm/reflectioninvocation.cpp index 3ca340c19af34..5a7dd5b48d2c2 100644 --- a/src/coreclr/vm/reflectioninvocation.cpp +++ b/src/coreclr/vm/reflectioninvocation.cpp @@ -1952,25 +1952,6 @@ extern "C" void QCALLTYPE ReflectionSerialization_GetCreateUninitializedObjectIn END_QCALL; } -//************************************************************************************************* -//************************************************************************************************* -//************************************************************************************************* -// ReflectionEnum -//************************************************************************************************* -//************************************************************************************************* -//************************************************************************************************* - -FCIMPL1(INT32, ReflectionEnum::InternalGetCorElementType, MethodTable* pMT) { - FCALL_CONTRACT; - - _ASSERTE(pMT->IsEnum()); - - // MethodTable::GetInternalCorElementType has unnecessary overhead for enums - // Call EEClass::GetInternalCorElementType directly to avoid it - return pMT->GetClass()->GetInternalCorElementType(); -} -FCIMPLEND - //******************************************************************************* struct TempEnumValue { diff --git a/src/coreclr/vm/reflectioninvocation.h b/src/coreclr/vm/reflectioninvocation.h index c26f137cdd927..ff20d72d870f9 100644 --- a/src/coreclr/vm/reflectioninvocation.h +++ b/src/coreclr/vm/reflectioninvocation.h @@ -79,11 +79,6 @@ extern "C" void QCALLTYPE ReflectionInvocation_GetBoxInfo( int32_t* pValueOffset, uint32_t* pValueSize); -class ReflectionEnum { -public: - static FCDECL1(INT32, InternalGetCorElementType, MethodTable* pMT); -}; - extern "C" void QCALLTYPE Enum_GetValuesAndNames(QCall::TypeHandle pEnumType, QCall::ObjectHandleOnStack pReturnValues, QCall::ObjectHandleOnStack pReturnNames, BOOL fGetNames); extern "C" int32_t QCALLTYPE ReflectionInvocation_SizeOf(QCall::TypeHandle pType); From 133cd8a41e7aa9fd8f48970f5aafa8d6ff4044fe Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Wed, 19 Jun 2024 21:18:38 +0800 Subject: [PATCH 38/51] Return ref from GetSpanDataFrom --- .../Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs | 4 ++-- .../Runtime/CompilerServices/RuntimeHelpers.NativeAot.cs | 2 +- .../src/System/Runtime/CompilerServices/RuntimeHelpers.cs | 3 ++- .../System/Runtime/CompilerServices/RuntimeHelpers.Mono.cs | 6 +++--- 4 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs index 8228fded96246..a345b732e4bee 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs @@ -79,7 +79,7 @@ public static unsafe void InitializeArray(Array array, RuntimeFieldHandle fldHan } } - private static unsafe void* GetSpanDataFrom( + private static unsafe ref byte GetSpanDataFrom( RuntimeFieldHandle fldHandle, RuntimeTypeHandle targetTypeHandle, out int count) @@ -107,7 +107,7 @@ public static unsafe void InitializeArray(Array array, RuntimeFieldHandle fldHan } count = (int)(totalSize / targetTypeSize); - return (void*)data; + return ref *(byte*)data; } // GetObjectValue is intended to allow value classes to be manipulated as 'Object' diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.NativeAot.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.NativeAot.cs index 916efe58017c7..2dd766c41e42d 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.NativeAot.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.NativeAot.cs @@ -28,7 +28,7 @@ public static void InitializeArray(Array array, RuntimeFieldHandle fldHandle) } #pragma warning disable IDE0060 - private static unsafe void* GetSpanDataFrom( + private static unsafe ref byte GetSpanDataFrom( RuntimeFieldHandle fldHandle, RuntimeTypeHandle targetTypeHandle, out int count) diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs index d1efa61d6cecf..f2a14d0d4959f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs @@ -145,7 +145,8 @@ internal static bool CanPrimitiveWiden(CorElementType srcET, CorElementType dstE /// does not refer to a field which is an Rva, is misaligned, or T is of an invalid type. /// This method is intended for compiler use rather than use directly in code. T must be one of byte, sbyte, bool, char, short, ushort, int, uint, long, ulong, float, or double. [Intrinsic] - public static unsafe ReadOnlySpan CreateSpan(RuntimeFieldHandle fldHandle) => new ReadOnlySpan(GetSpanDataFrom(fldHandle, typeof(T).TypeHandle, out int length), length); + public static unsafe ReadOnlySpan CreateSpan(RuntimeFieldHandle fldHandle) + => new ReadOnlySpan(ref Unsafe.As(ref GetSpanDataFrom(fldHandle, typeof(T).TypeHandle, out int length)), length); // The following intrinsics return true if input is a compile-time constant diff --git a/src/mono/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.Mono.cs index 016cc3e08568c..891e97640253c 100644 --- a/src/mono/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.Mono.cs @@ -19,14 +19,14 @@ public static void InitializeArray(Array array, RuntimeFieldHandle fldHandle) InitializeArray(array, fldHandle.Value); } - private static unsafe void* GetSpanDataFrom( + private static unsafe ref byte GetSpanDataFrom( RuntimeFieldHandle fldHandle, RuntimeTypeHandle targetTypeHandle, out int count) { fixed (int *pCount = &count) { - return (void*)GetSpanDataFrom(fldHandle.Value, targetTypeHandle.Value, new IntPtr(pCount)); + return ref GetSpanDataFrom(fldHandle.Value, targetTypeHandle.Value, new IntPtr(pCount)); } } @@ -196,7 +196,7 @@ public static object GetUninitializedObject( private static extern void InitializeArray(Array array, IntPtr fldHandle); [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern unsafe IntPtr GetSpanDataFrom( + private static extern unsafe ref byte GetSpanDataFrom( IntPtr fldHandle, IntPtr targetTypeHandle, IntPtr count); From e17bf0e3dd52d4cab937ac126d69ee5256c7a155 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Wed, 19 Jun 2024 23:22:52 +0800 Subject: [PATCH 39/51] Handle enum conversion to underlying type --- .../System.Private.CoreLib/src/System/Array.CoreCLR.cs | 10 +++++++++- .../tests/System.Runtime.Tests/System/ArrayTests.cs | 9 +++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs index 8f29eb4d4fb55..77c4cb5704d9d 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs @@ -496,7 +496,15 @@ private unsafe void InternalSetValue(object? value, nint flattenedIndex) if (!InvokeUtils.CanPrimitiveWiden(srcType, targetType)) throw new ArgumentException(SR.Arg_PrimWiden); - InvokeUtils.PrimitiveWiden(ref value.GetRawData(), ref offsetDataRef, srcType, targetType); + if (srcType == targetType) + { + // Primitive types are always tightly packed in array, using ComponentSize is sufficient. + SpanHelpers.Memmove(ref offsetDataRef, ref value.GetRawData(), pMethodTable->ComponentSize); + } + else + { + InvokeUtils.PrimitiveWiden(ref value.GetRawData(), ref offsetDataRef, srcType, targetType); + } } } diff --git a/src/libraries/System.Runtime/tests/System.Runtime.Tests/System/ArrayTests.cs b/src/libraries/System.Runtime/tests/System.Runtime.Tests/System/ArrayTests.cs index 2850347d59d6a..832d890ab61c2 100644 --- a/src/libraries/System.Runtime/tests/System.Runtime.Tests/System/ArrayTests.cs +++ b/src/libraries/System.Runtime/tests/System.Runtime.Tests/System/ArrayTests.cs @@ -4153,6 +4153,11 @@ public static void SetValue_Casting() var arr5 = new int[3]; arr5.SetValue(SByteEnum.MinusTwo, new int[] { 1 }); Assert.Equal(-2, arr5[1]); + + // Casting enum to underlying type + var arr6 = new int[3]; + arr6.SetValue(Int32Enum.Case3, new int[] { 1 }); + Assert.Equal(2, arr6[1]); } [Fact] @@ -4169,6 +4174,10 @@ public static void SetValue_Casting_Invalid() // T -> Nullable T must be exact var arr3 = new int?[3]; Assert.Throws(() => arr3.SetValue((short)42, new int[] { 1 })); + + // Converting enum to same size with wrong signed-ness + var arr4 = new uint[3]; + AssertExtensions.Throws(null, () => arr4.SetValue(Int32Enum.Case3, new int[] { 1 })); } [Fact] From dd1e2dd357e5a9f31f2594a7d1820ff65ec9d34d Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Thu, 20 Jun 2024 00:03:45 +0800 Subject: [PATCH 40/51] Update exception message --- .../System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs | 4 ++-- .../System.Private.CoreLib/src/Resources/Strings.resx | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs index a345b732e4bee..54979a2eb2a82 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs @@ -33,7 +33,7 @@ public static unsafe void InitializeArray(Array array, RuntimeFieldHandle fldHan TypeHandle elementTH = pMT->GetArrayElementTypeHandle(); if (elementTH.IsTypeDesc || !elementTH.AsMethodTable()->IsPrimitive) // Enum is included - throw new ArgumentException(SR.Argument_MustBePrimitiveArray); + throw new ArgumentException(SR.Argument_BadArrayForInitializeArray); nuint totalSize = pMT->ComponentSize * array.NativeLength; @@ -94,7 +94,7 @@ private static unsafe ref byte GetSpanDataFrom( MethodTable* targetMT = th.AsMethodTable(); if (!targetMT->IsPrimitive) // Enum is included - throw new ArgumentException(SR.Argument_MustBePrimitiveArray); + throw new ArgumentException(SR.Argument_BadArrayForInitializeArray); uint targetTypeSize = targetMT->GetNumInstanceFieldBytes(); diff --git a/src/libraries/System.Private.CoreLib/src/Resources/Strings.resx b/src/libraries/System.Private.CoreLib/src/Resources/Strings.resx index b9d10848b5a3d..77b9725603948 100644 --- a/src/libraries/System.Private.CoreLib/src/Resources/Strings.resx +++ b/src/libraries/System.Private.CoreLib/src/Resources/Strings.resx @@ -4325,7 +4325,7 @@ The field is invalid for initializing array or span. - - The array must be array of primitive or enum type. + + Only array or span of primitive or enum types can be initialized from static data. \ No newline at end of file From 32b87896ea60802772deedc951a9fe9da9b23cc5 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Thu, 20 Jun 2024 11:22:55 +0800 Subject: [PATCH 41/51] Add KeepAlive --- .../CompilerServices/RuntimeHelpers.CoreCLR.cs | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs index 54979a2eb2a82..e59ec863db8e0 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs @@ -41,7 +41,9 @@ public static unsafe void InitializeArray(Array array, RuntimeFieldHandle fldHan if (totalSize > size) throw new ArgumentException(SR.Argument_BadFieldForInitializeArray); - void* src = (void*)address; + ref byte src = ref *(byte*)address; + GC.KeepAlive(fldInfo); + ref byte dst = ref MemoryMarshal.GetArrayDataReference(array); Debug.Assert(!elementTH.AsMethodTable()->ContainsGCPointers); @@ -59,17 +61,17 @@ public static unsafe void InitializeArray(Array array, RuntimeFieldHandle fldHan break; case 2: BinaryPrimitives.ReverseEndianness( - new ReadOnlySpan(src, array.Length), + new ReadOnlySpan(ref Unsafe.As(ref src), array.Length), new Span(ref Unsafe.As(ref dst), array.Length)); break; case 4: BinaryPrimitives.ReverseEndianness( - new ReadOnlySpan(src, array.Length), + new ReadOnlySpan(ref Unsafe.As(ref src), array.Length), new Span(ref Unsafe.As(ref dst), array.Length)); break; case 8: BinaryPrimitives.ReverseEndianness( - new ReadOnlySpan(src, array.Length), + new ReadOnlySpan(ref Unsafe.As(ref src), array.Length), new Span(ref Unsafe.As(ref dst), array.Length)); break; default: @@ -107,7 +109,10 @@ private static unsafe ref byte GetSpanDataFrom( } count = (int)(totalSize / targetTypeSize); - return ref *(byte*)data; + ref byte dataRef = ref *(byte*)data; + GC.KeepAlive(fldInfo); + + return ref dataRef; } // GetObjectValue is intended to allow value classes to be manipulated as 'Object' From 582eaf17b4094940346856b6dd1e60ceb888a644 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Thu, 20 Jun 2024 11:24:15 +0800 Subject: [PATCH 42/51] Remove unnecessary qcall handle --- .../RuntimeHelpers.CoreCLR.cs | 14 +++++++++---- .../src/System/RuntimeHandles.cs | 2 +- src/coreclr/vm/qcall.h | 18 ---------------- src/coreclr/vm/reflectioninvocation.cpp | 12 +++++------ src/coreclr/vm/runtimehandles.h | 2 +- .../Runtime/CompilerServices/QCallHandles.cs | 21 ------------------- 6 files changed, 17 insertions(+), 52 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs index e59ec863db8e0..33696bb304da3 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs @@ -16,12 +16,15 @@ public static partial class RuntimeHelpers [Intrinsic] public static unsafe void InitializeArray(Array array, RuntimeFieldHandle fldHandle) { - IRuntimeFieldInfo fldInfo = fldHandle.GetRuntimeFieldInfo(); - if (array is null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - if (!RuntimeFieldHandle.GetRVAFieldInfo(new QCallFieldHandle(ref fldInfo), out IntPtr address, out uint size)) + if (fldHandle.IsNullHandle()) + throw new ArgumentException(SR.Argument_InvalidHandle); + + IRuntimeFieldInfo fldInfo = fldHandle.GetRuntimeFieldInfo(); + + if (!RuntimeFieldHandle.GetRVAFieldInfo(fldInfo.Value, out IntPtr address, out uint size)) throw new ArgumentException(SR.Argument_BadFieldForInitializeArray); // Note that we do not check that the field is actually in the PE file that is initializing @@ -86,9 +89,12 @@ private static unsafe ref byte GetSpanDataFrom( RuntimeTypeHandle targetTypeHandle, out int count) { + if (fldHandle.IsNullHandle()) + throw new ArgumentException(SR.Argument_InvalidHandle); + IRuntimeFieldInfo fldInfo = fldHandle.GetRuntimeFieldInfo(); - if (!RuntimeFieldHandle.GetRVAFieldInfo(new QCallFieldHandle(ref fldInfo), out IntPtr data, out uint totalSize)) + if (!RuntimeFieldHandle.GetRVAFieldInfo(fldInfo.Value, out IntPtr data, out uint totalSize)) throw new ArgumentException(SR.Argument_BadFieldForInitializeArray); TypeHandle th = targetTypeHandle.GetNativeTypeHandle(); diff --git a/src/coreclr/System.Private.CoreLib/src/System/RuntimeHandles.cs b/src/coreclr/System.Private.CoreLib/src/System/RuntimeHandles.cs index 6c4bc1bac538e..f84d9321d2670 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/RuntimeHandles.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/RuntimeHandles.cs @@ -1195,7 +1195,7 @@ internal static RuntimeType GetApproxDeclaringType(IRuntimeFieldInfo field) [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "RuntimeFieldHandle_GetRVAFieldInfo")] [return: MarshalAs(UnmanagedType.Bool)] - internal static partial bool GetRVAFieldInfo(QCallFieldHandle field, out IntPtr address, out uint size); + internal static partial bool GetRVAFieldInfo(RuntimeFieldHandleInternal field, out IntPtr address, out uint size); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern int GetToken(RtFieldInfo field); diff --git a/src/coreclr/vm/qcall.h b/src/coreclr/vm/qcall.h index b63d2ffa7beac..e3154c7b1334c 100644 --- a/src/coreclr/vm/qcall.h +++ b/src/coreclr/vm/qcall.h @@ -293,24 +293,6 @@ class QCall } }; - struct FieldHandle - { - Object ** m_ppObject; - FieldDesc * m_pField; - - operator FieldDesc * () - { - LIMITED_METHOD_CONTRACT; - return m_pField; - } - - FieldDesc * operator -> () - { - LIMITED_METHOD_CONTRACT; - return m_pField; - } - }; - struct LoaderAllocatorHandle { LoaderAllocator * m_pLoaderAllocator; diff --git a/src/coreclr/vm/reflectioninvocation.cpp b/src/coreclr/vm/reflectioninvocation.cpp index 5a7dd5b48d2c2..286a5dcead9c6 100644 --- a/src/coreclr/vm/reflectioninvocation.cpp +++ b/src/coreclr/vm/reflectioninvocation.cpp @@ -1257,7 +1257,7 @@ FCIMPL1(void*, RuntimeFieldHandle::GetStaticFieldAddress, ReflectFieldObject *pF } FCIMPLEND -extern "C" BOOL QCALLTYPE RuntimeFieldHandle_GetRVAFieldInfo(QCall::FieldHandle pField, void** address, UINT* size) +extern "C" BOOL QCALLTYPE RuntimeFieldHandle_GetRVAFieldInfo(FieldDesc* pField, void** address, UINT* size) { QCALL_CONTRACT; @@ -1265,16 +1265,14 @@ extern "C" BOOL QCALLTYPE RuntimeFieldHandle_GetRVAFieldInfo(QCall::FieldHandle BEGIN_QCALL; - FieldDesc* pFieldDesc = pField.m_pField; - - if (pFieldDesc != NULL && pFieldDesc->IsRVA()) + if (pField != NULL && pField->IsRVA()) { ret = TRUE; - Module* pModule = pFieldDesc->GetModule(); - *address = pModule->GetRvaField(pFieldDesc->GetOffset()); + Module* pModule = pField->GetModule(); + *address = pModule->GetRvaField(pField->GetOffset()); - *size = pFieldDesc->LoadSize(); + *size = pField->LoadSize(); } END_QCALL; diff --git a/src/coreclr/vm/runtimehandles.h b/src/coreclr/vm/runtimehandles.h index 93deb865b8bcb..0fd92c45bef33 100644 --- a/src/coreclr/vm/runtimehandles.h +++ b/src/coreclr/vm/runtimehandles.h @@ -309,7 +309,7 @@ class RuntimeFieldHandle { static FCDECL1(FC_BOOL_RET, AcquiresContextFromThis, FieldDesc *pField); static FCDECL1(Object*, GetLoaderAllocator, FieldDesc *pField); }; -extern "C" BOOL QCALLTYPE RuntimeFieldHandle_GetRVAFieldInfo(QCall::FieldHandle pField, void** address, UINT* size); +extern "C" BOOL QCALLTYPE RuntimeFieldHandle_GetRVAFieldInfo(FieldDesc* pField, void** address, UINT* size); class ModuleHandle { diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/QCallHandles.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/QCallHandles.cs index e6ab54d12e5d7..240e9932bf624 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/QCallHandles.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/QCallHandles.cs @@ -95,25 +95,4 @@ internal QCallTypeHandle(ref RuntimeTypeHandle rth) _handle = rth.Value; } } - - // Wraps IRuntimeFieldInfo into a handle. Used to pass IRuntimeFieldInfo to native code without letting it be collected - internal unsafe ref struct QCallFieldHandle - { - private void* _ptr; - private IntPtr _handle; - -#if CORECLR - internal QCallFieldHandle(ref IRuntimeFieldInfo field) - { - _ptr = Unsafe.AsPointer(ref field); - _handle = field.Value.Value; - } -#endif - - internal QCallFieldHandle(ref RuntimeFieldHandle rth) - { - _ptr = Unsafe.AsPointer(ref rth); - _handle = rth.Value; - } - } } From 1836ae5cda4fd0d00ce38c9cf05fa66f2528f281 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Thu, 20 Jun 2024 19:41:58 +0800 Subject: [PATCH 43/51] Fix ref src --- .../System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs index 33696bb304da3..5e46b9b303669 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs @@ -53,14 +53,14 @@ public static unsafe void InitializeArray(Array array, RuntimeFieldHandle fldHan if (BitConverter.IsLittleEndian) { - SpanHelpers.Memmove(ref dst, ref *(byte*)src, totalSize); + SpanHelpers.Memmove(ref dst, ref src, totalSize); } else { switch (pMT->ComponentSize) { case 1: - SpanHelpers.Memmove(ref dst, ref *(byte*)src, totalSize); + SpanHelpers.Memmove(ref dst, ref src, totalSize); break; case 2: BinaryPrimitives.ReverseEndianness( From cb6aa004d6a95eb8d12aaad2f4d9eb4636b40e8e Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Mon, 24 Jun 2024 20:51:59 +0800 Subject: [PATCH 44/51] Update FCall name and assert --- .../System.Private.CoreLib/src/System/Array.CoreCLR.cs | 4 ++-- .../System.Private.CoreLib/src/System/Enum.CoreCLR.cs | 6 +++--- .../Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs | 6 +++--- src/coreclr/vm/comutilnative.cpp | 5 ++++- src/coreclr/vm/comutilnative.h | 2 +- src/coreclr/vm/ecalllist.h | 2 +- 6 files changed, 14 insertions(+), 11 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs index 77c4cb5704d9d..2efcb649844af 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Array.CoreCLR.cs @@ -489,8 +489,8 @@ private unsafe void InternalSetValue(object? value, nint flattenedIndex) if (!pValueMethodTable->IsPrimitive || !pElementMethodTable->IsTruePrimitive) throw new InvalidCastException(SR.InvalidCast_StoreArrayElement); - CorElementType srcType = pValueMethodTable->GetVerifierCorElementType(); - CorElementType targetType = pElementMethodTable->GetVerifierCorElementType(); + CorElementType srcType = pValueMethodTable->GetPrimitiveCorElementType(); + CorElementType targetType = pElementMethodTable->GetPrimitiveCorElementType(); // Get a properly widened type if (!InvokeUtils.CanPrimitiveWiden(srcType, targetType)) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Enum.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Enum.CoreCLR.cs index 3f2eed3f20770..0946f79ae674c 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Enum.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Enum.CoreCLR.cs @@ -21,7 +21,7 @@ public abstract partial class Enum private static unsafe CorElementType InternalGetCorElementType(RuntimeType rt) { Debug.Assert(rt.IsActualEnum); - CorElementType elementType = rt.GetNativeTypeHandle().AsMethodTable()->GetVerifierCorElementType(); + CorElementType elementType = rt.GetNativeTypeHandle().AsMethodTable()->GetPrimitiveCorElementType(); GC.KeepAlive(rt); return elementType; } @@ -29,7 +29,7 @@ private static unsafe CorElementType InternalGetCorElementType(RuntimeType rt) [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe CorElementType InternalGetCorElementType() { - CorElementType elementType = RuntimeHelpers.GetMethodTable(this)->GetVerifierCorElementType(); + CorElementType elementType = RuntimeHelpers.GetMethodTable(this)->GetPrimitiveCorElementType(); GC.KeepAlive(this); return elementType; } @@ -71,7 +71,7 @@ internal static unsafe RuntimeType InternalGetUnderlyingType(RuntimeType enumTyp // Sanity check the last element in the table Debug.Assert(s_underlyingTypes[(int)CorElementType.ELEMENT_TYPE_U] == typeof(nuint)); - RuntimeType? underlyingType = s_underlyingTypes[(int)enumType.GetNativeTypeHandle().AsMethodTable()->GetVerifierCorElementType()]; + RuntimeType? underlyingType = s_underlyingTypes[(int)enumType.GetNativeTypeHandle().AsMethodTable()->GetPrimitiveCorElementType()]; GC.KeepAlive(enumType); Debug.Assert(underlyingType != null); diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs index 5e46b9b303669..623b5dff7fb67 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs @@ -785,11 +785,11 @@ public TypeHandle GetArrayElementTypeHandle() public extern uint GetNumInstanceFieldBytes(); /// - /// Get the representing this type. Enums are represented by underlying type. + /// Get the representing primitive-like type. Enums are represented by underlying type. /// - /// This method is optimized in favor of primitive types and enums. + /// This method should only be called when returns . [MethodImpl(MethodImplOptions.InternalCall)] - public extern CorElementType GetVerifierCorElementType(); + public extern CorElementType GetPrimitiveCorElementType(); } // Subset of src\vm\methodtable.h diff --git a/src/coreclr/vm/comutilnative.cpp b/src/coreclr/vm/comutilnative.cpp index 8f9c5667824ac..c17f94bc27d28 100644 --- a/src/coreclr/vm/comutilnative.cpp +++ b/src/coreclr/vm/comutilnative.cpp @@ -1815,9 +1815,12 @@ FCIMPL1(UINT32, MethodTableNative::GetNumInstanceFieldBytes, MethodTable* mt) } FCIMPLEND -FCIMPL1(CorElementType, MethodTableNative::GetVerifierCorElementType, MethodTable* mt) +FCIMPL1(CorElementType, MethodTableNative::GetPrimitiveCorElementType, MethodTable* mt) { FCALL_CONTRACT; + + _ASSERTE(mt->IsTruePrimitive() || mt->IsEnum()); + // MethodTable::GetInternalCorElementType has unnecessary overhead for primitives and enums // Call EEClass::GetInternalCorElementType directly to avoid it return mt->GetClass()->GetInternalCorElementType(); diff --git a/src/coreclr/vm/comutilnative.h b/src/coreclr/vm/comutilnative.h index c4194e7a322a2..0f00aca48466a 100644 --- a/src/coreclr/vm/comutilnative.h +++ b/src/coreclr/vm/comutilnative.h @@ -247,7 +247,7 @@ extern "C" void QCALLTYPE Interlocked_MemoryBarrierProcessWide(); class MethodTableNative { public: static FCDECL1(UINT32, GetNumInstanceFieldBytes, MethodTable* mt); - static FCDECL1(CorElementType, GetVerifierCorElementType, MethodTable* mt); + static FCDECL1(CorElementType, GetPrimitiveCorElementType, MethodTable* mt); }; extern "C" BOOL QCALLTYPE MethodTable_AreTypesEquivalent(MethodTable* mta, MethodTable* mtb); diff --git a/src/coreclr/vm/ecalllist.h b/src/coreclr/vm/ecalllist.h index f23cab2ee5d52..d820c4d8e33b2 100644 --- a/src/coreclr/vm/ecalllist.h +++ b/src/coreclr/vm/ecalllist.h @@ -448,7 +448,7 @@ FCFuncEnd() FCFuncStart(gMethodTableFuncs) FCFuncElement("GetNumInstanceFieldBytes", MethodTableNative::GetNumInstanceFieldBytes) - FCFuncElement("GetVerifierCorElementType", MethodTableNative::GetVerifierCorElementType) + FCFuncElement("GetPrimitiveCorElementType", MethodTableNative::GetPrimitiveCorElementType) FCFuncEnd() FCFuncStart(gStubHelperFuncs) From 49cf866f4e1173576944eb10f6b695b4f5040008 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Mon, 24 Jun 2024 20:53:55 +0800 Subject: [PATCH 45/51] Remove unused changes --- .../System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs | 4 +--- src/coreclr/classlibnative/bcltype/arraynative.h | 2 +- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs index 623b5dff7fb67..b01f3b8c88b61 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs @@ -817,7 +817,7 @@ public bool CanCompareBitsOrUseFastGetHashCode /// /// A type handle, which can wrap either a pointer to a TypeDesc or to a . /// - internal readonly unsafe partial struct TypeHandle + internal unsafe struct TypeHandle { // Subset of src\vm\typehandle.h @@ -864,8 +864,6 @@ public static TypeHandle TypeHandleOf() { return new TypeHandle((void*)RuntimeTypeHandle.ToIntPtr(typeof(T).TypeHandle)); } - - public static bool AreSameType(TypeHandle left, TypeHandle right) => left.m_asTAddr == right.m_asTAddr; } // Helper structs used for tail calls via helper. diff --git a/src/coreclr/classlibnative/bcltype/arraynative.h b/src/coreclr/classlibnative/bcltype/arraynative.h index 5d8248bf172a6..86b125c416bf0 100644 --- a/src/coreclr/classlibnative/bcltype/arraynative.h +++ b/src/coreclr/classlibnative/bcltype/arraynative.h @@ -20,7 +20,7 @@ class ArrayNative { public: static FCDECL1(INT32, GetCorElementTypeOfElementType, ArrayBase* arrayUNSAFE); - + static FCDECL2(FC_BOOL_RET, IsSimpleCopy, ArrayBase* pSrc, ArrayBase* pDst); }; From 7a0c39816019fe88b570740f48019e439c770570 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Mon, 24 Jun 2024 21:13:33 +0800 Subject: [PATCH 46/51] Use void* for address --- .../Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs | 7 ++++--- .../System.Private.CoreLib/src/System/RuntimeHandles.cs | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs index b01f3b8c88b61..0596b891c7fbf 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs @@ -24,7 +24,7 @@ public static unsafe void InitializeArray(Array array, RuntimeFieldHandle fldHan IRuntimeFieldInfo fldInfo = fldHandle.GetRuntimeFieldInfo(); - if (!RuntimeFieldHandle.GetRVAFieldInfo(fldInfo.Value, out IntPtr address, out uint size)) + if (!RuntimeFieldHandle.GetRVAFieldInfo(fldInfo.Value, out void* address, out uint size)) throw new ArgumentException(SR.Argument_BadFieldForInitializeArray); // Note that we do not check that the field is actually in the PE file that is initializing @@ -94,7 +94,7 @@ private static unsafe ref byte GetSpanDataFrom( IRuntimeFieldInfo fldInfo = fldHandle.GetRuntimeFieldInfo(); - if (!RuntimeFieldHandle.GetRVAFieldInfo(fldInfo.Value, out IntPtr data, out uint totalSize)) + if (!RuntimeFieldHandle.GetRVAFieldInfo(fldInfo.Value, out void* data, out uint totalSize)) throw new ArgumentException(SR.Argument_BadFieldForInitializeArray); TypeHandle th = targetTypeHandle.GetNativeTypeHandle(); @@ -105,8 +105,9 @@ private static unsafe ref byte GetSpanDataFrom( throw new ArgumentException(SR.Argument_BadArrayForInitializeArray); uint targetTypeSize = targetMT->GetNumInstanceFieldBytes(); + Debug.Assert(uint.IsPow2(targetTypeSize)); - if (data % targetTypeSize != 0) + if (((nuint)data & (targetTypeSize - 1)) != 0) throw new ArgumentException(SR.Argument_BadFieldForInitializeArray); if (!BitConverter.IsLittleEndian) diff --git a/src/coreclr/System.Private.CoreLib/src/System/RuntimeHandles.cs b/src/coreclr/System.Private.CoreLib/src/System/RuntimeHandles.cs index f84d9321d2670..a7fcf364f36d9 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/RuntimeHandles.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/RuntimeHandles.cs @@ -1195,7 +1195,7 @@ internal static RuntimeType GetApproxDeclaringType(IRuntimeFieldInfo field) [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "RuntimeFieldHandle_GetRVAFieldInfo")] [return: MarshalAs(UnmanagedType.Bool)] - internal static partial bool GetRVAFieldInfo(RuntimeFieldHandleInternal field, out IntPtr address, out uint size); + internal static partial bool GetRVAFieldInfo(RuntimeFieldHandleInternal field, out void* address, out uint size); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern int GetToken(RtFieldInfo field); From db677ad4822bedc93e5209af1d943fe6d1b125c2 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Tue, 25 Jun 2024 10:12:53 +0800 Subject: [PATCH 47/51] Apply suggestions from code review Co-authored-by: Aaron Robinson Co-authored-by: Jan Kotas --- src/coreclr/vm/reflectioninvocation.cpp | 5 ++--- .../src/System/Reflection/InvokeUtils.cs | 4 ++-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/coreclr/vm/reflectioninvocation.cpp b/src/coreclr/vm/reflectioninvocation.cpp index 286a5dcead9c6..27655cddc10a9 100644 --- a/src/coreclr/vm/reflectioninvocation.cpp +++ b/src/coreclr/vm/reflectioninvocation.cpp @@ -1267,12 +1267,11 @@ extern "C" BOOL QCALLTYPE RuntimeFieldHandle_GetRVAFieldInfo(FieldDesc* pField, if (pField != NULL && pField->IsRVA()) { - ret = TRUE; - Module* pModule = pField->GetModule(); *address = pModule->GetRvaField(pField->GetOffset()); - *size = pField->LoadSize(); + + ret = TRUE; } END_QCALL; diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/InvokeUtils.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/InvokeUtils.cs index 86e962ed1ae58..5a8f1b0e8c600 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/InvokeUtils.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/InvokeUtils.cs @@ -124,7 +124,7 @@ private static bool TryConvertPointer(object srcObject, [NotNullWhen(true)] out return false; } - [MethodImpl(MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] // Two callers, one of them is potentially perf sensitive public static void PrimitiveWiden(ref byte srcElement, ref byte destElement, CorElementType srcElType, CorElementType destElType) { switch (srcElType) @@ -147,7 +147,7 @@ public static void PrimitiveWiden(ref byte srcElement, ref byte destElement, Cor case CorElementType.ELEMENT_TYPE_R8: Unsafe.As(ref destElement) = srcElement; break; default: - Debug.Fail("Array.Copy from U1 to another type hit unsupported widening conversion"); break; + Debug.Fail("Expected to be unreachable"); break; } break; From 353715e3860ad3284d318eef871a35d531e6da5f Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Mon, 24 Jun 2024 23:57:09 +0800 Subject: [PATCH 48/51] Remove unused enum FCall --- src/coreclr/System.Private.CoreLib/src/System/Enum.CoreCLR.cs | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Enum.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Enum.CoreCLR.cs index 0946f79ae674c..066ca50e60497 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Enum.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Enum.CoreCLR.cs @@ -14,9 +14,6 @@ public abstract partial class Enum [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "Enum_GetValuesAndNames")] private static partial void GetEnumValuesAndNames(QCallTypeHandle enumType, ObjectHandleOnStack values, ObjectHandleOnStack names, Interop.BOOL getNames); - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern unsafe CorElementType InternalGetCorElementType(MethodTable* pMT); - [MethodImpl(MethodImplOptions.AggressiveInlining)] private static unsafe CorElementType InternalGetCorElementType(RuntimeType rt) { From 8fb1c969b6e5b87c927ebaa4ee99c214a751b0af Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Tue, 25 Jun 2024 10:23:28 +0800 Subject: [PATCH 49/51] Use sizeof --- .../Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs index 0596b891c7fbf..1d25d108e250c 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs @@ -59,20 +59,20 @@ public static unsafe void InitializeArray(Array array, RuntimeFieldHandle fldHan { switch (pMT->ComponentSize) { - case 1: + case sizeof(byte): SpanHelpers.Memmove(ref dst, ref src, totalSize); break; - case 2: + case sizeof(ushort): BinaryPrimitives.ReverseEndianness( new ReadOnlySpan(ref Unsafe.As(ref src), array.Length), new Span(ref Unsafe.As(ref dst), array.Length)); break; - case 4: + case sizeof(uint): BinaryPrimitives.ReverseEndianness( new ReadOnlySpan(ref Unsafe.As(ref src), array.Length), new Span(ref Unsafe.As(ref dst), array.Length)); break; - case 8: + case sizeof(ulong): BinaryPrimitives.ReverseEndianness( new ReadOnlySpan(ref Unsafe.As(ref src), array.Length), new Span(ref Unsafe.As(ref dst), array.Length)); From 26d4c805b3bdac8b354bdc5fd004d4972fb3e9ca Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Tue, 25 Jun 2024 11:05:49 +0800 Subject: [PATCH 50/51] Add some comment --- .../src/System/Reflection/InvokeUtils.cs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/InvokeUtils.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/InvokeUtils.cs index 5a8f1b0e8c600..cb83cbefe6dcb 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/InvokeUtils.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/InvokeUtils.cs @@ -273,7 +273,11 @@ public static void PrimitiveWiden(ref byte srcElement, ref byte destElement, Cor [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool CanPrimitiveWiden(CorElementType srcET, CorElementType dstET) { - ReadOnlySpan primitiveAttributes = + // The primitive widen table + // The index represents source type. The value in the table is a bit vector of destination types. + // If corresponding bit is set in the bit vector, source type can be widened into that type. + // All types widen to themselves. + ReadOnlySpan primitiveWidenTable = [ 0x00, // ELEMENT_TYPE_END 0x00, // ELEMENT_TYPE_VOID @@ -292,12 +296,12 @@ public static bool CanPrimitiveWiden(CorElementType srcET, CorElementType dstET) ]; Debug.Assert(srcET.IsPrimitiveType() && dstET.IsPrimitiveType()); - if ((int)srcET >= primitiveAttributes.Length) + if ((int)srcET >= primitiveWidenTable.Length) { // I or U return srcET == dstET; } - return (primitiveAttributes[(int)srcET] & (1 << (int)dstET)) != 0; + return (primitiveWidenTable[(int)srcET] & (1 << (int)dstET)) != 0; } } } From 5f7263f7fa9c2194f4362d939c145ff47e7b46fa Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Thu, 27 Jun 2024 01:57:20 +0800 Subject: [PATCH 51/51] Add comment to lifetime Co-authored-by: Aaron Robinson --- .../System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs index 1d25d108e250c..052f6970a298e 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs @@ -44,7 +44,7 @@ public static unsafe void InitializeArray(Array array, RuntimeFieldHandle fldHan if (totalSize > size) throw new ArgumentException(SR.Argument_BadFieldForInitializeArray); - ref byte src = ref *(byte*)address; + ref byte src = ref *(byte*)address; // Ref is extending the lifetime of the static field. GC.KeepAlive(fldInfo); ref byte dst = ref MemoryMarshal.GetArrayDataReference(array); @@ -116,7 +116,7 @@ private static unsafe ref byte GetSpanDataFrom( } count = (int)(totalSize / targetTypeSize); - ref byte dataRef = ref *(byte*)data; + ref byte dataRef = ref *(byte*)data; // Ref is extending the lifetime of the static field. GC.KeepAlive(fldInfo); return ref dataRef;