#include "WorkerWrapper.h" #include #include #include #include #include "ArgConverter.h" #include "CallbackHandlers.h" #include "CrashBreadcrumbs.h" #include "ErrorEvents.h" #include "EventLoop.h" #include "JEnv.h" #include "JniLocalRef.h" #include "ModuleInternal.h" #include "NativeScriptAssert.h" #include "NativeScriptException.h" #include "NativeScriptPlatform.h" #include "Runtime.h" #include "WorkerEvents.h" #include #ifdef APPLICATION_IN_DEBUG #include "JsV8InspectorClient.h" #include "WorkerInspectorClient.h" #endif using namespace v8; namespace tns { namespace { /* * The `name` and `message` the parent rebuilds the worker's error from. They * stay UTF-16 on the way, so both arrive exactly as thrown, embedded NULs and * unpaired surrogates included. */ struct ThrownErrorText { std::u16string name = u"Error"; std::u16string message; }; std::u16string ToUtf16(Isolate* isolate, Local value) { std::u16string result(value->Length(), u'\0'); value->WriteV2(isolate, 0, value->Length(), reinterpret_cast(result.data())); return result; } Local FromUtf16(Isolate* isolate, const std::u16string& value) { return String::NewFromTwoByte(isolate, reinterpret_cast(value.data()), NewStringType::kNormal, static_cast(value.size())) .ToLocalChecked(); } /* * Reads the text off the value the worker threw. An object's `name` and * `message` are taken when they are strings, so an Error or a DOMException * keeps both; anything else becomes an Error whose message is the value's * string form. Either property may be a getter, and one that throws leaves the * default in place. */ ThrownErrorText DescribeThrownValue(Isolate* isolate, Local context, Local thrown) { HandleScope handleScope(isolate); TryCatch tc(isolate); ThrownErrorText text; Local detail; if (thrown->ToDetailString(context).ToLocal(&detail)) { text.message = ToUtf16(isolate, detail); } if (!thrown->IsObject() || thrown->IsFunction()) { return text; } auto object = thrown.As(); Local value; if (object->Get(context, ArgConverter::ConvertToV8String(isolate, "name")).ToLocal(&value) && value->IsString()) { text.name = ToUtf16(isolate, value.As()); } if (object->Get(context, ArgConverter::ConvertToV8String(isolate, "message")) .ToLocal(&value) && value->IsString()) { text.message = ToUtf16(isolate, value.As()); } return text; } /* * An uncaught exception from a JS callback the event loop's internal lane * drove. While a pump is on the stack, returning to Java is not the next act * and arming a pending Java exception would be illegal, so the loop raises it * from its next ordered dispatch instead. */ void ReportFromEventLoopEntry(Isolate* isolate, TryCatch& tc) { if (EventLoop::IsPumping()) { auto runtime = Runtime::TryGetRuntime(isolate); auto eventLoop = runtime == nullptr ? nullptr : runtime->GetEventLoop(); if (eventLoop != nullptr) { eventLoop->DeferJavaThrow(std::make_shared(tc)); } return; } NativeScriptException(tc).ReThrowToJava(); } /* * 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 reason, const std::shared_ptr& wrapper) { auto context = isolate->GetCurrentContext(); std::string message = "Unhandled promise rejection: "; Local 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 onError; if (context->Global() ->Get(context, ArgConverter::ConvertToV8String(isolate, "onerror")) .ToLocal(&onError) && onError->IsFunction()) { Local args[] = {ArgConverter::ConvertToV8String(isolate, message)}; Local result; TryCatch tc(isolate); bool called = onError.As() ->Call(context, Undefined(isolate), 1, args) .ToLocal(&result); if (called && !result.IsEmpty() && result->BooleanValue(isolate)) { // Truthy return means handled, which is where the web stops // propagation. return; } if (!called && tc.HasCaught() && !tc.HasTerminated()) { // A handler that threw replaces the reason it was offered: its own // error reaches the parent, and the original does not. Local thrown = tc.Exception(); std::string thrownStack; auto stack = Exception::GetStackTrace(thrown); if (!stack.IsEmpty()) { thrownStack = NativeScriptException::GetErrorStackTrace(stack); } wrapper->PassUncaughtExceptionFromWorkerToParent( ArgConverter::ToString(isolate, thrown), "", thrownStack, 0, thrown); return; } } wrapper->PassUncaughtExceptionFromWorkerToParent(message, "", stackTrace, 0, reason); } } // namespace WorkerWrapper::WorkerWrapper(Isolate* parentIsolate, int workerId, std::string workerPath, std::string callingDir, int priority, IsolateLimits limits, Local 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(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 message) { if (!isTerminating_ && !isClosing_) { queue_.Push(message); } } void WorkerWrapper::PostMessageToParent(std::shared_ptr 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 (isDisposed_) { return; } bool wasTerminating = isTerminating_.exchange(true); if (wasTerminating) { return; } { // Held across the use, not just the read: the worker thread withdraws // the isolate under the same mutex before disposing it, so a terminate // that already read it finishes with it first, and a later one finds // null. std::lock_guard lock(workerIsolateMutex_); Isolate* isolate = workerIsolate_.load(); if (isolate != nullptr) { // Legal from any thread: interrupts any JS currently running on the // worker (e.g. a busy loop, including one that follows close()). 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 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(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 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(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); // 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; } // Messages dispatch on the EventTarget backing the global scope's listener // methods rather than on globalThis, so app code replacing // globalThis.dispatchEvent cannot intercept delivery. auto& globalEventTarget = runtime_->GlobalEventTarget(); if (globalEventTarget.IsEmpty()) { return 0; } auto globalTarget = globalEventTarget.Get(isolate); auto messages = queue_.PopAll(); if (messages.empty()) { return 0; } int dispatched = 0; for (auto& message : messages) { if (isTerminating_ || isClosing_) { break; } dispatched++; TryCatch tc(isolate); WorkerEvents::EmitMessage(isolate, globalTarget, message); 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 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 deliver a worker(id=%d) message because the worker has been cleared.", workerId); return; } auto worker = Local::New(isolate, *wrapper->poWorker_); auto context = Runtime::GetRuntime(isolate)->GetContext(); Context::Scope context_scope(context); try { // A listener that throws has no JS frame below it to unwind into, so it // is reported here the way a timer callback's exception is. TryCatch tc(isolate); WorkerEvents::EmitMessage(isolate, worker, message); if (tc.HasCaught() && !NativeScriptException::ContainUncaughtCallbackException(isolate, tc)) { ReportFromEventLoopEntry(isolate, tc); } } catch (NativeScriptException& ex) { ex.ReThrowToV8(); } } void WorkerWrapper::PassUncaughtExceptionFromWorkerToParent(const std::string& message, const std::string& filename, const std::string& stackTrace, int lineno, Local thrown) { auto parentTasks = parentTasks_.lock(); if (parentTasks == nullptr) { // the parent runtime is gone (e.g. a parent worker that shut down) return; } // Read here, on the worker's isolate. A report with no thrown value, such // as the heap-limit one made from inside a GC, touches no v8 handle. std::optional thrownText; if (!thrown.IsEmpty()) { Isolate* workerIsolate = Isolate::GetCurrent(); thrownText = DescribeThrownValue(workerIsolate, workerIsolate->GetCurrentContext(), thrown); } int workerId = workerId_; std::string threadName = threadName_; Isolate* parentIsolate = parentIsolate_; parentTasks->PostInternal([workerId, message, filename, stackTrace, lineno, threadName, parentIsolate, thrownText]() { v8::Locker locker(parentIsolate); Isolate::Scope isolate_scope(parentIsolate); HandleScope handle_scope(parentIsolate); auto context = Runtime::GetRuntime(parentIsolate)->GetContext(); Context::Scope context_scope(context); // Without a thrown value, the error is an Error carrying the report's // message. Local errorName = thrownText ? FromUtf16(parentIsolate, thrownText->name) : ArgConverter::ConvertToV8String(parentIsolate, "Error"); Local errorMessage = thrownText ? FromUtf16(parentIsolate, thrownText->message) : ArgConverter::ConvertToV8String(parentIsolate, message); WorkerWrapper::FireErrorOnParentWorkerObject(workerId, message, stackTrace, filename, lineno, threadName, errorName, errorMessage); }); } void WorkerWrapper::FireErrorOnParentWorkerObject(int workerId, const std::string& message, const std::string& stackTrace, const std::string& filename, int lineno, const std::string& threadName, Local errorName, Local errorMessage) { 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 deliver a worker(id=%d) error because the worker has been cleared.", workerId); return; } auto worker = Local::New(isolate, *wrapper->poWorker_); TryCatch tc(isolate); Local error; (void)WorkerEvents::EmitError(isolate, worker, message, filename, stackTrace, lineno, errorName, errorMessage) .ToLocal(&error); if (tc.HasCaught()) { // A listener that threw replaces the error it was handed; nothing // further is reported for the original. if (!NativeScriptException::ContainUncaughtCallbackException(isolate, tc)) { ReportFromEventLoopEntry(isolate, tc); } return; } if (!error.IsEmpty() && error->IsUndefined()) { // A handler took ownership of it. return; } // HTML: an error the Worker object leaves unhandled is reported to the // parent's global scope. if (error.IsEmpty() || !ErrorEvents::DispatchError(isolate, error, message, stackTrace)) { DEBUG_WRITE_FORCE( "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 self) { JavaVM* jvm = Runtime::GetJVM(); JNIEnv* jniEnv = nullptr; JavaVMAttachArgs attachArgs; attachArgs.version = JNI_VERSION_1_6; attachArgs.name = const_cast(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 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 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& info) { auto wrapper = WorkerWrapper::GetById( info.Data().As()->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& info) { auto wrapper = WorkerWrapper::GetById( info.Data().As()->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(), wrapper); }; auto workerIdData = v8::Integer::New(isolate, workerId_); Local enableFn; Local reportFn; if (Function::New(context, onFulfilled, workerIdData) .ToLocal(&enableFn) && Function::New(context, onRejected, workerIdData) .ToLocal(&reportFn)) { pendingEntry->Then(context, enableFn, reportFn) .FromMaybe(Local()); } 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; // A bootstrap that failed in Java after the native runtime was built (an // exception from internal/ts_helpers.js, or from the logger once the // runtime is up) never handed it back: initWorkerRuntime threw before // returning its id. It is still this thread's current runtime, so it is // torn down below like any other, and detached from Java by its own id. if (runtime_ == nullptr) { runtime_ = Runtime::GetCurrentRuntime(); if (runtime_ != nullptr) { runtimeId = runtime_->GetId(); } } // 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. { // Waits out a Terminate() on another thread that is still using it. std::lock_guard lock(workerIsolateMutex_); 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(); } 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 lock(looperMutex_); if (javaLooperRef_ != nullptr) { jniEnv->DeleteGlobalRef(javaLooperRef_); javaLooperRef_ = nullptr; } } isDisposed_ = true; // Notify the parent thread so the end reaches the Worker object and its // persistent handle and registry entry are released (no-op if the parent's // own shutdown already cleared them). if (auto parentTasks = parentTasks_.lock()) { int workerId = workerId_; parentTasks->PostInternal([workerId]() { WorkerWrapper::NotifyThreadEndedOnParent(workerId); }); } // ART aborts if a native thread exits while still attached. This must be // the very last JNI-touching action on this thread. JEnv::UnpinThreadEnv(); jvm->DetachCurrentThread(); } int WorkerWrapper::NextWorkerId() { return nextWorkerId_.fetch_add(1, std::memory_order_relaxed) + 1; } std::shared_ptr WorkerWrapper::GetById(int workerId) { std::lock_guard lock(registryMutex_); auto it = registry_.find(workerId); return it != registry_.end() ? it->second : nullptr; } void WorkerWrapper::Insert(int workerId, std::shared_ptr wrapper) { std::lock_guard lock(registryMutex_); registry_.emplace(workerId, std::move(wrapper)); } void WorkerWrapper::ClearWorkerOnParent(int workerId) { std::shared_ptr wrapper; { std::lock_guard 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::NotifyThreadEndedOnParent(int workerId) { auto wrapper = WorkerWrapper::GetById(workerId); if (wrapper == nullptr) { 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()) { auto worker = Local::New(isolate, *wrapper->poWorker_); auto context = Runtime::GetRuntime(isolate)->GetContext(); Context::Scope context_scope(context); try { // A listener that throws has no JS frame below it to unwind // into, so it is reported here the way a timer callback's // exception is. TryCatch tc(isolate); WorkerEvents::EmitEnded(isolate, worker); if (tc.HasCaught() && !NativeScriptException::ContainUncaughtCallbackException(isolate, tc)) { ReportFromEventLoopEntry(isolate, tc); } } catch (NativeScriptException& ex) { ex.ReThrowToV8(); } } } ClearWorkerOnParent(workerId); } void WorkerWrapper::TerminateChildren(Isolate* parentIsolate) { std::vector> children; { std::lock_guard 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( 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 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 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>& args) { std::lock_guard lock(inspectorMutex_); if (inspector_ != nullptr) { inspector_->consoleLog(method, args); } } #endif std::mutex WorkerWrapper::registryMutex_; std::map> 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