Skip to content

[memory-leak] Fix SKData leak in SKRuntimeEffectUniforms.Reset() - #4442

Draft
github-actions[bot] wants to merge 1 commit into
mainfrom
dev/memory-leak-runtimeeffect-uniforms-reset-7f2da0a70a30eb7b
Draft

github-actions[bot] wants to merge 1 commit into
mainfrom
dev/memory-leak-runtimeeffect-uniforms-reset-7f2da0a70a30eb7b

Conversation

@github-actions

Copy link
Copy Markdown
Contributor

🤖 Generated by the Fixer - Memory Leak agentic workflow using the memory-leak-fixer skill.

The fix

SKRuntimeEffectUniforms.Reset() replaced its backing SKData without disposing the previous one, orphaning an owned native buffer that was then only reclaimed at finalization (non-deterministic; accumulates under repeated Reset()).

This applies the idiomatic dispose-then-replace pattern (focus area 8, Fix ✓) — allocate the replacement first, then dispose the previous buffer, so the old reference is never dropped before it is freed:

public void Reset ()
{
    if (data.Size == 0)
        return;

    var previous = data;
    data = SKData.Create (data.Size);
    previous.Dispose ();
}

SKRuntimeEffectUniforms solely owns data (ToData() returns a copy), so disposing the replaced buffer is safe.

Proof (red→green)

New regression test SKRuntimeEffectTest.Shaders.UniformsResetDisposesPreviousData captures the internal data before Reset() and asserts the old native handle is released afterwards.

  • RED (without fix): Assert.Equal(IntPtr.Zero, oldData.Handle) fails — old handle still live (Actual: 140480394553552).
  • GREEN (with fix): old handle IntPtr.Zero, new buffer live.
dotnet cake --target=externals-download
dotnet test tests/SkiaSharp.Tests.Console/SkiaSharp.Tests.Console.csproj \
  -p:AllTargetFrameworks=net10.0 -p:BasicTargetFrameworks=net10.0 -p:PlatformTargetFrameworks=net10.0 \
  -- --filter-method "*UniformsResetDisposesPreviousData*"

Neighbouring tests: 47 uniforms tests pass; full SKRuntimeEffectTest class = 139 passed / 18 skipped / 0 failed.

Scope note

  • Framework disposal-correctness footgun (delayed/finalizer-reclaimed native leak), empirically proven via red→green.
  • Managed C# only (binding/SkiaSharp/SKRuntimeEffect.cs); no *.generated.cs or externals/skia/** touched.
  • ABI: no public signature changed.

Fixes #4441

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

@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 15, 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 -- 4442

PowerShell / Windows:

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

Step 2 — Add the local NuGet source

dotnet nuget add source ~/.skiasharp/hives/pr-4442/packages --name skiasharp-pr-4442
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-4442

@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

This pull request fixes a native-memory leak in SKRuntimeEffectUniforms.Reset() by deterministically disposing the previous owned SKData buffer when resetting uniforms, and adds a regression test to prevent the leak from reappearing.

Changes:

  • Update SKRuntimeEffectUniforms.Reset() to dispose the previous SKData before losing the reference.
  • Add a regression test that captures the old uniform backing buffer and asserts it is released after Reset().

Reviewed changes

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

File Description
binding/SkiaSharp/SKRuntimeEffect.cs Dispose-and-replace fix in SKRuntimeEffectUniforms.Reset() to prevent orphaned SKData buffers.
tests/Tests/SkiaSharp/SKRuntimeEffectTest.cs Regression test validating Reset() allocates a new buffer and disposes the old one.

Comment thread binding/SkiaSharp/SKRuntimeEffect.cs Outdated
Comment on lines +299 to +301
var previous = data;
data = SKData.Create (data.Size);
previous.Dispose ();

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.

The premise is true at the API level — SKData.Create(int) → GetObject → GetOrAddObject, which returns null when the native handle is IntPtr.Zero (SKObject.cs:91-92). However, this is out of scope for this leak fix:

  • Pre-existing, not introduced here. The old Reset() on main was already data = SKData.Create(data.Size); with no null check — identical null exposure. This PR neither creates nor worsens it.
  • Strictly not-worse. In the (hypothetical) null case, the pre-fix code orphaned the previous buffer to finalization; the new code deterministically frees it via previous.Dispose(). data ends up null either way, but the new version has no orphaned native buffer — which is exactly the leak this PR targets.
  • Effectively unreachable. size == 0 is guarded by the early return; for size > 0 it re-allocates the same size already proven to succeed in the constructor. Skia's uninitialized allocation goes through sk_malloc_throw, which aborts the process on OOM rather than returning null — so a null return here can't realistically occur.

The allocate-into-local/validate-then-swap hardening is a reasonable general nit, but it's a pre-existing footgun on an unreachable path, unrelated to the disposal fix. Leaving it out to keep this PR minimal and focused.

Comment on lines +347 to +362
var dataField = typeof(SKRuntimeEffectUniforms).GetField(
"data",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);

var oldData = (SKData)dataField.GetValue(uniforms);
Assert.NotNull(oldData);
Assert.NotEqual(IntPtr.Zero, oldData.Handle);

uniforms.Reset();

var newData = (SKData)dataField.GetValue(uniforms);

// Reset must allocate a fresh buffer and deterministically dispose the old one.
Assert.NotSame(oldData, newData);
Assert.Equal(IntPtr.Zero, oldData.Handle);
Assert.NotEqual(IntPtr.Zero, newData.Handle);

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.

Valid, but cosmetic. If the private data field is renamed, GetField returns null and the test throws an NullReferenceException at dataField.GetValue — but that is still a failing test, which is the desired outcome on a rename. Assert.NotNull(dataField) (and Assert.NotNull(newData) before dereferencing) would only improve the diagnostic message, not correctness or what the test proves. Happy to add the two asserts as polish, but it has no impact on the red→green validity of the regression test.

Reset() replaced the backing SKData without disposing the previous one,
leaking an owned native buffer until finalization. Dispose the old buffer
after allocating the replacement, and add a red->green regression test.

Co-authored-by: Copilot <[email protected]>
@mattleibow
mattleibow force-pushed the dev/memory-leak-runtimeeffect-uniforms-reset-7f2da0a70a30eb7b branch from 185ef00 to bccf60e Compare September 30, 2026 14:52
@github-actions

Copy link
Copy Markdown
Contributor Author

📊 SkiaSharp benchmarks — PR #4442

⭐ 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 — 🔴 47 slower · 🟢 35 faster

  • 🔴 ColorMathBenchmark.ToColor(Colors: 4096) · Windows · 4.92 µs → 15.80 µs (+221%)
  • 🔴 PathBoundsBenchmark.TightBounds(Points: 1024) · Windows · 8.80 µs → 20.47 µs (+133%)
  • 🔴 MatrixMapPointsBenchmark.MapPoints(Points: 256) · Windows · 86.0 ns → 192.6 ns (+124%)
  • 🔴 MatrixMapPointsBenchmark.MapPoints(Points: 4096) · Windows · 1.05 µs → 2.29 µs (+118%)
  • 🔴 PathBoundsBenchmark.TightBounds(Points: 64) · Windows · 880.6 ns → 1.89 µs (+114%)
  • …and 77 more (see details below)
Full per-OS benchmark deltas

Linux

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

Benchmark baseline this PR Δ
RuntimeEffectShaderBenchmark.DrawFrame 5.12 ms 2.82 ms 🟢 -45%
SceneRenderBenchmark.RenderFrame(Complexity: 4) 27.34 ms 18.34 ms 🟢 -33%
SceneRenderBenchmark.RenderFrame(Complexity: 1) 5.90 ms 3.99 ms 🟢 -32%
ColorMathBenchmark.ToColor(Colors: 4096) 11.89 µs 15.33 µs 🔴 +29%
MatrixMapPointsBenchmark.MapPoints(Points: 4096) 3.63 µs 2.63 µs 🟢 -27%
ColorMathBenchmark.ToColorF(Colors: 4096) 17.02 µs 13.23 µs 🟢 -22%
PathBoundsBenchmark.TightBounds(Points: 1024) 12.13 µs 9.96 µs 🟢 -18%
MatrixMapPointsBenchmark.MapPoints(Points: 256) 287.0 ns 235.6 ns 🟢 -18%
CanvasDrawBenchmark.Draw(Shapes: 64) 4.89 ms 4.20 ms 🟢 -14%
CanvasDrawBenchmark.Draw(Shapes: 512) 38.81 ms 33.51 ms 🟢 -14%
LargeImageScaleBenchmark.UpscaleCrossfade(Size: 2048) 8.94 ms 7.75 ms 🟢 -13%
LargeImageScaleBenchmark.UpscaleOpaque(Size: 2048) 3.01 ms 2.61 ms 🟢 -13%
LargeImageScaleBenchmark.UpscaleCrossfade(Size: 1024) 2.23 ms 1.94 ms 🟢 -13%
LargeImageScaleBenchmark.UpscaleOpaque(Size: 1024) 776.66 µs 678.16 µs 🟢 -13%
PathBoundsBenchmark.TightBounds(Points: 64) 1.12 µs 998.8 ns 🟢 -11%
MatrixMapPointsBenchmark.MapPoint(Points: 4096) 67.45 µs 73.90 µs 🔴 +10%
MatrixOpsBenchmark.Invert(Count: 4096) 116.69 µs 127.68 µs 🔴 +9%
MatrixMapPointsBenchmark.MapRect(Points: 256) 12.44 µs 11.28 µs 🟢 -9%
MatrixMapPointsBenchmark.MapRect(Points: 4096) 198.25 µs 180.81 µs 🟢 -9%
MatrixMapPointsBenchmark.MapPoint(Points: 256) 4.24 µs 4.61 µs 🔴 +9%
RasterImageLifecycleBenchmark.CreateDataWithReleaseProc(Count: 256) 111.29 µs 119.43 µs 🔴 +7%
ColorMathBenchmark.UnPreMultiply(Colors: 4096) 11.30 µs 12.09 µs 🔴 +7%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 256) 1.43 ms 1.33 ms 🟢 -7%
ColorParseBenchmark.Parse(Iterations: 1000) 72.67 µs 76.34 µs 🔴 +5%

Windows

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

Benchmark baseline this PR Δ
ColorMathBenchmark.ToColor(Colors: 4096) 4.92 µs 15.80 µs 🔴 +221%
PathBoundsBenchmark.TightBounds(Points: 1024) 8.80 µs 20.47 µs 🔴 +133%
MatrixMapPointsBenchmark.MapPoints(Points: 256) 86.0 ns 192.6 ns 🔴 +124%
MatrixMapPointsBenchmark.MapPoints(Points: 4096) 1.05 µs 2.29 µs 🔴 +118%
PathBoundsBenchmark.TightBounds(Points: 64) 880.6 ns 1.89 µs 🔴 +114%
CanvasDrawBenchmark.Draw(Shapes: 512) 11.04 ms 22.89 ms 🔴 +107%
CanvasDrawBenchmark.Draw(Shapes: 64) 1.39 ms 2.87 ms 🔴 +107%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 64) 171.80 µs 353.96 µs 🔴 +106%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 256) 654.75 µs 1.34 ms 🔴 +104%
RasterImageLifecycleBenchmark.CreateDataWithReleaseProc(Count: 256) 63.73 µs 129.85 µs 🔴 +104%
BitmapDrawBenchmark.DrawUnscaledTiles(Tiles: 64) 127.75 µs 253.58 µs 🔴 +98%
ColorParseBenchmark.Parse(Iterations: 1000) 42.68 µs 83.97 µs 🔴 +97%
BitmapDrawBenchmark.DrawUnscaledTiles(Tiles: 256) 495.52 µs 965.62 µs 🔴 +95%
MatrixMapPointsBenchmark.MapRadius(Points: 256) 5.63 µs 10.94 µs 🔴 +94%
RuntimeEffectShaderBenchmark.DrawFrame 592.64 µs 1.14 ms 🔴 +92%
RasterImageLifecycleBenchmark.CreateRasterImage(Count: 256) 153.55 µs 291.23 µs 🔴 +90%
MatrixMapPointsBenchmark.MapRadius(Points: 4096) 90.01 µs 167.88 µs 🔴 +87%
ColorMathBenchmark.UnPreMultiply(Colors: 4096) 6.78 µs 12.29 µs 🔴 +81%
MatrixMapPointsBenchmark.MapVector(Points: 256) 4.90 µs 8.86 µs 🔴 +81%
SceneRenderBenchmark.RenderFrame(Complexity: 4) 5.79 ms 10.44 ms 🔴 +80%
ColorMathBenchmark.PreMultiply(Colors: 4096) 7.36 µs 13.25 µs 🔴 +80%
MatrixMapPointsBenchmark.MapVector(Points: 4096) 78.45 µs 141.07 µs 🔴 +80%
SceneRenderBenchmark.RenderFrame(Complexity: 1) 1.22 ms 2.18 ms 🔴 +79%
MatrixOpsBenchmark.Concat(Count: 4096) 148.77 µs 262.94 µs 🔴 +77%
ColorMathBenchmark.ToColorF(Colors: 4096) 7.82 µs 13.29 µs 🔴 +70%
…and 9 more

macOS

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

Benchmark baseline this PR Δ
MatrixMapPointsBenchmark.MapPoints(Points: 4096) 1.90 µs 2.84 µs 🔴 +49%
MatrixMapPointsBenchmark.MapPoints(Points: 256) 156.0 ns 231.0 ns 🔴 +48%
RasterImageLifecycleBenchmark.CreateRasterImage(Count: 256) 205.69 µs 143.75 µs 🟢 -30%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 256) 1.20 ms 926.60 µs 🟢 -23%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 64) 228.38 µs 278.21 µs 🔴 +22%
BitmapDrawBenchmark.DrawUnscaledTiles(Tiles: 256) 791.18 µs 673.22 µs 🟢 -15%
RasterImageLifecycleBenchmark.CreateDataWithReleaseProc(Count: 256) 81.19 µs 71.82 µs 🟢 -12%
ColorMathBenchmark.ToColor(Colors: 4096) 25.53 µs 22.66 µs 🟢 -11%
CanvasDrawBenchmark.Draw(Shapes: 512) 12.79 ms 14.15 ms 🔴 +11%
ColorMathBenchmark.UnPreMultiply(Colors: 4096) 9.15 µs 8.20 µs 🟢 -10%
BitmapDrawBenchmark.DrawUnscaledTiles(Tiles: 64) 224.94 µs 245.44 µs 🔴 +9%
PathBoundsBenchmark.TightBounds(Points: 1024) 8.92 µs 8.12 µs 🟢 -9%
PathBoundsBenchmark.TightBounds(Points: 64) 961.1 ns 876.1 ns 🟢 -9%
ColorParseBenchmark.Parse(Iterations: 1000) 75.17 µs 68.91 µs 🟢 -8%
MatrixMapPointsBenchmark.MapRadius(Points: 4096) 103.56 µs 111.93 µs 🔴 +8%
MatrixMapPointsBenchmark.MapVector(Points: 256) 2.89 µs 2.67 µs 🟢 -8%
MatrixMapPointsBenchmark.MapPoint(Points: 256) 1.34 µs 1.24 µs 🟢 -7%
MatrixMapPointsBenchmark.MapPoint(Points: 4096) 21.18 µs 19.73 µs 🟢 -7%
LargeImageScaleBenchmark.UpscaleCrossfade(Size: 1024) 1.72 ms 1.60 ms 🟢 -7%
ColorMathBenchmark.PreMultiply(Colors: 4096) 9.91 µs 9.25 µs 🟢 -7%
SceneRenderBenchmark.RenderFrame(Complexity: 1) 1.26 ms 1.17 ms 🟢 -7%
RuntimeEffectShaderBenchmark.DrawFrame 542.45 µs 507.64 µs 🟢 -6%
LargeImageScaleBenchmark.UpscaleOpaque(Size: 1024) 770.11 µs 723.89 µs 🟢 -6%
MatrixMapPointsBenchmark.MapRect(Points: 4096) 55.84 µs 52.54 µs 🟢 -6%

📈 Full interactive perf-dashboard & run details →

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] SKData leak in SKRuntimeEffectUniforms.Reset()

2 participants