From f83066ddd257ece57c5ba1f188d20548ced5a6e2 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 16:42:48 -0300 Subject: [PATCH 1/9] fix(runtime): drop Java->JS calls into a worker that is shutting down Under multithreaded JS a Java thread calls into a worker's object on its own thread, under the worker isolate's Locker. It looked the runtime up, then waited for that Locker while the worker tore its runtime down under it: once the Locker came free the call read a null context, and the worker could go on to dispose the isolate and delete the runtime while the call was still using them. Each runtime now has a gate keyed by its id (RuntimeGates, the iOS runtime's IsolateGates). A Java->JS entry into another thread's runtime pins it before waiting for its Locker and re-checks that the runtime is still registered once the Locker is granted; the teardown unregisters the runtime first, closes the gate last under the Locker, and disposes the isolate only once no pin is held. A call that finds the runtime gone or closing is dropped. A thread entering its own runtime takes no pin. --- .../app/tests/testRuntimeBoundDispatch.js | 25 ++++++ .../com/tns/tests/RuntimeBoundHolder.java | 44 +++++++++ test-app/runtime/CMakeLists.txt | 1 + test-app/runtime/src/main/cpp/Runtime.cpp | 19 ++++ test-app/runtime/src/main/cpp/Runtime.h | 3 + .../runtime/src/main/cpp/RuntimeGates.cpp | 90 +++++++++++++++++++ test-app/runtime/src/main/cpp/RuntimeGates.h | 48 ++++++++++ .../runtime/src/main/cpp/WorkerWrapper.cpp | 4 + .../runtime/src/main/cpp/com_tns_Runtime.cpp | 67 ++++++++++++-- 9 files changed, 293 insertions(+), 8 deletions(-) create mode 100644 test-app/runtime/src/main/cpp/RuntimeGates.cpp create mode 100644 test-app/runtime/src/main/cpp/RuntimeGates.h diff --git a/test-app/app/src/main/assets/app/tests/testRuntimeBoundDispatch.js b/test-app/app/src/main/assets/app/tests/testRuntimeBoundDispatch.js index a69f4cc4a..e70d80c0d 100644 --- a/test-app/app/src/main/assets/app/tests/testRuntimeBoundDispatch.js +++ b/test-app/app/src/main/assets/app/tests/testRuntimeBoundDispatch.js @@ -92,6 +92,31 @@ describe("Runtime-bound Java->JS dispatch", function () { }); }); + // Callers on other threads take the worker's isolate while it terminates: each call is + // answered or dropped, never run against an isolate that is being torn down. + it("answers or drops calls other threads make while the worker terminates", function (done) { + if (!multithreaded) { + // Calls are posted to the worker's looper in this mode, not run under its lock. + done(); + return; + } + + startWorker(function (worker) { + Holder.startComparing("comparable", 4); + setTimeout(function () { + worker.terminate(); + setTimeout(function () { + var results = Array.prototype.slice.call(Holder.stopComparing()); + results.forEach(function (result) { + expect([42, 0]).toContain(result); + }); + expect(results).toContain(0); + done(); + }, 1000); + }, 50); + }); + }); + it("releases a caller whose queued call is discarded when the worker closes", function (done) { if (multithreaded) { // Calls are never queued on the worker's looper in this mode. diff --git a/test-app/app/src/main/java/com/tns/tests/RuntimeBoundHolder.java b/test-app/app/src/main/java/com/tns/tests/RuntimeBoundHolder.java index 4e84f14a3..d432737b8 100644 --- a/test-app/app/src/main/java/com/tns/tests/RuntimeBoundHolder.java +++ b/test-app/app/src/main/java/com/tns/tests/RuntimeBoundHolder.java @@ -1,5 +1,8 @@ package com.tns.tests; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** @@ -40,4 +43,45 @@ public void run() { public static int compare(String key) { return ((Comparable) objects.get(key)).compareTo(""); } + + private static final List comparers = new ArrayList<>(); + private static final Set compared = ConcurrentHashMap.newKeySet(); + private static volatile boolean comparing; + + // Keeps calling compare(key) from `threads` new threads until stopComparing(). + public static synchronized void startComparing(final String key, int threads) { + compared.clear(); + comparing = true; + for (int i = 0; i < threads; i++) { + Thread thread = new Thread(new Runnable() { + @Override + public void run() { + while (comparing) { + try { + compared.add(compare(key)); + } catch (Throwable t) { + compared.add(Integer.MIN_VALUE); + } + } + } + }, "RuntimeBoundHolder-comparer-" + i); + comparers.add(thread); + thread.start(); + } + } + + // Stops the comparing threads; returns every distinct result, MIN_VALUE for a throw. + public static synchronized int[] stopComparing() throws InterruptedException { + comparing = false; + for (Thread thread : comparers) { + thread.join(); + } + comparers.clear(); + int[] results = new int[compared.size()]; + int i = 0; + for (int result : compared) { + results[i++] = result; + } + return results; + } } diff --git a/test-app/runtime/CMakeLists.txt b/test-app/runtime/CMakeLists.txt index 8f64c421d..6a792c596 100644 --- a/test-app/runtime/CMakeLists.txt +++ b/test-app/runtime/CMakeLists.txt @@ -221,6 +221,7 @@ add_library( src/main/cpp/Profiler.cpp src/main/cpp/ReadWriteLock.cpp src/main/cpp/Runtime.cpp + src/main/cpp/RuntimeGates.cpp src/main/cpp/RuntimeState.cpp src/main/cpp/SimpleAllocator.cpp src/main/cpp/SimpleProfiler.cpp diff --git a/test-app/runtime/src/main/cpp/Runtime.cpp b/test-app/runtime/src/main/cpp/Runtime.cpp index d576841cb..8d1e8cfa0 100644 --- a/test-app/runtime/src/main/cpp/Runtime.cpp +++ b/test-app/runtime/src/main/cpp/Runtime.cpp @@ -1,4 +1,5 @@ #include "Runtime.h" +#include "RuntimeGates.h" #include @@ -137,6 +138,7 @@ Runtime::Runtime(JNIEnv* env, jobject runtime, int id) m_runtime = env->NewGlobalRef(runtime); m_objectManager = new ObjectManager(m_runtime); m_state = std::make_unique(); + RuntimeGates::Open(id); { std::lock_guard lock(s_runtimeCacheMutex); s_id2RuntimeCache.emplace(id, this); @@ -167,6 +169,16 @@ Runtime* Runtime::GetRuntime(int runtimeId) { return runtime; } +Runtime* Runtime::FindRuntime(int runtimeId) { + auto& current = s_current; + if (runtimeId == current.id) { + return current.runtime; + } + std::lock_guard lock(s_runtimeCacheMutex); + auto itFound = s_id2RuntimeCache.find(runtimeId); + return itFound != s_id2RuntimeCache.end() ? itFound->second : nullptr; +} + Runtime* Runtime::GetRuntime(v8::Isolate* isolate) { /* * Hot path, called from V8 callbacks on the isolate's own thread. The slot @@ -905,6 +917,7 @@ void Runtime::UnwindFailedInit() { Isolate::Scope isolateScope(m_isolate); DestroyRuntime(); } + RuntimeGates::WaitUntilUnpinnedAndRetire(m_id); m_isolate->Dispose(); m_isolate = nullptr; } @@ -1389,6 +1402,12 @@ void Runtime::DestroyRuntime() { if (m_state != nullptr) { m_state->Clear(); } + + // Under the Locker, after everything above: a thread that pinned the gate + // and waited for the Locker meanwhile finds the runtime unregistered once it + // gets it, and new pins are refused. The isolate is disposed only once those + // threads have let go. + RuntimeGates::Close(m_id); } Local Runtime::GetContext() { diff --git a/test-app/runtime/src/main/cpp/Runtime.h b/test-app/runtime/src/main/cpp/Runtime.h index 77913df69..d4182ba41 100644 --- a/test-app/runtime/src/main/cpp/Runtime.h +++ b/test-app/runtime/src/main/cpp/Runtime.h @@ -87,6 +87,9 @@ class Runtime { static Runtime* GetRuntime(int runtimeId); + // The runtime with this id, or null; never throws. + static Runtime* FindRuntime(int runtimeId); + static Runtime* GetRuntime(v8::Isolate* isolate); static Runtime* GetRuntimeFromIsolateData(v8::Isolate* isolate); diff --git a/test-app/runtime/src/main/cpp/RuntimeGates.cpp b/test-app/runtime/src/main/cpp/RuntimeGates.cpp new file mode 100644 index 000000000..27deaf4f5 --- /dev/null +++ b/test-app/runtime/src/main/cpp/RuntimeGates.cpp @@ -0,0 +1,90 @@ +#include "RuntimeGates.h" + +#include +#include +#include + +#include "robin_hood.h" + +namespace tns { +namespace RuntimeGates { + +namespace { + +struct Gate { + uint32_t pins = 0; + bool closed = false; +}; + +std::mutex& GatesMutex() { + static auto* mutex = new std::mutex(); + return *mutex; +} + +std::condition_variable& Unpinned() { + static auto* unpinned = new std::condition_variable(); + return *unpinned; +} + +// Never destroyed: process exit runs static destructors while other threads +// may still be pinning. +robin_hood::unordered_map& Gates() { + static auto* gates = new robin_hood::unordered_map(); + return *gates; +} + +} // namespace + +void Open(int id) { + std::lock_guard lock(GatesMutex()); + Gates()[id] = Gate(); +} + +bool TryPin(int id) { + std::lock_guard lock(GatesMutex()); + auto it = Gates().find(id); + if (it == Gates().end() || it->second.closed) { + return false; + } + it->second.pins++; + return true; +} + +void Unpin(int id) { + bool last = false; + { + std::lock_guard lock(GatesMutex()); + auto it = Gates().find(id); + if (it != Gates().end()) { + last = --it->second.pins == 0 && it->second.closed; + } + } + if (last) { + Unpinned().notify_all(); + } +} + +void Close(int id) { + std::lock_guard lock(GatesMutex()); + auto it = Gates().find(id); + if (it != Gates().end()) { + it->second.closed = true; + } +} + +void WaitUntilUnpinnedAndRetire(int id) { + std::unique_lock lock(GatesMutex()); + auto it = Gates().find(id); + if (it == Gates().end()) { + return; + } + it->second.closed = true; + Unpinned().wait(lock, [id]() { + auto found = Gates().find(id); + return found == Gates().end() || found->second.pins == 0; + }); + Gates().erase(id); +} + +} // namespace RuntimeGates +} // namespace tns diff --git a/test-app/runtime/src/main/cpp/RuntimeGates.h b/test-app/runtime/src/main/cpp/RuntimeGates.h new file mode 100644 index 000000000..363c781ec --- /dev/null +++ b/test-app/runtime/src/main/cpp/RuntimeGates.h @@ -0,0 +1,48 @@ +#ifndef RUNTIMEGATES_H_ +#define RUNTIMEGATES_H_ + +namespace tns { + +/* + * One gate per runtime, keyed by its id (ids are never reused); the iOS + * runtime's IsolateGates. A thread entering another thread's runtime pins the + * gate before it waits for the runtime's Locker and until it lets go of it. + * The runtime's teardown closes the gate last, under the Locker, and disposes + * the isolate only once no pin is held, so a pinned runtime and its isolate + * stay allocated. A missing gate reads as closed. + */ +namespace RuntimeGates { +// Before the runtime can be found by id. +void Open(int id); +// False once the gate is closed: the runtime may already be freed. +bool TryPin(int id); +void Unpin(int id); +// From the teardown, holding the runtime's Locker. +void Close(int id); +// Before Isolate::Dispose, without the runtime's Locker: a pinned thread may +// be waiting for it. Drops the gate. +void WaitUntilUnpinnedAndRetire(int id); +} // namespace RuntimeGates + +// Owns a pin for its scope. Declare it before the Locker it guards, so the +// Locker is released first. +class RuntimePin { + public: + explicit RuntimePin(int id) : m_id(id), m_pinned(RuntimeGates::TryPin(id)) {} + ~RuntimePin() { + if (m_pinned) { + RuntimeGates::Unpin(m_id); + } + } + RuntimePin(const RuntimePin&) = delete; + RuntimePin& operator=(const RuntimePin&) = delete; + explicit operator bool() const { return m_pinned; } + + private: + int m_id; + bool m_pinned; +}; + +} // namespace tns + +#endif /* RUNTIMEGATES_H_ */ diff --git a/test-app/runtime/src/main/cpp/WorkerWrapper.cpp b/test-app/runtime/src/main/cpp/WorkerWrapper.cpp index c36615cd3..cba9672ea 100644 --- a/test-app/runtime/src/main/cpp/WorkerWrapper.cpp +++ b/test-app/runtime/src/main/cpp/WorkerWrapper.cpp @@ -1,4 +1,5 @@ #include "WorkerWrapper.h" +#include "RuntimeGates.h" #include #include @@ -784,6 +785,9 @@ void WorkerWrapper::BackgroundLooper(std::shared_ptr self) { isolate->RemoveNearHeapLimitCallback(WorkerWrapper::OnNearHeapLimit, 0); runtime_->DestroyRuntime(); } + // Without the Locker: a thread pinned in a Java->JS call may be + // waiting for it, and lets go once it finds the runtime unregistered. + RuntimeGates::WaitUntilUnpinnedAndRetire(runtime_->GetId()); 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 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 8358e8812..1255105dd 100644 --- a/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp +++ b/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp @@ -1,10 +1,12 @@ #include "V8StringConstants.h" #include "Runtime.h" +#include "RuntimeGates.h" #include "NativeScriptException.h" #include "CallbackHandlers.h" #include "ArgConverter.h" #include "MetadataNode.h" #include +#include #include #include #include @@ -136,6 +138,57 @@ Runtime* TryGetRuntime(int runtimeId) { return runtime; } +namespace { + +/* + * A Java->JS entry's hold on a runtime: its Locker, after the admission gate + * when `admit`. Entering another thread's runtime pins it first (RuntimeGates, + * as the iOS runtime's native callbacks do), so a runtime tearing down while + * this thread waits for the Locker cannot dispose its isolate or free itself + * before the wait is over, and is found unregistered once the Locker is + * granted. Get() is null when the call is dropped: the runtime is gone or + * shutting down. + */ +class RuntimeEntry { +public: + RuntimeEntry(jint runtimeId, bool admit) { + auto current = Runtime::GetCurrentRuntime(); + // This thread's own runtime is torn down only on this thread. + bool own = current != nullptr && current->GetId() == runtimeId; + if (!own) { + m_pin.emplace(runtimeId); + if (!*m_pin) { + return; + } + } + auto runtime = own ? current : Runtime::FindRuntime(runtimeId); + if (runtime == nullptr) { + return; + } + auto isolate = runtime->GetIsolate(); + if (admit) { + m_admission.emplace(runtime->GetAdmissionGate(), isolate); + } + m_locker.emplace(isolate); + // The teardown unregisters the runtime under this Locker. + if (!own && Runtime::FindRuntime(runtimeId) != runtime) { + return; + } + m_runtime = runtime; + } + + tns::Runtime* Get() const { return m_runtime; } + +private: + tns::Runtime* m_runtime = nullptr; + // Released in reverse: the Locker, the admission gate, then the pin. + std::optional m_pin; + std::optional m_admission; + std::optional m_locker; +}; + +} // namespace + extern "C" JNIEXPORT void Java_com_tns_Runtime_runModule(JNIEnv* _env, jobject obj, jint runtimeId, jstring scriptFile) { JEnv::EntryScope envScope(_env); auto runtime = TryGetRuntime(runtimeId); @@ -201,14 +254,13 @@ extern "C" JNIEXPORT jobject Java_com_tns_Runtime_callJSMethodNative(JNIEnv* _en JEnv::EntryScope envScope(_env); jobject result = nullptr; - auto runtime = TryGetRuntime(runtimeId); + RuntimeEntry entry(runtimeId, true); + auto runtime = entry.Get(); if (runtime == nullptr) { return result; } auto isolate = runtime->GetIsolate(); - AdmissionScope admission(runtime->GetAdmissionGate(), isolate); - v8::Locker locker(isolate); v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope handleScope(isolate); auto context = runtime->GetContext(); @@ -238,14 +290,13 @@ extern "C" JNIEXPORT jobject Java_com_tns_Runtime_callJSMethodNative(JNIEnv* _en extern "C" JNIEXPORT void Java_com_tns_Runtime_createJSInstanceNative(JNIEnv* _env, jobject obj, jint runtimeId, jobject javaObject, jint javaObjectID, jstring className) { JEnv::EntryScope envScope(_env); - auto runtime = TryGetRuntime(runtimeId); + RuntimeEntry entry(runtimeId, true); + auto runtime = entry.Get(); if (runtime == nullptr) { return; } auto isolate = runtime->GetIsolate(); - AdmissionScope admission(runtime->GetAdmissionGate(), isolate); - v8::Locker locker(isolate); v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope handleScope(isolate); auto context = runtime->GetContext(); @@ -323,13 +374,13 @@ extern "C" JNIEXPORT void Java_com_tns_Runtime_unlock(JNIEnv* env, jobject obj, } extern "C" JNIEXPORT jboolean Java_com_tns_Runtime_passExceptionToJsNative(JNIEnv* env, jobject obj, jint runtimeId, jthrowable exception, jstring message, jstring fullStackTrace, jstring jsStackTrace, jboolean isDiscarded) { - auto runtime = TryGetRuntime(runtimeId); + RuntimeEntry entry(runtimeId, false); + auto runtime = entry.Get(); if (runtime == nullptr) { return JNI_FALSE; } auto isolate = runtime->GetIsolate(); - v8::Locker locker(isolate); v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope handleScope(isolate); auto context = runtime->GetContext(); From 18d7ddcd81c7c3b9e28d32e0d5a9ffbb90aa25d6 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 17:44:12 -0300 Subject: [PATCH 2/9] fix(runtime): pin a runtime while generating an object id for it Java registers a call's arguments on the calling thread without the isolate lock, and a fresh argument gets its id from generateNewObjectId, which read the runtime unpinned: a worker tearing down meanwhile could free it under the call. It now pins another thread's runtime like the other entries do, and returns 0 once the runtime is gone or closing. The regression spec waits for a call the live worker answered before terminating it and for a dropped call afterwards, each with a deadline, instead of a fixed delay, and the comparer threads are joined with a deadline, a thread still running reported as STUCK. --- .../app/tests/testRuntimeBoundDispatch.js | 30 +++++++++++++++---- .../com/tns/tests/RuntimeBoundHolder.java | 22 +++++++++++--- .../runtime/src/main/cpp/com_tns_Runtime.cpp | 13 +++++++- 3 files changed, 54 insertions(+), 11 deletions(-) diff --git a/test-app/app/src/main/assets/app/tests/testRuntimeBoundDispatch.js b/test-app/app/src/main/assets/app/tests/testRuntimeBoundDispatch.js index e70d80c0d..45076a9c9 100644 --- a/test-app/app/src/main/assets/app/tests/testRuntimeBoundDispatch.js +++ b/test-app/app/src/main/assets/app/tests/testRuntimeBoundDispatch.js @@ -101,19 +101,37 @@ describe("Runtime-bound Java->JS dispatch", function () { return; } + function waitFor(condition, what, then) { + var deadline = Date.now() + 10000; + (function poll() { + if (condition()) { + then(); + } else if (Date.now() > deadline) { + Holder.stopComparing(10000); + fail("timed out waiting for " + what); + done(); + } else { + setTimeout(poll, 20); + } + })(); + } + startWorker(function (worker) { Holder.startComparing("comparable", 4); - setTimeout(function () { + waitFor(function () { + return Holder.hasCompared(42); + }, "a call answered by the live worker", function () { worker.terminate(); - setTimeout(function () { - var results = Array.prototype.slice.call(Holder.stopComparing()); + waitFor(function () { + return Holder.hasCompared(0); + }, "a call dropped after terminate()", function () { + var results = Array.prototype.slice.call(Holder.stopComparing(10000)); results.forEach(function (result) { expect([42, 0]).toContain(result); }); - expect(results).toContain(0); done(); - }, 1000); - }, 50); + }); + }); }); }); diff --git a/test-app/app/src/main/java/com/tns/tests/RuntimeBoundHolder.java b/test-app/app/src/main/java/com/tns/tests/RuntimeBoundHolder.java index d432737b8..c76fed526 100644 --- a/test-app/app/src/main/java/com/tns/tests/RuntimeBoundHolder.java +++ b/test-app/app/src/main/java/com/tns/tests/RuntimeBoundHolder.java @@ -44,10 +44,19 @@ public static int compare(String key) { return ((Comparable) objects.get(key)).compareTo(""); } + // Results stopComparing reports for a comparison that threw, and for a comparer + // thread still running at its deadline. + public static final int THREW = Integer.MIN_VALUE; + public static final int STUCK = Integer.MAX_VALUE; + private static final List comparers = new ArrayList<>(); private static final Set compared = ConcurrentHashMap.newKeySet(); private static volatile boolean comparing; + public static boolean hasCompared(int result) { + return compared.contains(result); + } + // Keeps calling compare(key) from `threads` new threads until stopComparing(). public static synchronized void startComparing(final String key, int threads) { compared.clear(); @@ -60,7 +69,7 @@ public void run() { try { compared.add(compare(key)); } catch (Throwable t) { - compared.add(Integer.MIN_VALUE); + compared.add(THREW); } } } @@ -70,11 +79,16 @@ public void run() { } } - // Stops the comparing threads; returns every distinct result, MIN_VALUE for a throw. - public static synchronized int[] stopComparing() throws InterruptedException { + // Stops the comparing threads, waiting up to timeoutMillis for them; returns every + // distinct result, with THREW for a throw and STUCK if a thread is still running. + public static synchronized int[] stopComparing(long timeoutMillis) throws InterruptedException { comparing = false; + long deadline = System.currentTimeMillis() + timeoutMillis; for (Thread thread : comparers) { - thread.join(); + thread.join(Math.max(1, deadline - System.currentTimeMillis())); + if (thread.isAlive()) { + compared.add(STUCK); + } } comparers.clear(); int[] results = new int[compared.size()]; 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 1255105dd..4076c431a 100644 --- a/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp +++ b/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp @@ -320,7 +320,18 @@ extern "C" JNIEXPORT void Java_com_tns_Runtime_createJSInstanceNative(JNIEnv* _e // @CriticalNative ABI: no JNIEnv* / jclass. static jint generateNewObjectIdCritical_impl(jint runtimeId) { try { - auto runtime = TryGetRuntime(runtimeId); + // Java registers a call's arguments on the calling thread, without the + // isolate lock, so this can run on any thread while the runtime tears + // down. The counter needs no lock, only the runtime kept allocated. + auto current = Runtime::GetCurrentRuntime(); + std::optional pin; + if (current == nullptr || current->GetId() != runtimeId) { + pin.emplace(runtimeId); + if (!*pin) { + return 0; + } + } + auto runtime = Runtime::FindRuntime(runtimeId); if (runtime == nullptr) { return 0; } From 76c4c5e1700aa5e04e70628d681f6e2dd1e2dd19 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 17:58:01 -0300 Subject: [PATCH 3/9] test(runtime): terminate the worker on a timeout and copy results safely A spec that timed out before terminating its worker left the worker running into later specs. stopComparing copies the results through a snapshot, since a comparer still running after its join deadline can add one while they are copied. --- .../main/assets/app/tests/testRuntimeBoundDispatch.js | 5 ++++- .../src/main/java/com/tns/tests/RuntimeBoundHolder.java | 9 +++++---- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/test-app/app/src/main/assets/app/tests/testRuntimeBoundDispatch.js b/test-app/app/src/main/assets/app/tests/testRuntimeBoundDispatch.js index 45076a9c9..f202e4c9a 100644 --- a/test-app/app/src/main/assets/app/tests/testRuntimeBoundDispatch.js +++ b/test-app/app/src/main/assets/app/tests/testRuntimeBoundDispatch.js @@ -101,12 +101,14 @@ describe("Runtime-bound Java->JS dispatch", function () { return; } + var worker; function waitFor(condition, what, then) { var deadline = Date.now() + 10000; (function poll() { if (condition()) { then(); } else if (Date.now() > deadline) { + worker.terminate(); Holder.stopComparing(10000); fail("timed out waiting for " + what); done(); @@ -116,7 +118,8 @@ describe("Runtime-bound Java->JS dispatch", function () { })(); } - startWorker(function (worker) { + startWorker(function (started) { + worker = started; Holder.startComparing("comparable", 4); waitFor(function () { return Holder.hasCompared(42); diff --git a/test-app/app/src/main/java/com/tns/tests/RuntimeBoundHolder.java b/test-app/app/src/main/java/com/tns/tests/RuntimeBoundHolder.java index c76fed526..2682f1ba4 100644 --- a/test-app/app/src/main/java/com/tns/tests/RuntimeBoundHolder.java +++ b/test-app/app/src/main/java/com/tns/tests/RuntimeBoundHolder.java @@ -91,10 +91,11 @@ public static synchronized int[] stopComparing(long timeoutMillis) throws Interr } } comparers.clear(); - int[] results = new int[compared.size()]; - int i = 0; - for (int result : compared) { - results[i++] = result; + // A thread still running can add results while this copies them. + Integer[] snapshot = compared.toArray(new Integer[0]); + int[] results = new int[snapshot.length]; + for (int i = 0; i < snapshot.length; i++) { + results[i] = snapshot[i]; } return results; } From a11f2c189702ffa24e5577e00f177f14c331bd10 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 20:20:22 -0300 Subject: [PATCH 4/9] fix(runtime): register nothing under a refused object id A Java thread registering a call's new argument for another thread's runtime gets its id from generateNewObjectId, which is refused once that runtime is shutting down. The refusal was 0, a real object id, so findOrRegister stored the argument under it. Treat NO_ID from the id source as "no id": findOrRegister registers nothing and returns NO_ID, packageArgs gives up on the call, and the call is dropped with a logged discard and a default primitive value. Also corrects the comment on the multithreaded call's catch: native no longer throws "Cannot find runtime" for a runtime that went away; the catch covers a call whose JS a terminate() cut short. --- .../src/main/java/com/tns/ObjectTable.java | 7 ++++++- .../runtime/src/main/java/com/tns/Runtime.java | 17 ++++++++++++----- .../src/test/java/com/tns/ObjectTableTest.java | 17 +++++++++++++++++ 3 files changed, 35 insertions(+), 6 deletions(-) diff --git a/test-app/runtime/src/main/java/com/tns/ObjectTable.java b/test-app/runtime/src/main/java/com/tns/ObjectTable.java index eec847e5b..460fadcbe 100644 --- a/test-app/runtime/src/main/java/com/tns/ObjectTable.java +++ b/test-app/runtime/src/main/java/com/tns/ObjectTable.java @@ -21,6 +21,7 @@ final class ObjectTable { static final long FRESH = 1L << 32; interface IdSource { + // NO_ID when there is no id to give. int newId(); } @@ -104,7 +105,8 @@ private void putStrongLocked(int id, Object obj, int hash) { /** * The id obj is registered under, registering it strongly under a new id from ids when * it has none; FRESH is set in the result when this call registered it. The lookup and - * the insert happen under one lock, so concurrent calls agree on one id. + * the insert happen under one lock, so concurrent calls agree on one id. NO_ID (with + * nothing registered) when obj has no id and ids gives none. */ long findOrRegister(Object obj, IdSource ids) { synchronized (this) { @@ -114,6 +116,9 @@ long findOrRegister(Object obj, IdSource ids) { return id & 0xFFFFFFFFL; } id = ids.newId(); + if (id == NO_ID) { + return NO_ID & 0xFFFFFFFFL; + } putStrongLocked(id, obj, hash); return (id & 0xFFFFFFFFL) | FRESH; } 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 c9e5ea27f..95585dff0 100644 --- a/test-app/runtime/src/main/java/com/tns/Runtime.java +++ b/test-app/runtime/src/main/java/com/tns/Runtime.java @@ -1471,7 +1471,8 @@ private static final class PackagedArgs { private static final PackagedArgs NO_ARGS = new PackagedArgs(0, null, null); // If a javaObject has no javaObjectID, meaning no JavaScript object exists - // for it yet, it is assigned one. + // for it yet, it is assigned one. Null when no id can be had: the runtime is + // shutting down and the call has to be dropped. private PackagedArgs packageArgs(Object... args) { int len = (args != null) ? args.length : 0; if (len == 0) { @@ -1538,6 +1539,9 @@ private PackagedArgs packageArgs(Object... args) { // in with new objects only serialize on creating their wrappers. long found = objectTable.findOrRegister(value, objectIds); id = (int) found; + if (id == ObjectTable.NO_ID) { + return null; + } if ((found & ObjectTable.FRESH) != 0) { fresh = FRESH_ARG; } @@ -1660,6 +1664,10 @@ private Object dispatchCallJSMethodNative(final Object javaObject, int objectIdH if (enableMultithreadedJavascript || isWorkThread) { PackagedArgs packagedArgs = packageArgs(tmpArgs); + if (packagedArgs == null) { + return discardCall(methodName, retType, "runtime id=" + getRuntimeId() + " (workerId=" + workerId + + ") is shutting down"); + } long[] primitiveResult = newPrimitiveResult(returnType); try { // A hint: other threads may be writing the table, so native re-checks it under the @@ -1668,10 +1676,9 @@ private Object dispatchCallJSMethodNative(final Object javaObject, int objectIdH objectIdHint != ObjectTable.NO_ID ? objectIdHint : objectTable.findId(javaObject), methodName, MethodNameIds.idOf(methodName), returnType, isConstructor, packagedArgs.count, packagedArgs.values, packagedArgs.refs, primitiveResult); ret = takePrimitiveResult(ret, returnType, primitiveResult); } catch (NativeScriptException e) { - // With multithreaded JS the owner can be torn down between the - // routing check and the native call, which then throws - // "Cannot find runtime"; that is the same lifecycle race the - // other dead-owner paths drop. + // With multithreaded JS the owner can be terminated while the + // call runs on this thread, cutting its JS short; that is the + // same lifecycle race the other dead-owner paths drop. if (!isAcceptingWork()) { return discardCall(methodName, retType, "runtime id=" + getRuntimeId() + " (workerId=" + workerId + ") terminated during the call"); diff --git a/test-app/runtime/src/test/java/com/tns/ObjectTableTest.java b/test-app/runtime/src/test/java/com/tns/ObjectTableTest.java index e39fa3740..93356ba35 100644 --- a/test-app/runtime/src/test/java/com/tns/ObjectTableTest.java +++ b/test-app/runtime/src/test/java/com/tns/ObjectTableTest.java @@ -335,6 +335,23 @@ public int newId() { assertEquals(1, table.size()); } + @Test + public void registersNothingWhenNoIdIsGiven() { + ObjectTable table = new ObjectTable(); + Object a = new Object(); + + long found = table.findOrRegister(a, new ObjectTable.IdSource() { + @Override + public int newId() { + return ObjectTable.NO_ID; + } + }); + assertEquals(ObjectTable.NO_ID, (int) found); + assertFalse((found & ObjectTable.FRESH) != 0); + assertEquals(ObjectTable.NO_ID, table.findId(a)); + assertEquals(0, table.size()); + } + @Test public void matchesReferenceMapsUnderRandomOperations() { Random random = new Random(42); From 029ff0218eb7133ab3c4a2e1c7d478d570b72363 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 20:20:31 -0300 Subject: [PATCH 5/9] fix(runtime): pin and find a runtime in one step, and log dropped calls A Java->JS entry into another thread's runtime took four process-wide mutex round trips (pin, registry lookup, registry recheck after the Locker, unpin), and generateNewObjectId three, inside the ObjectTable monitor of a @CriticalNative call. - Each gate holds its runtime, so TryPin returns it: lookup and pin are one critical section. The recheck after the Locker is a flag DestroyRuntime sets under that Locker; the pin keeps the runtime allocated until it is read. A foreign entry is now two round trips. - generateNewObjectId bumps the counter under the gates' lock instead of pinning (one round trip), and returns -1 (ObjectTable.NO_ID) once the gate is closed. - ~Runtime retires the gate as a backstop: a bootstrap that failed before the isolate existed never closed it, and the gate now hands out the runtime pointer. An entry finding no isolate drops the call. - A dropped callJSMethodNative, createJSInstanceNative or passExceptionToJsNative logs a warning in the Java side's format; before, a listener that lost the race with terminate() returned 0/null with nothing in logcat. - UnwindFailedInit's comment claimed an outer Locker did not matter; the wait for pins deadlocks if one is held. Say so and DCHECK it, and DCHECK that DestroyRuntime holds the Locker the flag relies on. Same-thread entries still take no lock. --- test-app/runtime/src/main/cpp/Runtime.cpp | 38 ++++++------- test-app/runtime/src/main/cpp/Runtime.h | 8 +-- .../runtime/src/main/cpp/RuntimeGates.cpp | 23 ++++++-- test-app/runtime/src/main/cpp/RuntimeGates.h | 30 +++++++---- .../runtime/src/main/cpp/com_tns_Runtime.cpp | 53 ++++++++++--------- 5 files changed, 86 insertions(+), 66 deletions(-) diff --git a/test-app/runtime/src/main/cpp/Runtime.cpp b/test-app/runtime/src/main/cpp/Runtime.cpp index 8d1e8cfa0..4e8ebcbae 100644 --- a/test-app/runtime/src/main/cpp/Runtime.cpp +++ b/test-app/runtime/src/main/cpp/Runtime.cpp @@ -138,7 +138,7 @@ Runtime::Runtime(JNIEnv* env, jobject runtime, int id) m_runtime = env->NewGlobalRef(runtime); m_objectManager = new ObjectManager(m_runtime); m_state = std::make_unique(); - RuntimeGates::Open(id); + RuntimeGates::Open(id, this); { std::lock_guard lock(s_runtimeCacheMutex); s_id2RuntimeCache.emplace(id, this); @@ -169,16 +169,6 @@ Runtime* Runtime::GetRuntime(int runtimeId) { return runtime; } -Runtime* Runtime::FindRuntime(int runtimeId) { - auto& current = s_current; - if (runtimeId == current.id) { - return current.runtime; - } - std::lock_guard lock(s_runtimeCacheMutex); - auto itFound = s_id2RuntimeCache.find(runtimeId); - return itFound != s_id2RuntimeCache.end() ? itFound->second : nullptr; -} - Runtime* Runtime::GetRuntime(v8::Isolate* isolate) { /* * Hot path, called from V8 callbacks on the isolate's own thread. The slot @@ -306,10 +296,13 @@ Runtime::~Runtime() { } /* - * Idempotent backstop for the erase DestroyRuntime does: a bootstrap that - * failed before PrepareV8Runtime ran never reached it. The isolate entry is - * matched on value so it cannot evict a new runtime that reused the pointer. + * Idempotent backstops for the gate retirement and the erase the teardown + * does: a bootstrap that failed before PrepareV8Runtime ran never reached + * them. The gate goes first, while every member a pinned thread may read is + * still alive. The isolate entry is matched on value so it cannot evict a + * new runtime that reused the pointer. */ + RuntimeGates::WaitUntilUnpinnedAndRetire(m_id); { std::lock_guard lock(s_runtimeCacheMutex); s_id2RuntimeCache.erase(m_id); @@ -907,11 +900,12 @@ void Runtime::UnwindFailedInit() { /* * Reuses the two teardown windows rather than adding a third cleanup path. * Every step DestroyRuntime takes is null-tolerant, which is what makes it - * usable on a runtime that never finished building; the Locker is reentrant, - * so it does not matter whether the failure unwound past the one - * PrepareV8Runtime holds. + * usable on a runtime that never finished building. The caller must not + * hold the isolate's Locker: the wait for pins below would deadlock against + * a pinned thread waiting for it. */ if (m_isolate != nullptr) { + NS_DCHECK(!v8::Locker::IsLocked(m_isolate)); { v8::Locker locker(m_isolate); Isolate::Scope isolateScope(m_isolate); @@ -1292,6 +1286,10 @@ double Runtime::PerformanceNowMillis() { void Runtime::DestroyRuntime() { NS_CHECK(std::this_thread::get_id() == m_ownerThread); + NS_DCHECK(v8::Locker::IsLocked(m_isolate)); + // A thread that pinned this runtime and then waited for the Locker drops + // its call when it finds this set. + m_destroyed = true; CrashBreadcrumbs::UnregisterRuntime(m_id); { std::lock_guard lock(s_runtimeCacheMutex); @@ -1403,10 +1401,8 @@ void Runtime::DestroyRuntime() { m_state->Clear(); } - // Under the Locker, after everything above: a thread that pinned the gate - // and waited for the Locker meanwhile finds the runtime unregistered once it - // gets it, and new pins are refused. The isolate is disposed only once those - // threads have let go. + // New pins are refused from here on; the isolate is disposed only once the + // threads already pinned have let go. RuntimeGates::Close(m_id); } diff --git a/test-app/runtime/src/main/cpp/Runtime.h b/test-app/runtime/src/main/cpp/Runtime.h index d4182ba41..c51bff845 100644 --- a/test-app/runtime/src/main/cpp/Runtime.h +++ b/test-app/runtime/src/main/cpp/Runtime.h @@ -87,9 +87,6 @@ class Runtime { static Runtime* GetRuntime(int runtimeId); - // The runtime with this id, or null; never throws. - static Runtime* FindRuntime(int runtimeId); - static Runtime* GetRuntime(v8::Isolate* isolate); static Runtime* GetRuntimeFromIsolateData(v8::Isolate* isolate); @@ -212,6 +209,10 @@ class Runtime { jboolean PassExceptionToJsNative(JNIEnv* env, jobject obj, jthrowable exception, jstring message, jstring fullStackTrace, jstring jsStackTrace, jboolean isDiscarded); void DestroyRuntime(); + // Read under the isolate's Locker, which DestroyRuntime holds when it + // sets it. + bool IsDestroyed() const { return m_destroyed; } + void Lock(); void Unlock(); @@ -397,6 +398,7 @@ class Runtime { // Decided by ElectMainRuntime, before anything can read it. bool m_isMainThread = false; + bool m_destroyed = false; // This isolate's performance time origin, captured at isolate // creation: the monotonic clock reading now() is relative to, and the diff --git a/test-app/runtime/src/main/cpp/RuntimeGates.cpp b/test-app/runtime/src/main/cpp/RuntimeGates.cpp index 27deaf4f5..a404f871c 100644 --- a/test-app/runtime/src/main/cpp/RuntimeGates.cpp +++ b/test-app/runtime/src/main/cpp/RuntimeGates.cpp @@ -4,6 +4,7 @@ #include #include +#include "Runtime.h" #include "robin_hood.h" namespace tns { @@ -12,6 +13,7 @@ namespace RuntimeGates { namespace { struct Gate { + Runtime* runtime = nullptr; uint32_t pins = 0; bool closed = false; }; @@ -35,19 +37,30 @@ robin_hood::unordered_map& Gates() { } // namespace -void Open(int id) { +void Open(int id, Runtime* runtime) { std::lock_guard lock(GatesMutex()); - Gates()[id] = Gate(); + Gate gate; + gate.runtime = runtime; + Gates()[id] = gate; } -bool TryPin(int id) { +Runtime* TryPin(int id) { std::lock_guard lock(GatesMutex()); auto it = Gates().find(id); if (it == Gates().end() || it->second.closed) { - return false; + return nullptr; } it->second.pins++; - return true; + return it->second.runtime; +} + +int TryGenerateObjectId(int id) { + std::lock_guard lock(GatesMutex()); + auto it = Gates().find(id); + if (it == Gates().end() || it->second.closed) { + return -1; + } + return it->second.runtime->GenerateNewObjectId(nullptr, nullptr); } void Unpin(int id) { diff --git a/test-app/runtime/src/main/cpp/RuntimeGates.h b/test-app/runtime/src/main/cpp/RuntimeGates.h index 363c781ec..84e051629 100644 --- a/test-app/runtime/src/main/cpp/RuntimeGates.h +++ b/test-app/runtime/src/main/cpp/RuntimeGates.h @@ -3,24 +3,31 @@ namespace tns { +class Runtime; + /* * One gate per runtime, keyed by its id (ids are never reused); the iOS * runtime's IsolateGates. A thread entering another thread's runtime pins the * gate before it waits for the runtime's Locker and until it lets go of it. * The runtime's teardown closes the gate last, under the Locker, and disposes - * the isolate only once no pin is held, so a pinned runtime and its isolate - * stay allocated. A missing gate reads as closed. + * the isolate and frees the runtime only once no pin is held, so a pinned + * runtime and its isolate stay allocated. A missing gate reads as closed. */ namespace RuntimeGates { // Before the runtime can be found by id. -void Open(int id); -// False once the gate is closed: the runtime may already be freed. -bool TryPin(int id); +void Open(int id, Runtime* runtime); +// The gate's runtime, pinned; null once the gate is closed, when the runtime +// may already be freed. +Runtime* TryPin(int id); void Unpin(int id); +// A new object id from the runtime, or -1 once the gate is closed. Holds the +// gates' lock rather than a pin: the runtime is freed only after its gate is +// retired under that lock. +int TryGenerateObjectId(int id); // From the teardown, holding the runtime's Locker. void Close(int id); -// Before Isolate::Dispose, without the runtime's Locker: a pinned thread may -// be waiting for it. Drops the gate. +// Before Isolate::Dispose and before the runtime is freed, without the +// runtime's Locker: a pinned thread may be waiting for it. Drops the gate. void WaitUntilUnpinnedAndRetire(int id); } // namespace RuntimeGates @@ -28,19 +35,20 @@ void WaitUntilUnpinnedAndRetire(int id); // Locker is released first. class RuntimePin { public: - explicit RuntimePin(int id) : m_id(id), m_pinned(RuntimeGates::TryPin(id)) {} + explicit RuntimePin(int id) : m_id(id), m_runtime(RuntimeGates::TryPin(id)) {} ~RuntimePin() { - if (m_pinned) { + if (m_runtime != nullptr) { RuntimeGates::Unpin(m_id); } } RuntimePin(const RuntimePin&) = delete; RuntimePin& operator=(const RuntimePin&) = delete; - explicit operator bool() const { return m_pinned; } + // Null when the pin was refused. + Runtime* runtime() const { return m_runtime; } private: int m_id; - bool m_pinned; + Runtime* m_runtime; }; } // namespace tns 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 4076c431a..66b891175 100644 --- a/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp +++ b/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp @@ -145,33 +145,32 @@ namespace { * when `admit`. Entering another thread's runtime pins it first (RuntimeGates, * as the iOS runtime's native callbacks do), so a runtime tearing down while * this thread waits for the Locker cannot dispose its isolate or free itself - * before the wait is over, and is found unregistered once the Locker is - * granted. Get() is null when the call is dropped: the runtime is gone or - * shutting down. + * before the wait is over, and is found destroyed once the Locker is granted. + * Get() is null when the call is dropped: the runtime is gone or shutting + * down. */ class RuntimeEntry { public: RuntimeEntry(jint runtimeId, bool admit) { - auto current = Runtime::GetCurrentRuntime(); + auto runtime = Runtime::GetCurrentRuntime(); // This thread's own runtime is torn down only on this thread. - bool own = current != nullptr && current->GetId() == runtimeId; - if (!own) { + if (runtime == nullptr || runtime->GetId() != runtimeId) { m_pin.emplace(runtimeId); - if (!*m_pin) { + runtime = m_pin->runtime(); + if (runtime == nullptr) { return; } } - auto runtime = own ? current : Runtime::FindRuntime(runtimeId); - if (runtime == nullptr) { + auto isolate = runtime->GetIsolate(); + // A runtime whose bootstrap failed before it had an isolate. + if (isolate == nullptr) { return; } - auto isolate = runtime->GetIsolate(); if (admit) { m_admission.emplace(runtime->GetAdmissionGate(), isolate); } m_locker.emplace(isolate); - // The teardown unregisters the runtime under this Locker. - if (!own && Runtime::FindRuntime(runtimeId) != runtime) { + if (runtime->IsDestroyed()) { return; } m_runtime = runtime; @@ -187,6 +186,13 @@ class RuntimeEntry { std::optional m_locker; }; +// Same tag and wording as the Java side's dropped calls (Runtime.logDiscardedCall). +void LogDropped(jint runtimeId, const std::string& what) { + __android_log_print(ANDROID_LOG_WARN, "Warning", + "NativeScript discarding %s: runtime id=%d is shutting down", + what.c_str(), runtimeId); +} + } // namespace extern "C" JNIEXPORT void Java_com_tns_Runtime_runModule(JNIEnv* _env, jobject obj, jint runtimeId, jstring scriptFile) { @@ -257,6 +263,7 @@ extern "C" JNIEXPORT jobject Java_com_tns_Runtime_callJSMethodNative(JNIEnv* _en RuntimeEntry entry(runtimeId, true); auto runtime = entry.Get(); if (runtime == nullptr) { + LogDropped(runtimeId, "call to \"" + ArgConverter::jstringToString(methodName) + "\""); return result; } @@ -293,6 +300,7 @@ extern "C" JNIEXPORT void Java_com_tns_Runtime_createJSInstanceNative(JNIEnv* _e RuntimeEntry entry(runtimeId, true); auto runtime = entry.Get(); if (runtime == nullptr) { + LogDropped(runtimeId, "the JS instance of a " + ArgConverter::jstringToString(className)); return; } @@ -320,22 +328,14 @@ extern "C" JNIEXPORT void Java_com_tns_Runtime_createJSInstanceNative(JNIEnv* _e // @CriticalNative ABI: no JNIEnv* / jclass. static jint generateNewObjectIdCritical_impl(jint runtimeId) { try { - // Java registers a call's arguments on the calling thread, without the - // isolate lock, so this can run on any thread while the runtime tears - // down. The counter needs no lock, only the runtime kept allocated. auto current = Runtime::GetCurrentRuntime(); - std::optional pin; - if (current == nullptr || current->GetId() != runtimeId) { - pin.emplace(runtimeId); - if (!*pin) { - return 0; - } - } - auto runtime = Runtime::FindRuntime(runtimeId); - if (runtime == nullptr) { - return 0; + if (current != nullptr && current->GetId() == runtimeId) { + return current->GenerateNewObjectId(nullptr, nullptr); } - return runtime->GenerateNewObjectId(nullptr, nullptr); + // Java registers a call's arguments on the calling thread, without the + // isolate lock, so this can run on any thread while the runtime tears + // down. -1 is ObjectTable.NO_ID; Java drops the call it was for. + return RuntimeGates::TryGenerateObjectId(runtimeId); } catch (NativeScriptException& e) { e.ReThrowToJava(); } catch (std::exception e) { @@ -388,6 +388,7 @@ extern "C" JNIEXPORT jboolean Java_com_tns_Runtime_passExceptionToJsNative(JNIEn RuntimeEntry entry(runtimeId, false); auto runtime = entry.Get(); if (runtime == nullptr) { + LogDropped(runtimeId, "an exception report"); return JNI_FALSE; } From 812ba43a803aeaf9e993bda29ea37ba6c680ca5f Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 20:22:56 -0300 Subject: [PATCH 6/9] test(runtime): keep comparers calling through the worker's teardown The spec stopped its comparer threads at the first dropped call, but terminate()'s TerminateExecution can land on a comparer and yield a 0 before the worker starts tearing down, so the spec could pass without a call overlapping DestroyRuntime. Each comparer now stops on its own after 20 dropped calls in a row, which only happens once the worker is gone; the calls it had in flight are the ones that overlap the teardown. That also bounds the discard warnings the comparers log after the Java detach. Each call passes a new Object, so it registers the argument from the comparer thread and exercises generateNewObjectId's foreign-thread path. afterEach terminates the worker and stops the comparers even when jasmine times the spec out, and the poll chain stops with the spec. Waits are 5 s each, well inside the 30 s spec timeout. Without multithreaded JS the spec is pending rather than silently passing. --- .../app/tests/testRuntimeBoundDispatch.js | 41 +++++++++++++------ .../com/tns/tests/RuntimeBoundHolder.java | 29 ++++++++++--- 2 files changed, 53 insertions(+), 17 deletions(-) diff --git a/test-app/app/src/main/assets/app/tests/testRuntimeBoundDispatch.js b/test-app/app/src/main/assets/app/tests/testRuntimeBoundDispatch.js index f202e4c9a..78e6d2dcb 100644 --- a/test-app/app/src/main/assets/app/tests/testRuntimeBoundDispatch.js +++ b/test-app/app/src/main/assets/app/tests/testRuntimeBoundDispatch.js @@ -18,11 +18,22 @@ describe("Runtime-bound Java->JS dispatch", function () { } var originalTimeout; + // Set by a spec whose comparer threads and polls must not outlive it, even + // when jasmine times it out. + var comparingWorker = null; + var specEnded = false; beforeEach(function () { originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000; + specEnded = false; }); afterEach(function () { + specEnded = true; + if (comparingWorker !== null) { + comparingWorker.terminate(); + comparingWorker = null; + Holder.stopComparing(5000); + } jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; Holder.clear(); }); @@ -97,19 +108,19 @@ describe("Runtime-bound Java->JS dispatch", function () { it("answers or drops calls other threads make while the worker terminates", function (done) { if (!multithreaded) { // Calls are posted to the worker's looper in this mode, not run under its lock. - done(); - return; + pending("needs android.enableMultithreadedJavascript"); } - var worker; + // Each wait well inside the spec timeout, so a hang fails with its cause. function waitFor(condition, what, then) { - var deadline = Date.now() + 10000; + var deadline = Date.now() + 5000; (function poll() { + if (specEnded) { + return; + } if (condition()) { then(); } else if (Date.now() > deadline) { - worker.terminate(); - Holder.stopComparing(10000); fail("timed out waiting for " + what); done(); } else { @@ -118,17 +129,23 @@ describe("Runtime-bound Java->JS dispatch", function () { })(); } - startWorker(function (started) { - worker = started; - Holder.startComparing("comparable", 4); + comparingWorker = startWorker(function (worker) { + if (specEnded) { + return; + } + // A comparer stops once it has had 20 dropped calls in a row: by then the worker + // has been torn down, and the calls it had in flight overlapped that teardown. + Holder.startComparing("comparable", 4, 20); waitFor(function () { return Holder.hasCompared(42); }, "a call answered by the live worker", function () { worker.terminate(); waitFor(function () { - return Holder.hasCompared(0); - }, "a call dropped after terminate()", function () { - var results = Array.prototype.slice.call(Holder.stopComparing(10000)); + return Holder.comparersFinished(); + }, "every comparer to see its calls dropped", function () { + comparingWorker = null; + var results = Array.prototype.slice.call(Holder.stopComparing(5000)); + expect(results).toContain(0); results.forEach(function (result) { expect([42, 0]).toContain(result); }); diff --git a/test-app/app/src/main/java/com/tns/tests/RuntimeBoundHolder.java b/test-app/app/src/main/java/com/tns/tests/RuntimeBoundHolder.java index 2682f1ba4..dfcfc49b9 100644 --- a/test-app/app/src/main/java/com/tns/tests/RuntimeBoundHolder.java +++ b/test-app/app/src/main/java/com/tns/tests/RuntimeBoundHolder.java @@ -57,20 +57,30 @@ public static boolean hasCompared(int result) { return compared.contains(result); } - // Keeps calling compare(key) from `threads` new threads until stopComparing(). - public static synchronized void startComparing(final String key, int threads) { + /* + * Keeps calling compareTo on objects[key] from `threads` new threads, each with a new + * object as the argument (so the call registers it from that thread), until + * stopComparing() or until the thread has had `zerosToStop` results of 0 in a row. + */ + public static synchronized void startComparing(final String key, int threads, final int zerosToStop) { compared.clear(); comparing = true; for (int i = 0; i < threads; i++) { Thread thread = new Thread(new Runnable() { @Override + @SuppressWarnings("unchecked") public void run() { - while (comparing) { + Comparable comparable = (Comparable) objects.get(key); + int zeros = 0; + while (comparing && zeros < zerosToStop) { + int result; try { - compared.add(compare(key)); + result = comparable.compareTo(new Object()); } catch (Throwable t) { - compared.add(THREW); + result = THREW; } + compared.add(result); + zeros = result == 0 ? zeros + 1 : 0; } } }, "RuntimeBoundHolder-comparer-" + i); @@ -79,6 +89,15 @@ public void run() { } } + public static synchronized boolean comparersFinished() { + for (Thread thread : comparers) { + if (thread.isAlive()) { + return false; + } + } + return true; + } + // Stops the comparing threads, waiting up to timeoutMillis for them; returns every // distinct result, with THREW for a throw and STUCK if a thread is still running. public static synchronized int[] stopComparing(long timeoutMillis) throws InterruptedException { From 3e9e73d2212aef8ce2351db9fc149e8e7ab8c366 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 20:28:00 -0300 Subject: [PATCH 7/9] docs(runtime): describe the multithreaded call's catch by what it checks The comment named terminate() cutting a call's JS short as the source of the exception, which nothing confirms; state only what the catch relies on: the owner stopped accepting work while the call ran. --- test-app/runtime/src/main/java/com/tns/Runtime.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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 95585dff0..f67c9e469 100644 --- a/test-app/runtime/src/main/java/com/tns/Runtime.java +++ b/test-app/runtime/src/main/java/com/tns/Runtime.java @@ -1676,9 +1676,9 @@ private Object dispatchCallJSMethodNative(final Object javaObject, int objectIdH objectIdHint != ObjectTable.NO_ID ? objectIdHint : objectTable.findId(javaObject), methodName, MethodNameIds.idOf(methodName), returnType, isConstructor, packagedArgs.count, packagedArgs.values, packagedArgs.refs, primitiveResult); ret = takePrimitiveResult(ret, returnType, primitiveResult); } catch (NativeScriptException e) { - // With multithreaded JS the owner can be terminated while the - // call runs on this thread, cutting its JS short; that is the - // same lifecycle race the other dead-owner paths drop. + // With multithreaded JS the owner can stop accepting work while + // the call runs on this thread; an exception from such a call is + // the same lifecycle race the other dead-owner paths drop. if (!isAcceptingWork()) { return discardCall(methodName, retType, "runtime id=" + getRuntimeId() + " (workerId=" + workerId + ") terminated during the call"); From a6162c86b1f4466187a365e674a56f73efdf2031 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 20:57:53 -0300 Subject: [PATCH 8/9] perf(runtime): let go of a runtime pin without the gates' lock A pin now holds its gate's address (gates are boxed in the map) and the gate's state is one atomic word: the pin count and a closed bit. Unpinning is a single atomic decrement; only the last pin of a closed gate takes the lock, to notify the waiting teardown. A call from another thread into a runtime takes the process-wide lock once, as before the gates. --- .../runtime/src/main/cpp/RuntimeGates.cpp | 62 ++++++++++--------- test-app/runtime/src/main/cpp/RuntimeGates.h | 20 +++--- 2 files changed, 45 insertions(+), 37 deletions(-) diff --git a/test-app/runtime/src/main/cpp/RuntimeGates.cpp b/test-app/runtime/src/main/cpp/RuntimeGates.cpp index a404f871c..8f2430641 100644 --- a/test-app/runtime/src/main/cpp/RuntimeGates.cpp +++ b/test-app/runtime/src/main/cpp/RuntimeGates.cpp @@ -1,7 +1,9 @@ #include "RuntimeGates.h" +#include #include #include +#include #include #include "Runtime.h" @@ -10,14 +12,20 @@ namespace tns { namespace RuntimeGates { -namespace { +// The pin count shifted left by one, and kClosed. Pins are taken and the gate +// closed under the gates' lock; a pin is let go of with one atomic decrement, +// after which the unpinning thread never touches the gate: a waiting teardown +// may free it as soon as it reads no pins. +constexpr uint32_t kClosed = 1; +constexpr uint32_t kPin = 2; struct Gate { Runtime* runtime = nullptr; - uint32_t pins = 0; - bool closed = false; + std::atomic state{0}; }; +namespace { + std::mutex& GatesMutex() { static auto* mutex = new std::mutex(); return *mutex; @@ -30,49 +38,47 @@ std::condition_variable& Unpinned() { // Never destroyed: process exit runs static destructors while other threads // may still be pinning. -robin_hood::unordered_map& Gates() { - static auto* gates = new robin_hood::unordered_map(); +// Boxed: a pin holds its gate's address across rehashes. +robin_hood::unordered_map>& Gates() { + static auto* gates = new robin_hood::unordered_map>(); return *gates; } } // namespace void Open(int id, Runtime* runtime) { + auto gate = std::make_unique(); + gate->runtime = runtime; std::lock_guard lock(GatesMutex()); - Gate gate; - gate.runtime = runtime; - Gates()[id] = gate; + Gates()[id] = std::move(gate); } -Runtime* TryPin(int id) { +Gate* TryPin(int id, Runtime** runtime) { std::lock_guard lock(GatesMutex()); auto it = Gates().find(id); - if (it == Gates().end() || it->second.closed) { + if (it == Gates().end() || (it->second->state.load(std::memory_order_relaxed) & kClosed) != 0) { return nullptr; } - it->second.pins++; - return it->second.runtime; + Gate* gate = it->second.get(); + gate->state.fetch_add(kPin, std::memory_order_relaxed); + *runtime = gate->runtime; + return gate; } int TryGenerateObjectId(int id) { std::lock_guard lock(GatesMutex()); auto it = Gates().find(id); - if (it == Gates().end() || it->second.closed) { + if (it == Gates().end() || (it->second->state.load(std::memory_order_relaxed) & kClosed) != 0) { return -1; } - return it->second.runtime->GenerateNewObjectId(nullptr, nullptr); + return it->second->runtime->GenerateNewObjectId(nullptr, nullptr); } -void Unpin(int id) { - bool last = false; - { +void Unpin(Gate* gate) { + // Release: what the pinned thread did happens before the teardown that reads no pins. + if (gate->state.fetch_sub(kPin, std::memory_order_acq_rel) == (kPin | kClosed)) { + // Taking the lock orders the notify after a waiter's check of the state. std::lock_guard lock(GatesMutex()); - auto it = Gates().find(id); - if (it != Gates().end()) { - last = --it->second.pins == 0 && it->second.closed; - } - } - if (last) { Unpinned().notify_all(); } } @@ -81,7 +87,7 @@ void Close(int id) { std::lock_guard lock(GatesMutex()); auto it = Gates().find(id); if (it != Gates().end()) { - it->second.closed = true; + it->second->state.fetch_or(kClosed, std::memory_order_relaxed); } } @@ -91,10 +97,10 @@ void WaitUntilUnpinnedAndRetire(int id) { if (it == Gates().end()) { return; } - it->second.closed = true; - Unpinned().wait(lock, [id]() { - auto found = Gates().find(id); - return found == Gates().end() || found->second.pins == 0; + Gate* gate = it->second.get(); + gate->state.fetch_or(kClosed, std::memory_order_relaxed); + Unpinned().wait(lock, [gate]() { + return gate->state.load(std::memory_order_acquire) == kClosed; }); Gates().erase(id); } diff --git a/test-app/runtime/src/main/cpp/RuntimeGates.h b/test-app/runtime/src/main/cpp/RuntimeGates.h index 84e051629..d557ce998 100644 --- a/test-app/runtime/src/main/cpp/RuntimeGates.h +++ b/test-app/runtime/src/main/cpp/RuntimeGates.h @@ -14,12 +14,14 @@ class Runtime; * runtime and its isolate stay allocated. A missing gate reads as closed. */ namespace RuntimeGates { +struct Gate; // Before the runtime can be found by id. void Open(int id, Runtime* runtime); -// The gate's runtime, pinned; null once the gate is closed, when the runtime -// may already be freed. -Runtime* TryPin(int id); -void Unpin(int id); +// The pinned gate, and its runtime in *runtime; null once the gate is closed, +// when the runtime may already be freed. +Gate* TryPin(int id, Runtime** runtime); +// Lock-free unless it lets go of the last pin of a closed gate. +void Unpin(Gate* gate); // A new object id from the runtime, or -1 once the gate is closed. Holds the // gates' lock rather than a pin: the runtime is freed only after its gate is // retired under that lock. @@ -35,10 +37,10 @@ void WaitUntilUnpinnedAndRetire(int id); // Locker is released first. class RuntimePin { public: - explicit RuntimePin(int id) : m_id(id), m_runtime(RuntimeGates::TryPin(id)) {} + explicit RuntimePin(int id) : m_gate(RuntimeGates::TryPin(id, &m_runtime)) {} ~RuntimePin() { - if (m_runtime != nullptr) { - RuntimeGates::Unpin(m_id); + if (m_gate != nullptr) { + RuntimeGates::Unpin(m_gate); } } RuntimePin(const RuntimePin&) = delete; @@ -47,8 +49,8 @@ class RuntimePin { Runtime* runtime() const { return m_runtime; } private: - int m_id; - Runtime* m_runtime; + Runtime* m_runtime = nullptr; + RuntimeGates::Gate* m_gate; }; } // namespace tns From 3f592ea001b386cb897533b5141a7e4b3ee801a2 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 14:39:18 -0300 Subject: [PATCH 9/9] test(runtime): cancel a timed-out spec's polls with a per-spec token The shared specEnded flag was reset by the next spec's beforeEach, so a poll left pending by a spec Jasmine timed out could resume and run assertions or call its old done() during the next spec. Each spec now captures its own token, which afterEach cancels; the terminated-worker poll checks it too. --- .../app/tests/testRuntimeBoundDispatch.js | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/test-app/app/src/main/assets/app/tests/testRuntimeBoundDispatch.js b/test-app/app/src/main/assets/app/tests/testRuntimeBoundDispatch.js index 78e6d2dcb..668028ba2 100644 --- a/test-app/app/src/main/assets/app/tests/testRuntimeBoundDispatch.js +++ b/test-app/app/src/main/assets/app/tests/testRuntimeBoundDispatch.js @@ -21,14 +21,16 @@ describe("Runtime-bound Java->JS dispatch", function () { // Set by a spec whose comparer threads and polls must not outlive it, even // when jasmine times it out. var comparingWorker = null; - var specEnded = false; + // One per spec: a callback checks the token its spec captured, so a poll left + // pending by a timed-out spec stays cancelled once the next spec starts. + var currentSpec = null; beforeEach(function () { originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000; - specEnded = false; + currentSpec = { ended: false }; }); afterEach(function () { - specEnded = true; + currentSpec.ended = true; if (comparingWorker !== null) { comparingWorker.terminate(); comparingWorker = null; @@ -76,11 +78,15 @@ describe("Runtime-bound Java->JS dispatch", function () { }); it("drops calls to an object whose worker has terminated", function (done) { + var spec = currentSpec; startWorker(function (worker) { worker.terminate(); var deadline = Date.now() + 10000; (function poll() { + if (spec.ended) { + return; + } // Until teardown completes a call may still be answered. var result; try { @@ -111,11 +117,12 @@ describe("Runtime-bound Java->JS dispatch", function () { pending("needs android.enableMultithreadedJavascript"); } + var spec = currentSpec; // Each wait well inside the spec timeout, so a hang fails with its cause. function waitFor(condition, what, then) { var deadline = Date.now() + 5000; (function poll() { - if (specEnded) { + if (spec.ended) { return; } if (condition()) { @@ -130,7 +137,7 @@ describe("Runtime-bound Java->JS dispatch", function () { } comparingWorker = startWorker(function (worker) { - if (specEnded) { + if (spec.ended) { return; } // A comparer stops once it has had 20 dropped calls in a row: by then the worker