Skip to content

Commit 2baff33

Browse files
committed
Merge branch 'feat/wrapper-lifetime-canary' into feat/wrapper-lifetime-weak-collections
2 parents 5235c18 + 742e918 commit 2baff33

7 files changed

Lines changed: 79 additions & 16 deletions

File tree

‎docs/ns-builtin-modules.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,7 @@ every build on cold paths only:
185185
| `weakened` | Java objects held weakly because their wrapper was collected |
186186
| `collected` | wrappers released because Java had collected their object |
187187
| `releasedExplicitly` | links released through `__releaseNativeCounterpart` |
188-
| `releasedAccesses` | times JS used a wrapper whose Java object Java had already collected, or called a method on a wrapper whose link was released |
188+
| `releasedAccesses` | lookups of the Java object of a wrapper whose link was released or whose Java object Java had already collected: calling its methods, using its fields or passing it to Java. Resolving an overloaded method looks its arguments up too, so one call can count more than once |
189189
| `canaryStates` | `"canary"` only: state objects created to hold JS properties |
190190
| `canaryNativeDeaths` | `"canary"` only: state objects let go of because Java collected their object |
191191
| `canaryInterceptedWrites` | `"canary"` only: writes to canaries the write handler saw. Other wrappers have no handler |

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

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,45 @@ describe("Wrapper lifetime", function () {
5454
released.hashCode();
5555
}).toThrowError(/no longer has available Java instance counterpart/);
5656
expect(runtime.getWrapperLifetimeStats().releasedAccesses).toBe(before.releasedAccesses + 1);
57+
58+
// Not a wrapper at all: not a released access.
59+
var hashCode = new java.lang.Object().hashCode;
60+
[{}, new ArrayBuffer(8), new Int8Array(8)].forEach(function (receiver) {
61+
expect(function () {
62+
hashCode.call(receiver);
63+
}).toThrow();
64+
});
65+
expect(runtime.getWrapperLifetimeStats().releasedAccesses).toBe(before.releasedAccesses + 1);
66+
});
67+
68+
it("counts field accesses on, and arguments of, a released wrapper", function () {
69+
var point = new android.graphics.Point(1, 2);
70+
__releaseNativeCounterpart(point);
71+
var before = runtime.getWrapperLifetimeStats().releasedAccesses;
72+
expect(function () {
73+
return point.x;
74+
}).toThrowError(/no corresponding Java object/);
75+
expect(runtime.getWrapperLifetimeStats().releasedAccesses).toBe(before + 1);
76+
77+
// Resolving an overload looks the argument up too, so one call can count more than once.
78+
expect(function () {
79+
java.lang.String.valueOf(point);
80+
}).toThrow();
81+
expect(runtime.getWrapperLifetimeStats().releasedAccesses).toBeGreaterThan(before + 1);
82+
});
83+
84+
it("reports counters as own properties whatever Object.prototype defines", function () {
85+
Object.defineProperty(Object.prototype, "collected", {
86+
set: function () {},
87+
configurable: true
88+
});
89+
try {
90+
var stats = runtime.getWrapperLifetimeStats();
91+
expect(Object.prototype.hasOwnProperty.call(stats, "collected")).toBe(true);
92+
expect(typeof stats.collected).toBe("number");
93+
} finally {
94+
delete Object.prototype.collected;
95+
}
5796
});
5897

5998
if (mode !== "resurrecting") {

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -307,7 +307,7 @@ describe("Wrapper lifetime modes", function () {
307307
eventually(function () {
308308
return ref.get() === null && (!canary || stats().canaryNativeDeaths > deaths);
309309
}, done, "the Java object or its state stayed alive");
310-
});
310+
}, 20000);
311311

312312
// The contract: the state is rooted until Java collects the object, so state that
313313
// references its own object keeps it alive. Break such back references with a WeakRef.

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

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -533,7 +533,6 @@ void CallbackHandlers::CallJavaMethod(const Local<Object> &caller, const string
533533
ss << "No java object found on which to call \"" << methodName
534534
<< "\" method. It is possible your Javascript object is not linked with the corresponding Java class. Try passing context(this) to the constructor function.";
535535
} else {
536-
objectManager->CountReleasedAccess();
537536
ss << "Failed calling " << methodName << " on a " << className
538537
<< " instance. The JavaScript instance no longer has available Java instance counterpart.";
539538
}

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

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -171,8 +171,8 @@ void GetWrapperLifetimeStatsCallback(const FunctionCallbackInfo<Value>& info) {
171171
Local<Context> context = isolate->GetCurrentContext();
172172
Local<Object> result = Object::New(isolate);
173173
auto set = [&](const char* name, uint64_t value) {
174-
(void) result->Set(context, ArgConverter::ConvertToV8String(isolate, name),
175-
Number::New(isolate, static_cast<double>(value)));
174+
(void) result->CreateDataProperty(context, ArgConverter::ConvertToV8String(isolate, name),
175+
Number::New(isolate, static_cast<double>(value)));
176176
};
177177
set("resurrections", stats.resurrections);
178178
set("weakened", stats.weakened);
@@ -197,13 +197,14 @@ void GetWrapperClassCountsCallback(const FunctionCallbackInfo<Value>& info) {
197197
for (const auto& [name, counts] : objectManager->GetWrapperClassCounts()) {
198198
Local<Object> entry = Object::New(isolate);
199199
auto set = [&](const char* key, uint64_t value) {
200-
(void) entry->Set(context, ArgConverter::ConvertToV8String(isolate, key),
201-
Number::New(isolate, static_cast<double>(value)));
200+
(void) entry->CreateDataProperty(context, ArgConverter::ConvertToV8String(isolate, key),
201+
Number::New(isolate, static_cast<double>(value)));
202202
};
203203
set("wrappers", counts.wrappers);
204204
set("canaries", counts.canaries);
205205
set("states", counts.states);
206-
(void) result->Set(context, ArgConverter::ConvertToV8String(isolate, name), entry);
206+
// A class name such as "__proto__" must stay an own property.
207+
(void) result->CreateDataProperty(context, ArgConverter::ConvertToV8String(isolate, name), entry);
207208
}
208209
info.GetReturnValue().Set(result);
209210
}

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

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,9 @@ JniLocalRef ObjectManager::GetJavaObjectByJsObject(
128128
const Local<Object>& object) {
129129
JSInstanceInfo* jsInstanceInfo = GetJSInstanceInfo(object);
130130
if (jsInstanceInfo == nullptr) {
131+
if (IsReleasedWrapper(object)) {
132+
m_lifetimeStats.releasedAccesses++;
133+
}
131134
return JniLocalRef();
132135
}
133136
try {
@@ -313,6 +316,25 @@ bool ObjectManager::IsJsRuntimeObject(const v8::Local<v8::Object>& object) {
313316
internalFieldCount == V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT;
314317
}
315318

319+
void ObjectManager::MarkLinkReleased(const Local<Object>& object) {
320+
object->SetInternalField(static_cast<int>(MetadataNodeKeys::JsInfo), Null(m_isolate));
321+
}
322+
323+
bool ObjectManager::IsReleasedWrapper(const Local<Object>& object) {
324+
auto target = UnwrapProxy(object);
325+
if (!target->IsObject() || !HasMetadataField(target.As<Object>())) {
326+
return false;
327+
}
328+
auto jsInfoIdx = static_cast<int>(MetadataNodeKeys::JsInfo);
329+
auto field = target.As<Object>()->GetInternalField(jsInfoIdx).As<Value>();
330+
if (!field->IsUndefined()) {
331+
return field->IsNull();
332+
}
333+
auto prototype = target.As<Object>()->GetPrototype();
334+
return prototype->IsObject() && HasMetadataField(prototype.As<Object>()) &&
335+
prototype.As<Object>()->GetInternalField(jsInfoIdx).As<Value>()->IsNull();
336+
}
337+
316338
jweak ObjectManager::GetJavaObjectByID(uint32_t javaObjectID) {
317339
jweak obj = m_cache(javaObjectID);
318340

@@ -1267,8 +1289,7 @@ void ObjectManager::ReleaseCollectedWrapper(int javaObjectID) {
12671289
m_lifetimeStats.collected++;
12681290
Persistent<Object>* po = state->target;
12691291
if (state->linked) {
1270-
auto object = po->Get(m_isolate);
1271-
object->SetInternalField(static_cast<int>(MetadataNodeKeys::JsInfo), Undefined(m_isolate));
1292+
MarkLinkReleased(po->Get(m_isolate));
12721293
}
12731294
m_idToObject.Erase(javaObjectID);
12741295
po->Reset();
@@ -1416,7 +1437,6 @@ void ObjectManager::ReleaseNativeCounterpart(v8::Local<v8::Object>& object) {
14161437
throw NativeScriptException("Trying to release a non native object!");
14171438
}
14181439

1419-
auto jsInfoIdx = static_cast<int>(MetadataNodeKeys::JsInfo);
14201440
auto javaObjectID = LinkedIdOf(owner);
14211441

14221442
JEnv env;
@@ -1434,7 +1454,7 @@ void ObjectManager::ReleaseNativeCounterpart(v8::Local<v8::Object>& object) {
14341454
state->linked = false;
14351455
}
14361456

1437-
owner->SetInternalField(jsInfoIdx, Undefined(m_isolate));
1457+
MarkLinkReleased(owner);
14381458

14391459
// Every alias of the link is cleared with it.
14401460
Local<Value> aliasesValue;
@@ -1446,7 +1466,7 @@ void ObjectManager::ReleaseNativeCounterpart(v8::Local<v8::Object>& object) {
14461466
Local<Value> alias;
14471467
if (aliases->Get(context, i).ToLocal(&alias) && alias->IsObject() &&
14481468
IsJsRuntimeObject(alias.As<Object>())) {
1449-
alias.As<Object>()->SetInternalField(jsInfoIdx, Undefined(m_isolate));
1469+
MarkLinkReleased(alias.As<Object>());
14501470
}
14511471
}
14521472
}

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

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,10 @@ class ObjectManager {
137137
return LinkedIdOf(object) != -1;
138138
}
139139

140+
// Whether object, seen through any Proxy and the TypeScript layout, is a wrapper whose
141+
// link was released or whose Java object was collected.
142+
static bool IsReleasedWrapper(const v8::Local<v8::Object>& object);
143+
140144
/*
141145
* The innermost target of a Proxy chain; any other value is returned as is.
142146
* A revoked Proxy anywhere in the chain yields null. Internal fields and
@@ -166,9 +170,6 @@ class ObjectManager {
166170

167171
const WrapperLifetimeStats& GetLifetimeStats() const { return m_lifetimeStats; }
168172

169-
// JS called a method on a wrapper whose link is gone.
170-
void CountReleasedAccess() { m_lifetimeStats.releasedAccesses++; }
171-
172173
// Canary mode (WrapperLifetimeCanary), for its write handlers. holder is a
173174
// live canary: an object this manager linked as one, not yet released.
174175
bool IsCanary(const v8::Local<v8::Object>& holder);
@@ -368,6 +369,9 @@ class ObjectManager {
368369

369370
void ReleaseCollectedWrapper(int javaObjectID);
370371

372+
// A link that is gone leaves null in JsInfo; a link never made leaves undefined.
373+
void MarkLinkReleased(const v8::Local<v8::Object>& object);
374+
371375
// Drops id's registrations on both sides if Java has collected its object.
372376
bool ReleaseIfCollected(int javaObjectID);
373377

0 commit comments

Comments
 (0)