Skip to content

Dispose PNG chunk buffer if TryReadChunk throws after allocation - #3277

Merged
JimBobSquarePants merged 3 commits into
SixLabors:mainfrom
EnesKartal:fix/png-chunk-buffer-dispose-3215
Nov 23, 2026
Merged

JimBobSquarePants merged 3 commits into
SixLabors:mainfrom
EnesKartal:fix/png-chunk-buffer-dispose-3215

Conversation

@EnesKartal

Copy link
Copy Markdown
Contributor

Fixes #3215

Root Cause

In PngDecoderCore.TryReadChunk, once ReadChunkData allocates chunk.Data (an IMemoryOwner<byte>), the caller does not yet own chunk if TryReadChunk throws before returning. While ValidateChunk disposed chunk.Data on Exception, any exception (including OperationCanceledException) thrown after ValidateChunk — such as restoring this.currentStream.Position for IDAT/fdAT chunks — or if ValidateChunk is refactored would leak the pooled chunk.Data buffer until GC finalization.

Fix

  • Wrap ValidateChunk and the IDAT/fdAT stream position restoration in TryReadChunk with a try/catch that disposes chunk.Data and resets chunk = default before rethrowing.
  • Remove the redundant try/catch disposal inside ValidateChunk since TryReadChunk is its only caller.
  • Add cancellation regression tests in PngDecoderTests.Cancellation.cs using TestMemoryAllocator to verify all allocated buffers are disposed when cancellation occurs during chunk CRC reading or IDAT position restoration.

Verification

  • dotnet test --no-restore tests/ImageSharp.Tests/ImageSharp.Tests.csproj --filter FullyQualifiedName~SixLabors.ImageSharp.Tests.Formats.Png.PngDecoderTests: 237 passed, 0 failed, 0 skipped (net10.0).

@CLAassistant

CLAassistant commented Nov 15, 2026 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ JimBobSquarePants
❌ EnesKartal
You have signed the CLA already but the status is still pending? Let us recheck it.

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.
@JimBobSquarePants
JimBobSquarePants merged commit 155e7dc into SixLabors:main Nov 23, 2026
1 check was pending
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

PNG decoder: chunk buffer is still not disposed when cancellation is observed just after the chunk-data read (follow-up to #3202)

3 participants