Skip to content

Commit 6f4818c

Browse files
committed
extractor: recognize field disposal via a receiver-consuming helper
A field released through a 'drain and dispose' sink — a first-party extension method that disposes its receiver, like NLog's WaitForDispose(this Timer, TimeSpan) — was reported as an OWN001 owned-field leak, because the disposal scan only keys on a literal .Dispose()/.Close()/.DisposeAsync() on the field. Credit field.M(...) as a release when M is a first-party extension method whose receiver it disposes. CallReleasesReceiver reuses the existing ConsumesParam on the reduced extension method's receiver parameter, so the release is proved by inspecting M's real body (following first-party forwarding, cycle-guarded, IDisposable-only) — never guessed from the name. Scope is extension methods only; an instance method disposing its own 'this' is left out. Clears the NLog timer FPs where the sink is called on the field directly or through a 'var t = _field;' alias (AsyncTaskTarget, AsyncTargetWrapper, BufferingTargetWrapper). TimeoutContinuation, which disposes the result of Interlocked.Exchange(ref _timer, null), stays baselined until ref-exchange alias tracking lands. New corpus fixture field-dispose-via-helper proves it: before.cs leaks the Timer field (OWN001 caught), after.cs releases it via the sink and must be silent — the benchmark's after-clean gate is the end-to-end check. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019846YSZ35c7CdkWQ1qX5gm
1 parent daa4e83 commit 6f4818c

6 files changed

Lines changed: 153 additions & 4 deletions

File tree

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
using System;
2+
using System.Threading;
3+
4+
// A "drain and dispose" sink: stops the timer, then disposes it. Because its
5+
// receiver parameter is disposed in the body, a `_timer.WaitForDispose(...)` call
6+
// releases the field — the extractor proves this by inspecting the sink's body
7+
// (ConsumesParam on the reduced extension method's receiver), not by name.
8+
static class TimerSink
9+
{
10+
public static void WaitForDispose(this Timer timer, TimeSpan timeout)
11+
{
12+
timer.Change(Timeout.Infinite, Timeout.Infinite);
13+
timer.Dispose();
14+
}
15+
}
16+
17+
// FIX: the owned Timer field is released through the sink on Dispose. No literal
18+
// `_timer.Dispose()` appears, so recognising this requires following the sink's
19+
// dispose effect — once we do, there is no leak and the case is silent.
20+
sealed class Worker : IDisposable
21+
{
22+
readonly Timer _timer;
23+
24+
public Worker() => _timer = new Timer(_ => { }, null, 0, 1000);
25+
26+
public void Dispose() => _timer.WaitForDispose(TimeSpan.Zero);
27+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
using System;
2+
using System.Threading;
3+
4+
// A "drain and dispose" sink: the canonical shape mined on NLog, where a Timer
5+
// field is released not by a literal `_timer.Dispose()` but by a custom extension
6+
// method that stops the timer and then disposes it (NLog's
7+
// `WaitForDispose(this Timer, TimeSpan)` in Common/AsyncHelpers.cs).
8+
static class TimerSink
9+
{
10+
public static void WaitForDispose(this Timer timer, TimeSpan timeout)
11+
{
12+
timer.Change(Timeout.Infinite, Timeout.Infinite);
13+
timer.Dispose();
14+
}
15+
}
16+
17+
// BUG: the owned Timer field is constructed but never released on any path —
18+
// neither a literal `.Dispose()` nor the sink. A genuine OWN001 owned-field leak.
19+
sealed class Worker : IDisposable
20+
{
21+
readonly Timer _timer;
22+
23+
public Worker() => _timer = new Timer(_ => { }, null, 0, 1000);
24+
25+
public void Dispose()
26+
{
27+
// nothing — _timer is leaked
28+
}
29+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// OwnLang model of the "drain and dispose" field-release pattern mined on NLog
2+
// (src/NLog/Targets/AsyncTaskTarget.cs and siblings). A Timer field is owned by the
3+
// component; the real fix releases it not with a literal `_timer.Dispose()` but
4+
// through a custom extension method `WaitForDispose(this Timer, TimeSpan)` that
5+
// stops the timer and then disposes it (Common/AsyncHelpers.cs). The before.cs
6+
// leaks the timer (no release on any path) — the generic OWN001 owned-field leak
7+
// modelled here as an acquire with no `release`. The after.cs releases it via the
8+
// sink, which the extractor now recognises by inspecting the sink's body
9+
// (ConsumesParam on its receiver parameter); see notes.md for that recognition rule
10+
// and which NLog variants it does and does not reach.
11+
module Corpus
12+
resource Timer {
13+
acquire create
14+
release dispose
15+
kind "disposable"
16+
emit_type "Timer"
17+
emit_acquire "new Timer({args})"
18+
emit_release "{0}.WaitForDispose()"
19+
}
20+
fn Worker(callback: int) {
21+
let timer = acquire Timer(callback); // _timer = new Timer(_ => { }, null, 0, 1000)
22+
// no `release timer;` — the timer is never stopped or disposed (OWN001)
23+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
OWN001
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# field-dispose-via-helper
2+
3+
An owned `IDisposable` field is released not by a literal `_field.Dispose()` but by
4+
a **first-party extension method that disposes its receiver** — the "drain and
5+
dispose" sink. The canonical real-world shape is NLog's
6+
`WaitForDispose(this Timer, TimeSpan)` (`Common/AsyncHelpers.cs`), which stops the
7+
timer (`Change(Infinite, Infinite)`) and then disposes it; targets call
8+
`_taskTimeoutTimer.WaitForDispose(...)` from `Dispose(bool disposing)` /
9+
`CloseTarget()`.
10+
11+
- **before.cs** — the `Timer` field is constructed and never released on any path
12+
→ `OWN001` (the bug is caught).
13+
- **after.cs** — the field is released via `_timer.WaitForDispose(...)` → **clean**.
14+
No literal `.Dispose()` on the field appears, so the only way to see the release
15+
is to follow the sink's dispose effect.
16+
17+
## Recognition rule
18+
19+
The disposal scan already credits a field released anywhere in the class by
20+
`field.Dispose()` / `.Close()` / `.DisposeAsync()` (directly, through a
21+
`var t = _field;` alias, or null-conditional), so a field disposed in
22+
`Dispose(bool disposing)` or `CloseTarget()` is already handled. This case adds the
23+
missing hop: a call `field.M(...)` also releases the field when **`M` is a
24+
first-party extension method whose receiver it disposes**. It is proved, not
25+
guessed — `CallReleasesReceiver` reuses `ConsumesParam` on the reduced extension
26+
method's receiver parameter (index 0), which inspects `M`'s real body, follows
27+
first-party forwarding chains, is cycle-guarded, and requires an `IDisposable`
28+
parameter. So an unknown or borrowing callee never credits a release.
29+
30+
## Honesty caveat — what this does and does not reach
31+
32+
This clears the NLog variants where the sink is called on the field **directly** or
33+
through a simple `var t = _field;` alias (`AsyncTaskTarget`, `AsyncTargetWrapper`,
34+
`BufferingTargetWrapper`). It does **not** reach `TimeoutContinuation`, where the
35+
receiver is the result of `Interlocked.Exchange(ref _timer, null)` — an
36+
exchange-and-null-out idiom whose result is not a tracked field alias. That one
37+
stays in the oracle FP baseline
38+
([`corpus/oracle-fp-baseline.txt`](../../oracle-fp-baseline.txt),
39+
[`docs/notes/oracle-known-fps.md`](../../../docs/notes/oracle-known-fps.md)) until
40+
ref-exchange alias tracking lands. Scope is intentionally limited to **extension
41+
methods**: an instance method disposing its own `this` is not a real
42+
dispose-delegation shape and would drag in virtual-dispatch reasoning.

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

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2494,6 +2494,27 @@ static bool DisposesLocal(SyntaxNode body, string name)
24942494
return false;
24952495
}
24962496

2497+
// Does the call `recv.M(...)` RELEASE its receiver — i.e. is `M` a first-party
2498+
// EXTENSION method whose body disposes the value it is invoked on? The dispose is
2499+
// then laundered through a custom "drain and dispose" sink (e.g. NLog's
2500+
// `timer.WaitForDispose(timeout)`, which calls `timer.Change(...)` then disposes
2501+
// it) rather than a literal `recv.Dispose()`, so the disposal scan that only keys
2502+
// on `Dispose`/`Close`/`DisposeAsync` misses it and reports a false leak. We reuse
2503+
// `ConsumesParam` on the reduced extension method's RECEIVER parameter (the
2504+
// `this T` at index 0): that inspects M's real body, follows first-party
2505+
// forwarding, is cycle-guarded, and demands an IDisposable param — so we only ever
2506+
// credit a release we can SEE happen, never an unknown/borrowing callee. Scope is
2507+
// deliberately narrow (extension methods only): an instance method disposing its
2508+
// own `this` is not a real dispose-delegation shape, and widening to it would also
2509+
// have to reason about virtual dispatch — left out to keep the surface minimal.
2510+
static bool CallReleasesReceiver(IMethodSymbol? sym, SemanticModel model)
2511+
{
2512+
if (sym?.ReducedFrom is not { } def || def.Parameters.Length == 0)
2513+
return false;
2514+
return ConsumesParam(def, def.Parameters[0], model,
2515+
new HashSet<ISymbol>(SymbolEqualityComparer.Default));
2516+
}
2517+
24972518
// A field/local type treated as owned-disposable (syntax-only heuristic — no
24982519
// semantic model): a curated set plus a few suffixes. Gated on the class `new`ing
24992520
// the value, so injected/borrowed disposables are not flagged. Timer types are
@@ -3300,8 +3321,13 @@ or ImplicitObjectCreationExpressionSyntax
33003321
// `this`/bare receiver syntactically.
33013322
foreach (var inv in cls.DescendantNodes().OfType<InvocationExpressionSyntax>())
33023323
if (inv.Expression is MemberAccessExpressionSyntax m
3303-
&& m.Name.Identifier.Text is "Dispose" or "DisposeAsync" or "Close"
3304-
&& ThisFieldName(m.Expression) is { } df)
3324+
&& ThisFieldName(m.Expression) is { } df
3325+
// a literal `.Dispose()/.Close()/.DisposeAsync()`, OR a first-party
3326+
// extension method that disposes its receiver (`timer.WaitForDispose()`):
3327+
// both release the field. The name check is first (cheap) — the symbol
3328+
// resolution behind CallReleasesReceiver only runs for the rarer custom call.
3329+
&& (m.Name.Identifier.Text is "Dispose" or "DisposeAsync" or "Close"
3330+
|| CallReleasesReceiver(model.GetSymbolInfo(inv).Symbol as IMethodSymbol, model)))
33053331
disposed.Add(model.GetSymbolInfo(m.Expression).Symbol is ILocalSymbol ls
33063332
&& aliasToField.TryGetValue(ls, out var fa) ? fa : df);
33073333
// Also the NULL-CONDITIONAL form `field?.Dispose()` (a ConditionalAccess whose
@@ -3312,8 +3338,9 @@ or ImplicitObjectCreationExpressionSyntax
33123338
// (The same alias-by-symbol translation applies — `cts?.Dispose()` on an aliasing local.)
33133339
foreach (var cae in cls.DescendantNodes().OfType<ConditionalAccessExpressionSyntax>())
33143340
if (ThisFieldName(cae.Expression) is { } cdf // this-instance field / alias only (not `other._f?.Close()`)
3315-
&& cae.WhenNotNull is InvocationExpressionSyntax { Expression: MemberBindingExpressionSyntax mb }
3316-
&& mb.Name.Identifier.Text is "Dispose" or "DisposeAsync" or "Close")
3341+
&& cae.WhenNotNull is InvocationExpressionSyntax { Expression: MemberBindingExpressionSyntax mb } cinv
3342+
&& (mb.Name.Identifier.Text is "Dispose" or "DisposeAsync" or "Close"
3343+
|| CallReleasesReceiver(model.GetSymbolInfo(cinv).Symbol as IMethodSymbol, model)))
33173344
disposed.Add(model.GetSymbolInfo(cae.Expression).Symbol is ILocalSymbol lc
33183345
&& aliasToField.TryGetValue(lc, out var fc) ? fc : cdf);
33193346

0 commit comments

Comments
 (0)