diff --git a/test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp b/test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp index 5beb11a14..2ff208f61 100644 --- a/test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp +++ b/test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp @@ -1058,7 +1058,11 @@ JsV8InspectorClient* JsV8InspectorClient::GetInstance() { // handleMessageOnSocketThread also calls this from the socket thread, so a // concurrent first call is possible: construct, then publish with a CAS and // discard our copy if another thread won the race. - auto* created = new JsV8InspectorClient(Runtime::GetRuntime(0)->GetIsolate()); + Runtime* mainRuntime = Runtime::GetMainRuntime(); + if (mainRuntime == nullptr) { + throw NativeScriptException("Cannot create the inspector: the main runtime is not initialized"); + } + auto* created = new JsV8InspectorClient(mainRuntime->GetIsolate()); JsV8InspectorClient* expected = nullptr; if (!instance.compare_exchange_strong(expected, created, std::memory_order_acq_rel, std::memory_order_acquire)) { diff --git a/test-app/runtime/src/main/cpp/MetadataNode.cpp b/test-app/runtime/src/main/cpp/MetadataNode.cpp index ba45f2e13..435c8decb 100644 --- a/test-app/runtime/src/main/cpp/MetadataNode.cpp +++ b/test-app/runtime/src/main/cpp/MetadataNode.cpp @@ -2618,9 +2618,25 @@ MetadataEntry MetadataNode::GetChildMetadataForPackage(MetadataNode *node, const } namespace { + // Unmapped on destruction unless the reader keeps it, so a file that fails + // to map, or metadata that fails to parse, does not strand the files + // mapped before it. struct MappedMetadataFile { uint8_t* data; size_t length; + + MappedMetadataFile(uint8_t* data, size_t length) : data(data), length(length) {} + MappedMetadataFile(const MappedMetadataFile&) = delete; + MappedMetadataFile& operator=(const MappedMetadataFile&) = delete; + ~MappedMetadataFile() { + if (data != nullptr) { + munmap(data, length); + } + } + + void KeepMapped() { + data = nullptr; + } }; /* @@ -2702,6 +2718,8 @@ void MetadataNode::BuildMetadata(const string& filesPath) { throw NativeScriptException(ss.str()); } } + // Only opened to tell a missing folder from a missing file. + closedir(dir); auto nodes = MapMetadataFile(baseDir, "treeNodeStream.dat"); auto names = MapMetadataFile(baseDir, "treeStringsStream.dat"); @@ -2713,7 +2731,8 @@ void MetadataNode::BuildMetadata(const string& filesPath) { // The tree is built from the nodes; the names and the values stay mapped for // the life of the process. - munmap(nodes.data, nodes.length); + names.KeepMapped(); + values.KeepMapped(); } void MetadataNode::BuildMetadata(uint32_t nodesLength, uint8_t* nodeData, uint32_t nameLength, uint8_t* nameData, uint32_t valueLength, uint8_t* valueData) { diff --git a/test-app/runtime/src/main/cpp/ObjectManager.h b/test-app/runtime/src/main/cpp/ObjectManager.h index 7678a33dc..ca1bd0cd1 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -727,7 +727,7 @@ class ObjectManager { static jmethodID PROCESS_CANARY_BATCH_METHOD_ID; static jmethodID STRENGTHEN_INSTANCE_METHOD_ID; - v8::Persistent* m_poJsWrapperFunc; + v8::Persistent* m_poJsWrapperFunc = nullptr; v8::Persistent m_jsWrapperTemplate; }; diff --git a/test-app/runtime/src/main/cpp/Runtime.cpp b/test-app/runtime/src/main/cpp/Runtime.cpp index a9d74baab..55ca49ab2 100644 --- a/test-app/runtime/src/main/cpp/Runtime.cpp +++ b/test-app/runtime/src/main/cpp/Runtime.cpp @@ -287,6 +287,9 @@ Runtime::~Runtime() { s_isolate2RuntimesCache.erase(it); } } + // Same backstop for the breadcrumb slot Init took: the table is small and + // fixed, so slots lost to failed bootstraps would crowd out live runtimes. + CrashBreadcrumbs::UnregisterRuntime(m_id); delete this->m_objectManager; // idempotent backstop for the matched erase WorkerWrapper does right after @@ -864,9 +867,11 @@ void Runtime::ElectMainRuntime() { s_mainRuntimeElected = true; s_mainRuntimeFailed = false; m_isMainThread = true; - // Once per process: V8::Initialize freezes the flag list, and setting a - // flag afterwards aborts. - InitializeV8(); + // Once per process, not once per election: a main runtime that failed + // hands the election back, and V8 aborts both on a second + // InitializePlatform and on a flag set after V8::Initialize froze the list. + static std::once_flag v8Initialized; + std::call_once(v8Initialized, InitializeV8); return; } @@ -887,9 +892,13 @@ void Runtime::SignalMainRuntimeReady(bool failed) { { std::lock_guard lock(s_mainInitMutex); if (failed) { - // Hand the election back so a later bootstrap can retry. + // Hand the election back so a later bootstrap can retry. A main runtime + // that already signalled readiness and failed afterwards withdraws it + // too, so nothing waiting on the next main runtime starts against this + // one. s_mainRuntimeElected = false; s_mainRuntimeFailed = true; + s_mainThreadInitialized.store(false, std::memory_order_release); } else { s_mainThreadInitialized.store(true, std::memory_order_release); } @@ -897,6 +906,25 @@ void Runtime::SignalMainRuntimeReady(bool failed) { s_mainInitReady.notify_all(); } +void Runtime::UnwindFailedBootstrap(int runtimeId) { + Runtime* runtime = nullptr; + { + std::lock_guard lock(s_runtimeCacheMutex); + auto it = s_id2RuntimeCache.find(runtimeId); + if (it != s_id2RuntimeCache.end()) { + runtime = it->second; + } + } + if (runtime == nullptr) { + return; + } + // Only the bootstrapping thread can reach this runtime: no application JS + // has run on it, so nothing has handed it to another thread or started a + // worker from it. + runtime->UnwindFailedInit(); + delete runtime; +} + void Runtime::UnwindFailedInit() { /* * Reuses the two teardown windows rather than adding a third cleanup path. @@ -905,6 +933,17 @@ void Runtime::UnwindFailedInit() { * hold the isolate's Locker: the wait for pins below would deadlock against * a pinned thread waiting for it. */ + // Hands the election back even when the teardown below throws: an election + // left won would bring every later main bootstrap up as a non-main runtime. + struct MainElectionHandBack { + bool isMain; + ~MainElectionHandBack() { + if (isMain) { + SignalMainRuntimeReady(true /* failed */); + } + } + } handBack{m_isMainThread}; + if (m_isolate != nullptr) { NS_DCHECK(!v8::Locker::IsLocked(m_isolate)); { @@ -914,12 +953,14 @@ void Runtime::UnwindFailedInit() { } RuntimeGates::WaitUntilUnpinnedAndRetire(m_id); m_isolate->Dispose(); + // The ~Runtime backstop keys on m_isolate, which is cleared below, so the + // platform's loop entry has to go here. Left behind, it would hand the + // stopped loop to the next isolate allocated at this address. + if (m_eventLoop != nullptr) { + NativeScriptPlatform::Instance()->IsolateDisposed(m_isolate, m_eventLoop); + } m_isolate = nullptr; } - - if (m_isMainThread) { - SignalMainRuntimeReady(true /* failed */); - } } Isolate* Runtime::PrepareV8Runtime(const string& filesPath, @@ -1236,7 +1277,13 @@ Isolate* Runtime::PrepareV8Runtime(const string& filesPath, // Do not build metadata (which should be static for the process) for non-main // threads if (m_isMainThread) { - MetadataNode::BuildMetadata(filesPath); + // Once per process, like V8 itself: the tree is process-wide state that + // outlives the runtime that built it, so a main runtime elected after an + // earlier one failed past this point reads the tree already there. Only + // the elected main runtime gets here, one at a time. + static std::once_flag metadataBuilt; + std::call_once(metadataBuilt, + [&filesPath]() { MetadataNode::BuildMetadata(filesPath); }); } auto enableProfiler = !profilerOutputDir.empty(); @@ -1256,6 +1303,7 @@ Isolate* Runtime::PrepareV8Runtime(const string& filesPath, JEnv::PinThreadEnv(JEnv()); if (m_isMainThread) { + s_mainRuntime.store(this, std::memory_order_release); // Releases any runtime waiting in ElectMainRuntime: the metadata tree and // the main event loop they depend on are published by now. SignalMainRuntimeReady(false /* failed */); @@ -1332,6 +1380,9 @@ void Runtime::DestroyRuntime() { s_current.id = -1; JEnv::UnpinThreadEnv(); } + Runtime* self = this; + s_mainRuntime.compare_exchange_strong(self, nullptr, + std::memory_order_acq_rel); // The events state holds v8::Global handles (backing event target, dispatch // closures and tracked promise rejections) - reset them while the isolate // is still alive. @@ -1420,6 +1471,7 @@ bool Runtime::s_mainRuntimeFailed = false; v8::Platform* Runtime::platform = nullptr; int Runtime::m_androidVersion = Runtime::GetAndroidVersion(); std::shared_ptr Runtime::s_mainEventLoop; +std::atomic Runtime::s_mainRuntime{nullptr}; constinit thread_local Runtime::CurrentRuntime Runtime::s_current; thread_local PendingIsolateSetup Runtime::s_pendingIsolateSetup; diff --git a/test-app/runtime/src/main/cpp/Runtime.h b/test-app/runtime/src/main/cpp/Runtime.h index 32aa95b2e..47a20509e 100644 --- a/test-app/runtime/src/main/cpp/Runtime.h +++ b/test-app/runtime/src/main/cpp/Runtime.h @@ -87,6 +87,14 @@ class Runtime { */ static void SetPendingIsolateSetup(PendingIsolateSetup setup); + /* + * Tears down the native runtime of a bootstrap that failed on the + * Java side after initNativeScript returned, such as a throwing + * ts_helpers.js. No-op when no native runtime is registered under the + * id, which is the case for a bootstrap that failed inside Init. + */ + static void UnwindFailedBootstrap(int runtimeId); + static Runtime* GetRuntime(int runtimeId) { // A runtime is only destroyed on its own thread, which is busy in // this call, so the calling thread's own runtime needs neither the @@ -274,6 +282,16 @@ class Runtime { static std::shared_ptr GetMainEventLoop() { return s_mainEventLoop; } + + /* + * The main runtime, or null while there is none: before it finishes + * initializing and after it is destroyed. Its id is whatever its + * bootstrap attempt was handed, which is 0 only when the first attempt + * succeeded. + */ + static Runtime* GetMainRuntime() { + return s_mainRuntime.load(std::memory_order_acquire); + } static JavaVM* GetJVM() { return s_jvm; } @@ -439,7 +457,7 @@ class Runtime { v8::Persistent* m_gcFunc; volatile bool m_runGC; - v8::Persistent* m_context; + v8::Persistent* m_context = nullptr; // Decided by ElectMainRuntime, before anything can read it. bool m_isMainThread = false; @@ -476,10 +494,11 @@ class Runtime { static void SignalMainRuntimeReady(bool failed); /* - * Unwinds an initialization that threw after the isolate existed. The - * Java-side rollback only unwinds Java state, which would otherwise - * leave the isolate in the runtime caches and the half-built Runtime - * holding everything it had allocated. + * Unwinds an initialization that threw after the isolate existed, or + * one that finished and then failed on the Java side. The Java-side + * rollback only unwinds Java state, which would otherwise leave the + * isolate in the runtime caches and the Runtime holding everything it + * had allocated. */ void UnwindFailedInit(); jobject ConvertJsValueToJavaObject(JEnv& env, const v8::Local& value, int classReturnType); @@ -514,6 +533,7 @@ class Runtime { static bool s_mainRuntimeFailed; static std::shared_ptr s_mainEventLoop; + static std::atomic s_mainRuntime; // One struct because without ELF TLS (minSdk < 29) every thread_local costs a lookup. struct CurrentRuntime { diff --git a/test-app/runtime/src/main/cpp/WorkerWrapper.cpp b/test-app/runtime/src/main/cpp/WorkerWrapper.cpp index cba9672ea..8c621084c 100644 --- a/test-app/runtime/src/main/cpp/WorkerWrapper.cpp +++ b/test-app/runtime/src/main/cpp/WorkerWrapper.cpp @@ -707,11 +707,13 @@ void WorkerWrapper::BackgroundLooper(std::shared_ptr self) { 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. + // A bootstrap that failed in Java after Runtime.initRuntime returned (an + // exception from the logger once the runtime is up) never handed the + // runtime 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. A failure inside + // initRuntime, such as a throwing internal/ts_helpers.js, is unwound + // there and leaves no current runtime. if (runtime_ == nullptr) { runtime_ = Runtime::GetCurrentRuntime(); if (runtime_ != nullptr) { diff --git a/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp b/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp index 7a430ea9e..937820d93 100644 --- a/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp +++ b/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp @@ -124,6 +124,22 @@ extern "C" JNIEXPORT void Java_com_tns_Runtime_initNativeScript(JNIEnv* _env, jo } } +extern "C" JNIEXPORT void Java_com_tns_Runtime_unwindFailedBootstrap(JNIEnv* _env, jclass clazz, jint runtimeId) { + try { + Runtime::UnwindFailedBootstrap(runtimeId); + } catch (NativeScriptException& e) { + e.ReThrowToJava(); + } catch (std::exception e) { + stringstream ss; + ss << "Error: c++ exception: " << e.what() << endl; + NativeScriptException nsEx(ss.str()); + nsEx.ReThrowToJava(); + } catch (...) { + NativeScriptException nsEx(std::string("Error: c++ exception!")); + nsEx.ReThrowToJava(); + } +} + Runtime* TryGetRuntime(int runtimeId) { Runtime* runtime = nullptr; try { diff --git a/test-app/runtime/src/main/java/com/tns/Runtime.java b/test-app/runtime/src/main/java/com/tns/Runtime.java index dc51b898b..a0a5c8ec0 100644 --- a/test-app/runtime/src/main/java/com/tns/Runtime.java +++ b/test-app/runtime/src/main/java/com/tns/Runtime.java @@ -46,6 +46,8 @@ private native void initNativeScript(int runtimeId, String filesPath, String nat private native Object runScript(int runtimeId, String filePath) throws NativeScriptException; + private static native void unwindFailedBootstrap(int runtimeId); + private native Object callJSMethodNative(int runtimeId, Object javaObject, int javaObjectID, String methodName, int methodNameId, int retType, boolean isConstructor, int argCount, long[] argValues, Object[] argRefs, long[] primitiveResult) throws NativeScriptException; private native void createJSInstanceNative(int runtimeId, Object javaObject, int javaObjectID, String canonicalName); @@ -753,6 +755,15 @@ private static Runtime initRuntime(DynamicConfiguration dynamicConfiguration) { indexRuntime(runtime.getRuntimeId(), null); currentRuntime.remove(); GcListener.unsubscribe(runtime); + // ts_helpers.js runs after the native runtime is fully built, so a + // failure there leaves the isolate behind unless it is torn down + // here as well; after the unsubscribe, so no GC notification can + // still be running against it + try { + unwindFailedBootstrap(runtime.getRuntimeId()); + } catch (Throwable unwindError) { + t.addSuppressed(unwindError); + } throw t; }