33#include < CoreFoundation/CoreFoundation.h>
44#include < sstream>
55#include < unordered_map>
6+ #include < vector>
67#include " Caches.h"
78#include " ClassBuilder.h"
89#include " Constants.h"
910#include " DataWrapper.h"
1011#include " FFICall.h"
12+ #include " EventLoop.h"
1113#include " Helpers.h"
14+ #include " Runtime.h"
15+ #include " TNSDerivedClass.h"
1216
1317using namespace v8 ;
1418using namespace std ;
@@ -68,14 +72,6 @@ void ReconcileOwnershipBeforeGC(Isolate* isolate, GCType, GCCallbackFlags) {
6872
6973} // namespace
7074
71- void ObjectManager::Init (Isolate* isolate, Local<ObjectTemplate> globalTemplate) {
72- globalTemplate->Set (tns::ToV8String (isolate, " __releaseNativeCounterpart" ),
73- FunctionTemplate::New (isolate, ReleaseNativeCounterpartCallback));
74- isolate->AddGCPrologueCallback (
75- ReconcileOwnershipBeforeGC,
76- static_cast <GCType>(kGCTypeMarkSweepCompact | kGCTypeIncrementalMarking ));
77- }
78-
7975namespace {
8076
8177void LinkRegistered (v8::Isolate* isolate, ObjectWeakCallbackState* state) {
@@ -108,8 +104,99 @@ void UnlinkRegistered(ObjectWeakCallbackState* state) {
108104 state->next_ = nullptr ;
109105}
110106
107+ // The native release of an object that first reached JS on its runtime's
108+ // thread belongs on that thread. JS, and with it a collection and its
109+ // finalizers, can run on any thread that holds the isolate's Locker (a JS
110+ // callback dispatched to a background queue), and a -dealloc that tears down a
111+ // view, a CA transaction or a block capturing one crashes off the main thread.
112+ // Objects first wrapped on another thread are still released where the
113+ // collection runs.
114+ //
115+ // Every access holds the isolate's Locker: finalizers and
116+ // __releaseNativeCounterpart on any thread, and on the runtime's thread the
117+ // drain task, wrapper creation and teardown. So no other synchronization.
118+ struct DeferredReleases {
119+ // Object -> releases it is owed. An object stays alive while it is owed one,
120+ // so its address cannot be reused by another object meanwhile.
121+ std::unordered_map<void *, unsigned > objects;
122+ std::vector<const void *> blocks;
123+ bool drainPosted = false ;
124+ };
125+
126+ void DrainDeferredReleases (DeferredReleases* pending) {
127+ std::unordered_map<void *, unsigned > objects;
128+ std::vector<const void *> blocks;
129+ objects.swap (pending->objects );
130+ blocks.swap (pending->blocks );
131+ pending->drainPosted = false ;
132+ for (const auto & entry : objects) {
133+ id obj = (__bridge id )entry.first ;
134+ for (unsigned i = 0 ; i < entry.second ; i++) {
135+ [obj release ];
136+ }
137+ }
138+ for (const void * block : blocks) {
139+ Block_release (block);
140+ }
141+ }
142+
143+ // The queue to hand a release to, or null when the caller releases inline.
144+ // Created by Init, so a collection on another thread never creates it; read
145+ // without the validity check because a collection can still run on another
146+ // thread between InvalidateIsolate and teardown, which drains it.
147+ DeferredReleases* DeferralQueue (Isolate* isolate, bool bornOnRuntimeThread) {
148+ if (!bornOnRuntimeThread || OnRuntimeThreadOf (isolate)) {
149+ return nullptr ;
150+ }
151+ return Caches::ExistingStateFor<DeferredReleases>(isolate);
152+ }
153+
154+ // One event loop task per batch. If the loop no longer takes work, teardown is
155+ // under way and drains the queue itself.
156+ void PostDrain (Isolate* isolate, DeferredReleases* pending) {
157+ if (pending->drainPosted ) {
158+ return ;
159+ }
160+ Runtime* runtime = Runtime::GetRuntime (isolate);
161+ std::shared_ptr<EventLoop> loop = runtime != nullptr ? runtime->GetEventLoop () : nullptr ;
162+ pending->drainPosted = loop != nullptr && loop->PostInternal ([isolate]() {
163+ if (DeferredReleases* queued = Caches::ExistingStateFor<DeferredReleases>(isolate)) {
164+ DrainDeferredReleases (queued);
165+ }
166+ });
167+ }
168+
169+ void ReleaseOnRuntimeThread (Isolate* isolate, id obj, bool bornOnRuntimeThread) {
170+ DeferredReleases* pending = DeferralQueue (isolate, bornOnRuntimeThread);
171+ if (pending == nullptr ) {
172+ [obj release ];
173+ return ;
174+ }
175+ pending->objects [(__bridge void *)obj]++;
176+ PostDrain (isolate, pending);
177+ }
178+
179+ void BlockReleaseOnRuntimeThread (Isolate* isolate, const void * block, bool bornOnRuntimeThread) {
180+ DeferredReleases* pending = DeferralQueue (isolate, bornOnRuntimeThread);
181+ if (pending == nullptr ) {
182+ Block_release (block);
183+ return ;
184+ }
185+ pending->blocks .push_back (block);
186+ PostDrain (isolate, pending);
187+ }
188+
111189} // namespace
112190
191+ void ObjectManager::Init (Isolate* isolate, Local<ObjectTemplate> globalTemplate) {
192+ globalTemplate->Set (tns::ToV8String (isolate, " __releaseNativeCounterpart" ),
193+ FunctionTemplate::New (isolate, ReleaseNativeCounterpartCallback));
194+ isolate->AddGCPrologueCallback (
195+ ReconcileOwnershipBeforeGC,
196+ static_cast <GCType>(kGCTypeMarkSweepCompact | kGCTypeIncrementalMarking ));
197+ Caches::StateFor<DeferredReleases>(isolate);
198+ }
199+
113200std::shared_ptr<Persistent<Value>> ObjectManager::Register (Local<Context> context,
114201 const Local<Value> obj) {
115202 Isolate* isolate = v8::Isolate::GetCurrent ();
@@ -160,6 +247,12 @@ void DisposeHandle(v8::Isolate* isolate,
160247 Isolate::Scope isolateScope (isolate);
161248 HandleScope scope (isolate);
162249
250+ // The event loop has stopped taking work, so nothing else would drain.
251+ DeferredReleases* deferred = Caches::ExistingStateFor<DeferredReleases>(isolate);
252+ if (deferred != nullptr ) {
253+ DrainDeferredReleases (deferred);
254+ }
255+
163256 // Detach the whole list first so disposal can't walk into freed entries, and
164257 // claim every state up front: disposing one entry can re-enter JS from
165258 // -dealloc and reach __releaseNativeCounterpart for any other entry this
@@ -186,6 +279,12 @@ void DisposeHandle(v8::Isolate* isolate,
186279 state = next;
187280 }
188281
282+ // The walk's own releases are inline on the runtime's thread; this catches
283+ // any made from another.
284+ if (deferred != nullptr ) {
285+ DrainDeferredReleases (deferred);
286+ }
287+
189288 DisposeHandleMap (isolate, cache->CtorFuncs );
190289 DisposeHandleMap (isolate, cache->ProtocolCtorFuncs );
191290 DisposeHandleMap (isolate, cache->CFunctions );
@@ -265,6 +364,28 @@ void DisposeHandle(v8::Isolate* isolate,
265364 }
266365}
267366
367+ bool ObjectManager::TakeDeferredRelease (Isolate* isolate, id obj) {
368+ DeferredReleases* pending = Caches::ExistingStateFor<DeferredReleases>(isolate);
369+ if (pending == nullptr || pending->objects .empty ()) {
370+ return false ;
371+ }
372+ auto it = pending->objects .find ((__bridge void *)obj);
373+ if (it == pending->objects .end ()) {
374+ return false ;
375+ }
376+ if (--it->second == 0 ) {
377+ pending->objects .erase (it);
378+ }
379+ return true ;
380+ }
381+
382+ void ObjectManager::ProtectIfNativelyRetained (id obj, ObjCDataWrapper* wrapper) {
383+ if (class_conformsToProtocol (object_getClass (obj), @protocol (TNSDerivedClass)) &&
384+ [obj retainCount ] > 1 ) {
385+ wrapper->GcProtect ();
386+ }
387+ }
388+
268389bool ObjectManager::DisposeValue (Isolate* isolate, Local<Value> value, bool isFinalDisposal) {
269390 if (value.IsEmpty () || value->IsNullOrUndefined () || !value->IsObject ()) {
270391 return true ;
@@ -320,7 +441,12 @@ void DisposeHandle(v8::Isolate* isolate,
320441 cache->Instances .erase (it);
321442 }
322443 }
323- [target release ];
444+ if (objCObjectWrapper->IsAdapterClaim ()) {
445+ // The adapter's -dealloc retires this wrapper; it must run first.
446+ [target release ];
447+ } else {
448+ ReleaseOnRuntimeThread (isolate, target, objCObjectWrapper->BornOnRuntimeThread ());
449+ }
324450 }
325451 break ;
326452 }
@@ -338,7 +464,8 @@ void DisposeHandle(v8::Isolate* isolate,
338464 // Block_copy and runs the block's dispose helper once we drop the last
339465 // reference. (Using CFRelease here over-released stack blocks that were
340466 // never promoted to the heap, crashing in objc_release during GC.)
341- Block_release (blockWrapper->Block ());
467+ BlockReleaseOnRuntimeThread (isolate, blockWrapper->Block (),
468+ blockWrapper->BornOnRuntimeThread ());
342469 break ;
343470 }
344471 case WrapperType::Reference: {
@@ -517,7 +644,11 @@ void DisposeHandle(v8::Isolate* isolate,
517644 // wrapper, so it must not be touched afterwards.
518645 bool adapterClaim = objcWrapper->IsAdapterClaim ();
519646
520- [data release ];
647+ if (adapterClaim) {
648+ [data release ];
649+ } else {
650+ ReleaseOnRuntimeThread (isolate, data, objcWrapper->BornOnRuntimeThread ());
651+ }
521652
522653 // The release above can run a -dealloc that detaches this wrapper; the
523654 // internal field owns it, so free only what is still attached. An
0 commit comments