Skip to content

Commit 06c7ba8

Browse files
committed
fix(runtime): release native objects on the runtime's thread
1 parent e093b92 commit 06c7ba8

9 files changed

Lines changed: 308 additions & 15 deletions

File tree

‎NativeScript/runtime/ArgConverter.mm‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -744,9 +744,20 @@ bool IsKVOSubclassOf(Class klass, Class base) {
744744
tns::SetValue(isolate, thiz, wrapper);
745745
std::shared_ptr<Persistent<Value>> poThiz = ObjectManager::Register(context, thiz);
746746
cache->Instances.emplace(result, poThiz);
747-
if (!resultIsOwned) {
747+
// An initializer can answer with an existing object whose release is still
748+
// waiting (see CreateJsWrapper).
749+
bool tookOver = ObjectManager::TakeDeferredRelease(isolate, result);
750+
if (tookOver && resultIsOwned) {
751+
[result release];
752+
} else if (!tookOver && !resultIsOwned) {
748753
[result retain];
749754
}
755+
if (tookOver) {
756+
// Only releases of objects that first reached JS on the runtime's
757+
// thread are ever queued.
758+
wrapper->SetBornOnRuntimeThread();
759+
ObjectManager::ProtectIfNativelyRetained(result, wrapper);
760+
}
750761
ExternalMemory::ChargeEstimatedSize(isolate, thiz);
751762
}
752763
}
@@ -1014,7 +1025,15 @@ bool IsKVOSubclassOf(Class klass, Class base) {
10141025
receiver = poValue->Get(isolate).As<Object>();
10151026
tns::SetValue(isolate, receiver, wrapper);
10161027
cache->Instances.emplace(target, poValue);
1017-
[target retain];
1028+
// An extended class reads its retain count to decide whether native
1029+
// code owns the object, so a pending release is taken over, not stacked.
1030+
if (!ObjectManager::TakeDeferredRelease(isolate, target)) {
1031+
[target retain];
1032+
} else if (wrapper->Type() == WrapperType::ObjCObject) {
1033+
ObjCDataWrapper* objcWrapper = static_cast<ObjCDataWrapper*>(wrapper);
1034+
objcWrapper->SetBornOnRuntimeThread();
1035+
ObjectManager::ProtectIfNativelyRetained(target, objcWrapper);
1036+
}
10181037
}
10191038
} else {
10201039
tns::SetValue(isolate, receiver, wrapper);

‎NativeScript/runtime/Caches.h‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,22 @@ class Caches {
118118
return cache->GetOrCreateState<T>();
119119
}
120120

121+
// Teardown only: the existing state, even after InvalidateIsolate, for a
122+
// subsystem that must finish work its state still holds. Never creates.
123+
template <typename T>
124+
static T* ExistingStateFor(v8::Isolate* isolate) {
125+
auto raw = isolate->GetData(0);
126+
if (raw == nullptr) {
127+
return nullptr;
128+
}
129+
Caches* cache = reinterpret_cast<std::shared_ptr<Caches>*>(raw)->get();
130+
size_t index = StateSlotIndexFor<T>();
131+
if (index >= cache->stateSlots_.size()) {
132+
return nullptr;
133+
}
134+
return static_cast<T*>(cache->stateSlots_[index].get());
135+
}
136+
121137
inline int getIsolateId() { return isolateId_; }
122138

123139
// The id assigned at Init; unlike getIsolateId() it survives

‎NativeScript/runtime/DataWrapper.h‎

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

2121
namespace tns {
2222

23+
// Whether the calling thread is the one `isolate`'s runtime runs on (its event
24+
// loop's thread). JS can also run on other threads, any that take the
25+
// isolate's Locker. Several runtimes may share a thread. Defined in Runtime.mm.
26+
bool OnRuntimeThreadOf(v8::Isolate* isolate);
27+
2328
class PrimitiveDataWrapper;
2429
struct ObjectWeakCallbackState;
2530
class EventLoop;
@@ -396,7 +401,8 @@ class ObjCDataWrapper : public BaseDataWrapper {
396401
ObjCDataWrapper(id data, const TypeEncoding* typeEncoding = nullptr)
397402
: data_(data),
398403
typeEncoding_(typeEncoding),
399-
klass_(object_getClass(data)) {}
404+
klass_(object_getClass(data)),
405+
bornOnRuntimeThread_(OnRuntimeThreadOf(v8::Isolate::TryGetCurrent())) {}
400406

401407
const WrapperType Type() { return WrapperType::ObjCObject; }
402408

@@ -409,6 +415,11 @@ class ObjCDataWrapper : public BaseDataWrapper {
409415
bool IsAdapterClaim() { return this->adapterClaim_; }
410416
void MarkAdapterClaim() { this->adapterClaim_ = true; }
411417

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

414425
// The class Data() had when this wrapper was built. Data() alone cannot tell
@@ -435,6 +446,7 @@ class ObjCDataWrapper : public BaseDataWrapper {
435446
id data_;
436447
const tns::TypeEncoding* typeEncoding_;
437448
Class klass_;
449+
bool bornOnRuntimeThread_;
438450
};
439451

440452
class ObjCClassWrapper : public BaseDataWrapper {
@@ -502,7 +514,10 @@ class AnonymousFunctionWrapper : public BaseDataWrapper {
502514
class BlockWrapper : public BaseDataWrapper {
503515
public:
504516
BlockWrapper(void* block, const TypeEncoding* typeEncoding, bool ownsBlock)
505-
: block_(block), typeEncoding_(typeEncoding), ownsBlock_(ownsBlock) {}
517+
: block_(block),
518+
typeEncoding_(typeEncoding),
519+
ownsBlock_(ownsBlock),
520+
bornOnRuntimeThread_(OnRuntimeThreadOf(v8::Isolate::TryGetCurrent())) {}
506521

507522
const WrapperType Type() { return WrapperType::Block; }
508523

@@ -512,10 +527,14 @@ class BlockWrapper : public BaseDataWrapper {
512527

513528
bool OwnsBlock() { return this->ownsBlock_; }
514529

530+
// See ObjCDataWrapper::BornOnRuntimeThread.
531+
bool BornOnRuntimeThread() { return this->bornOnRuntimeThread_; }
532+
515533
private:
516534
void* block_;
517535
const TypeEncoding* typeEncoding_;
518536
bool ownsBlock_;
537+
bool bornOnRuntimeThread_;
519538
};
520539

521540
class FunctionReferenceTypeWrapper : public BaseDataWrapper {

‎NativeScript/runtime/ObjectManager.h‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,17 @@ class ObjectManager {
6464
static void ReconcileOwnership(v8::Isolate* isolate,
6565
ObjCDataWrapper* wrapper);
6666

67+
// A collection can run on any thread that holds the isolate's Locker, but
68+
// the native releases it causes are handed to the runtime's thread. A new
69+
// Instances entry for an object whose release is still waiting takes that
70+
// release over as its own retain instead of retaining again; returns whether
71+
// it did. Once the entry's retain is settled, call ProtectIfNativelyRetained.
72+
static bool TakeDeferredRelease(v8::Isolate* isolate, id obj);
73+
// An extended class protects its wrapper when native code first retains the
74+
// object past the runtime's own retain. A native retain made while a release
75+
// waited found no wrapper to protect; this catches up.
76+
static void ProtectIfNativelyRetained(id obj, ObjCDataWrapper* wrapper);
77+
6778
private:
6879
static void ReleaseNativeCounterpartCallback(
6980
const v8::FunctionCallbackInfo<v8::Value>& info);

‎NativeScript/runtime/ObjectManager.mm‎

Lines changed: 142 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,16 @@
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

1317
using namespace v8;
1418
using 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-
7975
namespace {
8076

8177
void 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+
113200
std::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+
268389
bool 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

‎NativeScript/runtime/Runtime.h‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#ifndef Runtime_h
22
#define Runtime_h
33

4+
#include <pthread.h>
45
#include <atomic>
56
#include <optional>
67

@@ -51,6 +52,8 @@ class Runtime {
5152

5253
inline CFRunLoopRef RuntimeLoop() { return runtimeLoop_; }
5354

55+
inline bool IsOnRuntimeThread() const { return pthread_equal(runtimeThread_, pthread_self()) != 0; }
56+
5457
/*
5558
* Scheduler bound to this runtime's runloop. Producers on any thread post;
5659
* entries run only on the runtime's home thread.
@@ -192,6 +195,7 @@ class Runtime {
192195
std::unique_ptr<ModuleInternal> moduleInternal_;
193196
int workerId_;
194197
CFRunLoopRef runtimeLoop_;
198+
pthread_t runtimeThread_;
195199
std::shared_ptr<EventLoop> eventLoop_;
196200
// Drains unhandled promise rejections once per runloop turn
197201
// (kCFRunLoopBeforeWaiting). Torn down before isolate disposal in ~Runtime.

0 commit comments

Comments
 (0)