Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.

Commit 9482ed8

Browse files
Cap allocation size in BinaryReader.ReadString
Do not allow the untrusted payload to dictate the initial capacity of temporary StringBuilder instances.
1 parent 05e3582 commit 9482ed8

File tree

2 files changed

+5
-2
lines changed

2 files changed

+5
-2
lines changed

src/System.Private.CoreLib/shared/System/IO/BinaryReader.cs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -323,9 +323,12 @@ public virtual string ReadString()
323323
return new string(_charBuffer, 0, charsRead);
324324
}
325325

326+
// Since we could be reading from an untrusted data source, limit the initial size of the
327+
// StringBuilder instance we're about to get or create. It'll expand automatically as needed.
328+
326329
if (sb == null)
327330
{
328-
sb = StringBuilderCache.Acquire(stringLength); // Actual string length in chars may be smaller.
331+
sb = StringBuilderCache.Acquire(Math.Min(stringLength, StringBuilderCache.MaxBuilderSize)); // Actual string length in chars may be smaller.
329332
}
330333

331334
sb.Append(_charBuffer, 0, charsRead);

src/System.Private.CoreLib/shared/System/Text/StringBuilderCache.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ internal static class StringBuilderCache
1111
// The value 360 was chosen in discussion with performance experts as a compromise between using
1212
// as litle memory per thread as possible and still covering a large part of short-lived
1313
// StringBuilder creations on the startup path of VS designers.
14-
private const int MaxBuilderSize = 360;
14+
internal const int MaxBuilderSize = 360;
1515
private const int DefaultCapacity = 16; // == StringBuilder.DefaultCapacity
1616

1717
// WARNING: We allow diagnostic tools to directly inspect this member (t_cachedInstance).

0 commit comments

Comments
 (0)