Skip to content

Commit 8f69f46

Browse files
PhysShellclaude
andauthored
fix(extractor): model TcpListener.Stop() as a release (Stop is the cleanup) (#62)
Codex review on #61: triaging the ShareX re-mine, the undisposed-TcpListener finding (WebHelpers.GetRandomUnusedPort: Start() then Stop() in a finally, no Dispose()) is a FALSE POSITIVE. TcpListener.Dispose() just delegates to Stop(), which disposes the listen socket and clears it — so a Stop()'d listener holds no resource. Flagging it OWN001 dents the 0-FP precision claim (CA2000 / CodeQL flag it conventionally, but it is not a real leak). EmitFlowExpr now models tcpListener.Stop() as a release of the local, alongside the Dispose()/Close()/pool-Return/Show() releases. TcpListener-specific, resolved on the method's containing type via the SemanticModel (Stop() on a Timer / Process / Stopwatch / etc. does NOT dispose and stays a tracked use), and path-sensitive like the WinForms Show() model: a listener never Stop()'d (nor disposed) still leaks. Pinned by two FlowLocalsSample cases in the wpf-extractor --flow-locals step: TcpListenerStopped (Start() + Stop() -> silent, the FP this removes) and TcpListenerNeverStopped (Start(), no Stop -> OWN001, the control proving the release is Stop()-specific). The sibling StreamReader FP from the same triage is deliberately NOT changed: the extractor's general behaviour there is correct (a StreamReader over a stream not otherwise disposed genuinely leaks it); only the narrow using-scoped-stream variant is a non-leak, a rare accepted residual. See docs/notes/tcplistener-stop-release.md. Supersedes the closed #61 (which would have locked these FPs). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Rg8kSk1YT14x7A1vo5zgED
1 parent cfcf7f6 commit 8f69f46

4 files changed

Lines changed: 120 additions & 1 deletion

File tree

‎.github/workflows/ci.yml‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -399,6 +399,12 @@ jobs:
399399
# previously-missed leak in ShareX's DeriveCryptoData.
400400
echo "$out" | grep -qE "OWN001.*'rngLeak' is never disposed" \
401401
|| { echo "FAIL: expected OWN001 on the undisposed crypto-factory acquire"; exit 1; }
402+
# TcpListener precision (Codex review on #61): Stop() IS the cleanup (Dispose()
403+
# delegates to Stop()), so a Stop()'d listener is modelled as released -> silent
404+
# ('stopped'); a listener NEVER Stop()'d still holds the socket -> OWN001 ('tcpLeak'),
405+
# proving the release is Stop()-specific, not a blanket TcpListener exemption.
406+
echo "$out" | grep -qE "OWN001.*'tcpLeak' is never disposed" \
407+
|| { echo "FAIL: expected OWN001 on the never-stopped TcpListener"; exit 1; }
402408
# dispose-optional (Task), disposed/escaping locals, a `for` loop whose
403409
# disposable is disposed after it (`looped`, balanced), a balanced
404410
# acquire+dispose in a loop (`whileClean`), a try/finally dispose (`tfClean`,
@@ -420,7 +426,7 @@ jobs:
420426
# case disposes (no default) -> last case is the tail, no phantom no-match leak.
421427
# `ncf`: `ncf?.Dispose()` (null-conditional) in a threaded finally IS a release
422428
# (member-binding form), so it is disposed on the return path -> silent (Codex review).
423-
for ok in clean looped esc exemptTask whileClean asyncDisposed asyncDisposedCfg tfClean tfCatch tfRet tfNull cda daci cif ctorLater lamPrior other doClean swAll ncf captured shaClean; do
429+
for ok in clean looped esc exemptTask whileClean asyncDisposed asyncDisposedCfg tfClean tfCatch tfRet tfNull cda daci cif ctorLater lamPrior other doClean swAll ncf captured shaClean stopped; do
424430
if echo "$out" | grep -q "'$ok'"; then echo "FAIL: silent/exempt case '$ok' was reported"; exit 1; fi
425431
done
426432
echo "OK: flow-sensitive OWN001/002/003 on real C# (path-sensitive, loops via while/foreach/for, try/finally sequential, never-vs-every-path wording, dispose-optional exempt, beyond flat)"
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
# `TcpListener.Stop()` is a release — Stop() is the cleanup, not a half-measure
2+
3+
A precision fix from a **Codex review** (PR #61). While triaging the ShareX re-mine I
4+
nearly locked an undisposed-`TcpListener` finding as a corpus regression — Codex caught
5+
that it is a **false positive**, and it was right.
6+
7+
## The false positive
8+
9+
```csharp
10+
public static int GetRandomUnusedPort() // ShareX WebHelpers.cs:191
11+
{
12+
TcpListener listener = new TcpListener(IPAddress.Loopback, 0);
13+
try
14+
{
15+
listener.Start();
16+
return ((IPEndPoint)listener.LocalEndpoint).Port;
17+
}
18+
finally
19+
{
20+
listener.Stop();
21+
}
22+
}
23+
```
24+
25+
The flow detector flagged `listener` OWN001: it is an `IDisposable` (`TcpListener`
26+
implements `IDisposable` since .NET Core 3.0), and `Stop()` is not in the release set
27+
(`Dispose`/`Close`/`DisposeAsync`). But **`TcpListener.Dispose()` just delegates to
28+
`Stop()`** — `Stop()` disposes the listen socket and clears it. So after `Stop()` there is
29+
no held resource: an undisposed-but-stopped listener is **not a leak**, and flagging it
30+
dents the 0-FP precision claim (CA2000 / CodeQL flag it conventionally, but it is not a
31+
real resource leak).
32+
33+
## The fix — Stop() is a release, for `TcpListener`
34+
35+
`EmitFlowExpr` now models `tcpListener.Stop()` as a `release` of the local, alongside the
36+
`Dispose()`/`Close()`/pool-`Return`/`Show()` releases:
37+
38+
```csharp
39+
if (expr is InvocationExpressionSyntax tlinv
40+
&& tlinv.Expression is MemberAccessExpressionSyntax
41+
{ Name.Identifier.Text: "Stop", Expression: IdentifierNameSyntax tlid }
42+
&& tracked.Contains(tlid.Identifier.Text)
43+
&& model.GetSymbolInfo(tlinv).Symbol is IMethodSymbol { ContainingType: { Name: "TcpListener" } tct }
44+
&& IsInNamespace(tct, "System", "Net", "Sockets"))
45+
{
46+
nodes.Add(new { op = "release", var = tlid.Identifier.Text, line = LineOf(tlinv) });
47+
return;
48+
}
49+
```
50+
51+
It is **`TcpListener`-specific**, resolved on the method's containing type via the
52+
SemanticModel — `Stop()` on a `Timer` / `Process` / `Stopwatch` / etc. does **not** dispose
53+
and is untouched (stays a tracked use). And it is path-sensitive (a release at the call
54+
site), like the WinForms `Show()` model: a listener never `Stop()`'d (nor disposed) still
55+
leaks on the path that misses it.
56+
57+
## Pinned in CI
58+
59+
Two `FlowLocalsSample.cs` cases in the `wpf-extractor` `--flow-locals` step:
60+
61+
- `TcpListenerStopped` — `new TcpListener(...); Start(); Stop();` → **silent** (the FP this
62+
removes);
63+
- `TcpListenerNeverStopped` — `new TcpListener(...); Start();` (no `Stop`) → **OWN001**, the
64+
control proving the release is `Stop()`-specific, not a blanket `TcpListener` exemption.
65+
66+
## The sibling that is *not* fixed (and why)
67+
68+
The same triage had a `StreamReader` finding (a reader over a `using`-scoped `MemoryStream`,
69+
the reader not disposed). That is also a non-leak *in that specific shape* — the stream is
70+
disposed separately and the reader holds no unmanaged resource of its own. But unlike
71+
`TcpListener`, the extractor's general behaviour there is **correct**: a `StreamReader` over
72+
a stream that is *not* otherwise disposed genuinely leaks the stream (the reader owns it).
73+
Suppressing it would need stream-ownership reasoning and would cost real recall, so it is
74+
left as-is — the narrow `using`-scoped-stream variant is an accepted, rare residual, not a
75+
systematic FP class like `TcpListener.Stop()`.

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

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -712,6 +712,22 @@ static void EmitFlowExpr(ExpressionSyntax expr, HashSet<string> tracked, Semanti
712712
nodes.Add(new { op = "release", var = sid.Identifier.Text, line = LineOf(sinv) });
713713
return;
714714
}
715+
// x.Stop() on a tracked System.Net.Sockets.TcpListener -> release: TcpListener.Dispose()
716+
// just delegates to Stop() (which disposes the listen socket and clears it), so a
717+
// Stop()'d listener holds no resource and is not a leak (Codex review on PR #61). It is
718+
// TcpListener-specific, resolved via the method symbol — Stop() on a Timer / Process / etc.
719+
// does NOT dispose, so it stays a tracked use; a listener never Stop()'d (nor Disposed)
720+
// still leaks.
721+
if (expr is InvocationExpressionSyntax tlinv
722+
&& tlinv.Expression is MemberAccessExpressionSyntax
723+
{ Name.Identifier.Text: "Stop", Expression: IdentifierNameSyntax tlid }
724+
&& tracked.Contains(tlid.Identifier.Text)
725+
&& model.GetSymbolInfo(tlinv).Symbol is IMethodSymbol { ContainingType: { Name: "TcpListener" } tct }
726+
&& IsInNamespace(tct, "System", "Net", "Sockets"))
727+
{
728+
nodes.Add(new { op = "release", var = tlid.Identifier.Text, line = LineOf(tlinv) });
729+
return;
730+
}
715731
// x?.Dispose()/x?.Close()/x?.DisposeAsync() (null-conditional) is the release too — the
716732
// call is a member BINDING under a conditional access, not a member access. Mirrors
717733
// IsDisposeShaped so a `?.` dispose (e.g. in a finally) is not mistaken for a bare use,

‎frontend/roslyn/samples/FlowLocalsSample.cs‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
using System;
22
using System.IO;
3+
using System.Net;
4+
using System.Net.Sockets;
35
using System.Security.Cryptography;
46
using System.Threading;
57
using System.Threading.Tasks;
@@ -462,6 +464,26 @@ public void CryptoFactoryDisposed()
462464
shaClean.ComputeHash(new byte[1]);
463465
shaClean.Dispose();
464466
}
467+
468+
// NOT a leak (precision): TcpListener.Stop() IS the cleanup — TcpListener.Dispose() just
469+
// delegates to Stop(), which disposes the listen socket. So a Stop()'d listener holds no
470+
// resource; the extractor models Stop() on a TcpListener as a release. Reduced from a
471+
// ShareX false positive (WebHelpers.GetRandomUnusedPort, Codex review on #61). Silent.
472+
public void TcpListenerStopped()
473+
{
474+
var stopped = new TcpListener(IPAddress.Loopback, 0);
475+
stopped.Start();
476+
stopped.Stop();
477+
}
478+
479+
// control (must still leak): a TcpListener never Stop()'d (nor Disposed) holds the listen
480+
// socket -> OWN001. Proves the release is Stop()-specific, not a blanket TcpListener
481+
// exemption (a Timer/Process Stop() would NOT release).
482+
public void TcpListenerNeverStopped()
483+
{
484+
var tcpLeak = new TcpListener(IPAddress.Loopback, 0);
485+
tcpLeak.Start();
486+
}
465487
}
466488

467489
// A domain exception type literally named `Exception`, in a non-System namespace — the

0 commit comments

Comments
 (0)