From 245280d8f95fbddb1211e2935ef736ab1a1874a5 Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Fri, 9 Oct 2026 17:36:34 +1000 Subject: [PATCH 1/3] Merge pull request #3203 from cloudsealed/fix/issue-3202-png-chunk-buffer-leak-on-cancel fix: Dispose chunk data buffer in ReadChunkData when read is cancelled (cherry picked from commit eefdbd9e6a73311c31d575b93db732acfe759c11) --- src/ImageSharp/Formats/Png/PngDecoderCore.cs | 12 +++- .../Png/PngDecoderTests.Cancellation.cs | 70 +++++++++++++++++++ 2 files changed, 81 insertions(+), 1 deletion(-) create mode 100644 tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.Cancellation.cs diff --git a/src/ImageSharp/Formats/Png/PngDecoderCore.cs b/src/ImageSharp/Formats/Png/PngDecoderCore.cs index 20f304d472..8cb1c27575 100644 --- a/src/ImageSharp/Formats/Png/PngDecoderCore.cs +++ b/src/ImageSharp/Formats/Png/PngDecoderCore.cs @@ -2002,7 +2002,17 @@ private IMemoryOwner ReadChunkData(int length) length = (int)Math.Min(length, this.currentStream.Length - this.currentStream.Position); IMemoryOwner buffer = this.configuration.MemoryAllocator.Allocate(length, AllocationOptions.Clean); - this.currentStream.Read(buffer.GetSpan(), 0, length); + try + { + this.currentStream.Read(buffer.GetSpan(), 0, length); + } + catch + { + // The read can throw before the caller takes ownership of the buffer (e.g. the stream + // observes a cancellation request), so dispose it here to avoid leaking the rented memory. + buffer.Dispose(); + throw; + } return buffer; } diff --git a/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.Cancellation.cs b/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.Cancellation.cs new file mode 100644 index 0000000000..75e5868661 --- /dev/null +++ b/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.Cancellation.cs @@ -0,0 +1,70 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +using SixLabors.ImageSharp.Formats; +using SixLabors.ImageSharp.Formats.Png; +using SixLabors.ImageSharp.PixelFormats; +using SixLabors.ImageSharp.Tests.TestUtilities; + +namespace SixLabors.ImageSharp.Tests.Formats.Png; + +public partial class PngDecoderTests +{ + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task Decode_DisposesChunkDataBuffer_WhenChunkReadIsCancelled(bool identifyOnly) + { + byte[] pngBytes; + using (Image source = new(4, 4)) + using (MemoryStream encoded = new()) + { + source.SaveAsPng(encoded); + pngBytes = encoded.ToArray(); + } + + using CancellationTokenSource cts = new(); + using PausedMemoryStream stream = new(pngBytes); + + stream.OnWaiting(s => + { + // The signature occupies bytes 0-7 and the chunk length occupies bytes 8-11. + // Cancel during the type read, after BufferedReadStream has checked its token. + // That read completes; the next read checks cancellation after allocating chunk data. + if (s.Position == 12) + { + cts.Cancel(); + stream.Release(); + } + else + { + stream.Next(); + } + }); + + Configuration configuration = Configuration.CreateDefaultInstance(); + + // Read the chunk length and type separately so cancellation occurs during the type read. + configuration.StreamProcessingBufferSize = 4; + DecoderOptions options = new() { Configuration = configuration }; + + // Calling the decoder directly avoids cancellation during format detection. + if (identifyOnly) + { + await Assert.ThrowsAnyAsync(async () => + { + await PngDecoder.Instance.IdentifyAsync(options, stream, cts.Token); + }); + } + else + { + await Assert.ThrowsAnyAsync(async () => + { + using Image image = + await PngDecoder.Instance.DecodeAsync(options, stream, cts.Token); + }); + } + + Assert.True(cts.IsCancellationRequested); + } +} From 725e2545132a9c15c6798ec54e4ffb5dab0ec583 Mon Sep 17 00:00:00 2001 From: EnesKartal Date: Sun, 15 Nov 2026 09:58:16 +0300 Subject: [PATCH 2/3] Dispose PNG chunk buffer if TryReadChunk throws after allocation --- src/ImageSharp/Formats/Png/PngDecoderCore.cs | 22 ++-- .../Png/PngDecoderTests.Cancellation.cs | 118 ++++++++++++++++++ 2 files changed, 132 insertions(+), 8 deletions(-) diff --git a/src/ImageSharp/Formats/Png/PngDecoderCore.cs b/src/ImageSharp/Formats/Png/PngDecoderCore.cs index 8cb1c27575..875884e845 100644 --- a/src/ImageSharp/Formats/Png/PngDecoderCore.cs +++ b/src/ImageSharp/Formats/Png/PngDecoderCore.cs @@ -1892,13 +1892,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; @@ -1949,9 +1958,6 @@ private void ValidateChunk(in PngChunk chunk, Span buffer) if (validCrc != 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 75e5868661..2e0ce3563c 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."); + } } From 188676b3b80a1f271d00e507f3c64ede0d5ec43f Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Mon, 23 Nov 2026 11:23:45 +1000 Subject: [PATCH 3/3] Cover the IDAT position restore and tidy the chunk dispose Both new tests cancelled at the seek after the direct IDAT data read, so both covered only the CRC read. The position restore test now cancels during the read that fills the CRC, which the position restore observes first. Also explain the ownership rule at the catch, remove an assignment that has no effect, and use BinaryPrimitives and using directives in the tests. --- src/ImageSharp/Formats/Png/PngDecoderCore.cs | 3 +- .../Png/PngDecoderTests.Cancellation.cs | 28 +++++++++++-------- 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/src/ImageSharp/Formats/Png/PngDecoderCore.cs b/src/ImageSharp/Formats/Png/PngDecoderCore.cs index 875884e845..5658b064eb 100644 --- a/src/ImageSharp/Formats/Png/PngDecoderCore.cs +++ b/src/ImageSharp/Formats/Png/PngDecoderCore.cs @@ -1905,8 +1905,9 @@ private bool TryReadChunk(Span buffer, out PngChunk chunk) } catch { + // The caller owns the chunk data only after this method returns. The CRC read and the position restore + // can throw first, for example when the stream observes a cancellation request, so dispose the data here. chunk.Data?.Dispose(); - chunk = default; throw; } diff --git a/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.Cancellation.cs b/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.Cancellation.cs index 2e0ce3563c..e00aa40bbe 100644 --- a/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.Cancellation.cs +++ b/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.Cancellation.cs @@ -1,9 +1,12 @@ // Copyright (c) Six Labors. // Licensed under the Six Labors Split License. +using System.Buffers.Binary; +using System.Text; using SixLabors.ImageSharp.Formats; using SixLabors.ImageSharp.Formats.Png; using SixLabors.ImageSharp.PixelFormats; +using SixLabors.ImageSharp.Tests.Memory; using SixLabors.ImageSharp.Tests.TestUtilities; namespace SixLabors.ImageSharp.Tests.Formats.Png; @@ -79,10 +82,12 @@ public async Task Decode_DisposesChunkDataBuffer_WhenCancelledDuringChunkCrcRead using CancellationTokenSource cts = new(); using PausedMemoryStream stream = new(pngBytes); - // Cancel as chunk data finishes so ReadChunkCrc observes cancellation. + // BufferedReadStream reads the IDAT data directly from this stream and then seeks this stream to the end of + // the data. That seek is the first operation at the CRC offset. Cancel during it, so that the CRC read in + // ValidateChunk is the first token check after the chunk data is allocated. stream.OnWaiting(s => { - if (s.Position >= idatCrcOffset - 1 && !cts.IsCancellationRequested) + if (s.Position == idatCrcOffset) { cts.Cancel(); stream.Release(); @@ -107,11 +112,14 @@ public async Task Decode_DisposesChunkDataBuffer_WhenCancelledDuringIdatPosition using CancellationTokenSource cts = new(); using PausedMemoryStream stream = new(pngBytes); + int operationsAtCrcOffset = 0; - // Cancel during the CRC read so restoring currentStream.Position observes cancellation. + // The first operation at the CRC offset is the seek after the direct IDAT data read. The second is the read + // that fills the BufferedReadStream buffer with the CRC. Cancel during that read. The read completes, so + // restoring the IDAT position in TryReadChunk is the first token check after it. stream.OnWaiting(s => { - if (s.Position == idatCrcOffset) + if (s.Position == idatCrcOffset && ++operationsAtCrcOffset == 2) { cts.Cancel(); stream.Release(); @@ -131,12 +139,12 @@ private static async Task AssertCancelledDecodeDisposesAllAllocationsAsync( CancellationToken cancellationToken, bool identifyOnly) { - SixLabors.ImageSharp.Tests.Memory.TestMemoryAllocator allocator = new(); + TestMemoryAllocator allocator = new(); allocator.EnableNonThreadSafeLogging(); Configuration configuration = Configuration.CreateDefaultInstance(); configuration.MemoryAllocator = allocator; configuration.StreamProcessingBufferSize = 4; - DecoderOptions options = new(configuration); + DecoderOptions options = new() { Configuration = configuration }; if (identifyOnly) { @@ -152,7 +160,6 @@ await Assert.ThrowsAnyAsync(async () => }); } - Assert.Equal(0, allocator.LiveBufferBytes); Assert.Equal(allocator.AllocationLog.Count, allocator.ReturnLog.Count); } @@ -169,11 +176,8 @@ 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 length = BinaryPrimitives.ReadInt32BigEndian(pngBytes.AsSpan(offset)); + string type = Encoding.ASCII.GetString(pngBytes, offset + 4, 4); int crcOffset = offset + 8 + length; if (type == chunkType) {