Repository navigation
fix(core): iOS double free of V8-owned buffers; getRandomValues view handling - #11370
Merged
Merged
Conversation
`dataWithBytesNoCopy:length:` implies freeWhenDone:YES, so Foundation takes ownership of the pointer it is handed. Two call sites handed it memory owned by a V8 BackingStore, which the ArrayBufferSweeper frees again when the ArrayBuffer dies. The deferred second free lands on whatever recycled small-heap chunk occupies the address by then, so the victim rotates with allocation layout — V8_Fatal in the kFinalizer machinery, corrupted wrappers, zeroed Persistent slots, or a silent hang, all on worker threads. Crypto.getRandomValues now uses the 3-arg freeWhenDone:NO form. It keeps the zero-copy behaviour — native randomness is still written straight into the JS buffer, which is guaranteed alive for the synchronous call — without donating ownership. This is the production trigger: getRandomValues backs randomUUID, so it fires constantly on UI paths, and wgc is new in 9.x. FileSystemAccess.getBuffer wrapped an interior pointer of a second NSData: free() on a non-chunk-start address whenever byteOffset > 0, plus a double free against that NSData's own dealloc even at offset 0. The view is now handed to dataWithBytes:length: directly — the runtime's pointer marshalling resolves it to backingStore->Data() + byteOffset — so this copies exactly the view's window instead of copying the whole underlying buffer and then wrapping it unsafely.
|
View your CI Pipeline Execution ↗ for commit b8ba488
💡 Verify your cache is correct by running tasks in a sandbox. Read docs ↗ ☁️ Nx Cloud last updated this comment at |
commit: |
Two defects in the same coercion, both reached only when the caller passes a non-byte typed array. The Android branch reinterpreted the view as `new Uint8Array(buffer, byteOffset)` with no length, widening it to the end of the ArrayBuffer. The runtime maps a typed array to a direct ByteBuffer over backingStore->Data() + byteOffset with capacity byteLength, and the Java side fills the whole capacity after a rewind(), so every byte from the view's offset to the end of the buffer was overwritten with randomness. Both branches also assigned the coerced view over the `typedArray` parameter and returned that, so callers got back a Uint8Array they never passed in. WebCrypto requires the same object back; #10658 added the missing `return` but returned the reassigned local. The coerced view is now a local and the parameter is returned untouched, with a generic signature that preserves the caller's element type the way the DOM's `getRandomValues<T>(array: T): T` does.
NathanWalker
approved these changes
Aug 27, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
PR Checklist
What is the current behavior?
1 & 2 — V8-owned buffers donated to Foundation (iOS)
Two iOS call sites hand a V8-owned pointer to
dataWithBytesNoCopy:length:. The 2-arg selector isfreeWhenDone:YES— Foundation takes ownership of the pointer and frees it. The same allocation is freed a second time by V8'sArrayBufferSweeperwhen theArrayBufferdies.Because the second free is deferred, it lands on whatever recycled small-heap chunk occupies that address by then, so the victim — and therefore the symptom — rotates with allocation layout. In a production app this surfaced as
V8_Fatalin the runtime'skFinalizermachinery, plus rotatingSIGSEGVflavours (corrupted wrappers, zeroedPersistentslots, payload-overwritten vptrs) on worker threads ~30–70s into a session; some runs hung silently instead.malloc_historyon a parked process captured both stacks verbatim on a single chunk: the Foundation-side free under-[NSConcreteMutableData initWithBytes:length:copy:deallocator:], and laterArrayBufferSweeper::SweepingJob→shared_ptr<BackingStore*>::__on_zero_shared→~BackingStore→free.1.
Crypto.getRandomValues—packages/core/wgc/crypto/index.ts(the production trigger)The donated pointer is the caller's typed array's V8
BackingStorebuffer. For small payloadsNSConcreteMutableDatacopies andfree()s the donor immediately insideinitWithBytes:length:copy:deallocator:; larger payloads free atdealloc. Either way Foundation frees memory V8 owns.Every
crypto.getRandomValues()call is one occurrence, and it backs UUID generation, so it fires constantly on UI paths. Sincewgc(andglobal.crypto) is new in core 9.x, apps upgrading from 8.x hit this the moment anything callscrypto.getRandomValues/crypto.randomUUID.2.
FileSystemAccess.getBuffer—packages/core/file-system/file-system-access.ios.ts(write path)Same
freeWhenDone:YES, but over an interior pointer of anotherNSData's buffer:free()on a non-chunk-start pointer wheneverbyteOffset > 0— immediate heap corruption;buf's owndealloceven at offset 0.It also copies the entire underlying
ArrayBuffer(dataWithData(buffer.buffer)) even when the view is a small window over it.3 —
getRandomValuesoverwrites past the caller's window (Android)No length, so the reinterpreted view runs from the caller's offset to the end of the
ArrayBuffer. The runtime maps a typed array to a directByteBufferoverbackingStore->Data() + array->ByteOffset()with capacityarray->ByteLength(), andCrypto.javafills the whole capacity after arewind():So for any non-byte typed array that is a window over a larger buffer, every byte from the view's offset to the end of that buffer is overwritten with randomness.
new Uint32Array(buffer32, 8, 2)asks for 8 bytes and gets 24 clobbered.4 —
getRandomValuesreturns an object the caller never passed inBoth branches assign the coerced view over the
typedArrayparameter and thenreturn typedArray, so for any non-byte typed array the caller gets back aUint8Arrayrather than its own view. WebCrypto requires the same object back. #10658 added the missingreturn, but by then the parameter had already been reassigned. The randomness does land correctly (the buffer is shared), so this is a return-value defect only.What is the new behavior?
1. The 3-arg
freeWhenDone:NOform:Zero-copy behaviour is preserved — native randomness is still written directly into the JS buffer — with no ownership donation. The buffer is guaranteed alive for the duration of the synchronous call.
2. The whole
elsebranch collapses to a single copying call:Passing the typed-array view itself as the
const void *bytesparameter: the iOS runtime's pointer marshalling resolves it tobackingStore->Data() + byteOffset(view-aware — audited against the runtime source), anddataWithBytes:length:copies exactly the view's window. Net result — one copy of only the window instead of a full-buffer copy plus an unsafe no-copy wrapper, no intermediateNSData, no ownership games.3 & 4. The coercion is now a local bound to the caller's window, and the parameter is returned untouched:
The generic signature preserves the caller's element type, matching the DOM's
getRandomValues<T>(array: T): T.Validation
With the two iOS ownership changes patched into core (unmodified runtime), a previously 100%-reproducible ~60s crash survived 10+ minute soaks including document close/reopen cycles — on both a fixed runtime and the original unfixed runtime, making bug 1 the proven sole production trigger.
Tests
New specs pin the selector and arguments each path picks, since ownership of the bytes is exactly what the selector choice decides, plus the window and identity guarantees:
packages/core/wgc/crypto/index.spec.ts— iOS:freeWhenDoneisfalse, the view itself is passed, and only the view's window is wrapped. Android: a byte view passes straight through, and a non-byte typed array is reinterpreted over its window only. Both: the object handed in is the object handed back.packages/core/file-system/file-system-access.ios.spec.ts—ArrayBufferstill copies whole;Uint8Array, offsetUint8Array, offsetUint8ClampedArrayand offsetDataViewall pass the view itself todataWithBytes:length:with the window'sbyteLength.packages/core/vitest.setup.tsgainsNSData/NSMutableData/NSCCryptostubs that record the selector and arguments they were called with, plus the Androidorg.nativescript.winter_tc.Cryptoshim so both platform branches are reachable from the specs.10 of the 13 new assertions fail against
mainand pass here; the other 3 cover behaviour this PR deliberately leaves alone. The fullcoresuite passes (442 tests), and lint/build are clean.Sweep
Any 2-arg
dataWithBytesNoCopy:length:(or theNSMutableDataequivalent) over a pointer derived from a typed array,interop.handleof, or anotherNSData'sbytesis this bug class. A repo-wide sweep found no other reachable JS-side occurrences. The one remaining native hit —[NSData dataWithBytesNoCopy:exponent length:size]inpackages/winter-tc/ios/NSCWinterTC/NSCWinterTC/NSCCrypto.m(generateKeyRsa) — is currently unreachable: every core call site passesnull, 0for the exponent (// ignore publicExponent for now). Worth tightening whenever that path is implemented.Cross-reference
The iOS runtime side is tracking a debug-build marshalling guard (warn when the 2-arg selector receives a pointer inside a live V8
BackingStore); NativeScript/ios#458 carries the full forensic narrative.