Skip to content
Draft
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
10 changes: 7 additions & 3 deletions NativeScript/runtime/MetadataBuilder.h
Original file line number Diff line number Diff line change
Expand Up @@ -111,11 +111,13 @@ class MetadataBuilder {
static void RegisterAllocMethod(
v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> ctorFuncTemplate,
const InterfaceMeta* interfaceMeta);
// `guarded`, when given, records the JS name of each method installed.
static void RegisterInstanceMethods(
v8::Local<v8::Context> context,
v8::Local<v8::FunctionTemplate> ctorFuncTemplate,
const BaseClassMeta* meta, KnownUnknownClassPair pair,
robin_hood::unordered_map<std::string, uint8_t>& names);
robin_hood::unordered_map<std::string, uint8_t>& names,
std::vector<std::string>* guarded = nullptr);
// `setters`, when given, records each accessor pair installed.
static void RegisterInstanceProperties(
v8::Local<v8::Context> context,
Expand All @@ -130,13 +132,15 @@ class MetadataBuilder {
const BaseClassMeta* meta, std::string className,
KnownUnknownClassPair pair,
robin_hood::unordered_map<std::string, uint8_t>& names,
NativeSetters* setters = nullptr);
NativeSetters* setters = nullptr,
std::vector<std::string>* guarded = nullptr);
static void RegisterAdditionalProtocols(
v8::Local<v8::Context> context,
v8::Local<v8::FunctionTemplate> ctorFuncTemplate,
KnownUnknownClassPair pair,
const std::vector<std::string>& additionalProtocols,
robin_hood::unordered_map<std::string, uint8_t>& names);
robin_hood::unordered_map<std::string, uint8_t>& names,
std::vector<std::string>* guarded = nullptr);
static void RegisterStaticMethods(
v8::Local<v8::Context> context, v8::Local<v8::Function> ctorFunc,
const BaseClassMeta* meta, KnownUnknownClassPair pair,
Expand Down
171 changes: 161 additions & 10 deletions NativeScript/runtime/MetadataBuilder.mm
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,126 @@ void ForgetNativeSetter(Isolate* isolate, Local<Object> prototype, Local<v8::Nam
}
}

// Set while the native member guard defines a property on an object whose
// handlers already saw the write: a native class prototype's handlers must
// not swizzle twice, nor take a guard's accessor pair for a native property's.
thread_local bool definingGuardedMember_ = false;

class DefiningGuardedMember {
public:
DefiningGuardedMember() : previous_(definingGuardedMember_) { definingGuardedMember_ = true; }
~DefiningGuardedMember() { definingGuardedMember_ = previous_; }

private:
bool previous_;
};

struct NativeMemberGuardState {
// (function (f) { return function () { return f; }; }): the getter is a JS
// closure, since an API getter sends `super.m` loads to the slow path.
Global<v8::Function> getterFactory;
};

std::string DescribeMemberName(Isolate* isolate, Local<v8::Name> name) {
if (name->IsSymbol()) {
Local<Value> description = name.As<Symbol>()->Description(isolate);
return "[" + (description->IsString() ? tns::ToString(isolate, description) : "") + "]";
}
return tns::ToString(isolate, name);
}

// The guard's setter: `info.Data()` is the member's name. An own property on a
// native object never reaches native code, which calls the class's
// implementation, so assigning a native method's name there throws. Any other
// receiver, such as a class prototype (whose handlers have swizzled already)
// or an object inheriting from a native one, gets the own data property an
// ordinary assignment would create.
void NativeMemberGuardSetter(const FunctionCallbackInfo<Value>& info) {
Isolate* isolate = info.GetIsolate();
Local<Context> context = isolate->GetCurrentContext();
Local<v8::Name> name = info.Data().As<v8::Name>();
Local<Object> receiver = info.This();
Local<Value> value = info.Length() > 0 ? info[0] : v8::Undefined(isolate).As<Value>();

BaseDataWrapper* wrapper = tns::GetValue(isolate, receiver);
bool nativeObject = wrapper != nullptr
? wrapper->Type() == WrapperType::ObjCObject ||
wrapper->Type() == WrapperType::ObjCAllocObject
: tns::GetReleasedReason(receiver) != ReleasedReason::kNone;
if (!nativeObject) {
DefiningGuardedMember defining;
(void)receiver->CreateDataProperty(context, name, value);
return;
}

// The JS class name: the native one can be a private class cluster member.
std::string className;
Local<Value> target = tns::UnwrapProxy(receiver);
if (!target.IsEmpty() && target->IsObject()) {
className = tns::ToString(isolate, target.As<Object>()->GetConstructorName());
}
std::string member = DescribeMemberName(isolate, name);
std::string message =
"Cannot assign '" + member + "' on an instance of " + className +
": it would shadow the native method for JS callers only, since native code never calls "
"JS own properties of a native object (wrapperLifetime mode \"" +
WrapperLifetimeModeName(GetWrapperLifetimeMode()) +
"\", debug builds). Override the method on a class instead (extend() or a subclass), "
"define a JS-only property with Object.defineProperty, or set \"wrapperLifetime\": { "
"\"allowShadowingNativeMembers\": true } in the app config.";
isolate->ThrowException(Exception::TypeError(tns::ToV8String(isolate, message)));
}

// Turns each named own method of a native class prototype, and the symbol
// `iterator` when given, into an accessor pair whose getter returns that same
// function. Configurable, so an assignment the setter allows can replace it.
void GuardNativeMembers(Isolate* isolate, Local<Context> context, Local<Object> prototype,
const std::vector<std::string>& names, Local<v8::Name> iterator) {
NativeMemberGuardState* state = Caches::StateFor<NativeMemberGuardState>(isolate);
if (state == nullptr) {
return;
}
if (state->getterFactory.IsEmpty()) {
Local<Script> script;
Local<Value> factory;
if (!Script::Compile(context, tns::ToV8String(isolate, "(function (f) { return function () { "
"return f; }; })"))
.ToLocal(&script) ||
!script->Run(context).ToLocal(&factory) || !factory->IsFunction()) {
return;
}
state->getterFactory.Reset(isolate, factory.As<v8::Function>());
}
Local<v8::Function> factory = state->getterFactory.Get(isolate);

DefiningGuardedMember defining;
auto guard = [&](Local<v8::Name> name) {
PropertyAttribute attributes = PropertyAttribute::None;
Local<Value> method;
if (!prototype->HasRealNamedProperty(context, name).FromMaybe(false) ||
prototype->HasRealNamedCallbackProperty(context, name).FromMaybe(true) ||
!prototype->GetRealNamedPropertyAttributes(context, name).To(&attributes) ||
!prototype->GetRealNamedProperty(context, name).ToLocal(&method) || !method->IsFunction()) {
return;
}
Local<Value> getter;
Local<v8::Function> setter;
if (!factory->Call(context, v8::Undefined(isolate), 1, &method).ToLocal(&getter) ||
!v8::Function::New(context, NativeMemberGuardSetter, name, 1, ConstructorBehavior::kThrow)
.ToLocal(&setter)) {
return;
}
prototype->SetAccessorProperty(name, getter.As<v8::Function>(), setter,
static_cast<PropertyAttribute>(attributes & DontEnum));
};
for (const std::string& name : names) {
guard(tns::ToV8String(isolate, name));
}
if (!iterator.IsEmpty()) {
guard(iterator);
}
}

} // namespace

void MetadataBuilder::RegisterConstantsOnGlobalObject(Isolate* isolate,
Expand Down Expand Up @@ -722,16 +842,26 @@ throw NativeScriptException(
if (GetWrapperLifetimeMode() == WrapperLifetimeMode::kCanary) {
setters = std::make_unique<NativeSetters>();
}
std::vector<std::string> guardedMethods;
std::vector<std::string>* guarded = GuardsNativeMembers() ? &guardedMethods : nullptr;
MetadataBuilder::RegisterInstanceProperties(context, ctorFuncTemplate, meta, meta->name(), pair,
instanceMembers, setters.get());
MetadataBuilder::RegisterInstanceMethods(context, ctorFuncTemplate, meta, pair, instanceMembers);
MetadataBuilder::RegisterInstanceMethods(context, ctorFuncTemplate, meta, pair, instanceMembers,
guarded);
MetadataBuilder::RegisterInstanceProtocols(context, ctorFuncTemplate, meta, meta->name(), pair,
instanceMembers, setters.get());
instanceMembers, setters.get(), guarded);
ctorFuncTemplate->PrototypeTemplate()->Set(
tns::ToV8String(isolate, "toString"),
FunctionTemplate::New(isolate, MetadataBuilder::ToStringFunctionCallback));
if (guarded != nullptr) {
guarded->push_back("toString");
}
Local<v8::Name> guardedIterator;
if (meta->type() == MetaType::Interface && strcmp(meta->name(), "NSArray") == 0) {
SymbolIterator::Install(isolate, ctorFuncTemplate->PrototypeTemplate());
if (guarded != nullptr) {
guardedIterator = Symbol::GetIterator(isolate);
}
}

if (meta->type() == MetaType::Interface) {
Expand Down Expand Up @@ -775,6 +905,10 @@ NamedPropertyHandlerConfiguration config(nullptr, MetadataBuilder::SwizzledInsta
tns::Assert(success, isolate);
Local<Object> prototype = prototypeValue.As<Object>();

if (guarded != nullptr) {
GuardNativeMembers(isolate, context, prototype, guardedMethods, guardedIterator);
}

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
Expand Down Expand Up @@ -909,8 +1043,10 @@ void CollectInstanceMemberNames(const BaseClassMeta* meta, Class klass, bool own
bindingTemplate->InstanceTemplate()->SetInternalFieldCount(1);
bindingTemplate->SetClassName(tns::ToV8String(isolate, meta->name()));
bindingTemplate->Inherit(classTemplate);
std::vector<std::string> guardedMethods;
MetadataBuilder::RegisterAdditionalProtocols(context, bindingTemplate, pair, additionalProtocols,
names);
names,
GuardsNativeMembers() ? &guardedMethods : nullptr);

Local<v8::Function> bindingFunc;
Local<v8::Function> classFunc;
Expand All @@ -927,6 +1063,9 @@ void CollectInstanceMemberNames(const BaseClassMeta* meta, Class klass, bool own
->DefineOwnProperty(context, tns::ToV8String(isolate, "constructor"), classFunc,
PropertyAttribute::DontEnum)
.FromMaybe(false);
if (!guardedMethods.empty()) {
GuardNativeMembers(isolate, context, prototype.As<Object>(), guardedMethods, Local<v8::Name>());
}

// Building the class's binding can wrap objects of this class first.
cached = findBinding();
Expand Down Expand Up @@ -990,7 +1129,8 @@ void CollectInstanceMemberNames(const BaseClassMeta* meta, Class klass, bool own

void MetadataBuilder::RegisterInstanceMethods(
Local<Context> context, Local<FunctionTemplate> ctorFuncTemplate, const BaseClassMeta* meta,
KnownUnknownClassPair pair, robin_hood::unordered_map<std::string, uint8_t>& names) {
KnownUnknownClassPair pair, robin_hood::unordered_map<std::string, uint8_t>& names,
std::vector<std::string>* guarded) {
Isolate* isolate = v8::Isolate::GetCurrent();
Local<ObjectTemplate> proto = ctorFuncTemplate->PrototypeTemplate();

Expand All @@ -1009,6 +1149,9 @@ void CollectInstanceMemberNames(const BaseClassMeta* meta, Class klass, bool own
Local<FunctionTemplate> instanceMethodTemplate =
FunctionTemplate::New(isolate, MethodCallback, ext);
proto->Set(tns::ToV8String(isolate, methodMeta->jsName()), instanceMethodTemplate);
if (guarded != nullptr) {
guarded->push_back(methodMeta->jsName());
}
names.emplace(methodName, 0);
}
}
Expand Down Expand Up @@ -1056,9 +1199,10 @@ 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, NativeSetters* setters) {
robin_hood::unordered_map<std::string, uint8_t>& names, NativeSetters* setters,
std::vector<std::string>* guarded) {
if (meta->type() == MetaType::ProtocolType) {
MetadataBuilder::RegisterInstanceMethods(context, ctorFuncTemplate, meta, pair, names);
MetadataBuilder::RegisterInstanceMethods(context, ctorFuncTemplate, meta, pair, names, guarded);
MetadataBuilder::RegisterInstanceProperties(context, ctorFuncTemplate, meta, className, pair,
names, setters);
}
Expand All @@ -1069,20 +1213,21 @@ 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, setters);
pair, names, setters, guarded);
}
}
}

void MetadataBuilder::RegisterAdditionalProtocols(
Local<Context> context, Local<FunctionTemplate> ctorFuncTemplate, KnownUnknownClassPair pair,
const std::vector<std::string>& additionalProtocols,
robin_hood::unordered_map<std::string, uint8_t>& names) {
robin_hood::unordered_map<std::string, uint8_t>& names, std::vector<std::string>* guarded) {
for (std::string protocolName : additionalProtocols) {
const Meta* meta = ArgConverter::GetMeta(protocolName.c_str());
if (meta != nullptr) {
const BaseClassMeta* baseMeta = static_cast<const BaseClassMeta*>(meta);
MetadataBuilder::RegisterInstanceMethods(context, ctorFuncTemplate, baseMeta, pair, names);
MetadataBuilder::RegisterInstanceMethods(context, ctorFuncTemplate, baseMeta, pair, names,
guarded);
MetadataBuilder::RegisterInstanceProperties(context, ctorFuncTemplate, baseMeta,
baseMeta->name(), pair, names);

Expand All @@ -1093,7 +1238,7 @@ void CollectInstanceMemberNames(const BaseClassMeta* meta, Class klass, bool own
}

MetadataBuilder::RegisterAdditionalProtocols(context, ctorFuncTemplate, pair, metaProtocols,
names);
names, guarded);
}
}
}
Expand Down Expand Up @@ -1568,6 +1713,9 @@ 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) {
if (definingGuardedMember_) {
return v8::Intercepted::kNo;
}
Isolate* isolate = info.GetIsolate();
ForgetNativeSetter(isolate, info.Holder(), property);
std::string methodName = tns::ToString(isolate, property);
Expand Down Expand Up @@ -1614,6 +1762,9 @@ void ReplaceKeepingOriginal(Class klass, SEL selector, const char* selectorName,
v8::Intercepted MetadataBuilder::SwizzledPropertyCallback(
Local<v8::Name> property, const PropertyDescriptor& desc,
const PropertyCallbackInfo<v8::Boolean>& info) {
if (definingGuardedMember_) {
return v8::Intercepted::kNo;
}
Isolate* isolate = info.GetIsolate();
ForgetNativeSetter(isolate, info.Holder(), property);
std::string propertyName = tns::ToString(isolate, property);
Expand Down
9 changes: 8 additions & 1 deletion NativeScript/runtime/NsBuiltinModules.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,8 @@ constexpr const char* kWrapperLifetimeWarningsKey = "wrapperLifetimeWarnings";
// Read-only: the lifetime mode is fixed at startup from the app config.
constexpr const char* kWrapperLifetimeModeKey = "wrapperLifetimeMode";
constexpr const char* kWrapperLifetimeScopeKey = "wrapperLifetimeScope";
constexpr const char* kWrapperLifetimeAllowShadowingKey =
"wrapperLifetimeAllowShadowingNativeMembers";

void ThrowTypeError(Isolate* isolate, const std::string& message) {
isolate->ThrowException(
Expand Down Expand Up @@ -146,7 +148,8 @@ void SetConfigCallback(const FunctionCallbackInfo<Value>& info) {
}
return;
}
if (key == kWrapperLifetimeModeKey || key == kWrapperLifetimeScopeKey) {
if (key == kWrapperLifetimeModeKey || key == kWrapperLifetimeScopeKey ||
key == kWrapperLifetimeAllowShadowingKey) {
ThrowTypeError(
isolate,
"'" + key +
Expand Down Expand Up @@ -227,6 +230,10 @@ void GetConfigCallback(const FunctionCallbackInfo<Value>& info) {
tns::WrapperLifetimeScopeName(tns::GetWrapperLifetimeScope())));
return;
}
if (key == kWrapperLifetimeAllowShadowingKey) {
info.GetReturnValue().Set(tns::GetAllowShadowingNativeMembers());
return;
}
ThrowTypeError(isolate, "Unknown runtime config key: '" + key + "'");
}

Expand Down
11 changes: 11 additions & 0 deletions NativeScript/runtime/WrapperLifetime.h
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ inline WrapperLifetimeMode wrapperLifetimeMode =
WrapperLifetimeMode::kResurrecting;
inline WrapperLifetimeScope wrapperLifetimeScope =
WrapperLifetimeScope::kExtended;
inline bool allowShadowingNativeMembers = false;
inline bool guardsNativeMembers = false;
} // namespace detail

inline WrapperLifetimeMode GetWrapperLifetimeMode() {
Expand All @@ -51,6 +53,15 @@ inline WrapperLifetimeMode GetWrapperLifetimeMode() {
inline WrapperLifetimeScope GetWrapperLifetimeScope() {
return detail::wrapperLifetimeScope;
}
// "wrapperLifetime": { "allowShadowingNativeMembers": true } in the app config.
inline bool GetAllowShadowingNativeMembers() {
return detail::allowShadowingNativeMembers;
}
// Debug builds in the "rooted" and "canary" modes, unless shadowing is
// allowed: assigning a native instance method's name on a native object
// throws instead of creating an own property native code never calls
// (MetadataBuilder's native member guard).
inline bool GuardsNativeMembers() { return detail::guardsNativeMembers; }
const char* WrapperLifetimeModeName(WrapperLifetimeMode mode);
const char* WrapperLifetimeScopeName(WrapperLifetimeScope scope);

Expand Down
11 changes: 11 additions & 0 deletions NativeScript/runtime/WrapperLifetime.mm
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
#include "Helpers.h"
#include "LeakProbe.h"
#include "Runtime.h"
#include "RuntimeConfig.h"
#import "TNSDerivedClass.h"
#include "WrapperLifetimeCanary.h"

Expand Down Expand Up @@ -55,6 +56,16 @@ void ReadConfig() {
[scope UTF8String]);
}
}
id allowShadowing = ((NSDictionary*)config)[@"allowShadowingNativeMembers"];
if (allowShadowing != nil && ![allowShadowing isKindOfClass:[NSNumber class]]) {
Log("NativeScript: wrapperLifetime allowShadowingNativeMembers must be a boolean; using "
"false.");
} else if (allowShadowing != nil) {
detail::allowShadowingNativeMembers = [allowShadowing boolValue];
}
detail::guardsNativeMembers = RuntimeConfig.IsDebug &&
GetWrapperLifetimeMode() != WrapperLifetimeMode::kResurrecting &&
!detail::allowShadowingNativeMembers;
}

// Per-isolate state of the rooted mode.
Expand Down
Loading