Skip to content
Merged
19 changes: 17 additions & 2 deletions NativeScript/runtime/ClassBuilder.h
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,21 @@ class ClassBuilder {
v8::Local<v8::Context> context);
static void RegisterNativeTypeScriptExtendsFunction(
v8::Local<v8::Context> context);
// Clears `*encodable` instead of asserting when a type has no compiler
// encoding the runtime can reproduce.
static std::string GetTypeEncoding(const TypeEncoding* typeEncoding,
int argsCount);
int argsCount, bool* encodable = nullptr);
// A JS-implemented property accessor's encoding, or `fallback` when its
// types have no compiler encoding the runtime can reproduce.
static std::string GetAccessorTypeEncoding(const TypeEncoding* typeEncoding,
int argsCount,
const char* fallback);
// `klass` or its nearest superclass not defined from JS.
static Class FindNativeClass(Class klass);
// The implementation of `method` from FindNativeClass(klass).
static IMP FindNotOverridenMethod(Class klass, SEL method);
// Whether `klass`, not one of its superclasses, implements `selector`.
static bool ImplementsItself(Class klass, SEL selector);

private:
static std::atomic<unsigned long long> classNameCounter_;
Expand Down Expand Up @@ -73,7 +82,13 @@ class ClassBuilder {
v8::Local<v8::Object> implementationObject,
v8::Local<v8::Value> getter,
v8::Local<v8::Value> setter);
static std::string GetTypeEncoding(const TypeEncoding* typeEncoding);
// Follows clang: a struct behind a pointer is expanded only when that
// pointer is the outermost type, otherwise it is named only ("{Name}"),
// which also bounds self-referential structs.
static std::string GetTypeEncoding(const TypeEncoding* typeEncoding,
bool* encodable,
bool expandStructures = true,
bool expandPointedToStructures = true);
static BinaryTypeEncodingType GetTypeEncodingType(v8::Isolate* isolate,
v8::Local<v8::Value> value);

Expand Down
68 changes: 56 additions & 12 deletions NativeScript/runtime/ClassBuilder.mm
Original file line number Diff line number Diff line change
Expand Up @@ -435,7 +435,8 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) {
implementationObject);
}

std::string ClassBuilder::GetTypeEncoding(const TypeEncoding* typeEncoding) {
std::string ClassBuilder::GetTypeEncoding(const TypeEncoding* typeEncoding, bool* encodable,
bool expandStructures, bool expandPointedToStructures) {
BinaryTypeEncodingType type = typeEncoding->type;
switch (type) {
case BinaryTypeEncodingType::VoidEncoding: {
Expand Down Expand Up @@ -504,15 +505,22 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) {
}
case BinaryTypeEncodingType::StructDeclarationReference: {
const char* structName = typeEncoding->details.declarationReference.name.valuePtr();
if (!expandStructures) {
return std::string("{") + structName + "}";
}
const Meta* meta = ArgConverter::GetMeta(structName);
if (encodable != nullptr && (meta == nullptr || meta->type() != MetaType::Struct)) {
*encodable = false;
return "";
}
tns::Assert(meta != nullptr && meta->type() == MetaType::Struct);
const StructMeta* structMeta = static_cast<const StructMeta*>(meta);
const TypeEncoding* fieldEncoding = structMeta->fieldsEncodings()->first();

std::stringstream ss;
ss << "{" << structName << "=";
for (int i = 0; i < structMeta->fieldsCount(); i++) {
ss << GetTypeEncoding(fieldEncoding);
ss << GetTypeEncoding(fieldEncoding, encodable, true, false);
fieldEncoding = fieldEncoding->next();
}
ss << "}";
Expand All @@ -522,24 +530,28 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) {
std::stringstream ss;
ss << "^";
const TypeEncoding* innerType = typeEncoding->details.pointer.getInnerType();
ss << GetTypeEncoding(innerType);
ss << GetTypeEncoding(innerType, encodable, expandPointedToStructures, false);
return ss.str();
}
case BinaryTypeEncodingType::ConstantArrayEncoding: {
const TypeEncoding* innerType = typeEncoding->details.constantArray.getInnerType();
std::stringstream ss;
ss << "[";
ss << typeEncoding->details.constantArray.size << GetTypeEncoding(innerType);
ss << typeEncoding->details.constantArray.size
<< GetTypeEncoding(innerType, encodable, expandStructures, false);
ss << "]";
return ss.str();
}
case BinaryTypeEncodingType::IncompleteArrayEncoding: {
const TypeEncoding* innerType = typeEncoding->details.incompleteArray.getInnerType();
std::stringstream ss;
ss << "^";
ss << GetTypeEncoding(innerType);
ss << GetTypeEncoding(innerType, encodable, expandStructures, false);
return ss.str();
}
case BinaryTypeEncodingType::FunctionPointerEncoding: {
return "^?";
}
case BinaryTypeEncodingType::ProtocolEncoding:
case BinaryTypeEncodingType::InterfaceDeclarationReference:
case BinaryTypeEncodingType::InstanceTypeEncoding:
Expand All @@ -549,24 +561,36 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) {

default:
// TODO: Handle the other possible types
if (encodable != nullptr) {
*encodable = false;
return "";
}
tns::Assert(false);
return "";
}
}

std::string ClassBuilder::GetTypeEncoding(const TypeEncoding* typeEncoding, int argsCount) {
std::string ClassBuilder::GetTypeEncoding(const TypeEncoding* typeEncoding, int argsCount,
bool* encodable) {
std::stringstream compilerEncoding;
compilerEncoding << GetTypeEncoding(typeEncoding);
compilerEncoding << GetTypeEncoding(typeEncoding, encodable);
compilerEncoding << "@:"; // id self, SEL _cmd

for (int i = 0; i < argsCount; i++) {
typeEncoding = typeEncoding->next();
compilerEncoding << GetTypeEncoding(typeEncoding);
compilerEncoding << GetTypeEncoding(typeEncoding, encodable);
}

return compilerEncoding.str();
}

std::string ClassBuilder::GetAccessorTypeEncoding(const TypeEncoding* typeEncoding, int argsCount,
const char* fallback) {
bool encodable = true;
std::string encoding = GetTypeEncoding(typeEncoding, argsCount, &encodable);
return encodable ? encoding : fallback;
}

BinaryTypeEncodingType ClassBuilder::GetTypeEncodingType(Isolate* isolate, Local<Value> value) {
if (BaseDataWrapper* wrapper = tns::GetValue(isolate, value)) {
if (wrapper->Type() == WrapperType::ObjCClass) {
Expand Down Expand Up @@ -883,6 +907,20 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) {
}
}

// Reads the class's own method list: class_getInstanceMethod asks the class to
// resolve a selector nothing implements, which initializes a class that is
// still being built.
bool ClassBuilder::ImplementsItself(Class klass, SEL selector) {
unsigned int count = 0;
Method* methods = class_copyMethodList(klass, &count);
bool found = false;
for (unsigned int i = 0; i < count && !found; i++) {
found = method_getName(methods[i]) == selector;
}
free(methods);
return found;
}

void ClassBuilder::ExposeProperties(Isolate* isolate, Class extendedClass,
std::vector<const PropertyMeta*> propertyMetas,
Local<Object> implementationObject, Local<Value> getter,
Expand All @@ -891,8 +929,12 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) {
const PropertyMeta* propertyMeta = propertyMetas[j];
std::string propertyName = propertyMeta->name();

bool hasGetter = !getter.IsEmpty() && getter->IsFunction() && propertyMeta->hasGetter();
bool hasSetter = !setter.IsEmpty() && setter->IsFunction() && propertyMeta->hasSetter();
// An accessor the class already implements itself came from an earlier
// metadata entry or exposedMethods; class_addMethod would refuse it.
bool hasGetter = !getter.IsEmpty() && getter->IsFunction() && propertyMeta->hasGetter() &&
!ImplementsItself(extendedClass, propertyMeta->getter()->selector());
bool hasSetter = !setter.IsEmpty() && setter->IsFunction() && propertyMeta->hasSetter() &&
!ImplementsItself(extendedClass, propertyMeta->setter()->selector());

std::shared_ptr<Persistent<Object>> poImplementationObject;
if (hasGetter || hasSetter) {
Expand Down Expand Up @@ -950,8 +992,9 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) {
};
const TypeEncoding* typeEncoding = propertyMeta->getter()->encodings()->first();
IMP impGetter = Interop::CreateMethod(2, 0, typeEncoding, getterCallback, userData);
std::string types = GetAccessorTypeEncoding(typeEncoding, 0, "@@:");

class_addMethod(extendedClass, propertyMeta->getter()->selector(), impGetter, "@@:");
class_addMethod(extendedClass, propertyMeta->getter()->selector(), impGetter, types.c_str());
}

if (hasSetter) {
Expand Down Expand Up @@ -1002,8 +1045,9 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) {

const TypeEncoding* typeEncoding = propertyMeta->setter()->encodings()->first();
IMP impSetter = Interop::CreateMethod(2, 1, typeEncoding, setterCallback, userData);
std::string types = GetAccessorTypeEncoding(typeEncoding, 1, "v@:@");

class_addMethod(extendedClass, propertyMeta->setter()->selector(), impSetter, "v@:@");
class_addMethod(extendedClass, propertyMeta->setter()->selector(), impSetter, types.c_str());
}
}
}
Expand Down
53 changes: 34 additions & 19 deletions NativeScript/runtime/MetadataBuilder.mm
Original file line number Diff line number Diff line change
Expand Up @@ -1366,6 +1366,30 @@ CMethodCall methodCall(context, item->userData_, typeEncoding, args,
}
}

namespace {

// The native implementation `klass` answered `selector` with stays reachable
// under the swizzled-prefixed selector that native calls from JS prefer. A
// class that only inherits `selector` below a replaced ancestor takes that
// ancestor's alias: its selector resolves to the ancestor's JS replacement,
// and an alias naming a native override in between would be re-entered when
// that override calls super. Every replaced class gets an alias of its own,
// which a later replacement keeps, so it never names an earlier replacement.
void ReplaceKeepingOriginal(Class klass, SEL selector, const char* selectorName, IMP imp,
const char* types) {
SEL alias = sel_registerName((Constants::SwizzledPrefix + selectorName).c_str());
bool inheritsAlias =
!ClassBuilder::ImplementsItself(klass, selector) && class_respondsToSelector(klass, alias);
Method method = class_getInstanceMethod(klass, inheritsAlias ? alias : selector);
IMP original = method != nullptr ? method_getImplementation(method) : nullptr;
class_replaceMethod(klass, selector, imp, types);
if (original != nullptr) {
class_addMethod(klass, alias, original, types);
}
}

} // namespace

v8::Intercepted MetadataBuilder::SwizzledInstanceMethodCallback(
Local<v8::Name> property, Local<Value> value, const PropertyCallbackInfo<v8::Boolean>& info) {
Isolate* isolate = info.GetIsolate();
Expand Down Expand Up @@ -1402,13 +1426,8 @@ CMethodCall methodCall(context, item->userData_, typeEncoding, args,
Interop::ConsumedObjectArgumentIndex(methodMeta->selector(), typeEncoding, argsCount));
IMP methodBody =
Interop::CreateMethod(2, argsCount, typeEncoding, ArgConverter::MethodCallback, userData);
IMP nativeImp =
class_replaceMethod(klass, methodMeta->selector(), methodBody, compilerEncoding.c_str());
if (nativeImp) {
std::string selector = methodMeta->selectorAsString();
SEL nativeSelector = sel_registerName((Constants::SwizzledPrefix + selector).c_str());
class_addMethod(klass, nativeSelector, nativeImp, compilerEncoding.c_str());
}
ReplaceKeepingOriginal(klass, methodMeta->selector(), methodMeta->selectorAsString(), methodBody,
compilerEncoding.c_str());
// Not intercepted: the native write is done, but V8 must still perform
// the ordinary store, which is what the old void-returning callback did
// by falling through without setting a return value.
Expand Down Expand Up @@ -1493,20 +1512,18 @@ CMethodCall methodCall(context, item->userData_, typeEncoding, args,
}
};

const char* compilerEncoding = "@@:";
const TypeEncoding* typeEncoding = propertyMeta->getter()->encodings()->first();
std::string compilerEncoding = ClassBuilder::GetAccessorTypeEncoding(typeEncoding, 0, "@@:");

Local<Value> getter = desc.get();
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);
IMP impGetter = Interop::CreateMethod(2, 0, typeEncoding, getterCallback, userData);
IMP nativeImp =
class_replaceMethod(klass, propertyMeta->getter()->selector(), impGetter, compilerEncoding);
std::string selector = propertyMeta->getter()->selectorAsString();
SEL nativeSelector = sel_registerName((Constants::SwizzledPrefix + selector).c_str());
class_addMethod(klass, nativeSelector, nativeImp, compilerEncoding);
ReplaceKeepingOriginal(klass, propertyMeta->getter()->selector(),
propertyMeta->getter()->selectorAsString(), impGetter,
compilerEncoding.c_str());
}

if (desc.has_set()) {
Expand Down Expand Up @@ -1566,12 +1583,10 @@ CMethodCall methodCall(context, item->userData_, typeEncoding, args,
new PropertyCallbackContext(isolate, poSetterFunc, nullptr, propertyMeta);
IMP impSetter = Interop::CreateMethod(2, 1, typeEncoding, setterCallback, userData);

const char* compilerEncoding = "v@:@";
IMP nativeImp =
class_replaceMethod(klass, propertyMeta->setter()->selector(), impSetter, compilerEncoding);
std::string selector = propertyMeta->setter()->selectorAsString();
SEL nativeSelector = sel_registerName((Constants::SwizzledPrefix + selector).c_str());
class_addMethod(klass, nativeSelector, nativeImp, compilerEncoding);
std::string compilerEncoding = ClassBuilder::GetAccessorTypeEncoding(typeEncoding, 1, "v@:@");
ReplaceKeepingOriginal(klass, propertyMeta->setter()->selector(),
propertyMeta->setter()->selectorAsString(), impSetter,
compilerEncoding.c_str());
}
// Not intercepted: the native write is done, but V8 must still perform
// the ordinary store, which is what the old void-returning callback did
Expand Down
Loading
Loading