Repository navigation
Fix finalizer-thread use-after-free in ReferenceTracker queued delete (TableView live updates) - #12919
Draft
Hitesh Kumar (hiteshkrmsft) wants to merge 10 commits into
Draft
Fix finalizer-thread use-after-free in ReferenceTracker queued delete (TableView live updates)#12919Hitesh Kumar (hiteshkrmsft) wants to merge 10 commits into
Hitesh Kumar (hiteshkrmsft) wants to merge 10 commits into
Conversation
…d delete is queued When a ReferenceTracker object's last reference is released off its UI thread (e.g. by a CsWinRT finalizer), final_release queues the delete to the UI thread. Until it runs the object can still be reached through raw-this event subscriptions; an ItemsSourceView that is still subscribed to its source raises CollectionChanged with itself as the sender, and an app handler takes a new reference to it. The queued delete freed it anyway, so that reference dangled and its later Release (IObjectReference.Finalize) crashed. TableViewSource mints a new ItemsSourceView over the same rows on every rebuild, so every live-shaping tick orphans one; at 100k+ rows the GC finalizes their projections while the UI thread re-projects and the next tick revives them (main's CompareLiveTick_100k/_500k crashed 6/6). The queued delete now drops its safety reference and deletes only when nothing else holds the object; otherwise the last new holder's Release runs final_release again. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 196fea63-b933-4d49-9a41-cf4b51a8d390
…nceTracker objects at count 2 Review follow-ups to the previous commit: - ReferenceTracker's queued delete probes the count with an AddRef/Release pair and deletes at 2 (the destructor's reference plus the safety ref), as the owning-thread path does, so AddRef/Release pairs while members such as m_inner are destroyed cannot reach 0 and delete twice. A revived object drops both refs and is deleted by its new last Release; a count below 2 asserts and leaks instead of deleting. The arithmetic is pinned to C++/WinRT 2.0.230706.1 with a static_assert. A refused TryEnqueue is now traced (still leaked). - InspectingDataSource subscribes to its source through C++/WinRT weak references, so a view whose last reference is gone no longer raises changes (which handed it to app handlers again and ran its event source's tracker_refs to already-collected managed handlers). - TableViewSource keeps its flat ItemsSourceView across rebuilds over the same rows instead of leaving one view per live-shaping tick listening to the rows. Tests: the TableView live-tick test now checks the rows and the view a handler received (renamed); new InspectingDataSource tests release subscribed views on the finalizer thread while their source changes. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 196fea63-b933-4d49-9a41-cf4b51a8d390
…kept flat rows view Review round 2: - ReferenceTracker::final_release asserts the count is 2 after its safety AddRef (or that the instance is aggregated), instead of pinning the C++/WinRT version; DeleteQueuedInstance keeps its runtime checks and traces (TraceLogging, warning) both a refused TryEnqueue and the count < 2 leak. - A revived instance gets OnRevived() when its type has one. ItemsSourceView declares it and InspectingDataSource re-subscribes to its source with a new C++/WinRT weak reference: the handlers' old weak references stay dead after final_release, so a view revived through XAML's weak reference (IWeakReferenceSource is m_inner's) would otherwise stay subscribed but never raise again. WeakHandler captures this alongside the weak reference and documents why it exists and why it must not become a QI-based weak reference. - MUXControlsTestHooks gets RecordItemsSourceViewForRevival/ReviveRecordedItemsSourceView (MUX_INTERNAL) to take a reference to a view while its delete is queued. - TableViewSource keys the kept flat view on the rows' IUnknown identity. Behavior change: a flat rebuild over the same rows (live tick, header sort, filter) no longer swaps the repeater's ItemsSource; the rows' own Reset re-realizes it. The body is no longer scrolled back by a source swap, and focus stays on a row in view (the reshape brings the focused row's new position into view). Selection goes through the in-place Reset path (SelectedItem kept, no SelectionChanged for an unchanged selection). Unshaped keeps minting a view (a rare degraded fallback). Tests: a revived view survives, raises again and is deleted when released; flat view identity across live ticks; selection across a header sort and a live tick; focus on a row in view, without a scroll reset, across a sort and a tick; flat->grouped->flat; a filter removing the selected row; the TableView lifetime test keeps its view referenced and asserts the handler runs. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 196fea63-b933-4d49-9a41-cf4b51a8d390
When the GC collects an unloaded TableView, its last release runs on the finalizer thread and its delete is queued to the UI thread. Until then the table stays subscribed to the app's source: the rows view, selection and reshape-focus handlers were raw-this subscriptions, so a change raised in that window called into a table whose tracker_refs name collected objects. Subscribe those handlers through weak references, and skip them (and the TableViewSource projection/shaping, columns and selection model callbacks) once a self tracker_ref no longer resolves. Test: VerifySourceChangesSkipATableViewReleasedOffThread (items and sorted TableViewSource) fails on the parent under PageHeap with an SEHException thrown into the app's collection change. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 196fea63-b933-4d49-9a41-cf4b51a8d390
…live tick The reshape brings the focused row's new position into view, and in fre under the full suite that can still be in progress when the test checks (offset 1086, row top 1122). Keep the checks the test is about: focus stays on a row inside the table and the body is not scrolled back to the top. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 196fea63-b933-4d49-9a41-cf4b51a8d390
…val hooks - Drop the tracker_ref the TableView held to itself (a real COM AddRef for a non-composed table, so every templated TableView leaked). Handlers now skip a table the GC found unreachable, probed through a tracker_ref to a private DependencyObject only the table references (template parts can be reachable through other roots); once the table is released its get_weak() handlers no longer resolve. - InspectingDataSource::OnRevived resolves its source with safe_get, stays detached if the GC collected it, and otherwise resets its cached size and raises Reset for the changes it missed while dying. - The ItemsSourceView revival test hooks exist only in Debug builds, and a recorded view is forgotten when it is deleted. - final_release asserts count >= 2; a null rows view throws as before rather than asserting; trace logging stays out of RuntimeClassHelpers.h. - Tests: collected TableView is deleted (no source subscribers left), a table kept across removal and a GC still follows its source, revived view resets to the current count, focus test checks the same item's row is in view. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: e509b00d-a95b-4106-ada1-1c1ecf0016f3
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: e509b00d-a95b-4106-ada1-1c1ecf0016f3
The dev spec keeps body focus at the same projected row index across a sort, filter or live re-shape, whichever record now occupies it; assert that rather than the item's identity. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: e509b00d-a95b-4106-ada1-1c1ecf0016f3
…es the rows The flat view is now kept across rebuilds, so a live tick's Reset reaches the repeater on the same view the reshape detector listens to; when the repeater handles it first, it recycles the focused row and moves focus along before the detector captures it, and the restore then aims at the wrong row (seen in chk: focus moved from row 31 to 13). The engine now raises ProjectionRebuilding before a rebuild or in-place re-shape, and the table captures focus there. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: e509b00d-a95b-4106-ada1-1c1ecf0016f3
|
Azure Pipelines: There may be pipelines that require an authorized user to comment /azp run to run. |
…d rewrites the rows" This reverts commit f392168. It made the live-tick focus test pass in isolation in chk but not in the full chk or fre TableView suites (focus still moves from row 31 to 13), and VerifyDroppedGroupToggleKeepsRowBringIntoView failed with it in the full fre suite (it had not failed in any earlier run). The live-tick focus issue stays open. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: e509b00d-a95b-4106-ada1-1c1ecf0016f3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What this fixes
TableView live updates (live shaping ticks over large sources) could crash on main with a use-after-free. When a
ReferenceTrackerobject's last reference is released off the UI thread — typically by the .NET finalizer releasing an RCW —final_releasequeues the delete to the UI thread. Until that delete runs the object can still be handed out again: anItemsSourceViewstill subscribed to its source raisesCollectionChangedwith itself as the sender and an app handler takes a new reference, or XAML resolves a weak reference to it throughm_inner'sIWeakReferenceSource. The queued delete freed the object anyway, so that new reference dangled and its laterReleasecrashed.TableViewSourcemade this frequent: it minted a newItemsSourceViewover the same rows on every flat rebuild, so every live tick orphaned one (main'sCompareLiveTick_100k/_500kbenchmarks crashed 6/6).Changes
ReferenceTrackerqueued delete (controls/dev/inc/RuntimeClassHelpers.h):DeleteQueuedInstancereads the reference count. At 2 (the reference~root_implementsdrops plus the safety reference) it deletes as before. Above 2 the object was revived: it callsOnRevived()if the type has one, drops its two references, and the new holder's lastReleaserunsfinal_releaseagain. Below 2 it leaks and traces (ReferenceTrackerQueuedDeleteLeaked) rather than risk a double delete. A refusedTryEnqueueis traced too. Composed (aggregated) instances are deleted as before.InspectingDataSource: subscribes to its source through a C++/WinRT weak reference, so a view with no references left no longer raises changes (and is no longer handed out while dying).OnRevivedre-subscribes, resolving the source withsafe_get(it stays detached if the GC collected it), resets its cached count and raisesResetfor the changes it missed.TableViewSource: keeps the flat projection'sItemsSourceViewacross rebuilds over the same rows instead of leaving one listening view per tick. Behavior change: a flat rebuild (live tick, header sort, filter) no longer swaps the repeater'sItemsSource; the rows' ownResetre-realizes it, so the body keeps its scroll position.TableView: its source, selection and column handlers are subscribed through weak references and skip a table the GC already found unreachable (its tracker_refs may name collected objects). Reachability is probed through atracker_refto a privateDependencyObjectonly the table references; a tracker_ref to the table itself would be a real AddRef and leak it.MUXControlsTestHooks.RecordItemsSourceViewForRevival/ReviveRecordedItemsSourceViewtake a reference to a view while its delete is queued.Tests
InspectingDataSourceTests: views released on the finalizer thread don't raise while their delete is queued and are deleted; a revived view survives, resets to the source's current count, raises changes again and is deleted when released again (Debug).TableViewLifetimeTests: source changes skip a TableView released off-thread (fails on main under PageHeap); a collected TableView is deleted (no source subscribers left); a TableView kept by the app across removal and a GC still follows its source.TableViewLiveShapingTests: flat view identity across live ticks; selection and focus (same row index, in view, no scroll reset) across a header sort and a live tick; flat → grouped → flat.Known limits (unchanged from main): app-subclassed (composed) instances are still deleted unconditionally by the queued delete; a TableView revived while its delete is queued does not re-subscribe until its
ItemsSourceorColumnschange.Open:
VerifyFlatSortAndLiveTickKeepFocusInViewWithoutScrollResetchecks the keyboard spec (a re-shape keeps body focus at the same row index). After the live tick it fails in full TableView suite runs (focus moves from row 31 to 13, in chk and fre) while passing in isolation in fre. With the flat view now kept, the repeater can handle the rows'Resetbefore the table's reshape-focus detector captures focus. Still being investigated.