|
| 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. |
0 commit comments