From 563b0d37dd8381accbe7490d9412417360c75bb7 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 15:05:21 -0300 Subject: [PATCH] fix(runtime): leak probe review fixes - Settle before every snapshot: findLeakCycles and the cycles, strict and inspect triggers run three full collections, each followed by the queued releases and a synchronous drain of deallocated canary records. A wrapper that dies in the snapshot's own collection reports its queued retains (Instance.queued), so its object is neither listed as changed nor stripped of its root status, and the pending retain counts as the runtime's. - Model the object a resurrecting wrapper lives for: an ns:kept edge from the object to a GC-protected wrapper behind a weak handle, excluded from the two-node loop check like ns:owned. - The state handles of canary records whose object is being or was deallocated are the runtime's handles, not roots. - Scope the handles EdgeName and NodeName make. - LeakProbe SPI version 3. - Docs: settling, ns:kept, and the JS block disposal race as a limitation. --- NativeScript/runtime/LeakProbe.mm | 34 +++++- NativeScript/runtime/LeakProbeSPI.h | 23 +++- NativeScript/runtime/WrapperLifetime.h | 6 + NativeScript/runtime/WrapperLifetime.mm | 11 ++ NativeScript/runtime/WrapperLifetimeCanary.h | 11 ++ NativeScript/runtime/WrapperLifetimeCanary.mm | 44 ++++++++ .../NativeScriptLeakProbe.mm | 83 ++++++++++---- .../app/tests/WrapperLifetimeLeaksTests.js | 106 ++++++++++++++++++ docs/ns-builtin-modules.md | 43 ++++--- 9 files changed, 316 insertions(+), 45 deletions(-) diff --git a/NativeScript/runtime/LeakProbe.mm b/NativeScript/runtime/LeakProbe.mm index 951d03eb1..4ec750ca6 100644 --- a/NativeScript/runtime/LeakProbe.mm +++ b/NativeScript/runtime/LeakProbe.mm @@ -1,6 +1,7 @@ #include "LeakProbe.h" #include #include +#include #include "Caches.h" #include "ClassBuilder.h" #include "DataWrapper.h" @@ -53,10 +54,20 @@ bool ForEachInstance(Isolate* isolate, void* context, if (cache == nullptr || !cache->IsValid()) { return false; } + // A wrapper built for an object whose previous wrapper's release is still + // queued replaces its Instances entry, so a queued retain may have none. + std::unordered_map queued; + WrapperLifetime::ForEachQueuedRelease(isolate, + [&](id object) { queued[(__bridge void*)object]++; }); for (auto& entry : cache->Instances) { const std::shared_ptr>& handle = entry.second; Instance instance{}; instance.object = (__bridge void*)entry.first; + auto pending = queued.find(instance.object); + if (pending != queued.end()) { + instance.queued = pending->second; + queued.erase(pending); + } if (handle != nullptr && !handle->IsEmpty()) { instance.wrapper = handle->Get(isolate); BaseDataWrapper* data = GetValue(isolate, instance.wrapper); @@ -71,10 +82,19 @@ bool ForEachInstance(Isolate* isolate, void* context, ObjectWeakCallbackState* ownership = wrapper->OwnershipState(); instance.reconciledStrong = ownership != nullptr && !ownership->disposing_ && ownership->target_ == handle && !handle->IsWeak(); + // A handle under ownership tracking is reconciled before every major + // collection, the snapshot's included, so reconciledStrong covers it. + instance.resurrects = handle->IsWeak() && wrapper->IsGcProtected(); } } visit(context, instance); } + for (const auto& [object, count] : queued) { + Instance instance{}; + instance.object = object; + instance.queued = count; + visit(context, instance); + } return true; } @@ -84,6 +104,17 @@ void ForEachCanaryState(Isolate* isolate, void* context, isolate, [&](id object, Local state) { visit(context, object, state); }); } +void ForEachCanaryStateHandle(Isolate* isolate, void* context, + void (*visit)(void* context, Local state)) { + WrapperLifetimeCanary::ForEachStateHandle(isolate, + [&](Local state) { visit(context, state); }); +} + +void DrainReleases(Isolate* isolate) { + WrapperLifetime::DrainReleases(isolate); + WrapperLifetimeCanary::ReleaseDeadStates(isolate); +} + void* IsolateState(Isolate* isolate) { ProbeState* probe = Caches::StateFor(isolate); return probe != nullptr ? probe->state : nullptr; @@ -141,6 +172,7 @@ bool LifetimeStats(Isolate* isolate, leakprobe::LifetimeStats* out) { .size = sizeof(Host), .forEachInstance = ForEachInstance, .forEachCanaryState = ForEachCanaryState, + .forEachCanaryStateHandle = ForEachCanaryStateHandle, .isJSBlock = Interop::IsJSBlock, .jsBlockCallback = Interop::JSBlockCallback, .nativeClass = ClassBuilder::FindNativeClass, @@ -149,7 +181,7 @@ bool LifetimeStats(Isolate* isolate, leakprobe::LifetimeStats* out) { .createPoster = CreatePoster, .post = Post, .destroyPoster = [](Poster* poster) { delete poster; }, - .drainReleases = WrapperLifetime::DrainReleases, + .drainReleases = DrainReleases, .lifetimeMode = []() { return WrapperLifetimeModeName(GetWrapperLifetimeMode()); }, .lifetimeScope = []() { return WrapperLifetimeScopeName(GetWrapperLifetimeScope()); }, .lifetimeStats = LifetimeStats, diff --git a/NativeScript/runtime/LeakProbeSPI.h b/NativeScript/runtime/LeakProbeSPI.h index 0bbb3f8ad..b4c168fce 100644 --- a/NativeScript/runtime/LeakProbeSPI.h +++ b/NativeScript/runtime/LeakProbeSPI.h @@ -23,16 +23,20 @@ namespace tns { namespace leakprobe { -constexpr uint32_t kVersion = 2; +constexpr uint32_t kVersion = 3; constexpr const char* kConnectSymbol = "NativeScriptLeakProbeConnect"; -// One entry of an isolate's native object -> wrapper map. The runtime has not -// dereferenced `object`, which another thread may have freed. +// One entry of an isolate's native object -> wrapper map, or an object whose +// only runtime retains are queued ones (`wrapper` empty). The runtime has not +// dereferenced `object`, which another thread may have freed unless `queued`. struct Instance { void* object; // Empty once the wrapper is gone. v8::Local wrapper; + // Retains the runtime still holds on `object` for wrappers that died, until + // the next drain (Host::drainReleases) on this isolate's thread. + uint32_t queued; // `wrapper` wraps an Objective-C object; the fields below are meaningful // only then. bool objc; @@ -44,6 +48,10 @@ struct Instance { // The map holds the wrapper through the strong handle the runtime keeps for // a JS-extended object native code also retains. bool reconciledStrong; + // The map holds the wrapper through a weak handle whose disposal is refused + // while native code retains the object ("resurrecting"): the object keeps + // the wrapper alive. + bool resurrects; }; struct LifetimeStats { @@ -75,6 +83,12 @@ struct Host { void (*forEachCanaryState)(v8::Isolate* isolate, void* context, void (*visit)(void* context, id object, v8::Local state)); + // Every canary state handle the runtime holds, those forEachCanaryState + // skips included: states of objects being deallocated, and of deallocated + // objects until the next drain lets go of them. + void (*forEachCanaryStateHandle)(v8::Isolate* isolate, void* context, + void (*visit)(void* context, + v8::Local state)); // Whether the runtime made `block` (alive) for JS. bool (*isJSBlock)(const void* block); // The JS function a JS block made for this isolate calls; empty for other @@ -100,7 +114,8 @@ struct Host { // Any thread. void (*destroyPoster)(Poster* poster); - // Releases the native objects wrapper lifetime modes queued for release. + // Releases the native objects wrapper lifetime modes queued for release, + // 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/WrapperLifetime.h b/NativeScript/runtime/WrapperLifetime.h index 6ca6ae624..e58c01d57 100644 --- a/NativeScript/runtime/WrapperLifetime.h +++ b/NativeScript/runtime/WrapperLifetime.h @@ -2,6 +2,7 @@ #define WrapperLifetime_h #include +#include #include "Common.h" #include "DataWrapper.h" @@ -94,6 +95,11 @@ class WrapperLifetime { // run: release can reach a JS-implemented -dealloc. static void DrainReleases(v8::Isolate* isolate); + // Calls `visit` with the object of each dead wrapper whose release + // DrainReleases has yet to make, once per queued retain. + static void ForEachQueuedRelease(v8::Isolate* isolate, + const std::function& visit); + // JS->native call entry: a long synchronous stretch of JS must not hold dead // objects until it yields. The gate is process-wide; while another isolate // has queued releases this costs one state lookup per call. diff --git a/NativeScript/runtime/WrapperLifetime.mm b/NativeScript/runtime/WrapperLifetime.mm index fb67d729b..a7d634892 100644 --- a/NativeScript/runtime/WrapperLifetime.mm +++ b/NativeScript/runtime/WrapperLifetime.mm @@ -427,6 +427,17 @@ void ReleaseAll(Isolate* isolate, RootedState* rooted) { ReleaseAll(isolate, rooted); } +void WrapperLifetime::ForEachQueuedRelease(Isolate* isolate, + const std::function& visit) { + RootedState* rooted = Caches::ExistingStateFor(isolate); + if (rooted == nullptr) { + return; + } + for (ObjectWeakCallbackState* state : rooted->releases) { + visit(state->lifetimeTarget_); + } +} + void WrapperLifetime::DrainForTeardown(Isolate* isolate) { WrapperLifetimeCanary::CloseForTeardown(isolate); RootedState* rooted = Caches::ExistingStateFor(isolate); diff --git a/NativeScript/runtime/WrapperLifetimeCanary.h b/NativeScript/runtime/WrapperLifetimeCanary.h index 06dfc2724..fd1f31edc 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.h +++ b/NativeScript/runtime/WrapperLifetimeCanary.h @@ -99,6 +99,17 @@ class WrapperLifetimeCanary { static void ForEachState( v8::Isolate* isolate, const std::function state)>& visit); + + // Calls `visit` with every state handle the registry holds: ForEachState's, + // and those of objects being deallocated or deallocated but not yet let go + // of. The caller provides the HandleScope. + static void ForEachStateHandle( + v8::Isolate* isolate, + const std::function state)>& visit); + + // Lets go of the state of every object known to be deallocated now, rather + // than on the drain its deallocation posted. + static void ReleaseDeadStates(v8::Isolate* isolate); }; } // namespace tns diff --git a/NativeScript/runtime/WrapperLifetimeCanary.mm b/NativeScript/runtime/WrapperLifetimeCanary.mm index bb878f945..76bc8fc4d 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.mm +++ b/NativeScript/runtime/WrapperLifetimeCanary.mm @@ -1021,4 +1021,48 @@ void WrapCallback(const FunctionCallbackInfo& info) { } } +void WrapperLifetimeCanary::ForEachStateHandle( + Isolate* isolate, const std::function state)>& visit) { + CanaryState* state = Caches::ExistingStateFor(isolate); + if (state == nullptr) { + return; + } + // Not gated on the live count: dead records outlast it. + std::vector> handles; + { + std::lock_guard lock(state->registry->mutex); + if (state->registry->closed) { + return; + } + for (auto& entry : state->registry->records) { + if (!entry.second->state.IsEmpty()) { + handles.push_back(entry.second->state.Get(isolate)); + } + } + for (const std::shared_ptr& record : state->registry->dead) { + if (!record->state.IsEmpty()) { + handles.push_back(record->state.Get(isolate)); + } + } + } + for (Local handle : handles) { + visit(handle); + } +} + +void WrapperLifetimeCanary::ReleaseDeadStates(Isolate* isolate) { + if (GetWrapperLifetimeMode() != WrapperLifetimeMode::kCanary) { + return; + } + CanaryState* state = Caches::ExistingStateFor(isolate); + if (state == nullptr) { + return; + } +#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_WEAK_SWEEP + Sweep(state->registry); +#else + DrainDead(state->registry); +#endif +} + } // namespace tns diff --git a/NativeScriptLeakProbe/NativeScriptLeakProbe.mm b/NativeScriptLeakProbe/NativeScriptLeakProbe.mm index 19f1c130e..e24b9d9ca 100644 --- a/NativeScriptLeakProbe/NativeScriptLeakProbe.mm +++ b/NativeScriptLeakProbe/NativeScriptLeakProbe.mm @@ -4,7 +4,8 @@ // // Heap snapshots carry both heaps: an embedder graph adds a node per native // object the runtime wraps or keeps JS state for, and the runtime's own -// cross-heap edges (wrapper -> object retain, rooted-strong object -> wrapper, +// cross-heap edges (wrapper -> object retain, object -> wrapper while native +// code owns the object and that keeps the wrapper strong or resurrects it, // canary object -> state, adapter -> JS object). Any snapshot gets these, // DevTools' included. JS block -> callback edges are added by findLeakCycles() // only: the runtime keeps no list of its JS blocks, and never wraps one made @@ -98,6 +99,13 @@ void ForEachState(Isolate* isolate, Visit&& visit) { }); } +template +void ForEachStateHandle(Isolate* isolate, Visit&& visit) { + host_->forEachCanaryStateHandle(isolate, &visit, [](void* context, Local state) { + (*static_cast*>(context))(state); + }); +} + constexpr const char* kCountsNotification = "org.nativescript.wrapperLifetime.counts"; constexpr const char* kCyclesNotification = "org.nativescript.wrapperLifetime.findLeakCycles"; constexpr const char* kStrictCyclesNotification = @@ -1064,6 +1072,8 @@ bool IsAdapter(Class cls) { // The map's handle is the strong one the runtime keeps while native code // also retains the object: a wrapper no lifetime mode adopted. bool reconciledStrong = false; + // The object keeps the wrapper alive through resurrection. + bool resurrects = false; }; // False for entries whose key must not be dereferenced as the wrapped object: @@ -1096,6 +1106,7 @@ bool ReadInstance(const ClassSet& classes, const Instance& instance, Wrapped* ou } out->rootedStrong = instance.rootedStrong; out->reconciledStrong = instance.reconciledStrong; + out->resurrects = instance.resurrects; return true; } @@ -1130,13 +1141,26 @@ bool BuildNativeGraph(Isolate* isolate, ProbeRun* run) { bool valid = ForEachInstance(isolate, [&](const Instance& instance) { Wrapped wrapped; - if (!ReadInstance(run->classes, instance, &wrapped)) { + if (ReadInstance(run->classes, instance, &wrapped)) { + if (NativeEntry* native = add(instance.object, wrapped.cls, 0)) { + native->seed = true; + native->held = !wrapped.adapter || instance.queued > 0; + native->runtimeRetains = (wrapped.adapter ? 0 : 1) + instance.queued; + } return; } - if (NativeEntry* native = add(instance.object, wrapped.cls, 0)) { - native->seed = true; - native->held = !wrapped.adapter; - native->runtimeRetains = wrapped.adapter ? 0 : 1; + // A queued retain is released only on this thread, by a drain, so it + // keeps the object readable until the probe ends. + uintptr_t p = reinterpret_cast(instance.object); + if (instance.queued == 0 || IsTaggedPointer(p)) { + return; + } + if (Class cls = ObjectClass(run->classes, p, HeapBlockSize(p))) { + if (NativeEntry* native = add(instance.object, cls, 0)) { + native->seed = true; + native->held = true; + native->runtimeRetains = instance.queued; + } } }); if (!valid) { @@ -1266,7 +1290,8 @@ void BuildEmbedderGraph(Isolate* isolate, EmbedderGraph* graph, void*) { bool valid = ForEachInstance(isolate, [&](const Instance& instance) { Wrapped wrapped; if (!ReadInstance(classes, instance, &wrapped)) { - if (run != nullptr) { + // A queued retain keeps the object: still the one the graph found. + if (run != nullptr && instance.queued == 0) { auto found = run->natives.find(instance.object); if (found != run->natives.end() && found->second.seed) { found->second.changed = true; @@ -1285,6 +1310,8 @@ void BuildEmbedderGraph(Isolate* isolate, EmbedderGraph* graph, void*) { if (wrapped.rootedStrong || wrapped.reconciledStrong) { graph->AddEdge(native, js, "ns:owned"); modeled(wrapped.js); + } else if (wrapped.resurrects) { + graph->AddEdge(native, js, "ns:kept"); } }); if (!valid) { @@ -1304,6 +1331,9 @@ void BuildEmbedderGraph(Isolate* isolate, EmbedderGraph* graph, void*) { if (run == nullptr) { return; } + // States of objects being or already deallocated have no ns:state edge, but + // their handles are the runtime's, not roots. + ForEachStateHandle(isolate, [&](Local state) { modeled(state); }); for (auto& native : run->natives) { EmbedderGraph::Node* from = nodeFor(native.first, native.second.cls); for (const auto& edge : native.second.out) { @@ -1328,7 +1358,10 @@ void BuildEmbedderGraph(Isolate* isolate, EmbedderGraph* graph, void*) { return *utf8 != nullptr ? std::string(*utf8, utf8.length()) : std::string(); } +// Both run once per edge or node of walks over the whole snapshot, and each +// call makes a handle. std::string EdgeName(Isolate* isolate, const HeapGraphEdge* edge) { + HandleScope scope(isolate); Local name = edge->GetName(); if (name->IsNumber()) { return "[" + std::to_string(static_cast(name.As()->Value())) + "]"; @@ -1337,6 +1370,7 @@ void BuildEmbedderGraph(Isolate* isolate, EmbedderGraph* graph, void*) { } std::string NodeName(Isolate* isolate, const HeapGraphNode* node) { + HandleScope scope(isolate); std::string name = Utf8(isolate, node->GetName()); return name.empty() ? "(anonymous)" : name; } @@ -1472,11 +1506,12 @@ void ForEachStrongEdge(Isolate* isolate, const Ephemerons& ephemerons, const Hea bool FindCycle(Isolate* isolate, const HeapGraphNode* start, const std::unordered_set& marked, const Ephemerons& ephemerons, std::vector* hops, bool* tooLong) { - // A rooted-strong wrapper and its object always form a two-node loop; a - // leak needs a cycle that leaves through another edge. + // A wrapper its object keeps (ns:owned, ns:kept) and that object always form + // a two-node loop; a leak needs a cycle that leaves through another edge. const HeapGraphNode* ownWrapper = nullptr; for (int i = 0; i < start->GetChildrenCount(); i++) { - if (EdgeName(isolate, start->GetChild(i)) == "ns:owned") { + std::string name = EdgeName(isolate, start->GetChild(i)); + if (name == "ns:owned" || name == "ns:kept") { ownWrapper = start->GetChild(i)->GetToNode(); } } @@ -1556,10 +1591,25 @@ bool FindCycle(Isolate* isolate, const HeapGraphNode* start, return out + " " + (forSignature ? std::regex_replace(name, volatileParts, "") : name); } +// Rooted mode frees a JS-only chain of native objects one link per major +// collection, and releases happen after the collection. +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. +void Settle(Isolate* isolate) { + for (int i = 0; i < kSettleCollections; i++) { + isolate->LowMemoryNotification(); + host_->drainReleases(isolate); + } +} + // `inspect` lists class-name prefixes whose native objects the report details // (retain accounting, root, reached), to explain a missing or unexpected cycle. MaybeLocal FindLeakCycles(Isolate* isolate, Local context, bool strict, const std::vector& inspect = {}) { + // First: the drains run JS, which can define classes and build wrappers. + Settle(isolate); ProbeRun run; run.strict = strict; run.calibration = GetCalibration(); @@ -2064,15 +2114,8 @@ void Post(Trigger trigger) { return [path UTF8String]; } -// Rooted mode frees a JS-only chain of native objects one link per major -// collection, and releases happen after the collection. -constexpr int kCountCollections = 3; - void ReportCounts(Isolate* isolate) { - for (int i = 0; i < kCountCollections; i++) { - isolate->LowMemoryNotification(); - host_->drainReleases(isolate); - } + Settle(isolate); Local context = isolate->GetCurrentContext(); Local report = Object::New(isolate); report->Set(context, ToV8String(isolate, "mode"), ToV8String(isolate, host_->lifetimeMode())) @@ -2232,10 +2275,6 @@ void RunTrigger(Isolate* isolate, void* trigger) { ReportCycles(isolate, true); break; case Trigger::kInspectCycles: - for (int i = 0; i < kCountCollections; i++) { - isolate->LowMemoryNotification(); - host_->drainReleases(isolate); - } ReportCycles(isolate, false, InspectPrefixes()); break; } diff --git a/TestRunner/app/tests/WrapperLifetimeLeaksTests.js b/TestRunner/app/tests/WrapperLifetimeLeaksTests.js index 901d66d59..e013d5d3b 100644 --- a/TestRunner/app/tests/WrapperLifetimeLeaksTests.js +++ b/TestRunner/app/tests/WrapperLifetimeLeaksTests.js @@ -27,6 +27,23 @@ describe("Wrapper lifetime leak cycles", function () { var Unexplained = shape("TNSLeakUnexplained"); var Counted = shape("TNSLeakCounted"); var InFlight = shape("TNSLeakInFlight"); + var QueuedOwned = shape("TNSLeakQueuedOwned"); + var SharedChild = shape("TNSLeakSharedChild"); + var ReleasedOwner = shape("TNSLeakReleasedOwner"); + // 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. + var Kept = (function (_super) { + __extends(TNSLeakKept, _super); + function TNSLeakKept() { + return (_super !== null && _super.apply(this, arguments)) || this; + } + TNSLeakKept.prototype.arm = function () { + this.x = 1; + this.op = NSBlockOperation.blockOperationWithBlock(() => this.x); + }; + return TNSLeakKept; + })(NSObject); // The operation retains its execution blocks. var SelfHandler = NSBlockOperation.extend({}, { name: "TNSLeakSelfHandler" }); var WeakHandler = NSBlockOperation.extend({}, { name: "TNSLeakWeakHandler" }); @@ -64,6 +81,7 @@ describe("Wrapper lifetime leak cycles", function () { TNSLeakWeakMapValue: true, TNSLeakWeakMapTable: true, TNSLeakInitOwned: true, + TNSLeakKept: false, }; function scrub(n) { @@ -188,6 +206,7 @@ describe("Wrapper lifetime leak cycles", function () { // Holds its element strongly, but the probe treats it as a weak // container: an owner it cannot see. var hiddenOwner = NSHashTable.hashTableWithOptions(0 /* NSPointerFunctionsStrongMemory */); + var keptOwner = NSHashTable.hashTableWithOptions(0 /* NSPointerFunctionsStrongMemory */); // Weak watchers, to reach the leaked objects again and break their cycles. var watched = NSHashTable.weakObjectsHashTable(); // Reachable from the roots for the whole describe, like a module-level map. @@ -297,6 +316,17 @@ describe("Wrapper lifetime leak cycles", function () { selfList.list = list; watched.addObject(selfList); })(); + (function () { + // Owned from outside, so whatever keeps its wrapper alive + // (resurrection, a rooted or state handle) is not a leak. The + // probe does not see a list only the hash table holds. + var kept = Kept.alloc().init(); + var list = NSMutableArray.new(); + list.addObject(kept); + keptOwner.addObject(list); + kept.arm(); + watched.addObject(kept); + })(); (function () { // Its wrapper's handle is strong while the list retains it. var initOwned = InitOwned.new(); @@ -334,6 +364,7 @@ describe("Wrapper lifetime leak cycles", function () { rootedKey = {}; owner.removeAllObjects(); hiddenOwner.removeAllObjects(); + keptOwner.removeAllObjects(); }); it("describe the run", function () { @@ -441,6 +472,11 @@ describe("Wrapper lifetime leak cycles", function () { }); }); + it("does not report, even when strict, a cycle through an object owned from outside", function () { + expect(cyclesNaming(reports.strict, "TNSLeakKept").length).toBe(0); + expect(aliveNamed(watched, "TNSLeakKept")).toBe(1); + }); + it("collects a handler that reaches its owner through a WeakRef", function () { expect(aliveNamed(watched, "TNSLeakWeakHandler")).toBe(0); expect(aliveNamed(watched, "TNSLeakSelfHandler")).toBe(1); @@ -449,7 +485,77 @@ describe("Wrapper lifetime leak cycles", function () { it("keeps the controls alive", function () { expect(owner.count).toBe(1); expect(hiddenOwner.count).toBe(1); + expect(keptOwner.count).toBe(1); + }); + }); + + // A probe that follows a collection or a native release in the same turn, + // before the runtime's posted releases and state drains have run. + describe("in the turn of a collection or a release", function () { + var hidden = NSHashTable.hashTableWithOptions(0 /* NSPointerFunctionsStrongMemory */); + var holder = NSMutableArray.new(); + var watched = NSHashTable.weakObjectsHashTable(); + + afterAll(function () { + watched.allObjects.enumerateObjectsUsingBlock(function (o) { + delete o.me; + if (o.list) { + o.list.removeAllObjects(); + delete o.list; + } + }); + hidden.removeAllObjects(); + holder.removeAllObjects(); + }); + + it("treats an object whose canary just died as the object it was", function () { + if (!canary) { + return; + } + (function () { + var queued = QueuedOwned.new(); + hidden.addObject(queued); + var list = NSMutableArray.new(); + list.addObject(queued); + queued.list = list; + watched.addObject(queued); + })(); + scrub(300); + __collect(); + var report = runtime.findLeakCycles(); + var changed = report.changed.filter(function (entry) { + return entry.className.indexOf("TNSLeakQueuedOwned") !== -1; + }); + expect(changed.length).toBe(0); + expect(cyclesNaming(report, "TNSLeakQueuedOwned").length).toBe(0); + expect(aliveNamed(watched, "TNSLeakQueuedOwned")).toBe(1); }); + + it("finds a cycle that an object released in the same turn shared", function (done) { + if (!canary) { + done(); + return; + } + (function () { + var child = SharedChild.new(); + child.me = child; + var owner = ReleasedOwner.new(); + owner.child = child; + holder.addObject(owner); + watched.addObject(child); + watched.addObject(owner); + })(); + settle(3, function () { + // Wrapping the owner before the release would keep it alive. + expect(holder.count).toBe(1); + holder.removeAllObjects(); + var report = runtime.findLeakCycles(); + expect(cyclesNaming(report, "TNSLeakSharedChild").length).toBe(1); + expect(aliveNamed(watched, "TNSLeakReleasedOwner")).toBe(0); + expect(aliveNamed(watched, "TNSLeakSharedChild")).toBe(1); + done(); + }); + }, 30000); }); // The session owns the task, the task its completion block, and the block diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 72030cab8..111edaba4 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -199,20 +199,25 @@ it in other builds, add `NativeScriptLeakProbe.framework` to `wrappers`, the rooted-`strong` ones and the canary `states`. It is cheap; compare it before and after repeating a journey to find classes that grow. -`findLeakCycles(options)` takes a heap snapshot and reports the cycles. The -snapshot carries the native objects the runtime wraps or keeps state for, the -native objects they own (strong ivars, collection and block storage), and the -runtime's cross-heap edges: `ns:retain` (wrapper → object), `ns:owned` -(object → wrapper, for a wrapper kept strong because native code owns its -object: rooted-strong, or a wrapper no lifetime mode adopted whose handle the -runtime keeps strong), `ns:state` (canary object → state), -`ns:block-callback` (JS block → function) and `ns:adapter` (collection adapter -→ JS object). A native object counts as owned from outside when its retain -count exceeds the retains found in that graph; everything else is marked from -the V8 roots, and cycles among what stays unmarked are reported. A `WeakMap` -value is marked only once both its key and its map are. Every heap snapshot, -DevTools' included, carries the runtime's edges while the framework is -embedded, except `ns:block-callback`: only `findLeakCycles` walks native +`findLeakCycles(options)` takes a heap snapshot and reports the cycles. It +first runs three full collections, each followed by the releases the wrapper +lifetime modes queue for dead wrappers and by letting go of the state of +deallocated canary objects, so that neither reads as an owner; those releases +can run JS-implemented `-dealloc` methods. The snapshot carries the native +objects the runtime wraps or keeps state for, the native objects they own +(strong ivars, collection and block storage), and the runtime's cross-heap +edges: `ns:retain` (wrapper → object), `ns:owned` (object → wrapper, for a +wrapper kept strong because native code owns its object: rooted-strong, or a +wrapper no lifetime mode adopted whose handle the runtime keeps strong), +`ns:kept` (object → wrapper, for a `"resurrecting"` wrapper whose collection +is refused while native code retains its object), `ns:state` (canary object → +state), `ns:block-callback` (JS block → function) and `ns:adapter` (collection +adapter → JS object). A native object counts as owned from outside when its +retain count exceeds the retains found in that graph; everything else is +marked from the V8 roots, and cycles among what stays unmarked are reported. A +`WeakMap` value is marked only once both its key and its map are. Every heap +snapshot, DevTools' included, carries the runtime's edges while the framework +is embedded, except `ns:block-callback`: only `findLeakCycles` walks native memory, which is where it finds JS blocks. | option | effect | @@ -261,7 +266,9 @@ missed rather than misreported: count is read from its ivars): another thread could free them while the probe calls it; - the contents of `NSHashTable`, `NSMapTable` and `NSPointerArray`, whose - storage may be weak: what they retain counts as owned from outside. + storage may be weak: what they retain counts as owned from outside; +- a JS block whose last release started on another thread while the probe + ran: until its disposal finishes, its function counts as a root. Some leaks are held from a root rather than by a cycle alone, and are not reported even when strict. Before iOS 26, UIKit's gesture environment retains @@ -281,9 +288,9 @@ also: path: `org.nativescript.wrapperLifetime.counts` (class counts after full collections), `org.nativescript.wrapperLifetime.findLeakCycles`, `org.nativescript.wrapperLifetime.findLeakCycles.strict` and - `org.nativescript.wrapperLifetime.findLeakCycles.inspect` (after full - collections, inspecting the class-name prefixes listed one per line in - `ns-wrapper-lifetime-inspect.txt` in the temporary directory). + `org.nativescript.wrapperLifetime.findLeakCycles.inspect` (inspecting the + class-name prefixes listed one per line in `ns-wrapper-lifetime-inspect.txt` + in the temporary directory). Remote-module security (`security.allowRemoteModules`, `security.remoteModuleAllowlist`) is **not** part of this surface. Those