Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions NativeScript/runtime/ArgConverter.mm
Original file line number Diff line number Diff line change
Expand Up @@ -686,7 +686,7 @@ throw NativeScriptException(isolate, v8::Exception::TypeError(tns::ToV8String(is
if (type == BinaryTypeEncodingType::InterfaceDeclarationReference ||
type == BinaryTypeEncodingType::InstanceTypeEncoding ||
type == BinaryTypeEncodingType::IdEncoding) {
BaseDataWrapper* baseWrapper = tns::GetValue(isolate, value);
BaseDataWrapper* baseWrapper = tns::GetValueForMarshalling(isolate, value);
if (baseWrapper != nullptr && baseWrapper->Type() == WrapperType::ObjCObject) {
ObjCDataWrapper* wrapper = static_cast<ObjCDataWrapper*>(baseWrapper);
WrapperLifetime::Escape(wrapper);
Expand Down Expand Up @@ -1505,7 +1505,7 @@ throw NativeScriptException(isolate, v8::Exception::TypeError(tns::ToV8String(is
return v8::Intercepted::kNo;
}

BaseDataWrapper* itemWrapper = tns::GetValue(isolate, value);
BaseDataWrapper* itemWrapper = tns::GetValueForMarshalling(isolate, value);
if (itemWrapper == nullptr || itemWrapper->Type() != WrapperType::ObjCObject) {
return v8::Intercepted::kNo;
}
Expand Down
79 changes: 46 additions & 33 deletions NativeScript/runtime/ArrayAdapter.mm
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,21 @@ - (instancetype)initWithJSObject:(Local<Object>)jsObject isolate:(Isolate*)isola

- (NSUInteger)count {
auto isolate = wrapper_->Isolate();
if (!wrapper_->IsValid()) {
return 0;
}
NSUInteger result = 0;
// Scopes-before-@throw: a branded escape from the JS boundary is @thrown only
// after the inner block's V8 scopes destruct.
NSException* __strong pendingThrow = nil;
{
// Any thread may read the array, so the isolate can be torn down while
// this one waits for the Locker; validity is checked again once it is held.
IsolatePin pin = wrapper_->Pin();
if (!pin || !wrapper_->IsValid()) {
return 0;
}
v8::Locker locker(isolate);
if (!wrapper_->IsValid()) {
return 0;
}
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);

Expand Down Expand Up @@ -76,10 +82,6 @@ - (NSUInteger)count {

- (id)objectAtIndex:(NSUInteger)index {
auto isolate = wrapper_->Isolate();
if (!wrapper_->IsValid()) {
return nil;
}

if (!(index < [self count])) {
// Out of bounds: return the adapter default rather than aborting.
return nil;
Expand All @@ -88,7 +90,14 @@ - (id)objectAtIndex:(NSUInteger)index {
id result = nil;
NSException* __strong pendingThrow = nil;
{
IsolatePin pin = wrapper_->Pin();
if (!pin || !wrapper_->IsValid()) {
return nil;
}
v8::Locker locker(isolate);
if (!wrapper_->IsValid()) {
return nil;
}
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);

Expand All @@ -112,35 +121,39 @@ - (id)objectAtIndex:(NSUInteger)index {
}

- (void)dealloc {
if (wrapper_->IsValid()) {
auto isolate = wrapper_->Isolate();
v8::Locker locker(isolate);
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
wrapper_->GetCache()->Instances.erase(self);
// Detach and free only a wrapper that is still the one we attached: a
// finalizer or __releaseNativeCounterpart can have retired it already, and
// whatever else sits in the field belongs to another owner. Once the
// isolate is gone the field can no longer be read, so the claim is dropped
// rather than freed blind.
if (dataWrapper_ != nullptr) {
Local<Value> value = self->object_->Get(isolate);
if (tns::GetValue(isolate, value) == dataWrapper_) {
tns::DeleteValue(isolate, value);
delete dataWrapper_;
// Reached from a thread inside another isolate, the teardown below runs on
// this adapter's own isolate instead; the object stays allocated until then.
if (wrapper_->HandOffTeardown([self]() { [self dealloc]; })) {
return;
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
{
IsolatePin pin = wrapper_->Pin();
if (pin) {
auto isolate = wrapper_->Isolate();
v8::Locker locker(isolate);
// Validity is not the test: until the teardown closes the gate it can
// still reach the claim through the JS object, so it is detached under
// the Locker even once the isolate is invalidated.
if (!wrapper_->IsTornDown()) {
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
wrapper_->GetCache()->Instances.erase(self);
// Detach only a claim that is still the one we attached: marshalling
// the object once this adapter's last release has started detaches
// it, and whatever else sits in the field belongs to another owner.
if (dataWrapper_ != nullptr) {
Local<Value> value = self->object_->Get(isolate);
if (tns::GetValue(isolate, value) == dataWrapper_) {
tns::DeleteValue(isolate, value);
}
}
self->object_->Reset();
}
dataWrapper_ = nullptr;
}
self->object_->Reset();
} else if (dataWrapper_ != nullptr) {
// The isolate is gone, and with it the JS object and every reader of the
// claim; no other path deletes one (__releaseNativeCounterpart leaves
// adapter claims attached), so the owner frees it here — adapters
// released after a worker isolate's teardown otherwise leak one wrapper
// each.
delete dataWrapper_;
dataWrapper_ = nullptr;
}
// No other path frees an adapter claim, attached or not.
delete dataWrapper_;
dataWrapper_ = nullptr;
delete wrapper_;
self->object_ = nullptr;
[super dealloc];
Expand Down
151 changes: 81 additions & 70 deletions NativeScript/runtime/ClassBuilder.mm
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@
#include "ArgConverter.h"
#include "BuiltinLoader.h"
#include "Caches.h"
#include "EventLoop.h"
#include "FastEnumerationAdapter.h"
#include "Helpers.h"
#include "Interop.h"
#include "MetadataBuilder.h"
#include "NativeScriptException.h"
#include "NativeScriptPlatform.h"
#include "ObjectManager.h"
#include "Runtime.h"
#include "TNSDerivedClass.h"
Expand Down Expand Up @@ -325,10 +327,15 @@ void ThrowTypeError(Isolate* isolate, const std::string& message) {
cache->CtorFuncs.emplace(extendedClassName, poExtendedClassCtorFunc);

IMP newInitialize = imp_implementationWithBlock(^(id self) {
if (!isolateWrapper.IsValid()) {
// +initialize runs on whichever thread first messages the class.
IsolatePin pin = isolateWrapper.Pin();
if (!pin || !isolateWrapper.IsValid()) {
return;
}
v8::Locker locker(isolate);
if (!isolateWrapper.IsValid()) {
return;
}
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
Local<Context> context = Caches::Get(isolate)->GetContext();
Expand Down Expand Up @@ -374,96 +381,100 @@ void ThrowTypeError(Isolate* isolate, const std::string& message) {
/// release the native counterpart as well.
id (*retain)(id, SEL) =
(id (*)(id, SEL))FindNotOverridenMethod(extendedClass, @selector(retain));
// Read here, on the isolate's thread: the blocks below run on any
// thread and must not reach the Runtime, which a teardown can free.
CFRunLoopRef runtimeLoop = Runtime::GetRuntime(isolate)->RuntimeLoop();
IMP newRetain = imp_implementationWithBlock(^id(id self) {
if (!isolateWrapper.IsValid()) {
if ([self retainCount] != 1) {
return retain(self, @selector(retain));
}
if ([self retainCount] == 1) {
auto runtime = Runtime::GetRuntime(isolate);
auto runtimeLoop = runtime->RuntimeLoop();
void* weakSelf = (__bridge void*)self;
auto gcProtect = [isolateWrapper, weakSelf, isolate]() {
auto innerCache = isolateWrapper.GetCache();
auto it = innerCache->Instances.find((id)weakSelf);
if (it != innerCache->Instances.end()) {
v8::Locker locker(isolate);
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
Local<Value> value = it->second->Get(isolate);
BaseDataWrapper* wrapper = tns::GetValue(isolate, value);
if (wrapper != nullptr && wrapper->Type() == WrapperType::ObjCObject) {
ObjCDataWrapper* objcWrapper = static_cast<ObjCDataWrapper*>(wrapper);
if (objcWrapper->OwnershipState() != nullptr) {
ObjectManager::ReconcileOwnership(isolate, objcWrapper);
} else {
objcWrapper->GcProtect();
}
IsolatePin pin = isolateWrapper.Pin();
if (!pin || !isolateWrapper.IsValid()) {
return retain(self, @selector(retain));
}
void* weakSelf = (__bridge void*)self;
auto gcProtect = [isolateWrapper, weakSelf, isolate]() {
v8::Locker locker(isolate);
auto innerCache = isolateWrapper.GetCache();
auto it = innerCache->Instances.find((id)weakSelf);
if (it != innerCache->Instances.end()) {
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
Local<Value> value = it->second->Get(isolate);
BaseDataWrapper* wrapper = tns::GetValue(isolate, value);
if (wrapper != nullptr && wrapper->Type() == WrapperType::ObjCObject) {
ObjCDataWrapper* objcWrapper = static_cast<ObjCDataWrapper*>(wrapper);
if (objcWrapper->OwnershipState() != nullptr) {
ObjectManager::ReconcileOwnership(isolate, objcWrapper);
} else {
objcWrapper->GcProtect();
}
}
};
// After the retain: reconciling reads the new retain count.
id result = retain(self, @selector(retain));
if (CFRunLoopGetCurrent() != runtimeLoop) {
// bare entry: the closure does its own Locker ceremony, exactly
// like the performed block it replaces
runtime->GetEventLoop()->PostInternalBare(gcProtect);
} else {
gcProtect();
}
return result;
};
// After the retain: reconciling reads the new retain count.
id result = retain(self, @selector(retain));
if (CFRunLoopGetCurrent() != runtimeLoop) {
// bare entry: the closure does its own Locker ceremony
std::shared_ptr<EventLoop> loop =
NativeScriptPlatform::Instance()->LookupEventLoop(isolate);
if (loop != nullptr) {
loop->PostInternalBare(gcProtect);
}
} else {
gcProtect();
}

return retain(self, @selector(retain));
return result;
});
class_addMethod(extendedClass, @selector(retain), newRetain, "@@:");

void (*release)(id, SEL) =
(void (*)(id, SEL))FindNotOverridenMethod(extendedClass, @selector(release));
IMP newRelease = imp_implementationWithBlock(^(id self) {
if (!isolateWrapper.IsValid()) {
if ([self retainCount] != 2) {
release(self, @selector(release));
return;
}

if ([self retainCount] == 2) {
void* weakSelf = (__bridge void*)self;
auto gcUnprotect = [isolateWrapper, weakSelf, isolate]() {
auto innerCache = isolateWrapper.GetCache();
auto it = innerCache->Instances.find((id)weakSelf);
if (it != innerCache->Instances.end()) {
v8::Locker locker(isolate);
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
if (it->second != nullptr) {
Local<Value> value = it->second->Get(isolate);
BaseDataWrapper* wrapper = tns::GetValue(isolate, value);
if (wrapper != nullptr && wrapper->Type() == WrapperType::ObjCObject) {
ObjCDataWrapper* objcWrapper = static_cast<ObjCDataWrapper*>(wrapper);
if (objcWrapper->OwnershipState() != nullptr) {
ObjectManager::ReconcileOwnership(isolate, objcWrapper);
} else {
objcWrapper->GcUnprotect();
}
IsolatePin pin = isolateWrapper.Pin();
if (!pin || !isolateWrapper.IsValid()) {
release(self, @selector(release));
return;
}
void* weakSelf = (__bridge void*)self;
auto gcUnprotect = [isolateWrapper, weakSelf, isolate]() {
v8::Locker locker(isolate);
auto innerCache = isolateWrapper.GetCache();
auto it = innerCache->Instances.find((id)weakSelf);
if (it != innerCache->Instances.end()) {
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
if (it->second != nullptr) {
Local<Value> value = it->second->Get(isolate);
BaseDataWrapper* wrapper = tns::GetValue(isolate, value);
if (wrapper != nullptr && wrapper->Type() == WrapperType::ObjCObject) {
ObjCDataWrapper* objcWrapper = static_cast<ObjCDataWrapper*>(wrapper);
if (objcWrapper->OwnershipState() != nullptr) {
ObjectManager::ReconcileOwnership(isolate, objcWrapper);
} else {
objcWrapper->GcUnprotect();
}
}
}
};
auto runtime = Runtime::GetRuntime(isolate);
auto runtimeLoop = runtime->RuntimeLoop();
// After the release: reconciling reads the new retain count, and
// the Instances entry still holds the object.
release(self, @selector(release));
if (CFRunLoopGetCurrent() != runtimeLoop) {
// bare entry: the closure does its own Locker ceremony, exactly
// like the performed block it replaces
runtime->GetEventLoop()->PostInternalBare(gcUnprotect);
} else {
gcUnprotect();
}
return;
}

};
// After the release: reconciling reads the new retain count, and
// the Instances entry still holds the object.
release(self, @selector(release));
if (CFRunLoopGetCurrent() != runtimeLoop) {
// bare entry: the closure does its own Locker ceremony
std::shared_ptr<EventLoop> loop =
NativeScriptPlatform::Instance()->LookupEventLoop(isolate);
if (loop != nullptr) {
loop->PostInternalBare(gcUnprotect);
}
} else {
gcUnprotect();
}
});
class_addMethod(extendedClass, @selector(release), newRelease, "v@:");
if (auto* tracked = Caches::StateFor<RetainTrackedClasses>(isolate)) {
Expand Down
31 changes: 23 additions & 8 deletions NativeScript/runtime/DataWrapper.h
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

#include <objc/runtime.h>

#include <atomic>
#include <functional>
#include <mutex>
#include <optional>
Expand Down Expand Up @@ -407,14 +408,20 @@ class ObjCDataWrapper : public BaseDataWrapper {

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

id Data() { return this->data_; }

// True for the claim a collection adapter attaches to the plain JS object it
// was built from. The adapter owns that claim exclusively -- it must stay
// deletable from the adapter's -dealloc even after isolate teardown -- so no
// other retirement path may free it.
bool IsAdapterClaim() { return this->adapterClaim_; }
void MarkAdapterClaim() { this->adapterClaim_ = true; }
// A claim borrows its adapter. Weak loading atomically retains a live
// adapter until the autorelease pool drains, or returns nil once its last
// release has started, including while -dealloc waits for another isolate.
id Data() { return adapterClaim_ ? objc_loadWeak(&data_) : data_; }
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

// The adapter owns its claim, including after isolate teardown. Retirement
// of the JS object must neither release the adapter nor free the claim.
bool IsAdapterClaim() { return adapterClaim_; }
void MarkAdapterClaim() {
id adapter = data_;
data_ = nil;
objc_storeWeak(&data_, adapter);
adapterClaim_ = true;
}

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

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

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

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

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

private:
std::mutex blockMutex_;
void* block_;
const TypeEncoding* typeEncoding_;
bool ownsBlock_;
Expand Down
Loading
Loading