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/Interop.mm b/NativeScript/runtime/Interop.mm index 9c83ce538..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: @@ -1217,14 +1222,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..a629bb64e 100644 --- a/NativeScript/runtime/IsolateWrapper.h +++ b/NativeScript/runtime/IsolateWrapper.h @@ -75,13 +75,21 @@ 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. 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::GateIdOf(isolate) == 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..6b9059f80 100644 --- a/TestFixtures/Marshalling/TNSAllocLog.m +++ b/TestFixtures/Marshalling/TNSAllocLog.m @@ -138,6 +138,54 @@ - (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. Precise lifetime keeps ARC from releasing it +// earlier, at its last use inside the lock. ++ (void)storeSharedBlock:(NSInteger (^)(NSInteger))block { + __attribute__((objc_precise_lifetime)) 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 { + __attribute__((objc_precise_lifetime)) 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)); + }); +});