From 704b6726dd8c7b39724f806d260062ea80d46142 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 19:19:54 -0300 Subject: [PATCH 1/8] perf(runtime): weak collections skip native calls for plain keys and live WeakRef targets In canary mode a WeakMap, WeakSet or FinalizationRegistry miss on a plain JS object asked native code for a lifetime key, and that native lookup read a private property twice to find the object was no wrapper. unwrap now returns at once for an object without internal fields, which no canary or -dealloc receiver is. WeakRef.prototype.deref asked native code for the wrapper on every call. A WeakRef now keeps a NativeWeakRef to the canary it was made with or last dereferenced to, and hands it back while it lives and the epoch native code bumps is unchanged: __releaseNativeCounterpart bumps it, as does a record dying under a live canary (its associations removed). A WeakRef whose target is not a lifetime key returns it without a native call. Weak collection lookups of canaries still ask native code every time. A JS-side canary -> key cache was measured: hits got about 30 ns faster, but caching a freshly built canary cost about 150 ns, more than a short-lived wrapper recovers. --- NativeScript/runtime/WrapperLifetimeCanary.h | 6 +- NativeScript/runtime/WrapperLifetimeCanary.mm | 78 ++++++++-- NativeScript/runtime/js/weak-collections.js | 53 ++++++- .../WrapperLifetimeWeakCollectionsTests.js | 141 ++++++++++++++++++ 4 files changed, 257 insertions(+), 21 deletions(-) diff --git a/NativeScript/runtime/WrapperLifetimeCanary.h b/NativeScript/runtime/WrapperLifetimeCanary.h index c65c7d24..1499c98d 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.h +++ b/NativeScript/runtime/WrapperLifetimeCanary.h @@ -101,9 +101,11 @@ class WrapperLifetimeCanary { // anew, as it does any result whose kind differs from the template's. static CanaryKind NativeInstancesKind(); - // Adds `unwrap` (a canary's native object -> its weak-collection key) and + // Adds `unwrap` (a canary's native object -> its weak-collection key), // `wrap` (key -> live or new canary, or undefined once the object is gone) - // to `binding`, for the weak-collections builtin. Canary mode only. + // and `cache` (the Uint32Array that tells the builtin when a wrapper it + // cached from wrap is stale) to `binding`, for the weak-collections builtin. + // Canary mode only. static bool RegisterWrapFunctions(v8::Local context, v8::Local binding); diff --git a/NativeScript/runtime/WrapperLifetimeCanary.mm b/NativeScript/runtime/WrapperLifetimeCanary.mm index 0e5e3468..010db0f4 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.mm +++ b/NativeScript/runtime/WrapperLifetimeCanary.mm @@ -89,6 +89,22 @@ bool ObjectAlive() const { namespace { +// What the weak-collections builtin reads through a Uint32Array over `slots` +// (RegisterWrapFunctions). It drops every wrapper it cached from wrap once +// kEpoch changes, which can happen on any thread. After an unwrap that asked +// (UnwrapCallback), kLiveCanary is 1 when the value is a live canary standing +// for the key it answered: the wrapper wrap answers with for that key. +struct WeakCollectionCache { + enum Slot { kEpoch, kLiveCanary, kSlotCount }; + std::atomic slots[kSlotCount]; + + // A wrapper wrap answered may no longer be the one it answers. + void Invalidate() { slots[kEpoch].fetch_add(1, std::memory_order_release); } + void SetLiveCanary(bool live) { + slots[kLiveCanary].store(live ? 1 : 0, std::memory_order_relaxed); + } +}; + // Per-isolate. Shared with the tokens associated with native objects, which // can be deallocated on any thread and after the isolate is gone. struct CanaryRegistry { @@ -105,6 +121,9 @@ bool ObjectAlive() const { bool sweepPosted = false; // Lets wrapper creation skip the lookup while no object has state. std::atomic count{0}; + // Outlives the registry while the builtin's array does. + std::shared_ptr weakCollectionCache = + std::make_shared(); Isolate* isolate = nullptr; std::weak_ptr loop; #if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_ASSOCIATION @@ -197,6 +216,12 @@ void NativeDied(const std::shared_ptr& registry, void* object, // Erased now, inside the object's -dealloc: an object later allocated at // this address must not find this record. it->second->died.store(true, std::memory_order_release); + // A record held outside the registry and not dying is a live canary's (its + // associations were removed): wrap no longer answers with that canary. + // A transient copy elsewhere bumps it spuriously, which only costs a refill. + if (!it->second->dying.load(std::memory_order_acquire) && it->second.use_count() > 1) { + registry->weakCollectionCache->Invalidate(); + } registry->dead.push_back(std::move(it->second)); registry->records.erase(it); registry->count.fetch_sub(1, std::memory_order_relaxed); @@ -993,21 +1018,30 @@ void PostSweepAfterGC(Isolate* isolate, GCType, GCCallbackFlags) { } #endif -// unwrap(value, create): the weak collections' key for a canary's native -// object, a frozen, null-prototype object that lives as long as the object's -// state, that is, until the native object is deallocated, or as long as a -// released canary of the object holding a copy. 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, as in every other mode). +// unwrap(value, create, reportLive): the weak collections' key for a canary's +// native object, a frozen, null-prototype object that lives as long as the +// object's state, that is, until the native object is deallocated, or as long +// as a released canary of the object holding a copy. 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, as in every other mode). With `reportLive`, also sets +// WeakCollectionCache::kLiveCanary. void UnwrapCallback(const FunctionCallbackInfo& info) { Isolate* isolate = info.GetIsolate(); Local value = info[0]; bool create = info[1]->IsTrue(); + bool reportLive = info[2]->IsTrue(); info.GetReturnValue().Set(value); CanaryState* canaryState = Caches::StateFor(isolate); Local state; - if (canaryState == nullptr || !value->IsObject() || value->IsProxy()) { + if (reportLive && canaryState != nullptr) { + canaryState->registry->weakCollectionCache->SetLiveCanary(false); + } + // Canaries and -dealloc receivers have internal fields; for any other object + // the wrapper lookups below would each read a private property to find no + // canary. + if (canaryState == nullptr || !value->IsObject() || value->IsProxy() || + value.As()->InternalFieldCount() == 0) { return; } Local context = isolate->GetCurrentContext(); @@ -1017,8 +1051,7 @@ void UnwrapCallback(const FunctionCallbackInfo& info) { : !ExistingState(isolate, value.As(), &state)) { // A released canary keeps its key itself, or null when it had none // (KeepWeakCollectionKey). - if (value.As()->InternalFieldCount() == 0 || - !value.As()->GetPrivate(context, keyOfState).ToLocal(&key)) { + if (!value.As()->GetPrivate(context, keyOfState).ToLocal(&key)) { return; } if (key->IsObject()) { @@ -1036,6 +1069,10 @@ void UnwrapCallback(const FunctionCallbackInfo& info) { return; } if (state->GetPrivate(context, keyOfState).ToLocal(&key) && key->IsObject()) { + if (reportLive) { + canaryState->registry->weakCollectionCache->SetLiveCanary( + CanaryOf(isolate, value.As()) != nullptr); + } info.GetReturnValue().Set(key); return; } @@ -1064,6 +1101,9 @@ void UnwrapCallback(const FunctionCallbackInfo& info) { !state->SetPrivate(context, keyOfState, newKey).FromMaybe(false)) { return; } + if (reportLive) { + canaryState->registry->weakCollectionCache->SetLiveCanary(true); + } info.GetReturnValue().Set(newKey); } @@ -1162,10 +1202,24 @@ void WrapCallback(const FunctionCallbackInfo& info) { Isolate* isolate = v8::Isolate::GetCurrent(); Local unwrap; Local wrap; + CanaryState* state = Caches::StateFor(isolate); + if (state == nullptr) { + return false; + } + auto* owner = new std::shared_ptr(state->registry->weakCollectionCache); + std::unique_ptr store = ArrayBuffer::NewBackingStore( + (*owner)->slots, sizeof((*owner)->slots), + [](void*, size_t, void* data) { + delete static_cast*>(data); + }, + owner); + Local cache = v8::Uint32Array::New(ArrayBuffer::New(isolate, std::move(store)), + 0, WeakCollectionCache::kSlotCount); return v8::Function::New(context, UnwrapCallback).ToLocal(&unwrap) && v8::Function::New(context, WrapCallback).ToLocal(&wrap) && binding->Set(context, tns::ToV8String(isolate, "unwrap"), unwrap).FromMaybe(false) && - binding->Set(context, tns::ToV8String(isolate, "wrap"), wrap).FromMaybe(false); + binding->Set(context, tns::ToV8String(isolate, "wrap"), wrap).FromMaybe(false) && + binding->Set(context, tns::ToV8String(isolate, "cache"), cache).FromMaybe(false); } void WrapperLifetimeCanary::KeepWeakCollectionKey(Isolate* isolate, Local canary) { @@ -1219,6 +1273,8 @@ void WrapCallback(const FunctionCallbackInfo& info) { if (std::shared_ptr current = currentRecord()) { current->released = true; } + // wrap hands out no wrapper of the object now. + canaryState->registry->weakCollectionCache->Invalidate(); } void WrapperLifetimeCanary::InstallDeallocHook(Class extendedClass) { diff --git a/NativeScript/runtime/js/weak-collections.js b/NativeScript/runtime/js/weak-collections.js index d265bdb1..be559bc6 100644 --- a/NativeScript/runtime/js/weak-collections.js +++ b/NativeScript/runtime/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 { unwrap, wrap, cache } = binding; const { FinalizationRegistry: NativeFinalizationRegistry, FinalizationRegistryPrototypeRegister, @@ -54,11 +54,18 @@ function canBeHeldWeakly(value) { // key (a class forbidding associated objects or refusing weak references, a // -dealloc receiver, a released wrapper that never had one), and unwrap then // returns the canary too. So every method first tries the value as is and -// unwraps it only when that misses: plain JS keys never reach native code. +// unwraps it only when that misses. + +// Slots of `cache` (WeakCollectionCache in WrapperLifetimeCanary.mm): EPOCH +// changes whenever a wrapper wrap answered may no longer be the one it +// answers; after unwrap(value, true, true), LIVE_CANARY says whether value is +// the wrapper wrap answers with for the key unwrap returned. +const EPOCH = 0; +const LIVE_CANARY = 1; // The lifetime key value stands for, or undefined when that is value itself. function otherKey(value) { - if (!isObject(value)) { + if ((typeof value !== "object" || value === null) && typeof value !== "function") { return undefined; } const key = unwrap(value, false); @@ -170,12 +177,26 @@ class WeakSet extends NativeWeakSet { } class WeakRef extends NativeWeakRef { + // Undefined when the target is not a lifetime key. Otherwise null, or a + // NativeWeakRef to the wrapper the WeakRef was made with or deref last + // returned, which wrap still answers with while the epoch is #epoch. + #wrapper = undefined; + #epoch = 0; + constructor(target) { - const key = isObject(target) ? unwrap(target, true) : target; + const now = cache[EPOCH]; + const key = isObject(target) ? unwrap(target, true, true) : target; + const live = key !== target && cache[LIVE_CANARY] !== 0; super(key); // The target itself, not only its key, stays alive until the job ends. if (key !== target) { - new NativeWeakRef(target); + const kept = new NativeWeakRef(target); + if (live) { + this.#wrapper = kept; + this.#epoch = now; + } else { + this.#wrapper = null; + } } } @@ -188,10 +209,26 @@ class WeakRef extends NativeWeakRef { if (!isObject(target)) { return target; } + if (!(#wrapper in this)) { + return wrap(target); + } + const last = this.#wrapper; + if (last === undefined) { + return target; + } + const now = cache[EPOCH]; + if (last !== null && this.#epoch === now) { + 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); + if (result !== undefined) { + this.#wrapper = new NativeWeakRef(result); + this.#epoch = now; + } else { + this.#wrapper = null; } return result; } diff --git a/TestRunner/app/tests/WrapperLifetimeWeakCollectionsTests.js b/TestRunner/app/tests/WrapperLifetimeWeakCollectionsTests.js index 54de2cdc..79e68f4c 100644 --- a/TestRunner/app/tests/WrapperLifetimeWeakCollectionsTests.js +++ b/TestRunner/app/tests/WrapperLifetimeWeakCollectionsTests.js @@ -186,6 +186,147 @@ describe("Weak collections of native objects", function () { }); }); + // Uses every collection, and a deref, on a canary in an earlier job, so + // whatever they keep for it would still be there. + function keyEverywhere(obj, collections) { + collections.map.set(obj, "value"); + collections.set.add(obj); + collections.registry.register(obj, "held", obj); + var ref = new WeakRef(obj); + ref.deref(); + collections.map.get(obj); + collections.set.has(obj); + collections.refs.push(ref); + collections.wrappers.push(new WrapperWeakRef(obj)); + } + + function collections() { + return { + map: new WeakMap(), + set: new WeakSet(), + registry: new FinalizationRegistry(function () {}), + refs: [], + wrappers: [] + }; + } + + it("lets a keyed wrapper nothing references die and its JS-owned native object go", function (done) { + var watch = NSHashTable.weakObjectsHashTable(); + var keyed = collections(); + (function () { + var obj = Extended.new(); + watch.addObject(obj); + keyEverywhere(obj, keyed); + })(); + var attempts = 15; + (function poll() { + settle(1, function () { + var gone = watch.allObjects.count === 0; + if (gone || --attempts === 0) { + expect(gone).toBe(true); + if (canary) { + expect(keyed.wrappers[0].deref() === undefined).toBe(true); + expect(keyed.refs[0].deref() === undefined).toBe(true); + } + done(); + return; + } + poll(); + }); + })(); + }); + + it("lets a keyed canary nothing references die while native code owns its object", function (done) { + if (!canary) { + done(); + return; + } + var owner = NSMutableArray.new(); + var keyed = collections(); + (function () { + var obj = Extended.new(); + owner.addObject(obj); + keyEverywhere(obj, keyed); + })(); + settle(2, function () { + expect(keyed.wrappers[0].deref() === undefined).toBe(true); + var later = owner.objectAtIndex(0); + expect(keyed.map.get(later)).toBe("value"); + expect(keyed.set.has(later)).toBe(true); + expect(keyed.refs[0].deref() === later).toBe(true); + expect(keyed.registry.unregister(later)).toBe(true); + done(); + }); + }); + + it("dereferences no wrapper of a released object a WeakRef returned before the release", function () { + if (!canary) { + return; + } + var owner = NSMutableArray.new(); + var obj = Extended.new(); + owner.addObject(obj); + var ref = new WeakRef(obj); + expect(ref.deref() === obj).toBe(true); + __releaseNativeCounterpart(obj); + expect(ref.deref() === undefined).toBe(true); + var later = owner.objectAtIndex(0); + expect(ref.deref() === later).toBe(true); + }); + + // Only objects outside JS-extended classes carry the token the removal + // releases, and they are canaries only under scope "all". + it("keys a live object again after its associations are removed", function (done) { + if (!canary || runtime.getConfig("wrapperLifetimeScope") !== "all" || + typeof objc_removeAssociatedObjects !== "function") { + done(); + return; + } + var owner = NSMutableArray.new(); + var before = new WeakMap(); + var after = new WeakMap(); + (function () { + var obj = TNSAllocLog.new(); + owner.addObject(obj); + before.set(obj, "before"); + expect(before.get(obj)).toBe("before"); + objc_removeAssociatedObjects(obj); + after.set(obj, "after"); + expect(after.get(obj)).toBe("after"); + })(); + settle(2, function () { + expect(after.get(owner.objectAtIndex(0))).toBe("after"); + done(); + }); + }); + + it("finds what was keyed on an object through its JS dealloc's receiver", function (done) { + var map = new WeakMap(); + var seen = []; + var Keyed = TNSAllocLog.extend({ + dealloc: function () { + seen.push(map.get(this)); + this.super.dealloc(); + } + }, { name: "WrapperLifetimeWeakCollectionsDeallocGet" }); + var owner = NSMutableArray.new(); + (function () { + var obj = Keyed.new(); + map.set(obj, "value"); + owner.addObject(obj); + })(); + settle(2, function () { + owner.removeAllObjects(); + settle(2, function () { + expect(seen.length).toBe(1); + if (canary) { + expect(seen[0]).toBe("value"); + } + done(); + }); + }); + }); + it("keys a Proxy around a native object by the Proxy", function () { var obj = Extended.new(); var proxy = new Proxy(obj, {}); From c64f4bba860571451cd0552f9da649e4e70b454d Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 15:23:43 -0300 Subject: [PATCH 2/8] test(runtime): let the keyed-wrapper spec's probe drain before collecting The spec polled a weak NSHashTable through allObjects and collected right after, in the same callback. The array allObjects returns retains its objects until the autorelease pool drains, and under the "rooted" mode the major-GC prologue counts that retain as native ownership: each round's probe re-rooted the wrapper it was waiting for, so the object never went under rooted/all. The probe now releases the array's wrapper, and the next collection waits for the run loop to drain the pool. --- .../tests/WrapperLifetimeWeakCollectionsTests.js | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/TestRunner/app/tests/WrapperLifetimeWeakCollectionsTests.js b/TestRunner/app/tests/WrapperLifetimeWeakCollectionsTests.js index 79e68f4c..9a71d2c9 100644 --- a/TestRunner/app/tests/WrapperLifetimeWeakCollectionsTests.js +++ b/TestRunner/app/tests/WrapperLifetimeWeakCollectionsTests.js @@ -210,6 +210,17 @@ describe("Weak collections of native objects", function () { }; } + // The objects a weak table still holds. The array allObjects returns + // retains them until its wrapper is released and the autorelease pool + // drains; a "rooted" collection before that counts the retain as native + // ownership and roots their wrappers. + function watchedCount(table) { + var all = table.allObjects; + var count = all.count; + __releaseNativeCounterpart(all); + return count; + } + it("lets a keyed wrapper nothing references die and its JS-owned native object go", function (done) { var watch = NSHashTable.weakObjectsHashTable(); var keyed = collections(); @@ -221,7 +232,7 @@ describe("Weak collections of native objects", function () { var attempts = 15; (function poll() { settle(1, function () { - var gone = watch.allObjects.count === 0; + var gone = watchedCount(watch) === 0; if (gone || --attempts === 0) { expect(gone).toBe(true); if (canary) { @@ -231,7 +242,8 @@ describe("Weak collections of native objects", function () { done(); return; } - poll(); + // Collects only after the run loop drained the probe's array. + setTimeout(poll, 10); }); })(); }); From 946ddc83d44491217d29c5b2119dd6b6360123ed Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 14:42:24 -0300 Subject: [PATCH 3/8] feat(runtime): weak collections key plain objects by lifetime under canary/extended Under "wrapperLifetime": { "mode": "canary", "scope": "extended" } a plain (not JS-extended) object's wrapper is a phantom handle that dies with its JS references while native code may still hold the object, yet the weak collections keyed that wrapper. WeakMap and WeakSet entries, WeakRef targets and FinalizationRegistry registrations followed the wrapper: lost, or fired, when it died while the object lived. The first set, add, new WeakRef or register of a plain object now gives it a key-only record in the canary registry: the lifecycle token, a weak slot and a state that holds only the weak-collection key. From then on the object is keyed by its lifetime as a canary is. Wrapping is untouched: plain wrappers stay kNone with no handlers, state or registry lookup. unwrap finds the record by the object's address only after the canary lookups miss, behind an atomic count of plain records, and canary adoption skips the registry when only plain records exist. wrap hands back the object's live wrapper or builds a plain one. __releaseNativeCounterpart on a plain wrapper copies the key (or the null marker when none was made) onto it and marks the record released; a live wrapper of the object reaching unwrap or wrap clears the mark. A token removed by objc_removeAssociatedObjects bumps the deref cache epoch when the object is still alive. Classes that forbid associated objects or refuse weak references, tagged pointers and blocks keep their wrapper as the key. Release simulator build, canary/extended, ns/op (medians of 5 launches before, 3 after): before after NSObject.new() create + drop 854 826 native call o.isEqual(o) 119 120 native property o.hash 95 92 native property store view.tag 120 122 owner.objectAtIndex(0), live wrapper 137 132 WeakMap has, never-keyed plain, no plain keys 111 108 WeakMap has, never-keyed plain, plain keys exist 107 126 WeakMap get / has / set on a keyed plain object 40/39/55 145/143/143 first keying: map.set(fresh plain object) 165 966 first keying: new WeakRef(fresh plain object) 248 1544 new WeakRef(o).deref() 236 360 ref.deref(), same ref 63 89 ref.deref() rebuilding a dead plain wrapper 48* 1152 map.get on a rebuilt wrapper, first touch 103* 214 * before: the dead wrapper was the key, so these found nothing (0 of 12000 lookups; 12000 of 12000 after). --- NativeScript/runtime/ObjectManager.mm | 15 +- NativeScript/runtime/WrapperLifetime.h | 3 + NativeScript/runtime/WrapperLifetime.mm | 2 + NativeScript/runtime/WrapperLifetimeCanary.h | 16 +- NativeScript/runtime/WrapperLifetimeCanary.mm | 397 +++++++++--- NativeScript/runtime/js/weak-collections.js | 20 +- .../app/tests/WrapperLifetimeLeaksTests.js | 20 + .../WrapperLifetimeWeakCollectionsTests.js | 609 +++++++++++------- docs/knowledge/v8-resurrecting-finalizers.md | 34 +- docs/ns-builtin-modules.md | 19 +- types/ns-runtime.d.ts | 10 +- 11 files changed, 791 insertions(+), 354 deletions(-) diff --git a/NativeScript/runtime/ObjectManager.mm b/NativeScript/runtime/ObjectManager.mm index f68e5339..b5d730c6 100644 --- a/NativeScript/runtime/ObjectManager.mm +++ b/NativeScript/runtime/ObjectManager.mm @@ -823,6 +823,7 @@ void DisposeHandle(v8::Isolate* isolate, if (data != nil) { std::shared_ptr cache = Caches::Get(isolate); auto it = cache->Instances.find(data); + bool canary = false; if (ObjectWeakCallbackState* managed = objcWrapper->OwnershipState()) { // The handle ReconcileOwnership manages is this wrapper's own, whatever // Instances maps the object to now. @@ -845,7 +846,8 @@ void DisposeHandle(v8::Isolate* isolate, // walk, or an outer call still writing the canary's key below. return; } - if (adopted->lifetimeCanary_) { + canary = adopted->lifetimeCanary_; + if (canary) { // Before the release below, which can run the object's -dealloc. The // write can allocate, and the finalizers of the collection that // triggers can run JS that calls this builtin on the same wrapper. @@ -893,6 +895,17 @@ void DisposeHandle(v8::Isolate* isolate, } } + if (!canary && !objcWrapper->IsAdapterClaim()) { + // Before the release below, which can run the object's -dealloc. The + // write can allocate, and the finalizers of the collection that + // triggers can run JS that calls this builtin on the same wrapper: a + // release that got through freed the wrapper. + WrapperLifetimeCanary::KeepPlainWeakCollectionKey(isolate, value.As(), data); + if (tns::GetValue(isolate, value) != wrapper) { + return; + } + } + // Release the runtime's strong reference (taken when the object was first // wrapped or adopted from an alloc/new/copy return). For instances solely // owned by JS this deallocates them, on the runtime's thread (at once when diff --git a/NativeScript/runtime/WrapperLifetime.h b/NativeScript/runtime/WrapperLifetime.h index 8282d6d4..977e039f 100644 --- a/NativeScript/runtime/WrapperLifetime.h +++ b/NativeScript/runtime/WrapperLifetime.h @@ -76,6 +76,9 @@ class WrapperLifetime { // of a JS-extended class. static bool InScope(id obj); + // A tagged pointer or a block: never in scope, whatever the scope. + static bool Excluded(id obj); + // A newly wrapped ObjC object: `handle` is its Instances entry, registered by // ObjectManager::Register and holding the entry's +1 on `target`. // `kind`: the canary handlers the wrapper carries diff --git a/NativeScript/runtime/WrapperLifetime.mm b/NativeScript/runtime/WrapperLifetime.mm index 76b93751..06074c38 100644 --- a/NativeScript/runtime/WrapperLifetime.mm +++ b/NativeScript/runtime/WrapperLifetime.mm @@ -352,6 +352,8 @@ void ReleaseAll(Isolate* isolate, RootedState* rooted) { bool WrapperLifetime::InScope(id obj) { return IsInScope(obj); } +bool WrapperLifetime::Excluded(id obj) { return IsTaggedPointer(obj) || IsBlock(obj); } + void WrapperLifetime::Adopt(Isolate* isolate, ObjCDataWrapper* wrapper, const std::shared_ptr>& handle, id target, CanaryKind kind) { diff --git a/NativeScript/runtime/WrapperLifetimeCanary.h b/NativeScript/runtime/WrapperLifetimeCanary.h index 1499c98d..668c027d 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.h +++ b/NativeScript/runtime/WrapperLifetimeCanary.h @@ -102,10 +102,13 @@ class WrapperLifetimeCanary { static CanaryKind NativeInstancesKind(); // Adds `unwrap` (a canary's native object -> its weak-collection key), - // `wrap` (key -> live or new canary, or undefined once the object is gone) + // `wrap` (key -> live or new wrapper, or undefined once the object is gone) // and `cache` (the Uint32Array that tells the builtin when a wrapper it // cached from wrap is stale) to `binding`, for the weak-collections builtin. - // Canary mode only. + // Canary mode only. Under scope "extended", a plain object (not JS-extended, + // not a tagged pointer or a block) gets a key-only record the first time a + // weak collection keys it: its wrappers are no canaries, so unwrap finds + // that record by the object's address, and wrap builds a plain wrapper. static bool RegisterWrapFunctions(v8::Local context, v8::Local binding); @@ -121,6 +124,15 @@ class WrapperLifetimeCanary { static void KeepWeakCollectionKey(v8::Isolate* isolate, v8::Local canary); + // KeepWeakCollectionKey for a wrapper of `object` that is not a canary, + // before the object is released: with the key-only record of a plain object + // a weak collection keyed, or with none. No-op unless the mode is canary, + // and for objects that can never have a key (a tagged pointer, a block, + // or under scope "all" anything that is not a canary). + static void KeepPlainWeakCollectionKey(v8::Isolate* isolate, + v8::Local wrapper, + id object); + // Takes a collected or released canary's reference to its record. A record // that died under that canary kept its state for it (it is the forwarding // canary's only copy), which can go now. Isolate thread. diff --git a/NativeScript/runtime/WrapperLifetimeCanary.mm b/NativeScript/runtime/WrapperLifetimeCanary.mm index 010db0f4..87365b44 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.mm +++ b/NativeScript/runtime/WrapperLifetimeCanary.mm @@ -67,12 +67,17 @@ // record whose object became a weak-collection key (Wrap reads it). id object = nil; bool weakSet = false; - // __releaseNativeCounterpart released a canary of the object and no canary - // adopted the record since. Isolate thread only. + // __releaseNativeCounterpart released a wrapper of the object, and since + // then no canary adopted the record or, for a plain record, no live wrapper + // of the object reached unwrap or wrap. Isolate thread only. bool released = false; // Its object's canaries forward (WrapperLifetimeCanary::Forwards): the state // is their only copy of the object's properties. bool forwards = false; + // The key-only record of a plain object under scope "extended" (PlainRecord): + // its state holds nothing but the weak collections' key, no wrapper holds + // it, and its weak slot is always set. + bool plain = false; // The object's address: after the record died, only a canary holding the // record keeps the object alive (ForEachState reads it then). void* address = nullptr; @@ -105,11 +110,13 @@ void SetLiveCanary(bool live) { } }; +using RecordMap = std::unordered_map>; + // Per-isolate. Shared with the tokens associated with native objects, which // can be deallocated on any thread and after the isolate is gone. struct CanaryRegistry { std::mutex mutex; - std::unordered_map> records; + RecordMap records; // Records whose token was deallocated; their handles are reset on the // runtime's thread. std::vector> dead; @@ -121,6 +128,9 @@ void SetLiveCanary(bool live) { bool sweepPosted = false; // Lets wrapper creation skip the lookup while no object has state. std::atomic count{0}; + // The plain records among them: lets a weak collection lookup of a plain + // wrapper skip the registry while no plain object was keyed. + std::atomic plainCount{0}; // Outlives the registry while the builtin's array does. std::shared_ptr weakCollectionCache = std::make_shared(); @@ -141,6 +151,21 @@ void SetLiveCanary(bool live) { Global objectOfKey; }; +// Under the registry mutex: marks the record died and moves it from the map to +// `dead`. Every removal from the map goes through here, so the counts stay +// exact. Returns the iterator after it. +RecordMap::iterator RetireRecord(CanaryRegistry* registry, RecordMap::iterator it, + std::vector>& dead) { + it->second->died.store(true, std::memory_order_release); + if (it->second->plain) { + registry->plainCount.fetch_sub(1, std::memory_order_relaxed); + } + // Release: Find reads count first (acquire) and then plainCount. + registry->count.fetch_sub(1, std::memory_order_release); + dead.push_back(std::move(it->second)); + return registry->records.erase(it); +} + // Isolate thread. Lets go of orphaned records no canary holds any more, and // of those whose state a canary took over. Only the list's own reference is // left then, so each handle is reset on this thread. @@ -204,6 +229,7 @@ void NativeDied(const std::shared_ptr& registry, void* object, return; } std::shared_ptr loop; + id liveObject = nil; { std::lock_guard lock(registry->mutex); if (registry->closed) { @@ -213,24 +239,30 @@ void NativeDied(const std::shared_ptr& registry, void* object, if (it == registry->records.end() || (expected != nullptr && it->second.get() != expected)) { return; } - // Erased now, inside the object's -dealloc: an object later allocated at - // this address must not find this record. - it->second->died.store(true, std::memory_order_release); // A record held outside the registry and not dying is a live canary's (its // associations were removed): wrap no longer answers with that canary. // A transient copy elsewhere bumps it spuriously, which only costs a refill. if (!it->second->dying.load(std::memory_order_acquire) && it->second.use_count() > 1) { registry->weakCollectionCache->Invalidate(); + } else if (it->second->plain) { + // No wrapper holds a plain record, so only its object tells: one being + // deallocated loads as nil, a live one had its associations removed, + // and a live wrapper of it is no longer what wrap answers with. + liveObject = objc_loadWeakRetained(&it->second->object); + if (liveObject != nil) { + registry->weakCollectionCache->Invalidate(); + } } - registry->dead.push_back(std::move(it->second)); - registry->records.erase(it); - registry->count.fetch_sub(1, std::memory_order_relaxed); - if (registry->drainPosted) { - return; + // Erased now, inside the object's -dealloc: an object later allocated at + // this address must not find this record. + RetireRecord(registry.get(), it, registry->dead); + if (!registry->drainPosted) { + loop = registry->loop.lock(); + registry->drainPosted = loop != nullptr; } - loop = registry->loop.lock(); - registry->drainPosted = loop != nullptr; } + // Outside the lock: the last release runs the object's -dealloc. + [liveObject release]; // A post dropped at shutdown is fine: teardown resets every handle. if (loop != nullptr && !loop->PostInternal([registry]() { DrainDead(registry); })) { std::lock_guard lock(registry->mutex); @@ -365,10 +397,7 @@ void Sweep(const std::shared_ptr& registry) { ++it; continue; } - it->second->died.store(true, std::memory_order_release); - dead.push_back(std::move(it->second)); - it = registry->records.erase(it); - registry->count.fetch_sub(1, std::memory_order_relaxed); + it = RetireRecord(registry.get(), it, dead); } } ReleaseStates(registry.get(), dead); @@ -434,15 +463,11 @@ bool Usable(const std::shared_ptr& record) { // Under the registry mutex: a record whose object is gone but which no sweep // has reached yet is moved out, so an object now at that address starts over. // True when it was; the caller then owes the registry a drain (PostDrain). -bool RetireIfDead(CanaryRegistry* registry, - std::unordered_map>::iterator it) { +bool RetireIfDead(CanaryRegistry* registry, RecordMap::iterator it) { if (it->second->ObjectAlive() && !it->second->dying.load(std::memory_order_acquire)) { return false; } - it->second->died.store(true, std::memory_order_release); - registry->dead.push_back(std::move(it->second)); - registry->records.erase(it); - registry->count.fetch_sub(1, std::memory_order_relaxed); + RetireRecord(registry, it, registry->dead); return true; } @@ -463,6 +488,20 @@ void PostDrain(const std::shared_ptr& registry) { } } +// After `object`'s first record in `registry` went into the map, for an object +// whose class's own -dealloc does not report it. ForbidsAssociatedObjects must +// have cleared the object. +void AttachToken(const std::shared_ptr& registry, id object) { +#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_ASSOCIATION + TNSCanaryLifecycleToken* token = [[TNSCanaryLifecycleToken alloc] init]; + token->registry_ = registry; + token->object_ = (__bridge void*)object; + objc_setAssociatedObject(object, ®istry->associationKey, token, + OBJC_ASSOCIATION_RETAIN_NONATOMIC); + [token release]; +#endif +} + // The record a receiver lent to JS from -dealloc reads: its object's record, // dying or not. Such a receiver is never adopted, so it has no canary state. std::shared_ptr BorrowedRecord(Isolate* isolate, Local holder) { @@ -639,16 +678,9 @@ bool StateForWrite(Isolate* isolate, Local holder, Local* out) { PostDrain(registry); } if (created) { -#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_ASSOCIATION if (!extended) { - TNSCanaryLifecycleToken* token = [[TNSCanaryLifecycleToken alloc] init]; - token->registry_ = registry; - token->object_ = (__bridge void*)object; - objc_setAssociatedObject(object, ®istry->associationKey, token, - OBJC_ASSOCIATION_RETAIN_NONATOMIC); - [token release]; + AttachToken(registry, object); } -#endif if (ObjectManager::LifetimeStats* stats = ObjectManager::GetLifetimeStats(isolate); stats != nullptr && !takesOver) { stats->canaryStates++; @@ -1018,14 +1050,126 @@ void PostSweepAfterGC(Isolate* isolate, GCType, GCCallbackFlags) { } #endif +// Scope "extended" only: the object of a live wrapper that is no canary and +// holds a reference to its object (not a -dealloc receiver or a collection +// adapter's claim). Nil otherwise. Under "all" every object such a wrapper can +// key by is a canary's. Whether the object can have a plain record is +// PlainRecord's to check. +id PlainObjectOf(Isolate* isolate, Local holder) { + if (GetWrapperLifetimeScope() != WrapperLifetimeScope::kExtended || + (holder->InternalFieldCount() > 1 && holder->GetInternalField(1).As()->IsString())) { + return nil; + } + BaseDataWrapper* wrapper = tns::GetValue(isolate, holder); + if (wrapper == nullptr || wrapper->Type() != WrapperType::ObjCObject) { + return nil; + } + ObjCDataWrapper* objcWrapper = static_cast(wrapper); + ObjectWeakCallbackState* lifetime = objcWrapper->LifetimeState(); + if (objcWrapper->IsBorrowed() || objcWrapper->IsAdapterClaim() || + (lifetime != nullptr && lifetime->lifetimeCanary_)) { + return nil; + } + return objcWrapper->Data(); +} + +// A plain record can be made for `object`: not JS-extended, a tagged pointer +// or a block. +bool CanHavePlainRecord(id object) { + return object != nil && !WrapperLifetime::Excluded(object) && !IsExtendedInstance(object); +} + +// Isolate thread, with `object` retained by a live wrapper. Its plain record: +// the one it has, or with `create` a new one, whose state holds only the key +// UnwrapCallback then adds. Null without one, and when it can get none +// (CanHavePlainRecord, a class forbidding associated objects under +// ASSOCIATION or refusing weak references, a closed registry). Lookups cost +// one atomic load while no plain record exists, and skip the class checks: a +// live plain record at the object's address was made for that object. +std::shared_ptr PlainRecord(Isolate* isolate, + const std::shared_ptr& registry, + id object, bool create) { + void* address = (__bridge void*)object; + if (registry->plainCount.load(std::memory_order_relaxed) > 0) { + std::shared_ptr existing; + bool retired = false; + { + std::lock_guard lock(registry->mutex); + if (registry->closed) { + return nullptr; + } + auto it = registry->records.find(address); + if (it != registry->records.end()) { + retired = RetireIfDead(registry.get(), it); + if (!retired) { + existing = it->second; + } + } + } + if (retired) { + PostDrain(registry); + } + if (existing != nullptr) { + // A canary's record at a plain object's address is a stale one: no key. + return existing->plain ? existing : nullptr; + } + } + if (!create || !CanHavePlainRecord(object)) { + return nullptr; + } +#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_ASSOCIATION + if (ForbidsAssociatedObjects(object)) { + return nullptr; + } +#endif + auto record = std::make_shared(); + record->plain = true; + record->reportsDeath = NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_ASSOCIATION; + record->address = address; + // Wrap reads the object through it. + if (objc_initWeakOrNil(&record->object, object) == nil) { + return nullptr; + } + record->weakSet = true; + // Allocated before the lock: a collection this allocation starts can run + // callbacks that take it. + record->state.Reset(isolate, Object::New(isolate, Null(isolate), nullptr, nullptr, 0)); + { + std::lock_guard lock(registry->mutex); + if (registry->closed) { + return nullptr; + } + std::shared_ptr& slot = registry->records[address]; + if (slot != nullptr) { + return slot->plain ? slot : nullptr; + } + slot = record; + registry->count.fetch_add(1, std::memory_order_relaxed); + registry->plainCount.fetch_add(1, std::memory_order_relaxed); + } + AttachToken(registry, object); + if (ObjectManager::LifetimeStats* stats = ObjectManager::GetLifetimeStats(isolate)) { + stats->canaryStates++; + } + return record; +} + +// Whether `wrapper` is the one wrap answers with for `object` while it lives: +// the object's Instances entry. +bool IsCachedWrapper(Isolate* isolate, id object, Local wrapper) { + std::shared_ptr> cached = + ArgConverter::FindCachedInstance(isolate, Caches::Get(isolate), object); + return cached != nullptr && !cached->IsEmpty() && cached->Get(isolate)->StrictEquals(wrapper); +} + // unwrap(value, create, reportLive): the weak collections' key for a canary's -// native object, a frozen, null-prototype object that lives as long as the -// object's state, that is, until the native object is deallocated, or as long -// as a released canary of the object holding a copy. 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, as in every other mode). With `reportLive`, also sets -// WeakCollectionCache::kLiveCanary. +// native object, or a plain wrapper's (PlainObjectOf), a frozen, +// null-prototype object that lives as long as the object's state, that is, +// until the native object is deallocated, or as long as a released wrapper of +// the object holding a copy. Lookups pass `create` false and never make one: +// with no key yet, no entry can be keyed by it. The value itself for anything +// else, a Proxy included (it is a key of its own, as in every other mode). +// With `reportLive`, also sets WeakCollectionCache::kLiveCanary. void UnwrapCallback(const FunctionCallbackInfo& info) { Isolate* isolate = info.GetIsolate(); Local value = info[0]; @@ -1047,9 +1191,25 @@ void UnwrapCallback(const FunctionCallbackInfo& info) { Local context = isolate->GetCurrentContext(); Local keyOfState = canaryState->keyOfState.Get(isolate); Local key; - if (create ? !StateForWrite(isolate, value.As(), &state) - : !ExistingState(isolate, value.As(), &state)) { - // A released canary keeps its key itself, or null when it had none + bool found = create ? StateForWrite(isolate, value.As(), &state) + : ExistingState(isolate, value.As(), &state); + std::shared_ptr plain; + id plainObject = nil; + if (!found && (create || canaryState->registry->plainCount.load(std::memory_order_relaxed) > 0)) { + plainObject = PlainObjectOf(isolate, value.As()); + if (plainObject != nil) { + plain = PlainRecord(isolate, canaryState->registry, plainObject, create); + found = Usable(plain); + } + if (found) { + // A live wrapper of the object: native code handed it back since any + // release. + plain->released = false; + state = Local::New(isolate, plain->state); + } + } + if (!found) { + // A released wrapper keeps its key itself, or null when it had none // (KeepWeakCollectionKey). if (!value.As()->GetPrivate(context, keyOfState).ToLocal(&key)) { return; @@ -1071,7 +1231,8 @@ void UnwrapCallback(const FunctionCallbackInfo& info) { if (state->GetPrivate(context, keyOfState).ToLocal(&key) && key->IsObject()) { if (reportLive) { canaryState->registry->weakCollectionCache->SetLiveCanary( - CanaryOf(isolate, value.As()) != nullptr); + plain != nullptr ? IsCachedWrapper(isolate, plainObject, value) + : CanaryOf(isolate, value.As()) != nullptr); } info.GetReturnValue().Set(key); return; @@ -1079,20 +1240,25 @@ void UnwrapCallback(const FunctionCallbackInfo& info) { if (!create) { return; } - ObjectWeakCallbackState* canary = CanaryOf(isolate, value.As()); - if (canary == nullptr) { - // A receiver lent to JS from -dealloc: its object is going away. - return; + CanaryRecord* record = plain.get(); + id target = plainObject; + if (record == nullptr) { + ObjectWeakCallbackState* canary = CanaryOf(isolate, value.As()); + if (canary == nullptr) { + // A receiver lent to JS from -dealloc: its object is going away. + return; + } + record = canary->canaryRecord_.get(); + target = canary->lifetimeTarget_; } - CanaryRecord* record = canary->canaryRecord_.get(); if (!record->weakSet) { - if (objc_initWeakOrNil(&record->object, canary->lifetimeTarget_) == nil) { + if (objc_initWeakOrNil(&record->object, target) == nil) { return; } record->weakSet = true; } Local newKey = Object::New(isolate, Null(isolate), nullptr, nullptr, 0); - uint64_t address = reinterpret_cast((__bridge void*)canary->lifetimeTarget_); + uint64_t address = reinterpret_cast((__bridge void*)target); if (!newKey ->SetPrivate(context, canaryState->objectOfKey.Get(isolate), BigInt::NewFromUnsigned(isolate, address)) @@ -1102,13 +1268,15 @@ void UnwrapCallback(const FunctionCallbackInfo& info) { return; } if (reportLive) { - canaryState->registry->weakCollectionCache->SetLiveCanary(true); + canaryState->registry->weakCollectionCache->SetLiveCanary( + plain == nullptr || IsCachedWrapper(isolate, plainObject, value)); } info.GetReturnValue().Set(newKey); } -// The object a key stands for: its live canary or a new one, or undefined once -// the native object is gone. Anything that is not a key passes through. +// The object a key stands for: its live wrapper or a new one (a canary, or for +// a plain record a plain wrapper), or undefined once the native object is +// gone. Anything that is not a key passes through. void WrapCallback(const FunctionCallbackInfo& info) { Isolate* isolate = info.GetIsolate(); Local value = info[0]; @@ -1156,6 +1324,11 @@ void WrapCallback(const FunctionCallbackInfo& info) { std::shared_ptr> cached = ArgConverter::FindCachedInstance(isolate, cache, object); if (cached != nullptr && !cached->IsEmpty()) { + // A plain record learns here, or in unwrap, that native code handed its + // object back: wrapping a plain object never looks the registry up. + if (record->plain) { + record->released = false; + } [object release]; info.GetReturnValue().Set(cached->Get(isolate)); return; @@ -1173,6 +1346,57 @@ void WrapCallback(const FunctionCallbackInfo& info) { info.GetReturnValue().Set(result); } +// KeepWeakCollectionKey's write onto `wrapper`, a wrapper of the object whose +// record `currentRecord` reads. +template +void WriteWeakCollectionKey(Isolate* isolate, CanaryState* canaryState, Local wrapper, + const CurrentRecord& currentRecord) { + HandleScope scope(isolate); + Local context = isolate->GetCurrentContext(); + Local keyOfState = canaryState->keyOfState.Get(isolate); + auto keyOf = [&](const std::shared_ptr& record) { + Local key; + if (Usable(record) && + Local::New(isolate, record->state)->GetPrivate(context, keyOfState).ToLocal(&key) && + key->IsObject()) { + return key; + } + return Local(v8::Null(isolate)); + }; + // The write can allocate, and the finalizers of a collection that starts + // there can run JS that gives the object a record or its record a key: the + // write repeats, a bounded number of times, until it stores the current key. + constexpr int kMaxWrites = 4; + std::shared_ptr record = currentRecord(); + if (record != nullptr && record->forwards && !record->state.IsEmpty()) { + // A name the prototype chain has never reaches a forwarding canary's + // handlers, so a property the canary owns is newer than the state's. + CopyOwnProperties(isolate, context, Local::New(isolate, record->state), wrapper, true); + } + Local copy = keyOf(record); + for (int writes = 1;; writes++) { + // Private symbols bypass the canary's handlers. + (void)wrapper->SetPrivate(context, keyOfState, copy); + std::shared_ptr current = currentRecord(); + if (!Usable(current) || writes == kMaxWrites) { + break; + } + Local currentCopy = keyOf(current); + if (current == record && currentCopy->StrictEquals(copy)) { + break; + } + record = std::move(current); + copy = currentCopy; + } + // Last, with nothing that allocates after it: whichever record the object + // has now is the one the release leaves behind. + if (std::shared_ptr current = currentRecord()) { + current->released = true; + } + // wrap hands out no wrapper of the object now. + canaryState->registry->weakCollectionCache->Invalidate(); +} + } // namespace void WrapperLifetimeCanary::Init(Isolate* isolate) { @@ -1227,54 +1451,25 @@ void WrapCallback(const FunctionCallbackInfo& info) { if (canaryState == nullptr || canaryState->keyOfState.IsEmpty()) { return; } - HandleScope scope(isolate); - Local context = isolate->GetCurrentContext(); - Local keyOfState = canaryState->keyOfState.Get(isolate); - auto currentRecord = [&]() { + WriteWeakCollectionKey(isolate, canaryState, canary, [&]() { ObjectWeakCallbackState* state = CanaryOf(isolate, canary); return state != nullptr ? state->canaryRecord_ : std::shared_ptr(); - }; - auto keyOf = [&](const std::shared_ptr& record) { - Local key; - if (Usable(record) && - Local::New(isolate, record->state)->GetPrivate(context, keyOfState).ToLocal(&key) && - key->IsObject()) { - return key; - } - return Local(v8::Null(isolate)); - }; - // The write can allocate, and the finalizers of a collection that starts - // there can run JS that gives the canary a record or its record a key: the - // write repeats, a bounded number of times, until it stores the current key. - constexpr int kMaxWrites = 4; - std::shared_ptr record = currentRecord(); - if (record != nullptr && record->forwards && !record->state.IsEmpty()) { - // A name the prototype chain has never reaches a forwarding canary's - // handlers, so a property the canary owns is newer than the state's. - CopyOwnProperties(isolate, context, Local::New(isolate, record->state), canary, true); - } - Local copy = keyOf(record); - for (int writes = 1;; writes++) { - // Private symbols bypass the canary's handlers. - (void)canary->SetPrivate(context, keyOfState, copy); - std::shared_ptr current = currentRecord(); - if (!Usable(current) || writes == kMaxWrites) { - break; - } - Local currentCopy = keyOf(current); - if (current == record && currentCopy->StrictEquals(copy)) { - break; - } - record = std::move(current); - copy = currentCopy; + }); +} + +void WrapperLifetimeCanary::KeepPlainWeakCollectionKey(Isolate* isolate, Local wrapper, + id object) { + if (GetWrapperLifetimeMode() != WrapperLifetimeMode::kCanary || + GetWrapperLifetimeScope() != WrapperLifetimeScope::kExtended || !CanHavePlainRecord(object)) { + return; } - // Last, with nothing that allocates after it: whichever record the canary - // holds now is the one the release leaves behind. - if (std::shared_ptr current = currentRecord()) { - current->released = true; + CanaryState* canaryState = Caches::StateFor(isolate); + if (canaryState == nullptr || canaryState->keyOfState.IsEmpty()) { + return; } - // wrap hands out no wrapper of the object now. - canaryState->registry->weakCollectionCache->Invalidate(); + WriteWeakCollectionKey(isolate, canaryState, wrapper, [&]() { + return PlainRecord(isolate, canaryState->registry, object, false); + }); } void WrapperLifetimeCanary::InstallDeallocHook(Class extendedClass) { @@ -1381,7 +1576,15 @@ void WrapCallback(const FunctionCallbackInfo& info) { std::shared_ptr WrapperLifetimeCanary::Find(Isolate* isolate, id object) { CanaryState* state = Caches::StateFor(isolate); - if (state == nullptr || state->registry->count.load(std::memory_order_relaxed) == 0) { + if (state == nullptr) { + return nullptr; + } + // Only canary records count: plain records never cost a canary's wrapping. + // Records are added on this thread only, and RetireRecord drops a plain one + // from plainCount before releasing it from count, so `count` read first + // equals plainCount only when no canary record exists. + size_t records = state->registry->count.load(std::memory_order_acquire); + if (records == 0 || records == state->registry->plainCount.load(std::memory_order_relaxed)) { return nullptr; } { diff --git a/NativeScript/runtime/js/weak-collections.js b/NativeScript/runtime/js/weak-collections.js index be559bc6..5692cf61 100644 --- a/NativeScript/runtime/js/weak-collections.js +++ b/NativeScript/runtime/js/weak-collections.js @@ -2,10 +2,11 @@ // Canary wrapper lifetime mode only (run by WeakRef.cpp): WeakMap, WeakSet, // WeakRef and FinalizationRegistry key a native object by its lifetime key -// instead of its wrapper. The wrapper is a canary that dies with its JS -// references while the native 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. +// instead of its wrapper. The wrapper (a canary, or under scope "extended" a +// plain object's wrapper) dies with its JS references while the native 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 @@ -50,11 +51,12 @@ function canBeHeldWeakly(value) { // no state behind: the receiver is checked first with a method that cannot // insert anything. // -// A canary is stored as a key itself only when its object can have no lifetime -// key (a class forbidding associated objects or refusing weak references, a -// -dealloc receiver, a released wrapper that never had one), and unwrap then -// returns the canary too. So every method first tries the value as is and -// unwraps it only when that misses. +// A native object's wrapper is stored as a key itself only when its object can +// have no lifetime key (a class forbidding associated objects or refusing weak +// references, a tagged pointer, a block, a -dealloc receiver, a released +// wrapper that never had one), and unwrap then returns the wrapper too. So +// every method first tries the value as is and unwraps it only when that +// misses. // Slots of `cache` (WeakCollectionCache in WrapperLifetimeCanary.mm): EPOCH // changes whenever a wrapper wrap answered may no longer be the one it diff --git a/TestRunner/app/tests/WrapperLifetimeLeaksTests.js b/TestRunner/app/tests/WrapperLifetimeLeaksTests.js index e013d5d3..e9b2cadd 100644 --- a/TestRunner/app/tests/WrapperLifetimeLeaksTests.js +++ b/TestRunner/app/tests/WrapperLifetimeLeaksTests.js @@ -140,6 +140,26 @@ describe("Wrapper lifetime leak cycles", function () { expect(held.length).toBe(3); }); + it("counts the key-only state of a plain object a weak collection keyed", function () { + if (!canary || runtime.getConfig("wrapperLifetimeScope") !== "extended") { + return; + } + var obj = NSUUID.UUID(); + // Summed over classes: the probe counts the runtime class, which + // -class hides for a class cluster. + function states() { + var counts = runtime.getWrapperClassCounts(); + return Object.keys(counts).reduce(function (sum, name) { + return sum + counts[name].states; + }, 0); + } + var before = states(); + var map = new WeakMap(); + map.set(obj, "value"); + expect(states()).toBe(before + 1); + expect(map.get(obj)).toBe("value"); + }); + it("rejects a non-object argument", function () { expect(function () { runtime.findLeakCycles(true); diff --git a/TestRunner/app/tests/WrapperLifetimeWeakCollectionsTests.js b/TestRunner/app/tests/WrapperLifetimeWeakCollectionsTests.js index 9a71d2c9..e712bcae 100644 --- a/TestRunner/app/tests/WrapperLifetimeWeakCollectionsTests.js +++ b/TestRunner/app/tests/WrapperLifetimeWeakCollectionsTests.js @@ -5,6 +5,9 @@ describe("Weak collections of native objects", function () { var runtime = require("ns:runtime"); var canary = runtime.getConfig("wrapperLifetimeMode") === "canary"; + // Under "extended" a plain object's wrapper is no canary, and the weak + // collections give the object a key-only state when they first key it. + var plainKeys = canary && runtime.getConfig("wrapperLifetimeScope") === "extended"; // The engine's WeakRef, which keys the wrapper itself. var WrapperWeakRef = canary ? Object.getPrototypeOf(WeakRef) : WeakRef; @@ -16,6 +19,18 @@ describe("Weak collections of native objects", function () { return Extended; })(TNSAllocLog); + // Release semantics hold for both: a JS-extended object is a canary in + // canary mode, and a plain one is a canary under "all" and keyed by a + // key-only state under "extended". + var kinds = [ + { name: "a JS-extended object", make: function () { return Extended.new(); } }, + { name: "a plain object", make: function () { return NSObject.new(); } } + ]; + + function canaryStates() { + return runtime.getWrapperLifetimeStats().canaryStates; + } + function scrub(n) { return n > 0 ? scrub(n - 1) + n : 0; } @@ -271,26 +286,143 @@ describe("Weak collections of native objects", function () { }); }); - it("dereferences no wrapper of a released object a WeakRef returned before the release", function () { - if (!canary) { + // The next collection runs in a later job than `condition`: a WeakRef + // target that condition dereferences is kept alive until its job ends. + function pollUntil(condition, callback) { + var attempts = 15; + (function poll() { + settle(1, function () { + if (condition() || --attempts === 0) { + callback(); + return; + } + setTimeout(poll, 0); + }); + })(); + } + + it("keys a natively owned plain object by its lifetime across a wrapper change", function (done) { + if (!plainKeys) { + done(); return; } var owner = NSMutableArray.new(); - var obj = Extended.new(); - owner.addObject(obj); - var ref = new WeakRef(obj); - expect(ref.deref() === obj).toBe(true); - __releaseNativeCounterpart(obj); - expect(ref.deref() === undefined).toBe(true); - var later = owner.objectAtIndex(0); - expect(ref.deref() === later).toBe(true); + var map = new WeakMap(); + var set = new WeakSet(); + var held = []; + var registry = new FinalizationRegistry(function (value) { + held.push(value); + }); + var ref; + var first; + (function () { + var obj = NSObject.new(); + owner.addObject(obj); + map.set(obj, "value"); + set.add(obj); + ref = new WeakRef(obj); + registry.register(obj, "held"); + first = new WrapperWeakRef(obj); + })(); + pollUntil(function () { + return first.deref() === undefined; + }, function () { + expect(first.deref() === undefined).toBe(true); + var later = owner.objectAtIndex(0); + expect(map.get(later)).toBe("value"); + expect(set.has(later)).toBe(true); + expect(ref.deref() === later).toBe(true); + expect(held.length).toBe(0); + later = null; + settle(2, function () { + expect(held.length).toBe(0); + owner.removeAllObjects(); + pollUntil(function () { + return held.length > 0; + }, function () { + expect(held).toEqual(["held"]); + expect(ref.deref() === undefined).toBe(true); + done(); + }); + }); + }); + }); + + it("lets a keyed plain object JS owned alone go with its wrapper", function (done) { + if (!plainKeys) { + done(); + return; + } + var watch = NSHashTable.weakObjectsHashTable(); + var map = new WeakMap(); + var held = []; + var registry = new FinalizationRegistry(function (value) { + held.push(value); + }); + var ref; + (function () { + var obj = NSObject.new(); + watch.addObject(obj); + map.set(obj, "value"); + ref = new WeakRef(obj); + registry.register(obj, "held"); + })(); + pollUntil(function () { + return watch.allObjects.count === 0 && held.length > 0; + }, function () { + expect(watch.allObjects.count).toBe(0); + expect(held).toEqual(["held"]); + expect(ref.deref() === undefined).toBe(true); + done(); + }); + }); + + it("gives a plain object a key-only state only when a weak collection keys it", function () { + if (!plainKeys) { + return; + } + var map = new WeakMap(); + var set = new WeakSet(); + var registry = new FinalizationRegistry(function () {}); + var obj = NSObject.new(); + var before = canaryStates(); + expect(map.has(obj)).toBe(false); + expect(map.get(obj)).toBeUndefined(); + expect(map.delete(obj)).toBe(false); + expect(set.has(obj)).toBe(false); + expect(set.delete(obj)).toBe(false); + expect(registry.unregister(obj)).toBe(false); + expect(canaryStates()).toBe(before); + map.set(obj, 1); + expect(canaryStates()).toBe(before + 1); + set.add(obj); + new WeakRef(obj); + registry.register({}, "held", obj); + expect(canaryStates()).toBe(before + 1); + expect(registry.unregister(obj)).toBe(true); + }); + + kinds.forEach(function (kind) { + it("dereferences no wrapper of a released object a WeakRef returned before the release (" + kind.name + ")", function () { + if (!canary) { + return; + } + var owner = NSMutableArray.new(); + var obj = kind.make(); + owner.addObject(obj); + var ref = new WeakRef(obj); + expect(ref.deref() === obj).toBe(true); + __releaseNativeCounterpart(obj); + expect(ref.deref() === undefined).toBe(true); + var later = owner.objectAtIndex(0); + expect(ref.deref() === later).toBe(true); + }); }); // Only objects outside JS-extended classes carry the token the removal - // releases, and they are canaries only under scope "all". + // releases: canaries under scope "all", key-only states under "extended". it("keys a live object again after its associations are removed", function (done) { - if (!canary || runtime.getConfig("wrapperLifetimeScope") !== "all" || - typeof objc_removeAssociatedObjects !== "function") { + if (!canary || typeof objc_removeAssociatedObjects !== "function") { done(); return; } @@ -302,7 +434,12 @@ describe("Weak collections of native objects", function () { owner.addObject(obj); before.set(obj, "before"); expect(before.get(obj)).toBe("before"); + var ref = new WeakRef(obj); + expect(ref.deref() === obj).toBe(true); objc_removeAssociatedObjects(obj); + // The WeakRef loses the object exactly when the WeakMap does: the + // token death signal retires the key, the weak sweep keeps it. + expect((ref.deref() === undefined) === (before.get(obj) === undefined)).toBe(true); after.set(obj, "after"); expect(after.get(obj)).toBe("after"); })(); @@ -500,43 +637,89 @@ describe("Weak collections of native objects", function () { })(); } - it("keeps what was keyed on a natively retained object after a wrapper of it is released", function (done) { - if (!canary) { - done(); - return; - } - var owner = NSMutableArray.new(); - var map = new WeakMap(); - var set = new WeakSet(); - var cleaned = false; - var registry = new FinalizationRegistry(function (held) { - cleaned = held === "released"; - }); - var obj = Extended.new(); - owner.addObject(obj); - map.set(obj, "value"); - set.add(obj); - var ref = new WeakRef(obj); - registry.register(obj, "released"); + // A wrapper released before anything keyed its object is a key of its own, + // which nothing keyed on the object can find. + function releasedNeverKeyed(kind) { + var obj = kind.make(); __releaseNativeCounterpart(obj); + return obj; + } + + function releasedAccesses() { + return runtime.getWrapperLifetimeStats().releasedAccesses; + } + + kinds.forEach(function (kind) { + it("keeps what was keyed on a natively retained object after a wrapper of it is released (" + kind.name + ")", function (done) { + if (!canary) { + done(); + return; + } + var owner = NSMutableArray.new(); + var map = new WeakMap(); + var set = new WeakSet(); + var cleaned = false; + var registry = new FinalizationRegistry(function (held) { + cleaned = held === "released"; + }); + var obj = kind.make(); + owner.addObject(obj); + map.set(obj, "value"); + set.add(obj); + var ref = new WeakRef(obj); + registry.register(obj, "released"); + __releaseNativeCounterpart(obj); - expect(map.get(obj)).toBe("value"); - expect(set.has(obj)).toBe(true); - expect(ref.deref() === undefined).toBe(true); - settle(2, function () { expect(map.get(obj)).toBe("value"); expect(set.has(obj)).toBe(true); expect(ref.deref() === undefined).toBe(true); - var later = owner.objectAtIndex(0); - expect(later === obj).toBe(false); - expect(map.get(later)).toBe("value"); - expect(set.has(later)).toBe(true); - expect(ref.deref() === later).toBe(true); - later = null; - obj = null; - settle(3, function () { + settle(2, function () { + expect(map.get(obj)).toBe("value"); + expect(set.has(obj)).toBe(true); + expect(ref.deref() === undefined).toBe(true); + var later = owner.objectAtIndex(0); + expect(later === obj).toBe(false); + expect(map.get(later)).toBe("value"); + expect(set.has(later)).toBe(true); + expect(ref.deref() === later).toBe(true); + later = null; + obj = null; + settle(3, function () { + expect(cleaned).toBe(false); + owner.removeAllObjects(); + pollCleaned(function () { + return cleaned; + }, registry, function () { + expect(cleaned).toBe(true); + done(); + }); + }); + }); + }); + + it("keeps what was keyed on a native object JS owned alone while its released wrapper lives (" + kind.name + ")", function (done) { + if (!canary) { + done(); + return; + } + var map = new WeakMap(); + var cleaned = false; + var registry = new FinalizationRegistry(function (held) { + cleaned = held === "released"; + }); + var obj = kind.make(); + map.set(obj, "value"); + var ref = new WeakRef(obj); + registry.register(obj, "released"); + __releaseNativeCounterpart(obj); + + expect(ref.deref() === undefined).toBe(true); + expect(map.get(obj)).toBe("value"); + settle(2, function () { + expect(map.get(obj)).toBe("value"); + expect(ref.deref() === undefined).toBe(true); expect(cleaned).toBe(false); - owner.removeAllObjects(); + obj = null; pollCleaned(function () { return cleaned; }, registry, function () { @@ -545,213 +728,169 @@ describe("Weak collections of native objects", function () { }); }); }); - }); - it("keeps what was keyed on a native object JS owned alone while its released wrapper lives", function (done) { - if (!canary) { - done(); - return; - } - var map = new WeakMap(); - var cleaned = false; - var registry = new FinalizationRegistry(function (held) { - cleaned = held === "released"; - }); - var obj = Extended.new(); - map.set(obj, "value"); - var ref = new WeakRef(obj); - registry.register(obj, "released"); - __releaseNativeCounterpart(obj); + // __releaseNativeCounterpart frees a heavy native object early: in every + // mode, neither its keys nor its released wrapper may keep it alive. The + // weak table sees the object without retaining it. + it("deallocates a keyed native object JS owned alone at its release (" + kind.name + ")", function () { + var watch = NSHashTable.weakObjectsHashTable(); + var map = new WeakMap(); + var set = new WeakSet(); + var registry = new FinalizationRegistry(function () {}); + var obj = kind.make(); + watch.addObject(obj); + map.set(obj, "value"); + set.add(obj); + var ref = new WeakRef(obj); + registry.register(obj, "held"); + __releaseNativeCounterpart(obj); - expect(ref.deref() === undefined).toBe(true); - expect(map.get(obj)).toBe("value"); - settle(2, function () { + expect(watch.allObjects.count).toBe(0); expect(map.get(obj)).toBe("value"); - expect(ref.deref() === undefined).toBe(true); - expect(cleaned).toBe(false); - obj = null; - pollCleaned(function () { - return cleaned; - }, registry, function () { - expect(cleaned).toBe(true); - done(); - }); + expect(set.has(obj)).toBe(true); + expect(ref.deref() === (canary ? undefined : obj)).toBe(true); }); - }); - // __releaseNativeCounterpart frees a heavy native object early: in every - // mode, neither its keys nor its released wrapper may keep it alive. The - // weak table sees the object without retaining it. - it("deallocates a keyed native object JS owned alone at its release", function () { - var watch = NSHashTable.weakObjectsHashTable(); - var map = new WeakMap(); - var set = new WeakSet(); - var registry = new FinalizationRegistry(function () {}); - var obj = Extended.new(); - watch.addObject(obj); - map.set(obj, "value"); - set.add(obj); - var ref = new WeakRef(obj); - registry.register(obj, "held"); - __releaseNativeCounterpart(obj); - - expect(watch.allObjects.count).toBe(0); - expect(map.get(obj)).toBe("value"); - expect(set.has(obj)).toBe(true); - expect(ref.deref() === (canary ? undefined : obj)).toBe(true); - }); - - it("deallocates a released natively retained object once native code lets go, while its wrapper is held and dereferenced", function (done) { - var watch = NSHashTable.weakObjectsHashTable(); - var owner = NSMutableArray.new(); - var map = new WeakMap(); - var set = new WeakSet(); - var obj = Extended.new(); - owner.addObject(obj); - watch.addObject(obj); - map.set(obj, "value"); - set.add(obj); - var ref = new WeakRef(obj); - __releaseNativeCounterpart(obj); - var expected = canary ? undefined : obj; - - // Whether every dereference gave the mode's expected target. - function poke() { - var matched = true; - for (var i = 0; i < 10; i++) { - matched = ref.deref() === expected && matched; - map.get(obj); - set.has(obj); + it("deallocates a released natively retained object once native code lets go, while its wrapper is held and dereferenced (" + kind.name + ")", function (done) { + var watch = NSHashTable.weakObjectsHashTable(); + var owner = NSMutableArray.new(); + var map = new WeakMap(); + var set = new WeakSet(); + var obj = kind.make(); + owner.addObject(obj); + watch.addObject(obj); + map.set(obj, "value"); + set.add(obj); + var ref = new WeakRef(obj); + __releaseNativeCounterpart(obj); + var expected = canary ? undefined : obj; + + // Whether every dereference gave the mode's expected target. + function poke() { + var matched = true; + for (var i = 0; i < 10; i++) { + matched = ref.deref() === expected && matched; + map.get(obj); + set.has(obj); + } + return matched; } - return matched; - } - expect(poke()).toBe(true); - settle(2, function () { - expect(poke()).toBe(true); - owner.removeAllObjects(); expect(poke()).toBe(true); - expect(watch.allObjects.count).toBe(0); - expect(ref.deref() === expected).toBe(true); - expect(map.get(obj)).toBe("value"); - expect(set.has(obj)).toBe(true); - done(); + settle(2, function () { + expect(poke()).toBe(true); + owner.removeAllObjects(); + expect(poke()).toBe(true); + expect(watch.allObjects.count).toBe(0); + expect(ref.deref() === expected).toBe(true); + expect(map.get(obj)).toBe("value"); + expect(set.has(obj)).toBe(true); + done(); + }); }); - }); - - // A canary released before anything keyed its object is a key of its own, - // which nothing keyed on the object can find. - function releasedNeverKeyed() { - var obj = Extended.new(); - __releaseNativeCounterpart(obj); - return obj; - } - function releasedAccesses() { - return runtime.getWrapperLifetimeStats().releasedAccesses; - } + it("reports a weak collection operation on a wrapper released before anything keyed its object (" + kind.name + ")", function (done) { + if (!canary) { + done(); + return; + } + var messages = []; + var onReleased = function (e) { + if (/weak collection/.test(e.error.message)) { + messages.push(e.error.message); + } + }; + global.addEventListener("releasednativeaccess", onReleased); + try { + var map = new WeakMap(); + var before = releasedAccesses(); + var kept = releasedNeverKeyed(kind); + map.set(kept, 1); + expect(releasedAccesses()).toBe(before + 1); + expect(map.get(kept) === 1).toBe(true); + expect(releasedAccesses()).toBe(before + 1); + new WeakRef(releasedNeverKeyed(kind)); + expect(releasedAccesses()).toBe(before + 2); + expect(map.get(releasedNeverKeyed(kind))).toBeUndefined(); + expect(releasedAccesses()).toBe(before + 3); + } catch (e) { + global.removeEventListener("releasednativeaccess", onReleased); + throw e; + } + setTimeout(function () { + global.removeEventListener("releasednativeaccess", onReleased); + expect(messages.length).toBe(3); + for (var i = 0; i < messages.length; i++) { + expect(messages[i]).toMatch(/released by __releaseNativeCounterpart \(weak collection key/); + } + done(); + }); + }); - it("reports a weak collection operation on a canary released before anything keyed its object", function (done) { - if (!canary) { - done(); - return; - } - var messages = []; - var onReleased = function (e) { - if (/weak collection/.test(e.error.message)) { - messages.push(e.error.message); + it("throws for a weak collection operation on a wrapper released before anything keyed its object under the throw policy (" + kind.name + ")", function () { + if (!canary) { + return; } - }; - global.addEventListener("releasednativeaccess", onReleased); - try { - var map = new WeakMap(); - var before = releasedAccesses(); - var kept = releasedNeverKeyed(); - map.set(kept, 1); - expect(releasedAccesses()).toBe(before + 1); - expect(map.get(kept) === 1).toBe(true); - expect(releasedAccesses()).toBe(before + 1); - new WeakRef(releasedNeverKeyed()); - expect(releasedAccesses()).toBe(before + 2); - expect(map.get(releasedNeverKeyed())).toBeUndefined(); - expect(releasedAccesses()).toBe(before + 3); - } catch (e) { - global.removeEventListener("releasednativeaccess", onReleased); - throw e; - } - setTimeout(function () { - global.removeEventListener("releasednativeaccess", onReleased); - expect(messages.length).toBe(3); - for (var i = 0; i < messages.length; i++) { - expect(messages[i]).toMatch(/released by __releaseNativeCounterpart \(weak collection key/); + var policy = runtime.getConfig("releasedObjectPolicy"); + runtime.setConfig("releasedObjectPolicy", "throw"); + try { + var map = new WeakMap(); + expect(function () { + map.set(releasedNeverKeyed(kind), 1); + }).toThrowError(ReferenceError, /weak collection key/); + expect(function () { + new WeakRef(releasedNeverKeyed(kind)); + }).toThrowError(ReferenceError, /weak collection key/); + expect(function () { + map.get(releasedNeverKeyed(kind)); + }).toThrowError(ReferenceError, /weak collection key/); + } finally { + runtime.setConfig("releasedObjectPolicy", policy); } - done(); }); - }); - it("throws for a weak collection operation on a canary released before anything keyed its object under the throw policy", function () { - if (!canary) { - return; - } - var policy = runtime.getConfig("releasedObjectPolicy"); - runtime.setConfig("releasedObjectPolicy", "throw"); - try { + it("gets an undefined value stored on a wrapper released before anything keyed its object (" + kind.name + ")", function (done) { + if (!canary) { + done(); + return; + } var map = new WeakMap(); - expect(function () { - map.set(releasedNeverKeyed(), 1); - }).toThrowError(ReferenceError, /weak collection key/); - expect(function () { - new WeakRef(releasedNeverKeyed()); - }).toThrowError(ReferenceError, /weak collection key/); - expect(function () { - map.get(releasedNeverKeyed()); - }).toThrowError(ReferenceError, /weak collection key/); - } finally { - runtime.setConfig("releasedObjectPolicy", policy); - } - }); - - it("gets an undefined value stored on a canary released before anything keyed its object", function (done) { - if (!canary) { - done(); - return; - } - var map = new WeakMap(); - var obj = releasedNeverKeyed(); - map.set(obj, undefined); - var policy = runtime.getConfig("releasedObjectPolicy"); - runtime.setConfig("releasedObjectPolicy", "throw"); - try { - var before = releasedAccesses(); - expect(map.get(obj) === undefined).toBe(true); - expect(map.has(obj)).toBe(true); - expect(releasedAccesses()).toBe(before); - } finally { - runtime.setConfig("releasedObjectPolicy", policy); - } - // Lets the report of the set() above be delivered within this spec. - setTimeout(done); - }); + var obj = releasedNeverKeyed(kind); + map.set(obj, undefined); + var policy = runtime.getConfig("releasedObjectPolicy"); + runtime.setConfig("releasedObjectPolicy", "throw"); + try { + var before = releasedAccesses(); + expect(map.get(obj) === undefined).toBe(true); + expect(map.has(obj)).toBe(true); + expect(releasedAccesses()).toBe(before); + } finally { + runtime.setConfig("releasedObjectPolicy", policy); + } + // Lets the report of the set() above be delivered within this spec. + setTimeout(done); + }); - it("does not report a weak collection operation on a released wrapper whose object was keyed", function () { - var policy = runtime.getConfig("releasedObjectPolicy"); - runtime.setConfig("releasedObjectPolicy", "throw"); - try { - var obj = Extended.new(); - var map = new WeakMap(); - map.set(obj, 1); - __releaseNativeCounterpart(obj); - var before = releasedAccesses(); - var other = new WeakMap(); - expect(map.get(obj)).toBe(1); - expect(other.get(obj)).toBeUndefined(); - other.set(obj, 2); - expect(other.get(obj)).toBe(2); - new WeakRef(obj); - new WeakSet().add(obj); - expect(releasedAccesses()).toBe(before); - } finally { - runtime.setConfig("releasedObjectPolicy", policy); - } + it("does not report a weak collection operation on a released wrapper whose object was keyed (" + kind.name + ")", function () { + var policy = runtime.getConfig("releasedObjectPolicy"); + runtime.setConfig("releasedObjectPolicy", "throw"); + try { + var obj = kind.make(); + var map = new WeakMap(); + map.set(obj, 1); + __releaseNativeCounterpart(obj); + var before = releasedAccesses(); + var other = new WeakMap(); + expect(map.get(obj)).toBe(1); + expect(other.get(obj)).toBeUndefined(); + other.set(obj, 2); + expect(other.get(obj)).toBe(2); + new WeakRef(obj); + new WeakSet().add(obj); + expect(releasedAccesses()).toBe(before); + } finally { + runtime.setConfig("releasedObjectPolicy", policy); + } + }); }); it("makes no key for a call the standard collection rejects", function () { diff --git a/docs/knowledge/v8-resurrecting-finalizers.md b/docs/knowledge/v8-resurrecting-finalizers.md index 54cc3840..63af30b8 100644 --- a/docs/knowledge/v8-resurrecting-finalizers.md +++ b/docs/knowledge/v8-resurrecting-finalizers.md @@ -352,7 +352,8 @@ documents it as not for general use. The alternative keeps an ObjC weak referenc references) and sweeps the records after every major collection, so state lingers until then. An instance of a class that refuses weak references and is not JS-extended gets no state under it, in the same way. With the default, `"scope": "all"` stays experimental because that -check reads private runtime layout; `"extended"` attaches no tokens at all. It cannot be +check reads private runtime layout; `"extended"` attaches tokens only to the plain objects a weak +collection keys (below), so the check runs there once per such object. It cannot be rooted at canary death instead, because a state reachable only through the canary is garbage in the same collection. The cost: state that references its own object (a closure over `this`) keeps it alive. A canary built after a death is a new object, but `===` cannot tell: only one @@ -372,12 +373,35 @@ lives while the state or the released canary does. A record whose token `objc_removeAssociatedObjects` already retired gets neither: the released canary then keys nothing, as that limitation describes. What could notice is whatever keys on the canary without keeping it. The weak collections don't: in canary mode a builtin (`js/weak-collections.js`) replaces `WeakMap`, `WeakSet`, -`WeakRef` and `FinalizationRegistry` with subclasses that key an in-scope native object (a -canary: not a plain object under `"extended"`, a tagged pointer, a block, or an object of a class +`WeakRef` and `FinalizationRegistry` with subclasses that key a native object (a canary's, or +under `"extended"` a plain object's; not a tagged pointer, a block, or an object of a class refusing weak references or forbidding associated objects) by an opaque, frozen key held by its state, so entries and targets live -exactly as long as the native object, and `WeakRef.prototype.deref` returns the live canary, a new +exactly as long as the native object, and `WeakRef.prototype.deref` returns the live wrapper, a new one, or `undefined` once the object is gone. Lookups never create that key, and a Proxy around a -native object stays a key of its own. The cost is the other side of the same rooting: a `WeakMap` +native object stays a key of its own. Under `"extended"` a plain object's wrapper is a phantom +handle with no handlers and no state, which dies with its JS references just as a canary does, so +the first keying of a plain object (`unwrap` with `create`) gives it a key-only record: the +lifecycle token, a weak slot, and a state holding nothing but the key, counted in `canaryStates` +and in the registry's `records`, so the leak probe walks it like any other state. The record is +flagged `plain` and no wrapper holds it: wrapping a plain object never consults the registry, and +`unwrap` finds the record by the object's address only after the canary lookups miss, behind an +atomic count of plain records, so a weak-collection lookup costs nothing more while no plain +object was ever keyed. `wrap` returns the object's `Instances` wrapper or builds a plain one (no +adoption, no hydration). Release semantics are the canary ones: `__releaseNativeCounterpart` on a +plain wrapper copies the key, or `null`, onto it (`KeepPlainWeakCollectionKey`) and marks the +record released; since no adoption looks the record up, `unwrap` or `wrap` meeting a live wrapper +of the object clears the mark instead. A native hand-back whose wrapper dies before any weak +collection operation sees it leaves the record released, so `deref` returns `undefined` until the +next hand-back reaches one. The token's `-dealloc` retires the record (`NativeDied`); it bumps the +`deref` cache epoch only when a weak load finds the object alive, i.e. when +`objc_removeAssociatedObjects` removed the token, which loses what was keyed on a plain object as +it does for a canary, where a wrapper key used to be immune. A plain key costs what a canary key +does otherwise: a `WeakMap` value referencing its key keeps the object alive. Measured on a +Release simulator build (median of launches, ns/op): a `WeakMap` hit on a keyed plain object +145 instead of 40 (the wrapper was the key), a miss on a never-keyed plain wrapper 126 instead +of 107 once any plain object was keyed and unchanged (108) before, the first keying 966 instead +of 165, and a `deref` that rebuilds a dead plain wrapper about 1150; creating plain wrappers, +native calls, native property reads and stores and `Instances` lookups are unchanged. The cost is the other side of the same rooting: a `WeakMap` value that references its native key keeps the key, its state and so the native object alive for as long as the map lives, where in the other modes the entry would be collectable. Native `#private` fields are branded on the canary and do not carry over. Other limits: `Object.freeze`, `seal` and `preventExtensions` throw on a canary (V8 refuses them on diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index a198fe64..8c1af609 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -169,7 +169,7 @@ on every write to a canary: | `promotions` | `"rooted"` only: weak wrappers made strong because native code retained their object | | `demotions` | `"rooted"` only: strong wrappers made weak at a major collection because native code no longer retained their object | | `queuedReleases` | `"rooted"` and `"canary"`: collected wrappers whose native object was queued for release on the runtime's thread | -| `canaryStates` | `"canary"` only: state objects created to hold native objects' JS properties, or only to hold the key a weak collection made for the object (see [Weak collections in canary mode](#weak-collections-in-canary-mode)) | +| `canaryStates` | `"canary"` only: state objects created to hold native objects' JS properties, or only to hold the key a weak collection made for the object, a plain object's included under scope `"extended"` (see [Weak collections in canary mode](#weak-collections-in-canary-mode)) | | `canaryNativeDeaths` | `"canary"` only: state objects let go of because their native object was deallocated or, with the default death signal, because `objc_removeAssociatedObjects` released its lifecycle token while the object was still alive | | `canaryInterceptedWrites` | `"canary"` only: writes to canaries the runtime's write handler saw. Other wrappers have no handler | @@ -245,6 +245,23 @@ in the standard collections. What follows from that: - A key lives in the object's state, so the first `set`, `add`, `new WeakRef` or `register` of an object without JS properties creates a state, counted in `canaryStates` and `getWrapperClassCounts()`'s `states`. Lookups never do. +- Under scope `"extended"` a plain (not JS-extended) object's wrapper is not a + canary, but it also dies with its JS references while the object lives on. + So the first `set`, `add`, `new WeakRef` or `register` of a plain object + gives the object a state holding only its key, with the same lifecycle + token a plain canary gets under `"all"`, and from then on it is keyed by + its lifetime exactly as a canary is, release included. Objects of a class + that forbids associated objects or refuses weak references, tagged pointers + and blocks stay keyed by their wrapper. Wrapping plain objects, calling + them and their properties cost nothing more. Each weak collection operation + on a keyed plain object asks native code for its key (about 145 ns + for a `WeakMap.prototype.get` hit instead of 40, Release + simulator build), the first keying of an object costs about 800 ns + more, and once any plain object was keyed a miss on one never keyed costs + about 126 ns instead of 107. As with canaries, a + `WeakMap` value that references its plain key keeps the object alive while + the map lives, and `objc_removeAssociatedObjects` on the object loses what + was keyed on it. - What was keyed on a native object follows the object, not a released wrapper of it. After `__releaseNativeCounterpart(w)`, `w` still finds the object's entries while JS holds it, and a wrapper native code hands back diff --git a/types/ns-runtime.d.ts b/types/ns-runtime.d.ts index 854bff04..6e580039 100644 --- a/types/ns-runtime.d.ts +++ b/types/ns-runtime.d.ts @@ -71,9 +71,11 @@ declare module "ns:runtime" { * on that wrapper and is gone with it. `wrapperLifetimeAllowShadowingNativeMembers` * makes plain objects' wrappers keep such properties too. * WeakMap, WeakSet, WeakRef and FinalizationRegistry key such native - * objects by their lifetime in this mode, so they carry over too; a - * WeakMap value that references its own native key keeps that object - * alive while the map lives. Native `#private` fields and index-keyed + * objects by their lifetime in this mode, so they carry over too, and + * under scope `"extended"` also key plain objects by their lifetime once + * they first key one (a state holding only the key, with the same + * token); a WeakMap value that references its own native key keeps that + * object alive while the map lives. Native `#private` fields and index-keyed * properties do not. * State that references its own object keeps that object alive. */ @@ -129,7 +131,7 @@ declare module "ns:runtime" { demotions: number; /** `"rooted"` and `"canary"`: collected wrappers whose native object was queued for release. */ queuedReleases: number; - /** `"canary"` only: state objects created for native objects' JS properties. */ + /** `"canary"` only: state objects created for native objects' JS properties, or only for the key a weak collection made for one. */ canaryStates: number; /** `"canary"` only: state objects let go of because their native object was deallocated, or because `objc_removeAssociatedObjects` released its lifecycle token. */ canaryNativeDeaths: number; From 68d0533f4b3a9586dd787283a57e1c4fbd2e56f5 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 15:45:20 -0300 Subject: [PATCH 4/8] feat(runtime): plain objects' weak-collection keys die by weak sweep, without a token Under canary/extended the key-only record a weak collection makes for a plain object carried the association token canaries use. That attached an object to every keyed plain object, read private class layout to check for classes that forbid associated objects, and let objc_removeAssociatedObjects drop what was keyed on the object. Plain records now attach nothing. Their weak slot, always set, is the only death signal: a major-GC epilogue posts a sweep over the registry's list of plain records (not the whole map) that retires those whose object is gone, and does nothing past an atomic load while there is no plain record. A lookup that meets a zeroed slot still retires the record at once. Canary records keep the death signal NS_CANARY_DEATH_SIGNAL chooses, and both run side by side. The sweep bumps no deref cache epoch: a live wrapper retains its object, so no cached wrapper outlives a swept one. A plain object of a class that forbids associated objects is now keyed by its lifetime, objc_removeAssociatedObjects leaves a plain record alone, and entries keyed on a deallocated plain object stay until the next major collection. Release simulator build, canary/extended, ns/op (medians of 3 launches; before = 56b4005a, token = the previous commit): before token sweep first keying: map.set(fresh plain object) 154 932 870 first keying: new WeakRef(fresh plain object) 216 1471 1568 ref.deref() rebuilding a dead plain wrapper 54* 1109 1120 major GC + next timer, no plain record 276 us 306 us 291 us major GC + next timer, 1000 held unkeyed 289 us 385 us 366 us major GC + next timer, 1000 held keyed 334 us 538 us 501 us * before: the dead wrapper was the key, so the deref found nothing. --- NativeScript/runtime/WrapperLifetimeCanary.h | 2 + NativeScript/runtime/WrapperLifetimeCanary.mm | 101 +++++++++++++----- .../WrapperLifetimeWeakCollectionsTests.js | 42 ++++++-- docs/knowledge/v8-resurrecting-finalizers.md | 62 ++++++----- docs/ns-builtin-modules.md | 35 +++--- types/ns-runtime.d.ts | 7 +- 6 files changed, 177 insertions(+), 72 deletions(-) diff --git a/NativeScript/runtime/WrapperLifetimeCanary.h b/NativeScript/runtime/WrapperLifetimeCanary.h index 668c027d..7935e9ed 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.h +++ b/NativeScript/runtime/WrapperLifetimeCanary.h @@ -109,6 +109,8 @@ class WrapperLifetimeCanary { // not a tagged pointer or a block) gets a key-only record the first time a // weak collection keys it: its wrappers are no canaries, so unwrap finds // that record by the object's address, and wrap builds a plain wrapper. + // Nothing is attached to the object: a weak reference tells when it is + // gone, read by a sweep after each major collection. static bool RegisterWrapFunctions(v8::Local context, v8::Local binding); diff --git a/NativeScript/runtime/WrapperLifetimeCanary.mm b/NativeScript/runtime/WrapperLifetimeCanary.mm index 87365b44..77ae7a75 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.mm +++ b/NativeScript/runtime/WrapperLifetimeCanary.mm @@ -31,7 +31,9 @@ // sweep after every major collection, so state lingers until then. // An object the chosen signal cannot watch (a class forbidding associated // objects, or refusing weak references) gets no state: its JS properties stay -// on the canary and the weak collections key its wrapper. +// on the canary and the weak collections key its wrapper. The key-only records +// of plain objects under scope "extended" always use the weak reference +// (SweepPlain), whatever this chooses for canaries. #define NS_CANARY_DEATH_ASSOCIATION 1 #define NS_CANARY_DEATH_WEAK_SWEEP 2 #ifndef NS_CANARY_DEATH_SIGNAL @@ -76,7 +78,8 @@ bool forwards = false; // The key-only record of a plain object under scope "extended" (PlainRecord): // its state holds nothing but the weak collections' key, no wrapper holds - // it, and its weak slot is always set. + // it, nothing reports its object's death, and its weak slot is always set + // (SweepPlain reads it). bool plain = false; // The object's address: after the record died, only a canary holding the // record keeps the object alive (ForEachState reads it then). @@ -126,11 +129,16 @@ void SetLiveCanary(bool live) { bool closed = false; bool drainPosted = false; bool sweepPosted = false; + bool plainSweepPosted = false; // Lets wrapper creation skip the lookup while no object has state. std::atomic count{0}; // The plain records among them: lets a weak collection lookup of a plain - // wrapper skip the registry while no plain object was keyed. + // wrapper, and the sweep after a major collection, skip the registry while + // no plain object was keyed. std::atomic plainCount{0}; + // Every plain record in `records`, and retired ones until the next + // SweepPlain drops them: what that sweep walks instead of the whole map. + std::vector> plainRecords; // Outlives the registry while the builtin's array does. std::shared_ptr weakCollectionCache = std::make_shared(); @@ -229,7 +237,6 @@ void NativeDied(const std::shared_ptr& registry, void* object, return; } std::shared_ptr loop; - id liveObject = nil; { std::lock_guard lock(registry->mutex); if (registry->closed) { @@ -244,14 +251,6 @@ void NativeDied(const std::shared_ptr& registry, void* object, // A transient copy elsewhere bumps it spuriously, which only costs a refill. if (!it->second->dying.load(std::memory_order_acquire) && it->second.use_count() > 1) { registry->weakCollectionCache->Invalidate(); - } else if (it->second->plain) { - // No wrapper holds a plain record, so only its object tells: one being - // deallocated loads as nil, a live one had its associations removed, - // and a live wrapper of it is no longer what wrap answers with. - liveObject = objc_loadWeakRetained(&it->second->object); - if (liveObject != nil) { - registry->weakCollectionCache->Invalidate(); - } } // Erased now, inside the object's -dealloc: an object later allocated at // this address must not find this record. @@ -261,8 +260,6 @@ void NativeDied(const std::shared_ptr& registry, void* object, registry->drainPosted = loop != nullptr; } } - // Outside the lock: the last release runs the object's -dealloc. - [liveObject release]; // A post dropped at shutdown is fine: teardown resets every handle. if (loop != nullptr && !loop->PostInternal([registry]() { DrainDead(registry); })) { std::lock_guard lock(registry->mutex); @@ -1082,8 +1079,9 @@ bool CanHavePlainRecord(id object) { // Isolate thread, with `object` retained by a live wrapper. Its plain record: // the one it has, or with `create` a new one, whose state holds only the key // UnwrapCallback then adds. Null without one, and when it can get none -// (CanHavePlainRecord, a class forbidding associated objects under -// ASSOCIATION or refusing weak references, a closed registry). Lookups cost +// (CanHavePlainRecord, a class refusing weak references, a closed registry). +// Nothing is attached to the object: SweepPlain finds it gone after a major +// collection, and lookups find it gone at once (RetireIfDead). Lookups cost // one atomic load while no plain record exists, and skip the class checks: a // live plain record at the object's address was made for that object. std::shared_ptr PlainRecord(Isolate* isolate, @@ -1117,16 +1115,10 @@ bool CanHavePlainRecord(id object) { if (!create || !CanHavePlainRecord(object)) { return nullptr; } -#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_ASSOCIATION - if (ForbidsAssociatedObjects(object)) { - return nullptr; - } -#endif auto record = std::make_shared(); record->plain = true; - record->reportsDeath = NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_ASSOCIATION; record->address = address; - // Wrap reads the object through it. + // The only death signal: SweepPlain, and wrap, read the object through it. if (objc_initWeakOrNil(&record->object, object) == nil) { return nullptr; } @@ -1144,10 +1136,10 @@ bool CanHavePlainRecord(id object) { return slot->plain ? slot : nullptr; } slot = record; + registry->plainRecords.push_back(record); registry->count.fetch_add(1, std::memory_order_relaxed); registry->plainCount.fetch_add(1, std::memory_order_relaxed); } - AttachToken(registry, object); if (ObjectManager::LifetimeStats* stats = ObjectManager::GetLifetimeStats(isolate)) { stats->canaryStates++; } @@ -1162,6 +1154,63 @@ bool IsCachedWrapper(Isolate* isolate, id object, Local wrapper) { return cached != nullptr && !cached->IsEmpty() && cached->Get(isolate)->StrictEquals(wrapper); } +// Isolate thread, as an event loop task. Retires the plain records whose +// object is gone, and drops retired ones from plainRecords. No deref cache +// epoch bump: a live wrapper retains its object, so no wrapper wrap answered +// with outlives a plain record's object. +void SweepPlain(const std::shared_ptr& registry) { + std::vector> dead; + { + std::lock_guard lock(registry->mutex); + registry->plainSweepPosted = false; + if (registry->closed) { + return; + } + std::vector>& plain = registry->plainRecords; + for (size_t i = 0; i < plain.size();) { + CanaryRecord* record = plain[i].get(); + bool gone = record->died.load(std::memory_order_acquire); + if (!gone && !record->ObjectAlive()) { + auto it = registry->records.find(record->address); + if (it != registry->records.end() && it->second.get() == record) { + RetireRecord(registry.get(), it, dead); + } + gone = true; + } + if (gone) { + plain[i] = std::move(plain.back()); + plain.pop_back(); + } else { + i++; + } + } + } + ReleaseStates(registry.get(), dead); +} + +// Scope "extended": posts SweepPlain when a major collection ends, behind the +// release drain the collection queued, so objects it released are gone by +// then. Only an atomic load while no plain record exists. +void PostPlainSweepAfterGC(Isolate* isolate, GCType, GCCallbackFlags) { + CanaryState* state = Caches::ExistingStateFor(isolate); + if (state == nullptr || state->registry->plainCount.load(std::memory_order_relaxed) == 0) { + return; + } + std::shared_ptr registry = state->registry; + std::shared_ptr loop = registry->loop.lock(); + { + std::lock_guard lock(registry->mutex); + if (registry->plainSweepPosted || loop == nullptr) { + return; + } + registry->plainSweepPosted = true; + } + if (!loop->PostInternal([registry]() { SweepPlain(registry); })) { + std::lock_guard lock(registry->mutex); + registry->plainSweepPosted = false; + } +} + // unwrap(value, create, reportLive): the weak collections' key for a canary's // native object, or a plain wrapper's (PlainObjectOf), a frozen, // null-prototype object that lives as long as the object's state, that is, @@ -1420,6 +1469,9 @@ void WriteWeakCollectionKey(Isolate* isolate, CanaryState* canaryState, LocalAddGCEpilogueCallback(PostSweepAfterGC, kGCTypeMarkSweepCompact); #endif + if (GetWrapperLifetimeScope() == WrapperLifetimeScope::kExtended) { + isolate->AddGCEpilogueCallback(PostPlainSweepAfterGC, kGCTypeMarkSweepCompact); + } } bool WrapperLifetimeCanary::RegisterWrapFunctions(Local context, Local binding) { @@ -1619,6 +1671,7 @@ void WriteWeakCollectionKey(Isolate* isolate, CanaryState* canaryState, Local& record : state->registry->orphaned) { record->state.Reset(); } + state->registry->plainRecords.clear(); } void WrapperLifetimeCanary::ForEachState( diff --git a/TestRunner/app/tests/WrapperLifetimeWeakCollectionsTests.js b/TestRunner/app/tests/WrapperLifetimeWeakCollectionsTests.js index e712bcae..2231ccbf 100644 --- a/TestRunner/app/tests/WrapperLifetimeWeakCollectionsTests.js +++ b/TestRunner/app/tests/WrapperLifetimeWeakCollectionsTests.js @@ -419,8 +419,9 @@ describe("Weak collections of native objects", function () { }); }); - // Only objects outside JS-extended classes carry the token the removal - // releases: canaries under scope "all", key-only states under "extended". + // Only canaries of objects outside JS-extended classes (scope "all") carry + // the token the removal releases; a key-only state under "extended" has + // none and survives it. it("keys a live object again after its associations are removed", function (done) { if (!canary || typeof objc_removeAssociatedObjects !== "function") { done(); @@ -437,6 +438,10 @@ describe("Weak collections of native objects", function () { var ref = new WeakRef(obj); expect(ref.deref() === obj).toBe(true); objc_removeAssociatedObjects(obj); + if (plainKeys) { + expect(before.get(obj)).toBe("before"); + expect(ref.deref() === obj).toBe(true); + } // The WeakRef loses the object exactly when the WeakMap does: the // token death signal retires the key, the weak sweep keeps it. expect((ref.deref() === undefined) === (before.get(obj) === undefined)).toBe(true); @@ -537,9 +542,10 @@ describe("Weak collections of native objects", function () { }); }); - // Under canary mode such an object gets no state: the token that would - // report its deallocation cannot be associated with it. - it("keys an object whose class forbids associated objects by its wrapper", function () { + // A canary of such an object gets no state: the token that would report + // its deallocation cannot be associated with it. A plain object's key-only + // state under "extended" needs no token, so the weak collections key it. + it("keys an object whose class forbids associated objects", function () { var obj = TNSAssociationForbidder.forbiddingInstance(); expect(TNSAssociationForbidder.forbidsAssociatedObjects(obj)).toBe(true); var before = runtime.getWrapperLifetimeStats(); @@ -558,8 +564,32 @@ describe("Weak collections of native objects", function () { expect(obj.tag).toBe("kept"); expect(obj.defined).toBe(1); if (canary) { - expect(runtime.getWrapperLifetimeStats().canaryStates).toBe(before.canaryStates); + expect(runtime.getWrapperLifetimeStats().canaryStates) + .toBe(before.canaryStates + (plainKeys ? 1 : 0)); + } + }); + + it("keeps what was keyed on a plain object whose class forbids associated objects across a wrapper change", function (done) { + if (!plainKeys) { + done(); + return; } + var owner = NSMutableArray.new(); + var map = new WeakMap(); + var first; + (function () { + var obj = TNSAssociationForbidder.forbiddingInstance(); + owner.addObject(obj); + map.set(obj, "value"); + first = new WrapperWeakRef(obj); + })(); + pollUntil(function () { + return first.deref() === undefined; + }, function () { + expect(first.deref() === undefined).toBe(true); + expect(map.get(owner.objectAtIndex(0))).toBe("value"); + done(); + }); }); it("keeps working as the standard collections for other keys", function () { diff --git a/docs/knowledge/v8-resurrecting-finalizers.md b/docs/knowledge/v8-resurrecting-finalizers.md index 63af30b8..c866158f 100644 --- a/docs/knowledge/v8-resurrecting-finalizers.md +++ b/docs/knowledge/v8-resurrecting-finalizers.md @@ -352,8 +352,8 @@ documents it as not for general use. The alternative keeps an ObjC weak referenc references) and sweeps the records after every major collection, so state lingers until then. An instance of a class that refuses weak references and is not JS-extended gets no state under it, in the same way. With the default, `"scope": "all"` stays experimental because that -check reads private runtime layout; `"extended"` attaches tokens only to the plain objects a weak -collection keys (below), so the check runs there once per such object. It cannot be +check reads private runtime layout; `"extended"` attaches no tokens at all (the key-only +records below use the weak reference). It cannot be rooted at canary death instead, because a state reachable only through the canary is garbage in the same collection. The cost: state that references its own object (a closure over `this`) keeps it alive. A canary built after a death is a new object, but `===` cannot tell: only one @@ -375,33 +375,45 @@ nothing, as that limitation describes. What could notice is whatever keys on the don't: in canary mode a builtin (`js/weak-collections.js`) replaces `WeakMap`, `WeakSet`, `WeakRef` and `FinalizationRegistry` with subclasses that key a native object (a canary's, or under `"extended"` a plain object's; not a tagged pointer, a block, or an object of a class -refusing weak references or forbidding associated objects) by an opaque, frozen key held by its state, so entries and targets live +refusing weak references or, for a canary, forbidding associated objects) by an opaque, frozen key held by its state, so entries and targets live exactly as long as the native object, and `WeakRef.prototype.deref` returns the live wrapper, a new one, or `undefined` once the object is gone. Lookups never create that key, and a Proxy around a native object stays a key of its own. Under `"extended"` a plain object's wrapper is a phantom handle with no handlers and no state, which dies with its JS references just as a canary does, so -the first keying of a plain object (`unwrap` with `create`) gives it a key-only record: the -lifecycle token, a weak slot, and a state holding nothing but the key, counted in `canaryStates` -and in the registry's `records`, so the leak probe walks it like any other state. The record is -flagged `plain` and no wrapper holds it: wrapping a plain object never consults the registry, and -`unwrap` finds the record by the object's address only after the canary lookups miss, behind an -atomic count of plain records, so a weak-collection lookup costs nothing more while no plain -object was ever keyed. `wrap` returns the object's `Instances` wrapper or builds a plain one (no -adoption, no hydration). Release semantics are the canary ones: `__releaseNativeCounterpart` on a -plain wrapper copies the key, or `null`, onto it (`KeepPlainWeakCollectionKey`) and marks the -record released; since no adoption looks the record up, `unwrap` or `wrap` meeting a live wrapper -of the object clears the mark instead. A native hand-back whose wrapper dies before any weak -collection operation sees it leaves the record released, so `deref` returns `undefined` until the -next hand-back reaches one. The token's `-dealloc` retires the record (`NativeDied`); it bumps the -`deref` cache epoch only when a weak load finds the object alive, i.e. when -`objc_removeAssociatedObjects` removed the token, which loses what was keyed on a plain object as -it does for a canary, where a wrapper key used to be immune. A plain key costs what a canary key -does otherwise: a `WeakMap` value referencing its key keeps the object alive. Measured on a -Release simulator build (median of launches, ns/op): a `WeakMap` hit on a keyed plain object -145 instead of 40 (the wrapper was the key), a miss on a never-keyed plain wrapper 126 instead -of 107 once any plain object was keyed and unchanged (108) before, the first keying 966 instead -of 165, and a `deref` that rebuilds a dead plain wrapper about 1150; creating plain wrappers, -native calls, native property reads and stores and `Instances` lookups are unchanged. The cost is the other side of the same rooting: a `WeakMap` +the first keying of a plain object (`unwrap` with `create`) gives it a key-only record: a weak +slot and a state holding nothing but the key, counted in `canaryStates` and in the registry's +`records`, so the leak probe walks it like any other state. Nothing is attached to the object: no +token, so no private class layout is read, a class forbidding associated objects is keyed like +any other, and `objc_removeAssociatedObjects` leaves the record alone. Only a class refusing weak +references keeps its wrapper as the key. The record is flagged `plain` and no wrapper holds it: +wrapping a plain object never consults the registry, and `unwrap` finds the record by the +object's address only after the canary lookups miss, behind an atomic count of plain records, so +a weak-collection lookup costs nothing more while no plain object was ever keyed, and canary +adoption skips the registry while every record is plain. `wrap` returns the object's `Instances` +wrapper or builds a plain one (no adoption, no hydration). Death is the weak sweep, whatever +`NS_CANARY_DEATH_SIGNAL` chooses for canaries: a major-GC epilogue posts `SweepPlain` (one atomic +load while there is no plain record), which walks the registry's `plainRecords` list, not the +map, and retires records whose weak slot was zeroed; a lookup that meets a zeroed slot retires +the record at once (`RetireIfDead`). So entries keyed on a dead plain object, and its +`FinalizationRegistry` callbacks, wait until the major collection after its deallocation (and the +key's own collection after that). The sweep bumps no `deref` cache epoch: a live wrapper retains +its object, so no cached wrapper outlives a swept object. Release semantics are the canary ones: +`__releaseNativeCounterpart` on a plain wrapper copies the key, or `null`, onto it +(`KeepPlainWeakCollectionKey`) and marks the record released; since no adoption looks the record +up, `unwrap` or `wrap` meeting a live wrapper of the object clears the mark instead. Limitation: +a native hand-back whose wrapper dies before any weak collection operation sees it leaves the +record released, so `deref` returns `undefined` until a later hand-back reaches `unwrap` or +`wrap`. Limitation: as for canaries, a `WeakMap` value referencing its plain key keeps the object +alive while the map lives, where the wrapper key used to let it go. Measured on a Release +simulator build (medians of launches, ns/op): a `WeakMap` hit on a keyed plain object 142 instead +of 39 (the wrapper was the key), a miss on a never-keyed plain wrapper 124 instead of 106 once any +plain object was keyed and unchanged (107) before, the first keying 870 instead of 154, a +`new WeakRef` of a fresh plain object 1570 instead of 216, and a `deref` that rebuilds a dead +plain wrapper about 1120. A major collection plus the next timer took about 500 µs with 1000 +keyed plain objects held against 370 with the same objects unkeyed, the same as a build that +reported their deaths with tokens (540 against 385): the difference is the states and keys on the +heap, and the sweep is below that noise. Creating plain wrappers, native calls, native property +reads and stores, `Instances` lookups and a major collection with no plain record are unchanged. The cost is the other side of the same rooting: a `WeakMap` value that references its native key keeps the key, its state and so the native object alive for as long as the map lives, where in the other modes the entry would be collectable. Native `#private` fields are branded on the canary and do not carry over. Other limits: `Object.freeze`, `seal` and `preventExtensions` throw on a canary (V8 refuses them on diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 8c1af609..930f3b79 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -248,20 +248,27 @@ in the standard collections. What follows from that: - Under scope `"extended"` a plain (not JS-extended) object's wrapper is not a canary, but it also dies with its JS references while the object lives on. So the first `set`, `add`, `new WeakRef` or `register` of a plain object - gives the object a state holding only its key, with the same lifecycle - token a plain canary gets under `"all"`, and from then on it is keyed by - its lifetime exactly as a canary is, release included. Objects of a class - that forbids associated objects or refuses weak references, tagged pointers - and blocks stay keyed by their wrapper. Wrapping plain objects, calling - them and their properties cost nothing more. Each weak collection operation - on a keyed plain object asks native code for its key (about 145 ns - for a `WeakMap.prototype.get` hit instead of 40, Release - simulator build), the first keying of an object costs about 800 ns - more, and once any plain object was keyed a miss on one never keyed costs - about 126 ns instead of 107. As with canaries, a - `WeakMap` value that references its plain key keeps the object alive while - the map lives, and `objc_removeAssociatedObjects` on the object loses what - was keyed on it. + gives the object a state holding only its key, and from then on it is keyed + by its lifetime as a canary is, release included. Nothing is attached to + the object: the runtime holds a weak reference to it and checks it after + each major garbage collection, so what was keyed on a plain object that + was deallocated stays until the next major collection (its + `FinalizationRegistry` callbacks run after that), and + `objc_removeAssociatedObjects` does not affect it. Objects of a class that + refuses weak references, tagged pointers and blocks stay keyed by their + wrapper. Wrapping plain objects, calling them and their properties cost + nothing more, and so does a major collection while no plain object is + keyed. Each weak collection operation on a keyed plain object asks native + code for its key (about 142 ns for a `WeakMap.prototype.get` hit instead of + 39, Release simulator build), the first keying of an object costs about + 700 ns more, once any plain object was keyed a miss on one never keyed + costs about 124 ns instead of 106, and with 1000 keyed plain objects a + major collection takes about 130 µs more than with the same objects + unkeyed, for their keys and states on the heap. Limitations: as with + canaries, a `WeakMap` value that references its plain key keeps the object + alive while the map lives; and if native code hands a released object back + and that wrapper dies before any weak collection operation sees it, + `deref` keeps returning `undefined` until native code hands it back again. - What was keyed on a native object follows the object, not a released wrapper of it. After `__releaseNativeCounterpart(w)`, `w` still finds the object's entries while JS holds it, and a wrapper native code hands back diff --git a/types/ns-runtime.d.ts b/types/ns-runtime.d.ts index 6e580039..dee337de 100644 --- a/types/ns-runtime.d.ts +++ b/types/ns-runtime.d.ts @@ -73,9 +73,10 @@ declare module "ns:runtime" { * WeakMap, WeakSet, WeakRef and FinalizationRegistry key such native * objects by their lifetime in this mode, so they carry over too, and * under scope `"extended"` also key plain objects by their lifetime once - * they first key one (a state holding only the key, with the same - * token); a WeakMap value that references its own native key keeps that - * object alive while the map lives. Native `#private` fields and index-keyed + * they first key one (a state holding only the key; nothing is attached + * to the object, whose death is found after a major collection); a + * WeakMap value that references its own native key keeps that object + * alive while the map lives. Native `#private` fields and index-keyed * properties do not. * State that references its own object keeps that object alive. */ From f89ce34adfe7411bb10984e319567bf241bea078 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 23:24:29 -0300 Subject: [PATCH 5/8] fix(runtime): retire a dead record holding a new plain record's address --- NativeScript/runtime/WrapperLifetimeCanary.mm | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/NativeScript/runtime/WrapperLifetimeCanary.mm b/NativeScript/runtime/WrapperLifetimeCanary.mm index 77ae7a75..f61ce160 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.mm +++ b/NativeScript/runtime/WrapperLifetimeCanary.mm @@ -1126,20 +1126,29 @@ bool CanHavePlainRecord(id object) { // Allocated before the lock: a collection this allocation starts can run // callbacks that take it. record->state.Reset(isolate, Object::New(isolate, Null(isolate), nullptr, nullptr, 0)); + bool retired = false; { std::lock_guard lock(registry->mutex); if (registry->closed) { return nullptr; } - std::shared_ptr& slot = registry->records[address]; - if (slot != nullptr) { - return slot->plain ? slot : nullptr; + // The lookup above is skipped while no plain record exists: a dead + // canary's record can still hold the address. + auto existing = registry->records.find(address); + if (existing != registry->records.end()) { + retired = RetireIfDead(registry.get(), existing); + if (!retired) { + return existing->second->plain ? existing->second : nullptr; + } } - slot = record; + registry->records.emplace(address, record); registry->plainRecords.push_back(record); registry->count.fetch_add(1, std::memory_order_relaxed); registry->plainCount.fetch_add(1, std::memory_order_relaxed); } + if (retired) { + PostDrain(registry); + } if (ObjectManager::LifetimeStats* stats = ObjectManager::GetLifetimeStats(isolate)) { stats->canaryStates++; } From 4616c29a97537b4e5c111a83af961e79633d8eb1 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 23:25:01 -0300 Subject: [PATCH 6/8] fix(runtime): sweep retired plain records after the last plain record is gone --- NativeScript/runtime/WrapperLifetimeCanary.mm | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/NativeScript/runtime/WrapperLifetimeCanary.mm b/NativeScript/runtime/WrapperLifetimeCanary.mm index f61ce160..90cb1f23 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.mm +++ b/NativeScript/runtime/WrapperLifetimeCanary.mm @@ -133,12 +133,16 @@ void SetLiveCanary(bool live) { // Lets wrapper creation skip the lookup while no object has state. std::atomic count{0}; // The plain records among them: lets a weak collection lookup of a plain - // wrapper, and the sweep after a major collection, skip the registry while - // no plain object was keyed. + // wrapper skip the registry while no plain object was keyed. std::atomic plainCount{0}; // Every plain record in `records`, and retired ones until the next // SweepPlain drops them: what that sweep walks instead of the whole map. std::vector> plainRecords; + // plainRecords' size, which lets the sweep after a major collection skip + // the registry: a lookup can retire the last plain record, which then waits + // in plainRecords with plainCount at zero. Written under the mutex, read + // without it. + std::atomic plainTracked{0}; // Outlives the registry while the builtin's array does. std::shared_ptr weakCollectionCache = std::make_shared(); @@ -1143,6 +1147,7 @@ bool CanHavePlainRecord(id object) { } registry->records.emplace(address, record); registry->plainRecords.push_back(record); + registry->plainTracked.store(registry->plainRecords.size(), std::memory_order_relaxed); registry->count.fetch_add(1, std::memory_order_relaxed); registry->plainCount.fetch_add(1, std::memory_order_relaxed); } @@ -1193,16 +1198,17 @@ void SweepPlain(const std::shared_ptr& registry) { i++; } } + registry->plainTracked.store(plain.size(), std::memory_order_relaxed); } ReleaseStates(registry.get(), dead); } // Scope "extended": posts SweepPlain when a major collection ends, behind the // release drain the collection queued, so objects it released are gone by -// then. Only an atomic load while no plain record exists. +// then. Only an atomic load while plainRecords is empty. void PostPlainSweepAfterGC(Isolate* isolate, GCType, GCCallbackFlags) { CanaryState* state = Caches::ExistingStateFor(isolate); - if (state == nullptr || state->registry->plainCount.load(std::memory_order_relaxed) == 0) { + if (state == nullptr || state->registry->plainTracked.load(std::memory_order_relaxed) == 0) { return; } std::shared_ptr registry = state->registry; @@ -1681,6 +1687,7 @@ void WriteWeakCollectionKey(Isolate* isolate, CanaryState* canaryState, Localstate.Reset(); } state->registry->plainRecords.clear(); + state->registry->plainTracked.store(0, std::memory_order_relaxed); } void WrapperLifetimeCanary::ForEachState( From 2cd98351ad7aad50ba7ba6d4415d4aa253c2b5aa Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 23:25:46 -0300 Subject: [PATCH 7/8] fix(runtime): unwrap answers with a key stored while it made a new one --- NativeScript/runtime/WrapperLifetimeCanary.mm | 23 ++++++++++++------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/NativeScript/runtime/WrapperLifetimeCanary.mm b/NativeScript/runtime/WrapperLifetimeCanary.mm index 90cb1f23..96417234 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.mm +++ b/NativeScript/runtime/WrapperLifetimeCanary.mm @@ -1292,13 +1292,16 @@ void UnwrapCallback(const FunctionCallbackInfo& info) { } return; } - if (state->GetPrivate(context, keyOfState).ToLocal(&key) && key->IsObject()) { + auto answer = [&](Local found) { if (reportLive) { canaryState->registry->weakCollectionCache->SetLiveCanary( plain != nullptr ? IsCachedWrapper(isolate, plainObject, value) : CanaryOf(isolate, value.As()) != nullptr); } - info.GetReturnValue().Set(key); + info.GetReturnValue().Set(found); + }; + if (state->GetPrivate(context, keyOfState).ToLocal(&key) && key->IsObject()) { + answer(key); return; } if (!create) { @@ -1327,15 +1330,19 @@ void UnwrapCallback(const FunctionCallbackInfo& info) { ->SetPrivate(context, canaryState->objectOfKey.Get(isolate), BigInt::NewFromUnsigned(isolate, address)) .FromMaybe(false) || - !newKey->SetIntegrityLevel(context, IntegrityLevel::kFrozen).FromMaybe(false) || - !state->SetPrivate(context, keyOfState, newKey).FromMaybe(false)) { + !newKey->SetIntegrityLevel(context, IntegrityLevel::kFrozen).FromMaybe(false)) { return; } - if (reportLive) { - canaryState->registry->weakCollectionCache->SetLiveCanary( - plain == nullptr || IsCachedWrapper(isolate, plainObject, value)); + // Making the key can allocate, and the finalizers of a collection that starts + // there can run JS that keys the object first: one object, one key. + if (state->GetPrivate(context, keyOfState).ToLocal(&key) && key->IsObject()) { + answer(key); + return; + } + if (!state->SetPrivate(context, keyOfState, newKey).FromMaybe(false)) { + return; } - info.GetReturnValue().Set(newKey); + answer(newKey); } // The object a key stands for: its live wrapper or a new one (a canary, or for From 32f0b4bf4807c889e85d55f4b6f7b3e3725d7bd8 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 23:56:31 -0300 Subject: [PATCH 8/8] docs: the plain sweep runs while plainRecords holds retired records --- docs/knowledge/v8-resurrecting-finalizers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/knowledge/v8-resurrecting-finalizers.md b/docs/knowledge/v8-resurrecting-finalizers.md index c866158f..20d6326c 100644 --- a/docs/knowledge/v8-resurrecting-finalizers.md +++ b/docs/knowledge/v8-resurrecting-finalizers.md @@ -392,7 +392,7 @@ a weak-collection lookup costs nothing more while no plain object was ever keyed adoption skips the registry while every record is plain. `wrap` returns the object's `Instances` wrapper or builds a plain one (no adoption, no hydration). Death is the weak sweep, whatever `NS_CANARY_DEATH_SIGNAL` chooses for canaries: a major-GC epilogue posts `SweepPlain` (one atomic -load while there is no plain record), which walks the registry's `plainRecords` list, not the +load while `plainRecords`, retired records included, is empty), which walks the registry's `plainRecords` list, not the map, and retires records whose weak slot was zeroed; a lookup that meets a zeroed slot retires the record at once (`RetireIfDead`). So entries keyed on a dead plain object, and its `FinalizationRegistry` callbacks, wait until the major collection after its deallocation (and the