From b2f0a0539d74b31d544d56e4b9d0e080f0b02990 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 15 Nov 2026 14:40:46 -0300 Subject: [PATCH 1/4] fix(runtime): wrap a JS block made by another isolate as a native block A block built from a JS function can reach another isolate through native state shared by the whole process (a static, a singleton, a shared object). When such a block came back to JS, as a call result or as an argument to a JS-implemented method, GetResult recognised it by the process-wide JSBlock descriptor and answered the function its Persistent held, reading another isolate's handle in the calling isolate without that isolate's lock. The function object lives in the other heap, so using it crashed in V8 code, and once the owning worker was gone the read was a use-after-free. Only the isolate that made the block now gets its function back. Any other isolate wraps it like any native block: Block_copy plus an owning BlockWrapper, and calling it goes through the block's entry point, which pins and locks the owning isolate, runs the function there, and answers a zeroed result once that isolate is gone. Passing that wrapper back to native code hands over the same block. Isolates are told apart by the id Caches::Init assigns, never by address: a disposed worker isolate's address is reused by later isolates, so an address check takes a dead worker's block for the new worker's own. --- NativeScript/runtime/Interop.mm | 18 +- NativeScript/runtime/IsolateWrapper.h | 5 + TestFixtures/Marshalling/TNSAllocLog.h | 10 + TestFixtures/Marshalling/TNSAllocLog.m | 47 ++++ TestRunner/app/tests/BlockCacheRaceTests.js | 228 ++++++++++++++++++++ 5 files changed, 301 insertions(+), 7 deletions(-) diff --git a/NativeScript/runtime/Interop.mm b/NativeScript/runtime/Interop.mm index 9c83ce538..728a03ebb 100644 --- a/NativeScript/runtime/Interop.mm +++ b/NativeScript/runtime/Interop.mm @@ -1217,14 +1217,18 @@ static bool SnapshotArrayLike(Isolate* isolate, Local object, Localdescriptor == &JSBlock::kJSBlockDescriptor) { MethodCallbackWrapper* wrapper = static_cast(block->userData); - Local callback = wrapper->callback_->Get(isolate).As(); - // The last reference runs the dispose helper right here, under the - // Locker this thread holds, which frees `wrapper`; `callback` is a - // handle of its own and stays usable. - if (releasesOwnedReturn) { - Block_release(block); + // Another isolate's block is wrapped below like any native block: + // calling it runs the function in the isolate that made it. + if (wrapper->isolateWrapper_.BelongsTo(isolate)) { + Local callback = wrapper->callback_->Get(isolate).As(); + // The last reference runs the dispose helper right here, under the + // Locker this thread holds, which frees `wrapper`; `callback` is a + // handle of its own and stays usable. + if (releasesOwnedReturn) { + Block_release(block); + } + return callback; } - return callback; } // Take ownership of the returned block. Block_copy (not CFRetain) is the diff --git a/NativeScript/runtime/IsolateWrapper.h b/NativeScript/runtime/IsolateWrapper.h index 964075657..04e4da7bf 100644 --- a/NativeScript/runtime/IsolateWrapper.h +++ b/NativeScript/runtime/IsolateWrapper.h @@ -82,6 +82,11 @@ class IsolateWrapper { // True once the teardown has finished with every wrapper reachable from // JS. Read it while pinned. inline bool IsTornDown() const { return IsolateGates::IsClosed(gateId_); } + // Compares isolate ids, not addresses: a disposed isolate's address can be + // reused by a later isolate. `isolate` must be alive. + inline bool BelongsTo(v8::Isolate* isolate) const { + return gateId_ != -1 && tns::Caches::Get(isolate)->getGateId() == gateId_; + } private: v8::Isolate* isolate_; diff --git a/TestFixtures/Marshalling/TNSAllocLog.h b/TestFixtures/Marshalling/TNSAllocLog.h index e425fe7d3..8537238ec 100644 --- a/TestFixtures/Marshalling/TNSAllocLog.h +++ b/TestFixtures/Marshalling/TNSAllocLog.h @@ -84,6 +84,16 @@ id TNSOwnedPrimitivesObjectAt(TNSOwnedPrimitives* holder, NSUInteger index); - (void)storeBlock:(NSInteger (^)(void))block; - (NSInteger (^)(void))retainedStoredBlock NS_RETURNS_RETAINED; +// One block slot for the whole process, reachable from every isolate. ++ (void)storeSharedBlock:(NSInteger (^)(NSInteger))block; ++ (NSInteger (^)(NSInteger))sharedBlock; +// Answers an extra reference; the slot keeps its own. ++ (NSInteger (^)(NSInteger))retainedSharedBlock NS_RETURNS_RETAINED; +// Hands the slot's reference over and empties the slot. ++ (NSInteger (^)(NSInteger))takeSharedBlock NS_RETURNS_RETAINED; ++ (void)clearSharedBlock; ++ (NSInteger)callBlock:(NSInteger (^)(NSInteger))block withValue:(NSInteger)value; + @end // Declares the owned-return members of TNSOwnedReturns itself, so JS can diff --git a/TestFixtures/Marshalling/TNSAllocLog.m b/TestFixtures/Marshalling/TNSAllocLog.m index dde24b773..ecf5f038c 100644 --- a/TestFixtures/Marshalling/TNSAllocLog.m +++ b/TestFixtures/Marshalling/TNSAllocLog.m @@ -138,6 +138,53 @@ - (void)storeBlock:(NSInteger (^)(void))block { return block; } +static NSInteger (^gSharedBlock)(NSInteger); + +// A JS block's dispose waits for its isolate, so the slot's previous block is +// released outside the lock. ++ (void)storeSharedBlock:(NSInteger (^)(NSInteger))block { + NSInteger (^previous)(NSInteger); + @synchronized([TNSOwnedBlocks class]) { + previous = gSharedBlock; + gSharedBlock = block; + } + previous = nil; +} + ++ (NSInteger (^)(NSInteger))sharedBlock { + NSInteger (^block)(NSInteger); + @synchronized([TNSOwnedBlocks class]) { + block = gSharedBlock; + } + return block; +} + ++ (NSInteger (^)(NSInteger))retainedSharedBlock { + return [self sharedBlock]; +} + ++ (NSInteger (^)(NSInteger))takeSharedBlock { + NSInteger (^block)(NSInteger); + @synchronized([TNSOwnedBlocks class]) { + block = gSharedBlock; + gSharedBlock = nil; + } + return block; +} + ++ (void)clearSharedBlock { + NSInteger (^block)(NSInteger); + @synchronized([TNSOwnedBlocks class]) { + block = gSharedBlock; + gSharedBlock = nil; + } + block = nil; +} + ++ (NSInteger)callBlock:(NSInteger (^)(NSInteger))block withValue:(NSInteger)value { + return block(value); +} + @end // Foundation answers tagged pointers for dates in the range JS can represent. diff --git a/TestRunner/app/tests/BlockCacheRaceTests.js b/TestRunner/app/tests/BlockCacheRaceTests.js index 05fbb512c..fdfdc5b01 100644 --- a/TestRunner/app/tests/BlockCacheRaceTests.js +++ b/TestRunner/app/tests/BlockCacheRaceTests.js @@ -157,3 +157,231 @@ describe("JS block outliving its worker", function () { worker.postMessage(0); }); }); + +// Native state such as a static is shared by every isolate, so a block made +// from one isolate's function can be handed to another. Only the isolate that +// made it gets the function itself back; any other one gets a function that +// calls the block, which runs the original function in its own isolate. +describe("JS block made by another isolate", function () { + var originalTimeout; + var workers = []; + beforeEach(function () { + originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; + jasmine.DEFAULT_TIMEOUT_INTERVAL = 20000; + }); + afterEach(function () { + TNSOwnedBlocks.clearSharedBlock(); + workers.splice(0).forEach(function (worker) { + worker.terminate(); + }); + jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; + }); + + function evalWorker() { + var worker = new Worker("~/shared/Workers/EvalWorker.js"); + worker.onerror = function (e) { + fail("unexpected worker error: " + (e && e.message ? e.message : e)); + return true; + }; + workers.push(worker); + return worker; + } + + // Resolves with the worker's next message. + function ask(worker, source) { + return new Promise(function (resolve) { + worker.onmessage = function (msg) { + resolve(msg.data); + }; + worker.postMessage({ eval: source }); + }); + } + + // Resolves once the worker's runtime is gone. + function terminate(worker) { + return new Promise(function (resolve) { + worker.addEventListener("nsworkerended", function () { + resolve(); + }); + worker.terminate(); + }); + } + + function collect() { + return new Promise(function (resolve) { + setTimeout(function () { + __collect(); + setTimeout(resolve, 20); + }, 20); + }); + } + + function finish(done) { + return function (err) { + if (err) { + fail(err && err.stack ? err.stack : err); + } + done(); + }; + } + + // `offset` exists only in the worker, so a call answering x + 1000 ran + // there. + var storeWorkerFunction = + "globalThis.offset = 1000;" + + "globalThis.calls = 0;" + + "globalThis.fn = function (x) { calls++; return x + offset; };" + + "TNSOwnedBlocks.storeSharedBlock(fn);" + + "postMessage('stored');"; + + it("calls a worker's function through its block, and answers zero once the worker is gone", function (done) { + var worker = evalWorker(); + var state = {}; + ask(worker, storeWorkerFunction) + .then(function (reply) { + expect(reply).toBe("stored"); + state.fn = TNSOwnedBlocks.sharedBlock(); + state.owned = TNSOwnedBlocks.retainedSharedBlock(); + expect(typeof state.fn).toBe("function"); + expect(typeof state.owned).toBe("function"); + expect(state.fn(1)).toBe(1001); + expect(state.owned(2)).toBe(1002); + state.taken = TNSOwnedBlocks.takeSharedBlock(); + expect(state.taken(3)).toBe(1003); + expect(TNSOwnedBlocks.sharedBlock()).toBe(null); + return ask(worker, "postMessage(calls);"); + }) + .then(function (calls) { + expect(calls).toBe(3); + return terminate(worker); + }) + .then(function () { + expect(state.fn(4)).toBe(0); + expect(state.owned(5)).toBe(0); + expect(state.taken(6)).toBe(0); + expect(TNSOwnedBlocks.callBlockWithValue(state.fn, 7)).toBe(0); + state = null; + return collect(); + }) + .then(finish(done), finish(done)); + }); + + it("hands native code the worker's own block when the function wrapping it is passed back", function (done) { + var worker = evalWorker(); + var state = {}; + ask(worker, storeWorkerFunction) + .then(function () { + state.fn = TNSOwnedBlocks.takeSharedBlock(); + expect(TNSOwnedBlocks.callBlockWithValue(state.fn, 1)).toBe(1001); + TNSOwnedBlocks.storeSharedBlock(state.fn); + state.fn = null; + return collect(); + }) + .then(function () { + return ask(worker, + "var back = TNSOwnedBlocks.sharedBlock();" + + "postMessage({ same: back === fn, calls: calls, result: back(2) });"); + }) + .then(function (reply) { + expect(reply.same).toBe(true); + expect(reply.calls).toBe(1); + expect(reply.result).toBe(1002); + TNSOwnedBlocks.clearSharedBlock(); + return terminate(worker); + }) + .then(finish(done), finish(done)); + }); + + // A block's function runs on the thread that calls the block, inside the + // isolate that made it. + it("calls the main isolate's function through its block from a worker", function (done) { + var worker = evalWorker(); + var state = { calls: 0, offset: 500 }; + state.fn = function (x) { + state.calls++; + state.thread = NSThread.currentThread.hash; + state.onMainThread = NSThread.isMainThread; + return x + state.offset; + }; + TNSOwnedBlocks.storeSharedBlock(state.fn); + ask(worker, + "var fn = TNSOwnedBlocks.sharedBlock();" + + "var owned = TNSOwnedBlocks.retainedSharedBlock();" + + "postMessage({ type: typeof fn, thread: NSThread.currentThread.hash," + + " results: [fn(1), owned(2), TNSOwnedBlocks.callBlockWithValue(fn, 3)] });") + .then(function (reply) { + expect(reply.type).toBe("function"); + expect(reply.results).toEqual([501, 502, 503]); + expect(state.calls).toBe(3); + expect(state.onMainThread).toBe(false); + expect(state.thread).toBe(reply.thread); + TNSOwnedBlocks.clearSharedBlock(); + return terminate(worker); + }) + .then(collect) + .then(finish(done), finish(done)); + }); + + it("answers the main isolate its own function", function () { + var fn = function (x) { + return x * 2; + }; + TNSOwnedBlocks.storeSharedBlock(fn); + expect(TNSOwnedBlocks.sharedBlock()).toBe(fn); + expect(TNSOwnedBlocks.retainedSharedBlock()).toBe(fn); + expect(TNSOwnedBlocks.takeSharedBlock()).toBe(fn); + expect(TNSOwnedBlocks.sharedBlock()).toBe(null); + }); + + it("answers a worker its own function", function (done) { + var worker = evalWorker(); + ask(worker, + "var own = function (x) { return x * 3; };" + + "TNSOwnedBlocks.storeSharedBlock(own);" + + "postMessage([TNSOwnedBlocks.sharedBlock() === own," + + " TNSOwnedBlocks.retainedSharedBlock() === own," + + " TNSOwnedBlocks.takeSharedBlock() === own," + + " TNSOwnedBlocks.sharedBlock() === null]);") + .then(function (reply) { + expect(reply).toEqual([true, true, true, true]); + return terminate(worker); + }) + .then(finish(done), finish(done)); + }); + + // A later worker's isolate may sit at the address of the one that made the + // block, so only an isolate id tells the two apart. Which later isolate + // lands there depends on the allocator, so several workers in a row read + // the block. + it("does not answer a later worker the function of a block whose worker is gone", function (done) { + var READERS = 4; + var maker = evalWorker(); + function read(i) { + if (i === READERS) { + return Promise.resolve(); + } + var reader = evalWorker(); + return ask(reader, + "var fn = TNSOwnedBlocks.sharedBlock();" + + "postMessage({ type: typeof fn, result: fn(1)," + + " owned: TNSOwnedBlocks.retainedSharedBlock()(2) });") + .then(function (reply) { + expect(reply.type).toBe("function"); + expect(reply.result).toBe(0); + expect(reply.owned).toBe(0); + return terminate(reader); + }) + .then(function () { + return read(i + 1); + }); + } + ask(maker, storeWorkerFunction) + .then(function () { + return terminate(maker); + }) + .then(function () { + return read(0); + }) + .then(finish(done), finish(done)); + }); +}); From 2aaa9ddea0c6190da5932c62bcfb31518253fd3c Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 15 Nov 2026 17:04:44 -0300 Subject: [PATCH 2/4] test(runtime): keep the shared-block fixture from releasing a block under its lock The fixture drops the slot's previous block after leaving its lock, because a JS block's dispose helper waits for the owning isolate. ARC may release an unused strong local at its last use, which is inside the lock; a precise lifetime keeps the release where the code puts it. --- TestFixtures/Marshalling/TNSAllocLog.m | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/TestFixtures/Marshalling/TNSAllocLog.m b/TestFixtures/Marshalling/TNSAllocLog.m index ecf5f038c..6b9059f80 100644 --- a/TestFixtures/Marshalling/TNSAllocLog.m +++ b/TestFixtures/Marshalling/TNSAllocLog.m @@ -141,9 +141,10 @@ - (void)storeBlock:(NSInteger (^)(void))block { static NSInteger (^gSharedBlock)(NSInteger); // A JS block's dispose waits for its isolate, so the slot's previous block is -// released outside the lock. +// released outside the lock. Precise lifetime keeps ARC from releasing it +// earlier, at its last use inside the lock. + (void)storeSharedBlock:(NSInteger (^)(NSInteger))block { - NSInteger (^previous)(NSInteger); + __attribute__((objc_precise_lifetime)) NSInteger (^previous)(NSInteger); @synchronized([TNSOwnedBlocks class]) { previous = gSharedBlock; gSharedBlock = block; @@ -173,7 +174,7 @@ + (void)storeSharedBlock:(NSInteger (^)(NSInteger))block { } + (void)clearSharedBlock { - NSInteger (^block)(NSInteger); + __attribute__((objc_precise_lifetime)) NSInteger (^block)(NSInteger); @synchronized([TNSOwnedBlocks class]) { block = gSharedBlock; gSharedBlock = nil; From a17cad3b5d5995e8ff3a4fb354377eb1bea50497 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 15 Nov 2026 21:20:14 -0300 Subject: [PATCH 3/4] fix(runtime): decide an entered isolate by id when pinning IsolateWrapper::Pin() took a thread as already inside the isolate when the entered isolate's address matched. A later isolate can sit at a disposed one's address, so that handed out a usable pin for an isolate that is gone and left it to each caller to notice. The entered isolate's id has to match as well now. --- NativeScript/runtime/Interop.mm | 7 ++++++- NativeScript/runtime/IsolateWrapper.h | 7 +++++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/NativeScript/runtime/Interop.mm b/NativeScript/runtime/Interop.mm index 728a03ebb..2ee515287 100644 --- a/NativeScript/runtime/Interop.mm +++ b/NativeScript/runtime/Interop.mm @@ -45,6 +45,10 @@ // resetting it never touches the finalizer drain's bookkeeping, // and a foreign-thread Locker into the block's own isolate is // legitimate now that extended class names are worker-scoped. + // A thread holding another isolate's Locker is the exception: it + // gets here when that isolate was handed this block, and it + // deadlocks if this isolate is waiting for that Locker in turn. + // Blocks shared between isolates carry that risk. // // Validity is not the test here: the slot stays reachable after // the isolate is invalidated, by JS still running under the Locker @@ -654,7 +658,8 @@ static bool SnapshotArrayLike(Isolate* isolate, Local object, LocalOwnsBlock()) { - // A native block; the wrapper's own Block_copy keeps it alive. + // A native block, or another isolate's JS block; the wrapper's own + // Block_copy keeps it alive. blockPtr = CFAutorelease(Block_copy(wrapper->Block())); } else if (TryRetainJSBlock(static_cast(wrapper->Block()))) { // Reading the block is safe even when its last release raced ahead: diff --git a/NativeScript/runtime/IsolateWrapper.h b/NativeScript/runtime/IsolateWrapper.h index 04e4da7bf..186c13b4f 100644 --- a/NativeScript/runtime/IsolateWrapper.h +++ b/NativeScript/runtime/IsolateWrapper.h @@ -75,9 +75,12 @@ class IsolateWrapper { } // Hold the returned pin across any wait for the isolate's Locker from a // thread that is not already inside the isolate; an empty pin means the - // isolate may already be disposed and must not be touched at all. + // isolate may already be disposed and must not be touched at all. The + // isolate this thread has entered counts only when its id matches too: it + // may be a later one at this isolate's address. inline IsolatePin Pin() const { - return IsolatePin(gateId_, v8::Isolate::TryGetCurrent() == isolate_); + v8::Isolate* current = v8::Isolate::TryGetCurrent(); + return IsolatePin(gateId_, current == isolate_ && BelongsTo(current)); } // True once the teardown has finished with every wrapper reachable from // JS. Read it while pinned. From f85a5830631b783b8b9e8c5fcb24c3e8982d0524 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 15 Nov 2026 22:12:38 -0300 Subject: [PATCH 4/4] perf(runtime): read an isolate's gate id without copying its caches IsolateWrapper::BelongsTo runs on every native call into JS made on the isolate's own thread, and went through Caches::Get: a shared_ptr copy, and a stand-in Caches once the real one is removed. Caches::GateIdOf reads the id straight from the isolate's data slot. --- NativeScript/runtime/Caches.h | 8 ++++++++ NativeScript/runtime/IsolateWrapper.h | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/NativeScript/runtime/Caches.h b/NativeScript/runtime/Caches.h index 666d7e631..36f1812e5 100644 --- a/NativeScript/runtime/Caches.h +++ b/NativeScript/runtime/Caches.h @@ -86,6 +86,14 @@ class Caches { // so we return a dummy cache return std::make_shared(isolate); } + // The gate id of the Caches `isolate` holds, or -1 once they are removed. + // Cheaper than Get(): no shared_ptr copy, and no stand-in Caches. + inline static int GateIdOf(v8::Isolate* isolate) { + auto cache = isolate->GetData(0); + return cache != nullptr + ? (*reinterpret_cast*>(cache))->gateId_ + : -1; + } static void Remove(v8::Isolate* isolate); // Per-isolate storage for subsystem state, so a subsystem can declare its diff --git a/NativeScript/runtime/IsolateWrapper.h b/NativeScript/runtime/IsolateWrapper.h index 186c13b4f..a629bb64e 100644 --- a/NativeScript/runtime/IsolateWrapper.h +++ b/NativeScript/runtime/IsolateWrapper.h @@ -88,7 +88,7 @@ class IsolateWrapper { // Compares isolate ids, not addresses: a disposed isolate's address can be // reused by a later isolate. `isolate` must be alive. inline bool BelongsTo(v8::Isolate* isolate) const { - return gateId_ != -1 && tns::Caches::Get(isolate)->getGateId() == gateId_; + return gateId_ != -1 && tns::Caches::GateIdOf(isolate) == gateId_; } private: