Skip to content

Commit 5a3ba52

Browse files
committed
fix(extractor): key the field-alias map by local SYMBOL, count ref/out rebinds (Codex P2 + CodeRabbit)
The first cut keyed the alias map by identifier STRING, scanned class-wide, and gated reassignment only on `=` expressions. Three holes, all flagged in review: - CodeRabbit (major) + Codex #2 — class-wide name keys conflate same-named locals across methods: an unrelated `c.Dispose()` in one method could credit a field aliased by a `c` in another (FN), and two aliases reusing a name overwrite each other. Now keyed by the LOCAL SYMBOL (model.GetDeclaredSymbol(decl)), and the dispose scan resolves the receiver symbol — so each alias is scope-exact. - Codex #1 — an alias rebound through a `ref`/`out` argument (`Swap(ref a)`) was not counted as reassigned, so a disposed-after-rebind alias wrongly credited the field (FN). The reassignment set now includes ref/out argument locals. - Iterating declarators by symbol (is ILocalSymbol) also drops non-local declarators from the map (locals-only, as intended). Direct field disposals are unchanged: a receiver that is not an alias local falls back to FieldName, exactly as before. Regression controls added: RefReboundAliasLeaks (`Swap(ref a)` then dispose -> _refRebound still leaks) and ScopedAliasNameLeak (an unrelated same-named `c` disposed in another method must not credit _scopedLeak -> it still leaks). CI asserts both, alongside the existing aliased-silent and never-disposed/`=`-rebound controls. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Rg8kSk1YT14x7A1vo5zgED
1 parent c678ab6 commit 5a3ba52

3 files changed

Lines changed: 74 additions & 17 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,13 @@ jobs:
253253
|| { echo "FAIL: a field aliased but never disposed must still warn"; exit 1; }
254254
echo "$out" | grep -qE "AliasDisposeSample\.cs:[0-9]+:.*\[OWN001\].*'_rebound'" \
255255
|| { echo "FAIL: a field whose alias was rebound to a new object must still warn"; exit 1; }
256+
# Codex control: an alias rebound through a ref/out ARGUMENT must still leak.
257+
echo "$out" | grep -qE "AliasDisposeSample\.cs:[0-9]+:.*\[OWN001\].*'_refRebound'" \
258+
|| { echo "FAIL: a field whose alias was rebound via a ref/out argument must still warn"; exit 1; }
259+
# Codex/CodeRabbit control: aliases are symbol-scoped, not name-keyed — an unrelated
260+
# same-named local disposed in another method must NOT credit the field, so it still leaks.
261+
echo "$out" | grep -qE "AliasDisposeSample\.cs:[0-9]+:.*\[OWN001\].*'_scopedLeak'" \
262+
|| { echo "FAIL: a same-named local in another scope must not be miscredited (symbol-scoped aliases)"; exit 1; }
256263
# WPF004: an ignored `X.Subscribe(...)` result leaks; the captured+
257264
# disposed one stays silent. "ignored" is unique to the WPF004 message.
258265
echo "$out" | grep -q "MessengerViewModel.cs" \

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

Lines changed: 29 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2201,39 +2201,51 @@ or ImplicitObjectCreationExpressionSyntax
22012201
var disposed = new HashSet<string>();
22022202
// A local that ALIASES a field of this class — `var cts = _cts;` / `var cts = this._cts;` —
22032203
// and is then disposed THROUGH the alias (`cts.Dispose()`) releases the field's object: the
2204-
// alias and the field name the same instance. Map each such alias local -> its field so the
2205-
// disposal scan below credits the FIELD. Mined: Npgsql's NpgsqlDataSource disposes its
2206-
// CancellationTokenSource via `var cts = _cts; cts.Dispose();`. Three gates keep it sound:
2207-
// the initializer is a `this`/bare field reference (never `other._f`); it BINDS to a real
2208-
// field symbol (not a same-named local); and the alias is never REASSIGNED anywhere (a
2209-
// rebound local no longer tracks the field, so we conservatively decline to credit it).
2210-
var reassignedLocals = new HashSet<string>(StringComparer.Ordinal);
2211-
foreach (var a in assigns)
2212-
if (a.Left is IdentifierNameSyntax lid)
2213-
reassignedLocals.Add(lid.Identifier.Text);
2214-
var aliasToField = new Dictionary<string, string>(StringComparer.Ordinal);
2204+
// alias and the field name the same instance. Map each such alias LOCAL SYMBOL -> its field
2205+
// so the disposal scan below credits the FIELD. Mined: Npgsql's NpgsqlDataSource disposes its
2206+
// CancellationTokenSource via `var cts = _cts; cts.Dispose();`. Sound by construction:
2207+
// - the initializer is a `this`/bare field reference (never `other._f`) that BINDS to a real
2208+
// field symbol (not a same-named local);
2209+
// - aliases are keyed by the LOCAL SYMBOL, not its name, so a same-named local in another
2210+
// method (or a second alias reusing the name) is a DISTINCT entry, never conflated (Codex);
2211+
// - an alias REASSIGNED anywhere — by `=`, or rebound through a `ref`/`out` argument — is
2212+
// excluded: a rebound local no longer tracks the field, so we decline to credit it (Codex).
2213+
var reassignedAliases = new HashSet<ISymbol>(SymbolEqualityComparer.Default);
2214+
foreach (var asg in assigns)
2215+
if (model.GetSymbolInfo(asg.Left).Symbol is ILocalSymbol rls)
2216+
reassignedAliases.Add(rls);
2217+
foreach (var arg in cls.DescendantNodes().OfType<ArgumentSyntax>())
2218+
if ((arg.RefKindKeyword.IsKind(SyntaxKind.RefKeyword) || arg.RefKindKeyword.IsKind(SyntaxKind.OutKeyword))
2219+
&& model.GetSymbolInfo(arg.Expression).Symbol is ILocalSymbol als)
2220+
reassignedAliases.Add(als);
2221+
var aliasToField = new Dictionary<ISymbol, string>(SymbolEqualityComparer.Default);
22152222
foreach (var decl in cls.DescendantNodes().OfType<VariableDeclaratorSyntax>())
22162223
if (decl.Initializer?.Value is { } init
22172224
&& ThisFieldName(init) is { } af
2218-
&& !reassignedLocals.Contains(decl.Identifier.Text)
2219-
&& model.GetSymbolInfo(init).Symbol is IFieldSymbol)
2220-
aliasToField[decl.Identifier.Text] = af;
2225+
&& model.GetSymbolInfo(init).Symbol is IFieldSymbol
2226+
&& model.GetDeclaredSymbol(decl) is ILocalSymbol aliasSym
2227+
&& !reassignedAliases.Contains(aliasSym))
2228+
aliasToField[aliasSym] = af;
2229+
// a `.Dispose()`/`.DisposeAsync()` on a field — directly (`_f.Dispose()`) or through an
2230+
// alias local (translated by SYMBOL via aliasToField) — releases that field.
22212231
foreach (var inv in cls.DescendantNodes().OfType<InvocationExpressionSyntax>())
22222232
if (inv.Expression is MemberAccessExpressionSyntax m
22232233
&& m.Name.Identifier.Text is "Dispose" or "DisposeAsync"
22242234
&& FieldName(m.Expression) is { } df)
2225-
disposed.Add(aliasToField.TryGetValue(df, out var ra) ? ra : df);
2235+
disposed.Add(model.GetSymbolInfo(m.Expression).Symbol is ILocalSymbol ls
2236+
&& aliasToField.TryGetValue(ls, out var fa) ? fa : df);
22262237
// Also the NULL-CONDITIONAL form `field?.Dispose()` (a ConditionalAccess whose
22272238
// WhenNotNull is the `.Dispose()` invocation, NOT a plain MemberAccess) — the
22282239
// dominant disposal shape the match above misses. Mined as an FP across ImageSharp:
22292240
// `this.memoryStream?.Dispose()` (ZipExrCompressor/DeflateCompressor/IccDataWriter)
22302241
// and the BufferedStreams benchmark's `[GlobalCleanup]` `field?.Dispose()` calls.
2231-
// (The same alias translation applies — `cts?.Dispose()` on a field-aliasing local.)
2242+
// (The same alias-by-symbol translation applies — `cts?.Dispose()` on an aliasing local.)
22322243
foreach (var cae in cls.DescendantNodes().OfType<ConditionalAccessExpressionSyntax>())
22332244
if (FieldName(cae.Expression) is { } cdf
22342245
&& cae.WhenNotNull is InvocationExpressionSyntax { Expression: MemberBindingExpressionSyntax mb }
22352246
&& mb.Name.Identifier.Text is "Dispose" or "DisposeAsync")
2236-
disposed.Add(aliasToField.TryGetValue(cdf, out var rc) ? rc : cdf);
2247+
disposed.Add(model.GetSymbolInfo(cae.Expression).Symbol is ILocalSymbol lc
2248+
&& aliasToField.TryGetValue(lc, out var fc) ? fc : cdf);
22372249

22382250
foreach (var fd in cls.Members.OfType<FieldDeclarationSyntax>())
22392251
{

‎frontend/roslyn/samples/AliasDisposeSample.cs‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,3 +48,41 @@ public void Dispose()
4848
a.Dispose(); // disposes the new one, not _rebound -> WARN OWN001
4949
}
5050
}
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)