Skip to content

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

Open
EnesKartal wants to merge 1 commit into
SixLabors:mainfrom
EnesKartal:fix/png-chunk-buffer-dispose-3215
Open

EnesKartal wants to merge 1 commit into
SixLabors:mainfrom
EnesKartal:fix/png-chunk-buffer-dispose-3215

Conversation

@EnesKartal

Copy link
Copy Markdown

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

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 sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

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)

2 participants