Skip to content
Merged
20 changes: 13 additions & 7 deletions NativeScript/runtime/ObjectManager.h
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,14 @@ struct ObjectWeakCallbackState {
ObjectWeakCallbackState* prev_ = nullptr;
ObjectWeakCallbackState* next_ = nullptr;

// Set while one of the two owning sites is disposing this handle's value.
// Disposal releases the native counterpart, whose -dealloc can re-enter JS
// and reach __releaseNativeCounterpart for this very handle; retiring it
// there would free the state under the frame that owns it. Retirement
// observes the flag and leaves the handle to that frame.
// Set while one of the two owning sites is disposing this handle's value,
// or while __releaseNativeCounterpart writes a canary's weak collection key
// before retiring the registration it adopted. Disposal releases the native
// counterpart, whose -dealloc can re-enter JS and reach
// __releaseNativeCounterpart for this very handle, and the key write can
// run a collection whose finalizers do; retiring it there would free the
// state under the frame that owns it. Retirement observes the flag and
// leaves the handle to that frame.
bool disposing_ = false;

// Set when WrapperLifetime adopted this registration (an ObjC object wrapper
Expand Down Expand Up @@ -73,13 +76,16 @@ class ObjectManager {
// getWrapperLifetimeStats().
struct LifetimeStats {
// An ObjC wrapper's finalizer refused disposal because native code still
// retains its object (IsGcProtected), keeping the wrapper alive.
// retains its object (IsGcProtected, or an OwnershipState wrapper whose
// object is natively owned), keeping the wrapper alive.
uint64_t resurrections = 0;
// An ObjC wrapper's finalizer released its native object.
uint64_t collected = 0;
// __releaseNativeCounterpart released a native object.
uint64_t releasedExplicitly = 0;
// JS handed a released wrapper to native code or used it as a receiver.
// A released wrapper was used: as a native argument, collection element or
// return value, as a receiver (toString included), or through a released
// pointer, reference or struct.
uint64_t releasedAccesses = 0;
// A finalized ObjC wrapper carried JS properties while something other
// than the wrapper still retained its object, and whether that object was
Expand Down
17 changes: 16 additions & 1 deletion NativeScript/runtime/ObjectManager.mm
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
#include "Helpers.h"
#include "Runtime.h"
#include "WrapperLifetime.h"
#include "WrapperLifetimeCanary.h"

// Exported by libobjc; not declared in a public header for MRC code.
extern "C" id objc_initWeak(id* location, id value);
Expand Down Expand Up @@ -840,9 +841,23 @@ void DisposeHandle(v8::Isolate* isolate,
// An adopted wrapper (WrapperLifetime) owns its registration whether or not
// the Instances entry still names it, and its handle may be strong.
if (adopted->disposing_) {
// The teardown walk owns this state and releases the object.
// Another frame owns this state and releases the object: the teardown
// walk, or an outer call still writing the canary's key below.
return;
}
if (adopted->lifetimeCanary_) {
// 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.
adopted->disposing_ = true;
WrapperLifetimeCanary::KeepWeakCollectionKey(isolate, value.As<Object>());
// The wrapper first: a release that got through would have freed it.
if (tns::GetValue(isolate, value) != wrapper || objcWrapper->LifetimeState() != adopted) {
return;
}
// Those finalizers can also have changed Instances.
it = cache->Instances.find(data);
}
if (it != cache->Instances.end() && it->second == adopted->target_) {
cache->Instances.erase(it);
}
Expand Down
12 changes: 11 additions & 1 deletion NativeScript/runtime/WrapperLifetimeCanary.h
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,18 @@ class WrapperLifetimeCanary {
static bool RegisterWrapFunctions(v8::Local<v8::Context> context,
v8::Local<v8::Object> binding);

// Before `canary`'s native object is released through
// __releaseNativeCounterpart: marks the canary's record released, so the
// weak collections hand out no wrapper of the object until native code
// returns it, and copies the object's weak-collection key onto the canary,
// so what was keyed on the object is still found through the released
// canary. With no key to copy, the canary is marked so that weak collections
// report it as a released-object access.
static void KeepWeakCollectionKey(v8::Isolate* isolate,
v8::Local<v8::Object> canary);

// The record of an object that already has state in this isolate, for a new
// canary to share. Null otherwise.
// canary to adopt; it is no longer released. Null otherwise.
static std::shared_ptr<CanaryRecord> Find(v8::Isolate* isolate, id object);

// Copies the state of a new canary's object, or of a -dealloc receiver's,
Expand Down
89 changes: 83 additions & 6 deletions NativeScript/runtime/WrapperLifetimeCanary.mm
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@
// 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.
bool released = false;

~CanaryRecord() { objc_destroyWeak(&object); }

Expand Down Expand Up @@ -105,7 +108,7 @@ bool ObjectAlive() const {
struct CanaryState {
std::shared_ptr<CanaryRegistry> registry = std::make_shared<CanaryRegistry>();
// The weak collections' key for a native object hangs off its state, and
// names the object it stands for.
// names the object it stands for. A released canary holds a copy.
Global<Private> keyOfState;
Global<Private> objectOfKey;
};
Expand Down Expand Up @@ -712,8 +715,9 @@ 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 exactly as long as the
// object's state, that is, until the native object is deallocated. Lookups pass
// 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).
Expand All @@ -727,13 +731,31 @@ void UnwrapCallback(const FunctionCallbackInfo<Value>& info) {
if (canaryState == nullptr || !value->IsObject() || value->IsProxy()) {
return;
}
Local<Context> context = isolate->GetCurrentContext();
Local<Private> keyOfState = canaryState->keyOfState.Get(isolate);
Local<Value> key;
if (create ? !StateForWrite(isolate, value.As<Object>(), &state)
: !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)) {
return;
}
if (key->IsObject()) {
info.GetReturnValue().Set(key);
} else if (key->IsNull()) {
// Such a canary is a key of its own, which nothing keyed on its object
// can find: a released-object access.
ReleasedReason reason = tns::GetReleasedReason(value);
if (reason != ReleasedReason::kNone) {
tns::ReportReleasedObject(
isolate, value, reason,
"weak collection key: WeakMap, WeakSet, WeakRef or FinalizationRegistry", true);
}
}
return;
}
Local<Context> context = isolate->GetCurrentContext();
Local<Private> keyOfState = canaryState->keyOfState.Get(isolate);
Local<Value> key;
if (state->GetPrivate(context, keyOfState).ToLocal(&key) && key->IsObject()) {
info.GetReturnValue().Set(key);
return;
Expand Down Expand Up @@ -819,6 +841,12 @@ void WrapCallback(const FunctionCallbackInfo<Value>& info) {
info.GetReturnValue().Set(cached->Get(isolate));
return;
}
if (record->released) {
// Released by JS and not handed back by native code: JS holds no wrapper
// of it until native code returns it.
[object release];
return;
}
ObjCDataWrapper* wrapper = new ObjCDataWrapper(object);
Local<Value> result = ArgConverter::ConvertArgument(context, wrapper);
tns::DeleteWrapperIfUnused(isolate, result, wrapper);
Expand Down Expand Up @@ -861,6 +889,54 @@ void WrapCallback(const FunctionCallbackInfo<Value>& info) {
binding->Set(context, tns::ToV8String(isolate, "wrap"), wrap).FromMaybe(false);
}

void WrapperLifetimeCanary::KeepWeakCollectionKey(Isolate* isolate, Local<Object> canary) {
CanaryState* canaryState = Caches::StateFor<CanaryState>(isolate);
if (canaryState == nullptr || canaryState->keyOfState.IsEmpty()) {
return;
}
HandleScope scope(isolate);
Local<Context> context = isolate->GetCurrentContext();
Local<Private> keyOfState = canaryState->keyOfState.Get(isolate);
auto currentRecord = [&]() {
ObjectWeakCallbackState* state = CanaryOf(isolate, canary);
return state != nullptr ? state->canaryRecord_ : std::shared_ptr<CanaryRecord>();
};
auto keyOf = [&](const std::shared_ptr<CanaryRecord>& record) {
Local<Value> key;
if (Usable(record) &&
Local<Object>::New(isolate, record->state)->GetPrivate(context, keyOfState).ToLocal(&key) &&
key->IsObject()) {
return key;
}
return Local<Value>(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<CanaryRecord> record = currentRecord();
Local<Value> copy = keyOf(record);
for (int writes = 1;; writes++) {
// Private symbols bypass the canary's handlers.
(void)canary->SetPrivate(context, keyOfState, copy);
std::shared_ptr<CanaryRecord> current = currentRecord();
if (!Usable(current) || writes == kMaxWrites) {
break;
}
Local<Value> 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 canary
// holds now is the one the release leaves behind.
if (std::shared_ptr<CanaryRecord> current = currentRecord()) {
current->released = true;
}
}

void WrapperLifetimeCanary::InstallDeallocHook(Class extendedClass) {
if (GetWrapperLifetimeMode() != WrapperLifetimeMode::kCanary) {
return;
Expand Down Expand Up @@ -948,6 +1024,7 @@ void WrapCallback(const FunctionCallbackInfo<Value>& info) {
}
std::shared_ptr<CanaryRecord> record = it->second;
if (!RetireIfDead(state->registry.get(), it)) {
record->released = false;
return record;
}
}
Expand Down
11 changes: 11 additions & 0 deletions NativeScript/runtime/js/primordials.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,13 @@ const intrinsics = {
Uint32Array,
URIError,
URL,
WeakMap,
WeakRef,
WeakSet,
SymbolFor: Symbol.for,
SymbolHasInstance: Symbol.hasInstance,
SymbolIterator: Symbol.iterator,
SymbolKeyFor: Symbol.keyFor,
SymbolToStringTag: Symbol.toStringTag,

// Namespaces / prototypes.
Expand Down Expand Up @@ -112,6 +114,15 @@ const intrinsics = {
StringPrototypeStartsWith: uncurryThis(String.prototype.startsWith),
StringPrototypeToLowerCase: uncurryThis(String.prototype.toLowerCase),
SymbolPrototypeToString: uncurryThis(Symbol.prototype.toString),
WeakMapPrototypeDelete: uncurryThis(WeakMap.prototype.delete),
WeakMapPrototypeGet: uncurryThis(WeakMap.prototype.get),
// The upsert proposal: undefined where V8 does not ship it.
WeakMapPrototypeGetOrInsert: typeof WeakMap.prototype.getOrInsert === "function"
? uncurryThis(WeakMap.prototype.getOrInsert) : undefined,
WeakMapPrototypeGetOrInsertComputed: typeof WeakMap.prototype.getOrInsertComputed === "function"
? uncurryThis(WeakMap.prototype.getOrInsertComputed) : undefined,
WeakMapPrototypeHas: uncurryThis(WeakMap.prototype.has),
WeakMapPrototypeSet: uncurryThis(WeakMap.prototype.set),
WeakRefPrototypeDeref: uncurryThis(WeakRef.prototype.deref),
WeakSetPrototypeAdd: uncurryThis(WeakSet.prototype.add),
WeakSetPrototypeDelete: uncurryThis(WeakSet.prototype.delete),
Expand Down
Loading
Loading