Skip to content

Commit 3f34ddc

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 1796250 commit 3f34ddc

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
@@ -113,6 +113,8 @@ void ObjectManager::Init(Isolate* isolate) {
113113

114114
if (WrapperLifetimeCanary::Enabled()) {
115115
m_instanceFieldTableKey.Reset(isolate, Private::New(isolate));
116+
m_keyOfState.Reset(isolate, Private::New(isolate));
117+
m_objectOfKey.Reset(isolate, Private::New(isolate));
116118
isolate->AddGCEpilogueCallback(CanaryGCEpilogue, this);
117119
m_canaryEpilogueAdded = true;
118120
}
@@ -1001,6 +1003,121 @@ std::map<std::string, ObjectManager::ClassCounts> ObjectManager::GetWrapperClass
10011003
return counts;
10021004
}
10031005

1006+
bool ObjectManager::AddWeakCollectionFunctions(Local<Context> context, Local<Object> binding) {
1007+
auto isolate = m_isolate;
1008+
Local<Function> unwrap;
1009+
Local<Function> wrap;
1010+
return Function::New(context, UnwrapForWeakCollection).ToLocal(&unwrap) &&
1011+
Function::New(context, WrapForWeakCollection).ToLocal(&wrap) &&
1012+
binding->Set(context, ArgConverter::ConvertToV8String(isolate, "unwrap"), unwrap)
1013+
.FromMaybe(false) &&
1014+
binding->Set(context, ArgConverter::ConvertToV8String(isolate, "wrap"), wrap)
1015+
.FromMaybe(false);
1016+
}
1017+
1018+
// unwrap(value, create): the weak collections' key for a canary's Java object,
1019+
// a frozen, null-prototype object that lives as long as the object's state,
1020+
// that is, until Java collects the object. Lookups pass `create` false and never
1021+
// make one: with no key yet, no entry can be keyed by it. The value itself for
1022+
// anything that is not a canary, a Proxy included (it is a key of its own).
1023+
void ObjectManager::UnwrapForWeakCollection(const FunctionCallbackInfo<Value>& info) {
1024+
Isolate* isolate = info.GetIsolate();
1025+
Local<Value> value = info[0];
1026+
bool create = info[1]->IsTrue();
1027+
info.GetReturnValue().Set(value);
1028+
if (!value->IsObject() || value->IsProxy()) {
1029+
return;
1030+
}
1031+
ObjectManager* thisPtr = Runtime::GetObjectManager(isolate);
1032+
Local<Object> holder = value.As<Object>();
1033+
Local<Object> state;
1034+
if (create ? !thisPtr->CanaryStateForWrite(holder, &state)
1035+
: !thisPtr->ExistingCanaryState(holder, &state)) {
1036+
return;
1037+
}
1038+
Local<Context> context = isolate->GetCurrentContext();
1039+
Local<Private> keyOfState = thisPtr->m_keyOfState.Get(isolate);
1040+
Local<Value> key;
1041+
if (state->GetPrivate(context, keyOfState).ToLocal(&key) && key->IsObject()) {
1042+
info.GetReturnValue().Set(key);
1043+
return;
1044+
}
1045+
if (!create) {
1046+
return;
1047+
}
1048+
Local<Object> newKey = Object::New(isolate, Null(isolate), nullptr, nullptr, 0);
1049+
if (!newKey
1050+
->SetPrivate(context, thisPtr->m_objectOfKey.Get(isolate),
1051+
Integer::NewFromUnsigned(isolate, static_cast<uint32_t>(LinkedIdOf(holder))))
1052+
.FromMaybe(false) ||
1053+
!newKey->SetIntegrityLevel(context, IntegrityLevel::kFrozen).FromMaybe(false) ||
1054+
!state->SetPrivate(context, keyOfState, newKey).FromMaybe(false)) {
1055+
return;
1056+
}
1057+
info.GetReturnValue().Set(newKey);
1058+
}
1059+
1060+
// wrap(key): the Java object a key stands for, as its live canary or a new one
1061+
// with its state, or undefined once Java collected it. Anything that is not a
1062+
// key passes through.
1063+
void ObjectManager::WrapForWeakCollection(const FunctionCallbackInfo<Value>& info) {
1064+
Isolate* isolate = info.GetIsolate();
1065+
Local<Value> value = info[0];
1066+
info.GetReturnValue().Set(value);
1067+
if (!value->IsObject()) {
1068+
return;
1069+
}
1070+
ObjectManager* thisPtr = Runtime::GetObjectManager(isolate);
1071+
Local<Context> context = isolate->GetCurrentContext();
1072+
Local<Object> key = value.As<Object>();
1073+
Local<Value> idValue;
1074+
if (!key->GetPrivate(context, thisPtr->m_objectOfKey.Get(isolate)).ToLocal(&idValue) ||
1075+
!idValue->IsUint32()) {
1076+
return;
1077+
}
1078+
info.GetReturnValue().SetUndefined();
1079+
int id = static_cast<int>(idValue.As<Uint32>()->Value());
1080+
CanaryRecord* record = thisPtr->FindCanaryRecord(id);
1081+
if (record == nullptr || record->state.IsEmpty()) {
1082+
return;
1083+
}
1084+
Local<Value> recordKey;
1085+
if (!record->state.Get(isolate)->GetPrivate(context, thisPtr->m_keyOfState.Get(isolate))
1086+
.ToLocal(&recordKey) ||
1087+
!recordKey->StrictEquals(key)) {
1088+
return;
1089+
}
1090+
if (auto live = thisPtr->m_idToObject.Find(id)) {
1091+
info.GetReturnValue().Set(thisPtr->JsObjectFor(live));
1092+
return;
1093+
}
1094+
Local<Object> result = thisPtr->RebuildCanary(id);
1095+
if (result.IsEmpty() && thisPtr->FindCanaryRecord(id) != nullptr) {
1096+
// A plain object: a wrapper made from it the usual way is hydrated from its state.
1097+
JniLocalRef javaObject(thisPtr->JavaObjectOrNull(id));
1098+
if (!javaObject.IsNull()) {
1099+
result = thisPtr->GetOrCreateJSWrapper(javaObject);
1100+
}
1101+
}
1102+
if (!result.IsEmpty()) {
1103+
info.GetReturnValue().Set(result);
1104+
}
1105+
}
1106+
1107+
jobject ObjectManager::JavaObjectOrNull(int javaObjectID) {
1108+
JEnv env;
1109+
JNIEnv* raw = env;
1110+
AssertIsolateLocked();
1111+
// getJavaObjectByID throws for an id whose object was collected.
1112+
jobject object = raw->CallObjectMethod(m_javaRuntimeObject, GET_JAVAOBJECT_BY_ID_METHOD_ID,
1113+
javaObjectID);
1114+
if (raw->ExceptionCheck()) {
1115+
raw->ExceptionClear();
1116+
return nullptr;
1117+
}
1118+
return object;
1119+
}
1120+
10041121
void ObjectManager::ReleaseCollectedCanaryStates() {
10051122
if (!m_deathInboxOpen) {
10061123
return;
@@ -1301,6 +1418,8 @@ void ObjectManager::ReleaseAllRegistered() {
13011418
m_idToObject.ForEach([](ObjectWeakCallbackState* state) { state->record = nullptr; });
13021419
m_canaryRecords.clear();
13031420
m_instanceFieldTableKey.Reset();
1421+
m_keyOfState.Reset();
1422+
m_objectOfKey.Reset();
13041423

13051424
auto jsInfoIdx = static_cast<int>(MetadataNodeKeys::JsInfo);
13061425

0 commit comments

Comments
 (0)