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

Commit b0b1217

Browse files
GrabYourPitchforksAnipik
authored andcommitted
Cap allocation size in BinaryReader.ReadString
Do not allow the untrusted payload to dictate the initial capacity of temporary StringBuilder instances.
1 parent e159b6f commit b0b1217

File tree

2 files changed

+5
-2
lines changed

2 files changed

+5
-2
lines changed

src/mscorlib/src/System/IO/BinaryReader.cs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -312,8 +312,11 @@ public virtual String ReadString()
312312
if (currPos == 0 && n == stringLength)
313313
return new String(_charBuffer, 0, charsRead);
314314

315+
// Since we could be reading from an untrusted data source, limit the initial size of the
316+
// StringBuilder instance we're about to get or create. It'll expand automatically as needed.
317+
315318
if (sb == null)
316-
sb = StringBuilderCache.Acquire(stringLength); // Actual string length in chars may be smaller.
319+
sb = StringBuilderCache.Acquire(Math.Min(stringLength, StringBuilderCache.MAX_BUILDER_SIZE)); // Actual string length in chars may be smaller.
317320
sb.Append(_charBuffer, 0, charsRead);
318321
currPos += n;
319322
} while (currPos < stringLength);

src/mscorlib/src/System/Text/StringBuilderCache.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ internal static class StringBuilderCache
4141
// The value 360 was chosen in discussion with performance experts as a compromise between using
4242
// as litle memory (per thread) as possible and still covering a large part of short-lived
4343
// StringBuilder creations on the startup path of VS designers.
44-
private const int MAX_BUILDER_SIZE = 360;
44+
internal const int MAX_BUILDER_SIZE = 360;
4545

4646
[ThreadStatic]
4747
private static StringBuilder CachedInstance;

0 commit comments

Comments
 (0)