Skip to content

Commit 80c0723

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. Adapter methods and teardown pin the isolate before waiting for its Locker and check it again under the lock. 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 20935bd commit 80c0723

17 files changed

Lines changed: 473 additions & 173 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: 33 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -38,16 +38,20 @@ - (instancetype)initWithJSObject:(Local<Object>)jsObject isolate:(Isolate*)isola
3838
}
3939

4040
- (NSUInteger)count {
41-
auto isolate = wrapper_->Isolate();
42-
if (!wrapper_->IsValid()) {
41+
IsolatePin pin = wrapper_->Pin();
42+
if (!pin) {
4343
return 0;
4444
}
45+
Isolate* isolate = wrapper_->Isolate();
4546
NSUInteger result = 0;
4647
// Scopes-before-@throw: a branded escape from the JS boundary is @thrown only
4748
// after the inner block's V8 scopes destruct.
4849
NSException* __strong pendingThrow = nil;
4950
{
5051
v8::Locker locker(isolate);
52+
if (!wrapper_->IsValid()) {
53+
return 0;
54+
}
5155
Isolate::Scope isolate_scope(isolate);
5256
HandleScope handle_scope(isolate);
5357

@@ -75,10 +79,11 @@ - (NSUInteger)count {
7579
}
7680

7781
- (id)objectAtIndex:(NSUInteger)index {
78-
auto isolate = wrapper_->Isolate();
79-
if (!wrapper_->IsValid()) {
82+
IsolatePin pin = wrapper_->Pin();
83+
if (!pin) {
8084
return nil;
8185
}
86+
Isolate* isolate = wrapper_->Isolate();
8287

8388
if (!(index < [self count])) {
8489
// Out of bounds: return the adapter default rather than aborting.
@@ -89,6 +94,9 @@ - (id)objectAtIndex:(NSUInteger)index {
8994
NSException* __strong pendingThrow = nil;
9095
{
9196
v8::Locker locker(isolate);
97+
if (!wrapper_->IsValid()) {
98+
return nil;
99+
}
92100
Isolate::Scope isolate_scope(isolate);
93101
HandleScope handle_scope(isolate);
94102

@@ -112,35 +120,32 @@ - (id)objectAtIndex:(NSUInteger)index {
112120
}
113121

114122
- (void)dealloc {
115-
if (wrapper_->IsValid()) {
123+
// Reached from a thread inside another isolate, the teardown below runs on
124+
// this adapter's own isolate instead; the object stays allocated until then.
125+
if (wrapper_->HandOffTeardown([self]() { [self dealloc]; })) {
126+
return;
127+
}
128+
IsolatePin pin = wrapper_->Pin();
129+
if (pin) {
116130
auto isolate = wrapper_->Isolate();
117131
v8::Locker locker(isolate);
118-
Isolate::Scope isolate_scope(isolate);
119-
HandleScope handle_scope(isolate);
120-
wrapper_->GetCache()->Instances.erase(self);
121-
// Detach and free only a wrapper that is still the one we attached: a
122-
// finalizer or __releaseNativeCounterpart can have retired it already, and
123-
// whatever else sits in the field belongs to another owner. Once the
124-
// isolate is gone the field can no longer be read, so the claim is dropped
125-
// rather than freed blind.
126-
if (dataWrapper_ != nullptr) {
127-
Local<Value> value = self->object_->Get(isolate);
128-
if (tns::GetValue(isolate, value) == dataWrapper_) {
129-
tns::DeleteValue(isolate, value);
130-
delete dataWrapper_;
132+
// Invalidation precedes the runtime's wrapper walk. Detach while that
133+
// walk can still reach the claim, even if IsValid() already reads false.
134+
if (!wrapper_->IsTornDown()) {
135+
Isolate::Scope isolate_scope(isolate);
136+
HandleScope handle_scope(isolate);
137+
wrapper_->GetCache()->Instances.erase(self);
138+
if (dataWrapper_ != nullptr) {
139+
Local<Value> value = self->object_->Get(isolate);
140+
if (tns::GetValue(isolate, value) == dataWrapper_) {
141+
tns::DeleteValue(isolate, value);
142+
}
131143
}
132-
dataWrapper_ = nullptr;
144+
self->object_->Reset();
133145
}
134-
self->object_->Reset();
135-
} else if (dataWrapper_ != nullptr) {
136-
// The isolate is gone, and with it the JS object and every reader of the
137-
// claim; no other path deletes one (__releaseNativeCounterpart leaves
138-
// adapter claims attached), so the owner frees it here — adapters
139-
// released after a worker isolate's teardown otherwise leak one wrapper
140-
// each.
141-
delete dataWrapper_;
142-
dataWrapper_ = nullptr;
143146
}
147+
delete dataWrapper_;
148+
dataWrapper_ = nullptr;
144149
delete wrapper_;
145150
self->object_ = nullptr;
146151
[super dealloc];

‎NativeScript/runtime/DataWrapper.h‎

Lines changed: 30 additions & 9 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>
@@ -398,16 +399,28 @@ class ObjCDataWrapper : public BaseDataWrapper {
398399
typeEncoding_(typeEncoding),
399400
klass_(object_getClass(data)) {}
400401

401-
const WrapperType Type() { return WrapperType::ObjCObject; }
402-
403-
id Data() { return this->data_; }
402+
~ObjCDataWrapper() override {
403+
if (adapterClaim_) {
404+
objc_storeWeak(&data_, nil);
405+
}
406+
}
404407

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

412425
const TypeEncoding* TypeEncoding() { return this->typeEncoding_; }
413426

@@ -492,13 +505,21 @@ class BlockWrapper : public BaseDataWrapper {
492505

493506
const WrapperType Type() { return WrapperType::Block; }
494507

508+
// Raw access is for wrappers that own a native block. A borrowed JS block
509+
// must be retained while the mutex excludes its dispose helper.
495510
void* Block() { return this->block_; }
511+
void* RetainBlock();
512+
void ClearBlock() {
513+
std::lock_guard<std::mutex> lock(blockMutex_);
514+
block_ = nullptr;
515+
}
496516

497517
const TypeEncoding* Encodings() { return this->typeEncoding_; }
498518

499519
bool OwnsBlock() { return this->ownsBlock_; }
500520

501521
private:
522+
std::mutex blockMutex_;
502523
void* block_;
503524
const TypeEncoding* typeEncoding_;
504525
bool ownsBlock_;

‎NativeScript/runtime/DictionaryAdapter.mm‎

Lines changed: 59 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,8 @@ - (instancetype)initWithMap:(std::shared_ptr<Persistent<Value>>)map
4141
}
4242

4343
- (id)nextObject {
44-
if (!wrapper_->IsValid()) {
44+
IsolatePin pin = wrapper_->Pin();
45+
if (!pin) {
4546
return nil;
4647
}
4748
Isolate* isolate = wrapper_->Isolate();
@@ -51,6 +52,9 @@ - (id)nextObject {
5152
NSException* __strong pendingThrow = nil;
5253
{
5354
v8::Locker locker(isolate);
55+
if (!wrapper_->IsValid()) {
56+
return nil;
57+
}
5458
Isolate::Scope isolate_scope(isolate);
5559
HandleScope handle_scope(isolate);
5660

@@ -140,14 +144,18 @@ - (instancetype)initWithProperties:(std::shared_ptr<Persistent<Value>>)dictionar
140144
}
141145

142146
- (id)nextObject {
143-
if (!wrapper_->IsValid()) {
147+
IsolatePin pin = wrapper_->Pin();
148+
if (!pin) {
144149
return nil;
145150
}
146151
Isolate* isolate = wrapper_->Isolate();
147152
NSString* result = nil;
148153
NSException* __strong pendingThrow = nil;
149154
{
150155
v8::Locker locker(isolate);
156+
if (!wrapper_->IsValid()) {
157+
return nil;
158+
}
151159
Isolate::Scope isolate_scope(isolate);
152160
HandleScope handle_scope(isolate);
153161

@@ -174,14 +182,18 @@ - (id)nextObject {
174182
}
175183

176184
- (NSArray*)allObjects {
177-
if (!wrapper_->IsValid()) {
185+
IsolatePin pin = wrapper_->Pin();
186+
if (!pin) {
178187
return nil;
179188
}
180189
Isolate* isolate = wrapper_->Isolate();
181190
NSMutableArray* array = [NSMutableArray array];
182191
NSException* __strong pendingThrow = nil;
183192
{
184193
v8::Locker locker(isolate);
194+
if (!wrapper_->IsValid()) {
195+
return nil;
196+
}
185197
Isolate::Scope isolate_scope(isolate);
186198
HandleScope handle_scope(isolate);
187199

@@ -256,14 +268,18 @@ - (instancetype)initWithJSObject:(Local<Object>)jsObject isolate:(Isolate*)isola
256268
}
257269

258270
- (NSUInteger)count {
259-
if (!wrapper_->IsValid()) {
271+
IsolatePin pin = wrapper_->Pin();
272+
if (!pin) {
260273
return 0;
261274
}
262275
Isolate* isolate = wrapper_->Isolate();
263276
NSUInteger result = 0;
264277
NSException* __strong pendingThrow = nil;
265278
{
266279
v8::Locker locker(isolate);
280+
if (!wrapper_->IsValid()) {
281+
return 0;
282+
}
267283
Isolate::Scope isolate_scope(isolate);
268284
HandleScope handle_scope(isolate);
269285

@@ -292,14 +308,18 @@ - (NSUInteger)count {
292308
}
293309

294310
- (id)objectForKey:(id)aKey {
295-
if (!wrapper_->IsValid()) {
311+
IsolatePin pin = wrapper_->Pin();
312+
if (!pin) {
296313
return nil;
297314
}
298315
Isolate* isolate = wrapper_->Isolate();
299316
id result = nil;
300317
NSException* __strong pendingThrow = nil;
301318
{
302319
v8::Locker locker(isolate);
320+
if (!wrapper_->IsValid()) {
321+
return nil;
322+
}
303323
Isolate::Scope isolate_scope(isolate);
304324
HandleScope handle_scope(isolate);
305325

@@ -343,11 +363,15 @@ - (id)objectForKey:(id)aKey {
343363
}
344364

345365
- (NSEnumerator*)keyEnumerator {
346-
if (!wrapper_->IsValid()) {
366+
IsolatePin pin = wrapper_->Pin();
367+
if (!pin) {
347368
return nil;
348369
}
349370
Isolate* isolate = wrapper_->Isolate();
350371
v8::Locker locker(isolate);
372+
if (!wrapper_->IsValid()) {
373+
return nil;
374+
}
351375
Isolate::Scope isolate_scope(isolate);
352376
HandleScope handle_scope(isolate);
353377

@@ -365,42 +389,39 @@ - (NSEnumerator*)keyEnumerator {
365389
}
366390

367391
- (void)dealloc {
368-
if (wrapper_->IsValid()) {
369-
Isolate* isolate = wrapper_->Isolate();
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+
}
397+
IsolatePin pin = wrapper_->Pin();
398+
if (pin) {
399+
auto isolate = wrapper_->Isolate();
370400
v8::Locker locker(isolate);
371-
Isolate::Scope isolate_scope(isolate);
372-
HandleScope handle_scope(isolate);
373-
wrapper_->GetCache()->Instances.erase(self);
374-
// Detach and free only a wrapper that is still the one we attached: a
375-
// finalizer or __releaseNativeCounterpart can have retired it already, and
376-
// whatever else sits in the field belongs to another owner. Once the
377-
// isolate is gone the field can no longer be read, so the claim is dropped
378-
// rather than freed blind.
379-
if (dataWrapper_ != nullptr) {
380-
Local<Value> value =
381-
claimTarget_ != nullptr ? claimTarget_->Get(isolate) : self->object_->Get(isolate);
382-
if (tns::GetValue(isolate, value) == dataWrapper_) {
383-
tns::DeleteValue(isolate, value);
384-
delete dataWrapper_;
401+
// Invalidation precedes the runtime's wrapper walk. Detach while that
402+
// walk can still reach the claim, even if IsValid() already reads false.
403+
if (!wrapper_->IsTornDown()) {
404+
Isolate::Scope isolate_scope(isolate);
405+
HandleScope handle_scope(isolate);
406+
wrapper_->GetCache()->Instances.erase(self);
407+
if (dataWrapper_ != nullptr) {
408+
Local<Value> value =
409+
claimTarget_ != nullptr ? claimTarget_->Get(isolate) : self->object_->Get(isolate);
410+
if (tns::GetValue(isolate, value) == dataWrapper_) {
411+
tns::DeleteValue(isolate, value);
412+
}
413+
}
414+
// Persistent<Value> does not reset in its destructor; the enumerators
415+
// vended by -keyEnumerator hold this adapter alive, so nothing can be
416+
// reading the handle by the time this runs.
417+
self->object_->Reset();
418+
if (claimTarget_ != nullptr) {
419+
claimTarget_->Reset();
385420
}
386-
dataWrapper_ = nullptr;
387-
}
388-
// Persistent<Value> does not reset in its destructor; the enumerators
389-
// vended by -keyEnumerator hold this adapter alive, so nothing can be
390-
// reading the handle by the time this runs.
391-
self->object_->Reset();
392-
if (claimTarget_ != nullptr) {
393-
claimTarget_->Reset();
394421
}
395-
} else if (dataWrapper_ != nullptr) {
396-
// The isolate is gone, and with it the JS object and every reader of the
397-
// claim; no other path deletes one (__releaseNativeCounterpart leaves
398-
// adapter claims attached), so the owner frees it here — adapters
399-
// released after a worker isolate's teardown otherwise leak one wrapper
400-
// each.
401-
delete dataWrapper_;
402-
dataWrapper_ = nullptr;
403422
}
423+
delete dataWrapper_;
424+
dataWrapper_ = nullptr;
404425
self->object_ = nullptr;
405426
delete claimTarget_;
406427
claimTarget_ = nullptr;

‎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+
// Acquires an autoreleased reference for an adapter claim. A claim whose
296+
// adapter's last release has started is detached and reads as null, so the
297+
// value gets a fresh adapter that attaches its own claim.
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

0 commit comments

Comments
 (0)