Skip to content

Commit aebaba9

Browse files
committed
fix(worker): drop __runOnMainThread callbacks from a closing worker
The main thread read a worker's isolate from the callback cache, released the cache lock, then took a Locker on it. A worker shutting down in that window disposed the isolate first, and the main thread crashed in v8::Locker::Initialize. Each worker now has a gate the main thread holds from checking it until it owns the worker's Locker. Shutdown closes the gate before taking its teardown Locker, so a callback that arrives after that is dropped without touching the isolate, and the worker never waits on the main thread. A worker callback that throws under uncaughtErrorPolicy "throw" is now reported through the worker's own error path (its onerror, then the parent's Worker object) instead of being rethrown on the main thread, where it became a Java exception that resolved a handle from the worker isolate against the main one and crashed.
1 parent 560b3bf commit aebaba9

5 files changed

Lines changed: 65 additions & 6 deletions

File tree

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

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -741,10 +741,16 @@ void CallbackHandlers::RunOnMainThreadCallback(const FunctionCallbackInfo<v8::Va
741741
return;
742742
}
743743

744+
std::shared_ptr<IsolateGate> gate;
745+
if (auto wrapper = WorkerWrapper::FromIsolate(isolate)) {
746+
gate = wrapper->Gate();
747+
}
748+
744749
{
745750
std::lock_guard<std::mutex> lock(cacheMutex_);
746751
bool inserted;
747-
std::tie(std::ignore, inserted) = cache_.try_emplace(key, isolate, callback);
752+
std::tie(std::ignore, inserted) = cache_.try_emplace(key, isolate, callback,
753+
std::move(gate));
748754
NS_DCHECK(inserted && "Main thread callback ID should not be duplicated");
749755
}
750756

@@ -756,16 +762,31 @@ void CallbackHandlers::RunOnMainThreadCallback(const FunctionCallbackInfo<v8::Va
756762

757763
void CallbackHandlers::RunMainThreadEntry(uint64_t key) {
758764
Isolate *isolate;
765+
std::shared_ptr<IsolateGate> gate;
759766
{
760767
std::lock_guard<std::mutex> lock(cacheMutex_);
761768
auto it = cache_.find(key);
762769
if (it == cache_.end()) {
763770
return;
764771
}
765772
isolate = it->second.isolate_;
773+
gate = it->second.gate_;
774+
}
775+
776+
// A worker that has started shutting down may dispose its isolate at any
777+
// moment, so its callback is dropped without touching the isolate.
778+
std::unique_lock<std::mutex> gateLock;
779+
if (gate != nullptr) {
780+
gateLock = std::unique_lock<std::mutex>(gate->mutex);
781+
if (!gate->open) {
782+
return;
783+
}
766784
}
767785

768786
v8::Locker locker(isolate);
787+
if (gateLock.owns_lock()) {
788+
gateLock.unlock();
789+
}
769790
Isolate::Scope isolate_scope(isolate);
770791
HandleScope handle_scope(isolate);
771792
Local<v8::Function> cb;
@@ -788,6 +809,14 @@ void CallbackHandlers::RunMainThreadEntry(uint64_t key) {
788809

789810
if (tc.HasCaught() &&
790811
!NativeScriptException::ContainUncaughtCallbackException(isolate, tc)) {
812+
if (gate != nullptr) {
813+
// A worker's error belongs to the worker, as if the callback had
814+
// run on its own thread: its onerror, then the parent's Worker
815+
// object. Thrown from here it would become a Java exception on the
816+
// main thread.
817+
CallWorkerScopeOnErrorHandle(isolate, tc);
818+
return;
819+
}
791820
// surfaces via the event loop's guard as a pending Java exception
792821
throw NativeScriptException(tc);
793822
}

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

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,11 @@
2020
#include "NativeScriptAssert.h"
2121
#include "NativeScriptException.h"
2222
#include "Runtime.h"
23+
#include <memory>
24+
25+
namespace tns {
26+
struct IsolateGate;
27+
}
2328

2429
namespace tns {
2530
class CallbackHandlers {
@@ -218,9 +223,11 @@ namespace tns {
218223

219224

220225
struct CacheEntry {
221-
CacheEntry(v8::Isolate* isolate, v8::Local<v8::Function> callback)
226+
CacheEntry(v8::Isolate* isolate, v8::Local<v8::Function> callback,
227+
std::shared_ptr<IsolateGate> gate)
222228
: isolate_(isolate),
223-
callback_(isolate, callback) {
229+
callback_(isolate, callback),
230+
gate_(std::move(gate)) {
224231
}
225232

226233
~CacheEntry() {
@@ -229,6 +236,8 @@ namespace tns {
229236

230237
v8::Isolate* isolate_;
231238
v8::Global<v8::Function> callback_;
239+
// null for the main isolate, which is never disposed
240+
std::shared_ptr<IsolateGate> gate_;
232241
};
233242

234243
static robin_hood::unordered_map<uint64_t, CacheEntry> cache_;

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

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1338,9 +1338,7 @@ void Runtime::DestroyRuntime() {
13381338
m_dispatchNativeUncaughtErrorFunc.Reset();
13391339
// Both hold v8::Global handles to JS callbacks, so their entries must be
13401340
// dropped here rather than in ~Runtime, which runs after Isolate::Dispose --
1341-
// resetting a Global then writes into a freed handle table. Doing it here
1342-
// also closes a window in which the main thread could take a Locker on this
1343-
// isolate (RunMainThreadEntry) after it had already been disposed.
1341+
// resetting a Global then writes into a freed handle table.
13441342
CallbackHandlers::RemoveIsolateEntries(m_isolate);
13451343
FrameCallbacks::RemoveIsolateEntries(m_isolate);
13461344

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

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -700,6 +700,12 @@ void WorkerWrapper::BackgroundLooper(std::shared_ptr<WorkerWrapper> self) {
700700

701701
isTerminating_ = true;
702702

703+
// No Locker is held here, as the gate requires.
704+
{
705+
std::lock_guard<std::mutex> lock(gate_->mutex);
706+
gate_->open = false;
707+
}
708+
703709
// Terminate any workers this worker created (nested workers). Their
704710
// Worker object persistents live in this isolate, so they must be
705711
// released before the isolate is disposed below. Each child cascades to

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

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,21 @@ class Runtime;
2929
class WorkerInspectorClient;
3030
#endif
3131

32+
/*
33+
* Lets a thread other than the worker's own take the worker's Locker without
34+
* racing its disposal. A caller holds `mutex`, gives up if `open` is false,
35+
* and releases `mutex` only once it owns the Locker. The worker's shutdown
36+
* closes the gate before it takes its teardown Locker, so a closed gate means
37+
* the isolate may already be gone.
38+
*
39+
* Never take `mutex` while holding the worker's Locker: a gated caller waits
40+
* for that Locker with `mutex` held.
41+
*/
42+
struct IsolateGate {
43+
std::mutex mutex;
44+
bool open = true;
45+
};
46+
3247
/*
3348
* Owns a worker's native thread and its lifecycle, mirroring the iOS
3449
* runtime's WorkerWrapper. The thread is a std::thread that attaches to the
@@ -53,6 +68,7 @@ class WorkerWrapper : public std::enable_shared_from_this<WorkerWrapper> {
5368
bool IsTerminating() const { return isTerminating_; }
5469
bool IsClosing() const { return isClosing_; }
5570
bool IsDisposed() const { return isDisposed_; }
71+
const std::shared_ptr<IsolateGate>& Gate() const { return gate_; }
5672

5773
/*
5874
* Spawns the (detached) worker thread. The thread holds a shared_ptr to
@@ -218,6 +234,7 @@ class WorkerWrapper : public std::enable_shared_from_this<WorkerWrapper> {
218234
std::atomic_bool isClosing_;
219235
std::atomic_bool isTerminating_;
220236
std::atomic_bool isDisposed_;
237+
const std::shared_ptr<IsolateGate> gate_ = std::make_shared<IsolateGate>();
221238
// False until the entry script has finished evaluating
222239
// (EnableMessageQueue); DrainPendingTasks leaves the queue untouched while
223240
// disabled. Written and read on the worker thread only - the atomic is

0 commit comments

Comments
 (0)