Skip to content

Commit

Permalink
Fix Icon(Stream) handling of partial reads (#82621)
Browse files Browse the repository at this point in the history
Icon's ctor assumes Read on a stream will always produce as much data as was asked for, and that's not guaranteed to be the case.
  • Loading branch information
stephentoub authored Mar 2, 2023
1 parent b61bdb9 commit bac3bef
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/libraries/System.Drawing.Common/src/System/Drawing/Icon.cs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,20 @@ public Icon(Stream stream, int width, int height) : this()
ArgumentNullException.ThrowIfNull(stream);

_iconData = new byte[(int)stream.Length];
stream.Read(_iconData, 0, _iconData.Length);
#if NET7_0_OR_GREATER
stream.ReadExactly(_iconData);
#else
int totalRead = 0;
while (totalRead < _iconData.Length)
{
int bytesRead = stream.Read(_iconData, totalRead, _iconData.Length - totalRead);
if (bytesRead <= 0)
{
throw new EndOfStreamException();
}
totalRead += bytesRead;
}
#endif
Initialize(width, height);
}

Expand Down
17 changes: 17 additions & 0 deletions src/libraries/System.Drawing.Common/tests/IconTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,23 @@ public void Ctor_Stream()
}
}

[ConditionalFact(Helpers.IsDrawingSupported)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug fix in core")]
public void Ctor_Stream_Trickled()
{
var stream = new TrickleStream(File.ReadAllBytes(Helpers.GetTestBitmapPath("48x48_multiple_entries_4bit.ico")));
var icon = new Icon(stream);
Assert.Equal(32, icon.Width);
Assert.Equal(32, icon.Height);
Assert.Equal(new Size(32, 32), icon.Size);
}

private sealed class TrickleStream : MemoryStream
{
public TrickleStream(byte[] bytes) : base(bytes) { }
public override int Read(byte[] buffer, int offset, int count) => base.Read(buffer, offset, Math.Min(count, 1));
}

[ConditionalTheory(Helpers.IsDrawingSupported)]
[MemberData(nameof(Size_TestData))]
public void Ctor_Stream_Width_Height(string fileName, Size size, Size expectedSize)
Expand Down

0 comments on commit bac3bef

Please sign in to comment.