Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions NativeScript/runtime/WrapperLifetimeCanary.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<v8::Context> context,
v8::Local<v8::Object> binding);

Expand Down
78 changes: 67 additions & 11 deletions NativeScript/runtime/WrapperLifetimeCanary.mm
Original file line number Diff line number Diff line change
Expand Up @@ -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<uint32_t> 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 {
Expand All @@ -105,6 +121,9 @@ bool ObjectAlive() const {
bool sweepPosted = false;
// Lets wrapper creation skip the lookup while no object has state.
std::atomic<size_t> count{0};
// Outlives the registry while the builtin's array does.
std::shared_ptr<WeakCollectionCache> weakCollectionCache =
std::make_shared<WeakCollectionCache>();
Isolate* isolate = nullptr;
std::weak_ptr<EventLoop> loop;
#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_ASSOCIATION
Expand Down Expand Up @@ -197,6 +216,12 @@ void NativeDied(const std::shared_ptr<CanaryRegistry>& 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);
Expand Down Expand Up @@ -989,21 +1014,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<Value>& info) {
Isolate* isolate = info.GetIsolate();
Local<Value> value = info[0];
bool create = info[1]->IsTrue();
bool reportLive = info[2]->IsTrue();
info.GetReturnValue().Set(value);
CanaryState* canaryState = Caches::StateFor<CanaryState>(isolate);
Local<Object> 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<Object>()->InternalFieldCount() == 0) {
return;
}
Local<Context> context = isolate->GetCurrentContext();
Expand All @@ -1013,8 +1047,7 @@ void UnwrapCallback(const FunctionCallbackInfo<Value>& info) {
: !ExistingState(isolate, value.As<Object>(), &state)) {
// A released canary keeps its key itself, or null when it had none
// (KeepWeakCollectionKey).
if (value.As<Object>()->InternalFieldCount() == 0 ||
!value.As<Object>()->GetPrivate(context, keyOfState).ToLocal(&key)) {
if (!value.As<Object>()->GetPrivate(context, keyOfState).ToLocal(&key)) {
return;
}
if (key->IsObject()) {
Expand All @@ -1032,6 +1065,10 @@ void UnwrapCallback(const FunctionCallbackInfo<Value>& info) {
return;
}
if (state->GetPrivate(context, keyOfState).ToLocal(&key) && key->IsObject()) {
if (reportLive) {
canaryState->registry->weakCollectionCache->SetLiveCanary(
CanaryOf(isolate, value.As<Object>()) != nullptr);
}
info.GetReturnValue().Set(key);
return;
}
Expand Down Expand Up @@ -1060,6 +1097,9 @@ void UnwrapCallback(const FunctionCallbackInfo<Value>& info) {
!state->SetPrivate(context, keyOfState, newKey).FromMaybe(false)) {
return;
}
if (reportLive) {
canaryState->registry->weakCollectionCache->SetLiveCanary(true);
}
info.GetReturnValue().Set(newKey);
}

Expand Down Expand Up @@ -1158,10 +1198,24 @@ void WrapCallback(const FunctionCallbackInfo<Value>& info) {
Isolate* isolate = v8::Isolate::GetCurrent();
Local<v8::Function> unwrap;
Local<v8::Function> wrap;
CanaryState* state = Caches::StateFor<CanaryState>(isolate);
if (state == nullptr) {
return false;
}
auto* owner = new std::shared_ptr<WeakCollectionCache>(state->registry->weakCollectionCache);
std::unique_ptr<BackingStore> store = ArrayBuffer::NewBackingStore(
(*owner)->slots, sizeof((*owner)->slots),
[](void*, size_t, void* data) {
delete static_cast<std::shared_ptr<WeakCollectionCache>*>(data);
},
owner);
Local<v8::Uint32Array> 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<Object> canary,
Expand All @@ -1185,6 +1239,8 @@ void WrapCallback(const FunctionCallbackInfo<Value>& info) {
copy = key;
}
}
// wrap hands out no wrapper of the object now.
canaryState->registry->weakCollectionCache->Invalidate();
// Private symbols bypass the canary's handlers.
(void)canary->SetPrivate(context, keyOfState, copy);
}
Expand Down
53 changes: 45 additions & 8 deletions NativeScript/runtime/js/weak-collections.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -169,12 +176,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;
}
}
}

Expand All @@ -187,10 +208,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;
}
Expand Down
Loading
Loading