From 81d83dee42d12fe1796ddbb95b4b885cce68e3bd Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Thu, 12 Nov 2026 19:32:53 -0300 Subject: [PATCH 01/24] feat(runtime): canary wrapper lifetime mode Adds "wrapperLifetime": { "mode": "canary" }, the portable resurrection- free model: the one the Node-API runtimes and Android can implement too. - A wrapper in scope is a canary: a phantom-weak JS object that dies with its JS references and releases the runtime's retain through the same queue as "rooted". No retain counts are read. - kNonMasking named interceptors on the three ObjC instance templates forward JS properties to a null-prototype state object. Prototype members (native methods and properties, JS-extended class methods) are found before the interceptors and never reach them. - The state object is rooted from its first write until the native object is deallocated, reported by an associated token's -dealloc. A canary built later for the same object forwards to the same state. The state cannot be rooted only once the canary dies: a state reachable only through the canary is garbage in the same collection. So state that references its own object (a closure over `this`) keeps it alive; the iOS-only alternative, unrooting at major-GC start when nothing native owns the object, is left as a marked switch point in WrapperLifetimeCanary.h. Records are shared between the registry and the canary and carry a died flag, so objc_removeAssociatedObjects on a live object leaves its canary with no state instead of a dangling record. Teardown empties every state handle while the isolate is alive and later token deallocs find the registry closed. Requires V8's own-property lookups through kNonMasking interceptors to skip a prototype's named interceptor (crbug 585053531), which the V8 prebuilts get from v8_nonmasking_own_lookup.patch. --- NativeScript/runtime/ArgConverter.mm | 4 +- NativeScript/runtime/ClassBuilder.mm | 15 +- NativeScript/runtime/MetadataBuilder.mm | 2 + NativeScript/runtime/NsBuiltinModules.cpp | 2 + NativeScript/runtime/ObjectManager.h | 11 + NativeScript/runtime/WrapperLifetime.h | 13 +- NativeScript/runtime/WrapperLifetime.mm | 32 +- NativeScript/runtime/WrapperLifetimeCanary.h | 53 +++ NativeScript/runtime/WrapperLifetimeCanary.mm | 393 ++++++++++++++++++ .../app/tests/WrapperLifetimeModesTests.js | 163 +++++++- TestRunner/app/tests/WrapperLifetimeTests.js | 2 + docs/knowledge/v8-resurrecting-finalizers.md | 20 + docs/ns-builtin-modules.md | 8 +- types/ns-runtime.d.ts | 15 +- v8ios.xcodeproj/project.pbxproj | 8 + 15 files changed, 709 insertions(+), 32 deletions(-) create mode 100644 NativeScript/runtime/WrapperLifetimeCanary.h create mode 100644 NativeScript/runtime/WrapperLifetimeCanary.mm diff --git a/NativeScript/runtime/ArgConverter.mm b/NativeScript/runtime/ArgConverter.mm index 8e7c07f22..28e0c8dda 100644 --- a/NativeScript/runtime/ArgConverter.mm +++ b/NativeScript/runtime/ArgConverter.mm @@ -11,9 +11,10 @@ #include "NSExceptionSupport.h" #include "NativeScriptException.h" #include "ObjectManager.h" +#include "WrapperLifetime.h" #include "Runtime.h" #include "RuntimeConfig.h" -#include "WrapperLifetime.h" +#include "WrapperLifetimeCanary.h" using namespace v8; using namespace std; @@ -1336,6 +1337,7 @@ bool IsKVOSubclassOf(Class klass, Class base) { instanceTemplate->SetHandler(IndexedPropertyHandlerConfiguration(IndexedPropertyGetterCallback, IndexedPropertySetterCallback)); + WrapperLifetimeCanary::ConfigureInstanceTemplate(instanceTemplate); Local emptyInstanceCtorFunc; if (!emptyInstanceCtorFuncTemplate->GetFunction(context).ToLocal(&emptyInstanceCtorFunc)) { diff --git a/NativeScript/runtime/ClassBuilder.mm b/NativeScript/runtime/ClassBuilder.mm index 9fdd80234..ecfaf8029 100644 --- a/NativeScript/runtime/ClassBuilder.mm +++ b/NativeScript/runtime/ClassBuilder.mm @@ -1,4 +1,5 @@ #include "ClassBuilder.h" +#include "WrapperLifetime.h" #include #include #include @@ -13,7 +14,7 @@ #include "ObjectManager.h" #include "Runtime.h" #include "TNSDerivedClass.h" -#include "WrapperLifetime.h" +#include "WrapperLifetimeCanary.h" using namespace v8; @@ -109,6 +110,8 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { Local extendedClassCtorFuncTemplate = FunctionTemplate::New(isolate, ExtendedClassConstructorCallback, ext); extendedClassCtorFuncTemplate->InstanceTemplate()->SetInternalFieldCount(1); + WrapperLifetimeCanary::ConfigureInstanceTemplate( + extendedClassCtorFuncTemplate->InstanceTemplate()); Local extendClassCtorFunc; if (!extendedClassCtorFuncTemplate->GetFunction(context).ToLocal(&extendClassCtorFunc)) { @@ -319,11 +322,11 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { /// 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. + /// 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) { diff --git a/NativeScript/runtime/MetadataBuilder.mm b/NativeScript/runtime/MetadataBuilder.mm index 4b55a8ebe..2087a0163 100644 --- a/NativeScript/runtime/MetadataBuilder.mm +++ b/NativeScript/runtime/MetadataBuilder.mm @@ -15,6 +15,7 @@ #include "SymbolLoader.h" #include "Tasks.h" #include "Worker.h" +#include "WrapperLifetimeCanary.h" using namespace v8; @@ -557,6 +558,7 @@ throw NativeScriptException( ctorFuncTemplate = FunctionTemplate::New(isolate, ClassConstructorCallback, ext); ctorFuncTemplate->InstanceTemplate()->SetInternalFieldCount(1); + WrapperLifetimeCanary::ConfigureInstanceTemplate(ctorFuncTemplate->InstanceTemplate()); ctorFuncTemplate->SetClassName(tns::ToV8String(isolate, meta->name())); Local baseCtorFunc; diff --git a/NativeScript/runtime/NsBuiltinModules.cpp b/NativeScript/runtime/NsBuiltinModules.cpp index 28062278e..48f698345 100644 --- a/NativeScript/runtime/NsBuiltinModules.cpp +++ b/NativeScript/runtime/NsBuiltinModules.cpp @@ -250,6 +250,8 @@ void GetWrapperLifetimeStatsCallback(const FunctionCallbackInfo& info) { {"promotions", stats->promotions}, {"demotions", stats->demotions}, {"queuedReleases", stats->queuedReleases}, + {"canaryStates", stats->canaryStates}, + {"canaryNativeDeaths", stats->canaryNativeDeaths}, }; for (const auto& [name, value] : fields) { result diff --git a/NativeScript/runtime/ObjectManager.h b/NativeScript/runtime/ObjectManager.h index 7aef0ebbc..6e4b693cb 100644 --- a/NativeScript/runtime/ObjectManager.h +++ b/NativeScript/runtime/ObjectManager.h @@ -10,6 +10,8 @@ namespace tns { +struct CanaryRecord; + class ObjectManager; class ObjCDataWrapper; @@ -56,6 +58,11 @@ struct ObjectWeakCallbackState { bool lifetimeTracked_ = false; // The handle is currently strong. bool lifetimeStrong_ = false; + // Canary mode: the wrapper forwards JS properties to a state object that + // outlives it (WrapperLifetimeCanary), found through this record once the + // object has state. + bool lifetimeCanary_ = false; + std::shared_ptr canaryRecord_; }; class ObjectManager { @@ -84,6 +91,10 @@ class ObjectManager { uint64_t promotions = 0; uint64_t demotions = 0; uint64_t queuedReleases = 0; + // Canary mode: state objects created for native objects, and state + // objects let go of because their native object was deallocated. + uint64_t canaryStates = 0; + uint64_t canaryNativeDeaths = 0; }; static LifetimeStats* GetLifetimeStats(v8::Isolate* isolate); diff --git a/NativeScript/runtime/WrapperLifetime.h b/NativeScript/runtime/WrapperLifetime.h index 82158bbc0..607840f21 100644 --- a/NativeScript/runtime/WrapperLifetime.h +++ b/NativeScript/runtime/WrapperLifetime.h @@ -21,13 +21,18 @@ enum class WrapperLifetimeMode { // Phantom callbacks, no resurrection: a wrapper is a strong root while // something other than the runtime retains its object, weak otherwise. kRooted, + // Phantom callbacks, no resurrection: the wrapper is a canary that dies with + // its JS references. JS properties set on it live on a separate state object + // that stays alive until the native object is deallocated, and a canary + // built for the same object later shares it (WrapperLifetimeCanary). + kCanary, }; 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). + // Only JS-extended instances (TNSDerivedClass) are rooted, or canaries; + // 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, }; diff --git a/NativeScript/runtime/WrapperLifetime.mm b/NativeScript/runtime/WrapperLifetime.mm index d55680389..4fb571fe0 100644 --- a/NativeScript/runtime/WrapperLifetime.mm +++ b/NativeScript/runtime/WrapperLifetime.mm @@ -13,6 +13,7 @@ #include "Helpers.h" #include "Runtime.h" #import "TNSDerivedClass.h" +#include "WrapperLifetimeCanary.h" using namespace v8; @@ -35,6 +36,8 @@ void ReadConfig() { } else if (mode != nil) { if ([mode isEqualToString:@"rooted"]) { detail::wrapperLifetimeMode = WrapperLifetimeMode::kRooted; + } else if ([mode isEqualToString:@"canary"]) { + detail::wrapperLifetimeMode = WrapperLifetimeMode::kCanary; } else if (![mode isEqualToString:@"resurrecting"]) { Log("NativeScript: unknown wrapperLifetime mode \"%s\"; using \"resurrecting\".", [mode UTF8String]); @@ -126,7 +129,8 @@ bool IsBlock(id obj) { return false; } -bool IsRootable(id obj) { +// Rooted (rooted mode) or a canary (canary mode). +bool IsInScope(id obj) { if (IsTaggedPointer(obj) || IsBlock(obj)) { return false; } @@ -295,7 +299,15 @@ void ReleaseAll(Isolate* isolate, RootedState* rooted) { } // namespace const char* WrapperLifetimeModeName(WrapperLifetimeMode mode) { - return mode == WrapperLifetimeMode::kRooted ? "rooted" : "resurrecting"; + switch (mode) { + case WrapperLifetimeMode::kRooted: + return "rooted"; + case WrapperLifetimeMode::kCanary: + return "canary"; + case WrapperLifetimeMode::kResurrecting: + break; + } + return "resurrecting"; } const char* WrapperLifetimeScopeName(WrapperLifetimeScope scope) { @@ -304,6 +316,7 @@ void ReleaseAll(Isolate* isolate, RootedState* rooted) { void WrapperLifetime::Init(Isolate* isolate) { std::call_once(configOnce_, ReadConfig); + WrapperLifetimeCanary::Init(isolate); if (GetWrapperLifetimeMode() != WrapperLifetimeMode::kRooted) { return; } @@ -314,7 +327,7 @@ void ReleaseAll(Isolate* isolate, RootedState* rooted) { void WrapperLifetime::Adopt(Isolate* isolate, ObjCDataWrapper* wrapper, const std::shared_ptr>& handle, id target) { - if (GetWrapperLifetimeMode() != WrapperLifetimeMode::kRooted || target == nil) { + if (GetWrapperLifetimeMode() == WrapperLifetimeMode::kResurrecting || target == nil) { return; } RootedState* rooted = Caches::StateFor(isolate); @@ -328,9 +341,17 @@ void ReleaseAll(Isolate* isolate, RootedState* rooted) { } state->lifetimeWrapper_ = wrapper; state->lifetimeTarget_ = target; - state->runtimeRetains_ = AcquireRuntimeRetain(target); + if (GetWrapperLifetimeMode() == WrapperLifetimeMode::kRooted) { + state->runtimeRetains_ = AcquireRuntimeRetain(target); + } wrapper->SetLifetimeState(state); - if (IsRootable(target)) { + if (GetWrapperLifetimeMode() == WrapperLifetimeMode::kCanary) { + state->lifetimeCanary_ = IsInScope(target); + if (state->lifetimeCanary_) { + state->canaryRecord_ = WrapperLifetimeCanary::Find(isolate, target); + } + MakeWeak(state); + } else if (IsInScope(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; @@ -387,6 +408,7 @@ void ReleaseAll(Isolate* isolate, RootedState* rooted) { } void WrapperLifetime::DrainForTeardown(Isolate* isolate) { + WrapperLifetimeCanary::CloseForTeardown(isolate); RootedState* rooted = Caches::ExistingStateFor(isolate); if (rooted == nullptr) { return; diff --git a/NativeScript/runtime/WrapperLifetimeCanary.h b/NativeScript/runtime/WrapperLifetimeCanary.h new file mode 100644 index 000000000..7cd90b7b6 --- /dev/null +++ b/NativeScript/runtime/WrapperLifetimeCanary.h @@ -0,0 +1,53 @@ +#ifndef WrapperLifetimeCanary_h +#define WrapperLifetimeCanary_h + +#include +#include "Common.h" + +namespace tns { + +struct CanaryRecord; + +// 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. JS +// properties set on a canary are forwarded by kNonMasking named interceptors +// to a state object, so prototype members (native methods and properties, +// JS-extended class methods) never reach these handlers. A canary built later +// for the same object forwards to the same state. +// +// The state object is rooted from its first write until the native object is +// deallocated (an associated token's -dealloc reports it). It cannot be rooted +// only once the canary dies instead: a state reachable only through the canary +// is garbage in the same collection, before any phantom callback runs. The +// cost is that state referencing its own canary (a closure over `this`, a +// WeakMap value naming the object) keeps the canary, and through its retain the +// native object, alive. This is the portable contract, the one the Node-API +// runtimes and Android can implement. +// +// SWITCH POINT (iOS only, not implemented): to collect that self-referencing +// shape, a major-GC prologue could make a record's state handle weak while the +// object is not natively owned and no canary is alive, the way the rooted mode +// scans retain counts (WrapperLifetime.mm, PrologueCallback). Records already +// carry everything such a scan needs: the native object and the state handle. +class WrapperLifetimeCanary { + public: + static void Init(v8::Isolate* isolate); + + // Installs the forwarding handlers on an ObjC instance template. No-op unless + // the mode is canary. + static void ConfigureInstanceTemplate(v8::Local instanceTemplate); + + // The record of an object that already has state in this isolate, for a new + // canary to share. Null otherwise. + static std::shared_ptr Find(v8::Isolate* isolate, id object); + + // Teardown: lets go of every state object while the isolate is alive. Tokens + // that outlive the isolate find the registry closed. + static void CloseForTeardown(v8::Isolate* isolate); +}; + +} // namespace tns + +#endif /* WrapperLifetimeCanary_h */ diff --git a/NativeScript/runtime/WrapperLifetimeCanary.mm b/NativeScript/runtime/WrapperLifetimeCanary.mm new file mode 100644 index 000000000..d28209df6 --- /dev/null +++ b/NativeScript/runtime/WrapperLifetimeCanary.mm @@ -0,0 +1,393 @@ +#include "WrapperLifetimeCanary.h" +#import +#include +#include +#include +#include +#include +#include +#include "Caches.h" +#include "DataWrapper.h" +#include "EventLoop.h" +#include "Helpers.h" +#include "ObjectManager.h" +#include "Runtime.h" +#include "WrapperLifetime.h" + +using namespace v8; + +namespace tns { + +// A native object's state in one isolate, shared by the registry and the +// object's live canary. Its token's -dealloc marks it died: normally when the +// object is deallocated, but objc_removeAssociatedObjects can release the token +// of a live object, whose canary then sees no state and starts a new record on +// its next write. Teardown empties the handle. +struct CanaryRecord { + Global state; + std::atomic died{false}; +}; + +namespace { + +// Per-isolate. Shared with the tokens associated with native objects, which +// can be deallocated on any thread and after the isolate is gone. +struct CanaryRegistry { + std::mutex mutex; + std::unordered_map> records; + // Records whose token was deallocated; their handles are reset on the + // runtime's thread. + std::vector> dead; + bool closed = false; + bool drainPosted = false; + // Lets wrapper creation skip the lookup while no object has state. + std::atomic count{0}; + Isolate* isolate = nullptr; + std::weak_ptr loop; + // The association key: one per isolate, and never reused while a token + // keeps this registry alive. + char associationKey = 0; +}; + +struct CanaryState { + std::shared_ptr registry = std::make_shared(); +}; + +void DrainDead(const std::shared_ptr& registry) { + std::vector> dead; + { + std::lock_guard lock(registry->mutex); + registry->drainPosted = false; + if (registry->closed) { + return; + } + 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++; + } + } +} + +// From the token's -dealloc, on whichever thread deallocates the object. +void NativeDied(const std::shared_ptr& registry, void* object) { + std::shared_ptr loop; + { + std::lock_guard lock(registry->mutex); + if (registry->closed) { + return; + } + auto it = registry->records.find(object); + if (it == registry->records.end()) { + return; + } + // Erased now, inside the object's -dealloc: an object later allocated at + // this address must not find this record. + it->second->died.store(true, std::memory_order_release); + registry->dead.push_back(std::move(it->second)); + registry->records.erase(it); + registry->count.fetch_sub(1, std::memory_order_relaxed); + if (registry->drainPosted) { + return; + } + loop = registry->loop.lock(); + registry->drainPosted = loop != nullptr; + } + // A post dropped at shutdown is fine: teardown resets every handle. + if (loop != nullptr && !loop->PostInternal([registry]() { DrainDead(registry); })) { + std::lock_guard lock(registry->mutex); + registry->drainPosted = false; + } +} + +std::shared_ptr RegistryFor(Isolate* isolate) { + CanaryState* state = Caches::StateFor(isolate); + return state != nullptr ? state->registry : nullptr; +} + +} // namespace + +} // namespace tns + +// Associated with a native object once it has state in an isolate; its +// -dealloc runs when the object is deallocated. +@interface TNSCanaryLifecycleToken : NSObject { + @public + std::shared_ptr registry_; + void* object_; +} +@end + +@implementation TNSCanaryLifecycleToken +- (void)dealloc { + if (registry_ != nullptr) { + tns::NativeDied(registry_, object_); + } + [super dealloc]; +} +@end + +namespace tns { + +namespace { + +// The adopted canary registration of an interceptor's holder, or null when the +// holder is not a canary: a plain wrapper outside the scope, a released one, or +// a `super` accessor object (internal field 1 holds a class name). +ObjectWeakCallbackState* CanaryOf(Isolate* isolate, Local holder) { + if (holder->InternalFieldCount() > 1 && holder->GetInternalField(1).As()->IsString()) { + return nullptr; + } + BaseDataWrapper* wrapper = tns::GetValue(isolate, holder); + if (wrapper == nullptr || wrapper->Type() != WrapperType::ObjCObject) { + return nullptr; + } + ObjectWeakCallbackState* state = static_cast(wrapper)->LifetimeState(); + return state != nullptr && state->lifetimeCanary_ ? state : nullptr; +} + +// The record's state is usable: its token is alive and teardown has not +// emptied it. Handles are only reset under the Locker these callers hold. +bool Usable(const std::shared_ptr& record) { + return record != nullptr && !record->died.load(std::memory_order_acquire) && + !record->state.IsEmpty(); +} + +// The state object of the holder, if it has one. +bool ExistingState(Isolate* isolate, Local holder, Local* out) { + ObjectWeakCallbackState* canary = CanaryOf(isolate, holder); + if (canary == nullptr || !Usable(canary->canaryRecord_)) { + return false; + } + *out = Local::New(isolate, canary->canaryRecord_->state); + return true; +} + +// The state object of the holder, created on its first write. +bool StateForWrite(Isolate* isolate, Local holder, Local* out) { + ObjectWeakCallbackState* canary = CanaryOf(isolate, holder); + if (canary == nullptr) { + return false; + } + if (canary->canaryRecord_ == nullptr || canary->canaryRecord_->died.load(std::memory_order_acquire)) { + std::shared_ptr registry = RegistryFor(isolate); + if (registry == nullptr) { + return false; + } + if (registry->loop.expired()) { + if (Runtime* runtime = Runtime::GetRuntime(isolate)) { + registry->loop = runtime->GetEventLoop(); + } + } + id object = canary->lifetimeTarget_; + bool created = false; + { + std::lock_guard lock(registry->mutex); + if (registry->closed) { + return false; + } + std::shared_ptr& slot = registry->records[(__bridge void*)object]; + if (slot == nullptr) { + slot = std::make_shared(); + slot->state.Reset(isolate, Object::New(isolate, Null(isolate), nullptr, nullptr, 0)); + registry->count.fetch_add(1, std::memory_order_relaxed); + created = true; + } + canary->canaryRecord_ = slot; + } + if (created) { + TNSCanaryLifecycleToken* token = [[TNSCanaryLifecycleToken alloc] init]; + token->registry_ = registry; + token->object_ = (__bridge void*)object; + objc_setAssociatedObject(object, ®istry->associationKey, token, + OBJC_ASSOCIATION_RETAIN_NONATOMIC); + [token release]; + if (ObjectManager::LifetimeStats* stats = ObjectManager::GetLifetimeStats(isolate)) { + stats->canaryStates++; + } + } + } + if (!Usable(canary->canaryRecord_)) { + return false; + } + *out = Local::New(isolate, canary->canaryRecord_->state); + return true; +} + +bool HasOwn(Local context, Local state, Local property) { + return state->HasOwnProperty(context, property).FromMaybe(false); +} + +Intercepted Getter(Local property, const PropertyCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + Local state; + if (!ExistingState(isolate, info.Holder(), &state)) { + return Intercepted::kNo; + } + Local context = isolate->GetCurrentContext(); + if (!HasOwn(context, state, property)) { + return Intercepted::kNo; + } + Local value; + // An accessor defined through the canary runs with the canary as `this` + // (interceptors do not see the receiver, only the holder). + if (state->Get(context, property, info.Holder()).ToLocal(&value)) { + info.GetReturnValue().Set(value); + } + return Intercepted::kYes; +} + +Intercepted Setter(Local property, Local value, + const PropertyCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + Local state; + if (!StateForWrite(isolate, info.Holder(), &state)) { + return Intercepted::kNo; + } + Local context = isolate->GetCurrentContext(); + Maybe result = state->HasRealNamedCallbackProperty(context, property).FromMaybe(false) + ? state->Set(context, property, value, info.Holder()) + : state->Set(context, property, value); + if (result.IsJust()) { + info.GetReturnValue().Set(result.FromJust()); + } + return Intercepted::kYes; +} + +Intercepted Query(Local property, const PropertyCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + Local state; + if (!ExistingState(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 Deleter(Local property, const PropertyCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + Local state; + if (!ExistingState(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 Enumerator(const PropertyCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + Local state; + if (!ExistingState(isolate, info.Holder(), &state)) { + return; + } + Local context = isolate->GetCurrentContext(); + Local names; + if (state + ->GetPropertyNames(context, KeyCollectionMode::kOwnOnly, PropertyFilter::ALL_PROPERTIES, + IndexFilter::kSkipIndices) + .ToLocal(&names)) { + info.GetReturnValue().Set(names); + } +} + +Intercepted Definer(Local property, const PropertyDescriptor& descriptor, + const PropertyCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + Local state; + if (!StateForWrite(isolate, info.Holder(), &state)) { + return Intercepted::kNo; + } + Local context = isolate->GetCurrentContext(); + bool defined; + if (state->DefineProperty(context, property, const_cast(descriptor)) + .To(&defined)) { + info.GetReturnValue().Set(defined); + } + return Intercepted::kYes; +} + +Intercepted Descriptor(Local property, const PropertyCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + Local state; + if (!ExistingState(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; +} + +} // namespace + +void WrapperLifetimeCanary::Init(Isolate* isolate) { + if (GetWrapperLifetimeMode() != WrapperLifetimeMode::kCanary) { + return; + } + CanaryState* state = Caches::StateFor(isolate); + if (state == nullptr) { + return; + } + state->registry->isolate = isolate; + if (Runtime* runtime = Runtime::GetRuntime(isolate)) { + state->registry->loop = runtime->GetEventLoop(); + } +} + +void WrapperLifetimeCanary::ConfigureInstanceTemplate(Local instanceTemplate) { + if (GetWrapperLifetimeMode() != WrapperLifetimeMode::kCanary) { + return; + } + instanceTemplate->SetHandler(NamedPropertyHandlerConfiguration( + Getter, Setter, Query, Deleter, Enumerator, Definer, Descriptor, Local(), + PropertyHandlerFlags::kNonMasking)); +} + +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) { + return nullptr; + } + std::lock_guard lock(state->registry->mutex); + auto it = state->registry->records.find((__bridge void*)object); + return it != state->registry->records.end() ? it->second : nullptr; +} + +void WrapperLifetimeCanary::CloseForTeardown(Isolate* isolate) { + CanaryState* state = Caches::ExistingStateFor(isolate); + if (state == nullptr) { + return; + } + std::lock_guard lock(state->registry->mutex); + state->registry->closed = true; + for (auto& entry : state->registry->records) { + entry.second->state.Reset(); + } + for (std::shared_ptr& record : state->registry->dead) { + record->state.Reset(); + } +} + +} // namespace tns diff --git a/TestRunner/app/tests/WrapperLifetimeModesTests.js b/TestRunner/app/tests/WrapperLifetimeModesTests.js index 0df5e7b88..711f25d7a 100644 --- a/TestRunner/app/tests/WrapperLifetimeModesTests.js +++ b/TestRunner/app/tests/WrapperLifetimeModesTests.js @@ -1,11 +1,14 @@ // 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". +// config). The suite runs under the default mode; the other expectations run +// when the TestRunner app is configured with "mode": "rooted" or "canary". 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 canary = mode === "canary"; + // JS state on a natively owned object survives its wrapper's death. + var keepsState = rooted || canary; var Extended = (function (_super) { __extends(Extended, _super); @@ -19,6 +22,18 @@ describe("Wrapper lifetime modes", function () { return n > 0 ? scrub(n - 1) + n : 0; } + // Watches specific objects without retaining them; unlike the dealloc log, + // it ignores objects earlier specs left to the collector. + function watch(obj) { + var table = NSHashTable.weakObjectsHashTable(); + table.addObject(obj); + return table; + } + + function alive(table) { + return table.allObjects.count; + } + function deallocs() { return (TNSGetOutput().match(/TNSAllocLog dealloc/g) || []).length; } @@ -45,7 +60,7 @@ describe("Wrapper lifetime modes", function () { // 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(["resurrecting", "rooted", "canary"].indexOf(mode)).not.toBe(-1); expect(["extended", "all"].indexOf(scope)).not.toBe(-1); expect(function () { runtime.setConfig("wrapperLifetimeMode", "rooted"); @@ -61,7 +76,7 @@ describe("Wrapper lifetime modes", function () { })(); settle(2, function () { var holder = owner.objectAtIndex(0); - if (rooted) { + if (keepsState) { expect(holder.state).toBeDefined(); expect(function () { holder.state.item.isEqual(null); @@ -71,7 +86,7 @@ describe("Wrapper lifetime modes", function () { }); }); - it("keeps the JS state of a natively owned plain object when every wrapper is rooted", function (done) { + it("keeps the JS state of a natively owned plain object when every wrapper is in scope", function (done) { var owner = NSMutableArray.new(); (function () { var obj = TNSAllocLog.new(); @@ -80,7 +95,7 @@ describe("Wrapper lifetime modes", function () { })(); settle(2, function () { var obj = owner.objectAtIndex(0); - if (rooted && scope === "all") { + if (keepsState && scope === "all") { expect(obj.state && obj.state.value).toBe(42); } done(); @@ -220,7 +235,7 @@ describe("Wrapper lifetime modes", function () { })(); settle(2, function () { var view = cell.owner.deref(); - if (rooted && view !== undefined) { + if (keepsState && view !== undefined) { expect(function () { view.color.isEqual(null); view.nativeView.isEqual(null); @@ -251,7 +266,7 @@ describe("Wrapper lifetime modes", function () { })(); settle(2, function () { expect(owner.count).toBe(4); - if (rooted) { + if (keepsState) { expect(owner.objectAtIndex(0).state).toBe(0); } done(); @@ -394,7 +409,7 @@ describe("Wrapper lifetime modes", function () { }); }); - it("counts rooted-mode activity", function (done) { + it("counts phantom-mode activity", function (done) { var before = runtime.getWrapperLifetimeStats(); (function () { for (var i = 0; i < 8; i++) { @@ -403,7 +418,7 @@ describe("Wrapper lifetime modes", function () { })(); settle(2, function () { var after = runtime.getWrapperLifetimeStats(); - if (rooted) { + if (mode !== "resurrecting") { expect(after.queuedReleases).toBeGreaterThan(before.queuedReleases); expect(after.resurrections).toBe(before.resurrections); } else { @@ -412,4 +427,132 @@ describe("Wrapper lifetime modes", function () { done(); }); }); + + // Own-property semantics hold whatever the mode: in canary mode the names + // live on the state object and the canary's interceptors present them. + it("keeps own-property semantics for JS properties on a native object", function () { + var obj = Extended.new(); + obj.a = 1; + Object.defineProperty(obj, "hidden", { value: 2, enumerable: false, configurable: true }); + Object.defineProperty(obj, "self", { + get: function () { + return this; + }, + configurable: true + }); + + expect(Object.keys(obj)).toEqual(["a"]); + expect(Object.getOwnPropertyNames(obj).sort()).toEqual(["a", "hidden", "self"]); + expect("a" in obj).toBe(true); + expect(Object.prototype.hasOwnProperty.call(obj, "hidden")).toBe(true); + expect(obj.hidden).toBe(2); + expect(obj.self).toBe(obj); + expect(Object.getOwnPropertyDescriptor(obj, "a").value).toBe(1); + + expect(delete obj.a).toBe(true); + expect("a" in obj).toBe(false); + expect(obj.a).toBeUndefined(); + // Prototype members are not own properties. + expect(Object.prototype.hasOwnProperty.call(obj, "isEqual")).toBe(false); + }); + + it("hands back a native object's JS properties on a new wrapper after the old one died", function (done) { + var owner = NSMutableArray.new(); + (function () { + var obj = Extended.new(); + obj.tag = "kept"; + owner.addObject(obj); + })(); + settle(2, function () { + var obj = owner.objectAtIndex(0); + if (keepsState) { + expect(obj.tag).toBe("kept"); + } + done(); + }); + }); + + it("leaves plain objects outside the extended scope without forwarding", function (done) { + var owner = NSMutableArray.new(); + (function () { + var obj = TNSAllocLog.new(); + obj.tag = "lost"; + owner.addObject(obj); + })(); + settle(2, function () { + if (canary && scope === "extended") { + expect(owner.objectAtIndex(0).tag).toBeUndefined(); + } + done(); + }); + }); + + it("lets a native object's JS state go when the object is deallocated", function (done) { + var owner = NSMutableArray.new(); + var before = runtime.getWrapperLifetimeStats(); + var watched; + (function () { + var obj = Extended.new(); + obj.tag = "state"; + owner.addObject(obj); + watched = watch(obj); + })(); + settle(2, function () { + owner.removeAllObjects(); + settle(3, function () { + var after = runtime.getWrapperLifetimeStats(); + expect(alive(watched)).toBe(0); + if (canary) { + expect(after.canaryStates).toBeGreaterThan(before.canaryStates); + expect(after.canaryNativeDeaths).toBeGreaterThan(before.canaryNativeDeaths); + } + done(); + }); + }); + }); + + // The documented cost of the canary contract: state that references its own + // object keeps the state, the object's wrapper and the native object alive + // until native code would have released it anyway, which nothing does here. + it("keeps a native object whose JS state references it", function (done) { + var watched; + (function () { + var obj = Extended.new(); + obj.callback = function () { + return obj; + }; + watched = watch(obj); + })(); + settle(3, function () { + expect(alive(watched)).toBe(canary ? 1 : 0); + done(); + }); + }); + + // Third-party code can strip a live object's associations, which releases + // the token that reports native death; the state goes with it. + it("survives a live object's associations being removed", function () { + if (typeof objc_removeAssociatedObjects !== "function") { + return; + } + var obj = Extended.new(); + obj.tag = "first"; + objc_removeAssociatedObjects(obj); + if (canary) { + expect(obj.tag).toBeUndefined(); + } + obj.tag = "second"; + expect(obj.tag).toBe("second"); + }); + + // V8 refuses to freeze, seal or prevent extensions on an object with + // interceptors, which every canary has. + it("refuses to freeze a canary", function () { + if (!canary) { + return; + } + expect(function () { + Object.freeze(Extended.new()); + }).toThrowError(TypeError); + }); }); diff --git a/TestRunner/app/tests/WrapperLifetimeTests.js b/TestRunner/app/tests/WrapperLifetimeTests.js index 1170df102..959702ccd 100644 --- a/TestRunner/app/tests/WrapperLifetimeTests.js +++ b/TestRunner/app/tests/WrapperLifetimeTests.js @@ -323,6 +323,8 @@ describe("Wrapper lifetime", function () { "demotions", "promotions", "queuedReleases", + "canaryStates", + "canaryNativeDeaths", "stateLostCandidates", "stateLostConfirmed", ].sort()); diff --git a/docs/knowledge/v8-resurrecting-finalizers.md b/docs/knowledge/v8-resurrecting-finalizers.md index 0490c8e78..402208cb2 100644 --- a/docs/knowledge/v8-resurrecting-finalizers.md +++ b/docs/knowledge/v8-resurrecting-finalizers.md @@ -257,6 +257,26 @@ silent in the rooted mode. Under `"scope": "extended"` there, a plain (not JS-ex 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. +`"mode": "canary"` (`WrapperLifetimeCanary.{h,mm}`) is the portable variant, the shape Android and +the Node-API runtimes can implement. A wrapper in scope is a canary: a phantom-weak JS object +that dies with its JS references, releasing the runtime's retain through the same queue. +`kNonMasking` named interceptors on the instance templates forward JS properties to a +null-prototype state object, so prototype members never reach them. The state is rooted from +its first write until the native object is deallocated, which an associated token's `-dealloc` +reports; a canary built later for the same object forwards to the same state. It cannot be +rooted at canary death instead, because a state reachable only through the canary is garbage in +the same collection. The cost: state that references its own object (a closure over `this`) +keeps it alive. Identity changes across a canary's death, so `===` with an old wrapper, `WeakMap` +keys and `WeakRef`s of the old canary, and native `#private` fields do not carry over. Other +limits: `Object.freeze`, `seal` and `preventExtensions` throw on a canary (V8 refuses them on +objects with interceptors); index-keyed properties are not forwarded and die with the canary; +a write through an object whose prototype is a canary lands in the canary's state, since +interceptors see the holder but not the receiver; and `"scope": "all"` is experimental, because +attaching the token aborts for any class the ObjC runtime marks as forbidding associated +objects, which has no public query. Relies on +V8's own-property lookup through `kNonMasking` interceptors when the prototype has a named +interceptor (`v8_nonmasking_own_lookup.patch` in v8-buildscripts, crbug 585053531). + 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 f9731f8d1..7b94fad7b 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -115,8 +115,8 @@ 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); 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"` | +| `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"` | ```js @@ -163,7 +163,9 @@ every build (they only cost an increment on finalizer and error paths): | `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 | +| `queuedReleases` | `"rooted"` and `"canary"`: collected wrappers whose native object was queued for release on the runtime's thread | +| `canaryStates` | `"canary"` only: state objects created to hold native objects' JS properties | +| `canaryNativeDeaths` | `"canary"` only: state objects let go of because their native object was deallocated | 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 49c9ffe8a..b8bf6ba13 100644 --- a/types/ns-runtime.d.ts +++ b/types/ns-runtime.d.ts @@ -51,10 +51,15 @@ declare module "ns:runtime" { * 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. + * - `"canary"`: no resurrection. A wrapper in scope dies with its JS + * references; JS properties set on it live on a state object kept until + * the native object is deallocated, and a wrapper built for the object + * later has them again (as a new object: `===` with the old one fails). + * State that references its own object keeps that object alive. */ - wrapperLifetimeMode: "resurrecting" | "rooted"; + wrapperLifetimeMode: "resurrecting" | "rooted" | "canary"; /** - * Which wrappers `"rooted"` roots, from the app config + * Which wrappers `"rooted"` roots, or `"canary"` makes canaries, from the app config * `"wrapperLifetime": { "scope": ... }`. Read-only: `setConfig` throws. * * - `"extended"` (default): instances of JS-extended classes. @@ -84,8 +89,12 @@ declare module "ns:runtime" { 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. */ + /** `"rooted"` and `"canary"`: collected wrappers whose native object was queued for release. */ queuedReleases: number; + /** `"canary"` only: state objects created for native objects' JS properties. */ + canaryStates: number; + /** `"canary"` only: state objects let go of because their native object was deallocated. */ + canaryNativeDeaths: number; } /** diff --git a/v8ios.xcodeproj/project.pbxproj b/v8ios.xcodeproj/project.pbxproj index 0dbf3f5a6..26569d0f6 100644 --- a/v8ios.xcodeproj/project.pbxproj +++ b/v8ios.xcodeproj/project.pbxproj @@ -313,6 +313,8 @@ 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 */; }; + A0636BA435F52099D6955AC5 /* WrapperLifetimeCanary.h in Headers */ = {isa = PBXBuildFile; fileRef = 06AF90E16F4178A9D3261C14 /* WrapperLifetimeCanary.h */; }; + 2A9D21FFAFE7419B7E69B585 /* WrapperLifetimeCanary.mm in Sources */ = {isa = PBXBuildFile; fileRef = CB7C1CED65B5F547091F0B28 /* WrapperLifetimeCanary.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 */; }; @@ -845,6 +847,8 @@ 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 = ""; }; + 06AF90E16F4178A9D3261C14 /* WrapperLifetimeCanary.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WrapperLifetimeCanary.h; sourceTree = ""; }; + CB7C1CED65B5F547091F0B28 /* WrapperLifetimeCanary.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = WrapperLifetimeCanary.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 = ""; }; @@ -1530,6 +1534,8 @@ C2DDEB86229EAC8300345BFE /* ObjectManager.mm */, 9E6F52B357F2776D77D71D8A /* WrapperLifetime.h */, 13A9D13202DBEA9487A90B03 /* WrapperLifetime.mm */, + 06AF90E16F4178A9D3261C14 /* WrapperLifetimeCanary.h */, + CB7C1CED65B5F547091F0B28 /* WrapperLifetimeCanary.mm */, C20AB5E526E1015200E2B41D /* OneByteStringResource.h */, C20AB5E426E1015200E2B41D /* OneByteStringResource.cpp */, 4A5C201A2E2B000300000002 /* Performance.h */, @@ -1688,6 +1694,7 @@ C20AB5E726E1015300E2B41D /* OneByteStringResource.h in Headers */, C2DDEBAC229EAC8300345BFE /* ObjectManager.h in Headers */, DD6B0F1ACE8AE363C72245E9 /* WrapperLifetime.h in Headers */, + A0636BA435F52099D6955AC5 /* WrapperLifetimeCanary.h in Headers */, 6573B9E7291FE2A700B0ED7C /* jsi.h in Headers */, 6573B9E2291FE2A700B0ED7C /* jsi-inl.h in Headers */, C2D21601248AAAD900EDC646 /* Constants.h in Headers */, @@ -2373,6 +2380,7 @@ AA8C47B22E27114300649BF5 /* ModuleInternalCallbacks.mm in Sources */, C2DDEBAF229EAC8300345BFE /* ObjectManager.mm in Sources */, 1DE238EF3BDD0EF221E13C44 /* WrapperLifetime.mm in Sources */, + 2A9D21FFAFE7419B7E69B585 /* WrapperLifetimeCanary.mm in Sources */, F6191AB029C0FCE8003F588F /* JsV8InspectorClient.mm in Sources */, A1B2C3D40000000000000004 /* WorkerInspectorClient.mm in Sources */, C2DDEB9C229EAC8300345BFE /* ClassBuilder.cpp in Sources */, From 0ed657d81c24d10916241dc7b62bd5f5090e93d0 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Thu, 12 Nov 2026 19:56:22 -0300 Subject: [PATCH 02/24] fix(runtime): iterate an NSArray's receiver instead of capturing it SymbolIterator::Set gave each NSArray wrapper its own Symbol.iterator function bound to the wrapper. Under the canary wrapper lifetime mode with "scope": "all" that property lives on the array's state object, so the state referenced its own canary and the array was never released. The function now iterates its receiver, which is what `for...of` and `arr[Symbol.iterator]()` pass anyway. --- NativeScript/runtime/SymbolIterator.mm | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/NativeScript/runtime/SymbolIterator.mm b/NativeScript/runtime/SymbolIterator.mm index 15fdec02a..33c940838 100644 --- a/NativeScript/runtime/SymbolIterator.mm +++ b/NativeScript/runtime/SymbolIterator.mm @@ -10,17 +10,18 @@ void SymbolIterator::Set(Local context, Local object) { Isolate* isolate = v8::Isolate::GetCurrent(); + // Iterates its receiver rather than capturing `object`: in the canary + // wrapper lifetime mode this property lives on the object's state, which a + // reference back to the object would keep alive until native death. Local iterator; - bool success = v8::Function::New( - context, - [](const FunctionCallbackInfo& args) { - Isolate* isolate = args.GetIsolate(); - Local context = isolate->GetCurrentContext(); - Local object = args.Data(); - Local result = CreateIteratorObject(context, object); - args.GetReturnValue().Set(result); - }, - object) + bool success = v8::Function::New(context, + [](const FunctionCallbackInfo& args) { + Isolate* isolate = args.GetIsolate(); + Local context = isolate->GetCurrentContext(); + Local result = + CreateIteratorObject(context, args.This()); + args.GetReturnValue().Set(result); + }) .ToLocal(&iterator); tns::Assert(success, isolate); From 053197255e87823980145cdf3887ea96a3ef9f17 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Thu, 12 Nov 2026 20:53:51 -0300 Subject: [PATCH 03/24] chore(v8): pin v8-14.9.207.39-10 The canary wrapper lifetime mode needs v8_nonmasking_own_lookup.patch (crbug 585053531), first shipped in -10. Moving from -7 also brings -8 (Apple TV variants) and -9 (Mac Catalyst with its JIT tiers, whose runtime support is #533). --- V8_RELEASE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/V8_RELEASE b/V8_RELEASE index d5a564b23..93699c903 100644 --- a/V8_RELEASE +++ b/V8_RELEASE @@ -1 +1 @@ -v8-14.9.207.39-9 +v8-14.9.207.39-10 From 96eca3c8f37f1712b0a0735c38998dacfeb5253c Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 13 Nov 2026 01:31:34 -0300 Subject: [PATCH 04/24] docs(runtime): a canary change is invisible to === Only one canary lives at a time, and anything referencing the old one keeps it alive, so no comparison can see the new one. Only weak references to the old canary and native #private brands notice. --- docs/knowledge/v8-resurrecting-finalizers.md | 6 ++++-- types/ns-runtime.d.ts | 3 ++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/knowledge/v8-resurrecting-finalizers.md b/docs/knowledge/v8-resurrecting-finalizers.md index 402208cb2..5df567e80 100644 --- a/docs/knowledge/v8-resurrecting-finalizers.md +++ b/docs/knowledge/v8-resurrecting-finalizers.md @@ -266,8 +266,10 @@ its first write until the native object is deallocated, which an associated toke reports; a canary built later for the same object forwards to the same state. It cannot be rooted at canary death instead, because a state reachable only through the canary is garbage in the same collection. The cost: state that references its own object (a closure over `this`) -keeps it alive. Identity changes across a canary's death, so `===` with an old wrapper, `WeakMap` -keys and `WeakRef`s of the old canary, and native `#private` fields do not carry over. Other +keeps it alive. A canary built after a death is a new object, but `===` cannot tell: only one +canary lives at a time, and anything still referencing the old one would have kept it alive. +What does notice is whatever keys on the canary without keeping it: `WeakMap` keys and `WeakRef`s +of the old canary, and native `#private` fields, which are branded on it. Other limits: `Object.freeze`, `seal` and `preventExtensions` throw on a canary (V8 refuses them on objects with interceptors); index-keyed properties are not forwarded and die with the canary; a write through an object whose prototype is a canary lands in the canary's state, since diff --git a/types/ns-runtime.d.ts b/types/ns-runtime.d.ts index b8bf6ba13..b78e6bc5c 100644 --- a/types/ns-runtime.d.ts +++ b/types/ns-runtime.d.ts @@ -54,7 +54,8 @@ declare module "ns:runtime" { * - `"canary"`: no resurrection. A wrapper in scope dies with its JS * references; JS properties set on it live on a state object kept until * the native object is deallocated, and a wrapper built for the object - * later has them again (as a new object: `===` with the old one fails). + * later has them again. Weak references to the old wrapper (WeakMap keys, + * WeakRef) and native `#private` fields do not carry over. * State that references its own object keeps that object alive. */ wrapperLifetimeMode: "resurrecting" | "rooted" | "canary"; From c7dde3998d009c7883c3f4719211319b5290a580 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 13 Nov 2026 02:03:02 -0300 Subject: [PATCH 05/24] feat(runtime): choose how canary mode notices native deaths at build time NS_CANARY_DEATH_SIGNAL selects between two ways of learning that a native object with state was deallocated: - NS_CANARY_DEATH_ASSOCIATION (default): an associated token's -dealloc reports it immediately, on any thread. The ObjC runtime aborts for a class that forbids associated objects, and there is no public query. - NS_CANARY_DEATH_WEAK_SWEEP: each record keeps an ObjC weak reference (objc_initWeakOrNil, which declines instead of aborting), and a sweep posted after every major collection lets dead objects' state go. A class refusing weak references keeps its properties on the canary. Both share the records; a re-wrap or write that finds a dead record not yet swept starts over, so a recycled address never inherits state. --- NativeScript/runtime/WrapperLifetimeCanary.h | 4 +- NativeScript/runtime/WrapperLifetimeCanary.mm | 153 ++++++++++++++++-- .../app/tests/WrapperLifetimeModesTests.js | 9 +- docs/knowledge/v8-resurrecting-finalizers.md | 16 +- 4 files changed, 162 insertions(+), 20 deletions(-) diff --git a/NativeScript/runtime/WrapperLifetimeCanary.h b/NativeScript/runtime/WrapperLifetimeCanary.h index 7cd90b7b6..22a8212e6 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.h +++ b/NativeScript/runtime/WrapperLifetimeCanary.h @@ -18,7 +18,9 @@ struct CanaryRecord; // for the same object forwards to the same state. // // The state object is rooted from its first write until the native object is -// deallocated (an associated token's -dealloc reports it). It cannot be rooted +// deallocated, reported by an associated token's -dealloc or found by a sweep +// of weak references after major collections (NS_CANARY_DEATH_SIGNAL in the +// .mm chooses). It cannot be rooted // only once the canary dies instead: a state reachable only through the canary // is garbage in the same collection, before any phantom callback runs. The // cost is that state referencing its own canary (a closure over `this`, a diff --git a/NativeScript/runtime/WrapperLifetimeCanary.mm b/NativeScript/runtime/WrapperLifetimeCanary.mm index d28209df6..e6eb60658 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.mm +++ b/NativeScript/runtime/WrapperLifetimeCanary.mm @@ -14,18 +14,51 @@ #include "Runtime.h" #include "WrapperLifetime.h" +// How canary mode learns that a native object with state was deallocated, so +// its state can be let go of: +// - ASSOCIATION: a token associated with the object reports it from its +// -dealloc, immediately and on any thread. The ObjC runtime aborts the +// process for a class that forbids associated objects (no public query). +// - WEAK_SWEEP: each record holds a weak reference to the object, checked by a +// sweep after every major collection, so state lingers until then. Classes +// that refuse weak references keep their JS properties on the canary. +#define NS_CANARY_DEATH_ASSOCIATION 1 +#define NS_CANARY_DEATH_WEAK_SWEEP 2 +#ifndef NS_CANARY_DEATH_SIGNAL +#define NS_CANARY_DEATH_SIGNAL NS_CANARY_DEATH_ASSOCIATION +#endif + +#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_WEAK_SWEEP +extern "C" id objc_initWeakOrNil(id* location, id value); +extern "C" void objc_destroyWeak(id* location); +#endif + using namespace v8; namespace tns { // A native object's state in one isolate, shared by the registry and the -// object's live canary. Its token's -dealloc marks it died: normally when the -// object is deallocated, but objc_removeAssociatedObjects can release the token -// of a live object, whose canary then sees no state and starts a new record on -// its next write. Teardown empties the handle. +// object's live canary. Marked died once the object is known to be gone (with +// ASSOCIATION, also when objc_removeAssociatedObjects releases the token of a +// live object): its canary then sees no state and starts a new record on its +// next write. Teardown empties the handle. struct CanaryRecord { Global state; std::atomic died{false}; +#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_WEAK_SWEEP + // Zeroed by the ObjC runtime when the object is deallocated, on any thread. + id object = nil; + + ~CanaryRecord() { objc_destroyWeak(&object); } + + // A racy read is enough: the slot only goes from the object to nil, and is + // never dereferenced here. + bool ObjectAlive() const { + return __atomic_load_n(reinterpret_cast(&object), __ATOMIC_ACQUIRE) != nullptr; + } +#else + bool ObjectAlive() const { return true; } +#endif }; namespace { @@ -40,19 +73,23 @@ std::vector> dead; bool closed = false; bool drainPosted = false; + bool sweepPosted = false; // Lets wrapper creation skip the lookup while no object has state. std::atomic count{0}; Isolate* isolate = nullptr; std::weak_ptr loop; +#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_ASSOCIATION // The association key: one per isolate, and never reused while a token // keeps this registry alive. char associationKey = 0; +#endif }; struct CanaryState { std::shared_ptr registry = std::make_shared(); }; +#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_ASSOCIATION void DrainDead(const std::shared_ptr& registry) { std::vector> dead; { @@ -102,6 +139,41 @@ void NativeDied(const std::shared_ptr& registry, void* object) { registry->drainPosted = false; } } +#endif + +#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_WEAK_SWEEP +// Lets go of the state of every object that was deallocated. Runs as an event +// loop task (under the Locker, on the runtime's thread), never inside the GC. +void Sweep(const std::shared_ptr& registry) { + std::vector> dead; + { + std::lock_guard lock(registry->mutex); + registry->sweepPosted = false; + if (registry->closed) { + return; + } + // Records a re-wrap or a write already found dead. + dead.swap(registry->dead); + for (auto it = registry->records.begin(); it != registry->records.end();) { + if (it->second->ObjectAlive()) { + ++it; + continue; + } + it->second->died.store(true, std::memory_order_release); + dead.push_back(std::move(it->second)); + it = registry->records.erase(it); + 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++; + } + } +} +#endif std::shared_ptr RegistryFor(Isolate* isolate) { CanaryState* state = Caches::StateFor(isolate); @@ -112,6 +184,7 @@ void NativeDied(const std::shared_ptr& registry, void* object) { } // namespace tns +#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_ASSOCIATION // Associated with a native object once it has state in an isolate; its // -dealloc runs when the object is deallocated. @interface TNSCanaryLifecycleToken : NSObject { @@ -129,6 +202,7 @@ - (void)dealloc { [super dealloc]; } @end +#endif namespace tns { @@ -149,13 +223,27 @@ - (void)dealloc { return state != nullptr && state->lifetimeCanary_ ? state : nullptr; } -// The record's state is usable: its token is alive and teardown has not -// emptied it. Handles are only reset under the Locker these callers hold. +// The record's state is usable: its object is not known to be gone and +// teardown has not emptied it. Handles are only reset under the Locker these +// callers hold. bool Usable(const std::shared_ptr& record) { return record != nullptr && !record->died.load(std::memory_order_acquire) && !record->state.IsEmpty(); } +// Under the registry mutex: a record whose object is gone but which no sweep +// has reached yet is moved out, so an object now at that address starts over. +void RetireIfDead(CanaryRegistry* registry, + std::unordered_map>::iterator it) { + if (it->second->ObjectAlive()) { + return; + } + it->second->died.store(true, std::memory_order_release); + registry->dead.push_back(std::move(it->second)); + registry->records.erase(it); + registry->count.fetch_sub(1, std::memory_order_relaxed); +} + // The state object of the holder, if it has one. bool ExistingState(Isolate* isolate, Local holder, Local* out) { ObjectWeakCallbackState* canary = CanaryOf(isolate, holder); @@ -189,22 +277,36 @@ bool StateForWrite(Isolate* isolate, Local holder, Local* out) { if (registry->closed) { return false; } + auto existing = registry->records.find((__bridge void*)object); + if (existing != registry->records.end()) { + RetireIfDead(registry.get(), existing); + } std::shared_ptr& slot = registry->records[(__bridge void*)object]; if (slot == nullptr) { - slot = std::make_shared(); - slot->state.Reset(isolate, Object::New(isolate, Null(isolate), nullptr, nullptr, 0)); + auto record = std::make_shared(); +#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_WEAK_SWEEP + if (objc_initWeakOrNil(&record->object, object) == nil) { + // The class refuses weak references. + registry->records.erase((__bridge void*)object); + return false; + } +#endif + record->state.Reset(isolate, Object::New(isolate, Null(isolate), nullptr, nullptr, 0)); + slot = std::move(record); registry->count.fetch_add(1, std::memory_order_relaxed); created = true; } canary->canaryRecord_ = slot; } if (created) { +#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_ASSOCIATION TNSCanaryLifecycleToken* token = [[TNSCanaryLifecycleToken alloc] init]; token->registry_ = registry; token->object_ = (__bridge void*)object; objc_setAssociatedObject(object, ®istry->associationKey, token, OBJC_ASSOCIATION_RETAIN_NONATOMIC); [token release]; +#endif if (ObjectManager::LifetimeStats* stats = ObjectManager::GetLifetimeStats(isolate)) { stats->canaryStates++; } @@ -340,6 +442,30 @@ Intercepted Descriptor(Local property, const PropertyCallbackInfo(isolate); + if (state == nullptr || state->registry->count.load(std::memory_order_relaxed) == 0) { + return; + } + std::shared_ptr registry = state->registry; + std::shared_ptr loop = registry->loop.lock(); + { + std::lock_guard lock(registry->mutex); + if (registry->sweepPosted || loop == nullptr) { + return; + } + registry->sweepPosted = true; + } + if (!loop->PostInternal([registry]() { Sweep(registry); })) { + std::lock_guard lock(registry->mutex); + registry->sweepPosted = false; + } +} +#endif + } // namespace void WrapperLifetimeCanary::Init(Isolate* isolate) { @@ -354,6 +480,10 @@ Intercepted Descriptor(Local property, const PropertyCallbackInforegistry->loop = runtime->GetEventLoop(); } +#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_WEAK_SWEEP + isolate->AddGCPrologueCallback( + PostSweepAfterGC, static_cast(kGCTypeMarkSweepCompact | kGCTypeIncrementalMarking)); +#endif } void WrapperLifetimeCanary::ConfigureInstanceTemplate(Local instanceTemplate) { @@ -372,7 +502,12 @@ Intercepted Descriptor(Local property, const PropertyCallbackInfo lock(state->registry->mutex); auto it = state->registry->records.find((__bridge void*)object); - return it != state->registry->records.end() ? it->second : nullptr; + if (it == state->registry->records.end()) { + return nullptr; + } + std::shared_ptr record = it->second; + RetireIfDead(state->registry.get(), it); + return record->ObjectAlive() ? record : nullptr; } void WrapperLifetimeCanary::CloseForTeardown(Isolate* isolate) { diff --git a/TestRunner/app/tests/WrapperLifetimeModesTests.js b/TestRunner/app/tests/WrapperLifetimeModesTests.js index 711f25d7a..c236c2b07 100644 --- a/TestRunner/app/tests/WrapperLifetimeModesTests.js +++ b/TestRunner/app/tests/WrapperLifetimeModesTests.js @@ -529,8 +529,9 @@ describe("Wrapper lifetime modes", function () { }); }); - // Third-party code can strip a live object's associations, which releases - // the token that reports native death; the state goes with it. + // Third-party code can strip a live object's associations. Where an + // associated token reports native death, the state goes with it; where a + // weak-reference sweep does, nothing changes. it("survives a live object's associations being removed", function () { if (typeof objc_removeAssociatedObjects !== "function") { return; @@ -538,9 +539,7 @@ describe("Wrapper lifetime modes", function () { var obj = Extended.new(); obj.tag = "first"; objc_removeAssociatedObjects(obj); - if (canary) { - expect(obj.tag).toBeUndefined(); - } + expect([undefined, "first"]).toContain(obj.tag); obj.tag = "second"; expect(obj.tag).toBe("second"); }); diff --git a/docs/knowledge/v8-resurrecting-finalizers.md b/docs/knowledge/v8-resurrecting-finalizers.md index 5df567e80..824c4056d 100644 --- a/docs/knowledge/v8-resurrecting-finalizers.md +++ b/docs/knowledge/v8-resurrecting-finalizers.md @@ -262,8 +262,16 @@ the Node-API runtimes can implement. A wrapper in scope is a canary: a phantom-w that dies with its JS references, releasing the runtime's retain through the same queue. `kNonMasking` named interceptors on the instance templates forward JS properties to a null-prototype state object, so prototype members never reach them. The state is rooted from -its first write until the native object is deallocated, which an associated token's `-dealloc` -reports; a canary built later for the same object forwards to the same state. It cannot be +its first write until the native object is deallocated; a canary built later for the same +object forwards to the same state. How the deallocation is noticed is a compile-time choice +(`NS_CANARY_DEATH_SIGNAL` in `WrapperLifetimeCanary.mm`): by default a token associated with the +object reports it from its `-dealloc`, immediately and on any thread, but the ObjC runtime aborts +the process for a class that forbids associated objects, and there is no public query for that; +the alternative keeps an ObjC weak reference in each record (`objc_initWeakOrNil`, which declines +instead of aborting for classes that refuse weak references) and sweeps the records after every +major collection, so state lingers until then. With the default, `"scope": "all"` is +experimental for that reason; with `"extended"` only instances of JS-extended classes get a +token (the flag is inherited, so a JS subclass of a forbidding class would still abort). It cannot be rooted at canary death instead, because a state reachable only through the canary is garbage in the same collection. The cost: state that references its own object (a closure over `this`) keeps it alive. A canary built after a death is a new object, but `===` cannot tell: only one @@ -273,9 +281,7 @@ of the old canary, and native `#private` fields, which are branded on it. Other limits: `Object.freeze`, `seal` and `preventExtensions` throw on a canary (V8 refuses them on objects with interceptors); index-keyed properties are not forwarded and die with the canary; a write through an object whose prototype is a canary lands in the canary's state, since -interceptors see the holder but not the receiver; and `"scope": "all"` is experimental, because -attaching the token aborts for any class the ObjC runtime marks as forbidding associated -objects, which has no public query. Relies on +interceptors see the holder but not the receiver. Relies on V8's own-property lookup through `kNonMasking` interceptors when the prototype has a named interceptor (`v8_nonmasking_own_lookup.patch` in v8-buildscripts, crbug 585053531). From 1ae21bd537b23993c2243b15c4dd37c8f6df1f2b Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 13 Nov 2026 02:17:01 -0300 Subject: [PATCH 06/24] feat(runtime): JS-extended classes report their own deallocation in canary mode In canary mode every JS-extended class gets a -dealloc that reports the instance to every isolate's canary registry (an instance can have state in an isolate other than the one that defined its class), then calls the superclass's. Their records need no associated token or weak reference, so the default "extended" scope attaches no associations at all. --- NativeScript/runtime/ClassBuilder.mm | 2 + NativeScript/runtime/WrapperLifetimeCanary.h | 10 +- NativeScript/runtime/WrapperLifetimeCanary.mm | 105 ++++++++++++++---- .../app/tests/WrapperLifetimeModesTests.js | 25 +++++ docs/knowledge/v8-resurrecting-finalizers.md | 7 +- 5 files changed, 123 insertions(+), 26 deletions(-) diff --git a/NativeScript/runtime/ClassBuilder.mm b/NativeScript/runtime/ClassBuilder.mm index ecfaf8029..7073a1553 100644 --- a/NativeScript/runtime/ClassBuilder.mm +++ b/NativeScript/runtime/ClassBuilder.mm @@ -92,6 +92,7 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { tns::Assert(extendedClass != nil, isolate); class_addProtocol(extendedClass, @protocol(TNSDerivedClass)); class_addProtocol(object_getClass(extendedClass), @protocol(TNSDerivedClass)); + WrapperLifetimeCanary::InstallDeallocHook(extendedClass); if (!nativeSignature.IsEmpty()) { ClassBuilder::ExposeDynamicMembers(context, extendedClass, implementationObject, @@ -238,6 +239,7 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { tns::Assert(extendedClass != nil, isolate); class_addProtocol(extendedClass, @protocol(TNSDerivedClass)); class_addProtocol(object_getClass(extendedClass), @protocol(TNSDerivedClass)); + WrapperLifetimeCanary::InstallDeallocHook(extendedClass); extendedClassName = class_getName(extendedClass); diff --git a/NativeScript/runtime/WrapperLifetimeCanary.h b/NativeScript/runtime/WrapperLifetimeCanary.h index 22a8212e6..255859e24 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.h +++ b/NativeScript/runtime/WrapperLifetimeCanary.h @@ -18,8 +18,9 @@ struct CanaryRecord; // for the same object forwards to the same state. // // The state object is rooted from its first write until the native object is -// deallocated, reported by an associated token's -dealloc or found by a sweep -// of weak references after major collections (NS_CANARY_DEATH_SIGNAL in the +// deallocated. A JS-extended class's own -dealloc reports its instances; for +// other objects an associated token's -dealloc does, or a sweep of weak +// references after major collections finds it (NS_CANARY_DEATH_SIGNAL in the // .mm chooses). It cannot be rooted // only once the canary dies instead: a state reachable only through the canary // is garbage in the same collection, before any phantom callback runs. The @@ -37,6 +38,11 @@ class WrapperLifetimeCanary { public: static void Init(v8::Isolate* isolate); + // Gives a JS-extended class a -dealloc that reports its instances' deaths, + // so their state needs no associated token or weak reference. No-op unless + // the mode is canary. + static void InstallDeallocHook(Class extendedClass); + // Installs the forwarding handlers on an ObjC instance template. No-op unless // the mode is canary. static void ConfigureInstanceTemplate(v8::Local instanceTemplate); diff --git a/NativeScript/runtime/WrapperLifetimeCanary.mm b/NativeScript/runtime/WrapperLifetimeCanary.mm index e6eb60658..cf44e239b 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.mm +++ b/NativeScript/runtime/WrapperLifetimeCanary.mm @@ -1,5 +1,6 @@ #include "WrapperLifetimeCanary.h" #import +#include #include #include #include @@ -12,10 +13,12 @@ #include "Helpers.h" #include "ObjectManager.h" #include "Runtime.h" +#import "TNSDerivedClass.h" #include "WrapperLifetime.h" // How canary mode learns that a native object with state was deallocated, so -// its state can be let go of: +// its state can be let go of. Instances of JS-extended classes are reported by +// their class's own -dealloc (InstallDeallocHook) either way; for others: // - ASSOCIATION: a token associated with the object reports it from its // -dealloc, immediately and on any thread. The ObjC runtime aborts the // process for a class that forbids associated objects (no public query). @@ -28,10 +31,8 @@ #define NS_CANARY_DEATH_SIGNAL NS_CANARY_DEATH_ASSOCIATION #endif -#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_WEAK_SWEEP extern "C" id objc_initWeakOrNil(id* location, id value); extern "C" void objc_destroyWeak(id* location); -#endif using namespace v8; @@ -45,8 +46,12 @@ struct CanaryRecord { Global state; std::atomic died{false}; -#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_WEAK_SWEEP - // Zeroed by the ObjC runtime when the object is deallocated, on any thread. + // Something reports this object's deallocation: a JS-extended class's + // -dealloc, or the associated token. Otherwise only the weak reference below + // tells, when a sweep reads it. + bool reportsDeath = false; + // An ObjC weak reference to the object, zeroed by the runtime when it is + // deallocated, on any thread. Set for records nothing reports. id object = nil; ~CanaryRecord() { objc_destroyWeak(&object); } @@ -54,11 +59,9 @@ // A racy read is enough: the slot only goes from the object to nil, and is // never dereferenced here. bool ObjectAlive() const { - return __atomic_load_n(reinterpret_cast(&object), __ATOMIC_ACQUIRE) != nullptr; + return reportsDeath || + __atomic_load_n(reinterpret_cast(&object), __ATOMIC_ACQUIRE) != nullptr; } -#else - bool ObjectAlive() const { return true; } -#endif }; namespace { @@ -89,7 +92,6 @@ bool ObjectAlive() const { std::shared_ptr registry = std::make_shared(); }; -#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_ASSOCIATION void DrainDead(const std::shared_ptr& registry) { std::vector> dead; { @@ -109,8 +111,11 @@ void DrainDead(const std::shared_ptr& registry) { } } -// From the token's -dealloc, on whichever thread deallocates the object. +// From a reporter's -dealloc, on whichever thread deallocates the object. void NativeDied(const std::shared_ptr& registry, void* object) { + if (registry->count.load(std::memory_order_relaxed) == 0) { + return; + } std::shared_ptr loop; { std::lock_guard lock(registry->mutex); @@ -139,7 +144,35 @@ void NativeDied(const std::shared_ptr& registry, void* object) { registry->drainPosted = false; } } -#endif + +// Every isolate's registry, for the extended classes' -dealloc: an instance can +// have state in an isolate other than the one that defined its class. +std::mutex registriesMutex_; +std::vector> registries_; + +void ReportDeallocToAllRegistries(void* object) { + std::vector> live; + { + std::lock_guard lock(registriesMutex_); + for (auto it = registries_.begin(); it != registries_.end();) { + if (std::shared_ptr registry = it->lock()) { + if (registry->count.load(std::memory_order_relaxed) > 0) { + live.push_back(std::move(registry)); + } + ++it; + } else { + it = registries_.erase(it); + } + } + } + for (const std::shared_ptr& registry : live) { + NativeDied(registry, object); + } +} + +bool IsExtendedInstance(id object) { + return [object_getClass(object) conformsToProtocol:@protocol(TNSDerivedClass)]; +} #if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_WEAK_SWEEP // Lets go of the state of every object that was deallocated. Runs as an event @@ -271,6 +304,8 @@ bool StateForWrite(Isolate* isolate, Local holder, Local* out) { } } id object = canary->lifetimeTarget_; + // A JS-extended class's own -dealloc reports its instances' deaths. + bool extended = IsExtendedInstance(object); bool created = false; { std::lock_guard lock(registry->mutex); @@ -284,13 +319,12 @@ bool StateForWrite(Isolate* isolate, Local holder, Local* out) { std::shared_ptr& slot = registry->records[(__bridge void*)object]; if (slot == nullptr) { auto record = std::make_shared(); -#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_WEAK_SWEEP - if (objc_initWeakOrNil(&record->object, object) == nil) { + record->reportsDeath = extended || NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_ASSOCIATION; + if (!record->reportsDeath && objc_initWeakOrNil(&record->object, object) == nil) { // The class refuses weak references. registry->records.erase((__bridge void*)object); return false; } -#endif record->state.Reset(isolate, Object::New(isolate, Null(isolate), nullptr, nullptr, 0)); slot = std::move(record); registry->count.fetch_add(1, std::memory_order_relaxed); @@ -300,12 +334,14 @@ bool StateForWrite(Isolate* isolate, Local holder, Local* out) { } if (created) { #if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_ASSOCIATION - TNSCanaryLifecycleToken* token = [[TNSCanaryLifecycleToken alloc] init]; - token->registry_ = registry; - token->object_ = (__bridge void*)object; - objc_setAssociatedObject(object, ®istry->associationKey, token, - OBJC_ASSOCIATION_RETAIN_NONATOMIC); - [token release]; + if (!extended) { + TNSCanaryLifecycleToken* token = [[TNSCanaryLifecycleToken alloc] init]; + token->registry_ = registry; + token->object_ = (__bridge void*)object; + objc_setAssociatedObject(object, ®istry->associationKey, token, + OBJC_ASSOCIATION_RETAIN_NONATOMIC); + [token release]; + } #endif if (ObjectManager::LifetimeStats* stats = ObjectManager::GetLifetimeStats(isolate)) { stats->canaryStates++; @@ -480,12 +516,39 @@ void PostSweepAfterGC(Isolate* isolate, GCType, GCCallbackFlags) { if (Runtime* runtime = Runtime::GetRuntime(isolate)) { state->registry->loop = runtime->GetEventLoop(); } + { + std::lock_guard lock(registriesMutex_); + registries_.push_back(state->registry); + } #if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_WEAK_SWEEP isolate->AddGCPrologueCallback( PostSweepAfterGC, static_cast(kGCTypeMarkSweepCompact | kGCTypeIncrementalMarking)); #endif } +void WrapperLifetimeCanary::InstallDeallocHook(Class extendedClass) { + if (GetWrapperLifetimeMode() != WrapperLifetimeMode::kCanary) { + return; + } + static std::mutex hookedMutex; + static std::unordered_map hooked; + { + std::lock_guard lock(hookedMutex); + if (hooked[extendedClass]) { + return; + } + hooked[extendedClass] = true; + } + Class superclass = class_getSuperclass(extendedClass); + IMP dealloc = imp_implementationWithBlock(^(id self) { + ReportDeallocToAllRegistries((__bridge void*)self); + struct objc_super super = {.receiver = self, .super_class = superclass}; + reinterpret_cast(objc_msgSendSuper)(&super, + @selector(dealloc)); + }); + class_addMethod(extendedClass, @selector(dealloc), dealloc, "v@:"); +} + void WrapperLifetimeCanary::ConfigureInstanceTemplate(Local instanceTemplate) { if (GetWrapperLifetimeMode() != WrapperLifetimeMode::kCanary) { return; diff --git a/TestRunner/app/tests/WrapperLifetimeModesTests.js b/TestRunner/app/tests/WrapperLifetimeModesTests.js index c236c2b07..83f5802a8 100644 --- a/TestRunner/app/tests/WrapperLifetimeModesTests.js +++ b/TestRunner/app/tests/WrapperLifetimeModesTests.js @@ -511,6 +511,31 @@ describe("Wrapper lifetime modes", function () { }); }); + // Plain objects have no class -dealloc of ours: an associated token or a + // weak-reference sweep reports them. + it("lets a plain native object's JS state go when the object is deallocated", function (done) { + var owner = NSMutableArray.new(); + var before = runtime.getWrapperLifetimeStats(); + var watched; + (function () { + var obj = TNSAllocLog.new(); + obj.tag = "state"; + owner.addObject(obj); + watched = watch(obj); + })(); + settle(2, function () { + owner.removeAllObjects(); + settle(3, function () { + var after = runtime.getWrapperLifetimeStats(); + expect(alive(watched)).toBe(0); + if (canary && scope === "all") { + expect(after.canaryNativeDeaths).toBeGreaterThan(before.canaryNativeDeaths); + } + done(); + }); + }); + }); + // The documented cost of the canary contract: state that references its own // object keeps the state, the object's wrapper and the native object alive // until native code would have released it anyway, which nothing does here. diff --git a/docs/knowledge/v8-resurrecting-finalizers.md b/docs/knowledge/v8-resurrecting-finalizers.md index 824c4056d..6c6fdf195 100644 --- a/docs/knowledge/v8-resurrecting-finalizers.md +++ b/docs/knowledge/v8-resurrecting-finalizers.md @@ -263,15 +263,16 @@ that dies with its JS references, releasing the runtime's retain through the sam `kNonMasking` named interceptors on the instance templates forward JS properties to a null-prototype state object, so prototype members never reach them. The state is rooted from its first write until the native object is deallocated; a canary built later for the same -object forwards to the same state. How the deallocation is noticed is a compile-time choice +object forwards to the same state. Instances of JS-extended classes report their own +deallocation: the runtime gives each extended class a `-dealloc` that tells every isolate's +registry, then calls the superclass's. For other objects it is a compile-time choice (`NS_CANARY_DEATH_SIGNAL` in `WrapperLifetimeCanary.mm`): by default a token associated with the object reports it from its `-dealloc`, immediately and on any thread, but the ObjC runtime aborts the process for a class that forbids associated objects, and there is no public query for that; the alternative keeps an ObjC weak reference in each record (`objc_initWeakOrNil`, which declines instead of aborting for classes that refuse weak references) and sweeps the records after every major collection, so state lingers until then. With the default, `"scope": "all"` is -experimental for that reason; with `"extended"` only instances of JS-extended classes get a -token (the flag is inherited, so a JS subclass of a forbidding class would still abort). It cannot be +experimental for that reason; `"extended"` attaches no tokens at all. It cannot be rooted at canary death instead, because a state reachable only through the canary is garbage in the same collection. The cost: state that references its own object (a closure over `this`) keeps it alive. A canary built after a death is a new object, but `===` cannot tell: only one From e6777d05f9d50bce1025048191f17662d2479bb6 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 17 Nov 2026 00:06:16 -0300 Subject: [PATCH 07/24] fix(runtime): canary mode review fixes - A JS-implemented -dealloc replaced the class's death hook, so instances never reported their death: their state stayed rooted and the record, keyed by the freed address, was handed to the next object allocated there. WrapDealloc reports the death once the JS method returns, on the metadata, exposedMethods and prototype-replacement paths. - The state object is allocated before the registry lock: a collection the allocation starts can run callbacks that take it. - The weak sweep is posted from a GC epilogue, behind the collection's release drain. - IsExtendedInstance checks the protocol through the superclasses without messaging the class; objc_initWeakOrNil is only referenced by the weak sweep build. - Outside canary mode an NSArray's Symbol.iterator keeps its array again, so an unbound call still iterates it. - Docs: a JS property named like a prototype member is defined on the canary itself and does not survive its replacement; the state-lost warnings do nothing in canary mode. - Specs: a JS -dealloc class reports its deaths, the prototype-name limit, the unbound iterator; the association spec uses an object that carries a token, and the hand-back spec checks the old canary died. --- NativeScript/runtime/ClassBuilder.mm | 13 ++- NativeScript/runtime/MetadataBuilder.mm | 2 +- NativeScript/runtime/SymbolIterator.mm | 32 +++++--- NativeScript/runtime/WrapperLifetimeCanary.h | 13 ++- NativeScript/runtime/WrapperLifetimeCanary.mm | 43 +++++++--- .../app/tests/WrapperLifetimeModesTests.js | 82 ++++++++++++++++++- docs/knowledge/v8-resurrecting-finalizers.md | 6 +- types/ns-runtime.d.ts | 4 +- 8 files changed, 164 insertions(+), 31 deletions(-) diff --git a/NativeScript/runtime/ClassBuilder.mm b/NativeScript/runtime/ClassBuilder.mm index 7073a1553..af78aacb0 100644 --- a/NativeScript/runtime/ClassBuilder.mm +++ b/NativeScript/runtime/ClassBuilder.mm @@ -742,7 +742,14 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { IMP methodBody = Interop::CreateMethod(2, argsCount, typeEncoding, ArgConverter::MethodCallback, userData); std::string typeInfo = GetTypeEncoding(typeEncoding, argsCount); - tns::Assert(class_addMethod(extendedClass, selector, methodBody, typeInfo.c_str()), isolate); + IMP installed = WrapperLifetimeCanary::WrapDealloc(selector, methodBody); + if (installed != methodBody) { + // Replaces the canary dealloc hook the class already carries. + class_replaceMethod(extendedClass, selector, installed, typeInfo.c_str()); + } else { + tns::Assert(class_addMethod(extendedClass, selector, methodBody, typeInfo.c_str()), + isolate); + } } } @@ -849,7 +856,9 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { IMP methodBody = Interop::CreateMethod(2, argsCount, typeEncoding, ArgConverter::MethodCallback, userData); std::string typeInfo = GetTypeEncoding(typeEncoding, argsCount); - class_replaceMethod(extendedClass, selector, methodBody, typeInfo.c_str()); + class_replaceMethod(extendedClass, selector, + WrapperLifetimeCanary::WrapDealloc(selector, methodBody), + typeInfo.c_str()); } } } diff --git a/NativeScript/runtime/MetadataBuilder.mm b/NativeScript/runtime/MetadataBuilder.mm index 2087a0163..5f96d152f 100644 --- a/NativeScript/runtime/MetadataBuilder.mm +++ b/NativeScript/runtime/MetadataBuilder.mm @@ -1403,7 +1403,7 @@ void ReplaceKeepingOriginal(Class klass, SEL selector, const char* selectorName, !ClassBuilder::ImplementsItself(klass, selector) && class_respondsToSelector(klass, alias); Method method = class_getInstanceMethod(klass, inheritsAlias ? alias : selector); IMP original = method != nullptr ? method_getImplementation(method) : nullptr; - class_replaceMethod(klass, selector, imp, types); + class_replaceMethod(klass, selector, WrapperLifetimeCanary::WrapDealloc(selector, imp), types); if (original != nullptr) { class_addMethod(klass, alias, original, types); } diff --git a/NativeScript/runtime/SymbolIterator.mm b/NativeScript/runtime/SymbolIterator.mm index 33c940838..a4c85c203 100644 --- a/NativeScript/runtime/SymbolIterator.mm +++ b/NativeScript/runtime/SymbolIterator.mm @@ -2,6 +2,7 @@ #include #include "ArgConverter.h" #include "Helpers.h" +#include "WrapperLifetime.h" using namespace v8; @@ -10,18 +11,27 @@ void SymbolIterator::Set(Local context, Local object) { Isolate* isolate = v8::Isolate::GetCurrent(); - // Iterates its receiver rather than capturing `object`: in the canary - // wrapper lifetime mode this property lives on the object's state, which a - // reference back to the object would keep alive until native death. + // In the canary wrapper lifetime mode it iterates its receiver: this + // property lives on the object's state there, which a reference back to the + // object would keep alive until native death. Elsewhere it keeps `object`, so + // an unbound call still iterates it. + Local captured = GetWrapperLifetimeMode() == WrapperLifetimeMode::kCanary + ? Local() + : object; Local iterator; - bool success = v8::Function::New(context, - [](const FunctionCallbackInfo& args) { - Isolate* isolate = args.GetIsolate(); - Local context = isolate->GetCurrentContext(); - Local result = - CreateIteratorObject(context, args.This()); - args.GetReturnValue().Set(result); - }) + bool success = v8::Function::New( + context, + [](const FunctionCallbackInfo& args) { + Isolate* isolate = args.GetIsolate(); + Local context = isolate->GetCurrentContext(); + Local target = args.Data(); + if (target.IsEmpty() || target->IsUndefined()) { + target = args.This(); + } + Local result = CreateIteratorObject(context, target); + args.GetReturnValue().Set(result); + }, + captured) .ToLocal(&iterator); tns::Assert(success, isolate); diff --git a/NativeScript/runtime/WrapperLifetimeCanary.h b/NativeScript/runtime/WrapperLifetimeCanary.h index 255859e24..7e8fefac3 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.h +++ b/NativeScript/runtime/WrapperLifetimeCanary.h @@ -1,6 +1,7 @@ #ifndef WrapperLifetimeCanary_h #define WrapperLifetimeCanary_h +#include #include #include "Common.h" @@ -21,9 +22,9 @@ struct CanaryRecord; // deallocated. A JS-extended class's own -dealloc reports its instances; for // other objects an associated token's -dealloc does, or a sweep of weak // references after major collections finds it (NS_CANARY_DEATH_SIGNAL in the -// .mm chooses). It cannot be rooted -// only once the canary dies instead: a state reachable only through the canary -// is garbage in the same collection, before any phantom callback runs. The +// .mm chooses). It cannot be rooted only once the canary dies instead: a state +// reachable only through the canary is garbage in the same collection, before +// any phantom callback runs. The // cost is that state referencing its own canary (a closure over `this`, a // WeakMap value naming the object) keeps the canary, and through its retain the // native object, alive. This is the portable contract, the one the Node-API @@ -43,6 +44,12 @@ class WrapperLifetimeCanary { // the mode is canary. static void InstallDeallocHook(Class extendedClass); + // The IMP to install for `selector` on a JS-extended class: a JS-implemented + // -dealloc replaces the hook above, so it reports the death itself once the + // JS method returns. `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. static void ConfigureInstanceTemplate(v8::Local instanceTemplate); diff --git a/NativeScript/runtime/WrapperLifetimeCanary.mm b/NativeScript/runtime/WrapperLifetimeCanary.mm index cf44e239b..280acd9eb 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.mm +++ b/NativeScript/runtime/WrapperLifetimeCanary.mm @@ -31,7 +31,9 @@ #define NS_CANARY_DEATH_SIGNAL NS_CANARY_DEATH_ASSOCIATION #endif +#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_WEAK_SWEEP extern "C" id objc_initWeakOrNil(id* location, id value); +#endif extern "C" void objc_destroyWeak(id* location); using namespace v8; @@ -170,8 +172,15 @@ void ReportDeallocToAllRegistries(void* object) { } } +// Not a message: a root class without -conformsToProtocol: would crash under +// scope "all". Walks the superclasses for key-value observing's subclass. bool IsExtendedInstance(id object) { - return [object_getClass(object) conformsToProtocol:@protocol(TNSDerivedClass)]; + for (Class cls = object_getClass(object); cls != nil; cls = class_getSuperclass(cls)) { + if (class_conformsToProtocol(cls, @protocol(TNSDerivedClass))) { + return true; + } + } + return false; } #if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_WEAK_SWEEP @@ -298,14 +307,12 @@ bool StateForWrite(Isolate* isolate, Local holder, Local* out) { if (registry == nullptr) { return false; } - if (registry->loop.expired()) { - if (Runtime* runtime = Runtime::GetRuntime(isolate)) { - registry->loop = runtime->GetEventLoop(); - } - } id object = canary->lifetimeTarget_; // A JS-extended class's own -dealloc reports its instances' deaths. bool extended = IsExtendedInstance(object); + // 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); bool created = false; { std::lock_guard lock(registry->mutex); @@ -320,12 +327,14 @@ 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; +#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_WEAK_SWEEP if (!record->reportsDeath && objc_initWeakOrNil(&record->object, object) == nil) { // The class refuses weak references. registry->records.erase((__bridge void*)object); return false; } - record->state.Reset(isolate, Object::New(isolate, Null(isolate), nullptr, nullptr, 0)); +#endif + record->state.Reset(isolate, freshState); slot = std::move(record); registry->count.fetch_add(1, std::memory_order_relaxed); created = true; @@ -479,8 +488,9 @@ Intercepted Descriptor(Local property, const PropertyCallbackInfo(isolate); if (state == nullptr || state->registry->count.load(std::memory_order_relaxed) == 0) { @@ -521,8 +531,7 @@ void PostSweepAfterGC(Isolate* isolate, GCType, GCCallbackFlags) { registries_.push_back(state->registry); } #if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_WEAK_SWEEP - isolate->AddGCPrologueCallback( - PostSweepAfterGC, static_cast(kGCTypeMarkSweepCompact | kGCTypeIncrementalMarking)); + isolate->AddGCEpilogueCallback(PostSweepAfterGC, kGCTypeMarkSweepCompact); #endif } @@ -549,6 +558,18 @@ void PostSweepAfterGC(Isolate* isolate, GCType, GCCallbackFlags) { class_addMethod(extendedClass, @selector(dealloc), dealloc, "v@:"); } +IMP WrapperLifetimeCanary::WrapDealloc(SEL selector, IMP imp) { + if (selector != @selector(dealloc) || + GetWrapperLifetimeMode() != WrapperLifetimeMode::kCanary) { + return imp; + } + return imp_implementationWithBlock(^(id self) { + void* object = (__bridge void*)self; + reinterpret_cast(imp)(self, @selector(dealloc)); + ReportDeallocToAllRegistries(object); + }); +} + void WrapperLifetimeCanary::ConfigureInstanceTemplate(Local instanceTemplate) { if (GetWrapperLifetimeMode() != WrapperLifetimeMode::kCanary) { return; diff --git a/TestRunner/app/tests/WrapperLifetimeModesTests.js b/TestRunner/app/tests/WrapperLifetimeModesTests.js index 83f5802a8..cf83e10b0 100644 --- a/TestRunner/app/tests/WrapperLifetimeModesTests.js +++ b/TestRunner/app/tests/WrapperLifetimeModesTests.js @@ -458,12 +458,17 @@ describe("Wrapper lifetime modes", function () { it("hands back a native object's JS properties on a new wrapper after the old one died", function (done) { var owner = NSMutableArray.new(); + var first; (function () { var obj = Extended.new(); obj.tag = "kept"; owner.addObject(obj); + first = new WeakRef(obj); })(); settle(2, function () { + if (canary) { + expect(first.deref()).toBeUndefined(); + } var obj = owner.objectAtIndex(0); if (keepsState) { expect(obj.tag).toBe("kept"); @@ -472,6 +477,80 @@ describe("Wrapper lifetime modes", function () { }); }); + // kNonMasking interceptors only see names the prototype chain lacks: a JS + // property shadowing a prototype member is defined on the wrapper itself, + // so in canary mode it goes with the wrapper. A documented limit. + it("keeps a JS property that shadows a prototype member only while its canary lives", function (done) { + var owner = NSMutableArray.new(); + (function () { + var obj = Extended.new(); + obj.isEqual = function () { + return "shadow"; + }; + obj.tag = "kept"; + owner.addObject(obj); + })(); + settle(2, function () { + var obj = owner.objectAtIndex(0); + if (canary) { + expect(obj.tag).toBe("kept"); + expect(obj.isEqual(obj)).toBe(true); + } else if (rooted) { + expect(obj.isEqual(obj)).toBe("shadow"); + } + done(); + }); + }); + + // A JS-implemented dealloc replaces the class's own death hook, so it + // reports the death itself, after the JS method ran. + it("lets the JS state go when a JS-implemented dealloc ran", function (done) { + var N = 8; + var seen = []; + var WithDealloc = TNSAllocLog.extend({ + dealloc: function () { + seen.push(true); + this.super.dealloc(); + } + }, { name: "WrapperLifetimeModesJSDealloc" }); + var owner = NSMutableArray.new(); + settle(2, function () { + var before = runtime.getWrapperLifetimeStats(); + (function () { + for (var i = 0; i < N; i++) { + var obj = WithDealloc.new(); + obj.tag = "state"; + owner.addObject(obj); + } + })(); + settle(2, function () { + owner.removeAllObjects(); + settle(3, function () { + var after = runtime.getWrapperLifetimeStats(); + expect(seen.length).toBe(N); + if (canary) { + expect(after.canaryNativeDeaths - before.canaryNativeDeaths).not.toBeLessThan(N); + } + done(); + }); + }); + }); + }); + + it("iterates an NSArray through an unbound Symbol.iterator outside canary mode", function () { + if (canary) { + return; + } + var array = NSArray.arrayWithArray(["a", "b"]); + var iterate = array[Symbol.iterator]; + var iterator = iterate(); + var values = []; + for (var step = iterator.next(); !step.done; step = iterator.next()) { + values.push(step.value); + } + expect(values).toEqual(["a", "b"]); + }); + it("leaves plain objects outside the extended scope without forwarding", function (done) { var owner = NSMutableArray.new(); (function () { @@ -561,7 +640,8 @@ describe("Wrapper lifetime modes", function () { if (typeof objc_removeAssociatedObjects !== "function") { return; } - var obj = Extended.new(); + // Only objects outside JS-extended classes carry the token. + var obj = scope === "all" ? TNSAllocLog.new() : Extended.new(); obj.tag = "first"; objc_removeAssociatedObjects(obj); expect([undefined, "first"]).toContain(obj.tag); diff --git a/docs/knowledge/v8-resurrecting-finalizers.md b/docs/knowledge/v8-resurrecting-finalizers.md index 6c6fdf195..0cef64e47 100644 --- a/docs/knowledge/v8-resurrecting-finalizers.md +++ b/docs/knowledge/v8-resurrecting-finalizers.md @@ -253,7 +253,7 @@ JS-referencing native cycles alive (ARC rules: break them with a `WeakRef`). Spe 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 +silent in the rooted and canary modes. Under `"scope": "extended"` in the rooted mode, 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. @@ -281,6 +281,10 @@ What does notice is whatever keys on the canary without keeping it: `WeakMap` ke of the old canary, and native `#private` fields, which are branded on it. Other limits: `Object.freeze`, `seal` and `preventExtensions` throw on a canary (V8 refuses them on objects with interceptors); index-keyed properties are not forwarded and die with the canary; +so does a property named like anything on the prototype chain (a class method rebound with +`this.onTap = this.onTap.bind(this)`, a field called `copy` or `toString`, any +`Object.defineProperty` or define-semantics class field over such a name): a `kNonMasking` +interceptor is skipped for a name the chain has, so V8 defines it on the canary itself; a write through an object whose prototype is a canary lands in the canary's state, since interceptors see the holder but not the receiver. Relies on V8's own-property lookup through `kNonMasking` interceptors when the prototype has a named diff --git a/types/ns-runtime.d.ts b/types/ns-runtime.d.ts index b78e6bc5c..324beb786 100644 --- a/types/ns-runtime.d.ts +++ b/types/ns-runtime.d.ts @@ -55,7 +55,9 @@ declare module "ns:runtime" { * references; JS properties set on it live on a state object kept until * the native object is deallocated, and a wrapper built for the object * later has them again. Weak references to the old wrapper (WeakMap keys, - * WeakRef) and native `#private` fields do not carry over. + * WeakRef), native `#private` fields, index-keyed properties and + * properties named like a member of the prototype chain (a rebound class + * method, a field called `copy`) do not carry over. * State that references its own object keeps that object alive. */ wrapperLifetimeMode: "resurrecting" | "rooted" | "canary"; From cc3f2d0163466bce8c4dc8213ecdcd5dd2038712 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 17 Nov 2026 01:31:09 -0300 Subject: [PATCH 08/24] fix(runtime): canary -dealloc receivers read state; retire dying records by identity - A JS-implemented -dealloc runs with a borrowed receiver that is never adopted, so it read no JS properties. It now finds its object's record by address, read-only: it reads and writes the existing state and never creates a record. - WrapDealloc marks the object's records dying in every isolate before the original -dealloc runs, and retires them by identity once it returns. An object allocated at the same address in between gets a record of its own instead of the old one, and the late report no longer erases it. --- NativeScript/runtime/WrapperLifetimeCanary.h | 4 +- NativeScript/runtime/WrapperLifetimeCanary.mm | 98 +++++++++++++++---- .../app/tests/WrapperLifetimeModesTests.js | 4 +- 3 files changed, 85 insertions(+), 21 deletions(-) diff --git a/NativeScript/runtime/WrapperLifetimeCanary.h b/NativeScript/runtime/WrapperLifetimeCanary.h index 7e8fefac3..3e3d516b9 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.h +++ b/NativeScript/runtime/WrapperLifetimeCanary.h @@ -46,8 +46,8 @@ class WrapperLifetimeCanary { // The IMP to install for `selector` on a JS-extended class: a JS-implemented // -dealloc replaces the hook above, so it reports the death itself once the - // JS method returns. `imp` unchanged for any other selector, or unless the - // mode is canary. + // JS method returns; the receiver it runs with reads the object's JS state. + // `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 diff --git a/NativeScript/runtime/WrapperLifetimeCanary.mm b/NativeScript/runtime/WrapperLifetimeCanary.mm index 280acd9eb..0019fb749 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.mm +++ b/NativeScript/runtime/WrapperLifetimeCanary.mm @@ -48,6 +48,10 @@ struct CanaryRecord { Global state; std::atomic died{false}; + // A JS-implemented -dealloc of its object is running (WrapDealloc): the + // object's own receiver still reads this record, but an object allocated + // at the same address once the original -dealloc frees it must not. + std::atomic dying{false}; // Something reports this object's deallocation: a JS-extended class's // -dealloc, or the associated token. Otherwise only the weak reference below // tells, when a sweep reads it. @@ -152,22 +156,57 @@ void NativeDied(const std::shared_ptr& registry, void* object) { std::mutex registriesMutex_; std::vector> registries_; -void ReportDeallocToAllRegistries(void* object) { +std::vector> LiveRegistries() { std::vector> live; - { - std::lock_guard lock(registriesMutex_); - for (auto it = registries_.begin(); it != registries_.end();) { - if (std::shared_ptr registry = it->lock()) { - if (registry->count.load(std::memory_order_relaxed) > 0) { - live.push_back(std::move(registry)); - } - ++it; - } else { - it = registries_.erase(it); + std::lock_guard lock(registriesMutex_); + for (auto it = registries_.begin(); it != registries_.end();) { + if (std::shared_ptr registry = it->lock()) { + if (registry->count.load(std::memory_order_relaxed) > 0) { + live.push_back(std::move(registry)); } + ++it; + } else { + it = registries_.erase(it); + } + } + return live; +} + +void ReportDeallocToAllRegistries(void* object) { + for (const std::shared_ptr& registry : LiveRegistries()) { + NativeDied(registry, object); + } +} + +using DyingRecords = + std::vector, std::shared_ptr>>; + +// Before a JS-implemented -dealloc runs: marks the object's records dying in +// every isolate. +DyingRecords MarkDying(void* object) { + DyingRecords dying; + for (std::shared_ptr& registry : LiveRegistries()) { + std::lock_guard lock(registry->mutex); + auto it = registry->records.find(object); + if (!registry->closed && it != registry->records.end()) { + it->second->dying.store(true, std::memory_order_release); + dying.emplace_back(registry, it->second); } } - for (const std::shared_ptr& registry : live) { + return dying; +} + +// After it returned: retires each record by identity. A record a new object at +// the address already displaced (RetireIfDead) is gone from the map. +void ReportDyingRecordsDied(const DyingRecords& dying, void* object) { + for (const auto& [registry, record] : dying) { + { + std::lock_guard lock(registry->mutex); + auto it = registry->records.find(object); + if (registry->closed || it == registry->records.end() || it->second != record) { + continue; + } + } NativeDied(registry, object); } } @@ -277,7 +316,7 @@ bool Usable(const std::shared_ptr& record) { // has reached yet is moved out, so an object now at that address starts over. void RetireIfDead(CanaryRegistry* registry, std::unordered_map>::iterator it) { - if (it->second->ObjectAlive()) { + if (it->second->ObjectAlive() && !it->second->dying.load(std::memory_order_acquire)) { return; } it->second->died.store(true, std::memory_order_release); @@ -286,13 +325,33 @@ void RetireIfDead(CanaryRegistry* registry, registry->count.fetch_sub(1, std::memory_order_relaxed); } +// The record a receiver lent to JS from -dealloc reads: its object's record, +// dying or not. Such a receiver is never adopted, so it has no canary state. +std::shared_ptr BorrowedRecord(Isolate* isolate, Local holder) { + BaseDataWrapper* wrapper = tns::GetValue(isolate, holder); + if (wrapper == nullptr || wrapper->Type() != WrapperType::ObjCObject || + !static_cast(wrapper)->IsBorrowed()) { + return nullptr; + } + CanaryState* state = Caches::StateFor(isolate); + if (state == nullptr || state->registry->count.load(std::memory_order_relaxed) == 0) { + return nullptr; + } + std::lock_guard lock(state->registry->mutex); + auto it = state->registry->records.find( + (__bridge void*)static_cast(wrapper)->Data()); + return it != state->registry->records.end() ? it->second : nullptr; +} + // The state object of the holder, if it has one. bool ExistingState(Isolate* isolate, Local holder, Local* out) { ObjectWeakCallbackState* canary = CanaryOf(isolate, holder); - if (canary == nullptr || !Usable(canary->canaryRecord_)) { + std::shared_ptr record = + canary != nullptr ? canary->canaryRecord_ : BorrowedRecord(isolate, holder); + if (!Usable(record)) { return false; } - *out = Local::New(isolate, canary->canaryRecord_->state); + *out = Local::New(isolate, record->state); return true; } @@ -300,7 +359,8 @@ bool ExistingState(Isolate* isolate, Local holder, Local* out) { bool StateForWrite(Isolate* isolate, Local holder, Local* out) { ObjectWeakCallbackState* canary = CanaryOf(isolate, holder); if (canary == nullptr) { - return false; + // A -dealloc receiver writes to its object's existing state only. + return ExistingState(isolate, holder, out); } if (canary->canaryRecord_ == nullptr || canary->canaryRecord_->died.load(std::memory_order_acquire)) { std::shared_ptr registry = RegistryFor(isolate); @@ -565,8 +625,9 @@ void PostSweepAfterGC(Isolate* isolate, GCType, GCCallbackFlags) { } return imp_implementationWithBlock(^(id self) { void* object = (__bridge void*)self; + DyingRecords dying = MarkDying(object); reinterpret_cast(imp)(self, @selector(dealloc)); - ReportDeallocToAllRegistries(object); + ReportDyingRecordsDied(dying, object); }); } @@ -591,7 +652,8 @@ void PostSweepAfterGC(Isolate* isolate, GCType, GCCallbackFlags) { } std::shared_ptr record = it->second; RetireIfDead(state->registry.get(), it); - return record->ObjectAlive() ? record : nullptr; + return record->ObjectAlive() && !record->dying.load(std::memory_order_acquire) ? record + : nullptr; } void WrapperLifetimeCanary::CloseForTeardown(Isolate* isolate) { diff --git a/TestRunner/app/tests/WrapperLifetimeModesTests.js b/TestRunner/app/tests/WrapperLifetimeModesTests.js index cf83e10b0..8ef237726 100644 --- a/TestRunner/app/tests/WrapperLifetimeModesTests.js +++ b/TestRunner/app/tests/WrapperLifetimeModesTests.js @@ -509,7 +509,7 @@ describe("Wrapper lifetime modes", function () { var seen = []; var WithDealloc = TNSAllocLog.extend({ dealloc: function () { - seen.push(true); + seen.push(this.tag); this.super.dealloc(); } }, { name: "WrapperLifetimeModesJSDealloc" }); @@ -529,6 +529,8 @@ describe("Wrapper lifetime modes", function () { var after = runtime.getWrapperLifetimeStats(); expect(seen.length).toBe(N); if (canary) { + // The JS dealloc still reads the object's JS state. + expect(seen.filter(function (tag) { return tag === "state"; }).length).toBe(N); expect(after.canaryNativeDeaths - before.canaryNativeDeaths).not.toBeLessThan(N); } done(); From 15bf1c3521f7cfc20614d14ce97a5965e2211b26 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 17 Nov 2026 02:52:23 -0300 Subject: [PATCH 09/24] fix(runtime): canary records outlive the superclass dealloc and drain when retired - A JS-extended class's own -dealloc hook marks the instance's records dying, calls the superclass's -dealloc, and then retires them by identity, as a wrapped JS -dealloc does, so a superclass -dealloc implemented in JS would still read the state. Nothing reaches that today: .extend() and __extends refuse to subclass a JS-extended class, and metadata exposes no -dealloc to replace on a native prototype. - Records that Find or a first write retire (a dying or swept object) get a drain posted, so their state is let go of without waiting for another native death. - The weak-sweep build posts a sweep after a major GC while retired records wait, even once no record is in use. - The native-death specs check that the JS state itself is collected. --- NativeScript/runtime/WrapperLifetimeCanary.mm | 67 +++++++++++++------ .../app/tests/WrapperLifetimeModesTests.js | 8 +++ 2 files changed, 55 insertions(+), 20 deletions(-) diff --git a/NativeScript/runtime/WrapperLifetimeCanary.mm b/NativeScript/runtime/WrapperLifetimeCanary.mm index 0019fb749..a247af5e5 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.mm +++ b/NativeScript/runtime/WrapperLifetimeCanary.mm @@ -172,12 +172,6 @@ void NativeDied(const std::shared_ptr& registry, void* object) { return live; } -void ReportDeallocToAllRegistries(void* object) { - for (const std::shared_ptr& registry : LiveRegistries()) { - NativeDied(registry, object); - } -} - using DyingRecords = std::vector, std::shared_ptr>>; @@ -314,15 +308,34 @@ bool Usable(const std::shared_ptr& record) { // Under the registry mutex: a record whose object is gone but which no sweep // has reached yet is moved out, so an object now at that address starts over. -void RetireIfDead(CanaryRegistry* registry, +// True when it was; the caller then owes the registry a drain (PostDrain). +bool RetireIfDead(CanaryRegistry* registry, std::unordered_map>::iterator it) { if (it->second->ObjectAlive() && !it->second->dying.load(std::memory_order_acquire)) { - return; + return false; } it->second->died.store(true, std::memory_order_release); registry->dead.push_back(std::move(it->second)); registry->records.erase(it); registry->count.fetch_sub(1, std::memory_order_relaxed); + return true; +} + +// Outside the registry mutex: lets go of retired records' state on the event +// loop, unless a drain is already on its way. +void PostDrain(const std::shared_ptr& registry) { + std::shared_ptr loop = registry->loop.lock(); + { + std::lock_guard lock(registry->mutex); + if (registry->closed || registry->drainPosted || registry->dead.empty() || loop == nullptr) { + return; + } + registry->drainPosted = true; + } + if (!loop->PostInternal([registry]() { DrainDead(registry); })) { + std::lock_guard lock(registry->mutex); + registry->drainPosted = false; + } } // The record a receiver lent to JS from -dealloc reads: its object's record, @@ -374,6 +387,7 @@ bool StateForWrite(Isolate* isolate, Local holder, Local* out) { // callbacks (the weak sweep's, a finalizer's -dealloc) that take it. Local freshState = Object::New(isolate, Null(isolate), nullptr, nullptr, 0); bool created = false; + bool retired = false; { std::lock_guard lock(registry->mutex); if (registry->closed) { @@ -381,7 +395,7 @@ bool StateForWrite(Isolate* isolate, Local holder, Local* out) { } auto existing = registry->records.find((__bridge void*)object); if (existing != registry->records.end()) { - RetireIfDead(registry.get(), existing); + retired = RetireIfDead(registry.get(), existing); } std::shared_ptr& slot = registry->records[(__bridge void*)object]; if (slot == nullptr) { @@ -401,6 +415,9 @@ bool StateForWrite(Isolate* isolate, Local holder, Local* out) { } canary->canaryRecord_ = slot; } + if (retired) { + PostDrain(registry); + } if (created) { #if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_ASSOCIATION if (!extended) { @@ -553,14 +570,16 @@ Intercepted Descriptor(Local property, const PropertyCallbackInfo(isolate); - if (state == nullptr || state->registry->count.load(std::memory_order_relaxed) == 0) { + if (state == nullptr) { return; } std::shared_ptr registry = state->registry; std::shared_ptr loop = registry->loop.lock(); { std::lock_guard lock(registry->mutex); - if (registry->sweepPosted || loop == nullptr) { + // Records already retired wait in `dead` even once none is left in use. + if (registry->sweepPosted || loop == nullptr || + (registry->count.load(std::memory_order_relaxed) == 0 && registry->dead.empty())) { return; } registry->sweepPosted = true; @@ -609,11 +628,15 @@ void PostSweepAfterGC(Isolate* isolate, GCType, GCCallbackFlags) { hooked[extendedClass] = true; } Class superclass = class_getSuperclass(extendedClass); + // The records stay dying, not gone, until the superclass's -dealloc returns, + // as WrapDealloc keeps them: one implemented in JS reads the state. IMP dealloc = imp_implementationWithBlock(^(id self) { - ReportDeallocToAllRegistries((__bridge void*)self); + void* object = (__bridge void*)self; + DyingRecords dying = MarkDying(object); struct objc_super super = {.receiver = self, .super_class = superclass}; reinterpret_cast(objc_msgSendSuper)(&super, @selector(dealloc)); + ReportDyingRecordsDied(dying, object); }); class_addMethod(extendedClass, @selector(dealloc), dealloc, "v@:"); } @@ -645,15 +668,19 @@ void PostSweepAfterGC(Isolate* isolate, GCType, GCCallbackFlags) { if (state == nullptr || state->registry->count.load(std::memory_order_relaxed) == 0) { return nullptr; } - std::lock_guard lock(state->registry->mutex); - auto it = state->registry->records.find((__bridge void*)object); - if (it == state->registry->records.end()) { - return nullptr; + { + std::lock_guard lock(state->registry->mutex); + auto it = state->registry->records.find((__bridge void*)object); + if (it == state->registry->records.end()) { + return nullptr; + } + std::shared_ptr record = it->second; + if (!RetireIfDead(state->registry.get(), it)) { + return record; + } } - std::shared_ptr record = it->second; - RetireIfDead(state->registry.get(), it); - return record->ObjectAlive() && !record->dying.load(std::memory_order_acquire) ? record - : nullptr; + PostDrain(state->registry); + return nullptr; } void WrapperLifetimeCanary::CloseForTeardown(Isolate* isolate) { diff --git a/TestRunner/app/tests/WrapperLifetimeModesTests.js b/TestRunner/app/tests/WrapperLifetimeModesTests.js index 8ef237726..93c9ce897 100644 --- a/TestRunner/app/tests/WrapperLifetimeModesTests.js +++ b/TestRunner/app/tests/WrapperLifetimeModesTests.js @@ -572,9 +572,12 @@ describe("Wrapper lifetime modes", function () { var owner = NSMutableArray.new(); var before = runtime.getWrapperLifetimeStats(); var watched; + var payload; (function () { var obj = Extended.new(); obj.tag = "state"; + obj.payload = {}; + payload = new WeakRef(obj.payload); owner.addObject(obj); watched = watch(obj); })(); @@ -586,6 +589,7 @@ describe("Wrapper lifetime modes", function () { if (canary) { expect(after.canaryStates).toBeGreaterThan(before.canaryStates); expect(after.canaryNativeDeaths).toBeGreaterThan(before.canaryNativeDeaths); + expect(payload.deref()).toBeUndefined(); } done(); }); @@ -598,9 +602,12 @@ describe("Wrapper lifetime modes", function () { var owner = NSMutableArray.new(); var before = runtime.getWrapperLifetimeStats(); var watched; + var payload; (function () { var obj = TNSAllocLog.new(); obj.tag = "state"; + obj.payload = {}; + payload = new WeakRef(obj.payload); owner.addObject(obj); watched = watch(obj); })(); @@ -611,6 +618,7 @@ describe("Wrapper lifetime modes", function () { expect(alive(watched)).toBe(0); if (canary && scope === "all") { expect(after.canaryNativeDeaths).toBeGreaterThan(before.canaryNativeDeaths); + expect(payload.deref()).toBeUndefined(); } done(); }); From a41932af7fb33954f8d067512a55f057c2356e88 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 17 Nov 2026 02:52:23 -0300 Subject: [PATCH 10/24] feat(runtime): canary mode mirrors JS properties onto the canary kNonMasking interceptors never see a write or define over a name the prototype chain has, so `this.onTap = this.onTap.bind(this)`, fields named `copy` and `Object.defineProperty` over a prototype member stayed on the canary and were lost when it was replaced. The canary's named interceptor is now masking, with only a setter, a deleter and a definer. Each one copies its write into the state object and declines, so V8 also applies it to the canary: - Reads find real own properties and never call into C++: expando reads cost what they cost on a plain object. - The setter classifies the name itself, because after it declines V8 adds a new name to the canary without calling the definer. A read-only name or an accessor (a native property, a JS getter/setter, an accessor defined on the canary) is left to V8 and never becomes state, so native setters run as before. - A canary built for an object with state, and the receiver a JS-implemented -dealloc runs with, get the state's properties copied onto them with their attributes and accessors (Hydrate). A record replaced under a live canary (its token was removed) is seeded from the canary. The state object stays the source of truth and keeps its lifetime. Costs: every write to a canary goes through the setter, and building a canary for an object with state copies each of its properties. Class fields still need v8-buildscripts#13: before it, the definer gets inverted attributes for a cold field and is bypassed once the field initializer is warm. --- NativeScript/runtime/ArgConverter.mm | 1 + NativeScript/runtime/ObjectManager.h | 2 +- NativeScript/runtime/WrapperLifetime.h | 2 +- NativeScript/runtime/WrapperLifetime.mm | 3 + NativeScript/runtime/WrapperLifetimeCanary.h | 16 +- NativeScript/runtime/WrapperLifetimeCanary.mm | 243 ++++++++----- .../app/tests/WrapperLifetimeModesTests.js | 343 ++++++++++++++++-- docs/knowledge/v8-resurrecting-finalizers.md | 49 ++- types/ns-runtime.d.ts | 14 +- 9 files changed, 529 insertions(+), 144 deletions(-) diff --git a/NativeScript/runtime/ArgConverter.mm b/NativeScript/runtime/ArgConverter.mm index 28e0c8dda..944b2e89d 100644 --- a/NativeScript/runtime/ArgConverter.mm +++ b/NativeScript/runtime/ArgConverter.mm @@ -1278,6 +1278,7 @@ bool IsKVOSubclassOf(Class klass, Class base) { wrapper->MarkBorrowed(); Local receiver = NewEmptyInstance(context, cache->EmptyObjCtorFunc.get()); CreateJsWrapper(context, wrapper, receiver); + WrapperLifetimeCanary::Hydrate(isolate, receiver); *borrowed = wrapper; return receiver; } diff --git a/NativeScript/runtime/ObjectManager.h b/NativeScript/runtime/ObjectManager.h index 6e4b693cb..7e8a93c9c 100644 --- a/NativeScript/runtime/ObjectManager.h +++ b/NativeScript/runtime/ObjectManager.h @@ -58,7 +58,7 @@ struct ObjectWeakCallbackState { bool lifetimeTracked_ = false; // The handle is currently strong. bool lifetimeStrong_ = false; - // Canary mode: the wrapper forwards JS properties to a state object that + // Canary mode: the wrapper mirrors JS properties into a state object that // outlives it (WrapperLifetimeCanary), found through this record once the // object has state. bool lifetimeCanary_ = false; diff --git a/NativeScript/runtime/WrapperLifetime.h b/NativeScript/runtime/WrapperLifetime.h index 607840f21..fe18ddb56 100644 --- a/NativeScript/runtime/WrapperLifetime.h +++ b/NativeScript/runtime/WrapperLifetime.h @@ -24,7 +24,7 @@ enum class WrapperLifetimeMode { // Phantom callbacks, no resurrection: the wrapper is a canary that dies with // its JS references. JS properties set on it live on a separate state object // that stays alive until the native object is deallocated, and a canary - // built for the same object later shares it (WrapperLifetimeCanary). + // built for the same object later gets them back (WrapperLifetimeCanary). kCanary, }; diff --git a/NativeScript/runtime/WrapperLifetime.mm b/NativeScript/runtime/WrapperLifetime.mm index 4fb571fe0..7df522c85 100644 --- a/NativeScript/runtime/WrapperLifetime.mm +++ b/NativeScript/runtime/WrapperLifetime.mm @@ -349,6 +349,9 @@ void ReleaseAll(Isolate* isolate, RootedState* rooted) { state->lifetimeCanary_ = IsInScope(target); if (state->lifetimeCanary_) { state->canaryRecord_ = WrapperLifetimeCanary::Find(isolate, target); + if (state->canaryRecord_ != nullptr) { + WrapperLifetimeCanary::Hydrate(isolate, handle->Get(isolate).As()); + } } MakeWeak(state); } else if (IsInScope(target)) { diff --git a/NativeScript/runtime/WrapperLifetimeCanary.h b/NativeScript/runtime/WrapperLifetimeCanary.h index 3e3d516b9..da343a422 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.h +++ b/NativeScript/runtime/WrapperLifetimeCanary.h @@ -12,11 +12,13 @@ struct CanaryRecord; // 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. JS -// properties set on a canary are forwarded by kNonMasking named interceptors -// to a state object, so prototype members (native methods and properties, -// JS-extended class methods) never reach these handlers. A canary built later -// for the same object forwards to the same state. +// 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. // // 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 @@ -58,6 +60,10 @@ class WrapperLifetimeCanary { // canary to share. Null otherwise. static std::shared_ptr Find(v8::Isolate* isolate, id object); + // 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); + // Teardown: lets go of every state object while the isolate is alive. Tokens // that outlive the isolate find the registry closed. static void CloseForTeardown(v8::Isolate* isolate); diff --git a/NativeScript/runtime/WrapperLifetimeCanary.mm b/NativeScript/runtime/WrapperLifetimeCanary.mm index a247af5e5..a38b139f5 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.mm +++ b/NativeScript/runtime/WrapperLifetimeCanary.mm @@ -356,6 +356,66 @@ void PostDrain(const std::shared_ptr& registry) { return it != state->registry->records.end() ? it->second : nullptr; } +// Set while this thread copies properties between a canary and its state, so +// the canary's definer lets those defines through. Per thread rather than per +// isolate: the copy runs no JS, so only its own defines reach an interceptor +// on this thread meanwhile. +thread_local bool copyingProperties_ = false; + +Local DescriptorField(Isolate* isolate, Local context, Local descriptor, + const char* name) { + Local value; + return descriptor->Get(context, tns::ToV8String(isolate, name)).ToLocal(&value) + ? value + : Local(v8::Undefined(isolate)); +} + +// 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`. +void CopyOwnProperties(Isolate* isolate, Local context, Local from, + Local to) { + HandleScope scope(isolate); + TryCatch tc(isolate); + bool wasCopying = copyingProperties_; + copyingProperties_ = true; + Local names; + if (from->GetPropertyNames(context, KeyCollectionMode::kOwnOnly, PropertyFilter::ALL_PROPERTIES, + IndexFilter::kSkipIndices, KeyConversionMode::kConvertToString) + .ToLocal(&names)) { + for (uint32_t i = 0; i < names->Length(); i++) { + Local name; + if (!names->Get(context, i).ToLocal(&name) || !name->IsName()) { + continue; + } + Local key = name.As(); + if (!from->HasRealNamedCallbackProperty(context, key).FromMaybe(true)) { + PropertyAttribute attributes; + Local value; + if (from->GetRealNamedPropertyAttributes(context, key).To(&attributes) && + from->GetRealNamedProperty(context, key).ToLocal(&value)) { + (void)to->DefineOwnProperty(context, key, value, attributes); + } + continue; + } + Local descriptorValue; + if (!from->GetOwnPropertyDescriptor(context, key).ToLocal(&descriptorValue) || + !descriptorValue->IsObject()) { + continue; + } + Local descriptor = descriptorValue.As(); + PropertyDescriptor accessor(DescriptorField(isolate, context, descriptor, "get"), + DescriptorField(isolate, context, descriptor, "set")); + accessor.set_enumerable( + DescriptorField(isolate, context, descriptor, "enumerable")->BooleanValue(isolate)); + accessor.set_configurable( + DescriptorField(isolate, context, descriptor, "configurable")->BooleanValue(isolate)); + (void)to->DefineProperty(context, key, accessor); + } + } + copyingProperties_ = wasCopying; +} + // The state object of the holder, if it has one. bool ExistingState(Isolate* isolate, Local holder, Local* out) { ObjectWeakCallbackState* canary = CanaryOf(isolate, holder); @@ -381,6 +441,9 @@ 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; // A JS-extended class's own -dealloc reports its instances' deaths. bool extended = IsExtendedInstance(object); // Allocated before the lock: a collection this allocation starts can run @@ -432,6 +495,13 @@ bool StateForWrite(Isolate* isolate, Local holder, Local* out) { if (ObjectManager::LifetimeStats* stats = ObjectManager::GetLifetimeStats(isolate)) { stats->canaryStates++; } + if (replacesDied) { + CopyOwnProperties(isolate, isolate->GetCurrentContext(), holder, freshState); + } + } else if (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); } } if (!Usable(canary->canaryRecord_)) { @@ -445,123 +515,102 @@ bool HasOwn(Local context, Local state, Local propert return state->HasOwnProperty(context, property).FromMaybe(false); } -Intercepted Getter(Local property, const PropertyCallbackInfo& info) { - Isolate* isolate = info.GetIsolate(); - Local state; - if (!ExistingState(isolate, info.Holder(), &state)) { - return Intercepted::kNo; - } - Local context = isolate->GetCurrentContext(); - if (!HasOwn(context, state, property)) { - return Intercepted::kNo; - } - Local value; - // An accessor defined through the canary runs with the canary as `this` - // (interceptors do not see the receiver, only the holder). - if (state->Get(context, property, info.Holder()).ToLocal(&value)) { - info.GetReturnValue().Set(value); +// The object of `holder`'s prototype chain, `holder` included, with a real own +// `property`, interceptors skipped; empty if there is none. +Local OwnerOf(Local context, Local holder, Local property) { + Local object = holder; + while (!object->HasRealNamedProperty(context, property).FromMaybe(false)) { + Local prototype = object->GetPrototype(); + if (!prototype->IsObject()) { + return Local(); + } + object = prototype.As(); } - return Intercepted::kYes; + return object; } +// The handlers mirror: 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 +// names the prototype chain has. After the setter declines, V8 adds a new name +// to the canary without calling the definer, so the setter itself decides what +// becomes state. Intercepted Setter(Local property, Local value, const PropertyCallbackInfo& info) { Isolate* isolate = info.GetIsolate(); - Local state; - if (!StateForWrite(isolate, info.Holder(), &state)) { - return Intercepted::kNo; - } - Local context = isolate->GetCurrentContext(); - Maybe result = state->HasRealNamedCallbackProperty(context, property).FromMaybe(false) - ? state->Set(context, property, value, info.Holder()) - : state->Set(context, property, value); - if (result.IsJust()) { - info.GetReturnValue().Set(result.FromJust()); - } - return Intercepted::kYes; -} - -Intercepted Query(Local property, const PropertyCallbackInfo& info) { - Isolate* isolate = info.GetIsolate(); - Local state; - if (!ExistingState(isolate, info.Holder(), &state)) { - return Intercepted::kNo; + Local holder = info.Holder(); + ObjectWeakCallbackState* canary = CanaryOf(isolate, holder); + std::shared_ptr borrowed; + if (canary == nullptr) { + borrowed = BorrowedRecord(isolate, holder); + if (!Usable(borrowed)) { + return Intercepted::kNo; + } } + CanaryRecord* record = canary != nullptr ? canary->canaryRecord_.get() : borrowed.get(); Local context = isolate->GetCurrentContext(); - if (!HasOwn(context, state, property)) { - return Intercepted::kNo; + if (record != nullptr && !record->died.load(std::memory_order_acquire) && + !record->state.IsEmpty()) { + // Own on the state means own on the canary: a rewrite of a JS property. + Local state = Local::New(isolate, record->state); + if (HasOwn(context, state, property)) { + if (!state->HasRealNamedCallbackProperty(context, property).FromMaybe(true)) { + (void)state->Set(context, property, value); + } + return Intercepted::kNo; + } } + // Searches the prototype chain too: absent there means a new name. PropertyAttribute attributes; - if (state->GetPropertyAttributes(context, property).To(&attributes)) { - info.GetReturnValue().Set(v8::Integer::New(isolate, attributes)); + if (holder->GetRealNamedPropertyAttributes(context, property).To(&attributes)) { + // V8 rejects a write to a read-only property and runs an accessor's + // setter: a native property's (an accessor pair on its class's + // prototype), a JS one's, or one defined on the canary, which runs with + // the canary as `this` and so mirrors whatever it writes. None is state. + if ((attributes & ReadOnly) != 0) { + return Intercepted::kNo; + } + Local owner = OwnerOf(context, holder, property); + if (owner.IsEmpty() || owner->HasRealNamedCallbackProperty(context, property).FromMaybe(true)) { + return Intercepted::kNo; + } } - return Intercepted::kYes; -} - -Intercepted Deleter(Local property, const PropertyCallbackInfo& info) { - Isolate* isolate = info.GetIsolate(); Local state; - if (!ExistingState(isolate, info.Holder(), &state)) { + if (!StateForWrite(isolate, holder, &state)) { return Intercepted::kNo; } - Local context = isolate->GetCurrentContext(); if (!HasOwn(context, state, property)) { - return Intercepted::kNo; + (void)state->CreateDataProperty(context, property, value); + } else if (!state->HasRealNamedCallbackProperty(context, property).FromMaybe(true)) { + (void)state->Set(context, property, value); } - bool deleted; - if (state->Delete(context, property).To(&deleted)) { - info.GetReturnValue().Set(deleted); - } - return Intercepted::kYes; + return Intercepted::kNo; } -void Enumerator(const PropertyCallbackInfo& info) { +Intercepted Deleter(Local property, const PropertyCallbackInfo& info) { Isolate* isolate = info.GetIsolate(); Local state; - if (!ExistingState(isolate, info.Holder(), &state)) { - return; - } - Local context = isolate->GetCurrentContext(); - Local names; - if (state - ->GetPropertyNames(context, KeyCollectionMode::kOwnOnly, PropertyFilter::ALL_PROPERTIES, - IndexFilter::kSkipIndices) - .ToLocal(&names)) { - info.GetReturnValue().Set(names); + if (ExistingState(isolate, info.Holder(), &state)) { + (void)state->Delete(isolate->GetCurrentContext(), property); } + return Intercepted::kNo; } +// Object.defineProperty, define-semantics class fields and `super.x = v` on a +// receiver that lacks `x` reach here. Intercepted Definer(Local property, const PropertyDescriptor& descriptor, const PropertyCallbackInfo& info) { - Isolate* isolate = info.GetIsolate(); - Local state; - if (!StateForWrite(isolate, info.Holder(), &state)) { + if (copyingProperties_) { return Intercepted::kNo; } - Local context = isolate->GetCurrentContext(); - bool defined; - if (state->DefineProperty(context, property, const_cast(descriptor)) - .To(&defined)) { - info.GetReturnValue().Set(defined); - } - return Intercepted::kYes; -} - -Intercepted Descriptor(Local property, const PropertyCallbackInfo& info) { Isolate* isolate = info.GetIsolate(); Local state; - if (!ExistingState(isolate, info.Holder(), &state)) { - return Intercepted::kNo; - } - Local context = isolate->GetCurrentContext(); - if (!HasOwn(context, state, property)) { - return Intercepted::kNo; + if (StateForWrite(isolate, info.Holder(), &state)) { + (void)state->DefineProperty(isolate->GetCurrentContext(), property, + const_cast(descriptor)); } - Local descriptor; - if (state->GetOwnPropertyDescriptor(context, property).ToLocal(&descriptor)) { - info.GetReturnValue().Set(descriptor); - } - return Intercepted::kYes; + return Intercepted::kNo; } #if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_WEAK_SWEEP @@ -659,8 +708,24 @@ void PostSweepAfterGC(Isolate* isolate, GCType, GCCallbackFlags) { return; } instanceTemplate->SetHandler(NamedPropertyHandlerConfiguration( - Getter, Setter, Query, Deleter, Enumerator, Definer, Descriptor, Local(), - PropertyHandlerFlags::kNonMasking)); + nullptr, Setter, nullptr, Deleter, nullptr, Definer, nullptr, Local(), + PropertyHandlerFlags::kNone)); +} + +void WrapperLifetimeCanary::Hydrate(Isolate* isolate, Local wrapper) { + if (GetWrapperLifetimeMode() != WrapperLifetimeMode::kCanary) { + return; + } + HandleScope scope(isolate); + Local state; + if (!ExistingState(isolate, wrapper, &state)) { + return; + } + Local context = isolate->GetCurrentContext(); + if (context.IsEmpty()) { + context = Caches::Get(isolate)->GetContext(); + } + CopyOwnProperties(isolate, context, state, wrapper); } std::shared_ptr WrapperLifetimeCanary::Find(Isolate* isolate, id object) { diff --git a/TestRunner/app/tests/WrapperLifetimeModesTests.js b/TestRunner/app/tests/WrapperLifetimeModesTests.js index 93c9ce897..cc183d0e2 100644 --- a/TestRunner/app/tests/WrapperLifetimeModesTests.js +++ b/TestRunner/app/tests/WrapperLifetimeModesTests.js @@ -54,6 +54,40 @@ describe("Wrapper lifetime modes", function () { }, 10); } + // Hands what `make` returns to native code, drops every JS reference to + // it, and calls back with the object read back from native code: under + // canary mode on a new wrapper. + function rewrap(make, callback) { + var owner = NSMutableArray.new(); + var first; + (function () { + var obj = make(); + owner.addObject(obj); + first = new WeakRef(obj); + })(); + settle(2, function () { + if (canary) { + expect(first.deref()).toBeUndefined(); + } + callback(owner.objectAtIndex(0)); + }); + } + + function hasOwn(obj, name) { + return Object.prototype.hasOwnProperty.call(obj, name); + } + + var WithMethod = (function (_super) { + __extends(WithMethod, _super); + function WithMethod() { + return (_super !== null && _super.apply(this, arguments)) || this; + } + WithMethod.prototype.greet = function () { + return this.greeting || "greet"; + }; + return WithMethod; + })(TNSAllocLog); + beforeEach(function () { TNSClearOutput(); }); @@ -428,8 +462,8 @@ describe("Wrapper lifetime modes", function () { }); }); - // Own-property semantics hold whatever the mode: in canary mode the names - // live on the state object and the canary's interceptors present them. + // Own-property semantics hold whatever the mode: in canary mode every + // write also lands on the canary itself. it("keeps own-property semantics for JS properties on a native object", function () { var obj = Extended.new(); obj.a = 1; @@ -477,31 +511,239 @@ describe("Wrapper lifetime modes", function () { }); }); - // kNonMasking interceptors only see names the prototype chain lacks: a JS - // property shadowing a prototype member is defined on the wrapper itself, - // so in canary mode it goes with the wrapper. A documented limit. - it("keeps a JS property that shadows a prototype member only while its canary lives", function (done) { - var owner = NSMutableArray.new(); - (function () { - var obj = Extended.new(); + it("hands back a JS property that shadows a prototype member on a new wrapper", function (done) { + rewrap(function () { + var obj = WithMethod.new(); obj.isEqual = function () { return "shadow"; }; + // Bound to another object: one bound to `obj` would keep it alive. + obj.greet = obj.greet.bind({ greeting: "bound" }); obj.tag = "kept"; - owner.addObject(obj); - })(); - settle(2, function () { - var obj = owner.objectAtIndex(0); - if (canary) { + return obj; + }, function (obj) { + if (keepsState) { expect(obj.tag).toBe("kept"); - expect(obj.isEqual(obj)).toBe(true); - } else if (rooted) { expect(obj.isEqual(obj)).toBe("shadow"); + expect(obj.greet()).toBe("bound"); + expect(hasOwn(obj, "greet")).toBe(true); + } + done(); + }); + }); + + it("hands back a property defined over a prototype member on a new wrapper", function (done) { + rewrap(function () { + var obj = WithMethod.new(); + Object.defineProperty(obj, "isEqual", { + value: function () { + return "defined"; + }, + writable: true, + configurable: true + }); + expect(obj.isEqual(obj)).toBe("defined"); + return obj; + }, function (obj) { + if (keepsState) { + expect(obj.isEqual(obj)).toBe("defined"); + var descriptor = Object.getOwnPropertyDescriptor(obj, "isEqual"); + expect(descriptor.writable).toBe(true); + expect(descriptor.enumerable).toBe(false); + expect(descriptor.configurable).toBe(true); + expect(Object.keys(obj)).toEqual([]); + } + done(); + }); + }); + + it("restores the prototype member a deleted shadowing property hid", function (done) { + rewrap(function () { + var obj = WithMethod.new(); + obj.greet = function () { + return "shadow"; + }; + obj.tag = "kept"; + expect(delete obj.greet).toBe(true); + expect(obj.greet()).toBe("greet"); + return obj; + }, function (obj) { + expect(hasOwn(obj, "greet")).toBe(false); + expect(obj.greet()).toBe("greet"); + if (keepsState) { + expect(obj.tag).toBe("kept"); + } + done(); + }); + }); + + it("hands back an accessor defined on the instance, running it on the new wrapper", function (done) { + rewrap(function () { + var obj = Extended.new(); + Object.defineProperty(obj, "self", { + get: function () { + return this; + }, + set: function (value) { + this.written = value; + }, + configurable: true + }); + obj.self = 1; + return obj; + }, function (obj) { + if (keepsState) { + expect(obj.self).toBe(obj); + expect(obj.written).toBe(1); + obj.self = 2; + expect(obj.written).toBe(2); + var descriptor = Object.getOwnPropertyDescriptor(obj, "self"); + expect(typeof descriptor.get).toBe("function"); + expect(typeof descriptor.set).toBe("function"); + expect(descriptor.enumerable).toBe(false); + } + done(); + }); + }); + + it("hands back non-enumerable, read-only and symbol-keyed properties with their attributes", function (done) { + var key = Symbol("key"); + rewrap(function () { + var obj = Extended.new(); + obj.visible = 1; + Object.defineProperty(obj, "hidden", { value: 2, writable: true, configurable: true }); + Object.defineProperty(obj, "fixed", { value: 3, enumerable: true }); + obj[key] = 4; + return obj; + }, function (obj) { + if (keepsState) { + expect(Object.keys(obj)).toEqual(["visible", "fixed"]); + expect(Object.getOwnPropertyNames(obj).sort()).toEqual(["fixed", "hidden", "visible"]); + expect(obj[key]).toBe(4); + expect(Object.getOwnPropertyDescriptor(obj, "hidden")).toEqual({ + value: 2, writable: true, enumerable: false, configurable: true + }); + expect(Object.getOwnPropertyDescriptor(obj, "fixed")).toEqual({ + value: 3, writable: false, enumerable: true, configurable: false + }); + expect(delete obj.fixed).toBe(false); + } + done(); + }); + }); + + function strictAssignThrows(obj, name, value) { + "use strict"; + try { + obj[name] = value; + } catch (e) { + return e instanceof TypeError; + } + return false; + } + + function answerGot() { + return "got"; + } + + // A rejected write is rejected by the wrapper's own property, and the + // state keeps the old value. No closure here may capture the wrapper: the + // getter stored in the state would keep it alive. + it("rejects writes to read-only and getter-only properties", function (done) { + rewrap(function () { + var obj = Extended.new(); + Object.defineProperty(obj, "fixed", { value: 1, writable: false, configurable: true }); + Object.defineProperty(obj, "getterOnly", { get: answerGot, configurable: true }); + expect(Reflect.set(obj, "fixed", 2)).toBe(false); + expect(Reflect.set(obj, "getterOnly", 2)).toBe(false); + expect(strictAssignThrows(obj, "fixed", 2)).toBe(true); + expect(strictAssignThrows(obj, "getterOnly", 2)).toBe(true); + expect(obj.fixed).toBe(1); + return obj; + }, function (obj) { + if (keepsState) { + expect(obj.fixed).toBe(1); + expect(obj.getterOnly).toBe("got"); + expect(Reflect.set(obj, "fixed", 2)).toBe(false); + } + done(); + }); + }); + + it("runs the native setter of a native property written on a wrapper", function (done) { + var Host = (function (_super) { + __extends(Host, _super); + function Host() { + return (_super !== null && _super.apply(this, arguments)) || this; + } + return Host; + })(TNSAccessorHost); + rewrap(function () { + var obj = Host.new(); + var before = runtime.getWrapperLifetimeStats(); + obj.name = "native"; + expect(hasOwn(obj, "name")).toBe(false); + if (canary) { + // Not JS state: no state object was made for it. + expect(runtime.getWrapperLifetimeStats().canaryStates).toBe(before.canaryStates); + } + obj.tag = "state"; + obj.name = "native2"; + expect(hasOwn(obj, "name")).toBe(false); + return obj; + }, function (obj) { + expect(obj.name).toBe("native2"); + expect(hasOwn(obj, "name")).toBe(false); + if (keepsState) { + expect(obj.tag).toBe("state"); + } + done(); + }); + }); + + it("shadows a native property with a defined one until it is deleted", function (done) { + var Host = (function (_super) { + __extends(Host, _super); + function Host() { + return (_super !== null && _super.apply(this, arguments)) || this; + } + return Host; + })(TNSAccessorHost); + var nativeName = Object.getOwnPropertyDescriptor(TNSAccessorHost.prototype, "name").get; + rewrap(function () { + var obj = Host.new(); + obj.name = "native"; + Object.defineProperty(obj, "name", { value: "js", writable: true, configurable: true }); + obj.name = "js2"; + expect(nativeName.call(obj)).toBe("native"); + return obj; + }, function (obj) { + if (keepsState) { + expect(hasOwn(obj, "name")).toBe(true); + expect(obj.name).toBe("js2"); } + expect(nativeName.call(obj)).toBe("native"); + delete obj.name; + expect(hasOwn(obj, "name")).toBe(false); + expect(obj.name).toBe("native"); + obj.name = "native3"; + expect(hasOwn(obj, "name")).toBe(false); + expect(nativeName.call(obj)).toBe("native3"); done(); }); }); + // Interceptors see only writes made through the wrapper itself. + it("keeps a write through an object inheriting from a wrapper on that object", function () { + var obj = Extended.new(); + var derived = Object.create(obj); + derived.tag = "derived"; + Object.defineProperty(derived, "defined", { value: 1, configurable: true }); + expect(hasOwn(derived, "tag")).toBe(true); + expect("tag" in obj).toBe(false); + expect("defined" in obj).toBe(false); + }); + // A JS-implemented dealloc replaces the class's own death hook, so it // reports the death itself, after the JS method ran. it("lets the JS state go when a JS-implemented dealloc ran", function (done) { @@ -644,19 +886,30 @@ describe("Wrapper lifetime modes", function () { }); // Third-party code can strip a live object's associations. Where an - // associated token reports native death, the state goes with it; where a - // weak-reference sweep does, nothing changes. - it("survives a live object's associations being removed", function () { + // associated token reports native death, the record goes with it, and the + // next write seeds a new state from the canary's own properties. + it("survives a live object's associations being removed", function (done) { if (typeof objc_removeAssociatedObjects !== "function") { + done(); return; } - // Only objects outside JS-extended classes carry the token. - var obj = scope === "all" ? TNSAllocLog.new() : Extended.new(); - obj.tag = "first"; - objc_removeAssociatedObjects(obj); - expect([undefined, "first"]).toContain(obj.tag); - obj.tag = "second"; - expect(obj.tag).toBe("second"); + rewrap(function () { + // Only objects outside JS-extended classes carry the token. + var obj = scope === "all" ? TNSAllocLog.new() : Extended.new(); + obj.tag = "first"; + obj.other = "kept"; + objc_removeAssociatedObjects(obj); + expect(obj.tag).toBe("first"); + obj.tag = "second"; + expect(obj.tag).toBe("second"); + return obj; + }, function (obj) { + if (keepsState) { + expect(obj.tag).toBe("second"); + expect(obj.other).toBe("kept"); + } + done(); + }); }); // V8 refuses to freeze, seal or prevent extensions on an object with @@ -668,5 +921,43 @@ describe("Wrapper lifetime modes", function () { expect(function () { Object.freeze(Extended.new()); }).toThrowError(TypeError); + expect(function () { + Object.seal(Extended.new()); + }).toThrowError(TypeError); + expect(function () { + Object.preventExtensions(Extended.new()); + }).toThrowError(TypeError); + }); + + // Named interceptors see neither index keys nor private names: both live + // on the canary only. + it("drops index-keyed properties and #private brands with a canary", function (done) { + var Stamp = (function () { + var Base = function (target) { + return target; + }; + return class extends Base { + #brand = 1; + static has(o) { + return #brand in o; + } + }; + })(); + rewrap(function () { + var obj = Extended.new(); + obj[0] = "index"; + obj.tag = "kept"; + new Stamp(obj); + expect(obj[0]).toBe("index"); + expect(Stamp.has(obj)).toBe(true); + return obj; + }, function (obj) { + if (canary) { + expect(obj.tag).toBe("kept"); + expect(obj[0]).toBeUndefined(); + expect(Stamp.has(obj)).toBe(false); + } + done(); + }); }); }); diff --git a/docs/knowledge/v8-resurrecting-finalizers.md b/docs/knowledge/v8-resurrecting-finalizers.md index 0cef64e47..551004c29 100644 --- a/docs/knowledge/v8-resurrecting-finalizers.md +++ b/docs/knowledge/v8-resurrecting-finalizers.md @@ -260,13 +260,32 @@ native code owns are lost without a warning. `"mode": "canary"` (`WrapperLifetimeCanary.{h,mm}`) is the portable variant, the shape Android and the Node-API runtimes can implement. A wrapper in scope is a canary: a phantom-weak JS object that dies with its JS references, releasing the runtime's retain through the same queue. -`kNonMasking` named interceptors on the instance templates forward JS properties to a -null-prototype state object, so prototype members never reach them. The state is rooted from -its first write until the native object is deallocated; a canary built later for the same -object forwards to the same state. Instances of JS-extended classes report their own -deallocation: the runtime gives each extended class a `-dealloc` that tells every isolate's -registry, then calls the superclass's. For other objects it is a compile-time choice -(`NS_CANARY_DEATH_SIGNAL` in `WrapperLifetimeCanary.mm`): by default a token associated with the +A masking named interceptor on the instance templates, with only a setter, a deleter and a +definer, mirrors JS properties into a null-prototype state object: each callback copies the +write into the state and declines, so V8 also applies it to the canary. Reads find real own +properties on the canary and never call into C++, so they cost what they cost on a plain +object. Being masking, the callbacks also see names the prototype chain has (a class method +rebound with `this.onTap = this.onTap.bind(this)`, a field called `copy`, any +`Object.defineProperty` over a prototype name), and those are state like any other. The +setter classifies the prototype chain itself, because once it declines V8 adds a new name +to the canary without calling the definer: a name that resolves to an inherited accessor (a +native property, a JS getter/setter) or a read-only data member is left to V8 and never +becomes state, so native setters run as before. The state is rooted from its first write +until the native object is deallocated, and stays the source of truth: a canary built later +for the same object, or the receiver a JS-implemented `-dealloc` runs with, gets the state's +properties copied onto it with their attributes and accessors. The costs, measured on a +Release simulator build: the handler is installed per template, so every write to any ObjC +wrapper goes through the setter, and V8 looks the name up again after it declines. Under +`"extended"`, a plain wrapper's expando write takes about 64 ns instead of 17 and a native +property store about 200 ns instead of 120. On a canary, where the setter also classifies the +name, an expando write takes about 100 ns and a native property store about 310 ns instead of +125 (380 instead of 115 four prototypes up). Building a canary for an object with state costs +about 330 ns per state property. 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 +a compile-time choice (`NS_CANARY_DEATH_SIGNAL` in `WrapperLifetimeCanary.mm`): by default a +token associated with the object reports it from its `-dealloc`, immediately and on any thread, but the ObjC runtime aborts the process for a class that forbids associated objects, and there is no public query for that; the alternative keeps an ObjC weak reference in each record (`objc_initWeakOrNil`, which declines @@ -280,15 +299,13 @@ canary lives at a time, and anything still referencing the old one would have ke What does notice is whatever keys on the canary without keeping it: `WeakMap` keys and `WeakRef`s of the old canary, and native `#private` fields, which are branded on it. Other limits: `Object.freeze`, `seal` and `preventExtensions` throw on a canary (V8 refuses them on -objects with interceptors); index-keyed properties are not forwarded and die with the canary; -so does a property named like anything on the prototype chain (a class method rebound with -`this.onTap = this.onTap.bind(this)`, a field called `copy` or `toString`, any -`Object.defineProperty` or define-semantics class field over such a name): a `kNonMasking` -interceptor is skipped for a name the chain has, so V8 defines it on the canary itself; -a write through an object whose prototype is a canary lands in the canary's state, since -interceptors see the holder but not the receiver. Relies on -V8's own-property lookup through `kNonMasking` interceptors when the prototype has a named -interceptor (`v8_nonmasking_own_lookup.patch` in v8-buildscripts, crbug 585053531). +objects with interceptors); index-keyed properties are not mirrored and die with the canary; +a write through an object whose prototype is a canary lands on that object, since +interceptors only see writes made through their own object. Class fields need the V8 fixes +in v8-buildscripts#13: before them, define-semantics fields reach the definer with inverted +attributes (the state keeps them read-only, hidden and undeletable) and, once their +initializer is warm, bypass it entirely (the field stays on the canary and is gone after a +replacement); `v8::Object::CreateDataProperty` bypasses it the same way. Two facts worth knowing when reasoning about which objects can husk: diff --git a/types/ns-runtime.d.ts b/types/ns-runtime.d.ts index 324beb786..42b1db854 100644 --- a/types/ns-runtime.d.ts +++ b/types/ns-runtime.d.ts @@ -52,12 +52,14 @@ declare module "ns:runtime" { * weak otherwise; native objects of collected wrappers are released on * the runtime's thread. * - `"canary"`: no resurrection. A wrapper in scope dies with its JS - * references; JS properties set on it live on a state object kept until - * the native object is deallocated, and a wrapper built for the object - * later has them again. Weak references to the old wrapper (WeakMap keys, - * WeakRef), native `#private` fields, index-keyed properties and - * properties named like a member of the prototype chain (a rebound class - * method, a field called `copy`) do not carry over. + * references; JS properties set on it, including ones that shadow a + * prototype member (a rebound class method, a field called `copy`), are + * also copied to a state object kept until the native object is + * deallocated, and a wrapper built for the object later gets them back + * with their attributes. Native property writes still reach the native + * setter. Writes cost more than in the other modes; reads do not. Weak + * references to the old wrapper (WeakMap keys, WeakRef), native + * `#private` fields and index-keyed properties do not carry over. * State that references its own object keeps that object alive. */ wrapperLifetimeMode: "resurrecting" | "rooted" | "canary"; From 9ba25ba709105d512a05e9b21a60f5cca9a25c67 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 17 Nov 2026 03:53:14 -0300 Subject: [PATCH 11/24] style(runtime): clang-format --- NativeScript/runtime/ArgConverter.mm | 2 +- NativeScript/runtime/ClassBuilder.mm | 12 ++++++------ NativeScript/runtime/SymbolIterator.mm | 5 ++--- NativeScript/runtime/WrapperLifetimeCanary.h | 5 ++++- NativeScript/runtime/WrapperLifetimeCanary.mm | 16 ++++++++-------- 5 files changed, 21 insertions(+), 19 deletions(-) diff --git a/NativeScript/runtime/ArgConverter.mm b/NativeScript/runtime/ArgConverter.mm index 944b2e89d..0917d5b0f 100644 --- a/NativeScript/runtime/ArgConverter.mm +++ b/NativeScript/runtime/ArgConverter.mm @@ -11,9 +11,9 @@ #include "NSExceptionSupport.h" #include "NativeScriptException.h" #include "ObjectManager.h" -#include "WrapperLifetime.h" #include "Runtime.h" #include "RuntimeConfig.h" +#include "WrapperLifetime.h" #include "WrapperLifetimeCanary.h" using namespace v8; diff --git a/NativeScript/runtime/ClassBuilder.mm b/NativeScript/runtime/ClassBuilder.mm index af78aacb0..0c652e928 100644 --- a/NativeScript/runtime/ClassBuilder.mm +++ b/NativeScript/runtime/ClassBuilder.mm @@ -1,5 +1,4 @@ #include "ClassBuilder.h" -#include "WrapperLifetime.h" #include #include #include @@ -14,6 +13,7 @@ #include "ObjectManager.h" #include "Runtime.h" #include "TNSDerivedClass.h" +#include "WrapperLifetime.h" #include "WrapperLifetimeCanary.h" using namespace v8; @@ -324,11 +324,11 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { /// 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. + /// 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) { diff --git a/NativeScript/runtime/SymbolIterator.mm b/NativeScript/runtime/SymbolIterator.mm index a4c85c203..72477f605 100644 --- a/NativeScript/runtime/SymbolIterator.mm +++ b/NativeScript/runtime/SymbolIterator.mm @@ -15,9 +15,8 @@ // property lives on the object's state there, which a reference back to the // object would keep alive until native death. Elsewhere it keeps `object`, so // an unbound call still iterates it. - Local captured = GetWrapperLifetimeMode() == WrapperLifetimeMode::kCanary - ? Local() - : object; + Local captured = + GetWrapperLifetimeMode() == WrapperLifetimeMode::kCanary ? Local() : object; Local iterator; bool success = v8::Function::New( context, diff --git a/NativeScript/runtime/WrapperLifetimeCanary.h b/NativeScript/runtime/WrapperLifetimeCanary.h index da343a422..8eeec8e18 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.h +++ b/NativeScript/runtime/WrapperLifetimeCanary.h @@ -2,7 +2,9 @@ #define WrapperLifetimeCanary_h #include + #include + #include "Common.h" namespace tns { @@ -54,7 +56,8 @@ class WrapperLifetimeCanary { // Installs the forwarding handlers on an ObjC instance template. No-op unless // the mode is canary. - static void ConfigureInstanceTemplate(v8::Local instanceTemplate); + static void ConfigureInstanceTemplate( + v8::Local instanceTemplate); // The record of an object that already has state in this isolate, for a new // canary to share. Null otherwise. diff --git a/NativeScript/runtime/WrapperLifetimeCanary.mm b/NativeScript/runtime/WrapperLifetimeCanary.mm index a38b139f5..f3dfb1d3b 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.mm +++ b/NativeScript/runtime/WrapperLifetimeCanary.mm @@ -351,8 +351,8 @@ void PostDrain(const std::shared_ptr& registry) { return nullptr; } std::lock_guard lock(state->registry->mutex); - auto it = state->registry->records.find( - (__bridge void*)static_cast(wrapper)->Data()); + auto it = + state->registry->records.find((__bridge void*)static_cast(wrapper)->Data()); return it != state->registry->records.end() ? it->second : nullptr; } @@ -435,7 +435,8 @@ bool StateForWrite(Isolate* isolate, Local holder, Local* out) { // A -dealloc receiver writes to its object's existing state only. return ExistingState(isolate, holder, out); } - if (canary->canaryRecord_ == nullptr || canary->canaryRecord_->died.load(std::memory_order_acquire)) { + if (canary->canaryRecord_ == nullptr || + canary->canaryRecord_->died.load(std::memory_order_acquire)) { std::shared_ptr registry = RegistryFor(isolate); if (registry == nullptr) { return false; @@ -691,8 +692,7 @@ void PostSweepAfterGC(Isolate* isolate, GCType, GCCallbackFlags) { } IMP WrapperLifetimeCanary::WrapDealloc(SEL selector, IMP imp) { - if (selector != @selector(dealloc) || - GetWrapperLifetimeMode() != WrapperLifetimeMode::kCanary) { + if (selector != @selector(dealloc) || GetWrapperLifetimeMode() != WrapperLifetimeMode::kCanary) { return imp; } return imp_implementationWithBlock(^(id self) { @@ -707,9 +707,9 @@ void PostSweepAfterGC(Isolate* isolate, GCType, GCCallbackFlags) { if (GetWrapperLifetimeMode() != WrapperLifetimeMode::kCanary) { return; } - instanceTemplate->SetHandler(NamedPropertyHandlerConfiguration( - nullptr, Setter, nullptr, Deleter, nullptr, Definer, nullptr, Local(), - PropertyHandlerFlags::kNone)); + instanceTemplate->SetHandler( + NamedPropertyHandlerConfiguration(nullptr, Setter, nullptr, Deleter, nullptr, Definer, + nullptr, Local(), PropertyHandlerFlags::kNone)); } void WrapperLifetimeCanary::Hydrate(Isolate* isolate, Local wrapper) { From 79f179ae8dc932b763c421a1a6f6170346c2c676 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 17 Nov 2026 10:22:51 -0300 Subject: [PATCH 12/24] perf(runtime): keep canary hydration out of the write handler v8::Object::DefineOwnProperty, which Hydrate uses to copy a state's properties onto a new canary, reaches the named setter interceptor rather than the definer. The setter then looked each copied name up on the state and wrote it back unchanged. It now declines straight away while properties are being copied, as the definer already did. Re-reading a natively owned object with 4 JS properties after its canary was collected: about 2190 -> 1890 ns (Release simulator). --- NativeScript/runtime/WrapperLifetimeCanary.mm | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/NativeScript/runtime/WrapperLifetimeCanary.mm b/NativeScript/runtime/WrapperLifetimeCanary.mm index f3dfb1d3b..ad358497d 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.mm +++ b/NativeScript/runtime/WrapperLifetimeCanary.mm @@ -357,7 +357,7 @@ void PostDrain(const std::shared_ptr& registry) { } // Set while this thread copies properties between a canary and its state, so -// the canary's definer lets those defines through. Per thread rather than per +// the canary's handlers let those defines through. Per thread rather than per // isolate: the copy runs no JS, so only its own defines reach an interceptor // on this thread meanwhile. thread_local bool copyingProperties_ = false; @@ -539,6 +539,10 @@ bool HasOwn(Local context, Local state, Local propert // becomes state. Intercepted Setter(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(); ObjectWeakCallbackState* canary = CanaryOf(isolate, holder); From d04160ef4cef7fe8b4d9c15c8a876c38d29428ef Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 17 Nov 2026 10:24:00 -0300 Subject: [PATCH 13/24] perf(runtime): give only canaries the canary write handlers Every ObjC instance template carried the canary handlers, so under scope "extended" a plain wrapper paid the masking setter on every write while never being a canary. Wrappers now carry them only when they are canaries (WrapperLifetimeCanary::Intercepts, the scope test Adopt uses): - Objects wrapped from native code (returns, callback receivers, the -dealloc receiver) come from one of two empty-instance constructors, chosen by their object. The alloc wrapper and `super` objects never carry them. - Native class constructors carry them only under scope "all". Under "extended", a native constructor that yields an instance of a JS-extended class (adopted from a pointer, or returned by its initializer) returns a new object with the handlers and `this`'s prototype in place of `this`. - JS-extended class constructors keep them. Adopt asserts that a canary carries the handlers, and getWrapperLifetimeStats() reports the writes the handler saw (canaryInterceptedWrites). Release simulator, canary/extended, median ns: - plain native property write: 200 -> 125 (resurrecting: 122) - plain UIButton native property write: 223 -> 112 (resurrecting: 113) - plain expando write: 64 -> 18 (resurrecting: 16) --- NativeScript/runtime/ArgConverter.h | 17 +++- NativeScript/runtime/ArgConverter.mm | 80 ++++++++++++--- NativeScript/runtime/ClassBuilder.mm | 2 +- NativeScript/runtime/MetadataBuilder.mm | 7 +- NativeScript/runtime/NsBuiltinModules.cpp | 1 + NativeScript/runtime/ObjectManager.h | 7 +- NativeScript/runtime/WrapperLifetime.h | 9 +- NativeScript/runtime/WrapperLifetime.mm | 9 +- NativeScript/runtime/WrapperLifetimeCanary.h | 14 ++- NativeScript/runtime/WrapperLifetimeCanary.mm | 13 +++ .../app/tests/WrapperLifetimeModesTests.js | 99 +++++++++++++++++++ TestRunner/app/tests/WrapperLifetimeTests.js | 1 + docs/ns-builtin-modules.md | 1 + types/ns-runtime.d.ts | 2 + 14 files changed, 239 insertions(+), 23 deletions(-) diff --git a/NativeScript/runtime/ArgConverter.h b/NativeScript/runtime/ArgConverter.h index b5cedbe71..30b2e7c72 100644 --- a/NativeScript/runtime/ArgConverter.h +++ b/NativeScript/runtime/ArgConverter.h @@ -64,8 +64,14 @@ class ArgConverter { v8::Local receiver, const std::vector& additionalProtocols = std::vector()); + // `intercepted`: the object carries the canary handlers + // (WrapperLifetimeCanary::Intercepts). static std::shared_ptr> CreateEmptyObject( - v8::Local context); + v8::Local context, bool intercepted); + // The constructor NewEmptyInstance takes: EmptyObjCtorFunc, or with + // `intercepted` its counterpart carrying the canary handlers. + static v8::Persistent* EmptyInstanceFunction( + v8::Isolate* isolate, bool intercepted); // CreateEmptyObject's object without the ObjectManager registration, for an // object whose collection has nothing to dispose. static v8::Local NewEmptyInstance( @@ -132,14 +138,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`. static void ConstructObject(v8::Local context, const v8::FunctionCallbackInfo& info, - Class klass, - const InterfaceMeta* interfaceMeta = nullptr); + Class klass, const InterfaceMeta* interfaceMeta, + bool thisIntercepts); private: static v8::Local CreateEmptyInstanceFunction( - v8::Local context); + v8::Local context, bool intercepted); 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 0917d5b0f..c60aff170 100644 --- a/NativeScript/runtime/ArgConverter.mm +++ b/NativeScript/runtime/ArgConverter.mm @@ -57,6 +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. +struct CanaryWrapperConstructors { + // 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; +}; + } // namespace NativeCallbackSelf::NativeCallbackSelf(Local context, id self) @@ -89,7 +98,32 @@ 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)); + isolate, ArgConverter::CreateEmptyInstanceFunction(context, false)); + if (GetWrapperLifetimeMode() != WrapperLifetimeMode::kCanary) { + return; + } + CanaryWrapperConstructors* canary = Caches::StateFor(isolate); + 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); +} + +Persistent* ArgConverter::EmptyInstanceFunction(Isolate* isolate, bool intercepted) { + if (intercepted) { + CanaryWrapperConstructors* canary = Caches::StateFor(isolate); + tns::Assert(canary != nullptr && canary->emptyInstance != nullptr, isolate); + return canary->emptyInstance.get(); + } + return Caches::Get(isolate)->EmptyObjCtorFunc.get(); } Local ArgConverter::Invoke(Local context, Class klass, Local receiver, @@ -703,7 +737,8 @@ bool IsKVOSubclassOf(Class klass, Class base) { } void ArgConverter::ConstructObject(Local context, const FunctionCallbackInfo& info, - Class klass, const InterfaceMeta* interfaceMeta) { + Class klass, const InterfaceMeta* interfaceMeta, + bool thisIntercepts) { Isolate* isolate = v8::Isolate::GetCurrent(); tns::Assert(klass != nullptr, isolate); WrapperLifetime::DrainAtCallEntry(isolate); @@ -767,6 +802,21 @@ 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(). + CanaryWrapperConstructors* canary = Caches::StateFor(isolate); + tns::Assert(canary != nullptr && canary->constructedInstance != nullptr, isolate); + Local replacement = NewEmptyInstance(context, canary->constructedInstance.get()); + bool success; + if (!replacement->SetPrototype(context, thiz->GetPrototype()).To(&success) || !success) { + tns::Assert(false, isolate); + } + thiz = replacement; + info.GetReturnValue().Set(thiz); + intercepted = true; + } tns::SetValue(isolate, thiz, wrapper); std::shared_ptr> poThiz = ObjectManager::Register(context, thiz); cache->Instances.emplace(result, poThiz); @@ -784,7 +834,7 @@ bool IsKVOSubclassOf(Class klass, Class base) { wrapper->SetBornOnRuntimeThread(); ObjectManager::ProtectIfNativelyRetained(isolate, result, wrapper); } - WrapperLifetime::Adopt(isolate, wrapper, poThiz, result); + WrapperLifetime::Adopt(isolate, wrapper, poThiz, result, intercepted); ExternalMemory::ChargeEstimatedSize(isolate, thiz); } } @@ -1005,7 +1055,7 @@ bool IsKVOSubclassOf(Class klass, Class base) { ObjCAllocDataWrapper* allocDataWrapper = static_cast(wrapper); Class klass = allocDataWrapper->Klass(); - std::shared_ptr> poValue = CreateEmptyObject(context); + std::shared_ptr> poValue = CreateEmptyObject(context, false); receiver = poValue->Get(isolate).As(); const Meta* meta = FindMeta(klass); @@ -1055,7 +1105,8 @@ bool IsKVOSubclassOf(Class klass, Class base) { receiver = it->second->Get(isolate).As(); WrapperLifetime::EscapeValue(isolate, receiver); } else { - std::shared_ptr> poValue = CreateEmptyObject(context); + bool intercepted = WrapperLifetimeCanary::Intercepts(target); + std::shared_ptr> poValue = CreateEmptyObject(context, intercepted); receiver = poValue->Get(isolate).As(); tns::SetValue(isolate, receiver, wrapper); cache->Instances.emplace(target, poValue); @@ -1069,7 +1120,8 @@ bool IsKVOSubclassOf(Class klass, Class base) { ObjectManager::ProtectIfNativelyRetained(isolate, target, objcWrapper); } if (wrapper->Type() == WrapperType::ObjCObject) { - WrapperLifetime::Adopt(isolate, static_cast(wrapper), poValue, target); + WrapperLifetime::Adopt(isolate, static_cast(wrapper), poValue, target, + intercepted); } } } else { @@ -1276,7 +1328,9 @@ bool IsKVOSubclassOf(Class klass, Class base) { // Called from -dealloc: a retain cannot keep the object alive, so the // wrapper is neither cached nor owning, and the caller detaches it. wrapper->MarkBorrowed(); - Local receiver = NewEmptyInstance(context, cache->EmptyObjCtorFunc.get()); + // Its writes reach the object's JS state through the canary handlers. + Local receiver = NewEmptyInstance( + context, EmptyInstanceFunction(isolate, WrapperLifetimeCanary::Intercepts(self))); CreateJsWrapper(context, wrapper, receiver); WrapperLifetimeCanary::Hydrate(isolate, receiver); *borrowed = wrapper; @@ -1305,9 +1359,10 @@ bool IsKVOSubclassOf(Class klass, Class base) { return result; } -std::shared_ptr> ArgConverter::CreateEmptyObject(Local context) { +std::shared_ptr> ArgConverter::CreateEmptyObject(Local context, + bool intercepted) { Isolate* isolate = v8::Isolate::GetCurrent(); - Persistent* ctorFunc = Caches::Get(isolate)->EmptyObjCtorFunc.get(); + Persistent* ctorFunc = EmptyInstanceFunction(isolate, intercepted); tns::Assert(ctorFunc != nullptr, isolate); return ArgConverter::CreateEmptyInstance(context, ctorFunc); } @@ -1330,7 +1385,8 @@ bool IsKVOSubclassOf(Class klass, Class base) { return ObjectManager::Register(context, result); } -Local ArgConverter::CreateEmptyInstanceFunction(Local context) { +Local ArgConverter::CreateEmptyInstanceFunction(Local context, + bool intercepted) { Isolate* isolate = v8::Isolate::GetCurrent(); Local emptyInstanceCtorFuncTemplate = FunctionTemplate::New(isolate, nullptr); Local instanceTemplate = emptyInstanceCtorFuncTemplate->InstanceTemplate(); @@ -1338,7 +1394,9 @@ bool IsKVOSubclassOf(Class klass, Class base) { instanceTemplate->SetHandler(IndexedPropertyHandlerConfiguration(IndexedPropertyGetterCallback, IndexedPropertySetterCallback)); - WrapperLifetimeCanary::ConfigureInstanceTemplate(instanceTemplate); + if (intercepted) { + WrapperLifetimeCanary::ConfigureInstanceTemplate(instanceTemplate); + } Local emptyInstanceCtorFunc; if (!emptyInstanceCtorFuncTemplate->GetFunction(context).ToLocal(&emptyInstanceCtorFunc)) { diff --git a/NativeScript/runtime/ClassBuilder.mm b/NativeScript/runtime/ClassBuilder.mm index 0c652e928..411a24d95 100644 --- a/NativeScript/runtime/ClassBuilder.mm +++ b/NativeScript/runtime/ClassBuilder.mm @@ -179,7 +179,7 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { info.Data().As()->Value(v8::kExternalPointerTypeTagDefault)); Class klass = item->data_; - ArgConverter::ConstructObject(context, info, klass); + ArgConverter::ConstructObject(context, info, klass, nullptr, true); } catch (NativeScriptException& ex) { ex.ReThrowToV8(isolate); } diff --git a/NativeScript/runtime/MetadataBuilder.mm b/NativeScript/runtime/MetadataBuilder.mm index 5f96d152f..724e5501b 100644 --- a/NativeScript/runtime/MetadataBuilder.mm +++ b/NativeScript/runtime/MetadataBuilder.mm @@ -558,7 +558,9 @@ throw NativeScriptException( ctorFuncTemplate = FunctionTemplate::New(isolate, ClassConstructorCallback, ext); ctorFuncTemplate->InstanceTemplate()->SetInternalFieldCount(1); - WrapperLifetimeCanary::ConfigureInstanceTemplate(ctorFuncTemplate->InstanceTemplate()); + if (WrapperLifetimeCanary::NativeInstancesIntercept()) { + WrapperLifetimeCanary::ConfigureInstanceTemplate(ctorFuncTemplate->InstanceTemplate()); + } ctorFuncTemplate->SetClassName(tns::ToV8String(isolate, meta->name())); Local baseCtorFunc; @@ -1078,7 +1080,8 @@ void CollectInstanceMemberNames(const BaseClassMeta* meta, Class klass, bool own Class klass = objc_getClass(item->meta_->name()); const InterfaceMeta* interfaceMeta = static_cast(item->meta_); - ArgConverter::ConstructObject(context, info, klass, interfaceMeta); + ArgConverter::ConstructObject(context, info, klass, interfaceMeta, + WrapperLifetimeCanary::NativeInstancesIntercept()); } catch (NativeScriptException& ex) { ex.ReThrowToV8(isolate); } diff --git a/NativeScript/runtime/NsBuiltinModules.cpp b/NativeScript/runtime/NsBuiltinModules.cpp index 48f698345..4c7e4fb2a 100644 --- a/NativeScript/runtime/NsBuiltinModules.cpp +++ b/NativeScript/runtime/NsBuiltinModules.cpp @@ -252,6 +252,7 @@ void GetWrapperLifetimeStatsCallback(const FunctionCallbackInfo& info) { {"queuedReleases", stats->queuedReleases}, {"canaryStates", stats->canaryStates}, {"canaryNativeDeaths", stats->canaryNativeDeaths}, + {"canaryInterceptedWrites", stats->canaryInterceptedWrites}, }; for (const auto& [name, value] : fields) { result diff --git a/NativeScript/runtime/ObjectManager.h b/NativeScript/runtime/ObjectManager.h index 7e8a93c9c..beadf1186 100644 --- a/NativeScript/runtime/ObjectManager.h +++ b/NativeScript/runtime/ObjectManager.h @@ -68,8 +68,9 @@ struct ObjectWeakCallbackState { class ObjectManager { public: // Per-isolate wrapper lifetime counters. Kept in every build: plain integers - // bumped only on cold paths (finalizers, released-object reports), exposed - // through ns:runtime's getWrapperLifetimeStats(). + // bumped on cold paths (finalizers, released-object reports) and by canary + // mode's write interceptor, exposed through ns:runtime's + // getWrapperLifetimeStats(). struct LifetimeStats { // An ObjC wrapper's finalizer refused disposal because native code still // retains its object (IsGcProtected), keeping the wrapper alive. @@ -95,6 +96,8 @@ class ObjectManager { // objects let go of because their native object was deallocated. uint64_t canaryStates = 0; uint64_t canaryNativeDeaths = 0; + // Canary mode: writes the canary handlers saw. + uint64_t canaryInterceptedWrites = 0; }; static LifetimeStats* GetLifetimeStats(v8::Isolate* isolate); diff --git a/NativeScript/runtime/WrapperLifetime.h b/NativeScript/runtime/WrapperLifetime.h index fe18ddb56..b92bea1a3 100644 --- a/NativeScript/runtime/WrapperLifetime.h +++ b/NativeScript/runtime/WrapperLifetime.h @@ -58,11 +58,18 @@ class WrapperLifetime { public: static void Init(v8::Isolate* isolate); + // Whether `obj`'s wrapper is rooted (rooted mode) or a canary (canary mode): + // not a tagged pointer or a block, and under scope "extended" an instance + // of a JS-extended class. + static bool InScope(id obj); + // 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). static void Adopt(v8::Isolate* isolate, ObjCDataWrapper* wrapper, const std::shared_ptr>& handle, - id target); + id target, bool intercepted); // 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 7df522c85..7c0f833f9 100644 --- a/NativeScript/runtime/WrapperLifetime.mm +++ b/NativeScript/runtime/WrapperLifetime.mm @@ -119,6 +119,8 @@ void DropRuntimeRetain(id obj, std::atomic* counter) { } } +// Not a message: it runs on objects in -dealloc, where a JS-implemented one +// would re-enter JS for the same object. bool IsBlock(id obj) { static Class blockClass = objc_getClass("NSBlock"); for (Class cls = object_getClass(obj); cls != nil; cls = class_getSuperclass(cls)) { @@ -325,8 +327,11 @@ void ReleaseAll(Isolate* isolate, RootedState* rooted) { PrologueCallback, static_cast(kGCTypeMarkSweepCompact | kGCTypeIncrementalMarking)); } +bool WrapperLifetime::InScope(id obj) { return IsInScope(obj); } + void WrapperLifetime::Adopt(Isolate* isolate, ObjCDataWrapper* wrapper, - const std::shared_ptr>& handle, id target) { + const std::shared_ptr>& handle, id target, + bool intercepted) { if (GetWrapperLifetimeMode() == WrapperLifetimeMode::kResurrecting || target == nil) { return; } @@ -347,6 +352,8 @@ 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); 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 8eeec8e18..d41f3191e 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.h +++ b/NativeScript/runtime/WrapperLifetimeCanary.h @@ -55,10 +55,22 @@ class WrapperLifetimeCanary { static IMP WrapDealloc(SEL selector, IMP imp); // Installs the forwarding handlers on an ObjC instance template. No-op unless - // the mode is canary. + // 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(); + // The record of an object that already has state in this isolate, for a new // canary to share. Null otherwise. static std::shared_ptr Find(v8::Isolate* isolate, id object); diff --git a/NativeScript/runtime/WrapperLifetimeCanary.mm b/NativeScript/runtime/WrapperLifetimeCanary.mm index ad358497d..3110358dc 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.mm +++ b/NativeScript/runtime/WrapperLifetimeCanary.mm @@ -553,6 +553,9 @@ Intercepted Setter(Local property, Local value, return Intercepted::kNo; } } + if (ObjectManager::LifetimeStats* stats = ObjectManager::GetLifetimeStats(isolate)) { + stats->canaryInterceptedWrites++; + } CanaryRecord* record = canary != nullptr ? canary->canaryRecord_.get() : borrowed.get(); Local context = isolate->GetCurrentContext(); if (record != nullptr && !record->died.load(std::memory_order_acquire) && @@ -716,6 +719,16 @@ void PostSweepAfterGC(Isolate* isolate, GCType, GCCallbackFlags) { nullptr, Local(), PropertyHandlerFlags::kNone)); } +bool WrapperLifetimeCanary::Intercepts(id object) { + return GetWrapperLifetimeMode() == WrapperLifetimeMode::kCanary && + WrapperLifetime::InScope(object); +} + +bool WrapperLifetimeCanary::NativeInstancesIntercept() { + return GetWrapperLifetimeMode() == WrapperLifetimeMode::kCanary && + GetWrapperLifetimeScope() == WrapperLifetimeScope::kAll; +} + void WrapperLifetimeCanary::Hydrate(Isolate* isolate, Local wrapper) { if (GetWrapperLifetimeMode() != WrapperLifetimeMode::kCanary) { return; diff --git a/TestRunner/app/tests/WrapperLifetimeModesTests.js b/TestRunner/app/tests/WrapperLifetimeModesTests.js index cc183d0e2..21b81575e 100644 --- a/TestRunner/app/tests/WrapperLifetimeModesTests.js +++ b/TestRunner/app/tests/WrapperLifetimeModesTests.js @@ -960,4 +960,103 @@ describe("Wrapper lifetime modes", function () { done(); }); }); + + describe("write handler", function () { + function stats() { + return runtime.getWrapperLifetimeStats(); + } + + function makeHost() { + return (function (_super) { + __extends(Host, _super); + function Host() { + return (_super !== null && _super.apply(this, arguments)) || this; + } + return Host; + })(TNSAccessorHost); + } + + var Host = makeHost(); + var nativeName = Object.getOwnPropertyDescriptor(TNSAccessorHost.prototype, "name").get; + + it("handles writes to JS-extended instances only, under scope extended", function () { + var Ext = TNSAllocLog.extend({}, { name: "WrapperLifetimeWriteHandlerExt" }); + var before = stats(); + TNSAllocLog.new().tag = 1; + new TNSAllocLog().tag = 1; + TNSAllocLog.alloc().init().tag = 1; + var plain = stats().canaryInterceptedWrites - before.canaryInterceptedWrites; + Extended.new().tag = 1; + new Ext().tag = 1; + Ext.alloc().init().tag = 1; + var extended = stats().canaryInterceptedWrites - before.canaryInterceptedWrites - plain; + if (canary) { + expect(plain).toBe(scope === "all" ? 3 : 0); + expect(extended).toBe(3); + } else { + expect(plain + extended).toBe(0); + } + }); + + it("handles writes to a key-value observed JS-extended instance on a new wrapper", function (done) { + var observer = NSObject.new(); + var before; + rewrap(function () { + var obj = Host.new(); + // Observing a key with a setter swaps in the notifying subclass. + obj.addObserverForKeyPathOptionsContext(observer, "name", 0, null); + obj.tag = "kept"; + return obj; + }, function (obj) { + expect(obj.observationInfo).not.toBeNull(); + if (keepsState) { + expect(obj.tag).toBe("kept"); + } + before = stats(); + obj.other = "new"; + if (canary) { + expect(stats().canaryInterceptedWrites - before.canaryInterceptedWrites).toBe(1); + } + obj.removeObserverForKeyPath(observer, "name"); + done(); + }); + }); + + it("gives a native constructor's JS-extended result the write handler", function (done) { + var owner = NSMutableArray.new(); + var handle; + var first; + (function () { + var obj = Extended.new(); + obj.tag = "kept"; + owner.addObject(obj); + handle = interop.handleof(obj); + first = new WeakRef(obj); + })(); + settle(2, function () { + var before = stats(); + var again = new TNSAllocLog(handle); + expect(again instanceof TNSAllocLog).toBe(true); + if (canary) { + expect(first.deref()).toBeUndefined(); + expect(Object.getPrototypeOf(again)).toBe(TNSAllocLog.prototype); + } + if (keepsState) { + expect(again.tag).toBe("kept"); + } + again.other = "new"; + if (canary) { + expect(stats().canaryInterceptedWrites - before.canaryInterceptedWrites).toBe(1); + } + again = null; + settle(2, function () { + var obj = owner.objectAtIndex(0); + if (keepsState) { + expect(obj.other).toBe("new"); + } + done(); + }); + }); + }); + }); }); diff --git a/TestRunner/app/tests/WrapperLifetimeTests.js b/TestRunner/app/tests/WrapperLifetimeTests.js index 959702ccd..2f5c97dd8 100644 --- a/TestRunner/app/tests/WrapperLifetimeTests.js +++ b/TestRunner/app/tests/WrapperLifetimeTests.js @@ -325,6 +325,7 @@ describe("Wrapper lifetime", function () { "queuedReleases", "canaryStates", "canaryNativeDeaths", + "canaryInterceptedWrites", "stateLostCandidates", "stateLostConfirmed", ].sort()); diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 7b94fad7b..958e96329 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -166,6 +166,7 @@ every build (they only cost an increment on finalizer and error paths): | `queuedReleases` | `"rooted"` and `"canary"`: collected wrappers whose native object was queued for release on the runtime's thread | | `canaryStates` | `"canary"` only: state objects created to hold native objects' JS properties | | `canaryNativeDeaths` | `"canary"` only: state objects let go of because their native object was deallocated | +| `canaryInterceptedWrites` | `"canary"` only: writes to canaries the runtime's write handler saw. Other wrappers have no handler | 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 42b1db854..56e920d8c 100644 --- a/types/ns-runtime.d.ts +++ b/types/ns-runtime.d.ts @@ -100,6 +100,8 @@ declare module "ns:runtime" { canaryStates: number; /** `"canary"` only: state objects let go of because their native object was deallocated. */ canaryNativeDeaths: number; + /** `"canary"` only: writes to canaries the runtime's write handler saw. */ + canaryInterceptedWrites: number; } /** From 2a212d6f0e90998370c3d0bb28c5b9676fbf79c7 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 17 Nov 2026 10:40:45 -0300 Subject: [PATCH 14/24] test(runtime): pin how the canary write handler treats inherited accessors The handler leaves an inherited accessor to V8 after declining. Calling the setter from the handler instead was measured slower (JS-extended native property write 316 -> 366 ns, Release simulator): the API hands a setter out only inside a property descriptor object. Keeping a setter, or a native property's metadata, across writes would need to know when JS changes a prototype, which V8 does not report. Specs cover native and JS setters running with the canary as `this` and making no state, setter exceptions propagating, getter-only and read-only properties rejected in strict mode, and prototype members replaced, shadowed or swapped (setPrototypeOf) after a first write. --- NativeScript/runtime/WrapperLifetimeCanary.mm | 6 +- .../app/tests/WrapperLifetimeModesTests.js | 184 ++++++++++++++++++ 2 files changed, 189 insertions(+), 1 deletion(-) diff --git a/NativeScript/runtime/WrapperLifetimeCanary.mm b/NativeScript/runtime/WrapperLifetimeCanary.mm index 3110358dc..4b77eead7 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.mm +++ b/NativeScript/runtime/WrapperLifetimeCanary.mm @@ -536,7 +536,7 @@ bool HasOwn(Local context, Local state, Local propert // callback for the same reason. The handlers are masking, so they also see // names the prototype chain has. After the setter declines, V8 adds a new name // to the canary without calling the definer, so the setter itself decides what -// becomes state. +// becomes state. V8 calls the setter only when the canary is the receiver. Intercepted Setter(Local property, Local value, const PropertyCallbackInfo& info) { // v8::Object::DefineOwnProperty reaches the setter, not the definer. @@ -576,6 +576,10 @@ Intercepted Setter(Local property, Local value, // setter: a native property's (an accessor pair on its class's // prototype), a JS one's, or one defined on the canary, which runs with // the canary as `this` and so mirrors whatever it writes. None is state. + // Calling the setter from here was measured slower than V8's own lookup + // after the decline: the API hands a setter out only in a descriptor + // object, and keeping one (or a native property's metadata) across + // writes needs to know when JS changes a prototype, which V8 never says. if ((attributes & ReadOnly) != 0) { return Intercepted::kNo; } diff --git a/TestRunner/app/tests/WrapperLifetimeModesTests.js b/TestRunner/app/tests/WrapperLifetimeModesTests.js index 21b81575e..08ddae98b 100644 --- a/TestRunner/app/tests/WrapperLifetimeModesTests.js +++ b/TestRunner/app/tests/WrapperLifetimeModesTests.js @@ -979,6 +979,190 @@ describe("Wrapper lifetime modes", function () { var Host = makeHost(); var nativeName = Object.getOwnPropertyDescriptor(TNSAccessorHost.prototype, "name").get; + it("runs the native setter of a native property on the receiver", function () { + var obj = Host.new(); + var other = Host.new(); + obj.tag = "state"; + other.name = "other"; + var before = stats(); + obj.name = "direct"; + var after = stats(); + expect(nativeName.call(obj)).toBe("direct"); + expect(nativeName.call(other)).toBe("other"); + expect(hasOwn(obj, "name")).toBe(false); + if (canary) { + expect(after.canaryInterceptedWrites - before.canaryInterceptedWrites).toBe(1); + expect(after.canaryStates).toBe(before.canaryStates); + } + }); + + it("propagates what a native setter throws", function () { + var obj = Host.new(); + obj.tag = "state"; + // NSObject's `hash` is read-only: its setter throws. + expect(function () { + obj.hash = 1; + }).toThrowError(/readonly/); + expect(function () { + "use strict"; + obj.hash = 1; + }).toThrowError(/readonly/); + expect(hasOwn(obj, "hash")).toBe(false); + }); + + it("runs a JS accessor's setter with the canary as this", function (done) { + var Labeled = makeHost(); + var receivers = []; + Object.defineProperty(Labeled.prototype, "label", { + get: function () { + return this._label; + }, + set: function (value) { + receivers.push(this); + this._label = value; + }, + configurable: true + }); + Object.defineProperty(Labeled.prototype, "boom", { + set: function () { + throw new RangeError("boom"); + }, + configurable: true + }); + rewrap(function () { + var obj = Labeled.new(); + var before = stats(); + obj.label = "set"; + expect(receivers.length).toBe(1); + expect(receivers[0]).toBe(obj); + expect(hasOwn(obj, "label")).toBe(false); + expect(hasOwn(obj, "_label")).toBe(true); + expect(function () { + obj.boom = 1; + }).toThrowError(RangeError); + expect(hasOwn(obj, "boom")).toBe(false); + if (canary) { + expect(stats().canaryStates).toBe(before.canaryStates + 1); + } + receivers.length = 0; + return obj; + }, function (obj) { + if (keepsState) { + expect(obj.label).toBe("set"); + } + obj.label = "again"; + expect(receivers[0]).toBe(obj); + expect(obj._label).toBe("again"); + done(); + }); + }); + + it("rejects writes to a getter-only accessor and a read-only property", function () { + var Fixed = makeHost(); + Object.defineProperty(Fixed.prototype, "getOnly", { + get: function () { + return "get"; + }, + configurable: true + }); + Object.defineProperty(Fixed.prototype, "fixed", { value: "fixed", writable: false, configurable: true }); + var obj = Fixed.new(); + obj.tag = "state"; + var before = stats(); + expect(function () { + "use strict"; + obj.getOnly = 1; + }).toThrowError(TypeError); + expect(function () { + "use strict"; + obj.fixed = 1; + }).toThrowError(TypeError); + obj.getOnly = 1; + obj.fixed = 1; + expect(obj.getOnly).toBe("get"); + expect(obj.fixed).toBe("fixed"); + expect(hasOwn(obj, "getOnly")).toBe(false); + expect(hasOwn(obj, "fixed")).toBe(false); + if (canary) { + expect(stats().canaryStates).toBe(before.canaryStates); + } + }); + + it("follows a prototype data property replaced by an accessor and back", function (done) { + var Flip = makeHost(); + var set = []; + Flip.prototype.flip = "data"; + var first = Flip.new(); + first.flip = "own"; + expect(hasOwn(first, "flip")).toBe(true); + Object.defineProperty(Flip.prototype, "flip", { + get: function () { + return "accessor"; + }, + set: function (value) { + set.push(value); + }, + configurable: true + }); + var second = Flip.new(); + second.flip = "through"; + expect(set).toEqual(["through"]); + expect(hasOwn(second, "flip")).toBe(false); + first.flip = "own2"; + expect(first.flip).toBe("own2"); + expect(set).toEqual(["through"]); + Object.defineProperty(Flip.prototype, "flip", { value: "data2", writable: true, configurable: true }); + rewrap(function () { + var third = Flip.new(); + third.flip = "own3"; + expect(hasOwn(third, "flip")).toBe(true); + expect(set).toEqual(["through"]); + return third; + }, function (third) { + if (keepsState) { + expect(third.flip).toBe("own3"); + } + done(); + }); + }); + + it("follows a native property shadowed and unshadowed on a JS prototype", function () { + var Shadow = makeHost(); + var obj = Shadow.new(); + obj.name = "native"; + Object.defineProperty(Shadow.prototype, "name", { value: "js", writable: true, configurable: true }); + obj.name = "own"; + expect(hasOwn(obj, "name")).toBe(true); + expect(nativeName.call(obj)).toBe("native"); + delete obj.name; + delete Shadow.prototype.name; + obj.name = "native2"; + expect(hasOwn(obj, "name")).toBe(false); + expect(nativeName.call(obj)).toBe("native2"); + }); + + it("follows a prototype chain changed after a write", function () { + var obj = Host.new(); + obj.name = "native"; + var set = []; + var proto = Object.create(Object.getPrototypeOf(obj), { + name: { + set: function (value) { + set.push(this === obj ? value : "wrong this"); + }, + configurable: true + } + }); + Object.setPrototypeOf(obj, proto); + obj.name = "swapped"; + expect(set).toEqual(["swapped"]); + expect(nativeName.call(obj)).toBe("native"); + Object.setPrototypeOf(obj, Host.prototype); + obj.name = "native2"; + expect(set).toEqual(["swapped"]); + expect(nativeName.call(obj)).toBe("native2"); + }); + it("handles writes to JS-extended instances only, under scope extended", function () { var Ext = TNSAllocLog.extend({}, { name: "WrapperLifetimeWriteHandlerExt" }); var before = stats(); From c03b68928c7cdc0401b454ebb7a014a8544a5b4b Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 17 Nov 2026 15:03:03 -0300 Subject: [PATCH 15/24] test(runtime): pin native property setters on canaries Specs for how the canary write handler treats native ObjC property setters: sloppy and strict writes, an ObjC exception from a setter, read-only rejection, a JS override, an accessor added later on the JS prototype or on the instance, the four routes that redefine a member on the native prototype, delete and re-add there, a Proxy prototype, and a setter override exposed to native code. TNSCanaryWriteTarget's `guarded` setter raises. --- TestFixtures/Marshalling/TNSAllocLog.h | 16 ++ TestFixtures/Marshalling/TNSAllocLog.m | 13 + .../app/tests/WrapperLifetimeModesTests.js | 252 ++++++++++++++++++ 3 files changed, 281 insertions(+) diff --git a/TestFixtures/Marshalling/TNSAllocLog.h b/TestFixtures/Marshalling/TNSAllocLog.h index 028be8046..e9e035362 100644 --- a/TestFixtures/Marshalling/TNSAllocLog.h +++ b/TestFixtures/Marshalling/TNSAllocLog.h @@ -140,6 +140,22 @@ id TNSOwnedPrimitivesObjectAt(TNSOwnedPrimitives* holder, NSUInteger index); @end +// Native properties for the canary write handler specs. Setting `guarded` to a +// negative value raises. Each `via*` property and `dropped` belongs to the one +// spec that redefines or deletes it on this class's prototype. +@interface TNSCanaryWriteTarget : NSObject + +@property(nonatomic) NSInteger level; +@property(nonatomic) NSInteger guarded; +@property(nonatomic, readonly) NSInteger fixed; +@property(nonatomic) NSInteger viaDefineProperty; +@property(nonatomic) NSInteger viaDefineProperties; +@property(nonatomic) NSInteger viaReflect; +@property(nonatomic) NSInteger viaDefineSetter; +@property(nonatomic) NSInteger dropped; + +@end + // -dealloc reads `value`. @interface TNSAccessorDeallocHost : TNSAccessorHost diff --git a/TestFixtures/Marshalling/TNSAllocLog.m b/TestFixtures/Marshalling/TNSAllocLog.m index 15c07cd2d..190f365a2 100644 --- a/TestFixtures/Marshalling/TNSAllocLog.m +++ b/TestFixtures/Marshalling/TNSAllocLog.m @@ -316,6 +316,19 @@ - (void)initHook { @implementation TNSAccessorHost @end +@implementation TNSCanaryWriteTarget + +- (void)setGuarded:(NSInteger)guarded { + if (guarded < 0) { + @throw [NSException exceptionWithName:NSInvalidArgumentException + reason:@"guarded must not be negative" + userInfo:nil]; + } + _guarded = guarded; +} + +@end + @implementation TNSAccessorDeallocHost - (void)dealloc { diff --git a/TestRunner/app/tests/WrapperLifetimeModesTests.js b/TestRunner/app/tests/WrapperLifetimeModesTests.js index 08ddae98b..72385e91b 100644 --- a/TestRunner/app/tests/WrapperLifetimeModesTests.js +++ b/TestRunner/app/tests/WrapperLifetimeModesTests.js @@ -1163,6 +1163,258 @@ describe("Wrapper lifetime modes", function () { expect(nativeName.call(obj)).toBe("native2"); }); + describe("native property setters", function () { + function makeTarget() { + return (function (_super) { + __extends(Target, _super); + function Target() { + return (_super !== null && _super.apply(this, arguments)) || this; + } + return Target; + })(TNSCanaryWriteTarget); + } + + function nativeGetter(name) { + return Object.getOwnPropertyDescriptor(TNSCanaryWriteTarget.prototype, name).get; + } + + var nativeLevel = nativeGetter("level"); + + it("run on the receiver, in sloppy and strict mode", function () { + var Target = makeTarget(); + var obj = Target.new(); + var other = Target.new(); + obj.tag = "state"; + var before = stats(); + obj.level = 3; + expect(nativeLevel.call(obj)).toBe(3); + (function () { + "use strict"; + obj.level = 4; + })(); + expect(nativeLevel.call(obj)).toBe(4); + expect(nativeLevel.call(other)).toBe(0); + expect(hasOwn(obj, "level")).toBe(false); + if (canary) { + expect(stats().canaryInterceptedWrites - before.canaryInterceptedWrites).toBe(2); + expect(stats().canaryStates).toBe(before.canaryStates); + } + }); + + it("propagate what the native setter raises", function () { + var obj = makeTarget().new(); + obj.guarded = 2; + var errors = []; + try { + obj.guarded = -1; + } catch (e) { + errors.push(e); + } + try { + (function () { + "use strict"; + obj.guarded = -2; + })(); + } catch (e) { + errors.push(e); + } + expect(errors.length).toBe(2); + errors.forEach(function (e) { + expect(e.nativeException instanceof NSException).toBe(true); + expect(e.nativeException.reason).toBe("guarded must not be negative"); + }); + expect(obj.guarded).toBe(2); + expect(hasOwn(obj, "guarded")).toBe(false); + obj.guarded = 5; + expect(obj.guarded).toBe(5); + }); + + it("reject a write to a read-only native property", function () { + var obj = makeTarget().new(); + obj.tag = "state"; + expect(function () { + obj.fixed = 1; + }).toThrowError(/readonly/); + expect(function () { + "use strict"; + obj.fixed = 1; + }).toThrowError(/readonly/); + expect(obj.fixed).toBe(0); + expect(hasOwn(obj, "fixed")).toBe(false); + }); + + it("give way to a JS accessor overriding the property, which gets the JS value", function () { + var Over = makeTarget(); + var calls = []; + Object.defineProperty(Over.prototype, "level", { + get: function () { + return -1; + }, + set: function (value) { + calls.push({ self: this, value: value }); + }, + configurable: true + }); + var obj = Over.new(); + var value = { not: "a number" }; + obj.level = value; + expect(calls.length).toBe(1); + expect(calls[0].self).toBe(obj); + expect(calls[0].value).toBe(value); + expect(nativeLevel.call(obj)).toBe(0); + }); + + it("give way to a JS accessor added to a JS prototype after a native write", function () { + var Late = makeTarget(); + var obj = Late.new(); + obj.level = 1; + expect(nativeLevel.call(obj)).toBe(1); + var set = []; + Object.defineProperty(Late.prototype, "level", { + set: function (value) { + set.push(this === obj ? value : "wrong this"); + }, + configurable: true + }); + obj.level = 2; + expect(set).toEqual([2]); + expect(nativeLevel.call(obj)).toBe(1); + delete Late.prototype.level; + obj.level = 3; + expect(set).toEqual([2]); + expect(nativeLevel.call(obj)).toBe(3); + }); + + it("give way to an accessor defined on the instance", function () { + var obj = makeTarget().new(); + obj.level = 1; + var set = []; + Object.defineProperty(obj, "level", { + set: function (value) { + set.push(this === obj ? value : "wrong this"); + }, + configurable: true + }); + obj.level = 2; + expect(set).toEqual([2]); + expect(nativeLevel.call(obj)).toBe(1); + delete obj.level; + obj.level = 3; + expect(set).toEqual([2]); + expect(nativeLevel.call(obj)).toBe(3); + }); + + it("give way to an accessor redefined on the native prototype after a native write", function () { + var proto = TNSCanaryWriteTarget.prototype; + var redefine = { + viaDefineProperty: function (name, setter) { + Object.defineProperty(proto, name, { set: setter, configurable: true }); + }, + viaDefineProperties: function (name, setter) { + var descriptors = {}; + descriptors[name] = { set: setter, configurable: true }; + Object.defineProperties(proto, descriptors); + }, + viaReflect: function (name, setter) { + expect(Reflect.defineProperty(proto, name, { set: setter, configurable: true })).toBe(true); + }, + viaDefineSetter: function (name, setter) { + proto.__defineSetter__(name, setter); + } + }; + var obj = makeTarget().new(); + Object.keys(redefine).forEach(function (name) { + var getter = nativeGetter(name); + obj[name] = 1; + expect(getter.call(obj)).toBe(1); + var set = []; + redefine[name](name, function (value) { + set.push(this === obj ? value : "wrong this"); + }); + var value = { name: name }; + obj[name] = value; + expect(set.length).toBe(1); + expect(set[0]).toBe(value); + expect(hasOwn(obj, name)).toBe(false); + }); + }); + + it("follow a native accessor deleted from its prototype and replaced", function () { + var proto = TNSCanaryWriteTarget.prototype; + var getter = nativeGetter("dropped"); + var obj = makeTarget().new(); + obj.dropped = 1; + expect(getter.call(obj)).toBe(1); + expect(delete proto.dropped).toBe(true); + obj.dropped = 2; + expect(hasOwn(obj, "dropped")).toBe(true); + expect(getter.call(obj)).toBe(1); + delete obj.dropped; + proto.dropped = "data"; + obj.dropped = 3; + expect(hasOwn(obj, "dropped")).toBe(true); + expect(obj.dropped).toBe(3); + delete obj.dropped; + var set = []; + Object.defineProperty(proto, "dropped", { + set: function (value) { + set.push(this === obj ? value : "wrong this"); + }, + configurable: true + }); + var value = { dropped: true }; + obj.dropped = value; + expect(set.length).toBe(1); + expect(set[0]).toBe(value); + expect(hasOwn(obj, "dropped")).toBe(false); + expect(getter.call(obj)).toBe(1); + }); + + it("give way to a proxy between the instance and the native prototype", function () { + var obj = makeTarget().new(); + obj.level = 1; + var trapped = []; + // The target owns `level`, so attribute queries find it at the proxy. + var target = Object.create(Object.getPrototypeOf(obj)); + Object.defineProperty(target, "level", { value: "target", writable: true, configurable: true }); + var proxy = new Proxy(target, { + set: function (target, key, value, receiver) { + trapped.push({ key: key, value: value, receiver: receiver }); + return true; + } + }); + Object.setPrototypeOf(obj, proxy); + obj.level = 2; + expect(trapped.length).toBe(1); + expect(trapped[0].key).toBe("level"); + expect(trapped[0].value).toBe(2); + expect(trapped[0].receiver).toBe(obj); + expect(nativeLevel.call(obj)).toBe(1); + }); + + it("dispatch to a setter override exposed to native code that JS no longer sees", function () { + var calls = []; + var Exposed = TNSCanaryWriteTarget.extend({ + get level() { + return -1; + }, + set level(value) { + calls.push(value); + } + }, { name: "WrapperLifetimeExposedLevelSetter" }); + // -setLevel: stays overridden for native callers. + expect(delete Exposed.prototype.level).toBe(true); + var obj = Exposed.new(); + obj.tag = "state"; + obj.level = 3; + expect(calls).toEqual([3]); + expect(nativeLevel.call(obj)).toBe(0); + obj.setValueForKey(5, "level"); + expect(calls).toEqual([3, 5]); + expect(nativeLevel.call(obj)).toBe(0); + }); + }); + it("handles writes to JS-extended instances only, under scope extended", function () { var Ext = TNSAllocLog.extend({}, { name: "WrapperLifetimeWriteHandlerExt" }); var before = stats(); From 43b1c14382350b818d981c84ff56d50306739fb8 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 17 Nov 2026 23:01:37 -0300 Subject: [PATCH 16/24] chore(v8): pin v8-14.9.207.39-11 Canary mode's write handlers rely on a named interceptor's definer seeing class fields and v8::Object::CreateDataProperty, with the descriptor V8 actually defines. Both fixes first ship in -11 (v8-buildscripts#13). --- V8_RELEASE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/V8_RELEASE b/V8_RELEASE index 93699c903..f730d502e 100644 --- a/V8_RELEASE +++ b/V8_RELEASE @@ -1 +1 @@ -v8-14.9.207.39-10 +v8-14.9.207.39-11 From 7548023a9bf3383d62545e13cde501e5ef0a4e02 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 18 Nov 2026 00:11:06 -0300 Subject: [PATCH 17/24] docs(runtime): canary state lost to a removed token or a class refusing weak references --- docs/knowledge/v8-resurrecting-finalizers.md | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/docs/knowledge/v8-resurrecting-finalizers.md b/docs/knowledge/v8-resurrecting-finalizers.md index 551004c29..60ff2e150 100644 --- a/docs/knowledge/v8-resurrecting-finalizers.md +++ b/docs/knowledge/v8-resurrecting-finalizers.md @@ -271,7 +271,8 @@ setter classifies the prototype chain itself, because once it declines V8 adds a to the canary without calling the definer: a name that resolves to an inherited accessor (a native property, a JS getter/setter) or a read-only data member is left to V8 and never becomes state, so native setters run as before. The state is rooted from its first write -until the native object is deallocated, and stays the source of truth: a canary built later +until the native object is deallocated (or, with the default death signal below, until its +token is released), and stays the source of truth: a canary built later for the same object, or the receiver a JS-implemented `-dealloc` runs with, gets the state's properties copied onto it with their attributes and accessors. The costs, measured on a Release simulator build: the handler is installed per template, so every write to any ObjC @@ -287,11 +288,17 @@ inherits, whose receiver still reads the state), and then retires them. For othe a compile-time choice (`NS_CANARY_DEATH_SIGNAL` in `WrapperLifetimeCanary.mm`): by default a token associated with the object reports it from its `-dealloc`, immediately and on any thread, but the ObjC runtime aborts -the process for a class that forbids associated objects, and there is no public query for that; -the alternative keeps an ObjC weak reference in each record (`objc_initWeakOrNil`, which declines -instead of aborting for classes that refuse weak references) and sweeps the records after every -major collection, so state lingers until then. With the default, `"scope": "all"` is -experimental for that reason; `"extended"` attaches no tokens at all. It cannot be +the process for a class that forbids associated objects, and there is no public query for that. +Code that calls `objc_removeAssociatedObjects` on a live object releases the token too, which +retires the state as if the object had died: the next write through the canary starts a new +state from the canary's properties, but if the canary dies before such a write, a canary built +later starts without them. The alternative keeps an ObjC weak reference in each record +(`objc_initWeakOrNil`, which declines instead of aborting for classes that refuse weak +references) and sweeps the records after every major collection, so state lingers until then. +An instance of a class that refuses weak references and is not JS-extended gets no state +under it: its properties live on the canary alone and are gone after a replacement. With the +default, `"scope": "all"` is experimental because of that abort; `"extended"` attaches no +tokens at all. It cannot be rooted at canary death instead, because a state reachable only through the canary is garbage in the same collection. The cost: state that references its own object (a closure over `this`) keeps it alive. A canary built after a death is a new object, but `===` cannot tell: only one From 9d83bd074fff195bbed4416e29449da1e335b285 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 18 Nov 2026 00:14:42 -0300 Subject: [PATCH 18/24] test(runtime): pin native dispatch for a setter override JS no longer sees The spec deleted the level accessor from Exposed.prototype, which inherits it from the implementation object, so nothing was deleted and the JS setter ran directly. With the accessor removed where it lives, a JS write goes through the native accessor and runs the base -setLevel: (the native object takes the value; no JS property is created), while native callers such as KVC reach the override. --- .../app/tests/WrapperLifetimeModesTests.js | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/TestRunner/app/tests/WrapperLifetimeModesTests.js b/TestRunner/app/tests/WrapperLifetimeModesTests.js index 72385e91b..a9491b067 100644 --- a/TestRunner/app/tests/WrapperLifetimeModesTests.js +++ b/TestRunner/app/tests/WrapperLifetimeModesTests.js @@ -1392,7 +1392,7 @@ describe("Wrapper lifetime modes", function () { expect(nativeLevel.call(obj)).toBe(1); }); - it("dispatch to a setter override exposed to native code that JS no longer sees", function () { + it("write through the native setter when JS no longer sees an override exposed to native code", function () { var calls = []; var Exposed = TNSCanaryWriteTarget.extend({ get level() { @@ -1402,16 +1402,23 @@ describe("Wrapper lifetime modes", function () { calls.push(value); } }, { name: "WrapperLifetimeExposedLevelSetter" }); - // -setLevel: stays overridden for native callers. - expect(delete Exposed.prototype.level).toBe(true); + // The accessor lives on the implementation object Exposed.prototype + // inherits from. -setLevel: stays overridden for native callers. + var implementation = Object.getPrototypeOf(Exposed.prototype); + expect(Object.getOwnPropertyDescriptor(implementation, "level")).toBeDefined(); + expect(delete implementation.level).toBe(true); + expect(Exposed.prototype.__lookupSetter__("level")).toBe(Object.getOwnPropertyDescriptor(TNSCanaryWriteTarget.prototype, "level").set); var obj = Exposed.new(); obj.tag = "state"; + // A JS write through the native accessor runs the base -setLevel:; + // native callers reach the override. obj.level = 3; - expect(calls).toEqual([3]); - expect(nativeLevel.call(obj)).toBe(0); + expect(calls).toEqual([]); + expect(nativeLevel.call(obj)).toBe(3); + expect(Object.prototype.hasOwnProperty.call(obj, "level")).toBe(false); obj.setValueForKey(5, "level"); - expect(calls).toEqual([3, 5]); - expect(nativeLevel.call(obj)).toBe(0); + expect(calls).toEqual([5]); + expect(nativeLevel.call(obj)).toBe(3); }); }); From 77fedf72bcfd4b80e22c7dfbcae877b62726f742 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 18 Nov 2026 08:05:28 -0300 Subject: [PATCH 19/24] fix(runtime): canary receivers of JS methods native code calls stay canaries WrapperLifetime::Relinquish handed a canary back to ObjectManager like any other unrooted wrapper. A canary keeps the canary mode's lifetime, so only wrappers outside the canary scope get ownership tracking. --- NativeScript/runtime/ArgConverter.mm | 3 ++- NativeScript/runtime/WrapperLifetime.h | 4 ++-- NativeScript/runtime/WrapperLifetime.mm | 3 ++- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/NativeScript/runtime/ArgConverter.mm b/NativeScript/runtime/ArgConverter.mm index c60aff170..143fd3023 100644 --- a/NativeScript/runtime/ArgConverter.mm +++ b/NativeScript/runtime/ArgConverter.mm @@ -1344,7 +1344,8 @@ 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. + // A wrapper a lifetime mode roots or makes a canary keeps the mode's own + // lifetime instead. if (wrapper->LifetimeState() != nullptr) { if (ObjectWeakCallbackState* state = WrapperLifetime::Relinquish(wrapper)) { ObjectManager::ManageOwnership(isolate, wrapper, state); diff --git a/NativeScript/runtime/WrapperLifetime.h b/NativeScript/runtime/WrapperLifetime.h index b92bea1a3..6ca6ae624 100644 --- a/NativeScript/runtime/WrapperLifetime.h +++ b/NativeScript/runtime/WrapperLifetime.h @@ -103,8 +103,8 @@ class WrapperLifetime { } } - // Gives an adopted wrapper that is not rooted back to ObjectManager: returns - // its registration with the handle strong, for + // Gives an adopted wrapper that is neither rooted nor a canary 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); diff --git a/NativeScript/runtime/WrapperLifetime.mm b/NativeScript/runtime/WrapperLifetime.mm index 7c0f833f9..aa435a14b 100644 --- a/NativeScript/runtime/WrapperLifetime.mm +++ b/NativeScript/runtime/WrapperLifetime.mm @@ -382,7 +382,8 @@ void ReleaseAll(Isolate* isolate, RootedState* rooted) { ObjectWeakCallbackState* WrapperLifetime::Relinquish(ObjCDataWrapper* wrapper) { ObjectWeakCallbackState* state = wrapper->LifetimeState(); - if (state == nullptr || state->lifetimeTracked_ || state->target_->IsEmpty()) { + if (state == nullptr || state->lifetimeTracked_ || state->lifetimeCanary_ || + state->target_->IsEmpty()) { return nullptr; } if (state->target_->IsWeak()) { From 727629acca0991bc1af09f7d02284196b5df7b6a Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 18 Nov 2026 10:17:51 -0300 Subject: [PATCH 20/24] fix(runtime): retire a dying canary record only while it is still the object's ReportDyingRecordsDied compared the record under the registry mutex, then released it before NativeDied erased by address. Once the original -dealloc has freed the object, a thread holding another Locker can install a record for a new object at that address in between, and the erase discarded it. NativeDied now takes the expected record and compares it in the same critical section as the erase. --- NativeScript/runtime/WrapperLifetimeCanary.mm | 25 +++++++++---------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/NativeScript/runtime/WrapperLifetimeCanary.mm b/NativeScript/runtime/WrapperLifetimeCanary.mm index 4b77eead7..99aeac1f5 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.mm +++ b/NativeScript/runtime/WrapperLifetimeCanary.mm @@ -117,8 +117,12 @@ void DrainDead(const std::shared_ptr& registry) { } } -// From a reporter's -dealloc, on whichever thread deallocates the object. -void NativeDied(const std::shared_ptr& registry, void* object) { +// From a reporter's -dealloc, on whichever thread deallocates the object. With +// `expected`, retires the object's record only while it is still that one: +// once the object is freed, another thread can install a new object's record +// at the address, so the comparison must stay under the same lock as the erase. +void NativeDied(const std::shared_ptr& registry, void* object, + const CanaryRecord* expected = nullptr) { if (registry->count.load(std::memory_order_relaxed) == 0) { return; } @@ -129,7 +133,7 @@ void NativeDied(const std::shared_ptr& registry, void* object) { return; } auto it = registry->records.find(object); - if (it == registry->records.end()) { + if (it == registry->records.end() || (expected != nullptr && it->second.get() != expected)) { return; } // Erased now, inside the object's -dealloc: an object later allocated at @@ -190,18 +194,13 @@ DyingRecords MarkDying(void* object) { return dying; } -// After it returned: retires each record by identity. A record a new object at -// the address already displaced (RetireIfDead) is gone from the map. +// After it returned, with `object` freed: retires each record by identity. A +// record a new object at the address already displaced (RetireIfDead) is gone +// from the map. `dying` keeps each record alive, so no new record can share +// its address. void ReportDyingRecordsDied(const DyingRecords& dying, void* object) { for (const auto& [registry, record] : dying) { - { - std::lock_guard lock(registry->mutex); - auto it = registry->records.find(object); - if (registry->closed || it == registry->records.end() || it->second != record) { - continue; - } - } - NativeDied(registry, object); + NativeDied(registry, object, record.get()); } } From 4ab1f2ca9574192557344ac202d77434f390a731 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 18 Nov 2026 10:17:51 -0300 Subject: [PATCH 21/24] fix(runtime): read canary wrapper constructors with the teardown-safe accessor EmptyInstanceFunction used Caches::StateFor, which returns null after InvalidateIsolate, so building a -dealloc receiver while deferred releases drain during teardown failed the assertion. The constructors are created in ArgConverter::Init; ExistingStateFor reads them without creating state. --- NativeScript/runtime/ArgConverter.mm | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/NativeScript/runtime/ArgConverter.mm b/NativeScript/runtime/ArgConverter.mm index 143fd3023..f4bf13d31 100644 --- a/NativeScript/runtime/ArgConverter.mm +++ b/NativeScript/runtime/ArgConverter.mm @@ -119,7 +119,10 @@ bool IsKVOSubclassOf(Class klass, Class base) { Persistent* ArgConverter::EmptyInstanceFunction(Isolate* isolate, bool intercepted) { if (intercepted) { - CanaryWrapperConstructors* canary = Caches::StateFor(isolate); + // 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(); } From 882c9ec1de4e36832d82893d60a5b20b47d58b61 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 18 Nov 2026 11:22:50 -0300 Subject: [PATCH 22/24] fix(runtime): post a release drain when a native release throws A -dealloc that throws out of the release loop left the rest of the queue waiting for an unrelated phantom callback or native call. The loop's guard now posts a drain when entries remain; once the event loop has stopped, teardown releases them as before. --- NativeScript/runtime/WrapperLifetime.mm | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/NativeScript/runtime/WrapperLifetime.mm b/NativeScript/runtime/WrapperLifetime.mm index aa435a14b..a0fd090da 100644 --- a/NativeScript/runtime/WrapperLifetime.mm +++ b/NativeScript/runtime/WrapperLifetime.mm @@ -283,11 +283,18 @@ void ReleaseAll(Isolate* isolate, RootedState* rooted) { rooted->draining = true; // A -dealloc can throw an NSException through here. struct Reset { + Isolate* isolate; RootedState* rooted; - ~Reset() { rooted->draining = false; } - } reset{rooted}; + ~Reset() { + rooted->draining = false; + if (!rooted->releases.empty()) { + ScheduleDrain(isolate, rooted); + } + } + } reset{isolate, rooted}; // One state leaves the queue at a time, so a release that throws leaves the - // rest queued for the next drain or teardown. + // rest queued for the drain the guard posts, or for teardown once the event + // loop has stopped. while (!rooted->releases.empty()) { ObjectWeakCallbackState* state = rooted->releases.back(); rooted->releases.pop_back(); From 43f66bc64356758774e5b51e61b9a4813fef6717 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 18 Nov 2026 11:22:56 -0300 Subject: [PATCH 23/24] test(runtime): JS dealloc canary spec checks each fixture's own state went The canary death counter is isolate-wide, so an unrelated record could stand in for a fixture whose state was kept. Each fixture now holds its own payload, watched through a WeakRef that must clear. --- TestRunner/app/tests/WrapperLifetimeModesTests.js | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/TestRunner/app/tests/WrapperLifetimeModesTests.js b/TestRunner/app/tests/WrapperLifetimeModesTests.js index a9491b067..7ac07e973 100644 --- a/TestRunner/app/tests/WrapperLifetimeModesTests.js +++ b/TestRunner/app/tests/WrapperLifetimeModesTests.js @@ -756,12 +756,16 @@ describe("Wrapper lifetime modes", function () { } }, { name: "WrapperLifetimeModesJSDealloc" }); var owner = NSMutableArray.new(); + var payloads = []; settle(2, function () { var before = runtime.getWrapperLifetimeStats(); (function () { for (var i = 0; i < N; i++) { var obj = WithDealloc.new(); obj.tag = "state"; + var payload = { index: i }; + obj.payload = payload; + payloads.push(new WeakRef(payload)); owner.addObject(obj); } })(); @@ -774,6 +778,9 @@ describe("Wrapper lifetime modes", function () { // The JS dealloc still reads the object's JS state. expect(seen.filter(function (tag) { return tag === "state"; }).length).toBe(N); expect(after.canaryNativeDeaths - before.canaryNativeDeaths).not.toBeLessThan(N); + // The death count is isolate-wide; each fixture's own + // state must be gone. + expect(payloads.filter(function (ref) { return ref.deref() !== undefined; }).length).toBe(0); } done(); }); From 8d45835744a9fbca6e2cd083d12daf1bbdc89068 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 18 Nov 2026 11:22:56 -0300 Subject: [PATCH 24/24] test(runtime): native constructor canary spec reads back after its wrapper died The readback goes through rewrap, so in canary mode the wrapper the native constructor returned is checked dead before the object is read back on a new one. --- TestRunner/app/tests/WrapperLifetimeModesTests.js | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/TestRunner/app/tests/WrapperLifetimeModesTests.js b/TestRunner/app/tests/WrapperLifetimeModesTests.js index 7ac07e973..faa701756 100644 --- a/TestRunner/app/tests/WrapperLifetimeModesTests.js +++ b/TestRunner/app/tests/WrapperLifetimeModesTests.js @@ -1498,9 +1498,11 @@ describe("Wrapper lifetime modes", function () { if (canary) { expect(stats().canaryInterceptedWrites - before.canaryInterceptedWrites).toBe(1); } - again = null; - settle(2, function () { - var obj = owner.objectAtIndex(0); + rewrap(function () { + var made = again; + again = null; + return made; + }, function (obj) { if (keepsState) { expect(obj.other).toBe("new"); }