Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent runtime prop metadata retrieval when [JsonIgnore] is used #60024

Merged
merged 4 commits into from
Oct 12, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
13 changes: 13 additions & 0 deletions src/libraries/System.Text.Json/Common/ReflectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -310,5 +310,18 @@ public static bool TryGetDeserializationConstructor(
deserializationCtor = ctorWithAttribute ?? publicParameterlessCtor ?? lonePublicCtor;
return true;
}

public static object? GetDefaultValue(this ParameterInfo parameterInfo)
eiriktsarpalis marked this conversation as resolved.
Show resolved Hide resolved
{
object? defaultValue = parameterInfo.DefaultValue;

// DBNull.Value is sometimes used as the default value (returned by reflection) of nullable params in place of null.
if (defaultValue == DBNull.Value && parameterInfo.ParameterType != typeof(DBNull))
{
return null;
}

return defaultValue;
}
}
}
15 changes: 10 additions & 5 deletions src/libraries/System.Text.Json/gen/JsonSourceGenerator.Emitter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -797,23 +797,28 @@ private string GenerateCtorParamMetadataInitFunc(TypeGenerationSpec typeGenerati
private static {JsonParameterInfoValuesTypeRef}[] {typeGenerationSpec.TypeInfoPropertyName}{CtorParamInitMethodNameSuffix}()
{{
{JsonParameterInfoValuesTypeRef}[] {parametersVarName} = new {JsonParameterInfoValuesTypeRef}[{paramCount}];
{JsonParameterInfoValuesTypeRef} info;
");

for (int i = 0; i < paramCount; i++)
{
ParameterInfo reflectionInfo = parameters[i].ParameterInfo;

string parameterTypeRef = reflectionInfo.ParameterType.GetCompilableName();

object? defaultValue = reflectionInfo.GetDefaultValue();
string defaultValueAsStr = defaultValue == null
? $"default({parameterTypeRef})"
layomia marked this conversation as resolved.
Show resolved Hide resolved
: GetParamDefaultValueAsString(defaultValue);

sb.Append(@$"
{InfoVarName} = new()
{parametersVarName}[{i}] = new()
{{
Name = ""{reflectionInfo.Name!}"",
ParameterType = typeof({reflectionInfo.ParameterType.GetCompilableName()}),
ParameterType = typeof({parameterTypeRef}),
Position = {reflectionInfo.Position},
HasDefaultValue = {ToCSharpKeyword(reflectionInfo.HasDefaultValue)},
DefaultValue = {GetParamDefaultValueAsString(reflectionInfo.DefaultValue)}
DefaultValue = {defaultValueAsStr}
}};
{parametersVarName}[{i}] = {InfoVarName};
layomia marked this conversation as resolved.
Show resolved Hide resolved
");
}

Expand Down
23 changes: 20 additions & 3 deletions src/libraries/System.Text.Json/gen/JsonSourceGenerator.Parser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ private sealed class Parser
private const string SystemTextJsonNamespace = "System.Text.Json";
private const string JsonConverterAttributeFullName = "System.Text.Json.Serialization.JsonConverterAttribute";
private const string JsonConverterFactoryFullName = "System.Text.Json.Serialization.JsonConverterFactory";
private const string JsonConverterOfTFullName = "System.Text.Json.Serialization.JsonConverter`1";
private const string JsonArrayFullName = "System.Text.Json.Nodes.JsonArray";
private const string JsonElementFullName = "System.Text.Json.JsonElement";
private const string JsonExtensionDataAttributeFullName = "System.Text.Json.Serialization.JsonExtensionDataAttribute";
Expand Down Expand Up @@ -101,6 +102,9 @@ private sealed class Parser
private readonly Type? _dateOnlyType;
private readonly Type? _timeOnlyType;

// Needed for converter validation
private readonly Type _jsonConverterOfTType;

private readonly HashSet<Type> _numberTypes = new();
private readonly HashSet<Type> _knownTypes = new();
private readonly HashSet<Type> _knownUnsupportedTypes = new();
Expand Down Expand Up @@ -215,6 +219,8 @@ public Parser(Compilation compilation, in JsonSourceGenerationContext sourceGene
_dateOnlyType = _metadataLoadContext.Resolve(DateOnlyFullName);
_timeOnlyType = _metadataLoadContext.Resolve(TimeOnlyFullName);

_jsonConverterOfTType = _metadataLoadContext.Resolve(JsonConverterOfTFullName);

PopulateKnownTypes();
}

Expand All @@ -224,8 +230,12 @@ public Parser(Compilation compilation, in JsonSourceGenerationContext sourceGene
INamedTypeSymbol jsonSerializerContextSymbol = compilation.GetBestTypeByMetadataName(JsonSerializerContextFullName);
INamedTypeSymbol jsonSerializableAttributeSymbol = compilation.GetBestTypeByMetadataName(JsonSerializerAttributeFullName);
INamedTypeSymbol jsonSourceGenerationOptionsAttributeSymbol = compilation.GetBestTypeByMetadataName(JsonSourceGenerationOptionsAttributeFullName);
INamedTypeSymbol jsonConverterOfTAttributeSymbol = compilation.GetBestTypeByMetadataName(JsonConverterOfTFullName);

if (jsonSerializerContextSymbol == null || jsonSerializableAttributeSymbol == null || jsonSourceGenerationOptionsAttributeSymbol == null)
if (jsonSerializerContextSymbol == null ||
jsonSerializableAttributeSymbol == null ||
jsonSourceGenerationOptionsAttributeSymbol == null ||
jsonConverterOfTAttributeSymbol == null)
{
return null;
}
Expand Down Expand Up @@ -1354,7 +1364,14 @@ private static bool PropertyAccessorCanBeReferenced(MethodInfo? accessor)
return null;
}

if (converterType.GetCompatibleBaseClass(JsonConverterFactoryFullName) != null)
// Validated when creating the source generation spec.
Debug.Assert(_jsonConverterOfTType != null);

if (converterType.GetCompatibleGenericBaseClass(_jsonConverterOfTType) != null)
{
return $"new {converterType.GetCompilableName()}()";
}
else if (converterType.GetCompatibleBaseClass(JsonConverterFactoryFullName) != null)
{
hasFactoryConverter = true;

Expand All @@ -1368,7 +1385,7 @@ private static bool PropertyAccessorCanBeReferenced(MethodInfo? accessor)
}
}

return $"new {converterType.GetCompilableName()}()";
return null;
}

private static string DetermineRuntimePropName(string clrPropName, string? jsonPropName, JsonKnownNamingPolicy namingPolicy)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,7 @@ protected sealed override void InitializeConstructorArgumentCaches(ref ReadStack
{
JsonParameterInfo? parameterInfo = cache[i].Value;
Debug.Assert(parameterInfo != null);

arguments[parameterInfo.ClrInfo.Position] = parameterInfo.ShouldDeserialize
? parameterInfo.DefaultValue
: parameterInfo.ClrDefaultValue;
arguments[parameterInfo.ClrInfo.Position] = parameterInfo.DefaultValue;
}

state.Current.CtorArgumentState!.Arguments = arguments;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,34 +92,32 @@ protected override void InitializeConstructorArgumentCaches(ref ReadStack state,
JsonParameterInfo? parameterInfo = cache[i].Value;
Debug.Assert(parameterInfo != null);

// We can afford not to set default values for ctor arguments when we should't deserialize because the
// type parameters of the `Arguments` type provide default semantics that work well with value types.
if (parameterInfo.ShouldDeserialize)
switch (parameterInfo.ClrInfo.Position)
{
int position = parameterInfo.ClrInfo.Position;

switch (position)
{
case 0:
arguments.Arg0 = ((JsonParameterInfo<TArg0>)parameterInfo).TypedDefaultValue!;
break;
case 1:
arguments.Arg1 = ((JsonParameterInfo<TArg1>)parameterInfo).TypedDefaultValue!;
break;
case 2:
arguments.Arg2 = ((JsonParameterInfo<TArg2>)parameterInfo).TypedDefaultValue!;
break;
case 3:
arguments.Arg3 = ((JsonParameterInfo<TArg3>)parameterInfo).TypedDefaultValue!;
break;
default:
Debug.Fail("More than 4 params: we should be in override for LargeObjectWithParameterizedConstructorConverter.");
throw new InvalidOperationException();
}
case 0:
arguments.Arg0 = GetDefaultValue<TArg0>(parameterInfo);
break;
case 1:
arguments.Arg1 = GetDefaultValue<TArg1>(parameterInfo);
break;
case 2:
arguments.Arg2 = GetDefaultValue<TArg2>(parameterInfo);
break;
case 3:
arguments.Arg3 = GetDefaultValue<TArg3>(parameterInfo);
break;
default:
Debug.Fail("More than 4 params: we should be in override for LargeObjectWithParameterizedConstructorConverter.");
throw new InvalidOperationException();
}
}

state.Current.CtorArgumentState!.Arguments = arguments;

static TArg GetDefaultValue<TArg>(JsonParameterInfo parameterInfo)
=> parameterInfo.ShouldDeserialize
? ((JsonParameterInfo<TArg>)parameterInfo).TypedDefaultValue
: parameterInfo.ClrInfo.HasDefaultValue ? (TArg?)parameterInfo.DefaultValue! : default(TArg)!;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@ internal abstract class JsonParameterInfo

private protected bool MatchingPropertyCanBeNull { get; private set; }

internal abstract object? ClrDefaultValue { get; }

// The default value of the parameter. This is `DefaultValue` of the `ParameterInfo`, if specified, or the CLR `default` for the `ParameterType`.
public object? DefaultValue { get; private protected set; }

Expand Down Expand Up @@ -78,14 +76,12 @@ public virtual void Initialize(JsonParameterInfoValues parameterInfo, JsonProper
// prevent issues with unsupported types and helps ensure we don't accidently (de)serialize it.
public static JsonParameterInfo CreateIgnoredParameterPlaceholder(JsonParameterInfoValues parameterInfo, JsonPropertyInfo matchingProperty)
{
JsonParameterInfo jsonParameterInfo = matchingProperty.ConverterBase.CreateJsonParameterInfo();
JsonParameterInfo jsonParameterInfo = new JsonParameterInfo<sbyte>();
jsonParameterInfo.ClrInfo = parameterInfo;
jsonParameterInfo.RuntimePropertyType = matchingProperty.RuntimePropertyType!;
jsonParameterInfo.NameAsUtf8Bytes = matchingProperty.NameAsUtf8Bytes!;
jsonParameterInfo.InitializeDefaultValue(matchingProperty);
jsonParameterInfo.DefaultValue = parameterInfo.DefaultValue;
return jsonParameterInfo;
}

protected abstract void InitializeDefaultValue(JsonPropertyInfo matchingProperty);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ namespace System.Text.Json.Serialization.Metadata
/// </summary>
internal sealed class JsonParameterInfo<T> : JsonParameterInfo
{
internal override object? ClrDefaultValue => default(T);

public T TypedDefaultValue { get; private set; } = default!;

public override void Initialize(JsonParameterInfoValues parameterInfo, JsonPropertyInfo matchingProperty, JsonSerializerOptions options)
Expand All @@ -21,7 +19,7 @@ public override void Initialize(JsonParameterInfoValues parameterInfo, JsonPrope
InitializeDefaultValue(matchingProperty);
}

protected override void InitializeDefaultValue(JsonPropertyInfo matchingProperty)
private void InitializeDefaultValue(JsonPropertyInfo matchingProperty)
{
Debug.Assert(ClrInfo.ParameterType == matchingProperty.DeclaredPropertyType);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,16 +42,14 @@ internal static JsonPropertyInfo GetPropertyPlaceholder()

// Create a property that is ignored at run-time.
internal static JsonPropertyInfo CreateIgnoredPropertyPlaceholder(
JsonConverter converter,
MemberInfo memberInfo,
Type memberType,
bool isVirtual,
JsonSerializerOptions options)
{
JsonPropertyInfo jsonPropertyInfo = converter.CreateJsonPropertyInfo();
JsonPropertyInfo jsonPropertyInfo = new JsonPropertyInfo<sbyte>();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you also add a comment here explaining why sbyte is being used?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will be sure to do so in a follow up to avoid CI reset. It will be the same as the comment on CreateIgnoredParameterPlaceholder below.


jsonPropertyInfo.Options = options;
jsonPropertyInfo.ConverterBase = converter;
jsonPropertyInfo.MemberInfo = memberInfo;
jsonPropertyInfo.IsIgnored = true;
jsonPropertyInfo.DeclaredPropertyType = memberType;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,19 +58,19 @@ internal static JsonPropertyInfo AddProperty(
JsonNumberHandling? parentTypeNumberHandling,
JsonSerializerOptions options)
{
JsonIgnoreCondition? ignoreCondition = JsonPropertyInfo.GetAttribute<JsonIgnoreAttribute>(memberInfo)?.Condition;
if (ignoreCondition == JsonIgnoreCondition.Always)
{
return JsonPropertyInfo.CreateIgnoredPropertyPlaceholder(memberInfo, memberType, isVirtual, options);
}

JsonConverter converter = GetConverter(
memberType,
parentClassType,
memberInfo,
out Type runtimeType,
options);

JsonIgnoreCondition? ignoreCondition = JsonPropertyInfo.GetAttribute<JsonIgnoreAttribute>(memberInfo)?.Condition;
if (ignoreCondition == JsonIgnoreCondition.Always)
{
return JsonPropertyInfo.CreateIgnoredPropertyPlaceholder(converter, memberInfo, memberType, isVirtual, options);
}

return CreateProperty(
declaredPropertyType: memberType,
runtimePropertyType: runtimeType,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -530,7 +530,7 @@ private static JsonParameterInfoValues[] GetParameterInfoArray(ParameterInfo[] p
ParameterType = reflectionInfo.ParameterType,
Position = reflectionInfo.Position,
HasDefaultValue = reflectionInfo.HasDefaultValue,
DefaultValue = reflectionInfo.DefaultValue
DefaultValue = reflectionInfo.GetDefaultValue()
};

jsonParameters[i] = jsonInfo;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1216,5 +1216,48 @@ public class TypeWithUri

public TypeWithUri(Uri myUri = default) => MyUri = myUri;
}

[Fact]
public async Task SmallObject_DefaultParamValueUsed_WhenMatchingPropIgnored()
{
string json = @"{""Prop"":20}";
var obj = await JsonSerializerWrapperForString.DeserializeWrapper<SmallType_IgnoredProp_Bind_ParamWithDefaultValue>(json);
Assert.Equal(5, obj.Prop);
}

public class SmallType_IgnoredProp_Bind_ParamWithDefaultValue
{
[JsonIgnore]
public int Prop { get; set; }

public SmallType_IgnoredProp_Bind_ParamWithDefaultValue(int prop = 5)
=> Prop = prop;
}


[Fact]
public async Task LargeObject_DefaultParamValueUsed_WhenMatchingPropIgnored()
{
string json = @"{""Prop"":20}";
var obj = await JsonSerializerWrapperForString.DeserializeWrapper<LargeType_IgnoredProp_Bind_ParamWithDefaultValue>(json);
Assert.Equal(5, obj.Prop);
}

public class LargeType_IgnoredProp_Bind_ParamWithDefaultValue
{
public int W { get; set; }

public int X { get; set; }

public int Y { get; set; }

public int Z { get; set; }

[JsonIgnore]
public int Prop { get; set; }

public LargeType_IgnoredProp_Bind_ParamWithDefaultValue(int w, int x, int y, int z, int prop = 5)
=> Prop = prop;
}
}
}
Loading