Skip to content

Commit 3c798e2

Browse files
authored
fix(worker): handle terminate() landing inside require() (#2115)
Every directory gets its require from the JS require factory, and the call into that factory is an interrupt check. A worker.terminate() that reached the worker's isolate since its previous check made the call come back empty, and the NS_CHECK on its result aborted the whole app: NS_CHECK failed: success && !result.IsEmpty() && result->IsFunction(), at ModuleInternal.cpp:302 The usual way in is terminating a worker that is still loading its entry module (new Worker, a few milliseconds of work on the parent, then terminate()). createRequire() reaches the same call from JS. GetRequireFunction now returns a MaybeLocal and leaves the termination pending. LoadModule throws the same NativeScriptException its other interrupted steps throw, so the load unwinds like a terminate() that lands in the module body; createRequire returns to JS with the termination pending. The mint done while the runtime boots keeps the hard check: terminate() cannot reach the isolate that early. A native callback that fails rethrows into V8 through NativeScriptException::ReThrowToV8, and Isolate::ThrowException replaces whatever exception is pending. When the failure was the isolate being terminated, the termination became an ordinary error, so a worker that wraps the call in try/catch caught it and carried on running after terminate(). ReThrowToV8 now leaves a pending termination alone, on entry and again right before the throw, since building the error to rethrow can itself run JS.
1 parent b8cc3cf commit 3c798e2

8 files changed

Lines changed: 162 additions & 18 deletions

‎test-app/app/src/main/assets/app/mainpage.js‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ require("./tests/testWebAssembly");
3232
require("./tests/testEventLoop");
3333
require("./tests/testMultithreadedJavascript");
3434
require("./tests/testWorkerTerminateDuringLoad");
35+
require("./tests/testWorkerTerminateDuringRequireMint");
36+
require("./tests/testWorkerTerminateCaughtRequire");
3537
require("./tests/testWorkerTerminateAfterClose");
3638
require("./tests/testWorkerOptions");
3739
require("./tests/testWorkerResourceLimits");
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
describe("Worker terminate inside a require the worker guards", function () {
2+
var START_DEADLINE = 3000;
3+
// Long enough for the worker to get from its flag into the module body.
4+
var TERMINATE_AFTER = 150;
5+
var SETTLE_AFTER = 300;
6+
var timers = [];
7+
8+
afterEach(function () {
9+
timers.forEach(clearTimeout);
10+
timers = [];
11+
});
12+
13+
function later(fn, ms) {
14+
timers.push(setTimeout(fn, ms));
15+
}
16+
17+
it("does not let the worker catch the interruption and carry on", function (done) {
18+
var shared = new Int32Array(new SharedArrayBuffer(8));
19+
var worker = new Worker("./workerTerminateCaughtRequireWorker.js");
20+
worker.onerror = function () {
21+
return true;
22+
};
23+
worker.postMessage(shared.buffer);
24+
var started = Date.now();
25+
26+
(function waitForRequire() {
27+
if (Atomics.load(shared, 0) === 0) {
28+
if (Date.now() - started > START_DEADLINE) {
29+
expect("the worker never reached its require").toBeNull();
30+
worker.terminate();
31+
done();
32+
return;
33+
}
34+
later(waitForRequire, 20);
35+
return;
36+
}
37+
later(function () {
38+
worker.terminate();
39+
later(function () {
40+
expect(Atomics.load(shared, 1)).toBe(0);
41+
done();
42+
}, SETTLE_AFTER);
43+
}, TERMINATE_AFTER);
44+
})();
45+
});
46+
});
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
describe("Worker terminate during a require mint", function () {
2+
// One terminate() lands inside a mint only some of the time, so the spec
3+
// takes enough shots for a miss on every one of them to be implausible.
4+
var ITERATIONS = 25;
5+
var SETTLE_AFTER = 60;
6+
var originalTimeout;
7+
8+
beforeEach(function () {
9+
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
10+
jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000;
11+
});
12+
13+
afterEach(function () {
14+
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
15+
});
16+
17+
it("should not report an error or crash when terminate() interrupts createRequire", function (done) {
18+
var errors = [];
19+
20+
function iteration(remaining) {
21+
if (remaining === 0) {
22+
expect(errors).toEqual([]);
23+
done();
24+
return;
25+
}
26+
27+
var worker = new Worker("./workerRequireMintSpinWorker.js");
28+
worker.onerror = function (e) {
29+
errors.push(e.message);
30+
return true;
31+
};
32+
worker.onmessage = function () {
33+
// Spread over a few milliseconds so the shots do not all hit
34+
// the same phase of the worker's loop.
35+
setTimeout(function () {
36+
worker.terminate();
37+
setTimeout(function () {
38+
iteration(remaining - 1);
39+
}, SETTLE_AFTER);
40+
}, remaining % 4);
41+
};
42+
}
43+
44+
iteration(ITERATIONS);
45+
});
46+
});
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// Entry for testWorkerTerminateDuringRequireMint. Every call names a directory
2+
// no earlier call used, so each one runs the native mint instead of being
3+
// served from the per-directory require cache.
4+
var createRequire = require("ns:module").createRequire;
5+
6+
postMessage("spinning");
7+
8+
// Bounded so a worker that terminate() failed to stop does not outlive the spec.
9+
var deadline = Date.now() + 2000;
10+
for (var i = 0; Date.now() < deadline;) {
11+
for (var batch = 0; batch < 200; batch++, i++) {
12+
createRequire("/worker-require-mint-spin/" + i + "/");
13+
}
14+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// Entry for testWorkerTerminateCaughtRequire. [0] tells the parent the
2+
// require below is about to start; [1] is only ever set by code that ran
3+
// after that require was interrupted.
4+
onmessage = function (msg) {
5+
var shared = new Int32Array(msg.data);
6+
Atomics.store(shared, 0, 1);
7+
try {
8+
// Spins at module scope, so the parent's terminate() lands inside it.
9+
require("./workerTerminateDuringLoadWorker.js");
10+
} catch (e) {
11+
}
12+
Atomics.store(shared, 1, 1);
13+
};

‎test-app/runtime/src/main/cpp/ModuleInternal.cpp‎

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -203,16 +203,14 @@ void ModuleInternal::Init(Isolate* isolate, const string& baseDir) {
203203
global->Set(context, ArgConverter::ConvertToV8String(isolate, "__nativeRequire"),
204204
publicRequireTemplate->GetFunction(context).ToLocalChecked());
205205

206+
// terminate() cannot reach this isolate yet - a worker's is published to its
207+
// parent only once the runtime is up - so this mint is checked as hard as
208+
// the factory's own load above.
206209
Local<Function> globalRequire;
207-
208-
if (!baseDir.empty()) {
209-
globalRequire = GetRequireFunction(isolate, baseDir, RequireEvaluationOptions(
210-
ModuleEvaluationPolicy::kSyncStrict));
211-
} else {
212-
globalRequire = GetRequireFunction(isolate, Constants::APP_ROOT_FOLDER_PATH,
213-
RequireEvaluationOptions(
214-
ModuleEvaluationPolicy::kSyncStrict));
215-
}
210+
const bool minted = GetRequireFunction(
211+
isolate, baseDir.empty() ? Constants::APP_ROOT_FOLDER_PATH : baseDir,
212+
RequireEvaluationOptions(ModuleEvaluationPolicy::kSyncStrict)).ToLocal(&globalRequire);
213+
NS_CHECK(minted);
216214
global->Set(context, ArgConverter::ConvertToV8String(isolate, "require"), globalRequire);
217215
}
218216

@@ -269,8 +267,8 @@ static std::string RequireCacheKey(const std::string& dirName,
269267
return key;
270268
}
271269

272-
Local<Function> ModuleInternal::GetRequireFunction(Isolate* isolate, const string& dirName,
273-
const ModuleEvaluationOptions& options) {
270+
MaybeLocal<Function> ModuleInternal::GetRequireFunction(Isolate* isolate, const string& dirName,
271+
const ModuleEvaluationOptions& options) {
274272
TNSPERF();
275273
Local<Function> requireFunc;
276274

@@ -297,9 +295,14 @@ Local<Function> ModuleInternal::GetRequireFunction(Isolate* isolate, const strin
297295
};
298296
Local<Value> result;
299297
auto thiz = Object::New(isolate);
300-
auto success = requireFuncFactory->Call(context, thiz, 6, args).ToLocal(&result);
298+
// The factory cannot throw, but entering it is an interrupt check: a
299+
// terminate() that reached this isolate since its last one surfaces
300+
// here and stays pending for the caller to unwind with.
301+
if (!requireFuncFactory->Call(context, thiz, 6, args).ToLocal(&result)) {
302+
return MaybeLocal<Function>();
303+
}
301304

302-
NS_CHECK(success && !result.IsEmpty() && result->IsFunction());
305+
NS_CHECK(result->IsFunction());
303306

304307
requireFunc = result.As<Function>();
305308

@@ -351,7 +354,10 @@ void ModuleInternal::CreateRequireCallback(const v8::FunctionCallbackInfo<v8::Va
351354
options.pumpRunLoop = args[4]->BooleanValue(isolate);
352355
}
353356

354-
args.GetReturnValue().Set(moduleInternal->GetRequireFunction(isolate, dirName, options));
357+
Local<Function> require;
358+
if (moduleInternal->GetRequireFunction(isolate, dirName, options).ToLocal(&require)) {
359+
args.GetReturnValue().Set(require);
360+
}
355361
}
356362

357363
bool ModuleInternal::InstallCreateRequireBinding(Local<Context> context, Local<Object> binding) {
@@ -931,7 +937,10 @@ Local<Object> ModuleInternal::LoadModule(Isolate* isolate, const string& moduleP
931937
auto dirName = ArgConverter::ConvertToV8String(isolate, strDirName);
932938
// A module's own require inherits the options it was loaded under, so a
933939
// pumping require's whole dependency tree keeps pumping.
934-
auto require = GetRequireFunction(isolate, strDirName, options);
940+
Local<Function> require;
941+
if (!GetRequireFunction(isolate, strDirName, options).ToLocal(&require)) {
942+
throw NativeScriptException(tc, "Cannot create the require function for " + modulePath);
943+
}
935944
Local<Value> requireArgs[5] {
936945
moduleObj, exportsObj, require, fileName, dirName
937946
};

‎test-app/runtime/src/main/cpp/ModuleInternal.h‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -216,10 +216,13 @@ class ModuleInternal {
216216
* The options ride along as trailing arguments to the require factory, so
217217
* nothing about them is ambient — and they are resolved once at mint time,
218218
* never per require() call.
219+
*
220+
* Empty when minting was interrupted - the isolate is terminating - in
221+
* which case nothing is cached and the termination is left pending.
219222
*/
220-
v8::Local<v8::Function> GetRequireFunction(v8::Isolate* isolate,
221-
const std::string& dirName,
222-
const ModuleEvaluationOptions& options);
223+
v8::MaybeLocal<v8::Function> GetRequireFunction(v8::Isolate* isolate,
224+
const std::string& dirName,
225+
const ModuleEvaluationOptions& options);
223226

224227
/*
225228
* A V8 code cache produced by a classic-script compile and one produced by a

‎test-app/runtime/src/main/cpp/NativeScriptException.cpp‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,12 @@ NativeScriptException::NativeScriptException(TryCatch& tc,
236236

237237
void NativeScriptException::ReThrowToV8() {
238238
auto isolate = Isolate::GetCurrent();
239+
// Throwing replaces whatever is pending. A pending termination has to keep
240+
// unwinding as one: turned into an ordinary error, a catch block in the
241+
// worker's JS would swallow terminate().
242+
if (isolate->IsExecutionTerminating()) {
243+
return;
244+
}
239245
auto context = isolate->GetCurrentContext();
240246
Local<Value> errObj;
241247

@@ -265,6 +271,11 @@ void NativeScriptException::ReThrowToV8() {
265271
isolate, "No javascript exception or message provided."));
266272
}
267273

274+
// Building the error can itself run JS (a `fullMessage` setter, the Java
275+
// exception wrapper), which is one more place a termination can surface.
276+
if (isolate->IsExecutionTerminating()) {
277+
return;
278+
}
268279
isolate->ThrowException(errObj);
269280
}
270281

0 commit comments

Comments
 (0)