Repository navigation
[memory-leak] Fix SKData leak in SKRuntimeEffectUniforms.Reset() - #4442
github-actions[bot] wants to merge 1 commit into
Conversation
…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]>
📦 Try the packages from this PRWarning 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 -- 4442PowerShell / 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-4442More options
Or download manually from Azure Pipelines — look for the Remove the source when you're done: dotnet nuget remove source skiasharp-pr-4442 |
|
📖 Documentation Preview The documentation for this PR has been deployed and is available at: 🔗 View Staging Site This preview will be updated automatically when you push new commits to this PR. This comment is automatically updated by the documentation staging workflow. |
There was a problem hiding this comment.
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 previousSKDatabefore 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. |
| var previous = data; | ||
| data = SKData.Create (data.Size); | ||
| previous.Dispose (); |
There was a problem hiding this comment.
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()onmainwas alreadydata = 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().dataends up null either way, but the new version has no orphaned native buffer — which is exactly the leak this PR targets. - Effectively unreachable.
size == 0is guarded by the earlyreturn; forsize > 0it re-allocates the same size already proven to succeed in the constructor. Skia's uninitialized allocation goes throughsk_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.
| 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); |
There was a problem hiding this comment.
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]>
185ef00 to
bccf60e
Compare
📊 SkiaSharp benchmarks — PR #4442⭐ this PR (full source build) vs 🌙 nightly · Linux · Windows · macOS
Highlights⏱️ Time — 🔴 47 slower · 🟢 35 faster
Full per-OS benchmark deltasLinux⏱️ Time (vs 🌙 nightly
Windows⏱️ Time (vs 🌙 nightly
macOS⏱️ Time (vs 🌙 nightly
|
The fix
SKRuntimeEffectUniforms.Reset()replaced its backingSKDatawithout disposing the previous one, orphaning an owned native buffer that was then only reclaimed at finalization (non-deterministic; accumulates under repeatedReset()).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:SKRuntimeEffectUniformssolely ownsdata(ToData()returns a copy), so disposing the replaced buffer is safe.Proof (red→green)
New regression test
SKRuntimeEffectTest.Shaders.UniformsResetDisposesPreviousDatacaptures the internaldatabeforeReset()and asserts the old native handle is released afterwards.Assert.Equal(IntPtr.Zero, oldData.Handle)fails — old handle still live (Actual: 140480394553552).IntPtr.Zero, new buffer live.Neighbouring tests: 47 uniforms tests pass; full
SKRuntimeEffectTestclass = 139 passed / 18 skipped / 0 failed.Scope note
binding/SkiaSharp/SKRuntimeEffect.cs); no*.generated.csorexternals/skia/**touched.Fixes #4441