Skip to content

Commit 8279e1a

Browse files
committed
feat(runtime): weak collections key Java objects in canary mode
Ports NativeScript/ios#563. In canary mode a builtin replaces WeakMap, WeakSet, WeakRef and FinalizationRegistry with subclasses that key a Java object whose wrapper is a canary by an opaque, frozen key its state holds, so entries and targets live as long as the Java object instead of dying with a canary. Lookups never create the key; deref returns the live canary, a new one with the object's state, or undefined once Java collected the object. Other values, and other modes, use V8's built-ins.
1 parent ab95f47 commit 8279e1a

8 files changed

Lines changed: 509 additions & 4 deletions

File tree

‎docs/ns-builtin-modules.md‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -255,9 +255,24 @@ state, and a rebuilt canary has the prototype it was built with (V8 reports
255255
no prototype change to the handler). Native `#private` fields are branded on
256256
the canary and do not carry over.
257257
A canary built after another died is a new JS object, which `===` cannot tell
258-
because nothing kept the old one, but which keys `WeakMap`, `WeakSet`,
259-
`WeakRef` and `FinalizationRegistry` entries separately.
260-
`__releaseNativeCounterpart` drops the object's state with its link.
258+
because nothing kept the old one. `__releaseNativeCounterpart` drops the
259+
object's state with its link.
260+
261+
**Weak collections.** What could notice a new canary is whatever keys on the
262+
old one without keeping it, so in canary mode a builtin
263+
(`js/weak-collections.js`) replaces `WeakMap`, `WeakSet`, `WeakRef` and
264+
`FinalizationRegistry` with subclasses that key a Java object whose wrapper is
265+
a canary by an opaque, frozen key its state holds. Entries and targets
266+
therefore live exactly as long as the Java object; `WeakRef.prototype.deref`
267+
(and the `get` alias) returns the live canary, a new one with the object's
268+
state, or `undefined` once Java collected the object. `set`, `add`,
269+
`getOrInsert`, `new WeakRef` and `register` create the key; lookups never do,
270+
so probing an object gives it no state. A Proxy around a Java object stays a
271+
key of its own, and every other value passes through to the standard
272+
collection. The cost is the other side of the same rooting: a `WeakMap` value
273+
that references its Java key keeps the key, its state and so the Java object
274+
alive for as long as the map lives. Each operation costs one native call in
275+
canary mode, whatever the key.
261276

262277
Remote-module security (`security.allowRemoteModules`,
263278
`security.remoteModuleAllowlist`) is **not** part of this surface. Those

‎test-app/app/src/main/assets/app/mainpage.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ require("./tests/testsForTypescript");
6262
require("./tests/testGC");
6363
require("./tests/testWrapperLifetime");
6464
require("./tests/testWrapperLifetimeModes");
65+
require("./tests/testWrapperLifetimeWeakCollections");
6566
require("./tests/testsMemoryManagement");
6667
require("./tests/testFieldGetSet");
6768
require("./tests/extendedClassesTests");
Lines changed: 195 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,195 @@
1+
// Holds in every wrapper lifetime mode: in "canary" the collections key a Java object by
2+
// its lifetime key, elsewhere the wrapper itself outlives the JS references.
3+
describe("Weak collections of Java objects", function () {
4+
var runtime = require("ns:runtime");
5+
var mode = runtime.getConfig("wrapperLifetimeMode");
6+
var canary = mode === "canary";
7+
var Holder = com.tns.tests.WrapperHolder;
8+
9+
function collectJava() {
10+
for (var i = 0; i < 3; i++) {
11+
java.lang.Runtime.getRuntime().gc();
12+
java.lang.System.runFinalization();
13+
}
14+
}
15+
16+
function crossIntoJava() {
17+
java.lang.System.nanoTime();
18+
}
19+
20+
// Lets JS drop every wrapper nothing references.
21+
function collectBoth() {
22+
gc();
23+
crossIntoJava();
24+
collectJava();
25+
gc();
26+
crossIntoJava();
27+
}
28+
29+
function eventually(predicate, done, message) {
30+
var deadline = Date.now() + 10000;
31+
(function poll() {
32+
collectBoth();
33+
collectJava();
34+
if (predicate()) {
35+
done();
36+
return;
37+
}
38+
if (Date.now() > deadline) {
39+
done.fail(message);
40+
return;
41+
}
42+
setTimeout(poll, 50);
43+
})();
44+
}
45+
46+
// A JS-extended object, a canary in every canary scope; Java keeps it in Holder.
47+
function heldRunnable() {
48+
var runnable = new java.lang.Runnable({ run: function () {} });
49+
Holder.held = runnable;
50+
return runnable;
51+
}
52+
53+
afterEach(function () {
54+
Holder.held = null;
55+
});
56+
57+
it("keeps a WeakMap entry for a Java object across a wrapper change (" + mode + ")", function () {
58+
var map = new WeakMap();
59+
(function () {
60+
map.set(heldRunnable(), "value");
61+
})();
62+
collectBoth();
63+
64+
var again = Holder.held;
65+
expect(map.has(again)).toBe(true);
66+
expect(map.get(again)).toBe("value");
67+
expect(map.delete(again)).toBe(true);
68+
expect(map.has(again)).toBe(false);
69+
});
70+
71+
it("keeps a WeakSet member for a Java object across a wrapper change", function () {
72+
var set = new WeakSet();
73+
(function () {
74+
set.add(heldRunnable());
75+
})();
76+
collectBoth();
77+
78+
expect(set.has(Holder.held)).toBe(true);
79+
});
80+
81+
it("keeps a getOrInsert entry for a Java object across a wrapper change", function () {
82+
var map = new WeakMap();
83+
if (typeof map.getOrInsert !== "function") {
84+
return;
85+
}
86+
(function () {
87+
map.getOrInsert(heldRunnable(), "first");
88+
})();
89+
collectBoth();
90+
91+
expect(map.getOrInsert(Holder.held, "second")).toBe("first");
92+
var seen;
93+
expect(map.getOrInsertComputed(Holder.held, function (key) {
94+
seen = key;
95+
return "computed";
96+
})).toBe("first");
97+
expect(seen).toBeUndefined();
98+
});
99+
100+
it("dereferences a WeakRef to a Java-held object while the object lives", function () {
101+
var ref = (function () {
102+
var runnable = heldRunnable();
103+
runnable.tag = "state";
104+
return new WeakRef(runnable);
105+
})();
106+
collectBoth();
107+
108+
var target = ref.deref();
109+
expect(target).toBeDefined();
110+
expect(target.tag).toBe("state");
111+
expect(ref.get()).toBe(target);
112+
expect(target.equals(Holder.held)).toBe(true);
113+
});
114+
115+
it("clears a WeakRef once Java collected the object", function (done) {
116+
var ref = (function () {
117+
return new WeakRef(new java.lang.Runnable({ run: function () {} }));
118+
})();
119+
eventually(function () {
120+
return ref.deref() === undefined;
121+
}, done, "the WeakRef still dereferences");
122+
});
123+
124+
it("runs a FinalizationRegistry callback once Java collected the object", function (done) {
125+
var cleaned = false;
126+
var registry = new FinalizationRegistry(function (held) {
127+
cleaned = held === "held";
128+
});
129+
(function () {
130+
registry.register(new java.lang.Runnable({ run: function () {} }), "held");
131+
})();
132+
eventually(function () {
133+
return cleaned;
134+
}, done, "the cleanup callback did not run");
135+
});
136+
137+
it("unregisters a FinalizationRegistry target through a later wrapper of its token", function () {
138+
var registry = new FinalizationRegistry(function () {});
139+
var target = {};
140+
(function () {
141+
var runnable = heldRunnable();
142+
registry.register(target, "held", runnable);
143+
})();
144+
collectBoth();
145+
146+
expect(registry.unregister(Holder.held)).toBe(true);
147+
expect(target).toBeDefined();
148+
});
149+
150+
it("rejects a FinalizationRegistry registration whose target is its held value", function () {
151+
var registry = new FinalizationRegistry(function () {});
152+
var runnable = new java.lang.Runnable({ run: function () {} });
153+
expect(function () {
154+
registry.register(runnable, runnable);
155+
}).toThrowError(TypeError);
156+
});
157+
158+
it("keys a Proxy around a Java object by the Proxy", function () {
159+
var runnable = new java.lang.Runnable({ run: function () {} });
160+
var proxy = new Proxy(runnable, {});
161+
var map = new WeakMap();
162+
map.set(proxy, "proxy");
163+
expect(map.get(proxy)).toBe("proxy");
164+
expect(map.has(runnable)).toBe(false);
165+
});
166+
167+
it("does not give state to a Java object a lookup only probes", function () {
168+
var map = new WeakMap();
169+
var set = new WeakSet();
170+
var runnable = new java.lang.Runnable({ run: function () {} });
171+
var states = runtime.getWrapperLifetimeStats().canaryStates;
172+
expect(map.get(runnable)).toBeUndefined();
173+
expect(map.has(runnable)).toBe(false);
174+
expect(set.has(runnable)).toBe(false);
175+
expect(map.delete(runnable)).toBe(false);
176+
expect(runtime.getWrapperLifetimeStats().canaryStates).toBe(states);
177+
});
178+
179+
it("keeps working as the standard collections for other keys", function () {
180+
var map = new WeakMap([[Object, 1]]);
181+
var key = {};
182+
map.set(key, 2);
183+
expect(map.get(Object)).toBe(1);
184+
expect(map.get(key)).toBe(2);
185+
var ref = new WeakRef(key);
186+
expect(ref.deref()).toBe(key);
187+
expect(new WeakSet([key]).has(key)).toBe(true);
188+
expect(map instanceof WeakMap).toBe(true);
189+
});
190+
191+
it("installs the canary collections only in canary mode", function () {
192+
var native = WeakMap.toString().indexOf("[native code]") !== -1;
193+
expect(native).toBe(!canary);
194+
});
195+
});

‎test-app/runtime/CMakeLists.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,7 @@ set(RUNTIME_BUILTIN_JS
9191
${RUNTIME_BUILTIN_JS_DIR}/require-factory.js
9292
${RUNTIME_BUILTIN_JS_DIR}/structured-clone.js
9393
${RUNTIME_BUILTIN_JS_DIR}/text-encoding.js
94+
${RUNTIME_BUILTIN_JS_DIR}/weak-collections.js
9495
${RUNTIME_BUILTIN_JS_DIR}/weak-ref.js
9596
${RUNTIME_BUILTIN_JS_DIR}/worker-events.js
9697
)

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

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,8 @@ void ObjectManager::Init(Isolate* isolate) {
118118
canaryTemplate, WrapperLifetimeCanary::TemplateKind::kExtended, this);
119119
m_canaryTemplate.Reset(isolate, canaryTemplate);
120120
m_instanceFieldTableKey.Reset(isolate, Private::New(isolate));
121+
m_keyOfState.Reset(isolate, Private::New(isolate));
122+
m_objectOfKey.Reset(isolate, Private::New(isolate));
121123
isolate->AddGCEpilogueCallback(CanaryGCEpilogue, this);
122124
m_canaryEpilogueAdded = true;
123125
}
@@ -955,6 +957,121 @@ std::map<std::string, ObjectManager::ClassCounts> ObjectManager::GetWrapperClass
955957
return counts;
956958
}
957959

960+
bool ObjectManager::AddWeakCollectionFunctions(Local<Context> context, Local<Object> binding) {
961+
auto isolate = m_isolate;
962+
Local<Function> unwrap;
963+
Local<Function> wrap;
964+
return Function::New(context, UnwrapForWeakCollection).ToLocal(&unwrap) &&
965+
Function::New(context, WrapForWeakCollection).ToLocal(&wrap) &&
966+
binding->Set(context, ArgConverter::ConvertToV8String(isolate, "unwrap"), unwrap)
967+
.FromMaybe(false) &&
968+
binding->Set(context, ArgConverter::ConvertToV8String(isolate, "wrap"), wrap)
969+
.FromMaybe(false);
970+
}
971+
972+
// unwrap(value, create): the weak collections' key for a canary's Java object,
973+
// a frozen, null-prototype object that lives as long as the object's state,
974+
// that is, until Java collects the object. Lookups pass `create` false and never
975+
// make one: with no key yet, no entry can be keyed by it. The value itself for
976+
// anything that is not a canary, a Proxy included (it is a key of its own).
977+
void ObjectManager::UnwrapForWeakCollection(const FunctionCallbackInfo<Value>& info) {
978+
Isolate* isolate = info.GetIsolate();
979+
Local<Value> value = info[0];
980+
bool create = info[1]->IsTrue();
981+
info.GetReturnValue().Set(value);
982+
if (!value->IsObject() || value->IsProxy()) {
983+
return;
984+
}
985+
ObjectManager* thisPtr = Runtime::GetObjectManager(isolate);
986+
Local<Object> holder = value.As<Object>();
987+
Local<Object> state;
988+
if (create ? !thisPtr->CanaryStateForWrite(holder, &state)
989+
: !thisPtr->ExistingCanaryState(holder, &state)) {
990+
return;
991+
}
992+
Local<Context> context = isolate->GetCurrentContext();
993+
Local<Private> keyOfState = thisPtr->m_keyOfState.Get(isolate);
994+
Local<Value> key;
995+
if (state->GetPrivate(context, keyOfState).ToLocal(&key) && key->IsObject()) {
996+
info.GetReturnValue().Set(key);
997+
return;
998+
}
999+
if (!create) {
1000+
return;
1001+
}
1002+
Local<Object> newKey = Object::New(isolate, Null(isolate), nullptr, nullptr, 0);
1003+
if (!newKey
1004+
->SetPrivate(context, thisPtr->m_objectOfKey.Get(isolate),
1005+
Integer::NewFromUnsigned(isolate, static_cast<uint32_t>(LinkedIdOf(holder))))
1006+
.FromMaybe(false) ||
1007+
!newKey->SetIntegrityLevel(context, IntegrityLevel::kFrozen).FromMaybe(false) ||
1008+
!state->SetPrivate(context, keyOfState, newKey).FromMaybe(false)) {
1009+
return;
1010+
}
1011+
info.GetReturnValue().Set(newKey);
1012+
}
1013+
1014+
// wrap(key): the Java object a key stands for, as its live canary or a new one
1015+
// with its state, or undefined once Java collected it. Anything that is not a
1016+
// key passes through.
1017+
void ObjectManager::WrapForWeakCollection(const FunctionCallbackInfo<Value>& info) {
1018+
Isolate* isolate = info.GetIsolate();
1019+
Local<Value> value = info[0];
1020+
info.GetReturnValue().Set(value);
1021+
if (!value->IsObject()) {
1022+
return;
1023+
}
1024+
ObjectManager* thisPtr = Runtime::GetObjectManager(isolate);
1025+
Local<Context> context = isolate->GetCurrentContext();
1026+
Local<Object> key = value.As<Object>();
1027+
Local<Value> idValue;
1028+
if (!key->GetPrivate(context, thisPtr->m_objectOfKey.Get(isolate)).ToLocal(&idValue) ||
1029+
!idValue->IsUint32()) {
1030+
return;
1031+
}
1032+
info.GetReturnValue().SetUndefined();
1033+
int id = static_cast<int>(idValue.As<Uint32>()->Value());
1034+
CanaryRecord* record = thisPtr->FindCanaryRecord(id);
1035+
if (record == nullptr || record->state.IsEmpty()) {
1036+
return;
1037+
}
1038+
Local<Value> recordKey;
1039+
if (!record->state.Get(isolate)->GetPrivate(context, thisPtr->m_keyOfState.Get(isolate))
1040+
.ToLocal(&recordKey) ||
1041+
!recordKey->StrictEquals(key)) {
1042+
return;
1043+
}
1044+
if (auto live = thisPtr->m_idToObject.Find(id)) {
1045+
info.GetReturnValue().Set(thisPtr->JsObjectFor(live));
1046+
return;
1047+
}
1048+
Local<Object> result = thisPtr->RebuildCanary(id);
1049+
if (result.IsEmpty() && thisPtr->FindCanaryRecord(id) != nullptr) {
1050+
// A plain object: a wrapper made from it the usual way is hydrated from its state.
1051+
JniLocalRef javaObject(thisPtr->JavaObjectOrNull(id));
1052+
if (!javaObject.IsNull()) {
1053+
result = thisPtr->GetOrCreateJSWrapper(javaObject);
1054+
}
1055+
}
1056+
if (!result.IsEmpty()) {
1057+
info.GetReturnValue().Set(result);
1058+
}
1059+
}
1060+
1061+
jobject ObjectManager::JavaObjectOrNull(int javaObjectID) {
1062+
JEnv env;
1063+
JNIEnv* raw = env;
1064+
AssertIsolateLocked();
1065+
// getJavaObjectByID throws for an id whose object was collected.
1066+
jobject object = raw->CallObjectMethod(m_javaRuntimeObject, GET_JAVAOBJECT_BY_ID_METHOD_ID,
1067+
javaObjectID);
1068+
if (raw->ExceptionCheck()) {
1069+
raw->ExceptionClear();
1070+
return nullptr;
1071+
}
1072+
return object;
1073+
}
1074+
9581075
void ObjectManager::ReleaseCollectedCanaryStates() {
9591076
if (!m_deathInboxOpen) {
9601077
return;
@@ -1256,6 +1373,8 @@ void ObjectManager::ReleaseAllRegistered() {
12561373
m_canaryRecords.clear();
12571374
m_canaryTemplate.Reset();
12581375
m_instanceFieldTableKey.Reset();
1376+
m_keyOfState.Reset();
1377+
m_objectOfKey.Reset();
12591378

12601379
auto jsInfoIdx = static_cast<int>(MetadataNodeKeys::JsInfo);
12611380

0 commit comments

Comments
 (0)