diff --git a/NativeScript/runtime/ArgConverter.h b/NativeScript/runtime/ArgConverter.h index 8201184da..b5cedbe71 100644 --- a/NativeScript/runtime/ArgConverter.h +++ b/NativeScript/runtime/ArgConverter.h @@ -86,6 +86,10 @@ class ArgConverter { // recycled the address and give it a foreign prototype. static std::shared_ptr> FindCachedInstance( v8::Isolate* isolate, const std::shared_ptr& cache, id target); + // The JS `this` for a native call into a JS-implemented member: the object's + // wrapper, built when it has none. + static v8::Local WrapCallbackSelf(v8::Local context, + id self); static const Meta* GetMeta(const std::string& name); static const ProtocolMeta* FindProtocolMeta(Protocol* protocol); static void MethodCallback(ffi_cif* cif, void* retValue, void** argValues, diff --git a/NativeScript/runtime/ArgConverter.mm b/NativeScript/runtime/ArgConverter.mm index 56bfc32b1..8e7c07f22 100644 --- a/NativeScript/runtime/ArgConverter.mm +++ b/NativeScript/runtime/ArgConverter.mm @@ -13,6 +13,7 @@ #include "ObjectManager.h" #include "Runtime.h" #include "RuntimeConfig.h" +#include "WrapperLifetime.h" using namespace v8; using namespace std; @@ -61,8 +62,14 @@ bool IsKVOSubclassOf(Class klass, Class base) { : isolate_(v8::Isolate::GetCurrent()) { auto cache = Caches::Get(isolate_); auto it = cache->Instances.find(self); + if (it != cache->Instances.end() && it->second->IsEmpty()) { + // A dead wrapper whose release is queued (WrapperLifetime): rebuild below. + cache->Instances.erase(it); + it = cache->Instances.end(); + } if (it != cache->Instances.end()) { receiver_ = it->second->Get(isolate_).As(); + WrapperLifetime::EscapeValue(isolate_, receiver_); } else { receiver_ = ArgConverter::WrapNativeCallbackSelf(context, self, &borrowed_); } @@ -91,8 +98,10 @@ bool IsKVOSubclassOf(Class klass, Class base) { Class allocKlass = nil; bool instanceMethod = !receiver.IsEmpty(); bool callSuper = false; + WrapperLifetime::DrainAtCallEntry(isolate); if (instanceMethod) { BaseDataWrapper* wrapper = tns::GetValue(isolate, receiver); + WrapperLifetime::Escape(wrapper); if (wrapper == nullptr) { tns::ReleasedReason releasedReason = tns::GetReleasedReason(receiver); @@ -645,6 +654,7 @@ bool IsKVOSubclassOf(Class klass, Class base) { BaseDataWrapper* baseWrapper = tns::GetValue(isolate, value); if (baseWrapper != nullptr && baseWrapper->Type() == WrapperType::ObjCObject) { ObjCDataWrapper* wrapper = static_cast(baseWrapper); + WrapperLifetime::Escape(wrapper); id data = wrapper->Data(); memset(retValue, 0, sizeof(id)); *static_cast(retValue) = data; @@ -695,6 +705,7 @@ bool IsKVOSubclassOf(Class klass, Class base) { Class klass, const InterfaceMeta* interfaceMeta) { Isolate* isolate = v8::Isolate::GetCurrent(); tns::Assert(klass != nullptr, isolate); + WrapperLifetime::DrainAtCallEntry(isolate); id result = nil; // A Caches::Instances entry owns exactly one reference to the object it maps @@ -772,6 +783,7 @@ bool IsKVOSubclassOf(Class klass, Class base) { wrapper->SetBornOnRuntimeThread(); ObjectManager::ProtectIfNativelyRetained(isolate, result, wrapper); } + WrapperLifetime::Adopt(isolate, wrapper, poThiz, result); ExternalMemory::ChargeEstimatedSize(isolate, thiz); } } @@ -1032,8 +1044,15 @@ bool IsKVOSubclassOf(Class klass, Class base) { auto cache = Caches::Get(isolate); if (receiver.IsEmpty()) { auto it = cache->Instances.find(target); + if (it != cache->Instances.end() && it->second->IsEmpty()) { + // The wrapper died and its release is still queued (WrapperLifetime); + // the queue entry keeps its own retain, so a new wrapper starts over. + cache->Instances.erase(it); + it = cache->Instances.end(); + } if (it != cache->Instances.end()) { receiver = it->second->Get(isolate).As(); + WrapperLifetime::EscapeValue(isolate, receiver); } else { std::shared_ptr> poValue = CreateEmptyObject(context); receiver = poValue->Get(isolate).As(); @@ -1048,6 +1067,9 @@ bool IsKVOSubclassOf(Class klass, Class base) { objcWrapper->SetBornOnRuntimeThread(); ObjectManager::ProtectIfNativelyRetained(isolate, target, objcWrapper); } + if (wrapper->Type() == WrapperType::ObjCObject) { + WrapperLifetime::Adopt(isolate, static_cast(wrapper), poValue, target); + } } } else { tns::SetValue(isolate, receiver, wrapper); @@ -1109,8 +1131,14 @@ bool IsKVOSubclassOf(Class klass, Class base) { if (it == cache->Instances.end()) { return nullptr; } + if (it->second->IsEmpty()) { + // A dead wrapper whose release is queued (WrapperLifetime). + cache->Instances.erase(it); + return nullptr; + } BaseDataWrapper* wrapper = tns::GetValue(isolate, it->second->Get(isolate)); + WrapperLifetime::Escape(wrapper); if (wrapper != nullptr && wrapper->Type() == WrapperType::ObjCObject) { Class expected = static_cast(wrapper)->Klass(); // A KVO-style isa swizzle replaces the class in place but keeps -class @@ -1131,6 +1159,26 @@ bool IsKVOSubclassOf(Class klass, Class base) { return it->second; } +Local ArgConverter::WrapCallbackSelf(Local context, id self) { + Isolate* isolate = v8::Isolate::GetCurrent(); + auto cache = Caches::Get(isolate); + auto it = cache->Instances.find(self); + if (it != cache->Instances.end() && it->second->IsEmpty()) { + // A dead wrapper whose release is queued (WrapperLifetime). + cache->Instances.erase(it); + it = cache->Instances.end(); + } + if (it != cache->Instances.end()) { + Local existing = it->second->Get(isolate).As(); + WrapperLifetime::EscapeValue(isolate, existing); + return existing; + } + ObjCDataWrapper* wrapper = new ObjCDataWrapper(self); + Local result = CreateJsWrapper(context, wrapper, Local()).As(); + tns::DeleteWrapperIfUnused(isolate, result, wrapper); + return result; +} + const Meta* ArgConverter::FindMeta(Class klass, const TypeEncoding* typeEncoding) { if (typeEncoding != nullptr && typeEncoding->type == BinaryTypeEncodingType::InterfaceDeclarationReference) { @@ -1240,6 +1288,13 @@ bool IsKVOSubclassOf(Class klass, Class base) { // Native code usually still holds the object (it is mid-initialization or // owned by whoever called in), and its JS state must outlive this call: the // handle stays strong until the Instances entry is the object's only owner. + // A wrapper a lifetime mode roots keeps the mode's own lifetime instead. + if (wrapper->LifetimeState() != nullptr) { + if (ObjectWeakCallbackState* state = WrapperLifetime::Relinquish(wrapper)) { + ObjectManager::ManageOwnership(isolate, wrapper, state); + } + return result; + } auto it = cache->Instances.find(self); if (it != cache->Instances.end() && it->second->IsWeak()) { ObjectManager::ManageOwnership(isolate, wrapper, @@ -1313,8 +1368,10 @@ bool IsKVOSubclassOf(Class klass, Class base) { std::shared_ptr cache = Caches::Get(isolate); auto it = cache->Instances.find(obj); - if (it != cache->Instances.end()) { - args.GetReturnValue().Set(it->second->Get(isolate)); + if (it != cache->Instances.end() && !it->second->IsEmpty()) { + Local existing = it->second->Get(isolate); + WrapperLifetime::EscapeValue(isolate, existing); + args.GetReturnValue().Set(existing); return v8::Intercepted::kYes; } diff --git a/NativeScript/runtime/ClassBuilder.mm b/NativeScript/runtime/ClassBuilder.mm index 05af7a68e..9fdd80234 100644 --- a/NativeScript/runtime/ClassBuilder.mm +++ b/NativeScript/runtime/ClassBuilder.mm @@ -13,6 +13,7 @@ #include "ObjectManager.h" #include "Runtime.h" #include "TNSDerivedClass.h" +#include "WrapperLifetime.h" using namespace v8; @@ -311,78 +312,35 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { class_addMethod(object_getClass(extendedClass), @selector(initialize), newInitialize, "v@:"); - /// We swizzle the retain and release methods for the following reason: - /// When we instantiate a native class via a JavaScript call we add it to the object - /// instances map thus incrementing the retainCount by 1. Then, when the native object is - /// referenced somewhere else its count will become more than 1. Since we want to keep the - /// corresponding JavaScript object alive even if it is not used anywhere, we call GcProtect - /// on it. Whenever the native object is released so that its retainCount is 1 (the object - /// instances map), we unprotect the corresponding JavaScript object in order to make both - /// of them destroyable/GC-able. When the JavaScript object is GC-ed we release the native - /// counterpart as well. - id (*retain)(id, SEL) = - (id (*)(id, SEL))FindNotOverridenMethod(extendedClass, @selector(retain)); - IMP newRetain = imp_implementationWithBlock(^id(id self) { - if (!isolateWrapper.IsValid()) { - return retain(self, @selector(retain)); - } - if ([self retainCount] == 1) { - auto runtime = Runtime::GetRuntime(isolate); - auto runtimeLoop = runtime->RuntimeLoop(); - void* weakSelf = (__bridge void*)self; - auto gcProtect = [isolateWrapper, weakSelf, isolate]() { - auto innerCache = isolateWrapper.GetCache(); - auto it = innerCache->Instances.find((id)weakSelf); - if (it != innerCache->Instances.end()) { - v8::Locker locker(isolate); - Isolate::Scope isolate_scope(isolate); - HandleScope handle_scope(isolate); - Local value = it->second->Get(isolate); - BaseDataWrapper* wrapper = tns::GetValue(isolate, value); - if (wrapper != nullptr && wrapper->Type() == WrapperType::ObjCObject) { - ObjCDataWrapper* objcWrapper = static_cast(wrapper); - if (objcWrapper->OwnershipState() != nullptr) { - ObjectManager::ReconcileOwnership(isolate, objcWrapper); - } else { - objcWrapper->GcProtect(); - } - } - } - }; - // After the retain: reconciling reads the new retain count. - id result = retain(self, @selector(retain)); - if (CFRunLoopGetCurrent() != runtimeLoop) { - // bare entry: the closure does its own Locker ceremony, exactly - // like the performed block it replaces - runtime->GetEventLoop()->PostInternalBare(gcProtect); - } else { - gcProtect(); + // The rooted lifetime mode reads native ownership from retain counts + // when a major collection starts, so it needs no swizzle. + if (GetWrapperLifetimeMode() == WrapperLifetimeMode::kResurrecting) { + /// We swizzle the retain and release methods for the following reason: + /// When we instantiate a native class via a JavaScript call we add it to the object + /// instances map thus incrementing the retainCount by 1. Then, when the native object is + /// referenced somewhere else its count will become more than 1. Since we want to keep the + /// corresponding JavaScript object alive even if it is not used anywhere, we call + /// GcProtect on it. Whenever the native object is released so that its retainCount is 1 + /// (the object instances map), we unprotect the corresponding JavaScript object in order + /// to make both of them destroyable/GC-able. When the JavaScript object is GC-ed we + /// release the native counterpart as well. + id (*retain)(id, SEL) = + (id (*)(id, SEL))FindNotOverridenMethod(extendedClass, @selector(retain)); + IMP newRetain = imp_implementationWithBlock(^id(id self) { + if (!isolateWrapper.IsValid()) { + return retain(self, @selector(retain)); } - return result; - } - - return retain(self, @selector(retain)); - }); - class_addMethod(extendedClass, @selector(retain), newRetain, "@@:"); - - void (*release)(id, SEL) = - (void (*)(id, SEL))FindNotOverridenMethod(extendedClass, @selector(release)); - IMP newRelease = imp_implementationWithBlock(^(id self) { - if (!isolateWrapper.IsValid()) { - release(self, @selector(release)); - return; - } - - if ([self retainCount] == 2) { - void* weakSelf = (__bridge void*)self; - auto gcUnprotect = [isolateWrapper, weakSelf, isolate]() { - auto innerCache = isolateWrapper.GetCache(); - auto it = innerCache->Instances.find((id)weakSelf); - if (it != innerCache->Instances.end()) { - v8::Locker locker(isolate); - Isolate::Scope isolate_scope(isolate); - HandleScope handle_scope(isolate); - if (it->second != nullptr) { + if ([self retainCount] == 1) { + auto runtime = Runtime::GetRuntime(isolate); + auto runtimeLoop = runtime->RuntimeLoop(); + void* weakSelf = (__bridge void*)self; + auto gcProtect = [isolateWrapper, weakSelf, isolate]() { + auto innerCache = isolateWrapper.GetCache(); + auto it = innerCache->Instances.find((id)weakSelf); + if (it != innerCache->Instances.end()) { + v8::Locker locker(isolate); + Isolate::Scope isolate_scope(isolate); + HandleScope handle_scope(isolate); Local value = it->second->Get(isolate); BaseDataWrapper* wrapper = tns::GetValue(isolate, value); if (wrapper != nullptr && wrapper->Type() == WrapperType::ObjCObject) { @@ -390,32 +348,79 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { if (objcWrapper->OwnershipState() != nullptr) { ObjectManager::ReconcileOwnership(isolate, objcWrapper); } else { - objcWrapper->GcUnprotect(); + objcWrapper->GcProtect(); } } } + }; + // After the retain: reconciling reads the new retain count. + id result = retain(self, @selector(retain)); + if (CFRunLoopGetCurrent() != runtimeLoop) { + // bare entry: the closure does its own Locker ceremony, exactly + // like the performed block it replaces + runtime->GetEventLoop()->PostInternalBare(gcProtect); + } else { + gcProtect(); } - }; - auto runtime = Runtime::GetRuntime(isolate); - auto runtimeLoop = runtime->RuntimeLoop(); - // After the release: reconciling reads the new retain count, and - // the Instances entry still holds the object. - release(self, @selector(release)); - if (CFRunLoopGetCurrent() != runtimeLoop) { - // bare entry: the closure does its own Locker ceremony, exactly - // like the performed block it replaces - runtime->GetEventLoop()->PostInternalBare(gcUnprotect); - } else { - gcUnprotect(); + return result; } - return; - } - release(self, @selector(release)); - }); - class_addMethod(extendedClass, @selector(release), newRelease, "v@:"); - if (auto* tracked = Caches::StateFor(isolate)) { - tracked->classes.insert((__bridge void*)extendedClass); + return retain(self, @selector(retain)); + }); + class_addMethod(extendedClass, @selector(retain), newRetain, "@@:"); + + void (*release)(id, SEL) = + (void (*)(id, SEL))FindNotOverridenMethod(extendedClass, @selector(release)); + IMP newRelease = imp_implementationWithBlock(^(id self) { + if (!isolateWrapper.IsValid()) { + release(self, @selector(release)); + return; + } + + if ([self retainCount] == 2) { + void* weakSelf = (__bridge void*)self; + auto gcUnprotect = [isolateWrapper, weakSelf, isolate]() { + auto innerCache = isolateWrapper.GetCache(); + auto it = innerCache->Instances.find((id)weakSelf); + if (it != innerCache->Instances.end()) { + v8::Locker locker(isolate); + Isolate::Scope isolate_scope(isolate); + HandleScope handle_scope(isolate); + if (it->second != nullptr) { + Local value = it->second->Get(isolate); + BaseDataWrapper* wrapper = tns::GetValue(isolate, value); + if (wrapper != nullptr && wrapper->Type() == WrapperType::ObjCObject) { + ObjCDataWrapper* objcWrapper = static_cast(wrapper); + if (objcWrapper->OwnershipState() != nullptr) { + ObjectManager::ReconcileOwnership(isolate, objcWrapper); + } else { + objcWrapper->GcUnprotect(); + } + } + } + } + }; + auto runtime = Runtime::GetRuntime(isolate); + auto runtimeLoop = runtime->RuntimeLoop(); + // After the release: reconciling reads the new retain count, and + // the Instances entry still holds the object. + release(self, @selector(release)); + if (CFRunLoopGetCurrent() != runtimeLoop) { + // bare entry: the closure does its own Locker ceremony, exactly + // like the performed block it replaces + runtime->GetEventLoop()->PostInternalBare(gcUnprotect); + } else { + gcUnprotect(); + } + return; + } + + release(self, @selector(release)); + }); + class_addMethod(extendedClass, @selector(release), newRelease, "v@:"); + if (auto* tracked = Caches::StateFor(isolate)) { + tracked->classes.insert((__bridge void*)extendedClass); + } } info.GetReturnValue().SetUndefined(); @@ -1106,11 +1111,16 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { } Class ClassBuilder::FindNativeClass(Class klass) { - while (class_conformsToProtocol(klass, @protocol(TNSDerivedClass))) { - klass = class_getSuperclass(klass); + // Walks the whole chain: key-value observing puts a subclass that does not + // conform below the JS class, and class_conformsToProtocol does not look at + // superclasses. + Class native = klass; + for (Class cls = klass; cls != nil; cls = class_getSuperclass(cls)) { + if (class_conformsToProtocol(cls, @protocol(TNSDerivedClass))) { + native = class_getSuperclass(cls); + } } - - return klass; + return native; } bool ClassBuilder::TracksNativeRetains(Isolate* isolate, Class klass) { diff --git a/NativeScript/runtime/DataWrapper.h b/NativeScript/runtime/DataWrapper.h index e90d38d67..d0a6bd036 100644 --- a/NativeScript/runtime/DataWrapper.h +++ b/NativeScript/runtime/DataWrapper.h @@ -403,6 +403,7 @@ class ObjCDataWrapper : public BaseDataWrapper { data_(data), typeEncoding_(typeEncoding), klass_(object_getClass(data)) {} + ~ObjCDataWrapper(); const WrapperType Type() { return WrapperType::ObjCObject; } @@ -434,6 +435,13 @@ class ObjCDataWrapper : public BaseDataWrapper { ObjectWeakCallbackState* OwnershipState() { return this->ownershipState_; } void SetOwnershipState(ObjectWeakCallbackState* state) { this->ownershipState_ = state; } + // Registration state of a wrapper adopted by WrapperLifetime; null otherwise. + // A wrapper has at most one of OwnershipState and LifetimeState. + ObjectWeakCallbackState* LifetimeState() { return this->lifetimeState_; } + void SetLifetimeState(ObjectWeakCallbackState* state) { + this->lifetimeState_ = state; + } + // A wrapper that holds no reference to its object (one made for an object // already deallocating), so nothing may release on its behalf. bool IsBorrowed() { return this->borrowed_; } @@ -444,6 +452,7 @@ class ObjCDataWrapper : public BaseDataWrapper { bool borrowed_ = false; bool bornOnRuntimeThread_; ObjectWeakCallbackState* ownershipState_ = nullptr; + ObjectWeakCallbackState* lifetimeState_ = nullptr; id data_; const tns::TypeEncoding* typeEncoding_; Class klass_; diff --git a/NativeScript/runtime/Helpers.h b/NativeScript/runtime/Helpers.h index 70a686044..c1f78c4ca 100644 --- a/NativeScript/runtime/Helpers.h +++ b/NativeScript/runtime/Helpers.h @@ -297,6 +297,20 @@ v8::Local GetCreationContextOrCurrent(v8::Isolate* isolate, void SetValue(v8::Isolate* isolate, const v8::Local& obj, BaseDataWrapper* value); BaseDataWrapper* GetValue(v8::Isolate* isolate, const v8::Local& val); +// A tagged pointer carries its value in the pointer itself: it is never +// retained, released or deallocated, and its retain count means nothing. Only +// x86_64 macOS and Mac Catalyst tag the low bit; every iOS target, the x86_64 +// simulator included, tags the high bit. +inline bool IsTaggedPointer(id obj) { + // Through void*: clang rejects bit tests on ObjC object pointers. + uintptr_t bits = reinterpret_cast(static_cast(obj)); +#if defined(__x86_64__) && (TARGET_OS_OSX || TARGET_OS_MACCATALYST) + return (bits & 1) != 0; +#else + return (bits >> 63) != 0; +#endif +} + // The receiver a `this.super` alias (ClassBuilder::SuperAccessorGetterCallback) // stands for, or empty when obj is not one. An alias keeps its receiver in // internal field 0 and the string "super" in internal field 1; it owns no diff --git a/NativeScript/runtime/Interop.mm b/NativeScript/runtime/Interop.mm index ea51039cd..fc4cf2414 100644 --- a/NativeScript/runtime/Interop.mm +++ b/NativeScript/runtime/Interop.mm @@ -20,6 +20,7 @@ #include "SymbolIterator.h" #include "SymbolLoader.h" #include "UnmanagedType.h" +#include "WrapperLifetime.h" #include "robin_hood.h" using namespace v8; @@ -818,6 +819,7 @@ static bool SnapshotArrayLike(Isolate* isolate, Local object, LocalType() == WrapperType::ObjCObject) { ObjCDataWrapper* objCDataWrapper = static_cast(wrapper); + WrapperLifetime::Escape(objCDataWrapper); id data = objCDataWrapper->Data(); Interop::SetValue(dest, data); } else if (wrapper->Type() == WrapperType::ObjCClass) { @@ -915,6 +917,7 @@ static bool SnapshotArrayLike(Isolate* isolate, Local object, LocalType()) { case WrapperType::ObjCObject: { ObjCDataWrapper* wr = static_cast(wrapper); + WrapperLifetime::Escape(wr); return wr->Data(); break; } diff --git a/NativeScript/runtime/MetadataBuilder.mm b/NativeScript/runtime/MetadataBuilder.mm index 2bc2ffad1..4b55a8ebe 100644 --- a/NativeScript/runtime/MetadataBuilder.mm +++ b/NativeScript/runtime/MetadataBuilder.mm @@ -1507,20 +1507,8 @@ void ReplaceKeepingOriginal(Class klass, SEL selector, const char* selectorName, Local res; id thiz = *static_cast(argValues[0]); - auto cache = Caches::Get(isolate); - auto it = cache->Instances.find(thiz); - Local v8Context = Caches::Get(isolate)->GetContext(); - ObjCDataWrapper* wrapper = nullptr; - Local self_ = - it != cache->Instances.end() - ? it->second->Get(isolate).As() - : ArgConverter::CreateJsWrapper(v8Context, wrapper = new ObjCDataWrapper(thiz), - Local()) - .As(); - if (wrapper != nullptr) { - tns::DeleteWrapperIfUnused(isolate, self_, wrapper); - } + Local self_ = ArgConverter::WrapCallbackSelf(v8Context, thiz); TryCatch tc(isolate); if (!getterFunc->Call(v8Context, self_, 0, nullptr).ToLocal(&res)) { NSException* ex = ArgConverter::HandleBoundaryException(v8Context, tc); @@ -1580,18 +1568,7 @@ void ReplaceKeepingOriginal(Class klass, SEL selector, const char* selectorName, Local v8Context = Caches::Get(isolate)->GetContext(); id thiz = *static_cast(argValues[0]); - auto cache = Caches::Get(isolate); - auto it = cache->Instances.find(thiz); - ObjCDataWrapper* wrapper = nullptr; - Local self_ = - it != cache->Instances.end() - ? it->second->Get(isolate).As() - : ArgConverter::CreateJsWrapper(v8Context, wrapper = new ObjCDataWrapper(thiz), - Local()) - .As(); - if (wrapper != nullptr) { - tns::DeleteWrapperIfUnused(isolate, self_, wrapper); - } + Local self_ = ArgConverter::WrapCallbackSelf(v8Context, thiz); uint8_t* argBuffer = (uint8_t*)argValues[2]; const TypeEncoding* typeEncoding = context->meta_->setter()->encodings()->first()->next(); diff --git a/NativeScript/runtime/NsBuiltinModules.cpp b/NativeScript/runtime/NsBuiltinModules.cpp index d35f4cf7d..28062278e 100644 --- a/NativeScript/runtime/NsBuiltinModules.cpp +++ b/NativeScript/runtime/NsBuiltinModules.cpp @@ -16,6 +16,7 @@ #include "URLImpl.h" #include "URLSearchParamsImpl.h" #include "Worker.h" +#include "WrapperLifetime.h" using namespace v8; @@ -103,6 +104,9 @@ std::string Canonicalize(const std::string& specifier) { constexpr const char* kReleasedObjectPolicyKey = "releasedObjectPolicy"; constexpr const char* kDebugKey = "debug"; constexpr const char* kWrapperLifetimeWarningsKey = "wrapperLifetimeWarnings"; +// Read-only: the lifetime mode is fixed at startup from the app config. +constexpr const char* kWrapperLifetimeModeKey = "wrapperLifetimeMode"; +constexpr const char* kWrapperLifetimeScopeKey = "wrapperLifetimeScope"; void ThrowTypeError(Isolate* isolate, const std::string& message) { isolate->ThrowException( @@ -141,6 +145,13 @@ void SetConfigCallback(const FunctionCallbackInfo& info) { } return; } + if (key == kWrapperLifetimeModeKey || key == kWrapperLifetimeScopeKey) { + ThrowTypeError( + isolate, + "'" + key + + "' is read-only; set \"wrapperLifetime\" in the app config"); + return; + } if (key == kWrapperLifetimeWarningsKey) { if (!EnsureMainIsolateWrite(isolate, key)) { return; @@ -204,6 +215,17 @@ void GetConfigCallback(const FunctionCallbackInfo& info) { info.GetReturnValue().Set(tns::WrapperLifetimeWarningsEnabled()); return; } + if (key == kWrapperLifetimeModeKey) { + info.GetReturnValue().Set(tns::ToV8String( + isolate, tns::WrapperLifetimeModeName(tns::GetWrapperLifetimeMode()))); + return; + } + if (key == kWrapperLifetimeScopeKey) { + info.GetReturnValue().Set(tns::ToV8String( + isolate, + tns::WrapperLifetimeScopeName(tns::GetWrapperLifetimeScope()))); + return; + } ThrowTypeError(isolate, "Unknown runtime config key: '" + key + "'"); } @@ -225,6 +247,9 @@ void GetWrapperLifetimeStatsCallback(const FunctionCallbackInfo& info) { {"releasedAccesses", stats->releasedAccesses}, {"stateLostCandidates", stats->stateLostCandidates}, {"stateLostConfirmed", stats->stateLostConfirmed}, + {"promotions", stats->promotions}, + {"demotions", stats->demotions}, + {"queuedReleases", stats->queuedReleases}, }; for (const auto& [name, value] : fields) { result diff --git a/NativeScript/runtime/ObjectManager.h b/NativeScript/runtime/ObjectManager.h index ddd866f2d..7aef0ebbc 100644 --- a/NativeScript/runtime/ObjectManager.h +++ b/NativeScript/runtime/ObjectManager.h @@ -3,6 +3,9 @@ #include +#include +#include + #include "Common.h" namespace tns { @@ -41,6 +44,18 @@ struct ObjectWeakCallbackState { // 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 + // under a phantom-callback mode). The JS object is unreadable after its + // phantom callback, so the wrapper and object are cached here. + ObjCDataWrapper* lifetimeWrapper_ = nullptr; + id lifetimeTarget_ = nullptr; + // WrapperLifetime's cross-isolate retain counter for lifetimeTarget_. + std::atomic* runtimeRetains_ = nullptr; + // May be rooted; scanned when a major collection starts. + bool lifetimeTracked_ = false; + // The handle is currently strong. + bool lifetimeStrong_ = false; }; class ObjectManager { @@ -63,6 +78,12 @@ class ObjectManager { // still alive a runloop turn later (see WrapperLifetimeWarningsEnabled). uint64_t stateLostCandidates = 0; uint64_t stateLostConfirmed = 0; + // Rooted mode (WrapperLifetime): wrappers made strong because native code + // owns their object, made weak because it no longer does, and dead + // wrappers whose object was queued for release. + uint64_t promotions = 0; + uint64_t demotions = 0; + uint64_t queuedReleases = 0; }; static LifetimeStats* GetLifetimeStats(v8::Isolate* isolate); @@ -86,6 +107,8 @@ class ObjectManager { // Requires the isolate locked and entered, on any thread. static void ReconcileOwnership(v8::Isolate* isolate, ObjCDataWrapper* wrapper); + // Removes a registration from the teardown list. + static void Unlink(ObjectWeakCallbackState* state); // A collection can run on any thread that holds the isolate's Locker, but // the native releases it causes are handed to the runtime's thread. A new @@ -106,6 +129,8 @@ class ObjectManager { // swizzled-prefixed alias. Null for NSTimer.alloc()'s placeholder, whose // -retainCount does not return, and for classes without a -retainCount. // Walks method lists, so callers cache the result per class. + // Unsupported: a native override that messages [super retainCount] still + // reaches a JS replacement on an ancestor, which then runs where JS may not. static IMP NativeRetainCountImp(Class cls); private: diff --git a/NativeScript/runtime/ObjectManager.mm b/NativeScript/runtime/ObjectManager.mm index a00bfa20a..8fe282a48 100644 --- a/NativeScript/runtime/ObjectManager.mm +++ b/NativeScript/runtime/ObjectManager.mm @@ -16,6 +16,7 @@ #include "FFICall.h" #include "Helpers.h" #include "Runtime.h" +#include "WrapperLifetime.h" // Exported by libobjc; not declared in a public header for MRC code. extern "C" id objc_initWeak(id* location, id value); @@ -121,16 +122,6 @@ void ReconcileOwnershipBeforeGC(Isolate* isolate, GCType, GCCallbackFlags) { } }; -bool IsTaggedPointer(id obj) { - // Through void*: clang rejects bit tests on ObjC object pointers. - uintptr_t bits = reinterpret_cast(static_cast(obj)); -#if defined(__x86_64__) && (TARGET_OS_OSX || TARGET_OS_MACCATALYST) - return (bits & 1) != 0; -#else - return (bits >> 63) != 0; -#endif -} - bool ReleasesPendingOnRuntimeThread(Isolate* isolate); bool PostStateLostConfirmation(Isolate* isolate); @@ -254,6 +245,14 @@ void LinkRegistered(v8::Isolate* isolate, ObjectWeakCallbackState* state) { *state->head_ = state; } +void UnlinkRegistered(ObjectWeakCallbackState* state); + +} // namespace + +void ObjectManager::Unlink(ObjectWeakCallbackState* state) { UnlinkRegistered(state); } + +namespace { + void UnlinkRegistered(ObjectWeakCallbackState* state) { if (state->head_ == nullptr) { return; @@ -382,6 +381,7 @@ void BlockReleaseOnRuntimeThread(Isolate* isolate, const void* block, bool bornO tns::InitReleasedMarkers(isolate); Caches::StateFor(isolate); tns::WrapperLifetimeWarningsEnabled(); + WrapperLifetime::Init(isolate); } std::shared_ptr> ObjectManager::Register(Local context, @@ -444,6 +444,10 @@ void DisposeHandle(v8::Isolate* isolate, // claim every state up front: disposing one entry can re-enter JS from // -dealloc and reach __releaseNativeCounterpart for any other entry this // walk still owns. + // Wrappers that died before teardown are already off the list, waiting in + // the release queue. + WrapperLifetime::DrainForTeardown(isolate); + ObjectWeakCallbackState* state = cache->ObjectManagedValues; cache->ObjectManagedValues = nullptr; for (ObjectWeakCallbackState* claimed = state; claimed != nullptr; claimed = claimed->next_) { @@ -454,13 +458,17 @@ void DisposeHandle(v8::Isolate* isolate, ObjectWeakCallbackState* next = state->next_; std::shared_ptr> handle = state->target_; + bool released = false; + WrapperLifetime::DropRetainBeforeDisposal(state); if (handle != nullptr && !handle->IsEmpty()) { ObjectManager::DisposeValue(isolate, handle->Get(isolate), true); + released = true; if (handle->IsWeak()) { handle->ClearWeak(); } handle->Reset(); } + WrapperLifetime::Retire(isolate, state, released); delete state; state = next; @@ -828,14 +836,31 @@ void DisposeHandle(v8::Isolate* isolate, ForgetOwnership(isolate, managed); delete managed; objcWrapper->SetOwnershipState(nullptr); + } else if (ObjectWeakCallbackState* adopted = objcWrapper->LifetimeState()) { + // 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. + return; + } + if (it != cache->Instances.end() && it->second == adopted->target_) { + cache->Instances.erase(it); + } + adopted->target_->Reset(); + WrapperLifetime::Forget(isolate, adopted); + objcWrapper->SetLifetimeState(nullptr); + UnlinkRegistered(adopted); + delete adopted; } else if (it != cache->Instances.end()) { std::shared_ptr> handle = it->second; + bool wasWeak = handle->IsWeak(); ObjectWeakCallbackState* state = - handle->IsWeak() ? handle->ClearWeak() : nullptr; + wasWeak ? handle->ClearWeak() : nullptr; if (state != nullptr && state->disposing_) { - // Reached from a -dealloc running inside this handle's own finalizer: - // that frame already released the native counterpart and owns the - // state, so restore the weakness and let it finish. + // Reached from a -dealloc running inside this handle's own finalizer + // or the teardown walk: that frame already released the native + // counterpart and owns the state, so restore the weakness and let it + // finish. handle->SetWeak(state, FinalizerCallback, WeakCallbackType::kFinalizer); return; } diff --git a/NativeScript/runtime/Reference.cpp b/NativeScript/runtime/Reference.cpp index d039b262e..72c3acdfc 100644 --- a/NativeScript/runtime/Reference.cpp +++ b/NativeScript/runtime/Reference.cpp @@ -6,6 +6,7 @@ #include "Interop.h" #include "ObjectManager.h" #include "Pointer.h" +#include "WrapperLifetime.h" using namespace v8; @@ -335,6 +336,7 @@ void* Reference::GetWrappedPointer(Local context, if (wrappedValue->Type() == WrapperType::ObjCObject) { ObjCDataWrapper* dataWrapper = static_cast(wrappedValue); + WrapperLifetime::Escape(dataWrapper); id target = dataWrapper->Data(); void* handle = malloc(sizeof(id)); *static_cast(handle) = target; diff --git a/NativeScript/runtime/WrapperLifetime.h b/NativeScript/runtime/WrapperLifetime.h new file mode 100644 index 000000000..82158bbc0 --- /dev/null +++ b/NativeScript/runtime/WrapperLifetime.h @@ -0,0 +1,126 @@ +#ifndef WrapperLifetime_h +#define WrapperLifetime_h + +#include + +#include "Common.h" +#include "DataWrapper.h" +#include "Helpers.h" +#include "ObjectManager.h" + +namespace tns { + +class ObjCDataWrapper; + +// How ObjC object wrappers live. Process-wide, read once from the app config +// "wrapperLifetime": { "mode": ..., "scope": ... } and fixed for the process. +enum class WrapperLifetimeMode { + // kFinalizer callbacks; a natively retained JS-extended instance refuses + // disposal and is resurrected (ObjectManager::DisposeValue). + kResurrecting, + // Phantom callbacks, no resurrection: a wrapper is a strong root while + // something other than the runtime retains its object, weak otherwise. + kRooted, +}; + +enum class WrapperLifetimeScope { + // Only JS-extended instances (TNSDerivedClass) are rooted; other wrappers are + // weak and die with their JS references, except receivers of JS methods + // native code calls, which keep the default mode's ownership tracking + // (ArgConverter::WrapNativeCallbackSelf). + kExtended, + kAll, +}; + +namespace detail { +// Written once, by the first WrapperLifetime::Init, before any wrapper exists. +inline WrapperLifetimeMode wrapperLifetimeMode = + WrapperLifetimeMode::kResurrecting; +inline WrapperLifetimeScope wrapperLifetimeScope = + WrapperLifetimeScope::kExtended; +} // namespace detail + +inline WrapperLifetimeMode GetWrapperLifetimeMode() { + return detail::wrapperLifetimeMode; +} +inline WrapperLifetimeScope GetWrapperLifetimeScope() { + return detail::wrapperLifetimeScope; +} +const char* WrapperLifetimeModeName(WrapperLifetimeMode mode); +const char* WrapperLifetimeScopeName(WrapperLifetimeScope scope); + +class WrapperLifetime { + public: + static void Init(v8::Isolate* isolate); + + // A newly wrapped ObjC object: `handle` is its Instances entry, registered by + // ObjectManager::Register and holding the entry's +1 on `target`. + static void Adopt(v8::Isolate* isolate, ObjCDataWrapper* wrapper, + const std::shared_ptr>& handle, + id target); + + // The object crossed the JS/native boundary: native code returned it to JS, + // or received it as a receiver, argument, return value of a JS-implemented + // member, collection element or reference target. A weak, rootable wrapper + // becomes strong until the next major collection re-evaluates it. + static inline void Escape(BaseDataWrapper* wrapper) { + if (GetWrapperLifetimeMode() == WrapperLifetimeMode::kRooted && + wrapper != nullptr && wrapper->Type() == WrapperType::ObjCObject) { + EscapeSlow(static_cast(wrapper)); + } + } + + // Escape for the wrapper `value` holds, looked up only in the rooted mode. + static inline void EscapeValue(v8::Isolate* isolate, + const v8::Local& value) { + if (GetWrapperLifetimeMode() == WrapperLifetimeMode::kRooted) { + Escape(tns::GetValue(isolate, value)); + } + } + + // Releases the native objects of wrappers that died. Runs only where JS may + // run: release can reach a JS-implemented -dealloc. + static void DrainReleases(v8::Isolate* isolate); + + // JS->native call entry: a long synchronous stretch of JS must not hold dead + // objects until it yields. The gate is process-wide; while another isolate + // has queued releases this costs one state lookup per call. + static inline void DrainAtCallEntry(v8::Isolate* isolate) { + if (pendingReleaseIsolates_.load(std::memory_order_relaxed) > 0) { + DrainReleases(isolate); + } + } + + // Gives an adopted wrapper that is not rooted back to ObjectManager: returns + // its registration with the handle strong, for + // ObjectManager::ManageOwnership. Null when the mode keeps the wrapper. + static ObjectWeakCallbackState* Relinquish(ObjCDataWrapper* wrapper); + + // __releaseNativeCounterpart retired this adopted wrapper's registration. + static void Forget(v8::Isolate* isolate, ObjectWeakCallbackState* state); + + // Teardown, before the registration walk: releases what the queue still + // holds. The isolate is already invalidated and its event loop stopped, so + // this releases inline on the tearing-down thread. + static void DrainForTeardown(v8::Isolate* isolate); + + // Teardown: called before DisposeValue releases an adopted wrapper's object, + // since the runtime's retain must be dropped before the native one. + static void DropRetainBeforeDisposal(ObjectWeakCallbackState* state); + + // Teardown (ObjectManager::DisposeAllRegistered) disposes an adopted wrapper; + // `released` tells whether DisposeValue already released the object. + static void Retire(v8::Isolate* isolate, ObjectWeakCallbackState* state, + bool released); + + private: + static void EscapeSlow(ObjCDataWrapper* wrapper); + + public: + // Isolates whose release queue is not empty. + static std::atomic pendingReleaseIsolates_; +}; + +} // namespace tns + +#endif /* WrapperLifetime_h */ diff --git a/NativeScript/runtime/WrapperLifetime.mm b/NativeScript/runtime/WrapperLifetime.mm new file mode 100644 index 000000000..d55680389 --- /dev/null +++ b/NativeScript/runtime/WrapperLifetime.mm @@ -0,0 +1,450 @@ +#include "WrapperLifetime.h" +#import +#include +#include +#include +#include +#include +#include +#include +#include "Caches.h" +#include "ClassBuilder.h" +#include "DataWrapper.h" +#include "Helpers.h" +#include "Runtime.h" +#import "TNSDerivedClass.h" + +using namespace v8; + +namespace tns { + +std::atomic WrapperLifetime::pendingReleaseIsolates_{0}; + +namespace { + +std::once_flag configOnce_; + +void ReadConfig() { + id config = Runtime::GetAppConfigValue("wrapperLifetime"); + if (![config isKindOfClass:[NSDictionary class]]) { + return; + } + id mode = ((NSDictionary*)config)[@"mode"]; + if (mode != nil && ![mode isKindOfClass:[NSString class]]) { + Log("NativeScript: wrapperLifetime mode must be a string; using \"resurrecting\"."); + } else if (mode != nil) { + if ([mode isEqualToString:@"rooted"]) { + detail::wrapperLifetimeMode = WrapperLifetimeMode::kRooted; + } else if (![mode isEqualToString:@"resurrecting"]) { + Log("NativeScript: unknown wrapperLifetime mode \"%s\"; using \"resurrecting\".", + [mode UTF8String]); + } + } + id scope = ((NSDictionary*)config)[@"scope"]; + if (scope != nil && ![scope isKindOfClass:[NSString class]]) { + Log("NativeScript: wrapperLifetime scope must be a string; using \"extended\"."); + } else if (scope != nil) { + if ([scope isEqualToString:@"all"]) { + detail::wrapperLifetimeScope = WrapperLifetimeScope::kAll; + } else if (![scope isEqualToString:@"extended"]) { + Log("NativeScript: unknown wrapperLifetime scope \"%s\"; using \"extended\".", + [scope UTF8String]); + } + } +} + +// Per-isolate state of the rooted mode. +struct RootedState { + ~RootedState() { + if (!releases.empty()) { + WrapperLifetime::pendingReleaseIsolates_.fetch_sub(1, std::memory_order_relaxed); + } + } + + // Adopted wrappers that may be rooted; scanned when a major collection starts. + std::unordered_set tracked; + // Wrappers whose JS object died; their objects are released by DrainReleases. + std::vector releases; + bool draining = false; + bool drainPosted = false; + // ObjectManager::NativeRetainCountImp per class: + // the scan runs in a GC prologue, where JS may not run. + std::unordered_map retainCountImps; +}; + +// Retains the runtime holds on an object across every isolate: one per +// Instances entry. A wrapper is natively owned when the object's retain count +// exceeds this. Readers in the GC prologue use the cached atomic without the +// lock; entries are only erased when their count reaches zero. Entries Adopt +// skipped (handles ObjectManager did not register) are not counted, so their +// retain reads as a native owner: such an object stays rooted in other +// isolates (a leak, never an early release). +// +// The low 32 bits count retains, the high 32 bits count changes. Every caller +// takes its native retain before acquiring and drops before releasing, and the +// scan reads the counter on both sides of -retainCount: a change in between +// keeps the wrapper strong, so no adopt or release on another thread can make +// a natively owned object read as unowned. +constexpr uint64_t kRetainAcquired = (uint64_t{1} << 32) + 1; +constexpr uint64_t kRetainDropped = (uint64_t{1} << 32) - 1; + +uint32_t RetainsIn(uint64_t value) { return static_cast(value); } + +std::mutex runtimeRetainsMutex_; +std::unordered_map>> runtimeRetains_; + +std::atomic* AcquireRuntimeRetain(id obj) { + std::lock_guard lock(runtimeRetainsMutex_); + std::unique_ptr>& slot = runtimeRetains_[(__bridge void*)obj]; + if (slot == nullptr) { + slot = std::make_unique>(0); + } + slot->fetch_add(kRetainAcquired); + return slot.get(); +} + +void DropRuntimeRetain(id obj, std::atomic* counter) { + if (counter == nullptr) { + return; + } + std::lock_guard lock(runtimeRetainsMutex_); + if (RetainsIn(counter->fetch_add(kRetainDropped)) == 1) { + auto it = runtimeRetains_.find((__bridge void*)obj); + if (it != runtimeRetains_.end() && it->second.get() == counter) { + runtimeRetains_.erase(it); + } + } +} + +bool IsBlock(id obj) { + static Class blockClass = objc_getClass("NSBlock"); + for (Class cls = object_getClass(obj); cls != nil; cls = class_getSuperclass(cls)) { + if (cls == blockClass) { + return true; + } + } + return false; +} + +bool IsRootable(id obj) { + if (IsTaggedPointer(obj) || IsBlock(obj)) { + return false; + } + if (GetWrapperLifetimeScope() == WrapperLifetimeScope::kAll) { + return true; + } + // Key-value observing swaps in an NSKVONotifying_ subclass that does not + // itself conform, so the protocol is looked up through the superclasses. + for (Class cls = object_getClass(obj); cls != nil; cls = class_getSuperclass(cls)) { + if (class_conformsToProtocol(cls, @protocol(TNSDerivedClass))) { + return true; + } + } + return false; +} + +// Classes without a native -retainCount read as 0. +NSUInteger NativeRetainCount(RootedState* state, id obj) { + Class cls = object_getClass(obj); + auto found = state->retainCountImps.find(cls); + if (found == state->retainCountImps.end()) { + found = state->retainCountImps.emplace(cls, ObjectManager::NativeRetainCountImp(cls)).first; + } + if (found->second == nullptr) { + return 0; + } + return reinterpret_cast(found->second)(obj, @selector(retainCount)); +} + +ObjectManager::LifetimeStats* Stats(Isolate* isolate) { + return ObjectManager::GetLifetimeStats(isolate); +} + +void MakeWeak(ObjectWeakCallbackState* state); + +void PromoteState(ObjectWeakCallbackState* state) { + if (state->lifetimeStrong_ || state->target_->IsEmpty()) { + return; + } + state->target_->ClearWeak(); + state->lifetimeStrong_ = true; +} + +void ScheduleDrain(Isolate* isolate, RootedState* state) { + if (state->drainPosted) { + return; + } + Runtime* runtime = Runtime::GetRuntime(isolate); + std::shared_ptr loop = runtime != nullptr ? runtime->GetEventLoop() : nullptr; + if (loop != nullptr && loop->PostInternal([isolate]() { + // Cleared before anything can return early, or no drain is posted again. + if (RootedState* posted = Caches::ExistingStateFor(isolate)) { + posted->drainPosted = false; + } + WrapperLifetime::DrainReleases(isolate); + })) { + state->drainPosted = true; + } +} + +// The wrapper's JS object died. Plain C++ only: the native object is released +// later, from DrainReleases. +void PhantomCallback(const WeakCallbackInfo& info) { + ObjectWeakCallbackState* state = info.GetParameter(); + state->target_->Reset(); + state->lifetimeStrong_ = false; + if (state->disposing_) { + // The teardown walk owns this state and finishes it (WrapperLifetime::Retire). + return; + } + Isolate* isolate = info.GetIsolate(); + RootedState* rooted = Caches::StateFor(isolate); + if (rooted == nullptr) { + // Teardown has begun; the registration stays linked for its walk. + return; + } + ObjectManager::Unlink(state); + rooted->tracked.erase(state); + if (rooted->releases.empty()) { + WrapperLifetime::pendingReleaseIsolates_.fetch_add(1, std::memory_order_relaxed); + } + rooted->releases.push_back(state); + if (ObjectManager::LifetimeStats* stats = Stats(isolate)) { + stats->queuedReleases++; + } + ScheduleDrain(isolate, rooted); +} + +void MakeWeak(ObjectWeakCallbackState* state) { + state->target_->SetWeak(state, PhantomCallback, WeakCallbackType::kParameter); + state->lifetimeStrong_ = false; +} + +// Major-collection scan: root what native code owns, let go of the rest. +// Demotes only at the atomic pause, where the main thread stops until weak +// processing and young survivors are tenured. At incremental-marking start a +// demoted wrapper could still be young, and a scavenge before the pause would +// collect it without another scan, even after native code retained its object +// without crossing into JS (say by loading a __weak reference). A wrapper +// native code let go of thus survives one more incremental cycle. +void PrologueCallback(Isolate* isolate, GCType type, GCCallbackFlags) { + const bool demote = type == kGCTypeMarkSweepCompact; + RootedState* rooted = Caches::StateFor(isolate); + if (rooted == nullptr) { + return; + } + ObjectManager::LifetimeStats* stats = Stats(isolate); + for (ObjectWeakCallbackState* state : rooted->tracked) { + if (state->target_->IsEmpty()) { + continue; + } + id target = state->lifetimeTarget_; + uint64_t before = state->runtimeRetains_ != nullptr ? state->runtimeRetains_->load() : 0; + NSUInteger count = NativeRetainCount(rooted, target); + uint64_t after = state->runtimeRetains_ != nullptr ? state->runtimeRetains_->load() : 0; + NSUInteger runtimeRetains = state->runtimeRetains_ != nullptr ? RetainsIn(before) : 1; + bool owned = before != after || count >= (NSUIntegerMax >> 1) || count > runtimeRetains; + if (owned && !state->lifetimeStrong_) { + PromoteState(state); + if (stats != nullptr) { + stats->promotions++; + } + } else if (demote && !owned && state->lifetimeStrong_) { + MakeWeak(state); + if (stats != nullptr) { + stats->demotions++; + } + } + } +} + +void ReleaseQueued(const std::shared_ptr& cache, ObjectWeakCallbackState* state) { + id target = state->lifetimeTarget_; + // A wrapper built for the object after this one died owns the entry now. + auto it = cache->Instances.find(target); + if (it != cache->Instances.end() && it->second == state->target_) { + cache->Instances.erase(it); + } + delete state->lifetimeWrapper_; + std::atomic* counter = state->runtimeRetains_; + delete state; + DropRuntimeRetain(target, counter); + [target release]; +} + +void ReleaseAll(Isolate* isolate, RootedState* rooted) { + std::shared_ptr cache = Caches::Get(isolate); + rooted->draining = true; + // A -dealloc can throw an NSException through here. + struct Reset { + RootedState* rooted; + ~Reset() { rooted->draining = false; } + } reset{rooted}; + // One state leaves the queue at a time, so a release that throws leaves the + // rest queued for the next drain or teardown. + while (!rooted->releases.empty()) { + ObjectWeakCallbackState* state = rooted->releases.back(); + rooted->releases.pop_back(); + if (rooted->releases.empty()) { + WrapperLifetime::pendingReleaseIsolates_.fetch_sub(1, std::memory_order_relaxed); + } + ReleaseQueued(cache, state); + } +} + +} // namespace + +const char* WrapperLifetimeModeName(WrapperLifetimeMode mode) { + return mode == WrapperLifetimeMode::kRooted ? "rooted" : "resurrecting"; +} + +const char* WrapperLifetimeScopeName(WrapperLifetimeScope scope) { + return scope == WrapperLifetimeScope::kAll ? "all" : "extended"; +} + +void WrapperLifetime::Init(Isolate* isolate) { + std::call_once(configOnce_, ReadConfig); + if (GetWrapperLifetimeMode() != WrapperLifetimeMode::kRooted) { + return; + } + Caches::StateFor(isolate); + isolate->AddGCPrologueCallback( + PrologueCallback, static_cast(kGCTypeMarkSweepCompact | kGCTypeIncrementalMarking)); +} + +void WrapperLifetime::Adopt(Isolate* isolate, ObjCDataWrapper* wrapper, + const std::shared_ptr>& handle, id target) { + if (GetWrapperLifetimeMode() != WrapperLifetimeMode::kRooted || target == nil) { + return; + } + RootedState* rooted = Caches::StateFor(isolate); + if (rooted == nullptr || !handle->IsWeak()) { + // Handles ObjectManager did not register keep their own lifetime. + return; + } + ObjectWeakCallbackState* state = handle->ClearWeak(); + if (state == nullptr) { + return; + } + state->lifetimeWrapper_ = wrapper; + state->lifetimeTarget_ = target; + state->runtimeRetains_ = AcquireRuntimeRetain(target); + wrapper->SetLifetimeState(state); + if (IsRootable(target)) { + // Born strong: a wrapper just handed to JS or native is in use; the next + // major collection decides whether native code keeps it. + state->lifetimeTracked_ = true; + state->lifetimeStrong_ = true; + rooted->tracked.insert(state); + } else { + MakeWeak(state); + } +} + +void WrapperLifetime::EscapeSlow(ObjCDataWrapper* wrapper) { + ObjectWeakCallbackState* state = wrapper->LifetimeState(); + if (state == nullptr || !state->lifetimeTracked_ || state->lifetimeStrong_) { + return; + } + PromoteState(state); +} + +ObjectWeakCallbackState* WrapperLifetime::Relinquish(ObjCDataWrapper* wrapper) { + ObjectWeakCallbackState* state = wrapper->LifetimeState(); + if (state == nullptr || state->lifetimeTracked_ || state->target_->IsEmpty()) { + return nullptr; + } + if (state->target_->IsWeak()) { + state->target_->ClearWeak(); + } + state->lifetimeStrong_ = false; + DropRuntimeRetain(state->lifetimeTarget_, state->runtimeRetains_); + state->runtimeRetains_ = nullptr; + state->lifetimeWrapper_ = nullptr; + state->lifetimeTarget_ = nil; + wrapper->SetLifetimeState(nullptr); + return state; +} + +void WrapperLifetime::DrainReleases(Isolate* isolate) { + RootedState* rooted = Caches::StateFor(isolate); + if (rooted == nullptr || rooted->releases.empty()) { + return; + } + // JS can run on another thread under the isolate's Locker; objects such as + // views and CA transactions must be released on the runtime's own thread. + Runtime* runtime = Runtime::GetRuntime(isolate); + if (runtime != nullptr && !runtime->IsOnRuntimeThread()) { + ScheduleDrain(isolate, rooted); + return; + } + rooted->drainPosted = false; + if (rooted->draining) { + // A release ran JS that reached a drain point; the outer loop continues. + return; + } + ReleaseAll(isolate, rooted); +} + +void WrapperLifetime::DrainForTeardown(Isolate* isolate) { + RootedState* rooted = Caches::ExistingStateFor(isolate); + if (rooted == nullptr) { + return; + } + rooted->tracked.clear(); + if (!rooted->draining) { + ReleaseAll(isolate, rooted); + } +} + +void WrapperLifetime::Forget(Isolate* isolate, ObjectWeakCallbackState* state) { + if (state == nullptr || state->lifetimeTarget_ == nil) { + return; + } + if (RootedState* rooted = Caches::StateFor(isolate)) { + rooted->tracked.erase(state); + } + DropRuntimeRetain(state->lifetimeTarget_, state->runtimeRetains_); + state->runtimeRetains_ = nullptr; + if (state->lifetimeWrapper_ != nullptr) { + state->lifetimeWrapper_->SetLifetimeState(nullptr); + } +} + +void WrapperLifetime::DropRetainBeforeDisposal(ObjectWeakCallbackState* state) { + DropRuntimeRetain(state->lifetimeTarget_, state->runtimeRetains_); + state->runtimeRetains_ = nullptr; +} + +void WrapperLifetime::Retire(Isolate* isolate, ObjectWeakCallbackState* state, bool released) { + if (state->lifetimeTarget_ == nil) { + return; + } + id target = state->lifetimeTarget_; + std::atomic* counter = state->runtimeRetains_; + state->runtimeRetains_ = nullptr; + if (!released) { + // The JS object died during the teardown walk, before DisposeValue could + // release it. + std::shared_ptr cache = Caches::Get(isolate); + if (cache != nullptr) { + auto it = cache->Instances.find(target); + if (it != cache->Instances.end() && it->second == state->target_) { + cache->Instances.erase(it); + } + } + delete state->lifetimeWrapper_; + DropRuntimeRetain(target, counter); + [target release]; + return; + } + DropRuntimeRetain(target, counter); +} + +ObjCDataWrapper::~ObjCDataWrapper() { + if (this->lifetimeState_ != nullptr) { + this->lifetimeState_->lifetimeWrapper_ = nullptr; + } +} + +} // namespace tns diff --git a/TestRunner/app/tests/GCFinalizerTests.js b/TestRunner/app/tests/GCFinalizerTests.js index 8c5f673b7..05aff3dba 100644 --- a/TestRunner/app/tests/GCFinalizerTests.js +++ b/TestRunner/app/tests/GCFinalizerTests.js @@ -1,4 +1,15 @@ describe("GC finalizer callbacks", function () { + // Under the rooted wrapper lifetime mode, a dead wrapper's object is + // released from a queue drained on entry to native calls, and a natively + // retained object only becomes collectable once its holder's release ran. + // Under the resurrecting mode the extra rounds change nothing. + function collectAndDrain() { + for (var round = 0; round < 3; round++) { + __collect(); + NSObject.new(); + } + } + // A finalizer callback runs from V8's GC epilogue. Since 14.9, // Heap::CollectGarbage holds a DisallowJavascriptExecution across the whole // collection, so entering JS from one is a GRACEFUL_FATAL that aborts the @@ -29,7 +40,7 @@ describe("GC finalizer callbacks", function () { for (var i = 0; i < 200000; i++) { sink += i % 7; } - __collect(); + collectAndDrain(); expect(sink).toBeGreaterThan(0); expect(calls).toBe(1); @@ -75,7 +86,10 @@ describe("GC finalizer callbacks", function () { // An object that first reached JS on a background thread has no tie to the // runtime's thread, so its release stays with the collection that ran there. + // The rooted and canary lifetime modes release through a queue drained on + // the runtime's thread instead. it("releases a background-born object where the background collection runs", function (done) { + var resurrecting = require("ns:runtime").getConfig("wrapperLifetimeMode") === "resurrecting"; var threads = []; var DeallocThread = TNSApi.extend({ methodCalledInDealloc: function () { @@ -96,7 +110,7 @@ describe("GC finalizer callbacks", function () { var attempts = 200; (function poll() { if (threads.length > 0 || --attempts === 0) { - expect(threads).toEqual([false]); + expect(threads).toEqual([!resurrecting]); done(); return; } @@ -473,8 +487,7 @@ describe("GC finalizer callbacks", function () { })(); scrubStack(); - __collect(); - __collect(); + collectAndDrain(); expect(retired).toBeGreaterThan(0); expect(keepAlive.count).toBe(8); diff --git a/TestRunner/app/tests/WrapperLifetimeModesTests.js b/TestRunner/app/tests/WrapperLifetimeModesTests.js new file mode 100644 index 000000000..0df5e7b88 --- /dev/null +++ b/TestRunner/app/tests/WrapperLifetimeModesTests.js @@ -0,0 +1,415 @@ +// Wrapper lifetime under the configured mode ("wrapperLifetime" in the app +// config). The suite runs under the default mode; the rooted expectations run +// when the TestRunner app is configured with "mode": "rooted". +describe("Wrapper lifetime modes", function () { + var runtime = require("ns:runtime"); + var mode = runtime.getConfig("wrapperLifetimeMode"); + var scope = runtime.getConfig("wrapperLifetimeScope"); + var rooted = mode === "rooted"; + + var Extended = (function (_super) { + __extends(Extended, _super); + function Extended() { + return (_super !== null && _super.apply(this, arguments)) || this; + } + return Extended; + })(TNSAllocLog); + + function scrub(n) { + return n > 0 ? scrub(n - 1) + n : 0; + } + + function deallocs() { + return (TNSGetOutput().match(/TNSAllocLog dealloc/g) || []).length; + } + + // Collect, then let the release queue drain (it drains on the event loop + // and on entry to native calls). + function settle(rounds, callback) { + scrub(300); + __collect(); + __collect(); + setTimeout(function () { + NSObject.new(); + if (rounds > 1) { + settle(rounds - 1, callback); + } else { + callback(); + } + }, 10); + } + + beforeEach(function () { + TNSClearOutput(); + }); + + // The name carries the mode so a run's log shows which one it exercised. + it("reports the configured mode and scope (" + mode + "/" + scope + ")", function () { + expect(["resurrecting", "rooted"].indexOf(mode)).not.toBe(-1); + expect(["extended", "all"].indexOf(scope)).not.toBe(-1); + expect(function () { + runtime.setConfig("wrapperLifetimeMode", "rooted"); + }).toThrowError(TypeError, /read-only/); + }); + + it("keeps the JS state of a natively owned JS-extended object and everything it references", function (done) { + var owner = NSMutableArray.new(); + (function () { + var holder = Extended.new(); + holder.state = { item: TNSAllocLog.new() }; + owner.addObject(holder); + })(); + settle(2, function () { + var holder = owner.objectAtIndex(0); + if (rooted) { + expect(holder.state).toBeDefined(); + expect(function () { + holder.state.item.isEqual(null); + }).not.toThrow(); + } + done(); + }); + }); + + it("keeps the JS state of a natively owned plain object when every wrapper is rooted", function (done) { + var owner = NSMutableArray.new(); + (function () { + var obj = TNSAllocLog.new(); + obj.state = { value: 42 }; + owner.addObject(obj); + })(); + settle(2, function () { + var obj = owner.objectAtIndex(0); + if (rooted && scope === "all") { + expect(obj.state && obj.state.value).toBe(42); + } + done(); + }); + }); + + it("keeps WeakMap entries and WeakRef targets of natively owned objects when every wrapper is rooted", function (done) { + var owner = NSMutableArray.new(); + var map = new WeakMap(); + var ref; + (function () { + var obj = TNSAllocLog.new(); + map.set(obj, "value"); + ref = new WeakRef(obj); + owner.addObject(obj); + })(); + settle(2, function () { + var obj = owner.objectAtIndex(0); + if (rooted && scope === "all") { + expect(map.get(obj)).toBe("value"); + expect(ref.deref()).toBe(obj); + } + done(); + }); + }); + + it("collects objects only JS references", function (done) { + var N = 16; + var watched = NSHashTable.weakObjectsHashTable(); + (function () { + for (var i = 0; i < N; i++) { + var obj = i % 2 === 0 ? Extended.new() : TNSAllocLog.new(); + obj.state = { i: i }; + watched.addObject(obj); + } + })(); + settle(2, function () { + expect(deallocs()).toBeGreaterThan(N / 2); + // Later specs count deallocations from a cleared log, so none of + // these objects may outlive this spec. Reading the table retains + // the survivors until that read's array is collected, hence the + // rounds between reads. + (function drain(attempts) { + var survivors = watched.allObjects.count; + if (survivors === 0 || attempts === 0) { + expect(survivors).toBe(0); + done(); + return; + } + settle(3, function () { + drain(attempts - 1); + }); + })(4); + }); + }); + + it("frees a natively owned object once native code lets go of it", function (done) { + var owner = NSMutableArray.new(); + (function () { + var obj = Extended.new(); + obj.state = { i: 1 }; + owner.addObject(obj); + })(); + settle(2, function () { + expect(deallocs()).toBe(0); + owner.removeAllObjects(); + settle(3, function () { + expect(deallocs()).toBe(1); + done(); + }); + }); + }); + + // +new runs the JS-implemented init from native code, before JS has a + // wrapper for the object. + it("manages the lifetime of an object whose JS-implemented initializer created its wrapper", function (done) { + var JSInit = (function (_super) { + __extends(JSInit, _super); + function JSInit() { + return (_super !== null && _super.apply(this, arguments)) || this; + } + JSInit.prototype.init = function () { + var self = _super.prototype.init.call(this); + self.initialized = true; + return self; + }; + return JSInit; + })(TNSAllocLog); + var owner = NSMutableArray.new(); + (function () { + var obj = JSInit.new(); + obj.state = { i: 1 }; + owner.addObject(obj); + })(); + settle(2, function () { + var obj = owner.objectAtIndex(0); + expect(obj.initialized).toBe(true); + expect(obj.state && obj.state.i).toBe(1); + obj = null; + expect(deallocs()).toBe(0); + owner.removeAllObjects(); + settle(3, function () { + if (mode !== "resurrecting") { + expect(deallocs()).toBe(1); + } + done(); + }); + }); + }); + + it("collects a native-retain cycle whose back reference is a WeakRef", function (done) { + (function () { + var owner = NSMutableArray.new(); + var child = Extended.new(); + owner.addObject(child); + child.state = { owner: new WeakRef(owner) }; + })(); + settle(4, function () { + expect(deallocs()).toBe(1); + done(); + }); + }); + + // The ListView shape: JS keeps the cell, the cell points at its item view + // through a WeakRef, and the item view owns native objects. After teardown + // the WeakRef must either be cleared or hand back a view whose native + // objects are alive. + it("never hands a WeakRef target back with released native objects", function (done) { + var cell = NSObject.new(); + (function () { + var view = {}; + var nativeView = TNSAllocLog.new(); + nativeView.owner = view; + view.nativeView = nativeView; + view.color = TNSAllocLog.new(); + cell.owner = new WeakRef(view); + })(); + settle(2, function () { + var view = cell.owner.deref(); + if (rooted && view !== undefined) { + expect(function () { + view.color.isEqual(null); + view.nativeView.isEqual(null); + }).not.toThrow(); + } + done(); + }); + }); + + it("tolerates a JS-implemented retainCount while scanning", function (done) { + var Counting = (function (_super) { + __extends(Counting, _super); + function Counting() { + return (_super !== null && _super.apply(this, arguments)) || this; + } + Counting.prototype.retainCount = function () { + return 1; + }; + return Counting; + })(NSObject); + var owner = NSMutableArray.new(); + (function () { + for (var i = 0; i < 4; i++) { + var obj = Counting.new(); + obj.state = i; + owner.addObject(obj); + } + })(); + settle(2, function () { + expect(owner.count).toBe(4); + if (rooted) { + expect(owner.objectAtIndex(0).state).toBe(0); + } + done(); + }); + }); + + it("reads the native retainCount of a key-value observed object whose JS class implements it", function (done) { + var Counting = (function (_super) { + __extends(Counting, _super); + function Counting() { + return (_super !== null && _super.apply(this, arguments)) || this; + } + Counting.prototype.retainCount = function () { + return 1; + }; + return Counting; + })(NSObject); + var owner = NSMutableArray.new(); + var observer = NSObject.new(); + (function () { + var obj = Counting.new(); + obj.addObserverForKeyPathOptionsContext(observer, "description", 0, null); + obj.state = 7; + owner.addObject(obj); + })(); + settle(2, function () { + var obj = owner.objectAtIndex(0); + if (rooted) { + expect(obj.state).toBe(7); + } + obj.removeObserverForKeyPath(observer, "description"); + done(); + }); + }); + + // Replaced through the protocol prototype, the native class itself answers + // -retainCount from JS, so the scan has to read the original. The + // replacement outlives the spec, and the other modes' ownership checks + // still call it from a GC prologue, so it is installed in the rooted mode + // only. + it("never calls a JS replacement of a native class's retainCount while scanning", function (done) { + if (!rooted) { + done(); + return; + } + var calls = 0; + var proto = TNSReplaceableRetainCountProtocol.prototype; + var original = proto.retainCount; + proto.retainCount = function () { + calls++; + return original.call(this); + }; + var Replaced = (function (_super) { + __extends(Replaced, _super); + function Replaced() { + return (_super !== null && _super.apply(this, arguments)) || this; + } + return Replaced; + })(TNSReplaceableRetainCount); + var owner = NSMutableArray.new(); + var scanned; + (function () { + var obj = Replaced.new(); + obj.state = 3; + owner.addObject(obj); + var before = calls; + expect(TNSReplaceableRetainCount.retainCountOf(obj)).toBeGreaterThan(1); + expect(calls).toBe(before + 1); + scanned = calls; + })(); + settle(2, function () { + if (rooted) { + expect(calls).toBe(scanned); + expect(owner.objectAtIndex(0).state).toBe(3); + } + owner.removeAllObjects(); + settle(3, function () { + if (rooted) { + expect(calls).toBe(scanned); + expect(deallocs()).toBe(1); + } + done(); + }); + }); + }); + + it("keeps the JS state of a natively owned timer when every wrapper is rooted", function (done) { + var owner = NSMutableArray.new(); + var map = new WeakMap(); + (function () { + var timer = NSTimer.timerWithTimeIntervalTargetSelectorUserInfoRepeats(1000, TNSAllocLog.new(), "description", null, false); + timer.state = 5; + map.set(timer, "timer"); + owner.addObject(timer); + })(); + settle(2, function () { + var timer = owner.objectAtIndex(0); + if (rooted && scope === "all") { + expect(timer.state).toBe(5); + expect(map.get(timer)).toBe("timer"); + } + timer = null; + expect(deallocs()).toBe(0); + owner.removeAllObjects(); + settle(4, function () { + if (rooted && scope === "all") { + expect(deallocs()).toBe(1); + } + done(); + }); + }); + }); + + it("scans a wrapper of NSTimer.alloc()'s uninitialized placeholder", function (done) { + if (!(rooted && scope === "all")) { + done(); + return; + } + var placeholder = TNSUninitializedTimer.placeholder(); + expect(placeholder.isKindOfClass(NSTimer)).toBe(true); + placeholder.state = 1; + settle(2, function () { + expect(placeholder.state).toBe(1); + done(); + }); + }); + + it("lets an explicitly released rooted wrapper go", function (done) { + var owner = NSMutableArray.new(); + var obj = Extended.new(); + owner.addObject(obj); + __releaseNativeCounterpart(obj); + expect(function () { + obj.isEqual(null); + }).toThrowError(ReferenceError); + owner.removeAllObjects(); + settle(2, function () { + expect(deallocs()).toBe(1); + done(); + }); + }); + + it("counts rooted-mode activity", function (done) { + var before = runtime.getWrapperLifetimeStats(); + (function () { + for (var i = 0; i < 8; i++) { + TNSAllocLog.new().state = i; + } + })(); + settle(2, function () { + var after = runtime.getWrapperLifetimeStats(); + if (rooted) { + expect(after.queuedReleases).toBeGreaterThan(before.queuedReleases); + expect(after.resurrections).toBe(before.resurrections); + } else { + expect(after.queuedReleases).toBe(before.queuedReleases); + } + done(); + }); + }); +}); diff --git a/TestRunner/app/tests/WrapperLifetimeTests.js b/TestRunner/app/tests/WrapperLifetimeTests.js index 5f02b45e0..1170df102 100644 --- a/TestRunner/app/tests/WrapperLifetimeTests.js +++ b/TestRunner/app/tests/WrapperLifetimeTests.js @@ -162,6 +162,10 @@ describe("Wrapper lifetime", function () { // object reached UIKit as a dictionary. Zero husks is a legal (if unlucky) // outcome, as in GCFinalizerTests. it("names garbage collection as the reason for an object released under a resurrected holder", function () { + if (runtime.getConfig("wrapperLifetimeMode") !== "resurrecting") { + // Nothing is resurrected, so nothing reachable is released. + return; + } var Holder = (function (_super) { __extends(Holder, _super); function Holder() { @@ -206,6 +210,12 @@ describe("Wrapper lifetime", function () { }); it("reports JS state lost on a wrapper whose native object lives on", function (done) { + if (runtime.getConfig("wrapperLifetimeMode") !== "resurrecting") { + // Rooted wrappers keep their state; unrooted ones die in a phantom + // callback, where their properties can no longer be read. + done(); + return; + } var previous = runtime.getConfig("wrapperLifetimeWarnings"); runtime.setConfig("wrapperLifetimeWarnings", true); var N = 16; @@ -310,9 +320,12 @@ describe("Wrapper lifetime", function () { "releasedAccesses", "releasedExplicitly", "resurrections", + "demotions", + "promotions", + "queuedReleases", "stateLostCandidates", "stateLostConfirmed", - ]); + ].sort()); Object.keys(current).forEach(function (key) { expect(typeof current[key]).toBe("number"); }); diff --git a/TestRunner/app/tests/index.js b/TestRunner/app/tests/index.js index d2b51fb0f..a3ddf8ddb 100644 --- a/TestRunner/app/tests/index.js +++ b/TestRunner/app/tests/index.js @@ -141,6 +141,7 @@ require("./NativeCallbackSelfTests"); require("./JSAccessorEncodingTests"); require("./JSAccessorReceiverTests"); require("./WrapperLifetimeTests"); +require("./WrapperLifetimeModesTests"); require("./BlockCacheRaceTests"); require("./WorkerConcurrentStartupTests"); require("./WorkerOptionsTests"); diff --git a/docs/knowledge/v8-resurrecting-finalizers.md b/docs/knowledge/v8-resurrecting-finalizers.md index 869cdd201..0490c8e78 100644 --- a/docs/knowledge/v8-resurrecting-finalizers.md +++ b/docs/knowledge/v8-resurrecting-finalizers.md @@ -237,6 +237,26 @@ receivers included) always throws. `ns:runtime`'s `getWrapperLifetimeStats()` co resurrections, collections, explicit releases and released-object accesses. Specs: `WrapperLifetimeTests.js`. +The app config `"wrapperLifetime": { "mode": "rooted" }` (`WrapperLifetime.{h,mm}`) avoids the +hazard instead of reporting it. An adopted wrapper never gets a `kFinalizer` callback: it is a +strong root while something other than the runtime retains its object and a phantom +(`kParameter`) weak handle otherwise. Strength is decided by a `-retainCount` scan in a +major-GC prologue, where flipping weakness is legal, and a wrapper is born strong and made +strong again whenever it crosses the JS/native boundary. A JS-unreachable holder therefore +stays rooted with its whole closure for as long as native code owns it, so nothing it reaches +is queued. Phantom callbacks only queue; the native objects are released later on the +runtime's thread, where JS may run. The extended classes' retain/release swizzle is not +installed in this mode. `"scope": "extended"` (default) roots only JS-extended instances; +`"all"` roots every ObjC wrapper except blocks and tagged pointers, at the cost of keeping +JS-referencing native cycles alive (ARC rules: break them with a `WeakRef`). Specs: +`WrapperLifetimeModesTests.js`; CI runs the default mode only, so the rooted expectations run +when the TestRunner app config selects `"mode": "rooted"`. + +The state-lost warnings (`wrapperLifetimeWarnings`) watch for resurrecting finalizers and stay +silent in the rooted mode. Under `"scope": "extended"` there, a plain (not JS-extended) wrapper +is a phantom handle that a scavenge can collect, so JS properties set on plain objects that +native code owns are lost without a warning. + Two facts worth knowing when reasoning about which objects can husk: - `Pointer`/`interop.alloc` objects never husk at runtime — `Caches::PointerInstances` diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 7a4d38a7e..f9731f8d1 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -115,7 +115,9 @@ Config keys: |---|---|---|---| | `releasedObjectPolicy` | `"report"` \| `"throw"` | process-wide (main-isolate writes only; read live by every isolate) | `"report"` | | `debug` | comma-separated category list, e.g. `"esm,fetch"` | process-wide (main-isolate writes only; read live by every isolate) | the `NS_DEBUG` environment variable, or `""` | -| `wrapperLifetimeWarnings` | `true` \| `false` | process-wide (main-isolate writes only; read live by every isolate) | the app config `"wrapperLifetime": { "warnings": … }`, or on in debug builds | +| `wrapperLifetimeWarnings` | `true` \| `false` | process-wide (main-isolate writes only; read live by every isolate); no effect in the `"rooted"` mode | the app config `"wrapperLifetime": { "warnings": … }`, or on in debug builds | +| `wrapperLifetimeMode` | `"resurrecting"` \| `"rooted"` | process-wide, read-only | the app config `"wrapperLifetime": { "mode": … }`, or `"resurrecting"` | +| `wrapperLifetimeScope` | `"extended"` \| `"all"` | process-wide, read-only | the app config `"wrapperLifetime": { "scope": … }`, or `"extended"` | ```js const { setConfig, getConfig } = require("ns:runtime"); @@ -144,6 +146,7 @@ The `TypeError` messages are part of the contract: | invalid `releasedObjectPolicy` value | `'releasedObjectPolicy' must be 'report' or 'throw'` | | non-string `debug` value | `'debug' must be a comma-separated category string (), or '' to disable tracing` | | non-boolean `wrapperLifetimeWarnings` value | `'wrapperLifetimeWarnings' must be a boolean` | +| `setConfig` of `wrapperLifetimeMode` or `wrapperLifetimeScope` | `'' is read-only; set "wrapperLifetime" in the app config` | ### Wrapper lifetime counters @@ -158,6 +161,9 @@ every build (they only cost an increment on finalizer and error paths): | `releasedAccesses` | times JS passed a released wrapper to native code, used it as a method receiver, or touched a released pointer, reference or struct | | `stateLostCandidates` | collected wrappers carrying JS properties whose object was still retained by something else (only while `wrapperLifetimeWarnings` is on) | | `stateLostConfirmed` | candidates whose object was still alive a runloop turn later, once releases queued for the runtime thread ran; each class is also reported once in the log | +| `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"` only: collected wrappers whose native object was queued for release on the runtime's thread | A wrapper whose native object was released keeps its JS identity. Passing it to native code follows `releasedObjectPolicy`: under `"report"` the argument diff --git a/types/ns-runtime.d.ts b/types/ns-runtime.d.ts index 8d0ee8890..49c9ffe8a 100644 --- a/types/ns-runtime.d.ts +++ b/types/ns-runtime.d.ts @@ -41,6 +41,26 @@ declare module "ns:runtime" { * Process-wide; main-isolate writes only. */ wrapperLifetimeWarnings: boolean; + /** + * How ObjC object wrappers live, from the app config + * `"wrapperLifetime": { "mode": ... }`. Read-only: `setConfig` throws. + * + * - `"resurrecting"` (default): a collected wrapper whose JS-extended + * object native code still retains is resurrected by its finalizer. + * - `"rooted"`: no resurrection. A wrapper in scope stays a strong root + * while something other than the runtime retains its object, and is + * weak otherwise; native objects of collected wrappers are released on + * the runtime's thread. + */ + wrapperLifetimeMode: "resurrecting" | "rooted"; + /** + * Which wrappers `"rooted"` roots, from the app config + * `"wrapperLifetime": { "scope": ... }`. Read-only: `setConfig` throws. + * + * - `"extended"` (default): instances of JS-extended classes. + * - `"all"`: every ObjC object wrapper except blocks and tagged pointers. + */ + wrapperLifetimeScope: "extended" | "all"; } /** @@ -60,6 +80,12 @@ declare module "ns:runtime" { stateLostCandidates: number; /** Candidates whose object was still alive a runloop turn later, once queued releases ran (warnings enabled only). */ stateLostConfirmed: number; + /** `"rooted"` only: weak wrappers made strong because native code retained their object. */ + promotions: number; + /** `"rooted"` only: strong wrappers made weak because native code let go of their object. */ + demotions: number; + /** `"rooted"` only: collected wrappers whose native object was queued for release. */ + queuedReleases: number; } /** diff --git a/v8ios.xcodeproj/project.pbxproj b/v8ios.xcodeproj/project.pbxproj index ecaad04b0..0dbf3f5a6 100644 --- a/v8ios.xcodeproj/project.pbxproj +++ b/v8ios.xcodeproj/project.pbxproj @@ -311,6 +311,8 @@ C2DDEBAD229EAC8300345BFE /* Caches.h in Headers */ = {isa = PBXBuildFile; fileRef = C2DDEB84229EAC8300345BFE /* Caches.h */; }; C2DDEBAE229EAC8300345BFE /* DictionaryAdapter.h in Headers */ = {isa = PBXBuildFile; fileRef = C2DDEB85229EAC8300345BFE /* DictionaryAdapter.h */; }; C2DDEBAF229EAC8300345BFE /* ObjectManager.mm in Sources */ = {isa = PBXBuildFile; fileRef = C2DDEB86229EAC8300345BFE /* ObjectManager.mm */; }; + DD6B0F1ACE8AE363C72245E9 /* WrapperLifetime.h in Headers */ = {isa = PBXBuildFile; fileRef = 9E6F52B357F2776D77D71D8A /* WrapperLifetime.h */; }; + 1DE238EF3BDD0EF221E13C44 /* WrapperLifetime.mm in Sources */ = {isa = PBXBuildFile; fileRef = 13A9D13202DBEA9487A90B03 /* WrapperLifetime.mm */; }; C2DDEBB0229EAC8300345BFE /* StringHasher.h in Headers */ = {isa = PBXBuildFile; fileRef = C2DDEB87229EAC8300345BFE /* StringHasher.h */; }; C2DDEBB1229EAC8300345BFE /* Caches.cpp in Sources */ = {isa = PBXBuildFile; fileRef = C2DDEB88229EAC8300345BFE /* Caches.cpp */; }; C2DDEBB2229EAC8300345BFE /* ModuleInternal.h in Headers */ = {isa = PBXBuildFile; fileRef = C2DDEB89229EAC8300345BFE /* ModuleInternal.h */; }; @@ -841,6 +843,8 @@ C2DDEB84229EAC8300345BFE /* Caches.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Caches.h; sourceTree = ""; }; C2DDEB85229EAC8300345BFE /* DictionaryAdapter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DictionaryAdapter.h; sourceTree = ""; }; C2DDEB86229EAC8300345BFE /* ObjectManager.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = ObjectManager.mm; sourceTree = ""; }; + 9E6F52B357F2776D77D71D8A /* WrapperLifetime.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WrapperLifetime.h; sourceTree = ""; }; + 13A9D13202DBEA9487A90B03 /* WrapperLifetime.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = WrapperLifetime.mm; sourceTree = ""; }; C2DDEB87229EAC8300345BFE /* StringHasher.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = StringHasher.h; sourceTree = ""; }; C2DDEB88229EAC8300345BFE /* Caches.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Caches.cpp; sourceTree = ""; }; C2DDEB89229EAC8300345BFE /* ModuleInternal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ModuleInternal.h; sourceTree = ""; }; @@ -1524,6 +1528,8 @@ E9A2699467FF325411FC11C4 /* NSExceptionSupport.mm */, C2DDEB83229EAC8300345BFE /* ObjectManager.h */, C2DDEB86229EAC8300345BFE /* ObjectManager.mm */, + 9E6F52B357F2776D77D71D8A /* WrapperLifetime.h */, + 13A9D13202DBEA9487A90B03 /* WrapperLifetime.mm */, C20AB5E526E1015200E2B41D /* OneByteStringResource.h */, C20AB5E426E1015200E2B41D /* OneByteStringResource.cpp */, 4A5C201A2E2B000300000002 /* Performance.h */, @@ -1681,6 +1687,7 @@ 6573B9D0291FE29F00B0ED7C /* JSIV8ValueConverter.h in Headers */, C20AB5E726E1015300E2B41D /* OneByteStringResource.h in Headers */, C2DDEBAC229EAC8300345BFE /* ObjectManager.h in Headers */, + DD6B0F1ACE8AE363C72245E9 /* WrapperLifetime.h in Headers */, 6573B9E7291FE2A700B0ED7C /* jsi.h in Headers */, 6573B9E2291FE2A700B0ED7C /* jsi-inl.h in Headers */, C2D21601248AAAD900EDC646 /* Constants.h in Headers */, @@ -2365,6 +2372,7 @@ C2A5F86A2359AEB600074AFA /* ExtVector.cpp in Sources */, AA8C47B22E27114300649BF5 /* ModuleInternalCallbacks.mm in Sources */, C2DDEBAF229EAC8300345BFE /* ObjectManager.mm in Sources */, + 1DE238EF3BDD0EF221E13C44 /* WrapperLifetime.mm in Sources */, F6191AB029C0FCE8003F588F /* JsV8InspectorClient.mm in Sources */, A1B2C3D40000000000000004 /* WorkerInspectorClient.mm in Sources */, C2DDEB9C229EAC8300345BFE /* ClassBuilder.cpp in Sources */,