Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions NativeScript/runtime/Caches.h
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,14 @@ class Caches {
// so we return a dummy cache
return std::make_shared<Caches>(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<std::shared_ptr<Caches>*>(cache))->gateId_
: -1;
}
static void Remove(v8::Isolate* isolate);

// Per-isolate storage for subsystem state, so a subsystem can declare its
Expand Down
25 changes: 17 additions & 8 deletions NativeScript/runtime/Interop.mm
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -654,7 +658,8 @@ static bool SnapshotArrayLike(Isolate* isolate, Local<Object> object, Local<v8::
// the JSBlock dispose helper owns the ffi closure and the callback wrapper
// and only runs once the last reference goes away.
if (wrapper->OwnsBlock()) {
// 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<JSBlock*>(wrapper->Block()))) {
// Reading the block is safe even when its last release raced ahead:
Expand Down Expand Up @@ -1217,14 +1222,18 @@ static bool SnapshotArrayLike(Isolate* isolate, Local<Object> object, Local<v8::

if (block->descriptor == &JSBlock::kJSBlockDescriptor) {
MethodCallbackWrapper* wrapper = static_cast<MethodCallbackWrapper*>(block->userData);
Local<v8::Function> callback = wrapper->callback_->Get(isolate).As<v8::Function>();
// 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<v8::Function> callback = wrapper->callback_->Get(isolate).As<v8::Function>();
// 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
Expand Down
12 changes: 10 additions & 2 deletions NativeScript/runtime/IsolateWrapper.h
Original file line number Diff line number Diff line change
Expand Up @@ -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_;
Expand Down
10 changes: 10 additions & 0 deletions TestFixtures/Marshalling/TNSAllocLog.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
48 changes: 48 additions & 0 deletions TestFixtures/Marshalling/TNSAllocLog.m
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
228 changes: 228 additions & 0 deletions TestRunner/app/tests/BlockCacheRaceTests.js
Original file line number Diff line number Diff line change
Expand Up @@ -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));
});
});
Loading