Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 14 additions & 8 deletions src/ImageSharp/Formats/Png/PngDecoderCore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2192,13 +2192,22 @@ private bool TryReadChunk(Span<byte> 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;
Expand Down Expand Up @@ -2250,9 +2259,6 @@ private void ValidateChunk(in PngChunk chunk, Span<byte> 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);
}
}
Expand Down
118 changes: 118 additions & 0 deletions tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.Cancellation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,122 @@ await Assert.ThrowsAnyAsync<OperationCanceledException>(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<OperationCanceledException>(async () =>
await PngDecoder.Instance.IdentifyAsync(options, stream, cancellationToken));
}
else
{
await Assert.ThrowsAnyAsync<OperationCanceledException>(async () =>
{
using Image<Rgba32> image =
await PngDecoder.Instance.DecodeAsync<Rgba32>(options, stream, cancellationToken);
});
}

Assert.Equal(0, allocator.LiveBufferBytes);
Assert.Equal(allocator.AllocationLog.Count, allocator.ReturnLog.Count);
}

private static byte[] CreateMultiPixelPngBytes()
{
using Image<Rgba32> 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.");
}
}