Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
#if NET
using System.Runtime.Loader;
#endif
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using System.Threading;
Expand Down Expand Up @@ -180,7 +183,16 @@ internal JsonTypeInfo GetTypeInfoForRootType(Type type, bool fallBackToNearestAn

if (jsonTypeInfo?.Type != type)
{
_lastTypeInfo = jsonTypeInfo = GetTypeInfoInternal(type, fallBackToNearestAncestorType: fallBackToNearestAncestorType);
jsonTypeInfo = GetTypeInfoInternal(type, fallBackToNearestAncestorType: fallBackToNearestAncestorType);

#if NET
// Metadata for types defined in a collectible AssemblyLoadContext is evicted from the caching context
// when the AssemblyLoadContext unloads; this field would keep such metadata alive beyond that point.
if (!jsonTypeInfo.Type.IsCollectible)
#endif
{
_lastTypeInfo = jsonTypeInfo;
}
}

return jsonTypeInfo;
Expand Down Expand Up @@ -237,7 +249,10 @@ internal void ClearCaches()
internal sealed class CachingContext
{
private readonly ConcurrentDictionary<Type, CacheEntry> _cache = new();
#if !NET
#if NET
// Set once the cache has stored metadata for a type defined in a collectible AssemblyLoadContext.
private volatile bool _containsCollectibleTypes;
#else
private readonly Func<Type, CacheEntry> _cacheEntryFactory;
#endif

Expand Down Expand Up @@ -276,9 +291,45 @@ public void Clear()
_cache.Clear();
}

#if NET
/// <summary>
/// Removes the metadata of every type defined in a collectible <see cref="AssemblyLoadContext"/>.
/// A caching context can live for as long as the process does, and would otherwise keep such a context from unloading.
/// </summary>
public void RemoveCollectibleTypes()
{
if (!_containsCollectibleTypes)
{
return;
}

_containsCollectibleTypes = false;

foreach (KeyValuePair<Type, CacheEntry> entry in _cache)
{
if (entry.Key.IsCollectible)
{
_cache.TryRemove(entry.Key, out _);
}
}
}
#endif

private CacheEntry GetOrAddCacheEntry(Type type)
{
#if NET
if (_cache.TryGetValue(type, out CacheEntry? entry))
{
return entry;
}

if (type.IsCollectible)
{
// Make sure the entry gets evicted when the AssemblyLoadContext of the type unloads.
CollectibleTypeEviction.EnsureRegistered(type);
_containsCollectibleTypes = true;
}

return _cache.GetOrAdd(type, CreateCacheEntry, this);
#else
return _cache.GetOrAdd(type, _cacheEntryFactory);
Expand Down Expand Up @@ -415,6 +466,56 @@ public CacheEntry(ExceptionDispatchInfo exception)
}
}

#if NET
/// <summary>
/// Evicts the cached metadata of types defined in collectible <see cref="AssemblyLoadContext"/> instances
/// when one of these contexts starts unloading. The metadata caches hold on to the types they describe,
/// and they can live for as long as the process does, so without eviction the context could never unload.
/// </summary>
internal static class CollectibleTypeEviction
{
private static readonly ConditionalWeakTable<AssemblyLoadContext, object?> s_registeredContexts = new();

public static void EnsureRegistered(Type type)
{
Debug.Assert(type.IsCollectible);

if (type.HasElementType)
{
EnsureRegistered(type.GetElementType()!);
return;
}

if (type.IsConstructedGenericType)
{
// A constructed generic type is collectible as soon as one of its type arguments is.
foreach (Type typeArgument in type.GetGenericArguments())
{
if (typeArgument.IsCollectible)
{
EnsureRegistered(typeArgument);
}
}
}

if (AssemblyLoadContext.GetLoadContext(type.Assembly) is { IsCollectible: true } loadContext &&
s_registeredContexts.TryAdd(loadContext, null))
{
loadContext.Unloading += static _ => RemoveCollectibleTypesFromAllCaches();
}
}

private static void RemoveCollectibleTypesFromAllCaches()
{
// Types of other collectible contexts are evicted as well; their metadata is rebuilt on next use.
foreach (KeyValuePair<JsonSerializerOptions, object?> options in TrackedOptionsInstances.All)
{
options.Key._cachingContext?.RemoveCollectibleTypes();
}
}
}
#endif

/// <summary>
/// Defines a cache of CachingContexts; instead of using a ConditionalWeakTable which can be slow to traverse
/// this approach uses a fixed-size array of weak references of <see cref="CachingContext"/> that can be looked up lock-free.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,15 @@ private static void PopulateUnionConstructor(
}
}

caseIndex[runtimeType] = found;
#if NET
// The index belongs to the metadata of the union type, which can outlive a collectible AssemblyLoadContext,
// so it must not hold on to a runtime type defined in one. The result is recomputed instead.
if (!runtimeType.IsCollectible)
#endif
{
caseIndex[runtimeType] = found;
}

return found;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,12 +150,12 @@ public bool TryGetDerivedJsonTypeInfo(Type runtimeType, [NotNullWhen(true)] out
// Calculate (and cache the result) of the nearest ancestor for given runtime type.
// A `null` result denotes no matching ancestor type, we also cache that.
result = CalculateNearestAncestor(runtimeType);
_typeToDiscriminatorId[runtimeType] = result;
CacheRuntimeType(runtimeType, result);
break;
case JsonUnknownDerivedTypeHandling.FallBackToBaseType:
// Recover the polymorphic contract (i.e. any type discriminators) for the base type, if it exists.
_typeToDiscriminatorId.TryGetValue(BaseType, out result);
_typeToDiscriminatorId[runtimeType] = result;
CacheRuntimeType(runtimeType, result);
break;

case JsonUnknownDerivedTypeHandling.FailSerialization:
Expand All @@ -182,6 +182,19 @@ public bool TryGetDerivedJsonTypeInfo(Type runtimeType, [NotNullWhen(true)] out
}
}

private void CacheRuntimeType(Type runtimeType, DerivedJsonTypeInfo? result)
{
#if NET
// The resolver can belong to a base type that outlives a collectible AssemblyLoadContext,
// so it must not hold on to a runtime type defined in one. The result is recomputed instead.
if (runtimeType.IsCollectible)
{
return;
}
#endif
_typeToDiscriminatorId[runtimeType] = result;
}

public bool TryGetDerivedJsonTypeInfo(object typeDiscriminator, [NotNullWhen(true)] out JsonTypeInfo? jsonTypeInfo)
{
Debug.Assert(typeDiscriminator is int or string);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,24 @@
// The .NET Foundation licenses this file to you under the MIT license.

#if NETFRAMEWORK || NET
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.CompilerServices;

namespace System.Text.Json.Serialization.Metadata
{
internal sealed partial class ReflectionEmitCachingMemberAccessor : MemberAccessor
{
private readonly ReflectionEmitMemberAccessor _sourceAccessor;
private readonly Cache<(string id, Type declaringType, MemberInfo? member)> _cache;
#if NET
// This accessor is a process-wide singleton, so a strong cache entry for a type or member defined in a collectible
// AssemblyLoadContext would keep that context from unloading. The delegates emitted for such types are cached
// per owning type in a ConditionalWeakTable instead, and go away together with the type.
private readonly ConditionalWeakTable<Type, ConcurrentDictionary<(string id, Type declaringType, MemberInfo? member), object?>> _collectibleTypeCache = new();
#endif

[RequiresDynamicCode(JsonSerializer.SerializationRequiresDynamicCodeMessage)]
[RequiresUnreferencedCode(JsonSerializer.SerializationRequiresDynamicCodeMessage)]
Expand All @@ -21,65 +29,93 @@ public ReflectionEmitCachingMemberAccessor()
_cache = new(slidingExpiration: TimeSpan.FromMilliseconds(1000), evictionInterval: TimeSpan.FromMilliseconds(200));
}

public override void Clear() => _cache.Clear();
public override void Clear()
{
_cache.Clear();
#if NET
_collectibleTypeCache.Clear();
#endif
}

private TValue GetOrAdd<TValue>((string id, Type declaringType, MemberInfo? member) key, Func<(string id, Type declaringType, MemberInfo? member), TValue> valueFactory)
where TValue : class?
{
#if NET
// The member is the more specific of the two: its declaring type can depend on the type in the key, but not the reverse.
Type? collectibleOwner =
key.member is { IsCollectible: true } member ? member.DeclaringType ?? key.declaringType :
key.declaringType.IsCollectible ? key.declaringType :
null;

if (collectibleOwner is not null)
{
return (TValue)_collectibleTypeCache.GetOrCreateValue(collectibleOwner).GetOrAdd(
key,
static (key, valueFactory) => valueFactory(key),
valueFactory)!;
}
#endif

return _cache.GetOrAdd(key, valueFactory);
}

public override Action<TCollection, object?> CreateAddMethodDelegate<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] TCollection>() =>
_cache.GetOrAdd(
GetOrAdd(
key: (nameof(CreateAddMethodDelegate), typeof(TCollection), null),
_ => _sourceAccessor.CreateAddMethodDelegate<TCollection>());

public override Func<object>? CreateParameterlessConstructor(Type type, ConstructorInfo? ctorInfo) =>
_cache.GetOrAdd(
GetOrAdd(
key: (nameof(CreateParameterlessConstructor), type, ctorInfo),
valueFactory: key => _sourceAccessor.CreateParameterlessConstructor(key.declaringType, (ConstructorInfo?)key.member));

public override Func<object, TProperty> CreateFieldGetter<TProperty>(FieldInfo fieldInfo) =>
_cache.GetOrAdd(
GetOrAdd(
key: (nameof(CreateFieldGetter), typeof(TProperty), fieldInfo),
valueFactory: key => _sourceAccessor.CreateFieldGetter<TProperty>((FieldInfo)key.member!));

public override Action<object, TProperty> CreateFieldSetter<TProperty>(FieldInfo fieldInfo) =>
_cache.GetOrAdd(
GetOrAdd(
key: (nameof(CreateFieldSetter), typeof(TProperty), fieldInfo),
valueFactory: key => _sourceAccessor.CreateFieldSetter<TProperty>((FieldInfo)key.member!));

public override Func<IEnumerable<KeyValuePair<TKey, TValue>>, TCollection> CreateImmutableDictionaryCreateRangeDelegate<TCollection, TKey, TValue>() =>
_cache.GetOrAdd(
GetOrAdd(
key: (nameof(CreateImmutableDictionaryCreateRangeDelegate), typeof((TCollection, TKey, TValue)), null),
valueFactory: _ => _sourceAccessor.CreateImmutableDictionaryCreateRangeDelegate<TCollection, TKey, TValue>());

public override Func<IEnumerable<TElement>, TCollection> CreateImmutableEnumerableCreateRangeDelegate<TCollection, TElement>() =>
_cache.GetOrAdd(
GetOrAdd(
key: (nameof(CreateImmutableEnumerableCreateRangeDelegate), typeof((TCollection, TElement)), null),
valueFactory: _ => _sourceAccessor.CreateImmutableEnumerableCreateRangeDelegate<TCollection, TElement>());

public override Func<object?[], T> CreateParameterizedConstructor<T>(ConstructorInfo constructor) =>
_cache.GetOrAdd(
GetOrAdd(
key: (nameof(CreateParameterizedConstructor), typeof(T), constructor),
valueFactory: key => _sourceAccessor.CreateParameterizedConstructor<T>((ConstructorInfo)key.member!));

public override JsonTypeInfo.ParameterizedConstructorDelegate<T, TArg0, TArg1, TArg2, TArg3>? CreateParameterizedConstructor<T, TArg0, TArg1, TArg2, TArg3>(ConstructorInfo constructor) =>
_cache.GetOrAdd(
GetOrAdd(
key: (nameof(CreateParameterizedConstructor), typeof(T), constructor),
valueFactory: key => _sourceAccessor.CreateParameterizedConstructor<T, TArg0, TArg1, TArg2, TArg3>((ConstructorInfo)key.member!));

public override Func<object?, T> CreateSingleParameterConstructor<T>(ConstructorInfo constructor) =>
_cache.GetOrAdd(
GetOrAdd(
key: (nameof(CreateSingleParameterConstructor), typeof(T), constructor),
valueFactory: key => _sourceAccessor.CreateSingleParameterConstructor<T>((ConstructorInfo)key.member!));

public override Func<object, TProperty> CreatePropertyGetter<TProperty>(PropertyInfo propertyInfo) =>
_cache.GetOrAdd(
GetOrAdd(
key: (nameof(CreatePropertyGetter), typeof(TProperty), propertyInfo),
valueFactory: key => _sourceAccessor.CreatePropertyGetter<TProperty>((PropertyInfo)key.member!));

public override Func<TDeclaringType, TProperty> CreatePropertyGetter<TDeclaringType, TProperty>(PropertyInfo propertyInfo) =>
_cache.GetOrAdd(
GetOrAdd(
key: ("CreatePropertyGetter`2", typeof((TDeclaringType, TProperty)), propertyInfo),
valueFactory: key => _sourceAccessor.CreatePropertyGetter<TDeclaringType, TProperty>((PropertyInfo)key.member!));

public override Action<object, TProperty> CreatePropertySetter<TProperty>(PropertyInfo propertyInfo) =>
_cache.GetOrAdd(
GetOrAdd(
key: (nameof(CreatePropertySetter), typeof(TProperty), propertyInfo),
valueFactory: key => _sourceAccessor.CreatePropertySetter<TProperty>((PropertyInfo)key.member!));

Expand Down
Loading
Loading