Skip to content

Commit 3648802

Browse files
committed
fix(extractor): recognize .Close() as a field release (receiver-scoped); drop the SemaphoreSlim exemption
Scopes this PR to the uncontentious fix and addresses the review. #1 `.Close()` releases a field — the field-disposable `disposed` scan credited a field only on Dispose()/DisposeAsync(), but the LOCAL detector (DisposesLocal and the flow detector) has always accepted Dispose/Close/DisposeAsync. That asymmetry flagged a field cleaned up by Close() as a leak. Mirror the local set on both the direct and null-conditional field-release checks. Mined: Npgsql ReplicationConnection releases its NpgsqlConnection field via `await _npgsqlConnection.Close(async: true)`. Receiver-scoped (Codex/CodeRabbit): credit only THIS instance's field or a validated alias via ThisFieldName, so `other._conn.Close()` on ANOTHER instance of the SAME class cannot mark this object's `_conn` released. (A field-symbol ContainingType check would NOT catch this — same class, same ContainingType — so the receiver is keyed syntactically; this also tightens the pre-existing Dispose path.) Dropped: the SemaphoreSlim dispose-optional change. Putting SemaphoreSlim in the shared IsDisposeOptional also affected the flow-locals detector and tripped the deliberate `semLeak` control (a prior ShareX fix explicitly decided SemaphoreSlim stays tracked for method-bounded locals, since reading AvailableWaitHandle allocates a handle Dispose must release — Codex flagged the same). A sound, field-scoped + AvailableWaitHandle-gated version is a separate decision, deferred. Regression sample CloseReleaseSample.cs: ReleasesViaClose._closedConn / _closedConnQ (direct + null-conditional Close) silent; controls still warn — LeaksUnclosed._leakedConn (never closed) and ClosesOtherInstanceField._xconn (closed only on ANOTHER instance). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Rg8kSk1YT14x7A1vo5zgED
1 parent d2f9599 commit 3648802

4 files changed

Lines changed: 74 additions & 90 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ jobs:
145145
frontend/roslyn/samples/EventSourceCountersSample.cs \
146146
frontend/roslyn/samples/AppDomainShutdownSample.cs \
147147
frontend/roslyn/samples/AliasDisposeSample.cs \
148-
frontend/roslyn/samples/SemaphoreAndCloseSample.cs \
148+
frontend/roslyn/samples/CloseReleaseSample.cs \
149149
-o "$RUNNER_TEMP/facts.json"
150150
cat "$RUNNER_TEMP/facts.json"
151151
- name: Check facts through the core
@@ -262,23 +262,19 @@ jobs:
262262
# same-named local disposed in another method must NOT credit the field, so it still leaks.
263263
echo "$out" | grep -qE "AliasDisposeSample\.cs:[0-9]+:.*\[OWN001\].*'_scopedLeak'" \
264264
|| { echo "FAIL: a same-named local in another scope must not be miscredited (symbol-scoped aliases)"; exit 1; }
265-
# #2 SemaphoreSlim is dispose-optional (Dispose only frees a lazy wait handle) -> an undisposed
266-
# SemaphoreSlim field must be SILENT (mined: Npgsql NpgsqlDataSource._setupMappingsSemaphore).
267-
if echo "$out" | grep -q "'_gate'"; then
268-
echo "FAIL: an undisposed SemaphoreSlim field was wrongly reported (it is dispose-optional)"; exit 1
269-
fi
270-
# #2 control: the exemption is SemaphoreSlim-specific — a real owned IDisposable (CTS) never
271-
# disposed must STILL warn, proving it is not a blanket "any field" suppression.
272-
echo "$out" | grep -qE "SemaphoreAndCloseSample\.cs:[0-9]+:.*\[OWN001\].*'_ctsControl'" \
273-
|| { echo "FAIL: a non-optional owned IDisposable field must still warn (dispose-optional stays SemaphoreSlim-scoped)"; exit 1; }
274-
# #1 a field released via `.Close()` (direct and null-conditional) must be SILENT — mirrors the
265+
# a field released via `.Close()` (direct and null-conditional) must be SILENT — mirrors the
275266
# local detector's Dispose/Close/DisposeAsync set (mined: Npgsql ReplicationConnection._npgsqlConnection).
276267
if echo "$out" | grep -qE "'_closedConn'|'_closedConnQ'"; then
277268
echo "FAIL: a field released via .Close() was wrongly reported as undisposed"; exit 1
278269
fi
279-
# #1 control: a connection-like field NEITHER closed NOR disposed must STILL warn.
280-
echo "$out" | grep -qE "SemaphoreAndCloseSample\.cs:[0-9]+:.*\[OWN001\].*'_leakedConn'" \
270+
# control: a connection-like field NEITHER closed NOR disposed must STILL warn.
271+
echo "$out" | grep -qE "CloseReleaseSample\.cs:[0-9]+:.*\[OWN001\].*'_leakedConn'" \
281272
|| { echo "FAIL: a field that is never closed/disposed must still warn (Close-as-release stays scoped to an actual Close call)"; exit 1; }
273+
# Codex/CodeRabbit control: Close() credits THIS instance's field only — closing ANOTHER instance
274+
# of the same class's same-named field must NOT suppress this object's leak (ThisFieldName, not a
275+
# receiver-stripping name match that a same-class ContainingType check would also miss).
276+
echo "$out" | grep -qE "CloseReleaseSample\.cs:[0-9]+:.*\[OWN001\].*'_xconn'" \
277+
|| { echo "FAIL: other-instance .Close() must not credit this field (receiver-scoped to this/alias)"; exit 1; }
282278
# WPF004: an ignored `X.Subscribe(...)` result leaks; the captured+
283279
# disposed one stays silent. "ignored" is unique to the WPF004 message.
284280
echo "$out" | grep -q "MessengerViewModel.cs" \

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

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -469,11 +469,7 @@ static bool IsDisposeOptional(ITypeSymbol t)
469469
{
470470
var ns = t.ContainingNamespace?.ToString();
471471
return (ns == "System.Threading.Tasks" && t.Name is "Task" or "ValueTask")
472-
|| (ns == "System.Data" && t.Name is "DataTable" or "DataSet" or "DataView")
473-
// SemaphoreSlim.Dispose() only frees a LAZILY-allocated wait handle (allocated solely if
474-
// AvailableWaitHandle is read); the common WaitAsync/Release usage allocates nothing, so an
475-
// undisposed SemaphoreSlim field is not a leak. Mined: Npgsql NpgsqlDataSource._setupMappingsSemaphore.
476-
|| (ns == "System.Threading" && t.Name == "SemaphoreSlim");
472+
|| (ns == "System.Data" && t.Name is "DataTable" or "DataSet" or "DataView");
477473
}
478474

479475
// A type that is System.Windows.Forms.Form or derives from it (semantic, walks the
@@ -2264,16 +2260,20 @@ or ImplicitObjectCreationExpressionSyntax
22642260
&& model.GetDeclaredSymbol(decl) is ILocalSymbol aliasSym
22652261
&& !reassignedAliases.Contains(aliasSym))
22662262
aliasToField[aliasSym] = af;
2267-
// a `.Dispose()`/`.DisposeAsync()`/`.Close()` on a field — directly (`_f.Dispose()`) or through
2268-
// an alias local (translated by SYMBOL via aliasToField) — releases that field. `Close()` counts
2269-
// as a release here exactly as it already does for LOCAL disposables (DisposesLocal and the flow
2270-
// detector both accept Dispose/Close/DisposeAsync); a field of a Stream / DbConnection-style type
2271-
// is released by Close just as Dispose would. Mined: Npgsql ReplicationConnection disposes its
2272-
// NpgsqlConnection field via `await _npgsqlConnection.Close(async: true)`.
2263+
// a `.Dispose()`/`.DisposeAsync()`/`.Close()` on a field — directly (`_f.Dispose()` / `this._f.…`)
2264+
// or through an alias local (translated by SYMBOL via aliasToField) — releases that field.
2265+
// `Close()` counts as a release here exactly as it already does for LOCAL disposables (DisposesLocal
2266+
// and the flow detector both accept Dispose/Close/DisposeAsync); a Stream / DbConnection-style field
2267+
// released by Close is not a leak. Mined: Npgsql ReplicationConnection disposes its NpgsqlConnection
2268+
// field via `await _npgsqlConnection.Close(async: true)`. ThisFieldName (not FieldName) scopes the
2269+
// credit to THIS instance's field / a validated alias: `other._f.Close()` on ANOTHER instance of
2270+
// the same class must NOT mark this object's `_f` released (Codex/CodeRabbit) — and a field-symbol
2271+
// ContainingType check would NOT catch that (same class -> same ContainingType), so key on the
2272+
// `this`/bare receiver syntactically.
22732273
foreach (var inv in cls.DescendantNodes().OfType<InvocationExpressionSyntax>())
22742274
if (inv.Expression is MemberAccessExpressionSyntax m
22752275
&& m.Name.Identifier.Text is "Dispose" or "DisposeAsync" or "Close"
2276-
&& FieldName(m.Expression) is { } df)
2276+
&& ThisFieldName(m.Expression) is { } df)
22772277
disposed.Add(model.GetSymbolInfo(m.Expression).Symbol is ILocalSymbol ls
22782278
&& aliasToField.TryGetValue(ls, out var fa) ? fa : df);
22792279
// Also the NULL-CONDITIONAL form `field?.Dispose()` (a ConditionalAccess whose
@@ -2283,7 +2283,7 @@ or ImplicitObjectCreationExpressionSyntax
22832283
// and the BufferedStreams benchmark's `[GlobalCleanup]` `field?.Dispose()` calls.
22842284
// (The same alias-by-symbol translation applies — `cts?.Dispose()` on an aliasing local.)
22852285
foreach (var cae in cls.DescendantNodes().OfType<ConditionalAccessExpressionSyntax>())
2286-
if (FieldName(cae.Expression) is { } cdf
2286+
if (ThisFieldName(cae.Expression) is { } cdf // this-instance field / alias only (not `other._f?.Close()`)
22872287
&& cae.WhenNotNull is InvocationExpressionSyntax { Expression: MemberBindingExpressionSyntax mb }
22882288
&& mb.Name.Identifier.Text is "Dispose" or "DisposeAsync" or "Close")
22892289
disposed.Add(model.GetSymbolInfo(cae.Expression).Symbol is ILocalSymbol lc
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
using System;
2+
3+
namespace Own.Samples;
4+
5+
// `.Close()` releases a field, exactly as it already does for LOCAL disposables (DisposesLocal and the
6+
// flow detector both accept Dispose/Close/DisposeAsync): a Stream / DbConnection-style field cleaned up
7+
// by Close() is not a leak. Mined: Npgsql's ReplicationConnection releases its NpgsqlConnection field
8+
// via `await _npgsqlConnection.Close(async: true)`.
9+
10+
// a field released via `.Close()` — direct and null-conditional — must be SILENT.
11+
public sealed class ReleasesViaClose : IDisposable
12+
{
13+
private readonly FakeConnection _closedConn = new FakeConnection();
14+
private readonly FakeConnection _closedConnQ = new FakeConnection();
15+
16+
public void Dispose()
17+
{
18+
_closedConn.Close(); // Close() releases the field -> SILENT
19+
_closedConnQ?.Close(); // null-conditional Close() -> SILENT
20+
}
21+
}
22+
23+
// control: a field NEITHER closed NOR disposed must STILL warn OWN001.
24+
public sealed class LeaksUnclosed : IDisposable
25+
{
26+
private readonly FakeConnection _leakedConn = new FakeConnection();
27+
28+
public void Dispose() { } // never closed/disposed -> WARN
29+
}
30+
31+
// Codex/CodeRabbit control: Close() must target THIS instance's field. Closing ANOTHER instance of the
32+
// SAME class's same-named private field must NOT credit this object — and note a field-symbol
33+
// ContainingType check could not tell them apart (same class), so this leans on the `this`/bare receiver.
34+
// This object's own _xconn is never closed, so it STILL leaks.
35+
public sealed class ClosesOtherInstanceField : IDisposable
36+
{
37+
private readonly FakeConnection _xconn = new FakeConnection();
38+
39+
public void CloseOther(ClosesOtherInstanceField other)
40+
{
41+
other._xconn.Close(); // closes ANOTHER instance's field -> must NOT credit this._xconn
42+
}
43+
44+
public void Dispose() { } // this._xconn is never closed -> WARN OWN001
45+
}
46+
47+
// A connection-like resource whose release is Close() (the DbConnection.Close() / Stream.Close() shape).
48+
internal sealed class FakeConnection : IDisposable
49+
{
50+
public void Close() { }
51+
public void Dispose() { }
52+
}

‎frontend/roslyn/samples/SemaphoreAndCloseSample.cs‎

Lines changed: 0 additions & 64 deletions
This file was deleted.

0 commit comments

Comments
 (0)