Skip to content

Commit c07e987

Browse files
fix(runtime): tear down an adapter on its own isolate when another isolate drops it
The collection adapters (DictionaryAdapter, ArrayAdapter, NSDataAdapter) take their isolate's Locker in -dealloc, on whatever thread drops the last reference. When that thread is inside another isolate, it waits for one isolate's Locker while holding the other's, and the two can deadlock: - the main thread, inside a JS task, calls a native API that invokes a callback registered by a worker, and waits for the worker's Locker; - the worker's thread is collecting, and a finalizer releases an object holding an adapter built from one of the main isolate's values, whose -dealloc waits for the main isolate's Locker. A notification posted from the main isolate with a JS object as userInfo, observed by a block registered in a worker, is enough: the worker ends up with the last reference to each notification. -dealloc now checks whether it was reached from a thread that is inside another isolate and does not hold the adapter's own Locker. If so it posts itself to the adapter's isolate loop and returns without freeing anything, and runs again there under the Locker. The object stays allocated in between, as it did while the old code waited. If the loop shuts down first, the dropped entry runs the teardown, which then takes the existing isolate-is-gone path. The adapter's claim on its JS object stays attached until that teardown runs, so -dealloc marks the claim first, and marshalling a value whose claim is marked builds a fresh adapter instead of handing out the one being torn down.
1 parent 20935bd commit c07e987

12 files changed

Lines changed: 187 additions & 3 deletions

‎NativeScript/runtime/ArgConverter.mm‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -534,7 +534,7 @@
534534
if (type == BinaryTypeEncodingType::InterfaceDeclarationReference ||
535535
type == BinaryTypeEncodingType::InstanceTypeEncoding ||
536536
type == BinaryTypeEncodingType::IdEncoding) {
537-
BaseDataWrapper* baseWrapper = tns::GetValue(isolate, value);
537+
BaseDataWrapper* baseWrapper = tns::GetValueForMarshalling(isolate, value);
538538
if (baseWrapper != nullptr && baseWrapper->Type() == WrapperType::ObjCObject) {
539539
ObjCDataWrapper* wrapper = static_cast<ObjCDataWrapper*>(baseWrapper);
540540
id data = wrapper->Data();

‎NativeScript/runtime/ArrayAdapter.mm‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,16 @@ - (id)objectAtIndex:(NSUInteger)index {
112112
}
113113

114114
- (void)dealloc {
115+
// The claim stays attached until the teardown below has run, so it is marked
116+
// first: the JS object is not marshalled to this adapter again.
117+
if (dataWrapper_ != nullptr) {
118+
dataWrapper_->MarkAdapterDeallocating();
119+
}
120+
// Reached from a thread inside another isolate, the teardown below runs on
121+
// this adapter's own isolate instead; the object stays allocated until then.
122+
if (wrapper_->HandOffTeardown([self]() { [self dealloc]; })) {
123+
return;
124+
}
115125
if (wrapper_->IsValid()) {
116126
auto isolate = wrapper_->Isolate();
117127
v8::Locker locker(isolate);

‎NativeScript/runtime/DataWrapper.h‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
#include <objc/runtime.h>
55

6+
#include <atomic>
67
#include <functional>
78
#include <mutex>
89
#include <optional>
@@ -409,6 +410,16 @@ class ObjCDataWrapper : public BaseDataWrapper {
409410
bool IsAdapterClaim() { return this->adapterClaim_; }
410411
void MarkAdapterClaim() { this->adapterClaim_ = true; }
411412

413+
// Set by an adapter when its -dealloc starts, on whatever thread that is.
414+
// The claim stays attached until the adapter's teardown has run on its own
415+
// isolate, and marshalling must not hand the adapter out in between.
416+
bool IsAdapterDeallocating() const {
417+
return this->adapterDeallocating_.load(std::memory_order_acquire);
418+
}
419+
void MarkAdapterDeallocating() {
420+
this->adapterDeallocating_.store(true, std::memory_order_release);
421+
}
422+
412423
const TypeEncoding* TypeEncoding() { return this->typeEncoding_; }
413424

414425
// The class Data() had when this wrapper was built. Data() alone cannot tell
@@ -418,6 +429,7 @@ class ObjCDataWrapper : public BaseDataWrapper {
418429

419430
private:
420431
bool adapterClaim_ = false;
432+
std::atomic<bool> adapterDeallocating_{false};
421433
id data_;
422434
const tns::TypeEncoding* typeEncoding_;
423435
Class klass_;

‎NativeScript/runtime/DictionaryAdapter.mm‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -365,6 +365,16 @@ - (NSEnumerator*)keyEnumerator {
365365
}
366366

367367
- (void)dealloc {
368+
// The claim stays attached until the teardown below has run, so it is marked
369+
// first: the JS object is not marshalled to this adapter again.
370+
if (dataWrapper_ != nullptr) {
371+
dataWrapper_->MarkAdapterDeallocating();
372+
}
373+
// Reached from a thread inside another isolate, the teardown below runs on
374+
// this adapter's own isolate instead; the object stays allocated until then.
375+
if (wrapper_->HandOffTeardown([self]() { [self dealloc]; })) {
376+
return;
377+
}
368378
if (wrapper_->IsValid()) {
369379
Isolate* isolate = wrapper_->Isolate();
370380
v8::Locker locker(isolate);

‎NativeScript/runtime/Helpers.h‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -292,6 +292,10 @@ v8::Local<v8::Context> GetCreationContextOrCurrent(v8::Isolate* isolate,
292292
// the Proxy target, so a proxied wrapper yields its target's wrapper.
293293
void SetValue(v8::Isolate* isolate, const v8::Local<v8::Object>& obj, BaseDataWrapper* value);
294294
BaseDataWrapper* GetValue(v8::Isolate* isolate, const v8::Local<v8::Value>& val);
295+
// GetValue for a value about to be handed to native code. The claim of an
296+
// adapter that has started deallocating reads as null, so the value gets a
297+
// fresh adapter.
298+
BaseDataWrapper* GetValueForMarshalling(v8::Isolate* isolate, const v8::Local<v8::Value>& val);
295299

296300
// What happens when JS touches a wrapper whose native counterpart has already
297301
// been released (its internal field was neutered by DisposeValue) — a state a

‎NativeScript/runtime/Helpers.mm‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,15 @@ throw NativeScriptException(
337337
metadataProp.As<External>()->Value(v8::kExternalPointerTypeTagDefault));
338338
}
339339

340+
tns::BaseDataWrapper* tns::GetValueForMarshalling(Isolate* isolate, const Local<Value>& val) {
341+
BaseDataWrapper* wrapper = tns::GetValue(isolate, val);
342+
if (wrapper != nullptr && wrapper->Type() == WrapperType::ObjCObject &&
343+
static_cast<ObjCDataWrapper*>(wrapper)->IsAdapterDeallocating()) {
344+
return nullptr;
345+
}
346+
return wrapper;
347+
}
348+
340349
namespace {
341350

342351
std::atomic<int> releasedObjectPolicy_{static_cast<int>(tns::ReleasedObjectPolicy::kReport)};

‎NativeScript/runtime/Interop.mm‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -742,7 +742,7 @@ static bool SnapshotArrayLike(Isolate* isolate, Local<Object> object, Local<v8::
742742
}
743743
} else if (argHelper.isObject()) {
744744
Local<Object> obj = arg.As<Object>();
745-
BaseDataWrapper* wrapper = tns::GetValue(isolate, obj);
745+
BaseDataWrapper* wrapper = tns::GetValueForMarshalling(isolate, obj);
746746

747747
if (wrapper != nullptr) {
748748
if (wrapper->Type() == WrapperType::Enum) {
@@ -852,7 +852,7 @@ static bool SnapshotArrayLike(Isolate* isolate, Local<Object> object, Local<v8::
852852
ArrayAdapter* adapter = [[ArrayAdapter alloc] initWithJSObject:array isolate:isolate];
853853
return adapter;
854854
} else if (arg->IsObject()) {
855-
if (BaseDataWrapper* wrapper = tns::GetValue(isolate, arg)) {
855+
if (BaseDataWrapper* wrapper = tns::GetValueForMarshalling(isolate, arg)) {
856856
switch (wrapper->Type()) {
857857
case WrapperType::ObjCObject: {
858858
ObjCDataWrapper* wr = static_cast<ObjCDataWrapper*>(wrapper);

‎NativeScript/runtime/IsolateWrapper.cpp‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
#include <cstdint>
1212
#include <mutex>
1313

14+
#include "NativeScriptPlatform.h"
1415
#include "Runtime.h"
1516
#include "UnfairLock.h"
1617
#include "robin_hood.h"
@@ -26,6 +27,53 @@ bool IsolateWrapper::IsValid() const {
2627
return cache->IsValid() && cache->getGateId() == gateId_;
2728
}
2829

30+
namespace {
31+
32+
// Runs the teardown from the loop entry, or from the entry's destructor when
33+
// the loop drops it unrun.
34+
struct HandedOffTeardown {
35+
explicit HandedOffTeardown(std::function<void()> teardown)
36+
: teardown_(std::move(teardown)) {}
37+
~HandedOffTeardown() { Run(); }
38+
void Run() {
39+
std::function<void()> teardown = std::move(teardown_);
40+
teardown_ = nullptr;
41+
if (teardown) {
42+
teardown();
43+
}
44+
}
45+
void Cancel() { teardown_ = nullptr; }
46+
47+
private:
48+
std::function<void()> teardown_;
49+
};
50+
51+
} // namespace
52+
53+
bool IsolateWrapper::HandOffTeardown(std::function<void()> teardown) const {
54+
v8::Isolate* current = v8::Isolate::TryGetCurrent();
55+
if (current == nullptr || current == isolate_) {
56+
return false;
57+
}
58+
// Keeps the isolate from being disposed while it is examined here.
59+
IsolatePin pin = Pin();
60+
if (!pin || !IsValid() || v8::Locker::IsLocked(isolate_)) {
61+
return false;
62+
}
63+
std::shared_ptr<EventLoop> loop =
64+
NativeScriptPlatform::Instance()->LookupEventLoop(isolate_);
65+
if (loop == nullptr) {
66+
return false;
67+
}
68+
auto pending = std::make_shared<HandedOffTeardown>(std::move(teardown));
69+
if (!loop->PostInternal([pending]() { pending->Run(); })) {
70+
pending->Cancel();
71+
return false;
72+
}
73+
// The loop may already have run the teardown, which frees this wrapper.
74+
return true;
75+
}
76+
2977
namespace IsolateGates {
3078

3179
namespace {

‎NativeScript/runtime/IsolateWrapper.h‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
#ifndef IsolateWrapper_h
1010
#define IsolateWrapper_h
1111

12+
#include <functional>
1213
#include <type_traits>
1314

1415
#include "Caches.h"
@@ -82,6 +83,16 @@ class IsolateWrapper {
8283
// True once the teardown has finished with every wrapper reachable from
8384
// JS. Read it while pinned.
8485
inline bool IsTornDown() const { return IsolateGates::IsClosed(gateId_); }
86+
// For a teardown that needs this isolate's Locker and can be reached from
87+
// any thread. A thread that is inside another isolate must not wait for
88+
// this one's Locker: it may hold the other isolate's, and a thread inside
89+
// this isolate may be waiting for that one. From such a thread `teardown`
90+
// is posted to this isolate's loop and true is returned; the caller must
91+
// then return without touching anything `teardown` frees, this wrapper
92+
// included. `teardown` runs once: from the loop, or when the loop drops
93+
// the entry while shutting down. False means the caller runs the teardown
94+
// itself.
95+
bool HandOffTeardown(std::function<void()> teardown) const;
8596

8697
private:
8798
v8::Isolate* isolate_;

‎NativeScript/runtime/NSDataAdapter.mm‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,16 @@ - (NSUInteger)length {
102102
}
103103

104104
- (void)dealloc {
105+
// The claim stays attached until the teardown below has run, so it is marked
106+
// first: the JS object is not marshalled to this adapter again.
107+
if (dataWrapper_ != nullptr) {
108+
dataWrapper_->MarkAdapterDeallocating();
109+
}
110+
// Reached from a thread inside another isolate, the teardown below runs on
111+
// this adapter's own isolate instead; the object stays allocated until then.
112+
if (wrapper_->HandOffTeardown([self]() { [self dealloc]; })) {
113+
return;
114+
}
105115
if (wrapper_->IsValid()) {
106116
auto isolate = wrapper_->Isolate();
107117
v8::Locker locker(isolate);

0 commit comments

Comments
 (0)