Skip to content

Commit f9605da

Browse files
authored
Merge pull request #90 from PhysShell/claude/fp-alias-dispose
fix(extractor): recognize a field disposed through a local alias (mined Npgsql NpgsqlDataSource)
2 parents 43a4709 + 5a3ba52 commit f9605da

3 files changed

Lines changed: 142 additions & 2 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,7 @@ jobs:
144144
frontend/roslyn/samples/StaticClassEscapeSample.cs \
145145
frontend/roslyn/samples/EventSourceCountersSample.cs \
146146
frontend/roslyn/samples/AppDomainShutdownSample.cs \
147+
frontend/roslyn/samples/AliasDisposeSample.cs \
147148
-o "$RUNNER_TEMP/facts.json"
148149
cat "$RUNNER_TEMP/facts.json"
149150
- name: Check facts through the core
@@ -241,6 +242,25 @@ jobs:
241242
fi
242243
echo "$out" | grep -q "pooled buffer 'leakedBuf'" \
243244
|| { echo "FAIL: a pooled field rented but never returned must still warn"; exit 1; }
245+
# field disposed through a local ALIAS (mined: Npgsql NpgsqlDataSource): `var cts = _cts;
246+
# cts.Dispose();` (and the `this._f` / `cts?.Dispose()` shapes) releases the field -> the
247+
# aliased fields must be SILENT.
248+
if echo "$out" | grep -qE "'_aliased'|'_aliasedQ'"; then
249+
echo "FAIL: a field disposed through a local alias was wrongly reported as undisposed"; exit 1
250+
fi
251+
# controls: an alias that is never disposed, and an alias REBOUND to a new object, must
252+
# both STILL leak (the recognition needs an actual dispose on an un-reassigned alias).
253+
echo "$out" | grep -qE "AliasDisposeSample\.cs:[0-9]+:.*\[OWN001\].*'_neverDisposed'" \
254+
|| { echo "FAIL: a field aliased but never disposed must still warn"; exit 1; }
255+
echo "$out" | grep -qE "AliasDisposeSample\.cs:[0-9]+:.*\[OWN001\].*'_rebound'" \
256+
|| { echo "FAIL: a field whose alias was rebound to a new object must still warn"; exit 1; }
257+
# Codex control: an alias rebound through a ref/out ARGUMENT must still leak.
258+
echo "$out" | grep -qE "AliasDisposeSample\.cs:[0-9]+:.*\[OWN001\].*'_refRebound'" \
259+
|| { echo "FAIL: a field whose alias was rebound via a ref/out argument must still warn"; exit 1; }
260+
# Codex/CodeRabbit control: aliases are symbol-scoped, not name-keyed — an unrelated
261+
# same-named local disposed in another method must NOT credit the field, so it still leaks.
262+
echo "$out" | grep -qE "AliasDisposeSample\.cs:[0-9]+:.*\[OWN001\].*'_scopedLeak'" \
263+
|| { echo "FAIL: a same-named local in another scope must not be miscredited (symbol-scoped aliases)"; exit 1; }
244264
# WPF004: an ignored `X.Subscribe(...)` result leaks; the captured+
245265
# disposed one stays silent. "ignored" is unique to the WPF004 message.
246266
echo "$out" | grep -q "MessengerViewModel.cs" \

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

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2233,21 +2233,53 @@ or ImplicitObjectCreationExpressionSyntax
22332233
// disposes. Owned (not injected) = in `constructed` (computed above);
22342234
// released = a `<field>.Dispose()` call somewhere in the class.
22352235
var disposed = new HashSet<string>();
2236+
// A local that ALIASES a field of this class — `var cts = _cts;` / `var cts = this._cts;` —
2237+
// and is then disposed THROUGH the alias (`cts.Dispose()`) releases the field's object: the
2238+
// alias and the field name the same instance. Map each such alias LOCAL SYMBOL -> its field
2239+
// so the disposal scan below credits the FIELD. Mined: Npgsql's NpgsqlDataSource disposes its
2240+
// CancellationTokenSource via `var cts = _cts; cts.Dispose();`. Sound by construction:
2241+
// - the initializer is a `this`/bare field reference (never `other._f`) that BINDS to a real
2242+
// field symbol (not a same-named local);
2243+
// - aliases are keyed by the LOCAL SYMBOL, not its name, so a same-named local in another
2244+
// method (or a second alias reusing the name) is a DISTINCT entry, never conflated (Codex);
2245+
// - an alias REASSIGNED anywhere — by `=`, or rebound through a `ref`/`out` argument — is
2246+
// excluded: a rebound local no longer tracks the field, so we decline to credit it (Codex).
2247+
var reassignedAliases = new HashSet<ISymbol>(SymbolEqualityComparer.Default);
2248+
foreach (var asg in assigns)
2249+
if (model.GetSymbolInfo(asg.Left).Symbol is ILocalSymbol rls)
2250+
reassignedAliases.Add(rls);
2251+
foreach (var arg in cls.DescendantNodes().OfType<ArgumentSyntax>())
2252+
if ((arg.RefKindKeyword.IsKind(SyntaxKind.RefKeyword) || arg.RefKindKeyword.IsKind(SyntaxKind.OutKeyword))
2253+
&& model.GetSymbolInfo(arg.Expression).Symbol is ILocalSymbol als)
2254+
reassignedAliases.Add(als);
2255+
var aliasToField = new Dictionary<ISymbol, string>(SymbolEqualityComparer.Default);
2256+
foreach (var decl in cls.DescendantNodes().OfType<VariableDeclaratorSyntax>())
2257+
if (decl.Initializer?.Value is { } init
2258+
&& ThisFieldName(init) is { } af
2259+
&& model.GetSymbolInfo(init).Symbol is IFieldSymbol
2260+
&& model.GetDeclaredSymbol(decl) is ILocalSymbol aliasSym
2261+
&& !reassignedAliases.Contains(aliasSym))
2262+
aliasToField[aliasSym] = af;
2263+
// a `.Dispose()`/`.DisposeAsync()` on a field — directly (`_f.Dispose()`) or through an
2264+
// alias local (translated by SYMBOL via aliasToField) — releases that field.
22362265
foreach (var inv in cls.DescendantNodes().OfType<InvocationExpressionSyntax>())
22372266
if (inv.Expression is MemberAccessExpressionSyntax m
22382267
&& m.Name.Identifier.Text is "Dispose" or "DisposeAsync"
22392268
&& FieldName(m.Expression) is { } df)
2240-
disposed.Add(df);
2269+
disposed.Add(model.GetSymbolInfo(m.Expression).Symbol is ILocalSymbol ls
2270+
&& aliasToField.TryGetValue(ls, out var fa) ? fa : df);
22412271
// Also the NULL-CONDITIONAL form `field?.Dispose()` (a ConditionalAccess whose
22422272
// WhenNotNull is the `.Dispose()` invocation, NOT a plain MemberAccess) — the
22432273
// dominant disposal shape the match above misses. Mined as an FP across ImageSharp:
22442274
// `this.memoryStream?.Dispose()` (ZipExrCompressor/DeflateCompressor/IccDataWriter)
22452275
// and the BufferedStreams benchmark's `[GlobalCleanup]` `field?.Dispose()` calls.
2276+
// (The same alias-by-symbol translation applies — `cts?.Dispose()` on an aliasing local.)
22462277
foreach (var cae in cls.DescendantNodes().OfType<ConditionalAccessExpressionSyntax>())
22472278
if (FieldName(cae.Expression) is { } cdf
22482279
&& cae.WhenNotNull is InvocationExpressionSyntax { Expression: MemberBindingExpressionSyntax mb }
22492280
&& mb.Name.Identifier.Text is "Dispose" or "DisposeAsync")
2250-
disposed.Add(cdf);
2281+
disposed.Add(model.GetSymbolInfo(cae.Expression).Symbol is ILocalSymbol lc
2282+
&& aliasToField.TryGetValue(lc, out var fc) ? fc : cdf);
22512283

22522284
// P-004 EventSource counter exemption: inside an EventSource, a DiagnosticCounter field
22532285
// constructed with `this` is registered to (and lifetime-owned by) the source — a
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
using System;
2+
using System.Threading;
3+
4+
namespace Own.Samples;
5+
6+
// WPF003/OWN001 field disposed through a local ALIAS (mined: Npgsql NpgsqlDataSource). A field copied to a
7+
// local (`var cts = _cts;`) and disposed through that alias (`cts.Dispose();`) IS released: the
8+
// alias and the field reference the same object. The field-disposable detector must credit the
9+
// FIELD so it is not reported as an undisposed leak. Contrast the controls below.
10+
public sealed class AliasDisposes : IDisposable
11+
{
12+
private readonly CancellationTokenSource _aliased = new CancellationTokenSource();
13+
private readonly CancellationTokenSource _aliasedQ = new CancellationTokenSource();
14+
15+
public void Dispose()
16+
{
17+
var a = _aliased; // bare-field alias
18+
a.Dispose(); // disposed through the alias -> _aliased released -> SILENT
19+
20+
var q = this._aliasedQ; // this-qualified alias
21+
q?.Dispose(); // null-conditional dispose through the alias -> _aliasedQ released -> SILENT
22+
}
23+
}
24+
25+
// Control: a field aliased to a local that is NEVER disposed must STILL leak — the alias
26+
// recognition requires an actual `.Dispose()` on the alias, not merely a copy.
27+
public sealed class AliasNeverDisposes : IDisposable
28+
{
29+
private readonly CancellationTokenSource _neverDisposed = new CancellationTokenSource();
30+
31+
public void Dispose()
32+
{
33+
var a = _neverDisposed; // aliased but never disposed -> _neverDisposed leaks -> WARN OWN001
34+
_ = a.Token;
35+
}
36+
}
37+
38+
// Control: a REASSIGNED alias no longer tracks the field — disposing it releases the NEW object,
39+
// not the field, so the field must STILL leak (the reassignment gate declines to credit it).
40+
public sealed class ReboundAliasLeaks : IDisposable
41+
{
42+
private readonly CancellationTokenSource _rebound = new CancellationTokenSource();
43+
44+
public void Dispose()
45+
{
46+
var a = _rebound; // starts as the field...
47+
a = new CancellationTokenSource(); // ...but is rebound to a NEW source
48+
a.Dispose(); // disposes the new one, not _rebound -> WARN OWN001
49+
}
50+
}
51+
52+
// Codex control: an alias rebound through a `ref`/`out` ARGUMENT (not just `=`) no longer tracks
53+
// the field — so the field must STILL leak. The reassignment gate counts ref/out args, not only
54+
// assignment expressions.
55+
public sealed class RefReboundAliasLeaks : IDisposable
56+
{
57+
private readonly CancellationTokenSource _refRebound = new CancellationTokenSource();
58+
59+
public void Dispose()
60+
{
61+
var a = _refRebound; // starts as the field...
62+
Swap(ref a); // ...but a helper rebinds it via `ref`
63+
a.Dispose(); // disposes whatever Swap installed, not _refRebound -> WARN OWN001
64+
}
65+
66+
private static void Swap(ref CancellationTokenSource c) => c = new CancellationTokenSource();
67+
}
68+
69+
// Codex/CodeRabbit control: aliases are scoped by the LOCAL SYMBOL, not its name. Here `Touch`
70+
// aliases the field but never disposes it, while an UNRELATED local also named `c` in `Other` is
71+
// disposed. A class-wide name key would miscredit `Other`'s `c.Dispose()` to the field and hide
72+
// the leak; symbol scoping keeps them distinct, so the field STILL leaks (WARN OWN001).
73+
public sealed class ScopedAliasNameLeak : IDisposable
74+
{
75+
private readonly CancellationTokenSource _scopedLeak = new CancellationTokenSource();
76+
77+
public void Touch()
78+
{
79+
var c = _scopedLeak; // aliases the field but does NOT dispose it
80+
_ = c.Token;
81+
}
82+
83+
public void Other()
84+
{
85+
var c = new CancellationTokenSource(); // a DIFFERENT local named `c`...
86+
c.Dispose(); // ...disposing it must NOT credit _scopedLeak
87+
}
88+
}

0 commit comments

Comments
 (0)