From b5a6da30cdc828f96bccf3556ca062d49122c144 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 18 Nov 2026 01:17:50 -0300 Subject: [PATCH] fix(runtime): read only the native retainCount when checking who owns a wrapped object The ownership check behind ManageOwnership (ReconcileOwnershipBeforeGC, a GC prologue, plus ReconcileOwnership, FinalizerCallback and DisposeValue) had two problems with the -retainCount it reads. It resolved the IMP with class_getMethodImplementation on the native class. JS can replace a native class's -retainCount through a protocol prototype that shares the class's name (NSObjectProtocol.prototype.retainCount replaces NSObject's), and the GC prologue then called into JS, which V8 aborts: V8_Fatal <- Execution::Call <- ArgConverter::MethodCallback <- NativelyOwnedWithoutJS <- ReconcileOwnershipBeforeGC. It also read every NSTimer as unowned. A timer whose wrapper was created for a JS-implemented method native code called on it had that wrapper collected while native code still held the timer, losing the JS properties and WeakMap identity on it. Only NSTimer.alloc()'s placeholder answers -retainCount without returning; initialized timers and NSTimer subclasses answer normally. ObjectManager::NativeRetainCountImp(Class) now resolves the IMP: null for the placeholder's class, taken from [NSTimer alloc] rather than by name, and otherwise the first class from the native class upward whose own method list has the original a JS replacement keeps under the swizzled-prefixed alias, or its own -retainCount. Results are cached per class and isolate. --- NativeScript/runtime/ObjectManager.h | 10 +++ NativeScript/runtime/ObjectManager.mm | 69 +++++++++++++--- TestFixtures/Marshalling/TNSAllocLog.h | 45 +++++++++++ TestFixtures/Marshalling/TNSAllocLog.m | 44 ++++++++++ .../app/tests/NativeCallbackSelfTests.js | 81 +++++++++++++++++++ 5 files changed, 236 insertions(+), 13 deletions(-) diff --git a/NativeScript/runtime/ObjectManager.h b/NativeScript/runtime/ObjectManager.h index d00bce017..23fda66a2 100644 --- a/NativeScript/runtime/ObjectManager.h +++ b/NativeScript/runtime/ObjectManager.h @@ -1,6 +1,8 @@ #ifndef ObjectManager_h #define ObjectManager_h +#include + #include "Common.h" namespace tns { @@ -76,6 +78,14 @@ class ObjectManager { // wrapper to protect; this catches up. A surplus reference the caller drops // afterwards goes through -release, which unprotects again. static void ProtectIfNativelyRetained(v8::Isolate* isolate, id obj, ObjCDataWrapper* wrapper); + // The -retainCount instances of `cls` answer with natively, never one JS + // implements, so it can be called where JS may not run, such as a GC + // prologue. JS subclasses are skipped, and a native class whose -retainCount + // JS replaced answers with the original that the replacement keeps under the + // swizzled-prefixed alias. Null for NSTimer.alloc()'s placeholder, whose + // -retainCount does not return, and for classes without a -retainCount. + // Walks method lists, so callers cache the result per class. + static IMP NativeRetainCountImp(Class cls); private: static void ReleaseNativeCounterpartCallback( diff --git a/NativeScript/runtime/ObjectManager.mm b/NativeScript/runtime/ObjectManager.mm index edc901e95..36a832e91 100644 --- a/NativeScript/runtime/ObjectManager.mm +++ b/NativeScript/runtime/ObjectManager.mm @@ -26,6 +26,8 @@ // finalizer state their handle carries. struct OwnershipTracking { std::unordered_map managed; + // ObjectManager::NativeRetainCountImp per class. + std::unordered_map retainCountImps; }; void ForgetOwnership(Isolate* isolate, ObjectWeakCallbackState* state) { @@ -43,17 +45,26 @@ void ApplyOwnership(ObjectWeakCallbackState* state, bool nativelyOwned) { } } -// The GC prologue may not enter JS, so a JS-implemented -retainCount is -// skipped. Timers read as unowned: the retain count of an uninitialized NSTimer -// (NSTimer.alloc()) can hang. -bool NativelyOwnedWithoutJS(id obj) { - for (Class c = object_getClass(obj); c != nil; c = class_getSuperclass(c)) { - if (c == NSTimerClass) { - return false; +// Runs in a GC prologue, where JS may not run, so only a native -retainCount +// is read. Objects without one read as unowned. +bool NativelyOwnedWithoutJS(OwnershipTracking* tracking, id obj) { + Class cls = object_getClass(obj); + IMP imp; + if (tracking != nullptr) { + auto found = tracking->retainCountImps.find(cls); + if (found == tracking->retainCountImps.end()) { + found = + tracking->retainCountImps.emplace(cls, ObjectManager::NativeRetainCountImp(cls)).first; } + imp = found->second; + } else { + imp = ObjectManager::NativeRetainCountImp(cls); } - IMP imp = ClassBuilder::FindNotOverridenMethod(object_getClass(obj), @selector(retainCount)); - return ((NSUInteger (*)(id, SEL))imp)(obj, @selector(retainCount)) > 1; + return imp != nullptr && ((NSUInteger (*)(id, SEL))imp)(obj, @selector(retainCount)) > 1; +} + +bool NativelyOwnedWithoutJS(Isolate* isolate, id obj) { + return NativelyOwnedWithoutJS(Caches::ExistingStateFor(isolate), obj); } void ReconcileOwnershipBeforeGC(Isolate* isolate, GCType, GCCallbackFlags) { @@ -65,7 +76,7 @@ void ReconcileOwnershipBeforeGC(Isolate* isolate, GCType, GCCallbackFlags) { if (state->disposing_ || state->target_ == nullptr || state->target_->IsEmpty()) { continue; } - ApplyOwnership(state, NativelyOwnedWithoutJS(wrapper->Data())); + ApplyOwnership(state, NativelyOwnedWithoutJS(tracking, wrapper->Data())); } } @@ -316,7 +327,7 @@ void DisposeHandle(v8::Isolate* isolate, // The handle's strength carries the ownership; a GcProtect from the retain // swizzle would keep a weak handle from ever being disposed. wrapper->GcUnprotect(); - ApplyOwnership(state, NativelyOwnedWithoutJS(wrapper->Data())); + ApplyOwnership(state, NativelyOwnedWithoutJS(isolate, wrapper->Data())); } void ObjectManager::FinalizerCallback(const WeakCallbackInfo& data) { @@ -361,7 +372,7 @@ void DisposeHandle(v8::Isolate* isolate, if (wrapper != nullptr && wrapper->Type() == WrapperType::ObjCObject) { ObjCDataWrapper* objcWrapper = static_cast(wrapper); if (objcWrapper->OwnershipState() == state) { - ApplyOwnership(state, NativelyOwnedWithoutJS(objcWrapper->Data())); + ApplyOwnership(state, NativelyOwnedWithoutJS(isolate, objcWrapper->Data())); } } } @@ -419,7 +430,8 @@ void DisposeHandle(v8::Isolate* isolate, // to making it strong again. if (!isFinalDisposal && wrapper->Type() == WrapperType::ObjCObject) { ObjCDataWrapper* objcWrapper = static_cast(wrapper); - if (objcWrapper->OwnershipState() != nullptr && NativelyOwnedWithoutJS(objcWrapper->Data())) { + if (objcWrapper->OwnershipState() != nullptr && + NativelyOwnedWithoutJS(isolate, objcWrapper->Data())) { return false; } } @@ -680,4 +692,35 @@ void DisposeHandle(v8::Isolate* isolate, return CFGetRetainCount(obj); } +IMP ObjectManager::NativeRetainCountImp(Class cls) { + static Class timerPlaceholder = object_getClass([NSTimer alloc]); + if (cls == timerPlaceholder) { + return nullptr; + } + SEL selector = @selector(retainCount); + static SEL original = sel_registerName((Constants::SwizzledPrefix + "retainCount").c_str()); + // Each class's own method list, rather than class_getMethodImplementation, + // so an alias inherited from a replaced ancestor never hides a native + // override below it. + for (Class c = ClassBuilder::FindNativeClass(cls); c != nil; c = class_getSuperclass(c)) { + unsigned int count = 0; + Method* methods = class_copyMethodList(c, &count); + IMP own = nullptr; + IMP kept = nullptr; + for (unsigned int i = 0; i < count; i++) { + SEL name = method_getName(methods[i]); + if (name == original) { + kept = method_getImplementation(methods[i]); + } else if (name == selector) { + own = method_getImplementation(methods[i]); + } + } + free(methods); + if (kept != nullptr || own != nullptr) { + return kept != nullptr ? kept : own; + } + } + return nullptr; +} + } // namespace tns diff --git a/TestFixtures/Marshalling/TNSAllocLog.h b/TestFixtures/Marshalling/TNSAllocLog.h index c2adcb5c8..a5767a50d 100644 --- a/TestFixtures/Marshalling/TNSAllocLog.h +++ b/TestFixtures/Marshalling/TNSAllocLog.h @@ -183,4 +183,49 @@ id TNSOwnedPrimitivesObjectAt(TNSOwnedPrimitives* holder, NSUInteger index); @end +// Declares -retainCount and shares its name with the class adopting it, so +// assigning TNSReplaceableRetainCountProtocol.prototype.retainCount replaces +// the method on that class alone, as NSObjectProtocol.prototype does on +// NSObject. +@protocol TNSReplaceableRetainCount + +- (NSUInteger)retainCount; + +@end + +@interface TNSReplaceableRetainCount : TNSAllocLog + +// Sends -retainCount to `object`. ++ (NSUInteger)retainCountOf:(id)object; + +// Adds a new instance to `owner`, then sends it -retainCount, so a JS +// replacement of -retainCount is what first hands the instance to JS. ++ (void)addNewInstanceTo:(NSMutableArray*)owner; + +@end + +// Only these fixtures send -tnsCallbackHook, so a JS replacement of it runs +// for their timers alone. +@interface NSTimer (TNSCallbackHook) + +- (void)tnsCallbackHook; + +// Adds an unscheduled timer targeting a new TNSAllocLog to `owner`, then +// sends it -tnsCallbackHook, so a JS replacement of the hook is what first +// hands the timer to JS. ++ (void)tnsAddHookedTimerTo:(NSMutableArray*)owner; + +@end + +@interface TNSUninitializedTimer : NSObject + +// NSTimer.alloc()'s placeholder, which a JS alloc() call never creates: its +// -retainCount does not return. ++ (id)placeholder; + +// Sends -tnsCallbackHook to the placeholder. ++ (void)hookPlaceholder; + +@end + #endif /* TNSAllocLog_h */ diff --git a/TestFixtures/Marshalling/TNSAllocLog.m b/TestFixtures/Marshalling/TNSAllocLog.m index 72d685671..5f9623197 100644 --- a/TestFixtures/Marshalling/TNSAllocLog.m +++ b/TestFixtures/Marshalling/TNSAllocLog.m @@ -1,4 +1,5 @@ #import "TNSAllocLog.h" +#import #import "../TNSTestCommon.h" @implementation TNSAllocLog @@ -422,3 +423,46 @@ + (void)dropKeptHost { } @end + +@implementation TNSReplaceableRetainCount + ++ (NSUInteger)retainCountOf:(id)object { + return ((NSUInteger (*)(id, SEL))objc_msgSend)(object, sel_registerName("retainCount")); +} + ++ (void)addNewInstanceTo:(NSMutableArray*)owner { + TNSReplaceableRetainCount* instance = [[self alloc] init]; + [owner addObject:instance]; + [self retainCountOf:instance]; +} + +@end + +@implementation NSTimer (TNSCallbackHook) + +- (void)tnsCallbackHook { +} + ++ (void)tnsAddHookedTimerTo:(NSMutableArray*)owner { + NSTimer* timer = [NSTimer timerWithTimeInterval:1000 + target:[[TNSAllocLog alloc] init] + selector:@selector(description) + userInfo:nil + repeats:NO]; + [owner addObject:timer]; + [timer tnsCallbackHook]; +} + +@end + +@implementation TNSUninitializedTimer + ++ (id)placeholder { + return [NSTimer alloc]; +} + ++ (void)hookPlaceholder { + [[NSTimer alloc] tnsCallbackHook]; +} + +@end diff --git a/TestRunner/app/tests/NativeCallbackSelfTests.js b/TestRunner/app/tests/NativeCallbackSelfTests.js index bc9351c96..923399e9a 100644 --- a/TestRunner/app/tests/NativeCallbackSelfTests.js +++ b/TestRunner/app/tests/NativeCallbackSelfTests.js @@ -157,6 +157,87 @@ describe("Native callback self wrappers", function () { }); }); + // Ownership checks run in a GC prologue, where JS may not run. The + // replacement stays installed for the rest of the run, on a class no other + // spec uses. + it("never calls a JS replacement of retainCount to decide whether native code owns an object", function (done) { + var calls = 0; + var proto = TNSReplaceableRetainCountProtocol.prototype; + var original = proto.retainCount; + proto.retainCount = function () { + calls++; + return original.call(this); + }; + var owner = NSMutableArray.new(); + TNSReplaceableRetainCount.addNewInstanceTo(owner); + expect(calls).toBe(1); + (function () { + var obj = owner.objectAtIndex(0); + obj.state = 3; + expect(TNSReplaceableRetainCount.retainCountOf(obj)).toBeGreaterThan(1); + expect(calls).toBe(2); + })(); + settle(2, function () { + expect(calls).toBe(2); + expect(owner.objectAtIndex(0).state).toBe(3); + owner.removeAllObjects(); + settle(3, function () { + expect(calls).toBe(2); + expect(deallocs()).toBe(1); + done(); + }); + }); + }); + + // The hook stays replaced for the rest of the run; only fixtures send it. + var timerHook = { installed: false, run: null }; + + function hookTimers(run) { + if (!timerHook.installed) { + timerHook.installed = true; + NSTimer.prototype.tnsCallbackHook = function () { + timerHook.run(this); + }; + } + timerHook.run = run; + } + + it("keeps the JS state of a natively owned timer whose JS method created its wrapper, then frees it once", function (done) { + var owner = NSMutableArray.new(); + var map = new WeakMap(); + hookTimers(function (timer) { + timer.state = 5; + map.set(timer, "timer"); + }); + NSTimer.tnsAddHookedTimerTo(owner); + settle(3, function () { + var timer = owner.objectAtIndex(0); + expect(timer.state).toBe(5); + expect(map.get(timer)).toBe("timer"); + timer = null; + expect(deallocs()).toBe(0); + owner.removeAllObjects(); + settle(3, function () { + expect(deallocs()).toBe(1); + done(); + }); + }); + }); + + it("checks who owns NSTimer.alloc()'s placeholder without sending it retainCount", function (done) { + hookTimers(function (timer) { + timer.state = 1; + }); + TNSUninitializedTimer.hookPlaceholder(); + var placeholder = TNSUninitializedTimer.placeholder(); + expect(placeholder.isKindOfClass(NSTimer)).toBe(true); + expect(placeholder.state).toBe(1); + settle(2, function () { + expect(placeholder.state).toBe(1); + done(); + }); + }); + it("does not release an instance method's owned return that is its receiver", function (done) { var obj = TNSAllocLog.alloc().init(); var same = obj.awakeAfterUsingCoder(null);