-
Notifications
You must be signed in to change notification settings - Fork 4.8k
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
Implement WriteStringValueSegment defined in Issue 67337 #101356
Open
ificator
wants to merge
26
commits into
dotnet:main
Choose a base branch
from
ificator:user/ificator/writestringvaluesegment
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
26 commits
Select commit
Hold shift + click to select a range
9122ef8
Implement WriteStringValueSegment defined in Issue 67337
ificator e044b13
Fix some review comments
ificator e7abe7f
merge upstream/main
ificator b8d578c
Handle split surrogate pair
ificator 181cef2
Merge remote-tracking branch 'upstream/main' into user/ificator/write…
ificator 65006ce
Commit old changes responding to comments
ificator 1601af8
utf8 and utf16
PranavSenthilnathan d6b66be
fix build error
PranavSenthilnathan a46a1cc
Update src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf…
PranavSenthilnathan b5d0c17
Update src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf…
PranavSenthilnathan 4a0d1c6
PR comments
PranavSenthilnathan 09d321d
Merge branch 'main' of https://github.com/dotnet/runtime into user/if…
PranavSenthilnathan 96ed922
add encoding flags
PranavSenthilnathan a078bfd
add test for switching encoding
PranavSenthilnathan 93e6ee9
use CoreLib Rune for polyfill instead of having a separate copy
PranavSenthilnathan 501813f
Merge branch 'main' of https://github.com/dotnet/runtime into user/if…
PranavSenthilnathan c3b1c3b
move warning disabling to top and fix up tests
PranavSenthilnathan c9c4884
add fuzzer
PranavSenthilnathan 8482b1c
Fix some tests I missed
PranavSenthilnathan d50bbca
clean up and add another test to fuzzer
PranavSenthilnathan 55827d9
comment typo
PranavSenthilnathan a5cd855
pr comments
PranavSenthilnathan c82b035
Merge branch 'main' of https://github.com/dotnet/runtime into user/if…
PranavSenthilnathan 4f63907
Merge branch 'user/ificator/writestringvaluesegment' of https://githu…
PranavSenthilnathan b7fd4a5
throw when encodings are mixed
PranavSenthilnathan c0a700c
update fuzzer to assert that mixing encodings always throws
PranavSenthilnathan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -45,4 +45,24 @@ static void Throw(ReadOnlySpan<T> expected, ReadOnlySpan<T> actual) | |
throw new Exception($"Expected={expected[diffIndex]} Actual={actual[diffIndex]} at index {diffIndex}"); | ||
} | ||
} | ||
|
||
public static void Throws<T, TState>(Action<TState> action, TState state) | ||
where T : Exception | ||
where TState : allows ref struct | ||
{ | ||
try | ||
{ | ||
action(state); | ||
} | ||
catch (T) | ||
{ | ||
return; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Consider returning the caught exception, since that's what existing |
||
} | ||
catch (Exception ex) | ||
{ | ||
throw new Exception($"Expected exception of type {typeof(T).Name} but got {ex.GetType().Name}"); | ||
} | ||
|
||
throw new Exception($"Expected exception of type {typeof(T).Name} but no exception was thrown"); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
214 changes: 214 additions & 0 deletions
214
src/libraries/Fuzzing/DotnetFuzzing/Fuzzers/Utf8JsonWriterFuzzer.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,214 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System; | ||
using System.Buffers; | ||
using System.Collections; | ||
using System.Collections.Generic; | ||
using System.Diagnostics; | ||
using System.IO; | ||
using System.Runtime.CompilerServices; | ||
using System.Runtime.InteropServices; | ||
using System.Text; | ||
using System.Text.Encodings.Web; | ||
using System.Text.Json; | ||
using System.Text.Unicode; | ||
using SharpFuzz; | ||
|
||
namespace DotnetFuzzing.Fuzzers; | ||
|
||
internal sealed class Utf8JsonWriterFuzzer : IFuzzer | ||
{ | ||
public string[] TargetAssemblies { get; } = ["System.Text.Json"]; | ||
|
||
public string[] TargetCoreLibPrefixes => []; | ||
|
||
// One of the bytes in the input is used to set various test options. | ||
// Each bit in that byte represents a different option as indicated here. | ||
|
||
// Options for JsonWriterOptions | ||
private const byte IndentFlag = 1; | ||
PranavSenthilnathan marked this conversation as resolved.
Show resolved
Hide resolved
|
||
private const byte EncoderFlag = 1 << 1; | ||
private const byte MaxDepthFlag = 1 << 2; | ||
private const byte NewLineFlag = 1 << 3; | ||
private const byte SkipValidationFlag = 1 << 4; | ||
|
||
// Options for choosing between UTF-8 and UTF-16 encoding | ||
private const byte EncodingFlag = 1 << 5; | ||
|
||
public void FuzzTarget(ReadOnlySpan<byte> bytes) | ||
{ | ||
const int minLength = 10; // 2 ints, 1 byte, and 1 padding to align chars | ||
if (bytes.Length < minLength) | ||
{ | ||
return; | ||
} | ||
|
||
// First 2 ints are used as indices to slice the input and the following byte is used for options | ||
ReadOnlySpan<int> ints = MemoryMarshal.Cast<byte, int>(bytes); | ||
int slice1 = ints[0]; | ||
int slice2 = ints[1]; | ||
byte optionsByte = bytes[8]; | ||
bytes = bytes.Slice(minLength); | ||
ReadOnlySpan<char> chars = MemoryMarshal.Cast<byte, char>(bytes); | ||
|
||
// Validate that the indices are within bounds of the input | ||
bool utf8 = (optionsByte & EncodingFlag) == 0; | ||
if (!(0 <= slice1 && slice1 <= slice2 && slice2 <= (utf8 ? bytes.Length : chars.Length))) | ||
{ | ||
return; | ||
} | ||
|
||
// Set up options based on the first byte | ||
bool indented = (optionsByte & IndentFlag) == 0; | ||
JsonWriterOptions options = new() | ||
{ | ||
Encoder = (optionsByte & EncodingFlag) == 0 ? JavaScriptEncoder.Default : JavaScriptEncoder.UnsafeRelaxedJsonEscaping, | ||
Indented = indented, | ||
MaxDepth = (optionsByte & MaxDepthFlag) == 0 ? 1 : 0, | ||
PranavSenthilnathan marked this conversation as resolved.
Show resolved
Hide resolved
|
||
NewLine = (optionsByte & NewLineFlag) == 0 ? "\n" : "\r\n", | ||
SkipValidation = (optionsByte & SkipValidationFlag) == 0, | ||
}; | ||
|
||
// Compute the expected result by using the encoder directly and the input | ||
int maxExpandedSizeBytes = 6 * bytes.Length + 2; | ||
byte[] expectedBuffer = ArrayPool<byte>.Shared.Rent(maxExpandedSizeBytes); | ||
Span<byte> expected = | ||
expectedBuffer.AsSpan(0, utf8 | ||
? EncodeToUtf8(bytes, expectedBuffer, options.Encoder) | ||
: EncodeToUtf8(chars, expectedBuffer, options.Encoder)); | ||
|
||
// Compute the actual result by using Utf8JsonWriter. Each iteration is a different slice of the input, but the result should be the same. | ||
byte[] actualBuffer = new byte[expected.Length]; | ||
foreach (ReadOnlySpan<Range> ranges in new[] | ||
{ | ||
new[] { 0.. }, | ||
new[] { 0..slice1, slice1.. }, | ||
new[] { 0..slice1, slice1..slice2, slice2.. }, | ||
}) | ||
{ | ||
using MemoryStream stream = new(actualBuffer); | ||
using Utf8JsonWriter writer = new(stream, options); | ||
|
||
if (utf8) | ||
{ | ||
WriteStringValueSegments(writer, bytes, ranges); | ||
} | ||
else | ||
{ | ||
WriteStringValueSegments(writer, chars, ranges); | ||
} | ||
|
||
writer.Flush(); | ||
|
||
// Compare the expected and actual results | ||
Assert.SequenceEqual(expected, actualBuffer); | ||
Assert.Equal(expected.Length, writer.BytesCommitted); | ||
Assert.Equal(0, writer.BytesPending); | ||
|
||
Array.Clear(actualBuffer); | ||
} | ||
|
||
// Additional test for mixing UTF-8 and UTF-16 encoding. The alignment math is easier in UTF-16 mode so just run it for that. | ||
if (!utf8) | ||
{ | ||
Array.Clear(expectedBuffer); | ||
|
||
{ | ||
ReadOnlySpan<char> firstSegment = chars[slice1..]; | ||
ReadOnlySpan<byte> secondSegment = bytes[0..(2 * slice1)]; | ||
|
||
expected = expectedBuffer.AsSpan(0, EncodeToUtf8(firstSegment, expectedBuffer, options.Encoder)); | ||
|
||
actualBuffer = new byte[expected.Length]; | ||
using MemoryStream stream = new(actualBuffer); | ||
using Utf8JsonWriter writer = new(stream, options); | ||
|
||
writer.WriteStringValueSegment(firstSegment, false); | ||
|
||
Assert.Throws<InvalidOperationException, ReadOnlySpan<byte>>(state => writer.WriteStringValueSegment(state, true), secondSegment); | ||
} | ||
|
||
Array.Clear(expectedBuffer); | ||
|
||
{ | ||
ReadOnlySpan<byte> firstSegment = bytes[0..(2 * slice1)]; | ||
ReadOnlySpan<char> secondSegment = chars[slice1..]; | ||
|
||
expected = expectedBuffer.AsSpan(0, EncodeToUtf8(firstSegment, secondSegment, expectedBuffer, options.Encoder)); | ||
|
||
actualBuffer = new byte[expected.Length]; | ||
using MemoryStream stream = new(actualBuffer); | ||
using Utf8JsonWriter writer = new(stream, options); | ||
|
||
writer.WriteStringValueSegment(firstSegment, false); | ||
Assert.Throws<InvalidOperationException, ReadOnlySpan<char>>(state => writer.WriteStringValueSegment(state, true), secondSegment); | ||
} | ||
} | ||
|
||
ArrayPool<byte>.Shared.Return(expectedBuffer); | ||
} | ||
|
||
private static void WriteStringValueSegments(Utf8JsonWriter writer, ReadOnlySpan<byte> bytes, ReadOnlySpan<Range> ranges) | ||
{ | ||
for (int i = 0; i < ranges.Length; i++) | ||
{ | ||
writer.WriteStringValueSegment(bytes[ranges[i]], i == ranges.Length - 1); | ||
} | ||
} | ||
|
||
private static void WriteStringValueSegments(Utf8JsonWriter writer, ReadOnlySpan<char> chars, ReadOnlySpan<Range> ranges) | ||
{ | ||
for (int i = 0; i < ranges.Length; i++) | ||
{ | ||
writer.WriteStringValueSegment(chars[ranges[i]], i == ranges.Length - 1); | ||
} | ||
} | ||
|
||
private static int EncodeToUtf8(ReadOnlySpan<byte> bytes, Span<byte> destBuffer, JavaScriptEncoder encoder) | ||
{ | ||
destBuffer[0] = (byte)'"'; | ||
encoder.EncodeUtf8(bytes, destBuffer[1..], out _, out int written, isFinalBlock: true); | ||
destBuffer[++written] = (byte)'"'; | ||
return written + 1; | ||
} | ||
|
||
private static int EncodeToUtf8(ReadOnlySpan<char> chars, Span<byte> destBuffer, JavaScriptEncoder encoder) | ||
{ | ||
int written = 1; | ||
destBuffer[0] = (byte)'"'; | ||
destBuffer[written += EncodeTranscode(chars, destBuffer[1..], encoder)] = (byte)'"'; | ||
return written + 1; | ||
} | ||
|
||
private static int EncodeToUtf8(ReadOnlySpan<byte> bytes, ReadOnlySpan<char> chars, Span<byte> destBuffer, JavaScriptEncoder encoder) | ||
{ | ||
int written = 1; | ||
destBuffer[0] = (byte)'"'; | ||
encoder.EncodeUtf8(bytes, destBuffer[1..], out _, out int writtenTemp, isFinalBlock: true); | ||
written += writtenTemp; | ||
destBuffer[written += EncodeTranscode(chars, destBuffer[written..], encoder, isFinalBlock: true)] = (byte)'"'; | ||
return written + 1; | ||
} | ||
|
||
private static int EncodeToUtf8(ReadOnlySpan<char> chars, ReadOnlySpan<byte> bytes, Span<byte> destBuffer, JavaScriptEncoder encoder) | ||
{ | ||
int written = 1; | ||
destBuffer[0] = (byte)'"'; | ||
written += EncodeTranscode(chars, destBuffer[1..], encoder, isFinalBlock: true); | ||
encoder.EncodeUtf8(bytes, destBuffer[written..], out _, out int writtenTemp, isFinalBlock: true); | ||
written += writtenTemp; | ||
destBuffer[written] = (byte)'"'; | ||
return written + 1; | ||
} | ||
|
||
private static int EncodeTranscode(ReadOnlySpan<char> chars, Span<byte> destBuffer, JavaScriptEncoder encoder, bool isFinalBlock = true) | ||
{ | ||
var utf16buffer = ArrayPool<char>.Shared.Rent(6 * chars.Length); | ||
encoder.Encode(chars, utf16buffer, out _, out int written, isFinalBlock: true); | ||
|
||
Utf8.FromUtf16(utf16buffer.AsSpan(0, written), destBuffer, out _, out written, isFinalBlock); | ||
ArrayPool<char>.Shared.Return(utf16buffer); | ||
return written; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.