Skip to content

fix(core): iOS double free of V8-owned buffers; getRandomValues view handling - #11370

Merged
NathanWalker merged 2 commits into
mainfrom
fix/ios-nsdata-buffer-ownership
Aug 27, 2026
Merged

NathanWalker merged 2 commits into
mainfrom
fix/ios-nsdata-buffer-ownership

Conversation

@edusperoni

@edusperoni edusperoni commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

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 is freeWhenDone:YES — Foundation takes ownership of the pointer and frees it. The same allocation is freed a second time by V8's ArrayBufferSweeper when the ArrayBuffer dies.

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_Fatal in the runtime's kFinalizer machinery, plus rotating SIGSEGV flavours (corrupted wrappers, zeroed Persistent slots, payload-overwritten vptrs) on worker threads ~30–70s into a session; some runs hung silently instead.

malloc_history on a parked process captured both stacks verbatim on a single chunk: the Foundation-side free under -[NSConcreteMutableData initWithBytes:length:copy:deallocator:], and later ArrayBufferSweeper::SweepingJob → shared_ptr<BackingStore*>::__on_zero_shared → ~BackingStore → free.

1. Crypto.getRandomValues — packages/core/wgc/crypto/index.ts (the production trigger)

const data = NSMutableData.dataWithBytesNoCopyLength(typedArray, typedArray.byteLength);
NSCCrypto.getRandomValues(data);

The donated pointer is the caller's typed array's V8 BackingStore buffer. For small payloads NSConcreteMutableData copies and free()s the donor immediately inside initWithBytes:length:copy:deallocator:; larger payloads free at dealloc. 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. Since wgc (and global.crypto) is new in core 9.x, apps upgrading from 8.x hit this the moment anything calls crypto.getRandomValues / crypto.randomUUID.

2. FileSystemAccess.getBuffer — packages/core/file-system/file-system-access.ios.ts (write path)

const buf = NSData.dataWithData(buffer?.buffer);
const len = buffer.byteLength;
return NSData.dataWithBytesNoCopyLength(buf.bytes.add(buffer?.byteOffset ?? 0), len);

Same freeWhenDone:YES, but over an interior pointer of another NSData's buffer:

  • free() on a non-chunk-start pointer whenever byteOffset > 0 — immediate heap corruption;
  • a double free against buf's own dealloc even at offset 0.

It also copies the entire underlying ArrayBuffer (dataWithData(buffer.buffer)) even when the view is a small window over it.

3 — getRandomValues overwrites past the caller's window (Android)

typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset);

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 direct ByteBuffer over backingStore->Data() + array->ByteOffset() with capacity array->ByteLength(), and Crypto.java fills the whole capacity after a rewind():

buffer.rewind();
int size = buffer.capacity();
byte[] tempBuf = new byte[size];
random.nextBytes(tempBuf);
buffer.put(tempBuf);

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 — getRandomValues returns an object the caller never passed in

Both branches assign the coerced view over the typedArray parameter and then return typedArray, so for any non-byte typed array the caller gets back a Uint8Array rather than its own view. WebCrypto requires the same object back. #10658 added the missing return, 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:NO form:

const data = NSMutableData.dataWithBytesNoCopyLengthFreeWhenDone(bytes, bytes.byteLength, false);

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 else branch collapses to a single copying call:

return NSData.dataWithBytesLength(buffer, buffer.byteLength);

Passing the typed-array view itself as the const void *bytes parameter: the iOS runtime's pointer marshalling resolves it to backingStore->Data() + byteOffset (view-aware — audited against the runtime source), and dataWithBytes: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 intermediate NSData, no ownership games.

3 & 4. The coercion is now a local bound to the caller's window, and the parameter is returned untouched:

getRandomValues<T extends Exclude<TypedArray, Float32Array | Float64Array>>(typedArray: T): T {
	const bytes = typedArray.BYTES_PER_ELEMENT === 1 ? typedArray : new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
	...
	return typedArray;
}

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: freeWhenDone is false, 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 — ArrayBuffer still copies whole; Uint8Array, offset Uint8Array, offset Uint8ClampedArray and offset DataView all pass the view itself to dataWithBytes:length: with the window's byteLength.

packages/core/vitest.setup.ts gains NSData / NSMutableData / NSCCrypto stubs that record the selector and arguments they were called with, plus the Android org.nativescript.winter_tc.Crypto shim so both platform branches are reachable from the specs.

10 of the 13 new assertions fail against main and pass here; the other 3 cover behaviour this PR deliberately leaves alone. The full core suite passes (442 tests), and lint/build are clean.

Sweep

Any 2-arg dataWithBytesNoCopy:length: (or the NSMutableData equivalent) over a pointer derived from a typed array, interop.handleof, or another NSData's bytes is this bug class. A repo-wide sweep found no other reachable JS-side occurrences. The one remaining native hit — [NSData dataWithBytesNoCopy:exponent length:size] in packages/winter-tc/ios/NSCWinterTC/NSCWinterTC/NSCCrypto.m (generateKeyRsa) — is currently unreachable: every core call site passes null, 0 for 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.

`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.
@nx-cloud

nx-cloud Bot commented Aug 27, 2026 •

Copy link
Copy Markdown

View your CI Pipeline Execution ↗ for commit b8ba488

Command Status Duration Result
nx test apps-automated -c=ios ✅ Succeeded 2m 9s View ↗
nx run-many --target=test --configuration=ci --... ✅ Succeeded 1s View ↗

💡 Verify your cache is correct by running tasks in a sandbox. Read docs ↗


☁️ Nx Cloud last updated this comment at 2026-08-27 16:02:31 UTC

@pkg-pr-new

pkg-pr-new Bot commented Aug 27, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/@nativescript/core@11370
npm i https://pkg.pr.new/@nativescript/vite@11370
npm i https://pkg.pr.new/@nativescript/webpack@11370

commit: b8ba488

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.
@edusperoni edusperoni changed the title fix(core): stop donating V8-owned buffers to Foundation on iOS fix(core): iOS double free of V8-owned buffers; getRandomValues view handling Aug 27, 2026
@NathanWalker
NathanWalker merged commit f609f17 into main Aug 27, 2026
8 of 9 checks passed
@NathanWalker
NathanWalker deleted the fix/ios-nsdata-buffer-ownership branch August 27, 2026 16:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants