From c292c09e66173d8de02383b0ece216a4cf50b11c Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 15 Nov 2026 17:02:23 -0300 Subject: [PATCH 1/8] fix(runtime): register JS property accessors with their real type encoding Accessors a JS class implements for a native property, on an .extend() or __extends subclass or replaced on a native class's prototype, were added to the ObjC class as "@@:" (getter) and "v@:@" (setter) whatever the property's type, although their ffi closures follow the property's metadata. Anything that reads the method's type encoding then disagreed with the IMP: KVC took an NSUInteger, BOOL or double getter result for an object and crashed in objc_retain/isKindOfClass (valueForKey:@"hash" on a class with a JS `get hash()`), boxed object pointers were handed to scalar and struct setters by setValue:forKey:, and method signatures reported "@". The accessors now get the encoding JS-implemented methods already use, built by GetTypeEncoding from the accessor's own metadata. Function pointers encode as "^?", as the compiler does. Types the runtime cannot encode (vectors, anonymous records) keep the object encoding instead of asserting, through an optional out flag the method paths do not pass. --- NativeScript/runtime/ClassBuilder.h | 12 +- NativeScript/runtime/ClassBuilder.mm | 41 +++- NativeScript/runtime/MetadataBuilder.mm | 16 +- TestFixtures/Api/TNSApi.h | 37 +++ TestFixtures/Api/TNSApi.m | 22 ++ .../app/tests/JSAccessorEncodingTests.js | 228 ++++++++++++++++++ TestRunner/app/tests/index.js | 1 + 7 files changed, 337 insertions(+), 20 deletions(-) create mode 100644 TestRunner/app/tests/JSAccessorEncodingTests.js diff --git a/NativeScript/runtime/ClassBuilder.h b/NativeScript/runtime/ClassBuilder.h index d6a353279..0bc3c1362 100644 --- a/NativeScript/runtime/ClassBuilder.h +++ b/NativeScript/runtime/ClassBuilder.h @@ -35,8 +35,15 @@ class ClassBuilder { v8::Local context); static void RegisterNativeTypeScriptExtendsFunction( v8::Local context); + // Clears `*encodable` instead of asserting when a type has no compiler + // encoding the runtime can reproduce. static std::string GetTypeEncoding(const TypeEncoding* typeEncoding, - int argsCount); + int argsCount, bool* encodable = nullptr); + // A JS-implemented property accessor's encoding, or `fallback` when its + // types have no compiler encoding the runtime can reproduce. + static std::string GetAccessorTypeEncoding(const TypeEncoding* typeEncoding, + int argsCount, + const char* fallback); // `klass` or its nearest superclass not defined from JS. static Class FindNativeClass(Class klass); // The implementation of `method` from FindNativeClass(klass). @@ -73,7 +80,8 @@ class ClassBuilder { v8::Local implementationObject, v8::Local getter, v8::Local setter); - static std::string GetTypeEncoding(const TypeEncoding* typeEncoding); + static std::string GetTypeEncoding(const TypeEncoding* typeEncoding, + bool* encodable); static BinaryTypeEncodingType GetTypeEncodingType(v8::Isolate* isolate, v8::Local value); diff --git a/NativeScript/runtime/ClassBuilder.mm b/NativeScript/runtime/ClassBuilder.mm index 47c77ea43..a4a1abc45 100644 --- a/NativeScript/runtime/ClassBuilder.mm +++ b/NativeScript/runtime/ClassBuilder.mm @@ -435,7 +435,7 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { implementationObject); } -std::string ClassBuilder::GetTypeEncoding(const TypeEncoding* typeEncoding) { +std::string ClassBuilder::GetTypeEncoding(const TypeEncoding* typeEncoding, bool* encodable) { BinaryTypeEncodingType type = typeEncoding->type; switch (type) { case BinaryTypeEncodingType::VoidEncoding: { @@ -505,6 +505,10 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { case BinaryTypeEncodingType::StructDeclarationReference: { const char* structName = typeEncoding->details.declarationReference.name.valuePtr(); const Meta* meta = ArgConverter::GetMeta(structName); + if (encodable != nullptr && (meta == nullptr || meta->type() != MetaType::Struct)) { + *encodable = false; + return ""; + } tns::Assert(meta != nullptr && meta->type() == MetaType::Struct); const StructMeta* structMeta = static_cast(meta); const TypeEncoding* fieldEncoding = structMeta->fieldsEncodings()->first(); @@ -512,7 +516,7 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { std::stringstream ss; ss << "{" << structName << "="; for (int i = 0; i < structMeta->fieldsCount(); i++) { - ss << GetTypeEncoding(fieldEncoding); + ss << GetTypeEncoding(fieldEncoding, encodable); fieldEncoding = fieldEncoding->next(); } ss << "}"; @@ -522,14 +526,14 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { std::stringstream ss; ss << "^"; const TypeEncoding* innerType = typeEncoding->details.pointer.getInnerType(); - ss << GetTypeEncoding(innerType); + ss << GetTypeEncoding(innerType, encodable); return ss.str(); } case BinaryTypeEncodingType::ConstantArrayEncoding: { const TypeEncoding* innerType = typeEncoding->details.constantArray.getInnerType(); std::stringstream ss; ss << "["; - ss << typeEncoding->details.constantArray.size << GetTypeEncoding(innerType); + ss << typeEncoding->details.constantArray.size << GetTypeEncoding(innerType, encodable); ss << "]"; return ss.str(); } @@ -537,9 +541,12 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { const TypeEncoding* innerType = typeEncoding->details.incompleteArray.getInnerType(); std::stringstream ss; ss << "^"; - ss << GetTypeEncoding(innerType); + ss << GetTypeEncoding(innerType, encodable); return ss.str(); } + case BinaryTypeEncodingType::FunctionPointerEncoding: { + return "^?"; + } case BinaryTypeEncodingType::ProtocolEncoding: case BinaryTypeEncodingType::InterfaceDeclarationReference: case BinaryTypeEncodingType::InstanceTypeEncoding: @@ -549,24 +556,36 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { default: // TODO: Handle the other possible types + if (encodable != nullptr) { + *encodable = false; + return ""; + } tns::Assert(false); return ""; } } -std::string ClassBuilder::GetTypeEncoding(const TypeEncoding* typeEncoding, int argsCount) { +std::string ClassBuilder::GetTypeEncoding(const TypeEncoding* typeEncoding, int argsCount, + bool* encodable) { std::stringstream compilerEncoding; - compilerEncoding << GetTypeEncoding(typeEncoding); + compilerEncoding << GetTypeEncoding(typeEncoding, encodable); compilerEncoding << "@:"; // id self, SEL _cmd for (int i = 0; i < argsCount; i++) { typeEncoding = typeEncoding->next(); - compilerEncoding << GetTypeEncoding(typeEncoding); + compilerEncoding << GetTypeEncoding(typeEncoding, encodable); } return compilerEncoding.str(); } +std::string ClassBuilder::GetAccessorTypeEncoding(const TypeEncoding* typeEncoding, int argsCount, + const char* fallback) { + bool encodable = true; + std::string encoding = GetTypeEncoding(typeEncoding, argsCount, &encodable); + return encodable ? encoding : fallback; +} + BinaryTypeEncodingType ClassBuilder::GetTypeEncodingType(Isolate* isolate, Local value) { if (BaseDataWrapper* wrapper = tns::GetValue(isolate, value)) { if (wrapper->Type() == WrapperType::ObjCClass) { @@ -950,8 +969,9 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { }; const TypeEncoding* typeEncoding = propertyMeta->getter()->encodings()->first(); IMP impGetter = Interop::CreateMethod(2, 0, typeEncoding, getterCallback, userData); + std::string types = GetAccessorTypeEncoding(typeEncoding, 0, "@@:"); - class_addMethod(extendedClass, propertyMeta->getter()->selector(), impGetter, "@@:"); + class_addMethod(extendedClass, propertyMeta->getter()->selector(), impGetter, types.c_str()); } if (hasSetter) { @@ -1002,8 +1022,9 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { const TypeEncoding* typeEncoding = propertyMeta->setter()->encodings()->first(); IMP impSetter = Interop::CreateMethod(2, 1, typeEncoding, setterCallback, userData); + std::string types = GetAccessorTypeEncoding(typeEncoding, 1, "v@:@"); - class_addMethod(extendedClass, propertyMeta->setter()->selector(), impSetter, "v@:@"); + class_addMethod(extendedClass, propertyMeta->setter()->selector(), impSetter, types.c_str()); } } } diff --git a/NativeScript/runtime/MetadataBuilder.mm b/NativeScript/runtime/MetadataBuilder.mm index c27caa1ba..52d8b61e8 100644 --- a/NativeScript/runtime/MetadataBuilder.mm +++ b/NativeScript/runtime/MetadataBuilder.mm @@ -1493,8 +1493,8 @@ CMethodCall methodCall(context, item->userData_, typeEncoding, args, } }; - const char* compilerEncoding = "@@:"; const TypeEncoding* typeEncoding = propertyMeta->getter()->encodings()->first(); + std::string compilerEncoding = ClassBuilder::GetAccessorTypeEncoding(typeEncoding, 0, "@@:"); Local getter = desc.get(); std::shared_ptr> poGetterFunc = @@ -1502,11 +1502,11 @@ CMethodCall methodCall(context, item->userData_, typeEncoding, args, PropertyCallbackContext* userData = new PropertyCallbackContext(isolate, poGetterFunc, nullptr, propertyMeta); IMP impGetter = Interop::CreateMethod(2, 0, typeEncoding, getterCallback, userData); - IMP nativeImp = - class_replaceMethod(klass, propertyMeta->getter()->selector(), impGetter, compilerEncoding); + IMP nativeImp = class_replaceMethod(klass, propertyMeta->getter()->selector(), impGetter, + compilerEncoding.c_str()); std::string selector = propertyMeta->getter()->selectorAsString(); SEL nativeSelector = sel_registerName((Constants::SwizzledPrefix + selector).c_str()); - class_addMethod(klass, nativeSelector, nativeImp, compilerEncoding); + class_addMethod(klass, nativeSelector, nativeImp, compilerEncoding.c_str()); } if (desc.has_set()) { @@ -1566,12 +1566,12 @@ CMethodCall methodCall(context, item->userData_, typeEncoding, args, new PropertyCallbackContext(isolate, poSetterFunc, nullptr, propertyMeta); IMP impSetter = Interop::CreateMethod(2, 1, typeEncoding, setterCallback, userData); - const char* compilerEncoding = "v@:@"; - IMP nativeImp = - class_replaceMethod(klass, propertyMeta->setter()->selector(), impSetter, compilerEncoding); + std::string compilerEncoding = ClassBuilder::GetAccessorTypeEncoding(typeEncoding, 1, "v@:@"); + IMP nativeImp = class_replaceMethod(klass, propertyMeta->setter()->selector(), impSetter, + compilerEncoding.c_str()); std::string selector = propertyMeta->setter()->selectorAsString(); SEL nativeSelector = sel_registerName((Constants::SwizzledPrefix + selector).c_str()); - class_addMethod(klass, nativeSelector, nativeImp, compilerEncoding); + class_addMethod(klass, nativeSelector, nativeImp, compilerEncoding.c_str()); } // Not intercepted: the native write is done, but V8 must still perform // the ordinary store, which is what the old void-returning callback did diff --git a/TestFixtures/Api/TNSApi.h b/TestFixtures/Api/TNSApi.h index 58ed3b310..de223c3f4 100644 --- a/TestFixtures/Api/TNSApi.h +++ b/TestFixtures/Api/TNSApi.h @@ -1,3 +1,5 @@ +#import + typedef NS_ENUM(NSInteger, TNSEnums) { TNSEnum1 = -1, TNSEnum2, @@ -77,3 +79,38 @@ typedef NSError* _Nullable TNSNullableError; @interface RectClass : NSObject @end + +@interface TNSAccessorTypes : NSObject +@property(nonatomic) BOOL boolProperty; +@property(nonatomic) NSUInteger unsignedProperty; +@property(nonatomic) NSInteger integerProperty; +@property(nonatomic) short shortProperty; +@property(nonatomic) unichar unicharProperty; +@property(nonatomic) char charProperty; +@property(nonatomic) unsigned char unsignedCharProperty; +@property(nonatomic) long long longLongProperty; +@property(nonatomic) float floatProperty; +@property(nonatomic) double doubleProperty; +@property(nonatomic) CGRect rectProperty; +@property(nonatomic) CGPoint pointProperty; +@property(nonatomic) SEL selectorProperty; +@property(nonatomic, strong) Class classProperty; +@property(nonatomic, copy) void (^blockProperty)(void); +@property(nonatomic) void* pointerProperty; +@property(nonatomic) int (*functionPointerProperty)(int); +@property(nonatomic) simd_float4 vectorProperty; +@property(nonatomic, copy) NSString* objectProperty; +@property(nonatomic, strong) id protocolObjectProperty; +@end + +@interface TNSAccessorSwizzleBase : NSObject +@property(nonatomic, readonly) double doubleProperty; +@property(nonatomic, readonly) BOOL boolProperty; +@end + +// Readwrite redeclarations keep these properties in this class's metadata, +// while their getters stay implemented by the superclass only. +@interface TNSAccessorSwizzleDerived : TNSAccessorSwizzleBase +@property(nonatomic, readwrite) double doubleProperty; +@property(nonatomic, readwrite) BOOL boolProperty; +@end diff --git a/TestFixtures/Api/TNSApi.m b/TestFixtures/Api/TNSApi.m index 2085b567d..5b79d0861 100644 --- a/TestFixtures/Api/TNSApi.m +++ b/TestFixtures/Api/TNSApi.m @@ -106,3 +106,25 @@ - (CGRect)getRect { } @end + +@implementation TNSAccessorTypes +@end + +@implementation TNSAccessorSwizzleBase +@end + +@implementation TNSAccessorSwizzleDerived { + double _derivedDouble; + BOOL _derivedBool; +} +@dynamic doubleProperty, boolProperty; + +- (void)setDoubleProperty:(double)value { + _derivedDouble = value; +} + +- (void)setBoolProperty:(BOOL)value { + _derivedBool = value; +} + +@end diff --git a/TestRunner/app/tests/JSAccessorEncodingTests.js b/TestRunner/app/tests/JSAccessorEncodingTests.js new file mode 100644 index 000000000..e8aac454f --- /dev/null +++ b/TestRunner/app/tests/JSAccessorEncodingTests.js @@ -0,0 +1,228 @@ +// Native code that introspects a method (KVC, NSMethodSignature) must see a +// JS-implemented property accessor with the property's own type. +describe("JS-implemented native property accessors", function () { + var rect = { origin: { x: 1, y: 2 }, size: { width: 3, height: 4 } }; + var point = { x: 5, y: 6 }; + + // Every TNSAccessorTypes property, with the value its JS getter answers. + var answers = { + boolProperty: true, + unsignedProperty: 4000000000, + integerProperty: -3, + shortProperty: -2, + unicharProperty: 65, + charProperty: 7, + unsignedCharProperty: 200, + longLongProperty: -5, + floatProperty: 1.5, + doubleProperty: 2.5, + rectProperty: rect, + pointProperty: point, + selectorProperty: "description", + classProperty: NSObject, + blockProperty: function () {}, + pointerProperty: null, + functionPointerProperty: null, + vectorProperty: [1, 2, 3, 4], + objectProperty: "text", + protocolObjectProperty: null + }; + + function typeString(cString) { + return NSString.stringWithUTF8String(cString).toString(); + } + + function setterName(property) { + return "set" + property[0].toUpperCase() + property.slice(1) + ":"; + } + + function accessorDescriptors(state) { + var descriptors = { + hash: { + get: function () { + return 7; + }, + configurable: true, + enumerable: true + } + }; + Object.keys(answers).forEach(function (property) { + descriptors[property] = { + get: function () { + return answers[property]; + }, + set: function (value) { + state.received[property] = value; + }, + configurable: true, + enumerable: true + }; + }); + return descriptors; + } + + function makeExtended(name, state) { + return TNSAccessorTypes.extend(Object.defineProperties({}, accessorDescriptors(state)), { name: name }); + } + + function makeTypeScript(name, state) { + var Klass = (function (_super) { + __extends(Klass, _super); + function Klass() { + return (_super !== null && _super.apply(this, arguments)) || this; + } + Object.defineProperties(Klass.prototype, accessorDescriptors(state)); + return Klass; + })(TNSAccessorTypes); + return Klass; + } + + function expectRect(value, expected) { + expect([value.origin.x, value.origin.y, value.size.width, value.size.height]) + .toEqual([expected.origin.x, expected.origin.y, expected.size.width, expected.size.height]); + } + + [ + { title: ".extend()", make: makeExtended, name: "JSAccessorEncodingExtended" }, + { title: "__extends", make: makeTypeScript, name: "JSAccessorEncodingTypeScript" } + ].forEach(function (variant) { + describe("of a class made with " + variant.title, function () { + var state = { received: {} }; + var Klass = variant.make(variant.name, state); + + beforeEach(function () { + state.received = {}; + }); + + it("answer valueForKey: with an NSUInteger", function () { + var obj = Klass.new(); + expect(obj.valueForKey("hash")).toBe(7); + expect(obj.valueForKey("unsignedProperty")).toBe(4000000000); + }); + + it("answer -[NSArray valueForKey:] with an NSUInteger", function () { + var values = NSArray.arrayWithArray([Klass.new(), Klass.new()]).valueForKey("hash"); + expect(values.count).toBe(2); + expect(values.objectAtIndex(0)).toBe(7); + expect(values.objectAtIndex(1)).toBe(7); + }); + + it("answer valueForKey: with a BOOL", function () { + expect(Klass.new().valueForKey("boolProperty")).toBe(true); + }); + + it("answer valueForKey: with a double", function () { + expect(Klass.new().valueForKey("doubleProperty")).toBe(2.5); + }); + + it("answer valueForKey: with a struct", function () { + var obj = Klass.new(); + expectRect(obj.valueForKey("rectProperty").CGRectValue, rect); + var boxedPoint = obj.valueForKey("pointProperty").CGPointValue; + expect([boxedPoint.x, boxedPoint.y]).toEqual([point.x, point.y]); + }); + + it("answer valueForKey: with an object", function () { + expect(Klass.new().valueForKey("objectProperty")).toBe("text"); + }); + + it("receive a number from setValue:forKey:", function () { + var obj = Klass.new(); + obj.setValueForKey(4000000001, "unsignedProperty"); + expect(state.received.unsignedProperty).toBe(4000000001); + obj.setValueForKey(-1.25, "doubleProperty"); + expect(state.received.doubleProperty).toBe(-1.25); + }); + + it("receive a BOOL from setValue:forKey:", function () { + var obj = Klass.new(); + obj.setValueForKey(true, "boolProperty"); + expect(state.received.boolProperty).toBe(true); + obj.setValueForKey(false, "boolProperty"); + expect(state.received.boolProperty).toBe(false); + }); + + it("receive a struct from setValue:forKey:", function () { + var obj = Klass.new(); + var other = { origin: { x: 10, y: 20 }, size: { width: 30, height: 40 } }; + obj.setValueForKey(NSValue.valueWithCGRect(other), "rectProperty"); + expectRect(state.received.rectProperty, other); + }); + + it("receive an object from setValue:forKey:", function () { + Klass.new().setValueForKey("other text", "objectProperty"); + expect(state.received.objectProperty).toBe("other text"); + }); + + // The compiler's encoding of a vector type is not one the runtime + // can reproduce, so vectorProperty is left out. + it("report the property's own types in their method signatures", function () { + var obj = Klass.new(); + var selectors = ["hash"]; + Object.keys(answers).forEach(function (property) { + if (property !== "vectorProperty") { + selectors.push(property, setterName(property)); + } + }); + selectors.forEach(function (selector) { + var expected = TNSAccessorTypes.instanceMethodSignatureForSelector(selector); + var registered = method_getTypeEncoding(class_getInstanceMethod(Klass.class(), selector)); + var signatures = [ + Klass.instanceMethodSignatureForSelector(selector), + obj.methodSignatureForSelector(selector), + NSMethodSignature.signatureWithObjCTypes(registered) + ]; + signatures.forEach(function (signature) { + expect([selector, typeString(signature.methodReturnType)]).toEqual([selector, typeString(expected.methodReturnType)]); + expect([selector, signature.numberOfArguments]).toEqual([selector, expected.numberOfArguments]); + for (var i = 2; i < expected.numberOfArguments; i++) { + expect([selector, typeString(signature.getArgumentTypeAtIndex(i))]) + .toEqual([selector, typeString(expected.getArgumentTypeAtIndex(i))]); + } + }); + }); + }); + }); + }); + + // The replacement is installed for the rest of the run, on a class no other + // spec uses. + describe("replaced on a native class's prototype", function () { + var installed = false; + + function install() { + if (installed) { + return; + } + installed = true; + Object.defineProperty(TNSAccessorSwizzleDerived.prototype, "doubleProperty", { + get: function () { + return 3.5; + }, + configurable: true + }); + Object.defineProperty(TNSAccessorSwizzleDerived.prototype, "boolProperty", { + get: function () { + return true; + }, + configurable: true + }); + } + + it("answer valueForKey: with the property's own type when the class inherits the accessor", function () { + install(); + var obj = TNSAccessorSwizzleDerived.new(); + expect(obj.valueForKey("doubleProperty")).toBe(3.5); + expect(obj.valueForKey("boolProperty")).toBe(true); + }); + + it("report the property's own type in the method signature when the class inherits the accessor", function () { + install(); + ["doubleProperty", "boolProperty"].forEach(function (selector) { + var expected = TNSAccessorSwizzleBase.instanceMethodSignatureForSelector(selector).methodReturnType; + var signature = TNSAccessorSwizzleDerived.instanceMethodSignatureForSelector(selector); + expect([selector, typeString(signature.methodReturnType)]).toEqual([selector, typeString(expected)]); + }); + }); + }); +}); diff --git a/TestRunner/app/tests/index.js b/TestRunner/app/tests/index.js index bb93113c4..aefe1e5e6 100644 --- a/TestRunner/app/tests/index.js +++ b/TestRunner/app/tests/index.js @@ -137,6 +137,7 @@ require("./NsUrlTests"); require("./NsInteropTests"); require("./GCFinalizerTests"); require("./NativeCallbackSelfTests"); +require("./JSAccessorEncodingTests"); require("./BlockCacheRaceTests"); require("./WorkerConcurrentStartupTests"); require("./WorkerOptionsTests"); From 7f33e06c81a8dee3e53b2b3103d9f22c486e40b7 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 15 Nov 2026 17:44:07 -0300 Subject: [PATCH 2/8] fix(runtime): keep the inherited original of a member swizzled from JS Replacing a native method or property accessor on a class's prototype adds the JS implementation to that class and keeps the one it replaced under a prefixed alias, which native calls from JS prefer. The alias was taken from class_replaceMethod's result, which is the class's own previous implementation only. For a member the class merely inherits: - a property accessor registered the alias with a NULL implementation, so JS calling the original getter or setter silently did nothing (a getter answered nil or 0, a setter never reached the native one); - a method registered no alias, so JS calling the original sent the plain selector back to the JS replacement and recursed until "Maximum call stack size exceeded". The alias now names the implementation the class answered with before the replacement, its own or inherited, looked up with class_getInstanceMethod, and no alias is registered when there is none. Subclasses inherit the alias and reach the same original; instances of the superclass are unaffected. A second replacement leaves the existing alias alone, so it keeps naming the implementation from before the first one. --- NativeScript/runtime/MetadataBuilder.mm | 44 ++++--- TestFixtures/Api/TNSApi.h | 29 +++++ TestFixtures/Api/TNSApi.m | 25 ++++ .../app/tests/JSAccessorEncodingTests.js | 122 ++++++++++++++++++ 4 files changed, 203 insertions(+), 17 deletions(-) diff --git a/NativeScript/runtime/MetadataBuilder.mm b/NativeScript/runtime/MetadataBuilder.mm index 52d8b61e8..76d9c1a86 100644 --- a/NativeScript/runtime/MetadataBuilder.mm +++ b/NativeScript/runtime/MetadataBuilder.mm @@ -1366,6 +1366,25 @@ CMethodCall methodCall(context, item->userData_, typeEncoding, args, } } +namespace { + +// The implementation `klass` answered `selector` with, its own or inherited, +// stays reachable under the swizzled-prefixed selector that native calls from +// JS prefer. An existing alias is kept, so it names the implementation from +// before the first replacement. +void ReplaceKeepingOriginal(Class klass, SEL selector, const char* selectorName, IMP imp, + const char* types) { + Method original = class_getInstanceMethod(klass, selector); + IMP originalImp = original != nullptr ? method_getImplementation(original) : nullptr; + class_replaceMethod(klass, selector, imp, types); + if (originalImp != nullptr) { + SEL nativeSelector = sel_registerName((Constants::SwizzledPrefix + selectorName).c_str()); + class_addMethod(klass, nativeSelector, originalImp, types); + } +} + +} // namespace + v8::Intercepted MetadataBuilder::SwizzledInstanceMethodCallback( Local property, Local value, const PropertyCallbackInfo& info) { Isolate* isolate = info.GetIsolate(); @@ -1402,13 +1421,8 @@ CMethodCall methodCall(context, item->userData_, typeEncoding, args, Interop::ConsumedObjectArgumentIndex(methodMeta->selector(), typeEncoding, argsCount)); IMP methodBody = Interop::CreateMethod(2, argsCount, typeEncoding, ArgConverter::MethodCallback, userData); - IMP nativeImp = - class_replaceMethod(klass, methodMeta->selector(), methodBody, compilerEncoding.c_str()); - if (nativeImp) { - std::string selector = methodMeta->selectorAsString(); - SEL nativeSelector = sel_registerName((Constants::SwizzledPrefix + selector).c_str()); - class_addMethod(klass, nativeSelector, nativeImp, compilerEncoding.c_str()); - } + ReplaceKeepingOriginal(klass, methodMeta->selector(), methodMeta->selectorAsString(), methodBody, + compilerEncoding.c_str()); // Not intercepted: the native write is done, but V8 must still perform // the ordinary store, which is what the old void-returning callback did // by falling through without setting a return value. @@ -1502,11 +1516,9 @@ CMethodCall methodCall(context, item->userData_, typeEncoding, args, PropertyCallbackContext* userData = new PropertyCallbackContext(isolate, poGetterFunc, nullptr, propertyMeta); IMP impGetter = Interop::CreateMethod(2, 0, typeEncoding, getterCallback, userData); - IMP nativeImp = class_replaceMethod(klass, propertyMeta->getter()->selector(), impGetter, - compilerEncoding.c_str()); - std::string selector = propertyMeta->getter()->selectorAsString(); - SEL nativeSelector = sel_registerName((Constants::SwizzledPrefix + selector).c_str()); - class_addMethod(klass, nativeSelector, nativeImp, compilerEncoding.c_str()); + ReplaceKeepingOriginal(klass, propertyMeta->getter()->selector(), + propertyMeta->getter()->selectorAsString(), impGetter, + compilerEncoding.c_str()); } if (desc.has_set()) { @@ -1567,11 +1579,9 @@ CMethodCall methodCall(context, item->userData_, typeEncoding, args, IMP impSetter = Interop::CreateMethod(2, 1, typeEncoding, setterCallback, userData); std::string compilerEncoding = ClassBuilder::GetAccessorTypeEncoding(typeEncoding, 1, "v@:@"); - IMP nativeImp = class_replaceMethod(klass, propertyMeta->setter()->selector(), impSetter, - compilerEncoding.c_str()); - std::string selector = propertyMeta->setter()->selectorAsString(); - SEL nativeSelector = sel_registerName((Constants::SwizzledPrefix + selector).c_str()); - class_addMethod(klass, nativeSelector, nativeImp, compilerEncoding.c_str()); + ReplaceKeepingOriginal(klass, propertyMeta->setter()->selector(), + propertyMeta->setter()->selectorAsString(), impSetter, + compilerEncoding.c_str()); } // Not intercepted: the native write is done, but V8 must still perform // the ordinary store, which is what the old void-returning callback did diff --git a/TestFixtures/Api/TNSApi.h b/TestFixtures/Api/TNSApi.h index de223c3f4..bf45f1942 100644 --- a/TestFixtures/Api/TNSApi.h +++ b/TestFixtures/Api/TNSApi.h @@ -114,3 +114,32 @@ typedef NSError* _Nullable TNSNullableError; @property(nonatomic, readwrite) double doubleProperty; @property(nonatomic, readwrite) BOOL boolProperty; @end + +@interface TNSInheritedSwizzleBase : NSObject +@property(nonatomic, strong) id objectValue; +@property(nonatomic) NSInteger scalarValue; +- (id)describeValue:(int)value; +- (id)storedObjectValue; +- (NSInteger)storedScalarValue; +@end + +@interface TNSInheritedSwizzleDerived : TNSInheritedSwizzleBase +@end + +// Compatible redeclarations with other types keep these members in this +// class's metadata, while only the superclass implements them. +@interface TNSInheritedSwizzleDerived (Redeclared) +@property(nonatomic, strong) NSString* objectValue; +@property(nonatomic) TNSEnums scalarValue; +- (NSString*)describeValue:(int)value; +@end + +@interface TNSInheritedSwizzleSubclass : TNSInheritedSwizzleDerived +@end + +@interface TNSInheritedSwizzleTwice : TNSInheritedSwizzleBase +@end + +@interface TNSInheritedSwizzleTwice (Redeclared) +@property(nonatomic) TNSEnums scalarValue; +@end diff --git a/TestFixtures/Api/TNSApi.m b/TestFixtures/Api/TNSApi.m index 5b79d0861..6648e8419 100644 --- a/TestFixtures/Api/TNSApi.m +++ b/TestFixtures/Api/TNSApi.m @@ -128,3 +128,28 @@ - (void)setBoolProperty:(BOOL)value { } @end + +@implementation TNSInheritedSwizzleBase + +- (id)describeValue:(int)value { + return [NSString stringWithFormat:@"base %d", value]; +} + +- (id)storedObjectValue { + return _objectValue; +} + +- (NSInteger)storedScalarValue { + return _scalarValue; +} + +@end + +@implementation TNSInheritedSwizzleDerived +@end + +@implementation TNSInheritedSwizzleSubclass +@end + +@implementation TNSInheritedSwizzleTwice +@end diff --git a/TestRunner/app/tests/JSAccessorEncodingTests.js b/TestRunner/app/tests/JSAccessorEncodingTests.js index e8aac454f..81549eda1 100644 --- a/TestRunner/app/tests/JSAccessorEncodingTests.js +++ b/TestRunner/app/tests/JSAccessorEncodingTests.js @@ -225,4 +225,126 @@ describe("JS-implemented native property accessors", function () { }); }); }); + + // TNSInheritedSwizzleDerived lists members only its superclass implements. + // The replacements stay installed for the rest of the run, on classes no + // other spec uses. + describe("replaced on a native class that inherits them", function () { + var installed = false; + + // The prototype of a class whose redeclaration keeps the accessor + // count of its superclass's property does not define it again. + function inheritedDescriptor(proto, name) { + for (var current = proto; current !== null; current = Object.getPrototypeOf(current)) { + var descriptor = Object.getOwnPropertyDescriptor(current, name); + if (descriptor !== undefined) { + return descriptor; + } + } + return undefined; + } + + function install() { + if (installed) { + return; + } + installed = true; + var proto = TNSInheritedSwizzleDerived.prototype; + var objectOriginal = inheritedDescriptor(proto, "objectValue"); + Object.defineProperty(proto, "objectValue", { + get: function () { + var value = objectOriginal.get.call(this); + return value === null ? null : "js " + value; + }, + set: function (value) { + objectOriginal.set.call(this, value + "!"); + }, + configurable: true + }); + var scalarOriginal = inheritedDescriptor(proto, "scalarValue"); + Object.defineProperty(proto, "scalarValue", { + get: function () { + return scalarOriginal.get.call(this) * 2; + }, + set: function (value) { + scalarOriginal.set.call(this, value + 1); + }, + configurable: true + }); + var describeOriginal = proto.describeValue; + proto.describeValue = function (value) { + return "js " + describeOriginal.call(this, value); + }; + } + + it("reach the inherited implementation of a method from JS", function () { + install(); + expect(TNSInheritedSwizzleDerived.new().describeValue(3)).toBe("js base 3"); + expect(TNSInheritedSwizzleSubclass.new().describeValue(4)).toBe("js base 4"); + expect(TNSInheritedSwizzleBase.new().describeValue(5)).toBe("base 5"); + }); + + it("reach the inherited accessors of an object property from JS", function () { + install(); + [TNSInheritedSwizzleDerived, TNSInheritedSwizzleSubclass].forEach(function (Klass) { + var obj = Klass.new(); + obj.objectValue = "a"; + expect(obj.storedObjectValue()).toBe("a!"); + expect(obj.objectValue).toBe("js a!"); + expect(obj.valueForKey("objectValue")).toBe("js a!"); + obj.setValueForKey("b", "objectValue"); + expect(obj.storedObjectValue()).toBe("b!"); + }); + var base = TNSInheritedSwizzleBase.new(); + base.objectValue = "a"; + base.setValueForKey("b", "objectValue"); + expect([base.storedObjectValue(), base.objectValue, base.valueForKey("objectValue")]).toEqual(["b", "b", "b"]); + }); + + it("reach the inherited accessors of a scalar property from JS", function () { + install(); + [TNSInheritedSwizzleDerived, TNSInheritedSwizzleSubclass].forEach(function (Klass) { + var obj = Klass.new(); + obj.scalarValue = 5; + expect(obj.storedScalarValue()).toBe(6); + expect(obj.scalarValue).toBe(12); + expect(obj.valueForKey("scalarValue")).toBe(12); + obj.setValueForKey(7, "scalarValue"); + expect(obj.storedScalarValue()).toBe(8); + }); + var base = TNSInheritedSwizzleBase.new(); + base.scalarValue = 5; + base.setValueForKey(7, "scalarValue"); + expect([base.storedScalarValue(), base.scalarValue, base.valueForKey("scalarValue")]).toEqual([7, 7, 7]); + }); + + it("reach the inherited accessors after a second replacement", function () { + var proto = TNSInheritedSwizzleTwice.prototype; + var original = inheritedDescriptor(proto, "scalarValue"); + Object.defineProperty(proto, "scalarValue", { + get: function () { + return original.get.call(this) * 2; + }, + set: function (value) { + original.set.call(this, value + 1); + }, + configurable: true + }); + var first = Object.getOwnPropertyDescriptor(proto, "scalarValue"); + Object.defineProperty(proto, "scalarValue", { + get: function () { + return first.get.call(this) * 10; + }, + set: function (value) { + first.set.call(this, value + 100); + }, + configurable: true + }); + var obj = TNSInheritedSwizzleTwice.new(); + obj.scalarValue = 5; + expect(obj.storedScalarValue()).toBe(106); + expect(obj.scalarValue).toBe(2120); + expect(obj.valueForKey("scalarValue")).toBe(2120); + }); + }); }); From c8170857515f1fceeea1704b75380048fe1087e3 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 15 Nov 2026 17:44:16 -0300 Subject: [PATCH 3/8] fix(runtime): skip JS property accessors the class already implements ExposeProperties built an ffi closure, a PropertyCallbackContext and Persistents for every metadata entry of an overridden property, then called class_addMethod and ignored its result. When two entries share an accessor selector (a property declared by the class and by a protocol, or a selector already added through exposedMethods), the later add fails and everything built for it leaked. An accessor the extended class already implements itself is now skipped before anything is built; an accessor it only inherits is still overridden, and the first entry still wins. --- NativeScript/runtime/ClassBuilder.mm | 19 +++++++++++++++-- .../app/tests/JSAccessorEncodingTests.js | 21 +++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/NativeScript/runtime/ClassBuilder.mm b/NativeScript/runtime/ClassBuilder.mm index a4a1abc45..9efb60d05 100644 --- a/NativeScript/runtime/ClassBuilder.mm +++ b/NativeScript/runtime/ClassBuilder.mm @@ -902,6 +902,17 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { } } +namespace { + +// Whether `klass`, not one of its superclasses, implements `selector`. +bool ImplementsItself(Class klass, SEL selector) { + Method method = class_getInstanceMethod(klass, selector); + return method != nullptr && + method != class_getInstanceMethod(class_getSuperclass(klass), selector); +} + +} // namespace + void ClassBuilder::ExposeProperties(Isolate* isolate, Class extendedClass, std::vector propertyMetas, Local implementationObject, Local getter, @@ -910,8 +921,12 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { const PropertyMeta* propertyMeta = propertyMetas[j]; std::string propertyName = propertyMeta->name(); - bool hasGetter = !getter.IsEmpty() && getter->IsFunction() && propertyMeta->hasGetter(); - bool hasSetter = !setter.IsEmpty() && setter->IsFunction() && propertyMeta->hasSetter(); + // An accessor the class already implements itself came from an earlier + // metadata entry or exposedMethods; class_addMethod would refuse it. + bool hasGetter = !getter.IsEmpty() && getter->IsFunction() && propertyMeta->hasGetter() && + !ImplementsItself(extendedClass, propertyMeta->getter()->selector()); + bool hasSetter = !setter.IsEmpty() && setter->IsFunction() && propertyMeta->hasSetter() && + !ImplementsItself(extendedClass, propertyMeta->setter()->selector()); std::shared_ptr> poImplementationObject; if (hasGetter || hasSetter) { diff --git a/TestRunner/app/tests/JSAccessorEncodingTests.js b/TestRunner/app/tests/JSAccessorEncodingTests.js index 81549eda1..46aac08ba 100644 --- a/TestRunner/app/tests/JSAccessorEncodingTests.js +++ b/TestRunner/app/tests/JSAccessorEncodingTests.js @@ -226,6 +226,27 @@ describe("JS-implemented native property accessors", function () { }); }); + // TNSDerivedInterface declares baseProperty through its base class and + // through a protocol, so two property metadata entries name each accessor. + it("run once per native call when the class and a protocol declare the property", function () { + var counts = { get: 0, set: 0, value: 0 }; + var Klass = TNSDerivedInterface.extend({ + get baseProperty() { + counts.get++; + return 41; + }, + set baseProperty(value) { + counts.set++; + counts.value = value; + } + }, { name: "JSAccessorEncodingSharedSelector" }); + var obj = Klass.new(); + expect(obj.valueForKey("baseProperty")).toBe(41); + obj.setValueForKey(7, "baseProperty"); + expect([counts.get, counts.set, counts.value]).toEqual([1, 1, 7]); + expect(typeString(Klass.instanceMethodSignatureForSelector("baseProperty").methodReturnType)).toBe("i"); + }); + // TNSInheritedSwizzleDerived lists members only its superclass implements. // The replacements stay installed for the rest of the run, on classes no // other spec uses. From 47a37522d31cf33c5861f1ba76709b4018fc5f1d Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 15 Nov 2026 17:44:33 -0300 Subject: [PATCH 4/8] fix(runtime): stop encoding structs again behind nested pointers The metadata names the struct a pointer points to, so GetTypeEncoding expanded the pointee of every pointer, at any depth. A struct that refers to itself through a pointer field (struct Node { struct Node *next; }) recursed until the stack overflowed while the class was being built, for a JS override of a property or method using it. The encoder now follows clang's rule: a struct behind a pointer is expanded only when that pointer is the outermost type, otherwise it is written by name only. Node * encodes as ^{Node=i^{Node}}, a struct holding a Node * or a pointer to another struct names it as ^{Node}, matching the compiler's own method signatures. --- NativeScript/runtime/ClassBuilder.h | 7 +- NativeScript/runtime/ClassBuilder.mm | 15 ++- TestFixtures/Api/TNSApi.h | 23 +++++ TestFixtures/Api/TNSApi.m | 14 +++ .../app/tests/JSAccessorEncodingTests.js | 94 +++++++++++++++++++ 5 files changed, 147 insertions(+), 6 deletions(-) diff --git a/NativeScript/runtime/ClassBuilder.h b/NativeScript/runtime/ClassBuilder.h index 0bc3c1362..b5ce925e4 100644 --- a/NativeScript/runtime/ClassBuilder.h +++ b/NativeScript/runtime/ClassBuilder.h @@ -80,8 +80,13 @@ class ClassBuilder { v8::Local implementationObject, v8::Local getter, v8::Local setter); + // Follows clang: a struct behind a pointer is expanded only when that + // pointer is the outermost type, otherwise it is named only ("{Name}"), + // which also bounds self-referential structs. static std::string GetTypeEncoding(const TypeEncoding* typeEncoding, - bool* encodable); + bool* encodable, + bool expandStructures = true, + bool expandPointedToStructures = true); static BinaryTypeEncodingType GetTypeEncodingType(v8::Isolate* isolate, v8::Local value); diff --git a/NativeScript/runtime/ClassBuilder.mm b/NativeScript/runtime/ClassBuilder.mm index 9efb60d05..ff5f15b5a 100644 --- a/NativeScript/runtime/ClassBuilder.mm +++ b/NativeScript/runtime/ClassBuilder.mm @@ -435,7 +435,8 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { implementationObject); } -std::string ClassBuilder::GetTypeEncoding(const TypeEncoding* typeEncoding, bool* encodable) { +std::string ClassBuilder::GetTypeEncoding(const TypeEncoding* typeEncoding, bool* encodable, + bool expandStructures, bool expandPointedToStructures) { BinaryTypeEncodingType type = typeEncoding->type; switch (type) { case BinaryTypeEncodingType::VoidEncoding: { @@ -504,6 +505,9 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { } case BinaryTypeEncodingType::StructDeclarationReference: { const char* structName = typeEncoding->details.declarationReference.name.valuePtr(); + if (!expandStructures) { + return std::string("{") + structName + "}"; + } const Meta* meta = ArgConverter::GetMeta(structName); if (encodable != nullptr && (meta == nullptr || meta->type() != MetaType::Struct)) { *encodable = false; @@ -516,7 +520,7 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { std::stringstream ss; ss << "{" << structName << "="; for (int i = 0; i < structMeta->fieldsCount(); i++) { - ss << GetTypeEncoding(fieldEncoding, encodable); + ss << GetTypeEncoding(fieldEncoding, encodable, true, false); fieldEncoding = fieldEncoding->next(); } ss << "}"; @@ -526,14 +530,15 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { std::stringstream ss; ss << "^"; const TypeEncoding* innerType = typeEncoding->details.pointer.getInnerType(); - ss << GetTypeEncoding(innerType, encodable); + ss << GetTypeEncoding(innerType, encodable, expandPointedToStructures, false); return ss.str(); } case BinaryTypeEncodingType::ConstantArrayEncoding: { const TypeEncoding* innerType = typeEncoding->details.constantArray.getInnerType(); std::stringstream ss; ss << "["; - ss << typeEncoding->details.constantArray.size << GetTypeEncoding(innerType, encodable); + ss << typeEncoding->details.constantArray.size + << GetTypeEncoding(innerType, encodable, expandStructures, expandPointedToStructures); ss << "]"; return ss.str(); } @@ -541,7 +546,7 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { const TypeEncoding* innerType = typeEncoding->details.incompleteArray.getInnerType(); std::stringstream ss; ss << "^"; - ss << GetTypeEncoding(innerType, encodable); + ss << GetTypeEncoding(innerType, encodable, expandPointedToStructures, false); return ss.str(); } case BinaryTypeEncodingType::FunctionPointerEncoding: { diff --git a/TestFixtures/Api/TNSApi.h b/TestFixtures/Api/TNSApi.h index bf45f1942..f15a9d000 100644 --- a/TestFixtures/Api/TNSApi.h +++ b/TestFixtures/Api/TNSApi.h @@ -143,3 +143,26 @@ typedef NSError* _Nullable TNSNullableError; @interface TNSInheritedSwizzleTwice (Redeclared) @property(nonatomic) TNSEnums scalarValue; @end + +typedef struct TNSLinkedNode { + int value; + struct TNSLinkedNode* next; +} TNSLinkedNode; + +typedef struct TNSLinkedLeaf { + int value; +} TNSLinkedLeaf; + +typedef struct TNSLinkedHolder { + TNSLinkedNode* node; + TNSLinkedLeaf* leaf; + int count; +} TNSLinkedHolder; + +@interface TNSLinkedTypes : NSObject +@property(nonatomic) TNSLinkedNode* nodeProperty; +@property(nonatomic) TNSLinkedHolder holderProperty; +@property(nonatomic) TNSLinkedLeaf* leafProperty; +- (TNSLinkedNode*)nextOf:(TNSLinkedNode*)node; +- (TNSLinkedHolder)holderWithLeaf:(TNSLinkedLeaf*)leaf; +@end diff --git a/TestFixtures/Api/TNSApi.m b/TestFixtures/Api/TNSApi.m index 6648e8419..6ad07fa0a 100644 --- a/TestFixtures/Api/TNSApi.m +++ b/TestFixtures/Api/TNSApi.m @@ -153,3 +153,17 @@ @implementation TNSInheritedSwizzleSubclass @implementation TNSInheritedSwizzleTwice @end + +static TNSLinkedNode sharedLinkedNodes[2] = {{1, &sharedLinkedNodes[1]}, {2, NULL}}; + +@implementation TNSLinkedTypes + +- (TNSLinkedNode*)nextOf:(TNSLinkedNode*)node { + return node != NULL ? node->next : NULL; +} + +- (TNSLinkedHolder)holderWithLeaf:(TNSLinkedLeaf*)leaf { + return (TNSLinkedHolder){&sharedLinkedNodes[0], leaf, 1}; +} + +@end diff --git a/TestRunner/app/tests/JSAccessorEncodingTests.js b/TestRunner/app/tests/JSAccessorEncodingTests.js index 46aac08ba..51388ff3c 100644 --- a/TestRunner/app/tests/JSAccessorEncodingTests.js +++ b/TestRunner/app/tests/JSAccessorEncodingTests.js @@ -368,4 +368,98 @@ describe("JS-implemented native property accessors", function () { expect(obj.valueForKey("scalarValue")).toBe(2120); }); }); + + // TNSLinkedNode refers to itself through a pointer field. + describe("of self-referential struct types", function () { + var state = {}; + var Klass = null; + + function linkedClass() { + if (Klass === null) { + Klass = TNSLinkedTypes.extend({ + get nodeProperty() { + return state.node; + }, + set nodeProperty(value) { + state.node = value; + }, + get holderProperty() { + return { node: null, leaf: null, count: 3 }; + }, + set holderProperty(value) { + state.holder = value; + }, + get leafProperty() { + return null; + }, + set leafProperty(value) { + state.leaf = value; + }, + nextOf: function (node) { + return null; + }, + holderWithLeaf: function (leaf) { + return { node: null, leaf: leaf, count: 0 }; + } + }, { name: "JSAccessorEncodingLinked" }); + } + return Klass; + } + + function address(value) { + return value ? interop.handleof(value).toNumber() : 0; + } + + function outcome(action) { + try { + return { value: action() }; + } catch (e) { + return { error: e.nativeException ? e.nativeException.name : String(e) }; + } + } + + it("report the compiler's types in the signatures of JS accessors and methods", function () { + var Linked = linkedClass(); + [ + "nodeProperty", "setNodeProperty:", "holderProperty", "setHolderProperty:", + "leafProperty", "setLeafProperty:", "nextOf:", "holderWithLeaf:" + ].forEach(function (selector) { + var expected = TNSLinkedTypes.instanceMethodSignatureForSelector(selector); + var registered = NSMethodSignature.signatureWithObjCTypes(method_getTypeEncoding(class_getInstanceMethod(Linked.class(), selector))); + expect([selector, typeString(registered.methodReturnType)]).toEqual([selector, typeString(expected.methodReturnType)]); + expect([selector, registered.numberOfArguments]).toEqual([selector, expected.numberOfArguments]); + for (var i = 2; i < expected.numberOfArguments; i++) { + expect([selector, typeString(registered.getArgumentTypeAtIndex(i))]) + .toEqual([selector, typeString(expected.getArgumentTypeAtIndex(i))]); + } + }); + }); + + // KVC answers NSUnknownKeyException for pointer-typed keys. + it("read and write a pointer property through KVC as the base class does", function () { + var Linked = linkedClass(); + var node = interop.alloc(16); + var base = TNSLinkedTypes.new(); + var obj = Linked.new(); + state.node = null; + + function read(target) { + return outcome(function () { + var boxed = target.valueForKey("nodeProperty"); + return [typeString(boxed.objCType), address(boxed.pointerValue)]; + }); + } + expect(read(obj)).toEqual(read(base)); + + var written = outcome(function () { + base.setValueForKey(NSValue.valueWithPointer(node), "nodeProperty"); + return address(base.nodeProperty); + }); + var writtenByJS = outcome(function () { + obj.setValueForKey(NSValue.valueWithPointer(node), "nodeProperty"); + return address(state.node); + }); + expect(writtenByJS).toEqual(written); + }); + }); }); From b19072a497d3dea39f626db4b8915d07232b1435 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 15 Nov 2026 18:19:17 -0300 Subject: [PATCH 5/8] fix(runtime): alias the native original when a superclass member was swizzled The alias kept for a member replaced from JS named whatever the class answered for the selector, its own or inherited. When a superclass had already replaced the member, that is the superclass's JS replacement: a subclass replacement then aliased it, and calling the original from either replacement sent the alias back to that JS replacement until the stack ran out (methods threw RangeError; accessors recursed until the stack limit, then answered nil or 0). Before the inherited alias was introduced, methods on a subclass fell back to the superclass's alias and did not recurse. The alias now names the native implementation the class would run had nothing been replaced: the class that provides the selector is found by walking up to the first one that implements it itself, and its alias is used when it has been replaced, its own implementation otherwise. A native override between a replaced superclass and a replaced subclass is the subclass's original. An alias the class already has is still kept, and no alias is added when nothing implements the selector. --- NativeScript/runtime/ClassBuilder.h | 2 + NativeScript/runtime/ClassBuilder.mm | 7 +- NativeScript/runtime/MetadataBuilder.mm | 29 ++- TestFixtures/Api/TNSApi.h | 56 +++++ TestFixtures/Api/TNSApi.m | 92 +++++++++ .../app/tests/JSAccessorEncodingTests.js | 192 ++++++++++++++++-- 6 files changed, 351 insertions(+), 27 deletions(-) diff --git a/NativeScript/runtime/ClassBuilder.h b/NativeScript/runtime/ClassBuilder.h index b5ce925e4..1b122fe0a 100644 --- a/NativeScript/runtime/ClassBuilder.h +++ b/NativeScript/runtime/ClassBuilder.h @@ -48,6 +48,8 @@ class ClassBuilder { static Class FindNativeClass(Class klass); // The implementation of `method` from FindNativeClass(klass). static IMP FindNotOverridenMethod(Class klass, SEL method); + // Whether `klass`, not one of its superclasses, implements `selector`. + static bool ImplementsItself(Class klass, SEL selector); private: static std::atomic classNameCounter_; diff --git a/NativeScript/runtime/ClassBuilder.mm b/NativeScript/runtime/ClassBuilder.mm index ff5f15b5a..79301896c 100644 --- a/NativeScript/runtime/ClassBuilder.mm +++ b/NativeScript/runtime/ClassBuilder.mm @@ -907,17 +907,12 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { } } -namespace { - -// Whether `klass`, not one of its superclasses, implements `selector`. -bool ImplementsItself(Class klass, SEL selector) { +bool ClassBuilder::ImplementsItself(Class klass, SEL selector) { Method method = class_getInstanceMethod(klass, selector); return method != nullptr && method != class_getInstanceMethod(class_getSuperclass(klass), selector); } -} // namespace - void ClassBuilder::ExposeProperties(Isolate* isolate, Class extendedClass, std::vector propertyMetas, Local implementationObject, Local getter, diff --git a/NativeScript/runtime/MetadataBuilder.mm b/NativeScript/runtime/MetadataBuilder.mm index 76d9c1a86..f4ff9dd0f 100644 --- a/NativeScript/runtime/MetadataBuilder.mm +++ b/NativeScript/runtime/MetadataBuilder.mm @@ -1368,18 +1368,29 @@ CMethodCall methodCall(context, item->userData_, typeEncoding, args, namespace { -// The implementation `klass` answered `selector` with, its own or inherited, -// stays reachable under the swizzled-prefixed selector that native calls from -// JS prefer. An existing alias is kept, so it names the implementation from -// before the first replacement. +// The native implementation `klass` would run for `selector` had nothing been +// replaced from JS. The class that provides `selector` keeps its native one +// under `alias` once it has been replaced. +IMP NativeImplementation(Class klass, SEL selector, SEL alias) { + for (Class owner = klass; owner != nil; owner = class_getSuperclass(owner)) { + if (ClassBuilder::ImplementsItself(owner, selector)) { + SEL native = ClassBuilder::ImplementsItself(owner, alias) ? alias : selector; + return method_getImplementation(class_getInstanceMethod(owner, native)); + } + } + return nullptr; +} + +// The native implementation stays reachable under the swizzled-prefixed +// selector that native calls from JS prefer. An alias `klass` already has is +// kept, so it names the implementation from before the first replacement. void ReplaceKeepingOriginal(Class klass, SEL selector, const char* selectorName, IMP imp, const char* types) { - Method original = class_getInstanceMethod(klass, selector); - IMP originalImp = original != nullptr ? method_getImplementation(original) : nullptr; + SEL alias = sel_registerName((Constants::SwizzledPrefix + selectorName).c_str()); + IMP original = NativeImplementation(klass, selector, alias); class_replaceMethod(klass, selector, imp, types); - if (originalImp != nullptr) { - SEL nativeSelector = sel_registerName((Constants::SwizzledPrefix + selectorName).c_str()); - class_addMethod(klass, nativeSelector, originalImp, types); + if (original != nullptr) { + class_addMethod(klass, alias, original, types); } } diff --git a/TestFixtures/Api/TNSApi.h b/TestFixtures/Api/TNSApi.h index f15a9d000..32dc59d6b 100644 --- a/TestFixtures/Api/TNSApi.h +++ b/TestFixtures/Api/TNSApi.h @@ -144,6 +144,62 @@ typedef NSError* _Nullable TNSNullableError; @property(nonatomic) TNSEnums scalarValue; @end +// Families for specs that replace members on a class and on its subclass. +@interface TNSSwizzleChainBase : NSObject +@property(nonatomic, strong) id objectValue; +@property(nonatomic) NSInteger scalarValue; +- (id)describeValue:(int)value; +- (id)storedObjectValue; +- (NSInteger)storedScalarValue; +@end + +@interface TNSSwizzleChainDerived : TNSSwizzleChainBase +@end + +@interface TNSSwizzleChainDerived (Redeclared) +@property(nonatomic, strong) NSString* objectValue; +@property(nonatomic) TNSEnums scalarValue; +- (NSString*)describeValue:(int)value; +@end + +@interface TNSSwizzleReverseBase : NSObject +@property(nonatomic, strong) id objectValue; +@property(nonatomic) NSInteger scalarValue; +- (id)describeValue:(int)value; +- (id)storedObjectValue; +- (NSInteger)storedScalarValue; +@end + +@interface TNSSwizzleReverseDerived : TNSSwizzleReverseBase +@end + +@interface TNSSwizzleReverseDerived (Redeclared) +@property(nonatomic, strong) NSString* objectValue; +@property(nonatomic) TNSEnums scalarValue; +- (NSString*)describeValue:(int)value; +@end + +@interface TNSSwizzleMiddleBase : NSObject +@property(nonatomic, strong) id objectValue; +@property(nonatomic) NSInteger scalarValue; +- (id)describeValue:(int)value; +- (id)storedObjectValue; +- (NSInteger)storedScalarValue; +@end + +// Overrides every member of its superclass natively, without calling it. +@interface TNSSwizzleMiddle : TNSSwizzleMiddleBase +@end + +@interface TNSSwizzleMiddleLeaf : TNSSwizzleMiddle +@end + +@interface TNSSwizzleMiddleLeaf (Redeclared) +@property(nonatomic, strong) NSString* objectValue; +@property(nonatomic) TNSEnums scalarValue; +- (NSString*)describeValue:(int)value; +@end + typedef struct TNSLinkedNode { int value; struct TNSLinkedNode* next; diff --git a/TestFixtures/Api/TNSApi.m b/TestFixtures/Api/TNSApi.m index 6ad07fa0a..3bcb0a75c 100644 --- a/TestFixtures/Api/TNSApi.m +++ b/TestFixtures/Api/TNSApi.m @@ -154,6 +154,98 @@ @implementation TNSInheritedSwizzleSubclass @implementation TNSInheritedSwizzleTwice @end +@implementation TNSSwizzleChainBase + +- (id)describeValue:(int)value { + return [NSString stringWithFormat:@"base %d", value]; +} + +- (id)storedObjectValue { + return _objectValue; +} + +- (NSInteger)storedScalarValue { + return _scalarValue; +} + +@end + +@implementation TNSSwizzleChainDerived +@end + +@implementation TNSSwizzleReverseBase + +- (id)describeValue:(int)value { + return [NSString stringWithFormat:@"base %d", value]; +} + +- (id)storedObjectValue { + return _objectValue; +} + +- (NSInteger)storedScalarValue { + return _scalarValue; +} + +@end + +@implementation TNSSwizzleReverseDerived +@end + +@implementation TNSSwizzleMiddleBase + +- (id)describeValue:(int)value { + return [NSString stringWithFormat:@"base %d", value]; +} + +- (id)storedObjectValue { + return _objectValue; +} + +- (NSInteger)storedScalarValue { + return _scalarValue; +} + +@end + +@implementation TNSSwizzleMiddle { + id _middleObject; + NSInteger _middleScalar; +} + +- (id)describeValue:(int)value { + return [NSString stringWithFormat:@"middle %d", value]; +} + +- (id)objectValue { + return [NSString stringWithFormat:@"middle %@", _middleObject]; +} + +- (void)setObjectValue:(id)value { + _middleObject = [NSString stringWithFormat:@"%@ via middle", value]; +} + +- (NSInteger)scalarValue { + return _middleScalar + 1000; +} + +- (void)setScalarValue:(NSInteger)value { + _middleScalar = value * 3; +} + +- (id)storedObjectValue { + return _middleObject; +} + +- (NSInteger)storedScalarValue { + return _middleScalar; +} + +@end + +@implementation TNSSwizzleMiddleLeaf +@end + static TNSLinkedNode sharedLinkedNodes[2] = {{1, &sharedLinkedNodes[1]}, {2, NULL}}; @implementation TNSLinkedTypes diff --git a/TestRunner/app/tests/JSAccessorEncodingTests.js b/TestRunner/app/tests/JSAccessorEncodingTests.js index 51388ff3c..f550a95ff 100644 --- a/TestRunner/app/tests/JSAccessorEncodingTests.js +++ b/TestRunner/app/tests/JSAccessorEncodingTests.js @@ -250,20 +250,20 @@ describe("JS-implemented native property accessors", function () { // TNSInheritedSwizzleDerived lists members only its superclass implements. // The replacements stay installed for the rest of the run, on classes no // other spec uses. - describe("replaced on a native class that inherits them", function () { - var installed = false; - - // The prototype of a class whose redeclaration keeps the accessor - // count of its superclass's property does not define it again. - function inheritedDescriptor(proto, name) { - for (var current = proto; current !== null; current = Object.getPrototypeOf(current)) { - var descriptor = Object.getOwnPropertyDescriptor(current, name); - if (descriptor !== undefined) { - return descriptor; - } + // The prototype of a class whose redeclaration keeps the accessor count of + // its superclass's property does not define it again. + function inheritedDescriptor(proto, name) { + for (var current = proto; current !== null; current = Object.getPrototypeOf(current)) { + var descriptor = Object.getOwnPropertyDescriptor(current, name); + if (descriptor !== undefined) { + return descriptor; } - return undefined; } + return undefined; + } + + describe("replaced on a native class that inherits them", function () { + var installed = false; function install() { if (installed) { @@ -369,6 +369,174 @@ describe("JS-implemented native property accessors", function () { }); }); + // Each family is replaced by one spec group for the rest of the run. A + // replacement records its tag in `trace` and calls the original it looked + // up when it was installed: describeValue wraps the result in "tag(...)", + // the object accessors wrap what they read and write, the scalar ones + // append the tag's digit. + describe("replaced on a class and on its subclass", function () { + var trace = []; + + function replaceMembers(Klass, tag, digit) { + var proto = Klass.prototype; + var describeOriginal = proto.describeValue; + proto.describeValue = function (value) { + trace.push(tag); + return tag + "(" + describeOriginal.call(this, value) + ")"; + }; + var objectOriginal = inheritedDescriptor(proto, "objectValue"); + Object.defineProperty(proto, "objectValue", { + get: function () { + trace.push(tag + " get"); + return tag + "(" + objectOriginal.get.call(this) + ")"; + }, + set: function (value) { + trace.push(tag + " set"); + objectOriginal.set.call(this, tag + "(" + value + ")"); + }, + configurable: true + }); + var scalarOriginal = inheritedDescriptor(proto, "scalarValue"); + Object.defineProperty(proto, "scalarValue", { + get: function () { + trace.push(tag + " get"); + return scalarOriginal.get.call(this) * 10 + digit; + }, + set: function (value) { + trace.push(tag + " set"); + scalarOriginal.set.call(this, value * 10 + digit); + }, + configurable: true + }); + return { describe: describeOriginal, object: objectOriginal, scalar: scalarOriginal }; + } + + function installer(replace) { + var originals = null; + return function () { + if (originals === null) { + originals = replace(); + } + trace.length = 0; + return originals; + }; + } + + function traced(action) { + trace.length = 0; + var result = action(); + return { result: result, trace: trace.slice() }; + } + + // The subclass's replacements find native members as their originals, + // which run the superclass's native implementation, not its + // replacement. + describe("the superclass first", function () { + var install = installer(function () { + return { base: replaceMembers(TNSSwizzleChainBase, "B", 1), derived: replaceMembers(TNSSwizzleChainDerived, "D", 2) }; + }); + + it("reach the native method from both replacements", function () { + var originals = install(); + var derived = TNSSwizzleChainDerived.new(); + expect(traced(function () { return derived.describeValue(1); })).toEqual({ result: "D(base 1)", trace: ["D"] }); + expect(traced(function () { return originals.base.describe.call(derived, 2); })).toEqual({ result: "base 2", trace: [] }); + expect(traced(function () { return TNSSwizzleChainBase.new().describeValue(3); })).toEqual({ result: "B(base 3)", trace: ["B"] }); + }); + + it("reach the native accessors of an object property from both replacements", function () { + var originals = install(); + var derived = TNSSwizzleChainDerived.new(); + expect(traced(function () { derived.objectValue = "x"; return derived.storedObjectValue(); })) + .toEqual({ result: "D(x)", trace: ["D set"] }); + expect(traced(function () { return derived.objectValue; })).toEqual({ result: "D(D(x))", trace: ["D get"] }); + expect(traced(function () { return derived.valueForKey("objectValue"); })).toEqual({ result: "D(D(x))", trace: ["D get"] }); + expect(traced(function () { return originals.base.object.get.call(derived); })).toEqual({ result: "D(x)", trace: [] }); + var base = TNSSwizzleChainBase.new(); + base.objectValue = "y"; + expect([base.storedObjectValue(), base.valueForKey("objectValue")]).toEqual(["B(y)", "B(B(y))"]); + }); + + it("reach the native accessors of a scalar property from both replacements", function () { + var originals = install(); + var derived = TNSSwizzleChainDerived.new(); + expect(traced(function () { derived.scalarValue = 5; return derived.storedScalarValue(); })) + .toEqual({ result: 52, trace: ["D set"] }); + expect(traced(function () { return derived.valueForKey("scalarValue"); })).toEqual({ result: 522, trace: ["D get"] }); + expect(traced(function () { return originals.base.scalar.get.call(derived); })).toEqual({ result: 52, trace: [] }); + var base = TNSSwizzleChainBase.new(); + base.scalarValue = 5; + expect([base.storedScalarValue(), base.valueForKey("scalarValue")]).toEqual([51, 511]); + }); + }); + + // The subclass's replacement finds the native implementation as its + // original, so the superclass's later replacement is not part of it. + describe("the subclass first", function () { + var install = installer(function () { + return { derived: replaceMembers(TNSSwizzleReverseDerived, "D", 2), base: replaceMembers(TNSSwizzleReverseBase, "B", 1) }; + }); + + it("reach the native method", function () { + install(); + expect(traced(function () { return TNSSwizzleReverseDerived.new().describeValue(1); })).toEqual({ result: "D(base 1)", trace: ["D"] }); + expect(traced(function () { return TNSSwizzleReverseBase.new().describeValue(2); })).toEqual({ result: "B(base 2)", trace: ["B"] }); + }); + + it("reach the native accessors of an object property", function () { + install(); + var derived = TNSSwizzleReverseDerived.new(); + derived.objectValue = "x"; + expect([derived.storedObjectValue(), derived.valueForKey("objectValue")]).toEqual(["D(x)", "D(D(x))"]); + var base = TNSSwizzleReverseBase.new(); + base.objectValue = "y"; + expect([base.storedObjectValue(), base.valueForKey("objectValue")]).toEqual(["B(y)", "B(B(y))"]); + }); + + it("reach the native accessors of a scalar property", function () { + install(); + var derived = TNSSwizzleReverseDerived.new(); + derived.scalarValue = 5; + expect([derived.storedScalarValue(), derived.valueForKey("scalarValue")]).toEqual([52, 522]); + var base = TNSSwizzleReverseBase.new(); + base.scalarValue = 5; + expect([base.storedScalarValue(), base.valueForKey("scalarValue")]).toEqual([51, 511]); + }); + }); + + // TNSSwizzleMiddle overrides every member natively, between the + // replaced superclass and the replaced leaf, whose originals are + // native functions. + describe("the superclass first, with a native override in between", function () { + var install = installer(function () { + return { base: replaceMembers(TNSSwizzleMiddleBase, "B", 1), leaf: replaceMembers(TNSSwizzleMiddleLeaf, "L", 3) }; + }); + + it("reach the middle class's native method", function () { + var originals = install(); + var leaf = TNSSwizzleMiddleLeaf.new(); + expect(traced(function () { return leaf.describeValue(1); })).toEqual({ result: "L(middle 1)", trace: ["L"] }); + expect(traced(function () { return originals.base.describe.call(leaf, 2); })).toEqual({ result: "middle 2", trace: [] }); + }); + + it("reach the middle class's native accessors of an object property", function () { + install(); + var leaf = TNSSwizzleMiddleLeaf.new(); + leaf.objectValue = "x"; + expect(leaf.storedObjectValue()).toBe("L(x) via middle"); + expect(leaf.valueForKey("objectValue")).toBe("L(middle L(x) via middle)"); + }); + + it("reach the middle class's native accessors of a scalar property", function () { + install(); + var leaf = TNSSwizzleMiddleLeaf.new(); + leaf.scalarValue = 5; + expect(leaf.storedScalarValue()).toBe(159); + expect(leaf.valueForKey("scalarValue")).toBe(11593); + }); + }); + }); + // TNSLinkedNode refers to itself through a pointer field. describe("of self-referential struct types", function () { var state = {}; From 66678021a0d54f2e7b5f196d8f21c4cc0434e5df Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 15 Nov 2026 18:27:39 -0300 Subject: [PATCH 6/8] fix(runtime): keep an inherited swizzle alias instead of adding one Aliasing the native implementation a class would run let a class below a replaced ancestor alias a native override in between. When that override calls super, it reaches the ancestor's JS replacement, whose original is sent to the receiver's class, finds the subclass's alias, and runs the override again, without end. A class that inherits the member and already responds to the alias, because an ancestor was replaced from JS, now adds no alias of its own and uses the inherited one, as methods did before inherited aliases were added; for accessors this replaces the NULL alias those registered. A class that implements the member itself still aliases its own implementation, and a class that inherits it with no alias inherited aliases the inherited native implementation. A native override between a replaced ancestor and a replaced subclass is therefore not part of the subclass's original. --- NativeScript/runtime/MetadataBuilder.mm | 29 ++++----- TestFixtures/Api/TNSApi.h | 21 ++++++ TestFixtures/Api/TNSApi.m | 41 +++++++++++- .../app/tests/JSAccessorEncodingTests.js | 65 +++++++++++++++---- 4 files changed, 125 insertions(+), 31 deletions(-) diff --git a/NativeScript/runtime/MetadataBuilder.mm b/NativeScript/runtime/MetadataBuilder.mm index f4ff9dd0f..bbdab6f32 100644 --- a/NativeScript/runtime/MetadataBuilder.mm +++ b/NativeScript/runtime/MetadataBuilder.mm @@ -1368,26 +1368,21 @@ CMethodCall methodCall(context, item->userData_, typeEncoding, args, namespace { -// The native implementation `klass` would run for `selector` had nothing been -// replaced from JS. The class that provides `selector` keeps its native one -// under `alias` once it has been replaced. -IMP NativeImplementation(Class klass, SEL selector, SEL alias) { - for (Class owner = klass; owner != nil; owner = class_getSuperclass(owner)) { - if (ClassBuilder::ImplementsItself(owner, selector)) { - SEL native = ClassBuilder::ImplementsItself(owner, alias) ? alias : selector; - return method_getImplementation(class_getInstanceMethod(owner, native)); - } - } - return nullptr; -} - -// The native implementation stays reachable under the swizzled-prefixed -// selector that native calls from JS prefer. An alias `klass` already has is -// kept, so it names the implementation from before the first replacement. +// The implementation `klass` answered `selector` with stays reachable under +// the swizzled-prefixed selector that native calls from JS prefer; an alias +// `klass` already has is kept, so it names the one from before the first +// replacement. A class that inherits `selector` and already responds to the +// alias, because an ancestor was replaced, gets none of its own: an own alias +// naming a native override that calls super would send the replaced +// ancestor's original back to that override. void ReplaceKeepingOriginal(Class klass, SEL selector, const char* selectorName, IMP imp, const char* types) { SEL alias = sel_registerName((Constants::SwizzledPrefix + selectorName).c_str()); - IMP original = NativeImplementation(klass, selector, alias); + IMP original = nullptr; + if (ClassBuilder::ImplementsItself(klass, selector) || !class_respondsToSelector(klass, alias)) { + Method method = class_getInstanceMethod(klass, selector); + original = method != nullptr ? method_getImplementation(method) : nullptr; + } class_replaceMethod(klass, selector, imp, types); if (original != nullptr) { class_addMethod(klass, alias, original, types); diff --git a/TestFixtures/Api/TNSApi.h b/TestFixtures/Api/TNSApi.h index 32dc59d6b..2da4d1619 100644 --- a/TestFixtures/Api/TNSApi.h +++ b/TestFixtures/Api/TNSApi.h @@ -200,6 +200,27 @@ typedef NSError* _Nullable TNSNullableError; - (NSString*)describeValue:(int)value; @end +@interface TNSSwizzleSuperBase : NSObject +@property(nonatomic, strong) id objectValue; +@property(nonatomic) NSInteger scalarValue; +- (id)describeValue:(int)value; +- (id)storedObjectValue; +- (NSInteger)storedScalarValue; +@end + +// Overrides every member of its superclass natively, calling it. +@interface TNSSwizzleSuperMiddle : TNSSwizzleSuperBase +@end + +@interface TNSSwizzleSuperLeaf : TNSSwizzleSuperMiddle +@end + +@interface TNSSwizzleSuperLeaf (Redeclared) +@property(nonatomic, strong) NSString* objectValue; +@property(nonatomic) TNSEnums scalarValue; +- (NSString*)describeValue:(int)value; +@end + typedef struct TNSLinkedNode { int value; struct TNSLinkedNode* next; diff --git a/TestFixtures/Api/TNSApi.m b/TestFixtures/Api/TNSApi.m index 3bcb0a75c..6a0e8aebb 100644 --- a/TestFixtures/Api/TNSApi.m +++ b/TestFixtures/Api/TNSApi.m @@ -233,17 +233,52 @@ - (void)setScalarValue:(NSInteger)value { _middleScalar = value * 3; } +@end + +@implementation TNSSwizzleMiddleLeaf +@end + +@implementation TNSSwizzleSuperBase + +- (id)describeValue:(int)value { + return [NSString stringWithFormat:@"base %d", value]; +} + - (id)storedObjectValue { - return _middleObject; + return _objectValue; } - (NSInteger)storedScalarValue { - return _middleScalar; + return _scalarValue; } @end -@implementation TNSSwizzleMiddleLeaf +@implementation TNSSwizzleSuperMiddle + +- (id)describeValue:(int)value { + return [NSString stringWithFormat:@"middle %@", [super describeValue:value]]; +} + +- (id)objectValue { + return [NSString stringWithFormat:@"middle %@", [super objectValue]]; +} + +- (void)setObjectValue:(id)value { + [super setObjectValue:[NSString stringWithFormat:@"%@ via middle", value]]; +} + +- (NSInteger)scalarValue { + return [super scalarValue] + 1000; +} + +- (void)setScalarValue:(NSInteger)value { + [super setScalarValue:value * 3]; +} + +@end + +@implementation TNSSwizzleSuperLeaf @end static TNSLinkedNode sharedLinkedNodes[2] = {{1, &sharedLinkedNodes[1]}, {2, NULL}}; diff --git a/TestRunner/app/tests/JSAccessorEncodingTests.js b/TestRunner/app/tests/JSAccessorEncodingTests.js index f550a95ff..357acbbf4 100644 --- a/TestRunner/app/tests/JSAccessorEncodingTests.js +++ b/TestRunner/app/tests/JSAccessorEncodingTests.js @@ -505,34 +505,77 @@ describe("JS-implemented native property accessors", function () { }); // TNSSwizzleMiddle overrides every member natively, between the - // replaced superclass and the replaced leaf, whose originals are - // native functions. + // replaced superclass and the replaced leaf. The leaf's originals run + // the superclass's native members, not the middle class's overrides. describe("the superclass first, with a native override in between", function () { var install = installer(function () { return { base: replaceMembers(TNSSwizzleMiddleBase, "B", 1), leaf: replaceMembers(TNSSwizzleMiddleLeaf, "L", 3) }; }); - it("reach the middle class's native method", function () { + it("reach the superclass's native method", function () { var originals = install(); var leaf = TNSSwizzleMiddleLeaf.new(); - expect(traced(function () { return leaf.describeValue(1); })).toEqual({ result: "L(middle 1)", trace: ["L"] }); - expect(traced(function () { return originals.base.describe.call(leaf, 2); })).toEqual({ result: "middle 2", trace: [] }); + expect(traced(function () { return leaf.describeValue(1); })).toEqual({ result: "L(base 1)", trace: ["L"] }); + expect(traced(function () { return originals.base.describe.call(leaf, 2); })).toEqual({ result: "base 2", trace: [] }); }); - it("reach the middle class's native accessors of an object property", function () { + it("reach the superclass's native accessors of an object property", function () { install(); var leaf = TNSSwizzleMiddleLeaf.new(); leaf.objectValue = "x"; - expect(leaf.storedObjectValue()).toBe("L(x) via middle"); - expect(leaf.valueForKey("objectValue")).toBe("L(middle L(x) via middle)"); + expect(leaf.storedObjectValue()).toBe("L(x)"); + expect(leaf.valueForKey("objectValue")).toBe("L(L(x))"); }); - it("reach the middle class's native accessors of a scalar property", function () { + it("reach the superclass's native accessors of a scalar property", function () { install(); var leaf = TNSSwizzleMiddleLeaf.new(); leaf.scalarValue = 5; - expect(leaf.storedScalarValue()).toBe(159); - expect(leaf.valueForKey("scalarValue")).toBe(11593); + expect(leaf.storedScalarValue()).toBe(53); + expect(leaf.valueForKey("scalarValue")).toBe(533); + }); + }); + + // TNSSwizzleSuperMiddle overrides every member natively and calls the + // superclass's, which is replaced; so is the leaf below it. + describe("the superclass first, with a native override calling super in between", function () { + var install = installer(function () { + return { base: replaceMembers(TNSSwizzleSuperBase, "B", 1), leaf: replaceMembers(TNSSwizzleSuperLeaf, "L", 3) }; + }); + + it("reach the superclass's native method from the leaf", function () { + var originals = install(); + var leaf = TNSSwizzleSuperLeaf.new(); + expect(traced(function () { return leaf.describeValue(1); })).toEqual({ result: "L(base 1)", trace: ["L"] }); + expect(traced(function () { return originals.base.describe.call(leaf, 2); })).toEqual({ result: "base 2", trace: [] }); + }); + + it("reach the superclass's native accessors of an object property", function () { + install(); + var leaf = TNSSwizzleSuperLeaf.new(); + expect(traced(function () { leaf.objectValue = "x"; return leaf.storedObjectValue(); })).toEqual({ result: "L(x)", trace: ["L set"] }); + expect(traced(function () { return leaf.valueForKey("objectValue"); })).toEqual({ result: "L(L(x))", trace: ["L get"] }); + var middle = TNSSwizzleSuperMiddle.new(); + expect(traced(function () { middle.setValueForKey("y", "objectValue"); return middle.storedObjectValue(); })) + .toEqual({ result: "B(y via middle)", trace: ["B set"] }); + expect(traced(function () { return middle.valueForKey("objectValue"); })).toEqual({ result: "middle B(B(y via middle))", trace: ["B get"] }); + var base = TNSSwizzleSuperBase.new(); + base.objectValue = "z"; + expect([base.storedObjectValue(), base.valueForKey("objectValue")]).toEqual(["B(z)", "B(B(z))"]); + }); + + it("reach the superclass's native accessors of a scalar property", function () { + install(); + var leaf = TNSSwizzleSuperLeaf.new(); + expect(traced(function () { leaf.scalarValue = 5; return leaf.storedScalarValue(); })).toEqual({ result: 53, trace: ["L set"] }); + expect(traced(function () { return leaf.valueForKey("scalarValue"); })).toEqual({ result: 533, trace: ["L get"] }); + var middle = TNSSwizzleSuperMiddle.new(); + expect(traced(function () { middle.setValueForKey(5, "scalarValue"); return middle.storedScalarValue(); })) + .toEqual({ result: 151, trace: ["B set"] }); + expect(traced(function () { return middle.valueForKey("scalarValue"); })).toEqual({ result: 2511, trace: ["B get"] }); + var base = TNSSwizzleSuperBase.new(); + base.scalarValue = 5; + expect([base.storedScalarValue(), base.valueForKey("scalarValue")]).toEqual([51, 511]); }); }); }); From c6a11a22f95ceff0a63631d3e0c1b1f2bf84d959 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 15 Nov 2026 19:06:16 -0300 Subject: [PATCH 7/8] fix(runtime): give every swizzled class its own alias A class that only inherits a member below a replaced ancestor got no alias of its own. A second replacement on that class then saw the first JS replacement as the class's own implementation and registered it as the alias, so the first replacement's original resolved back to itself and recursed. Such a class now gets an alias for the implementation behind the ancestor's alias on its first replacement, which later replacements keep. --- NativeScript/runtime/MetadataBuilder.mm | 23 +++++---- TestFixtures/Api/TNSApi.h | 17 +++++++ TestFixtures/Api/TNSApi.m | 19 ++++++++ .../app/tests/JSAccessorEncodingTests.js | 48 +++++++++++++++++++ 4 files changed, 95 insertions(+), 12 deletions(-) diff --git a/NativeScript/runtime/MetadataBuilder.mm b/NativeScript/runtime/MetadataBuilder.mm index bbdab6f32..cac616fd7 100644 --- a/NativeScript/runtime/MetadataBuilder.mm +++ b/NativeScript/runtime/MetadataBuilder.mm @@ -1368,21 +1368,20 @@ CMethodCall methodCall(context, item->userData_, typeEncoding, args, namespace { -// The implementation `klass` answered `selector` with stays reachable under -// the swizzled-prefixed selector that native calls from JS prefer; an alias -// `klass` already has is kept, so it names the one from before the first -// replacement. A class that inherits `selector` and already responds to the -// alias, because an ancestor was replaced, gets none of its own: an own alias -// naming a native override that calls super would send the replaced -// ancestor's original back to that override. +// The native implementation `klass` answered `selector` with stays reachable +// under the swizzled-prefixed selector that native calls from JS prefer. A +// class that only inherits `selector` below a replaced ancestor takes that +// ancestor's alias: its selector resolves to the ancestor's JS replacement, +// and an alias naming a native override in between would be re-entered when +// that override calls super. Every replaced class gets an alias of its own, +// which a later replacement keeps, so it never names an earlier replacement. void ReplaceKeepingOriginal(Class klass, SEL selector, const char* selectorName, IMP imp, const char* types) { SEL alias = sel_registerName((Constants::SwizzledPrefix + selectorName).c_str()); - IMP original = nullptr; - if (ClassBuilder::ImplementsItself(klass, selector) || !class_respondsToSelector(klass, alias)) { - Method method = class_getInstanceMethod(klass, selector); - original = method != nullptr ? method_getImplementation(method) : nullptr; - } + bool inheritsAlias = + !ClassBuilder::ImplementsItself(klass, selector) && class_respondsToSelector(klass, alias); + Method method = class_getInstanceMethod(klass, inheritsAlias ? alias : selector); + IMP original = method != nullptr ? method_getImplementation(method) : nullptr; class_replaceMethod(klass, selector, imp, types); if (original != nullptr) { class_addMethod(klass, alias, original, types); diff --git a/TestFixtures/Api/TNSApi.h b/TestFixtures/Api/TNSApi.h index 2da4d1619..3c82b9a20 100644 --- a/TestFixtures/Api/TNSApi.h +++ b/TestFixtures/Api/TNSApi.h @@ -179,6 +179,23 @@ typedef NSError* _Nullable TNSNullableError; - (NSString*)describeValue:(int)value; @end +@interface TNSSwizzleRepeatBase : NSObject +@property(nonatomic, strong) id objectValue; +@property(nonatomic) NSInteger scalarValue; +- (id)describeValue:(int)value; +- (id)storedObjectValue; +- (NSInteger)storedScalarValue; +@end + +@interface TNSSwizzleRepeatDerived : TNSSwizzleRepeatBase +@end + +@interface TNSSwizzleRepeatDerived (Redeclared) +@property(nonatomic, strong) NSString* objectValue; +@property(nonatomic) TNSEnums scalarValue; +- (NSString*)describeValue:(int)value; +@end + @interface TNSSwizzleMiddleBase : NSObject @property(nonatomic, strong) id objectValue; @property(nonatomic) NSInteger scalarValue; diff --git a/TestFixtures/Api/TNSApi.m b/TestFixtures/Api/TNSApi.m index 6a0e8aebb..fcdc6eafc 100644 --- a/TestFixtures/Api/TNSApi.m +++ b/TestFixtures/Api/TNSApi.m @@ -192,6 +192,25 @@ - (NSInteger)storedScalarValue { @implementation TNSSwizzleReverseDerived @end +@implementation TNSSwizzleRepeatBase + +- (id)describeValue:(int)value { + return [NSString stringWithFormat:@"base %d", value]; +} + +- (id)storedObjectValue { + return _objectValue; +} + +- (NSInteger)storedScalarValue { + return _scalarValue; +} + +@end + +@implementation TNSSwizzleRepeatDerived +@end + @implementation TNSSwizzleMiddleBase - (id)describeValue:(int)value { diff --git a/TestRunner/app/tests/JSAccessorEncodingTests.js b/TestRunner/app/tests/JSAccessorEncodingTests.js index 357acbbf4..5c944de2d 100644 --- a/TestRunner/app/tests/JSAccessorEncodingTests.js +++ b/TestRunner/app/tests/JSAccessorEncodingTests.js @@ -504,6 +504,54 @@ describe("JS-implemented native property accessors", function () { }); }); + // The subclass's second replacement finds the first one as its + // original, and the first one still finds the native members. + describe("the superclass once, then the subclass twice", function () { + var install = installer(function () { + return { + base: replaceMembers(TNSSwizzleRepeatBase, "B", 1), + first: replaceMembers(TNSSwizzleRepeatDerived, "D", 2), + second: replaceMembers(TNSSwizzleRepeatDerived, "E", 3) + }; + }); + + it("reach the native method through both of the subclass's replacements", function () { + var originals = install(); + var derived = TNSSwizzleRepeatDerived.new(); + expect(traced(function () { return derived.describeValue(1); })).toEqual({ result: "E(D(base 1))", trace: ["E", "D"] }); + expect(traced(function () { return originals.first.describe.call(derived, 2); })).toEqual({ result: "base 2", trace: [] }); + expect(traced(function () { return originals.base.describe.call(derived, 3); })).toEqual({ result: "base 3", trace: [] }); + expect(traced(function () { return TNSSwizzleRepeatBase.new().describeValue(4); })).toEqual({ result: "B(base 4)", trace: ["B"] }); + }); + + it("reach the native accessors of an object property through both of the subclass's replacements", function () { + var originals = install(); + var derived = TNSSwizzleRepeatDerived.new(); + expect(traced(function () { derived.objectValue = "x"; return derived.storedObjectValue(); })) + .toEqual({ result: "D(E(x))", trace: ["E set", "D set"] }); + expect(traced(function () { return derived.objectValue; })).toEqual({ result: "E(D(D(E(x))))", trace: ["E get", "D get"] }); + expect(traced(function () { return derived.valueForKey("objectValue"); })).toEqual({ result: "E(D(D(E(x))))", trace: ["E get", "D get"] }); + expect(traced(function () { return originals.first.object.get.call(derived); })).toEqual({ result: "D(E(x))", trace: [] }); + expect(traced(function () { return originals.base.object.get.call(derived); })).toEqual({ result: "D(E(x))", trace: [] }); + var base = TNSSwizzleRepeatBase.new(); + base.objectValue = "y"; + expect([base.storedObjectValue(), base.valueForKey("objectValue")]).toEqual(["B(y)", "B(B(y))"]); + }); + + it("reach the native accessors of a scalar property through both of the subclass's replacements", function () { + var originals = install(); + var derived = TNSSwizzleRepeatDerived.new(); + expect(traced(function () { derived.scalarValue = 5; return derived.storedScalarValue(); })) + .toEqual({ result: 532, trace: ["E set", "D set"] }); + expect(traced(function () { return derived.valueForKey("scalarValue"); })).toEqual({ result: 53223, trace: ["E get", "D get"] }); + expect(traced(function () { return originals.first.scalar.get.call(derived); })).toEqual({ result: 532, trace: [] }); + expect(traced(function () { return originals.base.scalar.get.call(derived); })).toEqual({ result: 532, trace: [] }); + var base = TNSSwizzleRepeatBase.new(); + base.scalarValue = 5; + expect([base.storedScalarValue(), base.valueForKey("scalarValue")]).toEqual([51, 511]); + }); + }); + // TNSSwizzleMiddle overrides every member natively, between the // replaced superclass and the replaced leaf. The leaf's originals run // the superclass's native members, not the middle class's overrides. From d07572f451b2caf4b9c7bb2923c85f0356abd905 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 15 Nov 2026 22:14:23 -0300 Subject: [PATCH 8/8] fix(runtime): keep the own-method check from resolving, and array elements from expanding pointees ImplementsItself used class_getInstanceMethod, which asks the class to resolve a selector nothing implements. For a class still being built by extend() that ran +resolveInstanceMethod: and +initialize early. It reads the class's own method list now. The encoder passed its pointee-expansion flag on to array elements, so an array of struct pointers expanded the struct where clang writes its name only. --- NativeScript/runtime/ClassBuilder.mm | 18 +++++++++++---- .../app/tests/JSAccessorEncodingTests.js | 23 +++++++++++++++++++ 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/NativeScript/runtime/ClassBuilder.mm b/NativeScript/runtime/ClassBuilder.mm index 79301896c..0605ff4ef 100644 --- a/NativeScript/runtime/ClassBuilder.mm +++ b/NativeScript/runtime/ClassBuilder.mm @@ -538,7 +538,7 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { std::stringstream ss; ss << "["; ss << typeEncoding->details.constantArray.size - << GetTypeEncoding(innerType, encodable, expandStructures, expandPointedToStructures); + << GetTypeEncoding(innerType, encodable, expandStructures, false); ss << "]"; return ss.str(); } @@ -546,7 +546,7 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { const TypeEncoding* innerType = typeEncoding->details.incompleteArray.getInnerType(); std::stringstream ss; ss << "^"; - ss << GetTypeEncoding(innerType, encodable, expandPointedToStructures, false); + ss << GetTypeEncoding(innerType, encodable, expandStructures, false); return ss.str(); } case BinaryTypeEncodingType::FunctionPointerEncoding: { @@ -907,10 +907,18 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { } } +// Reads the class's own method list: class_getInstanceMethod asks the class to +// resolve a selector nothing implements, which initializes a class that is +// still being built. bool ClassBuilder::ImplementsItself(Class klass, SEL selector) { - Method method = class_getInstanceMethod(klass, selector); - return method != nullptr && - method != class_getInstanceMethod(class_getSuperclass(klass), selector); + unsigned int count = 0; + Method* methods = class_copyMethodList(klass, &count); + bool found = false; + for (unsigned int i = 0; i < count && !found; i++) { + found = method_getName(methods[i]) == selector; + } + free(methods); + return found; } void ClassBuilder::ExposeProperties(Isolate* isolate, Class extendedClass, diff --git a/TestRunner/app/tests/JSAccessorEncodingTests.js b/TestRunner/app/tests/JSAccessorEncodingTests.js index 5c944de2d..89aedff0f 100644 --- a/TestRunner/app/tests/JSAccessorEncodingTests.js +++ b/TestRunner/app/tests/JSAccessorEncodingTests.js @@ -339,6 +339,29 @@ describe("JS-implemented native property accessors", function () { expect([base.storedScalarValue(), base.scalarValue, base.valueForKey("scalarValue")]).toEqual([7, 7, 7]); }); + it("reach the replacement and then the inherited implementation from a JS subclass calling super", function () { + install(); + var Klass = TNSInheritedSwizzleDerived.extend({ + describeValue: function (value) { + return "sub " + this.super.describeValue(value); + }, + get objectValue() { + return "sub " + this.super.objectValue; + }, + set objectValue(value) { + this.super.objectValue = value + "?"; + } + }, { name: "JSAccessorEncodingSwizzledSuper" }); + var obj = Klass.new(); + expect(obj.describeValue(6)).toBe("sub js base 6"); + obj.objectValue = "a"; + expect(obj.storedObjectValue()).toBe("a?!"); + expect(obj.objectValue).toBe("sub js a?!"); + expect(obj.valueForKey("objectValue")).toBe("sub js a?!"); + obj.setValueForKey("b", "objectValue"); + expect(obj.storedObjectValue()).toBe("b?!"); + }); + it("reach the inherited accessors after a second replacement", function () { var proto = TNSInheritedSwizzleTwice.prototype; var original = inheritedDescriptor(proto, "scalarValue");