diff --git a/src/ImageSharp/Formats/Png/PngDecoderCore.cs b/src/ImageSharp/Formats/Png/PngDecoderCore.cs index 01d7100bf7..8026f232f1 100644 --- a/src/ImageSharp/Formats/Png/PngDecoderCore.cs +++ b/src/ImageSharp/Formats/Png/PngDecoderCore.cs @@ -2192,13 +2192,22 @@ private bool TryReadChunk(Span buffer, out PngChunk chunk) type: type, data: this.ReadChunkData(length)); - this.ValidateChunk(chunk, buffer); + try + { + this.ValidateChunk(chunk, buffer); - // Restore the stream position for IDAT and fdAT chunks, because it will be decoded later and - // was only read to verifying the CRC is correct. - if (type is PngChunkType.Data or PngChunkType.FrameData) + // Restore the stream position for IDAT and fdAT chunks, because it will be decoded later and + // was only read to verifying the CRC is correct. + if (type is PngChunkType.Data or PngChunkType.FrameData) + { + this.currentStream.Position = position; + } + } + catch { - this.currentStream.Position = position; + chunk.Data?.Dispose(); + chunk = default; + throw; } return true; @@ -2250,9 +2259,6 @@ private void ValidateChunk(in PngChunk chunk, Span buffer) if (this.crc32.GetCurrentHashAsUInt32() != inputCrc) { string chunkTypeName = Encoding.ASCII.GetString(chunkType); - - // ensure when throwing we dispose the data back to the memory allocator - chunk.Data?.Dispose(); PngThrowHelper.ThrowInvalidChunkCrc(chunkTypeName); } } diff --git a/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.Cancellation.cs b/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.Cancellation.cs index 42deb3a9eb..6f956bc0a5 100644 --- a/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.Cancellation.cs +++ b/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.Cancellation.cs @@ -67,4 +67,122 @@ await Assert.ThrowsAnyAsync(async () => Assert.True(cts.IsCancellationRequested); } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task Decode_DisposesChunkDataBuffer_WhenCancelledDuringChunkCrcRead(bool identifyOnly) + { + byte[] pngBytes = CreateMultiPixelPngBytes(); + int idatCrcOffset = FindFirstChunkCrcOffset(pngBytes, "IDAT"); + + using CancellationTokenSource cts = new(); + using PausedMemoryStream stream = new(pngBytes); + + // Cancel as chunk data finishes so ReadChunkCrc observes cancellation. + stream.OnWaiting(s => + { + if (s.Position >= idatCrcOffset - 1 && !cts.IsCancellationRequested) + { + cts.Cancel(); + stream.Release(); + } + else + { + stream.Next(); + } + }); + + await AssertCancelledDecodeDisposesAllAllocationsAsync(stream, cts.Token, identifyOnly); + Assert.True(cts.IsCancellationRequested); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task Decode_DisposesChunkDataBuffer_WhenCancelledDuringIdatPositionRestore(bool identifyOnly) + { + byte[] pngBytes = CreateMultiPixelPngBytes(); + int idatCrcOffset = FindFirstChunkCrcOffset(pngBytes, "IDAT"); + + using CancellationTokenSource cts = new(); + using PausedMemoryStream stream = new(pngBytes); + + // Cancel during the CRC read so restoring currentStream.Position observes cancellation. + stream.OnWaiting(s => + { + if (s.Position == idatCrcOffset) + { + cts.Cancel(); + stream.Release(); + } + else + { + stream.Next(); + } + }); + + await AssertCancelledDecodeDisposesAllAllocationsAsync(stream, cts.Token, identifyOnly); + Assert.True(cts.IsCancellationRequested); + } + + private static async Task AssertCancelledDecodeDisposesAllAllocationsAsync( + Stream stream, + CancellationToken cancellationToken, + bool identifyOnly) + { + SixLabors.ImageSharp.Tests.Memory.TestMemoryAllocator allocator = new(); + allocator.EnableNonThreadSafeLogging(); + Configuration configuration = Configuration.CreateDefaultInstance(); + configuration.MemoryAllocator = allocator; + configuration.StreamProcessingBufferSize = 4; + DecoderOptions options = new(configuration); + + if (identifyOnly) + { + await Assert.ThrowsAnyAsync(async () => + await PngDecoder.Instance.IdentifyAsync(options, stream, cancellationToken)); + } + else + { + await Assert.ThrowsAnyAsync(async () => + { + using Image image = + await PngDecoder.Instance.DecodeAsync(options, stream, cancellationToken); + }); + } + + Assert.Equal(0, allocator.LiveBufferBytes); + Assert.Equal(allocator.AllocationLog.Count, allocator.ReturnLog.Count); + } + + private static byte[] CreateMultiPixelPngBytes() + { + using Image source = new(16, 16); + using MemoryStream encoded = new(); + source.SaveAsPng(encoded); + return encoded.ToArray(); + } + + private static int FindFirstChunkCrcOffset(byte[] pngBytes, string chunkType) + { + int offset = 8; + while (offset + 12 <= pngBytes.Length) + { + int length = (pngBytes[offset] << 24) + | (pngBytes[offset + 1] << 16) + | (pngBytes[offset + 2] << 8) + | pngBytes[offset + 3]; + string type = System.Text.Encoding.ASCII.GetString(pngBytes, offset + 4, 4); + int crcOffset = offset + 8 + length; + if (type == chunkType) + { + return crcOffset; + } + + offset = crcOffset + 4; + } + + throw new InvalidOperationException($"Chunk '{chunkType}' not found."); + } }