Skip to content

Commit b513579

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 fba87e0 commit b513579

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
@@ -236,9 +236,24 @@ on a canary, and on any wrapper built from a template that carries the write
236236
handler (every wrapper under `"all"`, released ones included); index-keyed properties are not mirrored and die with the canary;
237237
a write through an object whose prototype is a canary lands on that object.
238238
A canary built after another died is a new JS object, which `===` cannot tell
239-
because nothing kept the old one, but which keys `WeakMap`, `WeakSet`,
240-
`WeakRef` and `FinalizationRegistry` entries separately.
241-
`__releaseNativeCounterpart` drops the object's state with its link.
239+
because nothing kept the old one. `__releaseNativeCounterpart` drops the
240+
object's state with its link.
241+
242+
**Weak collections.** What could notice a new canary is whatever keys on the
243+
old one without keeping it, so in canary mode a builtin
244+
(`js/weak-collections.js`) replaces `WeakMap`, `WeakSet`, `WeakRef` and
245+
`FinalizationRegistry` with subclasses that key a Java object whose wrapper is
246+
a canary by an opaque, frozen key its state holds. Entries and targets
247+
therefore live exactly as long as the Java object; `WeakRef.prototype.deref`
248+
(and the `get` alias) returns the live canary, a new one with the object's
249+
state, or `undefined` once Java collected the object. `set`, `add`,
250+
`getOrInsert`, `new WeakRef` and `register` create the key; lookups never do,
251+
so probing an object gives it no state. A Proxy around a Java object stays a
252+
key of its own, and every other value passes through to the standard
253+
collection. The cost is the other side of the same rooting: a `WeakMap` value
254+
that references its Java key keeps the key, its state and so the Java object
255+
alive for as long as the map lives. Each operation costs one native call in
256+
canary mode, whatever the key.
242257

243258
Remote-module security (`security.allowRemoteModules`,
244259
`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
@@ -117,6 +117,8 @@ void ObjectManager::Init(Isolate* isolate) {
117117
WrapperLifetimeCanary::ConfigureInstanceTemplate(
118118
canaryTemplate, WrapperLifetimeCanary::TemplateKind::kExtended);
119119
m_canaryTemplate.Reset(isolate, canaryTemplate);
120+
m_keyOfState.Reset(isolate, Private::New(isolate));
121+
m_objectOfKey.Reset(isolate, Private::New(isolate));
120122
isolate->AddGCEpilogueCallback(CanaryGCEpilogue, this);
121123
m_canaryEpilogueAdded = true;
122124
}
@@ -883,6 +885,121 @@ std::map<std::string, ObjectManager::ClassCounts> ObjectManager::GetWrapperClass
883885
return counts;
884886
}
885887

888+
bool ObjectManager::AddWeakCollectionFunctions(Local<Context> context, Local<Object> binding) {
889+
auto isolate = m_isolate;
890+
Local<Function> unwrap;
891+
Local<Function> wrap;
892+
return Function::New(context, UnwrapForWeakCollection).ToLocal(&unwrap) &&
893+
Function::New(context, WrapForWeakCollection).ToLocal(&wrap) &&
894+
binding->Set(context, ArgConverter::ConvertToV8String(isolate, "unwrap"), unwrap)
895+
.FromMaybe(false) &&
896+
binding->Set(context, ArgConverter::ConvertToV8String(isolate, "wrap"), wrap)
897+
.FromMaybe(false);
898+
}
899+
900+
// unwrap(value, create): the weak collections' key for a canary's Java object,
901+
// a frozen, null-prototype object that lives as long as the object's state,
902+
// that is, until Java collects the object. Lookups pass `create` false and never
903+
// make one: with no key yet, no entry can be keyed by it. The value itself for
904+
// anything that is not a canary, a Proxy included (it is a key of its own).
905+
void ObjectManager::UnwrapForWeakCollection(const FunctionCallbackInfo<Value>& info) {
906+
Isolate* isolate = info.GetIsolate();
907+
Local<Value> value = info[0];
908+
bool create = info[1]->IsTrue();
909+
info.GetReturnValue().Set(value);
910+
if (!value->IsObject() || value->IsProxy()) {
911+
return;
912+
}
913+
ObjectManager* thisPtr = Runtime::GetObjectManager(isolate);
914+
Local<Object> holder = value.As<Object>();
915+
Local<Object> state;
916+
if (create ? !thisPtr->CanaryStateForWrite(holder, &state)
917+
: !thisPtr->ExistingCanaryState(holder, &state)) {
918+
return;
919+
}
920+
Local<Context> context = isolate->GetCurrentContext();
921+
Local<Private> keyOfState = thisPtr->m_keyOfState.Get(isolate);
922+
Local<Value> key;
923+
if (state->GetPrivate(context, keyOfState).ToLocal(&key) && key->IsObject()) {
924+
info.GetReturnValue().Set(key);
925+
return;
926+
}
927+
if (!create) {
928+
return;
929+
}
930+
Local<Object> newKey = Object::New(isolate, Null(isolate), nullptr, nullptr, 0);
931+
if (!newKey
932+
->SetPrivate(context, thisPtr->m_objectOfKey.Get(isolate),
933+
Integer::NewFromUnsigned(isolate, static_cast<uint32_t>(LinkedIdOf(holder))))
934+
.FromMaybe(false) ||
935+
!newKey->SetIntegrityLevel(context, IntegrityLevel::kFrozen).FromMaybe(false) ||
936+
!state->SetPrivate(context, keyOfState, newKey).FromMaybe(false)) {
937+
return;
938+
}
939+
info.GetReturnValue().Set(newKey);
940+
}
941+
942+
// wrap(key): the Java object a key stands for, as its live canary or a new one
943+
// with its state, or undefined once Java collected it. Anything that is not a
944+
// key passes through.
945+
void ObjectManager::WrapForWeakCollection(const FunctionCallbackInfo<Value>& info) {
946+
Isolate* isolate = info.GetIsolate();
947+
Local<Value> value = info[0];
948+
info.GetReturnValue().Set(value);
949+
if (!value->IsObject()) {
950+
return;
951+
}
952+
ObjectManager* thisPtr = Runtime::GetObjectManager(isolate);
953+
Local<Context> context = isolate->GetCurrentContext();
954+
Local<Object> key = value.As<Object>();
955+
Local<Value> idValue;
956+
if (!key->GetPrivate(context, thisPtr->m_objectOfKey.Get(isolate)).ToLocal(&idValue) ||
957+
!idValue->IsUint32()) {
958+
return;
959+
}
960+
info.GetReturnValue().SetUndefined();
961+
int id = static_cast<int>(idValue.As<Uint32>()->Value());
962+
CanaryRecord* record = thisPtr->FindCanaryRecord(id);
963+
if (record == nullptr || record->state.IsEmpty()) {
964+
return;
965+
}
966+
Local<Value> recordKey;
967+
if (!record->state.Get(isolate)->GetPrivate(context, thisPtr->m_keyOfState.Get(isolate))
968+
.ToLocal(&recordKey) ||
969+
!recordKey->StrictEquals(key)) {
970+
return;
971+
}
972+
if (auto live = thisPtr->m_idToObject.Find(id)) {
973+
info.GetReturnValue().Set(thisPtr->JsObjectFor(live));
974+
return;
975+
}
976+
Local<Object> result = thisPtr->RebuildCanary(id);
977+
if (result.IsEmpty() && thisPtr->FindCanaryRecord(id) != nullptr) {
978+
// A plain object: a wrapper made from it the usual way is hydrated from its state.
979+
JniLocalRef javaObject(thisPtr->JavaObjectOrNull(id));
980+
if (!javaObject.IsNull()) {
981+
result = thisPtr->GetOrCreateJSWrapper(javaObject);
982+
}
983+
}
984+
if (!result.IsEmpty()) {
985+
info.GetReturnValue().Set(result);
986+
}
987+
}
988+
989+
jobject ObjectManager::JavaObjectOrNull(int javaObjectID) {
990+
JEnv env;
991+
JNIEnv* raw = env;
992+
AssertIsolateLocked();
993+
// getJavaObjectByID throws for an id whose object was collected.
994+
jobject object = raw->CallObjectMethod(m_javaRuntimeObject, GET_JAVAOBJECT_BY_ID_METHOD_ID,
995+
javaObjectID);
996+
if (raw->ExceptionCheck()) {
997+
raw->ExceptionClear();
998+
return nullptr;
999+
}
1000+
return object;
1001+
}
1002+
8861003
void ObjectManager::ReleaseCollectedCanaryStates() {
8871004
if (!m_deathInboxOpen) {
8881005
return;
@@ -1183,6 +1300,8 @@ void ObjectManager::ReleaseAllRegistered() {
11831300
}
11841301
m_canaryRecords.clear();
11851302
m_canaryTemplate.Reset();
1303+
m_keyOfState.Reset();
1304+
m_objectOfKey.Reset();
11861305

11871306
auto jsInfoIdx = static_cast<int>(MetadataNodeKeys::JsInfo);
11881307

0 commit comments

Comments
 (0)