From 904ec71c8cc7b988c16003152e02a721e861b147 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 22:14:08 -0300 Subject: [PATCH 01/12] fix(runtime): throw a TypeError for invalid method receivers in every build A native method or accessor called on a receiver with no native object, or on a wrapper that is not an Objective-C instance (an interop.Pointer, a Reference), threw a JS error only when RuntimeConfig.IsDebug was set and hit tns::Assert otherwise, so the same JS aborted a Release app. Both cases now throw a catchable TypeError naming the method, class and selector. --- NativeScript/runtime/ArgConverter.mm | 44 ++++++-------- TestRunner/app/tests/InvalidReceiverTests.js | 60 ++++++++++++++++++++ TestRunner/app/tests/WrapperLifetimeTests.js | 4 +- TestRunner/app/tests/index.js | 1 + 4 files changed, 79 insertions(+), 30 deletions(-) create mode 100644 TestRunner/app/tests/InvalidReceiverTests.js diff --git a/NativeScript/runtime/ArgConverter.mm b/NativeScript/runtime/ArgConverter.mm index d9490c78..c3f9fa2a 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,7 @@ 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, "a receiver that has no native object"); } if (wrapper->Type() == WrapperType::ObjCAllocObject) { @@ -183,18 +180,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/TestRunner/app/tests/InvalidReceiverTests.js b/TestRunner/app/tests/InvalidReceiverTests.js new file mode 100644 index 00000000..e801d0b9 --- /dev/null +++ b/TestRunner/app/tests/InvalidReceiverTests.js @@ -0,0 +1,60 @@ +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("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/WrapperLifetimeTests.js b/TestRunner/app/tests/WrapperLifetimeTests.js index 43adf442..58ff6469 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/index.js b/TestRunner/app/tests/index.js index 2f47319e..7be398e0 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"); From 698000172a21cf336e9dd4e8ed4b5157f9291ea6 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 22:14:08 -0300 Subject: [PATCH 02/12] fix(test): fail run_tests.sh on failing specs and add --configuration XCTest passes once the app delivers its junit report, whatever the report says, and the script discarded verify-junit-xml's status, so a run with failing specs exited 0. The script now exits non-zero when the report is missing or records a failure, exporting the attachments without xcparse when it is not installed. -c/--configuration Debug|Release builds the suite in that configuration; a Release TestRunner also starts the runtime with IsDebug off. --- run_tests.sh | 54 ++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 44 insertions(+), 10 deletions(-) diff --git a/run_tests.sh b/run_tests.sh index 86febcee..cfea1e7c 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 From 63c947b8e1bf32363eb2d07d378e886d41983ab5 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 23:02:21 -0300 Subject: [PATCH 03/12] fix(runtime): log and abort from tns::Assert the same way in every build Release builds ran a bare assert(condition): no reason, no native or JS stack, and a check that NDEBUG would compile out. tns::Assert now has one path for every build: it logs the failure, the reason, the native backtrace and, when the isolate is entered on the calling thread, the JS stack, then calls abort(). --- NativeScript/runtime/Helpers.mm | 36 ++++++++++++++------------------- 1 file changed, 15 insertions(+), 21 deletions(-) diff --git a/NativeScript/runtime/Helpers.mm b/NativeScript/runtime/Helpers.mm index 76ce2be2..53864b35 100644 --- a/NativeScript/runtime/Helpers.mm +++ b/NativeScript/runtime/Helpers.mm @@ -1167,12 +1167,7 @@ throw NativeScriptException( } void tns::Assert(bool condition, Isolate* isolate, std::string const& reason) { - if (!RuntimeConfig.IsDebug) { - assert(condition); - return; - } - - if (condition) { + if (condition) [[likely]] { return; } @@ -1183,25 +1178,24 @@ throw NativeScriptException( } } - if (isolate == nullptr) { - Log(@"====== Assertion failed ======"); - if (!reason.empty()) { - Log(@"Reason: %s", reason.c_str()); - } - Log(@"Native stack trace:"); - LogBacktrace(); - assert(false); - return; - } - Log(@"====== Assertion failed ======"); + if (!reason.empty()) { + Log(@"Reason: %s", reason.c_str()); + } Log(@"Native stack trace:"); LogBacktrace(); - Log(@"JavaScript stack trace:"); - std::string stack = tns::GetStackTrace(isolate); - Log(@"%s", stack.c_str()); - assert(false); + // Reading the JS stack needs the isolate entered on this thread. + if (isolate != nullptr && isolate == v8::Isolate::TryGetCurrent()) { + HandleScope handleScope(isolate); + Log(@"JavaScript stack trace:"); + std::string stack = tns::GetStackTrace(isolate); + Log(@"%s", stack.c_str()); + } + + // abort(), not assert(): this must stop the process whether or not NDEBUG + // is defined. + abort(); } void tns::StopExecutionAndLogStackTrace(v8::Isolate* isolate) { Assert(false, isolate); } From 946073b42155134977aac45e051b0a86bca2b72a Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 23:02:48 -0300 Subject: [PATCH 04/12] refactor(runtime): remove the logRuntimeDetail write-value checks and traces The logRuntimeDetail app config key enabled, only in a runtime compiled with DEBUG (never the shipped framework), a trace of every method call and object write plus write-value checks that aborted on conversions every other build performs. Remove the key's readers, the checks and their helpers, and the now unused tns::StopExecutionAndLogStackTrace. --- NativeScript/runtime/Helpers.h | 2 - NativeScript/runtime/Helpers.mm | 2 - NativeScript/runtime/Interop.h | 3 - NativeScript/runtime/Interop.mm | 74 ------------------------- NativeScript/runtime/MetadataBuilder.mm | 15 ----- 5 files changed, 96 deletions(-) diff --git a/NativeScript/runtime/Helpers.h b/NativeScript/runtime/Helpers.h index c1f78c4c..7da20394 100644 --- a/NativeScript/runtime/Helpers.h +++ b/NativeScript/runtime/Helpers.h @@ -590,8 +590,6 @@ bool LiveSync(v8::Isolate* isolate); void Assert(bool condition, v8::Isolate* isolate = nullptr, std::string const& reason = std::string()); -void StopExecutionAndLogStackTrace(v8::Isolate* isolate); - // Helpers from Node inline v8::Local OneByteString(v8::Isolate* isolate, const char* data, int length) { return v8::String::NewFromOneByte(isolate, reinterpret_cast(data), diff --git a/NativeScript/runtime/Helpers.mm b/NativeScript/runtime/Helpers.mm index 53864b35..5af758fc 100644 --- a/NativeScript/runtime/Helpers.mm +++ b/NativeScript/runtime/Helpers.mm @@ -1198,8 +1198,6 @@ throw NativeScriptException( abort(); } -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 62b29479..d7b1ccc2 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 6edb223c..b3702889 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.mm b/NativeScript/runtime/MetadataBuilder.mm index e2de3e84..36f2835f 100644 --- a/NativeScript/runtime/MetadataBuilder.mm +++ b/NativeScript/runtime/MetadataBuilder.mm @@ -1733,21 +1733,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) { From 2345cd2012857bed662518f6bc7a515ed8191ae4 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 23:09:22 -0300 Subject: [PATCH 05/12] fix(runtime): reject non-native receivers of native instance members An instance method whose `this` had no internal fields was sent to the class instead: NSObject.prototype.isEqual.call({}, x) ran +[NSObject isEqual:], and an instance property getter returned undefined. Instance methods now have their own callback, and they and instance property accessors share one rule: a native class constructor receiver makes a class-side call, any other receiver must be a native object, or the call throws "Cannot call method ... on a receiver that is not a native object". Class methods are unchanged. Reading a native instance property on a prototype object now throws too. --- NativeScript/runtime/ArgConverter.mm | 5 +- NativeScript/runtime/MetadataBuilder.h | 2 + NativeScript/runtime/MetadataBuilder.mm | 54 ++++++++++++++++---- TestRunner/app/tests/InvalidReceiverTests.js | 48 +++++++++++++++++ 4 files changed, 99 insertions(+), 10 deletions(-) diff --git a/NativeScript/runtime/ArgConverter.mm b/NativeScript/runtime/ArgConverter.mm index c3f9fa2a..5e2d5e99 100644 --- a/NativeScript/runtime/ArgConverter.mm +++ b/NativeScript/runtime/ArgConverter.mm @@ -165,7 +165,10 @@ throw NativeScriptException(isolate, v8::Exception::TypeError(tns::ToV8String(is tns::ThrowReleasedObject(isolate, releasedReason, std::string("method '") + jsNameStr + "' receiver"); } - ThrowInvalidReceiver(isolate, klass, meta, "a receiver that has no native object"); + 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) { diff --git a/NativeScript/runtime/MetadataBuilder.h b/NativeScript/runtime/MetadataBuilder.h index 992a4abf..4fb7562f 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 36f2835f..2d581b74 100644 --- a/NativeScript/runtime/MetadataBuilder.mm +++ b/NativeScript/runtime/MetadataBuilder.mm @@ -78,6 +78,22 @@ 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(); +} + // 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 +1231,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()); @@ -1499,6 +1515,27 @@ 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*>( @@ -1509,10 +1546,6 @@ void CollectInstanceMemberNames(const BaseClassMeta* meta, Class klass, bool own return; } - if (receiver->InternalFieldCount() < 1) { - return; - } - if (!item->meta_->hasGetter()) { Local error = Exception::Error(tns::ToV8String(isolate, "Property is not readable.")); isolate->ThrowException(error); @@ -1520,9 +1553,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); } @@ -1548,9 +1583,10 @@ void CollectInstanceMemberNames(const BaseClassMeta* meta, Class klass, bool own 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, diff --git a/TestRunner/app/tests/InvalidReceiverTests.js b/TestRunner/app/tests/InvalidReceiverTests.js index e801d0b9..36191bf1 100644 --- a/TestRunner/app/tests/InvalidReceiverTests.js +++ b/TestRunner/app/tests/InvalidReceiverTests.js @@ -48,6 +48,54 @@ describe(module.id, function () { }); }); + 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"); From a219942c847d77457a9463ab23b027eacd120bc5 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 23:47:27 -0300 Subject: [PATCH 06/12] feat(runtime): add tns::Fatal and NS_CHECK/NS_DCHECK/NS_UNREACHABLE Checks.h holds the runtime's error-handling policy and one fatal path, 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. - NS_CHECK(cond, message): on in every build. - NS_DCHECK(cond) / NS_DCHECK_MSG(cond, message): on while NS_DCHECK_IS_ON, which defaults to 1 in DEBUG and AddressSanitizer builds and 0 otherwise. When off, the condition is compiled but never evaluated. - NS_UNREACHABLE(message). tns::Assert keeps its call signature and forwards to tns::Fatal with its caller's file and line. Node-API's v8impl::OnFatalError reports through tns::Fatal too. --- NativeScript/napi/NapiEnv.mm | 6 +-- NativeScript/runtime/Checks.h | 93 +++++++++++++++++++++++++++++++++ NativeScript/runtime/Helpers.h | 5 +- NativeScript/runtime/Helpers.mm | 38 ++++++++------ v8ios.xcodeproj/project.pbxproj | 4 ++ 5 files changed, 126 insertions(+), 20 deletions(-) create mode 100644 NativeScript/runtime/Checks.h diff --git a/NativeScript/napi/NapiEnv.mm b/NativeScript/napi/NapiEnv.mm index 79ec0c96..d04a6596 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/Checks.h b/NativeScript/runtime/Checks.h new file mode 100644 index 00000000..2cd6a015 --- /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/Helpers.h b/NativeScript/runtime/Helpers.h index 7da20394..bb6a7da2 100644 --- a/NativeScript/runtime/Helpers.h +++ b/NativeScript/runtime/Helpers.h @@ -587,8 +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()); + 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 5af758fc..d1a215ac 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,27 +1167,23 @@ throw NativeScriptException( return true; } -void tns::Assert(bool condition, Isolate* isolate, std::string const& reason) { - if (condition) [[likely]] { - return; - } - - if (isolate == nullptr) { - Runtime* runtime = Runtime::GetCurrentRuntime(); - if (runtime != nullptr) { - isolate = runtime->GetIsolate(); - } +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; - Log(@"====== Assertion failed ======"); - if (!reason.empty()) { - Log(@"Reason: %s", reason.c_str()); - } + Log(@"====== Fatal error ======"); + Log(@"Location: %s", location != nullptr ? location : ""); + Log(@"Message: %s", message.c_str()); Log(@"Native stack trace:"); LogBacktrace(); // Reading the JS stack needs the isolate entered on this thread. - if (isolate != nullptr && isolate == v8::Isolate::TryGetCurrent()) { + if (Isolate* isolate = v8::Isolate::TryGetCurrent()) { HandleScope handleScope(isolate); Log(@"JavaScript stack trace:"); std::string stack = tns::GetStackTrace(isolate); @@ -1198,6 +1195,17 @@ throw NativeScriptException( abort(); } +void tns::Assert(bool condition, Isolate* isolate, std::string const& reason, const char* file, + int line) { + (void)isolate; + if (condition) [[likely]] { + return; + } + std::string location = + std::string(file != nullptr ? file : "") + ":" + std::to_string(line); + tns::Fatal(location.c_str(), reason.empty() ? "assertion failed" : reason); +} + namespace tns { Local NewFunctionTemplate(v8::Isolate* isolate, v8::FunctionCallback callback, Local data, diff --git a/v8ios.xcodeproj/project.pbxproj b/v8ios.xcodeproj/project.pbxproj index 22c6a243..0c047568 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 */, From 9f8f6fba2c9671fdc47e8d8082f9ec1c1bbcadcc Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Mon, 23 Nov 2026 00:26:12 -0300 Subject: [PATCH 07/12] fix(runtime): throw instead of aborting for bad native constructor and alloc calls A native class constructor called without new (NSObject(), Reflect.apply) and alloc() called with arguments hit tns::Assert. They now throw a TypeError. Constructing a protocol (new NSCopying()) throws a TypeError, and constructing a class that metadata lists but the runtime does not load throws an Error, instead of reaching ConstructObject without a class. --- NativeScript/runtime/MetadataBuilder.mm | 29 ++++++++++++++++--- TestRunner/app/tests/ObjCConstructors.js | 37 ++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 4 deletions(-) diff --git a/NativeScript/runtime/MetadataBuilder.mm b/NativeScript/runtime/MetadataBuilder.mm index 2d581b74..fb8e2567 100644 --- a/NativeScript/runtime/MetadataBuilder.mm +++ b/NativeScript/runtime/MetadataBuilder.mm @@ -94,6 +94,10 @@ bool ResolveProxyReceiver(Isolate* isolate, Local& receiver, const char* 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; @@ -1437,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) { @@ -1453,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(); diff --git a/TestRunner/app/tests/ObjCConstructors.js b/TestRunner/app/tests/ObjCConstructors.js index 63482408..5857d947 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); + }); }); From 882a5e68fe2e38e21ddabbb970f28023607eef05 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Mon, 23 Nov 2026 00:50:40 -0300 Subject: [PATCH 08/12] fix(runtime): throw instead of aborting for invalid extend() and __extends arguments ClassBuilder::ExtendCallback asserted its arguments, so NSObject.extend() with no or a non-object first argument, or an unbound call, aborted the process. It now throws a TypeError for a receiver that is not a function, a missing or non-object first argument, and a second argument that is neither an object nor null/undefined. An exception thrown while reading the options' name propagates to JS, and an implementation object whose prototype cannot be set (for example a frozen one) throws a TypeError instead of aborting. The native __extends callback hands any base that is not a native class (including other native wrapper types) to the base __extends function, propagates that function's exceptions instead of crashing on ToLocalChecked, and throws a TypeError when the derived side is not a constructor function. --- NativeScript/runtime/ClassBuilder.mm | 55 +++++++++++++---- .../app/tests/Inheritance/InheritanceTests.js | 60 +++++++++++++++++++ 2 files changed, 102 insertions(+), 13 deletions(-) diff --git a/NativeScript/runtime/ClassBuilder.mm b/NativeScript/runtime/ClassBuilder.mm index a09e67c1..311615e0 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); } @@ -125,8 +145,12 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { 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); + // A refused change comes back as Nothing with no exception pending. + 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 +238,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 +254,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/TestRunner/app/tests/Inheritance/InheritanceTests.js b/TestRunner/app/tests/Inheritance/InheritanceTests.js index 2e45b515..6b7b82ae 100644 --- a/TestRunner/app/tests/Inheritance/InheritanceTests.js +++ b/TestRunner/app/tests/Inheritance/InheritanceTests.js @@ -2093,4 +2093,64 @@ 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("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"); + }); }); From 9af3945809219e5c6a93460bdbc6fc6ac36aede9 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Mon, 23 Nov 2026 00:50:40 -0300 Subject: [PATCH 09/12] fix(runtime): accept a Proxy around a native class as a native accessor receiver Native property getters and setters rejected new Proxy(NSObject, {}) before the class-side normalization, while the constructor itself and native instance methods accept it as a class-side call. Both accessor paths now let ResolveProxyReceiver admit a class target. Revoked proxies and proxies around non-native objects still throw a TypeError. --- NativeScript/runtime/MetadataBuilder.mm | 4 ++-- TestRunner/app/tests/ProxyReceiverTests.js | 20 ++++++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/NativeScript/runtime/MetadataBuilder.mm b/NativeScript/runtime/MetadataBuilder.mm index fb8e2567..02470cf4 100644 --- a/NativeScript/runtime/MetadataBuilder.mm +++ b/NativeScript/runtime/MetadataBuilder.mm @@ -1563,7 +1563,7 @@ throw NativeScriptException(std::string("Cannot construct ") + meta->jsName() + info.Data().As()->Value(v8::kExternalPointerTypeTagDefault)); Local receiver = info.This(); if (!ResolveProxyReceiver(isolate, receiver, "read native property", item->meta_->jsName(), - false)) { + true)) { return; } @@ -1600,7 +1600,7 @@ throw NativeScriptException(std::string("Cannot construct ") + meta->jsName() + } if (!ResolveProxyReceiver(isolate, receiver, "set native property", item->meta_->jsName(), - false)) { + true)) { return; } V8SimpleValueArgs args(value); diff --git a/TestRunner/app/tests/ProxyReceiverTests.js b/TestRunner/app/tests/ProxyReceiverTests.js index e39ce66d..ccedf12a 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 () { From a385b5ba9678f7ca0e9383e6766444a8e452ed48 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Mon, 23 Nov 2026 02:22:46 -0300 Subject: [PATCH 10/12] fix(runtime): reject a non-extensible extend() implementation before registering its class extend() set the implementation object's prototype only after GetExtendedClass had registered the native class, so a frozen implementation threw with the class already registered under the requested name: a corrected retry got a suffixed name while native lookup of the requested one found the failed class. The prototype change is now probed before registration and undone at once, since member discovery reads through the original prototype; the later assignment keeps its check. --- NativeScript/runtime/ClassBuilder.mm | 29 +++++++++++++------ .../app/tests/Inheritance/InheritanceTests.js | 8 +++++ 2 files changed, 28 insertions(+), 9 deletions(-) diff --git a/NativeScript/runtime/ClassBuilder.mm b/NativeScript/runtime/ClassBuilder.mm index 311615e0..d3f12027 100644 --- a/NativeScript/runtime/ClassBuilder.mm +++ b/NativeScript/runtime/ClassBuilder.mm @@ -108,6 +108,26 @@ void ThrowTypeError(Isolate* isolate, const std::string& message) { 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. + Local originalProto = implementationObject->GetPrototype(); + if (!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); @@ -123,9 +143,6 @@ void ThrowTypeError(Isolate* isolate, const std::string& message) { 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); @@ -140,12 +157,6 @@ void ThrowTypeError(Isolate* isolate, const std::string& message) { tns::Assert(false, isolate); } - Local baseProto; - bool success = - baseCtorFunc->Get(context, tns::ToV8String(isolate, "prototype")).ToLocal(&baseProto); - tns::Assert(success, isolate); - - // A refused change comes back as Nothing with no exception pending. if (!implementationObject->SetPrototype(context, baseProto).FromMaybe(false)) { ThrowTypeError(isolate, baseClassName + ".extend() could not set the prototype of its first argument, " diff --git a/TestRunner/app/tests/Inheritance/InheritanceTests.js b/TestRunner/app/tests/Inheritance/InheritanceTests.js index 6b7b82ae..90701113 100644 --- a/TestRunner/app/tests/Inheritance/InheritanceTests.js +++ b/TestRunner/app/tests/Inheritance/InheritanceTests.js @@ -2113,6 +2113,14 @@ describe(module.id, function () { }).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({}, { From 9e358aed7652ccd4aea1dfbc6505044e2bdde5de Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Mon, 23 Nov 2026 02:22:46 -0300 Subject: [PATCH 11/12] ci: skip the Catalyst job's report extraction when run_tests.sh already did it run_tests.sh now extracts the junit report from the result bundle itself, and a second export-test-attachments.sh run into the same folder fails on its existing manifest.json. --- .github/workflows/pull_request.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index 3f4941b4..6474d1e2 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 From 312ebc1a2e4f658779865325a1607dad8926d8c4 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Mon, 23 Nov 2026 02:50:37 -0300 Subject: [PATCH 12/12] fix(runtime): keep a Proxy implementation's prototype through the extend() probe v8::Object::GetPrototype() does not reach a Proxy's target while SetPrototype() forwards to it, so restoring after the probe dropped the target's prototype, and with it an inherited Symbol.iterator, before member discovery. A Proxy implementation skips the early probe; the later prototype assignment still rejects a frozen one. --- NativeScript/runtime/ClassBuilder.mm | 8 +++++--- .../tests/WrapperLifetimeWeakCollectionsTests.js | 13 +++++++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/NativeScript/runtime/ClassBuilder.mm b/NativeScript/runtime/ClassBuilder.mm index d3f12027..91c066b0 100644 --- a/NativeScript/runtime/ClassBuilder.mm +++ b/NativeScript/runtime/ClassBuilder.mm @@ -118,10 +118,12 @@ void ThrowTypeError(Isolate* isolate, const std::string& message) { // 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. + // 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->SetPrototype(context, baseProto).FromMaybe(false) || - !implementationObject->SetPrototype(context, originalProto).FromMaybe(false)) { + 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"); diff --git a/TestRunner/app/tests/WrapperLifetimeWeakCollectionsTests.js b/TestRunner/app/tests/WrapperLifetimeWeakCollectionsTests.js index 2231ccbf..7638a8a2 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(); + }); });