Skip to content

Commit

Permalink
Fix potential stack overflow in StdInReader (#68398)
Browse files Browse the repository at this point in the history
* Fix potential stack overflow

* Reduce the size of the stack allocation

* Update src/libraries/System.Console/src/System/IO/StdInReader.cs

Co-authored-by: Theodore Tsirpanis <teo@tsirpanis.gr>

* Fix range check

Co-authored-by: Theodore Tsirpanis <teo@tsirpanis.gr>
  • Loading branch information
vcsjones and teo-tsirpanis authored Apr 23, 2022
1 parent c5327b2 commit 10ac54d
Showing 1 changed file with 9 additions and 5 deletions.
14 changes: 9 additions & 5 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,15 @@ 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)];
// Most inputs to this will have a buffer length of one.
// The cases where it is larger than one only occur in ReadKey
// when the input is not redirected, so those cases should be
// rare, so just allocate.
const int MaxStackAllocation = 256;
int maxCharsCount = _encoding.GetMaxCharCount(buffer.Length);
Span<char> chars = (uint)maxCharsCount <= MaxStackAllocation ?
stackalloc char[MaxStackAllocation] :
new char[maxCharsCount];
int charLen = _encoding.GetChars(buffer, chars);
chars = chars.Slice(0, charLen);

Expand Down

0 comments on commit 10ac54d

Please sign in to comment.