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..8e50b0783 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,24 +49,34 @@ 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; - } - } - Isolate* isolate; - Local receiver; - ObjCDataWrapper* wrapper = nullptr; -}; +bool IsKVOSubclassOf(Class klass, Class base) { + static const char prefix[] = "NSKVONotifying_"; + return class_getSuperclass(klass) == base && + strncmp(class_getName(klass), prefix, sizeof(prefix) - 1) == 0; +} } // namespace +NativeCallbackSelf::NativeCallbackSelf(Local context, id self) + : isolate_(v8::Isolate::GetCurrent()) { + auto cache = Caches::Get(isolate_); + auto it = cache->Instances.find(self); + if (it != cache->Instances.end()) { + receiver_ = it->second->Get(isolate_).As(); + } else { + receiver_ = ArgConverter::WrapNativeCallbackSelf(context, self, &borrowed_); + } +} + +// The object is gone once the native call returns, so a borrowed receiver JS +// kept must read as released. +NativeCallbackSelf::~NativeCallbackSelf() { + if (borrowed_ != nullptr && tns::GetValue(isolate_, receiver_) == borrowed_) { + tns::SetValue(isolate_, receiver_, nullptr); + delete borrowed_; + } +} + void ArgConverter::Init(Local context) { Isolate* isolate = v8::Isolate::GetCurrent(); auto cache = Caches::Get(isolate); @@ -405,18 +416,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(); @@ -1019,6 +1024,11 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {} 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: @@ -1071,11 +1081,15 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {} if (wrapper != nullptr && wrapper->Type() == WrapperType::ObjCObject) { Class expected = static_cast(wrapper)->Klass(); // A KVO-style isa swizzle replaces the class in place but keeps -class - // answering the original, 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/ClassBuilder.h b/NativeScript/runtime/ClassBuilder.h index 1b122fe0a..a705e4b96 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 { @@ -11,15 +12,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) {} - v8::Isolate* isolate_; + : isolateWrapper_(isolate), callback_(callback), meta_(meta) {} + IsolateWrapper isolateWrapper_; std::shared_ptr> callback_; - std::shared_ptr> implementationObject_; const PropertyMeta* meta_; }; @@ -79,7 +75,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); // Follows clang: a struct behind a pointer is expanded only when that diff --git a/NativeScript/runtime/ClassBuilder.mm b/NativeScript/runtime/ClassBuilder.mm index 0605ff4ef..7c84f364f 100644 --- a/NativeScript/runtime/ClassBuilder.mm +++ b/NativeScript/runtime/ClassBuilder.mm @@ -796,7 +796,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; } @@ -923,8 +923,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(); @@ -936,40 +935,42 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { bool hasSetter = !setter.IsEmpty() && setter->IsFunction() && propertyMeta->hasSetter() && !ImplementsItself(extendedClass, propertyMeta->setter()->selector()); - 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) { 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); 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; @@ -1001,36 +1002,39 @@ 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) { 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); 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 cac616fd7..fa9729a3f 100644 --- a/NativeScript/runtime/MetadataBuilder.mm +++ b/NativeScript/runtime/MetadataBuilder.mm @@ -1464,12 +1464,24 @@ void ReplaceKeepingOriginal(Class klass, SEL selector, const char* selectorName, 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; { + // 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); @@ -1519,7 +1531,7 @@ void ReplaceKeepingOriginal(Class klass, SEL selector, const char* selectorName, 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); ReplaceKeepingOriginal(klass, propertyMeta->getter()->selector(), propertyMeta->getter()->selectorAsString(), impGetter, @@ -1530,10 +1542,17 @@ void ReplaceKeepingOriginal(Class klass, SEL selector, const char* selectorName, 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); @@ -1580,7 +1599,7 @@ void ReplaceKeepingOriginal(Class klass, SEL selector, const char* selectorName, 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); std::string compilerEncoding = ClassBuilder::GetAccessorTypeEncoding(typeEncoding, 1, "v@:@"); diff --git a/TestFixtures/Marshalling/TNSAllocLog.h b/TestFixtures/Marshalling/TNSAllocLog.h index 8537238ec..c2adcb5c8 100644 --- a/TestFixtures/Marshalling/TNSAllocLog.h +++ b/TestFixtures/Marshalling/TNSAllocLog.h @@ -127,4 +127,60 @@ 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) CGRect rect; +@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; +// 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; +// 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; ++ (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 6b9059f80..72d685671 100644 --- a/TestFixtures/Marshalling/TNSAllocLog.m +++ b/TestFixtures/Marshalling/TNSAllocLog.m @@ -302,3 +302,123 @@ - (void)initHook { } @end + +@implementation TNSAccessorHost +@end + +@implementation TNSAccessorDeallocHost + +- (void)dealloc { + id value = self.value; + (void)value; +} + +@end + +static TNSAccessorHost* keptAccessorHost; + +@implementation TNSAccessorSwizzleTarget +@end + +@implementation TNSAccessorDriver { + TNSAccessorHost* _host; + id _lastObservedValue; +} + +- (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; +} + +- (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; + 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; +} + ++ (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; +} + +@end diff --git a/TestRunner/app/tests/JSAccessorReceiverTests.js b/TestRunner/app/tests/JSAccessorReceiverTests.js new file mode 100644 index 000000000..db6022cd6 --- /dev/null +++ b/TestRunner/app/tests/JSAccessorReceiverTests.js @@ -0,0 +1,408 @@ +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; + }); + + // 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; + 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(); + }); + })); + }); + }); + + describe("of a class a worker defined", function () { + var wt = require("node:worker_threads"); + + 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 (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(); + expect(deallocs()).toBe(1); + done(); + }); + }); + worker.on("error", function (error) { + fail("worker error: " + error.message); + worker.terminate(); + TNSAccessorDriver.dropKeptHost(); + done(); + }); + 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/index.js b/TestRunner/app/tests/index.js index aefe1e5e6..2699fc8e0 100644 --- a/TestRunner/app/tests/index.js +++ b/TestRunner/app/tests/index.js @@ -138,6 +138,7 @@ require("./NsInteropTests"); require("./GCFinalizerTests"); require("./NativeCallbackSelfTests"); require("./JSAccessorEncodingTests"); +require("./JSAccessorReceiverTests"); require("./BlockCacheRaceTests"); require("./WorkerConcurrentStartupTests"); require("./WorkerOptionsTests"); diff --git a/TestRunner/app/tests/jsAccessorReceiverWorker.js b/TestRunner/app/tests/jsAccessorReceiverWorker.js new file mode 100644 index 000000000..0ff63330a --- /dev/null +++ b/TestRunner/app/tests/jsAccessorReceiverWorker.js @@ -0,0 +1,18 @@ +// 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; + }, + get rect() { + return CGRectMake(1, 2, 3, 4); + } + }, { name: "JSAccessorReceiverWorkerHost" }); + TNSAccessorDriver.keepNewHostOfName(Host.class(), "kept"); + 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()); +};