Skip to content

Fix finalizer-thread use-after-free in ReferenceTracker queued delete (TableView live updates) - #12919

Draft
Hitesh Kumar (hiteshkrmsft) wants to merge 10 commits into
mainfrom
user/hik/tableview/fix-live-shaping-finalizer-crash
Draft

Hitesh Kumar (hiteshkrmsft) wants to merge 10 commits into
mainfrom
user/hik/tableview/fix-live-shaping-finalizer-crash

Conversation

@hiteshkrmsft

@hiteshkrmsft Hitesh Kumar (hiteshkrmsft) commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

What this fixes

TableView live updates (live shaping ticks over large sources) could crash on main with a use-after-free. When a ReferenceTracker object's last reference is released off the UI thread — typically by the .NET finalizer releasing an RCW — final_release queues the delete to the UI thread. Until that delete runs the object can still be handed out again: an ItemsSourceView still subscribed to its source raises CollectionChanged with itself as the sender and an app handler takes a new reference, or XAML resolves a weak reference to it through m_inner's IWeakReferenceSource. The queued delete freed the object anyway, so that new reference dangled and its later Release crashed. TableViewSource made this frequent: it minted a new ItemsSourceView over the same rows on every flat rebuild, so every live tick orphaned one (main's CompareLiveTick_100k/_500k benchmarks crashed 6/6).

Changes

  • ReferenceTracker queued delete (controls/dev/inc/RuntimeClassHelpers.h): DeleteQueuedInstance reads the reference count. At 2 (the reference ~root_implements drops plus the safety reference) it deletes as before. Above 2 the object was revived: it calls OnRevived() if the type has one, drops its two references, and the new holder's last Release runs final_release again. Below 2 it leaks and traces (ReferenceTrackerQueuedDeleteLeaked) rather than risk a double delete. A refused TryEnqueue is 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). OnRevived re-subscribes, resolving the source with safe_get (it stays detached if the GC collected it), resets its cached count and raises Reset for the changes it missed.
  • TableViewSource: keeps the flat projection's ItemsSourceView across 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's ItemsSource; the rows' own Reset re-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 a tracker_ref to a private DependencyObject only the table references; a tracker_ref to the table itself would be a real AddRef and leak it.
  • Test hooks (Debug builds only): MUXControlsTestHooks.RecordItemsSourceViewForRevival / ReviveRecordedItemsSourceView take 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.
  • Ran on a VM: TableView, ItemsRepeater, ItemsView, NavigationView, TreeView, TeachingTip, TabView and Breadcrumb API tests in chk and fre, compared with the parent commit; the new lifetime tests also under PageHeap.

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 ItemsSource or Columns change.

Open: VerifyFlatSortAndLiveTickKeepFocusInViewWithoutScrollReset checks 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' Reset before the table's reshape-focus detector captures focus. Still being investigated.

…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

Copy link
Copy Markdown
Azure Pipelines:
There may be pipelines that require an authorized user to comment /azp run to run.

@microsoft-github-policy-service microsoft-github-policy-service Bot added the needs-triage Issue needs to be triaged by the area owners label Dec 1, 2026
…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-triage Issue needs to be triaged by the area owners

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant