From 100a9b40a98adbe677f0bc6d7c56478bba3c8bb6 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 14 Nov 2026 16:23:42 -0300 Subject: [PATCH 1/9] fix(runtime): release owned instance-method returns that hit a cached wrapper MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An owned result (copy, mutableCopy and new families, ns_returns_retained, initializers) whose object already had a JS wrapper kept its +1 when the method was an instance method: the Instances entry holds its own reference, so the object leaked one retain per call. `immutable.copy()` and `X.alloc().init…()` on a class whose initializer wraps the object (a JS initializer, or a native one calling a JS-implemented method) both hit it. The release was limited to class methods and C functions because two kinds of owned instance returns carried no net +1: methods that consume their receiver and answer it, and JS-implemented methods, which handed results to native callers at +0. The second was a bug of its own: a native caller of a JS copyWithZone:, mutableCopyWithZone: or new-family method released an object it did not own, freeing it under a live wrapper. - MethodCallback hands an owned result to native callers at +1: always for the copy/mutableCopy/new families and metadata-flagged owned returns (the receiver included), and for initializers and -awakeAfterUsingCoder: when the result is not the receiver. The classification comes from the method's metadata, or from the selector's method family for methods the metadata does not describe, and is stored on the MethodCallbackWrapper. - Interop::ReleasesCachedOwnedReturn is the one cache-hit rule, used by GetResult and ConstructObject: release unless the call consumed a receiver that existed before it (re-init, super.init…() inside a JS initializer, NS_REPLACES_RECEIVER on a live object). An initializer on a receiver allocated for the call releases whatever it answers; Invoke marks such calls on ObjCMethodCall. - Interop::ConsumesReceiver treats the init family and -awakeAfterUsingCoder: (the SDK's only NS_REPLACES_RECEIVER method) as receiver-consuming; the metadata does not record ns_consumes_self. Fixes #566 --- NativeScript/runtime/ArgConverter.h | 28 ++- NativeScript/runtime/ArgConverter.mm | 50 +++-- NativeScript/runtime/ClassBuilder.mm | 8 +- NativeScript/runtime/Interop.h | 37 +++- NativeScript/runtime/Interop.mm | 41 +++- NativeScript/runtime/MetadataBuilder.mm | 3 +- TestFixtures/Marshalling/TNSAllocLog.h | 14 ++ TestFixtures/Marshalling/TNSAllocLog.m | 29 +++ .../app/tests/NativeCallbackSelfTests.js | 209 ++++++++++++++++++ 9 files changed, 377 insertions(+), 42 deletions(-) diff --git a/NativeScript/runtime/ArgConverter.h b/NativeScript/runtime/ArgConverter.h index b8bcfe5ac..7a889ba34 100644 --- a/NativeScript/runtime/ArgConverter.h +++ b/NativeScript/runtime/ArgConverter.h @@ -13,23 +13,34 @@ namespace tns { class ArgConverter; +// What native callers of a JS-implemented method own of the object it answers. +enum class NativeReturnOwnership : uint8_t { + Unowned, + // A +1; the receiver stays the caller's. + Owned, + // A +1 in place of the receiver, whose reference the caller passed in. + ReplacesReceiver, +}; + struct MethodCallbackWrapper { public: - MethodCallbackWrapper(v8::Isolate* isolate, - std::shared_ptr> callback, - const uint8_t initialParamIndex, - const uint8_t paramsCount, - const TypeEncoding* typeEncoding) + MethodCallbackWrapper( + v8::Isolate* isolate, std::shared_ptr> callback, + const uint8_t initialParamIndex, const uint8_t paramsCount, + const TypeEncoding* typeEncoding, + NativeReturnOwnership returnOwnership = NativeReturnOwnership::Unowned) : isolateWrapper_(isolate), callback_(callback), initialParamIndex_(initialParamIndex), paramsCount_(paramsCount), - typeEncoding_(typeEncoding) {} + typeEncoding_(typeEncoding), + returnOwnership_(returnOwnership) {} IsolateWrapper isolateWrapper_; std::shared_ptr> callback_; const uint8_t initialParamIndex_; const uint8_t paramsCount_; const TypeEncoding* typeEncoding_; + const NativeReturnOwnership returnOwnership_; }; class ArgConverter { @@ -71,6 +82,11 @@ class ArgConverter { static const ProtocolMeta* FindProtocolMeta(Protocol* protocol); static void MethodCallback(ffi_cif* cif, void* retValue, void** argValues, void* userData); + // For a JS implementation of the instance method `selector`; `meta` is null + // for methods the metadata does not describe, which are classified by + // their selector's method family. + static NativeReturnOwnership ReturnOwnership(SEL selector, + const MethodMeta* meta); // returnSize is the ABI size of the return slot (cif->rtype->size); an // empty, null or undefined value zeroes all of it. static void SetValue(v8::Local context, void* retValue, diff --git a/NativeScript/runtime/ArgConverter.mm b/NativeScript/runtime/ArgConverter.mm index f83403f87..78cae0ece 100644 --- a/NativeScript/runtime/ArgConverter.mm +++ b/NativeScript/runtime/ArgConverter.mm @@ -36,23 +36,25 @@ bool IsDeallocating(id obj) { return !((BOOL (*)(id, SEL))imp)(obj, allowsWeakReference); } -// Clang's init method family: optional leading underscores, then "init", then -// the end of the selector's first piece or anything but a lowercase letter. -bool IsInitFamily(SEL selector) { +// Clang's method family rule: optional leading underscores, then the family +// name, then the end of the selector's first piece or anything but a +// lowercase letter. +bool InMethodFamily(SEL selector, const char* family) { const char* name = sel_getName(selector); while (*name == '_') { name++; } - return strncmp(name, "init", 4) == 0 && (name[4] < 'a' || name[4] > 'z'); + size_t length = strlen(family); + return strncmp(name, family, length) == 0 && (name[length] < 'a' || name[length] > 'z'); } -// The native caller of an init-family method owns its result. SetValue hands -// a wrapped object or a string over at +0: for the receiver that is the -// reference the caller passed in, any other object needs its own. The -// receiver is left alone: when a super initializer substituted it, that -// initializer already released it, and nothing here can tell that case apart. -void RetainInitializerResult(Isolate* isolate, void** argValues, void* retValue, - const TypeEncoding* typeEncoding, Local value) { +// SetValue hands a wrapped object or a string over at +0, so an owned result +// gets a reference of its own, except a receiver answered in place of itself: +// that is the reference the caller passed in. The receiver is never released +// when another object is answered instead: a super initializer that +// substituted it already did, and nothing here can tell that case apart. +void RetainOwnedResult(Isolate* isolate, NativeReturnOwnership ownership, void** argValues, + void* retValue, const TypeEncoding* typeEncoding, Local value) { BinaryTypeEncodingType type = typeEncoding->type; if (type != BinaryTypeEncodingType::IdEncoding && type != BinaryTypeEncodingType::InterfaceDeclarationReference && @@ -61,8 +63,8 @@ void RetainInitializerResult(Isolate* isolate, void** argValues, void* retValue, } id returned = *static_cast(retValue); - if (returned == nil || returned == *static_cast(argValues[0]) || - !IsInitFamily(*static_cast(argValues[1]))) { + if (returned == nil || (ownership == NativeReturnOwnership::ReplacesReceiver && + returned == *static_cast(argValues[0]))) { return; } @@ -192,7 +194,7 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {} target = [allocKlass alloc]; } - ObjCMethodCall methodCall(context, meta, target, klass, args, callSuper); + ObjCMethodCall methodCall(context, meta, target, klass, args, callSuper, allocKlass != nil); return Interop::CallFunction(methodCall); } @@ -513,8 +515,9 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {} memset(retValue, 0, cif->rtype->size); } else { ArgConverter::SetValue(context, retValue, cif->rtype->size, result, data->typeEncoding_); - if (data->initialParamIndex_ == 2) { - RetainInitializerResult(isolate, argValues, retValue, data->typeEncoding_, result); + if (data->returnOwnership_ != NativeReturnOwnership::Unowned) { + RetainOwnedResult(isolate, data->returnOwnership_, argValues, retValue, + data->typeEncoding_, result); } } } else { @@ -527,6 +530,19 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {} } } +NativeReturnOwnership ArgConverter::ReturnOwnership(SEL selector, const MethodMeta* meta) { + bool isInitializer = meta != nullptr ? meta->isInitializer() : InMethodFamily(selector, "init"); + if (Interop::ConsumesReceiver(selector, isInitializer)) { + return NativeReturnOwnership::ReplacesReceiver; + } + + bool owned = meta != nullptr + ? meta->ownsReturnedCocoaObject() + : InMethodFamily(selector, "copy") || InMethodFamily(selector, "mutableCopy") || + InMethodFamily(selector, "new"); + return owned ? NativeReturnOwnership::Owned : NativeReturnOwnership::Unowned; +} + void ArgConverter::SetValue(Local context, void* retValue, size_t returnSize, Local value, const TypeEncoding* typeEncoding) { if (typeEncoding->type == BinaryTypeEncodingType::VoidEncoding) { @@ -706,7 +722,7 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {} // An initializer that answered with an already wrapped object (a singleton, // a tagged pointer, a cached cluster instance) leaves us holding a +1 the // existing entry has no use for. - if (resultIsOwned) { + if (Interop::ReleasesCachedOwnedReturn(resultIsOwned, OwnedReturnReceiver::AllocatedForCall)) { [result release]; } info.GetReturnValue().Set(poInstance->Get(isolate)); diff --git a/NativeScript/runtime/ClassBuilder.mm b/NativeScript/runtime/ClassBuilder.mm index 3baac7706..40289ae9e 100644 --- a/NativeScript/runtime/ClassBuilder.mm +++ b/NativeScript/runtime/ClassBuilder.mm @@ -690,7 +690,8 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { std::shared_ptr> poCallback = std::make_shared>(isolate, method); MethodCallbackWrapper* userData = - new MethodCallbackWrapper(isolate, poCallback, 2, argsCount, typeEncoding); + new MethodCallbackWrapper(isolate, poCallback, 2, argsCount, typeEncoding, + ArgConverter::ReturnOwnership(selector, nullptr)); IMP methodBody = Interop::CreateMethod(2, argsCount, typeEncoding, ArgConverter::MethodCallback, userData); std::string typeInfo = GetTypeEncoding(typeEncoding, argsCount); @@ -793,9 +794,10 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { std::make_shared>(isolate, method); const TypeEncoding* typeEncoding = methodMeta->encodings()->first(); uint8_t argsCount = methodMeta->encodings()->count - 1; - MethodCallbackWrapper* userData = - new MethodCallbackWrapper(isolate, poCallback, 2, argsCount, typeEncoding); SEL selector = methodMeta->selector(); + MethodCallbackWrapper* userData = + new MethodCallbackWrapper(isolate, poCallback, 2, argsCount, typeEncoding, + ArgConverter::ReturnOwnership(selector, methodMeta)); IMP methodBody = Interop::CreateMethod(2, argsCount, typeEncoding, ArgConverter::MethodCallback, userData); std::string typeInfo = GetTypeEncoding(typeEncoding, argsCount); diff --git a/NativeScript/runtime/Interop.h b/NativeScript/runtime/Interop.h index 9dcfed691..8bfd7d578 100644 --- a/NativeScript/runtime/Interop.h +++ b/NativeScript/runtime/Interop.h @@ -15,6 +15,21 @@ namespace tns { typedef void (*FFIMethodCallback)(ffi_cif* cif, void* retValue, void** argValues, void* userData); +// The receiver of a call that returns an object, as far as releasing an owned +// result that already has a wrapper is concerned. +enum class OwnedReturnReceiver : uint8_t { + // A class method or a C function. + None, + // An instance method that leaves its receiver to the caller. + Kept, + // An initializer or NS_REPLACES_RECEIVER method sent to a receiver that + // existed before the call. + Consumed, + // An initializer or NS_REPLACES_RECEIVER method sent to a receiver the + // runtime allocated for this call. + AllocatedForCall, +}; + struct MethodCall { MethodCall(v8::Local context, bool isPrimitiveFunction, void* functionPointer, const TypeEncoding* typeEncoding, @@ -50,6 +65,7 @@ struct MethodCall { bool ownsReturnedObject_; bool returnsUnmanaged_; bool isInitializer_; + bool receiverAllocatedForCall_ = false; }; struct CMethodCall : MethodCall { @@ -63,7 +79,8 @@ struct CMethodCall : MethodCall { struct ObjCMethodCall : public MethodCall { ObjCMethodCall(v8::Local context, const MethodMeta* meta, - id target, Class clazz, V8Args& args, bool callSuper) + id target, Class clazz, V8Args& args, bool callSuper, + bool receiverAllocatedForCall = false) : MethodCall(context, false, callSuper ? (void*)objc_msgSendSuper : (void*)objc_msgSend, meta->encodings()->first(), args, target, clazz, @@ -71,7 +88,9 @@ struct ObjCMethodCall : public MethodCall { meta->hasErrorOutParameter() && args.Length() < meta->encodings()->count - 1, meta->ownsReturnedCocoaObject(), false, - meta->isInitializer()) {} + meta->isInitializer()) { + receiverAllocatedForCall_ = receiverAllocatedForCall; + } }; class Interop { @@ -96,19 +115,29 @@ class Interop { Class clazz, V8Args& args); static v8::Local CallFunction(ObjCMethodCall& methodCall); static v8::Local CallFunction(CMethodCall& methodCall); + // Whether a method answers in place of its receiver, consuming the caller's + // reference to it: the init family, and NS_REPLACES_RECEIVER methods, which + // the metadata does not record. + static bool ConsumesReceiver(SEL selector, bool isInitializer); + // Whether an owned object result that already has a wrapper carries a +1 + // the caller must drop, the Instances entry holding its own reference. + static bool ReleasesCachedOwnedReturn(bool ownsReturnedObject, + OwnedReturnReceiver receiver); static v8::Local GetResultByType( v8::Local context, BaseDataWrapper* typeWrapper, BaseCall* call, v8::Local parentStruct = v8::Local()); // A non-empty `parentStruct` makes a struct-typed result a view into the - // parent's buffer (`call` points at the field) instead of a copy. + // parent's buffer (`call` points at the field) instead of a copy. The + // default `ownedReturnReceiver` never releases an owned result found already + // wrapped. static v8::Local GetResult( v8::Local context, const TypeEncoding* typeEncoding, BaseCall* call, bool marshalToPrimitive, v8::Local parentStruct = v8::Local(), bool isStructMember = false, bool ownsReturnedObject = false, bool returnsUnmanaged = false, bool isInitializer = false, - bool releaseCachedOwnedReturn = false); + OwnedReturnReceiver ownedReturnReceiver = OwnedReturnReceiver::Consumed); static void SetStructPropertyValue(v8::Local context, StructWrapper* wrapper, const StructField& field, diff --git a/NativeScript/runtime/Interop.mm b/NativeScript/runtime/Interop.mm index 5cbc8f408..8bc057b67 100644 --- a/NativeScript/runtime/Interop.mm +++ b/NativeScript/runtime/Interop.mm @@ -168,6 +168,19 @@ return Interop::CallFunctionInternal(methodCall); } +bool Interop::ConsumesReceiver(SEL selector, bool isInitializer) { + return isInitializer || selector == @selector(awakeAfterUsingCoder:); +} + +// Balanced only while every owned result other than a consumed receiver +// reaches here at +1, JS-implemented methods included: MethodCallback retains +// what a JS implementation answers at +0, and for initializers anything but +// the receiver. AllocatedForCall does not check that the result is the +// receiver, so narrowing that retain makes this over-release. +bool Interop::ReleasesCachedOwnedReturn(bool ownsReturnedObject, OwnedReturnReceiver receiver) { + return ownsReturnedObject && receiver != OwnedReturnReceiver::Consumed; +} + id Interop::CallInitializer(Local context, const MethodMeta* methodMeta, id target, Class clazz, V8Args& args) { const TypeEncoding* typeEncoding = methodMeta->encodings()->first(); @@ -1029,7 +1042,7 @@ static bool SnapshotArrayLike(Isolate* isolate, Local object, Local Interop::GetResult(Local context, const TypeEncoding* typeEncoding, BaseCall* call, bool marshalToPrimitive, Local parentStruct, bool isStructMember, bool ownsReturnedObject, bool returnsUnmanaged, - bool isInitializer, bool releaseCachedOwnedReturn) { + bool isInitializer, OwnedReturnReceiver ownedReturnReceiver) { Isolate* isolate = v8::Isolate::GetCurrent(); if (returnsUnmanaged) { @@ -1364,12 +1377,7 @@ static bool SnapshotArrayLike(Isolate* isolate, Local object, Local cached = poInstance->Get(isolate); - // The Instances entry holds its own reference, so a returned +1 is - // surplus. Only class methods and C functions qualify: an instance - // method can hand back its receiver without a net retain (initializers, - // NS_REPLACES_RECEIVER) or come from a JS implementation, which returns - // at +0. - if (ownsReturnedObject && releaseCachedOwnedReturn) { + if (ReleasesCachedOwnedReturn(ownsReturnedObject || isInitializer, ownedReturnReceiver)) { [result release]; } return cached; @@ -1937,10 +1945,21 @@ throw NativeScriptException( } } - Local result = Interop::GetResult( - methodCall.context_, methodCall.typeEncoding_, &call, marshalToPrimitive, Local(), - false, methodCall.ownsReturnedObject_, methodCall.returnsUnmanaged_, - methodCall.isInitializer_, !isInstanceMethod); + OwnedReturnReceiver receiver = OwnedReturnReceiver::None; + if (isInstanceMethod) { + if (!ConsumesReceiver(methodCall.selector_, methodCall.isInitializer_)) { + receiver = OwnedReturnReceiver::Kept; + } else if (methodCall.receiverAllocatedForCall_) { + receiver = OwnedReturnReceiver::AllocatedForCall; + } else { + receiver = OwnedReturnReceiver::Consumed; + } + } + + Local result = + Interop::GetResult(methodCall.context_, methodCall.typeEncoding_, &call, marshalToPrimitive, + Local(), false, methodCall.ownsReturnedObject_, + methodCall.returnsUnmanaged_, methodCall.isInitializer_, receiver); // Owned returns, initializers and class factory methods hand out objects JS // most likely holds the last reference to. Instance getters do not: their diff --git a/NativeScript/runtime/MetadataBuilder.mm b/NativeScript/runtime/MetadataBuilder.mm index eca54cce5..c2add51ec 100644 --- a/NativeScript/runtime/MetadataBuilder.mm +++ b/NativeScript/runtime/MetadataBuilder.mm @@ -1397,7 +1397,8 @@ CMethodCall methodCall(context, item->userData_, typeEncoding, args, std::shared_ptr> poCallback = std::make_shared>(isolate, value); MethodCallbackWrapper* userData = - new MethodCallbackWrapper(isolate, poCallback, 2, argsCount, typeEncoding); + new MethodCallbackWrapper(isolate, poCallback, 2, argsCount, typeEncoding, + ArgConverter::ReturnOwnership(methodMeta->selector(), methodMeta)); IMP methodBody = Interop::CreateMethod(2, argsCount, typeEncoding, ArgConverter::MethodCallback, userData); IMP nativeImp = diff --git a/TestFixtures/Marshalling/TNSAllocLog.h b/TestFixtures/Marshalling/TNSAllocLog.h index ef80f9a93..a384c36db 100644 --- a/TestFixtures/Marshalling/TNSAllocLog.h +++ b/TestFixtures/Marshalling/TNSAllocLog.h @@ -19,4 +19,18 @@ @end +// Native callers that own what an owned-return message answers and drop it +// straight away. +@interface TNSOwnedReturns : TNSAllocLog + +// Answers a new TNSAllocLog. +- (id)newChild; + ++ (void)copyAndDrop:(id)object; ++ (void)mutableCopyAndDrop:(id)object; ++ (void)newChildAndDrop:(TNSOwnedReturns*)object; ++ (void)awakeAndDrop:(id)object; + +@end + #endif /* TNSAllocLog_h */ diff --git a/TestFixtures/Marshalling/TNSAllocLog.m b/TestFixtures/Marshalling/TNSAllocLog.m index e04bb917d..c70b76bd2 100644 --- a/TestFixtures/Marshalling/TNSAllocLog.m +++ b/TestFixtures/Marshalling/TNSAllocLog.m @@ -29,3 +29,32 @@ - (instancetype)init { } @end + +@implementation TNSOwnedReturns + +- (id)newChild { + return [[TNSAllocLog alloc] init]; +} + ++ (void)copyAndDrop:(id)object { + id result = [object copy]; + (void)result; +} + ++ (void)mutableCopyAndDrop:(id)object { + id result = [object mutableCopy]; + (void)result; +} + ++ (void)newChildAndDrop:(TNSOwnedReturns*)object { + id result = [object newChild]; + (void)result; +} + ++ (void)awakeAndDrop:(id)object { + NSCoder* coder = nil; + id result = [object awakeAfterUsingCoder:coder]; + (void)result; +} + +@end diff --git a/TestRunner/app/tests/NativeCallbackSelfTests.js b/TestRunner/app/tests/NativeCallbackSelfTests.js index 049ae5e21..9822939d6 100644 --- a/TestRunner/app/tests/NativeCallbackSelfTests.js +++ b/TestRunner/app/tests/NativeCallbackSelfTests.js @@ -408,4 +408,213 @@ describe("Native callback self wrappers", function () { }); }); }); + + it("leaves the retain count of an immutable object whose -copy answers itself unchanged", function (done) { + var array = NSArray.arrayWithArray([1, 2, 3]); + settle(2, function () { + var before = array.retainCount(); + var same = 0; + for (var i = 0; i < 50; i++) { + if (array.copy() === array) { + same++; + } + } + expect(same).toBe(50); + settle(2, function () { + expect(array.retainCount()).toBe(before); + done(); + }); + }); + }); + + it("frees an object JS alone holds after alloc().init() ran its JS initializer", function (done) { + var obj = JSInit.alloc().init(); + obj.state = { i: 3 }; + settle(2, function () { + expect(initCalls).toBe(1); + expect(obj.state.i).toBe(3); + expect(deallocs()).toBe(0); + obj = null; + settle(3, function () { + expect(deallocs()).toBe(1); + done(); + }); + }); + }); + + it("keeps the JS state of a natively owned object whose JS initializer ran from alloc().init(), then frees it once", function (done) { + var owner = NSMutableArray.new(); + (function () { + var obj = JSInit.alloc().init(); + obj.state = { i: 4 }; + owner.addObject(obj); + })(); + settle(3, function () { + var obj = owner.objectAtIndex(0); + expect(initCalls).toBe(1); + expect(obj.initialized).toBe(true); + expect(obj.state && obj.state.i).toBe(4); + obj = null; + expect(deallocs()).toBe(0); + owner.removeAllObjects(); + settle(3, function () { + expect(deallocs()).toBe(1); + done(); + }); + }); + }); + + it("keeps a wrapped object a JS initializer returns instead of its receiver (alloc().init())", function (done) { + expectInitializerResultOwnedByCaller(function () { + return createThroughInitReturningOther(function () { + return InitReturnsOther.alloc().init(); + }); + }, done); + }); + + it("keeps the substitute a super initializer returned through a JS initializer (alloc().init())", function (done) { + expectInitializerResultOwnedByCaller(function () { + return InitReturnsSubstitute.alloc().init(); + }, done); + }); + + it("does not release a wrapped receiver that is initialized again", function (done) { + var plain = TNSAllocLog.new(); + var jsInit = JSInit.new(); + expect(plain.init()).toBe(plain); + expect(TNSAllocLog.prototype.init.call(plain)).toBe(plain); + expect(TNSAllocLog.prototype.init.apply(plain, [])).toBe(plain); + expect(jsInit.init()).toBe(jsInit); + expect(JSInit.prototype.init.call(jsInit)).toBe(jsInit); + expect(JSInit.prototype.init.apply(jsInit, [])).toBe(jsInit); + expect(TNSAllocLog.prototype.init.call(jsInit)).toBe(jsInit); + settle(3, function () { + var freed = deallocs(); + expect(freed).toBe(0); + if (freed === 0) { + expect(plain.hash > 0).toBe(true); + expect(jsInit.initialized).toBe(true); + } + plain = null; + jsInit = null; + settle(3, function () { + expect(deallocs()).toBe(2); + done(); + }); + }); + }); + + // Native code that owns what an owned-return method answers drops it. The + // object a JS implementation answered must outlive that, and be freed + // exactly once after JS lets go. TNSOwnedReturns and TNSAllocLog log their + // deallocation; `freedAfterwards` counts those among receiver and result. + function expectKeptThroughNativeDrop(state, drop, freedAfterwards, done) { + drop(state.receiver); + settle(3, function () { + var freed = deallocs(); + expect(freed).toBe(0); + if (freed === 0) { + expect(state.receiver.hash > 0).toBe(true); + expect(state.result.hash > 0).toBe(true); + } + state.receiver = null; + state.result = null; + settle(3, function () { + expect(deallocs()).toBe(freedAfterwards); + done(); + }); + }); + } + + function ownedReturnState(base, name, method, protocols, answersReceiver) { + var state = {}; + var implementation = {}; + implementation[method] = function () { + return answersReceiver ? this : state.result; + }; + var Klass = base.extend(implementation, { name: name, protocols: protocols }); + state.receiver = Klass.new(); + state.result = answersReceiver ? state.receiver : TNSAllocLog.new(); + return state; + } + + it("hands a native -copy the receiver a JS copyWithZone answers at +1", function (done) { + var state = ownedReturnState(TNSOwnedReturns, "NativeCallbackSelfCopySelf", "copyWithZone", [NSCopying], true); + expectKeptThroughNativeDrop(state, function (receiver) { + TNSOwnedReturns.copyAndDrop(receiver); + }, 1, done); + }); + + it("hands a native -copy the other object a JS copyWithZone answers at +1", function (done) { + var state = ownedReturnState(TNSOwnedReturns, "NativeCallbackSelfCopyOther", "copyWithZone", [NSCopying], false); + expectKeptThroughNativeDrop(state, function (receiver) { + TNSOwnedReturns.copyAndDrop(receiver); + }, 2, done); + }); + + it("hands a native -mutableCopy the object a JS mutableCopyWithZone answers at +1", function (done) { + var state = ownedReturnState(TNSOwnedReturns, "NativeCallbackSelfMutableCopy", "mutableCopyWithZone", [NSMutableCopying], false); + expectKeptThroughNativeDrop(state, function (receiver) { + TNSOwnedReturns.mutableCopyAndDrop(receiver); + }, 2, done); + }); + + it("hands a native caller the object a JS new-family method answers at +1", function (done) { + var state = ownedReturnState(TNSOwnedReturns, "NativeCallbackSelfNewOther", "newChild", [], false); + expectKeptThroughNativeDrop(state, function (receiver) { + TNSOwnedReturns.newChildAndDrop(receiver); + }, 2, done); + }); + + it("hands a native caller the receiver a JS new-family method answers at +1", function (done) { + var state = ownedReturnState(TNSOwnedReturns, "NativeCallbackSelfNewSelf", "newChild", [], true); + expectKeptThroughNativeDrop(state, function (receiver) { + TNSOwnedReturns.newChildAndDrop(receiver); + }, 1, done); + }); + + it("hands a native caller back the receiver a JS awakeAfterUsingCoder answers", function (done) { + var state = ownedReturnState(TNSOwnedReturns, "NativeCallbackSelfAwakeSelf", "awakeAfterUsingCoder", [], true); + expectKeptThroughNativeDrop(state, function (receiver) { + TNSOwnedReturns.awakeAndDrop(receiver); + }, 1, done); + }); + + // The receiver is not a TNSAllocLog: its reference, consumed by the call, + // is not given back when the JS method answers another object. + it("hands a native caller the other object a JS awakeAfterUsingCoder answers at +1", function (done) { + var state = ownedReturnState(NSObject, "NativeCallbackSelfAwakeOther", "awakeAfterUsingCoder", [], false); + expectKeptThroughNativeDrop(state, function (receiver) { + TNSOwnedReturns.awakeAndDrop(receiver); + }, 1, done); + }); + + function expectBalancedJsCopies(answersReceiver, name, done) { + var state = ownedReturnState(TNSOwnedReturns, name, "copyWithZone", [NSCopying], answersReceiver); + for (var i = 0; i < 20; i++) { + expect(state.receiver.copy()).toBe(state.result); + } + settle(3, function () { + var freed = deallocs(); + expect(freed).toBe(0); + if (freed === 0) { + expect(state.receiver.hash > 0).toBe(true); + expect(state.result.hash > 0).toBe(true); + } + state.receiver = null; + state.result = null; + settle(3, function () { + expect(deallocs()).toBe(answersReceiver ? 1 : 2); + done(); + }); + }); + } + + it("balances copy() called from JS on a JS copyWithZone that answers its receiver", function (done) { + expectBalancedJsCopies(true, "NativeCallbackSelfJsCopySelf", done); + }); + + it("balances copy() called from JS on a JS copyWithZone that answers another object", function (done) { + expectBalancedJsCopies(false, "NativeCallbackSelfJsCopyOther", done); + }); }); From ee9fd8a9bf570eb57d0dfd6ef4f78bde86b436d5 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 14 Nov 2026 16:26:10 -0300 Subject: [PATCH 2/9] fix(runtime): do not read an unwritten return slot when retaining an owned result SetValue writes a JS string only into an id or interface return slot and leaves an instancetype slot untouched, so the retain for owned results must not treat a string answered for an instancetype return as an object it can retain. --- NativeScript/runtime/ArgConverter.mm | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/NativeScript/runtime/ArgConverter.mm b/NativeScript/runtime/ArgConverter.mm index 78cae0ece..fab27bfea 100644 --- a/NativeScript/runtime/ArgConverter.mm +++ b/NativeScript/runtime/ArgConverter.mm @@ -69,11 +69,13 @@ void RetainOwnedResult(Isolate* isolate, NativeReturnOwnership ownership, void** } // A plain JS object becomes a DictionaryAdapter SetValue already returns - // at +1. + // at +1. SetValue writes a string only into an id or interface slot; for + // instancetype it leaves the slot unwritten. value = tns::UnwrapProxy(value); BaseDataWrapper* wrapper = value->IsObject() ? tns::GetValue(isolate, value) : nullptr; bool atPlusZero = - value->IsString() || (wrapper != nullptr && wrapper->Type() == WrapperType::ObjCObject); + (value->IsString() && type != BinaryTypeEncodingType::InstanceTypeEncoding) || + (wrapper != nullptr && wrapper->Type() == WrapperType::ObjCObject); if (atPlusZero) { [returned retain]; } From fccb35aa7cf006d0fddf97402587a81bedee8e04 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 14 Nov 2026 19:45:44 -0300 Subject: [PATCH 3/9] fix(runtime): balance consumed arguments and JS property getters with owned returns -[NSKeyedUnarchiverDelegate unarchiver:didDecodeObject:] receives its object argument at +1 (NS_RELEASES_ARGUMENT) and returns at +1. A JS implementation that answered that same object was balanced only by accident before owned results were retained, and now leaked one reference per decoded object; one that answered another object, or nil, never released the argument at all. The metadata does not record consumed parameters, so Interop::ConsumesArgument names this one: MethodCallback neither retains nor releases an answered consumed argument and releases it otherwise, and a call from JS to a native implementation hands the callee the reference it consumes, which the cached-owned-return release then balances. Getters that JS implements, through extend() or by redefining a native class's property, returned with SetValue alone, so native callers of a copy/new-family getter got +0 where they own +1 and over-released the result. They now take the same RetainOwnedResult path as methods, classified by ArgConverter::ReturnOwnership from the getter's metadata. Specs cover the unarchiver delegate (unchanged, substituted and nil answers against a delegate-less control), a native delegate called from JS, JS new-family getters read natively and from JS, methods without metadata classified by name, JS replacements of a native class's owned-return method and getter, and a native -init that runs a JS method on its receiver. --- NativeScript/runtime/ArgConverter.h | 10 + NativeScript/runtime/ArgConverter.mm | 86 +++--- NativeScript/runtime/ClassBuilder.mm | 7 +- NativeScript/runtime/Interop.h | 4 + NativeScript/runtime/Interop.mm | 12 + NativeScript/runtime/MetadataBuilder.mm | 6 +- TestFixtures/Marshalling/TNSAllocLog.h | 39 ++- TestFixtures/Marshalling/TNSAllocLog.m | 63 ++++- .../app/tests/NativeCallbackSelfTests.js | 245 +++++++++++++++++- 9 files changed, 431 insertions(+), 41 deletions(-) diff --git a/NativeScript/runtime/ArgConverter.h b/NativeScript/runtime/ArgConverter.h index 7a889ba34..b01ea5f3e 100644 --- a/NativeScript/runtime/ArgConverter.h +++ b/NativeScript/runtime/ArgConverter.h @@ -87,6 +87,16 @@ class ArgConverter { // their selector's method family. static NativeReturnOwnership ReturnOwnership(SEL selector, const MethodMeta* meta); + // Gives the native caller of a JS implementation the reference it owns of + // the object SetValue wrote into retValue. `consumedArgument`, an argument + // the method took over, already carries that reference when it is the + // result. + static void RetainOwnedResult(v8::Isolate* isolate, + NativeReturnOwnership ownership, + void** argValues, void* retValue, + const TypeEncoding* typeEncoding, + v8::Local value, + id consumedArgument = nil); // returnSize is the ABI size of the return slot (cif->rtype->size); an // empty, null or undefined value zeroes all of it. static void SetValue(v8::Local context, void* retValue, diff --git a/NativeScript/runtime/ArgConverter.mm b/NativeScript/runtime/ArgConverter.mm index fab27bfea..0f7b98a23 100644 --- a/NativeScript/runtime/ArgConverter.mm +++ b/NativeScript/runtime/ArgConverter.mm @@ -48,37 +48,11 @@ bool InMethodFamily(SEL selector, const char* family) { return strncmp(name, family, length) == 0 && (name[length] < 'a' || name[length] > 'z'); } -// SetValue hands a wrapped object or a string over at +0, so an owned result -// gets a reference of its own, except a receiver answered in place of itself: -// that is the reference the caller passed in. The receiver is never released -// when another object is answered instead: a super initializer that -// substituted it already did, and nothing here can tell that case apart. -void RetainOwnedResult(Isolate* isolate, NativeReturnOwnership ownership, void** argValues, - void* retValue, const TypeEncoding* typeEncoding, Local value) { +bool IsObjectEncoding(const TypeEncoding* typeEncoding) { BinaryTypeEncodingType type = typeEncoding->type; - if (type != BinaryTypeEncodingType::IdEncoding && - type != BinaryTypeEncodingType::InterfaceDeclarationReference && - type != BinaryTypeEncodingType::InstanceTypeEncoding) { - return; - } - - id returned = *static_cast(retValue); - if (returned == nil || (ownership == NativeReturnOwnership::ReplacesReceiver && - returned == *static_cast(argValues[0]))) { - return; - } - - // A plain JS object becomes a DictionaryAdapter SetValue already returns - // at +1. SetValue writes a string only into an id or interface slot; for - // instancetype it leaves the slot unwritten. - value = tns::UnwrapProxy(value); - BaseDataWrapper* wrapper = value->IsObject() ? tns::GetValue(isolate, value) : nullptr; - bool atPlusZero = - (value->IsString() && type != BinaryTypeEncodingType::InstanceTypeEncoding) || - (wrapper != nullptr && wrapper->Type() == WrapperType::ObjCObject); - if (atPlusZero) { - [returned retain]; - } + return type == BinaryTypeEncodingType::IdEncoding || + type == BinaryTypeEncodingType::InterfaceDeclarationReference || + type == BinaryTypeEncodingType::InstanceTypeEncoding; } // The borrowed wrapper WrapNativeCallbackSelf made for an object in -dealloc @@ -409,6 +383,8 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {} std::vector> v8Args; v8Args.reserve(data->paramsCount_); + SEL selector = data->initialParamIndex_ == 2 ? *static_cast(argValues[1]) : nullptr; + id consumedArgument = nil; const TypeEncoding* typeEncoding = data->typeEncoding_; for (int i = 0; i < data->paramsCount_; i++) { typeEncoding = typeEncoding->next(); @@ -419,6 +395,10 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {} } int argIndex = i + data->initialParamIndex_; + if (selector != nullptr && Interop::ConsumesArgument(selector, i) && + IsObjectEncoding(typeEncoding)) { + consumedArgument = *static_cast(argValues[argIndex]); + } uint8_t* argBuffer = (uint8_t*)argValues[argIndex]; BaseCall call(argBuffer); @@ -517,14 +497,19 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {} memset(retValue, 0, cif->rtype->size); } else { ArgConverter::SetValue(context, retValue, cif->rtype->size, result, data->typeEncoding_); - if (data->returnOwnership_ != NativeReturnOwnership::Unowned) { - RetainOwnedResult(isolate, data->returnOwnership_, argValues, retValue, - data->typeEncoding_, result); - } + ArgConverter::RetainOwnedResult(isolate, data->returnOwnership_, argValues, retValue, + data->typeEncoding_, result, consumedArgument); } } else { memset(retValue, 0, cif->rtype->size); } + + // The call owns the argument it consumed and hands that reference on only + // by answering it. A wrapper JS made for the argument holds its own. + if (consumedArgument != nil && !(IsObjectEncoding(data->typeEncoding_) && + *static_cast(retValue) == consumedArgument)) { + [consumedArgument release]; + } } // all V8 scopes destruct here if (pendingThrow != nil) { @@ -532,6 +517,39 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {} } } +// SetValue hands a wrapped object or a string over at +0, so an owned result +// gets a reference of its own, except a receiver answered in place of itself: +// that is the reference the caller passed in. The receiver is never released +// when another object is answered instead: a super initializer that +// substituted it already did, and nothing here can tell that case apart. +void ArgConverter::RetainOwnedResult(Isolate* isolate, NativeReturnOwnership ownership, + void** argValues, void* retValue, + const TypeEncoding* typeEncoding, Local value, + id consumedArgument) { + if (ownership == NativeReturnOwnership::Unowned || !IsObjectEncoding(typeEncoding)) { + return; + } + + id returned = *static_cast(retValue); + if (returned == nil || returned == consumedArgument || + (ownership == NativeReturnOwnership::ReplacesReceiver && + returned == *static_cast(argValues[0]))) { + return; + } + + // A plain JS object becomes a DictionaryAdapter SetValue already returns + // at +1. SetValue writes a string only into an id or interface slot; for + // instancetype it leaves the slot unwritten. + value = tns::UnwrapProxy(value); + BaseDataWrapper* wrapper = value->IsObject() ? tns::GetValue(isolate, value) : nullptr; + bool atPlusZero = + (value->IsString() && typeEncoding->type != BinaryTypeEncodingType::InstanceTypeEncoding) || + (wrapper != nullptr && wrapper->Type() == WrapperType::ObjCObject); + if (atPlusZero) { + [returned retain]; + } +} + NativeReturnOwnership ArgConverter::ReturnOwnership(SEL selector, const MethodMeta* meta) { bool isInitializer = meta != nullptr ? meta->isInitializer() : InMethodFamily(selector, "init"); if (Interop::ConsumesReceiver(selector, isInitializer)) { diff --git a/NativeScript/runtime/ClassBuilder.mm b/NativeScript/runtime/ClassBuilder.mm index 40289ae9e..507879f05 100644 --- a/NativeScript/runtime/ClassBuilder.mm +++ b/NativeScript/runtime/ClassBuilder.mm @@ -933,8 +933,13 @@ new MethodCallbackWrapper(isolate, poCallback, 2, argsCount, typeEncoding, // Default getter result on a JS throw: zeroed return buffer. memset(retValue, 0, cif->rtype->size); } else { - const TypeEncoding* typeEncoding = context->meta_->getter()->encodings()->first(); + const MethodMeta* getterMeta = context->meta_->getter(); + const TypeEncoding* typeEncoding = getterMeta->encodings()->first(); ArgConverter::SetValue(v8Context, retValue, cif->rtype->size, res, typeEncoding); + ArgConverter::RetainOwnedResult( + isolate, + ArgConverter::ReturnOwnership(*static_cast(argValues[1]), getterMeta), + argValues, retValue, typeEncoding, res); } } if (pendingThrow != nil) { diff --git a/NativeScript/runtime/Interop.h b/NativeScript/runtime/Interop.h index 8bfd7d578..e40a4d3ed 100644 --- a/NativeScript/runtime/Interop.h +++ b/NativeScript/runtime/Interop.h @@ -119,6 +119,10 @@ class Interop { // reference to it: the init family, and NS_REPLACES_RECEIVER methods, which // the metadata does not record. static bool ConsumesReceiver(SEL selector, bool isInitializer); + // Whether a method takes over the caller's reference to its argument at + // `index`, counted from the first after the selector: NS_RELEASES_ARGUMENT + // parameters, which the metadata does not record. + static bool ConsumesArgument(SEL selector, int index); // Whether an owned object result that already has a wrapper carries a +1 // the caller must drop, the Instances entry holding its own reference. static bool ReleasesCachedOwnedReturn(bool ownsReturnedObject, diff --git a/NativeScript/runtime/Interop.mm b/NativeScript/runtime/Interop.mm index 8bc057b67..68d6fbd0b 100644 --- a/NativeScript/runtime/Interop.mm +++ b/NativeScript/runtime/Interop.mm @@ -172,6 +172,10 @@ return isInitializer || selector == @selector(awakeAfterUsingCoder:); } +bool Interop::ConsumesArgument(SEL selector, int index) { + return index == 1 && selector == @selector(unarchiver:didDecodeObject:); +} + // Balanced only while every owned result other than a consumed receiver // reaches here at +1, JS-implemented methods included: MethodCallback retains // what a JS implementation answers at +0, and for initializers anything but @@ -1838,6 +1842,14 @@ throw NativeScriptException( Interop::SetFFIParams(methodCall.context_, methodCall.typeEncoding_, &call, argsCount, initialParameterIndex, methodCall.args_); + if (initialParameterIndex > 1) { + for (int i = initialParameterIndex; i < argsCount; i++) { + if (ConsumesArgument(methodCall.selector_, i - initialParameterIndex)) { + [*static_cast(call.ArgumentBuffer(i)) retain]; + } + } + } + void* errorRef = nullptr; if (methodCall.provideErrorOutParameter_) { void* dest = call.ArgumentBuffer(argsCount); diff --git a/NativeScript/runtime/MetadataBuilder.mm b/NativeScript/runtime/MetadataBuilder.mm index c2add51ec..8ceedd9ee 100644 --- a/NativeScript/runtime/MetadataBuilder.mm +++ b/NativeScript/runtime/MetadataBuilder.mm @@ -1478,8 +1478,12 @@ new MethodCallbackWrapper(isolate, poCallback, 2, argsCount, typeEncoding, } memset(retValue, 0, cif->rtype->size); } else { - const TypeEncoding* typeEncoding = context->meta_->getter()->encodings()->first(); + const MethodMeta* getterMeta = context->meta_->getter(); + const TypeEncoding* typeEncoding = getterMeta->encodings()->first(); ArgConverter::SetValue(v8Context, retValue, cif->rtype->size, res, typeEncoding); + ArgConverter::RetainOwnedResult( + isolate, ArgConverter::ReturnOwnership(*static_cast(argValues[1]), getterMeta), + argValues, retValue, typeEncoding, res); } } if (pendingThrow != nil) { diff --git a/TestFixtures/Marshalling/TNSAllocLog.h b/TestFixtures/Marshalling/TNSAllocLog.h index a384c36db..71f436038 100644 --- a/TestFixtures/Marshalling/TNSAllocLog.h +++ b/TestFixtures/Marshalling/TNSAllocLog.h @@ -26,10 +26,47 @@ // Answers a new TNSAllocLog. - (id)newChild; +// Its getter answers a new TNSAllocLog, owned by the caller. +@property(nonatomic, readonly) id newItem; + + (void)copyAndDrop:(id)object; + (void)mutableCopyAndDrop:(id)object; -+ (void)newChildAndDrop:(TNSOwnedReturns*)object; ++ (void)newChildAndDrop:(id)object; + (void)awakeAndDrop:(id)object; ++ (void)newItemAndDrop:(id)object; +// Answers `newItem` of `object` without passing ownership on. ++ (id)readNewItemOf:(id)object; + +@end + +// Declares the owned-return members of TNSOwnedReturns itself, so JS can +// replace them on this class alone: metadata leaves out members a subclass +// redeclares. +@interface TNSSwizzledOwnedReturns : TNSAllocLog + +- (id)newChild; + +@property(nonatomic, readonly) id newItem; + +@end + +// A TNSAllocLog that survives a keyed archive. +@interface TNSCodingAllocLog : TNSAllocLog + +@end + +// Implements NSKeyedUnarchiverDelegate: answers the object it is given, or a +// new TNSAllocLog once `substitutes` is set. +@interface TNSDecodeDelegate : NSObject + +@property(nonatomic) BOOL substitutes; + +@end + +// -init sends -initHook to the receiver before returning it. +@interface TNSInitCallsHook : TNSAllocLog + +- (void)initHook; @end diff --git a/TestFixtures/Marshalling/TNSAllocLog.m b/TestFixtures/Marshalling/TNSAllocLog.m index c70b76bd2..1eedb09b3 100644 --- a/TestFixtures/Marshalling/TNSAllocLog.m +++ b/TestFixtures/Marshalling/TNSAllocLog.m @@ -46,7 +46,7 @@ + (void)mutableCopyAndDrop:(id)object { (void)result; } -+ (void)newChildAndDrop:(TNSOwnedReturns*)object { ++ (void)newChildAndDrop:(id)object { id result = [object newChild]; (void)result; } @@ -57,4 +57,65 @@ + (void)awakeAndDrop:(id)object { (void)result; } +- (id)newItem { + return [[TNSAllocLog alloc] init]; +} + ++ (void)newItemAndDrop:(id)object { + id result = [object newItem]; + (void)result; +} + ++ (id)readNewItemOf:(id)object { + return [object newItem]; +} + +@end + +@implementation TNSSwizzledOwnedReturns + +- (id)newChild { + return [[TNSAllocLog alloc] init]; +} + +- (id)newItem { + return [[TNSAllocLog alloc] init]; +} + +@end + +@implementation TNSCodingAllocLog + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder*)coder { + return [super init]; +} + +- (void)encodeWithCoder:(NSCoder*)coder { +} + +@end + +@implementation TNSDecodeDelegate + +- (id)unarchiver:(NSKeyedUnarchiver*)unarchiver didDecodeObject:(id)object { + return self.substitutes ? [[TNSAllocLog alloc] init] : object; +} + +@end + +@implementation TNSInitCallsHook + +- (instancetype)init { + self = [super init]; + [self initHook]; + return self; +} + +- (void)initHook { +} + @end diff --git a/TestRunner/app/tests/NativeCallbackSelfTests.js b/TestRunner/app/tests/NativeCallbackSelfTests.js index 9822939d6..7f82bfea6 100644 --- a/TestRunner/app/tests/NativeCallbackSelfTests.js +++ b/TestRunner/app/tests/NativeCallbackSelfTests.js @@ -526,13 +526,22 @@ describe("Native callback self wrappers", function () { }); } - function ownedReturnState(base, name, method, protocols, answersReceiver) { + function ownedReturnState(base, name, method, protocols, answersReceiver, extra) { var state = {}; var implementation = {}; - implementation[method] = function () { + var answer = function () { return answersReceiver ? this : state.result; }; - var Klass = base.extend(implementation, { name: name, protocols: protocols }); + // `extra.getter` implements `method` as a property getter; + // `extra.exposedMethods` declares it to a class that has no metadata + // for it. + extra = extra || {}; + if (extra.getter) { + Object.defineProperty(implementation, method, { get: answer, enumerable: true, configurable: true }); + } else { + implementation[method] = answer; + } + var Klass = base.extend(implementation, { name: name, protocols: protocols, exposedMethods: extra.exposedMethods }); state.receiver = Klass.new(); state.result = answersReceiver ? state.receiver : TNSAllocLog.new(); return state; @@ -617,4 +626,234 @@ describe("Native callback self wrappers", function () { it("balances copy() called from JS on a JS copyWithZone that answers another object", function (done) { expectBalancedJsCopies(false, "NativeCallbackSelfJsCopyOther", done); }); + + it("hands a native caller the object a JS new-family method without metadata answers at +1", function (done) { + var state = ownedReturnState(TNSAllocLog, "NativeCallbackSelfExposedNew", "newChild", [], false, { + exposedMethods: { newChild: { returns: NSObject, params: [] } } + }); + expectKeptThroughNativeDrop(state, function (receiver) { + TNSOwnedReturns.newChildAndDrop(receiver); + }, 2, done); + }); + + function ownedGetterState(answersReceiver, name) { + return ownedReturnState(TNSOwnedReturns, name, "newItem", [], answersReceiver, { getter: true }); + } + + it("hands a native caller the other object a JS new-family getter answers at +1", function (done) { + var state = ownedGetterState(false, "NativeCallbackSelfGetterOther"); + expectKeptThroughNativeDrop(state, function (receiver) { + TNSOwnedReturns.newItemAndDrop(receiver); + }, 2, done); + }); + + it("hands a native caller the receiver a JS new-family getter answers at +1", function (done) { + var state = ownedGetterState(true, "NativeCallbackSelfGetterSelf"); + expectKeptThroughNativeDrop(state, function (receiver) { + TNSOwnedReturns.newItemAndDrop(receiver); + }, 1, done); + }); + + function expectBalancedGetterReads(answersReceiver, name, done) { + var state = ownedGetterState(answersReceiver, name); + for (var i = 0; i < 20; i++) { + expect(state.receiver.newItem).toBe(state.result); + expect(TNSOwnedReturns.readNewItemOf(state.receiver)).toBe(state.result); + } + expectKeptThroughNativeDrop(state, function () {}, answersReceiver ? 1 : 2, done); + } + + it("balances reads of a JS new-family getter that answers another object", function (done) { + expectBalancedGetterReads(false, "NativeCallbackSelfGetterReadsOther", done); + }); + + it("balances reads of a JS new-family getter that answers its receiver", function (done) { + expectBalancedGetterReads(true, "NativeCallbackSelfGetterReadsSelf", done); + }); + + // The replacements stay installed for the rest of the run, on a class no + // other spec uses, and answer what `swizzled.answer` gives them. + var swizzled = { installed: false, answer: null }; + + function swizzledState(answersReceiver) { + if (!swizzled.installed) { + swizzled.installed = true; + TNSSwizzledOwnedReturns.prototype.newChild = function () { + return swizzled.answer(this); + }; + Object.defineProperty(TNSSwizzledOwnedReturns.prototype, "newItem", { + get: function () { + return swizzled.answer(this); + }, + configurable: true + }); + } + var state = { receiver: TNSSwizzledOwnedReturns.new() }; + state.result = answersReceiver ? state.receiver : TNSAllocLog.new(); + swizzled.answer = function (self) { + return answersReceiver ? self : state.result; + }; + return state; + } + + it("hands a native caller the other object a JS replacement of a new-family method answers at +1", function (done) { + var state = swizzledState(false); + expectKeptThroughNativeDrop(state, function (receiver) { + TNSOwnedReturns.newChildAndDrop(receiver); + }, 2, done); + }); + + it("hands a native caller the receiver a JS replacement of a new-family method answers at +1", function (done) { + var state = swizzledState(true); + expectKeptThroughNativeDrop(state, function (receiver) { + TNSOwnedReturns.newChildAndDrop(receiver); + }, 1, done); + }); + + it("hands a native caller the other object a JS replacement of a new-family getter answers at +1", function (done) { + var state = swizzledState(false); + expectKeptThroughNativeDrop(state, function (receiver) { + TNSOwnedReturns.newItemAndDrop(receiver); + expect(TNSOwnedReturns.readNewItemOf(receiver)).toBe(state.result); + }, 2, done); + }); + + it("frees once an object whose native -init ran a JS method on it (alloc().init())", function (done) { + var hooks = 0; + var Hooked = TNSInitCallsHook.extend({ + initHook: function () { + hooks++; + this.hooked = true; + } + }, { name: "NativeCallbackSelfInitHook" }); + var obj = Hooked.alloc().init(); + expect(hooks).toBe(1); + expect(obj.hooked).toBe(true); + settle(3, function () { + expect(deallocs()).toBe(0); + expect(obj.hash > 0).toBe(true); + obj = null; + settle(3, function () { + expect(deallocs()).toBe(1); + done(); + }); + }); + }); + + // -unarchiver:didDecodeObject: takes over the object it is given + // (NS_RELEASES_ARGUMENT) and answers an owned one. + var decodeAnswer = null; + var decodeCalls = 0; + var DecodeDelegate = NSObject.extend({ + unarchiverDidDecodeObject: function (unarchiver, object) { + decodeCalls++; + return decodeAnswer(object); + } + }, { name: "NativeCallbackSelfDecodeDelegate", protocols: [NSKeyedUnarchiverDelegate] }); + + // Decodes an array of two TNSCodingAllocLogs through a delegate answering + // `answer(object)`, or through none when `answer` is null. `freedAfterDecode` + // TNSAllocLogs are gone once the unarchiver is, `freedAtEnd` once JS + // drops the decoded root too. + function expectBalancedDecode(answer, freedAfterDecode, freedAtEnd, checkRoot, done) { + var data = (function () { + var root = NSMutableArray.new(); + root.addObject(TNSCodingAllocLog.new()); + root.addObject(TNSCodingAllocLog.new()); + return NSKeyedArchiver.archivedDataWithRootObjectRequiringSecureCodingError(root, false); + })(); + settle(3, function () { + expect(deallocs()).toBe(2); + TNSClearOutput(); + var state = {}; + (function () { + var delegate = answer ? DecodeDelegate.new() : null; + decodeAnswer = answer; + decodeCalls = 0; + var unarchiver = NSKeyedUnarchiver.alloc().initForReadingFromDataError(data); + unarchiver.requiresSecureCoding = false; + unarchiver.delegate = delegate; + state.root = unarchiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey); + unarchiver.finishDecoding(); + unarchiver.delegate = null; + decodeAnswer = null; + })(); + expect(decodeCalls).toBe(answer ? 3 : 0); + settle(3, function () { + expect(deallocs()).toBe(freedAfterDecode); + checkRoot(state.root); + state.root = null; + settle(3, function () { + expect(deallocs()).toBe(freedAtEnd); + done(); + }); + }); + }); + } + + function expectDecodedRoot(elementClass) { + return function (root) { + expect(root instanceof NSArray).toBe(true); + expect(root.count).toBe(2); + for (var i = 0; i < root.count; i++) { + var element = root.objectAtIndex(i); + expect(element instanceof elementClass).toBe(true); + expect(element.hash > 0).toBe(true); + } + }; + } + + it("decodes without an unarchiver delegate", function (done) { + expectBalancedDecode(null, 0, 2, expectDecodedRoot(TNSCodingAllocLog), done); + }); + + it("hands an unarchiver back the objects a JS delegate answers unchanged", function (done) { + expectBalancedDecode(function (object) { + return object; + }, 0, 2, expectDecodedRoot(TNSCodingAllocLog), done); + }); + + it("releases the objects a JS unarchiver delegate replaces", function (done) { + expectBalancedDecode(function (object) { + return object instanceof TNSCodingAllocLog ? TNSAllocLog.new() : object; + }, 2, 4, function (root) { + expectDecodedRoot(TNSAllocLog)(root); + expect(root.objectAtIndex(0) instanceof TNSCodingAllocLog).toBe(false); + }, done); + }); + + // The unarchiver keeps an object its delegate answers nil for. + it("releases the objects a JS unarchiver delegate answers nil for", function (done) { + expectBalancedDecode(function (object) { + return null; + }, 0, 2, expectDecodedRoot(TNSCodingAllocLog), done); + }); + + it("gives a native unarchiver delegate called from JS the reference it takes over", function (done) { + var delegate = TNSDecodeDelegate.new(); + var object = TNSAllocLog.new(); + var i; + for (i = 0; i < 20; i++) { + expect(delegate.unarchiverDidDecodeObject(null, object)).toBe(object); + } + delegate.substitutes = true; + for (i = 0; i < 20; i++) { + var other = delegate.unarchiverDidDecodeObject(null, object); + expect(other instanceof TNSAllocLog).toBe(true); + expect(other).not.toBe(object); + } + other = null; + settle(3, function () { + var freed = deallocs(); + expect(freed).toBe(20); + if (freed === 20) { + expect(object.hash > 0).toBe(true); + } + object = null; + settle(3, function () { + expect(deallocs()).toBe(21); + done(); + }); + }); + }); }); From 4598259575ac1756c9ecad7e452e1acaa76b2fa6 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 14 Nov 2026 20:38:29 -0300 Subject: [PATCH 4/9] fix(runtime): own unarchiver delegate results without metadata and release consumed arguments on rejected calls A JS class that implements -unarchiver:didDecodeObject: through exposedMethods, without declaring NSKeyedUnarchiverDelegate, has no metadata, and the selector-family classification called it unowned. A substituted object then went back to the unarchiver at +0 and was freed while the decoded graph still held it. Interop::ReturnsRetained records the selector's retained result next to its consumed argument, and the no-metadata branch of ArgConverter::ReturnOwnership consults it. MethodCallback's two isolate-validity guards answered nil without releasing the argument the method consumes, leaking it for every call rejected during teardown. The consumed argument is now found once, before the guards, from the native call alone, and both guards release it. --- NativeScript/runtime/ArgConverter.mm | 35 +++++++--- NativeScript/runtime/Interop.h | 4 ++ NativeScript/runtime/Interop.mm | 4 ++ .../app/tests/NativeCallbackSelfTests.js | 70 ++++++++++++------- 4 files changed, 79 insertions(+), 34 deletions(-) diff --git a/NativeScript/runtime/ArgConverter.mm b/NativeScript/runtime/ArgConverter.mm index 0f7b98a23..d43070914 100644 --- a/NativeScript/runtime/ArgConverter.mm +++ b/NativeScript/runtime/ArgConverter.mm @@ -55,6 +55,26 @@ bool IsObjectEncoding(const TypeEncoding* typeEncoding) { type == BinaryTypeEncodingType::InstanceTypeEncoding; } +// The argument a JS-implemented method takes over from its native caller, or +// nil. Reads only the native call, so it is usable without the isolate. +id ConsumedArgument(const MethodCallbackWrapper* data, void** argValues) { + if (data->initialParamIndex_ != 2) { + return nil; + } + SEL selector = *static_cast(argValues[1]); + for (int i = 0; i < data->paramsCount_; i++) { + if (!Interop::ConsumesArgument(selector, i)) { + continue; + } + const TypeEncoding* typeEncoding = data->typeEncoding_; + for (int j = 0; j <= i; j++) { + typeEncoding = typeEncoding->next(); + } + return IsObjectEncoding(typeEncoding) ? *static_cast(argValues[i + 2]) : nil; + } + return nil; +} + // 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. @@ -342,6 +362,8 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {} void ArgConverter::MethodCallback(ffi_cif* cif, void* retValue, void** argValues, void* userData) { MethodCallbackWrapper* data = static_cast(userData); + // Owned by this call, which gives it up on every path unless it answers it. + id consumedArgument = ConsumedArgument(data, argValues); Isolate* isolate = data->isolateWrapper_.Isolate(); @@ -358,6 +380,7 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {} IsolatePin pin = data->isolateWrapper_.Pin(); if (!pin || !data->isolateWrapper_.IsValid()) { memset(retValue, 0, cif->rtype->size); + [consumedArgument release]; return; } @@ -369,6 +392,7 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {} // what makes this second look reliable. if (!data->isolateWrapper_.IsValid()) { memset(retValue, 0, cif->rtype->size); + [consumedArgument release]; return; } Isolate::Scope isolate_scope(isolate); @@ -383,8 +407,6 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {} std::vector> v8Args; v8Args.reserve(data->paramsCount_); - SEL selector = data->initialParamIndex_ == 2 ? *static_cast(argValues[1]) : nullptr; - id consumedArgument = nil; const TypeEncoding* typeEncoding = data->typeEncoding_; for (int i = 0; i < data->paramsCount_; i++) { typeEncoding = typeEncoding->next(); @@ -395,10 +417,6 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {} } int argIndex = i + data->initialParamIndex_; - if (selector != nullptr && Interop::ConsumesArgument(selector, i) && - IsObjectEncoding(typeEncoding)) { - consumedArgument = *static_cast(argValues[argIndex]); - } uint8_t* argBuffer = (uint8_t*)argValues[argIndex]; BaseCall call(argBuffer); @@ -504,8 +522,7 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {} memset(retValue, 0, cif->rtype->size); } - // The call owns the argument it consumed and hands that reference on only - // by answering it. A wrapper JS made for the argument holds its own. + // A wrapper JS made for the consumed argument holds a reference of its own. if (consumedArgument != nil && !(IsObjectEncoding(data->typeEncoding_) && *static_cast(retValue) == consumedArgument)) { [consumedArgument release]; @@ -559,7 +576,7 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {} bool owned = meta != nullptr ? meta->ownsReturnedCocoaObject() : InMethodFamily(selector, "copy") || InMethodFamily(selector, "mutableCopy") || - InMethodFamily(selector, "new"); + InMethodFamily(selector, "new") || Interop::ReturnsRetained(selector); return owned ? NativeReturnOwnership::Owned : NativeReturnOwnership::Unowned; } diff --git a/NativeScript/runtime/Interop.h b/NativeScript/runtime/Interop.h index e40a4d3ed..de3328544 100644 --- a/NativeScript/runtime/Interop.h +++ b/NativeScript/runtime/Interop.h @@ -123,6 +123,10 @@ class Interop { // `index`, counted from the first after the selector: NS_RELEASES_ARGUMENT // parameters, which the metadata does not record. static bool ConsumesArgument(SEL selector, int index); + // Whether a method outside the copy, mutableCopy and new families answers + // an object its caller owns (NS_RETURNS_RETAINED), for implementations the + // metadata does not describe. + static bool ReturnsRetained(SEL selector); // Whether an owned object result that already has a wrapper carries a +1 // the caller must drop, the Instances entry holding its own reference. static bool ReleasesCachedOwnedReturn(bool ownsReturnedObject, diff --git a/NativeScript/runtime/Interop.mm b/NativeScript/runtime/Interop.mm index 68d6fbd0b..ae7be610f 100644 --- a/NativeScript/runtime/Interop.mm +++ b/NativeScript/runtime/Interop.mm @@ -172,10 +172,14 @@ return isInitializer || selector == @selector(awakeAfterUsingCoder:); } +// -[NSKeyedUnarchiverDelegate unarchiver:didDecodeObject:] is the only SDK +// method with an NS_RELEASES_ARGUMENT parameter; it also returns retained. bool Interop::ConsumesArgument(SEL selector, int index) { return index == 1 && selector == @selector(unarchiver:didDecodeObject:); } +bool Interop::ReturnsRetained(SEL selector) { return ConsumesArgument(selector, 1); } + // Balanced only while every owned result other than a consumed receiver // reaches here at +1, JS-implemented methods included: MethodCallback retains // what a JS implementation answers at +0, and for initializers anything but diff --git a/TestRunner/app/tests/NativeCallbackSelfTests.js b/TestRunner/app/tests/NativeCallbackSelfTests.js index 7f82bfea6..180485eaa 100644 --- a/TestRunner/app/tests/NativeCallbackSelfTests.js +++ b/TestRunner/app/tests/NativeCallbackSelfTests.js @@ -751,11 +751,24 @@ describe("Native callback self wrappers", function () { } }, { name: "NativeCallbackSelfDecodeDelegate", protocols: [NSKeyedUnarchiverDelegate] }); - // Decodes an array of two TNSCodingAllocLogs through a delegate answering - // `answer(object)`, or through none when `answer` is null. `freedAfterDecode` - // TNSAllocLogs are gone once the unarchiver is, `freedAtEnd` once JS - // drops the decoded root too. - function expectBalancedDecode(answer, freedAfterDecode, freedAtEnd, checkRoot, done) { + // The same method with no metadata to describe it. + var ExposedDecodeDelegate = NSObject.extend({ + "unarchiver:didDecodeObject:": function (unarchiver, object) { + decodeCalls++; + return decodeAnswer(object); + } + }, { + name: "NativeCallbackSelfExposedDecodeDelegate", + exposedMethods: { + "unarchiver:didDecodeObject:": { returns: NSObject, params: [NSObject, NSObject] } + } + }); + + // Decodes an array of two TNSCodingAllocLogs through a `Delegate` + // answering `answer(object)`, or through none when `answer` is null. + // `freedAfterDecode` TNSAllocLogs are gone once the unarchiver is, + // `freedAtEnd` once JS drops the decoded root too. + function expectBalancedDecode(Delegate, answer, freedAfterDecode, freedAtEnd, checkRoot, done) { var data = (function () { var root = NSMutableArray.new(); root.addObject(TNSCodingAllocLog.new()); @@ -767,7 +780,7 @@ describe("Native callback self wrappers", function () { TNSClearOutput(); var state = {}; (function () { - var delegate = answer ? DecodeDelegate.new() : null; + var delegate = answer ? Delegate.new() : null; decodeAnswer = answer; decodeCalls = 0; var unarchiver = NSKeyedUnarchiver.alloc().initForReadingFromDataError(data); @@ -804,29 +817,36 @@ describe("Native callback self wrappers", function () { } it("decodes without an unarchiver delegate", function (done) { - expectBalancedDecode(null, 0, 2, expectDecodedRoot(TNSCodingAllocLog), done); + expectBalancedDecode(null, null, 0, 2, expectDecodedRoot(TNSCodingAllocLog), done); }); - it("hands an unarchiver back the objects a JS delegate answers unchanged", function (done) { - expectBalancedDecode(function (object) { - return object; - }, 0, 2, expectDecodedRoot(TNSCodingAllocLog), done); - }); + [ + { Delegate: DecodeDelegate, suffix: "" }, + { Delegate: ExposedDecodeDelegate, suffix: " (exposedMethods, no protocol)" } + ].forEach(function (variant) { + var Delegate = variant.Delegate; - it("releases the objects a JS unarchiver delegate replaces", function (done) { - expectBalancedDecode(function (object) { - return object instanceof TNSCodingAllocLog ? TNSAllocLog.new() : object; - }, 2, 4, function (root) { - expectDecodedRoot(TNSAllocLog)(root); - expect(root.objectAtIndex(0) instanceof TNSCodingAllocLog).toBe(false); - }, done); - }); + it("hands an unarchiver back the objects a JS delegate answers unchanged" + variant.suffix, function (done) { + expectBalancedDecode(Delegate, function (object) { + return object; + }, 0, 2, expectDecodedRoot(TNSCodingAllocLog), done); + }); - // The unarchiver keeps an object its delegate answers nil for. - it("releases the objects a JS unarchiver delegate answers nil for", function (done) { - expectBalancedDecode(function (object) { - return null; - }, 0, 2, expectDecodedRoot(TNSCodingAllocLog), done); + it("releases the objects a JS unarchiver delegate replaces" + variant.suffix, function (done) { + expectBalancedDecode(Delegate, function (object) { + return object instanceof TNSCodingAllocLog ? TNSAllocLog.new() : object; + }, 2, 4, function (root) { + expectDecodedRoot(TNSAllocLog)(root); + expect(root.objectAtIndex(0) instanceof TNSCodingAllocLog).toBe(false); + }, done); + }); + + // The unarchiver keeps an object its delegate answers nil for. + it("releases the objects a JS unarchiver delegate answers nil for" + variant.suffix, function (done) { + expectBalancedDecode(Delegate, function (object) { + return null; + }, 0, 2, expectDecodedRoot(TNSCodingAllocLog), done); + }); }); it("gives a native unarchiver delegate called from JS the reference it takes over", function (done) { From 12f3c39599ab31ca45ea924bff0a17b673f57ae6 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 15 Nov 2026 13:23:03 -0300 Subject: [PATCH 5/9] fix(runtime): release owned results handed to JS as primitives Interop::GetResult converts NSNull, booleans, NSDate, NSString and NSNumber results to JS values before it looks for a wrapper, and returned without releasing a result the caller owned. Nothing else keeps a reference to such an object, so every owned one leaked: nsNumber.copy(), a copy or mutableCopy that JS receives as a string, a new-family or NS_RETURNS_RETAINED method answering a string, number or date, and the NSString a JS copyWithZone hands to a native -copy called from JS. Each conversion now drops the +1 after reading the object, by the same rule as a cached-wrapper hit: not for a receiver an initializer or awakeAfterUsingCoder: answered in place of itself, which carries no net reference. TNSOwnedPrimitives keeps a heap string, number and date (an NSDate subclass: Foundation tags every date JS can represent) and reports their retain counts, so the specs can see what JS only receives as primitives. --- NativeScript/runtime/Interop.h | 6 +- NativeScript/runtime/Interop.mm | 22 +++-- TestFixtures/Marshalling/TNSAllocLog.h | 13 +++ TestFixtures/Marshalling/TNSAllocLog.m | 58 +++++++++++++ .../app/tests/NativeCallbackSelfTests.js | 85 +++++++++++++++++++ 5 files changed, 177 insertions(+), 7 deletions(-) diff --git a/NativeScript/runtime/Interop.h b/NativeScript/runtime/Interop.h index de3328544..dee177996 100644 --- a/NativeScript/runtime/Interop.h +++ b/NativeScript/runtime/Interop.h @@ -127,8 +127,10 @@ class Interop { // an object its caller owns (NS_RETURNS_RETAINED), for implementations the // metadata does not describe. static bool ReturnsRetained(SEL selector); - // Whether an owned object result that already has a wrapper carries a +1 - // the caller must drop, the Instances entry holding its own reference. + // Whether an owned object result the runtime keeps no reference to carries + // a +1 the caller must drop: one that already has a wrapper, whose + // Instances entry holds its own reference, or one handed to JS as a + // primitive. static bool ReleasesCachedOwnedReturn(bool ownsReturnedObject, OwnedReturnReceiver receiver); static v8::Local GetResultByType( diff --git a/NativeScript/runtime/Interop.mm b/NativeScript/runtime/Interop.mm index ae7be610f..212fc2fe9 100644 --- a/NativeScript/runtime/Interop.mm +++ b/NativeScript/runtime/Interop.mm @@ -1336,23 +1336,34 @@ static bool SnapshotArrayLike(Isolate* isolate, Local object, Local boolean = v8::Boolean::New(isolate, [result boolValue]); + releaseSurplusOwnedReturn(); + return boolean; } if (marshalToPrimitive && [result isKindOfClass:[NSDate class]]) { double time = [result timeIntervalSince1970] * 1000.0; Local date; if (Date::New(context, time).ToLocal(&date)) { + releaseSurplusOwnedReturn(); return date; } std::ostringstream errorStream; errorStream << "Unable to convert " << [result description] << " to a Date object"; + releaseSurplusOwnedReturn(); std::string errorMessage = errorStream.str(); Local error = Exception::Error(tns::ToV8String(isolate, errorMessage)); isolate->ThrowException(error); @@ -1370,7 +1381,9 @@ static bool SnapshotArrayLike(Isolate* isolate, Local object, Local string = tns::ToV8String(isolate, result); + releaseSurplusOwnedReturn(); + return string; } } @@ -1378,6 +1391,7 @@ static bool SnapshotArrayLike(Isolate* isolate, Local object, Local object, Local cached = poInstance->Get(isolate); - if (ReleasesCachedOwnedReturn(ownsReturnedObject || isInitializer, ownedReturnReceiver)) { - [result release]; - } + releaseSurplusOwnedReturn(); return cached; } diff --git a/TestFixtures/Marshalling/TNSAllocLog.h b/TestFixtures/Marshalling/TNSAllocLog.h index 71f436038..e7aa63c49 100644 --- a/TestFixtures/Marshalling/TNSAllocLog.h +++ b/TestFixtures/Marshalling/TNSAllocLog.h @@ -39,6 +39,19 @@ @end +// Keeps one object of each kind JS receives as a primitive: at index 0 a +// string, 1 a number, 2 a date, none of them a tagged pointer. +@interface TNSOwnedPrimitives : NSObject + +// Answers the object at `index`, owned by the caller. +- (id)newObjectAt:(NSUInteger)index; +// Answers the object at `index` without passing ownership on. +- (id)objectAt:(NSUInteger)index; +- (NSUInteger)retainCountAt:(NSUInteger)index; +- (BOOL)isTaggedPointerAt:(NSUInteger)index; + +@end + // Declares the owned-return members of TNSOwnedReturns itself, so JS can // replace them on this class alone: metadata leaves out members a subclass // redeclares. diff --git a/TestFixtures/Marshalling/TNSAllocLog.m b/TestFixtures/Marshalling/TNSAllocLog.m index 1eedb09b3..d44ae715f 100644 --- a/TestFixtures/Marshalling/TNSAllocLog.m +++ b/TestFixtures/Marshalling/TNSAllocLog.m @@ -72,6 +72,64 @@ + (id)readNewItemOf:(id)object { @end +// Foundation answers tagged pointers for dates in the range JS can represent. +@interface TNSHeapDate : NSDate +@end + +@implementation TNSHeapDate { + NSTimeInterval _interval; +} + +// NSDate's initializers end in the one this class would have to override, so +// the instance is used uninitialized, which NSObject allows. ++ (instancetype)heapDateWithInterval:(NSTimeInterval)interval { + TNSHeapDate* date = [self alloc]; + date->_interval = interval; + return date; +} + +- (NSTimeInterval)timeIntervalSinceReferenceDate { + return _interval; +} + +@end + +@implementation TNSOwnedPrimitives { + NSArray* _objects; +} + +- (instancetype)init { + self = [super init]; + if (self) { + NSString* string = [[NSMutableString stringWithString:@"an owned string long enough to live on the heap"] copy]; + _objects = @[ string, [NSNumber numberWithDouble:M_PI], [TNSHeapDate heapDateWithInterval:700000000.5] ]; + } + return self; +} + +- (id)newObjectAt:(NSUInteger)index { + return _objects[index]; +} + +- (id)objectAt:(NSUInteger)index { + return _objects[index]; +} + +- (NSUInteger)retainCountAt:(NSUInteger)index { + return CFGetRetainCount((__bridge CFTypeRef)_objects[index]); +} + +- (BOOL)isTaggedPointerAt:(NSUInteger)index { + uintptr_t bits = (uintptr_t)(__bridge void*)_objects[index]; +#if __arm64__ + return (bits >> 63) != 0; +#else + return (bits & 1) != 0; +#endif +} + +@end + @implementation TNSSwizzledOwnedReturns - (id)newChild { diff --git a/TestRunner/app/tests/NativeCallbackSelfTests.js b/TestRunner/app/tests/NativeCallbackSelfTests.js index 180485eaa..b6809cc59 100644 --- a/TestRunner/app/tests/NativeCallbackSelfTests.js +++ b/TestRunner/app/tests/NativeCallbackSelfTests.js @@ -876,4 +876,89 @@ describe("Native callback self wrappers", function () { }); }); }); + + // JS receives these as primitives, so only the native side sees their + // reference counts. + var primitiveText = "an owned string long enough to live on the heap"; + var primitiveDateTime = (700000000.5 + 978307200) * 1000; + + function expectPrimitiveAt(index, value) { + if (index === 0) { + expect(value).toBe(primitiveText); + } else if (index === 1) { + expect(value).toBe(Math.PI); + } else { + expect(value instanceof Date).toBe(true); + expect(value.getTime()).toBe(primitiveDateTime); + } + } + + function expectPrimitivesRetainedAsBefore(read, done) { + var holder = TNSOwnedPrimitives.new(); + for (var i = 0; i < 3; i++) { + expect([i, holder.isTaggedPointerAt(i)]).toEqual([i, false]); + } + settle(2, function () { + var before = []; + for (var i = 0; i < 3; i++) { + before.push(holder.retainCountAt(i)); + for (var k = 0; k < 20; k++) { + expectPrimitiveAt(i, read(holder, i)); + } + } + settle(2, function () { + for (var i = 0; i < 3; i++) { + expect([i, holder.retainCountAt(i)]).toEqual([i, before[i]]); + } + done(); + }); + }); + } + + it("releases owned results JS receives as a string, a number and a date", function (done) { + expectPrimitivesRetainedAsBefore(function (holder, index) { + return holder.newObjectAt(index); + }, done); + }); + + it("leaves unowned results JS receives as primitives retained as they were", function (done) { + expectPrimitivesRetainedAsBefore(function (holder, index) { + return holder.objectAt(index); + }, done); + }); + + function copiesAsStringState(name, answer) { + var state = { answer: answer }; + var Copyable = TNSAllocLog.extend({ + copyWithZone: function () { + return state.answer; + } + }, { name: name, protocols: [NSCopying] }); + state.receiver = Copyable.new(); + return state; + } + + it("releases the string a native -copy answers for a JS copyWithZone returning an NSString", function (done) { + var text = primitiveText + ", wrapped"; + var state = copiesAsStringState("NativeCallbackSelfCopyToWrappedString", NSString.alloc().initWithString(text)); + settle(2, function () { + var before = state.answer.retainCount(); + for (var i = 0; i < 20; i++) { + expect(state.receiver.copy()).toBe(text); + } + settle(2, function () { + expect(state.answer.retainCount()).toBe(before); + done(); + }); + }); + }); + + // The NSString made for the JS string is never visible to JS, so only the + // answers are checked. + it("answers the string a JS copyWithZone returns through a native -copy", function () { + var state = copiesAsStringState("NativeCallbackSelfCopyToString", primitiveText); + for (var i = 0; i < 20; i++) { + expect(state.receiver.copy()).toBe(primitiveText); + } + }); }); From 5a6684476e09d970f12a71e604db65fe0a496d3c Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 15 Nov 2026 13:44:49 -0300 Subject: [PATCH 6/9] fix(runtime): release owned block results Interop::GetResult answered a block either with the JS function it was made for or with a function around its own Block_copy of a native block, and neither dropped a +1 the caller owned. An NS_RETURNS_RETAINED method or C function answering a block, dispatch_block_create among them, leaked the block and everything it captured; for a block made for a JS function that includes the function itself, rooted by the block's strong callback handle. The +1 is now released after the runtime holds what it keeps, by the same rule as owned object results. For a JS function's block that release can be the last one and run the dispose helper inline: it re-enters the Locker this thread holds, clears the function's wrapper slot and frees the callback wrapper, while the function handle already fetched stays valid. Method families do not apply to block results, so the fixtures declare ownership with NS_RETURNS_RETAINED. --- NativeScript/runtime/Interop.h | 8 +- NativeScript/runtime/Interop.mm | 14 +- TestFixtures/Marshalling/TNSAllocLog.h | 17 +++ TestFixtures/Marshalling/TNSAllocLog.m | 40 ++++++ .../app/tests/NativeCallbackSelfTests.js | 121 ++++++++++++++++++ 5 files changed, 195 insertions(+), 5 deletions(-) diff --git a/NativeScript/runtime/Interop.h b/NativeScript/runtime/Interop.h index dee177996..80f6d7b27 100644 --- a/NativeScript/runtime/Interop.h +++ b/NativeScript/runtime/Interop.h @@ -127,10 +127,10 @@ class Interop { // an object its caller owns (NS_RETURNS_RETAINED), for implementations the // metadata does not describe. static bool ReturnsRetained(SEL selector); - // Whether an owned object result the runtime keeps no reference to carries - // a +1 the caller must drop: one that already has a wrapper, whose - // Instances entry holds its own reference, or one handed to JS as a - // primitive. + // Whether the +1 of an owned object or block result is the caller's to + // drop once the runtime holds what it keeps: an Instances entry and a + // native block's wrapper hold references of their own, and a primitive or + // the JS function a block was made for keeps none. static bool ReleasesCachedOwnedReturn(bool ownsReturnedObject, OwnedReturnReceiver receiver); static v8::Local GetResultByType( diff --git a/NativeScript/runtime/Interop.mm b/NativeScript/runtime/Interop.mm index 212fc2fe9..433b3f67d 100644 --- a/NativeScript/runtime/Interop.mm +++ b/NativeScript/runtime/Interop.mm @@ -1052,6 +1052,9 @@ static bool SnapshotArrayLike(Isolate* isolate, Local object, LocalGetResult(); @@ -1192,6 +1195,12 @@ static bool SnapshotArrayLike(Isolate* isolate, Local object, Localdescriptor == &JSBlock::kJSBlockDescriptor) { MethodCallbackWrapper* wrapper = static_cast(block->userData); Local callback = wrapper->callback_->Get(isolate).As(); + // The last reference runs the dispose helper right here, under the + // Locker this thread holds, which frees `wrapper`; `callback` is a + // handle of its own and stays usable. + if (releasesOwnedReturn) { + Block_release(block); + } return callback; } @@ -1203,6 +1212,9 @@ static bool SnapshotArrayLike(Isolate* isolate, Local object, Local(Block_copy(block)); + if (releasesOwnedReturn) { + Block_release(block); + } BlockWrapper* blockWrapper = new BlockWrapper(ownedBlock, typeEncoding, true); Local ext = External::New(isolate, blockWrapper, v8::kExternalPointerTypeTagDefault); Local callback; @@ -1337,7 +1349,7 @@ static bool SnapshotArrayLike(Isolate* isolate, Local object, Local 0 ? 7 : -1; + }; + })(); + for (var i = 0; i < 20; i++) { + expect(answer(holder, state.fn)).toBe(state.fn); + } + settle(3, function () { + expect(deallocs()).toBe(0); + expect(state.fn()).toBe(7); + expect(TNSOwnedBlocks.callBlock(state.fn)).toBe(7); + expect(answer(holder, state.fn)).toBe(state.fn); + state.fn = null; + settle(3, function () { + expect(deallocs()).toBe(1); + done(); + }); + }); + } + + it("answers the JS function a block an owned-return method hands back was made for", function (done) { + expectJsBlockRoundTrips(function (holder, fn) { + return holder.retainedBlockFrom(fn); + }, done); + }); + + it("answers the JS function a block an unowned method hands back was made for", function (done) { + expectJsBlockRoundTrips(function (holder, fn) { + return holder.blockFrom(fn); + }, done); + }); + + // Once the autorelease pool has drained, the stored reference is the + // block's only one, so dropping it runs the block's dispose helper while + // the call that answered it is still marshalling the result. + it("answers the JS function of a block whose last reference an owned-return method hands back", function (done) { + var holder = TNSOwnedBlocks.new(); + var state = {}; + (function () { + var captured = TNSAllocLog.new(); + state.fn = function () { + return captured.hash > 0 ? 7 : -1; + }; + })(); + holder.storeBlock(state.fn); + settle(3, function () { + expect(deallocs()).toBe(0); + expect(holder.retainedStoredBlock()).toBe(state.fn); + expect(state.fn()).toBe(7); + expect(TNSOwnedBlocks.callBlock(state.fn)).toBe(7); + state.fn = null; + settle(3, function () { + expect(deallocs()).toBe(1); + done(); + }); + }); + }); + + it("frees what a JS function given to dispatch_block_create captures once JS drops the block", function (done) { + var state = { calls: 0 }; + (function () { + var captured = TNSAllocLog.new(); + state.block = dispatch_block_create(0, function () { + state.calls += captured.hash > 0 ? 1 : 0; + }); + })(); + state.block(); + state.block(); + expect(state.calls).toBe(2); + settle(3, function () { + expect(deallocs()).toBe(0); + state.block(); + expect(state.calls).toBe(3); + state.block = null; + settle(3, function () { + expect(deallocs()).toBe(1); + done(); + }); + }); + }); }); From 7c3341b92fda93f23f1f505557e30be3896346f2 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 15 Nov 2026 13:54:26 -0300 Subject: [PATCH 7/9] fix(runtime): do not retain a new DictionaryAdapter a JS owned-return method answers RetainOwnedResult inferred whether SetValue had handed its object over at +0 from the JS value afterwards: a value with an ObjCObject wrapper meant a wrapped object. A plain JS object is written as a new DictionaryAdapter at +1, but the adapter attaches its own ObjCObject claim to that object while it is created, so the check then saw a wrapped object and retained the adapter again. Every fresh plain object a JS owned-return method or JS initializer answered leaked its adapter, and the adapter's handle kept the JS object alive. SetValue now answers whether it wrote an object the caller does not own (a wrapped object, including an existing adapter, or a string made for an id or interface slot), and RetainOwnedResult takes that answer instead of re-deriving it. The TNSOwnedPrimitives fixture tests the tagged-pointer bit the ObjC runtime uses for the platform, which is the high bit on the x86_64 iOS simulator. --- NativeScript/runtime/ArgConverter.h | 20 ++-- NativeScript/runtime/ArgConverter.mm | 78 +++++++--------- NativeScript/runtime/ClassBuilder.mm | 6 +- NativeScript/runtime/MetadataBuilder.mm | 7 +- TestFixtures/Marshalling/TNSAllocLog.h | 12 +++ TestFixtures/Marshalling/TNSAllocLog.m | 35 ++++++- .../app/tests/NativeCallbackSelfTests.js | 92 +++++++++++++++++++ 7 files changed, 187 insertions(+), 63 deletions(-) diff --git a/NativeScript/runtime/ArgConverter.h b/NativeScript/runtime/ArgConverter.h index b01ea5f3e..fc3b52dce 100644 --- a/NativeScript/runtime/ArgConverter.h +++ b/NativeScript/runtime/ArgConverter.h @@ -88,18 +88,18 @@ class ArgConverter { static NativeReturnOwnership ReturnOwnership(SEL selector, const MethodMeta* meta); // Gives the native caller of a JS implementation the reference it owns of - // the object SetValue wrote into retValue. `consumedArgument`, an argument - // the method took over, already carries that reference when it is the - // result. - static void RetainOwnedResult(v8::Isolate* isolate, - NativeReturnOwnership ownership, + // the object SetValue wrote into retValue; `writtenUnowned` is what + // SetValue answered. `consumedArgument`, an argument the method took over, + // already carries that reference when it is the result. + static void RetainOwnedResult(NativeReturnOwnership ownership, void** argValues, void* retValue, - const TypeEncoding* typeEncoding, - v8::Local value, - id consumedArgument = nil); + bool writtenUnowned, id consumedArgument = nil); // returnSize is the ABI size of the return slot (cif->rtype->size); an - // empty, null or undefined value zeroes all of it. - static void SetValue(v8::Local context, void* retValue, + // empty, null or undefined value zeroes all of it. Answers whether it wrote + // an object the caller does not own: a wrapped object, or a string made + // for an id or interface slot. A plain JS object is written as a new + // DictionaryAdapter the caller owns. + static bool SetValue(v8::Local context, void* retValue, size_t returnSize, v8::Local value, const TypeEncoding* typeEncoding); // Returns (lazily creating) the per-isolate interop.escapeException brand diff --git a/NativeScript/runtime/ArgConverter.mm b/NativeScript/runtime/ArgConverter.mm index d43070914..139a4fe46 100644 --- a/NativeScript/runtime/ArgConverter.mm +++ b/NativeScript/runtime/ArgConverter.mm @@ -514,9 +514,10 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {} if (!success) { memset(retValue, 0, cif->rtype->size); } else { - ArgConverter::SetValue(context, retValue, cif->rtype->size, result, data->typeEncoding_); - ArgConverter::RetainOwnedResult(isolate, data->returnOwnership_, argValues, retValue, - data->typeEncoding_, result, consumedArgument); + bool writtenUnowned = ArgConverter::SetValue(context, retValue, cif->rtype->size, result, + data->typeEncoding_); + ArgConverter::RetainOwnedResult(data->returnOwnership_, argValues, retValue, writtenUnowned, + consumedArgument); } } else { memset(retValue, 0, cif->rtype->size); @@ -534,16 +535,14 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {} } } -// SetValue hands a wrapped object or a string over at +0, so an owned result -// gets a reference of its own, except a receiver answered in place of itself: -// that is the reference the caller passed in. The receiver is never released -// when another object is answered instead: a super initializer that -// substituted it already did, and nothing here can tell that case apart. -void ArgConverter::RetainOwnedResult(Isolate* isolate, NativeReturnOwnership ownership, - void** argValues, void* retValue, - const TypeEncoding* typeEncoding, Local value, - id consumedArgument) { - if (ownership == NativeReturnOwnership::Unowned || !IsObjectEncoding(typeEncoding)) { +// An owned result SetValue wrote at +0 gets a reference of its own, except a +// receiver answered in place of itself: that is the reference the caller +// passed in. The receiver is never released when another object is answered +// instead: a super initializer that substituted it already did, and nothing +// here can tell that case apart. +void ArgConverter::RetainOwnedResult(NativeReturnOwnership ownership, void** argValues, + void* retValue, bool writtenUnowned, id consumedArgument) { + if (ownership == NativeReturnOwnership::Unowned || !writtenUnowned) { return; } @@ -554,17 +553,7 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {} return; } - // A plain JS object becomes a DictionaryAdapter SetValue already returns - // at +1. SetValue writes a string only into an id or interface slot; for - // instancetype it leaves the slot unwritten. - value = tns::UnwrapProxy(value); - BaseDataWrapper* wrapper = value->IsObject() ? tns::GetValue(isolate, value) : nullptr; - bool atPlusZero = - (value->IsString() && typeEncoding->type != BinaryTypeEncodingType::InstanceTypeEncoding) || - (wrapper != nullptr && wrapper->Type() == WrapperType::ObjCObject); - if (atPlusZero) { - [returned retain]; - } + [returned retain]; } NativeReturnOwnership ArgConverter::ReturnOwnership(SEL selector, const MethodMeta* meta) { @@ -580,10 +569,10 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {} return owned ? NativeReturnOwnership::Owned : NativeReturnOwnership::Unowned; } -void ArgConverter::SetValue(Local context, void* retValue, size_t returnSize, +bool ArgConverter::SetValue(Local context, void* retValue, size_t returnSize, Local value, const TypeEncoding* typeEncoding) { if (typeEncoding->type == BinaryTypeEncodingType::VoidEncoding) { - return; + return false; } // Runs inside an ffi closure, where a C++ throw cannot propagate; a revoked @@ -593,7 +582,7 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {} value = tns::UnwrapProxy(value); if (value.IsEmpty() || value->IsNullOrUndefined()) { memset(retValue, 0, std::max(returnSize, sizeof(ffi_arg))); - return; + return false; } Isolate* isolate = v8::Isolate::GetCurrent(); @@ -604,52 +593,52 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {} if (tns::IsBool(value)) { bool boolValue = value.As()->Value(); *(ffi_arg*)retValue = (bool)boolValue; - return; + return false; } else if (tns::IsNumber(value)) { double numValue = tns::ToNumber(isolate, value); switch (type) { case BinaryTypeEncodingType::UShortEncoding: { *static_cast(retValue) = (unsigned short)numValue; - return; + return false; } case BinaryTypeEncodingType::ShortEncoding: { *static_cast(retValue) = (short)numValue; - return; + return false; } case BinaryTypeEncodingType::UIntEncoding: { *static_cast(retValue) = (unsigned int)numValue; - return; + return false; } case BinaryTypeEncodingType::IntEncoding: { *static_cast(retValue) = (int)numValue; - return; + return false; } case BinaryTypeEncodingType::ULongEncoding: { *static_cast(retValue) = (unsigned long)numValue; - return; + return false; } case BinaryTypeEncodingType::LongEncoding: { *static_cast(retValue) = (long)numValue; - return; + return false; } case BinaryTypeEncodingType::ULongLongEncoding: { *static_cast(retValue) = (unsigned long long)numValue; - return; + return false; } case BinaryTypeEncodingType::LongLongEncoding: { *static_cast(retValue) = (long long)numValue; - return; + return false; } case BinaryTypeEncodingType::FloatEncoding: { *static_cast(retValue) = (float)numValue; - return; + return false; } case BinaryTypeEncodingType::DoubleEncoding: { *static_cast(retValue) = numValue; - return; + return false; } default: - return; + return false; } } else if (value->IsString()) { if (type == BinaryTypeEncodingType::IdEncoding || @@ -660,7 +649,7 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {} auto ref = CFBridgingRetain(data); *(CFTypeRef*)retValue = ref; CFRelease(ref); - return; + return true; } } else if (value->IsObject()) { if (type == BinaryTypeEncodingType::InterfaceDeclarationReference || @@ -672,7 +661,7 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {} id data = wrapper->Data(); memset(retValue, 0, sizeof(id)); *static_cast(retValue) = data; - return; + return true; } else { id adapter = [[DictionaryAdapter alloc] initWithJSObject:tns::ProxyReadSource(original, value).As() @@ -680,7 +669,7 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {} memset(retValue, 0, sizeof(id)); *static_cast(retValue) = adapter; // CFAutorelease(adapter); - return; + return false; } } else if (type == BinaryTypeEncodingType::StructDeclarationReference) { BaseDataWrapper* baseWrapper = tns::GetValue(isolate, value); @@ -691,19 +680,20 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {} const StructMeta* structMeta = static_cast(meta); const StructInfo& structInfo = FFICall::GetStructInfo(structMeta); Interop::InitializeStruct(context, retValue, structInfo.Fields(), value); - return; + return false; } else if (baseWrapper->Type() == WrapperType::Struct) { StructWrapper* structWrapper = static_cast(baseWrapper); size_t size = structWrapper->StructInfo().FFIType()->size; void* data = structWrapper->Data(); memcpy(retValue, data, size); - return; + return false; } } } // TODO: Handle other return types, i.e. assign the retValue parameter from the v8 result tns::Assert(false, isolate); + return false; } void ArgConverter::ConstructObject(Local context, const FunctionCallbackInfo& info, diff --git a/NativeScript/runtime/ClassBuilder.mm b/NativeScript/runtime/ClassBuilder.mm index 507879f05..ac85a017c 100644 --- a/NativeScript/runtime/ClassBuilder.mm +++ b/NativeScript/runtime/ClassBuilder.mm @@ -935,11 +935,11 @@ new MethodCallbackWrapper(isolate, poCallback, 2, argsCount, typeEncoding, } else { const MethodMeta* getterMeta = context->meta_->getter(); const TypeEncoding* typeEncoding = getterMeta->encodings()->first(); - ArgConverter::SetValue(v8Context, retValue, cif->rtype->size, res, typeEncoding); + bool writtenUnowned = + ArgConverter::SetValue(v8Context, retValue, cif->rtype->size, res, typeEncoding); ArgConverter::RetainOwnedResult( - isolate, ArgConverter::ReturnOwnership(*static_cast(argValues[1]), getterMeta), - argValues, retValue, typeEncoding, res); + argValues, retValue, writtenUnowned); } } if (pendingThrow != nil) { diff --git a/NativeScript/runtime/MetadataBuilder.mm b/NativeScript/runtime/MetadataBuilder.mm index 8ceedd9ee..6a5d428d7 100644 --- a/NativeScript/runtime/MetadataBuilder.mm +++ b/NativeScript/runtime/MetadataBuilder.mm @@ -1480,10 +1480,11 @@ new MethodCallbackWrapper(isolate, poCallback, 2, argsCount, typeEncoding, } else { const MethodMeta* getterMeta = context->meta_->getter(); const TypeEncoding* typeEncoding = getterMeta->encodings()->first(); - ArgConverter::SetValue(v8Context, retValue, cif->rtype->size, res, typeEncoding); + bool writtenUnowned = + ArgConverter::SetValue(v8Context, retValue, cif->rtype->size, res, typeEncoding); ArgConverter::RetainOwnedResult( - isolate, ArgConverter::ReturnOwnership(*static_cast(argValues[1]), getterMeta), - argValues, retValue, typeEncoding, res); + ArgConverter::ReturnOwnership(*static_cast(argValues[1]), getterMeta), + argValues, retValue, writtenUnowned); } } if (pendingThrow != nil) { diff --git a/TestFixtures/Marshalling/TNSAllocLog.h b/TestFixtures/Marshalling/TNSAllocLog.h index 0e90704e8..d243c2e3b 100644 --- a/TestFixtures/Marshalling/TNSAllocLog.h +++ b/TestFixtures/Marshalling/TNSAllocLog.h @@ -36,6 +36,8 @@ + (void)newItemAndDrop:(id)object; // Answers `newItem` of `object` without passing ownership on. + (id)readNewItemOf:(id)object; +// Sends -init to a new instance of `cls` and drops what it answers. ++ (void)allocInitAndDrop:(Class)cls; @end @@ -52,6 +54,16 @@ @end +// Keeps what -copy answers until -drop. +@interface TNSCopyKeeper : NSObject + +- (void)keepCopyOf:(id)object; +// Answers whether both copies are the same object. +- (BOOL)keepTwoCopiesOf:(id)object; +- (void)drop; + +@end + // Blocks answered owned or not. Method families do not apply to block // results, so ownership is declared. @interface TNSOwnedBlocks : NSObject diff --git a/TestFixtures/Marshalling/TNSAllocLog.m b/TestFixtures/Marshalling/TNSAllocLog.m index 45cfcce4f..be25ae5d2 100644 --- a/TestFixtures/Marshalling/TNSAllocLog.m +++ b/TestFixtures/Marshalling/TNSAllocLog.m @@ -70,6 +70,34 @@ + (id)readNewItemOf:(id)object { return [object newItem]; } ++ (void)allocInitAndDrop:(Class)cls { + id result = [[cls alloc] init]; + (void)result; +} + +@end + +@implementation TNSCopyKeeper { + NSMutableArray* _copies; +} + +- (void)keepCopyOf:(id)object { + if (_copies == nil) { + _copies = [NSMutableArray array]; + } + [_copies addObject:[object copy]]; +} + +- (BOOL)keepTwoCopiesOf:(id)object { + [self keepCopyOf:object]; + [self keepCopyOf:object]; + return _copies[_copies.count - 1] == _copies[_copies.count - 2]; +} + +- (void)drop { + _copies = nil; +} + @end @implementation TNSOwnedBlocks { @@ -161,10 +189,11 @@ - (NSUInteger)retainCountAt:(NSUInteger)index { - (BOOL)isTaggedPointerAt:(NSUInteger)index { uintptr_t bits = (uintptr_t)(__bridge void*)_objects[index]; -#if __arm64__ - return (bits >> 63) != 0; -#else + // The ObjC runtime's OBJC_MSB_TAGGED_POINTERS condition (objc-internal.h). +#if (TARGET_OS_OSX || TARGET_OS_MACCATALYST) && __x86_64__ return (bits & 1) != 0; +#else + return (bits >> 63) != 0; #endif } diff --git a/TestRunner/app/tests/NativeCallbackSelfTests.js b/TestRunner/app/tests/NativeCallbackSelfTests.js index 8b0191e75..b17039e6c 100644 --- a/TestRunner/app/tests/NativeCallbackSelfTests.js +++ b/TestRunner/app/tests/NativeCallbackSelfTests.js @@ -1082,4 +1082,96 @@ describe("Native callback self wrappers", function () { }); }); }); + + // A plain JS object reaches native code as a DictionaryAdapter whose + // handle keeps the object alive, so the object outlives the adapter only + // if the adapter leaks. + function freshObjectState() { + var state = { weak: null }; + state.answer = function () { + var object = { fresh: true }; + state.weak = new WeakRef(object); + return object; + }; + return state; + } + + function expectCollected(state, done) { + settle(3, function () { + expect(state.weak).not.toBeNull(); + expect(state.weak && state.weak.deref()).toBeUndefined(); + done(); + }); + } + + it("keeps a fresh plain object a JS copyWithZone answers while native code holds its copy", function (done) { + var state = freshObjectState(); + var Klass = NSObject.extend({ + copyWithZone: function () { + return state.answer(); + } + }, { name: "NativeCallbackSelfCopyKeptPlainObject", protocols: [NSCopying] }); + var keeper = TNSCopyKeeper.new(); + keeper.keepCopyOf(Klass.new()); + settle(3, function () { + expect(state.weak.deref() && state.weak.deref().fresh).toBe(true); + keeper.drop(); + expectCollected(state, done); + }); + }); + + it("frees the adapter for a fresh plain object a JS copyWithZone answers", function (done) { + var state = freshObjectState(); + var Klass = NSObject.extend({ + copyWithZone: function () { + return state.answer(); + } + }, { name: "NativeCallbackSelfCopyPlainObject", protocols: [NSCopying] }); + TNSOwnedReturns.copyAndDrop(Klass.new()); + expectCollected(state, done); + }); + + it("frees the adapter for a fresh plain object a JS new-family method answers", function (done) { + var state = freshObjectState(); + var Klass = TNSOwnedReturns.extend({ + newChild: function () { + return state.answer(); + } + }, { name: "NativeCallbackSelfNewPlainObject" }); + TNSOwnedReturns.newChildAndDrop(Klass.new()); + expectCollected(state, done); + }); + + it("frees the adapter for a fresh plain object a JS initializer answers", function (done) { + var state = freshObjectState(); + var Klass = NSObject.extend({ + init: function () { + return state.answer(); + } + }, { name: "NativeCallbackSelfInitPlainObject" }); + TNSOwnedReturns.allocInitAndDrop(Klass.class()); + expectCollected(state, done); + }); + + it("balances the adapter for a plain object a JS copyWithZone answers twice", function (done) { + var state = { weak: null }; + (function () { + var object = { same: true }; + state.weak = new WeakRef(object); + state.answer = object; + })(); + var Klass = NSObject.extend({ + copyWithZone: function () { + return state.answer; + } + }, { name: "NativeCallbackSelfCopySamePlainObject", protocols: [NSCopying] }); + var keeper = TNSCopyKeeper.new(); + expect(keeper.keepTwoCopiesOf(Klass.new())).toBe(true); + state.answer = null; + settle(3, function () { + expect(state.weak.deref() && state.weak.deref().same).toBe(true); + keeper.drop(); + expectCollected(state, done); + }); + }); }); From 821e5ac38dcea2b01d40691205e560cc427bc338 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 15 Nov 2026 15:18:01 -0300 Subject: [PATCH 8/9] fix(runtime): answer the plain object a JS initializer returns from new ConstructObject released an owned initializer result that already had a cached wrapper before reading that wrapper's handle. When a JS init returns a plain object (or anything SetValue writes as a DictionaryAdapter), the release is the adapter's last reference: its -dealloc resets the Persistent the Instances entry shares, the handle reads empty, and `new X()` evaluated to `this`, an X with no native object. alloc().init() and new() already read the handle first through GetResult. Read it before the release here too. The retain a JS call gives a native unarchiver:didDecodeObject: for its consumed argument now checks that the parameter is an object, as its MethodCallback counterpart does, and looks the index up once instead of asking per argument. MethodCallback no longer classifies the consumed argument on every invocation: the method-wrapper sites compute it once, from the selector ReturnOwnership classifies, and store it on the MethodCallbackWrapper. --- NativeScript/runtime/ArgConverter.h | 8 +++- NativeScript/runtime/ArgConverter.mm | 39 +++++-------------- NativeScript/runtime/ClassBuilder.mm | 14 ++++--- NativeScript/runtime/Interop.h | 7 ++++ NativeScript/runtime/Interop.mm | 33 +++++++++++++--- NativeScript/runtime/MetadataBuilder.mm | 7 ++-- .../app/tests/NativeCallbackSelfTests.js | 33 ++++++++++++++++ 7 files changed, 95 insertions(+), 46 deletions(-) diff --git a/NativeScript/runtime/ArgConverter.h b/NativeScript/runtime/ArgConverter.h index fc3b52dce..2c8e8e8a7 100644 --- a/NativeScript/runtime/ArgConverter.h +++ b/NativeScript/runtime/ArgConverter.h @@ -28,19 +28,23 @@ struct MethodCallbackWrapper { v8::Isolate* isolate, std::shared_ptr> callback, const uint8_t initialParamIndex, const uint8_t paramsCount, const TypeEncoding* typeEncoding, - NativeReturnOwnership returnOwnership = NativeReturnOwnership::Unowned) + NativeReturnOwnership returnOwnership = NativeReturnOwnership::Unowned, + int8_t consumedArgumentIndex = -1) : isolateWrapper_(isolate), callback_(callback), initialParamIndex_(initialParamIndex), paramsCount_(paramsCount), typeEncoding_(typeEncoding), - returnOwnership_(returnOwnership) {} + returnOwnership_(returnOwnership), + consumedArgumentIndex_(consumedArgumentIndex) {} IsolateWrapper isolateWrapper_; std::shared_ptr> callback_; const uint8_t initialParamIndex_; const uint8_t paramsCount_; const TypeEncoding* typeEncoding_; const NativeReturnOwnership returnOwnership_; + // Interop::ConsumedObjectArgumentIndex of the implemented method. + const int8_t consumedArgumentIndex_; }; class ArgConverter { diff --git a/NativeScript/runtime/ArgConverter.mm b/NativeScript/runtime/ArgConverter.mm index 139a4fe46..48119c939 100644 --- a/NativeScript/runtime/ArgConverter.mm +++ b/NativeScript/runtime/ArgConverter.mm @@ -48,33 +48,6 @@ bool InMethodFamily(SEL selector, const char* family) { return strncmp(name, family, length) == 0 && (name[length] < 'a' || name[length] > 'z'); } -bool IsObjectEncoding(const TypeEncoding* typeEncoding) { - BinaryTypeEncodingType type = typeEncoding->type; - return type == BinaryTypeEncodingType::IdEncoding || - type == BinaryTypeEncodingType::InterfaceDeclarationReference || - type == BinaryTypeEncodingType::InstanceTypeEncoding; -} - -// The argument a JS-implemented method takes over from its native caller, or -// nil. Reads only the native call, so it is usable without the isolate. -id ConsumedArgument(const MethodCallbackWrapper* data, void** argValues) { - if (data->initialParamIndex_ != 2) { - return nil; - } - SEL selector = *static_cast(argValues[1]); - for (int i = 0; i < data->paramsCount_; i++) { - if (!Interop::ConsumesArgument(selector, i)) { - continue; - } - const TypeEncoding* typeEncoding = data->typeEncoding_; - for (int j = 0; j <= i; j++) { - typeEncoding = typeEncoding->next(); - } - return IsObjectEncoding(typeEncoding) ? *static_cast(argValues[i + 2]) : nil; - } - return nil; -} - // 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. @@ -363,7 +336,10 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {} void ArgConverter::MethodCallback(ffi_cif* cif, void* retValue, void** argValues, void* userData) { MethodCallbackWrapper* data = static_cast(userData); // Owned by this call, which gives it up on every path unless it answers it. - id consumedArgument = ConsumedArgument(data, argValues); + id consumedArgument = + data->consumedArgumentIndex_ < 0 + ? nil + : *static_cast(argValues[data->initialParamIndex_ + data->consumedArgumentIndex_]); Isolate* isolate = data->isolateWrapper_.Isolate(); @@ -524,7 +500,7 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {} } // A wrapper JS made for the consumed argument holds a reference of its own. - if (consumedArgument != nil && !(IsObjectEncoding(data->typeEncoding_) && + if (consumedArgument != nil && !(Interop::IsObjectEncoding(data->typeEncoding_) && *static_cast(retValue) == consumedArgument)) { [consumedArgument release]; } @@ -746,13 +722,16 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {} auto cache = Caches::Get(isolate); auto poInstance = ArgConverter::FindCachedInstance(isolate, cache, result); if (poInstance != nullptr) { + // Read before the release below: when it drops a DictionaryAdapter's last + // reference, the adapter's -dealloc resets this handle. + Local cached = poInstance->Get(isolate); // An initializer that answered with an already wrapped object (a singleton, // a tagged pointer, a cached cluster instance) leaves us holding a +1 the // existing entry has no use for. if (Interop::ReleasesCachedOwnedReturn(resultIsOwned, OwnedReturnReceiver::AllocatedForCall)) { [result release]; } - info.GetReturnValue().Set(poInstance->Get(isolate)); + info.GetReturnValue().Set(cached); } else { ObjCDataWrapper* wrapper = new ObjCDataWrapper(result); Local thiz = info.This(); diff --git a/NativeScript/runtime/ClassBuilder.mm b/NativeScript/runtime/ClassBuilder.mm index ac85a017c..4af08afa0 100644 --- a/NativeScript/runtime/ClassBuilder.mm +++ b/NativeScript/runtime/ClassBuilder.mm @@ -689,9 +689,10 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { std::shared_ptr> poCallback = std::make_shared>(isolate, method); - MethodCallbackWrapper* userData = - new MethodCallbackWrapper(isolate, poCallback, 2, argsCount, typeEncoding, - ArgConverter::ReturnOwnership(selector, nullptr)); + MethodCallbackWrapper* userData = new MethodCallbackWrapper( + isolate, poCallback, 2, argsCount, typeEncoding, + ArgConverter::ReturnOwnership(selector, nullptr), + Interop::ConsumedObjectArgumentIndex(selector, typeEncoding, argsCount)); IMP methodBody = Interop::CreateMethod(2, argsCount, typeEncoding, ArgConverter::MethodCallback, userData); std::string typeInfo = GetTypeEncoding(typeEncoding, argsCount); @@ -795,9 +796,10 @@ new MethodCallbackWrapper(isolate, poCallback, 2, argsCount, typeEncoding, const TypeEncoding* typeEncoding = methodMeta->encodings()->first(); uint8_t argsCount = methodMeta->encodings()->count - 1; SEL selector = methodMeta->selector(); - MethodCallbackWrapper* userData = - new MethodCallbackWrapper(isolate, poCallback, 2, argsCount, typeEncoding, - ArgConverter::ReturnOwnership(selector, methodMeta)); + MethodCallbackWrapper* userData = new MethodCallbackWrapper( + isolate, poCallback, 2, argsCount, typeEncoding, + ArgConverter::ReturnOwnership(selector, methodMeta), + Interop::ConsumedObjectArgumentIndex(selector, typeEncoding, argsCount)); IMP methodBody = Interop::CreateMethod(2, argsCount, typeEncoding, ArgConverter::MethodCallback, userData); std::string typeInfo = GetTypeEncoding(typeEncoding, argsCount); diff --git a/NativeScript/runtime/Interop.h b/NativeScript/runtime/Interop.h index 80f6d7b27..a8859b247 100644 --- a/NativeScript/runtime/Interop.h +++ b/NativeScript/runtime/Interop.h @@ -123,6 +123,13 @@ class Interop { // `index`, counted from the first after the selector: NS_RELEASES_ARGUMENT // parameters, which the metadata does not record. static bool ConsumesArgument(SEL selector, int index); + // The index ConsumesArgument names for `selector` when that parameter is an + // object, else -1. `typeEncoding` is the signature's return type, followed + // by its `paramsCount` parameter types. + static int ConsumedObjectArgumentIndex(SEL selector, + const TypeEncoding* typeEncoding, + int paramsCount); + static bool IsObjectEncoding(const TypeEncoding* typeEncoding); // Whether a method outside the copy, mutableCopy and new families answers // an object its caller owns (NS_RETURNS_RETAINED), for implementations the // metadata does not describe. diff --git a/NativeScript/runtime/Interop.mm b/NativeScript/runtime/Interop.mm index 433b3f67d..9c83ce538 100644 --- a/NativeScript/runtime/Interop.mm +++ b/NativeScript/runtime/Interop.mm @@ -174,8 +174,31 @@ // -[NSKeyedUnarchiverDelegate unarchiver:didDecodeObject:] is the only SDK // method with an NS_RELEASES_ARGUMENT parameter; it also returns retained. +static int ConsumedArgumentIndex(SEL selector) { + return selector == @selector(unarchiver:didDecodeObject:) ? 1 : -1; +} + bool Interop::ConsumesArgument(SEL selector, int index) { - return index == 1 && selector == @selector(unarchiver:didDecodeObject:); + return index >= 0 && index == ConsumedArgumentIndex(selector); +} + +int Interop::ConsumedObjectArgumentIndex(SEL selector, const TypeEncoding* typeEncoding, + int paramsCount) { + int index = ConsumedArgumentIndex(selector); + if (index < 0 || index >= paramsCount) { + return -1; + } + for (int i = 0; i <= index; i++) { + typeEncoding = typeEncoding->next(); + } + return IsObjectEncoding(typeEncoding) ? index : -1; +} + +bool Interop::IsObjectEncoding(const TypeEncoding* typeEncoding) { + BinaryTypeEncodingType type = typeEncoding->type; + return type == BinaryTypeEncodingType::IdEncoding || + type == BinaryTypeEncodingType::InterfaceDeclarationReference || + type == BinaryTypeEncodingType::InstanceTypeEncoding; } bool Interop::ReturnsRetained(SEL selector) { return ConsumesArgument(selector, 1); } @@ -1871,10 +1894,10 @@ throw NativeScriptException( initialParameterIndex, methodCall.args_); if (initialParameterIndex > 1) { - for (int i = initialParameterIndex; i < argsCount; i++) { - if (ConsumesArgument(methodCall.selector_, i - initialParameterIndex)) { - [*static_cast(call.ArgumentBuffer(i)) retain]; - } + int consumed = ConsumedObjectArgumentIndex(methodCall.selector_, methodCall.typeEncoding_, + argsCount - initialParameterIndex); + if (consumed >= 0) { + [*static_cast(call.ArgumentBuffer(initialParameterIndex + consumed)) retain]; } } diff --git a/NativeScript/runtime/MetadataBuilder.mm b/NativeScript/runtime/MetadataBuilder.mm index 6a5d428d7..c27caa1ba 100644 --- a/NativeScript/runtime/MetadataBuilder.mm +++ b/NativeScript/runtime/MetadataBuilder.mm @@ -1396,9 +1396,10 @@ CMethodCall methodCall(context, item->userData_, typeEncoding, args, std::string compilerEncoding = ClassBuilder::GetTypeEncoding(typeEncoding, argsCount); std::shared_ptr> poCallback = std::make_shared>(isolate, value); - MethodCallbackWrapper* userData = - new MethodCallbackWrapper(isolate, poCallback, 2, argsCount, typeEncoding, - ArgConverter::ReturnOwnership(methodMeta->selector(), methodMeta)); + MethodCallbackWrapper* userData = new MethodCallbackWrapper( + isolate, poCallback, 2, argsCount, typeEncoding, + ArgConverter::ReturnOwnership(methodMeta->selector(), methodMeta), + Interop::ConsumedObjectArgumentIndex(methodMeta->selector(), typeEncoding, argsCount)); IMP methodBody = Interop::CreateMethod(2, argsCount, typeEncoding, ArgConverter::MethodCallback, userData); IMP nativeImp = diff --git a/TestRunner/app/tests/NativeCallbackSelfTests.js b/TestRunner/app/tests/NativeCallbackSelfTests.js index b17039e6c..4eb8e51e3 100644 --- a/TestRunner/app/tests/NativeCallbackSelfTests.js +++ b/TestRunner/app/tests/NativeCallbackSelfTests.js @@ -1153,6 +1153,39 @@ describe("Native callback self wrappers", function () { expectCollected(state, done); }); + function expectConstructedFreshObject(name, construct, done) { + var state = freshObjectState(); + var Klass = NSObject.extend({ + init: function () { + return state.answer(); + } + }, { name: name }); + (function () { + var result = construct(Klass); + expect(result !== undefined && result === state.weak.deref()).toBe(true); + expect(!!result && result.fresh === true).toBe(true); + })(); + expectCollected(state, done); + } + + it("constructs with new the fresh plain object a JS initializer answers", function (done) { + expectConstructedFreshObject("NativeCallbackSelfNewOperatorPlainObject", function (Klass) { + return new Klass(); + }, done); + }); + + it("answers from alloc().init() the fresh plain object a JS initializer answers", function (done) { + expectConstructedFreshObject("NativeCallbackSelfAllocInitPlainObject", function (Klass) { + return Klass.alloc().init(); + }, done); + }); + + it("answers from new() the fresh plain object a JS initializer answers", function (done) { + expectConstructedFreshObject("NativeCallbackSelfNewMethodPlainObject", function (Klass) { + return Klass.new(); + }, done); + }); + it("balances the adapter for a plain object a JS copyWithZone answers twice", function (done) { var state = { weak: null }; (function () { From f81d2263d028865faffeff87a737a39819afd86b Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 15 Nov 2026 15:18:09 -0300 Subject: [PATCH 9/9] test(runtime): cover owned C function results JS receives as primitives C functions are where most owned strings, numbers and dates come from (the CF Create/Copy rule, NS_RETURNS_RETAINED, CF_RETURNS_RETAINED), but the primitive specs only called an instance method. An NS_RETURNS_RETAINED function and an unowned twin return the objects TNSOwnedPrimitives keeps, so the retain counts it reports show whether 20 calls leave them as they were. --- TestFixtures/Marshalling/TNSAllocLog.h | 5 +++++ TestFixtures/Marshalling/TNSAllocLog.m | 8 ++++++++ TestFixtures/exported-symbols.txt | 2 ++ TestRunner/app/tests/NativeCallbackSelfTests.js | 12 ++++++++++++ 4 files changed, 27 insertions(+) diff --git a/TestFixtures/Marshalling/TNSAllocLog.h b/TestFixtures/Marshalling/TNSAllocLog.h index d243c2e3b..e425fe7d3 100644 --- a/TestFixtures/Marshalling/TNSAllocLog.h +++ b/TestFixtures/Marshalling/TNSAllocLog.h @@ -54,6 +54,11 @@ @end +// The object `holder` keeps at `index`, owned by the caller. +id TNSOwnedPrimitivesRetainedObjectAt(TNSOwnedPrimitives* holder, NSUInteger index) NS_RETURNS_RETAINED; +// The object `holder` keeps at `index`, without passing ownership on. +id TNSOwnedPrimitivesObjectAt(TNSOwnedPrimitives* holder, NSUInteger index); + // Keeps what -copy answers until -drop. @interface TNSCopyKeeper : NSObject diff --git a/TestFixtures/Marshalling/TNSAllocLog.m b/TestFixtures/Marshalling/TNSAllocLog.m index be25ae5d2..dde24b773 100644 --- a/TestFixtures/Marshalling/TNSAllocLog.m +++ b/TestFixtures/Marshalling/TNSAllocLog.m @@ -199,6 +199,14 @@ - (BOOL)isTaggedPointerAt:(NSUInteger)index { @end +id TNSOwnedPrimitivesRetainedObjectAt(TNSOwnedPrimitives* holder, NSUInteger index) { + return [holder objectAt:index]; +} + +id TNSOwnedPrimitivesObjectAt(TNSOwnedPrimitives* holder, NSUInteger index) { + return [holder objectAt:index]; +} + @implementation TNSSwizzledOwnedReturns - (id)newChild { diff --git a/TestFixtures/exported-symbols.txt b/TestFixtures/exported-symbols.txt index 9a915ec8e..8b21d395d 100644 --- a/TestFixtures/exported-symbols.txt +++ b/TestFixtures/exported-symbols.txt @@ -150,6 +150,8 @@ _TNSGetOutput _TNSLog _TNSMutableObjectGet _TNSObjectGet +_TNSOwnedPrimitivesObjectAt +_TNSOwnedPrimitivesRetainedObjectAt _TNSSaveResults _TNSStructFunctionConflict _TNSStructVarConflict diff --git a/TestRunner/app/tests/NativeCallbackSelfTests.js b/TestRunner/app/tests/NativeCallbackSelfTests.js index 4eb8e51e3..bc9351c96 100644 --- a/TestRunner/app/tests/NativeCallbackSelfTests.js +++ b/TestRunner/app/tests/NativeCallbackSelfTests.js @@ -927,6 +927,18 @@ describe("Native callback self wrappers", function () { }, done); }); + it("releases owned C function results JS receives as a string, a number and a date", function (done) { + expectPrimitivesRetainedAsBefore(function (holder, index) { + return TNSOwnedPrimitivesRetainedObjectAt(holder, index); + }, done); + }); + + it("leaves unowned C function results JS receives as primitives retained as they were", function (done) { + expectPrimitivesRetainedAsBefore(function (holder, index) { + return TNSOwnedPrimitivesObjectAt(holder, index); + }, done); + }); + function copiesAsStringState(name, answer) { var state = { answer: answer }; var Copyable = TNSAllocLog.extend({