Skip to content

Commit 6a1ed2e

Browse files
committed
perf(runtime): weak collections find a canary's lifetime key in JS
A private WeakMap maps every canary that stands for a key to it: filled when a key is made, and by the runtime when it builds a canary for an object that has one. Lookups of canaries no longer call into native code, and a value missing there was never a key. WeakRef.deref returns the live canary through a WeakRef kept per key, made only by the WeakRef constructor and by deref, so keying a canary does not keep it alive.
1 parent 59e2d13 commit 6a1ed2e

4 files changed

Lines changed: 178 additions & 26 deletions

File tree

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

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -402,6 +402,86 @@ describe("Weak collections of Java objects", function () {
402402
}).toThrowError(TypeError, /invalid target/);
403403
});
404404

405+
// A canary built for an object that has a key, by any path (here a Java field read, not
406+
// a deref), stands for the key at once; a canary that was never a key makes no state.
407+
it("finds what was keyed on a Java object through a canary built by a Java read", function (done) {
408+
var map = new WeakMap();
409+
var set = new WeakSet();
410+
var registry = new FinalizationRegistry(function () {});
411+
var token = new java.lang.StringBuilder("token");
412+
var NativeWeakRef = Object.getPrototypeOf(WeakRef) === Function.prototype ? WeakRef : Object.getPrototypeOf(WeakRef);
413+
var rebuilds = runtime.getWrapperLifetimeStats().canaryRebuilds;
414+
var firstCanaries;
415+
var refs = (function () {
416+
var plain = new java.lang.StringBuilder("plain");
417+
map.set(plain, "plain value");
418+
set.add(plain);
419+
var runnable = new java.lang.Runnable({ run: function () {} });
420+
registry.register(runnable, "held", plain);
421+
map.set(runnable, "extended value");
422+
var list = new java.util.ArrayList();
423+
list.add(plain);
424+
list.add(runnable);
425+
Holder.held = list;
426+
firstCanaries = [new NativeWeakRef(plain), new NativeWeakRef(runnable)];
427+
return [new WeakRef(plain), new WeakRef(runnable)];
428+
})();
429+
setTimeout(function () {
430+
collectBoth();
431+
if (canary) {
432+
// A plain wrapper is a canary under scope "all" only.
433+
if (runtime.getConfig("wrapperLifetimeScope") === "all") {
434+
expect(firstCanaries[0].deref()).toBeUndefined();
435+
}
436+
expect(firstCanaries[1].deref()).toBeUndefined();
437+
}
438+
var list = Holder.held;
439+
var held = [list.get(0), list.get(1)];
440+
if (canary) {
441+
expect(runtime.getWrapperLifetimeStats().canaryRebuilds).toBeGreaterThan(rebuilds);
442+
}
443+
expect(map.get(held[0])).toBe("plain value");
444+
expect(set.has(held[0])).toBe(true);
445+
expect(map.get(held[1])).toBe("extended value");
446+
expect(refs[0].deref() === held[0]).toBe(true);
447+
expect(refs[1].deref() === held[1]).toBe(true);
448+
expect(refs[1].deref() === refs[1].deref()).toBe(true);
449+
expect(registry.unregister(held[0])).toBe(true);
450+
expect(set.delete(held[0])).toBe(true);
451+
expect(set.has(held[0])).toBe(false);
452+
expect(map.delete(held[1])).toBe(true);
453+
expect(map.has(held[1])).toBe(false);
454+
var states = runtime.getWrapperLifetimeStats().canaryStates;
455+
expect(map.has(token)).toBe(false);
456+
expect(map.get(token)).toBeUndefined();
457+
expect(set.delete(token)).toBe(false);
458+
expect(registry.unregister(token)).toBe(false);
459+
expect(runtime.getWrapperLifetimeStats().canaryStates).toBe(states);
460+
var plainTarget = {};
461+
expect(new WeakRef(plainTarget).deref()).toBe(plainTarget);
462+
done();
463+
}, 0);
464+
});
465+
466+
// Keying a canary must not keep it alive: only WeakRef construction and deref do, until
467+
// the job ends, as the standard says.
468+
it("lets a canary that was just keyed die in the same job", function () {
469+
var map = new WeakMap();
470+
var set = new WeakSet();
471+
var rebuilds = runtime.getWrapperLifetimeStats().canaryRebuilds;
472+
(function () {
473+
var runnable = heldRunnable();
474+
map.set(runnable, "value");
475+
set.add(runnable);
476+
})();
477+
collectBoth();
478+
expect(map.get(Holder.held)).toBe("value");
479+
expect(set.has(Holder.held)).toBe(true);
480+
if (canary) {
481+
expect(runtime.getWrapperLifetimeStats().canaryRebuilds).toBeGreaterThan(rebuilds);
482+
}
483+
});
484+
405485
it("installs the canary collections only in canary mode", function () {
406486
var native = WeakMap.toString().indexOf("[native code]") !== -1;
407487
expect(native).toBe(!canary);

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

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -643,13 +643,16 @@ ObjectManager::CanaryRecord* ObjectManager::AdoptCanary(
643643
if (!EnsureJavaStrong(javaObjectID, record)) {
644644
return nullptr;
645645
}
646-
if (hydrate && !record->state.IsEmpty()) {
646+
if (!record->state.IsEmpty()) {
647647
auto context = m_isolate->GetCurrentContext();
648648
if (context.IsEmpty()) {
649649
context = Runtime::GetRuntime(m_isolate)->GetContext();
650650
}
651-
WrapperLifetimeCanary::CopyOwnProperties(this, context, record->state.Get(m_isolate), object,
652-
!record->stateNotPlain);
651+
if (hydrate) {
652+
WrapperLifetimeCanary::CopyOwnProperties(this, context, record->state.Get(m_isolate), object,
653+
!record->stateNotPlain);
654+
}
655+
RekeyCanary(context, object, record);
653656
}
654657
return record;
655658
}
@@ -1035,11 +1038,15 @@ bool ObjectManager::AddWeakCollectionFunctions(Local<Context> context, Local<Obj
10351038
auto isolate = m_isolate;
10361039
Local<Function> unwrap;
10371040
Local<Function> wrap;
1041+
Local<Function> setRekey;
10381042
return Function::New(context, UnwrapForWeakCollection).ToLocal(&unwrap) &&
10391043
Function::New(context, WrapForWeakCollection).ToLocal(&wrap) &&
1044+
Function::New(context, SetRekeyForWeakCollection).ToLocal(&setRekey) &&
10401045
binding->Set(context, ArgConverter::ConvertToV8String(isolate, "unwrap"), unwrap)
10411046
.FromMaybe(false) &&
10421047
binding->Set(context, ArgConverter::ConvertToV8String(isolate, "wrap"), wrap)
1048+
.FromMaybe(false) &&
1049+
binding->Set(context, ArgConverter::ConvertToV8String(isolate, "setRekey"), setRekey)
10431050
.FromMaybe(false);
10441051
}
10451052

@@ -1179,6 +1186,29 @@ void ObjectManager::WrapForWeakCollection(const FunctionCallbackInfo<Value>& inf
11791186
}
11801187
}
11811188

1189+
void ObjectManager::SetRekeyForWeakCollection(const FunctionCallbackInfo<Value>& info) {
1190+
ObjectManager* thisPtr = WeakCollectionManagerOf(info.GetIsolate());
1191+
if (thisPtr != nullptr && info[0]->IsFunction()) {
1192+
thisPtr->m_rekey.Reset(info.GetIsolate(), info[0].As<Function>());
1193+
}
1194+
}
1195+
1196+
void ObjectManager::RekeyCanary(Local<Context> context, const Local<Object>& canary,
1197+
CanaryRecord* record) {
1198+
if (m_rekey.IsEmpty() || record->state.IsEmpty() || m_keyOfState.IsEmpty()) {
1199+
return;
1200+
}
1201+
Local<Value> key;
1202+
if (!record->state.Get(m_isolate)->GetPrivate(context, m_keyOfState.Get(m_isolate)).ToLocal(&key) ||
1203+
!key->IsObject()) {
1204+
return;
1205+
}
1206+
// Builtins only: WeakMap reads and writes, no user code.
1207+
TryCatch tc(m_isolate);
1208+
Local<Value> argv[] = {canary, key};
1209+
(void)m_rekey.Get(m_isolate)->Call(context, Undefined(m_isolate), 2, argv);
1210+
}
1211+
11821212
void ObjectManager::KeepWeakCollectionKey(int javaObjectID) {
11831213
CanaryRecord* record = FindCanaryRecord(javaObjectID);
11841214
auto live = m_idToObject.Find(javaObjectID);
@@ -1521,6 +1551,7 @@ void ObjectManager::ReleaseAllRegistered() {
15211551
m_canaryRecords.clear();
15221552
m_instanceFieldTableKey.Reset();
15231553
m_keyOfState.Reset();
1554+
m_rekey.Reset();
15241555
m_objectOfKey.Reset();
15251556
m_releasedOfKey.Reset();
15261557

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

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -259,8 +259,9 @@ class ObjectManager {
259259
std::map<std::string, ClassCounts> GetWrapperClassCounts();
260260

261261
// Canary mode: adds `unwrap` (a canary -> its Java object's weak-collection
262-
// key) and `wrap` (key -> live or new canary, or undefined once Java
263-
// collected the object) to binding, for js/weak-collections.js.
262+
// key), `wrap` (key -> live or new canary, or undefined once Java collected
263+
// the object) and `setRekey` (registers the function told about every canary
264+
// built for an object that has a key) to binding, for js/weak-collections.js.
264265
bool AddWeakCollectionFunctions(v8::Local<v8::Context> context,
265266
v8::Local<v8::Object> binding);
266267

@@ -456,6 +457,12 @@ class ObjectManager {
456457
void KeepWeakCollectionKey(int javaObjectID);
457458

458459
static void UnwrapForWeakCollection(const v8::FunctionCallbackInfo<v8::Value>& info);
460+
static void SetRekeyForWeakCollection(const v8::FunctionCallbackInfo<v8::Value>& info);
461+
// js/weak-collections.js's rekey(canary, key), or empty.
462+
v8::Persistent<v8::Function> m_rekey;
463+
// Tells weak-collections.js about a new canary whose record's state has a key.
464+
void RekeyCanary(v8::Local<v8::Context> context, const v8::Local<v8::Object>& canary,
465+
CanaryRecord* record);
459466
static void WrapForWeakCollection(const v8::FunctionCallbackInfo<v8::Value>& info);
460467

461468
// id's Java object, or null once Java collected it.

‎test-app/runtime/src/main/cpp/js/weak-collections.js‎

Lines changed: 55 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
// left as it is: Object.getPrototypeOf(WeakMap.prototype) is the native
1212
// prototype, and WeakMap.toString() is not native code.
1313

14-
const { unwrap, wrap } = binding;
14+
const { unwrap, wrap, setRekey } = binding;
1515
const {
1616
FinalizationRegistry: NativeFinalizationRegistry,
1717
FinalizationRegistryPrototypeRegister,
@@ -44,23 +44,46 @@ function canBeHeldWeakly(value) {
4444
return isObject(value) || (typeof value === "symbol" && SymbolKeyFor(value) === undefined);
4545
}
4646

47-
// unwrap(value, true) makes the key on first use; lookups pass false so they
48-
// never create state for an object that was never a key. A key is made only
49-
// once the native method can no longer reject the call, so a failed call leaves
50-
// no state behind: the receiver is checked first with a method that cannot
51-
// insert anything.
47+
// unwrap(value, true) makes the key on first use. A key is made only once the
48+
// native method can no longer reject the call, so a failed call leaves no state
49+
// behind: the receiver is checked first with a method that cannot insert
50+
// anything.
5251
//
5352
// A canary is never stored as a key itself (its lifetime key is), so every
54-
// method first tries the value as is and unwraps it only when that misses:
55-
// plain JS keys never reach native code.
53+
// method first tries the value as is. Every canary that stands for a key is in
54+
// canaryToKey: the ones keyFor unwrapped, and the ones the runtime builds for an
55+
// object that has a key (it calls the function given to setRekey). So a lookup
56+
// that misses there knows the value was never a key, without native code.
57+
const canaryToKey = new NativeWeakMap();
58+
// Every key -> null, or a NativeWeakRef to the canary a WeakRef was made with
59+
// or last dereferenced to. Only those two make one: a NativeWeakRef keeps its
60+
// target until the job ends, which they do by spec anyway.
61+
const keyToCanary = new NativeWeakMap();
62+
63+
function remember(canary, key) {
64+
WeakMapPrototypeSet(canaryToKey, canary, key);
65+
if (!WeakMapPrototypeHas(keyToCanary, key)) {
66+
WeakMapPrototypeSet(keyToCanary, key, null);
67+
}
68+
}
69+
setRekey(remember);
5670

5771
// The lifetime key value stands for, or undefined when that is value itself.
5872
function otherKey(value) {
59-
if (!isObject(value)) {
60-
return undefined;
73+
return isObject(value) ? WeakMapPrototypeGet(canaryToKey, value) : undefined;
74+
}
75+
76+
// The key to store for value, made on first use.
77+
function keyFor(value) {
78+
const known = WeakMapPrototypeGet(canaryToKey, value);
79+
if (known !== undefined) {
80+
return known;
6181
}
62-
const key = unwrap(value, false);
63-
return key !== value ? key : undefined;
82+
const key = unwrap(value, true);
83+
if (key !== value) {
84+
remember(value, key);
85+
}
86+
return key;
6487
}
6588

6689
// Unregistering it finds nothing: it is never a token.
@@ -79,7 +102,7 @@ class WeakMap extends NativeWeakMap {
79102
set(key, value) {
80103
// Also checks the receiver before a key is made.
81104
if (isObject(key) && !WeakMapPrototypeHas(this, key)) {
82-
key = unwrap(key, true);
105+
key = keyFor(key);
83106
}
84107
WeakMapPrototypeSet(this, key, value);
85108
return this;
@@ -107,7 +130,7 @@ if (WeakMapPrototypeGetOrInsert !== undefined) {
107130
ObjectDefineProperty(WeakMap.prototype, "getOrInsert", {
108131
value: function getOrInsert(key, value) {
109132
if (isObject(key) && !WeakMapPrototypeHas(this, key)) {
110-
key = unwrap(key, true);
133+
key = keyFor(key);
111134
}
112135
return WeakMapPrototypeGetOrInsert(this, key, value);
113136
},
@@ -131,7 +154,7 @@ if (WeakMapPrototypeGetOrInsertComputed !== undefined) {
131154
// Before the key exists, so a callback that throws leaves none; it sees
132155
// the key it was given, not the lifetime key.
133156
const value = callbackfn(key);
134-
WeakMapPrototypeSet(this, unwrap(key, true), value);
157+
WeakMapPrototypeSet(this, keyFor(key), value);
135158
return value;
136159
},
137160
writable: true,
@@ -143,7 +166,7 @@ class WeakSet extends NativeWeakSet {
143166
add(value) {
144167
// Also checks the receiver before a key is made.
145168
if (isObject(value) && !WeakSetPrototypeHas(this, value)) {
146-
value = unwrap(value, true);
169+
value = keyFor(value);
147170
}
148171
WeakSetPrototypeAdd(this, value);
149172
return this;
@@ -168,11 +191,11 @@ class WeakSet extends NativeWeakSet {
168191

169192
class WeakRef extends NativeWeakRef {
170193
constructor(target) {
171-
const key = isObject(target) ? unwrap(target, true) : target;
194+
const key = isObject(target) ? keyFor(target) : target;
172195
super(key);
173196
// The target itself, not only its key, stays alive until the job ends.
174197
if (key !== target) {
175-
new NativeWeakRef(target);
198+
WeakMapPrototypeSet(keyToCanary, key, new NativeWeakRef(target));
176199
}
177200
}
178201

@@ -185,10 +208,21 @@ class WeakRef extends NativeWeakRef {
185208
if (!isObject(target)) {
186209
return target;
187210
}
211+
const last = WeakMapPrototypeGet(keyToCanary, target);
212+
if (last === undefined) {
213+
// Not a key: the target itself.
214+
return target;
215+
}
216+
if (last !== null) {
217+
const live = WeakRefPrototypeDeref(last);
218+
if (live !== undefined) {
219+
return live;
220+
}
221+
}
188222
const result = wrap(target);
189223
// The native deref already keeps a target it returns as is.
190224
if (result !== target && result !== undefined) {
191-
new NativeWeakRef(result);
225+
WeakMapPrototypeSet(keyToCanary, target, new NativeWeakRef(result));
192226
}
193227
return result;
194228
}
@@ -218,9 +252,9 @@ class FinalizationRegistry extends NativeFinalizationRegistry {
218252
FinalizationRegistryPrototypeUnregister(this, receiverProbe);
219253
FinalizationRegistryPrototypeRegister(
220254
this,
221-
isObject(target) ? unwrap(target, true) : target,
255+
isObject(target) ? keyFor(target) : target,
222256
heldValue,
223-
isObject(unregisterToken) ? unwrap(unregisterToken, true) : unregisterToken,
257+
isObject(unregisterToken) ? keyFor(unregisterToken) : unregisterToken,
224258
);
225259
}
226260

0 commit comments

Comments
 (0)