11#include " ObjectManager.h"
22#include < Block.h>
33#include < CoreFoundation/CoreFoundation.h>
4- #include < atomic>
5- #include < mutex>
64#include < sstream>
75#include < unordered_map>
86#include < vector>
97#include " Caches.h"
108#include " Constants.h"
119#include " DataWrapper.h"
1210#include " FFICall.h"
11+ #include " EventLoop.h"
1312#include " Helpers.h"
1413#include " Runtime.h"
1514#include " TNSDerivedClass.h"
@@ -53,44 +52,31 @@ void UnlinkRegistered(ObjectWeakCallbackState* state) {
5352 state->next_ = nullptr ;
5453}
5554
56- // Native releases belong on the runtime's thread. JS, and with it a collection
57- // and its finalizers, can run on any thread that holds the isolate's Locker (a
58- // JS callback dispatched to a background queue), and a -dealloc that tears down
59- // a view, a CA transaction or a block capturing one crashes off that thread.
55+ // The native release of an object that first reached JS on its runtime's
56+ // thread belongs on that thread. JS, and with it a collection and its
57+ // finalizers, can run on any thread that holds the isolate's Locker (a JS
58+ // callback dispatched to a background queue), and a -dealloc that tears down a
59+ // view, a CA transaction or a block capturing one crashes off the main thread.
60+ // Objects first wrapped on another thread are still released where the
61+ // collection runs.
6062//
61- // Shared with the run loop block that drains it, which may run after the
62- // isolate's Caches is gone; the releases themselves need no Locker.
63+ // Every access holds the isolate's Locker: finalizers and
64+ // __releaseNativeCounterpart on any thread, and on the runtime's thread the
65+ // drain task, wrapper creation and teardown. So no other synchronization.
6366struct DeferredReleases {
64- std::mutex mutex;
6567 // Object -> releases it is owed. An object stays alive while it is owed one,
6668 // so its address cannot be reused by another object meanwhile.
6769 std::unordered_map<void *, unsigned > objects;
6870 std::vector<const void *> blocks;
69- bool scheduled = false ;
71+ bool drainPosted = false ;
7072};
7173
72- struct DeferredReleasesState {
73- std::shared_ptr<DeferredReleases> pending = std::make_shared<DeferredReleases>();
74- };
75-
76- // Object releases waiting in any isolate: lets wrapper creation skip the lookup.
77- // Process-wide, so while one isolate has some, the others pay a lookup too.
78- std::atomic<int > deferredObjectReleases_{0 };
79-
80- void DrainDeferredReleases (const std::shared_ptr<DeferredReleases>& pending) {
74+ void DrainDeferredReleases (DeferredReleases* pending) {
8175 std::unordered_map<void *, unsigned > objects;
8276 std::vector<const void *> blocks;
83- {
84- std::lock_guard<std::mutex> lock (pending->mutex );
85- objects.swap (pending->objects );
86- blocks.swap (pending->blocks );
87- pending->scheduled = false ;
88- int count = 0 ;
89- for (const auto & entry : objects) {
90- count += entry.second ;
91- }
92- deferredObjectReleases_.fetch_sub (count, std::memory_order_relaxed);
93- }
77+ objects.swap (pending->objects );
78+ blocks.swap (pending->blocks );
79+ pending->drainPosted = false ;
9480 for (const auto & entry : objects) {
9581 id obj = (__bridge id )entry.first ;
9682 for (unsigned i = 0 ; i < entry.second ; i++) {
@@ -102,73 +88,58 @@ void DrainDeferredReleases(const std::shared_ptr<DeferredReleases>& pending) {
10288 }
10389}
10490
105- // Null when the caller is on the runtime's thread (or there is no runtime to
106- // hand over to) and should release inline.
107- std::shared_ptr<DeferredReleases> DeferralTarget (Isolate* isolate, CFRunLoopRef* loop) {
108- Runtime* runtime = Runtime::GetRuntime (isolate);
109- if (runtime == nullptr || runtime->RuntimeLoop () == nullptr ||
110- CFRunLoopGetCurrent () == runtime->RuntimeLoop ()) {
111- return nullptr ;
112- }
113- DeferredReleasesState* state = Caches::StateFor<DeferredReleasesState>(isolate);
114- if (state == nullptr ) {
91+ // The queue to hand a release to, or null when the caller releases inline.
92+ // Created by Init, so a collection on another thread never creates it; read
93+ // without the validity check because a collection can still run on another
94+ // thread between InvalidateIsolate and teardown, which drains it.
95+ DeferredReleases* DeferralQueue (Isolate* isolate, bool bornOnRuntimeThread) {
96+ if (!bornOnRuntimeThread || OnRuntimeThreadOf (isolate)) {
11597 return nullptr ;
11698 }
117- *loop = runtime->RuntimeLoop ();
118- return state->pending ;
99+ return Caches::ExistingStateFor<DeferredReleases>(isolate);
119100}
120101
121- // Called with pending->mutex held.
122- void ScheduleDrain (const std::shared_ptr<DeferredReleases>& pending, CFRunLoopRef loop) {
123- if (pending->scheduled ) {
102+ // One event loop task per batch. If the loop no longer takes work, teardown is
103+ // under way and drains the queue itself.
104+ void PostDrain (Isolate* isolate, DeferredReleases* pending) {
105+ if (pending->drainPosted ) {
124106 return ;
125107 }
126- pending->scheduled = true ;
127- std::shared_ptr<DeferredReleases> shared = pending;
128- // A plain run loop block rather than an event loop task: it must run even
129- // once the event loop stops taking work, and needs no isolate. The loop is
130- // retained because a worker's thread can exit, freeing it, meanwhile.
131- CFRetain (loop);
132- CFRunLoopPerformBlock (loop, kCFRunLoopCommonModes , ^{
133- DrainDeferredReleases (shared);
108+ Runtime* runtime = Runtime::GetRuntime (isolate);
109+ std::shared_ptr<EventLoop> loop = runtime != nullptr ? runtime->GetEventLoop () : nullptr ;
110+ pending->drainPosted = loop != nullptr && loop->PostInternal ([isolate]() {
111+ if (DeferredReleases* queued = Caches::ExistingStateFor<DeferredReleases>(isolate)) {
112+ DrainDeferredReleases (queued);
113+ }
134114 });
135- CFRunLoopWakeUp (loop);
136- CFRelease (loop);
137115}
138116
139- void ReleaseOnRuntimeThread (Isolate* isolate, id obj) {
140- CFRunLoopRef loop = nullptr ;
141- std::shared_ptr<DeferredReleases> pending = DeferralTarget (isolate, &loop);
117+ void ReleaseOnRuntimeThread (Isolate* isolate, id obj, bool bornOnRuntimeThread) {
118+ DeferredReleases* pending = DeferralQueue (isolate, bornOnRuntimeThread);
142119 if (pending == nullptr ) {
143120 [obj release ];
144121 return ;
145122 }
146- std::lock_guard<std::mutex> lock (pending->mutex );
147123 pending->objects [(__bridge void *)obj]++;
148- deferredObjectReleases_.fetch_add (1 , std::memory_order_relaxed);
149- ScheduleDrain (pending, loop);
124+ PostDrain (isolate, pending);
150125}
151126
152- void BlockReleaseOnRuntimeThread (Isolate* isolate, const void * block) {
153- CFRunLoopRef loop = nullptr ;
154- std::shared_ptr<DeferredReleases> pending = DeferralTarget (isolate, &loop);
127+ void BlockReleaseOnRuntimeThread (Isolate* isolate, const void * block, bool bornOnRuntimeThread) {
128+ DeferredReleases* pending = DeferralQueue (isolate, bornOnRuntimeThread);
155129 if (pending == nullptr ) {
156130 Block_release (block);
157131 return ;
158132 }
159- std::lock_guard<std::mutex> lock (pending->mutex );
160133 pending->blocks .push_back (block);
161- ScheduleDrain (pending, loop );
134+ PostDrain (isolate, pending );
162135}
163136
164137} // namespace
165138
166139void ObjectManager::Init (Isolate* isolate, Local<ObjectTemplate> globalTemplate) {
167140 globalTemplate->Set (tns::ToV8String (isolate, " __releaseNativeCounterpart" ),
168141 FunctionTemplate::New (isolate, ReleaseNativeCounterpartCallback));
169- // Created here, on the runtime's thread: a collection on another thread must
170- // only find it.
171- Caches::StateFor<DeferredReleasesState>(isolate);
142+ Caches::StateFor<DeferredReleases>(isolate);
172143}
173144
174145std::shared_ptr<Persistent<Value>> ObjectManager::Register (Local<Context> context,
@@ -221,9 +192,10 @@ void DisposeHandle(v8::Isolate* isolate,
221192 Isolate::Scope isolateScope (isolate);
222193 HandleScope scope (isolate);
223194
224- // A worker's run loop stops with its runtime, so nothing else would drain.
225- if (DeferredReleasesState* deferred = Caches::ExistingStateFor<DeferredReleasesState>(isolate)) {
226- DrainDeferredReleases (deferred->pending );
195+ // The event loop has stopped taking work, so nothing else would drain.
196+ DeferredReleases* deferred = Caches::ExistingStateFor<DeferredReleases>(isolate);
197+ if (deferred != nullptr ) {
198+ DrainDeferredReleases (deferred);
227199 }
228200
229201 // Detach the whole list first so disposal can't walk into freed entries, and
@@ -252,6 +224,12 @@ void DisposeHandle(v8::Isolate* isolate,
252224 state = next;
253225 }
254226
227+ // The walk's own releases are inline on the runtime's thread; this catches
228+ // any made from another.
229+ if (deferred != nullptr ) {
230+ DrainDeferredReleases (deferred);
231+ }
232+
255233 DisposeHandleMap (isolate, cache->CtorFuncs );
256234 DisposeHandleMap (isolate, cache->ProtocolCtorFuncs );
257235 DisposeHandleMap (isolate, cache->CFunctions );
@@ -298,23 +276,17 @@ void DisposeHandle(v8::Isolate* isolate,
298276}
299277
300278bool ObjectManager::TakeDeferredRelease (Isolate* isolate, id obj) {
301- if (deferredObjectReleases_.load (std::memory_order_relaxed) == 0 ) {
302- return false ;
303- }
304- DeferredReleasesState* state = Caches::StateFor<DeferredReleasesState>(isolate);
305- if (state == nullptr ) {
279+ DeferredReleases* pending = Caches::ExistingStateFor<DeferredReleases>(isolate);
280+ if (pending == nullptr || pending->objects .empty ()) {
306281 return false ;
307282 }
308- DeferredReleases* pending = state->pending .get ();
309- std::lock_guard<std::mutex> lock (pending->mutex );
310283 auto it = pending->objects .find ((__bridge void *)obj);
311284 if (it == pending->objects .end ()) {
312285 return false ;
313286 }
314287 if (--it->second == 0 ) {
315288 pending->objects .erase (it);
316289 }
317- deferredObjectReleases_.fetch_sub (1 , std::memory_order_relaxed);
318290 return true ;
319291}
320292
@@ -373,7 +345,7 @@ void DisposeHandle(v8::Isolate* isolate,
373345 // The adapter's -dealloc retires this wrapper; it must run first.
374346 [target release ];
375347 } else {
376- ReleaseOnRuntimeThread (isolate, target);
348+ ReleaseOnRuntimeThread (isolate, target, objCObjectWrapper-> BornOnRuntimeThread () );
377349 }
378350 }
379351 break ;
@@ -392,7 +364,8 @@ void DisposeHandle(v8::Isolate* isolate,
392364 // Block_copy and runs the block's dispose helper once we drop the last
393365 // reference. (Using CFRelease here over-released stack blocks that were
394366 // never promoted to the heap, crashing in objc_release during GC.)
395- BlockReleaseOnRuntimeThread (isolate, blockWrapper->Block ());
367+ BlockReleaseOnRuntimeThread (isolate, blockWrapper->Block (),
368+ blockWrapper->BornOnRuntimeThread ());
396369 break ;
397370 }
398371 case WrapperType::Reference: {
@@ -544,7 +517,7 @@ void DisposeHandle(v8::Isolate* isolate,
544517 if (adapterClaim) {
545518 [data release ];
546519 } else {
547- ReleaseOnRuntimeThread (isolate, data);
520+ ReleaseOnRuntimeThread (isolate, data, objcWrapper-> BornOnRuntimeThread () );
548521 }
549522
550523 // The release above can run a -dealloc that detaches this wrapper; the
0 commit comments