diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index 3f4941b47..6474d1e28 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -289,9 +289,10 @@ jobs: # attempt's bundle out of it first. on_retry_command: rm -rf $TEST_FOLDER-attempt1; mv $TEST_FOLDER $TEST_FOLDER-attempt1 2>/dev/null || true - name: Extract test results + # run_tests.sh extracts the report itself; extracting again would collide. if: ${{ !cancelled() }} run: | - if [ -d "$TEST_FOLDER/test_results.xcresult" ]; then + if [ -d "$TEST_FOLDER/test_results.xcresult" ] && ! ls "$TEST_FOLDER"/test-out/*junit*.xml >/dev/null 2>&1; then ./scripts/export-test-attachments.sh --result "$TEST_FOLDER/test_results.xcresult" --output "$TEST_FOLDER/test-out" fi - name: Test report summary diff --git a/NativeScript/napi/NapiEnv.mm b/NativeScript/napi/NapiEnv.mm index 79ec0c967..d04a6596a 100644 --- a/NativeScript/napi/NapiEnv.mm +++ b/NativeScript/napi/NapiEnv.mm @@ -4,6 +4,7 @@ #include #include "NapiThreadSafeFunction.h" +#include "runtime/Checks.h" #include "runtime/Helpers.h" #include "runtime/NativeScriptException.h" #include "runtime/Runtime.h" @@ -187,10 +188,7 @@ namespace v8impl { void OnFatalError(const char* location, const char* message) { - Log(@"NativeScript Node-API fatal error: %s%s%s", message, - location != nullptr ? " at " : "", location != nullptr ? location : ""); - tns::LogBacktrace(); - abort(); + tns::Fatal(location, std::string("Node-API: ") + (message != nullptr ? message : "")); } } // namespace v8impl diff --git a/NativeScript/runtime/ArgConverter.mm b/NativeScript/runtime/ArgConverter.mm index d9490c78d..5e2d5e993 100644 --- a/NativeScript/runtime/ArgConverter.mm +++ b/NativeScript/runtime/ArgConverter.mm @@ -12,7 +12,6 @@ #include "NativeScriptException.h" #include "ObjectManager.h" #include "Runtime.h" -#include "RuntimeConfig.h" #include "WrapperLifetime.h" #include "WrapperLifetimeCanary.h" @@ -135,6 +134,18 @@ bool IsKVOSubclassOf(Class klass, Class base) { return Caches::Get(isolate)->EmptyObjCtorFunc.get(); } +[[noreturn]] static void ThrowInvalidReceiver(Isolate* isolate, Class klass, const MethodMeta* meta, + const std::string& receiverDescription) { + const char* selectorStr = meta ? meta->selectorAsString() : ""; + const char* jsNameStr = meta ? meta->jsName() : ""; + const char* classNameStr = klass ? class_getName(klass) : ""; + std::string message = std::string("Cannot call method '") + jsNameStr + "' on " + + receiverDescription + " (class: " + classNameStr + + ", selector: " + selectorStr + ")."; + throw NativeScriptException(isolate, v8::Exception::TypeError(tns::ToV8String(isolate, message)), + message); +} + Local ArgConverter::Invoke(Local context, Class klass, Local receiver, V8Args& args, const MethodMeta* meta, bool isMethodCallback) { Isolate* isolate = v8::Isolate::GetCurrent(); @@ -154,21 +165,10 @@ bool IsKVOSubclassOf(Class klass, Class base) { 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); - } + ThrowInvalidReceiver(isolate, klass, meta, + receiver->InternalFieldCount() > 0 + ? "a receiver that has no native object" + : "a receiver that is not a native object"); } if (wrapper->Type() == WrapperType::ObjCAllocObject) { @@ -183,18 +183,9 @@ bool IsKVOSubclassOf(Class klass, Class base) { // 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); - } + ThrowInvalidReceiver(isolate, klass, meta, + "a receiver that is not a native object instance (wrapper type " + + std::to_string((int)wrapper->Type()) + ")"); } } diff --git a/NativeScript/runtime/Checks.h b/NativeScript/runtime/Checks.h new file mode 100644 index 000000000..2cd6a0159 --- /dev/null +++ b/NativeScript/runtime/Checks.h @@ -0,0 +1,93 @@ +#ifndef Checks_h +#define Checks_h + +#include + +// How runtime code handles a failed condition: +// +// - A condition JS can reach throws a JS error: a TypeError for a bad +// argument or receiver, or the exception a failed V8 call left pending. +// - A failed v8::Maybe / MaybeLocal call propagates its pending exception. +// - NS_CHECK(cond, message): an invariant whose violation makes continuing +// unsafe. On in every build. +// - NS_DCHECK(cond) / NS_DCHECK_MSG(cond, message): a cheap internal sanity +// check, on only while NS_DCHECK_IS_ON. It is the one intentional +// Debug/Release difference, so it never guards anything JS can reach. +// - NS_UNREACHABLE(message): a branch that cannot be taken. +// - tns::Assert is legacy: a call site moves to the above when its code is +// touched. +// +// All of them end in tns::Fatal, which logs the location, the message, the +// native backtrace and, when an isolate is entered on the calling thread, the +// JS stack, then aborts. +// +// The names are prefixed: the vendored V8 inspector headers and the Node-API +// shim define their own unprefixed CHECK/DCHECK. + +namespace tns { + +[[noreturn]] void Fatal(const char* location, const std::string& message); + +} // namespace tns + +#define NS_CHECKS_STRINGIFY_HELPER(x) #x +#define NS_CHECKS_STRINGIFY(x) NS_CHECKS_STRINGIFY_HELPER(x) +#define NS_CHECKS_LOCATION __FILE__ ":" NS_CHECKS_STRINGIFY(__LINE__) + +#ifndef NS_DCHECK_IS_ON +#if defined(DEBUG) +#define NS_DCHECK_IS_ON 1 +#elif defined(__has_feature) +#if __has_feature(address_sanitizer) +#define NS_DCHECK_IS_ON 1 +#else +#define NS_DCHECK_IS_ON 0 +#endif +#else +#define NS_DCHECK_IS_ON 0 +#endif +#endif + +#define NS_CHECK(cond, message) \ + do { \ + if (!(cond)) [[unlikely]] { \ + ::tns::Fatal(NS_CHECKS_LOCATION, \ + std::string("NS_CHECK(" #cond ") failed: ") + (message)); \ + } \ + } while (0) + +#if NS_DCHECK_IS_ON +#define NS_DCHECK(cond) \ + do { \ + if (!(cond)) [[unlikely]] { \ + ::tns::Fatal(NS_CHECKS_LOCATION, "NS_DCHECK(" #cond ") failed"); \ + } \ + } while (0) +#define NS_DCHECK_MSG(cond, message) \ + do { \ + if (!(cond)) [[unlikely]] { \ + ::tns::Fatal(NS_CHECKS_LOCATION, \ + std::string("NS_DCHECK(" #cond ") failed: ") + (message)); \ + } \ + } while (0) +#else +// Never evaluated, but still compiled, so names used only here stay used. +#define NS_DCHECK(cond) \ + do { \ + if (false) { \ + (void)(cond); \ + } \ + } while (0) +#define NS_DCHECK_MSG(cond, message) \ + do { \ + if (false) { \ + (void)(cond); \ + (void)(message); \ + } \ + } while (0) +#endif + +#define NS_UNREACHABLE(message) \ + ::tns::Fatal(NS_CHECKS_LOCATION, std::string("NS_UNREACHABLE: ") + (message)) + +#endif /* Checks_h */ diff --git a/NativeScript/runtime/ClassBuilder.mm b/NativeScript/runtime/ClassBuilder.mm index a09e67c12..91c066b0b 100644 --- a/NativeScript/runtime/ClassBuilder.mm +++ b/NativeScript/runtime/ClassBuilder.mm @@ -41,6 +41,10 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { struct RetainTrackedClasses { std::unordered_set classes; }; + +void ThrowTypeError(Isolate* isolate, const std::string& message) { + isolate->ThrowException(Exception::TypeError(tns::ToV8String(isolate, message))); +} } // namespace Local ClassBuilder::GetExtendFunction(Isolate* isolate, @@ -54,7 +58,24 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { void ClassBuilder::ExtendCallback(const FunctionCallbackInfo& info) { Isolate* isolate = info.GetIsolate(); - tns::Assert(info.Length() > 0 && info[0]->IsObject() && info.This()->IsFunction(), isolate); + if (!info.This()->IsFunction()) { + ThrowTypeError(isolate, "extend() must be called on a native class constructor"); + return; + } + Local baseFunc = info.This().As(); + std::string baseClassName = tns::ToString(isolate, baseFunc->GetName()); + if (info.Length() == 0 || !info[0]->IsObject()) { + ThrowTypeError(isolate, baseClassName + + ".extend() expects an object with the class's members as its " + "first argument"); + return; + } + if (info.Length() > 1 && !info[1]->IsNullOrUndefined() && !info[1]->IsObject()) { + ThrowTypeError(isolate, baseClassName + + ".extend() expects an object with the native class options " + "(name, protocols, exposedMethods) as its second argument"); + return; + } try { Local context = isolate->GetCurrentContext(); @@ -62,8 +83,6 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { info.Data().As()->Value(v8::kExternalPointerTypeTagDefault)); Local implementationObject = info[0].As(); - Local baseFunc = info.This().As(); - std::string baseClassName = tns::ToString(isolate, baseFunc->GetName()); BaseDataWrapper* baseWrapper = tns::GetValue(isolate, baseFunc); if (baseWrapper != nullptr && baseWrapper->Type() == WrapperType::ObjCClass) { @@ -78,9 +97,10 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { if (info.Length() > 1 && info[1]->IsObject()) { nativeSignature = info[1].As(); Local explicitClassName; - tns::Assert(nativeSignature->Get(context, tns::ToV8String(isolate, "name")) - .ToLocal(&explicitClassName), - isolate); + if (!nativeSignature->Get(context, tns::ToV8String(isolate, "name")) + .ToLocal(&explicitClassName)) { + return; + } if (!explicitClassName.IsEmpty() && !explicitClassName->IsNullOrUndefined()) { staticClassName = tns::ToString(isolate, explicitClassName); } @@ -88,6 +108,28 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { auto cache = Caches::Get(isolate); auto isolateId = cache->getIsolateId(); + Local baseCtorFunc = + cache->CtorFuncs.find(item->meta_->name())->second->Get(isolate); + Local baseProto; + bool success = + baseCtorFunc->Get(context, tns::ToV8String(isolate, "prototype")).ToLocal(&baseProto); + tns::Assert(success, isolate); + + // Probed before the native class is registered, so a refusal leaves no class + // holding the requested name. The original prototype goes back right away: + // member discovery below reads through it. A refused change comes back as + // Nothing with no exception pending. Not for a Proxy: GetPrototype() does not + // reach its target, so the restore would drop the target's prototype. + Local originalProto = implementationObject->GetPrototype(); + if (!implementationObject->IsProxy() && + (!implementationObject->SetPrototype(context, baseProto).FromMaybe(false) || + !implementationObject->SetPrototype(context, originalProto).FromMaybe(false))) { + ThrowTypeError(isolate, baseClassName + + ".extend() could not set the prototype of its first argument, " + "which must be an extensible object"); + return; + } + ScopeClassNameToIsolate(staticClassName, isolateId); Class extendedClass = ClassBuilder::GetExtendedClass(baseClassName, staticClassName, isolateId); tns::Assert(extendedClass != nil, isolate); @@ -103,9 +145,6 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { implementationObject); } - Local baseCtorFunc = - cache->CtorFuncs.find(item->meta_->name())->second->Get(isolate); - CacheItem* cacheItem = new CacheItem(nullptr, extendedClass); Caches::Get(isolate)->registerCacheBoundObject(cacheItem); Local ext = External::New(isolate, cacheItem, v8::kExternalPointerTypeTagDefault); @@ -120,13 +159,11 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { tns::Assert(false, isolate); } - Local baseProto; - bool success = - baseCtorFunc->Get(context, tns::ToV8String(isolate, "prototype")).ToLocal(&baseProto); - tns::Assert(success, isolate); - - if (!implementationObject->SetPrototype(context, baseProto).To(&success) || !success) { - tns::Assert(false, isolate); + if (!implementationObject->SetPrototype(context, baseProto).FromMaybe(false)) { + ThrowTypeError(isolate, baseClassName + + ".extend() could not set the prototype of its first argument, " + "which must be an extensible object"); + return; } Local superGetter; if (!FunctionTemplate::New(isolate, SuperAccessorGetterCallback, ext) @@ -214,15 +251,15 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { Local context = isolate->GetCurrentContext(); auto cache = Caches::Get(isolate); - BaseDataWrapper* wrapper = tns::GetValue(isolate, info[1].As()); - if (!wrapper) { - // We are not extending a native object -> call the base __extends function + BaseDataWrapper* wrapper = + info[1]->IsObject() ? tns::GetValue(isolate, info[1].As()) : nullptr; + if (wrapper == nullptr || wrapper->Type() != WrapperType::ObjCClass) { + // Not a native class: the base __extends function's inheritance. Persistent* poExtendsFunc = cache->OriginalExtendsFunc.get(); tns::Assert(poExtendsFunc != nullptr, isolate); Local originalExtendsFunc = poExtendsFunc->Get(isolate); Local args[] = {info[0], info[1]}; - originalExtendsFunc->Call(context, context->Global(), info.Length(), args) - .ToLocalChecked(); + (void)originalExtendsFunc->Call(context, context->Global(), 2, args); return; } @@ -230,6 +267,11 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { Class baseClass = classWrapper->Klass(); std::string baseClassName = class_getName(baseClass); + if (!info[0]->IsFunction()) { + ThrowTypeError(isolate, + "__extends() expects a constructor function to extend " + baseClassName); + return; + } Local extendedClassCtorFunc = info[0].As(); std::string extendedClassName = tns::ToString(isolate, extendedClassCtorFunc->GetName()); diff --git a/NativeScript/runtime/Helpers.h b/NativeScript/runtime/Helpers.h index c1f78c4ca..bb6a7da2e 100644 --- a/NativeScript/runtime/Helpers.h +++ b/NativeScript/runtime/Helpers.h @@ -587,10 +587,11 @@ std::string GetSmartStackTrace(v8::Isolate* isolate, v8::TryCatch* tryCatch = nu bool LiveSync(v8::Isolate* isolate); +// Legacy: new code uses NS_CHECK / NS_DCHECK / NS_UNREACHABLE (Checks.h), or +// throws for a condition JS can reach. void Assert(bool condition, v8::Isolate* isolate = nullptr, - std::string const& reason = std::string()); - -void StopExecutionAndLogStackTrace(v8::Isolate* isolate); + std::string const& reason = std::string(), const char* file = __builtin_FILE(), + int line = __builtin_LINE()); // Helpers from Node inline v8::Local OneByteString(v8::Isolate* isolate, const char* data, int length) { diff --git a/NativeScript/runtime/Helpers.mm b/NativeScript/runtime/Helpers.mm index 76ce2be28..d1a215ac3 100644 --- a/NativeScript/runtime/Helpers.mm +++ b/NativeScript/runtime/Helpers.mm @@ -16,6 +16,7 @@ #include #include #include "Caches.h" +#include "Checks.h" #include "ErrorEvents.h" #include "NativeScriptException.h" #include "ObjectManager.h" @@ -1166,46 +1167,45 @@ throw NativeScriptException( return true; } -void tns::Assert(bool condition, Isolate* isolate, std::string const& reason) { - if (!RuntimeConfig.IsDebug) { - assert(condition); - return; +void tns::Fatal(const char* location, const std::string& message) { + // A check failing while this reports (say, inside the JS stack walk) must + // not recurse. + static thread_local bool reporting = false; + if (reporting) { + abort(); } + reporting = true; - if (condition) { - return; - } + Log(@"====== Fatal error ======"); + Log(@"Location: %s", location != nullptr ? location : ""); + Log(@"Message: %s", message.c_str()); + Log(@"Native stack trace:"); + LogBacktrace(); - if (isolate == nullptr) { - Runtime* runtime = Runtime::GetCurrentRuntime(); - if (runtime != nullptr) { - isolate = runtime->GetIsolate(); - } + // Reading the JS stack needs the isolate entered on this thread. + if (Isolate* isolate = v8::Isolate::TryGetCurrent()) { + HandleScope handleScope(isolate); + Log(@"JavaScript stack trace:"); + std::string stack = tns::GetStackTrace(isolate); + Log(@"%s", stack.c_str()); } - if (isolate == nullptr) { - Log(@"====== Assertion failed ======"); - if (!reason.empty()) { - Log(@"Reason: %s", reason.c_str()); - } - Log(@"Native stack trace:"); - LogBacktrace(); - assert(false); + // abort(), not assert(): this must stop the process whether or not NDEBUG + // is defined. + abort(); +} + +void tns::Assert(bool condition, Isolate* isolate, std::string const& reason, const char* file, + int line) { + (void)isolate; + if (condition) [[likely]] { return; } - - Log(@"====== Assertion failed ======"); - Log(@"Native stack trace:"); - LogBacktrace(); - - Log(@"JavaScript stack trace:"); - std::string stack = tns::GetStackTrace(isolate); - Log(@"%s", stack.c_str()); - assert(false); + std::string location = + std::string(file != nullptr ? file : "") + ":" + std::to_string(line); + tns::Fatal(location.c_str(), reason.empty() ? "assertion failed" : reason); } -void tns::StopExecutionAndLogStackTrace(v8::Isolate* isolate) { Assert(false, isolate); } - namespace tns { Local NewFunctionTemplate(v8::Isolate* isolate, v8::FunctionCallback callback, Local data, diff --git a/NativeScript/runtime/Interop.h b/NativeScript/runtime/Interop.h index 62b294794..d7b1ccc2f 100644 --- a/NativeScript/runtime/Interop.h +++ b/NativeScript/runtime/Interop.h @@ -182,9 +182,6 @@ class Interop { BaseCall* call); private: - static void ExecuteWriteValueDebugValidationsIfInDebug( - v8::Local context, const TypeEncoding* typeEncoding, - void* dest, v8::Local arg); static std::pair CreateMethodInternal( const uint8_t initialParamIndex, const uint8_t argsCount, const TypeEncoding* typeEncoding, FFIMethodCallback callback, diff --git a/NativeScript/runtime/Interop.mm b/NativeScript/runtime/Interop.mm index 6edb223c1..b37028899 100644 --- a/NativeScript/runtime/Interop.mm +++ b/NativeScript/runtime/Interop.mm @@ -410,7 +410,6 @@ static bool SnapshotArrayLike(Isolate* isolate, Local object, Local original = arg; arg = tns::UnwrapProxyOrThrow(isolate, arg); Local source = tns::ProxyReadSource(original, arg); - ExecuteWriteValueDebugValidationsIfInDebug(context, typeEncoding, dest, arg); ValueCache argHelper(arg); if (arg.IsEmpty() || arg->IsNullOrUndefined()) { ffi_type* ffiType = FFICall::GetArgumentType(typeEncoding, true); @@ -2105,77 +2104,4 @@ throw NativeScriptException( return result; } -// MARK: - Debug Messages for the runtime - -void ExecuteWriteValueValidationsAndStopExecutionAndLogStackTrace(Local context, - const TypeEncoding* typeEncoding, - void* dest, Local arg) { - Isolate* isolate = v8::Isolate::GetCurrent(); - std::string destName = typeEncoding->details.interfaceDeclarationReference.name.valuePtr(); - Local originArg = arg; - if (typeEncoding->type == BinaryTypeEncodingType::InterfaceDeclarationReference) { - if (originArg->IsObject()) { - Local originObj = originArg.As(); - if ((originObj->IsArrayBuffer() || originObj->IsArrayBufferView() || - originObj->IsSharedArrayBuffer()) && - destName != "NSArray") { - tns::StopExecutionAndLogStackTrace(isolate); - } - } - if (destName == "NSString" && tns::IsNumber(originArg)) { - tns::StopExecutionAndLogStackTrace(isolate); - } - if (destName == "NSString" && tns::IsBool(originArg)) { - tns::StopExecutionAndLogStackTrace(isolate); - } - if (destName == "NSString" && tns::IsArrayOrArrayLike(isolate, originArg)) { - tns::StopExecutionAndLogStackTrace(isolate); - } - } -} - -bool IsTypeEncondingHandldedByDebugMessages(const TypeEncoding* typeEncoding) { - if (typeEncoding->type != BinaryTypeEncodingType::InterfaceDeclarationReference && - typeEncoding->type != BinaryTypeEncodingType::StructDeclarationReference && - typeEncoding->type != BinaryTypeEncodingType::IdEncoding) { - return true; - } else { - return false; - } -} - -void LogWriteValueTraceMessage(Local context, const TypeEncoding* typeEncoding, void* dest, - Local arg) { - Isolate* isolate = v8::Isolate::GetCurrent(); - std::string destName = typeEncoding->details.interfaceDeclarationReference.name.valuePtr(); - std::string originName = tns::ToString(isolate, arg); - if (originName == "") { - // empty string - originName = "\"\""; - } - // NOTE: stringWithFormat is slow, perhaps use different c string concatenation? - NSString* message = [NSString stringWithFormat:@"Interop::WriteValue: from {%s} to {%s}", - originName.c_str(), destName.c_str()]; - Log(@"%@", message); -} - -void Interop::ExecuteWriteValueDebugValidationsIfInDebug(Local context, - const TypeEncoding* typeEncoding, - void* dest, Local arg) { -#ifdef DEBUG - id value = Runtime::GetAppConfigValue("logRuntimeDetail"); - bool logRuntimeDetail = value ? [value boolValue] : false; - if (logRuntimeDetail) { - if (arg.IsEmpty() || arg->IsNullOrUndefined()) { - return; - } - if (IsTypeEncondingHandldedByDebugMessages(typeEncoding)) { - return; - } - LogWriteValueTraceMessage(context, typeEncoding, dest, arg); - ExecuteWriteValueValidationsAndStopExecutionAndLogStackTrace(context, typeEncoding, dest, arg); - } -#endif -} - } // namespace tns diff --git a/NativeScript/runtime/MetadataBuilder.h b/NativeScript/runtime/MetadataBuilder.h index 992a4abf5..4fb7562f0 100644 --- a/NativeScript/runtime/MetadataBuilder.h +++ b/NativeScript/runtime/MetadataBuilder.h @@ -87,6 +87,8 @@ class MetadataBuilder { const v8::FunctionCallbackInfo& info); static void AllocCallback(const v8::FunctionCallbackInfo& info); static void MethodCallback(const v8::FunctionCallbackInfo& info); + static void InstanceMethodCallback( + const v8::FunctionCallbackInfo& info); static void CFunctionCallback( const v8::FunctionCallbackInfo& info); static void PropertyGetterCallback( diff --git a/NativeScript/runtime/MetadataBuilder.mm b/NativeScript/runtime/MetadataBuilder.mm index e2de3e844..02470cf4a 100644 --- a/NativeScript/runtime/MetadataBuilder.mm +++ b/NativeScript/runtime/MetadataBuilder.mm @@ -78,6 +78,26 @@ bool ResolveProxyReceiver(Isolate* isolate, Local& receiver, const char* return true; } +// The receiver an instance member dispatches on. A native class constructor +// makes it a class-side call: the result is empty and `klass` becomes that +// class. Any other receiver is returned as is, and ArgConverter::Invoke rejects +// one that is not a native object. +Local InstanceMemberReceiver(Isolate* isolate, Local receiver, Class& klass) { + if (receiver->InternalFieldCount() > 0 || !receiver->IsFunction()) { + return receiver; + } + BaseDataWrapper* wrapper = tns::GetValue(isolate, receiver); + if (wrapper == nullptr || wrapper->Type() != WrapperType::ObjCClass) { + return receiver; + } + klass = static_cast(wrapper)->Klass(); + return Local(); +} + +void ThrowTypeError(Isolate* isolate, const std::string& message) { + isolate->ThrowException(Exception::TypeError(tns::ToV8String(isolate, message))); +} + // Internal field layout: see StructWrapper. The parent<->view cycle is plain // JS, so the collector can reclaim it. constexpr int kStructParentField = StructWrapper::kParentField; @@ -1215,7 +1235,7 @@ void CollectInstanceMemberNames(const BaseClassMeta* meta, Class klass, bool own Caches::Get(isolate)->registerCacheBoundObject(item); Local ext = External::New(isolate, item, v8::kExternalPointerTypeTagDefault); Local instanceMethodTemplate = - FunctionTemplate::New(isolate, MethodCallback, ext); + FunctionTemplate::New(isolate, InstanceMethodCallback, ext); proto->Set(tns::ToV8String(isolate, methodMeta->jsName()), instanceMethodTemplate); if (guarded != nullptr) { guarded->push_back(methodMeta->jsName()); @@ -1421,13 +1441,27 @@ void CollectInstanceMemberNames(const BaseClassMeta* meta, Class klass, bool own void MetadataBuilder::ClassConstructorCallback(const FunctionCallbackInfo& info) { Isolate* isolate = info.GetIsolate(); Local context = isolate->GetCurrentContext(); - tns::Assert(info.IsConstructCall(), isolate); try { CacheItem* item = static_cast*>( info.Data().As()->Value(v8::kExternalPointerTypeTagDefault)); - Class klass = objc_getClass(item->meta_->name()); + const BaseClassMeta* meta = item->meta_; + if (!info.IsConstructCall()) { + ThrowTypeError(isolate, std::string("Class constructor ") + meta->jsName() + + " cannot be invoked without 'new'"); + return; + } + if (meta->type() == MetaType::ProtocolType) { + ThrowTypeError(isolate, + std::string("Cannot construct ") + meta->jsName() + ": it is a protocol"); + return; + } + Class klass = objc_getClass(meta->name()); + if (klass == nil) { + throw NativeScriptException(std::string("Cannot construct ") + meta->jsName() + + ": the class is not available at runtime"); + } - const InterfaceMeta* interfaceMeta = static_cast(item->meta_); + const InterfaceMeta* interfaceMeta = static_cast(meta); ArgConverter::ConstructObject(context, info, klass, interfaceMeta, WrapperLifetimeCanary::NativeInstancesKind()); } catch (NativeScriptException& ex) { @@ -1437,7 +1471,10 @@ void CollectInstanceMemberNames(const BaseClassMeta* meta, Class klass, bool own void MetadataBuilder::AllocCallback(const FunctionCallbackInfo& info) { Isolate* isolate = info.GetIsolate(); - tns::Assert(info.Length() == 0, isolate); + if (info.Length() != 0) { + ThrowTypeError(isolate, "alloc() takes no arguments"); + return; + } try { Local thiz = info.This(); @@ -1499,17 +1536,34 @@ void CollectInstanceMemberNames(const BaseClassMeta* meta, Class klass, bool own } } +void MetadataBuilder::InstanceMethodCallback(const FunctionCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + CacheItem* item = static_cast*>( + info.Data().As()->Value(v8::kExternalPointerTypeTagDefault)); + + Local thiz = info.This(); + if (!ResolveProxyReceiver(isolate, thiz, "call native method", item->meta_->jsName(), true)) { + return; + } + + V8FunctionCallbackArgs args(info); + Class klass = item->ResolveClass(); + Local receiver = InstanceMemberReceiver(isolate, thiz, klass); + Local context = isolate->GetCurrentContext(); + Local result = + MetadataBuilder::InvokeMethod(context, item->meta_, receiver, args, klass, true); + if (!result.IsEmpty()) { + info.GetReturnValue().Set(result); + } +} + void MetadataBuilder::PropertyGetterCallback(const FunctionCallbackInfo& info) { Isolate* isolate = info.GetIsolate(); CacheItem* item = static_cast*>( info.Data().As()->Value(v8::kExternalPointerTypeTagDefault)); Local receiver = info.This(); if (!ResolveProxyReceiver(isolate, receiver, "read native property", item->meta_->jsName(), - false)) { - return; - } - - if (receiver->InternalFieldCount() < 1) { + true)) { return; } @@ -1520,9 +1574,11 @@ void CollectInstanceMemberNames(const BaseClassMeta* meta, Class klass, bool own } V8EmptyValueArgs args; + Class klass = item->ResolveClass(); + Local target = InstanceMemberReceiver(isolate, receiver, klass); Local context = isolate->GetCurrentContext(); - Local result = MetadataBuilder::InvokeMethod(context, item->meta_->getter(), receiver, - args, item->ResolveClass(), true); + Local result = + MetadataBuilder::InvokeMethod(context, item->meta_->getter(), target, args, klass, true); if (!result.IsEmpty()) { info.GetReturnValue().Set(result); } @@ -1544,13 +1600,14 @@ void CollectInstanceMemberNames(const BaseClassMeta* meta, Class klass, bool own } if (!ResolveProxyReceiver(isolate, receiver, "set native property", item->meta_->jsName(), - false)) { + true)) { return; } V8SimpleValueArgs args(value); + Class klass = item->ResolveClass(); + Local target = InstanceMemberReceiver(isolate, receiver, klass); Local context = isolate->GetCurrentContext(); - MetadataBuilder::InvokeMethod(context, item->meta_->setter(), receiver, args, - item->ResolveClass(), true); + MetadataBuilder::InvokeMethod(context, item->meta_->setter(), target, args, klass, true); } void MetadataBuilder::GuardNativeCalledMethods(Local context, Local prototype, @@ -1733,21 +1790,6 @@ void CollectInstanceMemberNames(const BaseClassMeta* meta, Class klass, bool own // TODO: Find out if the isMethodCallback property can be determined based on a // UITableViewController.prototype.viewDidLoad.call(this) or super.viewDidLoad() call -#ifdef DEBUG - id value = Runtime::GetAppConfigValue("logRuntimeDetail"); - bool logRuntimeDetail = value ? [value boolValue] : false; - if (logRuntimeDetail) { - // NOTE: stringWithFormat is slow, perhaps use different c string concatenation? - NSString* message = [NSString - stringWithFormat:@"MetadataBuilder::InvokeMethod: class {%s}, selector {%s}, " - @"isInitializer {%s}, type {%s}, lib {%s}", - klass ? class_getName(klass) : "", meta->selectorAsString(), - meta->isInitializer() ? "true" : "false", meta->typeName(), - meta->topLevelModule()->getName()]; - Log(@"%@", message); - } -#endif - try { return ArgConverter::Invoke(context, klass, receiver, args, meta, isMethodCallback); } catch (NativeScriptException& ex) { diff --git a/TestRunner/app/tests/Inheritance/InheritanceTests.js b/TestRunner/app/tests/Inheritance/InheritanceTests.js index 2e45b515b..907011134 100644 --- a/TestRunner/app/tests/Inheritance/InheritanceTests.js +++ b/TestRunner/app/tests/Inheritance/InheritanceTests.js @@ -2093,4 +2093,72 @@ describe(module.id, function () { // baseMethod: is declared in the base class (TNSBaseInterface) expect(TNSDerivedInterface.prototype.hasOwnProperty('baseMethod')).toBe(false); }); + + it("throws a TypeError for invalid extend() arguments", function () { + expect(function () { + NSObject.extend(); + }).toThrowError(TypeError, /^NSObject\.extend\(\) expects an object with the class's members as its first argument$/); + expect(function () { + NSObject.extend(1); + }).toThrowError(TypeError, /first argument/); + expect(function () { + NSObject.extend({}, 1); + }).toThrowError(TypeError, /^NSObject\.extend\(\) expects an object with the native class options \(name, protocols, exposedMethods\) as its second argument$/); + var unbound = NSObject.extend; + expect(function () { + unbound({}); + }).toThrowError(TypeError, "extend() must be called on a native class constructor"); + expect(function () { + NSObject.extend(Object.freeze({})); + }).toThrowError(TypeError, /^NSObject\.extend\(\) could not set the prototype of its first argument, which must be an extensible object$/); + }); + + it("leaves a requested class name free when extend() rejects its first argument", function () { + expect(function () { + NSObject.extend(Object.freeze({}), { name: "TNSExtendRetryAfterFrozen" }); + }).toThrowError(TypeError, /extensible object/); + var Retried = NSObject.extend({}, { name: "TNSExtendRetryAfterFrozen" }); + expect(NSStringFromClass(Retried)).toBe("TNSExtendRetryAfterFrozen"); + }); + + it("propagates an exception thrown while reading extend() options", function () { + expect(function () { + NSObject.extend({}, { + get name() { + throw new Error("name getter"); + } + }); + }).toThrowError(Error, "name getter"); + }); + + it("accepts null or undefined extend() options", function () { + expect(NSObject.extend({}, null).new() instanceof NSObject).toBe(true); + expect(NSObject.extend({}, undefined).new() instanceof NSObject).toBe(true); + }); + + it("throws a TypeError when __extends is given a native class and no constructor", function () { + expect(function () { + __extends({}, NSObject); + }).toThrowError(TypeError, "__extends() expects a constructor function to extend NSObject"); + }); + + it("gives __extends plain JS inheritance for a base that is not a native class", function () { + var instance = NSObject.new(); + instance.extend = Math.max; + function Child() {} + __extends(Child, instance); + expect(Object.getPrototypeOf(Child)).toBe(instance); + expect(instance.isEqual(instance)).toBe(true); + + function Thrower() {} + var base = { + extend: Math.max, + get boom() { + throw new Error("boom getter"); + } + }; + expect(function () { + __extends(Thrower, base); + }).toThrowError(Error, "boom getter"); + }); }); diff --git a/TestRunner/app/tests/InvalidReceiverTests.js b/TestRunner/app/tests/InvalidReceiverTests.js new file mode 100644 index 000000000..36191bf1f --- /dev/null +++ b/TestRunner/app/tests/InvalidReceiverTests.js @@ -0,0 +1,108 @@ +describe(module.id, function () { + function findAccessor(proto, name) { + while (proto) { + var descriptor = Object.getOwnPropertyDescriptor(proto, name); + if (descriptor) { + return descriptor; + } + proto = Object.getPrototypeOf(proto); + } + return undefined; + } + + // Objects with internal fields that hold no native object wrapper. + function receiversWithoutNativeObject() { + return [ + new URL("https://example.com/"), + NSArray.arrayWithArray([1])[Symbol.iterator]() + ]; + } + + // Objects whose wrapper is not an Objective-C instance. + function receiversOfOtherWrapperTypes() { + return [ + new interop.Pointer(1), + new interop.Reference(interop.types.int32, 1) + ]; + } + + it("throws a TypeError when a native method is called on a receiver without a native object", function () { + receiversWithoutNativeObject().forEach(function (receiver) { + expect(function () { + NSMutableString.prototype.appendString.call(receiver, "x"); + }).toThrowError(TypeError, /Cannot call method 'appendString' on a receiver that has no native object \(class: NSMutableString, selector: appendString:\)/); + expect(function () { + findAccessor(NSString.prototype, "length").get.call(receiver); + }).toThrowError(TypeError, /receiver that has no native object \(class: NSString, selector: length\)/); + }); + }); + + it("throws a TypeError when a native method is called on a receiver that is not a native object instance", function () { + receiversOfOtherWrapperTypes().forEach(function (receiver) { + expect(function () { + NSMutableString.prototype.appendString.call(receiver, "x"); + }).toThrowError(TypeError, /Cannot call method 'appendString' on a receiver that is not a native object instance \(wrapper type \d+\) \(class: NSMutableString, selector: appendString:\)/); + expect(function () { + findAccessor(NSOperation.prototype, "name").set.call(receiver, "x"); + }).toThrowError(TypeError, /receiver that is not a native object instance .*selector: setName:\)/); + }); + }); + + it("throws a TypeError when a native instance method is called on a plain object", function () { + [{}, Object.create(NSObject.prototype), function () {}].forEach(function (receiver) { + expect(function () { + NSObject.prototype.isEqual.call(receiver, null); + }).toThrowError(TypeError, /Cannot call method 'isEqual' on a receiver that is not a native object \(class: NSObject, selector: isEqual:\)/); + }); + expect(function () { + Object.create(NSMutableString.prototype).appendString("x"); + }).toThrowError(TypeError, /receiver that is not a native object \(class: NSMutableString, selector: appendString:\)/); + }); + + it("throws a TypeError when a native instance property is read or written on a plain object", function () { + [{}, Object.create(NSOperation.prototype)].forEach(function (receiver) { + expect(function () { + findAccessor(NSObject.prototype, "description").get.call(receiver); + }).toThrowError(TypeError, /receiver that is not a native object \(class: NSObject, selector: description\)/); + expect(function () { + findAccessor(NSOperation.prototype, "name").set.call(receiver, "x"); + }).toThrowError(TypeError, /receiver that is not a native object \(class: NSOperation, selector: setName:\)/); + }); + expect(function () { + return NSOperation.prototype.name; + }).toThrowError(TypeError, /receiver that is not a native object/); + }); + + it("calls a native instance member on a native class constructor as a class-side call", function () { + expect(NSObject.prototype.isEqual.call(NSString, NSString)).toBe(true); + expect(NSObject.prototype.isEqual.call(NSString, NSNumber)).toBe(false); + expect(NSObject.prototype.isEqual.call(new Proxy(NSString, {}), NSString)).toBe(true); + expect(findAccessor(NSObject.prototype, "description").get.call(NSString)).toBe("NSString"); + }); + + it("keeps class methods callable on native, extended and unbound constructors", function () { + expect(NSString.stringWithString("a").toString()).toBe("a"); + var unbound = NSString.stringWithString; + expect(unbound("b").toString()).toBe("b"); + expect(NSString.stringWithString.call({}, "c").toString()).toBe("c"); + + var Extended = NSObject.extend({ answer: function () { return 42; } }); + var extended = Extended.new(); + expect(extended instanceof Extended).toBe(true); + expect(extended.answer()).toBe(42); + expect(extended.isEqual(extended)).toBe(true); + + class ESSubclass extends NSMutableArray {} + expect(ESSubclass.arrayWithArray([1, 2]).count).toBe(2); + }); + + it("leaves the runtime usable after rejecting an invalid receiver", function () { + expect(function () { + NSMutableString.prototype.appendString.call(new interop.Pointer(1), "x"); + }).toThrowError(TypeError); + + var string = NSMutableString.alloc().init(); + string.appendString("ok"); + expect(string.toString()).toBe("ok"); + }); +}); diff --git a/TestRunner/app/tests/ObjCConstructors.js b/TestRunner/app/tests/ObjCConstructors.js index 634824082..5857d9479 100644 --- a/TestRunner/app/tests/ObjCConstructors.js +++ b/TestRunner/app/tests/ObjCConstructors.js @@ -188,4 +188,41 @@ describe("Constructing Objective-C classes with new operator", function () { expect(url).toEqual(jasmine.any(NSURL)); }); }); + + it("throws a TypeError when a native class constructor is called without new", function () { + expect(function () { + NSObject(); + }).toThrowError(TypeError, "Class constructor NSObject cannot be invoked without 'new'"); + expect(function () { + Reflect.apply(NSMutableArray, undefined, []); + }).toThrowError(TypeError, "Class constructor NSMutableArray cannot be invoked without 'new'"); + expect(new NSObject() instanceof NSObject).toBe(true); + }); + + it("throws a TypeError when a protocol is constructed", function () { + expect(function () { + new NSCopying(); + }).toThrowError(TypeError, "Cannot construct NSCopying: it is a protocol"); + }); + + it("keeps TypeScript-compiled subclasses of native classes constructible", function () { + var Sub = (function (_super) { + __extends(Sub, _super); + function Sub() { + return _super !== null && _super.apply(this, arguments) || this; + } + Sub.prototype.answer = function () { return 42; }; + return Sub; + }(NSObject)); + var sub = new Sub(); + expect(sub instanceof NSObject).toBe(true); + expect(sub.answer()).toBe(42); + }); + + it("throws a TypeError when alloc is given arguments", function () { + expect(function () { + NSObject.alloc(1); + }).toThrowError(TypeError, "alloc() takes no arguments"); + expect(NSObject.alloc().init() instanceof NSObject).toBe(true); + }); }); diff --git a/TestRunner/app/tests/ProxyReceiverTests.js b/TestRunner/app/tests/ProxyReceiverTests.js index e39ce66d1..ccedf12af 100644 --- a/TestRunner/app/tests/ProxyReceiverTests.js +++ b/TestRunner/app/tests/ProxyReceiverTests.js @@ -67,6 +67,20 @@ describe(module.id, function () { expect(result.toString()).toBe("x"); }); + it("reads and writes a native instance property through a proxied class constructor as a class-side call", function () { + var descriptor = findAccessor(TNSBaseInterface.prototype, "baseProperty"); + var proxy = new Proxy(TNSBaseInterface, {}); + + TNSClearOutput(); + descriptor.set.call(proxy, 1); + descriptor.get.call(proxy); + var output = TNSGetOutput(); + TNSClearOutput(); + + expect(output).toBe("static setBaseProperty: calledstatic baseProperty called"); + expect(findAccessor(NSObject.prototype, "description").get.call(new Proxy(NSString, {}))).toBe("NSString"); + }); + it("passes a proxied native object as a method argument", function () { var array = NSMutableArray.alloc().init(); var object = NSObject.alloc().init(); @@ -143,6 +157,12 @@ describe(module.id, function () { expect(function () { NSString.stringWithString.call(new Proxy(function () {}, {}), "x"); }).toThrowError(TypeError, /not a native object/); + expect(function () { + findAccessor(NSObject.prototype, "description").get.call(new Proxy(function () {}, {})); + }).toThrowError(TypeError, /not a native object/); + expect(function () { + findAccessor(NSOperation.prototype, "name").set.call(new Proxy(function () {}, {}), "x"); + }).toThrowError(TypeError, /not a native object/); }); it("zeroes a struct return when a callback returns a revoked proxy", function () { diff --git a/TestRunner/app/tests/WrapperLifetimeTests.js b/TestRunner/app/tests/WrapperLifetimeTests.js index 43adf4422..58ff64695 100644 --- a/TestRunner/app/tests/WrapperLifetimeTests.js +++ b/TestRunner/app/tests/WrapperLifetimeTests.js @@ -94,8 +94,8 @@ describe("Wrapper lifetime", function () { } catch (e) { error = e; } - expect(error).not.toBeNull(); - expect(String(error && error.message)).not.toMatch(/native object was released/); + expect(error instanceof TypeError).toBe(true); + expect(String(error && error.message)).toMatch(/receiver that has no native object/); expect(stats().releasedAccesses).toBe(before.releasedAccesses); expect(url.pathname).toBe("/path"); }); diff --git a/TestRunner/app/tests/WrapperLifetimeWeakCollectionsTests.js b/TestRunner/app/tests/WrapperLifetimeWeakCollectionsTests.js index 2231ccbfd..7638a8a20 100644 --- a/TestRunner/app/tests/WrapperLifetimeWeakCollectionsTests.js +++ b/TestRunner/app/tests/WrapperLifetimeWeakCollectionsTests.js @@ -1041,4 +1041,17 @@ describe("Weak collections of native objects", function () { expect(TNSGetOutput()).toBe("only"); TNSClearOutput(); }); + + it("enumerates natively a JS class whose implementation is a Proxy over an object inheriting its iterator", function () { + var Iterated = NSObject.extend(new Proxy(Object.create({ + [Symbol.iterator]: function* () { + yield "proxied"; + } + }), {}), { name: "WrapperLifetimeWeakCollectionsProxiedIterator" }); + var obj = Iterated.alloc().init(); + TNSClearOutput(); + TNSObjCTypes.alloc().init().methodWithNSArray(obj); + expect(TNSGetOutput()).toBe("proxied"); + TNSClearOutput(); + }); }); diff --git a/TestRunner/app/tests/index.js b/TestRunner/app/tests/index.js index 2f47319e6..7be398e09 100644 --- a/TestRunner/app/tests/index.js +++ b/TestRunner/app/tests/index.js @@ -132,6 +132,7 @@ require("./ApiTests"); require("./SuperAliasTests"); require("./ProtocolBindingTests"); require("./ProxyReceiverTests"); +require("./InvalidReceiverTests"); require("./NsRuntimeTests"); require("./NsWorkerThreadsTests"); require("./NsUrlTests"); diff --git a/run_tests.sh b/run_tests.sh index 86febceeb..cfea1e7ce 100755 --- a/run_tests.sh +++ b/run_tests.sh @@ -299,6 +299,8 @@ Simulator options: (default: newest installed) Run options: + -c, --configuration Build configuration: Debug or Release (default: the scheme's, + Debug). Release also builds TestRunner with IsDebug off. -a, --asan Run under AddressSanitizer (-enableAddressSanitizer YES) --wrapper-lifetime [:] Run the suite under a wrapper lifetime mode: the built app's @@ -311,7 +313,8 @@ Run options: -h, --help Show this help Results go to build/tests/ (one simulator can only run one suite at a time), -or build/tests/catalyst with --catalyst. +or build/tests/catalyst with --catalyst. The exit status is non-zero when the build or +XCTest fails, or when the junit report is missing or records a failing spec. EOF } @@ -334,6 +337,7 @@ TEST_FOLDER="" CATALYST=0 WRAPPER_LIFETIME="" NO_XCTEST=0 +CONFIGURATION="" set_sim_mode() { if [ -n "$SIM_MODE" ] && [ "$SIM_MODE" != "$1" ]; then @@ -384,6 +388,8 @@ while [ $# -gt 0 ]; do --wrapper-lifetime|--wrapper-lifetime=*) take_value "--wrapper-lifetime" "$1" "${2:-}" "$has_next"; WRAPPER_LIFETIME="$OPT_VALUE"; shift "$OPT_SHIFT" ;; --no-xctest) NO_XCTEST=1; shift ;; + -c|--configuration|--configuration=*) + take_value "--configuration" "$1" "${2:-}" "$has_next"; CONFIGURATION="$OPT_VALUE"; shift "$OPT_SHIFT" ;; -a|--asan) ASAN=1; shift ;; -t|--temp-folder) TEMP_FOLDER=1; shift ;; -h|--help) usage; exit 0 ;; @@ -428,10 +434,15 @@ if { [ -n "$SIM_DEVICE_TYPE" ] || [ -n "$SIM_RUNTIME" ]; } && [ "$CREATES_SIM" - die_usage "--device-type and --runtime only apply when a simulator may be created." fi if [ -n "$SIM_MODE" ] && [ "$SIM_MODE" != "temp-sim" ] && [ "$SIM_MODE" != "keep-sim" ]; then - if [ "$ASAN" -eq 1 ] || [ "$TEMP_FOLDER" -eq 1 ] || [ -n "$WRAPPER_LIFETIME" ]; then - die_usage "--asan, --temp-folder and --wrapper-lifetime do not apply to --$SIM_MODE." + if [ "$ASAN" -eq 1 ] || [ "$TEMP_FOLDER" -eq 1 ] || [ -n "$WRAPPER_LIFETIME" ] \ + || [ -n "$CONFIGURATION" ]; then + die_usage "--asan, --temp-folder, --wrapper-lifetime and --configuration do not apply to --$SIM_MODE." fi fi +case "$CONFIGURATION" in + ""|Debug|Release) ;; + *) die_usage "--configuration: unknown configuration '$CONFIGURATION' (Debug or Release)." ;; +esac if [ -n "$WRAPPER_LIFETIME" ]; then WL_MODE="${WRAPPER_LIFETIME%%:*}" WL_SCOPE="extended" @@ -548,7 +559,7 @@ run_catalyst_directly() { local build_args=(-project "$SCRIPT_DIR/v8ios.xcodeproj" -scheme TestRunner -destination "$DESTINATION") xcodebuild "${build_args[@]}" "${XCODEBUILD_ARGS[@]}" build | xcpretty || return 1 local app - app=$(xcodebuild "${build_args[@]}" -showBuildSettings 2>/dev/null | + app=$(xcodebuild "${build_args[@]}" "${XCODEBUILD_ARGS[@]}" -showBuildSettings 2>/dev/null | awk -F' = ' '/^Build settings for .* target / { mine = ($0 ~ / target TestRunner:$/) } mine && $1 ~ /^ *CODESIGNING_FOLDER_PATH$/ { print $2; exit }') if [ ! -x "$app/Contents/MacOS/TestRunner" ]; then @@ -665,6 +676,10 @@ fi echo "Test folder: $TEST_FOLDER" XCODEBUILD_ARGS=() +if [ -n "$CONFIGURATION" ]; then + echo "Configuration: $CONFIGURATION" + XCODEBUILD_ARGS+=(-configuration "$CONFIGURATION") +fi if [ "$ASAN" -eq 1 ]; then echo "AddressSanitizer: enabled" XCODEBUILD_ARGS+=(-enableAddressSanitizer YES) @@ -692,18 +707,37 @@ else echo "Tests failed with exit code $TEST_EXIT" fi +fi + +# XCTest passes once the app delivers its junit report, whatever the report +# says, so failing specs only show up here. +if [ -d "$TEST_FOLDER/test_results.xcresult" ]; then if command -v xcparse &>/dev/null; then xcparse attachments "$TEST_FOLDER/test_results.xcresult" "$TEST_FOLDER/test-out" - find "$TEST_FOLDER/test-out" -name "*junit*.xml" -maxdepth 1 -print0 | xargs -n 1 -0 npx junit-cli-report-viewer - find "$TEST_FOLDER/test-out" -name "*junit*.xml" -maxdepth 1 -print0 | xargs -n 1 -0 npx verify-junit-xml + else + "$SCRIPT_DIR/scripts/export-test-attachments.sh" --result "$TEST_FOLDER/test_results.xcresult" \ + --output "$TEST_FOLDER/test-out" >/dev/null fi fi +JUNIT_REPORTS=() +while IFS= read -r -d '' report; do + JUNIT_REPORTS+=("$report") +done < <(find "$TEST_FOLDER/test-out" -maxdepth 1 -name "*junit*.xml" -print0 2>/dev/null) +if [ "${#JUNIT_REPORTS[@]}" -eq 0 ]; then + echo "No junit report found in $TEST_FOLDER/test-out" + [ $TEST_EXIT -ne 0 ] || TEST_EXIT=1 +else + for report in "${JUNIT_REPORTS[@]}"; do + npx junit-cli-report-viewer "$report" + done + for report in "${JUNIT_REPORTS[@]}"; do + if ! npx verify-junit-xml "$report"; then + [ $TEST_EXIT -ne 0 ] || TEST_EXIT=1 + fi + done +fi if [ -n "$WRAPPER_LIFETIME" ]; then - if ! ls "$TEST_FOLDER"/test-out/*junit*.xml >/dev/null 2>&1 && [ -d "$TEST_FOLDER/test_results.xcresult" ]; then - "$SCRIPT_DIR/scripts/export-test-attachments.sh" --result "$TEST_FOLDER/test_results.xcresult" \ - --output "$TEST_FOLDER/test-out" >/dev/null - fi if ! "$SCRIPT_DIR/scripts/check-wrapper-lifetime-report.sh" --reports "$TEST_FOLDER/test-out" \ --expect "$WL_MODE/$WL_SCOPE"; then [ $TEST_EXIT -ne 0 ] || TEST_EXIT=1 diff --git a/v8ios.xcodeproj/project.pbxproj b/v8ios.xcodeproj/project.pbxproj index 22c6a2431..0c047568a 100644 --- a/v8ios.xcodeproj/project.pbxproj +++ b/v8ios.xcodeproj/project.pbxproj @@ -354,6 +354,7 @@ A1EA4B0E0000000000000011 /* NativeScriptLeakProbe.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A1EA4B0E0000000000000001 /* NativeScriptLeakProbe.framework */; platformFilters = (ios, maccatalyst, xros, ); }; A1EA4B0E0000000000000012 /* NativeScriptLeakProbe.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = A1EA4B0E0000000000000001 /* NativeScriptLeakProbe.framework */; platformFilters = (ios, maccatalyst, xros, ); settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; A1EA4B0E0000000000000014 /* LeakProbeSPI.h in Headers */ = {isa = PBXBuildFile; fileRef = A1EA4B0E0000000000000013 /* LeakProbeSPI.h */; }; + 4426A118ED82F704A1361CE0 /* Checks.h in Headers */ = {isa = PBXBuildFile; fileRef = A139A5040624EECB430D25A8 /* Checks.h */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -908,6 +909,7 @@ A1EA4B0E0000000000000002 /* NativeScriptLeakProbe.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = NativeScriptLeakProbe.mm; sourceTree = ""; }; A1EA4B0E0000000000000003 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; A1EA4B0E0000000000000013 /* LeakProbeSPI.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LeakProbeSPI.h; sourceTree = ""; }; + A139A5040624EECB430D25A8 /* Checks.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Checks.h; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -1570,6 +1572,7 @@ CB7C1CED65B5F547091F0B28 /* WrapperLifetimeCanary.mm */, 9E3712759A1FB55EC4BA390B /* LeakProbe.h */, A1EA4B0E0000000000000013 /* LeakProbeSPI.h */, + A139A5040624EECB430D25A8 /* Checks.h */, 8ECE36189A0C784BBCDD3B55 /* LeakProbe.mm */, C20AB5E526E1015200E2B41D /* OneByteStringResource.h */, C20AB5E426E1015200E2B41D /* OneByteStringResource.cpp */, @@ -1741,6 +1744,7 @@ A0636BA435F52099D6955AC5 /* WrapperLifetimeCanary.h in Headers */, ADFC6948A446C61502AEE47F /* LeakProbe.h in Headers */, A1EA4B0E0000000000000014 /* LeakProbeSPI.h in Headers */, + 4426A118ED82F704A1361CE0 /* Checks.h in Headers */, 6573B9E7291FE2A700B0ED7C /* jsi.h in Headers */, 6573B9E2291FE2A700B0ED7C /* jsi-inl.h in Headers */, C2D21601248AAAD900EDC646 /* Constants.h in Headers */,