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
7 changes: 5 additions & 2 deletions NativeScript/runtime/ObjectManager.h
Original file line number Diff line number Diff line change
Expand Up @@ -73,13 +73,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
6 changes: 6 additions & 0 deletions 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 @@ -843,6 +844,11 @@ void DisposeHandle(v8::Isolate* isolate,
// The teardown walk owns this state and releases the object.
return;
}
if (adopted->lifetimeCanary_) {
// Before the release below, which can run the object's -dealloc.
WrapperLifetimeCanary::KeepWeakCollectionKey(isolate, value.As<Object>(),
adopted->canaryRecord_);
}
if (it != cache->Instances.end() && it->second == adopted->target_) {
cache->Instances.erase(it);
}
Expand Down
13 changes: 12 additions & 1 deletion NativeScript/runtime/WrapperLifetimeCanary.h
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,19 @@ 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 `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,
const std::shared_ptr<CanaryRecord>& record);

// 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
63 changes: 57 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,28 @@ void WrapCallback(const FunctionCallbackInfo<Value>& info) {
binding->Set(context, tns::ToV8String(isolate, "wrap"), wrap).FromMaybe(false);
}

void WrapperLifetimeCanary::KeepWeakCollectionKey(Isolate* isolate, Local<Object> canary,
const std::shared_ptr<CanaryRecord>& record) {
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);
Local<Value> copy = v8::Null(isolate);
if (Usable(record)) {
record->released = true;
Local<Value> key;
if (Local<Object>::New(isolate, record->state)->GetPrivate(context, keyOfState).ToLocal(&key) &&
key->IsObject()) {
copy = key;
}
}
// Private symbols bypass the canary's handlers.
(void)canary->SetPrivate(context, keyOfState, copy);
}

void WrapperLifetimeCanary::InstallDeallocHook(Class extendedClass) {
if (GetWrapperLifetimeMode() != WrapperLifetimeMode::kCanary) {
return;
Expand Down Expand Up @@ -948,6 +998,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