Skip to content

Commit 71be892

Browse files
fix(runtime): avoid cross-isolate adapter and block teardown deadlocks
The collection adapters (DictionaryAdapter, ArrayAdapter, NSDataAdapter) and the JS block dispose helper take their isolate's Locker on whatever thread drops the last native 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 or a block that belongs to the main isolate, whose teardown 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. IsolateWrapper::HandOffTeardown posts such a teardown to the owning isolate's loop when the calling thread is inside another isolate and does not hold the owner's Locker. If the loop drops the entry while shutting down, the entry runs it; if the loop refuses the post, a dispatch queue runs it with no isolate lock held. Adapters: -dealloc hands itself off and returns without freeing anything; the object stays allocated until it runs again on its own isolate. The claim an adapter attaches to its JS object holds the adapter weakly, so marshalling the object either takes a reference to a live adapter or, once its last release has started, detaches the dead claim and builds a fresh adapter that attaches its own. Only the adapter frees its claim: retiring the JS object, including __releaseNativeCounterpart, no longer releases the adapter. Blocks: libclosure frees a block as soon as its dispose helper returns, so the helper first clears the address cached in the function's BlockWrapper, under a mutex that reuse of the cached block also takes, and only then hands off the cleanup that needs the isolate. The ns:worker_threads specs get the 30 second startup bound the other worker suites use; the utility-priority worker did not always start within the default 5 seconds on CI.
1 parent c3ee452 commit 71be892

18 files changed

Lines changed: 392 additions & 130 deletions

‎NativeScript/runtime/ArgConverter.mm‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -686,7 +686,7 @@ throw NativeScriptException(isolate, v8::Exception::TypeError(tns::ToV8String(is
686686
if (type == BinaryTypeEncodingType::InterfaceDeclarationReference ||
687687
type == BinaryTypeEncodingType::InstanceTypeEncoding ||
688688
type == BinaryTypeEncodingType::IdEncoding) {
689-
BaseDataWrapper* baseWrapper = tns::GetValue(isolate, value);
689+
BaseDataWrapper* baseWrapper = tns::GetValueForMarshalling(isolate, value);
690690
if (baseWrapper != nullptr && baseWrapper->Type() == WrapperType::ObjCObject) {
691691
ObjCDataWrapper* wrapper = static_cast<ObjCDataWrapper*>(baseWrapper);
692692
WrapperLifetime::Escape(wrapper);

‎NativeScript/runtime/ArrayAdapter.mm‎

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,11 @@ - (id)objectAtIndex:(NSUInteger)index {
121121
}
122122

123123
- (void)dealloc {
124+
// Reached from a thread inside another isolate, the teardown below runs on
125+
// this adapter's own isolate instead; the object stays allocated until then.
126+
if (wrapper_->HandOffTeardown([self]() { [self dealloc]; })) {
127+
return;
128+
}
124129
{
125130
IsolatePin pin = wrapper_->Pin();
126131
if (pin) {
@@ -133,27 +138,22 @@ - (void)dealloc {
133138
Isolate::Scope isolate_scope(isolate);
134139
HandleScope handle_scope(isolate);
135140
wrapper_->GetCache()->Instances.erase(self);
136-
// Detach and free only a wrapper that is still the one we attached: a
137-
// finalizer or __releaseNativeCounterpart can have retired it already,
138-
// and whatever else sits in the field belongs to another owner.
141+
// Detach only a claim that is still the one we attached: marshalling
142+
// the object once this adapter's last release has started detaches
143+
// it, and whatever else sits in the field belongs to another owner.
139144
if (dataWrapper_ != nullptr) {
140145
Local<Value> value = self->object_->Get(isolate);
141146
if (tns::GetValue(isolate, value) == dataWrapper_) {
142147
tns::DeleteValue(isolate, value);
143-
delete dataWrapper_;
144148
}
145-
dataWrapper_ = nullptr;
146149
}
147150
self->object_->Reset();
148151
}
149152
}
150153
}
151-
if (dataWrapper_ != nullptr) {
152-
// The gate is closed: the JS object and every reader of the claim are
153-
// gone, and no other path deletes an adapter claim.
154-
delete dataWrapper_;
155-
dataWrapper_ = nullptr;
156-
}
154+
// No other path frees an adapter claim, attached or not.
155+
delete dataWrapper_;
156+
dataWrapper_ = nullptr;
157157
delete wrapper_;
158158
self->object_ = nullptr;
159159
[super dealloc];

‎NativeScript/runtime/DataWrapper.h‎

Lines changed: 23 additions & 8 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>
@@ -407,14 +408,20 @@ class ObjCDataWrapper : public BaseDataWrapper {
407408

408409
const WrapperType Type() { return WrapperType::ObjCObject; }
409410

410-
id Data() { return this->data_; }
411-
412-
// True for the claim a collection adapter attaches to the plain JS object it
413-
// was built from. The adapter owns that claim exclusively -- it must stay
414-
// deletable from the adapter's -dealloc even after isolate teardown -- so no
415-
// other retirement path may free it.
416-
bool IsAdapterClaim() { return this->adapterClaim_; }
417-
void MarkAdapterClaim() { this->adapterClaim_ = true; }
411+
// A claim borrows its adapter. Weak loading atomically retains a live
412+
// adapter until the autorelease pool drains, or returns nil once its last
413+
// release has started, including while -dealloc waits for another isolate.
414+
id Data() { return adapterClaim_ ? objc_loadWeak(&data_) : data_; }
415+
416+
// The adapter owns its claim, including after isolate teardown. Retirement
417+
// of the JS object must neither release the adapter nor free the claim.
418+
bool IsAdapterClaim() { return adapterClaim_; }
419+
void MarkAdapterClaim() {
420+
id adapter = data_;
421+
data_ = nil;
422+
objc_storeWeak(&data_, adapter);
423+
adapterClaim_ = true;
424+
}
418425

419426
// Whether the object first reached JS on its runtime's thread, the stand-in
420427
// for "belongs to that thread": its native release must happen there too.
@@ -530,7 +537,14 @@ class BlockWrapper : public BaseDataWrapper {
530537

531538
const WrapperType Type() { return WrapperType::Block; }
532539

540+
// Raw access is for wrappers that own a native block. A borrowed JS block
541+
// must be retained while the mutex excludes its dispose helper.
533542
void* Block() { return this->block_; }
543+
void* RetainBlock();
544+
void ClearBlock() {
545+
std::lock_guard<std::mutex> lock(blockMutex_);
546+
block_ = nullptr;
547+
}
534548

535549
const TypeEncoding* Encodings() { return this->typeEncoding_; }
536550

@@ -540,6 +554,7 @@ class BlockWrapper : public BaseDataWrapper {
540554
bool BornOnRuntimeThread() { return this->bornOnRuntimeThread_; }
541555

542556
private:
557+
std::mutex blockMutex_;
543558
void* block_;
544559
const TypeEncoding* typeEncoding_;
545560
bool ownsBlock_;

‎NativeScript/runtime/DictionaryAdapter.mm‎

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -389,6 +389,11 @@ - (NSEnumerator*)keyEnumerator {
389389
}
390390

391391
- (void)dealloc {
392+
// Reached from a thread inside another isolate, the teardown below runs on
393+
// this adapter's own isolate instead; the object stays allocated until then.
394+
if (wrapper_->HandOffTeardown([self]() { [self dealloc]; })) {
395+
return;
396+
}
392397
{
393398
IsolatePin pin = wrapper_->Pin();
394399
if (pin) {
@@ -401,17 +406,15 @@ - (void)dealloc {
401406
Isolate::Scope isolate_scope(isolate);
402407
HandleScope handle_scope(isolate);
403408
wrapper_->GetCache()->Instances.erase(self);
404-
// Detach and free only a wrapper that is still the one we attached: a
405-
// finalizer or __releaseNativeCounterpart can have retired it already,
406-
// and whatever else sits in the field belongs to another owner.
409+
// Detach only a claim that is still the one we attached: marshalling
410+
// the object once this adapter's last release has started detaches
411+
// it, and whatever else sits in the field belongs to another owner.
407412
if (dataWrapper_ != nullptr) {
408413
Local<Value> value =
409414
claimTarget_ != nullptr ? claimTarget_->Get(isolate) : self->object_->Get(isolate);
410415
if (tns::GetValue(isolate, value) == dataWrapper_) {
411416
tns::DeleteValue(isolate, value);
412-
delete dataWrapper_;
413417
}
414-
dataWrapper_ = nullptr;
415418
}
416419
// Persistent<Value> does not reset in its destructor; the enumerators
417420
// vended by -keyEnumerator hold this adapter alive, so nothing can be
@@ -423,12 +426,9 @@ - (void)dealloc {
423426
}
424427
}
425428
}
426-
if (dataWrapper_ != nullptr) {
427-
// The gate is closed: the JS object and every reader of the claim are
428-
// gone, and no other path deletes an adapter claim.
429-
delete dataWrapper_;
430-
dataWrapper_ = nullptr;
431-
}
429+
// No other path frees an adapter claim, attached or not.
430+
delete dataWrapper_;
431+
dataWrapper_ = nullptr;
432432
self->object_ = nullptr;
433433
delete claimTarget_;
434434
claimTarget_ = nullptr;

‎NativeScript/runtime/Helpers.h‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -296,6 +296,10 @@ v8::Local<v8::Context> GetCreationContextOrCurrent(v8::Isolate* isolate,
296296
// field instead of the wrapper it read.
297297
void SetValue(v8::Isolate* isolate, const v8::Local<v8::Object>& obj, BaseDataWrapper* value);
298298
BaseDataWrapper* GetValue(v8::Isolate* isolate, const v8::Local<v8::Value>& val);
299+
// Acquires an autoreleased reference for an adapter claim. A claim whose
300+
// adapter's last release has started is detached and reads as null, so the
301+
// value gets a fresh adapter that attaches its own claim.
302+
BaseDataWrapper* GetValueForMarshalling(v8::Isolate* isolate, const v8::Local<v8::Value>& val);
299303

300304
// A tagged pointer carries its value in the pointer itself: it is never
301305
// retained, released or deallocated, and its retain count means nothing. Only

‎NativeScript/runtime/Helpers.mm‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -359,6 +359,19 @@ throw NativeScriptException(
359359
metadataProp.As<External>()->Value(v8::kExternalPointerTypeTagDefault));
360360
}
361361

362+
tns::BaseDataWrapper* tns::GetValueForMarshalling(Isolate* isolate, const Local<Value>& val) {
363+
BaseDataWrapper* wrapper = tns::GetValue(isolate, val);
364+
if (wrapper != nullptr && wrapper->Type() == WrapperType::ObjCObject &&
365+
static_cast<ObjCDataWrapper*>(wrapper)->IsAdapterClaim() &&
366+
static_cast<ObjCDataWrapper*>(wrapper)->Data() == nil) {
367+
// Detached but not freed: the dying adapter owns its claim. With the slot
368+
// empty, the replacement attaches its own and is found by later marshals.
369+
tns::DeleteValue(isolate, val);
370+
return nullptr;
371+
}
372+
return wrapper;
373+
}
374+
362375
namespace {
363376

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

‎NativeScript/runtime/Interop.h‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -289,8 +289,9 @@ class Interop {
289289
static JSBlockDescriptor kJSBlockDescriptor;
290290
} JSBlock;
291291

292-
// Takes a reference to a cached JSBlock only while it is live. Block_copy
293-
// would also revive a block whose last release already started its dispose.
292+
friend class BlockWrapper;
293+
// Called with the wrapper's mutex held, before its dispose can clear and
294+
// free the cached block. Block_copy cannot reject a deallocating block.
294295
static bool TryRetainJSBlock(JSBlock* block);
295296
};
296297

‎NativeScript/runtime/Interop.mm‎

Lines changed: 52 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,36 @@
3131
static_cast<int64_t>(kUint64AllBitsSet << 53) + 1; // -9007199254740991 (-(2^53-1))
3232
static constexpr int64_t kMaxSafeInteger = -kMinSafeInteger; // 9007199254740991 (2^53-1)
3333

34+
namespace {
35+
36+
void DisposeJSBlockWrapper(MethodCallbackWrapper* wrapper, BlockWrapper* blockWrapper) {
37+
if (wrapper->isolateWrapper_.HandOffTeardown(
38+
[wrapper, blockWrapper]() { DisposeJSBlockWrapper(wrapper, blockWrapper); })) {
39+
return;
40+
}
41+
{
42+
IsolatePin pin = wrapper->isolateWrapper_.Pin();
43+
if (pin) {
44+
Isolate* isolate = wrapper->isolateWrapper_.Isolate();
45+
v8::Locker locker(isolate);
46+
if (!wrapper->isolateWrapper_.IsTornDown()) {
47+
Isolate::Scope isolate_scope(isolate);
48+
HandleScope handle_scope(isolate);
49+
Local<Value> callback = wrapper->callback_->Get(isolate);
50+
if (!callback.IsEmpty() && callback->IsObject() &&
51+
tns::GetValue(isolate, callback) == blockWrapper) {
52+
tns::DeleteValue(isolate, callback);
53+
}
54+
wrapper->callback_->Reset();
55+
}
56+
}
57+
}
58+
delete blockWrapper;
59+
delete wrapper;
60+
}
61+
62+
} // namespace
63+
3464
Interop::JSBlock::JSBlockDescriptor Interop::JSBlock::kJSBlockDescriptor = {
3565
.reserved = 0,
3666
.size = sizeof(JSBlock),
@@ -40,49 +70,12 @@
4070
if (block->descriptor == &JSBlock::kJSBlockDescriptor) {
4171
MethodCallbackWrapper* wrapper = static_cast<MethodCallbackWrapper*>(block->userData);
4272
BlockWrapper* blockWrapper = block->blockWrapper;
43-
// Runs on whatever thread drops the last native reference. That is
44-
// safe inline: callback_ is a strong, unregistered persistent, so
45-
// resetting it never touches the finalizer drain's bookkeeping,
46-
// and a foreign-thread Locker into the block's own isolate is
47-
// legitimate now that extended class names are worker-scoped.
48-
// A thread holding another isolate's Locker is the exception: it
49-
// gets here when that isolate was handed this block, and it
50-
// deadlocks if this isolate is waiting for that Locker in turn.
51-
// Blocks shared between isolates carry that risk.
52-
//
53-
// Validity is not the test here: the slot stays reachable after
54-
// the isolate is invalidated, by JS still running under the Locker
55-
// and by the teardown's own walk of registered objects. Until the
56-
// gate closes, the wrapper is only freed once the slot is cleared.
57-
{
58-
IsolatePin pin = wrapper->isolateWrapper_.Pin();
59-
if (pin) {
60-
Isolate* isolate = wrapper->isolateWrapper_.Isolate();
61-
v8::Locker locker(isolate);
62-
if (!wrapper->isolateWrapper_.IsTornDown()) {
63-
Isolate::Scope isolate_scope(isolate);
64-
HandleScope handle_scope(isolate);
65-
Local<Value> callback = wrapper->callback_->Get(isolate);
66-
if (!callback.IsEmpty() && callback->IsObject()) {
67-
// The slot may hold another wrapper by now; only our own is
68-
// cleared from it.
69-
if (tns::GetValue(isolate, callback) == blockWrapper) {
70-
tns::DeleteValue(isolate, callback);
71-
}
72-
}
73-
// Unconditional: an already-detached callback still owns its
74-
// node, and dropping the persistent without a reset would leave
75-
// that node rooted forever.
76-
wrapper->callback_->Reset();
77-
}
78-
}
79-
}
80-
// Outside the gate: once the teardown is done the cache slot is
81-
// unreachable and nothing else can free the wrapper.
82-
delete blockWrapper;
83-
delete wrapper;
73+
// libclosure frees the block as soon as this helper returns.
74+
// Invalidate its cached address before deferring any V8 cleanup.
75+
blockWrapper->ClearBlock();
8476
ffi_closure_free(block->ffiClosure);
8577
block->~JSBlock();
78+
DisposeJSBlockWrapper(wrapper, blockWrapper);
8679
}
8780
}};
8881

@@ -113,9 +106,9 @@
113106
return wrapper->callback_->Get(isolate);
114107
}
115108

116-
// libclosure's increment ignores the deallocating bit, so Block_copy would hand
117-
// out a block whose dispose is already waiting for the isolate's Locker and
118-
// which libclosure frees right after. This CASes the same word libclosure does.
109+
// libclosure's increment ignores the deallocating bit. The wrapper's mutex
110+
// keeps the allocation alive here; this CAS also rejects a last release that
111+
// won before dispose acquired that mutex.
119112
bool Interop::TryRetainJSBlock(JSBlock* block) {
120113
volatile int32_t* flags = &block->flags;
121114
int32_t old = __atomic_load_n(flags, __ATOMIC_RELAXED);
@@ -133,6 +126,17 @@
133126
}
134127
}
135128

129+
void* BlockWrapper::RetainBlock() {
130+
if (ownsBlock_) {
131+
return Block_copy(block_);
132+
}
133+
std::lock_guard<std::mutex> lock(blockMutex_);
134+
if (block_ == nullptr || !Interop::TryRetainJSBlock(static_cast<Interop::JSBlock*>(block_))) {
135+
return nullptr;
136+
}
137+
return block_;
138+
}
139+
136140
std::pair<IMP, ffi_closure*> Interop::CreateMethodInternal(const uint8_t initialParamIndex,
137141
const uint8_t argsCount,
138142
const TypeEncoding* typeEncoding,
@@ -683,16 +687,8 @@ static bool SnapshotArrayLike(Isolate* isolate, Local<Object> object, Local<v8::
683687
// so the reference that keeps it alive across the call must be balanced:
684688
// the JSBlock dispose helper owns the ffi closure and the callback wrapper
685689
// and only runs once the last reference goes away.
686-
if (wrapper->OwnsBlock()) {
687-
// A native block, or another isolate's JS block; the wrapper's own
688-
// Block_copy keeps it alive.
689-
blockPtr = CFAutorelease(Block_copy(wrapper->Block()));
690-
} else if (TryRetainJSBlock(static_cast<JSBlock*>(wrapper->Block()))) {
691-
// Reading the block is safe even when its last release raced ahead:
692-
// until the isolate's teardown closes its gate, dispose clears this
693-
// slot under the Locker this thread holds, before libclosure frees
694-
// the block.
695-
blockPtr = CFAutorelease(wrapper->Block());
690+
if (void* block = wrapper->RetainBlock()) {
691+
blockPtr = CFAutorelease(block);
696692
}
697693
}
698694
if (blockPtr == nullptr) {
@@ -808,7 +804,7 @@ static bool SnapshotArrayLike(Isolate* isolate, Local<Object> object, Local<v8::
808804
}
809805
} else if (argHelper.isObject()) {
810806
Local<Object> obj = arg.As<Object>();
811-
BaseDataWrapper* wrapper = tns::GetValue(isolate, obj);
807+
BaseDataWrapper* wrapper = tns::GetValueForMarshalling(isolate, obj);
812808

813809
if (wrapper != nullptr) {
814810
if (wrapper->Type() == WrapperType::Enum) {
@@ -932,7 +928,7 @@ static bool SnapshotArrayLike(Isolate* isolate, Local<Object> object, Local<v8::
932928
ArrayAdapter* adapter = [[ArrayAdapter alloc] initWithJSObject:array isolate:isolate];
933929
return adapter;
934930
} else if (arg->IsObject()) {
935-
if (BaseDataWrapper* wrapper = tns::GetValue(isolate, arg)) {
931+
if (BaseDataWrapper* wrapper = tns::GetValueForMarshalling(isolate, arg)) {
936932
switch (wrapper->Type()) {
937933
case WrapperType::ObjCObject: {
938934
ObjCDataWrapper* wr = static_cast<ObjCDataWrapper*>(wrapper);

‎NativeScript/runtime/InteropTypes.mm‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -787,8 +787,7 @@
787787
// A JS function does not keep its block alive: only native
788788
// references do. A live block is kept for the rest of the turn,
789789
// like one passed to a native call; a dying one is no handle.
790-
JSBlock* block = static_cast<JSBlock*>(blockWrapper->Block());
791-
if (TryRetainJSBlock(block)) {
790+
if (void* block = blockWrapper->RetainBlock()) {
792791
CFAutorelease(block);
793792
return Pointer::NewInstance(context, block);
794793
}

0 commit comments

Comments
 (0)