Skip to content

Commit b0d95ef

Browse files
committed
fix(runtime): defer only releases of objects born on the runtime's thread
Deferring every off-thread release moved all of a background queue's deallocations onto the main thread, including objects that never belonged there. Wrappers now record whether the object first reached JS on its runtime's thread (a thread-local marker the runtime sets where it binds its event loop, compared with the current isolate when the wrapper is built), and only those releases are handed over. Objects first wrapped on another thread are released where the collection runs, as before. The queue is now plain per-isolate containers: finalizers, __releaseNativeCounterpart, wrapper creation, the drain and teardown all hold the isolate's Locker, so it needs no mutex or atomics. It drains in one event loop task per batch instead of a CFRunLoop block; teardown, which runs after the loop stops, drains it inline before and after the disposal walk.
1 parent b9f5063 commit b0d95ef

6 files changed

Lines changed: 140 additions & 95 deletions

File tree

‎NativeScript/runtime/ArgConverter.mm‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -647,6 +647,9 @@
647647
[result retain];
648648
}
649649
if (tookOver) {
650+
// Only releases of objects that first reached JS on the runtime's
651+
// thread are ever queued.
652+
wrapper->SetBornOnRuntimeThread();
650653
ObjectManager::ProtectIfNativelyRetained(result, wrapper);
651654
}
652655
ExternalMemory::ChargeEstimatedSize(isolate, thiz);
@@ -921,7 +924,9 @@
921924
if (!ObjectManager::TakeDeferredRelease(isolate, target)) {
922925
[target retain];
923926
} else if (wrapper->Type() == WrapperType::ObjCObject) {
924-
ObjectManager::ProtectIfNativelyRetained(target, static_cast<ObjCDataWrapper*>(wrapper));
927+
ObjCDataWrapper* objcWrapper = static_cast<ObjCDataWrapper*>(wrapper);
928+
objcWrapper->SetBornOnRuntimeThread();
929+
ObjectManager::ProtectIfNativelyRetained(target, objcWrapper);
925930
}
926931
}
927932
} else {

‎NativeScript/runtime/DataWrapper.h‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,15 @@ class WorkerInspectorClient;
2020

2121
namespace tns {
2222

23+
// The isolate whose runtime runs on this thread (its event loop's thread),
24+
// while the runtime is bound here. JS can also run on other threads, any that
25+
// take the isolate's Locker.
26+
inline thread_local v8::Isolate* runtimeThreadIsolate = nullptr;
27+
28+
inline bool OnRuntimeThreadOf(v8::Isolate* isolate) {
29+
return isolate != nullptr && runtimeThreadIsolate == isolate;
30+
}
31+
2332
class PrimitiveDataWrapper;
2433
struct ObjectWeakCallbackState;
2534
class EventLoop;
@@ -396,7 +405,8 @@ class ObjCDataWrapper : public BaseDataWrapper {
396405
ObjCDataWrapper(id data, const TypeEncoding* typeEncoding = nullptr)
397406
: data_(data),
398407
typeEncoding_(typeEncoding),
399-
klass_(object_getClass(data)) {}
408+
klass_(object_getClass(data)),
409+
bornOnRuntimeThread_(OnRuntimeThreadOf(v8::Isolate::TryGetCurrent())) {}
400410

401411
const WrapperType Type() { return WrapperType::ObjCObject; }
402412

@@ -409,6 +419,11 @@ class ObjCDataWrapper : public BaseDataWrapper {
409419
bool IsAdapterClaim() { return this->adapterClaim_; }
410420
void MarkAdapterClaim() { this->adapterClaim_ = true; }
411421

422+
// Whether the object first reached JS on its runtime's thread, the stand-in
423+
// for "belongs to that thread": its native release must happen there too.
424+
bool BornOnRuntimeThread() { return this->bornOnRuntimeThread_; }
425+
void SetBornOnRuntimeThread() { this->bornOnRuntimeThread_ = true; }
426+
412427
const TypeEncoding* TypeEncoding() { return this->typeEncoding_; }
413428

414429
// The class Data() had when this wrapper was built. Data() alone cannot tell
@@ -421,6 +436,7 @@ class ObjCDataWrapper : public BaseDataWrapper {
421436
id data_;
422437
const tns::TypeEncoding* typeEncoding_;
423438
Class klass_;
439+
bool bornOnRuntimeThread_;
424440
};
425441

426442
class ObjCClassWrapper : public BaseDataWrapper {
@@ -488,7 +504,10 @@ class AnonymousFunctionWrapper : public BaseDataWrapper {
488504
class BlockWrapper : public BaseDataWrapper {
489505
public:
490506
BlockWrapper(void* block, const TypeEncoding* typeEncoding, bool ownsBlock)
491-
: block_(block), typeEncoding_(typeEncoding), ownsBlock_(ownsBlock) {}
507+
: block_(block),
508+
typeEncoding_(typeEncoding),
509+
ownsBlock_(ownsBlock),
510+
bornOnRuntimeThread_(OnRuntimeThreadOf(v8::Isolate::TryGetCurrent())) {}
492511

493512
const WrapperType Type() { return WrapperType::Block; }
494513

@@ -498,10 +517,14 @@ class BlockWrapper : public BaseDataWrapper {
498517

499518
bool OwnsBlock() { return this->ownsBlock_; }
500519

520+
// See ObjCDataWrapper::BornOnRuntimeThread.
521+
bool BornOnRuntimeThread() { return this->bornOnRuntimeThread_; }
522+
501523
private:
502524
void* block_;
503525
const TypeEncoding* typeEncoding_;
504526
bool ownsBlock_;
527+
bool bornOnRuntimeThread_;
505528
};
506529

507530
class FunctionReferenceTypeWrapper : public BaseDataWrapper {

‎NativeScript/runtime/ObjectManager.mm‎

Lines changed: 56 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,14 @@
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.
6366
struct 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

166139
void 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

174145
std::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

300278
bool 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

‎NativeScript/runtime/Runtime.mm‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#include "Runtime.h"
2+
#include "DataWrapper.h"
23
#include <chrono>
34
#include <string>
45
#include "ArgConverter.h"
@@ -277,12 +278,16 @@ void DisposeIsolateWhenPossible(Isolate* isolate, int gateId) {
277278
eventLoop_->BindToCurrentThread();
278279
isolate->SetData(Constants::RUNTIME_SLOT, this);
279280
isolate_ = isolate;
281+
tns::runtimeThreadIsolate = isolate;
280282
}
281283

282284
Runtime::~Runtime() {
283285
if (!initialized_) {
284286
// Never published: no other thread can know this isolate, and it holds no
285287
// caches, gate or wrappers.
288+
if (tns::runtimeThreadIsolate == isolate_) {
289+
tns::runtimeThreadIsolate = nullptr;
290+
}
286291
isolate_->Dispose();
287292
NativeScriptPlatform::Instance()->IsolateDisposed(isolate_, eventLoop_);
288293
currentRuntime_ = nullptr;
@@ -368,6 +373,9 @@ void DisposeIsolateWhenPossible(Isolate* isolate, int gateId) {
368373
Caches::Remove(this->isolate_);
369374

370375
this->isolate_->SetData(Constants::RUNTIME_SLOT, nullptr);
376+
if (tns::runtimeThreadIsolate == this->isolate_) {
377+
tns::runtimeThreadIsolate = nullptr;
378+
}
371379

372380
// Last, and under the Locker: from here on nothing reads a wrapper through
373381
// a JS object, so threads that never pinned may free theirs without the

0 commit comments

Comments
 (0)