Skip to content

Commit 42ec82e

Browse files
committed
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.
1 parent f81d226 commit 42ec82e

5 files changed

Lines changed: 301 additions & 7 deletions

File tree

‎NativeScript/runtime/Interop.mm‎

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1217,14 +1217,18 @@ static bool SnapshotArrayLike(Isolate* isolate, Local<Object> object, Local<v8::
12171217

12181218
if (block->descriptor == &JSBlock::kJSBlockDescriptor) {
12191219
MethodCallbackWrapper* wrapper = static_cast<MethodCallbackWrapper*>(block->userData);
1220-
Local<v8::Function> callback = wrapper->callback_->Get(isolate).As<v8::Function>();
1221-
// The last reference runs the dispose helper right here, under the
1222-
// Locker this thread holds, which frees `wrapper`; `callback` is a
1223-
// handle of its own and stays usable.
1224-
if (releasesOwnedReturn) {
1225-
Block_release(block);
1220+
// Another isolate's block is wrapped below like any native block:
1221+
// calling it runs the function in the isolate that made it.
1222+
if (wrapper->isolateWrapper_.BelongsTo(isolate)) {
1223+
Local<v8::Function> callback = wrapper->callback_->Get(isolate).As<v8::Function>();
1224+
// The last reference runs the dispose helper right here, under the
1225+
// Locker this thread holds, which frees `wrapper`; `callback` is a
1226+
// handle of its own and stays usable.
1227+
if (releasesOwnedReturn) {
1228+
Block_release(block);
1229+
}
1230+
return callback;
12261231
}
1227-
return callback;
12281232
}
12291233

12301234
// Take ownership of the returned block. Block_copy (not CFRetain) is the

‎NativeScript/runtime/IsolateWrapper.h‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,11 @@ class IsolateWrapper {
8282
// True once the teardown has finished with every wrapper reachable from
8383
// JS. Read it while pinned.
8484
inline bool IsTornDown() const { return IsolateGates::IsClosed(gateId_); }
85+
// Compares isolate ids, not addresses: a disposed isolate's address can be
86+
// reused by a later isolate. `isolate` must be alive.
87+
inline bool BelongsTo(v8::Isolate* isolate) const {
88+
return gateId_ != -1 && tns::Caches::Get(isolate)->getGateId() == gateId_;
89+
}
8590

8691
private:
8792
v8::Isolate* isolate_;

‎TestFixtures/Marshalling/TNSAllocLog.h‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,16 @@ id TNSOwnedPrimitivesObjectAt(TNSOwnedPrimitives* holder, NSUInteger index);
8484
- (void)storeBlock:(NSInteger (^)(void))block;
8585
- (NSInteger (^)(void))retainedStoredBlock NS_RETURNS_RETAINED;
8686

87+
// One block slot for the whole process, reachable from every isolate.
88+
+ (void)storeSharedBlock:(NSInteger (^)(NSInteger))block;
89+
+ (NSInteger (^)(NSInteger))sharedBlock;
90+
// Answers an extra reference; the slot keeps its own.
91+
+ (NSInteger (^)(NSInteger))retainedSharedBlock NS_RETURNS_RETAINED;
92+
// Hands the slot's reference over and empties the slot.
93+
+ (NSInteger (^)(NSInteger))takeSharedBlock NS_RETURNS_RETAINED;
94+
+ (void)clearSharedBlock;
95+
+ (NSInteger)callBlock:(NSInteger (^)(NSInteger))block withValue:(NSInteger)value;
96+
8797
@end
8898

8999
// Declares the owned-return members of TNSOwnedReturns itself, so JS can

‎TestFixtures/Marshalling/TNSAllocLog.m‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,53 @@ - (void)storeBlock:(NSInteger (^)(void))block {
138138
return block;
139139
}
140140

141+
static NSInteger (^gSharedBlock)(NSInteger);
142+
143+
// A JS block's dispose waits for its isolate, so the slot's previous block is
144+
// released outside the lock.
145+
+ (void)storeSharedBlock:(NSInteger (^)(NSInteger))block {
146+
NSInteger (^previous)(NSInteger);
147+
@synchronized([TNSOwnedBlocks class]) {
148+
previous = gSharedBlock;
149+
gSharedBlock = block;
150+
}
151+
previous = nil;
152+
}
153+
154+
+ (NSInteger (^)(NSInteger))sharedBlock {
155+
NSInteger (^block)(NSInteger);
156+
@synchronized([TNSOwnedBlocks class]) {
157+
block = gSharedBlock;
158+
}
159+
return block;
160+
}
161+
162+
+ (NSInteger (^)(NSInteger))retainedSharedBlock {
163+
return [self sharedBlock];
164+
}
165+
166+
+ (NSInteger (^)(NSInteger))takeSharedBlock {
167+
NSInteger (^block)(NSInteger);
168+
@synchronized([TNSOwnedBlocks class]) {
169+
block = gSharedBlock;
170+
gSharedBlock = nil;
171+
}
172+
return block;
173+
}
174+
175+
+ (void)clearSharedBlock {
176+
NSInteger (^block)(NSInteger);
177+
@synchronized([TNSOwnedBlocks class]) {
178+
block = gSharedBlock;
179+
gSharedBlock = nil;
180+
}
181+
block = nil;
182+
}
183+
184+
+ (NSInteger)callBlock:(NSInteger (^)(NSInteger))block withValue:(NSInteger)value {
185+
return block(value);
186+
}
187+
141188
@end
142189

143190
// Foundation answers tagged pointers for dates in the range JS can represent.

‎TestRunner/app/tests/BlockCacheRaceTests.js‎

Lines changed: 228 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,3 +157,231 @@ describe("JS block outliving its worker", function () {
157157
worker.postMessage(0);
158158
});
159159
});
160+
161+
// Native state such as a static is shared by every isolate, so a block made
162+
// from one isolate's function can be handed to another. Only the isolate that
163+
// made it gets the function itself back; any other one gets a function that
164+
// calls the block, which runs the original function in its own isolate.
165+
describe("JS block made by another isolate", function () {
166+
var originalTimeout;
167+
var workers = [];
168+
beforeEach(function () {
169+
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
170+
jasmine.DEFAULT_TIMEOUT_INTERVAL = 20000;
171+
});
172+
afterEach(function () {
173+
TNSOwnedBlocks.clearSharedBlock();
174+
workers.splice(0).forEach(function (worker) {
175+
worker.terminate();
176+
});
177+
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
178+
});
179+
180+
function evalWorker() {
181+
var worker = new Worker("~/shared/Workers/EvalWorker.js");
182+
worker.onerror = function (e) {
183+
fail("unexpected worker error: " + (e && e.message ? e.message : e));
184+
return true;
185+
};
186+
workers.push(worker);
187+
return worker;
188+
}
189+
190+
// Resolves with the worker's next message.
191+
function ask(worker, source) {
192+
return new Promise(function (resolve) {
193+
worker.onmessage = function (msg) {
194+
resolve(msg.data);
195+
};
196+
worker.postMessage({ eval: source });
197+
});
198+
}
199+
200+
// Resolves once the worker's runtime is gone.
201+
function terminate(worker) {
202+
return new Promise(function (resolve) {
203+
worker.addEventListener("nsworkerended", function () {
204+
resolve();
205+
});
206+
worker.terminate();
207+
});
208+
}
209+
210+
function collect() {
211+
return new Promise(function (resolve) {
212+
setTimeout(function () {
213+
__collect();
214+
setTimeout(resolve, 20);
215+
}, 20);
216+
});
217+
}
218+
219+
function finish(done) {
220+
return function (err) {
221+
if (err) {
222+
fail(err && err.stack ? err.stack : err);
223+
}
224+
done();
225+
};
226+
}
227+
228+
// `offset` exists only in the worker, so a call answering x + 1000 ran
229+
// there.
230+
var storeWorkerFunction =
231+
"globalThis.offset = 1000;" +
232+
"globalThis.calls = 0;" +
233+
"globalThis.fn = function (x) { calls++; return x + offset; };" +
234+
"TNSOwnedBlocks.storeSharedBlock(fn);" +
235+
"postMessage('stored');";
236+
237+
it("calls a worker's function through its block, and answers zero once the worker is gone", function (done) {
238+
var worker = evalWorker();
239+
var state = {};
240+
ask(worker, storeWorkerFunction)
241+
.then(function (reply) {
242+
expect(reply).toBe("stored");
243+
state.fn = TNSOwnedBlocks.sharedBlock();
244+
state.owned = TNSOwnedBlocks.retainedSharedBlock();
245+
expect(typeof state.fn).toBe("function");
246+
expect(typeof state.owned).toBe("function");
247+
expect(state.fn(1)).toBe(1001);
248+
expect(state.owned(2)).toBe(1002);
249+
state.taken = TNSOwnedBlocks.takeSharedBlock();
250+
expect(state.taken(3)).toBe(1003);
251+
expect(TNSOwnedBlocks.sharedBlock()).toBe(null);
252+
return ask(worker, "postMessage(calls);");
253+
})
254+
.then(function (calls) {
255+
expect(calls).toBe(3);
256+
return terminate(worker);
257+
})
258+
.then(function () {
259+
expect(state.fn(4)).toBe(0);
260+
expect(state.owned(5)).toBe(0);
261+
expect(state.taken(6)).toBe(0);
262+
expect(TNSOwnedBlocks.callBlockWithValue(state.fn, 7)).toBe(0);
263+
state = null;
264+
return collect();
265+
})
266+
.then(finish(done), finish(done));
267+
});
268+
269+
it("hands native code the worker's own block when the function wrapping it is passed back", function (done) {
270+
var worker = evalWorker();
271+
var state = {};
272+
ask(worker, storeWorkerFunction)
273+
.then(function () {
274+
state.fn = TNSOwnedBlocks.takeSharedBlock();
275+
expect(TNSOwnedBlocks.callBlockWithValue(state.fn, 1)).toBe(1001);
276+
TNSOwnedBlocks.storeSharedBlock(state.fn);
277+
state.fn = null;
278+
return collect();
279+
})
280+
.then(function () {
281+
return ask(worker,
282+
"var back = TNSOwnedBlocks.sharedBlock();" +
283+
"postMessage({ same: back === fn, calls: calls, result: back(2) });");
284+
})
285+
.then(function (reply) {
286+
expect(reply.same).toBe(true);
287+
expect(reply.calls).toBe(1);
288+
expect(reply.result).toBe(1002);
289+
TNSOwnedBlocks.clearSharedBlock();
290+
return terminate(worker);
291+
})
292+
.then(finish(done), finish(done));
293+
});
294+
295+
// A block's function runs on the thread that calls the block, inside the
296+
// isolate that made it.
297+
it("calls the main isolate's function through its block from a worker", function (done) {
298+
var worker = evalWorker();
299+
var state = { calls: 0, offset: 500 };
300+
state.fn = function (x) {
301+
state.calls++;
302+
state.thread = NSThread.currentThread.hash;
303+
state.onMainThread = NSThread.isMainThread;
304+
return x + state.offset;
305+
};
306+
TNSOwnedBlocks.storeSharedBlock(state.fn);
307+
ask(worker,
308+
"var fn = TNSOwnedBlocks.sharedBlock();" +
309+
"var owned = TNSOwnedBlocks.retainedSharedBlock();" +
310+
"postMessage({ type: typeof fn, thread: NSThread.currentThread.hash," +
311+
" results: [fn(1), owned(2), TNSOwnedBlocks.callBlockWithValue(fn, 3)] });")
312+
.then(function (reply) {
313+
expect(reply.type).toBe("function");
314+
expect(reply.results).toEqual([501, 502, 503]);
315+
expect(state.calls).toBe(3);
316+
expect(state.onMainThread).toBe(false);
317+
expect(state.thread).toBe(reply.thread);
318+
TNSOwnedBlocks.clearSharedBlock();
319+
return terminate(worker);
320+
})
321+
.then(collect)
322+
.then(finish(done), finish(done));
323+
});
324+
325+
it("answers the main isolate its own function", function () {
326+
var fn = function (x) {
327+
return x * 2;
328+
};
329+
TNSOwnedBlocks.storeSharedBlock(fn);
330+
expect(TNSOwnedBlocks.sharedBlock()).toBe(fn);
331+
expect(TNSOwnedBlocks.retainedSharedBlock()).toBe(fn);
332+
expect(TNSOwnedBlocks.takeSharedBlock()).toBe(fn);
333+
expect(TNSOwnedBlocks.sharedBlock()).toBe(null);
334+
});
335+
336+
it("answers a worker its own function", function (done) {
337+
var worker = evalWorker();
338+
ask(worker,
339+
"var own = function (x) { return x * 3; };" +
340+
"TNSOwnedBlocks.storeSharedBlock(own);" +
341+
"postMessage([TNSOwnedBlocks.sharedBlock() === own," +
342+
" TNSOwnedBlocks.retainedSharedBlock() === own," +
343+
" TNSOwnedBlocks.takeSharedBlock() === own," +
344+
" TNSOwnedBlocks.sharedBlock() === null]);")
345+
.then(function (reply) {
346+
expect(reply).toEqual([true, true, true, true]);
347+
return terminate(worker);
348+
})
349+
.then(finish(done), finish(done));
350+
});
351+
352+
// A later worker's isolate may sit at the address of the one that made the
353+
// block, so only an isolate id tells the two apart. Which later isolate
354+
// lands there depends on the allocator, so several workers in a row read
355+
// the block.
356+
it("does not answer a later worker the function of a block whose worker is gone", function (done) {
357+
var READERS = 4;
358+
var maker = evalWorker();
359+
function read(i) {
360+
if (i === READERS) {
361+
return Promise.resolve();
362+
}
363+
var reader = evalWorker();
364+
return ask(reader,
365+
"var fn = TNSOwnedBlocks.sharedBlock();" +
366+
"postMessage({ type: typeof fn, result: fn(1)," +
367+
" owned: TNSOwnedBlocks.retainedSharedBlock()(2) });")
368+
.then(function (reply) {
369+
expect(reply.type).toBe("function");
370+
expect(reply.result).toBe(0);
371+
expect(reply.owned).toBe(0);
372+
return terminate(reader);
373+
})
374+
.then(function () {
375+
return read(i + 1);
376+
});
377+
}
378+
ask(maker, storeWorkerFunction)
379+
.then(function () {
380+
return terminate(maker);
381+
})
382+
.then(function () {
383+
return read(0);
384+
})
385+
.then(finish(done), finish(done));
386+
});
387+
});

0 commit comments

Comments
 (0)