Skip to content

Commit 0473c89

Browse files
committed
feat(wpf): field-mediated cross-method use-after-dispose — a disposed field read in a subscribed handler → OWN002
An IDisposable field disposed in a class's Dispose()/DisposeAsync() and then DIRECTLY read (`_field.Member`) inside a live subscription-target handler (RHS of a `+=` or arg of a `.Subscribe(...)`, not torn down by a matching `-=`, with no `if (_disposed) return;` guard) is a use-after-dispose: an external event source can still invoke the handler after the object is torn down. The Roslyn extractor lowers it to a synthetic acquire/release/use flow (the trick the MemoryPool slices use), so the existing OwnIR bridge raises OWN002 — no new diagnostic, no second checker. Precise by construction to stay low-FP: the release must be in the dispose lifecycle; the handler must be a live (not unsubscribed) subscription target with no disposed-guard; and only a DIRECT field member access counts (an indirect use via a helper is deliberately not chased — that frontier stays an honest miss, the sibling handler-use-after-dispose case). New corpus case corpus/wpf/field-use-after-dispose (before → OWN002, guarded after → silent); benchmark recall floor 19 → 20. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Rg8kSk1YT14x7A1vo5zgED
1 parent d646d8d commit 0473c89

7 files changed

Lines changed: 291 additions & 3 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -796,7 +796,11 @@ jobs:
796796
# leak / double-dispose ride the flow (POOL001/003 — `memorypool-double-dispose` -> OWN003), and
797797
# its `owner.Memory` / `owner.Memory.Span` view is a borrow lowered to a use of the OWNER
798798
# (`ViewOwner`), so reading it after Dispose trips OWN002 (POOL002 — `memorypool-view-after-
799-
# dispose`). Remaining backlog: a FIELD-mediated cross-method use-after-dispose, a view stored in
800-
# a FIELD, and an injected-source region-escape. A drop below the floor is a regression.
801-
run: python scripts/benchmark.py --min-recall 19
799+
# dispose`). A FIELD-mediated cross-method use-after-dispose is caught too: an IDisposable field
800+
# disposed in `Dispose()` and DIRECTLY read (`_field.Member`) in a live subscription-target handler
801+
# (RHS of a `+=` / arg of a `.Subscribe(...)`, not torn down, no `if (_disposed) return;` guard) is
802+
# lowered to a synthetic acquire/release/use flow -> OWN002 (`field-use-after-dispose`). Remaining
803+
# backlog: a view stored in a FIELD, an INDIRECT (helper-mediated) field use after dispose, and an
804+
# injected-source region-escape. A drop below the floor is a regression.
805+
run: python scripts/benchmark.py --min-recall 20
802806

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// FIXED. The handler guards on the disposed flag, so a late dispatcher callback
2+
// bails before touching the connection. (Equivalently, drain the dispatcher queue
3+
// before disposing.) Nothing reads the connection after Dispose(), so the
4+
// extractor's field-mediated use-after-dispose detector — which excludes a handler
5+
// that opens with a `if (_disposed) return;` guard — stays silent.
6+
using System;
7+
using System.Data.SqlClient;
8+
9+
public sealed class ReportViewModel : IDisposable
10+
{
11+
private readonly SqlConnection _conn;
12+
private readonly IDisposable _sub;
13+
private bool _disposed;
14+
15+
public ReportViewModel(IEventBus bus)
16+
{
17+
_conn = new SqlConnection("Server=.;Database=Reports");
18+
_sub = bus.Subscribe(OnDataChanged);
19+
}
20+
21+
private void OnDataChanged(DataChanged e)
22+
{
23+
if (_disposed) return; // do not touch disposed state
24+
_conn.ChangeDatabase(e.Database);
25+
}
26+
27+
public void Dispose()
28+
{
29+
_disposed = true;
30+
_sub.Dispose();
31+
_conn.Dispose();
32+
}
33+
}
34+
35+
// Minimal in-file stand-ins so the reduction is self-contained.
36+
public interface IEventBus
37+
{
38+
IDisposable Subscribe(Action<DataChanged> handler);
39+
}
40+
41+
public sealed class DataChanged
42+
{
43+
public string Database { get; set; } = "";
44+
}
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// BUGGY (representative WPF/MVVM pattern; the C# extractor now catches this
2+
// directly under --flow-locals).
3+
//
4+
// A ViewModel OWNS a SqlConnection field and subscribes a handler to an injected
5+
// event bus. On teardown Dispose() disposes the connection (and the subscription
6+
// token), but a callback that was ALREADY queued on the dispatcher can still run
7+
// after Dispose() and DIRECTLY touch the disposed connection
8+
// (`_conn.ChangeDatabase(...)` on a connection already returned to the pool): an
9+
// ObjectDisposedException / use-after-dispose.
10+
//
11+
// Unlike handler-use-after-dispose — whose handler reaches the disposed state
12+
// INDIRECTLY through a `Refresh()` helper, which the extractor cannot follow — this
13+
// handler reads the disposed FIELD directly, so the extractor's field-mediated
14+
// cross-method detector lowers it to a synthetic acquire/release/use flow and the
15+
// core reports OWN002. The fix (after.cs) guards the handler on the disposed flag.
16+
using System;
17+
using System.Data.SqlClient;
18+
19+
public sealed class ReportViewModel : IDisposable
20+
{
21+
private readonly SqlConnection _conn;
22+
private readonly IDisposable _sub;
23+
24+
public ReportViewModel(IEventBus bus)
25+
{
26+
_conn = new SqlConnection("Server=.;Database=Reports");
27+
_sub = bus.Subscribe(OnDataChanged); // token captured + disposed below
28+
}
29+
30+
private void OnDataChanged(DataChanged e)
31+
{
32+
// a late, already-dispatched callback: may run AFTER Dispose()
33+
_conn.ChangeDatabase(e.Database); // <-- BUG: _conn may already be disposed
34+
}
35+
36+
public void Dispose()
37+
{
38+
_sub.Dispose(); // unsubscribe
39+
_conn.Dispose(); // dispose the owned connection
40+
}
41+
}
42+
43+
// Minimal in-file stand-ins so the reduction is self-contained.
44+
public interface IEventBus
45+
{
46+
IDisposable Subscribe(Action<DataChanged> handler);
47+
}
48+
49+
public sealed class DataChanged
50+
{
51+
public string Database { get; set; } = "";
52+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// OwnLang model of the field-mediated cross-method use-after-dispose the C#
2+
// extractor now lowers DIRECTLY (a disposed IDisposable field read in a subscribed
3+
// handler). `acquire` == the owned connection field's construction, `release` ==
4+
// its `Dispose()` in the ViewModel's Dispose(), `use` == a late dispatcher callback
5+
// (the subscribed handler) reading the connection AFTER it was disposed. Using a
6+
// disposable after its release is the generic OWN002, tagged with the resource kind.
7+
//
8+
// Contrast handler-use-after-dispose, whose handler reaches the disposed state
9+
// INDIRECTLY through a helper (`Refresh()`): the extractor only catches the DIRECT
10+
// `_field.Member` read, so that sibling case stays an honest extractor miss while
11+
// this one is caught end-to-end.
12+
module WpfFieldUseAfterDispose
13+
14+
// The owned IDisposable field (a SqlConnection): acquired when the ViewModel
15+
// constructs it, released by Dispose(). `kind` tags the verdict as a disposable.
16+
resource Connection {
17+
acquire Open
18+
release Dispose
19+
kind "disposable"
20+
}
21+
22+
fn OnDataChanged(bus: int) {
23+
let conn = acquire Connection(bus);
24+
release conn; // ViewModel.Dispose() disposes the owned connection
25+
use conn; // a late queued callback still touches it -> OWN002
26+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
OWN002
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# WPF field-mediated use-after-dispose (a disposed field touched in a handler)
2+
3+
**Pattern:** a ViewModel owns an `IDisposable` field (here a `SqlConnection`) and
4+
subscribes a handler to an event source. On teardown `Dispose()` disposes the field
5+
(and the subscription token), but a callback that was **already queued on the
6+
dispatcher** still runs after `Dispose()` and **directly reads the disposed field**
7+
(`_conn.ChangeDatabase(...)`). In real code this is an `ObjectDisposedException` or a
8+
read of torn state — the field-mediated cousin of the zombie-ViewModel leak. The
9+
defensive fix (the canonical one) is a disposed-flag guard at the top of the handler;
10+
relying on unsubscribe-ordering alone does not close the already-queued-callback race.
11+
12+
**What's new — the extractor catches this end-to-end.** The Roslyn extractor's
13+
field-mediated cross-method use-after-dispose pass (under `--flow-locals`) recognises
14+
an `IDisposable` field that is
15+
16+
1. disposed in this class's `Dispose()` / `DisposeAsync()` (the lifecycle release),
17+
2. directly read (`_field.Member`) inside a **live subscription target** — a method
18+
that is the RHS of a `+=` or the argument of a `.Subscribe(...)`, and whose
19+
subscription is **not** torn down by a matching `-=` (an unsubscribed callback
20+
cannot fire post-dispose, so it is exempt), and
21+
3. read in a handler with **no** `if (_disposed) return;` guard,
22+
23+
and lowers it to a synthetic `acquire`/`release`/`use` flow. That rides the existing
24+
OwnIR bridge — the same machinery the local-disposable and MemoryPool slices use — so
25+
the core raises **OWN002** ("use after release") with no new diagnostic and no second
26+
checker. `case.own` is the hand reduction of exactly that flow; on the real C# the
27+
`corpus-benchmark` job scores `before.cs` as caught (OWN002) and `after.cs` (the
28+
guarded fix) as silent.
29+
30+
**Precision (why it stays low-FP).** The check fires only on a field disposed in the
31+
dispose *lifecycle*, used in a *live* subscription target, with no guard, via a
32+
**direct** field member access. The guard exclusion is the canonical fix, so a fixed
33+
handler is silent; an unsubscribed (`-=`) or empty handler never fires; and an
34+
*indirect* use through a helper is deliberately **not** chased.
35+
36+
**Honesty / scope.** This catches the **direct** `_field.Member` read. Its sibling
37+
`handler-use-after-dispose` reaches the disposed state **indirectly** (`Refresh()`
38+
touches subscription-backed state) — the extractor does not follow that hop, so that
39+
case remains an honest extractor miss (a tracked recall gap, not a logic gap: its
40+
`case.own` reduction still fires OWN002). `case.own` here is a faithful hand reduction
41+
of the ownership logic; `before.cs` / `after.cs` are representative of the bug and its
42+
fix, not a verbatim copy of one PR.
43+
44+
Reference: [P-007](../../../docs/proposals/P-007-arraypool-span.md); the indirect twin
45+
is `handler-use-after-dispose`; the late-callback framing matches `zombie-viewmodel`.

‎frontend/roslyn/OwnSharp.Extractor/Program.cs‎

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -907,6 +907,17 @@ static void EmitOverspans(ExpressionSyntax expr, HashSet<string> tracked, Semant
907907
_ => null,
908908
};
909909

910+
// Does a handler body OPEN with a disposed-flag guard (`if (_disposed) return;`,
911+
// `if (IsDisposed) return;`)? Such a handler bails before touching state, so a field it then
912+
// references is NOT a use-after-dispose — exclude it (the canonical fix, keeps the field-UAF check
913+
// low-FP). Heuristic: a top-level `if` whose condition mentions a "dispos"-named identifier and whose
914+
// body returns.
915+
static bool HasDisposedGuard(BlockSyntax body) =>
916+
body.Statements.OfType<IfStatementSyntax>().Any(ifs =>
917+
ifs.Condition.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>()
918+
.Any(id => id.Identifier.Text.Contains("ispos"))
919+
&& ifs.DescendantNodes().OfType<ReturnStatementSyntax>().Any());
920+
910921
// Is `t` the System.Buffers.ArrayPool<T> type — the Return-based pool we model?
911922
// Checked on the resolved SYMBOL, not the receiver's text, so an aliased receiver
912923
// (`ArrayPool<int> p = ArrayPool<int>.Shared; p.Rent(n)`) binds correctly and an
@@ -1872,6 +1883,111 @@ or ImplicitObjectCreationExpressionSyntax
18721883
}
18731884
}
18741885

1886+
// P-007 / WPF: a field-mediated cross-method USE-AFTER-DISPOSE. An IDisposable
1887+
// field disposed in this class's Dispose()/DisposeAsync() is then DIRECTLY read
1888+
// (`_f.Member`) in an event-handler method — a callback an external event source
1889+
// can still invoke AFTER the object is disposed (the very reason WPF handler
1890+
// leaks matter). With no `if (_disposed) return;` guard the handler touches a
1891+
// field already disposed: a use-after-dispose. We lower it to a synthetic
1892+
// acquire/release/use flow so the existing OwnIR bridge raises OWN002 at the
1893+
// field — no new diagnostic, no second checker (the synthetic-flow trick the
1894+
// MemoryPool slices use). Precise by construction to stay low-FP: fires only when
1895+
// (a) the field is disposed in the dispose LIFECYCLE (not an ad-hoc `_f.Dispose()`),
1896+
// (b) the touching method is a LIVE subscription target — RHS of a `+=` / arg of
1897+
// a `.Subscribe(...)` — whose subscription is NOT torn down (`-= handler`
1898+
// means the callback cannot fire post-dispose, so it is safe),
1899+
// (c) the method has no disposed-guard (the canonical fix silences it), and
1900+
// (d) the use is a DIRECT field member access (an INDIRECT use via a helper is
1901+
// deliberately not chased — that is the harder frontier, left honest).
1902+
// Gated on --flow-locals like the rest of the synthetic-flow emission.
1903+
if (flowLocals)
1904+
{
1905+
// IDisposable fields -> declaration line (the synthetic `acquire`).
1906+
var dispoFieldLine = new Dictionary<string, int>(StringComparer.Ordinal);
1907+
foreach (var fd in cls.Members.OfType<FieldDeclarationSyntax>())
1908+
{
1909+
if (fd.Modifiers.Any(mm => mm.IsKind(SyntaxKind.StaticKeyword)))
1910+
continue;
1911+
if (!IsDisposableType(fd.Declaration.Type.ToString()))
1912+
continue;
1913+
foreach (var v in fd.Declaration.Variables)
1914+
dispoFieldLine[v.Identifier.Text] = LineOf(v);
1915+
}
1916+
// field -> line of its `.Dispose()` INSIDE Dispose()/DisposeAsync() (the
1917+
// release event). Restricted to the dispose methods so an ordinary
1918+
// `_f.Dispose()` helper is not misread as object teardown.
1919+
var releasedAt = new Dictionary<string, int>(StringComparer.Ordinal);
1920+
if (dispoFieldLine.Count > 0)
1921+
foreach (var dm in cls.Members.OfType<MethodDeclarationSyntax>())
1922+
{
1923+
if (dm.Identifier.Text is not ("Dispose" or "DisposeAsync"))
1924+
continue;
1925+
foreach (var inv in dm.DescendantNodes().OfType<InvocationExpressionSyntax>())
1926+
if (inv.Expression is MemberAccessExpressionSyntax dmm
1927+
&& dmm.Name.Identifier.Text is "Dispose" or "DisposeAsync"
1928+
&& FieldName(dmm.Expression) is { } df
1929+
&& dispoFieldLine.ContainsKey(df)
1930+
&& !releasedAt.ContainsKey(df))
1931+
releasedAt[df] = LineOf(inv);
1932+
}
1933+
if (releasedAt.Count > 0)
1934+
{
1935+
// handler method names that are LIVE subscription targets: RHS of a `+=`
1936+
// or arg of a `.Subscribe(...)`, minus any `-=`-removed handler.
1937+
var subscribed = new HashSet<string>(StringComparer.Ordinal);
1938+
var unsubscribed = new HashSet<string>(StringComparer.Ordinal);
1939+
foreach (var a in assigns)
1940+
if (IsHandler(a.Right) && FieldName(a.Right) is { } hn)
1941+
{
1942+
if (a.IsKind(SyntaxKind.AddAssignmentExpression)) subscribed.Add(hn);
1943+
else if (a.IsKind(SyntaxKind.SubtractAssignmentExpression)) unsubscribed.Add(hn);
1944+
}
1945+
foreach (var inv in cls.DescendantNodes().OfType<InvocationExpressionSyntax>())
1946+
if (inv.Expression is MemberAccessExpressionSyntax sm
1947+
&& sm.Name.Identifier.Text == "Subscribe")
1948+
foreach (var arg in inv.ArgumentList.Arguments)
1949+
if (FieldName(arg.Expression) is { } hn)
1950+
subscribed.Add(hn);
1951+
subscribed.ExceptWith(unsubscribed);
1952+
1953+
foreach (var hm in cls.Members.OfType<MethodDeclarationSyntax>())
1954+
{
1955+
if (hm.Body is not { } hbody)
1956+
continue;
1957+
var hname = hm.Identifier.Text;
1958+
if (hname is "Dispose" or "DisposeAsync")
1959+
continue;
1960+
if (!subscribed.Contains(hname))
1961+
continue;
1962+
if (HasDisposedGuard(hbody))
1963+
continue;
1964+
// emit ONE synthetic acquire/release/use flow per handler, on the
1965+
// first DIRECT read of a disposed field -> OWN002 via the bridge.
1966+
foreach (var ma in hbody.DescendantNodes().OfType<MemberAccessExpressionSyntax>())
1967+
{
1968+
if (ma.Name.Identifier.Text is "Dispose" or "DisposeAsync")
1969+
continue;
1970+
if (FieldName(ma.Expression) is { } uf
1971+
&& releasedAt.TryGetValue(uf, out var relLine))
1972+
{
1973+
flowFunctions.Add(new
1974+
{
1975+
name = $"{cls.Identifier.Text}.{hname}",
1976+
file,
1977+
body = new List<object>
1978+
{
1979+
new { op = "acquire", var = uf, line = dispoFieldLine[uf] },
1980+
new { op = "release", var = uf, line = relLine },
1981+
new { op = "use", var = uf, line = LineOf(ma) },
1982+
},
1983+
});
1984+
break;
1985+
}
1986+
}
1987+
}
1988+
}
1989+
}
1990+
18751991
// WPF004: a `X.Subscribe(...)` whose IDisposable result is ignored — the
18761992
// call stands as a bare statement (not assigned/returned/added), so the
18771993
// token is dropped and never disposed. Member-access only (`x.Subscribe`),

0 commit comments

Comments
 (0)