Repository navigation
Fix managed stream I/O, buffering, and callback contracts - #5464
mattleibow wants to merge 51 commits into
Conversation
📦 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 -- 5464PowerShell / Windows: iex "& { $(irm https://raw.githubusercontent.com/mono/SkiaSharp/main/scripts/get-skiasharp-pr.ps1) } 5464"Step 2 — Add the local NuGet source dotnet nuget add source ~/.skiasharp/hives/pr-5464/packages --name skiasharp-pr-5464More options
Or download manually from Azure Pipelines — look for the Remove the source when you're done: dotnet nuget remove source skiasharp-pr-5464 |
|
📖 Documentation Preview Add the Removing the label removes the preview. While the label is present, each new commit updates it. This comment is automatically updated by the documentation staging workflow. |
📊 SkiaSharp benchmarks — PR #5464⭐ this PR (full source build) vs 🌙 nightly · Linux · Windows · macOS
Highlights⏱️ Time — 🔴 5 slower · 🟢 80 faster
Full per-OS benchmark deltasLinux⏱️ Time (vs 🌙 nightly
Windows⏱️ Time (vs 🌙 nightly
macOS⏱️ Time (vs 🌙 nightly
|
|
@dalexsoto review |
dalexsoto
left a comment
There was a problem hiding this comment.
Reviewed all 24 changed managed-stream, data, callback, benchmark and test paths together with pinned native consumers, ABI and target-framework integration, including a separate final blocker search.
Relative moves overflow before the new clamping runs (binding/SkiaSharp/SKManagedStream.cs:302)
The signed Int64 addition is evaluated before SeekTo can clamp it. A seekable Stream may legally have Position beyond Length. With Length=100, Position=long.MaxValue, and Move(1), default unchecked arithmetic produces long.MinValue; SeekTo treats that as a negative target, sets Position=0, clears EOF, and returns true instead of clamping to the end (100). This requires only a large cursor value, not a large allocation or file.
A positive relative move can silently rewind a small stream and make subsequent native reads consume its prefix instead of remaining at its end, violating the documented SkStream move contract.
Fix: Use an overflow-safe/saturating relative-position calculation before applying the stream-bound clamp; checked addition alone would turn this into a failure rather than the specified clamped move.
The intended short-read, EOF, buffering, Span and callback policies remain accepted; the finding concerns the changed relative-move clamping behavior.
This is a static source-contract finding, not an executed runtime reproduction.
Fixed in |
dalexsoto
left a comment
There was a problem hiding this comment.
Reviewed all 24 changed managed-stream, data, callback, benchmark and test paths together with pinned native consumers, ABI and target-framework integration, including a separate final blocker search. Saturating relative-move arithmetic fixes the prior overflow and preserves the reviewed stream, callback, ownership and target-framework contracts. The intended short-read, EOF, buffering, Span and callback policies remain accepted; the relative-move clamping replacement and boundary handling have been checked. No independent high-confidence blocker remains in this bounded static review; no executed runtime or whole-pipeline certification is claimed.
dalexsoto
left a comment
There was a problem hiding this comment.
Reviewed all 4 changed files with their managed-stream, callback, ownership, native-consumer, ABI and target-framework integration, including a separate final blocker search. Saturating relative-move arithmetic fixes the prior overflow and preserves the reviewed stream, callback, ownership and target-framework contracts. The intended short-read, EOF, buffering, Span and callback policies remain accepted; the relative-move clamping replacement and boundary handling have been checked. No independent high-confidence blocker remains in this bounded static review; no executed runtime or whole-pipeline certification is claimed.
26bf9e3 to
d606c3e
Compare
dalexsoto
left a comment
There was a problem hiding this comment.
Reviewed all 3 changed files with their managed-stream, callback, ownership, native-consumer, ABI and target-framework integration, including a separate final blocker search.
Do not cache snapshots after failed native writes (binding/SkiaSharp/SKManagedStream.cs:378-381)
The new snapshot fallback treats a failed SKDynamicMemoryWStream.Write as successful end-of-input: it breaks the copy loop, then unconditionally detaches and caches the incomplete data. This path is used for unknown-length seekable streams and after a known-length factory rejects an early-ending stream. Native block allocation failure can therefore make Duplicate return a non-null empty or truncated stream, and Fork can also succeed when its position fits that prefix. The cached snapshot remains incomplete even after memory pressure clears, so subsequent duplicates silently reuse corrupted input instead of reporting failure.
Fix: Return null from snapshot creation when native.Write returns false, without publishing snapshotData. Preserve the existing finally restoration and using cleanup so Duplicate/Fork can report failure and a later attempt can retry.
The intended short-read, EOF, buffering, Span and callback policies remain accepted; the relative-move clamping replacement and boundary handling have been checked.
This is a static source-contract finding, not an executed runtime reproduction.
Fixed in
|
fefd756 to
670e7cb
Compare
186c83a to
d42f230
Compare
…s address-reuse safe (#5475) [tests] Make HandleDictionary assertions address-reuse safe (#5475) Context: #5464 Context: #4080 Context: https://dev.azure.com/dnceng-public/cbb18261-c48f-4abb-8651-8cdcb5474649/_build/results?buildId=1653003 Context: https://dev.azure.com/dnceng-public/cbb18261-c48f-4abb-8651-8cdcb5474649/_build/results?buildId=1653279 Context: https://dev.azure.com/dnceng-public/cbb18261-c48f-4abb-8651-8cdcb5474649/_build/results?buildId=1655413 Verify post-dispose and post-GC wrapper teardown by wrapper reference and registration-token identity in HandleDictionary.instances instead of querying SKObject.GetInstance<TDerived>(handle, out _) after native memory is freed. This prevents parallel xUnit tests that reuse a freed native pointer from causing false failures while catching disposed or collected wrappers whose dictionary entries were not removed. ~~ Inspect HandleDictionary.instances by wrapper and token identity ~~ During parallel xUnit runs of SkiaSharp.Tests, tests that freed a native object via Dispose() or CollectGarbage() and then asserted Assert.False(SKObject.GetInstance<TDerived>(handle, out _)) intermittently failed when another test thread allocated a new native object at the same address (malloc ABA reuse). Under THROW_OBJECT_EXCEPTIONS in Debug builds, HandleDictionary.GetInstanceNoLocks<TDerived> throws InvalidOperationException ("A managed object exists for the handle, but is not the expected type") when a live owning wrapper of a different concrete type occupies the reused handle, such as an SKImage at a freed SKTypeface address or an SKDynamicMemoryWStream at a freed SKMemoryStream address. When a parallel test allocated the same wrapper type at that address, GetInstance<TDerived> returned true and failed Assert.False. Calling HandleDictionary.GetInstance<SKObject> also missed real teardown bugs. GetInstanceNoLocks filters out wrappers with IsDisposed == true and ignores dead WeakReference entries, so the existing AssertDeregistered helper from #4080 could not detect a disposed wrapper left in HandleDictionary.instances. In addition, SKCodec and SKDocument implement ISKSkipObjectRegistration, so GetInstance<SKCodec> and GetInstance<SKDocument> always returned false without checking whether those wrappers were collected. Update AssertDeregistered<TSkiaObject>(IntPtr handle, TSkiaObject instance) and add Track(SKObject instance, out IntPtr handle, out WeakReference weak) and AssertCollected(IntPtr handle, WeakReference instance) in SKHandleDictionaryTestHelpers: * AssertDeregistered asserts handle != IntPtr.Zero, instance != null, instance.IsDisposed, and instance.Handle == IntPtr.Zero (which is zeroed by SKObject.Handle after DeregisterHandle), then reads HandleDictionary.instances under instancesLock and asserts !ReferenceEquals(current.Target, instance). Update 8 post-dispose assertions in SKCodecTest, SKTypefaceTest, SKManagedStreamTest, and SKRuntimeEffectTest to call AssertDeregistered. * Track captures handle = instance.Handle while the wrapper is live and asserts handle != IntPtr.Zero. For ISKSkipObjectRegistration types (SKCodec and SKDocument), it allocates a fresh WeakReference(instance); for registered types, it reads HandleDictionary.instances under instancesLock and asserts that the handle maps to instance, returning that exact WeakReference registration entry. * AssertCollected requires instance.Target is null (rejecting a wrapper that is still strongly reachable even if IsDisposed is true) and reads HandleDictionary.instances under instancesLock to assert !ReferenceEquals(current, instance). Because RegisterHandle allocates a new WeakReference on every registration, a concurrent test reusing the freed pointer installs a distinct WeakReference instance, whereas an unremoved dead entry from the original registration fails the assertion. Update 13 post-GC tests across SKCodecTest, SKDocumentTest, SKFontManagerTest, SKImageTest, SKManagedStreamTest, SKManagedWStreamTest, and SKTypefaceTest to use Track and AssertCollected. ~~ Preserve owner liveness and helper-frame boundaries across GC checks ~~ In SKCodecTest.StreamLosesOwnershipAndCanBeGarbageCollected, SKTypefaceTest.StreamLosesOwnershipAndCanBeGarbageCollected, SKManagedStreamTest.StreamLosesOwnershipAndCanBeGarbageCollected, and SKManagedWStreamTest.StreamIsReferencedAndNotDisposedPrematurely, DoWork runs an inner CollectGarbage(), uses the owner (codec.GetPixels, typeface.GetTableTags, or document.BeginPage/EndPage/Close), and then asserts Assert.True(SKObject.GetInstance<...>(streamHandle, out var stream)) to verify that OwnedObjects or KeepAliveObjects retained the child stream. Without a subsequent reference to the owner, the JIT could treat codec, typeface, or document as dead after its last native call and finalize it before the inner GetInstance assertion ran. Add GC.KeepAlive on the owning wrapper at the end of DoWork so it remains live through the inner retention check and becomes collectible only after DoWork returns, and mark all 17 local allocation/work helpers across the 7 post-GC test files with [MethodImpl(MethodImplOptions.NoInlining)] so JIT inlining cannot extend local lifetimes into the outer test frame. In SKTypefaceTest.ManagedStreamIsCollectedWhenCollected, SKTypeface.FromStream(SKStreamAsset) calls SKFontManager.CreateTypeface, which copies an SKManagedStream via managed.ToMemoryStream() and immediately calls managed.Dispose(), zeroing stream.Handle. The base test read stream.Handle after FromStream returned, passing IntPtr.Zero to GetInstance<SKManagedStream> and never tracking the created SKTypeface. When stream was tracked before FromStream inside DoWork in build 1653003, Android (API 21) Tests and Android (API 36) Tests failed with "Expected SKManagedStream (handle 0x...) to be garbage-collected, but it is still reachable" because Mono's conservative stack scanner retained the dead local slot in DoWork's frame. * Move SKManagedStream creation and Track(stream, ...) into a nested [MethodImpl(MethodImplOptions.NoInlining)] static CreateTypeface helper before SKTypeface.FromStream(stream), then track typeface, call CollectGarbage(), assert Assert.NotEmpty(typeface.GetTableTags()), and keep typeface alive in DoWork. Executing CollectGarbage() and GetTableTags() after CreateTypeface returns overwrites the inner stack frame before the outer collection check, and tracking both stream and typeface verifies that both wrappers are collected and dotnet.Position throws ObjectDisposedException. ~~ Drain queued finalizers asynchronously for non-skipped Mono and WASM tests ~~ Eleven of the thirteen post-GC tests call SkipOnMono(), which skips on Android, iOS, Mac Catalyst, and Browser WASM. The remaining two tests — SKDocumentTest.StreamIsNotCollectedPrematurely and SKTypefaceTest.ManagedStreamIsCollectedWhenCollected — run on all platforms. In build 1653003, both failed on WASM Tests and WASM (.NET Preview) Tests with "Collected wrapper is still registered under handle 0x588dd08" and "0x5153608". On single-threaded Browser WASM, synchronous BaseTest.CollectGarbage() clears the short WeakReference.Target to null, but ~SKNativeObject() does not run DeregisterHandle until execution yields to the runtime event loop. Add CollectGarbageAndAssertCollectedAsync(IntPtr handle, WeakReference instance) in SKHandleDictionaryTestHelpers and use it in those two tests. It polls BaseTest.CollectGarbage() inside await AssertEx.Eventually(..., timeout: 5000), yielding via Task.Delay between attempts until instance.Target is null and HandleDictionary.instances no longer holds ReferenceEquals(current, instance), then falls through to AssertCollected(handle, instance) so any timeout reports whether the wrapper stayed reachable or its registration token remained in the dictionary. Keeping AssertCollected strict avoids a Mono/WASM platform branch that would accept IsDisposed targets or dead !current.IsAlive entries and mask rooting leaks or broken finalizer deregistration. All 38 SkiaSharp.Tests runs in Azure Pipelines builds 1653279 and 1655413 passed with zero failures across Linux, macOS, Windows (.NET Core and .NET Framework x86/x64), Android (API 21 and API 36), iOS, Mac Catalyst, WASM (1,160 passed, 112 skipped), and WASM (.NET Preview) (1,160 passed, 112 skipped), and the local macOS ARM64 .NET 10 console suite passed (6,473 passed, 23 skipped in SkiaSharp.Tests.dll, plus 1 SingletonInit, 50 Gallery, 4 Vulkan, and 2 Direct3D tests). Co-authored-by: Matthew Leibowitz <[email protected]> Co-authored-by: Copilot App <[email protected]> Co-authored-by: Alex Soto <[email protected]>
670e7cb to
8e4cbdd
Compare
d42f230 to
70bb4a3
Compare
8e4cbdd to
2ad13e8
Compare
70bb4a3 to
71412ab
Compare
Put managed/native read dispatch and unsigned byte-count validation directly in the existing public Read(IntPtr, int) method. The array overload still forwards to it, and managed overrides now propagate their original exceptions without a reverse-P/Invoke round trip. Native callbacks and explicit-length native SKData factories keep their separate entry paths. Remove SKData.ReadStream and use the public instance method at all four existing call sites. Preserve bounded copy loops, nested front-buffer exception behavior, null-pointer skips and temporary-buffer cleanup. Keep the stream owner alive immediately after the read and before validating its result, without adding a read-wrapper try/finally. Three safe invalid-count regressions fail before the consolidation, including a full-width result that would otherwise narrow to an apparently valid int. Add original-exception identity and built-in managed array/pointer read coverage without proxy frames. All configured binding targets, net48 and retained benchmarks compile; all 13 compiler XML contracts verify, and the full source-matched net10 console solution passes with 6555 core tests plus 57 other-host tests. Co-authored-by: Copilot App <[email protected]>
Defer the unmeasured public managed-dispatch changes at the maintainer's request. Public Read, Length64 and Position64 consistently query native streams again, while retaining the additive wide APIs, unsigned count validation, checked conversions and argument guards. Keep direct managed metadata, reads and seek-back together in CreateFromManagedStream, including bounded known-length allocation and unknown-length native staging with exception cleanup. Preserve the built-in front-buffer adapter's two internal managed-safe reads and count checks so the accepted nested short-read failure path still keeps original exceptions off reverse P/Invoke. No new general reader helper or public member fast path is added. Retarget original-exception tests to the private factory contract and retain invalid-count coverage for both public native reads and factory reads. On 32-bit, unrepresentable managed metadata is exercised directly and through the managed factory, never deliberately through an uncontained native callback. All binding targets, net48 and retained copy benchmarks compile; all 13 XML contracts verify native-backed public behavior, and the full source-matched net10 solution passes with 6555 core tests plus 57 other-host tests. There are no public-dispatch performance measurements or speedup claims. Co-authored-by: Copilot App <[email protected]>
Make Create(SKStream) the orchestrator for managed/native input with known or unknown remaining length. Move managed metadata checks and seek-back fallback beside native routing, and delegate copying to separate typed known-length and unknown-length managed helpers. Keep public stream members native-backed and preserve existing byte-count, short-read, EOF, ownership and exception behavior. Keep the source owner alive once in the orchestrator's finally so every return and failure path is covered. Remove redundant per-read/metadata markers and the private native helper's duplicate lifetime scope. No tests or assertions are changed. All configured binding targets, net48 and retained benchmarks compile. The full source-matched net10 console solution passes with 6555 core tests plus 57 other-host tests; existing declared skips are unchanged. This is a structural cleanup, not a measured performance optimization. Co-authored-by: Copilot App <[email protected]>
Preserve the distinction between successful empty read-to-end/zero-length requests and failed positive exact-length requests. Keep native explicit-length one-shot behavior and the existing seek-back/fallback policy unchanged. Document the empty/null/data result contract on both lengthless stream overloads. Query System.IO.Stream length and position once after the capability checks, and use the same len/pos/remaining structure as the managed/native SKStream routes. Keep the explicit signed remaining-byte preflight for exact requests, including past-end positions; no generic metadata helper or new return policy is added. Add focused empty/past-end and zero-vs-positive exact-length checks across System.IO.Stream, SKManagedStream and native memory streams, plus known-length/exact-length metadata snapshot checks. All binding targets, net48 and retained benchmarks compile; the full source-matched net10 solution passes with 6559 core tests plus 57 other-host tests. Existing assertion and skip policies are unchanged. Co-authored-by: Copilot App <[email protected]>
Restore main's incomplete-known-length failure policy at the maintainer's explicit direction. All managed copy loops still fill legal positive short reads, but zero before the expected count releases partial data and returns null. Remove System.IO.Stream partial-prefix success and both managed/native SKStream seek-back/read-to-end recovery paths. Unknown remaining lengths still read to EOF normally; zero expected bytes remain a successful empty result. Keep public stream dispatch, native explicit-length one-shot factories, offsets, wide-size conversions and original managed read exceptions unchanged. Rename the private flag to checkRemainingLength because it now controls only the optional seekable availability preflight, not EOF behavior. Update source XML and retarget obsolete prefix/reset expectations to strict failure and no reset; preserve unknown-length partial content, input ownership and real read-failure identity checks. Five EOF-policy cases fail before the fix and pass afterward. The baseline red run also exposed an unrelated color-space assertion; its focused diagnostic and subsequent full runs pass without changing that test. All binding TFMs, net48 and retained benchmarks compile; all 13 XML contracts verify, and the final full source-matched net10 solution passes with 6562 core tests plus 57 other-host tests, existing declared skips unchanged. Co-authored-by: Copilot App <[email protected]>
Describe the existing write/flush exception handling and latched failure behavior on SKManagedWStream and its OnWrite/OnFlush hooks. Later writes return false and later flushes are ignored after either operation throws. Only source XML comment trivia changes; declarations and runtime code are identical to the Sonnet-reviewed revision. All 13 configured binding targets build, the three documentation entries are verified in all compiler XML artifacts, and the reference/library XML package transport tests pass. Runtime regression evidence remains the strict EOF run at 58f1176 (6562 core plus 57 other-host tests); no runtime code changed or extra review round was started. Co-authored-by: Copilot App <[email protected]>
Add brief comments for known-count fills, native staging of unknown input, managed exception boundaries, source-owner lifetime, bounded writes and null-buffer zero filling. Explain that checkRemainingLength rejects impossible explicit-length requests before allocation or consumption, while lengthless callers already resolved the count. This adds only 15 ordinary comment lines. Comment-stripped source, declarations, XML documentation and tests are unchanged; git diff --check passes. Runtime and documentation validation remains the named evidence from 58f1176 and 687d13a respectively; no extra runtime suite or review round is needed for this verified comment-only delta. Co-authored-by: Copilot App <[email protected]>
Add multi-chunk zero-fill and completed-write accounting regressions, and observe deterministic data cleanup through the existing registry and native reference count. Co-authored-by: Copilot App <[email protected]>
Keep unknown-length front-buffered inputs out of known-size allocations and report EOF from observed reads. Make read fixtures disposal-sensitive so caller-ownership checks detect premature closure. Co-authored-by: Copilot App <[email protected]>
Keep short-read/EOF/seek semantics together with the callback boundary that prevents exceptions escaping into native code. Preserve failure-state recovery, fork cleanup and native-origin deregistration, including all existing regression scenarios. ABI generation and user-data allocation optimization are separate changes. Co-authored-by: Copilot App <[email protected]>
Keep public int/64-bit metadata sentinel checks together with explicit native C API containment. Direct managed exception propagation remains a private data-factory contract; retain its separate failure assertions and all callback recovery scenarios. Co-authored-by: Copilot App <[email protected]>
Apply the requested strict incomplete-input policy to duplicate/fork snapshots as well as data creation. Only genuinely unknown lengths use read-to-end staging. Preserve source cursor and EOF restoration, uncached failure, native write rejection and fork cleanup. Retain the original early-ending inputs with failure assertions and verify unknown-length snapshots remain readable. Co-authored-by: Copilot App <[email protected]>
Keep unknown-length snapshot reads on the managed path so the outer duplicate/fork callback reports failure without caching a partial snapshot. Preserve source cursor and EOF restoration and strict known-length failure policy. Keep native transfer counts and bounded-loop accounting unsigned, including the 64-bit high bit. Add red-to-green regressions for both count boundaries and snapshot failures before and after a completed chunk, including successful recovery. Co-authored-by: Copilot App <[email protected]>
Use a Boolean for the caller-serialized callback error flag instead of interlocked integer operations. Document the instance threading contract, native callback failure/reset policy, and position/length-qualified EOF observation. Keep the separate native destruction guard unchanged. Co-authored-by: Copilot App <[email protected]>
Preserve the lower-layer unknown-length regression while asserting the upper reader's existing fill-until-zero behavior. Verify exactly one zero observation during the partial native read and another on an explicit subsequent read; retain every rewind/seek/move transition. Co-authored-by: Copilot App <[email protected]>
Co-authored-by: Copilot App <[email protected]>
…rve partial buffers Co-authored-by: Copilot App <[email protected]>
Validate before native allocation without invoking virtual disposal or consuming caller ownership on invalid arguments. Complete native-size conversions, retain short-read and EOF safeguards, and permit forward-only seeking after the front buffer so decorators keep the seek fast path. Simplify the test helper and add compatibility regressions. Co-authored-by: Copilot App <[email protected]>
Remove the duplicate ConfigurableTestStream declaration after stacking the front-buffered stream fixes on the SKData and SKManagedWStream changes. All existing front-buffer regression scenarios continue using the shared helper. Co-authored-by: Copilot App <[email protected]>
Remove the SKManagedStream-specific EOF workaround now that the real adapter fix is in ancestry. Restore original duplicate/fork, SKData front-buffered stream and nested adapter scenarios deferred during the split. Keep existing focused regression coverage intact. Co-authored-by: Copilot App <[email protected]>
…patch sync Co-authored-by: Copilot App <[email protected]>
Retain the original known-length early-ending source scenario while expecting null per the user's strict EOF decision. Verify pre-read bytes, consumed position, open input, bounded read calls and backward-seek rejection without restart. Co-authored-by: Copilot App <[email protected]>
Preserve the existing implementation and unknown-length sentinel while warning callers to use automatic decoding adapters or SKFrontBufferedManagedStream for explicit Skia buffering. Clarify the distinct .NET and Skia stream contracts. Co-authored-by: Copilot App <[email protected]>
47cd6f3 to
b9272f3
Compare
Preserve completed nested reads when later reads fail, including front-buffer replay and rewind eligibility, without bypassing virtual read overrides. Keep known-length snapshot failures inside the duplicate/fork callback boundary and retain strict short-read failure without another EOF probe. Use unsigned native counts and metadata throughout the front adapter, refresh a stale EOF observation when the underlying source becomes readable again, and apply the existing position-width guard to fork creation while preserving disposed-source cleanup. Add regressions for each path. Co-authored-by: Copilot App <[email protected]>
dalexsoto
left a comment
There was a problem hiding this comment.
Reviewed all 24 changed files and relevant managed/native consumers, ABI, ownership, framework branches and actual-target integration, including a separate final search for independent blockers. The prior relative-move overflow, failed-write snapshot caching, unknown-length read-fault caching and unsigned managed-reader transfer findings are Fixed; the accepted EOF, buffering, callback and general CanSeek policies remain preserved.
Validate the original fork position before native-width conversion (SKManagedStream.cs:434–436). On 32-bit, OnFork converts the source long position before validating it, and Utils.ToNativeSize drops the upper 32 bits. A four-byte cached snapshot and source position 0x1_0000_0001 become native target 1; both the child's seek and the comparison succeed, returning a child at byte 1 instead of failing to reproduce the original position. No large allocation is required. Validate the original long against native-width limits before conversion, preserving duplicate destruction on failure and valid unsigned 32-bit positions.
Account for actual child seek progress in nested front buffers (SKFrontBufferedStream.cs:289–297). The shortcut increments currentOffset by requested skipped bytes without checking where the child landed. With the added configurable source reporting length 20 but ending at byte 5, an inner front buffer of 10 and outer buffer of 0, outer.Seek(8, Begin) makes the inner wrapper stop at 5 while the outer records and returns 8. The wrappers then disagree about their cursors and report bytes never skipped, contrary to the documented stop-at-end behavior. Account for the child's actual position delta and discard retained prefix only after actual forward progress; the accepted general CanSeek fast path need not be removed.
Both are high-confidence static control-flow findings. Review-completeness correction: the fork conversion was already present at previously reviewed 90350db, and the nested front-buffer issue was already present in consolidated layer 887187f; these are not described as newly introduced by the current fixes. No executed runtime reproduction or build/test validation is claimed.
dalexsoto
left a comment
There was a problem hiding this comment.
Reviewed the current 24-file PR boundary using the complete five-file follow-up patch, unchanged-source coverage reuse, affected integration paths and a separate final independent-blocker pass. The original OnFork width validation, known-length snapshot fault containment and immediate SKManagedStream-child progress fixes are retained as Fixed. Accepted EOF, buffering, callback-failure and general CanSeek policies remain preserved.
Account for actual child seek progress in nested legacy front buffers (SKFrontBufferedStream.cs:289-297). The replacement shortcut increments the outer cursor by the requested skip without checking where the child landed. With a source reporting length 20 but ending at byte 5, an inner buffer of 10 and outer buffer of 0, outer.Seek(8, Begin) leaves the inner wrapper at 5 while the outer records and returns 8. This is tightly coupled to the PR's new bounded child-seek mechanism. The comparison base also miscounted this example through different accounting; this is not a claim that general early-EOF seeking was correct before the PR. Advance by the child's actual position delta and discard retained prefix only after actual progress, preserving the accepted general CanSeek strategy.
Propagate partial-read progress through nested managed front buffers (SKFrontBufferedManagedStream.cs:166-176, also 207-219). ReadWithProgress handles an immediate SKManagedStream child, but another SKFrontBufferedManagedStream takes the plain OnRead branch. If that child consumes bytes before throwing, the outer catch records zero progress. For source bytes 0 through 7, two-byte underlying reads, a failure on read call 2 and inner/outer buffers of 10, the first outer four-byte read returns failure/zero; after disabling failure and a successful outer Rewind(), the next read returns 2,3,4,5 rather than 0,1,2,3. At the comparison base, the first read returned the two-byte prefix without reaching the throwing call, and rewind replayed the correct prefix. Extend completed-progress propagation through library-owned front-buffer adapters, retaining virtual dispatch and both buffered/direct-read bookkeeping.
Both findings are high-confidence static traces. Review-completeness correction: the nested managed case was already discoverable at the previously reviewed consolidated head and is not described as newly introduced by this follow-up. No executed reproduction, build/test validation or runtime/native-archive certification is claimed.
Description
Fix the contract between legal .NET stream behavior and Skia's synchronous stream consumers. The original OneFuzz investigation exposed premature EOF on non-seekable input, legal short reads being mistaken for truncated input, and native WebP loops that could continue indefinitely after an early zero read while reported length remained larger than the readable input.
This is the standalone consolidated correctness PR, targeting
main: it includes the data/write-stream and 64-bit API work previously split into #5483, this reader/callback layer, and the front-buffer fixes from #5476. #5483 and #5476 are closed as superseded, with their branches, discussions and backups retained. The optional shared callback-storage allocation optimization remains independently reviewable in #5518 and is not included. Already-merged lifetime and ABI work from #5475/#5479 remains inmain, not new work in this diff. No other unmerged PR must land first.Read and EOF contracts
Managed reads fill the requested count across legal positive short reads, stopping at an actual zero read, with bounded 80 KiB transfer requests and scratch rentals. Modern targets use spans over native memory; older targets use bounded array scratch storage. Native transfer counts and totals retain unsigned pointer-sized values, including the 64-bit high bit, without request-sized allocations. The front adapter now uses the same unsigned helpers for counts, offsets and recorded metadata.
Observed EOF is distinct from a contained callback error. For seekable input, the raw managed stream qualifies its EOF observation by position and reported length; a visible external reposition or extension invalidates it. Non-seekable input learns EOF from reads. Raw managed reads are not permanently prohibited by EOF. Front-buffer reads refresh a cached EOF observation when the underlying source no longer reports EOF, allowing an ordinary grown
MemoryStreamto resume while preserving native codec behavior that avoids re-reading an unchanged ended source. This is not live-input polling or a promise to detect changes that the underlying stream cannot report.Peek and snapshot operations restore source cursor/EOF state. Negative legacy unknown-length metadata is reported as unavailable, not converted into an unsigned allocation size. Relative moves avoid arithmetic overflow and seek targets clamp to supported bounds.
Data, snapshots and writes
SKData.Createreads from the current input position. Known-length copies fill exactly across short reads; early EOF disposes the partial result and returnsnull, without prefix success, rewind/reset/re-read or unknown-length fallback. Unknown-length copies stage until normal EOF and return data, including empty data for a zero-byte result. A zero requested count succeeds with empty data.The lengthless
SKStreamfactory selects managed/native and known/unknown-length routes. Its private managed route preserves original managed exceptions and does not dispose caller-owned input. Required internal nested reads and snapshot staging avoid adding a read callback boundary that would convert an exception into apparent EOF or poison source error state. PublicReadand metadata queries remain native-backed. Public explicit-lengthSKData.Create(SKStream, ...)retains the native factory's at-most-one-read behavior, includingnullafter a short native read.Duplicate/fork snapshots share native immutable data while child cursors remain independent. Known-length snapshots now use a direct managed exact-copy path as well as unknown-length snapshots; their short-read failure remains strict, without another EOF probe or retry. Failed reads/native writes do not publish a cache. Failed forks release allocated children and share the existing guarded native position conversion, including on 32-bit hosts, without bypassing disposed-source position failures. Snapshot restoration in
finallypreserves its non-consuming contract, including internal read-progress bookkeeping.SKManagedWStreamcounts completed writes through this wrapper rather than destinationPosition, supports non-seekable output, and preserves completed-byte accounting after a later chunk fails. Transfers are bounded; null native buffers produce cleared zero-filled output. Write/flush exceptions latch failure: writes returnfalse, subsequent writes are rejected and flushes are ignored.Buffering and native callback boundaries
Both front-buffer implementations preserve buffered prefixes across short reads, forward movement and failure, track offsets without 32-bit truncation, and restore useful rewind behavior within the retained prefix. Constructor validation occurs before native allocation; wide native lengths are retained without using checked int metadata getters.
The managed front adapter now accounts for completed nested reads even when a later underlying read throws. Completed prefix bytes remain available after rewind; consumption beyond the prefix invalidates rewind before the exception propagates. The internal progress path still invokes the virtual
OnReadoverride, and tests cover both automatically wrapped sources and caller-supplied derived adapters. No byte count is invented for an unsuccessful underlying read call.Legacy
SKFrontBufferedStreamreceives a warning-only[Obsolete]attribute. Its .NET type, members, limited seeking andLength == -1unknown-length convention remain for compatibility. Migration guidance recommends passing the originalStreamto codec/bitmap overloads, or usingSKFrontBufferedManagedStreamexplicitly for Skia buffering. The latter is anSKStream, not a drop-inSystem.IO.Streamreplacement. This does not claim that all front-buffer limitations disappear.Native stream callbacks contain managed exceptions and return native failure values. Read/peek/reposition exceptions set an at-end failure latch; successful native rewind/seek/move clears it. Metadata and duplicate/fork callback failures return their own failure results without poisoning that latch. It is a plain Boolean: instances are not thread-safe, and callers must serialize access. Native-origin destruction clears/deregisters handles even if managed disposal throws, without a global
SKObjectrewrite.Whole-input managed pooling, Stream Span polyfills and public managed-dispatch fast paths remain excluded. No new performance or allocation measurements are claimed for this follow-up.
Preserved research and review provenance
Whole-input managed pooling was measured and removed: the results did not justify a portable default or size threshold. These historical experiments predate the final strict known-length EOF decision and are not claims about the final code.
Consolidation at
b9272f3802f78bfdfc9812f5833f43f429bec182preserved the frozen front-buffer correctness head887187f375a815fa54097e5dcd101cb2b0c68bd0plus the exact final deprecation/XML/test delta from15158ad8446fd76edab90551612507dd0345c459. All 50 logical commits replayed onto main snapshot21bc413b07b6c244ab2a7a3695ed8daaa4603763withrange-diff =; the complete correctness patch was byte-identical across that replay. The shared allocation file remains excluded.The maintainer subsequently requested independent Sonnet 5.5 and Gemini 4 Argon deep reviews of exact
b9272f3802f7. Those reviews identified the nested front-buffer failure, known-length snapshot error-state, full-width front-adapter count/metadata, backing-stream growth and 32-bit fork-position findings. The concrete findings are addressed bybc702db2d8e56ecaa13dfb56e6ed03f25f35fef8, with regressions and preserved neighboring behavior. The reviews are not presented as a fresh review or formal approval of that later fix commit. Lower-confidence or pre-existing concerns were not bundled into this correction.Original regressions, strict early-EOF policy, unsigned native widths, disposal-aware ownership fixtures, late-chunk/zero-fill/immediate-cleanup coverage and warning-only deprecation remain. No assertions or skip policies were weakened.
Related issues
Related to the OneFuzz
ManagedStreamsFuzzerinvestigation. Consolidates the correctness work from superseded #5483 and #5476; optional #5518 remains separate.Required skia PR
None.
Areas affected
binding/)externals/skia/src/c,include/c)Changes
Public API — additive signatures and warning-only deprecation
Behavior
Length/Positiongetters now use checked conversion and throwOverflowExceptionaboveInt32.MaxValue. Wide metadata decodes unsigned native sizes before checked conversion tolong; values aboveInt64.MaxValuecannot be represented.Moveremains supported. Public managed array reads/writes validate counts before native entry; null-array skip and null-buffer managed zero-fill behavior remain.-1convention. Instance access remains caller-serialized, not thread-safe.Testing
Current validated head:
bc702db2d8e56ecaa13dfb56e6ed03f25f35fef8. Local runtime validation is macOS ARM64/.NET 10. The correction is a five-file follow-up to the consolidatedb9272f3802f7snapshot; no public API declarations, generated bindings or native sources changed in the follow-up.dotnet test tests/SkiaSharp.Tests.Console.slnx -p:TargetFramework=net10.0 -p:TargetFrameworks=net10.0dotnet build binding/SkiaSharp/SkiaSharp.csproj -v:quietdotnet build tests/SkiaSharp.Tests.Console/SkiaSharp.Tests.Console.csproj -p:TargetFramework=net48 -p:TargetFrameworks=net48 -v:quietdotnet build benchmarks/SkiaSharp.Benchmarks/SkiaSharp.Benchmarks.csproj -c Release -p:TargetFramework=net10.0 -p:TargetFrameworks=net10.0 -v:quietpwsh -NoLogo -NoProfile -File ./scripts/infra/package/tests/AssembleArcadeAssets.Tests.ps1git diff --checkFifteen new cases cover known-length duplicate/fork read failures before input and after a completed chunk, nested prefix/direct partial failure through ordinary and overridden adapters, UInt64 high-bit skips and metadata, explicit reads after backing-memory growth, and unrepresentable fork-position/reference cleanup. Before production changes, the full baseline suite failed 14 newly added cases on the 64-bit host; the architecture-independent fork test already passed on 64-bit and covers the corrected branch when run on 32-bit. Final focused diagnostics passed 34 cases, followed by the full unfiltered solution gate. Existing strict snapshot EOF-probe counts, disposed-source fork cleanup, virtual read dispatch and codec no-read-after-end behavior remain passing.
All 13 compiler XML outputs parse successfully, with unchanged public source XML in the follow-up. Output natives and all nine rebuilt test-host library copies matched source-pinned Skia
748bc0c0116c3952f0a0089f5cc53edc55ae08deartifacts from Azure main build 1655687, producing sourceb45912c193582b20664445e506e92f773a1aa6e8. This PR makes no native/submodule changes.Broader retained coverage includes short reads, non-seekable EOF, early-ending seekable WebP input, peek/source restoration, seek/move bounds, external reposition/extension, independent duplicate/fork cursors, snapshot failure without caching and successful retry, full unsigned native counts against small sources, codecs/pictures, front-buffer boundary/constructor cases, metadata beyond 2 GiB without large payloads, strict factory EOF, ownership/disposal, completed-chunk write accounting, multichunk zero-fill, immediate SKData deregistration/native release, and retained legacy deprecation compatibility.
Limits: the local host did not execute a 32-bit runtime, Windows .NET Framework runtime or mobile/AOT device. The 32-bit fork correction is source-verified and compile-covered; the regression is ready for that platform's CI, not falsely claimed as locally exercised. Native allocation failure was not fault-injected. The pre-existing empty-input front-peek EOF observation and speculative/pre-existing review concerns are not claimed fixed by this follow-up. Local results are not current-head CI or formal reviewer approval. No rendering-output/golden-image change is intended; screenshots are not applicable.
Checklist
Changesabove lists all public API and behavioral changes (or "None.")///documentation and regenerated bindings when applicablemono/skiaPR linked above and bindings regeneratedNative companion PR and binding regeneration are not applicable: no native or generated declarations changed.