Skip to content

Commit 45e2a4d

Browse files
committed
Merge branch 'feat/wrapper-lifetime-weak-collections' into feat/wrapper-lifetime-leak-probe
2 parents 20dcb38 + 2baff33 commit 45e2a4d

8 files changed

Lines changed: 81 additions & 18 deletions

File tree

‎docs/ns-builtin-modules.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ every build on cold paths only:
186186
| `weakened` | Java objects held weakly because their wrapper was collected |
187187
| `collected` | wrappers released because Java had collected their object |
188188
| `releasedExplicitly` | links released through `__releaseNativeCounterpart` |
189-
| `releasedAccesses` | times JS used a wrapper whose Java object Java had already collected, or called a method on a wrapper whose link was released |
189+
| `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 |
190190
| `canaryStates` | `"canary"` only: state objects created to hold JS properties |
191191
| `canaryNativeDeaths` | `"canary"` only: state objects let go of because Java collected their object |
192192
| `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/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ describe("Weak collections of Java objects", function () {
154154
eventually(function () {
155155
return ref.deref() === undefined;
156156
}, done, "the WeakRef still dereferences");
157-
});
157+
}, 20000);
158158

159159
it("runs a FinalizationRegistry callback once Java collected the object", function (done) {
160160
var cleaned = false;
@@ -167,7 +167,7 @@ describe("Weak collections of Java objects", function () {
167167
eventually(function () {
168168
return cleaned;
169169
}, done, "the cleanup callback did not run");
170-
});
170+
}, 20000);
171171

172172
it("unregisters a FinalizationRegistry target through a later wrapper of its token", function () {
173173
var registry = new FinalizationRegistry(function () {});

‎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
@@ -175,8 +175,8 @@ void GetWrapperLifetimeStatsCallback(const FunctionCallbackInfo<Value>& info) {
175175
Local<Context> context = isolate->GetCurrentContext();
176176
Local<Object> result = Object::New(isolate);
177177
auto set = [&](const char* name, uint64_t value) {
178-
(void) result->Set(context, ArgConverter::ConvertToV8String(isolate, name),
179-
Number::New(isolate, static_cast<double>(value)));
178+
(void) result->CreateDataProperty(context, ArgConverter::ConvertToV8String(isolate, name),
179+
Number::New(isolate, static_cast<double>(value)));
180180
};
181181
set("resurrections", stats.resurrections);
182182
set("weakened", stats.weakened);
@@ -221,13 +221,14 @@ void GetWrapperClassCountsCallback(const FunctionCallbackInfo<Value>& info) {
221221
for (const auto& [name, counts] : objectManager->GetWrapperClassCounts()) {
222222
Local<Object> entry = Object::New(isolate);
223223
auto set = [&](const char* key, uint64_t value) {
224-
(void) entry->Set(context, ArgConverter::ConvertToV8String(isolate, key),
225-
Number::New(isolate, static_cast<double>(value)));
224+
(void) entry->CreateDataProperty(context, ArgConverter::ConvertToV8String(isolate, key),
225+
Number::New(isolate, static_cast<double>(value)));
226226
};
227227
set("wrappers", counts.wrappers);
228228
set("canaries", counts.canaries);
229229
set("states", counts.states);
230-
(void) result->Set(context, ArgConverter::ConvertToV8String(isolate, name), entry);
230+
// A class name such as "__proto__" must stay an own property.
231+
(void) result->CreateDataProperty(context, ArgConverter::ConvertToV8String(isolate, name), entry);
231232
}
232233
info.GetReturnValue().Set(result);
233234
}

‎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

@@ -1323,8 +1345,7 @@ void ObjectManager::ReleaseCollectedWrapper(int javaObjectID) {
13231345
m_lifetimeStats.collected++;
13241346
Persistent<Object>* po = state->target;
13251347
if (state->linked) {
1326-
auto object = po->Get(m_isolate);
1327-
object->SetInternalField(static_cast<int>(MetadataNodeKeys::JsInfo), Undefined(m_isolate));
1348+
MarkLinkReleased(po->Get(m_isolate));
13281349
}
13291350
m_idToObject.Erase(javaObjectID);
13301351
po->Reset();
@@ -1472,7 +1493,6 @@ void ObjectManager::ReleaseNativeCounterpart(v8::Local<v8::Object>& object) {
14721493
throw NativeScriptException("Trying to release a non native object!");
14731494
}
14741495

1475-
auto jsInfoIdx = static_cast<int>(MetadataNodeKeys::JsInfo);
14761496
auto javaObjectID = LinkedIdOf(owner);
14771497

14781498
JEnv env;
@@ -1490,7 +1510,7 @@ void ObjectManager::ReleaseNativeCounterpart(v8::Local<v8::Object>& object) {
14901510
state->linked = false;
14911511
}
14921512

1493-
owner->SetInternalField(jsInfoIdx, Undefined(m_isolate));
1513+
MarkLinkReleased(owner);
14941514

14951515
// Every alias of the link is cleared with it.
14961516
Local<Value> aliasesValue;
@@ -1502,7 +1522,7 @@ void ObjectManager::ReleaseNativeCounterpart(v8::Local<v8::Object>& object) {
15021522
Local<Value> alias;
15031523
if (aliases->Get(context, i).ToLocal(&alias) && alias->IsObject() &&
15041524
IsJsRuntimeObject(alias.As<Object>())) {
1505-
alias.As<Object>()->SetInternalField(jsInfoIdx, Undefined(m_isolate));
1525+
MarkLinkReleased(alias.As<Object>());
15061526
}
15071527
}
15081528
}

‎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);
@@ -391,6 +392,9 @@ class ObjectManager {
391392

392393
void ReleaseCollectedWrapper(int javaObjectID);
393394

395+
// A link that is gone leaves null in JsInfo; a link never made leaves undefined.
396+
void MarkLinkReleased(const v8::Local<v8::Object>& object);
397+
394398
// Drops id's registrations on both sides if Java has collected its object.
395399
bool ReleaseIfCollected(int javaObjectID);
396400

0 commit comments

Comments
 (0)