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

Fix potential stack overflow in StdInReader #68398

Merged
merged 4 commits into from
Apr 23, 2022
Merged
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: 10 additions & 3 deletions src/libraries/System.Console/src/System/IO/StdInReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,18 @@ internal bool IsUnprocessedBufferEmpty()

internal void AppendExtraBuffer(ReadOnlySpan<byte> buffer)
{
// Ensure a reasonable upper bound applies to the stackalloc
Debug.Assert(buffer.Length <= 1024);

// Then convert the bytes to chars
Span<char> chars = stackalloc char[_encoding.GetMaxCharCount(buffer.Length)];
// The maximum buffer size that can be passed is 1024 in length.
// For UTF-8, GetMaxCharCount(1024) is 1025, so that much is expected
// on the stack since we want to avoid allocating the array.
// For custom encodings where the behavior of GetMaxCharCount is
// not known beforehand, this may fall back to an array.
const int MaxStackAllocation = 1025;
vcsjones marked this conversation as resolved.
Show resolved Hide resolved
int maxCharsCount = _encoding.GetMaxCharCount(buffer.Length);
Span<char> chars = (uint)maxCharsCount < MaxStackAllocation ?
stackalloc char[maxCharsCount] :
vcsjones marked this conversation as resolved.
Show resolved Hide resolved
new char[maxCharsCount];
int charLen = _encoding.GetChars(buffer, chars);
chars = chars.Slice(0, charLen);

Expand Down