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
28 changes: 26 additions & 2 deletions NativeScript/runtime/MetadataBuilder.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@

namespace tns {

struct NativeSetters;

class MetadataBuilder {
public:
static void RegisterConstantsOnGlobalObject(
Expand All @@ -30,6 +32,18 @@ class MetadataBuilder {
void* data,
StructStorage storage,
v8::Local<v8::Object> parent);
// Runs the setter of `owner`'s native property `property` on `receiver`, as
// the property's accessor would, and returns true. Returns false, having
// run nothing, unless `owner` is a native class's prototype, still holding
// the accessor pair it was built with for `property`, which has a setter.
// The caller establishes that `owner` is where `receiver`'s prototype chain
// finds `property`. Only canary mode records the accessors this needs.
static bool TrySetNativeProperty(v8::Isolate* isolate,
v8::Local<v8::Context> context,
v8::Local<v8::Object> owner,
v8::Local<v8::Name> property,
v8::Local<v8::Object> receiver,
v8::Local<v8::Value> value);

private:
// The binding of an object whose static type adds protocols to `meta`: a
Expand Down Expand Up @@ -102,18 +116,21 @@ class MetadataBuilder {
v8::Local<v8::FunctionTemplate> ctorFuncTemplate,
const BaseClassMeta* meta, KnownUnknownClassPair pair,
robin_hood::unordered_map<std::string, uint8_t>& names);
// `setters`, when given, records each accessor pair installed.
static void RegisterInstanceProperties(
v8::Local<v8::Context> context,
v8::Local<v8::FunctionTemplate> ctorFuncTemplate,
const BaseClassMeta* meta, std::string className,
KnownUnknownClassPair pair,
robin_hood::unordered_map<std::string, uint8_t>& names);
robin_hood::unordered_map<std::string, uint8_t>& names,
NativeSetters* setters = nullptr);
static void RegisterInstanceProtocols(
v8::Local<v8::Context> context,
v8::Local<v8::FunctionTemplate> ctorFuncTemplate,
const BaseClassMeta* meta, std::string className,
KnownUnknownClassPair pair,
robin_hood::unordered_map<std::string, uint8_t>& names);
robin_hood::unordered_map<std::string, uint8_t>& names,
NativeSetters* setters = nullptr);
static void RegisterAdditionalProtocols(
v8::Local<v8::Context> context,
v8::Local<v8::FunctionTemplate> ctorFuncTemplate,
Expand Down Expand Up @@ -181,6 +198,13 @@ class MetadataBuilder {
private:
Class klass_ = nil;
};

friend struct NativeSetters;

static void SetNativeProperty(v8::Isolate* isolate,
CacheItem<PropertyMeta>* item,
v8::Local<v8::Object> receiver,
v8::Local<v8::Value> value);
};

} // namespace tns
Expand Down
184 changes: 167 additions & 17 deletions NativeScript/runtime/MetadataBuilder.mm
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
#include "SymbolLoader.h"
#include "Tasks.h"
#include "Worker.h"
#include "WrapperLifetime.h"
#include "WrapperLifetimeCanary.h"

using namespace v8;
Expand Down Expand Up @@ -88,6 +89,124 @@ bool ResolveProxyReceiver(Isolate* isolate, Local<Object>& receiver, const char*
constexpr int32_t kStructFieldIndexMask = (1 << kStructViewSlotShift) - 1;
} // namespace

// The native property setters a native class's prototype was built with, for
// TrySetNativeProperty. JS can replace one only by defining the name on that
// prototype, which its definer sees, and a name the prototype's own handlers
// see defined or assigned is forgotten for good. A deleted accessor needs no
// such care: the prototype then no longer has the property.
struct NativeSetters {
struct Entry {
Global<v8::Name> name;
MetadataBuilder::CacheItem<PropertyMeta>* item;
};

// In the order RegisterInstanceProperties installed them: a later accessor
// of a name replaces the earlier one on the prototype.
std::vector<std::pair<std::string, MetadataBuilder::CacheItem<PropertyMeta>*>> installed;
// By the name's identity hash. Names reaching an interceptor are internalized,
// so a lookup compares identities.
robin_hood::unordered_map<int, std::vector<Entry>> byHash;

Entry* Find(Local<v8::Name> name) {
auto it = byHash.find(name->GetIdentityHash());
if (it == byHash.end()) {
return nullptr;
}
for (Entry& entry : it->second) {
if (entry.name == name) {
return &entry;
}
}
return nullptr;
}

// Moves `installed` into `byHash`, keeping the last accessor of each name.
void Index(Isolate* isolate) {
for (const auto& [jsName, item] : installed) {
Local<v8::Name> name =
v8::String::NewFromUtf8(isolate, jsName.c_str(), NewStringType::kInternalized)
.ToLocalChecked();
MetadataBuilder::CacheItem<PropertyMeta>* setter = item->meta_->hasSetter() ? item : nullptr;
if (Entry* entry = Find(name)) {
entry->item = setter;
} else if (setter != nullptr) {
byHash[name->GetIdentityHash()].push_back({Global<v8::Name>(isolate, name), setter});
}
}
installed.clear();
installed.shrink_to_fit();
}

void Forget(Isolate* isolate, Local<v8::Name> name) {
auto it = byHash.find(name->GetIdentityHash());
if (it == byHash.end()) {
return;
}
for (Entry& entry : it->second) {
if (entry.name.Get(isolate)->StrictEquals(name)) {
entry.item = nullptr;
}
}
}
};

namespace {

// Per-isolate: each native class prototype carries its NativeSetters under a
// private key.
struct NativeSetterState {
Global<Private> key;
std::vector<std::unique_ptr<NativeSetters>> prototypes;
};

void PublishNativeSetters(Isolate* isolate, Local<Context> context, Local<Object> prototype,
std::unique_ptr<NativeSetters> setters) {
NativeSetterState* state = Caches::StateFor<NativeSetterState>(isolate);
if (state == nullptr) {
return;
}
if (state->key.IsEmpty()) {
state->key.Reset(isolate, Private::New(isolate, tns::ToV8String(isolate, "nativeSetters")));
}
setters->Index(isolate);
bool marked = false;
if (!prototype
->SetPrivate(context, state->key.Get(isolate),
External::New(isolate, setters.get(), v8::kExternalPointerTypeTagDefault))
.To(&marked) ||
!marked) {
return;
}
state->prototypes.push_back(std::move(setters));
}

NativeSetters* NativeSettersOf(Isolate* isolate, Local<Context> context, Local<Object> prototype) {
NativeSetterState* state = Caches::ExistingStateFor<NativeSetterState>(isolate);
if (state == nullptr || state->key.IsEmpty()) {
return nullptr;
}
Local<Value> marker;
if (!prototype->GetPrivate(context, state->key.Get(isolate)).ToLocal(&marker) ||
!marker->IsExternal()) {
return nullptr;
}
return static_cast<NativeSetters*>(
marker.As<External>()->Value(v8::kExternalPointerTypeTagDefault));
}

// From a native class prototype's own handlers, which see JS define or assign
// `property` on that prototype.
void ForgetNativeSetter(Isolate* isolate, Local<Object> prototype, Local<v8::Name> property) {
if (GetWrapperLifetimeMode() != WrapperLifetimeMode::kCanary) {
return;
}
if (NativeSetters* setters = NativeSettersOf(isolate, isolate->GetCurrentContext(), prototype)) {
setters->Forget(isolate, property);
}
}

} // namespace

void MetadataBuilder::RegisterConstantsOnGlobalObject(Isolate* isolate,
Local<ObjectTemplate> globalTemplate,
bool isWorkerThread) {
Expand Down Expand Up @@ -599,11 +718,15 @@ throw NativeScriptException(
}
}

std::unique_ptr<NativeSetters> setters;
if (GetWrapperLifetimeMode() == WrapperLifetimeMode::kCanary) {
setters = std::make_unique<NativeSetters>();
}
MetadataBuilder::RegisterInstanceProperties(context, ctorFuncTemplate, meta, meta->name(), pair,
instanceMembers);
instanceMembers, setters.get());
MetadataBuilder::RegisterInstanceMethods(context, ctorFuncTemplate, meta, pair, instanceMembers);
MetadataBuilder::RegisterInstanceProtocols(context, ctorFuncTemplate, meta, meta->name(), pair,
instanceMembers);
instanceMembers, setters.get());
ctorFuncTemplate->PrototypeTemplate()->Set(
tns::ToV8String(isolate, "toString"),
FunctionTemplate::New(isolate, MetadataBuilder::ToStringFunctionCallback));
Expand Down Expand Up @@ -647,6 +770,19 @@ NamedPropertyHandlerConfiguration config(nullptr, MetadataBuilder::SwizzledInsta
}
ObjectManager::Register(context, ctorFunc);

Local<Value> prototypeValue;
success = ctorFunc->Get(context, tns::ToV8String(isolate, "prototype")).ToLocal(&prototypeValue);
tns::Assert(success, isolate);
Local<Object> prototype = prototypeValue.As<Object>();

Persistent<Value>* poPrototype = new Persistent<Value>(isolate, prototype);
cache->Prototypes.emplace(meta, poPrototype);
// Before the constructor is exposed: a JS accessor on the global can run
// during the Set and redefine prototype members, which must find the tracker.
if (setters != nullptr) {
PublishNativeSetters(isolate, context, prototype, std::move(setters));
}

Local<Object> global = context->Global();
auto jsNameV8String = tns::ToV8String(isolate, meta->jsName());
auto maybeSet = global->Set(context, jsNameV8String, ctorFunc);
Expand All @@ -666,14 +802,6 @@ NamedPropertyHandlerConfiguration config(nullptr, MetadataBuilder::SwizzledInsta
MetadataBuilder::RegisterStaticProtocols(context, ctorFunc, meta, meta->name(), pair,
staticMembers);

Local<Value> prototypeValue;
success = ctorFunc->Get(context, tns::ToV8String(isolate, "prototype")).ToLocal(&prototypeValue);
tns::Assert(success, isolate);
Local<Object> prototype = prototypeValue.As<Object>();

Persistent<Value>* poPrototype = new Persistent<Value>(isolate, prototype);
cache->Prototypes.emplace(meta, poPrototype);

return ctorFuncTemplate;
}

Expand Down Expand Up @@ -889,7 +1017,7 @@ void CollectInstanceMemberNames(const BaseClassMeta* meta, Class klass, bool own
void MetadataBuilder::RegisterInstanceProperties(
Local<Context> context, Local<FunctionTemplate> ctorFuncTemplate, const BaseClassMeta* meta,
const std::string className, KnownUnknownClassPair pair,
robin_hood::unordered_map<std::string, uint8_t>& names) {
robin_hood::unordered_map<std::string, uint8_t>& names, NativeSetters* setters) {
Isolate* isolate = v8::Isolate::GetCurrent();
Local<ObjectTemplate> proto = ctorFuncTemplate->PrototypeTemplate();

Expand Down Expand Up @@ -917,6 +1045,9 @@ void CollectInstanceMemberNames(const BaseClassMeta* meta, Class klass, bool own
Local<FunctionTemplate> setter = FunctionTemplate::New(isolate, PropertySetterCallback, ext);
proto->SetAccessorProperty(tns::ToV8String(isolate, propMeta->jsName()), getter, setter,
PropertyAttribute::None);
if (setters != nullptr) {
setters->installed.emplace_back(propMeta->jsName(), item);
}
names.emplace(propertyName, accessors);
}
}
Expand All @@ -925,11 +1056,11 @@ void CollectInstanceMemberNames(const BaseClassMeta* meta, Class klass, bool own
void MetadataBuilder::RegisterInstanceProtocols(
Local<Context> context, Local<FunctionTemplate> ctorFuncTemplate, const BaseClassMeta* meta,
const std::string className, KnownUnknownClassPair pair,
robin_hood::unordered_map<std::string, uint8_t>& names) {
robin_hood::unordered_map<std::string, uint8_t>& names, NativeSetters* setters) {
if (meta->type() == MetaType::ProtocolType) {
MetadataBuilder::RegisterInstanceMethods(context, ctorFuncTemplate, meta, pair, names);
MetadataBuilder::RegisterInstanceProperties(context, ctorFuncTemplate, meta, className, pair,
names);
names, setters);
}

for (auto itProto = meta->protocols->begin(); itProto != meta->protocols->end(); itProto++) {
Expand All @@ -938,7 +1069,7 @@ void CollectInstanceMemberNames(const BaseClassMeta* meta, Class klass, bool own
if (m != nullptr) {
const BaseClassMeta* protoMeta = static_cast<const BaseClassMeta*>(m);
MetadataBuilder::RegisterInstanceProtocols(context, ctorFuncTemplate, protoMeta, className,
pair, names);
pair, names, setters);
}
}
}
Expand Down Expand Up @@ -1185,28 +1316,45 @@ void CollectInstanceMemberNames(const BaseClassMeta* meta, Class klass, bool own
}

void MetadataBuilder::PropertySetterCallback(const FunctionCallbackInfo<Value>& info) {
Isolate* isolate = info.GetIsolate();
CacheItem<PropertyMeta>* item = static_cast<CacheItem<PropertyMeta>*>(
info.Data().As<External>()->Value(v8::kExternalPointerTypeTagDefault));
SetNativeProperty(info.GetIsolate(), item, info.This(), info[0]);
}

void MetadataBuilder::SetNativeProperty(Isolate* isolate, CacheItem<PropertyMeta>* item,
Local<Object> receiver, Local<Value> value) {
if (!item->meta_->hasSetter()) {
Local<Value> error =
Exception::Error(tns::ToV8String(isolate, "Attempted to assign to readonly property."));
isolate->ThrowException(error);
return;
}

Local<Object> receiver = info.This();
if (!ResolveProxyReceiver(isolate, receiver, "set native property", item->meta_->jsName(),
false)) {
return;
}
Local<Value> value = info[0];
V8SimpleValueArgs args(value);
Local<Context> context = isolate->GetCurrentContext();
MetadataBuilder::InvokeMethod(context, item->meta_->setter(), receiver, args,
item->ResolveClass(), true);
}

bool MetadataBuilder::TrySetNativeProperty(Isolate* isolate, Local<Context> context,
Local<Object> owner, Local<v8::Name> property,
Local<Object> receiver, Local<Value> value) {
NativeSetters* setters = NativeSettersOf(isolate, context, owner);
if (setters == nullptr) {
return false;
}
NativeSetters::Entry* entry = setters->Find(property);
if (entry == nullptr || entry->item == nullptr) {
return false;
}
SetNativeProperty(isolate, entry->item, receiver, value);
return true;
}

void MetadataBuilder::PropertyNameGetterCallback(const FunctionCallbackInfo<Value>& info) {
Isolate* isolate = info.GetIsolate();
CacheItem<PropertyMeta>* item = static_cast<CacheItem<PropertyMeta>*>(
Expand Down Expand Up @@ -1421,6 +1569,7 @@ void ReplaceKeepingOriginal(Class klass, SEL selector, const char* selectorName,
v8::Intercepted MetadataBuilder::SwizzledInstanceMethodCallback(
Local<v8::Name> property, Local<Value> value, const PropertyCallbackInfo<v8::Boolean>& info) {
Isolate* isolate = info.GetIsolate();
ForgetNativeSetter(isolate, info.Holder(), property);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
std::string methodName = tns::ToString(isolate, property);

CacheItem<BaseClassMeta>* item = static_cast<CacheItem<BaseClassMeta>*>(
Expand Down Expand Up @@ -1466,6 +1615,7 @@ void ReplaceKeepingOriginal(Class klass, SEL selector, const char* selectorName,
Local<v8::Name> property, const PropertyDescriptor& desc,
const PropertyCallbackInfo<v8::Boolean>& info) {
Isolate* isolate = info.GetIsolate();
ForgetNativeSetter(isolate, info.Holder(), property);
std::string propertyName = tns::ToString(isolate, property);

CacheItem<BaseClassMeta>* item = static_cast<CacheItem<BaseClassMeta>*>(
Expand Down
22 changes: 18 additions & 4 deletions NativeScript/runtime/WrapperLifetimeCanary.mm
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
#include "DataWrapper.h"
#include "EventLoop.h"
#include "Helpers.h"
#include "MetadataBuilder.h"
#include "ObjectManager.h"
#include "Runtime.h"
#import "TNSDerivedClass.h"
Expand Down Expand Up @@ -621,15 +622,28 @@ Intercepted Setter(Local<v8::Name> property, Local<Value> value,
// setter: a native property's (an accessor pair on its class's
// prototype), a JS one's, or one defined on the canary, which runs with
// the canary as `this` and so mirrors whatever it writes. None is state.
// Calling the setter from here was measured slower than V8's own lookup
// Calling a JS setter from here was measured slower than V8's own lookup
// after the decline: the API hands a setter out only in a descriptor
// object, and keeping one (or a native property's metadata) across
// writes needs to know when JS changes a prototype, which V8 never says.
// object. A native property's setter runs from here when its class's
// prototype vouches that the accessor found is still its own.
if ((attributes & ReadOnly) != 0) {
return Intercepted::kNo;
}
Local<Object> owner = OwnerOf(context, holder, property);
if (owner.IsEmpty() || owner->HasRealNamedCallbackProperty(context, property).FromMaybe(true)) {
if (owner.IsEmpty()) {
return Intercepted::kNo;
}
Maybe<bool> accessor = owner->HasRealNamedCallbackProperty(context, property);
if (accessor.IsNothing()) {
return Intercepted::kNo;
}
if (accessor.FromJust()) {
// The setter can run JS, a collection or a -dealloc: neither the canary
// nor its record is touched after it.
if (MetadataBuilder::TrySetNativeProperty(isolate, context, owner, property, holder, value)) {
info.GetReturnValue().Set(true);
return Intercepted::kYes;
}
return Intercepted::kNo;
}
}
Expand Down
Loading
Loading