#include "ArgConverter.h" #include #include #include #include #include "ClassBuilder.h" #include "DictionaryAdapter.h" #include "ExternalMemory.h" #include "Helpers.h" #include "Interop.h" #include "NSExceptionSupport.h" #include "NativeScriptException.h" #include "ObjectManager.h" #include "Runtime.h" #include "RuntimeConfig.h" using namespace v8; using namespace std; namespace tns { namespace { // -allowsWeakReference answers NO once deallocation has begun, and for the // rare classes that refuse weak references altogether. Runs before `obj` has // a cached wrapper, so nothing here may be a message a JS class implements: // it would re-enter MethodCallback for the same object. bool IsDeallocating(id obj) { static SEL allowsWeakReference = sel_registerName("allowsWeakReference"); Class nativeClass = ClassBuilder::FindNativeClass(object_getClass(obj)); // class_getMethodImplementation answers the forwarding IMP for a selector // the class lacks. if (!class_respondsToSelector(nativeClass, allowsWeakReference)) { return false; } IMP imp = class_getMethodImplementation(nativeClass, allowsWeakReference); return !((BOOL (*)(id, SEL))imp)(obj, allowsWeakReference); } // Clang's method family rule: optional leading underscores, then the family // name, then the end of the selector's first piece or anything but a // lowercase letter. bool InMethodFamily(SEL selector, const char* family) { const char* name = sel_getName(selector); while (*name == '_') { name++; } size_t length = strlen(family); return strncmp(name, family, length) == 0 && (name[length] < 'a' || name[length] > 'z'); } 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, 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(); } 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::MarkReleased(isolate_, receiver_, tns::ReleasedReason::kDeallocated); delete borrowed_; } } void ArgConverter::Init(Local context) { Isolate* isolate = v8::Isolate::GetCurrent(); auto cache = Caches::Get(isolate); cache->EmptyObjCtorFunc = std::make_unique>( isolate, ArgConverter::CreateEmptyInstanceFunction(context)); } Local ArgConverter::Invoke(Local context, Class klass, Local receiver, V8Args& args, const MethodMeta* meta, bool isMethodCallback) { Isolate* isolate = v8::Isolate::GetCurrent(); id target = nil; Class allocKlass = nil; bool instanceMethod = !receiver.IsEmpty(); bool callSuper = false; if (instanceMethod) { BaseDataWrapper* wrapper = tns::GetValue(isolate, receiver); if (wrapper == nullptr) { tns::ReleasedReason releasedReason = tns::GetReleasedReason(receiver); if (releasedReason != tns::ReleasedReason::kNone) { const char* jsNameStr = meta ? meta->jsName() : ""; tns::ThrowReleasedObject(isolate, releasedReason, std::string("method '") + jsNameStr + "' receiver"); } // During fast view churn like HMR in development, JS objects can outlive their // native wrappers briefly. In Debug, throw a catchable JS error instead of crashing. // In Release, assert so crash reporting can capture unexpected cases. if (RuntimeConfig.IsDebug) { const char* selectorStr = meta ? meta->selectorAsString() : ""; const char* jsNameStr = meta ? meta->jsName() : ""; const char* classNameStr = klass ? class_getName(klass) : ""; std::string errMsg = std::string("Cannot call method '") + jsNameStr + "' on a disposed native object (class: " + classNameStr + ", selector: " + selectorStr + "). This can happen during HMR or fast view churn."; throw NativeScriptException(isolate, errMsg); } else { tns::Assert(false, isolate); } } if (wrapper->Type() == WrapperType::ObjCAllocObject) { ObjCAllocDataWrapper* allocWrapper = static_cast(wrapper); allocKlass = allocWrapper->Klass(); } else if (wrapper->Type() == WrapperType::ObjCObject) { ObjCDataWrapper* objcWrapper = static_cast(wrapper); target = objcWrapper->Data(); auto cache = Caches::Get(isolate); auto it = cache->ClassPrototypes.find(std::string_view(object_getClassName(target))); // For extended classes we will call the base method callSuper = isMethodCallback && it != cache->ClassPrototypes.end(); } else { if (RuntimeConfig.IsDebug) { const char* selectorStr = meta ? meta->selectorAsString() : ""; const char* jsNameStr = meta ? meta->jsName() : ""; const char* classNameStr = klass ? class_getName(klass) : ""; std::string errMsg = std::string("Unexpected receiver wrapper type ") + std::to_string((int)wrapper->Type()) + " for method '" + jsNameStr + "' (class: " + classNameStr + ", selector: " + selectorStr + "). This can happen during HMR or fast view churn."; throw NativeScriptException(isolate, errMsg); } else { tns::Assert(false, isolate); } } } if (args.Length() != meta->encodings()->count - 1) { // Arguments number mismatch -> search for a possible method overload in the class hierarchy std::string methodName = meta->jsName(); std::string className = class_getName(klass); MemberType type = instanceMethod ? MemberType::InstanceMethod : MemberType::StaticMethod; std::vector overloads; ArgConverter::FindMethodOverloads(klass, methodName, type, overloads); if (overloads.size() > 0) { for (auto it = overloads.begin(); it != overloads.end(); it++) { const MethodMeta* methodMeta = (*it); if (args.Length() == methodMeta->encodings()->count - 1) { meta = methodMeta; break; } } } } int argsCount = meta->encodings()->count - 1; if ((!meta->hasErrorOutParameter() && args.Length() != argsCount) || (meta->hasErrorOutParameter() && args.Length() != argsCount && args.Length() != argsCount - 1)) { std::ostringstream errorStream; errorStream << "Actual arguments count: \"" << argsCount << ". Expected: \"" << args.Length() << "\"."; std::string errorMessage = errorStream.str(); throw NativeScriptException(errorMessage); } if (allocKlass != nil) { // The +1 belongs to the initializer invoked below, which consumes it. Nothing // between here and that call may throw, or the reference is lost. target = [allocKlass alloc]; } ObjCMethodCall methodCall(context, meta, target, klass, args, callSuper, allocKlass != nil); return Interop::CallFunction(methodCall); } Local ArgConverter::ConvertArgument(Local context, BaseDataWrapper* wrapper, const std::vector& additionalProtocols) { Isolate* isolate = v8::Isolate::GetCurrent(); if (wrapper == nullptr) { return Null(isolate); } Local result = CreateJsWrapper(context, wrapper, Local(), additionalProtocols); return result; } Local ArgConverter::GetEscapeExceptionBrand(Isolate* isolate) { auto cache = Caches::Get(isolate); // Caches::Get never returns null — after isolate removal it returns a dummy // cache — so validity is the real liveness check before touching V8 state. if (cache == nullptr || !cache->IsValid()) { return Local(); } if (cache->EscapeExceptionBrand == nullptr) { Local brand = Private::New(isolate, tns::ToV8String(isolate, "interop.escapeException")); cache->EscapeExceptionBrand = std::make_unique>(isolate, brand); } return cache->EscapeExceptionBrand->Get(isolate); } // Builds the combined JS stack string attached to an escaped exception via the // associated object: the origin (propagation) stack of the wrapping error and // the escape-site stack, each under a labeled section. Empty or duplicate // sections are omitted; returns nil when nothing is available. static NSString* BuildCombinedJSStack(const std::string& origin, const std::string& escape) { NSMutableArray* parts = [NSMutableArray array]; if (!origin.empty()) { [parts addObject:[NSString stringWithFormat:@"JS stack:\n%@", tns::ToNSString(origin)]]; } if (!escape.empty() && escape != origin) { [parts addObject:[NSString stringWithFormat:@"Escaped at:\n%@", tns::ToNSString(escape)]]; } if (parts.count == 0) { return nil; } return [parts componentsJoinedByString:@"\n\n"]; } id ArgConverter::ExtractEscapedException(Local context, Local value) { Isolate* isolate = v8::Isolate::GetCurrent(); if (value.IsEmpty() || !value->IsObject()) { return nil; } Local brand = GetEscapeExceptionBrand(isolate); if (brand.IsEmpty()) { return nil; } Local obj = value.As(); Maybe hasBrand = obj->HasPrivate(context, brand); if (hasBrand.IsNothing() || !hasBrand.FromJust()) { return nil; } Local payloadVal; if (!obj->GetPrivate(context, brand).ToLocal(&payloadVal) || !payloadVal->IsObject()) { return nil; } Local payload = payloadVal.As(); auto readString = [&](const char* key, const std::string& fallback) -> std::string { Local v; if (payload->Get(context, tns::ToV8String(isolate, key)).ToLocal(&v) && !v.IsEmpty() && v->IsString()) { return tns::ToString(isolate, v); } return fallback; }; // The escape-site stack always travels with the payload; the origin stack is // the wrapping error's own `.stack`, carried when present. std::string escapeStack = readString("escapeStack", ""); // Original NSException carried through unchanged when present. Local nativeExc; if (payload->Get(context, tns::ToV8String(isolate, "nativeException")).ToLocal(&nativeExc) && nativeExc->IsObject()) { BaseDataWrapper* wrapper = tns::GetValue(isolate, nativeExc); if (wrapper != nullptr && wrapper->Type() == WrapperType::ObjCObject) { id data = static_cast(wrapper)->Data(); if ([data isKindOfClass:[NSException class]]) { // Attach the JS stack WITHOUT mutating the original exception's identity // or userInfo — the round-trip contract requires the very same object to // reach the native @catch. The category accessor surfaces it uniformly. std::string originStack = readString("stack", ""); NSString* combined = BuildCombinedJSStack(originStack, escapeStack); if (combined != nil) { tns::SetJSStackOnException((NSException*)data, combined); } return (NSException*)data; } } } // Otherwise synthesize an NSException from the branded name/message/stack. std::string name = readString("name", "NativeScriptException"); std::string message = readString("message", ""); std::string stack = readString("stack", ""); NSString* reasonText = tns::ToNSString(message); if (!stack.empty()) { // Put the JS stack in the reason too so it shows up in native crash logs. reasonText = [reasonText stringByAppendingFormat:@"\n%@", tns::ToNSString(stack)]; } NSMutableDictionary* userInfo = [NSMutableDictionary dictionary]; if (!stack.empty()) { userInfo[TNSJavaScriptStackTraceKey] = tns::ToNSString(stack); } // Carry the escape-site stack separately only when it adds information beyond // the origin stack. if (!escapeStack.empty() && escapeStack != stack) { userInfo[TNSJavaScriptEscapeStackTraceKey] = tns::ToNSString(escapeStack); } NSException* synthesized = [NSException exceptionWithName:tns::ToNSString(name) reason:reasonText userInfo:userInfo.count ? userInfo : nil]; // Attach the combined stack via associated object so the category accessor is // uniform across synthesized and rethrown-original exceptions. NSString* combined = BuildCombinedJSStack(stack, escapeStack); if (combined != nil) { tns::SetJSStackOnException(synthesized, combined); } return synthesized; } id ArgConverter::HandleBoundaryException(Local context, TryCatch& tc) { if (!tc.HasCaught()) { return nil; } Isolate* isolate = v8::Isolate::GetCurrent(); Local exception = tc.Exception(); id escaped = ExtractEscapedException(context, exception); if (escaped != nil) { // Branded escape: convert to an ObjC throw. Clear the V8 exception; the // caller @throws this AFTER closing all V8 scopes. tc.Reset(); return escaped; } // Unbranded: report exactly once through the uncaught path (error-event // dispatch + shims + log; honors uncaughtErrorPolicy). This is the // path for the Assert-hardened sites that today never reach the message // listener at all. Local message = tc.Message(); NativeScriptException::ReportToJsHandlersAndLog(isolate, exception, message); tc.Reset(); // uncaughtErrorPolicy "throw": the report above runs synchronously here (still // under the boundary's live V8 scopes). Under the "throw" policy it deposited // the NSException into the per-isolate slot; claim it and hand it back so the // caller @throws it AFTER closing every V8 scope (same scopes-before-@throw // discipline as a branded escape) — a native @try/@catch around the boundary // then catches it, matching Android. Under the default "report" policy nothing // is deposited and this is nil. id policyThrow = NativeScriptException::ClaimPendingPolicyThrow(isolate); if (policyThrow != nil) { return policyThrow; } return nil; } void ArgConverter::MethodCallback(ffi_cif* cif, void* retValue, void** argValues, void* userData) { MethodCallbackWrapper* data = static_cast(userData); // Owned by this call, which gives it up on every path unless it answers it. id consumedArgument = data->consumedArgumentIndex_ < 0 ? nil : *static_cast(argValues[data->initialParamIndex_ + data->consumedArgumentIndex_]); Isolate* isolate = data->isolateWrapper_.Isolate(); // Declared before all V8 scopes: an ObjC exception must never unwind through a // live V8 scope (Locker/HandleScope/Context::Scope). A branded escape caught // below is captured here and @thrown only after the inner block closes every // V8 scope. NSException* __strong pendingThrow = nil; { // Outlives the Locker: a runtime torn down while this thread waits for the // lock cannot dispose the isolate before the wait is over. Free when this // thread has already entered the isolate. IsolatePin pin = data->isolateWrapper_.Pin(); if (!pin || !data->isolateWrapper_.IsValid()) { memset(retValue, 0, cif->rtype->size); [consumedArgument release]; return; } v8::Locker locker(isolate); // Checked again with the isolate locked: a runtime being destroyed holds // this lock while it removes its caches, so the check above can pass and // the lock then be granted only once the context is gone. ~Runtime drops // the isolate from the live registry before it takes the lock, which is // what makes this second look reliable. if (!data->isolateWrapper_.IsValid()) { memset(retValue, 0, cif->rtype->size); [consumedArgument release]; return; } Isolate::Scope isolate_scope(isolate); HandleScope handle_scope(isolate); std::shared_ptr cache = Caches::Get(isolate); Local context = cache->GetContext(); Context::Scope context_scope(context); std::shared_ptr> poCallback = data->callback_; bool hasErrorOutParameter = false; std::vector> v8Args; v8Args.reserve(data->paramsCount_); const TypeEncoding* typeEncoding = data->typeEncoding_; for (int i = 0; i < data->paramsCount_; i++) { typeEncoding = typeEncoding->next(); if (i == data->paramsCount_ - 1 && ArgConverter::IsErrorOutParameter(typeEncoding)) { hasErrorOutParameter = true; // No need to provide the NSError** parameter to the javascript callback continue; } int argIndex = i + data->initialParamIndex_; uint8_t* argBuffer = (uint8_t*)argValues[argIndex]; BaseCall call(argBuffer); Local jsWrapper = Interop::GetResult(context, typeEncoding, &call, true); if (!jsWrapper.IsEmpty()) { v8Args.push_back(jsWrapper); } else { v8Args.push_back(v8::Undefined(isolate)); } } // Blocks and C function pointers have no receiver. std::optional receiver; if (data->initialParamIndex_ > 1) { receiver.emplace(context, *static_cast(argValues[0])); } Local thiz = receiver ? receiver->Get() : context->Global(); Local result; Local callback = poCallback->Get(isolate).As(); bool success = false; if (hasErrorOutParameter) { // We don't want the global error handler (NativeScriptException::OnUncaughtError) to be // called for javascript exceptions occuring inside methods that have NSError* parameters. // Those js errors will be marshalled to NSError* and sent directly to the calling native // code. The v8::TryCatch statement prevents the global handler to be called. TryCatch tc(isolate); success = callback->Call(context, thiz, (int)v8Args.size(), v8Args.data()).ToLocal(&result); if (!success && tc.HasCaught()) { // A branded escapeException follows the @throw path even here, taking // precedence over NSError-out marshaling. NSException* escaped = ExtractEscapedException(context, tc.Exception()); if (escaped != nil) { pendingThrow = escaped; } else { Local exception = tc.Exception(); std::string message = tns::ToString(isolate, exception); int errorParamIndex = data->initialParamIndex_ + data->paramsCount_ - 1; void* errorParam = argValues[errorParamIndex]; NSError* __strong** outPtr = static_cast(errorParam); if (outPtr && *outPtr) { NSError* error = [NSError errorWithDomain:@"TNSErrorDomain" code:164 userInfo:@{@"TNSJavaScriptError" : tns::ToNSString(message)}]; **static_cast(outPtr) = error; } } } } else { TryCatch tc(isolate); success = callback->Call(context, thiz, (int)v8Args.size(), v8Args.data()).ToLocal(&result); if (!success && tc.HasCaught()) { NSException* escaped = ExtractEscapedException(context, tc.Exception()); if (escaped != nil) { pendingThrow = escaped; } else { // Unbranded: re-throw so the pending exception surfaces to V8's message // listener exactly once (OnUncaughtError), preserving existing behavior. tc.ReThrow(); } } } // uncaughtErrorPolicy "throw" boundary claim (best-effort). Unlike the // HandleBoundaryException sites (property accessors, DictionaryAdapter), // which report the throw SYNCHRONOUSLY within their own frame and can // therefore claim the deposit here, this path uses tc.ReThrow(): the // unbranded exception is surfaced to V8 as pending and only reported when it // reaches an uncaught V8 Invoke boundary UP THE STACK (or is caught in JS // first). Empirically (verified with instrumentation over the suite, // including a native-origin NSOperationQueue-invoked block) the message // listener does NOT run during `tc`'s teardown, so under the "throw" policy // nothing has been deposited by the time we reach this point and this claim // is a no-op — those errors are instead handled by the deferred clean-frame // fallback. The claim is kept as a defensive hook (harmless when the slot is // empty; identity-checked so it can never steal an unrelated deposit) and to // mirror the boundary discipline. Under the default "report" policy nothing // is ever deposited. The NSError-out branch neither reports nor deposits. // Skip when a branded escape already set pendingThrow. if (pendingThrow == nil) { pendingThrow = NativeScriptException::ClaimPendingPolicyThrow(isolate); } if (pendingThrow == nil) { if (!success) { memset(retValue, 0, cif->rtype->size); } else { bool writtenUnowned = ArgConverter::SetValue(context, retValue, cif->rtype->size, result, data->typeEncoding_); ArgConverter::RetainOwnedResult(data->returnOwnership_, argValues, retValue, writtenUnowned, consumedArgument); } } else { memset(retValue, 0, cif->rtype->size); } // A wrapper JS made for the consumed argument holds a reference of its own. if (consumedArgument != nil && !(Interop::IsObjectEncoding(data->typeEncoding_) && *static_cast(retValue) == consumedArgument)) { [consumedArgument release]; } } // all V8 scopes destruct here if (pendingThrow != nil) { @throw pendingThrow; } } // An owned result SetValue wrote at +0 gets a reference of its own, except a // receiver answered in place of itself: that is the reference the caller // passed in. The receiver is never released when another object is answered // instead: a super initializer that substituted it already did, and nothing // here can tell that case apart. void ArgConverter::RetainOwnedResult(NativeReturnOwnership ownership, void** argValues, void* retValue, bool writtenUnowned, id consumedArgument) { if (ownership == NativeReturnOwnership::Unowned || !writtenUnowned) { return; } id returned = *static_cast(retValue); if (returned == nil || returned == consumedArgument || (ownership == NativeReturnOwnership::ReplacesReceiver && returned == *static_cast(argValues[0]))) { return; } [returned retain]; } NativeReturnOwnership ArgConverter::ReturnOwnership(SEL selector, const MethodMeta* meta) { bool isInitializer = meta != nullptr ? meta->isInitializer() : InMethodFamily(selector, "init"); if (Interop::ConsumesReceiver(selector, isInitializer)) { return NativeReturnOwnership::ReplacesReceiver; } bool owned = meta != nullptr ? meta->ownsReturnedCocoaObject() : InMethodFamily(selector, "copy") || InMethodFamily(selector, "mutableCopy") || InMethodFamily(selector, "new") || Interop::ReturnsRetained(selector); return owned ? NativeReturnOwnership::Owned : NativeReturnOwnership::Unowned; } bool ArgConverter::SetValue(Local context, void* retValue, size_t returnSize, Local value, const TypeEncoding* typeEncoding) { if (typeEncoding->type == BinaryTypeEncodingType::VoidEncoding) { return false; } // Runs inside an ffi closure, where a C++ throw cannot propagate; a revoked // proxy returns nil. libffi sizes the return slot to at least ffi_arg even // for narrower types, and the full slot must be written. Local original = value; value = tns::UnwrapProxy(value); if (value.IsEmpty() || value->IsNullOrUndefined()) { memset(retValue, 0, std::max(returnSize, sizeof(ffi_arg))); return false; } Isolate* isolate = v8::Isolate::GetCurrent(); // TODO: Refactor this to reuse some existing logic in Interop::SetFFIParams BinaryTypeEncodingType type = typeEncoding->type; if (tns::IsBool(value)) { bool boolValue = value.As()->Value(); *(ffi_arg*)retValue = (bool)boolValue; return false; } else if (tns::IsNumber(value)) { double numValue = tns::ToNumber(isolate, value); switch (type) { case BinaryTypeEncodingType::UShortEncoding: { *static_cast(retValue) = (unsigned short)numValue; return false; } case BinaryTypeEncodingType::ShortEncoding: { *static_cast(retValue) = (short)numValue; return false; } case BinaryTypeEncodingType::UIntEncoding: { *static_cast(retValue) = (unsigned int)numValue; return false; } case BinaryTypeEncodingType::IntEncoding: { *static_cast(retValue) = (int)numValue; return false; } case BinaryTypeEncodingType::ULongEncoding: { *static_cast(retValue) = (unsigned long)numValue; return false; } case BinaryTypeEncodingType::LongEncoding: { *static_cast(retValue) = (long)numValue; return false; } case BinaryTypeEncodingType::ULongLongEncoding: { *static_cast(retValue) = (unsigned long long)numValue; return false; } case BinaryTypeEncodingType::LongLongEncoding: { *static_cast(retValue) = (long long)numValue; return false; } case BinaryTypeEncodingType::FloatEncoding: { *static_cast(retValue) = (float)numValue; return false; } case BinaryTypeEncodingType::DoubleEncoding: { *static_cast(retValue) = numValue; return false; } default: return false; } } else if (value->IsString()) { if (type == BinaryTypeEncodingType::IdEncoding || type == BinaryTypeEncodingType::InterfaceDeclarationReference) { id data = tns::ToNSString(isolate, value); // this feels wrong but follows the other CFBridgingRetain calls // and also solves a leak auto ref = CFBridgingRetain(data); *(CFTypeRef*)retValue = ref; CFRelease(ref); return true; } } else if (value->IsObject()) { if (type == BinaryTypeEncodingType::InterfaceDeclarationReference || type == BinaryTypeEncodingType::InstanceTypeEncoding || type == BinaryTypeEncodingType::IdEncoding) { BaseDataWrapper* baseWrapper = tns::GetValue(isolate, value); if (baseWrapper != nullptr && baseWrapper->Type() == WrapperType::ObjCObject) { ObjCDataWrapper* wrapper = static_cast(baseWrapper); id data = wrapper->Data(); memset(retValue, 0, sizeof(id)); *static_cast(retValue) = data; return true; } else { // Native code receives this value outside any JS frame, so a released // wrapper is reported (never thrown) and returned as nil. tns::ReleasedReason releasedReason = tns::GetReleasedReason(value); if (releasedReason != tns::ReleasedReason::kNone) { tns::ReportReleasedObject(isolate, value, releasedReason, "method return value", false); memset(retValue, 0, sizeof(id)); return false; } id adapter = [[DictionaryAdapter alloc] initWithJSObject:tns::ProxyReadSource(original, value).As() isolate:isolate]; memset(retValue, 0, sizeof(id)); *static_cast(retValue) = adapter; // CFAutorelease(adapter); return false; } } else if (type == BinaryTypeEncodingType::StructDeclarationReference) { BaseDataWrapper* baseWrapper = tns::GetValue(isolate, value); if (baseWrapper == nullptr) { const char* structName = typeEncoding->details.declarationReference.name.valuePtr(); const Meta* meta = ArgConverter::GetMeta(structName); tns::Assert(meta != nullptr && meta->type() == MetaType::Struct, isolate); const StructMeta* structMeta = static_cast(meta); const StructInfo& structInfo = FFICall::GetStructInfo(structMeta); Interop::InitializeStruct(context, retValue, structInfo.Fields(), value); return false; } else if (baseWrapper->Type() == WrapperType::Struct) { StructWrapper* structWrapper = static_cast(baseWrapper); size_t size = structWrapper->StructInfo().FFIType()->size; void* data = structWrapper->Data(); memcpy(retValue, data, size); return false; } } } // TODO: Handle other return types, i.e. assign the retValue parameter from the v8 result tns::Assert(false, isolate); return false; } void ArgConverter::ConstructObject(Local context, const FunctionCallbackInfo& info, Class klass, const InterfaceMeta* interfaceMeta) { Isolate* isolate = v8::Isolate::GetCurrent(); tns::Assert(klass != nullptr, isolate); id result = nil; // A Caches::Instances entry owns exactly one reference to the object it maps // (ObjectManager::DisposeValue gives it back, and ClassBuilder's swizzled // retain/release read a retainCount of 1 as "only the map holds this"), so // this function must hand the entry a +1 and no more. Tracks whether `result` // already carries one: the alloc/init paths do, a pointer handed in from JS // does not. Constructing from a pointer is non-consuming — interop.handleof // hands out a retain-neutral address, and a +1 reaches JS as an Unmanaged to // be claimed with takeRetainedValue — so that path takes its own reference. bool resultIsOwned = false; if (info.Length() == 1) { BaseDataWrapper* wrapper = tns::GetValue(isolate, info[0]); if (wrapper != nullptr && wrapper->Type() == WrapperType::Pointer) { PointerWrapper* pointerWrapper = static_cast(wrapper); result = (__bridge id)pointerWrapper->Data(); } } if (result == nil && interfaceMeta == nullptr) { const Meta* meta = ArgConverter::FindMeta(klass); if (meta != nullptr && meta->type() == MetaType::Interface) { interfaceMeta = static_cast(meta); } } if (result == nil && interfaceMeta != nullptr && info.Length() > 0) { std::vector> args; const MethodMeta* initializer = ArgConverter::FindInitializer(context, klass, interfaceMeta, info, args); result = [klass alloc]; V8VectorArgs vectorArgs(args); result = Interop::CallInitializer(context, initializer, result, klass, vectorArgs); resultIsOwned = true; } if (result == nil) { result = [[klass alloc] init]; resultIsOwned = true; } auto cache = Caches::Get(isolate); auto poInstance = ArgConverter::FindCachedInstance(isolate, cache, result); if (poInstance != nullptr) { // Read before the release below: when it drops a DictionaryAdapter's last // reference, the adapter's -dealloc resets this handle. Local cached = poInstance->Get(isolate); // An initializer that answered with an already wrapped object (a singleton, // a tagged pointer, a cached cluster instance) leaves us holding a +1 the // existing entry has no use for. if (Interop::ReleasesCachedOwnedReturn(resultIsOwned, OwnedReturnReceiver::AllocatedForCall)) { [result release]; } info.GetReturnValue().Set(cached); } else { ObjCDataWrapper* wrapper = new ObjCDataWrapper(result); Local thiz = info.This(); Local context = cache->GetContext(); tns::SetValue(isolate, thiz, wrapper); std::shared_ptr> poThiz = ObjectManager::Register(context, thiz); cache->Instances.emplace(result, poThiz); // An initializer can answer with an existing object whose release is still // waiting (see CreateJsWrapper). bool tookOver = ObjectManager::TakeDeferredRelease(isolate, result); if (tookOver && resultIsOwned) { [result release]; } else if (!tookOver && !resultIsOwned) { [result retain]; } if (tookOver) { // Only releases of objects that first reached JS on the runtime's // thread are ever queued. wrapper->SetBornOnRuntimeThread(); ObjectManager::ProtectIfNativelyRetained(isolate, result, wrapper); } ExternalMemory::ChargeEstimatedSize(isolate, thiz); } } const MethodMeta* ArgConverter::FindInitializer(Local context, Class klass, const InterfaceMeta* interfaceMeta, const FunctionCallbackInfo& info, std::vector>& args) { Isolate* isolate = v8::Isolate::GetCurrent(); std::vector candidates; args = tns::ArgsToVector(info); std::vector> initializerArgs; std::string constructorTokens; if (info.Length() == 1 && info[0]->IsObject() && tns::GetValue(isolate, info[0]) == nullptr) { Local initializer = tns::UnwrapProxyOrThrow(isolate, info[0]); initializerArgs = GetInitializerArgs(tns::ProxyReadSource(info[0], initializer).As(), constructorTokens); } std::shared_ptr cache = Caches::Get(isolate); bool found = false; do { std::vector initializers = ArgConverter::GetInitializers(cache.get(), klass, interfaceMeta); for (const MethodMeta* candidate : initializers) { if (constructorTokens != "") { const char* expectedTokens = candidate->constructorTokens(); if (strcmp(expectedTokens, constructorTokens.c_str()) == 0) { candidates.clear(); candidates.push_back(candidate); args = initializerArgs; found = true; break; } } if (ArgConverter::CanInvoke(context, candidate, info)) { candidates.push_back(candidate); } } if (found) { break; } interfaceMeta = interfaceMeta->baseMeta(); } while (interfaceMeta); if (candidates.size() == 0) { throw NativeScriptException("No initializer found that matches constructor invocation."); } else if (candidates.size() > 1) { if (info.Length() == 0) { auto it = std::find_if(candidates.begin(), candidates.end(), [](const MethodMeta* c) -> bool { return strcmp(c->name(), "init") == 0; }); if (it != candidates.end()) { return (*it); } } std::stringstream ss; ss << "More than one initializer found that matches constructor invocation:"; for (int i = 0; i < candidates.size(); i++) { ss << " "; ss << candidates[i]->selectorAsString(); } std::string errorMessage = ss.str(); throw NativeScriptException(errorMessage); } return candidates[0]; } bool ArgConverter::CanInvoke(Local context, const MethodMeta* candidate, const FunctionCallbackInfo& info) { if (candidate->encodings()->count - 1 != info.Length()) { return false; } if (info.Length() == 0) { return true; } const TypeEncoding* typeEncoding = candidate->encodings()->first(); for (int i = 0; i < info.Length(); i++) { typeEncoding = typeEncoding->next(); Local arg = info[i]; if (!CanInvoke(context, typeEncoding, arg)) { return false; } } return true; } bool ArgConverter::CanInvoke(Local context, const TypeEncoding* typeEncoding, Local arg) { // A revoked proxy matches anything so marshalling reports it as such. arg = tns::UnwrapProxy(arg); if (arg.IsEmpty() || arg->IsNullOrUndefined()) { return true; } Isolate* isolate = v8::Isolate::GetCurrent(); if (typeEncoding->type == BinaryTypeEncodingType::InterfaceDeclarationReference) { const char* name = typeEncoding->details.declarationReference.name.valuePtr(); if (strcmp(name, "NSNumber") == 0 && tns::IsNumber(arg)) { return true; } if (strcmp(name, "NSString") == 0 && tns::IsString(arg)) { return true; } if (strcmp(name, "NSArray") == 0 && arg->IsArray()) { return true; } if (BaseDataWrapper* wrapper = tns::GetValue(isolate, arg)) { if (wrapper->Type() == WrapperType::ObjCObject) { ObjCDataWrapper* objcWrapper = static_cast(wrapper); Class candidateClass = objc_getClass(name); if (candidateClass != nil && [objcWrapper->Data() isKindOfClass:candidateClass]) { return true; } } } } if (typeEncoding->type == BinaryTypeEncodingType::StructDeclarationReference) { return arg->IsObject(); } if (tns::IsBool(arg)) { return typeEncoding->type == BinaryTypeEncodingType::BoolEncoding || typeEncoding->type == BinaryTypeEncodingType::IdEncoding; } if (tns::IsNumber(arg)) { return typeEncoding->type == BinaryTypeEncodingType::IdEncoding || typeEncoding->type == BinaryTypeEncodingType::UShortEncoding || typeEncoding->type == BinaryTypeEncodingType::ShortEncoding || typeEncoding->type == BinaryTypeEncodingType::UIntEncoding || typeEncoding->type == BinaryTypeEncodingType::IntEncoding || typeEncoding->type == BinaryTypeEncodingType::ULongEncoding || typeEncoding->type == BinaryTypeEncodingType::LongEncoding || typeEncoding->type == BinaryTypeEncodingType::ULongLongEncoding || typeEncoding->type == BinaryTypeEncodingType::LongLongEncoding || typeEncoding->type == BinaryTypeEncodingType::FloatEncoding || typeEncoding->type == BinaryTypeEncodingType::DoubleEncoding || typeEncoding->type == BinaryTypeEncodingType::UCharEncoding || typeEncoding->type == BinaryTypeEncodingType::CharEncoding; } if (tns::IsString(arg)) { return typeEncoding->type == BinaryTypeEncodingType::SelectorEncoding || typeEncoding->type == BinaryTypeEncodingType::UnicharEncoding || typeEncoding->type == BinaryTypeEncodingType::IdEncoding || typeEncoding->type == BinaryTypeEncodingType::CStringEncoding; } if (arg->IsFunction()) { return typeEncoding->type == BinaryTypeEncodingType::BlockEncoding || typeEncoding->type == BinaryTypeEncodingType::ProtocolEncoding; } if (arg->IsArrayBuffer() || arg->IsArrayBufferView() || arg->IsSharedArrayBuffer()) { return typeEncoding->type == BinaryTypeEncodingType::IncompleteArrayEncoding; } return false; } std::vector> ArgConverter::GetInitializerArgs(Local obj, std::string& constructorTokens) { std::vector> args; constructorTokens = ""; Isolate* isolate = v8::Isolate::GetCurrent(); Local context = tns::GetCreationContextOrCurrent(isolate, obj); Local properties; TryCatch tc(isolate); if (!obj->GetOwnPropertyNames(context).ToLocal(&properties)) { throw NativeScriptException(isolate, tc, "Cannot read initializer object"); } std::stringstream ss; for (uint32_t i = 0; i < properties->Length(); i++) { Local propertyName; if (properties->Get(context, i).ToLocal(&propertyName)) { std::string name = tns::ToString(isolate, propertyName); ss << name << ":"; Local propertyValue; if (!obj->Get(context, propertyName).ToLocal(&propertyValue)) { throw NativeScriptException(isolate, tc, "Cannot read initializer object"); } args.push_back(propertyValue); } } constructorTokens = ss.str(); return args; } Local ArgConverter::CreateJsWrapper(Local context, BaseDataWrapper* wrapper, Local receiver, const std::vector& additionalProtocols) { Isolate* isolate = v8::Isolate::GetCurrent(); if (wrapper == nullptr) { return Null(isolate); } // Struct objects come from Interop::StructToValue or a struct constructor, // never from here: their shape and lifetime are per struct type. tns::Assert(wrapper->Type() != WrapperType::Struct, isolate); if (wrapper->Type() == WrapperType::ObjCAllocObject) { ObjCAllocDataWrapper* allocDataWrapper = static_cast(wrapper); Class klass = allocDataWrapper->Klass(); std::shared_ptr> poValue = CreateEmptyObject(context); receiver = poValue->Get(isolate).As(); const Meta* meta = FindMeta(klass); if (meta != nullptr) { auto cache = Caches::Get(isolate); KnownUnknownClassPair pair(objc_getClass(meta->name())); std::vector emptyProtocols; cache->ObjectCtorInitializer(context, static_cast(meta), pair, emptyProtocols); auto it = cache->Prototypes.find(meta); if (it != cache->Prototypes.end()) { Local 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; const TypeEncoding* typeEncoding = nullptr; if (wrapper->Type() == WrapperType::ObjCObject) { ObjCDataWrapper* dataWrapper = static_cast(wrapper); target = dataWrapper->Data(); typeEncoding = dataWrapper->TypeEncoding(); } if (target == nil) { return Null(isolate); } auto cache = Caches::Get(isolate); if (receiver.IsEmpty()) { auto it = cache->Instances.find(target); if (it != cache->Instances.end()) { receiver = it->second->Get(isolate).As(); } else { std::shared_ptr> poValue = CreateEmptyObject(context); receiver = poValue->Get(isolate).As(); tns::SetValue(isolate, receiver, wrapper); cache->Instances.emplace(target, poValue); // An extended class reads its retain count to decide whether native // code owns the object, so a pending release is taken over, not stacked. if (!ObjectManager::TakeDeferredRelease(isolate, target)) { [target retain]; } else if (wrapper->Type() == WrapperType::ObjCObject) { ObjCDataWrapper* objcWrapper = static_cast(wrapper); objcWrapper->SetBornOnRuntimeThread(); ObjectManager::ProtectIfNativelyRetained(isolate, target, objcWrapper); } } } else { tns::SetValue(isolate, receiver, wrapper); } Class klass = [target class]; 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: // class {%@}", NSStringFromClass(klass)]; Log(@"%@", message); Local prototype = it->second->Get(isolate); bool success; if (!receiver->SetPrototype(context, prototype).To(&success) || !success) { tns::Assert(false, isolate); } } else { Class knownClass = objc_getClass(meta->name()); KnownUnknownClassPair pair(knownClass, klass); Local ctorFuncTemplate = cache->ObjectCtorInitializer( context, static_cast(meta), pair, additionalProtocols); Local ctorFunc; bool success = ctorFuncTemplate->GetFunction(context).ToLocal(&ctorFunc); tns::Assert(success, isolate); Local prototypeValue; success = ctorFunc->Get(context, tns::ToV8String(isolate, "prototype")).ToLocal(&prototypeValue); tns::Assert(success, isolate); Local prototype = prototypeValue.As(); if (!receiver->SetPrototype(context, prototype).To(&success) || !success) { tns::Assert(false, isolate); } } } Class metaClass = object_getClass(target); if (class_isMetaClass(metaClass)) { if (tns::GetValue(isolate, receiver) == nullptr) { ObjCClassWrapper* wrapper = new ObjCClassWrapper(klass); tns::SetValue(isolate, receiver, wrapper); } } return receiver; } std::shared_ptr> ArgConverter::FindCachedInstance( Isolate* isolate, const std::shared_ptr& cache, id target) { auto it = cache->Instances.find(target); if (it == cache->Instances.end()) { return nullptr; } BaseDataWrapper* wrapper = tns::GetValue(isolate, it->second->Get(isolate)); if (wrapper != nullptr && wrapper->Type() == WrapperType::ObjCObject) { Class expected = static_cast(wrapper)->Klass(); // A KVO-style isa swizzle replaces the class in place but keeps -class // 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; } } return it->second; } const Meta* ArgConverter::FindMeta(Class klass, const TypeEncoding* typeEncoding) { if (typeEncoding != nullptr && typeEncoding->type == BinaryTypeEncodingType::InterfaceDeclarationReference) { const char* name = typeEncoding->details.interfaceDeclarationReference.name.valuePtr(); const Meta* result = GetMeta(name); if (result != nullptr && result->type() == MetaType::Interface) { return result; } } std::string origClassName = class_getName(klass); const Meta* meta = Caches::Metadata->Get(origClassName); if (meta != nullptr) { return meta; } std::string className = origClassName; while (true) { const Meta* result = GetMeta(className); if (result != nullptr && result->type() == MetaType::Interface) { Caches::Metadata->Insert(origClassName, result); return result; } klass = class_getSuperclass(klass); if (klass == nullptr) { break; } className = class_getName(klass); } return nullptr; } const Meta* ArgConverter::GetMeta(const std::string& name) { bool found; const Meta* meta = Caches::Metadata->Get(name, found); if (meta != nullptr || found) { return meta; } const GlobalTable* globalTable = MetaFile::instance()->globalTableJs(); const Meta* result = globalTable->findMeta(name.c_str(), false /** onlyIfAvailable **/); if (result == nullptr) { const GlobalTable* globalTableInterfaceNames = MetaFile::instance()->globalTableNativeInterfaces(); result = globalTableInterfaceNames->findMeta(name.c_str(), false /** onlyIfAvailable **/); if (result == nullptr) { const GlobalTable* globalTableProtocolNames = MetaFile::instance()->globalTableNativeProtocols(); result = globalTableProtocolNames->findMeta(name.c_str(), false /** onlyIfAvailable **/); } } Caches::Metadata->Insert(name, result); return result; } const ProtocolMeta* ArgConverter::FindProtocolMeta(Protocol* protocol) { std::string protocolName = protocol_getName(protocol); const Meta* meta = ArgConverter::GetMeta(protocolName); if (meta != nullptr && meta->type() != MetaType::ProtocolType) { std::string newProtocolName = protocolName + "Protocol"; size_t protocolIndex = 2; while (objc_getProtocol(newProtocolName.c_str())) { newProtocolName = protocolName + "Protocol" + std::to_string(protocolIndex++); } meta = ArgConverter::GetMeta(newProtocolName); } if (meta == nullptr) { return nullptr; } tns::Assert(meta->type() == MetaType::ProtocolType); const ProtocolMeta* protocolMeta = static_cast(meta); return protocolMeta; } Local ArgConverter::WrapNativeCallbackSelf(Local context, id self, ObjCDataWrapper** borrowed) { Isolate* isolate = v8::Isolate::GetCurrent(); auto cache = Caches::Get(isolate); ObjCDataWrapper* wrapper = new ObjCDataWrapper(self); if (IsDeallocating(self)) { // Called from -dealloc: a retain cannot keep the object alive, so the // wrapper is neither cached nor owning, and the caller detaches it. wrapper->MarkBorrowed(); Local receiver = NewEmptyInstance(context, cache->EmptyObjCtorFunc.get()); CreateJsWrapper(context, wrapper, receiver); *borrowed = wrapper; return receiver; } Local result = CreateJsWrapper(context, wrapper, Local()).As(); if (tns::DeleteWrapperIfUnused(isolate, result, wrapper)) { return result; } // Native code usually still holds the object (it is mid-initialization or // owned by whoever called in), and its JS state must outlive this call: the // handle stays strong until the Instances entry is the object's only owner. auto it = cache->Instances.find(self); if (it != cache->Instances.end() && it->second->IsWeak()) { ObjectManager::ManageOwnership(isolate, wrapper, it->second->ClearWeak()); } return result; } std::shared_ptr> ArgConverter::CreateEmptyObject(Local context) { Isolate* isolate = v8::Isolate::GetCurrent(); Persistent* ctorFunc = Caches::Get(isolate)->EmptyObjCtorFunc.get(); tns::Assert(ctorFunc != nullptr, isolate); return ArgConverter::CreateEmptyInstance(context, ctorFunc); } Local ArgConverter::NewEmptyInstance(Local context, Persistent* ctorFunc) { Isolate* isolate = v8::Isolate::GetCurrent(); Local emptyCtorFunc = ctorFunc->Get(isolate); Local value; if (!emptyCtorFunc->CallAsConstructor(context, 0, nullptr).ToLocal(&value) || value.IsEmpty() || !value->IsObject()) { tns::Assert(false, isolate); } return value.As(); } std::shared_ptr> ArgConverter::CreateEmptyInstance( Local context, Persistent* ctorFunc) { Local result = NewEmptyInstance(context, ctorFunc); return ObjectManager::Register(context, result); } Local ArgConverter::CreateEmptyInstanceFunction(Local context) { Isolate* isolate = v8::Isolate::GetCurrent(); Local emptyInstanceCtorFuncTemplate = FunctionTemplate::New(isolate, nullptr); Local instanceTemplate = emptyInstanceCtorFuncTemplate->InstanceTemplate(); instanceTemplate->SetInternalFieldCount(2); instanceTemplate->SetHandler(IndexedPropertyHandlerConfiguration(IndexedPropertyGetterCallback, IndexedPropertySetterCallback)); Local emptyInstanceCtorFunc; if (!emptyInstanceCtorFuncTemplate->GetFunction(context).ToLocal(&emptyInstanceCtorFunc)) { tns::Assert(false, isolate); } return emptyInstanceCtorFunc; } Intercepted ArgConverter::IndexedPropertyGetterCallback(uint32_t index, const PropertyCallbackInfo& args) { Local thiz = args.Holder(); Isolate* isolate = args.GetIsolate(); BaseDataWrapper* wrapper = tns::GetValue(isolate, thiz); if (wrapper == nullptr || wrapper->Type() != WrapperType::ObjCObject) { return v8::Intercepted::kNo; } ObjCDataWrapper* objcDataWrapper = static_cast(wrapper); id target = objcDataWrapper->Data(); if (![target isKindOfClass:[NSArray class]]) { return v8::Intercepted::kNo; } NSArray* array = (NSArray*)target; if (index >= [array count]) { return v8::Intercepted::kNo; } id obj = [array objectAtIndex:index]; std::shared_ptr cache = Caches::Get(isolate); auto it = cache->Instances.find(obj); if (it != cache->Instances.end()) { args.GetReturnValue().Set(it->second->Get(isolate)); return v8::Intercepted::kYes; } if (obj == nil || obj == [NSNull null]) { args.GetReturnValue().SetNull(); return v8::Intercepted::kYes; } if ([obj isKindOfClass:[@YES class]]) { args.GetReturnValue().Set([obj boolValue]); return v8::Intercepted::kYes; } if ([obj isKindOfClass:[NSDate class]]) { Local context = isolate->GetCurrentContext(); double time = [obj timeIntervalSince1970] * 1000.0; Local date; if (Date::New(context, time).ToLocal(&date)) { args.GetReturnValue().Set(date); return v8::Intercepted::kYes; } std::ostringstream errorStream; errorStream << "Unable to convert " << [obj description] << " to a Date object"; std::string errorMessage = errorStream.str(); Local error = Exception::Error(tns::ToV8String(isolate, errorMessage)); isolate->ThrowException(error); return v8::Intercepted::kYes; } if ([obj isKindOfClass:[NSString class]]) { NSString* nativeStr = (NSString*)obj; args.GetReturnValue().Set(tns::ToV8String(isolate, nativeStr)); return v8::Intercepted::kYes; } if ([obj isKindOfClass:[NSNumber class]] && ![obj isKindOfClass:[NSDecimalNumber class]]) { double value = [obj doubleValue]; args.GetReturnValue().Set(value); return v8::Intercepted::kYes; } Local context = isolate->GetCurrentContext(); auto newWrapper = new ObjCDataWrapper(obj); Local result = ArgConverter::ConvertArgument(context, newWrapper); tns::DeleteWrapperIfUnused(isolate, result, newWrapper); args.GetReturnValue().Set(result); return v8::Intercepted::kYes; } Intercepted ArgConverter::IndexedPropertySetterCallback( uint32_t index, Local value, const PropertyCallbackInfo& args) { Local thiz = args.Holder(); Isolate* isolate = args.GetIsolate(); BaseDataWrapper* wrapper = tns::GetValue(isolate, thiz); if (wrapper == nullptr || wrapper->Type() != WrapperType::ObjCObject) { return v8::Intercepted::kNo; } ObjCDataWrapper* objcDataWrapper = static_cast(wrapper); id target = objcDataWrapper->Data(); if (![target isKindOfClass:[NSMutableArray class]]) { return v8::Intercepted::kNo; } NSMutableArray* array = (NSMutableArray*)target; if (index >= [array count]) { return v8::Intercepted::kNo; } BaseDataWrapper* itemWrapper = tns::GetValue(isolate, value); if (itemWrapper == nullptr || itemWrapper->Type() != WrapperType::ObjCObject) { return v8::Intercepted::kNo; } ObjCDataWrapper* objcItemDataWrapper = static_cast(itemWrapper); id item = objcItemDataWrapper->Data(); [target replaceObjectAtIndex:index withObject:item]; // 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. return v8::Intercepted::kNo; } void ArgConverter::FindMethodOverloads(Class klass, std::string methodName, MemberType type, std::vector& overloads) { const Meta* meta = ArgConverter::FindMeta(klass); if (klass == nullptr || meta == nullptr || meta->type() != MetaType::Interface) { return; } const InterfaceMeta* interfaceMeta = static_cast(meta); MembersCollection members = interfaceMeta->members(methodName.c_str(), methodName.length(), type, true, true, ProtocolMetas()); for (auto it = members.begin(); it != members.end(); it++) { const MethodMeta* methodMeta = static_cast(*it); overloads.push_back(methodMeta); } if (interfaceMeta->baseName() != nullptr) { Class baseClass = objc_getClass(interfaceMeta->baseName()); ArgConverter::FindMethodOverloads(baseClass, methodName, type, overloads); } } bool ArgConverter::IsErrorOutParameter(const TypeEncoding* typeEncoding) { if (typeEncoding->type != BinaryTypeEncodingType::PointerEncoding) { return false; } const TypeEncoding* innerTypeEncoding = typeEncoding->details.pointer.getInnerType(); if (innerTypeEncoding->type != BinaryTypeEncodingType::InterfaceDeclarationReference) { return false; } const char* name = innerTypeEncoding->details.declarationReference.name.valuePtr(); if (name == nullptr) { return false; } return strcmp(name, "NSError") == 0; } std::vector ArgConverter::GetInitializers(Caches* cache, Class klass, const InterfaceMeta* interfaceMeta) { auto it = cache->Initializers.find(interfaceMeta); if (it != cache->Initializers.end()) { return it->second; } KnownUnknownClassPair klasses(klass); std::vector initializers = interfaceMeta->initializersWithProtocols(klasses, ProtocolMetas()); cache->Initializers.emplace(interfaceMeta, initializers); return initializers; } } // namespace tns