Skip to content

Fix DeepEquals_DeepJsonDocument stack overflow that manifests in xunit.console and netfx. #105309

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

Merged
Merged
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
3 changes: 3 additions & 0 deletions src/libraries/System.Text.Json/src/Resources/Strings.resx
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,9 @@
<data name="JsonElementHasWrongType" xml:space="preserve">
<value>The requested operation requires an element of type '{0}', but the target element has type '{1}'.</value>
</data>
<data name="JsonElementDeepEqualsInsufficientExecutionStack" xml:space="preserve">
<value>Insufficient stack to continue executing 'JsonElement.DeepEquals'. This can happen either because the 'JsonElement' values are too deep or 'DeepEquals' is being called too deep in the stack.</value>
</data>
<data name="JsonNumberExponentTooLarge" xml:space="preserve">
<value>The exponent value in the specified JSON number is too large.</value>
</data>
Expand Down
1 change: 1 addition & 0 deletions src/libraries/System.Text.Json/src/System.Text.Json.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@ The System.Text.Json library is built-in as part of the shared framework in .NET
<Compile Include="System\Text\Json\Serialization\Metadata\JsonTypeInfoResolverWithAddedModifiers.cs" />
<Compile Include="System\Text\Json\Serialization\Metadata\PropertyRefCacheBuilder.cs" />
<Compile Include="System\Text\Json\Serialization\PolymorphicSerializationState.cs" />
<Compile Include="System\Text\Json\StackHelper.cs" />
<Compile Include="System\Text\Json\ValueQueue.cs" />
<Compile Include="System\Text\Json\Writer\Utf8JsonWriterCache.cs" />
<Compile Include="System\Text\Json\Serialization\ReferenceEqualsWrapper.cs" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1262,6 +1262,11 @@ internal ReadOnlySpan<byte> ValueSpan
/// </remarks>
public static bool DeepEquals(JsonElement element1, JsonElement element2)
{
if (!StackHelper.TryEnsureSufficientExecutionStack())
{
ThrowHelper.ThrowInsufficientExecutionStackException_JsonElementDeepEqualsInsufficientExecutionStack();
}

element1.CheckValidInstance();
element2.CheckValidInstance();

Expand Down
29 changes: 29 additions & 0 deletions src/libraries/System.Text.Json/src/System/Text/Json/StackHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Runtime.CompilerServices;

namespace System.Text.Json
{
/// <summary>Provides tools for avoiding stack overflows.</summary>
internal static class StackHelper
{
/// <summary>Tries to ensure there is sufficient stack to execute the average .NET function.</summary>
public static bool TryEnsureSufficientExecutionStack()
{
#if NET
return RuntimeHelpers.TryEnsureSufficientExecutionStack();
#else
try
{
RuntimeHelpers.EnsureSufficientExecutionStack();
return true;
}
catch
{
return false;
}
#endif
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -719,6 +719,12 @@ public static void ThrowObjectDisposedException_JsonDocument()
{
throw new ObjectDisposedException(nameof(JsonDocument));
}

[DoesNotReturn]
public static void ThrowInsufficientExecutionStackException_JsonElementDeepEqualsInsufficientExecutionStack()
{
throw new InsufficientExecutionStackException(SR.JsonElementDeepEqualsInsufficientExecutionStack);
}
}

internal enum ExceptionResource
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -221,11 +221,26 @@ public static void DeepEquals_NotEqualValuesReturnFalse(string value1, string va
[Theory]
[InlineData(10)]
[InlineData(100)]
[InlineData(1000)]
[InlineData(500)]
public static void DeepEquals_DeepJsonDocument(int depth)
{
using JsonDocument jDoc = CreateDeepJsonDocument(depth);
JsonElement element = jDoc.RootElement;
Assert.True(JsonElement.DeepEquals(element, element));
}

[Fact]
public static void DeepEquals_TooDeepJsonDocument_ThrowsInsufficientExecutionStackException()
{
using JsonDocument jDoc = CreateDeepJsonDocument(10_000);
JsonElement element = jDoc.RootElement;
Assert.Throws<InsufficientExecutionStackException>(() => JsonElement.DeepEquals(element, element));
}

private static JsonDocument CreateDeepJsonDocument(int depth)
{
ArrayBufferWriter<byte> bufferWriter = new();
using Utf8JsonWriter writer = new(bufferWriter);
using Utf8JsonWriter writer = new(bufferWriter, new() { MaxDepth = depth + 1 });

for (int i = 0; i < depth; i++)
{
Expand Down Expand Up @@ -257,10 +272,7 @@ public static void DeepEquals_DeepJsonDocument(int depth)
writer.Flush();

JsonDocumentOptions options = new JsonDocumentOptions { MaxDepth = depth };
using JsonDocument jDoc = JsonDocument.Parse(bufferWriter.WrittenSpan.ToArray(), options);
JsonElement element = jDoc.RootElement;

Assert.True(JsonElement.DeepEquals(element, element));
return JsonDocument.Parse(bufferWriter.WrittenSpan.ToArray(), options);
}
}
}
Loading