From 3f256713dfbcb46524b823fe49410258126295a4 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 17:00:09 -0300 Subject: [PATCH 1/3] refactor(runtime): canary wrapper templates by kind Canary handlers are now configured per CanaryKind: kPlain for objects outside JS-extended classes (native class constructors under scope "all", empty instances of such objects) and kExtended for instances of JS-extended classes. Wrappers take the kind of their object (WrapperLifetimeCanary:: KindOf), computed once per wrap; whether a class is JS-extended is cached per class and thread, since the superclass walk costs tens of nanoseconds a class. Adopt checks the kind it is given in debug builds only. ArgConverter::ConstructObject now gives a result whose kind differs from its constructor's template a new object of the result's kind, returned in place of `this`. Before, it did so only for a canary built from a template without handlers. The new cases are a plain template with a JS-extended result and the reverse, which constructing from a pointer (`new NativeClass(handle)`) or an initializer that returns another object reaches. `new` of a JS-extended subclass through a native base does not: ClassConstructorCallback takes the class from the native constructor's metadata, not from new.target. Both kinds install the same masking handlers at this commit, so the replacement object behaves as `this` would have; a later change gives plain canaries different handlers. --- NativeScript/runtime/ArgConverter.h | 23 ++--- NativeScript/runtime/ArgConverter.mm | 85 ++++++++++--------- NativeScript/runtime/ClassBuilder.mm | 4 +- NativeScript/runtime/MetadataBuilder.mm | 7 +- NativeScript/runtime/WrapperLifetime.h | 7 +- NativeScript/runtime/WrapperLifetime.mm | 9 +- NativeScript/runtime/WrapperLifetimeCanary.h | 43 ++++++---- NativeScript/runtime/WrapperLifetimeCanary.mm | 40 ++++++--- 8 files changed, 131 insertions(+), 87 deletions(-) diff --git a/NativeScript/runtime/ArgConverter.h b/NativeScript/runtime/ArgConverter.h index 30b2e7c72..7d06d7f99 100644 --- a/NativeScript/runtime/ArgConverter.h +++ b/NativeScript/runtime/ArgConverter.h @@ -7,6 +7,7 @@ #include "Common.h" #include "DataWrapper.h" #include "IsolateWrapper.h" +#include "WrapperLifetimeCanary.h" #include "libffi.h" namespace tns { @@ -64,14 +65,14 @@ class ArgConverter { v8::Local receiver, const std::vector& additionalProtocols = std::vector()); - // `intercepted`: the object carries the canary handlers - // (WrapperLifetimeCanary::Intercepts). + // `kind`: the canary handlers the object carries + // (WrapperLifetimeCanary::KindOf). static std::shared_ptr> CreateEmptyObject( - v8::Local context, bool intercepted); - // The constructor NewEmptyInstance takes: EmptyObjCtorFunc, or with - // `intercepted` its counterpart carrying the canary handlers. + v8::Local context, CanaryKind kind); + // The constructor NewEmptyInstance takes: EmptyObjCtorFunc for kNone, or its + // counterpart carrying `kind`'s canary handlers. static v8::Persistent* EmptyInstanceFunction( - v8::Isolate* isolate, bool intercepted); + v8::Isolate* isolate, CanaryKind kind); // CreateEmptyObject's object without the ObjectManager registration, for an // object whose collection has nothing to dispose. static v8::Local NewEmptyInstance( @@ -138,17 +139,17 @@ class ArgConverter { // caller returns its defined default. Resets `tc` in both cases. static id HandleBoundaryException(v8::Local context, v8::TryCatch& tc); - // `thisIntercepts`: the constructor's instance template carries the canary - // handlers (WrapperLifetimeCanary::ConfigureInstanceTemplate). Without them, - // a canary gets a new object, returned in place of `this`. + // `thisKind`: the canary handlers the constructor's instance template + // carries (WrapperLifetimeCanary::ConfigureInstanceTemplate). A canary whose + // kind differs gets a new object, returned in place of `this`. static void ConstructObject(v8::Local context, const v8::FunctionCallbackInfo& info, Class klass, const InterfaceMeta* interfaceMeta, - bool thisIntercepts); + CanaryKind thisKind); private: static v8::Local CreateEmptyInstanceFunction( - v8::Local context, bool intercepted); + v8::Local context, CanaryKind kind); static std::shared_ptr> CreateEmptyInstance( v8::Local context, v8::Persistent* ctorFunc); static void FindMethodOverloads(Class klass, std::string methodName, diff --git a/NativeScript/runtime/ArgConverter.mm b/NativeScript/runtime/ArgConverter.mm index f4bf13d31..41dd5f5af 100644 --- a/NativeScript/runtime/ArgConverter.mm +++ b/NativeScript/runtime/ArgConverter.mm @@ -57,13 +57,15 @@ bool IsKVOSubclassOf(Class klass, Class base) { strncmp(class_getName(klass), prefix, sizeof(prefix) - 1) == 0; } -// Canary mode: constructors of wrappers that carry the canary handlers. +// Canary mode: constructors of wrappers that carry the canary handlers, per +// CanaryKind (kNone has none). struct CanaryWrapperConstructors { + static constexpr size_t kKinds = 3; // The empty instance's, for canaries. - std::unique_ptr> emptyInstance; - // Shaped like a native class constructor's instances, which lack the - // handlers under scope "extended". - std::unique_ptr> constructedInstance; + std::unique_ptr> emptyInstance[kKinds]; + // Shaped like a native class constructor's instances, whose template is + // configured for one kind only (WrapperLifetimeCanary::NativeInstancesKind). + std::unique_ptr> constructedInstance[kKinds]; }; } // namespace @@ -98,7 +100,7 @@ bool IsKVOSubclassOf(Class klass, Class base) { Isolate* isolate = v8::Isolate::GetCurrent(); auto cache = Caches::Get(isolate); cache->EmptyObjCtorFunc = std::make_unique>( - isolate, ArgConverter::CreateEmptyInstanceFunction(context, false)); + isolate, ArgConverter::CreateEmptyInstanceFunction(context, CanaryKind::kNone)); if (GetWrapperLifetimeMode() != WrapperLifetimeMode::kCanary) { return; } @@ -106,25 +108,29 @@ bool IsKVOSubclassOf(Class klass, Class base) { if (canary == nullptr) { return; } - canary->emptyInstance = std::make_unique>( - isolate, ArgConverter::CreateEmptyInstanceFunction(context, true)); - Local constructedTemplate = FunctionTemplate::New(isolate); - constructedTemplate->InstanceTemplate()->SetInternalFieldCount(1); - WrapperLifetimeCanary::ConfigureInstanceTemplate(constructedTemplate->InstanceTemplate()); - Local constructedFunc; - tns::Assert(constructedTemplate->GetFunction(context).ToLocal(&constructedFunc), isolate); - canary->constructedInstance = - std::make_unique>(isolate, constructedFunc); + for (CanaryKind kind : {CanaryKind::kPlain, CanaryKind::kExtended}) { + size_t index = static_cast(kind); + canary->emptyInstance[index] = std::make_unique>( + isolate, ArgConverter::CreateEmptyInstanceFunction(context, kind)); + Local constructedTemplate = FunctionTemplate::New(isolate); + constructedTemplate->InstanceTemplate()->SetInternalFieldCount(1); + WrapperLifetimeCanary::ConfigureInstanceTemplate(constructedTemplate->InstanceTemplate(), kind); + Local constructedFunc; + tns::Assert(constructedTemplate->GetFunction(context).ToLocal(&constructedFunc), isolate); + canary->constructedInstance[index] = + std::make_unique>(isolate, constructedFunc); + } } -Persistent* ArgConverter::EmptyInstanceFunction(Isolate* isolate, bool intercepted) { - if (intercepted) { +Persistent* ArgConverter::EmptyInstanceFunction(Isolate* isolate, CanaryKind kind) { + if (kind != CanaryKind::kNone) { // Teardown-safe: a -dealloc receiver can be built after InvalidateIsolate, // while deferred releases drain. CanaryWrapperConstructors* canary = Caches::ExistingStateFor(isolate); - tns::Assert(canary != nullptr && canary->emptyInstance != nullptr, isolate); - return canary->emptyInstance.get(); + size_t index = static_cast(kind); + tns::Assert(canary != nullptr && canary->emptyInstance[index] != nullptr, isolate); + return canary->emptyInstance[index].get(); } return Caches::Get(isolate)->EmptyObjCtorFunc.get(); } @@ -741,7 +747,7 @@ bool IsKVOSubclassOf(Class klass, Class base) { void ArgConverter::ConstructObject(Local context, const FunctionCallbackInfo& info, Class klass, const InterfaceMeta* interfaceMeta, - bool thisIntercepts) { + CanaryKind thisKind) { Isolate* isolate = v8::Isolate::GetCurrent(); tns::Assert(klass != nullptr, isolate); WrapperLifetime::DrainAtCallEntry(isolate); @@ -805,20 +811,23 @@ bool IsKVOSubclassOf(Class klass, Class base) { ObjCDataWrapper* wrapper = new ObjCDataWrapper(result); Local thiz = info.This(); Local context = cache->GetContext(); - bool intercepted = thisIntercepts; - if (!intercepted && WrapperLifetimeCanary::Intercepts(result)) { - // A canary needs the handlers `this` was built without: returning - // another object makes it the result of `new`, and `this` after super(). + CanaryKind kind = thisKind; + CanaryKind resultKind = WrapperLifetimeCanary::KindOf(result); + if (resultKind != CanaryKind::kNone && resultKind != kind) { + // A canary needs handlers `this` was built without: returning another + // object makes it the result of `new`, and `this` after super(). CanaryWrapperConstructors* canary = Caches::StateFor(isolate); - tns::Assert(canary != nullptr && canary->constructedInstance != nullptr, isolate); - Local replacement = NewEmptyInstance(context, canary->constructedInstance.get()); + size_t index = static_cast(resultKind); + tns::Assert(canary != nullptr && canary->constructedInstance[index] != nullptr, isolate); + Local replacement = + NewEmptyInstance(context, canary->constructedInstance[index].get()); bool success; if (!replacement->SetPrototype(context, thiz->GetPrototype()).To(&success) || !success) { tns::Assert(false, isolate); } thiz = replacement; info.GetReturnValue().Set(thiz); - intercepted = true; + kind = resultKind; } tns::SetValue(isolate, thiz, wrapper); std::shared_ptr> poThiz = ObjectManager::Register(context, thiz); @@ -837,7 +846,7 @@ bool IsKVOSubclassOf(Class klass, Class base) { wrapper->SetBornOnRuntimeThread(); ObjectManager::ProtectIfNativelyRetained(isolate, result, wrapper); } - WrapperLifetime::Adopt(isolate, wrapper, poThiz, result, intercepted); + WrapperLifetime::Adopt(isolate, wrapper, poThiz, result, kind); ExternalMemory::ChargeEstimatedSize(isolate, thiz); } } @@ -1058,7 +1067,7 @@ bool IsKVOSubclassOf(Class klass, Class base) { ObjCAllocDataWrapper* allocDataWrapper = static_cast(wrapper); Class klass = allocDataWrapper->Klass(); - std::shared_ptr> poValue = CreateEmptyObject(context, false); + std::shared_ptr> poValue = CreateEmptyObject(context, CanaryKind::kNone); receiver = poValue->Get(isolate).As(); const Meta* meta = FindMeta(klass); @@ -1108,8 +1117,8 @@ bool IsKVOSubclassOf(Class klass, Class base) { receiver = it->second->Get(isolate).As(); WrapperLifetime::EscapeValue(isolate, receiver); } else { - bool intercepted = WrapperLifetimeCanary::Intercepts(target); - std::shared_ptr> poValue = CreateEmptyObject(context, intercepted); + CanaryKind kind = WrapperLifetimeCanary::KindOf(target); + std::shared_ptr> poValue = CreateEmptyObject(context, kind); receiver = poValue->Get(isolate).As(); tns::SetValue(isolate, receiver, wrapper); cache->Instances.emplace(target, poValue); @@ -1124,7 +1133,7 @@ bool IsKVOSubclassOf(Class klass, Class base) { } if (wrapper->Type() == WrapperType::ObjCObject) { WrapperLifetime::Adopt(isolate, static_cast(wrapper), poValue, target, - intercepted); + kind); } } } else { @@ -1333,7 +1342,7 @@ bool IsKVOSubclassOf(Class klass, Class base) { wrapper->MarkBorrowed(); // Its writes reach the object's JS state through the canary handlers. Local receiver = NewEmptyInstance( - context, EmptyInstanceFunction(isolate, WrapperLifetimeCanary::Intercepts(self))); + context, EmptyInstanceFunction(isolate, WrapperLifetimeCanary::KindOf(self))); CreateJsWrapper(context, wrapper, receiver); WrapperLifetimeCanary::Hydrate(isolate, receiver); *borrowed = wrapper; @@ -1364,9 +1373,9 @@ bool IsKVOSubclassOf(Class klass, Class base) { } std::shared_ptr> ArgConverter::CreateEmptyObject(Local context, - bool intercepted) { + CanaryKind kind) { Isolate* isolate = v8::Isolate::GetCurrent(); - Persistent* ctorFunc = EmptyInstanceFunction(isolate, intercepted); + Persistent* ctorFunc = EmptyInstanceFunction(isolate, kind); tns::Assert(ctorFunc != nullptr, isolate); return ArgConverter::CreateEmptyInstance(context, ctorFunc); } @@ -1390,7 +1399,7 @@ bool IsKVOSubclassOf(Class klass, Class base) { } Local ArgConverter::CreateEmptyInstanceFunction(Local context, - bool intercepted) { + CanaryKind kind) { Isolate* isolate = v8::Isolate::GetCurrent(); Local emptyInstanceCtorFuncTemplate = FunctionTemplate::New(isolate, nullptr); Local instanceTemplate = emptyInstanceCtorFuncTemplate->InstanceTemplate(); @@ -1398,9 +1407,7 @@ bool IsKVOSubclassOf(Class klass, Class base) { instanceTemplate->SetHandler(IndexedPropertyHandlerConfiguration(IndexedPropertyGetterCallback, IndexedPropertySetterCallback)); - if (intercepted) { - WrapperLifetimeCanary::ConfigureInstanceTemplate(instanceTemplate); - } + WrapperLifetimeCanary::ConfigureInstanceTemplate(instanceTemplate, kind); Local emptyInstanceCtorFunc; if (!emptyInstanceCtorFuncTemplate->GetFunction(context).ToLocal(&emptyInstanceCtorFunc)) { diff --git a/NativeScript/runtime/ClassBuilder.mm b/NativeScript/runtime/ClassBuilder.mm index 92fcd674a..a09e67c12 100644 --- a/NativeScript/runtime/ClassBuilder.mm +++ b/NativeScript/runtime/ClassBuilder.mm @@ -113,7 +113,7 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { FunctionTemplate::New(isolate, ExtendedClassConstructorCallback, ext); extendedClassCtorFuncTemplate->InstanceTemplate()->SetInternalFieldCount(1); WrapperLifetimeCanary::ConfigureInstanceTemplate( - extendedClassCtorFuncTemplate->InstanceTemplate()); + extendedClassCtorFuncTemplate->InstanceTemplate(), CanaryKind::kExtended); Local extendClassCtorFunc; if (!extendedClassCtorFuncTemplate->GetFunction(context).ToLocal(&extendClassCtorFunc)) { @@ -180,7 +180,7 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { info.Data().As()->Value(v8::kExternalPointerTypeTagDefault)); Class klass = item->data_; - ArgConverter::ConstructObject(context, info, klass, nullptr, true); + ArgConverter::ConstructObject(context, info, klass, nullptr, CanaryKind::kExtended); } catch (NativeScriptException& ex) { ex.ReThrowToV8(isolate); } diff --git a/NativeScript/runtime/MetadataBuilder.mm b/NativeScript/runtime/MetadataBuilder.mm index b8159ffb8..d01535265 100644 --- a/NativeScript/runtime/MetadataBuilder.mm +++ b/NativeScript/runtime/MetadataBuilder.mm @@ -863,9 +863,8 @@ throw NativeScriptException( ctorFuncTemplate = FunctionTemplate::New(isolate, ClassConstructorCallback, ext); ctorFuncTemplate->InstanceTemplate()->SetInternalFieldCount(1); - if (WrapperLifetimeCanary::NativeInstancesIntercept()) { - WrapperLifetimeCanary::ConfigureInstanceTemplate(ctorFuncTemplate->InstanceTemplate()); - } + WrapperLifetimeCanary::ConfigureInstanceTemplate(ctorFuncTemplate->InstanceTemplate(), + WrapperLifetimeCanary::NativeInstancesKind()); ctorFuncTemplate->SetClassName(tns::ToV8String(isolate, meta->name())); Local baseCtorFunc; @@ -1426,7 +1425,7 @@ void CollectInstanceMemberNames(const BaseClassMeta* meta, Class klass, bool own const InterfaceMeta* interfaceMeta = static_cast(item->meta_); ArgConverter::ConstructObject(context, info, klass, interfaceMeta, - WrapperLifetimeCanary::NativeInstancesIntercept()); + WrapperLifetimeCanary::NativeInstancesKind()); } catch (NativeScriptException& ex) { ex.ReThrowToV8(isolate); } diff --git a/NativeScript/runtime/WrapperLifetime.h b/NativeScript/runtime/WrapperLifetime.h index b1390fc7e..8282d6d4e 100644 --- a/NativeScript/runtime/WrapperLifetime.h +++ b/NativeScript/runtime/WrapperLifetime.h @@ -8,6 +8,7 @@ #include "DataWrapper.h" #include "Helpers.h" #include "ObjectManager.h" +#include "WrapperLifetimeCanary.h" namespace tns { @@ -77,11 +78,11 @@ class WrapperLifetime { // A newly wrapped ObjC object: `handle` is its Instances entry, registered by // ObjectManager::Register and holding the entry's +1 on `target`. - // `intercepted`: the wrapper carries the canary handlers - // (WrapperLifetimeCanary::Intercepts). + // `kind`: the canary handlers the wrapper carries + // (WrapperLifetimeCanary::KindOf). static void Adopt(v8::Isolate* isolate, ObjCDataWrapper* wrapper, const std::shared_ptr>& handle, - id target, bool intercepted); + id target, CanaryKind kind); // 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 diff --git a/NativeScript/runtime/WrapperLifetime.mm b/NativeScript/runtime/WrapperLifetime.mm index 2f4935823..163c5819e 100644 --- a/NativeScript/runtime/WrapperLifetime.mm +++ b/NativeScript/runtime/WrapperLifetime.mm @@ -351,7 +351,7 @@ void ReleaseAll(Isolate* isolate, RootedState* rooted) { void WrapperLifetime::Adopt(Isolate* isolate, ObjCDataWrapper* wrapper, const std::shared_ptr>& handle, id target, - bool intercepted) { + CanaryKind kind) { if (GetWrapperLifetimeMode() == WrapperLifetimeMode::kResurrecting || target == nil) { return; } @@ -372,8 +372,11 @@ void ReleaseAll(Isolate* isolate, RootedState* rooted) { wrapper->SetLifetimeState(state); if (GetWrapperLifetimeMode() == WrapperLifetimeMode::kCanary) { state->lifetimeCanary_ = IsInScope(target); - // A canary without the handlers would lose its JS properties when it dies. - tns::Assert(!state->lifetimeCanary_ || intercepted, isolate); +#ifdef DEBUG + // A canary without its kind's handlers would lose its JS properties when it + // dies. + tns::Assert(!state->lifetimeCanary_ || kind == WrapperLifetimeCanary::KindOf(target), isolate); +#endif if (state->lifetimeCanary_) { state->canaryRecord_ = WrapperLifetimeCanary::Find(isolate, target); if (state->canaryRecord_ != nullptr) { diff --git a/NativeScript/runtime/WrapperLifetimeCanary.h b/NativeScript/runtime/WrapperLifetimeCanary.h index 1eecd8e60..ca49a61ac 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.h +++ b/NativeScript/runtime/WrapperLifetimeCanary.h @@ -3,6 +3,7 @@ #include +#include #include #include @@ -12,6 +13,18 @@ namespace tns { struct CanaryRecord; +// The handlers a wrapper's template carries in canary mode: none for a wrapper +// that is not a canary, and per kind for one that is. A canary must be built +// from a template configured for its object's kind (WrapperLifetimeCanary:: +// KindOf). +enum class CanaryKind : uint8_t { + kNone, + // A canary of an object outside JS-extended classes (scope "all"). + kPlain, + // A canary of an instance of a JS-extended class. + kExtended, +}; + // The canary wrapper lifetime mode (WrapperLifetimeMode::kCanary). // // An ObjC object's wrapper is a canary: a phantom-weak JS object that dies @@ -55,22 +68,22 @@ class WrapperLifetimeCanary { // `imp` unchanged for any other selector, or unless the mode is canary. static IMP WrapDealloc(SEL selector, IMP imp); - // Installs the forwarding handlers on an ObjC instance template. No-op unless - // the mode is canary. Only canaries need them: other wrappers would pay for - // every write and gain nothing. + // Installs `kind`'s handlers on an ObjC instance template. No-op for kNone, + // or unless the mode is canary. Only canaries need them: other wrappers would + // pay for every write and gain nothing. static void ConfigureInstanceTemplate( - v8::Local instanceTemplate); - - // Whether `object`'s wrapper is a canary, so must be built from a template - // ConfigureInstanceTemplate configured. - static bool Intercepts(id object); - - // Whether a native class constructor's instance template gets the handlers: - // under scope "all" its instances are canaries. Under "extended" they are - // canaries only when the constructor yields an instance of a JS-extended - // class (an existing object adopted from a pointer, or one an initializer - // returned instead), which ArgConverter::ConstructObject wraps anew. - static bool NativeInstancesIntercept(); + v8::Local instanceTemplate, CanaryKind kind); + + // The kind of canary `object`'s wrapper is, kNone when it is not one. + static CanaryKind KindOf(id object); + + // The kind a native class constructor's instance template is configured + // for: under scope "all" its instances are plain canaries. Under "extended" + // they are canaries only when the constructor yields an instance of a + // JS-extended class (an existing object adopted from a pointer, or one an + // initializer returned instead), which ArgConverter::ConstructObject wraps + // anew, as it does any result whose kind differs from the template's. + static CanaryKind NativeInstancesKind(); // Adds `unwrap` (a canary's native object -> its weak-collection key) and // `wrap` (key -> live or new canary, or undefined once the object is gone) diff --git a/NativeScript/runtime/WrapperLifetimeCanary.mm b/NativeScript/runtime/WrapperLifetimeCanary.mm index 9ba3a90d0..b0cd9789e 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.mm +++ b/NativeScript/runtime/WrapperLifetimeCanary.mm @@ -221,13 +221,27 @@ void ReportDyingRecordsDied(const DyingRecords& dying, void* object) { // Not a message: a root class without -conformsToProtocol: would crash under // scope "all". Walks the superclasses for key-value observing's subclass. +// Cached per class and thread, as every wrap under scope "all" asks and the +// walk costs tens of nanoseconds a class: the answer for a class is fixed +// before it has instances (ClassBuilder adds TNSDerivedClass to a class it +// creates first thing). A class disposed with objc_disposeClassPair and +// another allocated at its address would read the old answer. bool IsExtendedInstance(id object) { - for (Class cls = object_getClass(object); cls != nil; cls = class_getSuperclass(cls)) { + Class klass = object_getClass(object); + thread_local std::unordered_map extendedClasses; + auto cached = extendedClasses.find(klass); + if (cached != extendedClasses.end()) { + return cached->second; + } + bool extended = false; + for (Class cls = klass; cls != nil; cls = class_getSuperclass(cls)) { if (class_conformsToProtocol(cls, @protocol(TNSDerivedClass))) { - return true; + extended = true; + break; } } - return false; + extendedClasses.emplace(klass, extended); + return extended; } #if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_ASSOCIATION @@ -976,8 +990,9 @@ void WrapCallback(const FunctionCallbackInfo& info) { }); } -void WrapperLifetimeCanary::ConfigureInstanceTemplate(Local instanceTemplate) { - if (GetWrapperLifetimeMode() != WrapperLifetimeMode::kCanary) { +void WrapperLifetimeCanary::ConfigureInstanceTemplate(Local instanceTemplate, + CanaryKind kind) { + if (kind == CanaryKind::kNone || GetWrapperLifetimeMode() != WrapperLifetimeMode::kCanary) { return; } instanceTemplate->SetHandler( @@ -985,14 +1000,19 @@ void WrapCallback(const FunctionCallbackInfo& info) { nullptr, Local(), PropertyHandlerFlags::kNone)); } -bool WrapperLifetimeCanary::Intercepts(id object) { - return GetWrapperLifetimeMode() == WrapperLifetimeMode::kCanary && - WrapperLifetime::InScope(object); +CanaryKind WrapperLifetimeCanary::KindOf(id object) { + if (GetWrapperLifetimeMode() != WrapperLifetimeMode::kCanary || + !WrapperLifetime::InScope(object)) { + return CanaryKind::kNone; + } + return IsExtendedInstance(object) ? CanaryKind::kExtended : CanaryKind::kPlain; } -bool WrapperLifetimeCanary::NativeInstancesIntercept() { +CanaryKind WrapperLifetimeCanary::NativeInstancesKind() { return GetWrapperLifetimeMode() == WrapperLifetimeMode::kCanary && - GetWrapperLifetimeScope() == WrapperLifetimeScope::kAll; + GetWrapperLifetimeScope() == WrapperLifetimeScope::kAll + ? CanaryKind::kPlain + : CanaryKind::kNone; } void WrapperLifetimeCanary::Hydrate(Isolate* isolate, Local wrapper) { From 0060e217634c616be265f1c0bcd8f70c6bcd953a Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 17:07:19 -0300 Subject: [PATCH 2/3] feat(runtime): plain canaries keep their JS properties in the state only Under the canary wrapper lifetime mode with scope "all", wrappers of plain (not JS-extended) objects now carry a non-masking forwarding handler set (getter, setter, query, deleter, enumerator, definer and descriptor) instead of the masking mirror. Their JS properties live in the object's state object only, so a new wrapper for the object needs no copy, and native calls and native property stores never reach the handler. JS-extended instances keep the masking mirror, and allowShadowingNativeMembers keeps plain wrappers on it too. Names the prototype chain has never reach a non-masking handler: an instance assignment or Object.defineProperty over an inherited data property (a native method, toString, valueOf, constructor, a member JS added to a prototype) stays on that wrapper and is gone with it, deleting such a name deletes nothing, and a state property whose name the chain gains later is hidden. A state accessor reached through another receiver (a Proxy, Reflect with a receiver, an inheriting object) runs with the wrapper as `this` and its setter is skipped. These are documented limitations. The setter honours read-only properties and getter-only accessors in the state, which v8::Object::Set would report as written. A record that dies under a live forwarding canary (objc_removeAssociatedObjects) keeps its state while the canary holds it, the leak probe still sees it, and the canary's next write moves the state object, weak-collection key included, into a new record; it is let go once the canary is collected or released. A released forwarding canary gets the state's properties, accessors and attributes included, copied onto it. Release simulator build, plain NSObject, forwarding vs masking: expando read 64 vs 19 ns, miss 47 vs 20, `in` 111 vs 21, expando rewrite 81 vs 105, first write 544 vs 676, UIView tag store 112 vs 219, rebuilding a wrapper with five properties 903 vs 2496 (925 without state). --- NativeScript/runtime/ArgConverter.mm | 6 +- NativeScript/runtime/ObjectManager.mm | 2 + NativeScript/runtime/WrapperLifetime.mm | 9 +- NativeScript/runtime/WrapperLifetimeCanary.h | 54 ++- NativeScript/runtime/WrapperLifetimeCanary.mm | 357 ++++++++++++++++-- .../app/tests/WrapperLifetimeModesTests.js | 279 +++++++++++++- docs/knowledge/v8-resurrecting-finalizers.md | 37 +- docs/ns-builtin-modules.md | 50 ++- types/ns-runtime.d.ts | 12 + 9 files changed, 758 insertions(+), 48 deletions(-) diff --git a/NativeScript/runtime/ArgConverter.mm b/NativeScript/runtime/ArgConverter.mm index 41dd5f5af..d9490c78d 100644 --- a/NativeScript/runtime/ArgConverter.mm +++ b/NativeScript/runtime/ArgConverter.mm @@ -1341,10 +1341,10 @@ bool IsKVOSubclassOf(Class klass, Class base) { // wrapper is neither cached nor owning, and the caller detaches it. wrapper->MarkBorrowed(); // Its writes reach the object's JS state through the canary handlers. - Local receiver = NewEmptyInstance( - context, EmptyInstanceFunction(isolate, WrapperLifetimeCanary::KindOf(self))); + CanaryKind kind = WrapperLifetimeCanary::KindOf(self); + Local receiver = NewEmptyInstance(context, EmptyInstanceFunction(isolate, kind)); CreateJsWrapper(context, wrapper, receiver); - WrapperLifetimeCanary::Hydrate(isolate, receiver); + WrapperLifetimeCanary::Hydrate(isolate, receiver, kind); *borrowed = wrapper; return receiver; } diff --git a/NativeScript/runtime/ObjectManager.mm b/NativeScript/runtime/ObjectManager.mm index e51e10b80..f68e53391 100644 --- a/NativeScript/runtime/ObjectManager.mm +++ b/NativeScript/runtime/ObjectManager.mm @@ -865,7 +865,9 @@ void DisposeHandle(v8::Isolate* isolate, WrapperLifetime::Forget(isolate, adopted); objcWrapper->SetLifetimeState(nullptr); UnlinkRegistered(adopted); + std::shared_ptr record = std::move(adopted->canaryRecord_); delete adopted; + WrapperLifetimeCanary::DropRecord(isolate, std::move(record)); } else if (it != cache->Instances.end()) { std::shared_ptr> handle = it->second; bool wasWeak = handle->IsWeak(); diff --git a/NativeScript/runtime/WrapperLifetime.mm b/NativeScript/runtime/WrapperLifetime.mm index 163c5819e..76b937514 100644 --- a/NativeScript/runtime/WrapperLifetime.mm +++ b/NativeScript/runtime/WrapperLifetime.mm @@ -276,7 +276,8 @@ void PrologueCallback(Isolate* isolate, GCType type, GCCallbackFlags) { } } -void ReleaseQueued(const std::shared_ptr& cache, ObjectWeakCallbackState* state) { +void ReleaseQueued(Isolate* isolate, 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); @@ -285,7 +286,9 @@ void ReleaseQueued(const std::shared_ptr& cache, ObjectWeakCallbackState } delete state->lifetimeWrapper_; std::atomic* counter = state->runtimeRetains_; + std::shared_ptr record = std::move(state->canaryRecord_); delete state; + WrapperLifetimeCanary::DropRecord(isolate, std::move(record)); DropRuntimeRetain(target, counter); [target release]; } @@ -313,7 +316,7 @@ void ReleaseAll(Isolate* isolate, RootedState* rooted) { if (rooted->releases.empty()) { WrapperLifetime::pendingReleaseIsolates_.fetch_sub(1, std::memory_order_relaxed); } - ReleaseQueued(cache, state); + ReleaseQueued(isolate, cache, state); } } @@ -380,7 +383,7 @@ void ReleaseAll(Isolate* isolate, RootedState* rooted) { if (state->lifetimeCanary_) { state->canaryRecord_ = WrapperLifetimeCanary::Find(isolate, target); if (state->canaryRecord_ != nullptr) { - WrapperLifetimeCanary::Hydrate(isolate, handle->Get(isolate).As()); + WrapperLifetimeCanary::Hydrate(isolate, handle->Get(isolate).As(), kind); } } MakeWeak(state); diff --git a/NativeScript/runtime/WrapperLifetimeCanary.h b/NativeScript/runtime/WrapperLifetimeCanary.h index ca49a61ac..c65c7d245 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.h +++ b/NativeScript/runtime/WrapperLifetimeCanary.h @@ -28,13 +28,29 @@ enum class CanaryKind : uint8_t { // The canary wrapper lifetime mode (WrapperLifetimeMode::kCanary). // // An ObjC object's wrapper is a canary: a phantom-weak JS object that dies -// with its JS references, releasing the runtime's retain on the object. A -// masking named interceptor with only a setter, deleter and definer mirrors -// every JS property written to a canary into a state object and then declines, -// so the property also lands on the canary and reads never leave V8. Writes to -// native properties and other inherited accessors are not state. A canary -// built later for the same object gets the state's properties copied back -// (Hydrate). The state object is the source of truth. +// with its JS references, releasing the runtime's retain on the object. Its JS +// properties live in a state object that outlives it, which is the source of +// truth. Writes to native properties and other inherited accessors are not +// state. Two handler sets keep the state: +// +// - Mirroring (kExtended canaries, and kPlain ones when the app config allows +// shadowing native members): a masking named interceptor with only a +// setter, deleter and definer mirrors every JS property written to the +// canary into the state and then declines, so the property also lands on +// the canary and reads never leave V8. A canary built later for the same +// object gets the state's properties copied back (Hydrate). Masking, so it +// also sees an instance write over a name its prototype chain has. +// - Forwarding (kPlain canaries under scope "all" otherwise): a non-masking +// interceptor keeps the properties in the state only, and every access to +// them goes through it; a canary built later needs no copy. V8 calls a +// non-masking interceptor only for names absent from the object and its +// prototype chain, so names the chain has never reach it: an instance write +// over an inherited data property (a native method, toString, constructor, +// a member JS added to a prototype), and Object.defineProperty of such a +// name, land on the canary and die with it; deleting such a name deletes +// nothing. Native members cannot be overridden per instance anyway: native +// code sends messages, which never read JS own properties of a plain +// object. // // The state object is rooted from its first write until the native object is // deallocated. A JS-extended class's own -dealloc reports its instances; for @@ -97,17 +113,30 @@ class WrapperLifetimeCanary { // 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. + // report it as a released-object access. A forwarding canary also gets the + // state's properties copied onto it: once released, its handlers no longer + // reach the state. static void KeepWeakCollectionKey(v8::Isolate* isolate, v8::Local canary); + // Takes a collected or released canary's reference to its record. A record + // that died under that canary kept its state for it (it is the forwarding + // canary's only copy), which can go now. Isolate thread. + static void DropRecord(v8::Isolate* isolate, + std::shared_ptr record); + // The record of an object that already has state in this isolate, for a new // canary to adopt; it is no longer released. Null otherwise. static std::shared_ptr Find(v8::Isolate* isolate, id object); + // Whether `kind`'s canaries carry the forwarding handlers. + static bool Forwards(CanaryKind kind); + // Copies the state of a new canary's object, or of a -dealloc receiver's, - // onto that wrapper. No-op without state, or unless the mode is canary. - static void Hydrate(v8::Isolate* isolate, v8::Local wrapper); + // onto that wrapper of kind `kind`. No-op without state, for a forwarding + // kind, or unless the mode is canary. + static void Hydrate(v8::Isolate* isolate, v8::Local wrapper, + CanaryKind kind); // Teardown: lets go of every state object while the isolate is alive. Tokens // that outlive the isolate find the registry closed. @@ -124,8 +153,9 @@ class WrapperLifetimeCanary { const std::function state)>& visit); // Calls `visit` with every state handle the registry holds: ForEachState's, - // and those of objects being deallocated or deallocated but not yet let go - // of. The caller provides the HandleScope. + // those of objects being deallocated or deallocated but not yet let go of, + // and those of dead forwarding records a canary still holds. Isolate thread; + // the caller provides the HandleScope. static void ForEachStateHandle( v8::Isolate* isolate, const std::function state)>& visit); diff --git a/NativeScript/runtime/WrapperLifetimeCanary.mm b/NativeScript/runtime/WrapperLifetimeCanary.mm index b0cd9789e..d25282eda 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.mm +++ b/NativeScript/runtime/WrapperLifetimeCanary.mm @@ -70,6 +70,12 @@ // __releaseNativeCounterpart released a canary of the object and no canary // adopted the record since. Isolate thread only. bool released = false; + // Its object's canaries forward (WrapperLifetimeCanary::Forwards): the state + // is their only copy of the object's properties. + bool forwards = false; + // The object's address: after the record died, only a canary holding the + // record keeps the object alive (ForEachState reads it then). + void* address = nullptr; ~CanaryRecord() { objc_destroyWeak(&object); } @@ -91,6 +97,9 @@ bool ObjectAlive() const { // Records whose token was deallocated; their handles are reset on the // runtime's thread. std::vector> dead; + // Dead forwarding records a live canary still held when they were drained + // (ReleaseStates). Isolate thread only. + std::vector> orphaned; bool closed = false; bool drainPosted = false; bool sweepPosted = false; @@ -113,6 +122,46 @@ bool ObjectAlive() const { Global objectOfKey; }; +// Isolate thread. Lets go of orphaned records no canary holds any more, and +// of those whose state a canary took over. Only the list's own reference is +// left then, so each handle is reset on this thread. +void SweepOrphaned(CanaryRegistry* registry) { + std::vector>& orphaned = registry->orphaned; + for (auto it = orphaned.begin(); it != orphaned.end();) { + if (it->use_count() > 1 && !(*it)->state.IsEmpty()) { + ++it; + continue; + } + (*it)->state.Reset(); + it = orphaned.erase(it); + } +} + +// Isolate thread. Lets go of the state of `dead` records, except that of a +// forwarding record a canary still holds: the record died under the live +// canary (its object's associations were removed), and its state stays the +// canary's only copy of the object's properties until the canary's next write +// moves it to a new record (StateForWrite). Such a record waits in `orphaned` +// until no canary holds it. Besides canaries, only a JS-implemented -dealloc +// (MarkDying, on the deallocating thread, also for a plain class whose +// -dealloc JS replaced) holds a record outside the registry; such a record is +// dying, and no canary can hold it, as a canary retains its object. +void ReleaseStates(CanaryRegistry* registry, std::vector>& dead) { + ObjectManager::LifetimeStats* stats = ObjectManager::GetLifetimeStats(registry->isolate); + for (std::shared_ptr& record : dead) { + if (record->forwards && !record->dying.load(std::memory_order_acquire) && + !record->state.IsEmpty() && record.use_count() > 1) { + registry->orphaned.push_back(std::move(record)); + } else { + record->state.Reset(); + } + if (stats != nullptr) { + stats->canaryNativeDeaths++; + } + } + SweepOrphaned(registry); +} + void DrainDead(const std::shared_ptr& registry) { std::vector> dead; { @@ -123,13 +172,7 @@ void DrainDead(const std::shared_ptr& registry) { } dead.swap(registry->dead); } - ObjectManager::LifetimeStats* stats = ObjectManager::GetLifetimeStats(registry->isolate); - for (std::shared_ptr& record : dead) { - record->state.Reset(); - if (stats != nullptr) { - stats->canaryNativeDeaths++; - } - } + ReleaseStates(registry.get(), dead); } // From a reporter's -dealloc, on whichever thread deallocates the object. With @@ -244,6 +287,14 @@ bool IsExtendedInstance(id object) { return extended; } +// Plain canaries forward unless the app config allows shadowing native members, +// which only the mirroring handlers capture. +bool PlainCanariesForward() { + return GetWrapperLifetimeMode() == WrapperLifetimeMode::kCanary && + GetWrapperLifetimeScope() == WrapperLifetimeScope::kAll && + !GetAllowShadowingNativeMembers(); +} + #if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_ASSOCIATION // The check objc_setAssociatedObject aborts on: RW_FORBIDS_ASSOCIATED_OBJECTS // in the class_rw_t flags of the object's own class, reached through the mask @@ -295,13 +346,7 @@ void Sweep(const std::shared_ptr& registry) { registry->count.fetch_sub(1, std::memory_order_relaxed); } } - ObjectManager::LifetimeStats* stats = ObjectManager::GetLifetimeStats(registry->isolate); - for (std::shared_ptr& record : dead) { - record->state.Reset(); - if (stats != nullptr) { - stats->canaryNativeDeaths++; - } - } + ReleaseStates(registry.get(), dead); } #endif @@ -497,19 +542,26 @@ bool StateForWrite(Isolate* isolate, Local holder, Local* out) { return false; } id object = canary->lifetimeTarget_; - // The record died under a live canary (its token was removed): the - // canary's properties seed the new state. - bool replacesDied = canary->canaryRecord_ != nullptr; + // The record died under a live canary (its token was removed): a + // forwarding canary's new record takes over the dead record's state + // object, weak-collection key included; a mirroring canary's own + // properties seed a new one. + std::shared_ptr previous = canary->canaryRecord_; // A JS-extended class's own -dealloc reports its instances' deaths. bool extended = IsExtendedInstance(object); + bool forwards = !extended && PlainCanariesForward(); #if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_ASSOCIATION if (!extended && ForbidsAssociatedObjects(object)) { return false; } #endif + bool takesOver = forwards && previous != nullptr && !previous->state.IsEmpty(); // Allocated before the lock: a collection this allocation starts can run // callbacks (the weak sweep's, a finalizer's -dealloc) that take it. - Local freshState = Object::New(isolate, Null(isolate), nullptr, nullptr, 0); + Local freshState; + if (!takesOver) { + freshState = Object::New(isolate, Null(isolate), nullptr, nullptr, 0); + } bool created = false; bool retired = false; { @@ -525,6 +577,8 @@ bool StateForWrite(Isolate* isolate, Local holder, Local* out) { if (slot == nullptr) { auto record = std::make_shared(); record->reportsDeath = extended || NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_ASSOCIATION; + record->forwards = forwards; + record->address = (__bridge void*)object; #if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_WEAK_SWEEP if (!record->reportsDeath) { if (objc_initWeakOrNil(&record->object, object) == nil) { @@ -535,7 +589,17 @@ bool StateForWrite(Isolate* isolate, Local holder, Local* out) { record->weakSet = true; } #endif - record->state.Reset(isolate, freshState); + if (takesOver) { + record->state = std::move(previous->state); + // The weak collections reach the record of a key's object through + // this slot (WrapCallback). The canary retains the object. + if (previous->weakSet && !record->weakSet && + objc_initWeakOrNil(&record->object, object) != nil) { + record->weakSet = true; + } + } else { + record->state.Reset(isolate, freshState); + } slot = std::move(record); registry->count.fetch_add(1, std::memory_order_relaxed); created = true; @@ -556,13 +620,14 @@ bool StateForWrite(Isolate* isolate, Local holder, Local* out) { [token release]; } #endif - if (ObjectManager::LifetimeStats* stats = ObjectManager::GetLifetimeStats(isolate)) { + if (ObjectManager::LifetimeStats* stats = ObjectManager::GetLifetimeStats(isolate); + stats != nullptr && !takesOver) { stats->canaryStates++; } - if (replacesDied) { + if (previous != nullptr && !forwards) { CopyOwnProperties(isolate, isolate->GetCurrentContext(), holder, freshState); } - } else if (Usable(canary->canaryRecord_)) { + } else if (!forwards && Usable(canary->canaryRecord_)) { // Joined state another wrapper of the object wrote: the canary mirrors it. CopyOwnProperties(isolate, isolate->GetCurrentContext(), Local::New(isolate, canary->canaryRecord_->state), holder); @@ -593,7 +658,7 @@ bool HasOwn(Local context, Local state, Local propert return object; } -// The handlers mirror: each copies its write into the state and declines, so +// The mirroring handlers: each copies its write into the state and declines, so // V8 also applies it to the canary, where reads find a real own property and // never call into C++. There is no getter, query, enumerator or descriptor // callback for the same reason. The handlers are masking, so they also see @@ -701,6 +766,202 @@ Intercepted Definer(Local property, const PropertyDescriptor& descript return Intercepted::kNo; } +// The forwarding handlers: the state is the only copy of the canary's +// properties, so every access to them is answered from it and intercepted. +// Non-masking: V8 calls them only for names absent from the canary and its +// prototype chain, so native calls and native property writes never reach C++ +// here. + +// The state the forwarding handlers read: the canary's record's, also once +// that record died under the live canary, until the canary's next write +// carries it over to a new record (StateForWrite); or the record of a receiver +// lent to JS from -dealloc. +bool ForwardedState(Isolate* isolate, Local holder, Local* out) { + // Copying the state onto the canary (KeepWeakCollectionKey) must find no + // current property, or V8 skips defining an identical one. + if (copyingProperties_) { + return false; + } + ObjectWeakCallbackState* canary = CanaryOf(isolate, holder); + if (canary == nullptr) { + std::shared_ptr borrowed = BorrowedRecord(isolate, holder); + if (!Usable(borrowed)) { + return false; + } + *out = Local::New(isolate, borrowed->state); + return true; + } + CanaryRecord* record = canary->canaryRecord_.get(); + if (record == nullptr || record->state.IsEmpty()) { + return false; + } + *out = Local::New(isolate, record->state); + return true; +} + +Intercepted ForwardGetter(Local property, const PropertyCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + Local state; + if (!ForwardedState(isolate, info.Holder(), &state)) { + return Intercepted::kNo; + } + Local context = isolate->GetCurrentContext(); + if (!HasOwn(context, state, property)) { + return Intercepted::kNo; + } + Local value; + // An accessor runs with the canary as `this` (interceptors see the holder, + // not the receiver). + if (state->Get(context, property, info.Holder()).ToLocal(&value)) { + info.GetReturnValue().Set(value); + } + return Intercepted::kYes; +} + +Intercepted ForwardSetter(Local property, Local value, + const PropertyCallbackInfo& info) { + // v8::Object::DefineOwnProperty reaches the setter, not the definer. + if (copyingProperties_) { + return Intercepted::kNo; + } + Isolate* isolate = info.GetIsolate(); + Local holder = info.Holder(); + Local state; + if (!StateForWrite(isolate, holder, &state)) { + return Intercepted::kNo; + } + if (ObjectManager::LifetimeStats* stats = ObjectManager::GetLifetimeStats(isolate)) { + stats->canaryInterceptedWrites++; + } + Local context = isolate->GetCurrentContext(); + // v8::Object::Set reports success for a write [[Set]] rejects, so a + // read-only property and an accessor without a setter are checked here: the + // false return makes V8 throw in strict code. + PropertyAttribute attributes; + if (!state->GetRealNamedPropertyAttributes(context, property).To(&attributes)) { + Maybe created = state->CreateDataProperty(context, property, value); + if (created.IsJust()) { + info.GetReturnValue().Set(created.FromJust()); + } + return Intercepted::kYes; + } + if ((attributes & ReadOnly) != 0) { + info.GetReturnValue().Set(false); + return Intercepted::kYes; + } + if (!state->HasRealNamedCallbackProperty(context, property).FromMaybe(false)) { + Maybe set = state->Set(context, property, value); + if (set.IsJust()) { + info.GetReturnValue().Set(set.FromJust()); + } + return Intercepted::kYes; + } + Local descriptor; + Local setter; + if (!state->GetOwnPropertyDescriptor(context, property).ToLocal(&descriptor) || + !descriptor->IsObject() || + !descriptor.As()->Get(context, tns::ToV8String(isolate, "set")).ToLocal(&setter)) { + return Intercepted::kYes; + } + if (!setter->IsFunction()) { + info.GetReturnValue().Set(false); + return Intercepted::kYes; + } + // An accessor runs with the canary as `this`. + Local argv[] = {value}; + if (!setter.As()->Call(context, holder, 1, argv).IsEmpty()) { + info.GetReturnValue().Set(true); + } + return Intercepted::kYes; +} + +Intercepted ForwardQuery(Local property, const PropertyCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + Local state; + if (!ForwardedState(isolate, info.Holder(), &state)) { + return Intercepted::kNo; + } + Local context = isolate->GetCurrentContext(); + if (!HasOwn(context, state, property)) { + return Intercepted::kNo; + } + PropertyAttribute attributes; + if (state->GetPropertyAttributes(context, property).To(&attributes)) { + info.GetReturnValue().Set(v8::Integer::New(isolate, attributes)); + } + return Intercepted::kYes; +} + +Intercepted ForwardDeleter(Local property, + const PropertyCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + Local state; + if (!ForwardedState(isolate, info.Holder(), &state)) { + return Intercepted::kNo; + } + Local context = isolate->GetCurrentContext(); + if (!HasOwn(context, state, property)) { + return Intercepted::kNo; + } + bool deleted; + if (state->Delete(context, property).To(&deleted)) { + info.GetReturnValue().Set(deleted); + } + return Intercepted::kYes; +} + +void ForwardEnumerator(const PropertyCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + Local state; + if (!ForwardedState(isolate, info.Holder(), &state)) { + return; + } + Local names; + if (state + ->GetPropertyNames(isolate->GetCurrentContext(), KeyCollectionMode::kOwnOnly, + PropertyFilter::ALL_PROPERTIES, IndexFilter::kSkipIndices) + .ToLocal(&names)) { + info.GetReturnValue().Set(names); + } +} + +Intercepted ForwardDefiner(Local property, const PropertyDescriptor& descriptor, + const PropertyCallbackInfo& info) { + if (copyingProperties_) { + return Intercepted::kNo; + } + Isolate* isolate = info.GetIsolate(); + Local state; + if (!StateForWrite(isolate, info.Holder(), &state)) { + return Intercepted::kNo; + } + bool defined; + if (state + ->DefineProperty(isolate->GetCurrentContext(), property, + const_cast(descriptor)) + .To(&defined)) { + info.GetReturnValue().Set(defined); + } + return Intercepted::kYes; +} + +Intercepted ForwardDescriptor(Local property, const PropertyCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + Local state; + if (!ForwardedState(isolate, info.Holder(), &state)) { + return Intercepted::kNo; + } + Local context = isolate->GetCurrentContext(); + if (!HasOwn(context, state, property)) { + return Intercepted::kNo; + } + Local descriptor; + if (state->GetOwnPropertyDescriptor(context, property).ToLocal(&descriptor)) { + info.GetReturnValue().Set(descriptor); + } + return Intercepted::kYes; +} + #if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_WEAK_SWEEP // Posts a sweep when a major collection ends, behind the release drain the // collection queued: objects it released are gone by the time the sweep runs. @@ -929,6 +1190,9 @@ void WrapCallback(const FunctionCallbackInfo& info) { // write repeats, a bounded number of times, until it stores the current key. constexpr int kMaxWrites = 4; std::shared_ptr record = currentRecord(); + if (record != nullptr && record->forwards && !record->state.IsEmpty()) { + CopyOwnProperties(isolate, context, Local::New(isolate, record->state), canary); + } Local copy = keyOf(record); for (int writes = 1;; writes++) { // Private symbols bypass the canary's handlers. @@ -995,11 +1259,21 @@ void WrapCallback(const FunctionCallbackInfo& info) { if (kind == CanaryKind::kNone || GetWrapperLifetimeMode() != WrapperLifetimeMode::kCanary) { return; } + if (Forwards(kind)) { + instanceTemplate->SetHandler(NamedPropertyHandlerConfiguration( + ForwardGetter, ForwardSetter, ForwardQuery, ForwardDeleter, ForwardEnumerator, + ForwardDefiner, ForwardDescriptor, Local(), PropertyHandlerFlags::kNonMasking)); + return; + } instanceTemplate->SetHandler( NamedPropertyHandlerConfiguration(nullptr, Setter, nullptr, Deleter, nullptr, Definer, nullptr, Local(), PropertyHandlerFlags::kNone)); } +bool WrapperLifetimeCanary::Forwards(CanaryKind kind) { + return kind == CanaryKind::kPlain && PlainCanariesForward(); +} + CanaryKind WrapperLifetimeCanary::KindOf(id object) { if (GetWrapperLifetimeMode() != WrapperLifetimeMode::kCanary || !WrapperLifetime::InScope(object)) { @@ -1015,8 +1289,8 @@ void WrapCallback(const FunctionCallbackInfo& info) { : CanaryKind::kNone; } -void WrapperLifetimeCanary::Hydrate(Isolate* isolate, Local wrapper) { - if (GetWrapperLifetimeMode() != WrapperLifetimeMode::kCanary) { +void WrapperLifetimeCanary::Hydrate(Isolate* isolate, Local wrapper, CanaryKind kind) { + if (GetWrapperLifetimeMode() != WrapperLifetimeMode::kCanary || Forwards(kind)) { return; } HandleScope scope(isolate); @@ -1031,6 +1305,18 @@ void WrapCallback(const FunctionCallbackInfo& info) { CopyOwnProperties(isolate, context, state, wrapper); } +void WrapperLifetimeCanary::DropRecord(Isolate* isolate, std::shared_ptr record) { + if (record == nullptr || !record->forwards || !record->died.load(std::memory_order_acquire)) { + return; + } + record.reset(); + CanaryState* state = Caches::ExistingStateFor(isolate); + if (state == nullptr || state->registry->orphaned.empty()) { + return; + } + SweepOrphaned(state->registry.get()); +} + std::shared_ptr WrapperLifetimeCanary::Find(Isolate* isolate, id object) { CanaryState* state = Caches::StateFor(isolate); if (state == nullptr || state->registry->count.load(std::memory_order_relaxed) == 0) { @@ -1065,12 +1351,16 @@ void WrapCallback(const FunctionCallbackInfo& info) { for (std::shared_ptr& record : state->registry->dead) { record->state.Reset(); } + for (std::shared_ptr& record : state->registry->orphaned) { + record->state.Reset(); + } } void WrapperLifetimeCanary::ForEachState( Isolate* isolate, const std::function state)>& visit) { CanaryState* state = Caches::StateFor(isolate); - if (state == nullptr || state->registry->count.load(std::memory_order_relaxed) == 0) { + if (state == nullptr || (state->registry->count.load(std::memory_order_relaxed) == 0 && + state->registry->orphaned.empty())) { return; } std::vector>> live; @@ -1106,6 +1396,15 @@ void WrapCallback(const FunctionCallbackInfo& info) { } } } + // Isolate thread only, as is the list: a record held by a canary has a live + // object, retained by that canary. + for (const std::shared_ptr& record : state->registry->orphaned) { + if (record.use_count() < 2 || record->state.IsEmpty() || + record->dying.load(std::memory_order_acquire)) { + continue; + } + live.emplace_back([(__bridge id)record->address retain], record); + } // Read before any visit, whose release can run JS. Only this thread resets // state handles. std::vector> states; @@ -1142,6 +1441,12 @@ void WrapCallback(const FunctionCallbackInfo& info) { } } } + // Isolate thread only, as is the list. + for (const std::shared_ptr& record : state->registry->orphaned) { + if (!record->state.IsEmpty()) { + handles.push_back(record->state.Get(isolate)); + } + } for (Local handle : handles) { visit(handle); } diff --git a/TestRunner/app/tests/WrapperLifetimeModesTests.js b/TestRunner/app/tests/WrapperLifetimeModesTests.js index cbc18c310..4f616ba72 100644 --- a/TestRunner/app/tests/WrapperLifetimeModesTests.js +++ b/TestRunner/app/tests/WrapperLifetimeModesTests.js @@ -914,7 +914,8 @@ describe("Wrapper lifetime modes", function () { // Third-party code can strip a live object's associations. Where an // associated token reports native death, the record goes with it, and the - // next write seeds a new state from the canary's own properties. + // next write seeds a new state from the canary's own properties, or from + // the dead record's state for a plain canary that forwards. it("survives a live object's associations being removed", function (done) { if (typeof objc_removeAssociatedObjects !== "function") { done(); @@ -1533,4 +1534,280 @@ describe("Wrapper lifetime modes", function () { }); }); }); + + // Under scope "all", a plain native object's canary keeps its JS + // properties in the state only (forwarding), unless the app config allows + // shadowing native members, which only the mirroring handlers capture. + describe("plain canaries", function () { + var allowShadowing = runtime.getConfig("wrapperLifetimeAllowShadowingNativeMembers"); + var plainKeepsState = keepsState && scope === "all"; + var forwarding = canary && scope === "all" && !allowShadowing; + + // rewrap for a plain object, which only scope "all" makes a canary. + function rewrapPlain(make, callback) { + var owner = NSMutableArray.new(); + var first; + (function () { + var obj = make(); + owner.addObject(obj); + first = new WrapperWeakRef(obj); + })(); + settle(2, function () { + if (canary && scope === "all") { + expect(first.deref()).toBeUndefined(); + } + callback(owner.objectAtIndex(0)); + }); + } + + it("reports whether native members may be shadowed (" + allowShadowing + ")", function () { + expect(typeof allowShadowing).toBe("boolean"); + expect(function () { + runtime.setConfig("wrapperLifetimeAllowShadowingNativeMembers", !allowShadowing); + }).toThrowError(TypeError, /read-only/); + }); + + it("keeps own-property semantics for JS properties on a plain native object", function () { + var key = Symbol("key"); + var obj = TNSAllocLog.new(); + obj.a = 1; + obj[key] = 2; + Object.defineProperty(obj, "hidden", { value: 3, enumerable: false, configurable: true }); + Object.defineProperty(obj, "fixed", { value: 4, enumerable: true }); + Object.defineProperty(obj, "me", { + get: function () { + return this; + }, + configurable: true + }); + + expect(Object.keys(obj)).toEqual(["a", "fixed"]); + expect(Object.getOwnPropertyNames(obj).sort()).toEqual(["a", "fixed", "hidden", "me"]); + expect(Object.getOwnPropertySymbols(obj)).toEqual([key]); + expect("a" in obj).toBe(true); + expect(hasOwn(obj, "hidden")).toBe(true); + expect(obj.hidden).toBe(3); + expect(obj[key]).toBe(2); + expect(obj.me).toBe(obj); + expect(Object.getOwnPropertyDescriptor(obj, "fixed")).toEqual({ + value: 4, writable: false, enumerable: true, configurable: false + }); + expect(strictAssignThrows(obj, "fixed", 5)).toBe(true); + expect(obj.fixed).toBe(4); + expect(strictAssignThrows(obj, "me", 5)).toBe(true); + var receiver; + Object.defineProperty(obj, "watched", { + set: function () { + receiver = this; + }, + configurable: true + }); + obj.watched = 1; + expect(receiver).toBe(obj); + receiver = null; + expect(delete obj.fixed).toBe(false); + expect(JSON.parse(JSON.stringify(obj))).toEqual({ a: 1, fixed: 4 }); + + expect(delete obj.a).toBe(true); + expect("a" in obj).toBe(false); + expect(obj.a).toBeUndefined(); + expect(hasOwn(obj, "isEqual")).toBe(false); + }); + + it("hands back a plain object's JS properties with their attributes on a new wrapper", function (done) { + var key = Symbol("key"); + var payload = {}; + rewrapPlain(function () { + var obj = TNSAllocLog.new(); + obj.visible = 1; + obj.payload = payload; + obj[key] = 2; + Object.defineProperty(obj, "hidden", { value: 3, writable: true, configurable: true }); + Object.defineProperty(obj, "me", { + get: function () { + return this; + }, + configurable: true + }); + return obj; + }, function (obj) { + if (plainKeepsState) { + expect(Object.keys(obj)).toEqual(["visible", "payload"]); + expect(Object.getOwnPropertyNames(obj).sort()).toEqual(["hidden", "me", "payload", "visible"]); + expect(obj.payload).toBe(payload); + expect(obj[key]).toBe(2); + expect(obj.me).toBe(obj); + expect(Object.getOwnPropertyDescriptor(obj, "hidden")).toEqual({ + value: 3, writable: true, enumerable: false, configurable: true + }); + obj.visible = 5; + expect(obj.visible).toBe(5); + } + done(); + }); + }); + + it("counts the writes of new names to a plain canary", function () { + var obj = TNSAllocLog.new(); + var before = runtime.getWrapperLifetimeStats().canaryInterceptedWrites; + obj.first = 1; + obj.second = 2; + var writes = runtime.getWrapperLifetimeStats().canaryInterceptedWrites - before; + expect(writes).toBe(canary && scope === "all" ? 2 : 0); + }); + + // Names the prototype chain has never reach a forwarding canary's + // handlers: such writes and defines land on the canary and die with it. + it("keeps an instance write over an inherited data property on its wrapper only", function (done) { + TNSAllocLog.prototype.wrapperLifetimeJsMember = function () { + return "prototype"; + }; + rewrapPlain(function () { + var obj = TNSAllocLog.new(); + obj.valueOf = function () { + return 42; + }; + obj.wrapperLifetimeJsMember = function () { + return "shadow"; + }; + obj.tag = "kept"; + expect(+obj).toBe(42); + expect(obj.wrapperLifetimeJsMember()).toBe("shadow"); + expect(hasOwn(obj, "valueOf")).toBe(true); + return obj; + }, function (obj) { + var member = obj.wrapperLifetimeJsMember(); + delete TNSAllocLog.prototype.wrapperLifetimeJsMember; + if (plainKeepsState) { + expect(obj.tag).toBe("kept"); + } + if (forwarding) { + expect(hasOwn(obj, "valueOf")).toBe(false); + expect(obj.valueOf()).toBe(obj); + expect(member).toBe("prototype"); + } else if (plainKeepsState) { + expect(+obj).toBe(42); + expect(member).toBe("shadow"); + } + done(); + }); + }); + + it("keeps a property defined over an inherited name on its wrapper only", function (done) { + rewrapPlain(function () { + var obj = TNSAllocLog.new(); + Object.defineProperty(obj, "isEqual", { + value: function () { + return "defined"; + }, + writable: true, + configurable: true + }); + obj.tag = "kept"; + expect(obj.isEqual(obj)).toBe("defined"); + return obj; + }, function (obj) { + if (plainKeepsState) { + expect(obj.tag).toBe("kept"); + } + if (forwarding) { + expect(hasOwn(obj, "isEqual")).toBe(false); + expect(obj.isEqual(obj)).toBe(true); + } else if (plainKeepsState) { + expect(obj.isEqual(obj)).toBe("defined"); + } + done(); + }); + }); + + it("deletes nothing when an inherited name is deleted", function () { + var obj = TNSAllocLog.new(); + var isEqual = TNSAllocLog.prototype.isEqual; + expect(delete obj.isEqual).toBe(true); + expect(obj.isEqual).toBe(isEqual); + expect(TNSAllocLog.prototype.isEqual).toBe(isEqual); + expect(obj.isEqual(obj)).toBe(true); + }); + + it("keeps a released plain canary's JS properties", function () { + var payload = {}; + var obj = TNSAllocLog.new(); + obj.tag = "kept"; + obj.payload = payload; + __releaseNativeCounterpart(obj); + expect(obj.tag).toBe("kept"); + expect(obj.payload).toBe(payload); + expect(Object.keys(obj)).toEqual(["tag", "payload"]); + }); + + it("keeps a released plain canary's accessors and read-only properties with their attributes", function () { + var obj = TNSAllocLog.new(); + Object.defineProperty(obj, "me", { + get: function () { + return this; + }, + configurable: true + }); + Object.defineProperty(obj, "fixed", { value: 4, enumerable: true }); + obj.plain = 5; + __releaseNativeCounterpart(obj); + expect(obj.me).toBe(obj); + var me = Object.getOwnPropertyDescriptor(obj, "me"); + expect(me && typeof me.get).toBe("function"); + expect(me && me.set).toBeUndefined(); + expect(me && me.enumerable).toBe(false); + expect(me && me.configurable).toBe(true); + expect(Object.getOwnPropertyDescriptor(obj, "fixed")).toEqual({ + value: 4, writable: false, enumerable: true, configurable: false + }); + expect(Object.getOwnPropertyDescriptor(obj, "plain")).toEqual({ + value: 5, writable: true, enumerable: true, configurable: true + }); + expect(Object.keys(obj)).toEqual(["fixed", "plain"]); + }); + + // Third-party code can strip a live object's associations, which ends + // its record. A forwarding canary keeps reading that record's state, + // and its next write carries it over to a new record. + it("keeps a live plain object's JS properties after its associations are removed", function (done) { + if (typeof objc_removeAssociatedObjects !== "function") { + done(); + return; + } + var map = new WeakMap(); + var value = {}; + var obj = TNSAllocLog.new(); + obj.tag = "first"; + obj.other = "kept"; + map.set(obj, value); + objc_removeAssociatedObjects(obj); + settle(2, function () { + expect(obj.tag).toBe("first"); + expect(obj.other).toBe("kept"); + expect(Object.keys(obj)).toEqual(["tag", "other"]); + obj.tag = "second"; + expect(obj.tag).toBe("second"); + expect(obj.other).toBe("kept"); + // The new record took over the state, and the weak + // collections' key with it. + if (forwarding) { + expect(map.get(obj)).toBe(value); + } + rewrapPlain(function () { + var made = obj; + obj = null; + return made; + }, function (again) { + if (plainKeepsState) { + expect(again.tag).toBe("second"); + expect(again.other).toBe("kept"); + } + if (forwarding) { + expect(map.get(again)).toBe(value); + } + done(); + }); + }); + }); + }); }); diff --git a/docs/knowledge/v8-resurrecting-finalizers.md b/docs/knowledge/v8-resurrecting-finalizers.md index d32a9eeae..54cc38406 100644 --- a/docs/knowledge/v8-resurrecting-finalizers.md +++ b/docs/knowledge/v8-resurrecting-finalizers.md @@ -289,7 +289,42 @@ of 125 (380 instead of 115 four prototypes up) while the handler left it to V8; setter from the handler brings it from about 324 to 289 ns two prototypes up and from 396 to 324 for a `UIButton` `tag` four up (323 to 292 and 392 to 334 under `"all"`, where a plain `UIButton`'s goes from 322 to 266). Building a canary for an object with state costs -about 330 ns per state property. Instances of JS-extended classes report their own +about 330 ns per state property. + +That masking handler is what JS-extended instances keep. Under `"scope": "all"`, wrappers of +plain objects get a non-masking forwarding set instead (getter, setter, query, deleter, +enumerator, definer and descriptor), unless `"allowShadowingNativeMembers": true` in the app +config gives them the masking one: the state is the only copy of their properties, every access +to one is answered from it, and a new canary needs no copy. V8 calls a non-masking interceptor +only for names absent from the object and its whole prototype chain, own lookups included +(WebIDL's named-property visibility, `LookupIterator::kSkipNonMaskingOwnProperty`), so native +calls and native property stores never reach C++. ObjC prototypes carry the swizzle interceptor, +which made an own lookup on such a canary stop at the prototype until the prebuilts' patch +`v8_nonmasking_own_lookup` (v8-buildscripts #11): without it `delete obj.m` deleted `m` from the +prototype. The holes are names the chain has: an instance write or `Object.defineProperty` over +an inherited data property (a native method, `toString`, `valueOf`, `constructor`, a member JS put +on a prototype) creates an own property of that canary only, and deleting such a name deletes +nothing. `v8::Object::Set` reports success for a store `[[Set]]` rejects, so the setter checks a +read-only property and a getter-only accessor in the state itself, and runs a state accessor's +setter with the canary as `this`. A record that dies under a live forwarding canary +(`objc_removeAssociatedObjects`) keeps its state while the canary holds it (`ReleaseStates` parks +it in `orphaned`, which the leak probe also walks, and `DropRecord` sweeps once the canary is +collected or released); the canary keeps reading it, and its next write moves the state object +into a new record, so what the weak collections keyed on the object survives too. A released +forwarding canary gets the state's properties copied onto it (`KeepWeakCollectionKey`), since its +handlers no longer reach the state; the handlers answer nothing while that copy runs, or V8 would +find each property already defined and skip it. An accessor kept in the state sees the canary as +`this` whatever the receiver, and a write through a Proxy or an inheriting object never runs its +setter: interceptors are given only the holder, and V8 consults only the query callback when the +holder is not the receiver. Measured on a Release +simulator build (iPhone 16 Pro simulator, jitless), forwarding vs masking for a plain `NSObject`: +an expando read takes 64 ns instead of 19 and a miss 47 instead of 20, `in` 111 instead of 21, an +expando rewrite 81 instead of 105, a first write creating the state 544 instead of 676, a native +property store (`UIView` `tag`) 112 instead of 219, and wrapping an object with five state +properties again costs what wrapping one without state does (903 vs 925 ns) instead of 2496; +native method calls and native property reads are unchanged. + +Instances of JS-extended classes report their own deallocation: the runtime gives each extended class a `-dealloc` that marks the instance's records dying in every isolate, calls the superclass's (which can be a JS one the class inherits, whose receiver still reads the state), and then retires them. For other objects it is diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 49f39927f..a198fe64d 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -120,7 +120,7 @@ Config keys: | `wrapperLifetimeWarnings` | `true` \| `false` | process-wide (main-isolate writes only; read live by every isolate); no effect in the `"rooted"` and `"canary"` modes | the app config `"wrapperLifetime": { "warnings": … }`, or on in debug builds | | `wrapperLifetimeMode` | `"resurrecting"` \| `"rooted"` \| `"canary"` | 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"` | -| `wrapperLifetimeAllowShadowingNativeMembers` | `true` \| `false` | process-wide, read-only | the app config `"wrapperLifetime": { "allowShadowingNativeMembers": … }`, or `false` (see [Native member guard](#native-member-guard)) | +| `wrapperLifetimeAllowShadowingNativeMembers` | `true` \| `false` | process-wide, read-only | the app config `"wrapperLifetime": { "allowShadowingNativeMembers": … }`, or `false` (see [Native member guard](#native-member-guard) and [Plain canaries](#plain-canaries)) | ```js const { setConfig, getConfig } = require("ns:runtime"); @@ -183,6 +183,48 @@ or return value becomes `nil` (`NSNull` inside a collection) and a value there (an attributes dictionary holding a released `UIColor`, say); the event names the element so the cause can be found. +### Plain canaries + +Under `"canary"` with scope `"all"`, a wrapper of a plain (not JS-extended) +native object keeps its JS properties in the object's state only: a +non-masking handler answers every read, write, `in`, `delete`, enumeration and +`Object.defineProperty` of them from the state, so a new wrapper for the object +needs no copy, while each access to such a property costs a native call. +JS-extended instances keep the mirroring handler (properties live on the +wrapper too and are copied onto a new one), because `this.onTap = +this.onTap.bind(this)` and other writes over names their prototype has must +carry over. + +V8 calls a non-masking handler only for names absent from the object and its +prototype chain, so on a plain wrapper: + +- an assignment or `Object.defineProperty` over an inherited data property (a + native method, `toString`, `valueOf`, `constructor`, a member JS added to a + prototype) creates an own property of that wrapper alone, gone once a new + wrapper replaces it. Native code never sees such a property either way: it + sends the message, which runs the class's implementation. In debug builds the + assignment throws for the members the native member guard covers; +- `delete` of an inherited name deletes nothing and returns `true`; +- a property kept in the state before the prototype chain gets the same name + (JS adds it to a native prototype, or a later wrapper of the object has a + different prototype) is hidden by the inherited one: reads and + `hasOwnProperty` see that one and new writes land on the wrapper, while + `Object.keys` still lists the name; +- native property writes run the native setter with no handler involved. + +A handler sees the object it is installed on, not the receiver of the access. +So an accessor property kept in the state and reached through another +receiver (a Proxy around the wrapper, `Reflect.get` or `Reflect.set` with a +receiver, `Object.create(wrapper)`) runs its getter with the wrapper itself as +`this`, and a write through such a receiver never runs its setter: through a +Proxy it fails (a `TypeError` in strict code), and on an object inheriting +from the wrapper it defines an own data property there. Data properties work +through all of them. Under `allowShadowingNativeMembers` the accessor is a +real property of the wrapper and behaves as on any object. + +`allowShadowingNativeMembers` (see [Native member guard](#native-member-guard)) +gives plain wrappers the mirroring handler instead. + ### Weak collections in canary mode In the `"canary"` mode a wrapper dies with its JS references while its native @@ -277,7 +319,11 @@ object: use it for a JS-only member that native code is not meant to see. Class fields have define semantics and bypass the guard the same way. `"wrapperLifetime": { "allowShadowingNativeMembers": true }` in the app config -turns the guard off, leaving data properties as in the `"resurrecting"` mode; +turns the guard off, leaving data properties as in the `"resurrecting"` mode, +and under `"canary"` with scope `"all"` also keeps plain wrappers on the +mirroring handler, so a shadowing property on one carries over to a new +wrapper as it does on a JS-extended instance, at the cost of a handler on every +write to a plain wrapper (see [Plain canaries](#plain-canaries)); `getConfig("wrapperLifetimeAllowShadowingNativeMembers")` reads it. Release builds never throw and keep data properties, since the accessor costs diff --git a/types/ns-runtime.d.ts b/types/ns-runtime.d.ts index ae7d53692..854bff043 100644 --- a/types/ns-runtime.d.ts +++ b/types/ns-runtime.d.ts @@ -63,6 +63,13 @@ declare module "ns:runtime" { * it lives, and one whose class forbids associated objects (or, under * the alternative death signal, refuses weak references) gets none. * Native property writes still reach the native setter. Writes cost more than in the other modes; reads do not. + * Under scope `"all"`, a plain (not JS-extended) object's properties are + * kept in its state object only, so reading one costs a native call and a + * new wrapper needs no copy; an instance assignment or + * `Object.defineProperty` over a name its prototype chain has (a native + * method, `toString`, `valueOf`, a member JS added to a prototype) stays + * on that wrapper and is gone with it. `wrapperLifetimeAllowShadowingNativeMembers` + * makes plain objects' wrappers keep such properties too. * WeakMap, WeakSet, WeakRef and FinalizationRegistry key such native * objects by their lifetime in this mode, so they carry over too; a * WeakMap value that references its own native key keeps that object @@ -90,6 +97,11 @@ declare module "ns:runtime" { * on a native object throws a `TypeError`, since native code never calls * a JS own property of a native object; `true` turns that off. Those members are then accessor pairs on their class's prototype. * Release builds and the `"resurrecting"` mode never throw. + * Under `"canary"` with scope `"all"`, `true` also gives a plain (not + * JS-extended) object's wrapper the mirroring handler JS-extended + * instances' wrappers have, so JS properties over a name its prototype + * chain has carry over to a new wrapper too, at the cost of a write + * handler on every write. */ wrapperLifetimeAllowShadowingNativeMembers: boolean; } From 4480eea9962488a045ac9bb785b86e86ce77b35b Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 23:27:48 -0300 Subject: [PATCH 3/3] fix(runtime): a released forwarding canary keeps the properties it owns --- NativeScript/runtime/WrapperLifetimeCanary.mm | 12 +++++++++--- .../app/tests/WrapperLifetimeModesTests.js | 16 ++++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/NativeScript/runtime/WrapperLifetimeCanary.mm b/NativeScript/runtime/WrapperLifetimeCanary.mm index d25282eda..0e5e34688 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.mm +++ b/NativeScript/runtime/WrapperLifetimeCanary.mm @@ -472,9 +472,10 @@ void PostDrain(const std::shared_ptr& registry) { // Copies `from`'s own string- and symbol-keyed properties onto `to`, with their // attributes; an accessor keeps its functions, which run with whichever object -// they are reached through as `this`. +// they are reached through as `this`. With `keepExisting`, a name `to` already +// owns keeps its property. void CopyOwnProperties(Isolate* isolate, Local context, Local from, - Local to) { + Local to, bool keepExisting = false) { HandleScope scope(isolate); TryCatch tc(isolate); bool wasCopying = copyingProperties_; @@ -489,6 +490,9 @@ void CopyOwnProperties(Isolate* isolate, Local context, Local f continue; } Local key = name.As(); + if (keepExisting && to->HasRealNamedProperty(context, key).FromMaybe(true)) { + continue; + } if (!from->HasRealNamedCallbackProperty(context, key).FromMaybe(true)) { PropertyAttribute attributes; Local value; @@ -1191,7 +1195,9 @@ void WrapCallback(const FunctionCallbackInfo& info) { constexpr int kMaxWrites = 4; std::shared_ptr record = currentRecord(); if (record != nullptr && record->forwards && !record->state.IsEmpty()) { - CopyOwnProperties(isolate, context, Local::New(isolate, record->state), canary); + // A name the prototype chain has never reaches a forwarding canary's + // handlers, so a property the canary owns is newer than the state's. + CopyOwnProperties(isolate, context, Local::New(isolate, record->state), canary, true); } Local copy = keyOf(record); for (int writes = 1;; writes++) { diff --git a/TestRunner/app/tests/WrapperLifetimeModesTests.js b/TestRunner/app/tests/WrapperLifetimeModesTests.js index 4f616ba72..8eabd8014 100644 --- a/TestRunner/app/tests/WrapperLifetimeModesTests.js +++ b/TestRunner/app/tests/WrapperLifetimeModesTests.js @@ -1766,6 +1766,22 @@ describe("Wrapper lifetime modes", function () { expect(Object.keys(obj)).toEqual(["fixed", "plain"]); }); + // A name the prototype chain gained after the first write never reaches + // a forwarding canary's handlers again: later writes land on the canary. + it("keeps a released plain canary's latest write to a name its prototype gained", function () { + var obj = TNSAllocLog.new(); + obj.wrapperLifetimeLateInherited = 1; + TNSAllocLog.prototype.wrapperLifetimeLateInherited = 0; + try { + obj.wrapperLifetimeLateInherited = 2; + expect(obj.wrapperLifetimeLateInherited).toBe(2); + __releaseNativeCounterpart(obj); + expect(obj.wrapperLifetimeLateInherited).toBe(2); + } finally { + delete TNSAllocLog.prototype.wrapperLifetimeLateInherited; + } + }); + // Third-party code can strip a live object's associations, which ends // its record. A forwarding canary keeps reading that record's state, // and its next write carries it over to a new record.