From 08c3eb05e40e1aee1e1aea53d7cd222665de8e12 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 15 Nov 2026 17:16:59 -0300 Subject: [PATCH 1/6] refactor(runtime): share the native callback receiver lookup Native code calling into JS on an object needs the object's JS wrapper as `this`: the cached one, or a new one made through WrapNativeCallbackSelf, which is borrowed (uncached, non-owning) when the object is already in -dealloc and must be detached once the call returns. MethodCallback did this inline with a file-local BorrowedSelfScope. Move it into NativeCallbackSelf, a scoped helper the other native-to-JS entry points can use, so they get the same lookup, the same -dealloc handling and the same detach instead of their own variants. No behaviour change. --- NativeScript/runtime/ArgConverter.h | 18 ++++++++++ NativeScript/runtime/ArgConverter.mm | 49 ++++++++++++++-------------- 2 files changed, 42 insertions(+), 25 deletions(-) diff --git a/NativeScript/runtime/ArgConverter.h b/NativeScript/runtime/ArgConverter.h index 7e39661f2..8201184da 100644 --- a/NativeScript/runtime/ArgConverter.h +++ b/NativeScript/runtime/ArgConverter.h @@ -166,6 +166,24 @@ class ArgConverter { void** argValues, void* userData); }; +// The JS receiver for a native-to-JS callback on `self`: the cached wrapper, +// or a new one (borrowed and detached on scope exit when `self` is in +// -dealloc). Live only inside the callback's V8 scopes, and destroyed before +// anything is @thrown out of the callback. +class NativeCallbackSelf { + public: + NativeCallbackSelf(v8::Local context, id self); + ~NativeCallbackSelf(); + NativeCallbackSelf(const NativeCallbackSelf&) = delete; + NativeCallbackSelf& operator=(const NativeCallbackSelf&) = delete; + v8::Local Get() const { return receiver_; } + + private: + v8::Isolate* isolate_; + v8::Local receiver_; + ObjCDataWrapper* borrowed_ = nullptr; +}; + } // namespace tns #endif /* ArgConverter_h */ diff --git a/NativeScript/runtime/ArgConverter.mm b/NativeScript/runtime/ArgConverter.mm index 48119c939..a10564b44 100644 --- a/NativeScript/runtime/ArgConverter.mm +++ b/NativeScript/runtime/ArgConverter.mm @@ -1,6 +1,7 @@ #include "ArgConverter.h" #include #include +#include #include #include "ClassBuilder.h" #include "DictionaryAdapter.h" @@ -48,23 +49,27 @@ bool InMethodFamily(SEL selector, const char* family) { return strncmp(name, family, length) == 0 && (name[length] < 'a' || name[length] > 'z'); } -// The borrowed wrapper WrapNativeCallbackSelf made for an object in -dealloc -// is detached once the native call returns: the object is gone afterwards, -// so a receiver JS kept must read as released. -struct BorrowedSelfScope { - explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {} - ~BorrowedSelfScope() { - if (wrapper != nullptr && tns::GetValue(isolate, receiver) == wrapper) { - tns::SetValue(isolate, receiver, nullptr); - delete wrapper; - } +} // namespace + +NativeCallbackSelf::NativeCallbackSelf(Local context, id self) + : isolate_(v8::Isolate::GetCurrent()) { + auto cache = Caches::Get(isolate_); + auto it = cache->Instances.find(self); + if (it != cache->Instances.end()) { + receiver_ = it->second->Get(isolate_).As(); + } else { + receiver_ = ArgConverter::WrapNativeCallbackSelf(context, self, &borrowed_); } - Isolate* isolate; - Local receiver; - ObjCDataWrapper* wrapper = nullptr; -}; +} -} // namespace +// The object is gone once the native call returns, so a borrowed receiver JS +// kept must read as released. +NativeCallbackSelf::~NativeCallbackSelf() { + if (borrowed_ != nullptr && tns::GetValue(isolate_, receiver_) == borrowed_) { + tns::SetValue(isolate_, receiver_, nullptr); + delete borrowed_; + } +} void ArgConverter::Init(Local context) { Isolate* isolate = v8::Isolate::GetCurrent(); @@ -405,18 +410,12 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {} } } - Local thiz = context->Global(); - BorrowedSelfScope borrowedSelf(isolate); + // Blocks and C function pointers have no receiver. + std::optional receiver; if (data->initialParamIndex_ > 1) { - id self_ = *static_cast(argValues[0]); - auto it = cache->Instances.find(self_); - if (it != cache->Instances.end()) { - thiz = it->second->Get(data->isolateWrapper_.Isolate()).As(); - } else { - thiz = ArgConverter::WrapNativeCallbackSelf(context, self_, &borrowedSelf.wrapper); - borrowedSelf.receiver = thiz; - } + receiver.emplace(context, *static_cast(argValues[0])); } + Local thiz = receiver ? receiver->Get() : context->Global(); Local result; Local callback = poCallback->Get(isolate).As(); From 58d5d5ceef6b8a722d413e75904da73279f5c94e Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 15 Nov 2026 17:20:14 -0300 Subject: [PATCH 2/6] fix(runtime): run JS property accessors on the instance native code called When native code read or wrote a property that a JS subclass implements (through .extend() or a TypeScript class) on an instance JS had no wrapper for yet, the accessor ran with `this` bound to the class's implementation object, shared by every instance. A getter reading per-instance state saw the wrong object, and a setter wrote its state where every other instance of the class would read it. This is the common case for objects native code creates itself (cells, views, delegates made by a framework). Bind `this` through NativeCallbackSelf, as JS-implemented methods already do: the cached wrapper, or a new one that keeps the instance's JS state while native code holds the object, and a borrowed, detached one when the accessor runs from the object's own -dealloc. The implementation-object fallback dates from the first version of these accessors, which always ran on the implementation object; it never stood for a class-side receiver: the accessors are installed on the extended class only and are looked up among instance properties, so the receiver is always an instance. With the fallback gone the implementation object is no longer stored in PropertyCallbackContext. Both lambdas now also enter the context before making the receiver, as MethodCallback does. --- NativeScript/runtime/ClassBuilder.h | 8 +- NativeScript/runtime/ClassBuilder.mm | 36 +- NativeScript/runtime/MetadataBuilder.mm | 4 +- TestFixtures/Marshalling/TNSAllocLog.h | 38 ++ TestFixtures/Marshalling/TNSAllocLog.m | 82 +++++ .../app/tests/JSAccessorReceiverTests.js | 325 ++++++++++++++++++ TestRunner/app/tests/index.js | 1 + 7 files changed, 460 insertions(+), 34 deletions(-) create mode 100644 TestRunner/app/tests/JSAccessorReceiverTests.js diff --git a/NativeScript/runtime/ClassBuilder.h b/NativeScript/runtime/ClassBuilder.h index d6a353279..3e298d3c6 100644 --- a/NativeScript/runtime/ClassBuilder.h +++ b/NativeScript/runtime/ClassBuilder.h @@ -11,15 +11,10 @@ struct PropertyCallbackContext { PropertyCallbackContext( v8::Isolate* isolate, std::shared_ptr> callback, - std::shared_ptr> implementationObject, const PropertyMeta* meta) - : isolate_(isolate), - callback_(callback), - implementationObject_(implementationObject), - meta_(meta) {} + : isolate_(isolate), callback_(callback), meta_(meta) {} v8::Isolate* isolate_; std::shared_ptr> callback_; - std::shared_ptr> implementationObject_; const PropertyMeta* meta_; }; @@ -70,7 +65,6 @@ class ClassBuilder { std::vector exposedProtocols); static void ExposeProperties(v8::Isolate* isolate, Class extendedClass, std::vector propertyMetas, - v8::Local implementationObject, v8::Local getter, v8::Local setter); static std::string GetTypeEncoding(const TypeEncoding* typeEncoding); diff --git a/NativeScript/runtime/ClassBuilder.mm b/NativeScript/runtime/ClassBuilder.mm index 47c77ea43..0a28d04c9 100644 --- a/NativeScript/runtime/ClassBuilder.mm +++ b/NativeScript/runtime/ClassBuilder.mm @@ -772,7 +772,7 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { (getter->IsFunction() || setter->IsFunction())) { std::vector propertyMetas; VisitProperties(methodName, extendedClassMeta, propertyMetas, protocols); - ExposeProperties(isolate, extendedClass, propertyMetas, implementationObject, getter, setter); + ExposeProperties(isolate, extendedClass, propertyMetas, getter, setter); continue; } @@ -885,8 +885,7 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { void ClassBuilder::ExposeProperties(Isolate* isolate, Class extendedClass, std::vector propertyMetas, - Local implementationObject, Local getter, - Local setter) { + Local getter, Local setter) { for (int j = 0; j < propertyMetas.size(); j++) { const PropertyMeta* propertyMeta = propertyMetas[j]; std::string propertyName = propertyMeta->name(); @@ -894,16 +893,11 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { bool hasGetter = !getter.IsEmpty() && getter->IsFunction() && propertyMeta->hasGetter(); bool hasSetter = !setter.IsEmpty() && setter->IsFunction() && propertyMeta->hasSetter(); - std::shared_ptr> poImplementationObject; - if (hasGetter || hasSetter) { - poImplementationObject = std::make_shared>(isolate, implementationObject); - } - if (hasGetter) { std::shared_ptr> poGetterFunc = std::make_shared>(isolate, getter.As()); PropertyCallbackContext* userData = - new PropertyCallbackContext(isolate, poGetterFunc, poImplementationObject, propertyMeta); + new PropertyCallbackContext(isolate, poGetterFunc, propertyMeta); FFIMethodCallback getterCallback = [](ffi_cif* cif, void* retValue, void** argValues, void* userData) { @@ -919,15 +913,11 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { Local getterFunc = context->callback_->Get(isolate); Local res; - id thiz = *static_cast(argValues[0]); - auto cache = Caches::Get(isolate); - auto it = cache->Instances.find(thiz); - Local self_ = it != cache->Instances.end() - ? it->second->Get(isolate).As() - : context->implementationObject_->Get(isolate); Local v8Context = Caches::Get(isolate)->GetContext(); + Context::Scope context_scope(v8Context); + NativeCallbackSelf receiver(v8Context, *static_cast(argValues[0])); TryCatch tc(isolate); - if (!getterFunc->Call(v8Context, self_, 0, nullptr).ToLocal(&res)) { + if (!getterFunc->Call(v8Context, receiver.Get(), 0, nullptr).ToLocal(&res)) { NSException* ex = ArgConverter::HandleBoundaryException(v8Context, tc); if (ex != nil) { pendingThrow = ex; @@ -958,7 +948,7 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { std::shared_ptr> poSetterFunc = std::make_shared>(isolate, setter.As()); PropertyCallbackContext* userData = - new PropertyCallbackContext(isolate, poSetterFunc, poImplementationObject, propertyMeta); + new PropertyCallbackContext(isolate, poSetterFunc, propertyMeta); FFIMethodCallback setterCallback = [](ffi_cif* cif, void* retValue, void** argValues, void* userData) { @@ -972,22 +962,18 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { Local setterFunc = context->callback_->Get(isolate); Local res; - id thiz = *static_cast(argValues[0]); - auto cache = Caches::Get(isolate); - auto it = cache->Instances.find(thiz); - Local self_ = it != cache->Instances.end() - ? it->second->Get(isolate).As() - : context->implementationObject_->Get(isolate); + Local v8Context = Caches::Get(isolate)->GetContext(); + Context::Scope context_scope(v8Context); + NativeCallbackSelf receiver(v8Context, *static_cast(argValues[0])); uint8_t* argBuffer = (uint8_t*)argValues[2]; const TypeEncoding* typeEncoding = context->meta_->setter()->encodings()->first()->next(); BaseCall call(argBuffer); - Local v8Context = Caches::Get(isolate)->GetContext(); Local jsWrapper = Interop::GetResult(v8Context, typeEncoding, &call, true); Local params[1] = {jsWrapper}; TryCatch tc(isolate); - if (!setterFunc->Call(v8Context, self_, 1, params).ToLocal(&res)) { + if (!setterFunc->Call(v8Context, receiver.Get(), 1, params).ToLocal(&res)) { NSException* ex = ArgConverter::HandleBoundaryException(v8Context, tc); if (ex != nil) { pendingThrow = ex; diff --git a/NativeScript/runtime/MetadataBuilder.mm b/NativeScript/runtime/MetadataBuilder.mm index c27caa1ba..2ebd330c9 100644 --- a/NativeScript/runtime/MetadataBuilder.mm +++ b/NativeScript/runtime/MetadataBuilder.mm @@ -1500,7 +1500,7 @@ CMethodCall methodCall(context, item->userData_, typeEncoding, args, std::shared_ptr> poGetterFunc = std::make_shared>(isolate, getter.As()); PropertyCallbackContext* userData = - new PropertyCallbackContext(isolate, poGetterFunc, nullptr, propertyMeta); + new PropertyCallbackContext(isolate, poGetterFunc, propertyMeta); IMP impGetter = Interop::CreateMethod(2, 0, typeEncoding, getterCallback, userData); IMP nativeImp = class_replaceMethod(klass, propertyMeta->getter()->selector(), impGetter, compilerEncoding); @@ -1563,7 +1563,7 @@ CMethodCall methodCall(context, item->userData_, typeEncoding, args, std::shared_ptr> poSetterFunc = std::make_shared>(isolate, setter.As()); PropertyCallbackContext* userData = - new PropertyCallbackContext(isolate, poSetterFunc, nullptr, propertyMeta); + new PropertyCallbackContext(isolate, poSetterFunc, propertyMeta); IMP impSetter = Interop::CreateMethod(2, 1, typeEncoding, setterCallback, userData); const char* compilerEncoding = "v@:@"; diff --git a/TestFixtures/Marshalling/TNSAllocLog.h b/TestFixtures/Marshalling/TNSAllocLog.h index e425fe7d3..0be837b40 100644 --- a/TestFixtures/Marshalling/TNSAllocLog.h +++ b/TestFixtures/Marshalling/TNSAllocLog.h @@ -117,4 +117,42 @@ id TNSOwnedPrimitivesObjectAt(TNSOwnedPrimitives* holder, NSUInteger index); @end +// JS subclasses implement `value`; `name` is state native code sets. +@interface TNSAccessorHost : TNSAllocLog + +@property(nonatomic, strong) id value; +@property(nonatomic, copy) NSString* name; + +@end + +// -dealloc reads `value`. +@interface TNSAccessorDeallocHost : TNSAccessorHost + +@end + +// Reaches the `value` accessors of the host it keeps through compiled property +// access only. +@interface TNSAccessorDriver : NSObject + +// Keeps a new instance of `cls`, created natively and named `name`. +- (instancetype)initWithNewHostOf:(Class)cls name:(NSString*)name; +- (instancetype)initWithHost:(TNSAccessorHost*)host; +- (id)readValue; +- (void)writeValue:(id)value; +- (TNSAccessorHost*)host; +- (void)dropHost; + +// Creates an instance of `cls` named `name`, reads its `value` and drops it. ++ (id)valueOfNewHostOf:(Class)cls name:(NSString*)name; +// Creates an instance of `cls` named `name` and drops it. ++ (void)dropNewHostOf:(Class)cls name:(NSString*)name; + +// A process-wide host, kept until +dropKeptHost. ++ (void)keepNewHostOf:(Class)cls name:(NSString*)name; ++ (id)readKeptValue; ++ (void)writeKeptValue:(id)value; ++ (void)dropKeptHost; + +@end + #endif /* TNSAllocLog_h */ diff --git a/TestFixtures/Marshalling/TNSAllocLog.m b/TestFixtures/Marshalling/TNSAllocLog.m index dde24b773..44e5148c9 100644 --- a/TestFixtures/Marshalling/TNSAllocLog.m +++ b/TestFixtures/Marshalling/TNSAllocLog.m @@ -254,3 +254,85 @@ - (void)initHook { } @end + +@implementation TNSAccessorHost +@end + +@implementation TNSAccessorDeallocHost + +- (void)dealloc { + id value = self.value; + (void)value; +} + +@end + +static TNSAccessorHost* keptAccessorHost; + +@implementation TNSAccessorDriver { + TNSAccessorHost* _host; +} + +- (instancetype)initWithNewHostOf:(Class)cls name:(NSString*)name { + self = [super init]; + if (self) { + _host = [[cls alloc] init]; + _host.name = name; + } + return self; +} + +- (instancetype)initWithHost:(TNSAccessorHost*)host { + self = [super init]; + if (self) { + _host = host; + } + return self; +} + +- (id)readValue { + return _host.value; +} + +- (void)writeValue:(id)value { + _host.value = value; +} + +- (TNSAccessorHost*)host { + return _host; +} + +- (void)dropHost { + _host = nil; +} + ++ (id)valueOfNewHostOf:(Class)cls name:(NSString*)name { + TNSAccessorHost* host = [[cls alloc] init]; + host.name = name; + return host.value; +} + ++ (void)dropNewHostOf:(Class)cls name:(NSString*)name { + TNSAccessorHost* host = [[cls alloc] init]; + host.name = name; +} + ++ (void)keepNewHostOf:(Class)cls name:(NSString*)name { + TNSAccessorHost* host = [[cls alloc] init]; + host.name = name; + keptAccessorHost = host; +} + ++ (id)readKeptValue { + return keptAccessorHost.value; +} + ++ (void)writeKeptValue:(id)value { + keptAccessorHost.value = value; +} + ++ (void)dropKeptHost { + keptAccessorHost = nil; +} + +@end diff --git a/TestRunner/app/tests/JSAccessorReceiverTests.js b/TestRunner/app/tests/JSAccessorReceiverTests.js new file mode 100644 index 000000000..971a52311 --- /dev/null +++ b/TestRunner/app/tests/JSAccessorReceiverTests.js @@ -0,0 +1,325 @@ +const { raisesGlobalErrors } = require("../Infrastructure/Jasmine/globalErrorSpy"); + +// JS accessors of native properties run with `this` bound to the instance +// native code called them on, whether or not JS had a wrapper for it yet. +describe("JS accessor receivers", function () { + function scrub(n) { + return n > 0 ? scrub(n - 1) + n : 0; + } + + // Collect, then give autorelease pools and posted retain/release work a + // turn of the run loop. + function settle(rounds, callback) { + scrub(300); + __collect(); + __collect(); + setTimeout(function () { + NSObject.new(); + if (rounds > 1) { + settle(rounds - 1, callback); + } else { + callback(); + } + }, 10); + } + + function deallocs() { + return (TNSGetOutput().match(/TNSAllocLog dealloc/g) || []).length; + } + + function hasOwn(object, key) { + return Object.prototype.hasOwnProperty.call(object, key); + } + + // `record.lastThis` is the receiver of the latest accessor call; + // `record.onGet` runs inside the getter; `record.throws` makes both + // accessors throw an Error with that message. + function accessors(record) { + return { + get: function () { + record.lastThis = this; + if (record.onGet) { + record.onGet(this); + } + if (record.throws) { + throw new Error(record.throws); + } + return this._stored !== undefined ? this._stored : "name:" + this.name; + }, + set: function (value) { + record.lastThis = this; + if (record.throws) { + throw new Error(record.throws); + } + this._stored = value; + } + }; + } + + function defineWithExtend(name, Base) { + var record = {}; + var body = {}; + Object.defineProperty(body, "value", Object.assign({ enumerable: true, configurable: true }, accessors(record))); + var Klass = Base.extend(body, { name: name }); + return { Klass: Klass, record: record, implementation: Object.getPrototypeOf(Klass.prototype) }; + } + + function defineWithTypeScript(Base) { + var record = {}; + var Klass = (function (_super) { + __extends(JSAccessorReceiverTSHost, _super); + function JSAccessorReceiverTSHost() { + return (_super !== null && _super.apply(this, arguments)) || this; + } + // Only enumerable accessors are exposed to native code. + Object.defineProperty(JSAccessorReceiverTSHost.prototype, "value", Object.assign({ enumerable: true, configurable: true }, accessors(record))); + return JSAccessorReceiverTSHost; + })(Base); + return { Klass: Klass, record: record, implementation: Klass.prototype }; + } + + // Neither the implementation object nor the prototype between it and the + // instances ever holds per-instance state. + function expectNoSharedState(def) { + expect(hasOwn(def.implementation, "_stored")).toBe(false); + expect(hasOwn(def.Klass.prototype, "_stored")).toBe(false); + expect(hasOwn(Object.getPrototypeOf(def.Klass.prototype), "_stored")).toBe(false); + } + + beforeEach(function (done) { + settle(2, function () { + TNSClearOutput(); + done(); + }); + }); + + var variants = [ + { + suffix: " (extend)", + define: function (tag, Base) { + return defineWithExtend("JSAccessorReceiver" + tag, Base || TNSAccessorHost); + } + }, + { + suffix: " (__extends)", + define: function (tag, Base) { + return defineWithTypeScript(Base || TNSAccessorHost); + } + } + ]; + + variants.forEach(function (variant) { + it("runs a getter read natively on a never-wrapped instance on that instance" + variant.suffix, function () { + var def = variant.define("Read"); + var cls = def.Klass.class(); + expect(TNSAccessorDriver.valueOfNewHostOfName(cls, "first")).toBe("name:first"); + expect(TNSAccessorDriver.valueOfNewHostOfName(cls, "second")).toBe("name:second"); + expect(def.record.lastThis).not.toBe(def.implementation); + expectNoSharedState(def); + def.record.lastThis = null; + }); + + it("stores what a setter called natively on a never-wrapped instance writes on that instance" + variant.suffix, function () { + var def = variant.define("Write"); + var cls = def.Klass.class(); + var first = TNSAccessorDriver.alloc().initWithNewHostOfName(cls, "first"); + var second = TNSAccessorDriver.alloc().initWithNewHostOfName(cls, "second"); + first.writeValue("written-first"); + expect(first.readValue()).toBe("written-first"); + expect(second.readValue()).toBe("name:second"); + second.writeValue("written-second"); + expect(first.readValue()).toBe("written-first"); + expect(second.readValue()).toBe("written-second"); + expectNoSharedState(def); + + var host = first.host(); + expect(host._stored).toBe("written-first"); + expect(host.value).toBe("written-first"); + expect(host.name).toBe("first"); + def.record.lastThis = null; + }); + + it("binds this in a native accessor call to the object JS later gets for that instance" + variant.suffix, function () { + var def = variant.define("Identity"); + var driver = TNSAccessorDriver.alloc().initWithNewHostOfName(def.Klass.class(), "identity"); + def.record.onGet = function (self) { + self.seenInGetter = true; + }; + expect(driver.readValue()).toBe("name:identity"); + var receiver = def.record.lastThis; + var host = driver.host(); + expect(receiver).toBe(host); + expect(host instanceof def.Klass).toBe(true); + expect(host.seenInGetter).toBe(true); + expect(hasOwn(def.implementation, "seenInGetter")).toBe(false); + def.record.lastThis = null; + }); + + it("keeps an instance an accessor call wrapped first while native code holds it, then frees it once" + variant.suffix, function (done) { + var def = variant.define("Lifetime"); + var driver = TNSAccessorDriver.alloc().initWithNewHostOfName(def.Klass.class(), "kept"); + driver.writeValue("kept-value"); + def.record.lastThis = null; + settle(3, function () { + expect(deallocs()).toBe(0); + expect(driver.readValue()).toBe("kept-value"); + def.record.lastThis = null; + (function () { + var host = driver.host(); + expect(host._stored).toBe("kept-value"); + })(); + driver.dropHost(); + settle(3, function () { + expect(deallocs()).toBe(1); + expectNoSharedState(def); + done(); + }); + }); + }); + + it("frees once an instance whose only accessor call happened inside a native method" + variant.suffix, function (done) { + var def = variant.define("Transient"); + expect(TNSAccessorDriver.valueOfNewHostOfName(def.Klass.class(), "transient")).toBe("name:transient"); + def.record.lastThis = null; + settle(3, function () { + expect(deallocs()).toBe(1); + done(); + }); + }); + + it("runs accessors of an instance JS already holds on its existing wrapper" + variant.suffix, function () { + var def = variant.define("Existing"); + var host = def.Klass.alloc().init(); + host.name = "existing"; + var driver = TNSAccessorDriver.alloc().initWithHost(host); + expect(driver.readValue()).toBe("name:existing"); + expect(def.record.lastThis).toBe(host); + driver.writeValue("existing-value"); + expect(def.record.lastThis).toBe(host); + expect(host._stored).toBe("existing-value"); + expect(driver.readValue()).toBe("existing-value"); + expectNoSharedState(def); + def.record.lastThis = null; + }); + + it("reports a receiver kept from a getter run by -dealloc as released" + variant.suffix, function (done) { + var def = variant.define("Dealloc", TNSAccessorDeallocHost); + var nameInDealloc; + def.record.onGet = function (self) { + nameInDealloc = self.name; + }; + TNSAccessorDriver.dropNewHostOfName(def.Klass.class(), "dying"); + var saved = def.record.lastThis; + def.record.lastThis = null; + expect(saved).toBeDefined(); + expect(saved).not.toBe(def.implementation); + expect(nameInDealloc).toBe("dying"); + expect(deallocs()).toBe(1); + settle(3, function () { + var value; + var error = null; + try { + value = saved.hash; + } catch (e) { + error = e; + } + if (error !== null) { + expect(error.message).toContain("disposed native object"); + } else { + expect(value).toBeUndefined(); + } + saved = null; + expect(deallocs()).toBe(1); + done(); + }); + }); + }); + + describe("that throw", function () { + var previousHook; + var uncaught; + + beforeEach(function () { + previousHook = global.__onUncaughtError; + uncaught = []; + global.__onUncaughtError = function (error) { + uncaught.push(error); + }; + }); + + afterEach(function () { + global.__onUncaughtError = previousHook; + }); + + function uncaughtCount(message) { + return uncaught.filter(function (e) { + return e && String(e.message !== undefined ? e.message : e).indexOf(message) > -1; + }).length; + } + + function pollUntil(predicate, callback) { + var turns = 0; + (function poll() { + if (predicate() || turns >= 25) { + callback(); + return; + } + turns++; + setTimeout(poll, 10); + })(); + } + + variants.forEach(function (variant) { + it("report the error, answer nil and leave the instance to be freed once" + variant.suffix, raisesGlobalErrors(function (done) { + var def = variant.define("Throws"); + var driver = TNSAccessorDriver.alloc().initWithNewHostOfName(def.Klass.class(), "throws"); + def.record.throws = "accessor-receiver-boom"; + expect(driver.readValue()).toBeNull(); + driver.writeValue("ignored"); + var receiver = def.record.lastThis; + def.record.lastThis = null; + def.record.throws = null; + expect(receiver).toBe(driver.host()); + receiver = null; + expect(driver.readValue()).toBe("name:throws"); + def.record.lastThis = null; + expectNoSharedState(def); + pollUntil(function () { return uncaughtCount("accessor-receiver-boom") >= 2; }, function () { + expect(uncaughtCount("accessor-receiver-boom")).toBe(2); + driver.dropHost(); + settle(3, function () { + expect(deallocs()).toBe(1); + done(); + }); + }); + })); + + it("report the error of a getter run by -dealloc and detach its receiver" + variant.suffix, raisesGlobalErrors(function (done) { + var def = variant.define("ThrowsInDealloc", TNSAccessorDeallocHost); + def.record.throws = "accessor-receiver-dealloc-boom"; + TNSAccessorDriver.dropNewHostOfName(def.Klass.class(), "dying"); + var saved = def.record.lastThis; + def.record.lastThis = null; + expect(saved).not.toBe(def.implementation); + expect(deallocs()).toBe(1); + pollUntil(function () { return uncaughtCount("accessor-receiver-dealloc-boom") >= 1; }, function () { + expect(uncaughtCount("accessor-receiver-dealloc-boom")).toBe(1); + var value; + var error = null; + try { + value = saved.hash; + } catch (e) { + error = e; + } + if (error !== null) { + expect(error.message).toContain("disposed native object"); + } else { + expect(value).toBeUndefined(); + } + saved = null; + done(); + }); + })); + }); + }); +}); diff --git a/TestRunner/app/tests/index.js b/TestRunner/app/tests/index.js index bb93113c4..693efd3a0 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("./JSAccessorReceiverTests"); require("./BlockCacheRaceTests"); require("./WorkerConcurrentStartupTests"); require("./WorkerOptionsTests"); From b46b20c0f8c87f20941b8561f1ca660108644245 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 15 Nov 2026 17:28:51 -0300 Subject: [PATCH 3/6] fix(runtime): stop JS property accessors from locking a disposed isolate The native getter and setter installed for JS-implemented properties took the isolate's Locker straight from a raw isolate pointer. Native code can call them after the runtime that defined the class is gone: an object of a worker's class that outlives the worker, read from the main thread or from background KVO. Locking the disposed isolate crashed. Give PropertyCallbackContext an IsolateWrapper and repeat MethodCallback's sequence: pin the isolate, check it is still valid, take the Locker, check again, and answer a zeroed value (or do nothing, for the setter) when the runtime is gone. --- NativeScript/runtime/ClassBuilder.h | 5 ++-- NativeScript/runtime/ClassBuilder.mm | 22 ++++++++++++++-- NativeScript/runtime/MetadataBuilder.mm | 4 +-- .../app/tests/JSAccessorReceiverTests.js | 26 +++++++++++++++++++ .../app/tests/jsAccessorReceiverWorker.js | 14 ++++++++++ 5 files changed, 65 insertions(+), 6 deletions(-) create mode 100644 TestRunner/app/tests/jsAccessorReceiverWorker.js diff --git a/NativeScript/runtime/ClassBuilder.h b/NativeScript/runtime/ClassBuilder.h index 3e298d3c6..b1d9c104a 100644 --- a/NativeScript/runtime/ClassBuilder.h +++ b/NativeScript/runtime/ClassBuilder.h @@ -2,6 +2,7 @@ #define ClassBuilder_h #include "Common.h" +#include "IsolateWrapper.h" #include "Metadata.h" namespace tns { @@ -12,8 +13,8 @@ struct PropertyCallbackContext { v8::Isolate* isolate, std::shared_ptr> callback, const PropertyMeta* meta) - : isolate_(isolate), callback_(callback), meta_(meta) {} - v8::Isolate* isolate_; + : isolateWrapper_(isolate), callback_(callback), meta_(meta) {} + IsolateWrapper isolateWrapper_; std::shared_ptr> callback_; const PropertyMeta* meta_; }; diff --git a/NativeScript/runtime/ClassBuilder.mm b/NativeScript/runtime/ClassBuilder.mm index 0a28d04c9..7e43a1195 100644 --- a/NativeScript/runtime/ClassBuilder.mm +++ b/NativeScript/runtime/ClassBuilder.mm @@ -902,12 +902,23 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { FFIMethodCallback getterCallback = [](ffi_cif* cif, void* retValue, void** argValues, void* userData) { PropertyCallbackContext* context = static_cast(userData); - Isolate* isolate = context->isolate_; + Isolate* isolate = context->isolateWrapper_.Isolate(); // Scopes-before-@throw: a branded escape is captured and @thrown only // after every V8 scope in the inner block has destructed. NSException* __strong pendingThrow = nil; { + // Validity is checked before and again after taking the Locker, for + // the reasons given in ArgConverter::MethodCallback. + IsolatePin pin = context->isolateWrapper_.Pin(); + if (!pin || !context->isolateWrapper_.IsValid()) { + memset(retValue, 0, cif->rtype->size); + return; + } v8::Locker locker(isolate); + if (!context->isolateWrapper_.IsValid()) { + memset(retValue, 0, cif->rtype->size); + return; + } Isolate::Scope isolate_scope(isolate); HandleScope handle_scope(isolate); Local getterFunc = context->callback_->Get(isolate); @@ -953,10 +964,17 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { FFIMethodCallback setterCallback = [](ffi_cif* cif, void* retValue, void** argValues, void* userData) { PropertyCallbackContext* context = static_cast(userData); - Isolate* isolate = context->isolate_; + Isolate* isolate = context->isolateWrapper_.Isolate(); NSException* __strong pendingThrow = nil; { + IsolatePin pin = context->isolateWrapper_.Pin(); + if (!pin || !context->isolateWrapper_.IsValid()) { + return; + } v8::Locker locker(isolate); + if (!context->isolateWrapper_.IsValid()) { + return; + } Isolate::Scope isolate_scope(isolate); HandleScope handle_scope(isolate); Local setterFunc = context->callback_->Get(isolate); diff --git a/NativeScript/runtime/MetadataBuilder.mm b/NativeScript/runtime/MetadataBuilder.mm index 2ebd330c9..a0775ae7b 100644 --- a/NativeScript/runtime/MetadataBuilder.mm +++ b/NativeScript/runtime/MetadataBuilder.mm @@ -1445,7 +1445,7 @@ CMethodCall methodCall(context, item->userData_, typeEncoding, args, FFIMethodCallback getterCallback = [](ffi_cif* cif, void* retValue, void** argValues, void* userData) { PropertyCallbackContext* context = static_cast(userData); - Isolate* isolate = context->isolate_; + Isolate* isolate = context->isolateWrapper_.Isolate(); // Scopes-before-@throw: capture a branded escape and @throw only after // the inner block's V8 scopes destruct. NSException* __strong pendingThrow = nil; @@ -1513,7 +1513,7 @@ CMethodCall methodCall(context, item->userData_, typeEncoding, args, FFIMethodCallback setterCallback = [](ffi_cif* cif, void* retValue, void** argValues, void* userData) { PropertyCallbackContext* context = static_cast(userData); - Isolate* isolate = context->isolate_; + Isolate* isolate = context->isolateWrapper_.Isolate(); NSException* __strong pendingThrow = nil; { v8::Locker locker(isolate); diff --git a/TestRunner/app/tests/JSAccessorReceiverTests.js b/TestRunner/app/tests/JSAccessorReceiverTests.js index 971a52311..1cd183b48 100644 --- a/TestRunner/app/tests/JSAccessorReceiverTests.js +++ b/TestRunner/app/tests/JSAccessorReceiverTests.js @@ -322,4 +322,30 @@ describe("JS accessor receivers", function () { })); }); }); + + describe("of a class a worker defined", function () { + var wt = require("node:worker_threads"); + + it("answer nil and store nothing once the worker ended", function (done) { + var worker = new wt.Worker("~/tests/jsAccessorReceiverWorker.js"); + worker.on("message", function (value) { + expect(value).toBe("worker:kept"); + worker.terminate().then(function () { + expect(TNSAccessorDriver.readKeptValue()).toBeNull(); + TNSAccessorDriver.writeKeptValue("after the worker"); + expect(TNSAccessorDriver.readKeptValue()).toBeNull(); + TNSAccessorDriver.dropKeptHost(); + expect(deallocs()).toBe(1); + done(); + }); + }); + worker.on("error", function (error) { + fail("worker error: " + error.message); + worker.terminate(); + TNSAccessorDriver.dropKeptHost(); + done(); + }); + worker.postMessage(0); + }); + }); }); diff --git a/TestRunner/app/tests/jsAccessorReceiverWorker.js b/TestRunner/app/tests/jsAccessorReceiverWorker.js new file mode 100644 index 000000000..21ea2c3df --- /dev/null +++ b/TestRunner/app/tests/jsAccessorReceiverWorker.js @@ -0,0 +1,14 @@ +// Leaves a natively created instance of a class with JS `value` accessors in +// a process-wide native slot, for the parent to reach after this worker ended. +onmessage = function () { + var Host = TNSAccessorHost.extend({ + get value() { + return "worker:" + this.name; + }, + set value(value) { + this._stored = value; + } + }, { name: "JSAccessorReceiverWorkerHost" }); + TNSAccessorDriver.keepNewHostOfName(Host.class(), "kept"); + postMessage(TNSAccessorDriver.readKeptValue()); +}; From eba01703ba7be7ab1b14861f6b8fd5e26eb44466 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 15 Nov 2026 20:41:23 -0300 Subject: [PATCH 4/6] fix(runtime): validate the cached receiver of a native callback NativeCallbackSelf read Caches::Instances directly, so a native call into JS could get a cached wrapper that no longer describes the object at that address as its receiver. Look it up through FindCachedInstance, as every other read that hands a cached wrapper to JS does. --- NativeScript/runtime/ArgConverter.mm | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/NativeScript/runtime/ArgConverter.mm b/NativeScript/runtime/ArgConverter.mm index a10564b44..a924674ca 100644 --- a/NativeScript/runtime/ArgConverter.mm +++ b/NativeScript/runtime/ArgConverter.mm @@ -54,9 +54,9 @@ bool InMethodFamily(SEL selector, const char* family) { NativeCallbackSelf::NativeCallbackSelf(Local context, id self) : isolate_(v8::Isolate::GetCurrent()) { auto cache = Caches::Get(isolate_); - auto it = cache->Instances.find(self); - if (it != cache->Instances.end()) { - receiver_ = it->second->Get(isolate_).As(); + auto cached = ArgConverter::FindCachedInstance(isolate_, cache, self); + if (cached != nullptr) { + receiver_ = cached->Get(isolate_).As(); } else { receiver_ = ArgConverter::WrapNativeCallbackSelf(context, self, &borrowed_); } From a85d9ac3627247a8586816682cbc043c369a78b4 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 15 Nov 2026 21:04:28 -0300 Subject: [PATCH 5/6] revert: "fix(runtime): validate the cached receiver of a native callback" This reverts commit eba01703. FindCachedInstance compares the object's current class with the class the wrapper recorded when it was made. An object wrapped while it was KVO-observed fails that comparison once its last observer is removed, so a live, correctly wrapped receiver lost its cache entry: the next native call into JS ran on a second, blank wrapper, and the two wrappers kept the object alive for good. --- NativeScript/runtime/ArgConverter.mm | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/NativeScript/runtime/ArgConverter.mm b/NativeScript/runtime/ArgConverter.mm index a924674ca..a10564b44 100644 --- a/NativeScript/runtime/ArgConverter.mm +++ b/NativeScript/runtime/ArgConverter.mm @@ -54,9 +54,9 @@ bool InMethodFamily(SEL selector, const char* family) { NativeCallbackSelf::NativeCallbackSelf(Local context, id self) : isolate_(v8::Isolate::GetCurrent()) { auto cache = Caches::Get(isolate_); - auto cached = ArgConverter::FindCachedInstance(isolate_, cache, self); - if (cached != nullptr) { - receiver_ = cached->Get(isolate_).As(); + auto it = cache->Instances.find(self); + if (it != cache->Instances.end()) { + receiver_ = it->second->Get(isolate_).As(); } else { receiver_ = ArgConverter::WrapNativeCallbackSelf(context, self, &borrowed_); } From 7012e54bbbefb152e98fa3b9cb58291576ab82d8 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 15 Nov 2026 22:32:46 -0300 Subject: [PATCH 6/6] fix(runtime): guard swizzled accessors against a dead isolate and keep wrappers made under KVO An accessor redefined on a native class's prototype stays on that class after the isolate that installed it is gone, and took its Locker without checking. A worker that redefined one and ended made every native read of the property crash. Both lambdas now pin and check validity before and after taking the Locker, and answer zeroes otherwise. A wrapper records the object's class when it is made. For an object first wrapped while key-value observed that is the notifying subclass, which the object leaves when its last observer goes; FindCachedInstance then took the live entry for a stale one, dropped it and handed JS a second, blank wrapper. It accepts that subclass now. The wrapper of an observed object also had no prototype registered under the notifying subclass's name, so it falls back to the class it was made for. --- NativeScript/runtime/ArgConverter.mm | 25 ++++++-- NativeScript/runtime/MetadataBuilder.mm | 19 ++++++ TestFixtures/Marshalling/TNSAllocLog.h | 18 ++++++ TestFixtures/Marshalling/TNSAllocLog.m | 38 +++++++++++ .../app/tests/JSAccessorReceiverTests.js | 63 ++++++++++++++++++- .../app/tests/jsAccessorReceiverWorker.js | 6 +- .../app/tests/jsAccessorSwizzleWorker.js | 12 ++++ 7 files changed, 172 insertions(+), 9 deletions(-) create mode 100644 TestRunner/app/tests/jsAccessorSwizzleWorker.js diff --git a/NativeScript/runtime/ArgConverter.mm b/NativeScript/runtime/ArgConverter.mm index a10564b44..8e50b0783 100644 --- a/NativeScript/runtime/ArgConverter.mm +++ b/NativeScript/runtime/ArgConverter.mm @@ -49,6 +49,12 @@ bool InMethodFamily(SEL selector, const char* family) { return strncmp(name, family, length) == 0 && (name[length] < 'a' || name[length] > 'z'); } +bool IsKVOSubclassOf(Class klass, Class base) { + static const char prefix[] = "NSKVONotifying_"; + return class_getSuperclass(klass) == base && + strncmp(class_getName(klass), prefix, sizeof(prefix) - 1) == 0; +} + } // namespace NativeCallbackSelf::NativeCallbackSelf(Local context, id self) @@ -1018,6 +1024,11 @@ bool InMethodFamily(SEL selector, const char* family) { const Meta* meta = FindMeta(klass, typeEncoding); if (meta != nullptr) { auto it = cache->ClassPrototypes.find(std::string_view(object_getClassName(target))); + // A key-value observed object is an instance of a notifying subclass, + // which has no prototype of its own. + if (it == cache->ClassPrototypes.end() && IsKVOSubclassOf(object_getClass(target), klass)) { + it = cache->ClassPrototypes.find(std::string_view(class_getName(klass))); + } if (it != cache->ClassPrototypes.end()) { // for debugging rlv cell handling: // NSString* message = [NSString stringWithFormat:@"ArgConverter::CreateJsWrapper FindMeta: @@ -1070,11 +1081,15 @@ bool InMethodFamily(SEL selector, const char* family) { if (wrapper != nullptr && wrapper->Type() == WrapperType::ObjCObject) { Class expected = static_cast(wrapper)->Klass(); // A KVO-style isa swizzle replaces the class in place but keeps -class - // answering the original, so only an address that now belongs to a - // different object fails both comparisons. Dropping such an entry turns a - // wrapper that would otherwise be handed out with the wrong prototype into - // a plain cache miss, which rebuilds it correctly. - if (expected != nil && object_getClass(target) != expected && [target class] != expected) { + // answering the original, and a wrapper made while the object was + // key-value observed recorded the notifying subclass, which the object + // leaves when its last observer goes. So only an address that now belongs + // to a different object fails all three comparisons. Dropping such an + // entry turns a wrapper that would otherwise be handed out with the wrong + // prototype into a plain cache miss, which rebuilds it correctly. + Class current = object_getClass(target); + if (expected != nil && current != expected && [target class] != expected && + !IsKVOSubclassOf(expected, current)) { cache->Instances.erase(it); return nullptr; } diff --git a/NativeScript/runtime/MetadataBuilder.mm b/NativeScript/runtime/MetadataBuilder.mm index a0775ae7b..980662abd 100644 --- a/NativeScript/runtime/MetadataBuilder.mm +++ b/NativeScript/runtime/MetadataBuilder.mm @@ -1450,7 +1450,19 @@ CMethodCall methodCall(context, item->userData_, typeEncoding, args, // the inner block's V8 scopes destruct. NSException* __strong pendingThrow = nil; { + // This IMP stays on the native class after the isolate that installed + // it is gone. Validity is checked before and again after taking the + // Locker, for the reasons given in ArgConverter::MethodCallback. + IsolatePin pin = context->isolateWrapper_.Pin(); + if (!pin || !context->isolateWrapper_.IsValid()) { + memset(retValue, 0, cif->rtype->size); + return; + } v8::Locker locker(isolate); + if (!context->isolateWrapper_.IsValid()) { + memset(retValue, 0, cif->rtype->size); + return; + } Isolate::Scope isolate_scope(isolate); HandleScope handle_scope(isolate); Local getterFunc = context->callback_->Get(isolate); @@ -1516,7 +1528,14 @@ CMethodCall methodCall(context, item->userData_, typeEncoding, args, Isolate* isolate = context->isolateWrapper_.Isolate(); NSException* __strong pendingThrow = nil; { + IsolatePin pin = context->isolateWrapper_.Pin(); + if (!pin || !context->isolateWrapper_.IsValid()) { + return; + } v8::Locker locker(isolate); + if (!context->isolateWrapper_.IsValid()) { + return; + } Isolate::Scope isolate_scope(isolate); HandleScope handle_scope(isolate); Local setterFunc = context->callback_->Get(isolate); diff --git a/TestFixtures/Marshalling/TNSAllocLog.h b/TestFixtures/Marshalling/TNSAllocLog.h index 0be837b40..c5a0bcc79 100644 --- a/TestFixtures/Marshalling/TNSAllocLog.h +++ b/TestFixtures/Marshalling/TNSAllocLog.h @@ -121,6 +121,7 @@ id TNSOwnedPrimitivesObjectAt(TNSOwnedPrimitives* holder, NSUInteger index); @interface TNSAccessorHost : TNSAllocLog @property(nonatomic, strong) id value; +@property(nonatomic) CGRect rect; @property(nonatomic, copy) NSString* name; @end @@ -141,6 +142,10 @@ id TNSOwnedPrimitivesObjectAt(TNSOwnedPrimitives* holder, NSUInteger index); - (void)writeValue:(id)value; - (TNSAccessorHost*)host; - (void)dropHost; +// Key-value observes the host's `value`, without reading it. +- (void)observeHost; +- (void)unobserveHost; +- (id)lastObservedValue; // Creates an instance of `cls` named `name`, reads its `value` and drops it. + (id)valueOfNewHostOf:(Class)cls name:(NSString*)name; @@ -150,9 +155,22 @@ id TNSOwnedPrimitivesObjectAt(TNSOwnedPrimitives* holder, NSUInteger index); // A process-wide host, kept until +dropKeptHost. + (void)keepNewHostOf:(Class)cls name:(NSString*)name; + (id)readKeptValue; ++ (CGRect)readKeptRect; + (void)writeKeptValue:(id)value; + (void)dropKeptHost; +// Reads and writes `value` on a new TNSAccessorSwizzleTarget. ++ (id)readSwizzleTargetValue; ++ (void)writeSwizzleTargetValue:(id)value; + +@end + +// Its `value` accessors are replaced on the prototype, by one spec, for the +// rest of the run. +@interface TNSAccessorSwizzleTarget : NSObject + +@property(nonatomic, strong) id value; + @end #endif /* TNSAllocLog_h */ diff --git a/TestFixtures/Marshalling/TNSAllocLog.m b/TestFixtures/Marshalling/TNSAllocLog.m index 44e5148c9..24a0313bb 100644 --- a/TestFixtures/Marshalling/TNSAllocLog.m +++ b/TestFixtures/Marshalling/TNSAllocLog.m @@ -269,8 +269,12 @@ - (void)dealloc { static TNSAccessorHost* keptAccessorHost; +@implementation TNSAccessorSwizzleTarget +@end + @implementation TNSAccessorDriver { TNSAccessorHost* _host; + id _lastObservedValue; } - (instancetype)initWithNewHostOf:(Class)cls name:(NSString*)name { @@ -306,6 +310,28 @@ - (void)dropHost { _host = nil; } +- (void)observeHost { + [_host addObserver:self + forKeyPath:@"value" + options:NSKeyValueObservingOptionNew + context:NULL]; +} + +- (void)unobserveHost { + [_host removeObserver:self forKeyPath:@"value"]; +} + +- (id)lastObservedValue { + return _lastObservedValue; +} + +- (void)observeValueForKeyPath:(NSString*)keyPath + ofObject:(id)object + change:(NSDictionary*)change + context:(void*)context { + _lastObservedValue = [object valueForKey:keyPath]; +} + + (id)valueOfNewHostOf:(Class)cls name:(NSString*)name { TNSAccessorHost* host = [[cls alloc] init]; host.name = name; @@ -327,10 +353,22 @@ + (id)readKeptValue { return keptAccessorHost.value; } ++ (CGRect)readKeptRect { + return keptAccessorHost.rect; +} + + (void)writeKeptValue:(id)value { keptAccessorHost.value = value; } ++ (id)readSwizzleTargetValue { + return [[TNSAccessorSwizzleTarget alloc] init].value; +} + ++ (void)writeSwizzleTargetValue:(id)value { + [[TNSAccessorSwizzleTarget alloc] init].value = value; +} + + (void)dropKeptHost { keptAccessorHost = nil; } diff --git a/TestRunner/app/tests/JSAccessorReceiverTests.js b/TestRunner/app/tests/JSAccessorReceiverTests.js index 1cd183b48..db6022cd6 100644 --- a/TestRunner/app/tests/JSAccessorReceiverTests.js +++ b/TestRunner/app/tests/JSAccessorReceiverTests.js @@ -202,6 +202,38 @@ describe("JS accessor receivers", function () { def.record.lastThis = null; }); + // Key-value observing swaps the instance's class for as long as it is + // observed, so the first wrap here happens under the swapped class. + it("keeps the wrapper of an instance an accessor call wrapped first while it was key-value observed" + variant.suffix, function (done) { + var def = variant.define("Observed"); + var driver = TNSAccessorDriver.alloc().initWithNewHostOfName(def.Klass.class(), "observed"); + driver.observeHost(); + expect(def.record.lastThis).toBeUndefined(); + expect(driver.readValue()).toBe("name:observed"); + var receiver = def.record.lastThis; + expect(receiver instanceof def.Klass).toBe(true); + expect(driver.host()).toBe(receiver); + driver.writeValue("observed-value"); + expect(driver.lastObservedValue()).toBe("observed-value"); + driver.unobserveHost(); + + (function () { + var host = driver.host(); + expect(host).toBe(receiver); + expect(host._stored).toBe("observed-value"); + expect(driver.readValue()).toBe("observed-value"); + expect(def.record.lastThis).toBe(host); + })(); + receiver = null; + def.record.lastThis = null; + expectNoSharedState(def); + driver.dropHost(); + settle(3, function () { + expect(deallocs()).toBe(1); + done(); + }); + }); + it("reports a receiver kept from a getter run by -dealloc as released" + variant.suffix, function (done) { var def = variant.define("Dealloc", TNSAccessorDeallocHost); var nameInDealloc; @@ -326,12 +358,14 @@ describe("JS accessor receivers", function () { describe("of a class a worker defined", function () { var wt = require("node:worker_threads"); - it("answer nil and store nothing once the worker ended", function (done) { + it("answer nil or zeroes and store nothing once the worker ended", function (done) { var worker = new wt.Worker("~/tests/jsAccessorReceiverWorker.js"); - worker.on("message", function (value) { - expect(value).toBe("worker:kept"); + worker.on("message", function (values) { + expect(values).toEqual(["worker:kept", 1, 2, 3, 4]); worker.terminate().then(function () { expect(TNSAccessorDriver.readKeptValue()).toBeNull(); + var rect = TNSAccessorDriver.readKeptRect(); + expect([rect.origin.x, rect.origin.y, rect.size.width, rect.size.height]).toEqual([0, 0, 0, 0]); TNSAccessorDriver.writeKeptValue("after the worker"); expect(TNSAccessorDriver.readKeptValue()).toBeNull(); TNSAccessorDriver.dropKeptHost(); @@ -348,4 +382,27 @@ describe("JS accessor receivers", function () { worker.postMessage(0); }); }); + + describe("a worker put on a native class's prototype", function () { + var wt = require("node:worker_threads"); + + it("answer nil and store nothing once the worker ended", function (done) { + var worker = new wt.Worker("~/tests/jsAccessorSwizzleWorker.js"); + worker.on("message", function (value) { + expect(value).toBe("swizzled by the worker"); + worker.terminate().then(function () { + expect(TNSAccessorDriver.readSwizzleTargetValue()).toBeNull(); + TNSAccessorDriver.writeSwizzleTargetValue("after the worker"); + expect(TNSAccessorDriver.readSwizzleTargetValue()).toBeNull(); + done(); + }); + }); + worker.on("error", function (error) { + fail("worker error: " + error.message); + worker.terminate(); + done(); + }); + worker.postMessage(0); + }); + }); }); diff --git a/TestRunner/app/tests/jsAccessorReceiverWorker.js b/TestRunner/app/tests/jsAccessorReceiverWorker.js index 21ea2c3df..0ff63330a 100644 --- a/TestRunner/app/tests/jsAccessorReceiverWorker.js +++ b/TestRunner/app/tests/jsAccessorReceiverWorker.js @@ -7,8 +7,12 @@ onmessage = function () { }, set value(value) { this._stored = value; + }, + get rect() { + return CGRectMake(1, 2, 3, 4); } }, { name: "JSAccessorReceiverWorkerHost" }); TNSAccessorDriver.keepNewHostOfName(Host.class(), "kept"); - postMessage(TNSAccessorDriver.readKeptValue()); + var rect = TNSAccessorDriver.readKeptRect(); + postMessage([TNSAccessorDriver.readKeptValue(), rect.origin.x, rect.origin.y, rect.size.width, rect.size.height]); }; diff --git a/TestRunner/app/tests/jsAccessorSwizzleWorker.js b/TestRunner/app/tests/jsAccessorSwizzleWorker.js new file mode 100644 index 000000000..9d11f7370 --- /dev/null +++ b/TestRunner/app/tests/jsAccessorSwizzleWorker.js @@ -0,0 +1,12 @@ +// Replaces the `value` accessors of a native class from this worker; the +// replacements stay installed on the class after the worker ended. +onmessage = function () { + Object.defineProperty(TNSAccessorSwizzleTarget.prototype, "value", { + get: function () { + return "swizzled by the worker"; + }, + set: function (value) {}, + configurable: true + }); + postMessage(TNSAccessorDriver.readSwizzleTargetValue()); +};