Skip to content

Jpeg decoder can lead to finalizer memory leaks with specific malformed images #2078

@br3aker

Description

@br3aker

Prerequisites

  • I have written a descriptive issue title
  • I have verified that I am running the latest version of ImageSharp
  • I have verified if the problem exist in both DEBUG and RELEASE mode
  • I have searched open and closed issues to ensure it has not already been reported

ImageSharp version

Current main branch

Other ImageSharp packages and versions

None

Environment (Operating system, version and so on)

Windows 10

.NET Framework version

Any supported

Description

Jpeg decoder can leak IDisposable memory wrapper to the finalizer, no memory is actually leaked this way but MemoryDiagnostics reports this as a leak even with proper exception handling via try/catch;

Current decoding pipeline:

1. Gather jpeg info (components, tables, frame size, etc.) <- pixel buffer is allocated here
2. For each scan:
       For each mcu row:
           Decode: huffman -> spectral -> rgb -> TPixel
3. Create Image object using allocated pixel buffer

Any exceptions between step 1 and 3 would cause allocated pixel buffer to be gc'd leading to a false positive memory leak reported by memory diagnostics. Any invalid marker between scans can cause this, it shouldn't crash the entire process.

Steps to Reproduce

This code:

try
{
    using Image img = Image.Load(/* path to image */);
}
catch(Exception ex)
{
    Console.WriteLine($"{ex.GetType()}\n{ex.Message}");
}

GC.Collect();
Console.WriteLine(MemoryDiagnostics.TotalUndisposedAllocationCount);

With attached image prints:

SixLabors.ImageSharp.InvalidImageContentException
Multiple SOF markers. Only single frame jpegs supported.
1

Note that 1 at the end signaling that we have a single leaked memory resource which we can't resolve from user perspective.

Images

progressive_inter_scan_exception.zip

Attached image is a manually malformed progressive jpeg image with multiple scans, it contains second SOS marker right after the first scan which is considered a malformed jpeg. It doesn't contain any actual data after malformed marker to reduce test image size.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions