From 06c7ba85cda4edaa35bb0df09524c79f7f6c4fe3 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 15 Nov 2026 23:13:40 -0300 Subject: [PATCH 1/4] fix(runtime): release native objects on the runtime's thread --- NativeScript/runtime/ArgConverter.mm | 23 ++- NativeScript/runtime/Caches.h | 16 ++ NativeScript/runtime/DataWrapper.h | 23 ++- NativeScript/runtime/ObjectManager.h | 11 ++ NativeScript/runtime/ObjectManager.mm | 153 +++++++++++++++++-- NativeScript/runtime/Runtime.h | 4 + NativeScript/runtime/Runtime.mm | 10 ++ TestRunner/app/tests/GCFinalizerTests.js | 65 ++++++++ docs/knowledge/v8-resurrecting-finalizers.md | 18 +++ 9 files changed, 308 insertions(+), 15 deletions(-) diff --git a/NativeScript/runtime/ArgConverter.mm b/NativeScript/runtime/ArgConverter.mm index 8e50b0783..9fb834292 100644 --- a/NativeScript/runtime/ArgConverter.mm +++ b/NativeScript/runtime/ArgConverter.mm @@ -744,9 +744,20 @@ bool IsKVOSubclassOf(Class klass, Class base) { tns::SetValue(isolate, thiz, wrapper); std::shared_ptr> poThiz = ObjectManager::Register(context, thiz); cache->Instances.emplace(result, poThiz); - if (!resultIsOwned) { + // An initializer can answer with an existing object whose release is still + // waiting (see CreateJsWrapper). + bool tookOver = ObjectManager::TakeDeferredRelease(isolate, result); + if (tookOver && resultIsOwned) { + [result release]; + } else if (!tookOver && !resultIsOwned) { [result retain]; } + if (tookOver) { + // Only releases of objects that first reached JS on the runtime's + // thread are ever queued. + wrapper->SetBornOnRuntimeThread(); + ObjectManager::ProtectIfNativelyRetained(result, wrapper); + } ExternalMemory::ChargeEstimatedSize(isolate, thiz); } } @@ -1014,7 +1025,15 @@ bool IsKVOSubclassOf(Class klass, Class base) { receiver = poValue->Get(isolate).As(); tns::SetValue(isolate, receiver, wrapper); cache->Instances.emplace(target, poValue); - [target retain]; + // An extended class reads its retain count to decide whether native + // code owns the object, so a pending release is taken over, not stacked. + if (!ObjectManager::TakeDeferredRelease(isolate, target)) { + [target retain]; + } else if (wrapper->Type() == WrapperType::ObjCObject) { + ObjCDataWrapper* objcWrapper = static_cast(wrapper); + objcWrapper->SetBornOnRuntimeThread(); + ObjectManager::ProtectIfNativelyRetained(target, objcWrapper); + } } } else { tns::SetValue(isolate, receiver, wrapper); diff --git a/NativeScript/runtime/Caches.h b/NativeScript/runtime/Caches.h index 36f1812e5..9bee6766b 100644 --- a/NativeScript/runtime/Caches.h +++ b/NativeScript/runtime/Caches.h @@ -118,6 +118,22 @@ class Caches { return cache->GetOrCreateState(); } + // Teardown only: the existing state, even after InvalidateIsolate, for a + // subsystem that must finish work its state still holds. Never creates. + template + static T* ExistingStateFor(v8::Isolate* isolate) { + auto raw = isolate->GetData(0); + if (raw == nullptr) { + return nullptr; + } + Caches* cache = reinterpret_cast*>(raw)->get(); + size_t index = StateSlotIndexFor(); + if (index >= cache->stateSlots_.size()) { + return nullptr; + } + return static_cast(cache->stateSlots_[index].get()); + } + inline int getIsolateId() { return isolateId_; } // The id assigned at Init; unlike getIsolateId() it survives diff --git a/NativeScript/runtime/DataWrapper.h b/NativeScript/runtime/DataWrapper.h index 7b2b2c591..22172a9d1 100644 --- a/NativeScript/runtime/DataWrapper.h +++ b/NativeScript/runtime/DataWrapper.h @@ -20,6 +20,11 @@ class WorkerInspectorClient; namespace tns { +// Whether the calling thread is the one `isolate`'s runtime runs on (its event +// loop's thread). JS can also run on other threads, any that take the +// isolate's Locker. Several runtimes may share a thread. Defined in Runtime.mm. +bool OnRuntimeThreadOf(v8::Isolate* isolate); + class PrimitiveDataWrapper; struct ObjectWeakCallbackState; class EventLoop; @@ -396,7 +401,8 @@ class ObjCDataWrapper : public BaseDataWrapper { ObjCDataWrapper(id data, const TypeEncoding* typeEncoding = nullptr) : data_(data), typeEncoding_(typeEncoding), - klass_(object_getClass(data)) {} + klass_(object_getClass(data)), + bornOnRuntimeThread_(OnRuntimeThreadOf(v8::Isolate::TryGetCurrent())) {} const WrapperType Type() { return WrapperType::ObjCObject; } @@ -409,6 +415,11 @@ class ObjCDataWrapper : public BaseDataWrapper { bool IsAdapterClaim() { return this->adapterClaim_; } void MarkAdapterClaim() { this->adapterClaim_ = true; } + // Whether the object first reached JS on its runtime's thread, the stand-in + // for "belongs to that thread": its native release must happen there too. + bool BornOnRuntimeThread() { return this->bornOnRuntimeThread_; } + void SetBornOnRuntimeThread() { this->bornOnRuntimeThread_ = true; } + const TypeEncoding* TypeEncoding() { return this->typeEncoding_; } // The class Data() had when this wrapper was built. Data() alone cannot tell @@ -435,6 +446,7 @@ class ObjCDataWrapper : public BaseDataWrapper { id data_; const tns::TypeEncoding* typeEncoding_; Class klass_; + bool bornOnRuntimeThread_; }; class ObjCClassWrapper : public BaseDataWrapper { @@ -502,7 +514,10 @@ class AnonymousFunctionWrapper : public BaseDataWrapper { class BlockWrapper : public BaseDataWrapper { public: BlockWrapper(void* block, const TypeEncoding* typeEncoding, bool ownsBlock) - : block_(block), typeEncoding_(typeEncoding), ownsBlock_(ownsBlock) {} + : block_(block), + typeEncoding_(typeEncoding), + ownsBlock_(ownsBlock), + bornOnRuntimeThread_(OnRuntimeThreadOf(v8::Isolate::TryGetCurrent())) {} const WrapperType Type() { return WrapperType::Block; } @@ -512,10 +527,14 @@ class BlockWrapper : public BaseDataWrapper { bool OwnsBlock() { return this->ownsBlock_; } + // See ObjCDataWrapper::BornOnRuntimeThread. + bool BornOnRuntimeThread() { return this->bornOnRuntimeThread_; } + private: void* block_; const TypeEncoding* typeEncoding_; bool ownsBlock_; + bool bornOnRuntimeThread_; }; class FunctionReferenceTypeWrapper : public BaseDataWrapper { diff --git a/NativeScript/runtime/ObjectManager.h b/NativeScript/runtime/ObjectManager.h index 145ba894e..c1ff207e1 100644 --- a/NativeScript/runtime/ObjectManager.h +++ b/NativeScript/runtime/ObjectManager.h @@ -64,6 +64,17 @@ class ObjectManager { static void ReconcileOwnership(v8::Isolate* isolate, ObjCDataWrapper* wrapper); + // A collection can run on any thread that holds the isolate's Locker, but + // the native releases it causes are handed to the runtime's thread. A new + // Instances entry for an object whose release is still waiting takes that + // release over as its own retain instead of retaining again; returns whether + // it did. Once the entry's retain is settled, call ProtectIfNativelyRetained. + static bool TakeDeferredRelease(v8::Isolate* isolate, id obj); + // An extended class protects its wrapper when native code first retains the + // object past the runtime's own retain. A native retain made while a release + // waited found no wrapper to protect; this catches up. + static void ProtectIfNativelyRetained(id obj, ObjCDataWrapper* wrapper); + private: static void ReleaseNativeCounterpartCallback( const v8::FunctionCallbackInfo& info); diff --git a/NativeScript/runtime/ObjectManager.mm b/NativeScript/runtime/ObjectManager.mm index a433c64c0..a708f5fe8 100644 --- a/NativeScript/runtime/ObjectManager.mm +++ b/NativeScript/runtime/ObjectManager.mm @@ -3,12 +3,16 @@ #include #include #include +#include #include "Caches.h" #include "ClassBuilder.h" #include "Constants.h" #include "DataWrapper.h" #include "FFICall.h" +#include "EventLoop.h" #include "Helpers.h" +#include "Runtime.h" +#include "TNSDerivedClass.h" using namespace v8; using namespace std; @@ -68,14 +72,6 @@ void ReconcileOwnershipBeforeGC(Isolate* isolate, GCType, GCCallbackFlags) { } // namespace -void ObjectManager::Init(Isolate* isolate, Local globalTemplate) { - globalTemplate->Set(tns::ToV8String(isolate, "__releaseNativeCounterpart"), - FunctionTemplate::New(isolate, ReleaseNativeCounterpartCallback)); - isolate->AddGCPrologueCallback( - ReconcileOwnershipBeforeGC, - static_cast(kGCTypeMarkSweepCompact | kGCTypeIncrementalMarking)); -} - namespace { void LinkRegistered(v8::Isolate* isolate, ObjectWeakCallbackState* state) { @@ -108,8 +104,99 @@ void UnlinkRegistered(ObjectWeakCallbackState* state) { state->next_ = nullptr; } +// The native release of an object that first reached JS on its runtime's +// thread belongs on that thread. JS, and with it a collection and its +// finalizers, can run on any thread that holds the isolate's Locker (a JS +// callback dispatched to a background queue), and a -dealloc that tears down a +// view, a CA transaction or a block capturing one crashes off the main thread. +// Objects first wrapped on another thread are still released where the +// collection runs. +// +// Every access holds the isolate's Locker: finalizers and +// __releaseNativeCounterpart on any thread, and on the runtime's thread the +// drain task, wrapper creation and teardown. So no other synchronization. +struct DeferredReleases { + // Object -> releases it is owed. An object stays alive while it is owed one, + // so its address cannot be reused by another object meanwhile. + std::unordered_map objects; + std::vector blocks; + bool drainPosted = false; +}; + +void DrainDeferredReleases(DeferredReleases* pending) { + std::unordered_map objects; + std::vector blocks; + objects.swap(pending->objects); + blocks.swap(pending->blocks); + pending->drainPosted = false; + for (const auto& entry : objects) { + id obj = (__bridge id)entry.first; + for (unsigned i = 0; i < entry.second; i++) { + [obj release]; + } + } + for (const void* block : blocks) { + Block_release(block); + } +} + +// The queue to hand a release to, or null when the caller releases inline. +// Created by Init, so a collection on another thread never creates it; read +// without the validity check because a collection can still run on another +// thread between InvalidateIsolate and teardown, which drains it. +DeferredReleases* DeferralQueue(Isolate* isolate, bool bornOnRuntimeThread) { + if (!bornOnRuntimeThread || OnRuntimeThreadOf(isolate)) { + return nullptr; + } + return Caches::ExistingStateFor(isolate); +} + +// One event loop task per batch. If the loop no longer takes work, teardown is +// under way and drains the queue itself. +void PostDrain(Isolate* isolate, DeferredReleases* pending) { + if (pending->drainPosted) { + return; + } + Runtime* runtime = Runtime::GetRuntime(isolate); + std::shared_ptr loop = runtime != nullptr ? runtime->GetEventLoop() : nullptr; + pending->drainPosted = loop != nullptr && loop->PostInternal([isolate]() { + if (DeferredReleases* queued = Caches::ExistingStateFor(isolate)) { + DrainDeferredReleases(queued); + } + }); +} + +void ReleaseOnRuntimeThread(Isolate* isolate, id obj, bool bornOnRuntimeThread) { + DeferredReleases* pending = DeferralQueue(isolate, bornOnRuntimeThread); + if (pending == nullptr) { + [obj release]; + return; + } + pending->objects[(__bridge void*)obj]++; + PostDrain(isolate, pending); +} + +void BlockReleaseOnRuntimeThread(Isolate* isolate, const void* block, bool bornOnRuntimeThread) { + DeferredReleases* pending = DeferralQueue(isolate, bornOnRuntimeThread); + if (pending == nullptr) { + Block_release(block); + return; + } + pending->blocks.push_back(block); + PostDrain(isolate, pending); +} + } // namespace +void ObjectManager::Init(Isolate* isolate, Local globalTemplate) { + globalTemplate->Set(tns::ToV8String(isolate, "__releaseNativeCounterpart"), + FunctionTemplate::New(isolate, ReleaseNativeCounterpartCallback)); + isolate->AddGCPrologueCallback( + ReconcileOwnershipBeforeGC, + static_cast(kGCTypeMarkSweepCompact | kGCTypeIncrementalMarking)); + Caches::StateFor(isolate); +} + std::shared_ptr> ObjectManager::Register(Local context, const Local obj) { Isolate* isolate = v8::Isolate::GetCurrent(); @@ -160,6 +247,12 @@ void DisposeHandle(v8::Isolate* isolate, Isolate::Scope isolateScope(isolate); HandleScope scope(isolate); + // The event loop has stopped taking work, so nothing else would drain. + DeferredReleases* deferred = Caches::ExistingStateFor(isolate); + if (deferred != nullptr) { + DrainDeferredReleases(deferred); + } + // Detach the whole list first so disposal can't walk into freed entries, and // claim every state up front: disposing one entry can re-enter JS from // -dealloc and reach __releaseNativeCounterpart for any other entry this @@ -186,6 +279,12 @@ void DisposeHandle(v8::Isolate* isolate, state = next; } + // The walk's own releases are inline on the runtime's thread; this catches + // any made from another. + if (deferred != nullptr) { + DrainDeferredReleases(deferred); + } + DisposeHandleMap(isolate, cache->CtorFuncs); DisposeHandleMap(isolate, cache->ProtocolCtorFuncs); DisposeHandleMap(isolate, cache->CFunctions); @@ -265,6 +364,28 @@ void DisposeHandle(v8::Isolate* isolate, } } +bool ObjectManager::TakeDeferredRelease(Isolate* isolate, id obj) { + DeferredReleases* pending = Caches::ExistingStateFor(isolate); + if (pending == nullptr || pending->objects.empty()) { + return false; + } + auto it = pending->objects.find((__bridge void*)obj); + if (it == pending->objects.end()) { + return false; + } + if (--it->second == 0) { + pending->objects.erase(it); + } + return true; +} + +void ObjectManager::ProtectIfNativelyRetained(id obj, ObjCDataWrapper* wrapper) { + if (class_conformsToProtocol(object_getClass(obj), @protocol(TNSDerivedClass)) && + [obj retainCount] > 1) { + wrapper->GcProtect(); + } +} + bool ObjectManager::DisposeValue(Isolate* isolate, Local value, bool isFinalDisposal) { if (value.IsEmpty() || value->IsNullOrUndefined() || !value->IsObject()) { return true; @@ -320,7 +441,12 @@ void DisposeHandle(v8::Isolate* isolate, cache->Instances.erase(it); } } - [target release]; + if (objCObjectWrapper->IsAdapterClaim()) { + // The adapter's -dealloc retires this wrapper; it must run first. + [target release]; + } else { + ReleaseOnRuntimeThread(isolate, target, objCObjectWrapper->BornOnRuntimeThread()); + } } break; } @@ -338,7 +464,8 @@ void DisposeHandle(v8::Isolate* isolate, // Block_copy and runs the block's dispose helper once we drop the last // reference. (Using CFRelease here over-released stack blocks that were // never promoted to the heap, crashing in objc_release during GC.) - Block_release(blockWrapper->Block()); + BlockReleaseOnRuntimeThread(isolate, blockWrapper->Block(), + blockWrapper->BornOnRuntimeThread()); break; } case WrapperType::Reference: { @@ -517,7 +644,11 @@ void DisposeHandle(v8::Isolate* isolate, // wrapper, so it must not be touched afterwards. bool adapterClaim = objcWrapper->IsAdapterClaim(); - [data release]; + if (adapterClaim) { + [data release]; + } else { + ReleaseOnRuntimeThread(isolate, data, objcWrapper->BornOnRuntimeThread()); + } // The release above can run a -dealloc that detaches this wrapper; the // internal field owns it, so free only what is still attached. An diff --git a/NativeScript/runtime/Runtime.h b/NativeScript/runtime/Runtime.h index f4faf180e..714e44ae6 100644 --- a/NativeScript/runtime/Runtime.h +++ b/NativeScript/runtime/Runtime.h @@ -1,6 +1,7 @@ #ifndef Runtime_h #define Runtime_h +#include #include #include @@ -51,6 +52,8 @@ class Runtime { inline CFRunLoopRef RuntimeLoop() { return runtimeLoop_; } + inline bool IsOnRuntimeThread() const { return pthread_equal(runtimeThread_, pthread_self()) != 0; } + /* * Scheduler bound to this runtime's runloop. Producers on any thread post; * entries run only on the runtime's home thread. @@ -192,6 +195,7 @@ class Runtime { std::unique_ptr moduleInternal_; int workerId_; CFRunLoopRef runtimeLoop_; + pthread_t runtimeThread_; std::shared_ptr eventLoop_; // Drains unhandled promise rejections once per runloop turn // (kCFRunLoopBeforeWaiting). Torn down before isolate disposal in ~Runtime. diff --git a/NativeScript/runtime/Runtime.mm b/NativeScript/runtime/Runtime.mm index ebe46f48d..26b0236a5 100644 --- a/NativeScript/runtime/Runtime.mm +++ b/NativeScript/runtime/Runtime.mm @@ -1,4 +1,5 @@ #include "Runtime.h" +#include "DataWrapper.h" #include #include #include "ArgConverter.h" @@ -265,6 +266,7 @@ void DisposeIsolateWhenPossible(Isolate* isolate, int gateId) { #endif Isolate* isolate = Isolate::New(create_params); runtimeLoop_ = CFRunLoopGetCurrent(); + runtimeThread_ = pthread_self(); // v8 already asked for this isolate's task runner during Isolate::New, so // the registry may hold an unbound loop - or a stopped one, when a worker // isolate reuses a disposed isolate's address. Refresh, then attach to this @@ -387,6 +389,14 @@ void DisposeIsolateWhenPossible(Isolate* isolate, int gateId) { currentRuntime_ = nullptr; } +bool OnRuntimeThreadOf(v8::Isolate* isolate) { + if (isolate == nullptr) { + return false; + } + Runtime* runtime = Runtime::GetRuntime(isolate); + return runtime != nullptr && runtime->IsOnRuntimeThread(); +} + Runtime* Runtime::GetRuntime(v8::Isolate* isolate) { return static_cast(isolate->GetData(Constants::RUNTIME_SLOT)); } diff --git a/TestRunner/app/tests/GCFinalizerTests.js b/TestRunner/app/tests/GCFinalizerTests.js index 4d77e7a59..a40a61ad5 100644 --- a/TestRunner/app/tests/GCFinalizerTests.js +++ b/TestRunner/app/tests/GCFinalizerTests.js @@ -35,6 +35,71 @@ describe("GC finalizer callbacks", function () { expect(calls).toBe(1); }); + // A JS callback dispatched to a background queue holds the isolate's + // Locker there, so a collection and its finalizers can run off the main + // thread. The native releases they make must still happen on it. + it("releases natively on the runtime's thread after a background collection", function (done) { + var threads = []; + var DeallocThread = TNSApi.extend({ + methodCalledInDealloc: function () { + threads.push(NSThread.isMainThread); + } + }, { name: "TNSApiDeallocThread" }); + + // Owned only through its wrapper, so its finalizer releases it. + (function () { + DeallocThread.alloc().init(); + })(); + + var queue = dispatch_get_global_queue(qos_class_t.QOS_CLASS_DEFAULT, 0); + dispatch_async(queue, function () { + scrubStack(); + __collect(); + __collect(); + }); + + var attempts = 200; + (function poll() { + if (threads.length > 0 || --attempts === 0) { + expect(threads).toEqual([true]); + done(); + return; + } + setTimeout(poll, 10); + })(); + }); + + // An object that first reached JS on a background thread has no tie to the + // runtime's thread, so its release stays with the collection that ran there. + it("releases a background-born object where the background collection runs", function (done) { + var threads = []; + var DeallocThread = TNSApi.extend({ + methodCalledInDealloc: function () { + threads.push(NSThread.isMainThread); + } + }, { name: "TNSApiDeallocBackgroundThread" }); + + var queue = dispatch_get_global_queue(qos_class_t.QOS_CLASS_DEFAULT, 0); + dispatch_async(queue, function () { + (function () { + DeallocThread.alloc().init(); + })(); + scrubStack(); + __collect(); + __collect(); + }); + + var attempts = 200; + (function poll() { + if (threads.length > 0 || --attempts === 0) { + expect(threads).toEqual([false]); + done(); + return; + } + setTimeout(poll, 10); + })(); + }); + // A GcProtected (natively retained) instance is resurrected by its // finalizer, but anything reachable only through it is queued in the same // GC and disposed — the resurrected parent then holds "husks" whose diff --git a/docs/knowledge/v8-resurrecting-finalizers.md b/docs/knowledge/v8-resurrecting-finalizers.md index ece736d69..233749e91 100644 --- a/docs/knowledge/v8-resurrecting-finalizers.md +++ b/docs/knowledge/v8-resurrecting-finalizers.md @@ -129,6 +129,24 @@ global handles via `IterateStrongRoots` (`SkipRoot::kWeak`), so pending nodes ar during a nested GC; root *updating* uses `IterateAllRoots`, a single pass over `NORMAL||WEAK`, so a pending node's slot is updated exactly once after evacuation. +## Which thread releases the native object + +Finalizers run on whichever thread triggered the collection, and that can be any thread holding +the isolate's Locker — a JS function dispatched to a background queue included. An object that +first reached JS on the runtime's thread (`ObjCDataWrapper`/`BlockWrapper::BornOnRuntimeThread`, +recorded when the wrapper is built) is released on that thread: off it, `ObjectManager` queues +the native release (`[object release]`, `Block_release`) and posts one event loop task to drain +the queue; the JS side is disposed immediately either way. The same applies to +`__releaseNativeCounterpart` called from such a thread: the wrapper is retired at once, the +object a loop turn later. Objects that first reached JS on another thread are released where the +collection runs, as are collection adapters, whose `-dealloc` retires the wrapper. + +The queue needs no synchronization of its own: finalizers, `__releaseNativeCounterpart`, the +drain task, wrapper creation and teardown all hold the Locker. A new wrapper built for an object +whose release is still queued takes that release over (keeping the retain counts the extended +classes' swizzle reads exact). Teardown drains the queue inline, since the event loop has stopped +by then. For a worker, the runtime's thread is the worker's own thread, not the main thread. + ## Deliberate deviations from upstream's original - **No `PENDING` state, no `NEAR_DEATH` for finalizers.** 14.9's `NodeState` is 2 bits with all From af2d1c6625b4d9915a67f44f9bf69088b6b7ffe5 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 15 Nov 2026 23:35:20 -0300 Subject: [PATCH 2/4] fix(runtime): protect a re-wrapped instance only when its class unprotects again A wrapper that takes over a waiting release catches up on the protection a native retain would have given it. That protection is undone by the swizzled -release, which only __extends classes carry; an .extend() class conforms to TNSDerivedClass too, so its instance stayed protected and was never collected. The check now asks for the swizzle itself, through the superclass chain, so an observed instance of such a class is covered as well. --- NativeScript/runtime/Caches.h | 5 +- NativeScript/runtime/ClassBuilder.h | 3 + NativeScript/runtime/ClassBuilder.mm | 10 +++ NativeScript/runtime/DataWrapper.h | 8 +- NativeScript/runtime/ObjectManager.h | 7 +- NativeScript/runtime/ObjectManager.mm | 11 ++- NativeScript/runtime/TNSDerivedClass.h | 7 ++ TestRunner/app/tests/GCFinalizerTests.js | 95 +++++++++++++++++++- docs/knowledge/v8-resurrecting-finalizers.md | 7 ++ 9 files changed, 134 insertions(+), 19 deletions(-) diff --git a/NativeScript/runtime/Caches.h b/NativeScript/runtime/Caches.h index 9bee6766b..194e3d026 100644 --- a/NativeScript/runtime/Caches.h +++ b/NativeScript/runtime/Caches.h @@ -118,8 +118,9 @@ class Caches { return cache->GetOrCreateState(); } - // Teardown only: the existing state, even after InvalidateIsolate, for a - // subsystem that must finish work its state still holds. Never creates. + // The existing state, even after InvalidateIsolate, for a subsystem that + // must finish work its state still holds. Never creates, so a state made on + // the isolate's thread can be read from any thread holding the Locker. template static T* ExistingStateFor(v8::Isolate* isolate) { auto raw = isolate->GetData(0); diff --git a/NativeScript/runtime/ClassBuilder.h b/NativeScript/runtime/ClassBuilder.h index a705e4b96..92adb1a44 100644 --- a/NativeScript/runtime/ClassBuilder.h +++ b/NativeScript/runtime/ClassBuilder.h @@ -42,6 +42,9 @@ class ClassBuilder { const char* fallback); // `klass` or its nearest superclass not defined from JS. static Class FindNativeClass(Class klass); + // Whether instances of `klass` run the -retain/-release pair that protects + // and unprotects their wrapper, inherited ones included. + static bool TracksNativeRetains(Class klass); // The implementation of `method` from FindNativeClass(klass). static IMP FindNotOverridenMethod(Class klass, SEL method); // Whether `klass`, not one of its superclasses, implements `selector`. diff --git a/NativeScript/runtime/ClassBuilder.mm b/NativeScript/runtime/ClassBuilder.mm index 7c84f364f..adc0b7575 100644 --- a/NativeScript/runtime/ClassBuilder.mm +++ b/NativeScript/runtime/ClassBuilder.mm @@ -405,6 +405,7 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { release(self, @selector(release)); }); class_addMethod(extendedClass, @selector(release), newRelease, "v@:"); + class_addProtocol(extendedClass, @protocol(TNSRetainTrackedClass)); info.GetReturnValue().SetUndefined(); }).ToLocalChecked(); @@ -1101,6 +1102,15 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { return klass; } +bool ClassBuilder::TracksNativeRetains(Class klass) { + for (; klass != nil; klass = class_getSuperclass(klass)) { + if (class_conformsToProtocol(klass, @protocol(TNSRetainTrackedClass))) { + return true; + } + } + return false; +} + IMP ClassBuilder::FindNotOverridenMethod(Class klass, SEL method) { return class_getMethodImplementation(FindNativeClass(klass), method); } diff --git a/NativeScript/runtime/DataWrapper.h b/NativeScript/runtime/DataWrapper.h index 22172a9d1..e90d38d67 100644 --- a/NativeScript/runtime/DataWrapper.h +++ b/NativeScript/runtime/DataWrapper.h @@ -399,10 +399,10 @@ class UnmanagedTypeWrapper : public BaseDataWrapper { class ObjCDataWrapper : public BaseDataWrapper { public: ObjCDataWrapper(id data, const TypeEncoding* typeEncoding = nullptr) - : data_(data), + : bornOnRuntimeThread_(OnRuntimeThreadOf(v8::Isolate::TryGetCurrent())), + data_(data), typeEncoding_(typeEncoding), - klass_(object_getClass(data)), - bornOnRuntimeThread_(OnRuntimeThreadOf(v8::Isolate::TryGetCurrent())) {} + klass_(object_getClass(data)) {} const WrapperType Type() { return WrapperType::ObjCObject; } @@ -442,11 +442,11 @@ class ObjCDataWrapper : public BaseDataWrapper { private: bool adapterClaim_ = false; bool borrowed_ = false; + bool bornOnRuntimeThread_; ObjectWeakCallbackState* ownershipState_ = nullptr; id data_; const tns::TypeEncoding* typeEncoding_; Class klass_; - bool bornOnRuntimeThread_; }; class ObjCClassWrapper : public BaseDataWrapper { diff --git a/NativeScript/runtime/ObjectManager.h b/NativeScript/runtime/ObjectManager.h index c1ff207e1..1d8fc9a7a 100644 --- a/NativeScript/runtime/ObjectManager.h +++ b/NativeScript/runtime/ObjectManager.h @@ -70,9 +70,10 @@ class ObjectManager { // release over as its own retain instead of retaining again; returns whether // it did. Once the entry's retain is settled, call ProtectIfNativelyRetained. static bool TakeDeferredRelease(v8::Isolate* isolate, id obj); - // An extended class protects its wrapper when native code first retains the - // object past the runtime's own retain. A native retain made while a release - // waited found no wrapper to protect; this catches up. + // A class that tracks native retains (ClassBuilder::TracksNativeRetains) + // protects its wrapper when native code first retains the object past the + // runtime's own retain. A native retain made while a release waited found no + // wrapper to protect; this catches up. static void ProtectIfNativelyRetained(id obj, ObjCDataWrapper* wrapper); private: diff --git a/NativeScript/runtime/ObjectManager.mm b/NativeScript/runtime/ObjectManager.mm index a708f5fe8..f4fe98c06 100644 --- a/NativeScript/runtime/ObjectManager.mm +++ b/NativeScript/runtime/ObjectManager.mm @@ -12,7 +12,6 @@ #include "EventLoop.h" #include "Helpers.h" #include "Runtime.h" -#include "TNSDerivedClass.h" using namespace v8; using namespace std; @@ -112,9 +111,9 @@ void UnlinkRegistered(ObjectWeakCallbackState* state) { // Objects first wrapped on another thread are still released where the // collection runs. // -// Every access holds the isolate's Locker: finalizers and -// __releaseNativeCounterpart on any thread, and on the runtime's thread the -// drain task, wrapper creation and teardown. So no other synchronization. +// Every access holds the isolate's Locker: finalizers, +// __releaseNativeCounterpart and wrapper creation on any thread, and on the +// runtime's thread the drain task and teardown. So no other synchronization. struct DeferredReleases { // Object -> releases it is owed. An object stays alive while it is owed one, // so its address cannot be reused by another object meanwhile. @@ -380,8 +379,8 @@ void DisposeHandle(v8::Isolate* isolate, } void ObjectManager::ProtectIfNativelyRetained(id obj, ObjCDataWrapper* wrapper) { - if (class_conformsToProtocol(object_getClass(obj), @protocol(TNSDerivedClass)) && - [obj retainCount] > 1) { + // Only a class whose -release unprotects again may be protected here. + if (ClassBuilder::TracksNativeRetains(object_getClass(obj)) && [obj retainCount] > 1) { wrapper->GcProtect(); } } diff --git a/NativeScript/runtime/TNSDerivedClass.h b/NativeScript/runtime/TNSDerivedClass.h index 9b8f5b334..63f92e1c4 100644 --- a/NativeScript/runtime/TNSDerivedClass.h +++ b/NativeScript/runtime/TNSDerivedClass.h @@ -5,4 +5,11 @@ @end +// Adopted by a derived class whose -retain and -release tell its instance's +// wrapper when native code starts and stops owning the object. Subclasses +// inherit those methods but not the conformance. +@protocol TNSRetainTrackedClass + +@end + #endif /* TNSDerivedClass_h */ diff --git a/TestRunner/app/tests/GCFinalizerTests.js b/TestRunner/app/tests/GCFinalizerTests.js index a40a61ad5..cd65b42b5 100644 --- a/TestRunner/app/tests/GCFinalizerTests.js +++ b/TestRunner/app/tests/GCFinalizerTests.js @@ -46,21 +46,25 @@ describe("GC finalizer callbacks", function () { } }, { name: "TNSApiDeallocThread" }); - // Owned only through its wrapper, so its finalizer releases it. - (function () { - DeallocThread.alloc().init(); - })(); + // Owned only through its wrapper, so its finalizer releases it. Held + // until the background block, so no collection on the main thread + // gets to it first. + var keep = DeallocThread.alloc().init(); + var deallocsInBlock = -1; var queue = dispatch_get_global_queue(qos_class_t.QOS_CLASS_DEFAULT, 0); dispatch_async(queue, function () { + keep = null; scrubStack(); __collect(); __collect(); + deallocsInBlock = threads.length; }); var attempts = 200; (function poll() { if (threads.length > 0 || --attempts === 0) { + expect(deallocsInBlock).toBe(0); expect(threads).toEqual([true]); done(); return; @@ -100,6 +104,89 @@ describe("GC finalizer callbacks", function () { })(); }); + // A wrapper built for an object whose release still waits for the + // runtime's thread adopts that release as its own retain. The block below + // holds the Locker throughout, so the release cannot run in between. + [ + { + suffix: " (extend)", + // No retain/release swizzle: natively held instances are not kept. + keepsWrapper: false, + define: function (onDealloc) { + return TNSApi.extend({ methodCalledInDealloc: onDealloc }, { name: "TNSApiReleaseTakeover" }); + } + }, + { + suffix: " (__extends)", + keepsWrapper: true, + define: function (onDealloc) { + return (function (_super) { + __extends(TNSApiReleaseTakeoverTS, _super); + function TNSApiReleaseTakeoverTS() { + return (_super !== null && _super.apply(this, arguments)) || this; + } + TNSApiReleaseTakeoverTS.prototype.methodCalledInDealloc = onDealloc; + return TNSApiReleaseTakeoverTS; + })(TNSApi); + } + } + ].forEach(function (variant) { + it("hands a waiting release to the wrapper that replaces it" + variant.suffix, function (done) { + var threads = []; + var Klass = variant.define(function () { + threads.push(NSThread.isMainThread); + }); + + var holder = NSMutableArray.alloc().init(); + (function () { + holder.addObject(Klass.alloc().init()); + })(); + + var retainCount = -1; + var queue = dispatch_get_global_queue(qos_class_t.QOS_CLASS_DEFAULT, 0); + dispatch_async(queue, function () { + __releaseNativeCounterpart(holder.objectAtIndex(0)); + var again = holder.objectAtIndex(0); + again.marker = "kept"; + // The holder's reference and the adopted one. + retainCount = again.retainCount(); + }); + + function collectAndWait(rounds, callback) { + scrubStack(); + __collect(); + __collect(); + setTimeout(function () { + if (rounds > 1) { + collectAndWait(rounds - 1, callback); + } else { + callback(); + } + }, 10); + } + + var attempts = 200; + (function poll() { + if (retainCount === -1 && --attempts > 0) { + setTimeout(poll, 10); + return; + } + expect(retainCount).toBe(2); + collectAndWait(2, function () { + expect(threads).toEqual([]); + if (variant.keepsWrapper) { + expect(holder.objectAtIndex(0).marker).toBe("kept"); + } + holder.removeAllObjects(); + collectAndWait(3, function () { + expect(threads).toEqual([true]); + done(); + }); + }); + })(); + }); + }); + // A GcProtected (natively retained) instance is resurrected by its // finalizer, but anything reachable only through it is queued in the same // GC and disposed — the resurrected parent then holds "husks" whose diff --git a/docs/knowledge/v8-resurrecting-finalizers.md b/docs/knowledge/v8-resurrecting-finalizers.md index 233749e91..799831f88 100644 --- a/docs/knowledge/v8-resurrecting-finalizers.md +++ b/docs/knowledge/v8-resurrecting-finalizers.md @@ -147,6 +147,13 @@ whose release is still queued takes that release over (keeping the retain counts classes' swizzle reads exact). Teardown drains the queue inline, since the event loop has stopped by then. For a worker, the runtime's thread is the worker's own thread, not the main thread. +While a release is queued the object is alive without a wrapper, where an inline release would +have deallocated it and zeroed the weak references to it. A native callback reaching it in that +window (a delegate method through a weak reference) builds a new wrapper, which takes the queued +release over: the JS override runs on a blank `this`, without the state the collected wrapper +held, and the object then lives as long as that new wrapper. Only an object that nothing but its +wrapper owned, collected off the runtime's thread, has this window. + ## Deliberate deviations from upstream's original - **No `PENDING` state, no `NEAR_DEATH` for finalizers.** 14.9's `NodeState` is 2 bits with all From 85fa00fa4c1121ddab169982973a60ac74597769 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Mon, 16 Nov 2026 00:34:17 -0300 Subject: [PATCH 3/4] fix(runtime): ask the isolate whose swizzle it is before protecting a re-wrapped instance The -retain/-release pair of an __extends class looks its instance's wrapper up in the isolate that defined the class only. A wrapper another isolate made for the same instance and protected on takeover would never be unprotected, so the classes carrying the pair are kept per isolate in place of a marker protocol. --- NativeScript/runtime/ArgConverter.mm | 4 +- NativeScript/runtime/ClassBuilder.h | 7 ++-- NativeScript/runtime/ClassBuilder.mm | 21 ++++++++-- NativeScript/runtime/ObjectManager.h | 7 ++-- NativeScript/runtime/ObjectManager.mm | 16 ++++---- NativeScript/runtime/TNSDerivedClass.h | 7 ---- TestRunner/app/tests/GCFinalizerTests.js | 49 +++++++++++++++++------- 7 files changed, 71 insertions(+), 40 deletions(-) diff --git a/NativeScript/runtime/ArgConverter.mm b/NativeScript/runtime/ArgConverter.mm index 9fb834292..49053bf6a 100644 --- a/NativeScript/runtime/ArgConverter.mm +++ b/NativeScript/runtime/ArgConverter.mm @@ -756,7 +756,7 @@ bool IsKVOSubclassOf(Class klass, Class base) { // Only releases of objects that first reached JS on the runtime's // thread are ever queued. wrapper->SetBornOnRuntimeThread(); - ObjectManager::ProtectIfNativelyRetained(result, wrapper); + ObjectManager::ProtectIfNativelyRetained(isolate, result, wrapper); } ExternalMemory::ChargeEstimatedSize(isolate, thiz); } @@ -1032,7 +1032,7 @@ bool IsKVOSubclassOf(Class klass, Class base) { } else if (wrapper->Type() == WrapperType::ObjCObject) { ObjCDataWrapper* objcWrapper = static_cast(wrapper); objcWrapper->SetBornOnRuntimeThread(); - ObjectManager::ProtectIfNativelyRetained(target, objcWrapper); + ObjectManager::ProtectIfNativelyRetained(isolate, target, objcWrapper); } } } else { diff --git a/NativeScript/runtime/ClassBuilder.h b/NativeScript/runtime/ClassBuilder.h index 92adb1a44..8ff5530f9 100644 --- a/NativeScript/runtime/ClassBuilder.h +++ b/NativeScript/runtime/ClassBuilder.h @@ -42,9 +42,10 @@ class ClassBuilder { const char* fallback); // `klass` or its nearest superclass not defined from JS. static Class FindNativeClass(Class klass); - // Whether instances of `klass` run the -retain/-release pair that protects - // and unprotects their wrapper, inherited ones included. - static bool TracksNativeRetains(Class klass); + // Whether instances of `klass` run a -retain/-release pair that protects + // and unprotects their wrapper in `isolate`: one this isolate installed, on + // `klass` or a class it inherits from. + static bool TracksNativeRetains(v8::Isolate* isolate, Class klass); // The implementation of `method` from FindNativeClass(klass). static IMP FindNotOverridenMethod(Class klass, SEL method); // Whether `klass`, not one of its superclasses, implements `selector`. diff --git a/NativeScript/runtime/ClassBuilder.mm b/NativeScript/runtime/ClassBuilder.mm index adc0b7575..05af7a68e 100644 --- a/NativeScript/runtime/ClassBuilder.mm +++ b/NativeScript/runtime/ClassBuilder.mm @@ -2,6 +2,7 @@ #include #include #include +#include #include "ArgConverter.h" #include "BuiltinLoader.h" #include "Caches.h" @@ -29,6 +30,14 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { name += std::to_string(isolateId); } } + +// The classes an isolate gave the -retain/-release pair that protects and +// unprotects an instance's wrapper. The pair looks the wrapper up in that +// isolate only, so another isolate's wrapper of the same instance is never +// unprotected by it. +struct RetainTrackedClasses { + std::unordered_set classes; +}; } // namespace Local ClassBuilder::GetExtendFunction(Isolate* isolate, @@ -405,7 +414,9 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { release(self, @selector(release)); }); class_addMethod(extendedClass, @selector(release), newRelease, "v@:"); - class_addProtocol(extendedClass, @protocol(TNSRetainTrackedClass)); + if (auto* tracked = Caches::StateFor(isolate)) { + tracked->classes.insert((__bridge void*)extendedClass); + } info.GetReturnValue().SetUndefined(); }).ToLocalChecked(); @@ -1102,9 +1113,13 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { return klass; } -bool ClassBuilder::TracksNativeRetains(Class klass) { +bool ClassBuilder::TracksNativeRetains(Isolate* isolate, Class klass) { + RetainTrackedClasses* tracked = Caches::ExistingStateFor(isolate); + if (tracked == nullptr || tracked->classes.empty()) { + return false; + } for (; klass != nil; klass = class_getSuperclass(klass)) { - if (class_conformsToProtocol(klass, @protocol(TNSRetainTrackedClass))) { + if (tracked->classes.count((__bridge void*)klass) != 0) { return true; } } diff --git a/NativeScript/runtime/ObjectManager.h b/NativeScript/runtime/ObjectManager.h index 1d8fc9a7a..d00bce017 100644 --- a/NativeScript/runtime/ObjectManager.h +++ b/NativeScript/runtime/ObjectManager.h @@ -68,13 +68,14 @@ class ObjectManager { // the native releases it causes are handed to the runtime's thread. A new // Instances entry for an object whose release is still waiting takes that // release over as its own retain instead of retaining again; returns whether - // it did. Once the entry's retain is settled, call ProtectIfNativelyRetained. + // it did. Once the entry holds its reference, call ProtectIfNativelyRetained. static bool TakeDeferredRelease(v8::Isolate* isolate, id obj); // A class that tracks native retains (ClassBuilder::TracksNativeRetains) // protects its wrapper when native code first retains the object past the // runtime's own retain. A native retain made while a release waited found no - // wrapper to protect; this catches up. - static void ProtectIfNativelyRetained(id obj, ObjCDataWrapper* wrapper); + // wrapper to protect; this catches up. A surplus reference the caller drops + // afterwards goes through -release, which unprotects again. + static void ProtectIfNativelyRetained(v8::Isolate* isolate, id obj, ObjCDataWrapper* wrapper); private: static void ReleaseNativeCounterpartCallback( diff --git a/NativeScript/runtime/ObjectManager.mm b/NativeScript/runtime/ObjectManager.mm index f4fe98c06..6fe58d8d0 100644 --- a/NativeScript/runtime/ObjectManager.mm +++ b/NativeScript/runtime/ObjectManager.mm @@ -8,8 +8,8 @@ #include "ClassBuilder.h" #include "Constants.h" #include "DataWrapper.h" -#include "FFICall.h" #include "EventLoop.h" +#include "FFICall.h" #include "Helpers.h" #include "Runtime.h" @@ -278,8 +278,7 @@ void DisposeHandle(v8::Isolate* isolate, state = next; } - // The walk's own releases are inline on the runtime's thread; this catches - // any made from another. + // A walk that runs off the runtime's thread queues its own releases. if (deferred != nullptr) { DrainDeferredReleases(deferred); } @@ -378,9 +377,9 @@ void DisposeHandle(v8::Isolate* isolate, return true; } -void ObjectManager::ProtectIfNativelyRetained(id obj, ObjCDataWrapper* wrapper) { - // Only a class whose -release unprotects again may be protected here. - if (ClassBuilder::TracksNativeRetains(object_getClass(obj)) && [obj retainCount] > 1) { +void ObjectManager::ProtectIfNativelyRetained(Isolate* isolate, id obj, ObjCDataWrapper* wrapper) { + // Only a wrapper the class's -release unprotects again may be protected. + if (ClassBuilder::TracksNativeRetains(isolate, object_getClass(obj)) && [obj retainCount] > 1) { wrapper->GcProtect(); } } @@ -635,8 +634,9 @@ void DisposeHandle(v8::Isolate* isolate, // Release the runtime's strong reference (taken when the object was first // wrapped or adopted from an alloc/new/copy return). For instances solely - // owned by JS this deallocates immediately; for shared natives (e.g. an - // NSNotificationCenter observer token) the remaining owners keep it alive. + // owned by JS this deallocates them, on the runtime's thread (at once when + // called there); for shared natives (e.g. an NSNotificationCenter observer + // token) the remaining owners keep it alive. // Calling [data dealloc] here, as this used to do, destroyed objects that // were still referenced elsewhere and caused use-after-free crashes. // Read before the release below: an adapter claim's -dealloc frees the diff --git a/NativeScript/runtime/TNSDerivedClass.h b/NativeScript/runtime/TNSDerivedClass.h index 63f92e1c4..9b8f5b334 100644 --- a/NativeScript/runtime/TNSDerivedClass.h +++ b/NativeScript/runtime/TNSDerivedClass.h @@ -5,11 +5,4 @@ @end -// Adopted by a derived class whose -retain and -release tell its instance's -// wrapper when native code starts and stops owning the object. Subclasses -// inherit those methods but not the conformance. -@protocol TNSRetainTrackedClass - -@end - #endif /* TNSDerivedClass_h */ diff --git a/TestRunner/app/tests/GCFinalizerTests.js b/TestRunner/app/tests/GCFinalizerTests.js index cd65b42b5..8e252ff34 100644 --- a/TestRunner/app/tests/GCFinalizerTests.js +++ b/TestRunner/app/tests/GCFinalizerTests.js @@ -107,11 +107,23 @@ describe("GC finalizer callbacks", function () { // A wrapper built for an object whose release still waits for the // runtime's thread adopts that release as its own retain. The block below // holds the Locker throughout, so the release cannot run in between. + function defineTakeoverWithExtends(onDealloc) { + return (function (_super) { + __extends(TNSApiReleaseTakeoverTS, _super); + function TNSApiReleaseTakeoverTS() { + return (_super !== null && _super.apply(this, arguments)) || this; + } + TNSApiReleaseTakeoverTS.prototype.methodCalledInDealloc = onDealloc; + return TNSApiReleaseTakeoverTS; + })(TNSApi); + } + [ { suffix: " (extend)", // No retain/release swizzle: natively held instances are not kept. keepsWrapper: false, + observed: false, define: function (onDealloc) { return TNSApi.extend({ methodCalledInDealloc: onDealloc }, { name: "TNSApiReleaseTakeover" }); } @@ -119,16 +131,16 @@ describe("GC finalizer callbacks", function () { { suffix: " (__extends)", keepsWrapper: true, - define: function (onDealloc) { - return (function (_super) { - __extends(TNSApiReleaseTakeoverTS, _super); - function TNSApiReleaseTakeoverTS() { - return (_super !== null && _super.apply(this, arguments)) || this; - } - TNSApiReleaseTakeoverTS.prototype.methodCalledInDealloc = onDealloc; - return TNSApiReleaseTakeoverTS; - })(TNSApi); - } + observed: false, + define: defineTakeoverWithExtends + }, + { + // The instance's class is then the NSKVONotifying_ subclass of + // the JS class. + suffix: " (__extends, key-value observed)", + keepsWrapper: true, + observed: true, + define: defineTakeoverWithExtends } ].forEach(function (variant) { it("hands a waiting release to the wrapper that replaces it" + variant.suffix, function (done) { @@ -137,15 +149,21 @@ describe("GC finalizer callbacks", function () { threads.push(NSThread.isMainThread); }); + // Held until the background block, so its wrapper is still the + // main thread's when the block releases it. + var first = Klass.alloc().init(); + var observer = NSObject.alloc().init(); + if (variant.observed) { + first.addObserverForKeyPathOptionsContext(observer, "strokeColor", 0, null); + } var holder = NSMutableArray.alloc().init(); - (function () { - holder.addObject(Klass.alloc().init()); - })(); + holder.addObject(first); var retainCount = -1; var queue = dispatch_get_global_queue(qos_class_t.QOS_CLASS_DEFAULT, 0); dispatch_async(queue, function () { - __releaseNativeCounterpart(holder.objectAtIndex(0)); + __releaseNativeCounterpart(first); + first = null; var again = holder.objectAtIndex(0); again.marker = "kept"; // The holder's reference and the adopted one. @@ -177,6 +195,9 @@ describe("GC finalizer callbacks", function () { if (variant.keepsWrapper) { expect(holder.objectAtIndex(0).marker).toBe("kept"); } + if (variant.observed) { + holder.objectAtIndex(0).removeObserverForKeyPath(observer, "strokeColor"); + } holder.removeAllObjects(); collectAndWait(3, function () { expect(threads).toEqual([true]); From acdfe8de41aa31c4af96877150dfa79f07d6b950 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Mon, 16 Nov 2026 01:20:12 -0300 Subject: [PATCH 4/4] fix(runtime): keep waiting releases adoptable while their batch drains The drain took the whole batch out of the queue before releasing anything. A release that ran JS (a -dealloc implemented in JS) could wrap an object whose release was later in the batch: the takeover missed it, the wrapper retained on top of the waiting release, and neither the retain nor the later release crossed the count at which the swizzle protects, so a natively held instance lost its wrapper at the next collection. One release leaves the queue at a time now. --- NativeScript/runtime/ObjectManager.mm | 22 ++++--- TestRunner/app/tests/GCFinalizerTests.js | 83 ++++++++++++++++++++---- 2 files changed, 83 insertions(+), 22 deletions(-) diff --git a/NativeScript/runtime/ObjectManager.mm b/NativeScript/runtime/ObjectManager.mm index 6fe58d8d0..edc901e95 100644 --- a/NativeScript/runtime/ObjectManager.mm +++ b/NativeScript/runtime/ObjectManager.mm @@ -122,19 +122,23 @@ void UnlinkRegistered(ObjectWeakCallbackState* state) { bool drainPosted = false; }; +// A release can run JS (a -dealloc implemented in JS) that wraps an object +// whose own release still waits, or that reaches this drain again. So one +// release leaves the queue at a time, the rest stay there for +// TakeDeferredRelease, and nothing is held across a release. void DrainDeferredReleases(DeferredReleases* pending) { - std::unordered_map objects; - std::vector blocks; - objects.swap(pending->objects); - blocks.swap(pending->blocks); pending->drainPosted = false; - for (const auto& entry : objects) { - id obj = (__bridge id)entry.first; - for (unsigned i = 0; i < entry.second; i++) { - [obj release]; + while (!pending->objects.empty()) { + auto it = pending->objects.begin(); + id obj = (__bridge id)it->first; + if (--it->second == 0) { + pending->objects.erase(it); } + [obj release]; } - for (const void* block : blocks) { + while (!pending->blocks.empty()) { + const void* block = pending->blocks.back(); + pending->blocks.pop_back(); Block_release(block); } } diff --git a/TestRunner/app/tests/GCFinalizerTests.js b/TestRunner/app/tests/GCFinalizerTests.js index 8e252ff34..8c5f673b7 100644 --- a/TestRunner/app/tests/GCFinalizerTests.js +++ b/TestRunner/app/tests/GCFinalizerTests.js @@ -118,6 +118,19 @@ describe("GC finalizer callbacks", function () { })(TNSApi); } + function collectAndWait(rounds, callback) { + scrubStack(); + __collect(); + __collect(); + setTimeout(function () { + if (rounds > 1) { + collectAndWait(rounds - 1, callback); + } else { + callback(); + } + }, 10); + } + [ { suffix: " (extend)", @@ -170,19 +183,6 @@ describe("GC finalizer callbacks", function () { retainCount = again.retainCount(); }); - function collectAndWait(rounds, callback) { - scrubStack(); - __collect(); - __collect(); - setTimeout(function () { - if (rounds > 1) { - collectAndWait(rounds - 1, callback); - } else { - callback(); - } - }, 10); - } - var attempts = 200; (function poll() { if (retainCount === -1 && --attempts > 0) { @@ -208,6 +208,63 @@ describe("GC finalizer callbacks", function () { }); }); + // Releases wait in batches, and one of them can run JS (a -dealloc + // implemented in JS) that wraps an object whose own release comes later + // in the same batch. The order within a batch is unspecified, so the + // instance whose -dealloc does the wrapping is rarely the last one. + it("lets a wrapper adopt a release that waits behind the one running JS", function (done) { + var Held = defineTakeoverWithExtends(function () {}); + var count = 16; + var holder = NSMutableArray.alloc().init(); + var held = []; + for (var i = 0; i < count; i++) { + var instance = Held.alloc().init(); + held.push(instance); + holder.addObject(instance); + } + + var wrapped = 0; + var Trigger = TNSApi.extend({ + methodCalledInDealloc: function () { + for (var j = 0; j < count; j++) { + holder.objectAtIndex(j).marker = j; + wrapped++; + } + } + }, { name: "TNSApiReleaseBatchTrigger" }); + var trigger = Trigger.alloc().init(); + + var queue = dispatch_get_global_queue(qos_class_t.QOS_CLASS_DEFAULT, 0); + dispatch_async(queue, function () { + for (var k = 0; k < count; k++) { + __releaseNativeCounterpart(held[k]); + } + held = null; + __releaseNativeCounterpart(trigger); + trigger = null; + }); + + var attempts = 200; + (function poll() { + if (wrapped === 0 && --attempts > 0) { + setTimeout(poll, 10); + return; + } + expect(wrapped).toBe(count); + collectAndWait(2, function () { + var markers = []; + var expected = []; + for (var m = 0; m < count; m++) { + markers.push(holder.objectAtIndex(m).marker); + expected.push(m); + } + expect(markers).toEqual(expected); + holder.removeAllObjects(); + done(); + }); + })(); + }); + // A GcProtected (natively retained) instance is resurrected by its // finalizer, but anything reachable only through it is queued in the same // GC and disposed — the resurrected parent then holds "husks" whose