Repository navigation
Expand file tree
/
Copy pathWorkerWrapper.cpp
More file actions
868 lines (748 loc) · 34.2 KB
/
Copy pathWorkerWrapper.cpp
File metadata and controls
868 lines (748 loc) · 34.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
#include "WorkerWrapper.h"
#include <android/looper.h>
#include <pthread.h>
#include <thread>
#include "ArgConverter.h"
#include "CallbackHandlers.h"
#include "CrashBreadcrumbs.h"
#include "JEnv.h"
#include "JniLocalRef.h"
#include "ModuleInternal.h"
#include "NativeScriptAssert.h"
#include "NativeScriptException.h"
#include "NativeScriptPlatform.h"
#include "Runtime.h"
#include <unistd.h>
#ifdef APPLICATION_IN_DEBUG
#include "JsV8InspectorClient.h"
#include "WorkerInspectorClient.h"
#endif
using namespace v8;
namespace tns {
namespace {
/*
* Reports a worker entry that failed to evaluate, with the web's order: the
* worker scope's own `onerror` gets first refusal (a truthy return consumes the
* failure) and only an unconsumed one reaches the parent's Worker object.
* Mirrors the worker branch of the unhandled-rejection path in
* NativeScriptException.cpp, which this rejection no longer travels: attaching
* a rejection handler to the entry's evaluation promise marks it handled.
*/
void ReportEntryRejection(Isolate* isolate, Local<Value> reason,
const std::shared_ptr<WorkerWrapper>& wrapper) {
auto context = isolate->GetCurrentContext();
std::string message = "Unhandled promise rejection: ";
Local<String> detail;
if (!reason.IsEmpty() && reason->ToDetailString(context).ToLocal(&detail)) {
message += ArgConverter::ConvertToString(detail);
}
std::string stackTrace;
if (!reason.IsEmpty()) {
auto stack = Exception::GetStackTrace(reason);
if (!stack.IsEmpty()) {
stackTrace = NativeScriptException::GetErrorStackTrace(stack);
}
}
Local<Value> onError;
if (context->Global()
->Get(context, ArgConverter::ConvertToV8String(isolate, "onerror"))
.ToLocal(&onError) &&
onError->IsFunction()) {
Local<Value> args[] = {ArgConverter::ConvertToV8String(isolate, message)};
Local<Value> result;
// A handler that throws has not consumed anything - the failure falls
// through to the parent, as if no handler had been installed.
TryCatch tc(isolate);
if (onError.As<Function>()
->Call(context, Undefined(isolate), 1, args)
.ToLocal(&result) &&
!result.IsEmpty() && result->BooleanValue(isolate)) {
return;
}
}
wrapper->PassUncaughtExceptionFromWorkerToParent(message, "", stackTrace, 0);
}
} // namespace
WorkerWrapper::WorkerWrapper(Isolate* parentIsolate, int workerId, std::string workerPath,
std::string callingDir, int priority, IsolateLimits limits,
Local<Object> workerObject)
: parentIsolate_(parentIsolate),
// runs on the parent's thread, where the parent runtime is alive
parentTasks_(Runtime::GetRuntime(parentIsolate)->GetEventLoop()),
workerIsolate_(nullptr),
runtime_(nullptr),
workerId_(workerId),
workerPath_(std::move(workerPath)),
callingDir_(std::move(callingDir)),
// workerPath_ (not workerPath) - the parameter was just moved from
threadName_("W" + std::to_string(workerId) + ": " + workerPath_),
priority_(priority),
limits_(std::move(limits)),
// Runs on the parent's thread, so this is the parent's live vocabulary.
inheritedVocabulary_(CaptureLoaderVocabulary(parentIsolate)),
poWorker_(new Persistent<Object>(parentIsolate, workerObject)),
isClosing_(false),
isTerminating_(false),
isDisposed_(false),
messagesEnabled_(false),
heapLimitExceeded_(false),
javaLooperRef_(nullptr) {
heapLimitMessage_ = "Worker JS heap out of memory";
if (limits_.maxOldGenerationSizeBytes.has_value()) {
heapLimitMessage_ += " (maxOldGenerationSizeMb: " +
std::to_string(*limits_.maxOldGenerationSizeBytes / (1024 * 1024)) +
")";
}
}
void WorkerWrapper::Start() {
auto self = shared_from_this();
std::thread thread([self]() {
self->BackgroundLooper(self);
});
thread.detach();
}
void WorkerWrapper::PostMessage(std::shared_ptr<worker::Message> message) {
if (!isTerminating_ && !isClosing_) {
queue_.Push(message);
}
}
void WorkerWrapper::PostMessageToParent(std::shared_ptr<worker::Message> message) {
if (isTerminating_) {
return;
}
auto parentTasks = parentTasks_.lock();
if (parentTasks == nullptr) {
// the parent runtime is gone (e.g. a parent worker that shut down)
return;
}
int workerId = workerId_;
parentTasks->PostInternal([workerId, message]() {
WorkerWrapper::FireMessageOnParentWorkerObject(workerId, message);
});
}
void WorkerWrapper::Terminate() {
if (isClosing_ || isDisposed_) {
// The worker is already shutting down on its own; nothing to do.
return;
}
bool wasTerminating = isTerminating_.exchange(true);
if (wasTerminating) {
return;
}
Isolate* isolate = workerIsolate_.load();
if (isolate != nullptr) {
// The only v8 call that is legal from another thread - interrupts any
// JS currently running on the worker (e.g. a busy loop).
isolate->TerminateExecution();
// A pump parked with nothing queued runs no JS, so the interrupt
// above never materializes for it - the loop's own flag ends it.
auto loop = NativeScriptPlatform::Instance()->LookupEventLoop(isolate);
if (loop != nullptr) {
loop->NoteTerminationRequested();
}
}
#ifdef APPLICATION_IN_DEBUG
{
// A worker paused at a breakpoint sits in the inspector's nested pause
// loop, not in Looper.loop() - kick it loose so TerminateExecution and
// the looper quit below can take effect.
std::lock_guard<std::mutex> lock(inspectorMutex_);
if (inspector_ != nullptr) {
inspector_->NotifyTerminating();
}
}
#endif
QuitLooper();
}
size_t WorkerWrapper::OnNearHeapLimit(void* data, size_t currentHeapLimit,
size_t initialHeapLimit) {
auto* worker = static_cast<WorkerWrapper*>(data);
// Node's allowance: raising the limit lets the in-progress GC finish
// instead of aborting the process, and the isolate is being torn down
// anyway. The same raised limit has to come back on every later
// invocation, because returning a lower one is fatal to v8.
constexpr size_t kHeapLimitAllowance = 16 * 1024 * 1024;
size_t raisedLimit = currentHeapLimit + kHeapLimitAllowance;
if (worker->heapLimitExceeded_.exchange(true, std::memory_order_acq_rel)) {
return raisedLimit;
}
// Marshals strings onto the parent's loop and touches no v8 handle, which
// is the only kind of reporting allowed from inside a GC.
worker->PassUncaughtExceptionFromWorkerToParent(worker->heapLimitMessage_, worker->workerPath_,
"", 0);
// Terminate() below only reaches workerIsolate_, which the bootstrap
// publishes once the runtime is up - and a worker can exhaust its heap
// before that. The isolate being collected is the one to interrupt.
Isolate* isolate = Isolate::GetCurrent();
if (isolate != nullptr) {
isolate->TerminateExecution();
}
worker->Terminate();
return raisedLimit;
}
void WorkerWrapper::Close() {
bool wasClosing = isClosing_.exchange(true);
if (wasClosing) {
return;
}
// Once the current callback unwinds, Looper.loop() returns and the
// thread proceeds to cleanup. Pending messages are dropped, matching the
// previous front-of-queue TerminateAndCloseThread behavior.
QuitLooper();
}
void WorkerWrapper::QuitLooper() {
std::lock_guard<std::mutex> lock(looperMutex_);
if (javaLooperRef_ != nullptr) {
JEnv env;
env.CallVoidMethod(javaLooperRef_, LOOPER_QUIT_METHOD_ID);
}
}
int WorkerWrapper::DrainCallback(int fd, int events, void* data) {
uint64_t value;
read(fd, &value, sizeof(value));
auto wrapper = static_cast<WorkerWrapper*>(data);
wrapper->DrainPendingTasks();
return 1;
}
int WorkerWrapper::DrainPendingTasks() {
Isolate* isolate = workerIsolate_.load();
if (isolate == nullptr || isTerminating_) {
return 0;
}
v8::Locker locker(isolate);
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
auto context = runtime_->GetContext();
Context::Scope context_scope(context);
auto globalObject = context->Global();
// WHATWG parity: the implicit port's message queue starts disabled and is
// enabled once the entry script has finished evaluating (including after a
// pending top-level await settles). Until then messages stay buffered here;
// afterwards every message dispatches whether or not a handler exists — a
// handler installed later misses earlier messages, exactly as on the web.
if (!messagesEnabled_.load(std::memory_order_acquire)) {
return 0;
}
auto messages = queue_.PopAll();
if (messages.empty()) {
return 0;
}
int dispatched = 0;
for (auto& message : messages) {
if (isTerminating_ || isClosing_) {
break;
}
dispatched++;
TryCatch tc(isolate);
Local<Value> callback;
if (!globalObject->Get(context, ArgConverter::ConvertToV8String(isolate, "onmessage"))
.ToLocal(&callback) ||
!callback->IsFunction()) {
DEBUG_WRITE(
"WORKER: couldn't fire a worker's `onmessage` callback because it isn't implemented!");
continue;
}
Local<Value> data;
if (message->Deserialize(isolate, context).ToLocal(&data)) {
auto event = Object::New(isolate);
event->DefineOwnProperty(context, ArgConverter::ConvertToV8String(isolate, "data"),
data, PropertyAttribute::ReadOnly);
Local<Value> args[] = {event};
callback.As<Function>()->Call(context, Undefined(isolate), 1, args);
}
if (tc.HasCaught() && !isTerminating_) {
CallbackHandlers::CallWorkerScopeOnErrorHandle(isolate, tc);
}
}
return dispatched;
}
void WorkerWrapper::EnableMessageQueue() {
messagesEnabled_.store(true, std::memory_order_release);
queue_.Signal();
}
void WorkerWrapper::FireMessageOnParentWorkerObject(int workerId,
std::shared_ptr<worker::Message> message) {
auto wrapper = WorkerWrapper::GetById(workerId);
if (wrapper == nullptr) {
DEBUG_WRITE("MAIN: no worker instance was found with workerId=%d.", workerId);
return;
}
Isolate* isolate = wrapper->parentIsolate_;
v8::Locker locker(isolate);
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
if (wrapper->poWorker_ == nullptr || wrapper->poWorker_->IsEmpty()) {
DEBUG_WRITE(
"MAIN: couldn't fire a worker(id=%d) object's `onmessage` callback because the worker has been cleared.",
workerId);
return;
}
auto worker = Local<Object>::New(isolate, *wrapper->poWorker_);
auto context = Runtime::GetRuntime(isolate)->GetContext();
Context::Scope context_scope(context);
try {
Local<Value> callback;
if (!worker->Get(context, ArgConverter::ConvertToV8String(isolate, "onmessage"))
.ToLocal(&callback) ||
!callback->IsFunction()) {
DEBUG_WRITE(
"MAIN: couldn't fire a worker(id=%d) object's `onmessage` callback because it isn't implemented.",
workerId);
return;
}
Local<Value> data;
if (message->Deserialize(isolate, context).ToLocal(&data)) {
auto event = Object::New(isolate);
event->DefineOwnProperty(context, ArgConverter::ConvertToV8String(isolate, "data"),
data, PropertyAttribute::ReadOnly);
Local<Value> args[] = {event};
callback.As<Function>()->Call(context, Undefined(isolate), 1, args);
}
} catch (NativeScriptException& ex) {
ex.ReThrowToV8();
}
}
void WorkerWrapper::PassUncaughtExceptionFromWorkerToParent(const std::string& message,
const std::string& filename,
const std::string& stackTrace,
int lineno) {
auto parentTasks = parentTasks_.lock();
if (parentTasks == nullptr) {
// the parent runtime is gone (e.g. a parent worker that shut down)
return;
}
int workerId = workerId_;
std::string threadName = threadName_;
Isolate* parentIsolate = parentIsolate_;
parentTasks->PostInternal([workerId, message, filename, stackTrace, lineno, threadName,
parentIsolate]() {
v8::Locker locker(parentIsolate);
Isolate::Scope isolate_scope(parentIsolate);
HandleScope handle_scope(parentIsolate);
auto context = Runtime::GetRuntime(parentIsolate)->GetContext();
Context::Scope context_scope(context);
WorkerWrapper::FireErrorOnParentWorkerObject(workerId, message, stackTrace, filename,
lineno, threadName);
});
}
void WorkerWrapper::FireErrorOnParentWorkerObject(int workerId, const std::string& message,
const std::string& stackTrace,
const std::string& filename, int lineno,
const std::string& threadName) {
auto wrapper = WorkerWrapper::GetById(workerId);
if (wrapper == nullptr) {
DEBUG_WRITE("MAIN: no worker instance was found with workerId=%d.", workerId);
return;
}
Isolate* isolate = wrapper->parentIsolate_;
try {
if (wrapper->poWorker_ == nullptr || wrapper->poWorker_->IsEmpty()) {
DEBUG_WRITE(
"MAIN: couldn't fire a worker(id=%d) object's `onerror` callback because the worker has been cleared.",
workerId);
return;
}
auto worker = Local<Object>::New(isolate, *wrapper->poWorker_);
auto context = Runtime::GetRuntime(isolate)->GetContext();
Local<Value> callback;
bool hasOnError =
worker->Get(context, ArgConverter::ConvertToV8String(isolate, "onerror"))
.ToLocal(&callback) &&
callback->IsFunction();
if (hasOnError) {
auto errEvent = Object::New(isolate);
errEvent->Set(context, ArgConverter::ConvertToV8String(isolate, "message"),
ArgConverter::ConvertToV8String(isolate, message));
errEvent->Set(context, ArgConverter::ConvertToV8String(isolate, "stackTrace"),
ArgConverter::ConvertToV8String(isolate, stackTrace));
errEvent->Set(context, ArgConverter::ConvertToV8String(isolate, "filename"),
ArgConverter::ConvertToV8String(isolate, filename));
errEvent->Set(context, ArgConverter::ConvertToV8String(isolate, "lineno"),
Number::New(isolate, lineno));
Local<Value> args[] = {errEvent};
// If the handler returns a truthy value the exception is handled
// and must not be raised to application level
Local<Value> result;
callback.As<Function>()->Call(context, Undefined(isolate), 1, args).ToLocal(&result);
if (!result.IsEmpty() && result->BooleanValue(isolate)) {
return;
}
}
DEBUG_WRITE(
"Unhandled exception in '%s' thread. file: %s, line %d, message: %s\nStackTrace: %s",
threadName.c_str(), filename.c_str(), lineno, message.c_str(),
stackTrace.c_str());
} catch (NativeScriptException& ex) {
ex.ReThrowToV8();
}
}
void WorkerWrapper::BackgroundLooper(std::shared_ptr<WorkerWrapper> self) {
JavaVM* jvm = Runtime::GetJVM();
JNIEnv* jniEnv = nullptr;
JavaVMAttachArgs attachArgs;
attachArgs.version = JNI_VERSION_1_6;
attachArgs.name = const_cast<char*>(threadName_.c_str());
attachArgs.group = nullptr;
jvm->AttachCurrentThread(&jniEnv, &attachArgs);
// pthread names are limited to 15 chars
pthread_setname_np(pthread_self(), threadName_.substr(0, 15).c_str());
int runtimeId = -1;
try {
JEnv env;
// Performs the cgroup/scheduling-policy move in addition to the nice
// value, exactly like the previous Java-side
// Process.setThreadPriority(THREAD_PRIORITY_BACKGROUND) call.
env.CallStaticVoidMethod(PROCESS_CLASS, SET_THREAD_PRIORITY_METHOD_ID, priority_);
if (!isTerminating_ && !isClosing_) {
// Prepares the Java Looper for this thread and creates the
// per-worker com.tns.Runtime (which creates the worker isolate on
// this thread via initNativeScript -> PrepareV8Runtime).
JniLocalRef callingDir(env.NewStringUTF(callingDir_.c_str()));
// The isolate is created on this thread inside the call below,
// which has no parameter to carry any of this; the thread-local
// slot is the channel. The near-heap-limit callback is armed for
// every worker, capped or not - without it an isolate that
// exhausts its heap aborts the whole process instead of surfacing
// on the parent's Worker object.
Runtime::SetPendingIsolateSetup({limits_, WorkerWrapper::OnNearHeapLimit, this});
runtimeId = env.CallStaticIntMethod(RUNTIME_CLASS, INIT_WORKER_RUNTIME_METHOD_ID,
workerId_, (jstring) callingDir);
runtime_ = Runtime::GetRuntime(runtimeId);
CrashBreadcrumbs::SetWorkerScript(runtimeId, workerPath_.c_str());
{
std::lock_guard<std::mutex> lock(looperMutex_);
JniLocalRef looper(env.CallStaticObjectMethod(LOOPER_CLASS, MY_LOOPER_METHOD_ID));
javaLooperRef_ = env.NewGlobalRef(looper);
}
// Looper.prepare() ran above, so ALooper_forThread() returns the
// native looper backing the Java one - fds added here are pumped
// by Looper.loop().
queue_.Initialize(ALooper_forThread(), WorkerWrapper::DrainCallback, this);
// The inbox rides its own fd, which a pump never polls; the hook
// lets a looper-equivalent pump drain it (the loop's Shutdown, on
// this thread, unregisters it before `this` can die).
auto pumpLoop = runtime_->GetEventLoop();
if (pumpLoop != nullptr) {
pumpLoop->SetPumpDrainHook([this]() { return DrainPendingTasks(); });
}
Isolate* isolate = runtime_->GetIsolate();
{
v8::Locker locker(isolate);
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
isolate->SetData((uint32_t) Runtime::IsolateData::WORKER_WRAPPER, this);
workerIsolate_.store(isolate);
auto context = runtime_->GetContext();
Context::Scope context_scope(context);
// Before any module load runs in this isolate.
InstallLoaderVocabulary(isolate, inheritedVocabulary_);
#ifdef APPLICATION_IN_DEBUG
// Expose this worker to an attached Chrome DevTools frontend
// as a child target, mirroring the iOS runtime. Created before
// the script runs so the worker's scripts are visible to the
// debugger from the start.
CreateInspector(isolate);
#endif
if (!isTerminating_) {
runtime_->RunWorker(workerPath_);
// The near-heap-limit callback has already reported to
// the parent and asked v8 to terminate this isolate;
// everything below would run JS on it.
if (!HeapLimitExceeded()) {
// WHATWG parity: enable the implicit port's message queue
// once the entry has finished evaluating. RunWorker returns
// settled for classic scripts and pumped HTTP entries; a
// local top-level-await entry that outlived its settle
// window enables when its evaluation promise settles —
// rejected included, since a broken worker still drains its
// inbox into a listenerless global, as on the web.
Local<Promise> pendingEntry;
if (!ModuleInternal::PendingEntryEvaluation(isolate, workerPath_)
.ToLocal(&pendingEntry)) {
EnableMessageQueue();
} else {
// Neither handler may capture anything: they resolve the
// wrapper by id because the worker may be gone by the
// time the entry settles. Both run on this thread, in
// this isolate.
auto onFulfilled = [](const v8::FunctionCallbackInfo<Value>& info) {
auto wrapper = WorkerWrapper::GetById(
info.Data().As<v8::Int32>()->Value());
if (wrapper != nullptr) {
wrapper->EnableMessageQueue();
}
};
// A rejection needs its own handler: sharing the fulfill
// one would mark the entry's evaluation promise handled
// and drop the failure on the floor.
auto onRejected = [](const v8::FunctionCallbackInfo<Value>& info) {
auto wrapper = WorkerWrapper::GetById(
info.Data().As<v8::Int32>()->Value());
if (wrapper == nullptr) {
return;
}
wrapper->EnableMessageQueue();
if (wrapper->IsTerminating() || wrapper->IsDisposed()) {
return;
}
auto isolate = info.GetIsolate();
ReportEntryRejection(isolate,
info.Length() > 0
? info[0]
: Undefined(isolate).As<Value>(),
wrapper);
};
auto workerIdData = v8::Integer::New(isolate, workerId_);
Local<Function> enableFn;
Local<Function> reportFn;
if (Function::New(context, onFulfilled, workerIdData)
.ToLocal(&enableFn) &&
Function::New(context, onRejected, workerIdData)
.ToLocal(&reportFn)) {
pendingEntry->Then(context, enableFn, reportFn)
.FromMaybe(Local<Promise>());
} else {
EnableMessageQueue();
}
}
}
}
}
// Deliver messages that were posted before the worker was ready
// (replaces the old Java Handshake + pendingWorkerMessages).
DrainPendingTasks();
if (!isTerminating_ && !isClosing_) {
// Blocks, pumping Java Handler messages (cross-thread Java->JS
// calls), timers and the worker inbox until quit() is called.
env.CallStaticVoidMethod(RUNTIME_CLASS, RUN_WORKER_LOOP_METHOD_ID);
}
}
} catch (NativeScriptException& ex) {
if (jniEnv->ExceptionCheck()) {
jniEnv->ExceptionClear();
}
if (!isTerminating_) {
PassUncaughtExceptionFromWorkerToParent(ex.GetErrorMessage(), workerPath_, "", 0);
}
} catch (std::exception& ex) {
DEBUG_WRITE_FORCE("Worker(id=%d) error: c++ exception: %s", workerId_, ex.what());
} catch (...) {
DEBUG_WRITE_FORCE("Worker(id=%d) error: unknown c++ exception!", workerId_);
}
// ----- Shutdown (close, terminate or bootstrap failure) -----
isTerminating_ = true;
// Terminate any workers this worker created (nested workers). Their
// Worker object persistents live in this isolate, so they must be
// released before the isolate is disposed below. Each child cascades to
// its own children during its shutdown.
{
Isolate* isolate = workerIsolate_.load();
if (isolate != nullptr) {
TerminateChildren(isolate);
}
}
#ifdef APPLICATION_IN_DEBUG
// The inspector must be gone before the Runtime (and with it the isolate)
// is deleted below; unregistering also tells DevTools the target is gone.
DestroyInspector();
#endif
// On this thread: safe to unregister the inbox fd from the looper.
queue_.Terminate();
if (runtime_ != nullptr) {
try {
// Java-side detach (GcListener.unsubscribe + runtimeCache.remove)
// must happen before the isolate is disposed, preserving the old
// WorkerThreadHandler -> TerminateWorkerCallback ordering.
JEnv env;
env.CallStaticVoidMethod(RUNTIME_CLASS, DETACH_WORKER_RUNTIME_METHOD_ID, runtimeId);
} catch (NativeScriptException& ex) {
if (jniEnv->ExceptionCheck()) {
jniEnv->ExceptionClear();
}
DEBUG_WRITE_FORCE("Worker(id=%d) error while detaching Java runtime: %s", workerId_,
ex.GetErrorMessage().c_str());
}
// Take the isolate from the runtime, not from workerIsolate_: if the
// bootstrap failed between initWorkerRuntime and the workerIsolate_
// publish (e.g. a JNI error while resolving the looper), the atomic is
// still null while the isolate very much needs disposing.
workerIsolate_.store(nullptr);
Isolate* isolate = runtime_->GetIsolate();
{
v8::Locker locker(isolate);
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
// v8 keeps the registration until the isolate is disposed, and a
// final GC during disposal would find `this` mid-teardown.
isolate->RemoveNearHeapLimitCallback(WorkerWrapper::OnNearHeapLimit, 0);
runtime_->DestroyRuntime();
}
CallbackHandlers::WaitForMainThreadCallbacks(isolate);
isolate->Dispose();
// Dispose freed the isolate's memory, so its address can be reused by
// a concurrent Isolate::New - drop the platform's loop entry now, not
// in ~Runtime (which still runs JNI calls first). The matched erase
// means the late ~Runtime backstop can't evict a new tenant.
NativeScriptPlatform::Instance()->IsolateDisposed(isolate,
runtime_->GetEventLoop());
// The Runtime destructor still makes JNI calls - it must run before
// DetachCurrentThread below.
delete runtime_;
runtime_ = nullptr;
}
{
std::lock_guard<std::mutex> lock(looperMutex_);
if (javaLooperRef_ != nullptr) {
jniEnv->DeleteGlobalRef(javaLooperRef_);
javaLooperRef_ = nullptr;
}
}
isDisposed_ = true;
// Notify the parent thread so the Worker object's persistent handle and
// the registry entry are released (no-op if terminate() or the parent's
// own shutdown already cleared them).
if (auto parentTasks = parentTasks_.lock()) {
int workerId = workerId_;
parentTasks->PostInternal([workerId]() {
WorkerWrapper::ClearWorkerOnParent(workerId);
});
}
// ART aborts if a native thread exits while still attached. This must be
// the very last JNI-touching action on this thread.
jvm->DetachCurrentThread();
}
int WorkerWrapper::NextWorkerId() {
return nextWorkerId_.fetch_add(1, std::memory_order_relaxed) + 1;
}
std::shared_ptr<WorkerWrapper> WorkerWrapper::GetById(int workerId) {
std::lock_guard<std::mutex> lock(registryMutex_);
auto it = registry_.find(workerId);
return it != registry_.end() ? it->second : nullptr;
}
void WorkerWrapper::Insert(int workerId, std::shared_ptr<WorkerWrapper> wrapper) {
std::lock_guard<std::mutex> lock(registryMutex_);
registry_.emplace(workerId, std::move(wrapper));
}
void WorkerWrapper::ClearWorkerOnParent(int workerId) {
std::shared_ptr<WorkerWrapper> wrapper;
{
std::lock_guard<std::mutex> lock(registryMutex_);
auto it = registry_.find(workerId);
if (it == registry_.end()) {
return;
}
wrapper = it->second;
registry_.erase(it);
}
if (wrapper->poWorker_ != nullptr) {
v8::Locker locker(wrapper->parentIsolate_);
wrapper->poWorker_->Reset();
delete wrapper->poWorker_;
wrapper->poWorker_ = nullptr;
}
}
void WorkerWrapper::TerminateChildren(Isolate* parentIsolate) {
std::vector<std::shared_ptr<WorkerWrapper>> children;
{
std::lock_guard<std::mutex> lock(registryMutex_);
for (auto& entry : registry_) {
if (entry.second->parentIsolate_ == parentIsolate) {
children.push_back(entry.second);
}
}
}
for (auto& child : children) {
DEBUG_WRITE(
"Terminating nested worker(id=%d) because its parent is shutting down",
child->workerId_);
child->Terminate();
ClearWorkerOnParent(child->workerId_);
}
}
WorkerWrapper* WorkerWrapper::FromIsolate(Isolate* isolate) {
return static_cast<WorkerWrapper*>(
isolate->GetData((uint32_t) Runtime::IsolateData::WORKER_WRAPPER));
}
void WorkerWrapper::EnsureJniCached() {
if (RUNTIME_CLASS != nullptr) {
return;
}
JEnv env;
RUNTIME_CLASS = env.FindClass("com/tns/Runtime");
NS_CHECK(RUNTIME_CLASS != nullptr);
INIT_WORKER_RUNTIME_METHOD_ID =
env.GetStaticMethodID(RUNTIME_CLASS, "initWorkerRuntime", "(ILjava/lang/String;)I");
RUN_WORKER_LOOP_METHOD_ID = env.GetStaticMethodID(RUNTIME_CLASS, "runWorkerLoop", "()V");
DETACH_WORKER_RUNTIME_METHOD_ID =
env.GetStaticMethodID(RUNTIME_CLASS, "detachWorkerRuntime", "(I)V");
LOOPER_CLASS = env.FindClass("android/os/Looper");
NS_CHECK(LOOPER_CLASS != nullptr);
MY_LOOPER_METHOD_ID =
env.GetStaticMethodID(LOOPER_CLASS, "myLooper", "()Landroid/os/Looper;");
LOOPER_QUIT_METHOD_ID = env.GetMethodID(LOOPER_CLASS, "quit", "()V");
PROCESS_CLASS = env.FindClass("android/os/Process");
NS_CHECK(PROCESS_CLASS != nullptr);
SET_THREAD_PRIORITY_METHOD_ID =
env.GetStaticMethodID(PROCESS_CLASS, "setThreadPriority", "(I)V");
}
#ifdef APPLICATION_IN_DEBUG
void WorkerWrapper::CreateInspector(Isolate* isolate) {
// Only when the root inspector client exists (debuggable app, created on
// the main thread during runtime init) - never construct it from here.
JsV8InspectorClient* root = JsV8InspectorClient::GetInstanceIfCreated();
if (root == nullptr) {
return;
}
// Same url the module loader reports in Debugger.scriptParsed: an http(s)
// entry already IS that url, only a filesystem path needs the scheme.
std::string url = ModuleInternal::IsHttpModulePath(workerPath_)
? workerPath_
: "file://" + workerPath_;
auto* client = new WorkerInspectorClient(workerId_, isolate, ALooper_forThread(), url);
{
std::lock_guard<std::mutex> lock(inspectorMutex_);
inspector_ = client;
}
// Register only once fully constructed: registration makes the client
// reachable from the socket thread.
root->RegisterWorkerTarget(workerId_, client);
}
void WorkerWrapper::DestroyInspector() {
WorkerInspectorClient* client = nullptr;
{
std::lock_guard<std::mutex> lock(inspectorMutex_);
client = inspector_;
inspector_ = nullptr;
}
if (client == nullptr) {
return;
}
// Unregister first: after this returns no other thread can reach the
// client through the root's registry.
JsV8InspectorClient* root = JsV8InspectorClient::GetInstanceIfCreated();
if (root != nullptr) {
root->UnregisterWorkerTarget(workerId_);
}
delete client;
}
void WorkerWrapper::ConsoleLog(v8_inspector::ConsoleAPIType method,
const std::vector<Local<Value>>& args) {
std::lock_guard<std::mutex> lock(inspectorMutex_);
if (inspector_ != nullptr) {
inspector_->consoleLog(method, args);
}
}
#endif
std::mutex WorkerWrapper::registryMutex_;
std::map<int, std::shared_ptr<WorkerWrapper>> WorkerWrapper::registry_;
std::atomic_int WorkerWrapper::nextWorkerId_(0);
jclass WorkerWrapper::RUNTIME_CLASS = nullptr;
jclass WorkerWrapper::LOOPER_CLASS = nullptr;
jclass WorkerWrapper::PROCESS_CLASS = nullptr;
jmethodID WorkerWrapper::INIT_WORKER_RUNTIME_METHOD_ID = nullptr;
jmethodID WorkerWrapper::RUN_WORKER_LOOP_METHOD_ID = nullptr;
jmethodID WorkerWrapper::DETACH_WORKER_RUNTIME_METHOD_ID = nullptr;
jmethodID WorkerWrapper::MY_LOOPER_METHOD_ID = nullptr;
jmethodID WorkerWrapper::LOOPER_QUIT_METHOD_ID = nullptr;
jmethodID WorkerWrapper::SET_THREAD_PRIORITY_METHOD_ID = nullptr;
} // namespace tns