From 79e52840f71d47c5213a76c646fc4a9467e5904e Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 14:17:35 -0300 Subject: [PATCH 01/15] 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. --- docs/ns-builtin-modules.md | 21 +- test-app/app/src/main/assets/app/mainpage.js | 1 + .../testWrapperLifetimeWeakCollections.js | 195 ++++++++++++++++++ test-app/runtime/CMakeLists.txt | 1 + .../runtime/src/main/cpp/ObjectManager.cpp | 119 +++++++++++ test-app/runtime/src/main/cpp/ObjectManager.h | 18 +- test-app/runtime/src/main/cpp/WeakRef.cpp | 12 ++ .../src/main/cpp/js/weak-collections.js | 146 +++++++++++++ 8 files changed, 509 insertions(+), 4 deletions(-) create mode 100644 test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js create mode 100644 test-app/runtime/src/main/cpp/js/weak-collections.js diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index b0f381b55..748e9a4cc 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -265,9 +265,24 @@ overrides either) is linked as a plain wrapper: under `"extended"`, a canary built later for one of its objects has the Java class's prototype, not `X.prototype`, and none of the old canary's JS properties. A canary built after another died is a new JS object, which `===` cannot tell -because nothing kept the old one, but which keys `WeakMap`, `WeakSet`, -`WeakRef` and `FinalizationRegistry` entries separately. -`__releaseNativeCounterpart` drops the object's state with its link. +because nothing kept the old one. `__releaseNativeCounterpart` drops the +object's state with its link. + +**Weak collections.** What could notice a new canary is whatever keys on the +old one without keeping it, so in canary mode a builtin +(`js/weak-collections.js`) 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. Entries and targets +therefore live exactly as long as the Java object; `WeakRef.prototype.deref` +(and the `get` alias) returns the live canary, a new one with the object's +state, or `undefined` once Java collected the object. `set`, `add`, +`getOrInsert`, `new WeakRef` and `register` create the key; lookups never do, +so probing an object gives it no state. A Proxy around a Java object stays a +key of its own, and every other value passes through to the standard +collection. The cost is the other side of the same rooting: a `WeakMap` value +that references its Java key keeps the key, its state and so the Java object +alive for as long as the map lives. Each operation costs one native call in +canary mode, whatever the key. Remote-module security (`security.allowRemoteModules`, `security.remoteModuleAllowlist`) is **not** part of this surface. Those diff --git a/test-app/app/src/main/assets/app/mainpage.js b/test-app/app/src/main/assets/app/mainpage.js index 5c5c185b5..a8b1d2014 100644 --- a/test-app/app/src/main/assets/app/mainpage.js +++ b/test-app/app/src/main/assets/app/mainpage.js @@ -65,6 +65,7 @@ require("./tests/testWrapperLifetimeModes"); require("./tests/testWrapperLifetimeStateWrites"); require("./tests/testWrapperLifetimeFieldWrites"); require("./tests/testWrapperLifetimeRecordSharing"); +require("./tests/testWrapperLifetimeWeakCollections"); require("./tests/testsMemoryManagement"); require("./tests/testFieldGetSet"); require("./tests/extendedClassesTests"); diff --git a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js new file mode 100644 index 000000000..2abbbbae3 --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js @@ -0,0 +1,195 @@ +// Holds in every wrapper lifetime mode: in "canary" the collections key a Java object by +// its lifetime key, elsewhere the wrapper itself outlives the JS references. +describe("Weak collections of Java objects", function () { + var runtime = require("ns:runtime"); + var mode = runtime.getConfig("wrapperLifetimeMode"); + var canary = mode === "canary"; + var Holder = com.tns.tests.WrapperHolder; + + function collectJava() { + for (var i = 0; i < 3; i++) { + java.lang.Runtime.getRuntime().gc(); + java.lang.System.runFinalization(); + } + } + + function crossIntoJava() { + java.lang.System.nanoTime(); + } + + // Lets JS drop every wrapper nothing references. + function collectBoth() { + gc(); + crossIntoJava(); + collectJava(); + gc(); + crossIntoJava(); + } + + function eventually(predicate, done, message) { + var deadline = Date.now() + 10000; + (function poll() { + collectBoth(); + collectJava(); + if (predicate()) { + done(); + return; + } + if (Date.now() > deadline) { + done.fail(message); + return; + } + setTimeout(poll, 50); + })(); + } + + // A JS-extended object, a canary in every canary scope; Java keeps it in Holder. + function heldRunnable() { + var runnable = new java.lang.Runnable({ run: function () {} }); + Holder.held = runnable; + return runnable; + } + + afterEach(function () { + Holder.held = null; + }); + + it("keeps a WeakMap entry for a Java object across a wrapper change (" + mode + ")", function () { + var map = new WeakMap(); + (function () { + map.set(heldRunnable(), "value"); + })(); + collectBoth(); + + var again = Holder.held; + expect(map.has(again)).toBe(true); + expect(map.get(again)).toBe("value"); + expect(map.delete(again)).toBe(true); + expect(map.has(again)).toBe(false); + }); + + it("keeps a WeakSet member for a Java object across a wrapper change", function () { + var set = new WeakSet(); + (function () { + set.add(heldRunnable()); + })(); + collectBoth(); + + expect(set.has(Holder.held)).toBe(true); + }); + + it("keeps a getOrInsert entry for a Java object across a wrapper change", function () { + var map = new WeakMap(); + if (typeof map.getOrInsert !== "function") { + return; + } + (function () { + map.getOrInsert(heldRunnable(), "first"); + })(); + collectBoth(); + + expect(map.getOrInsert(Holder.held, "second")).toBe("first"); + var seen; + expect(map.getOrInsertComputed(Holder.held, function (key) { + seen = key; + return "computed"; + })).toBe("first"); + expect(seen).toBeUndefined(); + }); + + it("dereferences a WeakRef to a Java-held object while the object lives", function () { + var ref = (function () { + var runnable = heldRunnable(); + runnable.tag = "state"; + return new WeakRef(runnable); + })(); + collectBoth(); + + var target = ref.deref(); + expect(target).toBeDefined(); + expect(target.tag).toBe("state"); + expect(ref.get()).toBe(target); + expect(target.equals(Holder.held)).toBe(true); + }); + + it("clears a WeakRef once Java collected the object", function (done) { + var ref = (function () { + return new WeakRef(new java.lang.Runnable({ run: function () {} })); + })(); + eventually(function () { + return ref.deref() === undefined; + }, done, "the WeakRef still dereferences"); + }); + + it("runs a FinalizationRegistry callback once Java collected the object", function (done) { + var cleaned = false; + var registry = new FinalizationRegistry(function (held) { + cleaned = held === "held"; + }); + (function () { + registry.register(new java.lang.Runnable({ run: function () {} }), "held"); + })(); + eventually(function () { + return cleaned; + }, done, "the cleanup callback did not run"); + }); + + it("unregisters a FinalizationRegistry target through a later wrapper of its token", function () { + var registry = new FinalizationRegistry(function () {}); + var target = {}; + (function () { + var runnable = heldRunnable(); + registry.register(target, "held", runnable); + })(); + collectBoth(); + + expect(registry.unregister(Holder.held)).toBe(true); + expect(target).toBeDefined(); + }); + + it("rejects a FinalizationRegistry registration whose target is its held value", function () { + var registry = new FinalizationRegistry(function () {}); + var runnable = new java.lang.Runnable({ run: function () {} }); + expect(function () { + registry.register(runnable, runnable); + }).toThrowError(TypeError); + }); + + it("keys a Proxy around a Java object by the Proxy", function () { + var runnable = new java.lang.Runnable({ run: function () {} }); + var proxy = new Proxy(runnable, {}); + var map = new WeakMap(); + map.set(proxy, "proxy"); + expect(map.get(proxy)).toBe("proxy"); + expect(map.has(runnable)).toBe(false); + }); + + it("does not give state to a Java object a lookup only probes", function () { + var map = new WeakMap(); + var set = new WeakSet(); + var runnable = new java.lang.Runnable({ run: function () {} }); + var states = runtime.getWrapperLifetimeStats().canaryStates; + expect(map.get(runnable)).toBeUndefined(); + expect(map.has(runnable)).toBe(false); + expect(set.has(runnable)).toBe(false); + expect(map.delete(runnable)).toBe(false); + expect(runtime.getWrapperLifetimeStats().canaryStates).toBe(states); + }); + + it("keeps working as the standard collections for other keys", function () { + var map = new WeakMap([[Object, 1]]); + var key = {}; + map.set(key, 2); + expect(map.get(Object)).toBe(1); + expect(map.get(key)).toBe(2); + var ref = new WeakRef(key); + expect(ref.deref()).toBe(key); + expect(new WeakSet([key]).has(key)).toBe(true); + expect(map instanceof WeakMap).toBe(true); + }); + + it("installs the canary collections only in canary mode", function () { + var native = WeakMap.toString().indexOf("[native code]") !== -1; + expect(native).toBe(!canary); + }); +}); diff --git a/test-app/runtime/CMakeLists.txt b/test-app/runtime/CMakeLists.txt index e50fbb951..707ecec1c 100644 --- a/test-app/runtime/CMakeLists.txt +++ b/test-app/runtime/CMakeLists.txt @@ -100,6 +100,7 @@ set(RUNTIME_BUILTIN_JS ${RUNTIME_BUILTIN_JS_DIR}/require-factory.js ${RUNTIME_BUILTIN_JS_DIR}/structured-clone.js ${RUNTIME_BUILTIN_JS_DIR}/text-encoding.js + ${RUNTIME_BUILTIN_JS_DIR}/weak-collections.js ${RUNTIME_BUILTIN_JS_DIR}/weak-ref.js ${RUNTIME_BUILTIN_JS_DIR}/worker-events.js ) diff --git a/test-app/runtime/src/main/cpp/ObjectManager.cpp b/test-app/runtime/src/main/cpp/ObjectManager.cpp index d8e7b7b99..90547d59a 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -117,6 +117,8 @@ void ObjectManager::Init(Isolate* isolate) { if (WrapperLifetimeCanary::Enabled()) { m_instanceFieldTableKey.Reset(isolate, Private::New(isolate)); + m_keyOfState.Reset(isolate, Private::New(isolate)); + m_objectOfKey.Reset(isolate, Private::New(isolate)); isolate->AddGCEpilogueCallback(CanaryGCEpilogue, this); m_canaryEpilogueAdded = true; } @@ -1206,6 +1208,121 @@ std::map ObjectManager::GetWrapperClass return counts; } +bool ObjectManager::AddWeakCollectionFunctions(Local context, Local binding) { + auto isolate = m_isolate; + Local unwrap; + Local wrap; + return Function::New(context, UnwrapForWeakCollection).ToLocal(&unwrap) && + Function::New(context, WrapForWeakCollection).ToLocal(&wrap) && + binding->Set(context, ArgConverter::ConvertToV8String(isolate, "unwrap"), unwrap) + .FromMaybe(false) && + binding->Set(context, ArgConverter::ConvertToV8String(isolate, "wrap"), wrap) + .FromMaybe(false); +} + +// unwrap(value, create): the weak collections' key for a canary's Java object, +// a frozen, null-prototype object that lives as long as the object's state, +// that is, until Java collects the object. Lookups pass `create` false and never +// make one: with no key yet, no entry can be keyed by it. The value itself for +// anything that is not a canary, a Proxy included (it is a key of its own). +void ObjectManager::UnwrapForWeakCollection(const FunctionCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + Local value = info[0]; + bool create = info[1]->IsTrue(); + info.GetReturnValue().Set(value); + if (!value->IsObject() || value->IsProxy()) { + return; + } + ObjectManager* thisPtr = Runtime::GetObjectManager(isolate); + Local holder = value.As(); + Local state; + if (create ? !thisPtr->CanaryStateForWrite(holder, &state) + : !thisPtr->ExistingCanaryState(holder, &state)) { + return; + } + Local context = isolate->GetCurrentContext(); + Local keyOfState = thisPtr->m_keyOfState.Get(isolate); + Local key; + if (state->GetPrivate(context, keyOfState).ToLocal(&key) && key->IsObject()) { + info.GetReturnValue().Set(key); + return; + } + if (!create) { + return; + } + Local newKey = Object::New(isolate, Null(isolate), nullptr, nullptr, 0); + if (!newKey + ->SetPrivate(context, thisPtr->m_objectOfKey.Get(isolate), + Integer::NewFromUnsigned(isolate, static_cast(LinkedIdOf(holder)))) + .FromMaybe(false) || + !newKey->SetIntegrityLevel(context, IntegrityLevel::kFrozen).FromMaybe(false) || + !state->SetPrivate(context, keyOfState, newKey).FromMaybe(false)) { + return; + } + info.GetReturnValue().Set(newKey); +} + +// wrap(key): the Java object a key stands for, as its live canary or a new one +// with its state, or undefined once Java collected it. Anything that is not a +// key passes through. +void ObjectManager::WrapForWeakCollection(const FunctionCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + Local value = info[0]; + info.GetReturnValue().Set(value); + if (!value->IsObject()) { + return; + } + ObjectManager* thisPtr = Runtime::GetObjectManager(isolate); + Local context = isolate->GetCurrentContext(); + Local key = value.As(); + Local idValue; + if (!key->GetPrivate(context, thisPtr->m_objectOfKey.Get(isolate)).ToLocal(&idValue) || + !idValue->IsUint32()) { + return; + } + info.GetReturnValue().SetUndefined(); + int id = static_cast(idValue.As()->Value()); + CanaryRecord* record = thisPtr->FindCanaryRecord(id); + if (record == nullptr || record->state.IsEmpty()) { + return; + } + Local recordKey; + if (!record->state.Get(isolate)->GetPrivate(context, thisPtr->m_keyOfState.Get(isolate)) + .ToLocal(&recordKey) || + !recordKey->StrictEquals(key)) { + return; + } + if (auto live = thisPtr->m_idToObject.Find(id)) { + info.GetReturnValue().Set(thisPtr->JsObjectFor(live)); + return; + } + Local result = thisPtr->RebuildCanary(id); + if (result.IsEmpty() && thisPtr->FindCanaryRecord(id) != nullptr) { + // A plain object: a wrapper made from it the usual way is hydrated from its state. + JniLocalRef javaObject(thisPtr->JavaObjectOrNull(id)); + if (!javaObject.IsNull()) { + result = thisPtr->GetOrCreateJSWrapper(javaObject); + } + } + if (!result.IsEmpty()) { + info.GetReturnValue().Set(result); + } +} + +jobject ObjectManager::JavaObjectOrNull(int javaObjectID) { + JEnv env; + JNIEnv* raw = env; + AssertIsolateLocked(); + // getJavaObjectByID throws for an id whose object was collected. + jobject object = raw->CallObjectMethod(m_javaRuntimeObject, GET_JAVAOBJECT_BY_ID_METHOD_ID, + javaObjectID); + if (raw->ExceptionCheck()) { + raw->ExceptionClear(); + return nullptr; + } + return object; +} + void ObjectManager::ReleaseCollectedCanaryStates() { if (!m_deathInboxOpen) { return; @@ -1526,7 +1643,9 @@ void ObjectManager::ReleaseAllRegistered() { m_canaryRecords.DrainAll([](CanaryRecord* record) { delete record; }); m_canaryRecordCount = 0; m_instanceFieldTableKey.Reset(); + m_keyOfState.Reset(); m_emptyState.Reset(); + m_objectOfKey.Reset(); auto jsInfoIdx = static_cast(MetadataNodeKeys::JsInfo); diff --git a/test-app/runtime/src/main/cpp/ObjectManager.h b/test-app/runtime/src/main/cpp/ObjectManager.h index e8da69dbe..87ffe25f3 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -284,6 +284,12 @@ class ObjectManager { // Per Java class name (dotted), for ns:runtime's getWrapperClassCounts(). std::map GetWrapperClassCounts(); + // Canary mode: adds `unwrap` (a canary -> its Java object's weak-collection + // key) and `wrap` (key -> live or new canary, or undefined once Java + // collected the object) to binding, for js/weak-collections.js. + bool AddWeakCollectionFunctions(v8::Local context, + v8::Local binding); + private: static void InitializeJNI(); @@ -541,12 +547,22 @@ class ObjectManager { std::vector m_pendingCanaryDeaths; bool m_copyingCanaryProperties = false; bool m_deathInboxOpen = false; - bool m_canaryEpilogueAdded = false; int m_deathInboxRuntimeId = -1; v8::Persistent m_instanceFieldTableKey; // Cloned for each new state; never handed to JS. v8::Global m_emptyState; v8::Local NewEmptyState(); + bool m_canaryEpilogueAdded = false; + // The weak-collection key of a canary's Java object hangs off its state + // object, and names the object's id. + v8::Persistent m_keyOfState; + v8::Persistent m_objectOfKey; + + static void UnwrapForWeakCollection(const v8::FunctionCallbackInfo& info); + static void WrapForWeakCollection(const v8::FunctionCallbackInfo& info); + + // id's Java object, or null once Java collected it. + jobject JavaObjectOrNull(int javaObjectID); void JSObjectFinalizer(v8::Isolate* isolate, ObjectWeakCallbackState* callbackState); diff --git a/test-app/runtime/src/main/cpp/WeakRef.cpp b/test-app/runtime/src/main/cpp/WeakRef.cpp index 68c85512f..c6be39871 100644 --- a/test-app/runtime/src/main/cpp/WeakRef.cpp +++ b/test-app/runtime/src/main/cpp/WeakRef.cpp @@ -1,4 +1,7 @@ #include "WeakRef.h" +#include "ObjectManager.h" +#include "Runtime.h" +#include "WrapperLifetimeCanary.h" #include "NativeScriptAssert.h" #include "ArgConverter.h" #include "BuiltinLoader.h" @@ -17,4 +20,13 @@ WeakRef::WeakRef() { void WeakRef::Init(v8::Isolate* isolate, Local context) { bool success = !BuiltinLoader::RunBuiltin(context, BuiltinId::kWeakRef).IsEmpty(); NS_DCHECK(success); + + if (!WrapperLifetimeCanary::Enabled()) { + return; + } + // Canary mode: the weak collections key Java objects, not their canaries. + auto binding = Object::New(isolate); + success = Runtime::GetObjectManager(isolate)->AddWeakCollectionFunctions(context, binding) && + !BuiltinLoader::RunBuiltin(context, BuiltinId::kWeakCollections, binding).IsEmpty(); + NS_CHECK(success); } diff --git a/test-app/runtime/src/main/cpp/js/weak-collections.js b/test-app/runtime/src/main/cpp/js/weak-collections.js new file mode 100644 index 000000000..88465c6d9 --- /dev/null +++ b/test-app/runtime/src/main/cpp/js/weak-collections.js @@ -0,0 +1,146 @@ +"use strict"; + +// Canary wrapper lifetime mode only (run by WeakRef.cpp): WeakMap, WeakSet, +// WeakRef and FinalizationRegistry key a Java object by its lifetime key +// instead of its wrapper. The wrapper is a canary that dies with its JS +// references while the Java object lives on, and a later wrapper for the same +// object is a new JS object; keyed by the wrapper, entries and targets would be +// lost with it. Every other value passes through unchanged. + +const { unwrap, wrap } = binding; +const { ObjectDefineProperty, TypeError } = primordials; +const { + FinalizationRegistry: NativeFinalizationRegistry, + WeakMap: NativeWeakMap, + WeakRef: NativeWeakRef, + WeakSet: NativeWeakSet, +} = globalThis; + +// unwrap(value, true) makes the key on first use; lookups pass false so they +// never create state for an object that was never a key. +class WeakMap extends NativeWeakMap { + get(key) { + return super.get(unwrap(key, false)); + } + + set(key, value) { + super.set(unwrap(key, true), value); + return this; + } + + has(key) { + return super.has(unwrap(key, false)); + } + + delete(key) { + return super.delete(unwrap(key, false)); + } +} + +// V8 ships the upsert proposal; inherited, these would key on the wrapper. +if (typeof NativeWeakMap.prototype.getOrInsert === "function") { + ObjectDefineProperty(WeakMap.prototype, "getOrInsert", { + value: function getOrInsert(key, value) { + return NativeWeakMap.prototype.getOrInsert.call(this, unwrap(key, true), value); + }, + writable: true, + configurable: true, + }); +} +if (typeof NativeWeakMap.prototype.getOrInsertComputed === "function") { + ObjectDefineProperty(WeakMap.prototype, "getOrInsertComputed", { + value: function getOrInsertComputed(key, callbackfn) { + if (typeof callbackfn !== "function") { + throw new TypeError("WeakMap.prototype.getOrInsertComputed: callback is not a function"); + } + // The callback sees the key it was given, not the lifetime key. + return NativeWeakMap.prototype.getOrInsertComputed.call(this, unwrap(key, true), () => + callbackfn(key), + ); + }, + writable: true, + configurable: true, + }); +} + +class WeakSet extends NativeWeakSet { + add(value) { + super.add(unwrap(value, true)); + return this; + } + + has(value) { + return super.has(unwrap(value, false)); + } + + delete(value) { + return super.delete(unwrap(value, false)); + } +} + +class WeakRef extends NativeWeakRef { + constructor(target) { + const key = unwrap(target, true); + super(key); + // The target itself, not only its key, stays alive until the job ends. + if (key !== target) { + new NativeWeakRef(target); + } + } + + // The live wrapper, a new one if the old one died while the Java object + // lived, or undefined once the Java object is gone. Like a native WeakRef + // target, the wrapper it returns stays alive until the job ends, so a second + // deref in the same job sees the same object. + deref() { + const result = wrap(super.deref()); + if (typeof result === "object" && result !== null) { + new NativeWeakRef(result); + } + return result; + } +} + +// weak-ref.js gave the native prototype `get` (an alias of `deref`) and a +// deprecated `clear`; inherited as is, `get` would hand out the lifetime key. +ObjectDefineProperty(WeakRef.prototype, "get", { + value: WeakRef.prototype.deref, + writable: true, + configurable: true, +}); + +class FinalizationRegistry extends NativeFinalizationRegistry { + constructor(cleanupCallback) { + super(cleanupCallback); + } + + register(target, heldValue, unregisterToken) { + // Checked on the original values: unwrapping would make them differ. + if (target === heldValue) { + throw new TypeError("FinalizationRegistry.prototype.register: target and holdings must not be same"); + } + super.register( + unwrap(target, true), + heldValue, + unregisterToken === undefined ? undefined : unwrap(unregisterToken, true), + ); + } + + unregister(unregisterToken) { + return super.unregister(unwrap(unregisterToken, false)); + } +} + +for (const [name, value] of [ + ["WeakMap", WeakMap], + ["WeakSet", WeakSet], + ["WeakRef", WeakRef], + ["FinalizationRegistry", FinalizationRegistry], +]) { + ObjectDefineProperty(globalThis, name, { + value, + writable: true, + configurable: true, + enumerable: false, + }); +} From 8355beac19f2d86381d55a9c0eba849c50612b0a Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 15:28:42 -0300 Subject: [PATCH 02/15] test(runtime): weak collections across a real wrapper change, plain objects included A WeakRef keeps its target alive until its job ends, so the deref spec now collects on a later task, where the canary actually changes. Adds a plain Java-held object's WeakMap entry and WeakRef target. --- .../testWrapperLifetimeWeakCollections.js | 49 ++++++++++++++++--- 1 file changed, 42 insertions(+), 7 deletions(-) diff --git a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js index 2abbbbae3..1ea8867a2 100644 --- a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js @@ -97,19 +97,54 @@ describe("Weak collections of Java objects", function () { expect(seen).toBeUndefined(); }); - it("dereferences a WeakRef to a Java-held object while the object lives", function () { + // A WeakRef keeps its target alive until the job that made it ends, so the wrapper can + // only change on a later task. + it("dereferences a WeakRef to a Java-held object while the object lives", function (done) { + var rebuilds = runtime.getWrapperLifetimeStats().canaryRebuilds; var ref = (function () { var runnable = heldRunnable(); runnable.tag = "state"; return new WeakRef(runnable); })(); - collectBoth(); + setTimeout(function () { + collectBoth(); + if (canary) { + // Rebuilt by deref below, not by anything this spec kept. + expect(runtime.getWrapperLifetimeStats().canaryRebuilds).toBe(rebuilds); + } + var target = ref.deref(); + expect(target).toBeDefined(); + expect(target.tag).toBe("state"); + expect(ref.get()).toBe(target); + expect(target.equals(Holder.held)).toBe(true); + if (canary) { + expect(runtime.getWrapperLifetimeStats().canaryRebuilds).toBe(rebuilds + 1); + } + done(); + }, 0); + }); - var target = ref.deref(); - expect(target).toBeDefined(); - expect(target.tag).toBe("state"); - expect(ref.get()).toBe(target); - expect(target.equals(Holder.held)).toBe(true); + // Under scope "all" a plain wrapper is a canary: its key hangs off its state, and deref + // makes a new wrapper the usual way, hydrated from the state. + it("keeps a WeakMap entry and a WeakRef target for a Java-held plain object across a wrapper change", function (done) { + var map = new WeakMap(); + var ref = (function () { + var builder = new java.lang.StringBuilder("plain"); + builder.tag = "state"; + map.set(builder, "value"); + Holder.held = builder; + return new WeakRef(builder); + })(); + setTimeout(function () { + collectBoth(); + var again = Holder.held; + expect(map.get(again)).toBe("value"); + var target = ref.deref(); + expect(target).toBeDefined(); + expect(target.toString()).toBe("plain"); + expect(target.tag).toBe("state"); + done(); + }, 0); }); it("clears a WeakRef once Java collected the object", function (done) { From 9ec742d94a39bd3a32c359879f5bbda8c5705da7 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 19:07:24 -0300 Subject: [PATCH 03/15] test(runtime): give the polling weak collection specs a timeout past their deadline eventually() polls for up to 10 s, past Jasmine's default 5 s timeout. --- .../assets/app/tests/testWrapperLifetimeWeakCollections.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js index 1ea8867a2..de3aa9957 100644 --- a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js @@ -154,7 +154,7 @@ describe("Weak collections of Java objects", function () { eventually(function () { return ref.deref() === undefined; }, done, "the WeakRef still dereferences"); - }); + }, 20000); it("runs a FinalizationRegistry callback once Java collected the object", function (done) { var cleaned = false; @@ -167,7 +167,7 @@ describe("Weak collections of Java objects", function () { eventually(function () { return cleaned; }, done, "the cleanup callback did not run"); - }); + }, 20000); it("unregisters a FinalizationRegistry target through a later wrapper of its token", function () { var registry = new FinalizationRegistry(function () {}); From 7df60a8eee0f7867e8a1b7cd671cde3d1035dcc9 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 20:27:53 -0300 Subject: [PATCH 04/15] refactor(runtime): keep the canary members in their original order The weak-collections change swapped two unrelated ObjectManager members for no reason; put them back so the diff shows only what it adds. --- test-app/runtime/src/main/cpp/ObjectManager.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test-app/runtime/src/main/cpp/ObjectManager.h b/test-app/runtime/src/main/cpp/ObjectManager.h index 87ffe25f3..d360b9df4 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -547,12 +547,12 @@ class ObjectManager { std::vector m_pendingCanaryDeaths; bool m_copyingCanaryProperties = false; bool m_deathInboxOpen = false; + bool m_canaryEpilogueAdded = false; int m_deathInboxRuntimeId = -1; v8::Persistent m_instanceFieldTableKey; // Cloned for each new state; never handed to JS. v8::Global m_emptyState; v8::Local NewEmptyState(); - bool m_canaryEpilogueAdded = false; // The weak-collection key of a canary's Java object hangs off its state // object, and names the object's id. v8::Persistent m_keyOfState; From 6c767afa2148c5227da5fd644d247e13f603fa5d Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 20:30:37 -0300 Subject: [PATCH 05/15] fix(runtime): a released canary keeps what weak collections keyed on it __releaseNativeCounterpart on a live canary erased its record, the state and with it the object's weak-collection key, so while the wrapper was still held map.get(w) and ref.deref() returned undefined and a FinalizationRegistry callback for w ran at the next collection. The released canary is a plain JS object from then on, and what was keyed on it should behave as on one. Before the record goes, the key moves onto the canary itself and a private on the key leads back to it: unwrap returns that key for the released wrapper, wrap returns the wrapper for the key, and the two die together. The weak-collection natives also gain the exception boundary other V8 callbacks have, rethrowing C++ exceptions to V8 (RebuildCanary and GetOrCreateJSWrapper can throw), and find the object manager without throwing when the isolate has no runtime. --- .../runtime/src/main/cpp/ObjectManager.cpp | 211 ++++++++++++------ test-app/runtime/src/main/cpp/ObjectManager.h | 8 +- 2 files changed, 149 insertions(+), 70 deletions(-) diff --git a/test-app/runtime/src/main/cpp/ObjectManager.cpp b/test-app/runtime/src/main/cpp/ObjectManager.cpp index 90547d59a..80299d4ff 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -119,6 +119,7 @@ void ObjectManager::Init(Isolate* isolate) { m_instanceFieldTableKey.Reset(isolate, Private::New(isolate)); m_keyOfState.Reset(isolate, Private::New(isolate)); m_objectOfKey.Reset(isolate, Private::New(isolate)); + m_releasedOfKey.Reset(isolate, Private::New(isolate)); isolate->AddGCEpilogueCallback(CanaryGCEpilogue, this); m_canaryEpilogueAdded = true; } @@ -1225,88 +1226,156 @@ bool ObjectManager::AddWeakCollectionFunctions(Local context, LocalGetObjectManager() : nullptr; +} + +void RethrowToV8(const char* what) { + NativeScriptException nsEx(std::string("Error: c++ exception: ") + what); + nsEx.ReThrowToV8(); +} +} // namespace + void ObjectManager::UnwrapForWeakCollection(const FunctionCallbackInfo& info) { - Isolate* isolate = info.GetIsolate(); - Local value = info[0]; - bool create = info[1]->IsTrue(); - info.GetReturnValue().Set(value); - if (!value->IsObject() || value->IsProxy()) { - return; - } - ObjectManager* thisPtr = Runtime::GetObjectManager(isolate); - Local holder = value.As(); - Local state; - if (create ? !thisPtr->CanaryStateForWrite(holder, &state) - : !thisPtr->ExistingCanaryState(holder, &state)) { - return; - } - Local context = isolate->GetCurrentContext(); - Local keyOfState = thisPtr->m_keyOfState.Get(isolate); - Local key; - if (state->GetPrivate(context, keyOfState).ToLocal(&key) && key->IsObject()) { - info.GetReturnValue().Set(key); - return; - } - if (!create) { - return; - } - Local newKey = Object::New(isolate, Null(isolate), nullptr, nullptr, 0); - if (!newKey - ->SetPrivate(context, thisPtr->m_objectOfKey.Get(isolate), - Integer::NewFromUnsigned(isolate, static_cast(LinkedIdOf(holder)))) - .FromMaybe(false) || - !newKey->SetIntegrityLevel(context, IntegrityLevel::kFrozen).FromMaybe(false) || - !state->SetPrivate(context, keyOfState, newKey).FromMaybe(false)) { - return; + try { + Isolate* isolate = info.GetIsolate(); + Local value = info[0]; + bool create = info[1]->IsTrue(); + info.GetReturnValue().Set(value); + if (!value->IsObject() || value->IsProxy()) { + return; + } + ObjectManager* thisPtr = WeakCollectionManagerOf(isolate); + if (thisPtr == nullptr) { + return; + } + Local holder = value.As(); + Local context = isolate->GetCurrentContext(); + Local keyOfState = thisPtr->m_keyOfState.Get(isolate); + Local key; + Local state; + if (create ? !thisPtr->CanaryStateForWrite(holder, &state) + : !thisPtr->ExistingCanaryState(holder, &state)) { + // A canary whose link was released keeps its key itself. + if (HasMetadataField(holder) && holder->GetPrivate(context, keyOfState).ToLocal(&key) && + key->IsObject()) { + info.GetReturnValue().Set(key); + } + return; + } + if (state->GetPrivate(context, keyOfState).ToLocal(&key) && key->IsObject()) { + info.GetReturnValue().Set(key); + return; + } + if (!create) { + return; + } + Local newKey = Object::New(isolate, Null(isolate), nullptr, nullptr, 0); + if (!newKey + ->SetPrivate(context, thisPtr->m_objectOfKey.Get(isolate), + Integer::NewFromUnsigned(isolate, static_cast(LinkedIdOf(holder)))) + .FromMaybe(false) || + !newKey->SetIntegrityLevel(context, IntegrityLevel::kFrozen).FromMaybe(false) || + !state->SetPrivate(context, keyOfState, newKey).FromMaybe(false)) { + return; + } + info.GetReturnValue().Set(newKey); + } catch (NativeScriptException& e) { + e.ReThrowToV8(); + } catch (std::exception& e) { + RethrowToV8(e.what()); + } catch (...) { + RethrowToV8("unknown"); } - info.GetReturnValue().Set(newKey); } // wrap(key): the Java object a key stands for, as its live canary or a new one // with its state, or undefined once Java collected it. Anything that is not a // key passes through. void ObjectManager::WrapForWeakCollection(const FunctionCallbackInfo& info) { - Isolate* isolate = info.GetIsolate(); - Local value = info[0]; - info.GetReturnValue().Set(value); - if (!value->IsObject()) { - return; - } - ObjectManager* thisPtr = Runtime::GetObjectManager(isolate); - Local context = isolate->GetCurrentContext(); - Local key = value.As(); - Local idValue; - if (!key->GetPrivate(context, thisPtr->m_objectOfKey.Get(isolate)).ToLocal(&idValue) || - !idValue->IsUint32()) { - return; - } - info.GetReturnValue().SetUndefined(); - int id = static_cast(idValue.As()->Value()); - CanaryRecord* record = thisPtr->FindCanaryRecord(id); - if (record == nullptr || record->state.IsEmpty()) { - return; + try { + Isolate* isolate = info.GetIsolate(); + Local value = info[0]; + info.GetReturnValue().Set(value); + if (!value->IsObject()) { + return; + } + ObjectManager* thisPtr = WeakCollectionManagerOf(isolate); + if (thisPtr == nullptr) { + return; + } + Local context = isolate->GetCurrentContext(); + Local key = value.As(); + Local idValue; + if (!key->GetPrivate(context, thisPtr->m_objectOfKey.Get(isolate)).ToLocal(&idValue) || + !idValue->IsUint32()) { + return; + } + // The key of a released canary lives exactly as long as the canary. + Local released; + if (key->GetPrivate(context, thisPtr->m_releasedOfKey.Get(isolate)).ToLocal(&released) && + released->IsObject()) { + info.GetReturnValue().Set(released); + return; + } + info.GetReturnValue().SetUndefined(); + int id = static_cast(idValue.As()->Value()); + CanaryRecord* record = thisPtr->FindCanaryRecord(id); + if (record == nullptr || record->state.IsEmpty()) { + return; + } + Local recordKey; + if (!record->state.Get(isolate)->GetPrivate(context, thisPtr->m_keyOfState.Get(isolate)) + .ToLocal(&recordKey) || + !recordKey->StrictEquals(key)) { + return; + } + if (auto live = thisPtr->m_idToObject.Find(id)) { + info.GetReturnValue().Set(thisPtr->JsObjectFor(live)); + return; + } + Local result = thisPtr->RebuildCanary(id); + if (result.IsEmpty() && thisPtr->FindCanaryRecord(id) != nullptr) { + // A plain object: a wrapper made from it the usual way is hydrated from its state. + JniLocalRef javaObject(thisPtr->JavaObjectOrNull(id)); + if (!javaObject.IsNull()) { + result = thisPtr->GetOrCreateJSWrapper(javaObject); + } + } + if (!result.IsEmpty()) { + info.GetReturnValue().Set(result); + } + } catch (NativeScriptException& e) { + e.ReThrowToV8(); + } catch (std::exception& e) { + RethrowToV8(e.what()); + } catch (...) { + RethrowToV8("unknown"); } - Local recordKey; - if (!record->state.Get(isolate)->GetPrivate(context, thisPtr->m_keyOfState.Get(isolate)) - .ToLocal(&recordKey) || - !recordKey->StrictEquals(key)) { +} + +void ObjectManager::KeepWeakCollectionKey(int javaObjectID) { + CanaryRecord* record = FindCanaryRecord(javaObjectID); + auto live = m_idToObject.Find(javaObjectID); + if (record == nullptr || record->state.IsEmpty() || live == nullptr || !live->canary || + m_keyOfState.IsEmpty()) { return; } - if (auto live = thisPtr->m_idToObject.Find(id)) { - info.GetReturnValue().Set(thisPtr->JsObjectFor(live)); + Local context = m_isolate->GetCurrentContext(); + Local keyOfState = m_keyOfState.Get(m_isolate); + Local key; + if (!record->state.Get(m_isolate)->GetPrivate(context, keyOfState).ToLocal(&key) || + !key->IsObject()) { return; } - Local result = thisPtr->RebuildCanary(id); - if (result.IsEmpty() && thisPtr->FindCanaryRecord(id) != nullptr) { - // A plain object: a wrapper made from it the usual way is hydrated from its state. - JniLocalRef javaObject(thisPtr->JavaObjectOrNull(id)); - if (!javaObject.IsNull()) { - result = thisPtr->GetOrCreateJSWrapper(javaObject); - } - } - if (!result.IsEmpty()) { - info.GetReturnValue().Set(result); - } + // Private symbols bypass the canary's write handler, and V8 lets them be + // added to the frozen key. + Local canary = Local::New(m_isolate, *live->target); + (void)canary->SetPrivate(context, keyOfState, key); + (void)key.As()->SetPrivate(context, m_releasedOfKey.Get(m_isolate), canary); } jobject ObjectManager::JavaObjectOrNull(int javaObjectID) { @@ -1646,6 +1715,7 @@ void ObjectManager::ReleaseAllRegistered() { m_keyOfState.Reset(); m_emptyState.Reset(); m_objectOfKey.Reset(); + m_releasedOfKey.Reset(); auto jsInfoIdx = static_cast(MetadataNodeKeys::JsInfo); @@ -1768,6 +1838,9 @@ void ObjectManager::ReleaseNativeCounterpart(v8::Local& object) { javaObjectID); m_releaseCount++; m_lifetimeStats.releasedExplicitly++; + // What weak collections keyed on the object stays keyed on the released + // canary, now a plain JS object, for as long as it lives. + KeepWeakCollectionKey(javaObjectID); // Java no longer knows the id, so nothing could rebuild a canary from it. EraseCanaryRecord(javaObjectID); diff --git a/test-app/runtime/src/main/cpp/ObjectManager.h b/test-app/runtime/src/main/cpp/ObjectManager.h index d360b9df4..1f6c1c77d 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -554,9 +554,15 @@ class ObjectManager { v8::Global m_emptyState; v8::Local NewEmptyState(); // The weak-collection key of a canary's Java object hangs off its state - // object, and names the object's id. + // object, and names the object's id. Once the canary's link is released, + // the canary holds the key and the key leads back to the canary. v8::Persistent m_keyOfState; v8::Persistent m_objectOfKey; + v8::Persistent m_releasedOfKey; + + // Moves id's weak-collection key from its state to its live canary, whose + // link is being released. + void KeepWeakCollectionKey(int javaObjectID); static void UnwrapForWeakCollection(const v8::FunctionCallbackInfo& info); static void WrapForWeakCollection(const v8::FunctionCallbackInfo& info); From e1501b09c25b99c576ab4f6e3965dbe48dee373b Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 20:30:37 -0300 Subject: [PATCH 06/15] fix(runtime): weak collections validate before they make a key - A canary's key and state are made only once the call can no longer fail: set, add, getOrInsert and register check their receiver first (WeakMap.prototype.set.call({}, canary, v) left a state and key behind), register leaves an invalid target or token to the native method, and getOrInsertComputed runs its callback before making the key, so a callback that throws leaves none. It no longer allocates a closure either. - register keeps the native length (2) and errors: register(1, 1) reports the invalid target rather than target and holdings being the same. - WeakRef.prototype.deref keeps the result alive for the job only when wrap() replaced what the native deref returned; it did so for every target. - The native methods are captured at startup through primordials, which gains WeakMap and its methods and Symbol.keyFor, instead of being resolved through super and the native prototype at call time. - Values that cannot be canaries skip the native unwrap call. --- .../runtime/src/main/cpp/js/primordials.js | 11 ++ .../src/main/cpp/js/weak-collections.js | 125 +++++++++++++----- 2 files changed, 106 insertions(+), 30 deletions(-) diff --git a/test-app/runtime/src/main/cpp/js/primordials.js b/test-app/runtime/src/main/cpp/js/primordials.js index b8bb6f2dd..1521754c7 100644 --- a/test-app/runtime/src/main/cpp/js/primordials.js +++ b/test-app/runtime/src/main/cpp/js/primordials.js @@ -37,12 +37,14 @@ const intrinsics = { Uint32Array, URIError, URL, + WeakMap, WeakRef, WeakSet, // Well-known symbols. SymbolFor: Symbol.for, SymbolIterator: Symbol.iterator, + SymbolKeyFor: Symbol.keyFor, SymbolToStringTag: Symbol.toStringTag, // Namespaces / prototypes. @@ -108,6 +110,15 @@ const intrinsics = { StringPrototypeSlice: uncurryThis(String.prototype.slice), StringPrototypeStartsWith: uncurryThis(String.prototype.startsWith), SymbolPrototypeToString: uncurryThis(Symbol.prototype.toString), + WeakMapPrototypeDelete: uncurryThis(WeakMap.prototype.delete), + WeakMapPrototypeGet: uncurryThis(WeakMap.prototype.get), + // The upsert proposal: undefined where V8 does not ship it. + WeakMapPrototypeGetOrInsert: typeof WeakMap.prototype.getOrInsert === "function" + ? uncurryThis(WeakMap.prototype.getOrInsert) : undefined, + WeakMapPrototypeGetOrInsertComputed: typeof WeakMap.prototype.getOrInsertComputed === "function" + ? uncurryThis(WeakMap.prototype.getOrInsertComputed) : undefined, + WeakMapPrototypeHas: uncurryThis(WeakMap.prototype.has), + WeakMapPrototypeSet: uncurryThis(WeakMap.prototype.set), WeakRefPrototypeDeref: uncurryThis(WeakRef.prototype.deref), WeakSetPrototypeAdd: uncurryThis(WeakSet.prototype.add), WeakSetPrototypeDelete: uncurryThis(WeakSet.prototype.delete), diff --git a/test-app/runtime/src/main/cpp/js/weak-collections.js b/test-app/runtime/src/main/cpp/js/weak-collections.js index 88465c6d9..a1988ab0d 100644 --- a/test-app/runtime/src/main/cpp/js/weak-collections.js +++ b/test-app/runtime/src/main/cpp/js/weak-collections.js @@ -6,57 +6,108 @@ // references while the Java object lives on, and a later wrapper for the same // object is a new JS object; keyed by the wrapper, entries and targets would be // lost with it. Every other value passes through unchanged. +// +// They are subclasses of the native collections, so what subclassing shows is +// left as it is: Object.getPrototypeOf(WeakMap.prototype) is the native +// prototype, and WeakMap.toString() is not native code. const { unwrap, wrap } = binding; -const { ObjectDefineProperty, TypeError } = primordials; const { FinalizationRegistry: NativeFinalizationRegistry, + FinalizationRegistryPrototypeRegister, + FinalizationRegistryPrototypeUnregister, + ObjectDefineProperty, + ObjectFreeze, + SymbolKeyFor, WeakMap: NativeWeakMap, + WeakMapPrototypeDelete, + WeakMapPrototypeGet, + WeakMapPrototypeGetOrInsert, + WeakMapPrototypeGetOrInsertComputed, + WeakMapPrototypeHas, + WeakMapPrototypeSet, WeakRef: NativeWeakRef, + WeakRefPrototypeDeref, WeakSet: NativeWeakSet, -} = globalThis; + WeakSetPrototypeAdd, + WeakSetPrototypeDelete, + WeakSetPrototypeHas, +} = primordials; + +// Only an object can be a canary; anything else goes to the native method as is. +function isObject(value) { + return (typeof value === "object" && value !== null) || typeof value === "function"; +} + +// The values the native collections accept as keys and targets. +function canBeHeldWeakly(value) { + return isObject(value) || (typeof value === "symbol" && SymbolKeyFor(value) === undefined); +} // unwrap(value, true) makes the key on first use; lookups pass false so they -// never create state for an object that was never a key. +// never create state for an object that was never a key. A key is made only +// once the native method can no longer reject the call, so a failed call leaves +// no state behind: the receiver is checked first with a method that cannot +// insert anything. +function lookupKey(value) { + return isObject(value) ? unwrap(value, false) : value; +} + +// Unregistering it finds nothing: it is never a token. +const receiverProbe = ObjectFreeze({ __proto__: null }); + class WeakMap extends NativeWeakMap { get(key) { - return super.get(unwrap(key, false)); + return WeakMapPrototypeGet(this, lookupKey(key)); } set(key, value) { - super.set(unwrap(key, true), value); + if (isObject(key)) { + WeakMapPrototypeHas(this, undefined); + key = unwrap(key, true); + } + WeakMapPrototypeSet(this, key, value); return this; } has(key) { - return super.has(unwrap(key, false)); + return WeakMapPrototypeHas(this, lookupKey(key)); } delete(key) { - return super.delete(unwrap(key, false)); + return WeakMapPrototypeDelete(this, lookupKey(key)); } } // V8 ships the upsert proposal; inherited, these would key on the wrapper. -if (typeof NativeWeakMap.prototype.getOrInsert === "function") { +if (WeakMapPrototypeGetOrInsert !== undefined) { ObjectDefineProperty(WeakMap.prototype, "getOrInsert", { value: function getOrInsert(key, value) { - return NativeWeakMap.prototype.getOrInsert.call(this, unwrap(key, true), value); + if (isObject(key)) { + WeakMapPrototypeHas(this, undefined); + key = unwrap(key, true); + } + return WeakMapPrototypeGetOrInsert(this, key, value); }, writable: true, configurable: true, }); } -if (typeof NativeWeakMap.prototype.getOrInsertComputed === "function") { +if (WeakMapPrototypeGetOrInsertComputed !== undefined) { ObjectDefineProperty(WeakMap.prototype, "getOrInsertComputed", { value: function getOrInsertComputed(key, callbackfn) { - if (typeof callbackfn !== "function") { - throw new TypeError("WeakMap.prototype.getOrInsertComputed: callback is not a function"); + if (!isObject(key) || typeof callbackfn !== "function") { + return WeakMapPrototypeGetOrInsertComputed(this, key, callbackfn); + } + const existing = unwrap(key, false); + if (WeakMapPrototypeHas(this, existing)) { + return WeakMapPrototypeGet(this, existing); } - // The callback sees the key it was given, not the lifetime key. - return NativeWeakMap.prototype.getOrInsertComputed.call(this, unwrap(key, true), () => - callbackfn(key), - ); + // Before the key exists, so a callback that throws leaves none; it sees + // the key it was given, not the lifetime key. + const value = callbackfn(key); + WeakMapPrototypeSet(this, unwrap(key, true), value); + return value; }, writable: true, configurable: true, @@ -65,22 +116,26 @@ if (typeof NativeWeakMap.prototype.getOrInsertComputed === "function") { class WeakSet extends NativeWeakSet { add(value) { - super.add(unwrap(value, true)); + if (isObject(value)) { + WeakSetPrototypeHas(this, undefined); + value = unwrap(value, true); + } + WeakSetPrototypeAdd(this, value); return this; } has(value) { - return super.has(unwrap(value, false)); + return WeakSetPrototypeHas(this, lookupKey(value)); } delete(value) { - return super.delete(unwrap(value, false)); + return WeakSetPrototypeDelete(this, lookupKey(value)); } } class WeakRef extends NativeWeakRef { constructor(target) { - const key = unwrap(target, true); + const key = isObject(target) ? unwrap(target, true) : target; super(key); // The target itself, not only its key, stays alive until the job ends. if (key !== target) { @@ -93,8 +148,13 @@ class WeakRef extends NativeWeakRef { // target, the wrapper it returns stays alive until the job ends, so a second // deref in the same job sees the same object. deref() { - const result = wrap(super.deref()); - if (typeof result === "object" && result !== null) { + const target = WeakRefPrototypeDeref(this); + if (!isObject(target)) { + return target; + } + const result = wrap(target); + // The native deref already keeps a target it returns as is. + if (result !== target && result !== undefined) { new NativeWeakRef(result); } return result; @@ -114,20 +174,25 @@ class FinalizationRegistry extends NativeFinalizationRegistry { super(cleanupCallback); } - register(target, heldValue, unregisterToken) { - // Checked on the original values: unwrapping would make them differ. - if (target === heldValue) { - throw new TypeError("FinalizationRegistry.prototype.register: target and holdings must not be same"); + // The default keeps `length` at 2, as on the native method. + register(target, heldValue, unregisterToken = undefined) { + // Checked on the original values: unwrapping would make target and + // heldValue differ. A call the native method rejects gets its error. + if (!canBeHeldWeakly(target) || target === heldValue || + (unregisterToken !== undefined && !canBeHeldWeakly(unregisterToken))) { + return FinalizationRegistryPrototypeRegister(this, target, heldValue, unregisterToken); } - super.register( - unwrap(target, true), + FinalizationRegistryPrototypeUnregister(this, receiverProbe); + FinalizationRegistryPrototypeRegister( + this, + isObject(target) ? unwrap(target, true) : target, heldValue, - unregisterToken === undefined ? undefined : unwrap(unregisterToken, true), + isObject(unregisterToken) ? unwrap(unregisterToken, true) : unregisterToken, ); } unregister(unregisterToken) { - return super.unregister(unwrap(unregisterToken, false)); + return FinalizationRegistryPrototypeUnregister(this, lookupKey(unregisterToken)); } } From 7f3d0682ceaa28e7c0d8fca9f0f7f8d9a883575f Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 20:30:37 -0300 Subject: [PATCH 07/15] docs(runtime): weak collections: released canaries, polled WeakRefs, counts - A released canary keeps what weak collections keyed on its object. - A WeakRef to a Java object dereferenced on every frame or event builds a canary each time its wrapper died, holding the object strongly, so it may never clear. - canaryStates and getWrapperClassCounts().states include states made only to hold a weak-collection key. - The receiver check names has/unregister in its TypeError, and the collections show that they are subclasses. --- docs/ns-builtin-modules.md | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 748e9a4cc..f16f30751 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -104,7 +104,7 @@ wrapper. | `setConfig(key, value)` | Sets a runtime config key. Throws `TypeError` on an unknown key, an invalid value, or (for process-wide keys) when called from a worker isolate. | | `getConfig(key)` | Returns the current value of a config key. Throws `TypeError` on an unknown key. Readable from any isolate. | | `getWrapperLifetimeStats()` | Wrapper lifetime counters for the calling isolate (see [Wrapper lifetime](#wrapper-lifetime)). A fresh object on every call. | -| `getWrapperClassCounts()` | Per Java class name (`` for a link whose class was never recorded), the calling isolate's live `wrappers`, the `canaries` among them and the canary `states` (see [Wrapper lifetime](#wrapper-lifetime)). | +| `getWrapperClassCounts()` | Per Java class name (`` for a link whose class was never recorded), the calling isolate's live `wrappers`, the `canaries` among them and the canary `states`, which include those made only for a weak-collection key (see [Wrapper lifetime](#wrapper-lifetime)). | | `escapeException(x)` | Returns an `Error` branded so that, when it is thrown back across a native callback boundary, the native caller receives the original native exception `x` carries rather than the runtime's wrapper exception. Idempotent: a branded error is returned unchanged. Throws `TypeError` when called with no argument. The global `interop.escapeException` is this same function (see [Legacy globals](#legacy-globals)). | *Platform note (Android):* the original exception is the Java throwable `x` @@ -189,7 +189,7 @@ every build on cold paths only: | `collected` | wrappers released because Java had collected their object | | `releasedExplicitly` | links released through `__releaseNativeCounterpart` | | `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 | -| `canaryStates` | `"canary"` only: state objects created to hold JS properties | +| `canaryStates` | `"canary"` only: state objects created to hold JS properties, or to hold the key a weak collection made for the object, in which case no JS property was written | | `canaryNativeDeaths` | `"canary"` only: state objects let go of because Java collected their object | | `canaryInterceptedWrites` | `"canary"` only: writes to canaries the write handler saw. Canaries without state have no handler | | `canaryCachedWrites` | `"canary"` only: of those writes, rewrites of a name the handler knew to be a plain data property of the state, mirrored with one store | @@ -266,7 +266,9 @@ built later for one of its objects has the Java class's prototype, not `X.prototype`, and none of the old canary's JS properties. A canary built after another died is a new JS object, which `===` cannot tell because nothing kept the old one. `__releaseNativeCounterpart` drops the -object's state with its link. +object's state with its link, and the released canary is a plain JS object +from then on: what the weak collections keyed on its Java object stays keyed +on it, and lives as long as it does. **Weak collections.** What could notice a new canary is whatever keys on the old one without keeping it, so in canary mode a builtin @@ -281,8 +283,15 @@ so probing an object gives it no state. A Proxy around a Java object stays a key of its own, and every other value passes through to the standard collection. The cost is the other side of the same rooting: a `WeakMap` value that references its Java key keeps the key, its state and so the Java object -alive for as long as the map lives. Each operation costs one native call in -canary mode, whatever the key. +alive for as long as the map lives. And `deref` builds a canary, which holds +the Java object strongly until it dies again, so a `WeakRef` to a Java object +that is dereferenced on every frame or event may keep the object from ever +being collected. In canary mode, an operation on an object costs a native +call, and one that can create the key also checks its receiver first so that +a call that fails leaves no key behind; that check names `has` (or +`unregister`) in its `TypeError`. The collections are subclasses of the +standard ones, which shows: `Object.getPrototypeOf(WeakMap.prototype)` is the +standard prototype, and `WeakMap.toString()` is not native code. Remote-module security (`security.allowRemoteModules`, `security.remoteModuleAllowlist`) is **not** part of this surface. Those From fe9d162a1a3852022163faeaec171ad1112ed719 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 20:30:37 -0300 Subject: [PATCH 08/15] test(runtime): weak collection specs for constructors, subclasses, release and errors - Entries given to the WeakMap and WeakSet constructors, and set through a user subclass of WeakMap, key the Java object. - A FinalizationRegistry callback does not run while Java holds the object and its wrapper is dead. - After __releaseNativeCounterpart, WeakMap, WeakSet, WeakRef and FinalizationRegistry treat the wrapper as a plain JS object. - A call the standard collection rejects makes no key; the computed callback sees the key it was given; register has the standard length and invalid-target error. --- .../testWrapperLifetimeWeakCollections.js | 145 ++++++++++++++++++ 1 file changed, 145 insertions(+) diff --git a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js index de3aa9957..e715fe44a 100644 --- a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js @@ -223,6 +223,151 @@ describe("Weak collections of Java objects", function () { expect(map instanceof WeakMap).toBe(true); }); + it("keys the entries given to the WeakMap and WeakSet constructors by the Java object", function () { + var map; + var set; + (function () { + var runnable = heldRunnable(); + map = new WeakMap([[runnable, "constructed"]]); + set = new WeakSet([runnable]); + })(); + collectBoth(); + + expect(map.get(Holder.held)).toBe("constructed"); + expect(set.has(Holder.held)).toBe(true); + }); + + it("keys a Java object in a subclass of WeakMap", function () { + class TaggedMap extends WeakMap { + set(key, value) { + return super.set(key, "tagged:" + value); + } + } + var map = new TaggedMap(); + (function () { + map.set(heldRunnable(), "value"); + })(); + collectBoth(); + + expect(map.get(Holder.held)).toBe("tagged:value"); + expect(map instanceof WeakMap).toBe(true); + }); + + it("does not run a FinalizationRegistry callback while Java holds the object", function (done) { + var cleaned = false; + var registry = new FinalizationRegistry(function () { + cleaned = true; + }); + (function () { + registry.register(heldRunnable(), "held"); + })(); + var polls = 0; + (function poll() { + collectBoth(); + if (cleaned) { + done.fail("the cleanup callback ran while Java held the object"); + return; + } + if (++polls < 5) { + setTimeout(poll, 50); + return; + } + expect(Holder.held).not.toBe(null); + done(); + })(); + }, 20000); + + // Released, the wrapper is a plain JS object: what was keyed on it lives exactly as long + // as it does. Only booleans reach expect(), which could otherwise keep the wrapper. + it("keeps what was keyed on a Java object after its link is released, while the wrapper lives", function (done) { + var map = new WeakMap(); + var set = new WeakSet(); + var cleaned = false; + var registry = new FinalizationRegistry(function (held) { + cleaned = held === "released"; + }); + var runnable = new java.lang.Runnable({ run: function () {} }); + map.set(runnable, "value"); + set.add(runnable); + var ref = new WeakRef(runnable); + registry.register(runnable, "released"); + __releaseNativeCounterpart(runnable); + + expect(map.get(runnable)).toBe("value"); + expect(set.has(runnable)).toBe(true); + expect(ref.deref() === runnable).toBe(true); + setTimeout(function () { + collectBoth(); + expect(map.get(runnable)).toBe("value"); + expect(set.has(runnable)).toBe(true); + expect(ref.deref() === runnable).toBe(true); + expect(new WeakRef(runnable).deref() === runnable).toBe(true); + map.set(runnable, "again"); + expect(map.get(runnable)).toBe("again"); + expect(cleaned).toBe(false); + runnable = null; + setTimeout(function () { + eventually(function () { + // A collected registry runs no callbacks. + return cleaned && registry !== null; + }, done, "the cleanup callback did not run once the wrapper was collected"); + }, 0); + }, 0); + }, 20000); + + it("makes no key for a call the standard collection rejects", function () { + var runnable = new java.lang.Runnable({ run: function () {} }); + var registry = new FinalizationRegistry(function () {}); + var map = new WeakMap(); + var states = runtime.getWrapperLifetimeStats().canaryStates; + expect(function () { + WeakMap.prototype.set.call({}, runnable, 1); + }).toThrowError(TypeError); + expect(function () { + WeakSet.prototype.add.call({}, runnable); + }).toThrowError(TypeError); + expect(function () { + registry.register(runnable, "held", 1); + }).toThrowError(TypeError); + expect(function () { + FinalizationRegistry.prototype.register.call({}, runnable, "held"); + }).toThrowError(TypeError); + if (typeof map.getOrInsertComputed === "function") { + expect(function () { + WeakMap.prototype.getOrInsert.call({}, runnable, 1); + }).toThrowError(TypeError); + expect(function () { + map.getOrInsertComputed(runnable, function () { + throw new Error("callback"); + }); + }).toThrowError("callback"); + } + expect(runtime.getWrapperLifetimeStats().canaryStates).toBe(states); + }); + + it("hands getOrInsertComputed's callback the key it was given", function () { + var map = new WeakMap(); + if (typeof map.getOrInsertComputed !== "function") { + return; + } + var runnable = new java.lang.Runnable({ run: function () {} }); + var seen; + expect(map.getOrInsertComputed(runnable, function (key) { + seen = key; + return "computed"; + })).toBe("computed"); + expect(seen === runnable).toBe(true); + expect(map.get(runnable)).toBe("computed"); + }); + + it("matches the standard FinalizationRegistry.prototype.register signature and errors", function () { + var registry = new FinalizationRegistry(function () {}); + expect(FinalizationRegistry.prototype.register.length).toBe(2); + expect(function () { + registry.register(1, 1); + }).toThrowError(TypeError, /invalid target/); + }); + it("installs the canary collections only in canary mode", function () { var native = WeakMap.toString().indexOf("[native code]") !== -1; expect(native).toBe(!canary); From 1f0ceff2508e632981d55a8dc6403c3b42a92df0 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 02:55:17 -0300 Subject: [PATCH 09/15] perf(runtime): weak collections look a value up as is before unwrapping it Every WeakMap, WeakSet and FinalizationRegistry.unregister call with an object asked native code for the object's lifetime key, so plain JS keys and wrappers that are not canaries paid for a native call even when they were present. A canary is never stored as a key itself (its lifetime key is), so each method now tries the value as is and asks for the lifetime key only when that misses, and looks again only when the lifetime key is another object. set, add and getOrInsert check the receiver with has(value), which also skips the unwrap when the value is already present. Measured on a phone with the reference implementation, a hit: get with a plain JS key 38 -> 17 ns (16 ns in resurrecting mode), with a wrapper that is not a canary under scope "extended" 111 -> 16 ns; canary keys cost 2-5 ns more. A miss still makes the native call. --- .../src/main/cpp/js/weak-collections.js | 69 ++++++++++++++----- 1 file changed, 53 insertions(+), 16 deletions(-) diff --git a/test-app/runtime/src/main/cpp/js/weak-collections.js b/test-app/runtime/src/main/cpp/js/weak-collections.js index a1988ab0d..aad0f26f7 100644 --- a/test-app/runtime/src/main/cpp/js/weak-collections.js +++ b/test-app/runtime/src/main/cpp/js/weak-collections.js @@ -49,8 +49,18 @@ function canBeHeldWeakly(value) { // once the native method can no longer reject the call, so a failed call leaves // no state behind: the receiver is checked first with a method that cannot // insert anything. -function lookupKey(value) { - return isObject(value) ? unwrap(value, false) : value; +// +// A canary is never stored as a key itself (its lifetime key is), so every +// method first tries the value as is and unwraps it only when that misses: +// plain JS keys never reach native code. + +// The lifetime key value stands for, or undefined when that is value itself. +function otherKey(value) { + if (!isObject(value)) { + return undefined; + } + const key = unwrap(value, false); + return key !== value ? key : undefined; } // Unregistering it finds nothing: it is never a token. @@ -58,12 +68,17 @@ const receiverProbe = ObjectFreeze({ __proto__: null }); class WeakMap extends NativeWeakMap { get(key) { - return WeakMapPrototypeGet(this, lookupKey(key)); + const direct = WeakMapPrototypeGet(this, key); + if (direct !== undefined) { + return direct; + } + const other = otherKey(key); + return other === undefined ? undefined : WeakMapPrototypeGet(this, other); } set(key, value) { - if (isObject(key)) { - WeakMapPrototypeHas(this, undefined); + // Also checks the receiver before a key is made. + if (isObject(key) && !WeakMapPrototypeHas(this, key)) { key = unwrap(key, true); } WeakMapPrototypeSet(this, key, value); @@ -71,11 +86,19 @@ class WeakMap extends NativeWeakMap { } has(key) { - return WeakMapPrototypeHas(this, lookupKey(key)); + if (WeakMapPrototypeHas(this, key)) { + return true; + } + const other = otherKey(key); + return other !== undefined && WeakMapPrototypeHas(this, other); } delete(key) { - return WeakMapPrototypeDelete(this, lookupKey(key)); + if (WeakMapPrototypeDelete(this, key)) { + return true; + } + const other = otherKey(key); + return other !== undefined && WeakMapPrototypeDelete(this, other); } } @@ -83,8 +106,7 @@ class WeakMap extends NativeWeakMap { if (WeakMapPrototypeGetOrInsert !== undefined) { ObjectDefineProperty(WeakMap.prototype, "getOrInsert", { value: function getOrInsert(key, value) { - if (isObject(key)) { - WeakMapPrototypeHas(this, undefined); + if (isObject(key) && !WeakMapPrototypeHas(this, key)) { key = unwrap(key, true); } return WeakMapPrototypeGetOrInsert(this, key, value); @@ -99,8 +121,11 @@ if (WeakMapPrototypeGetOrInsertComputed !== undefined) { if (!isObject(key) || typeof callbackfn !== "function") { return WeakMapPrototypeGetOrInsertComputed(this, key, callbackfn); } - const existing = unwrap(key, false); - if (WeakMapPrototypeHas(this, existing)) { + if (WeakMapPrototypeHas(this, key)) { + return WeakMapPrototypeGet(this, key); + } + const existing = otherKey(key); + if (existing !== undefined && WeakMapPrototypeHas(this, existing)) { return WeakMapPrototypeGet(this, existing); } // Before the key exists, so a callback that throws leaves none; it sees @@ -116,8 +141,8 @@ if (WeakMapPrototypeGetOrInsertComputed !== undefined) { class WeakSet extends NativeWeakSet { add(value) { - if (isObject(value)) { - WeakSetPrototypeHas(this, undefined); + // Also checks the receiver before a key is made. + if (isObject(value) && !WeakSetPrototypeHas(this, value)) { value = unwrap(value, true); } WeakSetPrototypeAdd(this, value); @@ -125,11 +150,19 @@ class WeakSet extends NativeWeakSet { } has(value) { - return WeakSetPrototypeHas(this, lookupKey(value)); + if (WeakSetPrototypeHas(this, value)) { + return true; + } + const other = otherKey(value); + return other !== undefined && WeakSetPrototypeHas(this, other); } delete(value) { - return WeakSetPrototypeDelete(this, lookupKey(value)); + if (WeakSetPrototypeDelete(this, value)) { + return true; + } + const other = otherKey(value); + return other !== undefined && WeakSetPrototypeDelete(this, other); } } @@ -192,7 +225,11 @@ class FinalizationRegistry extends NativeFinalizationRegistry { } unregister(unregisterToken) { - return FinalizationRegistryPrototypeUnregister(this, lookupKey(unregisterToken)); + if (FinalizationRegistryPrototypeUnregister(this, unregisterToken)) { + return true; + } + const other = otherKey(unregisterToken); + return other !== undefined && FinalizationRegistryPrototypeUnregister(this, other); } } From c94ad4da8a2e3d725a635926670bc236e4d78fed Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 02:55:17 -0300 Subject: [PATCH 10/15] test(runtime): weak collections key canaries rebuilt from a shell by their Java object Rebuilt more than once, a canary is a copy of an earlier rebuilt one. The key a weak collection made for the object stays with its state, reaches every later canary, and moves onto the canary whose link is released, never onto the copy. --- .../testWrapperLifetimeWeakCollections.js | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js index e715fe44a..64d4dc03b 100644 --- a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js @@ -68,6 +68,40 @@ describe("Weak collections of Java objects", function () { expect(map.has(again)).toBe(false); }); + // A canary rebuilt more than once is a copy of an earlier rebuilt one: the key lives + // with the object's state, not on any canary, until the link is released. + it("keys canaries rebuilt from a copy of an earlier one by their Java object, through a release", function () { + var map = new WeakMap(); + var set = new WeakSet(); + (function () { + heldRunnable(); + })(); + collectBoth(); + (function () { + map.set(Holder.held, "first"); + })(); + collectBoth(); + (function () { + var second = Holder.held; + expect(map.get(second)).toBe("first"); + expect(map.delete(second)).toBe(true); + set.add(second); + })(); + collectBoth(); + + var third = Holder.held; + expect(map.has(third)).toBe(false); + expect(set.has(third)).toBe(true); + map.set(third, "third"); + __releaseNativeCounterpart(third); + expect(map.get(third)).toBe("third"); + expect(set.has(third)).toBe(true); + var after = Holder.held; + expect(after === third).toBe(false); + expect(map.has(after)).toBe(false); + expect(set.has(after)).toBe(false); + }); + it("keeps a WeakSet member for a Java object across a wrapper change", function () { var set = new WeakSet(); (function () { From f9e7a096ff6add9bd65a857718495d2d835c19f3 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 13:33:33 -0300 Subject: [PATCH 11/15] perf(runtime): weak collections learn rebuilt keyed canaries lazily A private WeakMap maps every canary that stands for a key to that key, so lookups of canaries make no native call, and a value missing there was never a key. The runtime does not call into JS for each canary it builds for a keyed object: it counts them in a shared Int32Array, and the first lookup that misses while the count is nonzero takes them all in one call. The key lives on the object's canary record, where that call reads it, so keying an object no longer gives it a state. keyFor rules out plain JS objects first with maybeCanary, a V8 fast call, so set, add, register and new WeakRef make no native call for them. Each WeakRef keeps a native WeakRef to its canary for deref. A weakCollectionNativeCalls counter counts the calls into the runtime. --- docs/ns-builtin-modules.md | 32 ++- .../assets/app/tests/testWrapperLifetime.js | 3 +- .../testWrapperLifetimeWeakCollections.js | 193 +++++++++++++++ .../runtime/src/main/cpp/NsBuiltinModules.cpp | 1 + .../runtime/src/main/cpp/ObjectManager.cpp | 231 ++++++++++++++---- test-app/runtime/src/main/cpp/ObjectManager.h | 48 +++- .../runtime/src/main/cpp/WrapperLifetime.h | 2 + .../src/main/cpp/js/weak-collections.js | 93 +++++-- 8 files changed, 519 insertions(+), 84 deletions(-) diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index f16f30751..5a42398dd 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -104,7 +104,7 @@ wrapper. | `setConfig(key, value)` | Sets a runtime config key. Throws `TypeError` on an unknown key, an invalid value, or (for process-wide keys) when called from a worker isolate. | | `getConfig(key)` | Returns the current value of a config key. Throws `TypeError` on an unknown key. Readable from any isolate. | | `getWrapperLifetimeStats()` | Wrapper lifetime counters for the calling isolate (see [Wrapper lifetime](#wrapper-lifetime)). A fresh object on every call. | -| `getWrapperClassCounts()` | Per Java class name (`` for a link whose class was never recorded), the calling isolate's live `wrappers`, the `canaries` among them and the canary `states`, which include those made only for a weak-collection key (see [Wrapper lifetime](#wrapper-lifetime)). | +| `getWrapperClassCounts()` | Per Java class name (`` for a link whose class was never recorded), the calling isolate's live `wrappers`, the `canaries` among them and the canary `states` (see [Wrapper lifetime](#wrapper-lifetime)). | | `escapeException(x)` | Returns an `Error` branded so that, when it is thrown back across a native callback boundary, the native caller receives the original native exception `x` carries rather than the runtime's wrapper exception. Idempotent: a branded error is returned unchanged. Throws `TypeError` when called with no argument. The global `interop.escapeException` is this same function (see [Legacy globals](#legacy-globals)). | *Platform note (Android):* the original exception is the Java throwable `x` @@ -189,17 +189,19 @@ every build on cold paths only: | `collected` | wrappers released because Java had collected their object | | `releasedExplicitly` | links released through `__releaseNativeCounterpart` | | `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 | -| `canaryStates` | `"canary"` only: state objects created to hold JS properties, or to hold the key a weak collection made for the object, in which case no JS property was written | +| `canaryStates` | `"canary"` only: state objects created to hold JS properties | | `canaryNativeDeaths` | `"canary"` only: state objects let go of because Java collected their object | | `canaryInterceptedWrites` | `"canary"` only: writes to canaries the write handler saw. Canaries without state have no handler | | `canaryCachedWrites` | `"canary"` only: of those writes, rewrites of a name the handler knew to be a plain data property of the state, mirrored with one store | | `canaryCachedFieldWrites` | `"canary"` only: of those writes, Java field writes the handler placed from an earlier write of the same name through an object with the same prototype, without looking the name up along the prototype chain | | `canaryRebuilds` | `"canary"` only: canaries built anew for a JS-extended instance whose previous canary died while Java kept the object | +| `weakCollectionNativeCalls` | `"canary"` only: calls the weak collections make into the runtime: to make the key of a canary's Java object, to find the canary for a key, and to learn about canaries built for keyed objects since the last such call. Lookups of a value that was never a key make none | In `"canary"` mode only array buffers backed by Java buffers resurrect; `weakened` counts objects held weakly because their canary died while they -had a record (JS state, or a JS-extended instance), and `collected` counts -canaries whose object had none, which Java no longer holds for JS. +had a record (JS state, a weak-collection key, or a JS-extended instance), +and `collected` counts canaries whose object had none, which Java no longer +holds for JS. `"canary"` is the resurrection-free model the iOS runtime and the Node-API runtimes share. Every wrapper of a Java object is a canary: a phantom-weak JS @@ -274,21 +276,27 @@ on it, and lives as long as it does. old one without keeping it, so in canary mode a builtin (`js/weak-collections.js`) 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. Entries and targets -therefore live exactly as long as the Java object; `WeakRef.prototype.deref` +a canary by an opaque, frozen key the object's record holds. Entries and +targets therefore live exactly as long as the Java object; `WeakRef.prototype.deref` (and the `get` alias) returns the live canary, a new one with the object's state, or `undefined` once Java collected the object. `set`, `add`, -`getOrInsert`, `new WeakRef` and `register` create the key; lookups never do, -so probing an object gives it no state. A Proxy around a Java object stays a +`getOrInsert`, `new WeakRef` and `register` create the key; lookups never do. +Neither gives the object a state. A Proxy around a Java object stays a key of its own, and every other value passes through to the standard collection. The cost is the other side of the same rooting: a `WeakMap` value -that references its Java key keeps the key, its state and so the Java object +that references its Java key keeps the key, its record and so the Java object alive for as long as the map lives. And `deref` builds a canary, which holds the Java object strongly until it dies again, so a `WeakRef` to a Java object that is dereferenced on every frame or event may keep the object from ever -being collected. In canary mode, an operation on an object costs a native -call, and one that can create the key also checks its receiver first so that -a call that fails leaves no key behind; that check names `has` (or +being collected. In canary mode, an operation that can create the key costs a +native call for a Java object the collection does not hold yet; a plain JS +object costs only a V8 fast call that rules it out. Lookups (`get`, `has`, +`delete`, `unregister`, `deref`) make no native call, except a `deref` that +has to build a canary, and the first lookup that misses after the runtime +built canaries for keyed objects, which makes one call for all of them. An +operation that can create the +key also checks its receiver first so that a call that fails leaves no key +behind; that check names `has` (or `unregister`) in its `TypeError`. The collections are subclasses of the standard ones, which shows: `Object.getPrototypeOf(WeakMap.prototype)` is the standard prototype, and `WeakMap.toString()` is not native code. diff --git a/test-app/app/src/main/assets/app/tests/testWrapperLifetime.js b/test-app/app/src/main/assets/app/tests/testWrapperLifetime.js index 99fdb589e..f275310d0 100644 --- a/test-app/app/src/main/assets/app/tests/testWrapperLifetime.js +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetime.js @@ -38,7 +38,8 @@ describe("Wrapper lifetime", function () { var stats = runtime.getWrapperLifetimeStats(); expect(Object.keys(stats).sort()).toEqual( ["canaryCachedFieldWrites", "canaryCachedWrites", "canaryInterceptedWrites", "canaryNativeDeaths", - "canaryRebuilds", "canaryStates", "collected", "releasedAccesses", "releasedExplicitly", "resurrections", "weakened"]); + "canaryRebuilds", "canaryStates", "collected", "releasedAccesses", "releasedExplicitly", "resurrections", + "weakCollectionNativeCalls", "weakened"]); Object.keys(stats).forEach(function (key) { expect(typeof stats[key]).toBe("number"); }); diff --git a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js index 64d4dc03b..3c5d6eebb 100644 --- a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js @@ -349,6 +349,18 @@ describe("Weak collections of Java objects", function () { }, 0); }, 20000); + it("gives no state to a Java object it only keys", function () { + var map = new WeakMap(); + var set = new WeakSet(); + var builder = new java.lang.StringBuilder("keyed"); + var states = runtime.getWrapperLifetimeStats().canaryStates; + map.set(builder, 1); + set.add(builder); + expect(map.get(builder)).toBe(1); + expect(set.has(builder)).toBe(true); + expect(runtime.getWrapperLifetimeStats().canaryStates).toBe(states); + }); + it("makes no key for a call the standard collection rejects", function () { var runnable = new java.lang.Runnable({ run: function () {} }); var registry = new FinalizationRegistry(function () {}); @@ -402,6 +414,187 @@ describe("Weak collections of Java objects", function () { }).toThrowError(TypeError, /invalid target/); }); + // A canary built for an object that has a key, by any path (here a Java field read, not + // a deref), stands for the key at once; a canary that was never a key makes no state. + it("finds what was keyed on a Java object through a canary built by a Java read", function (done) { + var map = new WeakMap(); + var set = new WeakSet(); + var registry = new FinalizationRegistry(function () {}); + var token = new java.lang.StringBuilder("token"); + var NativeWeakRef = Object.getPrototypeOf(WeakRef) === Function.prototype ? WeakRef : Object.getPrototypeOf(WeakRef); + var rebuilds = runtime.getWrapperLifetimeStats().canaryRebuilds; + var firstCanaries; + var refs = (function () { + var plain = new java.lang.StringBuilder("plain"); + map.set(plain, "plain value"); + set.add(plain); + var runnable = new java.lang.Runnable({ run: function () {} }); + registry.register(runnable, "held", plain); + map.set(runnable, "extended value"); + var list = new java.util.ArrayList(); + list.add(plain); + list.add(runnable); + Holder.held = list; + firstCanaries = [new NativeWeakRef(plain), new NativeWeakRef(runnable)]; + return [new WeakRef(plain), new WeakRef(runnable)]; + })(); + setTimeout(function () { + collectBoth(); + if (canary) { + // A plain wrapper is a canary under scope "all" only. + if (runtime.getConfig("wrapperLifetimeScope") === "all") { + expect(firstCanaries[0].deref()).toBeUndefined(); + } + expect(firstCanaries[1].deref()).toBeUndefined(); + } + var list = Holder.held; + var held = [list.get(0), list.get(1)]; + if (canary) { + expect(runtime.getWrapperLifetimeStats().canaryRebuilds).toBeGreaterThan(rebuilds); + } + expect(map.get(held[0])).toBe("plain value"); + expect(set.has(held[0])).toBe(true); + expect(map.get(held[1])).toBe("extended value"); + expect(refs[0].deref() === held[0]).toBe(true); + expect(refs[1].deref() === held[1]).toBe(true); + expect(refs[1].deref() === refs[1].deref()).toBe(true); + expect(registry.unregister(held[0])).toBe(true); + expect(set.delete(held[0])).toBe(true); + expect(set.has(held[0])).toBe(false); + expect(map.delete(held[1])).toBe(true); + expect(map.has(held[1])).toBe(false); + var states = runtime.getWrapperLifetimeStats().canaryStates; + expect(map.has(token)).toBe(false); + expect(map.get(token)).toBeUndefined(); + expect(set.delete(token)).toBe(false); + expect(registry.unregister(token)).toBe(false); + expect(runtime.getWrapperLifetimeStats().canaryStates).toBe(states); + var plainTarget = {}; + expect(new WeakRef(plainTarget).deref()).toBe(plainTarget); + done(); + }, 0); + }); + + // Keying a canary must not keep it alive: only WeakRef construction and deref do, until + // the job ends, as the standard says. + it("lets a canary that was just keyed die in the same job", function () { + var map = new WeakMap(); + var set = new WeakSet(); + var rebuilds = runtime.getWrapperLifetimeStats().canaryRebuilds; + (function () { + var runnable = heldRunnable(); + map.set(runnable, "value"); + set.add(runnable); + })(); + collectBoth(); + expect(map.get(Holder.held)).toBe("value"); + expect(set.has(Holder.held)).toBe(true); + if (canary) { + expect(runtime.getWrapperLifetimeStats().canaryRebuilds).toBeGreaterThan(rebuilds); + } + }); + + function nativeCalls() { + return runtime.getWrapperLifetimeStats().weakCollectionNativeCalls; + } + + it("never calls into the runtime for plain JS objects or lookups of values that were never keys", function () { + var map = new WeakMap(); + var set = new WeakSet(); + var registry = new FinalizationRegistry(function () {}); + var plain = {}; + var other = {}; + map.set(plain, 1); + set.add(plain); + registry.register(plain, "held", plain); + var ref = new WeakRef(plain); + var javaObject = new java.lang.Object(); + var runnable = new java.lang.Runnable({ run: function () {} }); + // A miss takes whatever canaries earlier specs left to be told about. + map.has({}); + var before = nativeCalls(); + expect(map.get(plain)).toBe(1); + expect(map.has(other)).toBe(false); + expect(map.get(other)).toBeUndefined(); + expect(map.delete(other)).toBe(false); + expect(set.has(plain)).toBe(true); + expect(set.has(other)).toBe(false); + expect(set.delete(other)).toBe(false); + expect(ref.deref()).toBe(plain); + expect(ref.get()).toBe(plain); + expect(registry.unregister(other)).toBe(false); + map.set(plain, 2); + set.add(plain); + expect(map.has(javaObject)).toBe(false); + expect(map.get(runnable)).toBeUndefined(); + expect(set.has(runnable)).toBe(false); + expect(registry.unregister(runnable)).toBe(false); + var fresh = {}; + map.set(fresh, 3); + set.add(fresh); + registry.register(fresh, "fresh", fresh); + expect(new WeakRef(fresh).deref()).toBe(fresh); + expect(map.getOrInsert ? map.getOrInsert({}, 4) : 4).toBe(4); + expect(nativeCalls()).toBe(before); + }); + + // The runtime only counts the canaries it builds for keyed objects; the first lookup + // that misses learns them all with one call. + it("finds a keyed Java object through canaries built while no lookup ran", function () { + var map = new WeakMap(); + var set = new WeakSet(); + var registry = new FinalizationRegistry(function () {}); + var rebuilds = runtime.getWrapperLifetimeStats().canaryRebuilds; + (function () { + var runnable = heldRunnable(); + map.set(runnable, "value"); + set.add(runnable); + registry.register(runnable, "held", runnable); + })(); + collectBoth(); + (function () { + expect(set.has(Holder.held)).toBe(true); + })(); + collectBoth(); + // Built and dead again before any lookup saw it. + (function () { + Holder.held.hashCode(); + })(); + collectBoth(); + var again = Holder.held; + if (canary) { + expect(runtime.getWrapperLifetimeStats().canaryRebuilds).toBeGreaterThan(rebuilds + 2); + } + var before = nativeCalls(); + expect(map.has({})).toBe(false); + if (canary) { + expect(nativeCalls()).toBe(before + 1); + } + expect(map.has({})).toBe(false); + expect(map.get(again)).toBe("value"); + expect(set.has(again)).toBe(true); + expect(registry.unregister(again)).toBe(true); + if (canary) { + expect(nativeCalls()).toBe(before + 1); + } + }); + + it("finds a keyed Java object through a canary built and released while no lookup ran", function () { + var map = new WeakMap(); + var set = new WeakSet(); + (function () { + var runnable = heldRunnable(); + map.set(runnable, "value"); + set.add(runnable); + })(); + collectBoth(); + var released = Holder.held; + __releaseNativeCounterpart(released); + expect(set.has(released)).toBe(true); + expect(map.get(released)).toBe("value"); + expect(map.has({})).toBe(false); + }); + it("installs the canary collections only in canary mode", function () { var native = WeakMap.toString().indexOf("[native code]") !== -1; expect(native).toBe(!canary); diff --git a/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp b/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp index 3c6e8bc72..829b6ed51 100644 --- a/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp +++ b/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp @@ -175,6 +175,7 @@ void GetWrapperLifetimeStatsCallback(const FunctionCallbackInfo& info) { set("collected", stats.collected); set("releasedExplicitly", stats.releasedExplicitly); set("releasedAccesses", stats.releasedAccesses); + set("weakCollectionNativeCalls", stats.weakCollectionNativeCalls); set("canaryStates", stats.canaryStates); set("canaryNativeDeaths", stats.canaryNativeDeaths); set("canaryInterceptedWrites", stats.canaryInterceptedWrites); diff --git a/test-app/runtime/src/main/cpp/ObjectManager.cpp b/test-app/runtime/src/main/cpp/ObjectManager.cpp index 80299d4ff..185c1d03c 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -14,6 +14,7 @@ #include "V8GlobalHelpers.h" #include "V8StringConstants.h" #include "WrapperLifetimeCanary.h" +#include "include/v8-fast-api-calls.h" #include "include/v8.h" using namespace v8; @@ -117,7 +118,7 @@ void ObjectManager::Init(Isolate* isolate) { if (WrapperLifetimeCanary::Enabled()) { m_instanceFieldTableKey.Reset(isolate, Private::New(isolate)); - m_keyOfState.Reset(isolate, Private::New(isolate)); + m_keyOfReleased.Reset(isolate, Private::New(isolate)); m_objectOfKey.Reset(isolate, Private::New(isolate)); m_releasedOfKey.Reset(isolate, Private::New(isolate)); isolate->AddGCEpilogueCallback(CanaryGCEpilogue, this); @@ -621,6 +622,9 @@ void ObjectManager::Link(const Local& object, uint32_t javaObjectID, jcl state->record = AdoptCanary(object, javaObjectID, kind, instanceTemplate, record.has_value() ? *record : FindCanaryRecord(javaObjectID), hydrate); + if (state->record != nullptr && !state->record->key.IsEmpty()) { + MarkRekeyPending(state); + } } } @@ -983,14 +987,7 @@ bool ObjectManager::CanaryStateForWrite(const Local& holder, Local ObjectManager::AttachState(CanaryHandle* canary, const Local& fresh) { - CanaryRecord* record = canary->record; - if (record == nullptr) { - record = FindCanaryRecord(canary->javaObjectID); - } - if (record == nullptr) { - record = NewCanaryRecord(canary->javaObjectID); - } - canary->record = record; + CanaryRecord* record = RecordForWrite(canary); record->state.Reset(m_isolate, fresh); m_lifetimeStats.canaryStates++; return fresh; @@ -1022,6 +1019,18 @@ Local ObjectManager::NewEmptyState() { return m_emptyState.Get(m_isolate)->Clone(m_isolate); } +ObjectManager::CanaryRecord* ObjectManager::RecordForWrite(ObjectWeakCallbackState* canary) { + CanaryRecord* record = canary->record; + if (record == nullptr) { + record = FindCanaryRecord(canary->javaObjectID); + } + if (record == nullptr) { + record = NewCanaryRecord(canary->javaObjectID); + } + canary->record = record; + return record; +} + Local ObjectManager::StateOf(CanaryHandle* canary) { CanaryRecord* record = canary->record; return record != nullptr && !record->state.IsEmpty() ? record->state.Get(m_isolate) @@ -1063,6 +1072,7 @@ void ObjectManager::CanaryDiedStatic( } thisPtr->m_pendingCanaryDeaths.push_back(static_cast(id)); } + thisPtr->DropRekeyPending(state); delete state; } @@ -1209,20 +1219,60 @@ std::map ObjectManager::GetWrapperClass return counts; } +namespace { +// Only an object with a Metadata field can be a canary, released ones included; +// a Proxy is a key of its own. +bool MaybeCanary(Local value) { + return value->IsObject() && !value->IsProxy() && + ObjectManager::HasMetadataField(value.As()); +} + +void MaybeCanaryCallback(const FunctionCallbackInfo& info) { + info.GetReturnValue().Set(MaybeCanary(info[0])); +} + +#if NATIVESCRIPT_ENABLE_FAST_API +bool FastMaybeCanary(Local receiver, Local value) { + return MaybeCanary(value); +} + +const CFunction kFastMaybeCanary = CFunction::Make(FastMaybeCanary); +#endif +} // namespace + bool ObjectManager::AddWeakCollectionFunctions(Local context, Local binding) { +#if NATIVESCRIPT_ENABLE_FAST_API + tns::SetFastMethodNoSideEffect(context, binding, "maybeCanary", MaybeCanaryCallback, + &kFastMaybeCanary); +#else + tns::SetMethodNoSideEffect(context, binding, "maybeCanary", MaybeCanaryCallback); +#endif auto isolate = m_isolate; Local unwrap; Local wrap; + Local takeRekeys; + std::shared_ptr store = + ArrayBuffer::NewBackingStore(isolate, sizeof(int32_t)); + m_rekeyPendingCount = static_cast(store->Data()); + *m_rekeyPendingCount = 0; + Local pendingRekeys = Int32Array::New(ArrayBuffer::New(isolate, store), 0, 1); + m_rekeyPendingArray.Reset(isolate, pendingRekeys); return Function::New(context, UnwrapForWeakCollection).ToLocal(&unwrap) && Function::New(context, WrapForWeakCollection).ToLocal(&wrap) && + Function::New(context, TakeRekeysForWeakCollection).ToLocal(&takeRekeys) && binding->Set(context, ArgConverter::ConvertToV8String(isolate, "unwrap"), unwrap) .FromMaybe(false) && binding->Set(context, ArgConverter::ConvertToV8String(isolate, "wrap"), wrap) + .FromMaybe(false) && + binding->Set(context, ArgConverter::ConvertToV8String(isolate, "takeRekeys"), takeRekeys) + .FromMaybe(false) && + binding->Set(context, ArgConverter::ConvertToV8String(isolate, "pendingRekeys"), + pendingRekeys) .FromMaybe(false); } // unwrap(value, create): the weak collections' key for a canary's Java object, -// a frozen, null-prototype object that lives as long as the object's state, +// a frozen, null-prototype object that lives as long as the object's record, // that is, until Java collects the object. Lookups pass `create` false and never // make one: with no key yet, no entry can be keyed by it. The value itself for // anything that is not a canary, a Proxy included (it is a key of its own). @@ -1245,43 +1295,44 @@ void ObjectManager::UnwrapForWeakCollection(const FunctionCallbackInfo& i Local value = info[0]; bool create = info[1]->IsTrue(); info.GetReturnValue().Set(value); - if (!value->IsObject() || value->IsProxy()) { + // Canaries, released ones included, are runtime objects with a Metadata field. + if (!value->IsObject() || value->IsProxy() || !HasMetadataField(value.As())) { return; } ObjectManager* thisPtr = WeakCollectionManagerOf(isolate); if (thisPtr == nullptr) { return; } + thisPtr->m_lifetimeStats.weakCollectionNativeCalls++; Local holder = value.As(); Local context = isolate->GetCurrentContext(); - Local keyOfState = thisPtr->m_keyOfState.Get(isolate); - Local key; - Local state; - if (create ? !thisPtr->CanaryStateForWrite(holder, &state) - : !thisPtr->ExistingCanaryState(holder, &state)) { + ObjectWeakCallbackState* live = thisPtr->CanaryOf(holder); + CanaryRecord* record = live != nullptr ? thisPtr->FindCanaryRecord(live->javaObjectID) : nullptr; + if (record != nullptr && !record->key.IsEmpty()) { + info.GetReturnValue().Set(record->key.Get(isolate)); + return; + } + if (live == nullptr) { // A canary whose link was released keeps its key itself. - if (HasMetadataField(holder) && holder->GetPrivate(context, keyOfState).ToLocal(&key) && + Local key; + if (holder->GetPrivate(context, thisPtr->m_keyOfReleased.Get(isolate)).ToLocal(&key) && key->IsObject()) { info.GetReturnValue().Set(key); } return; } - if (state->GetPrivate(context, keyOfState).ToLocal(&key) && key->IsObject()) { - info.GetReturnValue().Set(key); - return; - } if (!create) { return; } Local newKey = Object::New(isolate, Null(isolate), nullptr, nullptr, 0); if (!newKey ->SetPrivate(context, thisPtr->m_objectOfKey.Get(isolate), - Integer::NewFromUnsigned(isolate, static_cast(LinkedIdOf(holder)))) + Integer::NewFromUnsigned(isolate, live->javaObjectID)) .FromMaybe(false) || - !newKey->SetIntegrityLevel(context, IntegrityLevel::kFrozen).FromMaybe(false) || - !state->SetPrivate(context, keyOfState, newKey).FromMaybe(false)) { + !newKey->SetIntegrityLevel(context, IntegrityLevel::kFrozen).FromMaybe(false)) { return; } + thisPtr->RecordForWrite(live)->key.Reset(isolate, newKey); info.GetReturnValue().Set(newKey); } catch (NativeScriptException& e) { e.ReThrowToV8(); @@ -1307,6 +1358,7 @@ void ObjectManager::WrapForWeakCollection(const FunctionCallbackInfo& inf if (thisPtr == nullptr) { return; } + thisPtr->m_lifetimeStats.weakCollectionNativeCalls++; Local context = isolate->GetCurrentContext(); Local key = value.As(); Local idValue; @@ -1324,13 +1376,7 @@ void ObjectManager::WrapForWeakCollection(const FunctionCallbackInfo& inf info.GetReturnValue().SetUndefined(); int id = static_cast(idValue.As()->Value()); CanaryRecord* record = thisPtr->FindCanaryRecord(id); - if (record == nullptr || record->state.IsEmpty()) { - return; - } - Local recordKey; - if (!record->state.Get(isolate)->GetPrivate(context, thisPtr->m_keyOfState.Get(isolate)) - .ToLocal(&recordKey) || - !recordKey->StrictEquals(key)) { + if (record == nullptr || record->key.IsEmpty() || record->key.Get(isolate) != key) { return; } if (auto live = thisPtr->m_idToObject.Find(id)) { @@ -1357,25 +1403,122 @@ void ObjectManager::WrapForWeakCollection(const FunctionCallbackInfo& inf } } +void ObjectManager::MarkRekeyPending(ObjectWeakCallbackState* state) { + if (m_rekeyPendingCount == nullptr || state->rekeyPending) { + return; + } + // Stale ids pile up only while JS makes no lookup that misses; prune them + // once they outnumber the live ones. + if (m_rekeyPendingIds.size() >= 64 && + m_rekeyPendingIds.size() > 2 * static_cast(*m_rekeyPendingCount)) { + m_rekeyPendingIds.erase( + std::remove_if(m_rekeyPendingIds.begin(), m_rekeyPendingIds.end(), + [this](uint32_t id) { + auto live = m_idToObject.Find(id); + return live == nullptr || !live->rekeyPending; + }), + m_rekeyPendingIds.end()); + } + state->rekeyPending = true; + m_rekeyPendingIds.push_back(state->javaObjectID); + ++*m_rekeyPendingCount; +} + +// takeRekeys(): [canary, key, canary, key, ...] for every live canary of a +// keyed object built since the last call. A canary whose link was released +// since holds its key itself. +void ObjectManager::TakeRekeysForWeakCollection(const FunctionCallbackInfo& info) { + try { + Isolate* isolate = info.GetIsolate(); + ObjectManager* thisPtr = WeakCollectionManagerOf(isolate); + if (thisPtr == nullptr) { + info.GetReturnValue().Set(Array::New(isolate, 0)); + return; + } + thisPtr->m_lifetimeStats.weakCollectionNativeCalls++; + std::vector& ids = thisPtr->m_rekeyTakenIds; + ids.swap(thisPtr->m_rekeyPendingIds); + if (thisPtr->m_rekeyPendingCount != nullptr) { + *thisPtr->m_rekeyPendingCount = 0; + } + // Handles only until every pair is taken: an allocation could start a + // collection, whose weak callbacks free registrations. + constexpr size_t kInlinePairs = 8; + Local inlinePairs[2 * kInlinePairs]; + LocalVector morePairs(isolate); + size_t count = 0; + bool released = false; + auto add = [&](Local canary, Local key) { + if (count < kInlinePairs) { + inlinePairs[2 * count] = canary; + inlinePairs[2 * count + 1] = key; + } else { + if (morePairs.empty()) { + morePairs.insert(morePairs.end(), inlinePairs, inlinePairs + 2 * kInlinePairs); + } + morePairs.push_back(canary); + morePairs.push_back(key); + } + count++; + }; + for (uint32_t id : ids) { + auto live = thisPtr->m_idToObject.Find(id); + if (live == nullptr || !live->rekeyPending) { + continue; + } + live->rekeyPending = false; + Local canary = Local::New(isolate, *live->target); + if (live->record != nullptr && !live->record->key.IsEmpty()) { + add(canary, live->record->key.Get(isolate)); + } else { + add(canary, Local()); + released = true; + } + } + ids.clear(); + Local* pairs = count <= kInlinePairs ? inlinePairs : morePairs.data(); + if (released) { + Local context = isolate->GetCurrentContext(); + Local keyOfReleased = thisPtr->m_keyOfReleased.Get(isolate); + size_t kept = 0; + for (size_t i = 0; i < count; i++) { + Local canary = pairs[2 * i]; + Local key = pairs[2 * i + 1]; + if (key.IsEmpty() && + (!canary.As()->GetPrivate(context, keyOfReleased).ToLocal(&key) || + !key->IsObject())) { + continue; + } + pairs[2 * kept] = canary; + pairs[2 * kept + 1] = key; + kept++; + } + count = kept; + } + info.GetReturnValue().Set(Array::New(isolate, pairs, 2 * count)); + } catch (NativeScriptException& e) { + e.ReThrowToV8(); + } catch (std::exception& e) { + RethrowToV8(e.what()); + } catch (...) { + RethrowToV8("unknown"); + } +} + void ObjectManager::KeepWeakCollectionKey(int javaObjectID) { CanaryRecord* record = FindCanaryRecord(javaObjectID); auto live = m_idToObject.Find(javaObjectID); - if (record == nullptr || record->state.IsEmpty() || live == nullptr || !live->canary || - m_keyOfState.IsEmpty()) { + if (record == nullptr || record->key.IsEmpty() || live == nullptr || !live->canary || + m_keyOfReleased.IsEmpty()) { return; } Local context = m_isolate->GetCurrentContext(); - Local keyOfState = m_keyOfState.Get(m_isolate); - Local key; - if (!record->state.Get(m_isolate)->GetPrivate(context, keyOfState).ToLocal(&key) || - !key->IsObject()) { - return; - } + Local key = record->key.Get(m_isolate); // Private symbols bypass the canary's write handler, and V8 lets them be // added to the frozen key. Local canary = Local::New(m_isolate, *live->target); - (void)canary->SetPrivate(context, keyOfState, key); - (void)key.As()->SetPrivate(context, m_releasedOfKey.Get(m_isolate), canary); + (void)canary->SetPrivate(context, m_keyOfReleased.Get(m_isolate), key); + (void)key->SetPrivate(context, m_releasedOfKey.Get(m_isolate), canary); } jobject ObjectManager::JavaObjectOrNull(int javaObjectID) { @@ -1712,8 +1855,12 @@ void ObjectManager::ReleaseAllRegistered() { m_canaryRecords.DrainAll([](CanaryRecord* record) { delete record; }); m_canaryRecordCount = 0; m_instanceFieldTableKey.Reset(); - m_keyOfState.Reset(); + m_keyOfReleased.Reset(); m_emptyState.Reset(); + m_rekeyPendingIds.clear(); + m_rekeyTakenIds.clear(); + m_rekeyPendingCount = nullptr; + m_rekeyPendingArray.Reset(); m_objectOfKey.Reset(); m_releasedOfKey.Reset(); diff --git a/test-app/runtime/src/main/cpp/ObjectManager.h b/test-app/runtime/src/main/cpp/ObjectManager.h index 1f6c1c77d..57ff4f7c0 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -284,9 +284,13 @@ class ObjectManager { // Per Java class name (dotted), for ns:runtime's getWrapperClassCounts(). std::map GetWrapperClassCounts(); - // Canary mode: adds `unwrap` (a canary -> its Java object's weak-collection - // key) and `wrap` (key -> live or new canary, or undefined once Java - // collected the object) to binding, for js/weak-collections.js. + // Canary mode: adds `maybeCanary` (a V8 fast call, false for any value but a + // runtime object), `unwrap` (a canary -> its Java object's weak-collection + // key), `wrap` (key -> live or new canary, or undefined once Java collected + // the object), `takeRekeys` (the canaries built for objects that have a key + // since the last call, with their keys) and `pendingRekeys` (an Int32Array + // whose element counts those still alive) to binding, for + // js/weak-collections.js. bool AddWeakCollectionFunctions(v8::Local context, v8::Local binding); @@ -333,6 +337,8 @@ class ObjectManager { bool keepsState = false; // A canary's record, cached; EraseCanaryRecord clears it. CanaryRecord* record = nullptr; + // A canary of a keyed object that takeRekeys has not returned yet. + bool rekeyPending = false; }; // Canary mode: what a canary built later for a JS-extended instance starts @@ -378,6 +384,8 @@ class ObjectManager { static constexpr uint8_t kStateTags = 6; uint8_t stateTagCount = 0; uint32_t stateTags[kStateTags]; + // The object's weak-collection key, made on first use. + v8::Global key; }; using JSInstanceInfo = ObjectWeakCallbackState; @@ -452,6 +460,8 @@ class ObjectManager { ObjectWeakCallbackState* CanaryOf(const v8::Local& holder); CanaryRecord* FindCanaryRecord(int javaObjectID); + // canary's record, made if it has none. + CanaryRecord* RecordForWrite(ObjectWeakCallbackState* canary); // A new canary for a JS-extended instance whose canary died; empty when id // has no extended record or Java collected the object meanwhile. @@ -553,19 +563,39 @@ class ObjectManager { // Cloned for each new state; never handed to JS. v8::Global m_emptyState; v8::Local NewEmptyState(); - // The weak-collection key of a canary's Java object hangs off its state - // object, and names the object's id. Once the canary's link is released, - // the canary holds the key and the key leads back to the canary. - v8::Persistent m_keyOfState; + // A weak-collection key names its object's id. Once the canary's link is + // released, the canary holds the key and the key leads back to the canary. + v8::Persistent m_keyOfReleased; v8::Persistent m_objectOfKey; v8::Persistent m_releasedOfKey; - // Moves id's weak-collection key from its state to its live canary, whose - // link is being released. + // Gives id's weak-collection key to its live canary, whose link is being + // released. void KeepWeakCollectionKey(int javaObjectID); static void UnwrapForWeakCollection(const v8::FunctionCallbackInfo& info); static void WrapForWeakCollection(const v8::FunctionCallbackInfo& info); + static void TakeRekeysForWeakCollection(const v8::FunctionCallbackInfo& info); + + // Canaries of keyed objects that JS has not been told about: ids whose + // registration has rekeyPending set, plus stale ids of ones that died. + std::vector m_rekeyPendingIds; + // takeRekeys swaps it with m_rekeyPendingIds, so neither reallocates. + std::vector m_rekeyTakenIds; + // The element of binding.pendingRekeys: the live ones among them. Written + // from the canary weak callback too, which may not call into V8. + int32_t* m_rekeyPendingCount = nullptr; + // Keeps the count's memory alive. + v8::Persistent m_rekeyPendingArray; + void MarkRekeyPending(ObjectWeakCallbackState* state); + void DropRekeyPending(ObjectWeakCallbackState* state) { + if (state->rekeyPending) { + state->rekeyPending = false; + if (m_rekeyPendingCount != nullptr && *m_rekeyPendingCount > 0) { + --*m_rekeyPendingCount; + } + } + } // id's Java object, or null once Java collected it. jobject JavaObjectOrNull(int javaObjectID); diff --git a/test-app/runtime/src/main/cpp/WrapperLifetime.h b/test-app/runtime/src/main/cpp/WrapperLifetime.h index 6c1995d18..6d96c6fa6 100644 --- a/test-app/runtime/src/main/cpp/WrapperLifetime.h +++ b/test-app/runtime/src/main/cpp/WrapperLifetime.h @@ -77,6 +77,8 @@ struct WrapperLifetimeStats { // "canary" only: canaries built anew for a JS-extended instance whose // previous canary died while Java kept the object. uint64_t canaryRebuilds = 0; + // "canary" only: calls from js/weak-collections.js into the runtime. + uint64_t weakCollectionNativeCalls = 0; }; } // namespace tns diff --git a/test-app/runtime/src/main/cpp/js/weak-collections.js b/test-app/runtime/src/main/cpp/js/weak-collections.js index aad0f26f7..a11204bab 100644 --- a/test-app/runtime/src/main/cpp/js/weak-collections.js +++ b/test-app/runtime/src/main/cpp/js/weak-collections.js @@ -11,7 +11,7 @@ // left as it is: Object.getPrototypeOf(WeakMap.prototype) is the native // prototype, and WeakMap.toString() is not native code. -const { unwrap, wrap } = binding; +const { maybeCanary, unwrap, wrap, takeRekeys, pendingRekeys } = binding; const { FinalizationRegistry: NativeFinalizationRegistry, FinalizationRegistryPrototypeRegister, @@ -44,23 +44,54 @@ function canBeHeldWeakly(value) { return isObject(value) || (typeof value === "symbol" && SymbolKeyFor(value) === undefined); } -// unwrap(value, true) makes the key on first use; lookups pass false so they -// never create state for an object that was never a key. A key is made only -// once the native method can no longer reject the call, so a failed call leaves -// no state behind: the receiver is checked first with a method that cannot -// insert anything. +// unwrap(value, true) makes the key on first use. A key is made only once the +// native method can no longer reject the call, so a failed call leaves no key +// behind: the receiver is checked first with a method that cannot insert +// anything. // // A canary is never stored as a key itself (its lifetime key is), so every -// method first tries the value as is and unwraps it only when that misses: -// plain JS keys never reach native code. +// method first tries the value as is. canaryToKey holds every canary that +// stands for a key and that this file has seen: the ones keyFor unwrapped, and +// the ones takeRekeys returned. pendingRekeys[0] counts the live canaries the +// runtime built for keyed objects since takeRekeys last ran; while it is 0, a +// value missing from canaryToKey was never a key, and no native code runs. +const canaryToKey = new NativeWeakMap(); + +function takePendingRekeys() { + const pairs = takeRekeys(); + for (let i = 0; i < pairs.length; i += 2) { + WeakMapPrototypeSet(canaryToKey, pairs[i], pairs[i + 1]); + } +} // The lifetime key value stands for, or undefined when that is value itself. function otherKey(value) { if (!isObject(value)) { return undefined; } - const key = unwrap(value, false); - return key !== value ? key : undefined; + const key = WeakMapPrototypeGet(canaryToKey, value); + if (key !== undefined || pendingRekeys[0] === 0) { + return key; + } + takePendingRekeys(); + return WeakMapPrototypeGet(canaryToKey, value); +} + +// The key to store for value, an object, made on first use. +function keyFor(value) { + // A V8 fast call: a plain JS object reaches neither canaryToKey nor unwrap. + if (!maybeCanary(value)) { + return value; + } + const known = otherKey(value); + if (known !== undefined) { + return known; + } + const key = unwrap(value, true); + if (key !== value) { + WeakMapPrototypeSet(canaryToKey, value, key); + } + return key; } // Unregistering it finds nothing: it is never a token. @@ -79,7 +110,7 @@ class WeakMap extends NativeWeakMap { set(key, value) { // Also checks the receiver before a key is made. if (isObject(key) && !WeakMapPrototypeHas(this, key)) { - key = unwrap(key, true); + key = keyFor(key); } WeakMapPrototypeSet(this, key, value); return this; @@ -107,7 +138,7 @@ if (WeakMapPrototypeGetOrInsert !== undefined) { ObjectDefineProperty(WeakMap.prototype, "getOrInsert", { value: function getOrInsert(key, value) { if (isObject(key) && !WeakMapPrototypeHas(this, key)) { - key = unwrap(key, true); + key = keyFor(key); } return WeakMapPrototypeGetOrInsert(this, key, value); }, @@ -131,7 +162,7 @@ if (WeakMapPrototypeGetOrInsertComputed !== undefined) { // Before the key exists, so a callback that throws leaves none; it sees // the key it was given, not the lifetime key. const value = callbackfn(key); - WeakMapPrototypeSet(this, unwrap(key, true), value); + WeakMapPrototypeSet(this, keyFor(key), value); return value; }, writable: true, @@ -143,7 +174,7 @@ class WeakSet extends NativeWeakSet { add(value) { // Also checks the receiver before a key is made. if (isObject(value) && !WeakSetPrototypeHas(this, value)) { - value = unwrap(value, true); + value = keyFor(value); } WeakSetPrototypeAdd(this, value); return this; @@ -167,12 +198,19 @@ class WeakSet extends NativeWeakSet { } class WeakRef extends NativeWeakRef { + // A NativeWeakRef to the canary this was made with or last dereferenced to, + // or undefined when the target is not a key. A live canary is always what + // wrap returns for its key: Java cannot collect the object while it lives, + // and a released canary stays its key's object. Only the constructor and + // deref make one: a NativeWeakRef keeps its target until the job ends, which + // they do by spec anyway. + #canary; + constructor(target) { - const key = isObject(target) ? unwrap(target, true) : target; + const key = isObject(target) ? keyFor(target) : target; super(key); - // The target itself, not only its key, stays alive until the job ends. if (key !== target) { - new NativeWeakRef(target); + this.#canary = new NativeWeakRef(target); } } @@ -185,10 +223,25 @@ class WeakRef extends NativeWeakRef { if (!isObject(target)) { return target; } + // False for a native WeakRef given this method through call(). + const cached = #canary in this; + if (cached) { + const last = this.#canary; + if (last === undefined) { + return target; + } + const live = WeakRefPrototypeDeref(last); + if (live !== undefined) { + return live; + } + } const result = wrap(target); // The native deref already keeps a target it returns as is. if (result !== target && result !== undefined) { - new NativeWeakRef(result); + const ref = new NativeWeakRef(result); + if (cached) { + this.#canary = ref; + } } return result; } @@ -218,9 +271,9 @@ class FinalizationRegistry extends NativeFinalizationRegistry { FinalizationRegistryPrototypeUnregister(this, receiverProbe); FinalizationRegistryPrototypeRegister( this, - isObject(target) ? unwrap(target, true) : target, + isObject(target) ? keyFor(target) : target, heldValue, - isObject(unregisterToken) ? unwrap(unregisterToken, true) : unregisterToken, + isObject(unregisterToken) ? keyFor(unregisterToken) : unregisterToken, ); } From cc2e77dfa1f27ca175600f1ffd75a32b0d3ee0e1 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 16:46:36 -0300 Subject: [PATCH 12/15] test(runtime): weak collections on plain canaries without state Under scope "extended" a plain wrapper is now a canary without state, so the spec that kept a plain object's JS property across a wrapper change expects it there only under "all" (and "resurrecting"), and the first canary of a plain object dies in either canary scope. New specs, in canary mode: a keyed Java-held plain object whose canary died is found through the canary a deref builds and through the next one a Java read makes, neither of which has the old JS properties or a state; a FinalizationRegistry callback for a plain object runs once Java collected it and not while Java holds it; a released plain canary keeps what was keyed on it. The docs suggest a WeakMap keyed by the native object for plain-object state under "extended". --- docs/ns-builtin-modules.md | 4 +- .../testWrapperLifetimeWeakCollections.js | 111 ++++++++++++++++-- .../runtime/src/main/cpp/ObjectManager.cpp | 7 +- 3 files changed, 111 insertions(+), 11 deletions(-) diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 5a42398dd..8e3345863 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -239,7 +239,9 @@ their JS properties: object for JS; when Java hands the object back later, its wrapper is a new object without the old one's JS properties. JS properties on plain native objects are therefore not preserved under `"extended"`: keep such state on a - JS object of your own, or use `"all"`, which gives every wrapper state. + JS object of your own, such as a `WeakMap` keyed by the native object (in + canary mode its entries live exactly as long as the Java object, see below), + or use `"all"`, which gives every wrapper state. Array buffers backed by Java buffers keep the `"resurrecting"` lifetime under either scope. diff --git a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js index 3c5d6eebb..0ca433465 100644 --- a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js @@ -3,6 +3,7 @@ describe("Weak collections of Java objects", function () { var runtime = require("ns:runtime"); var mode = runtime.getConfig("wrapperLifetimeMode"); + var scope = runtime.getConfig("wrapperLifetimeScope"); var canary = mode === "canary"; var Holder = com.tns.tests.WrapperHolder; @@ -158,8 +159,9 @@ describe("Weak collections of Java objects", function () { }, 0); }); - // Under scope "all" a plain wrapper is a canary: its key hangs off its state, and deref - // makes a new wrapper the usual way, hydrated from the state. + // In canary mode a plain wrapper is a canary: its key hangs off its record, and deref + // makes a new wrapper the usual way, with the old one's JS properties under scope "all" + // only. it("keeps a WeakMap entry and a WeakRef target for a Java-held plain object across a wrapper change", function (done) { var map = new WeakMap(); var ref = (function () { @@ -176,11 +178,109 @@ describe("Weak collections of Java objects", function () { var target = ref.deref(); expect(target).toBeDefined(); expect(target.toString()).toBe("plain"); - expect(target.tag).toBe("state"); + if (canary && scope === "extended") { + expect(target.tag).toBeUndefined(); + } else { + expect(target.tag).toBe("state"); + } done(); }, 0); }); + // A keyed plain wrapper under scope "extended" is a canary with a record and no state: + // the next one is a new, empty object that stands for the same key. + it("finds a keyed Java-held plain object through its next canary, which has no state, under scope extended", function (done) { + if (!canary || scope !== "extended") { + done(); + return; + } + var NativeWeakRef = Object.getPrototypeOf(WeakRef); + var map = new WeakMap(); + var set = new WeakSet(); + var registry = new FinalizationRegistry(function () {}); + var target = {}; + var states = runtime.getWrapperLifetimeStats().canaryStates; + var first; + var refs = (function () { + var builder = new java.lang.StringBuilder("plain"); + builder.tag = "lost"; + map.set(builder, "value"); + set.add(builder); + registry.register(target, "held", builder); + Holder.held = builder; + first = new NativeWeakRef(builder); + return [new WeakRef(builder), new WeakRef(builder)]; + })(); + setTimeout(function () { + collectBoth(); + expect(first.deref()).toBeUndefined(); + // No canary is alive: deref builds one. + var built = refs[0].deref(); + expect(built).toBeDefined(); + expect(built.toString()).toBe("plain"); + expect(built.tag).toBeUndefined(); + expect(Holder.held === built).toBe(true); + built = null; + collectBoth(); + var again = Holder.held; + expect(again.tag).toBeUndefined(); + expect(map.get(again)).toBe("value"); + expect(map.has(again)).toBe(true); + expect(set.has(again)).toBe(true); + expect(refs[1].deref() === again).toBe(true); + expect(registry.unregister(again)).toBe(true); + expect(runtime.getWrapperLifetimeStats().canaryStates).toBe(states); + done(); + }, 0); + }); + + it("runs a FinalizationRegistry callback for a plain object only once Java collected it", function (done) { + if (!canary) { + done(); + return; + } + var heldCleaned = false; + var droppedCleaned = false; + var registry = new FinalizationRegistry(function (held) { + if (held === "held") { + heldCleaned = true; + } else if (held === "dropped") { + droppedCleaned = true; + } + }); + (function () { + var held = new java.lang.StringBuilder("held"); + Holder.held = held; + registry.register(held, "held"); + registry.register(new java.lang.StringBuilder("dropped"), "dropped"); + })(); + function finish() { + expect(heldCleaned).toBe(false); + expect(Holder.held.toString()).toBe("held"); + done(); + } + finish.fail = done.fail; + eventually(function () { + return droppedCleaned; + }, finish, "the cleanup callback did not run"); + }, 20000); + + it("keeps what was keyed on a plain Java object after its link is released", function () { + if (!canary) { + return; + } + var map = new WeakMap(); + var set = new WeakSet(); + var builder = new java.lang.StringBuilder("released"); + map.set(builder, "value"); + set.add(builder); + __releaseNativeCounterpart(builder); + collectBoth(); + expect(map.get(builder)).toBe("value"); + expect(set.has(builder)).toBe(true); + expect(new WeakRef(builder).deref() === builder).toBe(true); + }); + it("clears a WeakRef once Java collected the object", function (done) { var ref = (function () { return new WeakRef(new java.lang.Runnable({ run: function () {} })); @@ -441,10 +541,7 @@ describe("Weak collections of Java objects", function () { setTimeout(function () { collectBoth(); if (canary) { - // A plain wrapper is a canary under scope "all" only. - if (runtime.getConfig("wrapperLifetimeScope") === "all") { - expect(firstCanaries[0].deref()).toBeUndefined(); - } + expect(firstCanaries[0].deref()).toBeUndefined(); expect(firstCanaries[1].deref()).toBeUndefined(); } var list = Holder.held; diff --git a/test-app/runtime/src/main/cpp/ObjectManager.cpp b/test-app/runtime/src/main/cpp/ObjectManager.cpp index 185c1d03c..a57148cea 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -1344,8 +1344,8 @@ void ObjectManager::UnwrapForWeakCollection(const FunctionCallbackInfo& i } // wrap(key): the Java object a key stands for, as its live canary or a new one -// with its state, or undefined once Java collected it. Anything that is not a -// key passes through. +// (with its state, when it keeps one), or undefined once Java collected it. +// Anything that is not a key passes through. void ObjectManager::WrapForWeakCollection(const FunctionCallbackInfo& info) { try { Isolate* isolate = info.GetIsolate(); @@ -1385,7 +1385,8 @@ void ObjectManager::WrapForWeakCollection(const FunctionCallbackInfo& inf } Local result = thisPtr->RebuildCanary(id); if (result.IsEmpty() && thisPtr->FindCanaryRecord(id) != nullptr) { - // A plain object: a wrapper made from it the usual way is hydrated from its state. + // A plain object: a wrapper made from it the usual way links to its record, + // and gets its state back in scope. JniLocalRef javaObject(thisPtr->JavaObjectOrNull(id)); if (!javaObject.IsNull()) { result = thisPtr->GetOrCreateJSWrapper(javaObject); From 39b704cba9cd7f8988e26f280adb1911a62f5cde Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 20:07:17 -0300 Subject: [PATCH 13/15] docs(runtime): a lookup miss can pay for learning rebuilt keyed canaries The weakCollectionNativeCalls row said lookups of a value that was never a key make no call, but the first lookup that misses while the runtime has built canaries for keyed objects makes the call that learns them, whatever value it looks up, as the weak collections section already says. --- docs/ns-builtin-modules.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 8e3345863..f787f5d19 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -195,7 +195,7 @@ every build on cold paths only: | `canaryCachedWrites` | `"canary"` only: of those writes, rewrites of a name the handler knew to be a plain data property of the state, mirrored with one store | | `canaryCachedFieldWrites` | `"canary"` only: of those writes, Java field writes the handler placed from an earlier write of the same name through an object with the same prototype, without looking the name up along the prototype chain | | `canaryRebuilds` | `"canary"` only: canaries built anew for a JS-extended instance whose previous canary died while Java kept the object | -| `weakCollectionNativeCalls` | `"canary"` only: calls the weak collections make into the runtime: to make the key of a canary's Java object, to find the canary for a key, and to learn about canaries built for keyed objects since the last such call. Lookups of a value that was never a key make none | +| `weakCollectionNativeCalls` | `"canary"` only: calls the weak collections make into the runtime: to make the key of a canary's Java object, to find the canary for a key, and to learn about canaries built for keyed objects since the last such call. A lookup of a value that was never a key makes none of its own, but the first lookup that misses after the runtime built such canaries, whatever value it looks up, makes that last call | In `"canary"` mode only array buffers backed by Java buffers resurrect; `weakened` counts objects held weakly because their canary died while they From 72597fac74fe0996c61374dec70328fc7367db98 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 20:22:31 -0300 Subject: [PATCH 14/15] perf(runtime): keep one queued rekey per id when the queue is pruned MarkRekeyPending queues an id once per canary built for a keyed object, and the prune kept every row whose id's latest canary is pending. An object rebuilt many times before a lookup missed therefore kept all its rows through prunes made by other objects' canaries: such a prune removed nothing, and the next mark ran it again over the same rows, until that object was rebuilt once more (its own mark prunes its rows), the pending count caught up with the queue, or JS drained it. The prune now also keeps one row per id, so the queue is back to the pending count after each prune. The queue's length is not in the stats; the spec drives the prune with one object's canaries and checks that every keyed object is still found through its latest canary, with one call for all of them. --- .../testWrapperLifetimeWeakCollections.js | 41 +++++++++++++++++++ .../runtime/src/main/cpp/ObjectManager.cpp | 7 +++- 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js index 0ca433465..15bf3fafe 100644 --- a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js @@ -676,6 +676,47 @@ describe("Weak collections of Java objects", function () { } }); + // Past 64 queued canaries the runtime prunes the queue as it builds more; the latest + // canary of an object built many times must survive the prunes the others' canaries make. + it("finds keyed Java objects through canaries built past the queue's prune while no lookup ran", function () { + var map = new WeakMap(); + var list = new java.util.ArrayList(); + Holder.held = list; + var count = 8; + (function () { + for (var i = 0; i < count; i++) { + var runnable = new java.lang.Runnable({ run: function () {} }); + list.add(runnable); + map.set(runnable, i); + } + })(); + gc(); + map.has({}); + var rebuilds = runtime.getWrapperLifetimeStats().canaryRebuilds; + for (var n = 0; n < 63; n++) { + (function () { + list.get(0).hashCode(); + })(); + gc(); + } + var first = list.get(0); + var others = []; + for (var i = 1; i < count; i++) { + others.push(list.get(i)); + } + if (canary) { + expect(runtime.getWrapperLifetimeStats().canaryRebuilds).toBeGreaterThan(rebuilds + 64); + } + var before = nativeCalls(); + expect(map.get(first)).toBe(0); + for (var j = 0; j < others.length; j++) { + expect(map.get(others[j])).toBe(j + 1); + } + if (canary) { + expect(nativeCalls()).toBe(before + 1); + } + }); + it("finds a keyed Java object through a canary built and released while no lookup ran", function () { var map = new WeakMap(); var set = new WeakSet(); diff --git a/test-app/runtime/src/main/cpp/ObjectManager.cpp b/test-app/runtime/src/main/cpp/ObjectManager.cpp index a57148cea..65ca90fc3 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -1409,7 +1409,9 @@ void ObjectManager::MarkRekeyPending(ObjectWeakCallbackState* state) { return; } // Stale ids pile up only while JS makes no lookup that misses; prune them - // once they outnumber the live ones. + // once they outnumber the live ones. An id is queued once per canary built + // for it, and every copy looks live while its latest canary is pending, so + // keep one copy of each; takeRekeys does not depend on their order. if (m_rekeyPendingIds.size() >= 64 && m_rekeyPendingIds.size() > 2 * static_cast(*m_rekeyPendingCount)) { m_rekeyPendingIds.erase( @@ -1419,6 +1421,9 @@ void ObjectManager::MarkRekeyPending(ObjectWeakCallbackState* state) { return live == nullptr || !live->rekeyPending; }), m_rekeyPendingIds.end()); + std::sort(m_rekeyPendingIds.begin(), m_rekeyPendingIds.end()); + m_rekeyPendingIds.erase(std::unique(m_rekeyPendingIds.begin(), m_rekeyPendingIds.end()), + m_rekeyPendingIds.end()); } state->rekeyPending = true; m_rekeyPendingIds.push_back(state->javaObjectID); From b395518b0b3cfb558171511b8f73d9e5fd80ba12 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 20:08:33 -0300 Subject: [PATCH 15/15] test(runtime): FinalizationRegistry polling specs name their registry A collected registry runs no callbacks, so a spec that polls for a cleanup callback could time out, and one that polls for its absence could pass without a registration. The polling closures of these specs share a V8 context with the closure that registers, which already keeps the registry alive; naming it in the poll, as the released-canary spec does, makes that not depend on how V8 allocates contexts. --- .../app/tests/testWrapperLifetimeWeakCollections.js | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js index 15bf3fafe..d9f93d17c 100644 --- a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js @@ -261,7 +261,8 @@ describe("Weak collections of Java objects", function () { } finish.fail = done.fail; eventually(function () { - return droppedCleaned; + // A collected registry runs no callbacks. + return droppedCleaned && registry !== null; }, finish, "the cleanup callback did not run"); }, 20000); @@ -299,7 +300,8 @@ describe("Weak collections of Java objects", function () { registry.register(new java.lang.Runnable({ run: function () {} }), "held"); })(); eventually(function () { - return cleaned; + // A collected registry runs no callbacks. + return cleaned && registry !== null; }, done, "the cleanup callback did not run"); }, 20000); @@ -407,6 +409,8 @@ describe("Weak collections of Java objects", function () { return; } expect(Holder.held).not.toBe(null); + // A collected registry runs no callbacks, so this spec would pass without one. + expect(registry instanceof FinalizationRegistry).toBe(true); done(); })(); }, 20000);