diff --git a/NativeScript/runtime/ArgConverter.mm b/NativeScript/runtime/ArgConverter.mm index 8e50b0783..49053bf6a 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(isolate, 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(isolate, target, objcWrapper); + } } } else { tns::SetValue(isolate, receiver, wrapper); diff --git a/NativeScript/runtime/Caches.h b/NativeScript/runtime/Caches.h index 36f1812e5..194e3d026 100644 --- a/NativeScript/runtime/Caches.h +++ b/NativeScript/runtime/Caches.h @@ -118,6 +118,23 @@ class Caches { return cache->GetOrCreateState(); } + // 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); + 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/ClassBuilder.h b/NativeScript/runtime/ClassBuilder.h index a705e4b96..8ff5530f9 100644 --- a/NativeScript/runtime/ClassBuilder.h +++ b/NativeScript/runtime/ClassBuilder.h @@ -42,6 +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 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 7c84f364f..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,6 +414,9 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { release(self, @selector(release)); }); class_addMethod(extendedClass, @selector(release), newRelease, "v@:"); + if (auto* tracked = Caches::StateFor(isolate)) { + tracked->classes.insert((__bridge void*)extendedClass); + } info.GetReturnValue().SetUndefined(); }).ToLocalChecked(); @@ -1101,6 +1113,19 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { return 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 (tracked->classes.count((__bridge void*)klass) != 0) { + 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 7b2b2c591..e90d38d67 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; @@ -394,7 +399,8 @@ 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)) {} @@ -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 @@ -431,6 +442,7 @@ class ObjCDataWrapper : public BaseDataWrapper { private: bool adapterClaim_ = false; bool borrowed_ = false; + bool bornOnRuntimeThread_; ObjectWeakCallbackState* ownershipState_ = nullptr; id data_; const tns::TypeEncoding* typeEncoding_; @@ -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..d00bce017 100644 --- a/NativeScript/runtime/ObjectManager.h +++ b/NativeScript/runtime/ObjectManager.h @@ -64,6 +64,19 @@ 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 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. 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( const v8::FunctionCallbackInfo& info); diff --git a/NativeScript/runtime/ObjectManager.mm b/NativeScript/runtime/ObjectManager.mm index a433c64c0..edc901e95 100644 --- a/NativeScript/runtime/ObjectManager.mm +++ b/NativeScript/runtime/ObjectManager.mm @@ -3,12 +3,15 @@ #include #include #include +#include #include "Caches.h" #include "ClassBuilder.h" #include "Constants.h" #include "DataWrapper.h" +#include "EventLoop.h" #include "FFICall.h" #include "Helpers.h" +#include "Runtime.h" using namespace v8; using namespace std; @@ -68,14 +71,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 +103,103 @@ 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, +// __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. + std::unordered_map objects; + std::vector blocks; + 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) { + pending->drainPosted = false; + 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]; + } + while (!pending->blocks.empty()) { + const void* block = pending->blocks.back(); + pending->blocks.pop_back(); + 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 +250,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 +282,11 @@ void DisposeHandle(v8::Isolate* isolate, state = next; } + // A walk that runs off the runtime's thread queues its own releases. + if (deferred != nullptr) { + DrainDeferredReleases(deferred); + } + DisposeHandleMap(isolate, cache->CtorFuncs); DisposeHandleMap(isolate, cache->ProtocolCtorFuncs); DisposeHandleMap(isolate, cache->CFunctions); @@ -265,6 +366,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(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(); + } +} + bool ObjectManager::DisposeValue(Isolate* isolate, Local value, bool isFinalDisposal) { if (value.IsEmpty() || value->IsNullOrUndefined() || !value->IsObject()) { return true; @@ -320,7 +443,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 +466,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: { @@ -509,15 +638,20 @@ 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 // 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..8c5f673b7 100644 --- a/TestRunner/app/tests/GCFinalizerTests.js +++ b/TestRunner/app/tests/GCFinalizerTests.js @@ -35,6 +35,236 @@ 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. 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; + } + 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 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); + } + + function collectAndWait(rounds, callback) { + scrubStack(); + __collect(); + __collect(); + setTimeout(function () { + if (rounds > 1) { + collectAndWait(rounds - 1, callback); + } else { + callback(); + } + }, 10); + } + + [ + { + 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" }); + } + }, + { + suffix: " (__extends)", + keepsWrapper: true, + 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) { + var threads = []; + var Klass = variant.define(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(); + holder.addObject(first); + + var retainCount = -1; + var queue = dispatch_get_global_queue(qos_class_t.QOS_CLASS_DEFAULT, 0); + dispatch_async(queue, function () { + __releaseNativeCounterpart(first); + first = null; + var again = holder.objectAtIndex(0); + again.marker = "kept"; + // The holder's reference and the adopted one. + retainCount = again.retainCount(); + }); + + 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"); + } + if (variant.observed) { + holder.objectAtIndex(0).removeObserverForKeyPath(observer, "strokeColor"); + } + holder.removeAllObjects(); + collectAndWait(3, function () { + expect(threads).toEqual([true]); + done(); + }); + }); + })(); + }); + }); + + // 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 diff --git a/docs/knowledge/v8-resurrecting-finalizers.md b/docs/knowledge/v8-resurrecting-finalizers.md index ece736d69..799831f88 100644 --- a/docs/knowledge/v8-resurrecting-finalizers.md +++ b/docs/knowledge/v8-resurrecting-finalizers.md @@ -129,6 +129,31 @@ 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. + +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