Skip to content

Commit b96e522

Browse files
authored
fix(runtime): drop Java->JS calls into a worker that is shutting down (#2131)
### Description Fixes a native crash when a Java thread calls into a worker's JS object while the worker shuts down. Independent of the wrapper lifetime series (#2125–#2130); found while testing it. #### The bug With `enableMultithreadedJavascript`, a Java->JS call on a worker's object runs on the calling thread under the worker isolate's `Locker`. `callJSMethodNative` looked the runtime up by id, then waited for that `Locker`. If the worker was tearing down meanwhile (`DestroyRuntime` holds the `Locker`), the call got the `Locker` afterwards and read the context `DestroyRuntime` had just freed: `SIGSEGV` in `Runtime::GetContext()` under `Java_com_tns_Runtime_callJSMethodNative`, seen in `testRuntimeBoundDispatch` ("drops calls to an object whose worker has terminated"). Had it got past that, the worker would go on to `Isolate::Dispose()` and `delete runtime_` while the call still used them. `createJSInstanceNative` and `passExceptionToJsNative` take another thread's runtime the same way, and `generateNewObjectId` reads it unpinned when Java registers a call's arguments on the calling thread. #### The fix The model the iOS runtime uses for native callbacks into an isolate (`IsolateGates`/`IsolatePin`): - Each runtime has a gate keyed by its id (`RuntimeGates`; ids are never reused), opened in the `Runtime` constructor before the runtime can be found by id. - A Java->JS entry into **another thread's** runtime pins the gate before it waits for the `Locker`; the gate hands out the runtime, so finding and pinning it is one critical section. Once the `Locker` is granted the call checks a flag `DestroyRuntime` sets under that `Locker`. A thread entering its own runtime takes no pin, so the common paths (the main thread, a worker calling itself, every call when multithreaded JS is off) are unchanged. A cross-thread call takes the process-wide gate mutex once, to pin, as `main` took the runtime cache mutex once: unpinning is one atomic decrement on the gate's state (pin count and closed bit), and only the last pin of a closed gate takes the mutex, to wake the teardown. - The teardown unregisters the runtime first (as before), closes the gate last in `DestroyRuntime`, still under the `Locker`, and waits for in-flight pins to drain before `Isolate::Dispose()` (worker teardown and `UnwindFailedInit`). It holds no `Locker` while it waits, and a pinned thread lets go as soon as it gets the `Locker` and finds the runtime destroyed, so the wait cannot deadlock. `~Runtime` also waits and retires the gate, for an init that failed before the isolate existed. - `generateNewObjectId` for another thread's runtime bumps the id counter under the gate mutex, without the `Locker` (the counter needs none), and returns `ObjectTable.NO_ID` (-1) once the runtime is gone or closing; `ObjectTable` then registers nothing and the call is dropped. - A call whose pin is refused or whose runtime is gone is dropped and logged (`NativeScript discarding call to "…": runtime id=N is shutting down`), as calls to a terminated worker already are; an unknown runtime id is dropped too, where it used to throw "Cannot find runtime for id" into Java. `__runOnMainThread` keeps its own `IsolateGate` (#2108): it never pins, so it never delays a worker's disposal, and is dropped if the worker is closing. ### Testing - New spec in `testRuntimeBoundDispatch.js` (multithreaded JS only): four Java threads call into a worker's `Comparable` in a loop, each passing a new `Object` (so the foreign-thread `generateNewObjectId` path runs too); the spec waits for a call the live worker answered, terminates the worker, and waits for every caller to finish on its own after 20 dropped calls in a row, so the calls keep running through the teardown (each wait with a 5 s deadline). Every result must be the answer (42) or a dropped call (0), never a throw, a stuck thread or a crash; `afterEach` terminates the worker and stops the callers if the spec timed out. Uses a new `RuntimeBoundHolder` fixture whose joins have a deadline. Pending when multithreaded JS is off. - Full suite on an arm64 API 36.1 emulator: 1774 specs, 0 failures, with multithreaded JS on and off (the new spec pending when off). In the multithreaded run's logcat, 3 in-flight calls were dropped natively while overlapping `DestroyRuntime` and 1 `generateNewObjectId` was refused. - `ObjectTableTest.registersNothingWhenNoIdIsGiven` (JVM unit test). - The same spec on unfixed `main` crashed on its first run, with the trace above (`SIGSEGV` in `Runtime::GetContext()` under `callJSMethodNative`, on one of the calling threads). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Improved reliability when JavaScript calls overlap worker shutdown, reducing the risk of calls accessing a runtime as it is being disposed. * Calls made from other threads now return safe fallback results when the runtime is unavailable, rather than attempting to use it. * **Tests** * Added coverage for concurrent calls during worker termination, including checks for completed calls, dropped calls, and clean comparer shutdown. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
1 parent 9a514a7 commit b96e522

12 files changed

Lines changed: 456 additions & 24 deletions

File tree

‎test-app/app/src/main/assets/app/tests/testRuntimeBoundDispatch.js‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,24 @@ describe("Runtime-bound Java->JS dispatch", function () {
1818
}
1919

2020
var originalTimeout;
21+
// Set by a spec whose comparer threads and polls must not outlive it, even
22+
// when jasmine times it out.
23+
var comparingWorker = null;
24+
// One per spec: a callback checks the token its spec captured, so a poll left
25+
// pending by a timed-out spec stays cancelled once the next spec starts.
26+
var currentSpec = null;
2127
beforeEach(function () {
2228
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
2329
jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000;
30+
currentSpec = { ended: false };
2431
});
2532
afterEach(function () {
33+
currentSpec.ended = true;
34+
if (comparingWorker !== null) {
35+
comparingWorker.terminate();
36+
comparingWorker = null;
37+
Holder.stopComparing(5000);
38+
}
2639
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
2740
Holder.clear();
2841
});
@@ -65,11 +78,15 @@ describe("Runtime-bound Java->JS dispatch", function () {
6578
});
6679

6780
it("drops calls to an object whose worker has terminated", function (done) {
81+
var spec = currentSpec;
6882
startWorker(function (worker) {
6983
worker.terminate();
7084

7185
var deadline = Date.now() + 10000;
7286
(function poll() {
87+
if (spec.ended) {
88+
return;
89+
}
7390
// Until teardown completes a call may still be answered.
7491
var result;
7592
try {
@@ -92,6 +109,59 @@ describe("Runtime-bound Java->JS dispatch", function () {
92109
});
93110
});
94111

112+
// Callers on other threads take the worker's isolate while it terminates: each call is
113+
// answered or dropped, never run against an isolate that is being torn down.
114+
it("answers or drops calls other threads make while the worker terminates", function (done) {
115+
if (!multithreaded) {
116+
// Calls are posted to the worker's looper in this mode, not run under its lock.
117+
pending("needs android.enableMultithreadedJavascript");
118+
}
119+
120+
var spec = currentSpec;
121+
// Each wait well inside the spec timeout, so a hang fails with its cause.
122+
function waitFor(condition, what, then) {
123+
var deadline = Date.now() + 5000;
124+
(function poll() {
125+
if (spec.ended) {
126+
return;
127+
}
128+
if (condition()) {
129+
then();
130+
} else if (Date.now() > deadline) {
131+
fail("timed out waiting for " + what);
132+
done();
133+
} else {
134+
setTimeout(poll, 20);
135+
}
136+
})();
137+
}
138+
139+
comparingWorker = startWorker(function (worker) {
140+
if (spec.ended) {
141+
return;
142+
}
143+
// A comparer stops once it has had 20 dropped calls in a row: by then the worker
144+
// has been torn down, and the calls it had in flight overlapped that teardown.
145+
Holder.startComparing("comparable", 4, 20);
146+
waitFor(function () {
147+
return Holder.hasCompared(42);
148+
}, "a call answered by the live worker", function () {
149+
worker.terminate();
150+
waitFor(function () {
151+
return Holder.comparersFinished();
152+
}, "every comparer to see its calls dropped", function () {
153+
comparingWorker = null;
154+
var results = Array.prototype.slice.call(Holder.stopComparing(5000));
155+
expect(results).toContain(0);
156+
results.forEach(function (result) {
157+
expect([42, 0]).toContain(result);
158+
});
159+
done();
160+
});
161+
});
162+
});
163+
});
164+
95165
it("releases a caller whose queued call is discarded when the worker closes", function (done) {
96166
if (multithreaded) {
97167
// Calls are never queued on the worker's looper in this mode.

‎test-app/app/src/main/java/com/tns/tests/RuntimeBoundHolder.java‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
package com.tns.tests;
22

3+
import java.util.ArrayList;
4+
import java.util.List;
5+
import java.util.Set;
36
import java.util.concurrent.ConcurrentHashMap;
47

58
/**
@@ -40,4 +43,79 @@ public void run() {
4043
public static int compare(String key) {
4144
return ((Comparable<Object>) objects.get(key)).compareTo("");
4245
}
46+
47+
// Results stopComparing reports for a comparison that threw, and for a comparer
48+
// thread still running at its deadline.
49+
public static final int THREW = Integer.MIN_VALUE;
50+
public static final int STUCK = Integer.MAX_VALUE;
51+
52+
private static final List<Thread> comparers = new ArrayList<>();
53+
private static final Set<Integer> compared = ConcurrentHashMap.newKeySet();
54+
private static volatile boolean comparing;
55+
56+
public static boolean hasCompared(int result) {
57+
return compared.contains(result);
58+
}
59+
60+
/*
61+
* Keeps calling compareTo on objects[key] from `threads` new threads, each with a new
62+
* object as the argument (so the call registers it from that thread), until
63+
* stopComparing() or until the thread has had `zerosToStop` results of 0 in a row.
64+
*/
65+
public static synchronized void startComparing(final String key, int threads, final int zerosToStop) {
66+
compared.clear();
67+
comparing = true;
68+
for (int i = 0; i < threads; i++) {
69+
Thread thread = new Thread(new Runnable() {
70+
@Override
71+
@SuppressWarnings("unchecked")
72+
public void run() {
73+
Comparable<Object> comparable = (Comparable<Object>) objects.get(key);
74+
int zeros = 0;
75+
while (comparing && zeros < zerosToStop) {
76+
int result;
77+
try {
78+
result = comparable.compareTo(new Object());
79+
} catch (Throwable t) {
80+
result = THREW;
81+
}
82+
compared.add(result);
83+
zeros = result == 0 ? zeros + 1 : 0;
84+
}
85+
}
86+
}, "RuntimeBoundHolder-comparer-" + i);
87+
comparers.add(thread);
88+
thread.start();
89+
}
90+
}
91+
92+
public static synchronized boolean comparersFinished() {
93+
for (Thread thread : comparers) {
94+
if (thread.isAlive()) {
95+
return false;
96+
}
97+
}
98+
return true;
99+
}
100+
101+
// Stops the comparing threads, waiting up to timeoutMillis for them; returns every
102+
// distinct result, with THREW for a throw and STUCK if a thread is still running.
103+
public static synchronized int[] stopComparing(long timeoutMillis) throws InterruptedException {
104+
comparing = false;
105+
long deadline = System.currentTimeMillis() + timeoutMillis;
106+
for (Thread thread : comparers) {
107+
thread.join(Math.max(1, deadline - System.currentTimeMillis()));
108+
if (thread.isAlive()) {
109+
compared.add(STUCK);
110+
}
111+
}
112+
comparers.clear();
113+
// A thread still running can add results while this copies them.
114+
Integer[] snapshot = compared.toArray(new Integer[0]);
115+
int[] results = new int[snapshot.length];
116+
for (int i = 0; i < snapshot.length; i++) {
117+
results[i] = snapshot[i];
118+
}
119+
return results;
120+
}
43121
}

‎test-app/runtime/CMakeLists.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,7 @@ add_library(
221221
src/main/cpp/Profiler.cpp
222222
src/main/cpp/ReadWriteLock.cpp
223223
src/main/cpp/Runtime.cpp
224+
src/main/cpp/RuntimeGates.cpp
224225
src/main/cpp/RuntimeState.cpp
225226
src/main/cpp/SimpleAllocator.cpp
226227
src/main/cpp/SimpleProfiler.cpp

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

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#include "Runtime.h"
2+
#include "RuntimeGates.h"
23

34
#include <console/Console.h>
45

@@ -137,6 +138,7 @@ Runtime::Runtime(JNIEnv* env, jobject runtime, int id)
137138
m_runtime = env->NewGlobalRef(runtime);
138139
m_objectManager = new ObjectManager(m_runtime);
139140
m_state = std::make_unique<RuntimeState>();
141+
RuntimeGates::Open(id, this);
140142
{
141143
std::lock_guard<std::mutex> lock(s_runtimeCacheMutex);
142144
s_id2RuntimeCache.emplace(id, this);
@@ -294,10 +296,13 @@ Runtime::~Runtime() {
294296
}
295297

296298
/*
297-
* Idempotent backstop for the erase DestroyRuntime does: a bootstrap that
298-
* failed before PrepareV8Runtime ran never reached it. The isolate entry is
299-
* matched on value so it cannot evict a new runtime that reused the pointer.
299+
* Idempotent backstops for the gate retirement and the erase the teardown
300+
* does: a bootstrap that failed before PrepareV8Runtime ran never reached
301+
* them. The gate goes first, while every member a pinned thread may read is
302+
* still alive. The isolate entry is matched on value so it cannot evict a
303+
* new runtime that reused the pointer.
300304
*/
305+
RuntimeGates::WaitUntilUnpinnedAndRetire(m_id);
301306
{
302307
std::lock_guard<std::mutex> lock(s_runtimeCacheMutex);
303308
s_id2RuntimeCache.erase(m_id);
@@ -895,16 +900,18 @@ void Runtime::UnwindFailedInit() {
895900
/*
896901
* Reuses the two teardown windows rather than adding a third cleanup path.
897902
* Every step DestroyRuntime takes is null-tolerant, which is what makes it
898-
* usable on a runtime that never finished building; the Locker is reentrant,
899-
* so it does not matter whether the failure unwound past the one
900-
* PrepareV8Runtime holds.
903+
* usable on a runtime that never finished building. The caller must not
904+
* hold the isolate's Locker: the wait for pins below would deadlock against
905+
* a pinned thread waiting for it.
901906
*/
902907
if (m_isolate != nullptr) {
908+
NS_DCHECK(!v8::Locker::IsLocked(m_isolate));
903909
{
904910
v8::Locker locker(m_isolate);
905911
Isolate::Scope isolateScope(m_isolate);
906912
DestroyRuntime();
907913
}
914+
RuntimeGates::WaitUntilUnpinnedAndRetire(m_id);
908915
m_isolate->Dispose();
909916
m_isolate = nullptr;
910917
}
@@ -1279,6 +1286,10 @@ double Runtime::PerformanceNowMillis() {
12791286

12801287
void Runtime::DestroyRuntime() {
12811288
NS_CHECK(std::this_thread::get_id() == m_ownerThread);
1289+
NS_DCHECK(v8::Locker::IsLocked(m_isolate));
1290+
// A thread that pinned this runtime and then waited for the Locker drops
1291+
// its call when it finds this set.
1292+
m_destroyed = true;
12821293
CrashBreadcrumbs::UnregisterRuntime(m_id);
12831294
{
12841295
std::lock_guard<std::mutex> lock(s_runtimeCacheMutex);
@@ -1389,6 +1400,10 @@ void Runtime::DestroyRuntime() {
13891400
if (m_state != nullptr) {
13901401
m_state->Clear();
13911402
}
1403+
1404+
// New pins are refused from here on; the isolate is disposed only once the
1405+
// threads already pinned have let go.
1406+
RuntimeGates::Close(m_id);
13921407
}
13931408

13941409
Local<Context> Runtime::GetContext() {

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,10 @@ class Runtime {
209209
jboolean PassExceptionToJsNative(JNIEnv* env, jobject obj, jthrowable exception, jstring message, jstring fullStackTrace, jstring jsStackTrace, jboolean isDiscarded);
210210
void DestroyRuntime();
211211

212+
// Read under the isolate's Locker, which DestroyRuntime holds when it
213+
// sets it.
214+
bool IsDestroyed() const { return m_destroyed; }
215+
212216
void Lock();
213217
void Unlock();
214218

@@ -394,6 +398,7 @@ class Runtime {
394398

395399
// Decided by ElectMainRuntime, before anything can read it.
396400
bool m_isMainThread = false;
401+
bool m_destroyed = false;
397402

398403
// This isolate's performance time origin, captured at isolate
399404
// creation: the monotonic clock reading now() is relative to, and the

0 commit comments

Comments
 (0)