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 c65c7d24..7935e9ed 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.h +++ b/NativeScript/runtime/WrapperLifetimeCanary.h @@ -101,9 +101,16 @@ 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 - // `wrap` (key -> live or new canary, or undefined once the object is gone) - // to `binding`, for the weak-collections builtin. Canary mode only. + // Adds `unwrap` (a canary's native object -> its weak-collection key), + // `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. 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. + // 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); @@ -119,6 +126,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 0e5e3468..96417234 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 @@ -67,12 +69,18 @@ // 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, 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). void* address = nullptr; @@ -89,11 +97,29 @@ 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); + } +}; + +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; @@ -103,8 +129,23 @@ bool ObjectAlive() const { 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. + 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(); Isolate* isolate = nullptr; std::weak_ptr loop; #if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_ASSOCIATION @@ -122,6 +163,21 @@ bool ObjectAlive() const { 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. @@ -194,17 +250,19 @@ void NativeDied(const std::shared_ptr& registry, void* object, if (it == registry->records.end() || (expected != nullptr && it->second.get() != expected)) { return; } + // 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(); + } // 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); - 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; + 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; } // A post dropped at shutdown is fine: teardown resets every handle. if (loop != nullptr && !loop->PostInternal([registry]() { DrainDead(registry); })) { @@ -340,10 +398,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); @@ -409,15 +464,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; } @@ -438,6 +489,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) { @@ -614,16 +679,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++; @@ -993,32 +1051,231 @@ 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). +// 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 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, + 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; + } + auto record = std::make_shared(); + record->plain = true; + record->address = address; + // The only death signal: SweepPlain, and wrap, read 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)); + bool retired = false; + { + std::lock_guard lock(registry->mutex); + if (registry->closed) { + return 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; + } + } + 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); + } + if (retired) { + PostDrain(registry); + } + 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); +} + +// 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++; + } + } + 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 plainRecords is empty. +void PostPlainSweepAfterGC(Isolate* isolate, GCType, GCCallbackFlags) { + CanaryState* state = Caches::ExistingStateFor(isolate); + if (state == nullptr || state->registry->plainTracked.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, +// 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]; 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(); 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()->InternalFieldCount() == 0 || - !value.As()->GetPrivate(context, keyOfState).ToLocal(&key)) { + if (!value.As()->GetPrivate(context, keyOfState).ToLocal(&key)) { return; } if (key->IsObject()) { @@ -1035,40 +1292,62 @@ void UnwrapCallback(const FunctionCallbackInfo& info) { } return; } + auto answer = [&](Local found) { + if (reportLive) { + canaryState->registry->weakCollectionCache->SetLiveCanary( + plain != nullptr ? IsCachedWrapper(isolate, plainObject, value) + : CanaryOf(isolate, value.As()) != nullptr); + } + info.GetReturnValue().Set(found); + }; if (state->GetPrivate(context, keyOfState).ToLocal(&key) && key->IsObject()) { - info.GetReturnValue().Set(key); + answer(key); return; } 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)) .FromMaybe(false) || - !newKey->SetIntegrityLevel(context, IntegrityLevel::kFrozen).FromMaybe(false) || - !state->SetPrivate(context, keyOfState, newKey).FromMaybe(false)) { + !newKey->SetIntegrityLevel(context, IntegrityLevel::kFrozen).FromMaybe(false)) { return; } - info.GetReturnValue().Set(newKey); + // 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; + } + answer(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]; @@ -1116,6 +1395,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; @@ -1133,6 +1417,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) { @@ -1156,16 +1491,33 @@ void WrapCallback(const FunctionCallbackInfo& info) { #if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_WEAK_SWEEP isolate->AddGCEpilogueCallback(PostSweepAfterGC, kGCTypeMarkSweepCompact); #endif + if (GetWrapperLifetimeScope() == WrapperLifetimeScope::kExtended) { + isolate->AddGCEpilogueCallback(PostPlainSweepAfterGC, kGCTypeMarkSweepCompact); + } } bool WrapperLifetimeCanary::RegisterWrapFunctions(Local context, Local binding) { 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) { @@ -1173,52 +1525,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; } + WriteWeakCollectionKey(isolate, canaryState, wrapper, [&]() { + return PlainRecord(isolate, canaryState->registry, object, false); + }); } void WrapperLifetimeCanary::InstallDeallocHook(Class extendedClass) { @@ -1325,7 +1650,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; } { @@ -1360,6 +1693,8 @@ void WrapCallback(const FunctionCallbackInfo& info) { for (std::shared_ptr& record : state->registry->orphaned) { record->state.Reset(); } + state->registry->plainRecords.clear(); + state->registry->plainTracked.store(0, std::memory_order_relaxed); } void WrapperLifetimeCanary::ForEachState( diff --git a/NativeScript/runtime/js/weak-collections.js b/NativeScript/runtime/js/weak-collections.js index d265bdb1..5692cf61 100644 --- a/NativeScript/runtime/js/weak-collections.js +++ b/NativeScript/runtime/js/weak-collections.js @@ -2,16 +2,17 @@ // 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 // prototype, and WeakMap.toString() is not native code. -const { unwrap, wrap } = binding; +const { unwrap, wrap, cache } = binding; const { FinalizationRegistry: NativeFinalizationRegistry, FinalizationRegistryPrototypeRegister, @@ -50,15 +51,23 @@ 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: plain JS keys never reach native code. +// 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 +// 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 +179,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 +211,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/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 54de2cdc..2231ccbf 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; } @@ -186,6 +201,286 @@ 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: [] + }; + } + + // 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(); + (function () { + var obj = Extended.new(); + watch.addObject(obj); + keyEverywhere(obj, keyed); + })(); + var attempts = 15; + (function poll() { + settle(1, function () { + var gone = watchedCount(watch) === 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; + } + // Collects only after the run loop drained the probe's array. + setTimeout(poll, 10); + }); + })(); + }); + + 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(); + }); + }); + + // 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 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 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(); + 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"); + 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); + 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, {}); @@ -247,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(); @@ -268,10 +564,34 @@ 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 () { var key = {}; var map = new WeakMap([[key, 1]]); @@ -347,43 +667,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 () { @@ -392,213 +758,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 (" + 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; - 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); + // 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..20d6326c 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 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 @@ -372,12 +373,47 @@ 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 -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 +`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, 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. 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: 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 `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 +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 a198fe64..930f3b79 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,30 @@ 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, 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 854bff04..dee337de 100644 --- a/types/ns-runtime.d.ts +++ b/types/ns-runtime.d.ts @@ -71,7 +71,10 @@ 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 + * 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; 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. @@ -129,7 +132,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;