Skip to content

Drawing on a canvas wider than 8,388,608 pixels fails with AggregateException, even for a small shape #447

Backlog

Description

@sebastienros

Prerequisites

  • I have written a descriptive issue title
  • I have verified that I am running the latest version of ImageSharp.Drawing
  • 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.Drawing version

main at commit a4e94b8

Other ImageSharp packages and versions

SixLabors.ImageSharp 5.0.0-alpha.0.38, SixLabors.Fonts 3.2.1, SixLabors.PolygonClipper 2.0.0-alpha.0.2

Environment (Operating system, version and so on)

macOS 15.8.3 (arm64)

.NET Framework version

.NET 10 (net10.0)

Description

The default backend allocates rasterizer scratch of 128 bytes per pixel of canvas width for each worker, as one contiguous buffer. The default ImageSharp allocator refuses a single buffer above 1 GB, so any fill on a canvas wider than 8,388,608 pixels throws. The size of the shape does not matter: a 10 x 1 rectangle on a canvas one pixel high fails. The exception is an AggregateException from Parallel.For that wraps InvalidMemoryOperationException.

Explanation

  • DefaultDrawingBackend.ExecuteSceneRow (Processing/Backends/DefaultDrawingBackend.cs, line 293) computes scratchWidth = GetRowScratchWidth(scene, row, target.Region.Width). GetRowScratchWidth (line 410) starts from the width of the target region and only grows it, so the scratch is at least as wide as the canvas.
  • WorkerState.GetOrCreateScratch calls DefaultRasterizer.CreateWorkerScratch(allocator, width) (Processing/Backends/DefaultRasterizer.cs, line 334), which calls WorkerScratch.Create with a cover stride of width << 1 cells and a tile height of DefaultTileHeight = 16 rows.
  • WorkerScratch.Create allocates coverStride * tileCapacity integers in one call (line 3224): 2 * 16 * 4 = 128 bytes per pixel of width. At 8,388,609 pixels that is 1,073,741,952 bytes, above MemoryAllocator.SingleBufferAllocationLimitBytes (1 GB by default), so MemoryAllocator.Allocate throws InvalidMemoryOperationException.
  • The call runs inside the Parallel.For of ExecuteSceneRows, so the caller receives an AggregateException.

Below the limit the buffer is still large: 1 GB of address space per worker for a canvas of 8 million pixels width. In a run of the program below on Linux the working set stayed small (73 MB) because the pages of the unmanaged buffer were not touched, but the allocation counts against AccumulativeAllocationLimitBytes when one is set (not checked).

Suggested fix

  • Size the scratch by what the row draws, not by the canvas: start GetRowScratchWidth from 0 (or from the width of the widest item of the row, which it already computes) instead of target.Region.Width. Check first that no code path indexes the scratch by canvas column beyond the item width.
  • Allocate the cover and area cells per row, or as a 2D buffer (Allocate2D) that may be discontiguous, instead of one contiguous block of 16 rows.
  • Or process wide rows in column tiles of a fixed maximum width.
  • In any case, unwrap a single exception of the parallel loop (for example with ExceptionDispatchInfo.Capture(e.InnerException).Throw() when the AggregateException holds one exception), so that callers see InvalidMemoryOperationException.

The SVG work does not change this code. Its SVG renderer limits the side of an image whose size the document sets to 65,535 pixels, which avoids this case for SVG input; a caller that passes its own wide canvas still gets the exception.

Notes

  • Found by a hostile-input test of the SVG work: a document 9.6 million pixels wide and 8 pixels high is within the pixel limit of the renderer, but the canvas requested a 1.2 GB buffer and failed with AggregateException(InvalidMemoryOperationException).
  • The scratch is per worker, so a canvas of several bands may hold several such buffers at once.
  • Not checked: the WebGPU backend.
  • Add static SVG rendering through DrawingCanvas (SvgDocument, DrawSvg) #442 (the SVG work) unwraps the exception of the parallel loop (the last point above): with it the program prints InvalidMemoryOperationException for the two wide canvases. It does not change the size of the scratch, so the draw still fails.

Steps to Reproduce

Project file (Repro.csproj). It references a Release build of main; the path is a placeholder.

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="SixLabors.ImageSharp.Drawing" HintPath="path/to/SixLabors.ImageSharp.Drawing.dll" />
    <PackageReference Include="SixLabors.ImageSharp" Version="5.0.0-alpha.0.38" />
    <PackageReference Include="SixLabors.Fonts" Version="3.2.1" />
    <PackageReference Include="SixLabors.PolygonClipper" Version="2.0.0-alpha.0.2" />
  </ItemGroup>
</Project>

Program.cs:

using System.Diagnostics;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Drawing;
using SixLabors.ImageSharp.Drawing.Processing;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;

// A canvas one pixel high (L8, so that a row of 9 million pixels fits in one ImageSharp buffer), and a fill of a 10 x 1 rectangle at its left end.
foreach (int width in new[] { 1_000_000, 8_388_608, 8_388_609, 9_000_000 })
{
    using Image<L8> image = new(width, 1);
    try
    {
        image.Mutate(c => c.Paint(canvas => canvas.Fill(Brushes.Solid(Color.White), new RectanglePolygon(0, 0, 10, 1))));
        Console.WriteLine($"width {width,9}: drawn, pixel (5, 0) = {image[5, 0]}, peak working set {Process.GetCurrentProcess().PeakWorkingSet64 >> 20} MB");
    }
    catch (Exception e)
    {
        Console.WriteLine($"width {width,9}: {e.GetType().Name}: {e.Message}");
        for (Exception? inner = e.InnerException; inner is not null; inner = inner.InnerException)
        {
            Console.WriteLine($"    inner {inner.GetType().FullName}: {inner.Message}");
        }
    }
}

Run with dotnet run -c Release. A Debug build gives the same output.

Observed output:

width   1000000: drawn, pixel (5, 0) = L8(255), peak working set 0 MB
width   8388608: drawn, pixel (5, 0) = L8(255), peak working set 0 MB
width   8388609: AggregateException: One or more errors occurred. (Attempted to allocate a buffer of length=1073741952 that exceeded the limit 1073741824.)
    inner SixLabors.ImageSharp.Memory.InvalidMemoryOperationException: Attempted to allocate a buffer of length=1073741952 that exceeded the limit 1073741824.
width   9000000: AggregateException: One or more errors occurred. (Attempted to allocate a buffer of length=1152000000 that exceeded the limit 1073741824.)
    inner SixLabors.ImageSharp.Memory.InvalidMemoryOperationException: Attempted to allocate a buffer of length=1152000000 that exceeded the limit 1073741824.

On macOS Process.PeakWorkingSet64 returns 0, so the program prints 0 MB; on Linux the same program printed 48 MB and 73 MB for the first two widths.

The inner stack trace starts at DefaultRasterizer.WorkerScratch.Create (DefaultRasterizer.cs, line 3224), called from DefaultDrawingBackend.WorkerState.GetOrCreateScratch and DefaultDrawingBackend.ExecuteSceneRow.

L8 is used because, with the default allocator, the constructor of an Rgba32 image 9,000,000 pixels wide already throws ("The buffer capacity of the provided MemoryAllocator is insufficient for the requested buffer alignment"), so with Rgba32 an earlier limit of ImageSharp hides this defect. Narrower pixel formats, or an allocator with a larger buffer capacity, reach it.

Expected: the 10 x 1 rectangle is drawn on all four canvases. If a canvas is too wide to draw at all, the canvas should throw a documented exception before it starts, not an AggregateException from inside the flush.

Images

No response

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions