Skip to content

Commit fba87e0

Browse files
committed
fix(runtime): canary review fixes
- Remove the canary GC epilogue callback only if it was added: a bootstrap that fails before ObjectManager::Init unwinds through ReleaseAllRegistered. - Resolve a fresh Java->JS argument again under the lock in canary mode: a settle may have released its id after another thread wrapped and dropped the object. - Send every recorded id to the weakening batch, and treat a failed batch's ids as weak: Java may have weakened some before failing. - Stop AdoptCanary once its record is gone. - Keep the lifetime watcher alive across a failure to report. - Stop CallJSMethodNative overwriting a constructed instance's class with a local ref of com.tns.Runtime's class; registration already records the instance's class. - Docs: where states are let go of, what weakened counts, which wrappers refuse freeze, and <unknown> class names.
1 parent 289e995 commit fba87e0

6 files changed

Lines changed: 68 additions & 41 deletions

File tree

‎docs/ns-builtin-modules.md‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ wrapper.
104104
| `setConfig(key, value)` | Sets a runtime config key. Throws `TypeError` on an unknown key, an invalid value, or (for process-wide keys) when called from a worker isolate. |
105105
| `getConfig(key)` | Returns the current value of a config key. Throws `TypeError` on an unknown key. Readable from any isolate. |
106106
| `getWrapperLifetimeStats()` | Wrapper lifetime counters for the calling isolate (see [Wrapper lifetime](#wrapper-lifetime)). A fresh object on every call. |
107-
| `getWrapperClassCounts()` | Per Java class name, the calling isolate's live `wrappers`, the `canaries` among them and the canary `states` (see [Wrapper lifetime](#wrapper-lifetime)). |
107+
| `getWrapperClassCounts()` | Per Java class name (`<unknown>` for a link whose class was never recorded), the calling isolate's live `wrappers`, the `canaries` among them and the canary `states` (see [Wrapper lifetime](#wrapper-lifetime)). |
108108
| `escapeException(x)` | Returns an `Error` branded so that, when it is thrown back across a native callback boundary, the native caller receives the original native exception `x` carries rather than the runtime's wrapper exception. Idempotent: a branded error is returned unchanged. Throws `TypeError` when called with no argument. The global `interop.escapeException` is this same function (see [Legacy globals](#legacy-globals)). |
109109

110110
*Platform note (Android):* the original exception is the Java throwable `x`
@@ -192,8 +192,9 @@ every build on cold paths only:
192192
| `canaryRebuilds` | `"canary"` only: canaries built anew for a JS-extended instance whose previous canary died while Java kept the object |
193193

194194
In `"canary"` mode, `weakened` counts objects held weakly because their
195-
canary died while they had JS state, and `collected` counts canaries whose
196-
object had none, which Java no longer holds for JS.
195+
canary died while they had a record (JS state, or a JS-extended instance),
196+
and `collected` counts canaries whose object had none, which Java no longer
197+
holds for JS.
197198

198199
`"canary"` is the resurrection-free model the iOS runtime and the Node-API
199200
runtimes share. A wrapper in scope is a canary: a phantom-weak JS object that
@@ -210,7 +211,9 @@ dies with its JS references.
210211
- **Java's side.** While a canary is alive, Java holds its object strongly.
211212
When it dies, Java holds an object with state weakly and releases any other.
212213
A thread watching those weak references tells the runtime when Java collects
213-
an object, and its state is let go of on the runtime's thread.
214+
an object, and its state is let go of under the isolate's lock: on the
215+
runtime's thread, or on a thread calling in under
216+
`enableMultithreadedJavascript`.
214217
- **JS-extended instances** (`extend()`, interface implementations, Java
215218
objects of those classes) keep a record from the moment they are registered,
216219
whether or not JS wrote to them, so that Java can still call into JS after
@@ -229,7 +232,8 @@ a `WeakMap` value naming it) keeps the object alive, through Java, for as long
229232
as the cycle lasts; break such back references with a `WeakRef`.
230233
`getWrapperClassCounts()` shows which classes grow across a repeated journey.
231234
Other limits, as on iOS: `Object.freeze`, `seal` and `preventExtensions` throw
232-
on a canary; index-keyed properties are not mirrored and die with the canary;
235+
on a canary, and on any wrapper built from a template that carries the write
236+
handler (every wrapper under `"all"`, released ones included); index-keyed properties are not mirrored and die with the canary;
233237
a write through an object whose prototype is a canary lands on that object.
234238
A canary built after another died is a new JS object, which `===` cannot tell
235239
because nothing kept the old one, but which keys `WeakMap`, `WeakSet`,

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#include "ArgConverter.h"
2+
#include "WrapperLifetimeCanary.h"
23
#include "JniLocalRef.h"
34
#include "ObjectManager.h"
45
#include "Util.h"
@@ -150,7 +151,9 @@ void ArgConverter::ConvertJavaArgsToJsArgs(Isolate* isolate, JNIEnv* env, const
150151
// hint Java read without the isolate lock, or -1) and the class index above.
151152
auto hintedObjectID = static_cast<jint>(bits);
152153
auto classIndex = static_cast<int>((bits >> 32) & 0x7fffffff);
153-
if ((bits & JavaCallArgs::FreshArg) != 0 &&
154+
// In canary mode a settle may have released a fresh id whose canary another
155+
// thread made and dropped before this call took the lock: resolve it again.
156+
if ((bits & JavaCallArgs::FreshArg) != 0 && !WrapperLifetimeCanary::Enabled() &&
154157
!objectManager->HasJsObject(hintedObjectID)) {
155158
JniLocalRef arg(env->GetObjectArrayElement(args.refs, i));
156159
jsArg = objectManager->CreateJSWrapper(hintedObjectID, classIndex, arg);

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

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,7 @@ void ObjectManager::Init(Isolate* isolate) {
118118
canaryTemplate, WrapperLifetimeCanary::TemplateKind::kExtended);
119119
m_canaryTemplate.Reset(isolate, canaryTemplate);
120120
isolate->AddGCEpilogueCallback(CanaryGCEpilogue, this);
121+
m_canaryEpilogueAdded = true;
121122
}
122123
}
123124

@@ -591,7 +592,9 @@ void ObjectManager::AdoptCanary(const Local<Object>& object, uint32_t javaObject
591592
m_canaryRecords.emplace(javaObjectID, std::move(created));
592593
return;
593594
}
594-
EnsureJavaStrong(javaObjectID, record);
595+
if (!EnsureJavaStrong(javaObjectID, record)) {
596+
return;
597+
}
595598
if (!record->state.IsEmpty()) {
596599
auto context = m_isolate->GetCurrentContext();
597600
if (context.IsEmpty()) {
@@ -774,10 +777,10 @@ bool ObjectManager::FlushCanaryDeaths() {
774777
// A new canary was built since: the Java side stays strong.
775778
continue;
776779
}
777-
CanaryRecord* record = FindCanaryRecord(id);
778-
if (record == nullptr) {
780+
// Weakening is idempotent: an id a failed batch already weakened is sent again.
781+
if (FindCanaryRecord(id) == nullptr) {
779782
release.push_back(id);
780-
} else if (!record->javaWeak) {
783+
} else {
781784
weaken.push_back(id);
782785
}
783786
}
@@ -814,6 +817,13 @@ bool ObjectManager::FlushCanaryDeaths() {
814817
raw->ExceptionDescribe();
815818
raw->ExceptionClear();
816819
}
820+
// Java may have weakened some of them before failing: a canary rebuilt
821+
// meanwhile must make its object strong again.
822+
for (jint id : weaken) {
823+
if (CanaryRecord* record = FindCanaryRecord(id)) {
824+
record->javaWeak = true;
825+
}
826+
}
817827
m_pendingCanaryDeaths.insert(m_pendingCanaryDeaths.end(), deaths.begin(), deaths.end());
818828
return false;
819829
}
@@ -1161,8 +1171,11 @@ void ObjectManager::ReleaseAllRegistered() {
11611171
m_pendingWeaken.clear();
11621172
m_pendingCheck.clear();
11631173
m_pendingCanaryDeaths.clear();
1164-
if (WrapperLifetimeCanary::Enabled()) {
1174+
if (m_canaryEpilogueAdded) {
11651175
m_isolate->RemoveGCEpilogueCallback(CanaryGCEpilogue, this);
1176+
m_canaryEpilogueAdded = false;
1177+
}
1178+
if (WrapperLifetimeCanary::Enabled()) {
11661179
if (m_deathInboxOpen) {
11671180
WrapperLifetimeCanary::CloseDeathInbox(m_deathInboxRuntimeId);
11681181
m_deathInboxOpen = false;

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,9 @@ class ObjectManager {
177177
// The state object of a canary, created on its first write.
178178
bool CanaryStateForWrite(const v8::Local<v8::Object>& holder, v8::Local<v8::Object>* out);
179179
void CountCanaryWrite() { m_lifetimeStats.canaryInterceptedWrites++; }
180-
// Lets go of the state of objects Java reported collected. Runtime thread.
180+
// Lets go of the state of objects Java reported collected. Under the
181+
// isolate's Locker: the runtime's thread, or a thread calling in under
182+
// enableMultithreadedJavascript.
181183
void ReleaseCollectedCanaryStates();
182184

183185
struct ClassCounts {
@@ -331,6 +333,7 @@ class ObjectManager {
331333
// Template of a canary rebuilt for a JS-extended instance.
332334
v8::Persistent<v8::ObjectTemplate> m_canaryTemplate;
333335
bool m_deathInboxOpen = false;
336+
bool m_canaryEpilogueAdded = false;
334337
int m_deathInboxRuntimeId = -1;
335338

336339
void JSObjectFinalizer(v8::Isolate* isolate,

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

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -662,13 +662,6 @@ jobject Runtime::CallJSMethodNative(JNIEnv* _env, jobject obj,
662662
throw NativeScriptException(ss.str());
663663
}
664664

665-
if (isConstructor) {
666-
DEBUG_WRITE(
667-
"CallJSMethodNative: Updating linked instance with its real class");
668-
jclass instanceClass = env.GetObjectClass(obj);
669-
m_objectManager->SetJavaClass(jsObject, instanceClass);
670-
}
671-
672665
DEBUG_WRITE("CallJSMethodNative called jsObject=%d",
673666
jsObject->GetIdentityHash());
674667

‎test-app/runtime/src/main/java/com/tns/WrapperLifetimeWatcher.java‎

Lines changed: 33 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -38,30 +38,41 @@ private static void run() {
3838
} catch (InterruptedException e) {
3939
return;
4040
}
41-
// Every reference collected so far, grouped by consecutive runtime.
42-
int runtimeId = -1;
43-
int count = 0;
44-
for (; next != null; next = watched.poll()) {
45-
if (!(next instanceof ObjectTable.WatchedRef)) {
46-
continue;
47-
}
48-
ObjectTable.WatchedRef ref = (ObjectTable.WatchedRef) next;
49-
if (ref.runtimeId != runtimeId) {
50-
notify(runtimeId, ids, count);
51-
runtimeId = ref.runtimeId;
52-
count = 0;
53-
}
54-
Runtime runtime = Runtime.runtimeForId(ref.runtimeId);
55-
if (runtime == null || !runtime.removeWatched(ref)) {
56-
continue;
57-
}
58-
if (count == ids.length) {
59-
ids = Arrays.copyOf(ids, count * 2);
60-
}
61-
ids[count++] = ref.id;
41+
try {
42+
ids = drain(watched, next, ids);
43+
} catch (Throwable t) {
44+
// The only watcher: losing it would leak every later collected object's state.
45+
Log.w("JS", "Wrapper lifetime watcher failed to report collected objects", t);
46+
}
47+
}
48+
}
49+
50+
// Reports next and every reference already queued behind it; returns the id buffer to reuse.
51+
private static int[] drain(ReferenceQueue<Object> watched, Reference<?> next, int[] ids) {
52+
// Every reference collected so far, grouped by consecutive runtime.
53+
int runtimeId = -1;
54+
int count = 0;
55+
for (; next != null; next = watched.poll()) {
56+
if (!(next instanceof ObjectTable.WatchedRef)) {
57+
continue;
58+
}
59+
ObjectTable.WatchedRef ref = (ObjectTable.WatchedRef) next;
60+
if (ref.runtimeId != runtimeId) {
61+
notify(runtimeId, ids, count);
62+
runtimeId = ref.runtimeId;
63+
count = 0;
64+
}
65+
Runtime runtime = Runtime.runtimeForId(ref.runtimeId);
66+
if (runtime == null || !runtime.removeWatched(ref)) {
67+
continue;
68+
}
69+
if (count == ids.length) {
70+
ids = Arrays.copyOf(ids, count * 2);
6271
}
63-
notify(runtimeId, ids, count);
72+
ids[count++] = ref.id;
6473
}
74+
notify(runtimeId, ids, count);
75+
return ids;
6576
}
6677

6778
private static void notify(int runtimeId, int[] ids, int count) {

0 commit comments

Comments
 (0)