Skip to content
Merged
18 changes: 18 additions & 0 deletions NativeScript/runtime/ArgConverter.h
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,24 @@ class ArgConverter {
void** argValues, void* userData);
};

// The JS receiver for a native-to-JS callback on `self`: the cached wrapper,
// or a new one (borrowed and detached on scope exit when `self` is in
// -dealloc). Live only inside the callback's V8 scopes, and destroyed before
// anything is @thrown out of the callback.
class NativeCallbackSelf {
public:
NativeCallbackSelf(v8::Local<v8::Context> context, id self);
~NativeCallbackSelf();
NativeCallbackSelf(const NativeCallbackSelf&) = delete;
NativeCallbackSelf& operator=(const NativeCallbackSelf&) = delete;
v8::Local<v8::Object> Get() const { return receiver_; }

private:
v8::Isolate* isolate_;
v8::Local<v8::Object> receiver_;
ObjCDataWrapper* borrowed_ = nullptr;
};

} // namespace tns

#endif /* ArgConverter_h */
74 changes: 44 additions & 30 deletions NativeScript/runtime/ArgConverter.mm
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#include "ArgConverter.h"
#include <Foundation/Foundation.h>
#include <algorithm>
#include <optional>
#include <sstream>
#include "ClassBuilder.h"
#include "DictionaryAdapter.h"
Expand Down Expand Up @@ -48,24 +49,34 @@ bool InMethodFamily(SEL selector, const char* family) {
return strncmp(name, family, length) == 0 && (name[length] < 'a' || name[length] > 'z');
}

// The borrowed wrapper WrapNativeCallbackSelf made for an object in -dealloc
// is detached once the native call returns: the object is gone afterwards,
// so a receiver JS kept must read as released.
struct BorrowedSelfScope {
explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {}
~BorrowedSelfScope() {
if (wrapper != nullptr && tns::GetValue(isolate, receiver) == wrapper) {
tns::SetValue(isolate, receiver, nullptr);
delete wrapper;
}
}
Isolate* isolate;
Local<Object> receiver;
ObjCDataWrapper* wrapper = nullptr;
};
bool IsKVOSubclassOf(Class klass, Class base) {
static const char prefix[] = "NSKVONotifying_";
return class_getSuperclass(klass) == base &&
strncmp(class_getName(klass), prefix, sizeof(prefix) - 1) == 0;
}

} // namespace

NativeCallbackSelf::NativeCallbackSelf(Local<Context> context, id self)
: isolate_(v8::Isolate::GetCurrent()) {
auto cache = Caches::Get(isolate_);
auto it = cache->Instances.find(self);
if (it != cache->Instances.end()) {
receiver_ = it->second->Get(isolate_).As<Object>();
} else {
receiver_ = ArgConverter::WrapNativeCallbackSelf(context, self, &borrowed_);
}
}

// The object is gone once the native call returns, so a borrowed receiver JS
// kept must read as released.
NativeCallbackSelf::~NativeCallbackSelf() {
if (borrowed_ != nullptr && tns::GetValue(isolate_, receiver_) == borrowed_) {
tns::SetValue(isolate_, receiver_, nullptr);
delete borrowed_;
}
}

void ArgConverter::Init(Local<Context> context) {
Isolate* isolate = v8::Isolate::GetCurrent();
auto cache = Caches::Get(isolate);
Expand Down Expand Up @@ -405,18 +416,12 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {}
}
}

Local<Object> thiz = context->Global();
BorrowedSelfScope borrowedSelf(isolate);
// Blocks and C function pointers have no receiver.
std::optional<NativeCallbackSelf> receiver;
if (data->initialParamIndex_ > 1) {
id self_ = *static_cast<const id*>(argValues[0]);
auto it = cache->Instances.find(self_);
if (it != cache->Instances.end()) {
thiz = it->second->Get(data->isolateWrapper_.Isolate()).As<Object>();
} else {
thiz = ArgConverter::WrapNativeCallbackSelf(context, self_, &borrowedSelf.wrapper);
borrowedSelf.receiver = thiz;
}
receiver.emplace(context, *static_cast<const id*>(argValues[0]));
}
Local<Object> thiz = receiver ? receiver->Get() : context->Global();

Local<Value> result;
Local<v8::Function> callback = poCallback->Get(isolate).As<v8::Function>();
Expand Down Expand Up @@ -1019,6 +1024,11 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {}
const Meta* meta = FindMeta(klass, typeEncoding);
if (meta != nullptr) {
auto it = cache->ClassPrototypes.find(std::string_view(object_getClassName(target)));
// A key-value observed object is an instance of a notifying subclass,
// which has no prototype of its own.
if (it == cache->ClassPrototypes.end() && IsKVOSubclassOf(object_getClass(target), klass)) {
it = cache->ClassPrototypes.find(std::string_view(class_getName(klass)));
}
if (it != cache->ClassPrototypes.end()) {
// for debugging rlv cell handling:
// NSString* message = [NSString stringWithFormat:@"ArgConverter::CreateJsWrapper FindMeta:
Expand Down Expand Up @@ -1071,11 +1081,15 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {}
if (wrapper != nullptr && wrapper->Type() == WrapperType::ObjCObject) {
Class expected = static_cast<ObjCDataWrapper*>(wrapper)->Klass();
// A KVO-style isa swizzle replaces the class in place but keeps -class
// answering the original, so only an address that now belongs to a
// different object fails both comparisons. Dropping such an entry turns a
// wrapper that would otherwise be handed out with the wrong prototype into
// a plain cache miss, which rebuilds it correctly.
if (expected != nil && object_getClass(target) != expected && [target class] != expected) {
// answering the original, and a wrapper made while the object was
// key-value observed recorded the notifying subclass, which the object
// leaves when its last observer goes. So only an address that now belongs
// to a different object fails all three comparisons. Dropping such an
// entry turns a wrapper that would otherwise be handed out with the wrong
// prototype into a plain cache miss, which rebuilds it correctly.
Class current = object_getClass(target);
if (expected != nil && current != expected && [target class] != expected &&
!IsKVOSubclassOf(expected, current)) {
cache->Instances.erase(it);
return nullptr;
}
Expand Down
11 changes: 3 additions & 8 deletions NativeScript/runtime/ClassBuilder.h
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#define ClassBuilder_h

#include "Common.h"
#include "IsolateWrapper.h"
#include "Metadata.h"

namespace tns {
Expand All @@ -11,15 +12,10 @@ struct PropertyCallbackContext {
PropertyCallbackContext(
v8::Isolate* isolate,
std::shared_ptr<v8::Persistent<v8::Function>> callback,
std::shared_ptr<v8::Persistent<v8::Object>> implementationObject,
const PropertyMeta* meta)
: isolate_(isolate),
callback_(callback),
implementationObject_(implementationObject),
meta_(meta) {}
v8::Isolate* isolate_;
: isolateWrapper_(isolate), callback_(callback), meta_(meta) {}
IsolateWrapper isolateWrapper_;
std::shared_ptr<v8::Persistent<v8::Function>> callback_;
std::shared_ptr<v8::Persistent<v8::Object>> implementationObject_;
const PropertyMeta* meta_;
};

Expand Down Expand Up @@ -79,7 +75,6 @@ class ClassBuilder {
std::vector<const ProtocolMeta*> exposedProtocols);
static void ExposeProperties(v8::Isolate* isolate, Class extendedClass,
std::vector<const PropertyMeta*> propertyMetas,
v8::Local<v8::Object> implementationObject,
v8::Local<v8::Value> getter,
v8::Local<v8::Value> setter);
// Follows clang: a struct behind a pointer is expanded only when that
Expand Down
58 changes: 31 additions & 27 deletions NativeScript/runtime/ClassBuilder.mm
Original file line number Diff line number Diff line change
Expand Up @@ -796,7 +796,7 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) {
(getter->IsFunction() || setter->IsFunction())) {
std::vector<const PropertyMeta*> propertyMetas;
VisitProperties(methodName, extendedClassMeta, propertyMetas, protocols);
ExposeProperties(isolate, extendedClass, propertyMetas, implementationObject, getter, setter);
ExposeProperties(isolate, extendedClass, propertyMetas, getter, setter);
continue;
}

Expand Down Expand Up @@ -923,8 +923,7 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) {

void ClassBuilder::ExposeProperties(Isolate* isolate, Class extendedClass,
std::vector<const PropertyMeta*> propertyMetas,
Local<Object> implementationObject, Local<Value> getter,
Local<Value> setter) {
Local<Value> getter, Local<Value> setter) {
for (int j = 0; j < propertyMetas.size(); j++) {
const PropertyMeta* propertyMeta = propertyMetas[j];
std::string propertyName = propertyMeta->name();
Expand All @@ -936,40 +935,42 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) {
bool hasSetter = !setter.IsEmpty() && setter->IsFunction() && propertyMeta->hasSetter() &&
!ImplementsItself(extendedClass, propertyMeta->setter()->selector());

std::shared_ptr<Persistent<Object>> poImplementationObject;
if (hasGetter || hasSetter) {
poImplementationObject = std::make_shared<Persistent<Object>>(isolate, implementationObject);
}

if (hasGetter) {
std::shared_ptr<Persistent<v8::Function>> poGetterFunc =
std::make_shared<Persistent<v8::Function>>(isolate, getter.As<v8::Function>());
PropertyCallbackContext* userData =
new PropertyCallbackContext(isolate, poGetterFunc, poImplementationObject, propertyMeta);
new PropertyCallbackContext(isolate, poGetterFunc, propertyMeta);

FFIMethodCallback getterCallback = [](ffi_cif* cif, void* retValue, void** argValues,
void* userData) {
PropertyCallbackContext* context = static_cast<PropertyCallbackContext*>(userData);
Isolate* isolate = context->isolate_;
Isolate* isolate = context->isolateWrapper_.Isolate();
// Scopes-before-@throw: a branded escape is captured and @thrown only
// after every V8 scope in the inner block has destructed.
NSException* __strong pendingThrow = nil;
{
// Validity is checked before and again after taking the Locker, for
// the reasons given in ArgConverter::MethodCallback.
IsolatePin pin = context->isolateWrapper_.Pin();
if (!pin || !context->isolateWrapper_.IsValid()) {
memset(retValue, 0, cif->rtype->size);
return;
}
v8::Locker locker(isolate);
if (!context->isolateWrapper_.IsValid()) {
memset(retValue, 0, cif->rtype->size);
return;
}
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
Local<v8::Function> getterFunc = context->callback_->Get(isolate);
Local<Value> res;

id thiz = *static_cast<const id*>(argValues[0]);
auto cache = Caches::Get(isolate);
auto it = cache->Instances.find(thiz);
Local<Object> self_ = it != cache->Instances.end()
? it->second->Get(isolate).As<Object>()
: context->implementationObject_->Get(isolate);
Local<Context> v8Context = Caches::Get(isolate)->GetContext();
Context::Scope context_scope(v8Context);
NativeCallbackSelf receiver(v8Context, *static_cast<const id*>(argValues[0]));
TryCatch tc(isolate);
if (!getterFunc->Call(v8Context, self_, 0, nullptr).ToLocal(&res)) {
if (!getterFunc->Call(v8Context, receiver.Get(), 0, nullptr).ToLocal(&res)) {
NSException* ex = ArgConverter::HandleBoundaryException(v8Context, tc);
if (ex != nil) {
pendingThrow = ex;
Expand Down Expand Up @@ -1001,36 +1002,39 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) {
std::shared_ptr<Persistent<v8::Function>> poSetterFunc =
std::make_shared<Persistent<v8::Function>>(isolate, setter.As<v8::Function>());
PropertyCallbackContext* userData =
new PropertyCallbackContext(isolate, poSetterFunc, poImplementationObject, propertyMeta);
new PropertyCallbackContext(isolate, poSetterFunc, propertyMeta);

FFIMethodCallback setterCallback = [](ffi_cif* cif, void* retValue, void** argValues,
void* userData) {
PropertyCallbackContext* context = static_cast<PropertyCallbackContext*>(userData);
Isolate* isolate = context->isolate_;
Isolate* isolate = context->isolateWrapper_.Isolate();
NSException* __strong pendingThrow = nil;
{
IsolatePin pin = context->isolateWrapper_.Pin();
if (!pin || !context->isolateWrapper_.IsValid()) {
return;
}
v8::Locker locker(isolate);
if (!context->isolateWrapper_.IsValid()) {
return;
}
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
Local<v8::Function> setterFunc = context->callback_->Get(isolate);
Local<Value> res;

id thiz = *static_cast<const id*>(argValues[0]);
auto cache = Caches::Get(isolate);
auto it = cache->Instances.find(thiz);
Local<Object> self_ = it != cache->Instances.end()
? it->second->Get(isolate).As<Object>()
: context->implementationObject_->Get(isolate);
Local<Context> v8Context = Caches::Get(isolate)->GetContext();
Context::Scope context_scope(v8Context);
NativeCallbackSelf receiver(v8Context, *static_cast<const id*>(argValues[0]));

uint8_t* argBuffer = (uint8_t*)argValues[2];
const TypeEncoding* typeEncoding = context->meta_->setter()->encodings()->first()->next();
BaseCall call(argBuffer);
Local<Context> v8Context = Caches::Get(isolate)->GetContext();
Local<Value> jsWrapper = Interop::GetResult(v8Context, typeEncoding, &call, true);
Local<Value> params[1] = {jsWrapper};

TryCatch tc(isolate);
if (!setterFunc->Call(v8Context, self_, 1, params).ToLocal(&res)) {
if (!setterFunc->Call(v8Context, receiver.Get(), 1, params).ToLocal(&res)) {
NSException* ex = ArgConverter::HandleBoundaryException(v8Context, tc);
if (ex != nil) {
pendingThrow = ex;
Expand Down
27 changes: 23 additions & 4 deletions NativeScript/runtime/MetadataBuilder.mm
Original file line number Diff line number Diff line change
Expand Up @@ -1464,12 +1464,24 @@ void ReplaceKeepingOriginal(Class klass, SEL selector, const char* selectorName,
FFIMethodCallback getterCallback = [](ffi_cif* cif, void* retValue, void** argValues,
void* userData) {
PropertyCallbackContext* context = static_cast<PropertyCallbackContext*>(userData);
Isolate* isolate = context->isolate_;
Isolate* isolate = context->isolateWrapper_.Isolate();
// Scopes-before-@throw: capture a branded escape and @throw only after
// the inner block's V8 scopes destruct.
NSException* __strong pendingThrow = nil;
{
// This IMP stays on the native class after the isolate that installed
// it is gone. Validity is checked before and again after taking the
// Locker, for the reasons given in ArgConverter::MethodCallback.
IsolatePin pin = context->isolateWrapper_.Pin();
if (!pin || !context->isolateWrapper_.IsValid()) {
memset(retValue, 0, cif->rtype->size);
return;
}
v8::Locker locker(isolate);
if (!context->isolateWrapper_.IsValid()) {
memset(retValue, 0, cif->rtype->size);
return;
}
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
Local<v8::Function> getterFunc = context->callback_->Get(isolate);
Expand Down Expand Up @@ -1519,7 +1531,7 @@ void ReplaceKeepingOriginal(Class klass, SEL selector, const char* selectorName,
std::shared_ptr<Persistent<v8::Function>> poGetterFunc =
std::make_shared<Persistent<v8::Function>>(isolate, getter.As<v8::Function>());
PropertyCallbackContext* userData =
new PropertyCallbackContext(isolate, poGetterFunc, nullptr, propertyMeta);
new PropertyCallbackContext(isolate, poGetterFunc, propertyMeta);
IMP impGetter = Interop::CreateMethod(2, 0, typeEncoding, getterCallback, userData);
ReplaceKeepingOriginal(klass, propertyMeta->getter()->selector(),
propertyMeta->getter()->selectorAsString(), impGetter,
Expand All @@ -1530,10 +1542,17 @@ void ReplaceKeepingOriginal(Class klass, SEL selector, const char* selectorName,
FFIMethodCallback setterCallback = [](ffi_cif* cif, void* retValue, void** argValues,
void* userData) {
PropertyCallbackContext* context = static_cast<PropertyCallbackContext*>(userData);
Isolate* isolate = context->isolate_;
Isolate* isolate = context->isolateWrapper_.Isolate();
NSException* __strong pendingThrow = nil;
{
IsolatePin pin = context->isolateWrapper_.Pin();
if (!pin || !context->isolateWrapper_.IsValid()) {
return;
}
v8::Locker locker(isolate);
if (!context->isolateWrapper_.IsValid()) {
return;
}
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
Local<v8::Function> setterFunc = context->callback_->Get(isolate);
Expand Down Expand Up @@ -1580,7 +1599,7 @@ void ReplaceKeepingOriginal(Class klass, SEL selector, const char* selectorName,
std::shared_ptr<Persistent<v8::Function>> poSetterFunc =
std::make_shared<Persistent<v8::Function>>(isolate, setter.As<v8::Function>());
PropertyCallbackContext* userData =
new PropertyCallbackContext(isolate, poSetterFunc, nullptr, propertyMeta);
new PropertyCallbackContext(isolate, poSetterFunc, propertyMeta);
IMP impSetter = Interop::CreateMethod(2, 1, typeEncoding, setterCallback, userData);

std::string compilerEncoding = ClassBuilder::GetAccessorTypeEncoding(typeEncoding, 1, "v@:@");
Expand Down
Loading
Loading