Skip to content

[memory-leak] Fix GCHandle leak on release-proc factory failure path - #4453

Open
github-actions[bot] wants to merge 1 commit into
mainfrom
dev/memory-leak-release-proc-gchandle-ab82e648318c0666
Open

github-actions[bot] wants to merge 1 commit into
mainfrom
dev/memory-leak-release-proc-gchandle-ab82e648318c0666

Conversation

@github-actions

Copy link
Copy Markdown
Contributor

🤖 Produced automatically by the Fixer - Memory Leak agentic workflow using the memory-leak-fixer skill (focus area 9 — delegate-proxy lifetime).

Problem

SKImage.FromPixels, SKImage.FromTexture, SKSurface.Create (raster direct) and SKData.Create wrap a managed release delegate in a GCHandle (via DelegateProxies.Create) and pass it to native code. Native frees that handle by invoking the release proc when the wrapped native object is destroyed. When the native factory fails and returns null, no object is created, the release proc never fires, and the GCHandle — plus the delegate and the caller's captured context — leaks for the process lifetime.

Fix

Free the GCHandle when the native factory returns null and a delegate was supplied:

DelegateProxies.Create (del, out var gch, out var ctx);
...
if (result is null && del is not null)
    gch.Free ();

Managed-C# only (binding/**), no public signature change — ABI stable. SKBitmap.InstallPixels is intentionally not touched: native calls its release proc itself on failure (freeing the handle would double-free — verified empirically).

Proof (red → green)

New regression test tests/Tests/SkiaSharp/ReleaseProcHandleLeakTest.cs drives the failure path (unknown SKColorType / too-small rowBytes) with a release proc capturing a tracked context, then asserts the context is collected.

  • Without fix: both tests FAIL — 50/50 contexts stay alive (leaked).
  • With fix: both tests PASS — all contexts collected. Neighbouring SKImage/SKSurface/SKData/SKBitmap test classes remain green.

Test command used on the runner:

dotnet build tests/SkiaSharp.Tests.Console/SkiaSharp.Tests.Console.csproj -f net10.0 \
  -p:AllTargetFrameworks=net10.0 -p:BasicTargetFrameworks=net10.0 -p:PlatformTargetFrameworks=
dotnet SkiaSharp.Tests.dll --filter-class "*ReleaseProcHandleLeakTest*"

Scope note

Framework bug (real leak on the allocation-failure path), not just a footgun. Empirically proven for SKImage.FromPixels and SKSurface.Create; statically reasoned (identical pattern) for SKImage.FromTexture and SKData.Create. ABI-safe, internal-only change.

Fixes #4452

Generated by Fixer - Memory Leak · ● 49.1M · ◷

@github-actions github-actions Bot added partner/agentic-workflows Issues and PRs created by SkiaSharp agentic workflows. perf/memory-leak Unbounded memory growth: leaked native handles or undisposed objects. Implies tenet/performance. tenet/performance Performance related issues labels Jul 16, 2026
mattleibow added a commit that referenced this pull request Jul 17, 2026
…4476)

Add regression-tracking benchmarks for common colour/interop paths (#4476)

Derived from: #4370, #4385, #4442, #4453, #4455
CI: Track - Benchmarks run 29608575980 (green, all OS/roles)

The permanent regression-tracking suite (SkiaSharp.Benchmarks.Tracking) landed
recently alongside a wave of perf/agentic PRs, but it had no coverage for the
managed colour/interop paths those PRs actually touch. This adds a small,
curated set of trackers so a future regression (or the improvement itself) shows
up as a step in the persisted per-OS time/allocation history.

Following the suite's scaled-pyramid philosophy (a few small common-path trackers
plus one broad composite, not a micro-benchmark per PR), four benchmarks are
added under Tracking/Benchmarks/ (auto-linked into the source-mode project, so
they also drive the PR column):

  * ColorMathBenchmark - managed SKColor->SKColorF (#4370) and SKPMColor
    PreMultiply/UnPreMultiply (#4385). Zero-alloc; the ToColorF/ToColor ratio
    (the reverse operator stays native) is a managed-regression signal even on
    noisy shared runners. These two ports are the real, dashboard-visible speed
    wins - their time lines should drop when the ports merge.
  * RasterImageLifecycleBenchmark - create+dispose churn of SKImage.Create raster
    (#4455) and SKData.Create with a managed release proc (#4453). Allocation is
    the tracked signal for that object-lifecycle area.
  * RuntimeEffectShaderBenchmark - a per-frame animated SkSL shader: build
    uniforms (the SKColor uniform pays the #4370 convert), ToShader, draw. Covers
    the uniforms lifecycle whose SKData leak #4442 touched.
  * SceneRenderBenchmark - one broad frame (transforms, linear+radial gradients,
    filled/stroked primitives, a built path, a scaled image draw, a colour-filter
    layer, clipping, managed colour maths) so many unrelated future optimizations
    each nudge it - a merge indicator rather than a micro-benchmark.

Scope notes: the failure-path leak fixes (#4453, #4455), the native uniforms leak
(#4442), and the UAF/double-free fixes (#4372, #4468) are correctness/native-memory
changes that a throughput + managed-allocation dashboard largely will not register;
they are represented here by area, not as leak assertions (those belong in soak/
leak tests). #4372 and #4468 are intentionally not benchmarked (niche debug canvases;
HarfBuzz lives in a separate assembly the tracking project does not reference).

All benchmarks use public API only (the project references the nightly NuGet, not
internal SkiaApi), are deterministic and machine-independent (fixed seeds, no fonts
or external content), and compile against every benchmarked role - verified against
the 3.119.4 baseline (prev-major) and 4.151 nightly, with only SKPath/SKPathBuilder
behind the existing #if. A short local run and the full CI matrix (Linux/Windows/
macOS, all version roles plus the source-built PR column) emit time and allocation
data for every case.

Co-authored-by: Matthew Leibowitz <[email protected]>
Co-authored-by: Copilot App <[email protected]>
@github-actions

github-actions Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor Author

📦 Try the packages from this PR

Warning

Do not run these scripts without first reviewing the code in this PR.

Step 1 — Download the packages

bash / macOS / Linux:

curl -fsSL https://raw.githubusercontent.com/mono/SkiaSharp/main/scripts/get-skiasharp-pr.sh | bash -s -- 4453

PowerShell / Windows:

iex "& { $(irm https://raw.githubusercontent.com/mono/SkiaSharp/main/scripts/get-skiasharp-pr.ps1) } 4453"

Step 2 — Add the local NuGet source

dotnet nuget add source ~/.skiasharp/hives/pr-4453/packages --name skiasharp-pr-4453
More options
Option Description
--successful-only / -SuccessfulOnly Only use successful builds
--force / -Force Overwrite previously downloaded packages
--list / -List List available artifacts without downloading
--build-id ID / -BuildId ID Download from a specific build

Or download manually from Azure Pipelines — look for the nuget artifact on the build for this PR.

Remove the source when you're done:

dotnet nuget remove source skiasharp-pr-4453

@github-actions

Copy link
Copy Markdown
Contributor Author

📖 Documentation Preview

The documentation for this PR has been deployed and is available at:

🔗 View Staging Site
🔗 View Staging Docs
🔗 View Staging Gallery (Blazor)
🔗 View Staging Gallery (Uno Platform)
🔗 View Staging SkiaFiddle

This preview will be updated automatically when you push new commits to this PR.


This comment is automatically updated by the documentation staging workflow.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Fixes a managed GCHandle leak when native factory methods that use release-proc delegates fail and return null, ensuring the delegate/context handle is freed on the failure path to prevent process-lifetime retention.

Changes:

  • Free the GCHandle created by DelegateProxies.Create(...) when SKImage.FromPixels(...) / SKImage.FromTexture(...) return null.
  • Free the GCHandle created by DelegateProxies.Create(...) when raster-direct SKSurface.Create(...) returns null.
  • Free the GCHandle created by DelegateProxies.Create(...) when SKData.Create(...) returns null.
  • Add regression tests that drive known failure paths and assert the captured context becomes collectible.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.

File Description
tests/Tests/SkiaSharp/ReleaseProcHandleLeakTest.cs Adds regression tests that fail on the leaky failure-path behavior and pass once handles are freed.
binding/SkiaSharp/SKSurface.cs Ensures release-proc GCHandle is freed when raster-direct surface creation fails and returns null.
binding/SkiaSharp/SKImage.cs Ensures release-proc GCHandle is freed when raster/texture image creation fails and returns null.
binding/SkiaSharp/SKData.cs Ensures release-proc GCHandle is freed when data creation fails and returns null.

@mattleibow
mattleibow marked this pull request as ready for review July 28, 2026 22:33
@github-actions

github-actions Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor Author

📊 SkiaSharp benchmarks — PR #4453

⭐ this PR (full source build) vs 🌙 nightly · Linux · Windows · macOS

Informational only — this never blocks the PR. 🟢 faster / less allocation · 🔴 slower / more allocation; moves under 5% are hidden as noise.

⏱️ Times are raw BenchmarkDotNet means, and the ⭐ PR and baseline legs run on separate CI runners, so microbenchmarks can swing run-to-run — treat small time deltas as noise. Allocations are deterministic and the reliable signal. The interactive perf-dashboard (linked below) applies smoothing for the trend view.

Highlights

⏱️ Time — 🔴 45 slower · 🟢 18 faster

  • 🔴 MatrixMapPointsBenchmark.MapPoints(Points: 4096) · macOS · 1.51 µs → 3.05 µs (+101%)
  • 🔴 MatrixMapPointsBenchmark.MapPoints(Points: 256) · macOS · 130.9 ns → 245.7 ns (+88%)
  • 🟢 BitmapDrawBenchmark.DrawUnscaledTiles(Tiles: 64) · Linux · 596.95 µs → 238.57 µs (-60%)
  • 🔴 PathBoundsBenchmark.TightBounds(Points: 1024) · macOS · 8.11 µs → 12.29 µs (+52%)
  • 🔴 BitmapDrawBenchmark.DrawUnscaledTiles(Tiles: 64) · macOS · 159.27 µs → 226.48 µs (+42%)
  • …and 58 more (see details below)
Full per-OS benchmark deltas

Linux

⏱️ Time (vs 🌙 nightly 4.155.0-nightly.26479.19)

Benchmark baseline this PR Δ
BitmapDrawBenchmark.DrawUnscaledTiles(Tiles: 64) 596.95 µs 238.57 µs 🟢 -60%
MatrixMapPointsBenchmark.MapPoints(Points: 256) 264.7 ns 205.9 ns 🟢 -22%
MatrixMapPointsBenchmark.MapPoints(Points: 4096) 2.94 µs 2.48 µs 🟢 -16%
ColorMathBenchmark.ToColor(Colors: 4096) 15.36 µs 13.68 µs 🟢 -11%
MatrixMapPointsBenchmark.MapRadius(Points: 4096) 228.49 µs 213.86 µs 🟢 -6%
LargeImageScaleBenchmark.UpscaleCrossfade(Size: 2048) 7.74 ms 7.25 ms 🟢 -6%
MatrixMapPointsBenchmark.MapVector(Points: 4096) 175.84 µs 166.85 µs 🟢 -5%

Windows

⏱️ Time (vs 🌙 nightly 4.155.0-nightly.26479.19)

Benchmark baseline this PR Δ
ColorMathBenchmark.ToColor(Colors: 4096) 11.11 µs 15.67 µs 🔴 +41%
RasterImageLifecycleBenchmark.CreateDataWithReleaseProc(Count: 256) 92.56 µs 128.15 µs 🔴 +38%
MatrixOpsBenchmark.Concat(Count: 4096) 253.12 µs 349.07 µs 🔴 +38%
PathBoundsBenchmark.TightBounds(Points: 1024) 16.50 µs 20.51 µs 🔴 +24%
PathBoundsBenchmark.TightBounds(Points: 64) 1.54 µs 1.90 µs 🔴 +23%
RasterImageLifecycleBenchmark.CreateRasterImage(Count: 256) 241.39 µs 294.57 µs 🔴 +22%
MatrixMapPointsBenchmark.MapPoints(Points: 256) 164.4 ns 192.5 ns 🔴 +17%
MatrixMapPointsBenchmark.MapPoints(Points: 4096) 2.14 µs 2.45 µs 🔴 +15%
CanvasDrawBenchmark.Draw(Shapes: 512) 20.56 ms 23.00 ms 🔴 +12%
CanvasDrawBenchmark.Draw(Shapes: 64) 2.58 ms 2.87 ms 🔴 +11%
ColorMathBenchmark.PreMultiply(Colors: 4096) 14.67 µs 13.22 µs 🟢 -10%
MatrixMapPointsBenchmark.MapPoint(Points: 4096) 87.20 µs 78.85 µs 🟢 -10%
MatrixMapPointsBenchmark.MapRadius(Points: 256) 9.61 µs 10.51 µs 🔴 +9%
LargeImageScaleBenchmark.UpscaleOpaque(Size: 2048) 3.23 ms 2.93 ms 🟢 -9%
LargeImageScaleBenchmark.UpscaleCrossfade(Size: 1024) 2.85 ms 2.60 ms 🟢 -9%
MatrixOpsBenchmark.Invert(Count: 4096) 149.42 µs 137.49 µs 🟢 -8%
MatrixMapPointsBenchmark.MapRadius(Points: 4096) 152.78 µs 164.03 µs 🔴 +7%
MatrixMapPointsBenchmark.MapPoint(Points: 256) 5.40 µs 5.01 µs 🟢 -7%
LargeImageScaleBenchmark.UpscaleOpaque(Size: 1024) 813.28 µs 760.67 µs 🟢 -6%
ColorParseBenchmark.Parse(Iterations: 1000) 77.90 µs 82.92 µs 🔴 +6%
ColorMathBenchmark.UnPreMultiply(Colors: 4096) 13.12 µs 12.30 µs 🟢 -6%
MatrixMapPointsBenchmark.MapRect(Points: 4096) 132.03 µs 139.94 µs 🔴 +6%
ColorMathBenchmark.ToColorF(Colors: 4096) 14.09 µs 13.32 µs 🟢 -5%
LargeImageScaleBenchmark.UpscaleCrossfade(Size: 2048) 11.16 ms 10.57 ms 🟢 -5%
RuntimeEffectShaderBenchmark.DrawFrame 1.20 ms 1.14 ms 🟢 -5%

macOS

⏱️ Time (vs 🌙 nightly 4.155.0-nightly.26479.19)

Benchmark baseline this PR Δ
MatrixMapPointsBenchmark.MapPoints(Points: 4096) 1.51 µs 3.05 µs 🔴 +101%
MatrixMapPointsBenchmark.MapPoints(Points: 256) 130.9 ns 245.7 ns 🔴 +88%
PathBoundsBenchmark.TightBounds(Points: 1024) 8.11 µs 12.29 µs 🔴 +52%
BitmapDrawBenchmark.DrawUnscaledTiles(Tiles: 64) 159.27 µs 226.48 µs 🔴 +42%
RasterImageLifecycleBenchmark.CreateRasterImage(Count: 256) 145.64 µs 199.49 µs 🔴 +37%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 256) 690.16 µs 923.91 µs 🔴 +34%
RasterImageLifecycleBenchmark.CreateDataWithReleaseProc(Count: 256) 64.64 µs 85.83 µs 🔴 +33%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 64) 198.65 µs 253.87 µs 🔴 +28%
LargeImageScaleBenchmark.UpscaleOpaque(Size: 1024) 661.08 µs 841.13 µs 🔴 +27%
LargeImageScaleBenchmark.UpscaleCrossfade(Size: 2048) 5.66 ms 7.07 ms 🔴 +25%
MatrixOpsBenchmark.Concat(Count: 4096) 109.39 µs 134.61 µs 🔴 +23%
PathBoundsBenchmark.TightBounds(Points: 64) 886.5 ns 1.07 µs 🔴 +20%
CanvasDrawBenchmark.Draw(Shapes: 64) 1.46 ms 1.75 ms 🔴 +20%
MatrixOpsBenchmark.Invert(Count: 4096) 65.97 µs 78.14 µs 🔴 +18%
BitmapDrawBenchmark.DrawUnscaledTiles(Tiles: 256) 584.55 µs 684.65 µs 🔴 +17%
SceneRenderBenchmark.RenderFrame(Complexity: 4) 5.27 ms 6.17 ms 🔴 +17%
MatrixMapPointsBenchmark.MapPoint(Points: 256) 1.14 µs 1.32 µs 🔴 +16%
SceneRenderBenchmark.RenderFrame(Complexity: 1) 1.15 ms 1.34 ms 🔴 +16%
RuntimeEffectShaderBenchmark.DrawFrame 507.35 µs 580.10 µs 🔴 +14%
MatrixMapPointsBenchmark.MapRadius(Points: 4096) 98.70 µs 111.78 µs 🔴 +13%
ColorMathBenchmark.UnPreMultiply(Colors: 4096) 7.43 µs 8.37 µs 🔴 +13%
ColorMathBenchmark.PreMultiply(Colors: 4096) 8.24 µs 9.28 µs 🔴 +13%
MatrixMapPointsBenchmark.MapRect(Points: 256) 3.08 µs 3.45 µs 🔴 +12%
MatrixMapPointsBenchmark.MapPoint(Points: 4096) 18.19 µs 20.34 µs 🔴 +12%
LargeImageScaleBenchmark.UpscaleCrossfade(Size: 1024) 1.44 ms 1.60 ms 🔴 +11%
…and 6 more

📈 Full interactive perf-dashboard & run details →

@github-actions

github-actions Bot commented Aug 3, 2026

Copy link
Copy Markdown
Contributor Author

📦 Artifact size report

Packages from this PR (build 1538164) vs the latest nightly baseline 4.151.0-nightly.120 (observed 2026-08-03).

Total .nupkg size: 569.2 MB → 568.8 MB (−394.7 KB, -0.1%)

Packages

⚠️ marks growth over 500.0 KB or 2%. Changes under 50.0 KB are treated as noise.

Package baseline this PR Δ Δ%
SkiaSharp.NativeAssets.WinUI 109.0 MB 108.4 MB 🟢 −559.4 KB -0.5%
HarfBuzzSharp.NativeAssets.Win32 20.7 MB 20.8 MB 🔴 +91.5 KB +0.4%

+38 package(s) unchanged (< 50.0 KB).

Per-file changes

HarfBuzzSharp.NativeAssets.Win32

File Size
runtimes/win-x86/native/libHarfBuzzSharp.pdb 21.9 MB → 22.2 MB (🔴 +272.0 KB)
runtimes/win-arm64/native/libHarfBuzzSharp.pdb 22.3 MB → 22.5 MB (🔴 +184.0 KB)

SkiaSharp.NativeAssets.WinUI

File Size
runtimes/win-x64/native/libGLESv2.pdb 66.6 MB → 66.6 MB (🟢 −64.0 KB)
runtimes/win-arm64/native/libGLESv2.pdb 64.5 MB → 64.4 MB (🟢 −32.0 KB)
runtimes/win-x86/native/libGLESv2.pdb 67.2 MB → 67.2 MB (🟢 −32.0 KB)

Informational only — this never blocks the PR. Native binaries are labelled by os/arch.

When SKImage.FromPixels/FromTexture, SKSurface.Create and SKData.Create wrap a
managed release delegate in a GCHandle and hand it to native code, native frees
that handle by invoking the release proc on destruction. If the native factory
fails (returns null), the release proc is never invoked and the GCHandle - plus
the delegate and captured context it roots - leaks for the process lifetime.

Free the GCHandle when the native call returns null and a delegate was supplied.

Co-authored-by: Copilot <[email protected]>
@mattleibow
mattleibow force-pushed the dev/memory-leak-release-proc-gchandle-ab82e648318c0666 branch from e23b3cb to e207bd3 Compare September 30, 2026 14:50

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

partner/agentic-workflows Issues and PRs created by SkiaSharp agentic workflows. perf/memory-leak Unbounded memory growth: leaked native handles or undisposed objects. Implies tenet/performance. tenet/performance Performance related issues

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

[memory-leak] GCHandle leak on release-proc factory failure path (SKImage/SKSurface/SKData)

2 participants