diff --git a/NativeScript/runtime/LeakProbe.mm b/NativeScript/runtime/LeakProbe.mm index 4ec750ca..783ff1a6 100644 --- a/NativeScript/runtime/LeakProbe.mm +++ b/NativeScript/runtime/LeakProbe.mm @@ -111,6 +111,7 @@ void ForEachCanaryStateHandle(Isolate* isolate, void* context, } void DrainReleases(Isolate* isolate) { + ObjectManager::RunDeferredReleases(isolate); WrapperLifetime::DrainReleases(isolate); WrapperLifetimeCanary::ReleaseDeadStates(isolate); } diff --git a/NativeScript/runtime/LeakProbeSPI.h b/NativeScript/runtime/LeakProbeSPI.h index b4c168fc..b7b31529 100644 --- a/NativeScript/runtime/LeakProbeSPI.h +++ b/NativeScript/runtime/LeakProbeSPI.h @@ -114,8 +114,9 @@ struct Host { // Any thread. void (*destroyPoster)(Poster* poster); - // Releases the native objects wrapper lifetime modes queued for release, - // and lets go of the canary states of deallocated objects. Can run JS. + // Releases the native objects wrapper lifetime modes queued for release and + // those a collection or explicit release on another thread left for this + // one, and lets go of the canary states of deallocated objects. Can run JS. void (*drainReleases)(v8::Isolate* isolate); const char* (*lifetimeMode)(); const char* (*lifetimeScope)(); diff --git a/NativeScript/runtime/ObjectManager.h b/NativeScript/runtime/ObjectManager.h index beadf118..38c98895 100644 --- a/NativeScript/runtime/ObjectManager.h +++ b/NativeScript/runtime/ObjectManager.h @@ -130,6 +130,10 @@ class ObjectManager { // release over as its own retain instead of retaining again; returns whether // it did. Once the entry holds its reference, call ProtectIfNativelyRetained. static bool TakeDeferredRelease(v8::Isolate* isolate, id obj); + // Makes the releases waiting for the runtime's thread now, rather than from + // the event loop task posted for them. Only where JS may run: a release can + // reach a JS-implemented -dealloc. Off the runtime's thread, does nothing. + static void RunDeferredReleases(v8::Isolate* isolate); // A class that tracks native retains (ClassBuilder::TracksNativeRetains) // protects its wrapper when native code first retains the object past the // runtime's own retain. A native retain made while a release waited found no diff --git a/NativeScript/runtime/ObjectManager.mm b/NativeScript/runtime/ObjectManager.mm index 8fe282a4..981ac485 100644 --- a/NativeScript/runtime/ObjectManager.mm +++ b/NativeScript/runtime/ObjectManager.mm @@ -573,6 +573,15 @@ void DisposeHandle(v8::Isolate* isolate, return true; } +void ObjectManager::RunDeferredReleases(Isolate* isolate) { + if (!OnRuntimeThreadOf(isolate)) { + return; + } + if (DeferredReleases* pending = Caches::ExistingStateFor(isolate)) { + DrainDeferredReleases(pending); + } +} + void ObjectManager::ProtectIfNativelyRetained(Isolate* isolate, id obj, ObjCDataWrapper* wrapper) { // Only a wrapper the class's -release unprotects again may be protected. if (ClassBuilder::TracksNativeRetains(isolate, object_getClass(obj)) && [obj retainCount] > 1) { diff --git a/NativeScriptLeakProbe/NativeScriptLeakProbe.mm b/NativeScriptLeakProbe/NativeScriptLeakProbe.mm index e24b9d9c..0df9cffa 100644 --- a/NativeScriptLeakProbe/NativeScriptLeakProbe.mm +++ b/NativeScriptLeakProbe/NativeScriptLeakProbe.mm @@ -1596,7 +1596,9 @@ bool FindCycle(Isolate* isolate, const HeapGraphNode* start, constexpr int kSettleCollections = 3; // Until drained, a dead wrapper's queued retain reads as an owner of its -// object, and a deallocated object's canary state as a root. Runs JS. +// object, a deallocated object's canary state as a root, and an object whose +// release waits for this thread has no wrapper, so what it owns looks owned +// from outside. Runs JS. void Settle(Isolate* isolate) { for (int i = 0; i < kSettleCollections; i++) { isolate->LowMemoryNotification(); diff --git a/TestRunner/app/tests/NativeCallbackSelfTests.js b/TestRunner/app/tests/NativeCallbackSelfTests.js index ee5dfc13..a1e2a4a7 100644 --- a/TestRunner/app/tests/NativeCallbackSelfTests.js +++ b/TestRunner/app/tests/NativeCallbackSelfTests.js @@ -2,6 +2,10 @@ // methods, and the native objects attached to errors: kept while native code // owns them, released exactly once afterwards. describe("Native callback self wrappers", function () { + // Several full collections under ASan, on a late-suite heap, can outlast + // Jasmine's default async timeout. + var SETTLE_TIMEOUT_MS = 30000; + function scrub(n) { return n > 0 ? scrub(n - 1) + n : 0; } @@ -49,7 +53,7 @@ describe("Native callback self wrappers", function () { initCalls = 0; done(); }); - }); + }, SETTLE_TIMEOUT_MS); // +new runs the JS-implemented init from native code, before JS has a // wrapper for the object. @@ -73,7 +77,7 @@ describe("Native callback self wrappers", function () { done(); }); }); - }); + }, SETTLE_TIMEOUT_MS); it("frees an object JS alone holds after +new ran its JS initializer", function (done) { var obj = JSInit.new(); @@ -87,7 +91,7 @@ describe("Native callback self wrappers", function () { done(); }); }); - }); + }, SETTLE_TIMEOUT_MS); it("keeps the JS state of cells UIKit creates from a registered class until their superview lets them go", function (done) { var cellInits = 0; @@ -134,7 +138,7 @@ describe("Native callback self wrappers", function () { done(); }); }); - }); + }, SETTLE_TIMEOUT_MS); it("frees a managed wrapper's object once when __releaseNativeCounterpart runs on it", function (done) { var owner = NSMutableArray.new(); @@ -155,7 +159,7 @@ describe("Native callback self wrappers", function () { }); }); }); - }); + }, SETTLE_TIMEOUT_MS); // 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 @@ -187,7 +191,7 @@ describe("Native callback self wrappers", function () { done(); }); }); - }); + }, SETTLE_TIMEOUT_MS); // The hook stays replaced for the rest of the run; only fixtures send it. var timerHook = { installed: false, run: null }; @@ -222,7 +226,7 @@ describe("Native callback self wrappers", function () { done(); }); }); - }); + }, SETTLE_TIMEOUT_MS); it("checks who owns NSTimer.alloc()'s placeholder without sending it retainCount", function (done) { hookTimers(function (timer) { @@ -236,7 +240,7 @@ describe("Native callback self wrappers", function () { expect(placeholder.state).toBe(1); done(); }); - }); + }, SETTLE_TIMEOUT_MS); it("does not release an instance method's owned return that is its receiver", function (done) { var obj = TNSAllocLog.alloc().init(); @@ -247,7 +251,7 @@ describe("Native callback self wrappers", function () { expect(obj.hash > 0).toBe(true); done(); }); - }); + }, SETTLE_TIMEOUT_MS); it("does not release what a JS copyWithZone hands to a native -copy", function (done) { var target = TNSAllocLog.alloc().init(); @@ -266,7 +270,7 @@ describe("Native callback self wrappers", function () { expect(original.hash > 0).toBe(true); done(); }); - }); + }, SETTLE_TIMEOUT_MS); // The JS init runs from native code on an object JS has no wrapper for // yet; wrapping it must not send it a message its JS class implements. @@ -387,7 +391,7 @@ describe("Native callback self wrappers", function () { return InitReturnsOther.new(); }); }, done); - }); + }, SETTLE_TIMEOUT_MS); it("keeps a wrapped object a JS initializer returns instead of its receiver (new)", function (done) { expectInitializerResultOwnedByCaller(function () { @@ -395,7 +399,7 @@ describe("Native callback self wrappers", function () { return new InitReturnsOther(); }); }, done); - }); + }, SETTLE_TIMEOUT_MS); var InitReturnsSubstitute = TNSSubstitutingInit.extend({ init: function () { @@ -408,13 +412,13 @@ describe("Native callback self wrappers", function () { expectInitializerResultOwnedByCaller(function () { return InitReturnsSubstitute.new(); }, done); - }); + }, SETTLE_TIMEOUT_MS); it("keeps the substitute a super initializer returned through a JS initializer (new)", function (done) { expectInitializerResultOwnedByCaller(function () { return new InitReturnsSubstitute(); }, done); - }); + }, SETTLE_TIMEOUT_MS); it("reports a receiver kept from a JS method run by -dealloc as released", function (done) { var saved = null; @@ -441,7 +445,7 @@ describe("Native callback self wrappers", function () { saved = null; done(); }); - }); + }, SETTLE_TIMEOUT_MS); it("keeps an error's NSError while the error lives and frees it afterwards", function (done) { var watch = NSHashTable.weakObjectsHashTable(); @@ -463,7 +467,7 @@ describe("Native callback self wrappers", function () { done(); }); }); - }); + }, SETTLE_TIMEOUT_MS); it("keeps an error's NSException while the error lives and frees it afterwards", function (done) { var watch = NSHashTable.weakObjectsHashTable(); @@ -485,7 +489,7 @@ describe("Native callback self wrappers", function () { done(); }); }); - }); + }, SETTLE_TIMEOUT_MS); it("leaves the retain count of an immutable object whose -copy answers itself unchanged", function (done) { var array = NSArray.arrayWithArray([1, 2, 3]); @@ -503,7 +507,7 @@ describe("Native callback self wrappers", function () { done(); }); }); - }); + }, SETTLE_TIMEOUT_MS); it("frees an object JS alone holds after alloc().init() ran its JS initializer", function (done) { var obj = JSInit.alloc().init(); @@ -518,7 +522,7 @@ describe("Native callback self wrappers", function () { done(); }); }); - }); + }, SETTLE_TIMEOUT_MS); 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(); @@ -540,7 +544,7 @@ describe("Native callback self wrappers", function () { done(); }); }); - }); + }, SETTLE_TIMEOUT_MS); it("keeps a wrapped object a JS initializer returns instead of its receiver (alloc().init())", function (done) { expectInitializerResultOwnedByCaller(function () { @@ -548,13 +552,13 @@ describe("Native callback self wrappers", function () { return InitReturnsOther.alloc().init(); }); }, done); - }); + }, SETTLE_TIMEOUT_MS); it("keeps the substitute a super initializer returned through a JS initializer (alloc().init())", function (done) { expectInitializerResultOwnedByCaller(function () { return InitReturnsSubstitute.alloc().init(); }, done); - }); + }, SETTLE_TIMEOUT_MS); it("does not release a wrapped receiver that is initialized again", function (done) { var plain = TNSAllocLog.new(); @@ -580,7 +584,7 @@ describe("Native callback self wrappers", function () { done(); }); }); - }); + }, SETTLE_TIMEOUT_MS); // Native code that owns what an owned-return method answers drops it. The // object a JS implementation answered must outlive that, and be freed @@ -630,42 +634,42 @@ describe("Native callback self wrappers", function () { expectKeptThroughNativeDrop(state, function (receiver) { TNSOwnedReturns.copyAndDrop(receiver); }, 1, done); - }); + }, SETTLE_TIMEOUT_MS); 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); - }); + }, SETTLE_TIMEOUT_MS); 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); - }); + }, SETTLE_TIMEOUT_MS); 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); - }); + }, SETTLE_TIMEOUT_MS); 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); - }); + }, SETTLE_TIMEOUT_MS); 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); - }); + }, SETTLE_TIMEOUT_MS); // The receiver is not a TNSAllocLog: its reference, consumed by the call, // is not given back when the JS method answers another object. @@ -674,7 +678,7 @@ describe("Native callback self wrappers", function () { expectKeptThroughNativeDrop(state, function (receiver) { TNSOwnedReturns.awakeAndDrop(receiver); }, 1, done); - }); + }, SETTLE_TIMEOUT_MS); function expectBalancedJsCopies(answersReceiver, name, done) { var state = ownedReturnState(TNSOwnedReturns, name, "copyWithZone", [NSCopying], answersReceiver); @@ -699,11 +703,11 @@ describe("Native callback self wrappers", function () { it("balances copy() called from JS on a JS copyWithZone that answers its receiver", function (done) { expectBalancedJsCopies(true, "NativeCallbackSelfJsCopySelf", done); - }); + }, SETTLE_TIMEOUT_MS); it("balances copy() called from JS on a JS copyWithZone that answers another object", function (done) { expectBalancedJsCopies(false, "NativeCallbackSelfJsCopyOther", done); - }); + }, SETTLE_TIMEOUT_MS); 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, { @@ -712,7 +716,7 @@ describe("Native callback self wrappers", function () { expectKeptThroughNativeDrop(state, function (receiver) { TNSOwnedReturns.newChildAndDrop(receiver); }, 2, done); - }); + }, SETTLE_TIMEOUT_MS); function ownedGetterState(answersReceiver, name) { return ownedReturnState(TNSOwnedReturns, name, "newItem", [], answersReceiver, { getter: true }); @@ -723,14 +727,14 @@ describe("Native callback self wrappers", function () { expectKeptThroughNativeDrop(state, function (receiver) { TNSOwnedReturns.newItemAndDrop(receiver); }, 2, done); - }); + }, SETTLE_TIMEOUT_MS); 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); - }); + }, SETTLE_TIMEOUT_MS); function expectBalancedGetterReads(answersReceiver, name, done) { var state = ownedGetterState(answersReceiver, name); @@ -743,11 +747,11 @@ describe("Native callback self wrappers", function () { it("balances reads of a JS new-family getter that answers another object", function (done) { expectBalancedGetterReads(false, "NativeCallbackSelfGetterReadsOther", done); - }); + }, SETTLE_TIMEOUT_MS); it("balances reads of a JS new-family getter that answers its receiver", function (done) { expectBalancedGetterReads(true, "NativeCallbackSelfGetterReadsSelf", done); - }); + }, SETTLE_TIMEOUT_MS); // The replacements stay installed for the rest of the run, on a class no // other spec uses, and answer what `swizzled.answer` gives them. @@ -779,14 +783,14 @@ describe("Native callback self wrappers", function () { expectKeptThroughNativeDrop(state, function (receiver) { TNSOwnedReturns.newChildAndDrop(receiver); }, 2, done); - }); + }, SETTLE_TIMEOUT_MS); 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); - }); + }, SETTLE_TIMEOUT_MS); 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); @@ -794,7 +798,7 @@ describe("Native callback self wrappers", function () { TNSOwnedReturns.newItemAndDrop(receiver); expect(TNSOwnedReturns.readNewItemOf(receiver)).toBe(state.result); }, 2, done); - }); + }, SETTLE_TIMEOUT_MS); it("frees once an object whose native -init ran a JS method on it (alloc().init())", function (done) { var hooks = 0; @@ -816,7 +820,7 @@ describe("Native callback self wrappers", function () { done(); }); }); - }); + }, SETTLE_TIMEOUT_MS); // -unarchiver:didDecodeObject: takes over the object it is given // (NS_RELEASES_ARGUMENT) and answers an owned one. @@ -896,7 +900,7 @@ describe("Native callback self wrappers", function () { it("decodes without an unarchiver delegate", function (done) { expectBalancedDecode(null, null, 0, 2, expectDecodedRoot(TNSCodingAllocLog), done); - }); + }, SETTLE_TIMEOUT_MS); [ { Delegate: DecodeDelegate, suffix: "" }, @@ -908,7 +912,7 @@ describe("Native callback self wrappers", function () { expectBalancedDecode(Delegate, function (object) { return object; }, 0, 2, expectDecodedRoot(TNSCodingAllocLog), done); - }); + }, SETTLE_TIMEOUT_MS); it("releases the objects a JS unarchiver delegate replaces" + variant.suffix, function (done) { expectBalancedDecode(Delegate, function (object) { @@ -917,14 +921,14 @@ describe("Native callback self wrappers", function () { expectDecodedRoot(TNSAllocLog)(root); expect(root.objectAtIndex(0) instanceof TNSCodingAllocLog).toBe(false); }, done); - }); + }, SETTLE_TIMEOUT_MS); // 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); - }); + }, SETTLE_TIMEOUT_MS); }); it("gives a native unarchiver delegate called from JS the reference it takes over", function (done) { @@ -953,7 +957,7 @@ describe("Native callback self wrappers", function () { done(); }); }); - }); + }, SETTLE_TIMEOUT_MS); // JS receives these as primitives, so only the native side sees their // reference counts. @@ -997,25 +1001,25 @@ describe("Native callback self wrappers", function () { expectPrimitivesRetainedAsBefore(function (holder, index) { return holder.newObjectAt(index); }, done); - }); + }, SETTLE_TIMEOUT_MS); it("leaves unowned results JS receives as primitives retained as they were", function (done) { expectPrimitivesRetainedAsBefore(function (holder, index) { return holder.objectAt(index); }, done); - }); + }, SETTLE_TIMEOUT_MS); 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); - }); + }, SETTLE_TIMEOUT_MS); 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); - }); + }, SETTLE_TIMEOUT_MS); function copiesAsStringState(name, answer) { var state = { answer: answer }; @@ -1041,7 +1045,7 @@ describe("Native callback self wrappers", function () { done(); }); }); - }); + }, SETTLE_TIMEOUT_MS); // The NSString made for the JS string is never visible to JS, so only the // answers are checked. @@ -1077,13 +1081,13 @@ describe("Native callback self wrappers", function () { expectNativeBlocksFreedOnce(function (holder, value) { return holder.retainedBlockAnswering(value); }, done); - }); + }, SETTLE_TIMEOUT_MS); it("frees a native block an unowned method answers once JS drops it", function (done) { expectNativeBlocksFreedOnce(function (holder, value) { return holder.blockAnswering(value); }, done); - }); + }, SETTLE_TIMEOUT_MS); // A JS function handed to native code becomes a block that keeps the // function, and what it captures, alive until the block is freed. @@ -1116,13 +1120,13 @@ describe("Native callback self wrappers", function () { expectJsBlockRoundTrips(function (holder, fn) { return holder.retainedBlockFrom(fn); }, done); - }); + }, SETTLE_TIMEOUT_MS); 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); - }); + }, SETTLE_TIMEOUT_MS); // 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 @@ -1148,7 +1152,7 @@ describe("Native callback self wrappers", function () { done(); }); }); - }); + }, SETTLE_TIMEOUT_MS); it("frees what a JS function given to dispatch_block_create captures once JS drops the block", function (done) { var state = { calls: 0 }; @@ -1171,7 +1175,7 @@ describe("Native callback self wrappers", function () { done(); }); }); - }); + }, SETTLE_TIMEOUT_MS); // A plain JS object reaches native code as a DictionaryAdapter whose // handle keeps the object alive, so the object outlives the adapter only @@ -1208,7 +1212,7 @@ describe("Native callback self wrappers", function () { keeper.drop(); expectCollected(state, done); }); - }); + }, SETTLE_TIMEOUT_MS); it("frees the adapter for a fresh plain object a JS copyWithZone answers", function (done) { var state = freshObjectState(); @@ -1219,7 +1223,7 @@ describe("Native callback self wrappers", function () { }, { name: "NativeCallbackSelfCopyPlainObject", protocols: [NSCopying] }); TNSOwnedReturns.copyAndDrop(Klass.new()); expectCollected(state, done); - }); + }, SETTLE_TIMEOUT_MS); it("frees the adapter for a fresh plain object a JS new-family method answers", function (done) { var state = freshObjectState(); @@ -1230,7 +1234,7 @@ describe("Native callback self wrappers", function () { }, { name: "NativeCallbackSelfNewPlainObject" }); TNSOwnedReturns.newChildAndDrop(Klass.new()); expectCollected(state, done); - }); + }, SETTLE_TIMEOUT_MS); it("frees the adapter for a fresh plain object a JS initializer answers", function (done) { var state = freshObjectState(); @@ -1241,7 +1245,7 @@ describe("Native callback self wrappers", function () { }, { name: "NativeCallbackSelfInitPlainObject" }); TNSOwnedReturns.allocInitAndDrop(Klass.class()); expectCollected(state, done); - }); + }, SETTLE_TIMEOUT_MS); function expectConstructedFreshObject(name, construct, done) { var state = freshObjectState(); @@ -1262,19 +1266,19 @@ describe("Native callback self wrappers", function () { expectConstructedFreshObject("NativeCallbackSelfNewOperatorPlainObject", function (Klass) { return new Klass(); }, done); - }); + }, SETTLE_TIMEOUT_MS); it("answers from alloc().init() the fresh plain object a JS initializer answers", function (done) { expectConstructedFreshObject("NativeCallbackSelfAllocInitPlainObject", function (Klass) { return Klass.alloc().init(); }, done); - }); + }, SETTLE_TIMEOUT_MS); it("answers from new() the fresh plain object a JS initializer answers", function (done) { expectConstructedFreshObject("NativeCallbackSelfNewMethodPlainObject", function (Klass) { return Klass.new(); }, done); - }); + }, SETTLE_TIMEOUT_MS); it("balances the adapter for a plain object a JS copyWithZone answers twice", function (done) { var state = { weak: null }; @@ -1296,5 +1300,5 @@ describe("Native callback self wrappers", function () { keeper.drop(); expectCollected(state, done); }); - }); + }, SETTLE_TIMEOUT_MS); }); diff --git a/TestRunner/app/tests/WrapperLifetimeLeaksTests.js b/TestRunner/app/tests/WrapperLifetimeLeaksTests.js index e013d5d3..b61e22da 100644 --- a/TestRunner/app/tests/WrapperLifetimeLeaksTests.js +++ b/TestRunner/app/tests/WrapperLifetimeLeaksTests.js @@ -30,6 +30,7 @@ describe("Wrapper lifetime leak cycles", function () { var QueuedOwned = shape("TNSLeakQueuedOwned"); var SharedChild = shape("TNSLeakSharedChild"); var ReleasedOwner = shape("TNSLeakReleasedOwner"); + var DeferredShared = shape("TNSLeakDeferredShared"); // Its operation's block names the object through `this`. Extended the // way TypeScript does: only such classes track native retains, which is // what makes "resurrecting" keep a natively owned instance's wrapper. @@ -217,32 +218,47 @@ describe("Wrapper lifetime leak cycles", function () { var reports = {}; beforeAll(function (done) { + // Each shape gets its own scope: functions created in one scope + // share its context, which would tie a shape's reachability to + // every variable the other shapes' closures capture. (function () { var selfRef = SelfRef.new(); selfRef.me = selfRef; - + watched.addObject(selfRef); + })(); + (function () { var closure = Closure.new(); closure.onTap = function () { return closure; }; - + watched.addObject(closure); + })(); + (function () { var nativeCycle = NativeCycle.new(); var list = NSMutableArray.new(); list.addObject(nativeCycle); nativeCycle.list = list; - + watched.addObject(nativeCycle); + })(); + (function () { var blockCycle = BlockCycle.new(); blockCycle.op = NSBlockOperation.blockOperationWithBlock(function () { return blockCycle; }); - + watched.addObject(blockCycle); + })(); + (function () { var ownedSelfRef = OwnedSelfRef.new(); ownedSelfRef.me = ownedSelfRef; owner.addObject(ownedSelfRef); - + watched.addObject(ownedSelfRef); + })(); + (function () { var weakBackRef = WeakBackRef.new(); weakBackRef.me = new WeakRef(weakBackRef); - + watched.addObject(weakBackRef); + })(); + (function () { // Two non-owning pointers (NSValue's storage) explain more // retains than the object has. var unexplained = Unexplained.new(); @@ -251,7 +267,9 @@ describe("Wrapper lifetime leak cycles", function () { NSValue.valueWithNonretainedObject(unexplained), NSValue.valueWithNonretainedObject(unexplained), ]; - + watched.addObject(unexplained); + })(); + (function () { // A handler on the object that owns it, naming the object: the // block's strong handle on its function closes the cycle. var selfHandler = SelfHandler.new(); @@ -259,7 +277,9 @@ describe("Wrapper lifetime leak cycles", function () { selfHandler.addExecutionBlock(function () { return selfHandler.x; }); - + watched.addObject(selfHandler); + })(); + (function () { var weakHandler = WeakHandler.new(); weakHandler.x = 1; var weakHandlerRef = new WeakRef(weakHandler); @@ -267,16 +287,8 @@ describe("Wrapper lifetime leak cycles", function () { var o = weakHandlerRef.deref(); return o && o.x; }); - - [selfRef, closure, nativeCycle, blockCycle, ownedSelfRef, weakBackRef, unexplained, selfHandler, weakHandler].forEach( - function (o) { - watched.addObject(o); - } - ); + watched.addObject(weakHandler); })(); - // Shapes below get their own scopes: functions created in one - // scope share its context, which would tie their reachability - // to every variable the other shapes' closures capture. (function () { // The handler does not close over its operation; the WeakMap // entry keyed by the handler does. @@ -503,6 +515,7 @@ describe("Wrapper lifetime leak cycles", function () { o.list.removeAllObjects(); delete o.list; } + delete o.op; }); hidden.removeAllObjects(); holder.removeAllObjects(); @@ -556,6 +569,36 @@ describe("Wrapper lifetime leak cycles", function () { done(); }); }, 30000); + + // An explicit release on another thread of an object first wrapped on + // the runtime's thread waits there for an event loop task. The + // Atomics.waitAsync wakeup is posted to the same lane first, so the + // probe runs while that release still waits. + it("finds a cycle that an object waiting for its release on the runtime's thread shared", function (done) { + var other; + (function () { + var shared = DeferredShared.new(); + shared.op = NSBlockOperation.blockOperationWithBlock(function () { + return shared; + }); + other = NSMutableArray.new(); + other.addObject(shared.op); + watched.addObject(shared); + })(); + var signal = new Int32Array(new SharedArrayBuffer(4)); + Atomics.waitAsync(signal, 0, 0).value.then(function () { + var report = runtime.findLeakCycles(); + expect(cyclesNaming(report, "TNSLeakDeferredShared").length).toBeGreaterThan(0); + expect(aliveNamed(watched, "TNSLeakDeferredShared")).toBe(1); + done(); + }, done.fail); + var queue = dispatch_get_global_queue(qos_class_t.QOS_CLASS_DEFAULT, 0); + dispatch_async(queue, function () { + Atomics.notify(signal, 0); + __releaseNativeCounterpart(other); + other = null; + }); + }); }); // The session owns the task, the task its completion block, and the block diff --git a/run_tests.sh b/run_tests.sh index 48fb6705..86febcee 100755 --- a/run_tests.sh +++ b/run_tests.sh @@ -277,6 +277,11 @@ Destination (default: the single booted simulator, else a prompt): Mac (hardened runtime, ad-hoc signed, allow-jit entitlement). Cannot be combined with any simulator option. Only one Catalyst run per user at a time: later ones wait for it. + --no-xctest With --catalyst: launch the built app directly instead of + through XCUITest, so Automation Mode is not needed. The app's + console goes to /console.log and its junit report + to /test-out/junit-result.xml. No host HTTP server + runs, so the specs that need one are skipped. Simulator management (no tests run): --create-sim Create and boot ${SIM_PREFIX}, print its UDID, exit @@ -328,6 +333,7 @@ DELETE_TARGET="" TEST_FOLDER="" CATALYST=0 WRAPPER_LIFETIME="" +NO_XCTEST=0 set_sim_mode() { if [ -n "$SIM_MODE" ] && [ "$SIM_MODE" != "$1" ]; then @@ -377,6 +383,7 @@ while [ $# -gt 0 ]; do --catalyst) CATALYST=1; shift ;; --wrapper-lifetime|--wrapper-lifetime=*) take_value "--wrapper-lifetime" "$1" "${2:-}" "$has_next"; WRAPPER_LIFETIME="$OPT_VALUE"; shift "$OPT_SHIFT" ;; + --no-xctest) NO_XCTEST=1; shift ;; -a|--asan) ASAN=1; shift ;; -t|--temp-folder) TEMP_FOLDER=1; shift ;; -h|--help) usage; exit 0 ;; @@ -384,6 +391,10 @@ while [ $# -gt 0 ]; do esac done +if [ "$NO_XCTEST" -eq 1 ]; then + [ "$CATALYST" -eq 1 ] || die_usage "--no-xctest only applies to --catalyst." + [ "$ASAN" -eq 0 ] || die_usage "--no-xctest cannot be combined with --asan." +fi if [ "$CATALYST" -eq 1 ]; then if [ -n "$SIM_MODE" ] || [ -n "$DEVICE_NAME" ] || [ -n "$DEVICE_UDID" ] || [ -n "$SIM_NAME" ] \ || [ -n "$SIM_DEVICE_TYPE" ] || [ -n "$SIM_RUNTIME" ]; then @@ -397,7 +408,7 @@ if [ "$CATALYST" -eq 1 ]; then # TestRunnerTests is a UI-testing bundle; on macOS its runner must switch the # session into Automation Mode, which otherwise asks for an admin password and # times out unattended. GitHub's macOS runner images come preconfigured. - if ! automationmodetool 2>/dev/null | grep -q "DOES NOT REQUIRE"; then + if [ "$NO_XCTEST" -eq 0 ] && ! automationmodetool 2>/dev/null | grep -q "DOES NOT REQUIRE"; then echo "--catalyst needs Automation Mode without authentication. Enable it once with:" >&2 echo " sudo automationmodetool enable-automationmode-without-authentication" >&2 exit 1 @@ -452,6 +463,7 @@ for devices in json.load(sys.stdin)['devices'].values(): finish_run() { local status=$? if [ "$CATALYST" -eq 1 ]; then + stop_direct_app release_catalyst_lock [ -n "$TEST_FOLDER" ] && echo "Test folder: $TEST_FOLDER" echo "Simulator: none (--catalyst ran on this Mac)" @@ -511,6 +523,78 @@ release_catalyst_lock() { fi } +DIRECT_APP_PID="" +DIRECT_TIMEOUT_SECONDS=900 + +# SIGTERM, then SIGKILL after 5 s; returns once the app is gone. +stop_direct_app() { + [ -n "$DIRECT_APP_PID" ] || return 0 + kill -TERM "$DIRECT_APP_PID" 2>/dev/null + local waited=0 + while kill -0 "$DIRECT_APP_PID" 2>/dev/null && [ "$waited" -lt 50 ]; do + sleep 0.1 + waited=$((waited + 1)) + done + kill -KILL "$DIRECT_APP_PID" 2>/dev/null + wait "$DIRECT_APP_PID" 2>/dev/null + DIRECT_APP_PID="" +} + +# --catalyst --no-xctest. The app never quits by itself; the junit report it +# writes once the suite ends is the end marker. CFFIXED_USER_HOME moves that +# report's ~/Documents into the test folder, and OS_ACTIVITY_DT_MODE mirrors +# the runtime's os_log output to stderr. +run_catalyst_directly() { + local build_args=(-project "$SCRIPT_DIR/v8ios.xcodeproj" -scheme TestRunner -destination "$DESTINATION") + xcodebuild "${build_args[@]}" "${XCODEBUILD_ARGS[@]}" build | xcpretty || return 1 + local app + app=$(xcodebuild "${build_args[@]}" -showBuildSettings 2>/dev/null | + awk -F' = ' '/^Build settings for .* target / { mine = ($0 ~ / target TestRunner:$/) } + mine && $1 ~ /^ *CODESIGNING_FOLDER_PATH$/ { print $2; exit }') + if [ ! -x "$app/Contents/MacOS/TestRunner" ]; then + echo "No Mac Catalyst TestRunner.app at '$app'." >&2 + return 1 + fi + + local home="$TEST_FOLDER/home" + local report="$home/Documents/junit-result.xml" + local log="$TEST_FOLDER/console.log" + mkdir -p "$home/Documents" "$TEST_FOLDER/test-out" + echo "Launching $app" + echo "Console: $log" + CFFIXED_USER_HOME="$home" OS_ACTIVITY_DT_MODE=1 "$app/Contents/MacOS/TestRunner" > "$log" 2>&1 & + DIRECT_APP_PID=$! + + local deadline=$((SECONDS + DIRECT_TIMEOUT_SECONDS)) status=0 + while [ ! -f "$report" ]; do + if ! kill -0 "$DIRECT_APP_PID" 2>/dev/null; then + wait "$DIRECT_APP_PID" || status=$? + DIRECT_APP_PID="" + echo "TestRunner exited (status $status) before the suite finished: it CRASHED. See $log and ~/Library/Logs/DiagnosticReports/TestRunner-*.ips." >&2 + return 1 + fi + if [ "$SECONDS" -ge "$deadline" ]; then + echo "No junit report after ${DIRECT_TIMEOUT_SECONDS}s while TestRunner was still running: the suite HUNG. See $log." >&2 + return 1 + fi + sleep 1 + done + stop_direct_app + + cp "$report" "$TEST_FOLDER/test-out/junit-result.xml" + local summary failures + summary=$(grep -oE 'CONSOLE LOG: (SUCCESS|FAILURE): .*' "$log" | tail -n 1 | sed 's/^CONSOLE LOG: //') + echo "$summary" + failures=$(grep -c -e '&2 + grep -B1 -e '&2 + return 1 + fi + # Run-level errors (a focused spec, an error outside any spec) fail no spec. + [ "${summary#SUCCESS: }" != "$summary" ] +} + if [ "$CATALYST" -eq 1 ]; then SIM_MODE="catalyst" fi @@ -592,22 +676,27 @@ if [ -n "$WRAPPER_LIFETIME" ]; then fi set -o pipefail -xcodebuild -project "$SCRIPT_DIR/v8ios.xcodeproj" -scheme TestRunner \ - -resultBundlePath "$TEST_FOLDER/test_results" \ - -destination "$DESTINATION" \ - "${XCODEBUILD_ARGS[@]}" \ - build test | xcpretty +if [ "$NO_XCTEST" -eq 1 ]; then + run_catalyst_directly + TEST_EXIT=$? +else + xcodebuild -project "$SCRIPT_DIR/v8ios.xcodeproj" -scheme TestRunner \ + -resultBundlePath "$TEST_FOLDER/test_results" \ + -destination "$DESTINATION" \ + "${XCODEBUILD_ARGS[@]}" \ + build test | xcpretty -TEST_EXIT=$? + TEST_EXIT=$? -if [ $TEST_EXIT -ne 0 ]; then - echo "Tests failed with exit code $TEST_EXIT" -fi + if [ $TEST_EXIT -ne 0 ]; then + echo "Tests failed with exit code $TEST_EXIT" + fi -if command -v xcparse &>/dev/null; then - xcparse attachments "$TEST_FOLDER/test_results.xcresult" "$TEST_FOLDER/test-out" - find "$TEST_FOLDER/test-out" -name "*junit*.xml" -maxdepth 1 -print0 | xargs -n 1 -0 npx junit-cli-report-viewer - find "$TEST_FOLDER/test-out" -name "*junit*.xml" -maxdepth 1 -print0 | xargs -n 1 -0 npx verify-junit-xml + if command -v xcparse &>/dev/null; then + xcparse attachments "$TEST_FOLDER/test_results.xcresult" "$TEST_FOLDER/test-out" + find "$TEST_FOLDER/test-out" -name "*junit*.xml" -maxdepth 1 -print0 | xargs -n 1 -0 npx junit-cli-report-viewer + find "$TEST_FOLDER/test-out" -name "*junit*.xml" -maxdepth 1 -print0 | xargs -n 1 -0 npx verify-junit-xml + fi fi if [ -n "$WRAPPER_LIFETIME" ]; then