Skip to content

Commit c3ee452

Browse files
edusperoniadrian-niculescu
authored andcommitted
fix(runtime): pin the isolate gate at the remaining foreign-thread entries
The collection adapters, the extended classes' synthesized methods and the JS property accessors installed on native classes all checked IsolateWrapper::IsValid() and then waited for the isolate's Locker. A thread that passed the check could get the Locker only after ~Runtime had removed the isolate's Caches, or after Isolate::Dispose, and then read a null context or a freed isolate. These entries now follow ArgConverter::MethodCallback: pin the gate, bail when the pin is refused or the isolate is invalid, take the Locker, and check validity again under it. - ArrayAdapter, DictionaryAdapter and its key enumerators: count, objectAtIndex:, objectForKey:, keyEnumerator, nextObject and allObjects return 0/nil once the isolate is gone. - Adapter -dealloc (Array, Dictionary, NSData): like the JS block dispose, it detaches its claim under the Locker until the gate closes, even after the isolate is invalidated, because the teardown can still reach the claim through the JS object. Once the gate is closed it frees the claim without the Locker. - Extended class +initialize: skipped once the isolate is gone. - Extended class retain/release: pin only on the retain counts that toggle GC protection. The foreign-thread path posts through NativeScriptPlatform::LookupEventLoop and checks the runtime thread captured at __extends time instead of reading the Runtime, which the teardown frees. The protect/unprotect closures take the Locker before they read Instances. - PropertyCallbackContext carries an IsolateWrapper, and the property getter/setter callbacks of ClassBuilder and MetadataBuilder pin like MethodCallback: a getter returns a zeroed value and a setter does nothing once the isolate is gone.
1 parent eca990d commit c3ee452

5 files changed

Lines changed: 230 additions & 171 deletions

File tree

‎NativeScript/runtime/ArrayAdapter.mm‎

Lines changed: 44 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -39,15 +39,21 @@ - (instancetype)initWithJSObject:(Local<Object>)jsObject isolate:(Isolate*)isola
3939

4040
- (NSUInteger)count {
4141
auto isolate = wrapper_->Isolate();
42-
if (!wrapper_->IsValid()) {
43-
return 0;
44-
}
4542
NSUInteger result = 0;
4643
// Scopes-before-@throw: a branded escape from the JS boundary is @thrown only
4744
// after the inner block's V8 scopes destruct.
4845
NSException* __strong pendingThrow = nil;
4946
{
47+
// Any thread may read the array, so the isolate can be torn down while
48+
// this one waits for the Locker; validity is checked again once it is held.
49+
IsolatePin pin = wrapper_->Pin();
50+
if (!pin || !wrapper_->IsValid()) {
51+
return 0;
52+
}
5053
v8::Locker locker(isolate);
54+
if (!wrapper_->IsValid()) {
55+
return 0;
56+
}
5157
Isolate::Scope isolate_scope(isolate);
5258
HandleScope handle_scope(isolate);
5359

@@ -76,10 +82,6 @@ - (NSUInteger)count {
7682

7783
- (id)objectAtIndex:(NSUInteger)index {
7884
auto isolate = wrapper_->Isolate();
79-
if (!wrapper_->IsValid()) {
80-
return nil;
81-
}
82-
8385
if (!(index < [self count])) {
8486
// Out of bounds: return the adapter default rather than aborting.
8587
return nil;
@@ -88,7 +90,14 @@ - (id)objectAtIndex:(NSUInteger)index {
8890
id result = nil;
8991
NSException* __strong pendingThrow = nil;
9092
{
93+
IsolatePin pin = wrapper_->Pin();
94+
if (!pin || !wrapper_->IsValid()) {
95+
return nil;
96+
}
9197
v8::Locker locker(isolate);
98+
if (!wrapper_->IsValid()) {
99+
return nil;
100+
}
92101
Isolate::Scope isolate_scope(isolate);
93102
HandleScope handle_scope(isolate);
94103

@@ -112,32 +121,36 @@ - (id)objectAtIndex:(NSUInteger)index {
112121
}
113122

114123
- (void)dealloc {
115-
if (wrapper_->IsValid()) {
116-
auto isolate = wrapper_->Isolate();
117-
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_;
124+
{
125+
IsolatePin pin = wrapper_->Pin();
126+
if (pin) {
127+
auto isolate = wrapper_->Isolate();
128+
v8::Locker locker(isolate);
129+
// Validity is not the test: until the teardown closes the gate it can
130+
// still reach the claim through the JS object, so it is detached under
131+
// the Locker even once the isolate is invalidated.
132+
if (!wrapper_->IsTornDown()) {
133+
Isolate::Scope isolate_scope(isolate);
134+
HandleScope handle_scope(isolate);
135+
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.
139+
if (dataWrapper_ != nullptr) {
140+
Local<Value> value = self->object_->Get(isolate);
141+
if (tns::GetValue(isolate, value) == dataWrapper_) {
142+
tns::DeleteValue(isolate, value);
143+
delete dataWrapper_;
144+
}
145+
dataWrapper_ = nullptr;
146+
}
147+
self->object_->Reset();
131148
}
132-
dataWrapper_ = nullptr;
133149
}
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.
150+
}
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.
141154
delete dataWrapper_;
142155
dataWrapper_ = nullptr;
143156
}

‎NativeScript/runtime/ClassBuilder.mm‎

Lines changed: 81 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,13 @@
66
#include "ArgConverter.h"
77
#include "BuiltinLoader.h"
88
#include "Caches.h"
9+
#include "EventLoop.h"
910
#include "FastEnumerationAdapter.h"
1011
#include "Helpers.h"
1112
#include "Interop.h"
1213
#include "MetadataBuilder.h"
1314
#include "NativeScriptException.h"
15+
#include "NativeScriptPlatform.h"
1416
#include "ObjectManager.h"
1517
#include "Runtime.h"
1618
#include "TNSDerivedClass.h"
@@ -325,10 +327,15 @@ void ThrowTypeError(Isolate* isolate, const std::string& message) {
325327
cache->CtorFuncs.emplace(extendedClassName, poExtendedClassCtorFunc);
326328

327329
IMP newInitialize = imp_implementationWithBlock(^(id self) {
328-
if (!isolateWrapper.IsValid()) {
330+
// +initialize runs on whichever thread first messages the class.
331+
IsolatePin pin = isolateWrapper.Pin();
332+
if (!pin || !isolateWrapper.IsValid()) {
329333
return;
330334
}
331335
v8::Locker locker(isolate);
336+
if (!isolateWrapper.IsValid()) {
337+
return;
338+
}
332339
Isolate::Scope isolate_scope(isolate);
333340
HandleScope handle_scope(isolate);
334341
Local<Context> context = Caches::Get(isolate)->GetContext();
@@ -374,94 +381,100 @@ void ThrowTypeError(Isolate* isolate, const std::string& message) {
374381
/// release the native counterpart as well.
375382
id (*retain)(id, SEL) =
376383
(id (*)(id, SEL))FindNotOverridenMethod(extendedClass, @selector(retain));
384+
// Read here, on the isolate's thread: the blocks below run on any
385+
// thread and must not reach the Runtime, which a teardown can free.
386+
pthread_t runtimeThread = Runtime::GetRuntime(isolate)->RuntimeThread();
377387
IMP newRetain = imp_implementationWithBlock(^id(id self) {
378-
if (!isolateWrapper.IsValid()) {
388+
if ([self retainCount] != 1) {
379389
return retain(self, @selector(retain));
380390
}
381-
if ([self retainCount] == 1) {
382-
auto runtime = Runtime::GetRuntime(isolate);
383-
void* weakSelf = (__bridge void*)self;
384-
auto gcProtect = [isolateWrapper, weakSelf, isolate]() {
385-
auto innerCache = isolateWrapper.GetCache();
386-
auto it = innerCache->Instances.find((id)weakSelf);
387-
if (it != innerCache->Instances.end()) {
388-
v8::Locker locker(isolate);
389-
Isolate::Scope isolate_scope(isolate);
390-
HandleScope handle_scope(isolate);
391-
Local<Value> value = it->second->Get(isolate);
392-
BaseDataWrapper* wrapper = tns::GetValue(isolate, value);
393-
if (wrapper != nullptr && wrapper->Type() == WrapperType::ObjCObject) {
394-
ObjCDataWrapper* objcWrapper = static_cast<ObjCDataWrapper*>(wrapper);
395-
if (objcWrapper->OwnershipState() != nullptr) {
396-
ObjectManager::ReconcileOwnership(isolate, objcWrapper);
397-
} else {
398-
objcWrapper->GcProtect();
399-
}
391+
IsolatePin pin = isolateWrapper.Pin();
392+
if (!pin || !isolateWrapper.IsValid()) {
393+
return retain(self, @selector(retain));
394+
}
395+
void* weakSelf = (__bridge void*)self;
396+
auto gcProtect = [isolateWrapper, weakSelf, isolate]() {
397+
v8::Locker locker(isolate);
398+
auto innerCache = isolateWrapper.GetCache();
399+
auto it = innerCache->Instances.find((id)weakSelf);
400+
if (it != innerCache->Instances.end()) {
401+
Isolate::Scope isolate_scope(isolate);
402+
HandleScope handle_scope(isolate);
403+
Local<Value> value = it->second->Get(isolate);
404+
BaseDataWrapper* wrapper = tns::GetValue(isolate, value);
405+
if (wrapper != nullptr && wrapper->Type() == WrapperType::ObjCObject) {
406+
ObjCDataWrapper* objcWrapper = static_cast<ObjCDataWrapper*>(wrapper);
407+
if (objcWrapper->OwnershipState() != nullptr) {
408+
ObjectManager::ReconcileOwnership(isolate, objcWrapper);
409+
} else {
410+
objcWrapper->GcProtect();
400411
}
401412
}
402-
};
403-
// After the retain: reconciling reads the new retain count.
404-
id result = retain(self, @selector(retain));
405-
if (!runtime->IsOnRuntimeThread()) {
406-
// bare entry: the closure does its own Locker ceremony, exactly
407-
// like the performed block it replaces
408-
runtime->GetEventLoop()->PostInternalBare(gcProtect);
409-
} else {
410-
gcProtect();
411413
}
412-
return result;
414+
};
415+
// After the retain: reconciling reads the new retain count.
416+
id result = retain(self, @selector(retain));
417+
if (!pthread_equal(pthread_self(), runtimeThread)) {
418+
// bare entry: the closure does its own Locker ceremony
419+
std::shared_ptr<EventLoop> loop =
420+
NativeScriptPlatform::Instance()->LookupEventLoop(isolate);
421+
if (loop != nullptr) {
422+
loop->PostInternalBare(gcProtect);
423+
}
424+
} else {
425+
gcProtect();
413426
}
414-
415-
return retain(self, @selector(retain));
427+
return result;
416428
});
417429
class_addMethod(extendedClass, @selector(retain), newRetain, "@@:");
418430

419431
void (*release)(id, SEL) =
420432
(void (*)(id, SEL))FindNotOverridenMethod(extendedClass, @selector(release));
421433
IMP newRelease = imp_implementationWithBlock(^(id self) {
422-
if (!isolateWrapper.IsValid()) {
434+
if ([self retainCount] != 2) {
423435
release(self, @selector(release));
424436
return;
425437
}
426-
427-
if ([self retainCount] == 2) {
428-
void* weakSelf = (__bridge void*)self;
429-
auto gcUnprotect = [isolateWrapper, weakSelf, isolate]() {
430-
auto innerCache = isolateWrapper.GetCache();
431-
auto it = innerCache->Instances.find((id)weakSelf);
432-
if (it != innerCache->Instances.end()) {
433-
v8::Locker locker(isolate);
434-
Isolate::Scope isolate_scope(isolate);
435-
HandleScope handle_scope(isolate);
436-
if (it->second != nullptr) {
437-
Local<Value> value = it->second->Get(isolate);
438-
BaseDataWrapper* wrapper = tns::GetValue(isolate, value);
439-
if (wrapper != nullptr && wrapper->Type() == WrapperType::ObjCObject) {
440-
ObjCDataWrapper* objcWrapper = static_cast<ObjCDataWrapper*>(wrapper);
441-
if (objcWrapper->OwnershipState() != nullptr) {
442-
ObjectManager::ReconcileOwnership(isolate, objcWrapper);
443-
} else {
444-
objcWrapper->GcUnprotect();
445-
}
438+
IsolatePin pin = isolateWrapper.Pin();
439+
if (!pin || !isolateWrapper.IsValid()) {
440+
release(self, @selector(release));
441+
return;
442+
}
443+
void* weakSelf = (__bridge void*)self;
444+
auto gcUnprotect = [isolateWrapper, weakSelf, isolate]() {
445+
v8::Locker locker(isolate);
446+
auto innerCache = isolateWrapper.GetCache();
447+
auto it = innerCache->Instances.find((id)weakSelf);
448+
if (it != innerCache->Instances.end()) {
449+
Isolate::Scope isolate_scope(isolate);
450+
HandleScope handle_scope(isolate);
451+
if (it->second != nullptr) {
452+
Local<Value> value = it->second->Get(isolate);
453+
BaseDataWrapper* wrapper = tns::GetValue(isolate, value);
454+
if (wrapper != nullptr && wrapper->Type() == WrapperType::ObjCObject) {
455+
ObjCDataWrapper* objcWrapper = static_cast<ObjCDataWrapper*>(wrapper);
456+
if (objcWrapper->OwnershipState() != nullptr) {
457+
ObjectManager::ReconcileOwnership(isolate, objcWrapper);
458+
} else {
459+
objcWrapper->GcUnprotect();
446460
}
447461
}
448462
}
449-
};
450-
auto runtime = Runtime::GetRuntime(isolate);
451-
// After the release: reconciling reads the new retain count, and
452-
// the Instances entry still holds the object.
453-
release(self, @selector(release));
454-
if (!runtime->IsOnRuntimeThread()) {
455-
// bare entry: the closure does its own Locker ceremony, exactly
456-
// like the performed block it replaces
457-
runtime->GetEventLoop()->PostInternalBare(gcUnprotect);
458-
} else {
459-
gcUnprotect();
460463
}
461-
return;
462-
}
463-
464+
};
465+
// After the release: reconciling reads the new retain count, and
466+
// the Instances entry still holds the object.
464467
release(self, @selector(release));
468+
if (!pthread_equal(pthread_self(), runtimeThread)) {
469+
// bare entry: the closure does its own Locker ceremony
470+
std::shared_ptr<EventLoop> loop =
471+
NativeScriptPlatform::Instance()->LookupEventLoop(isolate);
472+
if (loop != nullptr) {
473+
loop->PostInternalBare(gcUnprotect);
474+
}
475+
} else {
476+
gcUnprotect();
477+
}
465478
});
466479
class_addMethod(extendedClass, @selector(release), newRelease, "v@:");
467480
if (auto* tracked = Caches::StateFor<RetainTrackedClasses>(isolate)) {

0 commit comments

Comments
 (0)