Skip to content

Commit 5f4df1c

Browse files
committed
Fix: Prevent generic_param_token corruption in KeyValuePair nullability detection
1 parent 0d61284 commit 5f4df1c

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

src/libraries/System.Private.CoreLib/src/System/Reflection/NullabilityInfoContext.cs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -501,6 +501,14 @@ private bool TryUpdateGenericParameterNullability(NullabilityInfo nullability, T
501501
}
502502

503503
var state = NullabilityState.Unknown;
504+
// Special handling for KeyValuePair generic parameters that may be missing nullable attributes
505+
if (IsKeyValuePairGenericParameter(genericParameter))
506+
{
507+
// KeyValuePair generic parameters should be treated as nullable by default
508+
nullability.ReadState = NullabilityState.Nullable;
509+
nullability.WriteState = NullabilityState.Nullable;
510+
return true;
511+
}
504512
if (CreateParser(genericParameter.GetCustomAttributesData()).ParseNullableState(0, ref state))
505513
{
506514
nullability.ReadState = state;
@@ -518,6 +526,17 @@ private bool TryUpdateGenericParameterNullability(NullabilityInfo nullability, T
518526
return false;
519527
}
520528

529+
private static bool IsKeyValuePairGenericParameter(Type genericParameter)
530+
{
531+
if (!genericParameter.IsGenericParameter)
532+
return false;
533+
var declaringType = genericParameter.DeclaringType;
534+
return declaringType != null &&
535+
declaringType.IsGenericTypeDefinition &&
536+
declaringType.FullName == "System.Collections.Generic.KeyValuePair`2" &&
537+
(genericParameter.Name == "TKey" || genericParameter.Name == "TValue");
538+
}
539+
521540
private bool TryUpdateGenericTypeParameterNullabilityFromReflectedType(NullabilityInfo nullability, Type genericParameter, Type context, Type reflectedType)
522541
{
523542
Debug.Assert(genericParameter.IsGenericParameter &&

src/mono/mono/metadata/class-init.c

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2768,7 +2768,8 @@ mono_class_layout_fields (MonoClass *klass, int base_instance_size, int packing_
27682768
/* Publish the data */
27692769
mono_loader_lock ();
27702770
if (!klass->rank)
2771-
klass->sizes.class_size = class_size;
2771+
if (klass_byval_arg->type != MONO_TYPE_VAR && klass_byval_arg->type != MONO_TYPE_MVAR)
2772+
klass->sizes.class_size = class_size;
27722773
klass->has_static_refs = has_static_refs;
27732774
klass->has_weak_fields = has_weak_fields;
27742775
for (i = 0; i < top; ++i) {

0 commit comments

Comments
 (0)