Skip to content

Commit 31b04ca

Browse files
PhysShellclaude
andauthored
fix(extractor): treat closure-captured locals as escaped (ShareX throttler FP) (#59)
Triaging the ShareX re-mine left one false positive among the surviving local-disposable findings: Helpers.ForEachAsync's `SemaphoreSlim throttler`, captured by the async lambdas of a returned `Task.WhenAll(tasks)`. The semaphore must outlive the method frame (the caller awaits the returned task), so it cannot be disposed at method scope — not a method-local leak. The flow detector flagged it OWN001. The escape filter already untracks a local that escapes by return / out / argument. A capture into a closure is the same kind of escape, so the filter now also untracks a candidate whose reference is lexically inside a lambda / anonymous method / local function (a syntactic ancestor walk — crash-proof, no data-flow analysis). It does not require proving the closure escapes: a captured local MAY outlive the method, and the precision-first stance is to not flag what cannot be proven to leak (a sound, bounded recall gap). Not a blanket SemaphoreSlim exemption — SemaphoreSlim is not dispose-optional (AvailableWaitHandle allocates a handle Dispose must release), so a method-bounded one still leaks; the bug is the capture, not the type. A `nameof(x)` operand is skipped before the escape checks (Codex review): it surfaces an identifier under the closure (or as an argument) but is a compile-time string that captures nothing, so it must not untrack a still-leaking local — closing both the new lambda path and the pre-existing arg path. Pinned by three FlowLocalsSample cases in the wpf-extractor --flow-locals step: ThrottlerCaptured (captured -> silent), SemaphoreLeaks (non-captured -> OWN001), NameofInLambda (nameof-only -> OWN001). The existing UnitOfWorkFlowSample OWN001 is unaffected (`uow` is the receiver of `uow.Member`, outside the lambda bodies; the join is query syntax). Writeup in docs/notes/closure-capture-escape-precision.md. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Rg8kSk1YT14x7A1vo5zgED
1 parent 0568bde commit 31b04ca

4 files changed

Lines changed: 168 additions & 1 deletion

File tree

‎.github/workflows/ci.yml‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -380,6 +380,18 @@ jobs:
380380
|| { echo "FAIL: expected OWN001 on the undisposed local in a do-while loop"; exit 1; }
381381
echo "$out" | grep -qE "OWN001.*'swLeak'" \
382382
|| { echo "FAIL: expected OWN001 on the switch default-branch leak"; exit 1; }
383+
# closure-capture escape (precision): a SemaphoreSlim captured by a returned async
384+
# lambda outlives the method, so it cannot be disposed at method scope -> escaped ->
385+
# silent ('captured'). A SemaphoreSlim NOT captured and never disposed STILL leaks ->
386+
# OWN001 ('semLeak'), proving the exemption is closure-capture, not a blanket
387+
# SemaphoreSlim dispose-optional (reduced from a ShareX FP — Helpers.ForEachAsync).
388+
echo "$out" | grep -qE "OWN001.*'semLeak' is never disposed" \
389+
|| { echo "FAIL: expected OWN001 on the non-captured SemaphoreSlim leak"; exit 1; }
390+
# a `nameof(x)` operand inside a lambda is NOT a closure capture (it is a compile-time
391+
# string) -> the local stays method-bounded and still leaks -> OWN001 (Codex review on
392+
# #59: nameof must not masquerade as a capture/escape).
393+
echo "$out" | grep -qE "OWN001.*'nofLeak' is never disposed" \
394+
|| { echo "FAIL: expected OWN001 on the nameof-in-lambda local (not a capture)"; exit 1; }
383395
# dispose-optional (Task), disposed/escaping locals, a `for` loop whose
384396
# disposable is disposed after it (`looped`, balanced), a balanced
385397
# acquire+dispose in a loop (`whileClean`), a try/finally dispose (`tfClean`,
@@ -401,7 +413,7 @@ jobs:
401413
# case disposes (no default) -> last case is the tail, no phantom no-match leak.
402414
# `ncf`: `ncf?.Dispose()` (null-conditional) in a threaded finally IS a release
403415
# (member-binding form), so it is disposed on the return path -> silent (Codex review).
404-
for ok in clean looped esc exemptTask whileClean asyncDisposed asyncDisposedCfg tfClean tfCatch tfRet tfNull cda daci cif ctorLater lamPrior other doClean swAll ncf; do
416+
for ok in clean looped esc exemptTask whileClean asyncDisposed asyncDisposedCfg tfClean tfCatch tfRet tfNull cda daci cif ctorLater lamPrior other doClean swAll ncf captured; do
405417
if echo "$out" | grep -q "'$ok'"; then echo "FAIL: silent/exempt case '$ok' was reported"; exit 1; fi
406418
done
407419
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: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
# Closure-capture escape — a local captured by a lambda is not method-bounded
2+
3+
A precision fix driven by triaging the **re-mine of ShareX** (after the WinForms
4+
modeless-`Form` fix, #57): of the seven local-disposable findings that survived, six
5+
were real or defensible and **one was a false positive** — `Helpers.ForEachAsync`'s
6+
`SemaphoreSlim throttler`:
7+
8+
```csharp
9+
public static Task ForEachAsync<T>(IEnumerable<T> items, Func<T, Task> body, int max)
10+
{
11+
SemaphoreSlim throttler = new SemaphoreSlim(max, max);
12+
13+
IEnumerable<Task> tasks = items.Select(async input =>
14+
{
15+
await throttler.WaitAsync(); // throttler used INSIDE the lambda
16+
try { await body(input); } finally { throttler.Release(); }
17+
});
18+
19+
return Task.WhenAll(tasks); // the lambdas (and throttler) escape
20+
}
21+
```
22+
23+
The flow detector saw `throttler = new SemaphoreSlim(...)` (an undisposed `IDisposable`
24+
local) and flagged OWN001. But `throttler` is **captured by the async lambdas**, and
25+
those lambdas escape the method — they run while the returned `Task.WhenAll(tasks)` is
26+
awaited by the caller. The semaphore must stay alive until every task finishes, so it
27+
*cannot* be disposed at method scope. It is not a method-local leak.
28+
29+
## The fix — capture into a closure is an escape
30+
31+
The flow detector already untracks a local that escapes by **return**, **out/ref**, or
32+
being **passed as an argument** (an ambiguous ownership transfer). A capture into a
33+
closure is the same kind of escape — the closure can be stored, returned, or run async,
34+
so the local outlives the method frame. The escape filter now also untracks a candidate
35+
local when any reference to it is **lexically inside a lambda / anonymous method / local
36+
function** body:
37+
38+
```csharp
39+
// in the --flow-locals escape filter, before the return/out/arg checks:
40+
var capturedInClosure = false;
41+
for (var a = idn.Parent; a is not null && a != mbody; a = a.Parent)
42+
if (a is AnonymousFunctionExpressionSyntax or LocalFunctionStatementSyntax)
43+
{ capturedInClosure = true; break; }
44+
if (capturedInClosure) { escapedLocals.Add(nm); continue; }
45+
```
46+
47+
It is purely syntactic (an ancestor walk to the method body), so it is crash-proof and
48+
needs no escape/data-flow analysis of where the closure goes. It deliberately does **not**
49+
require proving the closure escapes: a captured local *may* outlive the method, and the
50+
precision-first stance is to not flag what we cannot prove leaks.
51+
52+
One syntactic exception: a **`nameof(x)`** operand is skipped before the escape checks. It
53+
exposes an `IdentifierNameSyntax` under the closure (or as an argument), but `nameof` is a
54+
compile-time string that captures and transfers nothing — so it must not be mistaken for a
55+
capture (nor, on the argument path, an ownership transfer), or a still-leaking method-bounded
56+
local would be wrongly untracked (Codex review). Pinned by the `NameofInLambda` sample case.
57+
58+
### Why not just exempt `SemaphoreSlim`?
59+
60+
`SemaphoreSlim` is **not** unconditionally dispose-optional: accessing
61+
`AvailableWaitHandle` lazily allocates a wait handle that `Dispose()` must release (CA2000
62+
flags an undisposed one). Blanket-exempting it (the way `Task`/`DataTable` are exempt in
63+
`IsDisposeOptional`) would be unsound — it would hide a real method-local semaphore leak.
64+
The bug here is the **capture/escape**, not the type, so the fix targets the capture.
65+
66+
## The recall trade-off (sound, bounded)
67+
68+
The rule is conservative: a local captured by a closure that does **not** escape, and is
69+
never disposed, is now silenced too (e.g. `var s = new MemoryStream(); Action a = () =>
70+
s.Use(); a(); /* never disposed */`). Proving such a closure stays method-local is exactly
71+
the data-flow analysis the syntactic rule avoids, so this is an accepted recall gap, never
72+
a false positive — the same precision-over-recall trade the escape filter already makes for
73+
argument-passing.
74+
75+
## Pinned in CI
76+
77+
`frontend/roslyn/samples/FlowLocalsSample.cs` gains two cases, asserted in the
78+
`wpf-extractor` `--flow-locals` step:
79+
80+
- `ThrottlerCaptured` — a `SemaphoreSlim` captured by a returned async lambda → **silent**
81+
(the FP this removes);
82+
- `SemaphoreLeaks` — a `SemaphoreSlim` **not** captured by any closure and never disposed →
83+
**OWN001**, proving the exemption is closure-capture, not a blanket `SemaphoreSlim`
84+
dispose-optional.
85+
86+
The existing `UnitOfWorkFlowSample` OWN001 is unaffected: its `uow` is always the
87+
*receiver* of `uow.Member` (outside the `.Where(p => …)` lambda bodies, which reference
88+
`p`), and the `join … in uow.TempProducts` is query syntax, not an
89+
`AnonymousFunctionExpressionSyntax` — so the ancestor walk never marks `uow` captured.

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

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1450,6 +1450,34 @@ or ImplicitObjectCreationExpressionSyntax } init
14501450
var nm = idn.Identifier.Text;
14511451
if (!candidates.Contains(nm))
14521452
continue;
1453+
// A `nameof(x)` operand is a compile-time string, not a real reference: it
1454+
// neither uses, captures, nor transfers the local. Skip it so it triggers no
1455+
// escape rule — otherwise `nameof(s)` would look like an argument (the arg
1456+
// rule below) or, inside a lambda, a closure capture, and wrongly untrack a
1457+
// still-leaking method-bounded local (Codex review on PR #59).
1458+
if (idn.Parent is ArgumentSyntax { Parent: ArgumentListSyntax
1459+
{ Parent: InvocationExpressionSyntax ninv } }
1460+
&& ninv.Expression is IdentifierNameSyntax { Identifier.Text: "nameof" })
1461+
continue;
1462+
// Captured into a CLOSURE (lambda / anonymous method / local function):
1463+
// the closure can outlive the method — stored, returned, or run async —
1464+
// so the local is no longer method-bounded and cannot be disposed at
1465+
// method scope. Conservatively treat the capture as an escape (don't
1466+
// flag it), the same way a returned/out-passed local is untracked.
1467+
// Reduced from a ShareX false positive: a SemaphoreSlim throttler captured
1468+
// by the async lambdas of a returned `Task.WhenAll(...)` (Helpers.ForEachAsync).
1469+
var capturedInClosure = false;
1470+
for (var a = idn.Parent; a is not null && a != mbody; a = a.Parent)
1471+
if (a is AnonymousFunctionExpressionSyntax or LocalFunctionStatementSyntax)
1472+
{
1473+
capturedInClosure = true;
1474+
break;
1475+
}
1476+
if (capturedInClosure)
1477+
{
1478+
escapedLocals.Add(nm);
1479+
continue;
1480+
}
14531481
// ... unless it is handed to a CONSUMER (a first-party method that
14541482
// disposes a by-value IDisposable param) as a bare `Consume(s);`
14551483
// statement: that is a handoff RELEASED at the call site, not an escape

‎frontend/roslyn/samples/FlowLocalsSample.cs‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -403,6 +403,44 @@ public async Task DisposedAsyncConfigured()
403403
asyncDisposedCfg.WriteByte(1);
404404
await asyncDisposedCfg.DisposeAsync().ConfigureAwait(false);
405405
}
406+
407+
// NOT a leak (precision): a SemaphoreSlim captured into an async lambda whose Task is
408+
// returned outlives the method — the caller awaits it, so it cannot be disposed at
409+
// method scope. A local referenced inside a closure (lambda / anonymous method / local
410+
// function) is treated as escaped, exactly like a returned/out-passed local. Reduced
411+
// from a ShareX false positive (Helpers.ForEachAsync's `throttler` captured by the async
412+
// lambdas of a returned Task.WhenAll). Silent.
413+
public Task ThrottlerCaptured(int max)
414+
{
415+
var captured = new SemaphoreSlim(max, max);
416+
Func<Task> run = async () =>
417+
{
418+
await captured.WaitAsync();
419+
captured.Release();
420+
};
421+
return run();
422+
}
423+
424+
// control (must still leak): a SemaphoreSlim NOT captured by any closure and never
425+
// disposed -> OWN001. Proves the exemption is about CLOSURE CAPTURE (escape), not
426+
// SemaphoreSlim being blanket dispose-optional — it is not (accessing AvailableWaitHandle
427+
// allocates a handle Dispose must release), so it must stay tracked when method-bounded.
428+
public void SemaphoreLeaks()
429+
{
430+
var semLeak = new SemaphoreSlim(1, 1);
431+
semLeak.Wait();
432+
}
433+
434+
// OWN001 (Codex review on #59): a `nameof(x)` operand inside a lambda exposes an
435+
// identifier under the closure, but `nameof` is a compile-time string — it captures
436+
// nothing. `nofLeak` is only mentioned via nameof, so it is still method-bounded and
437+
// never disposed -> a real leak. The nameof operand must not be mistaken for a capture.
438+
public void NameofInLambda()
439+
{
440+
var nofLeak = new MemoryStream();
441+
Action log = () => System.Console.WriteLine(nameof(nofLeak));
442+
log();
443+
}
406444
}
407445

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

0 commit comments

Comments
 (0)