Skip to content

Disable ARC #30

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Feb 19, 2020
Merged
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
2 changes: 1 addition & 1 deletion NativeScript/NativeScript.h
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

@interface Config : NSObject

@property (nonatomic) NSString* BaseDir;
@property (nonatomic, retain) NSString* BaseDir;
@property (nonatomic) void* MetadataPtr;
@property BOOL IsDebug;
@property BOOL LogToSystemConsole;
Expand Down
2 changes: 2 additions & 0 deletions NativeScript/NativeScript.mm
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ + (void)start:(Config*)config {

runtime_->RunMainScript();

CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, true);

tns::Tasks::Drain();

runtime_.reset();
Expand Down
4 changes: 1 addition & 3 deletions NativeScript/runtime/ArgConverter.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,13 @@ struct MethodCallbackWrapper {
callback_(callback),
initialParamIndex_(initialParamIndex),
paramsCount_(paramsCount),
typeEncoding_(typeEncoding),
runLoop_(CFRunLoopGetCurrent()) {
typeEncoding_(typeEncoding) {
}
v8::Isolate* isolate_;
std::shared_ptr<v8::Persistent<v8::Value>> callback_;
const uint8_t initialParamIndex_;
const uint8_t paramsCount_;
const TypeEncoding* typeEncoding_;
const CFRunLoopRef runLoop_;
};

class ArgConverter {
Expand Down
67 changes: 52 additions & 15 deletions NativeScript/runtime/ArgConverter.mm
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,25 @@
bool instanceMethod = !receiver.IsEmpty();
bool callSuper = false;
if (instanceMethod) {
tns::Assert(receiver->InternalFieldCount() > 0, isolate);

Local<External> ext = receiver->GetInternalField(0).As<External>();
// TODO: Check the actual type of the DataWrapper
ObjCDataWrapper* wrapper = static_cast<ObjCDataWrapper*>(ext->Value());
target = wrapper->Data();

std::string className = object_getClassName(target);
auto cache = Caches::Get(isolate);
auto it = cache->ClassPrototypes.find(className);
// For extended classes we will call the base method
callSuper = isMethodCallback && it != cache->ClassPrototypes.end();
BaseDataWrapper* wrapper = tns::GetValue(isolate, receiver);
tns::Assert(wrapper != nullptr, isolate);

if (wrapper->Type() == WrapperType::ObjCAllocObject) {
ObjCAllocDataWrapper* allocWrapper = static_cast<ObjCAllocDataWrapper*>(wrapper);
Class klass = allocWrapper->Klass();
target = [klass alloc];
} else if (wrapper->Type() == WrapperType::ObjCObject) {
ObjCDataWrapper* objcWrapper = static_cast<ObjCDataWrapper*>(wrapper);
target = objcWrapper->Data();

std::string className = object_getClassName(target);
auto cache = Caches::Get(isolate);
auto it = cache->ClassPrototypes.find(className);
// For extended classes we will call the base method
callSuper = isMethodCallback && it != cache->ClassPrototypes.end();
} else {
tns::Assert(false, isolate);
}
}

if (args.Length() != meta->encodings()->count - 1) {
Expand Down Expand Up @@ -66,7 +73,8 @@
throw NativeScriptException(errorMessage);
}

return Interop::CallFunction(context, meta, target, klass, args, callSuper);
ObjCMethodCall methodCall(context, meta, target, klass, args, callSuper);
return Interop::CallFunction(methodCall);
}

Local<Value> ArgConverter::ConvertArgument(Local<Context> context, BaseDataWrapper* wrapper, bool skipGCRegistration) {
Expand Down Expand Up @@ -324,6 +332,7 @@
ArgConverter::CreateJsWrapper(context, wrapper, thiz);
std::shared_ptr<Persistent<Value>> poThiz = ObjectManager::Register(context, thiz);
cache->Instances.emplace(result, poThiz);
[result retain];
}
}

Expand Down Expand Up @@ -540,6 +549,32 @@
return receiver;
}

if (wrapper->Type() == WrapperType::ObjCAllocObject) {
ObjCAllocDataWrapper* allocDataWrapper = static_cast<ObjCAllocDataWrapper*>(wrapper);
Class klass = allocDataWrapper->Klass();

std::shared_ptr<Persistent<Value>> poValue = CreateEmptyObject(context, false);
receiver = poValue->Get(isolate).As<Object>();

const Meta* meta = FindMeta(klass);
if (meta != nullptr) {
auto cache = Caches::Get(isolate);
cache->ObjectCtorInitializer(context, static_cast<const BaseClassMeta*>(meta));
auto it = cache->Prototypes.find(meta);
if (it != cache->Prototypes.end()) {
Local<Value> prototype = it->second->Get(isolate);
bool success;
if (!receiver->SetPrototype(context, prototype).To(&success) || !success) {
tns::Assert(false, isolate);
}
}
}

tns::SetValue(isolate, receiver, wrapper);

return receiver;
}

id target = nil;
if (wrapper->Type() == WrapperType::ObjCObject) {
ObjCDataWrapper* dataWrapper = static_cast<ObjCDataWrapper*>(wrapper);
Expand All @@ -558,8 +593,12 @@
} else {
std::shared_ptr<Persistent<Value>> poValue = CreateEmptyObject(context, skipGCRegistration);
receiver = poValue->Get(isolate).As<Object>();
tns::SetValue(isolate, receiver, wrapper);
cache->Instances.emplace(target, poValue);
[target retain];
}
} else {
tns::SetValue(isolate, receiver, wrapper);
}

Class klass = [target class];
Expand Down Expand Up @@ -594,8 +633,6 @@
}
}

tns::SetValue(isolate, receiver, wrapper);

return receiver;
}

Expand Down
6 changes: 3 additions & 3 deletions NativeScript/runtime/ArrayAdapter.mm
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#include "ArrayAdapter.h"
#include "ObjectManager.h"
#include "DataWrapper.h"
#include "Helpers.h"
#include "Interop.h"
Expand All @@ -17,8 +16,8 @@ - (instancetype)initWithJSObject:(Local<Object>)jsObject isolate:(Isolate*)isola
if (self) {
self->isolate_ = isolate;
std::shared_ptr<Caches> cache = Caches::Get(isolate);
Local<Context> context = cache->GetContext();
self->object_ = ObjectManager::Register(context, jsObject);
// TODO: Handle the lifetime of this persistent js object
self->object_ = std::make_shared<Persistent<Value>>(isolate, jsObject);
cache->Instances.emplace(self, self->object_);
tns::SetValue(isolate, jsObject, new ObjCDataWrapper(self));
}
Expand Down Expand Up @@ -101,6 +100,7 @@ - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state object

- (void)dealloc {
self->object_->Reset();
[super dealloc];
}

@end
2 changes: 2 additions & 0 deletions NativeScript/runtime/ClassBuilder.h
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ class ClassBuilder {
static std::string GetTypeEncoding(const TypeEncoding* typeEncoding, int argsCount);
static std::string GetTypeEncoding(const TypeEncoding* typeEncoding);
static BinaryTypeEncodingType GetTypeEncodingType(v8::Isolate* isolate, v8::Local<v8::Value> value);
static IMP FindNotOverridenMethod(Class klass, SEL method);


struct CacheItem {
public:
Expand Down
67 changes: 65 additions & 2 deletions NativeScript/runtime/ClassBuilder.mm
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#include <numeric>
#include <sstream>
#include "ClassBuilder.h"
#include "TNSDerivedClass.h"
#include "NativeScriptException.h"
#include "FastEnumerationAdapter.h"
#include "ArgConverter.h"
Expand Down Expand Up @@ -61,6 +62,9 @@
}

Class extendedClass = ClassBuilder::GetExtendedClass(baseClassName, staticClassName);
class_addProtocol(extendedClass, @protocol(TNSDerivedClass));
class_addProtocol(object_getClass(extendedClass), @protocol(TNSDerivedClass));

if (!nativeSignature.IsEmpty()) {
ClassBuilder::ExposeDynamicMembers(context, extendedClass, implementationObject, nativeSignature);
} else {
Expand Down Expand Up @@ -182,14 +186,17 @@
return;
}

ObjCDataWrapper* dataWrapper = static_cast<ObjCDataWrapper*>(wrapper);
Class baseClass = dataWrapper->Data();
ObjCClassWrapper* classWrapper = static_cast<ObjCClassWrapper*>(wrapper);
Class baseClass = classWrapper->Klass();
std::string baseClassName = class_getName(baseClass);

Local<v8::Function> extendedClassCtorFunc = info[0].As<v8::Function>();
std::string extendedClassName = tns::ToString(isolate, extendedClassCtorFunc->GetName());

__block Class extendedClass = ClassBuilder::GetExtendedClass(baseClassName, extendedClassName);
class_addProtocol(extendedClass, @protocol(TNSDerivedClass));
class_addProtocol(object_getClass(extendedClass), @protocol(TNSDerivedClass));

extendedClassName = class_getName(extendedClass);

tns::SetValue(isolate, extendedClassCtorFunc, new ObjCClassWrapper(extendedClass, true));
Expand Down Expand Up @@ -247,6 +254,54 @@
});
class_addMethod(object_getClass(extendedClass), @selector(initialize), newInitialize, "v@:");

/// We swizzle the retain and release methods for the following reason:
/// When we instantiate a native class via a JavaScript call we add it to the object instances map thus
/// incrementing the retainCount by 1. Then, when the native object is referenced somewhere else its count will become more than 1.
/// Since we want to keep the corresponding JavaScript object alive even if it is not used anywhere, we call GcProtect on it.
/// Whenever the native object is released so that its retainCount is 1 (the object instances map), we unprotect the corresponding JavaScript object
/// in order to make both of them destroyable/GC-able. When the JavaScript object is GC-ed we release the native counterpart as well.
void (*retain)(id, SEL) = (void (*)(id, SEL))FindNotOverridenMethod(extendedClass, @selector(retain));
IMP newRetain = imp_implementationWithBlock(^(id self) {
if ([self retainCount] == 1) {
auto it = cache->Instances.find(self);
if (it != cache->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);
objcWrapper->GcProtect();
}
}
}

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

void (*release)(id, SEL) = (void (*)(id, SEL))FindNotOverridenMethod(extendedClass, @selector(release));
IMP newRelease = imp_implementationWithBlock(^(id self) {
if ([self retainCount] == 2) {
auto it = cache->Instances.find(self);
if (it != cache->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);
objcWrapper->GcUnprotect();
}
}
}

release(self, @selector(release));
});
class_addMethod(extendedClass, @selector(release), newRelease, "v@:");

info.GetReturnValue().Set(v8::Undefined(isolate));
}).ToLocalChecked();

Expand Down Expand Up @@ -761,6 +816,14 @@
info.GetReturnValue().Set(superValue);
}

IMP ClassBuilder::FindNotOverridenMethod(Class klass, SEL method) {
while (class_conformsToProtocol(klass, @protocol(TNSDerivedClass))) {
klass = class_getSuperclass(klass);
}

return class_getMethodImplementation(klass, method);
}

unsigned long long ClassBuilder::classNameCounter_ = 0;

}
76 changes: 56 additions & 20 deletions NativeScript/runtime/DataWrapper.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,25 +13,26 @@ namespace tns {
class PrimitiveDataWrapper;

enum class WrapperType {
Base,
Primitive,
Enum,
Struct,
StructType,
ObjCObject,
ObjCClass,
ObjCProtocol,
Function,
AnonymousFunction,
Block,
Reference,
ReferenceType,
Pointer,
PointerType,
FunctionReference,
FunctionReferenceType,
ExtVector,
Worker,
Base = 1 << 0,
Primitive = 1 << 1,
Enum = 1 << 2,
Struct = 1 << 3,
StructType = 1 << 4,
ObjCAllocObject = 1 << 5,
ObjCObject = 1 << 6,
ObjCClass = 1 << 7,
ObjCProtocol = 1 << 8,
Function = 1 << 9,
AnonymousFunction = 1 << 10,
Block = 1 << 11,
Reference = 1 << 12,
ReferenceType = 1 << 13,
Pointer = 1 << 14,
PointerType = 1 << 15,
FunctionReference = 1 << 16,
FunctionReferenceType = 1 << 17,
ExtVector = 1 << 18,
Worker = 1 << 19,
};

struct V8Args {
Expand Down Expand Up @@ -160,11 +161,29 @@ struct StructInfo {

class BaseDataWrapper {
public:
BaseDataWrapper()
: gcProtected_(false) {
}

virtual ~BaseDataWrapper() = default;

const virtual WrapperType Type() {
return WrapperType::Base;
}

bool IsGcProtected() {
return this->gcProtected_;
}

void GcProtect() {
this->gcProtected_ = true;
}

void GcUnprotect() {
this->gcProtected_ = false;
}
private:
bool gcProtected_;
};

class EnumDataWrapper: public BaseDataWrapper {
Expand Down Expand Up @@ -367,6 +386,23 @@ class StructWrapper: public StructTypeWrapper {
std::shared_ptr<v8::Persistent<v8::Value>> parent_;
};

class ObjCAllocDataWrapper: public BaseDataWrapper {
public:
ObjCAllocDataWrapper(Class klass)
: klass_(klass) {
}

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

Class Klass() {
return this->klass_;
}
private:
Class klass_;
};

class ObjCDataWrapper: public BaseDataWrapper {
public:
ObjCDataWrapper(id data)
Expand All @@ -378,7 +414,7 @@ class ObjCDataWrapper: public BaseDataWrapper {
}

id Data() {
return data_;
return this->data_;
}
private:
id data_;
Expand Down
Loading