Skip to content

Commit 4351f4a

Browse files
committed
extractor: pooled buffer transferred to a wrapper via an escaping local is not a leak
Oracle sweep (StackExchange.Redis) surfaced a false-positive class: a rented ArrayPool buffer handed to `new Wrapper(buf)` that is bound to a LOCAL which then leaves the method — `var lease = new Lease(arr); return lease;` (Lease<T>.Create) and `var r = new ScanResult(keys); SetResult(m, r);` (RedisServer scan) — was flagged OWN001 "rented but never returned". The buffer is transferred to the wrapper (which owns the Return), not leaked. PassedToEscapingCtor already exempts the DIRECT `return new Wrapper(buf)` / `_field = new Wrapper(buf)`. The Codex one-level rule deliberately kept a wrapper-in-a-local as a borrow (a method-scoped wrapper that never returns the buffer is a real leak). WrapperLocalEscapes adds the one-extra-hop case while preserving that: the `new Wrapper(buf)` bound to a local `w` is a transfer only when `w` provably leaves the method (`return w` / `<field> = w` / `w` as a call argument); a wrapper local that stays method-scoped still leaks. Corpus fixture pool-transfer-via-wrapper-local: before.cs (wrapper dropped method-scoped -> OWN001 caught) / after.cs (wrapper returned -> clean). Also re-runs the Redis oracle (oracle-target bump) to confirm the 4 own-only FPs clear. corpus 31/31, ruff clean. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019846YSZ35c7CdkWQ1qX5gm
1 parent 4589a94 commit 4351f4a

7 files changed

Lines changed: 158 additions & 3 deletions

File tree

‎corpus/oracle-target.txt‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
# TEMPORARY (revert before any PR): fresh-repo oracle sweep for new FP classes / recall gaps.
77
# Target 1 (done, clean): DapperLib/Dapper — 0 own-only; oracle-only = Infer# WrappedBasicReader
88
# ownership-transfer FPs + CodeQL dispose-on-throw honest-skips. No new FP class.
9-
# Target 2: StackExchange/StackExchange.Redis — heavy Subscribe tokens / ConnectionMultiplexer
10-
# IDisposable / timers; likelier to exercise subscription + disposable-field detectors.
9+
# Target 2: StackExchange/StackExchange.Redis — surfaced the pooled-buffer-transfer-via-escaping-
10+
# local FP class (Lease.cs:42, RedisServer.cs:917). RE-RUN to confirm the WrapperLocalEscapes fix
11+
# clears those 4 own-only findings (expect Lease.cs / RedisServer.cs `keys`/`arr` gone from own-only).
1112
StackExchange/StackExchange.Redis
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
using System;
2+
using System.Buffers;
3+
4+
sealed class Holder : IDisposable
5+
{
6+
readonly int[] _buf;
7+
public Holder(int[] buf) => _buf = buf;
8+
public void Dispose() => ArrayPool<int>.Shared.Return(_buf);
9+
}
10+
11+
static class Demo
12+
{
13+
// FIX: the rented buffer is wrapped into a local Holder that is RETURNED — ownership transfers to
14+
// the Holder (which Returns the buffer on Dispose), so the buffer does not leak here. The extractor
15+
// follows the buffer through the wrapper local because that local provably leaves the method
16+
// (`return holder`), so it stays silent. Mirrors StackExchange.Redis Lease<T>.Create.
17+
public static Holder Run(int n)
18+
{
19+
var buf = ArrayPool<int>.Shared.Rent(n);
20+
var holder = new Holder(buf);
21+
return holder;
22+
}
23+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
using System;
2+
using System.Buffers;
3+
4+
// A wrapper that takes ownership of a rented buffer and returns it to the pool on Dispose.
5+
sealed class Holder : IDisposable
6+
{
7+
readonly int[] _buf;
8+
public Holder(int[] buf) => _buf = buf;
9+
public void Dispose() => ArrayPool<int>.Shared.Return(_buf);
10+
}
11+
12+
static class Demo
13+
{
14+
// BUG: the rented buffer is wrapped into a LOCAL Holder that never leaves the method — it is
15+
// dropped (never disposed, never returned, never handed out) — so the buffer is genuinely never
16+
// returned to the pool. A real pooled-buffer leak (OWN001). The wrapper being method-scoped is
17+
// exactly the case the transfer exemption must NOT cover.
18+
public static void Run(int n)
19+
{
20+
var buf = ArrayPool<int>.Shared.Rent(n);
21+
var holder = new Holder(buf); // method-scoped; dropped -> buffer leaks
22+
_ = holder.GetHashCode();
23+
}
24+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// OwnLang model of a rented ArrayPool buffer that (in the fix) is transferred to a wrapper which
2+
// leaves the method through a local — StackExchange.Redis Lease<T>.Create (`var lease = new
3+
// Lease(arr); return lease;`) and RedisServer scan (`var r = new ScanResult(keys); SetResult(m, r)`).
4+
// The before.cs wraps the buffer in a METHOD-SCOPED Holder that is dropped, so the buffer is never
5+
// returned -> a real leak, modelled here as an acquire with no `release` (OWN001). The after.cs
6+
// returns the wrapper, so the extractor follows the transfer through the escaping local and stays
7+
// silent (extractor-level; the before.cs/after.cs benchmark exercises it end to end). See notes.md.
8+
module Corpus
9+
resource Buffer {
10+
acquire rent
11+
release give
12+
emit_type "int[]"
13+
emit_acquire "ArrayPool<int>.Shared.Rent({args})"
14+
emit_release "ArrayPool<int>.Shared.Return({0})"
15+
}
16+
fn Run(n: int) {
17+
let buf = acquire Buffer(n); // ArrayPool.Rent; wrapped in a method-scoped Holder, never returned
18+
// no `release buf;` -> OWN001
19+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
OWN001
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# pool-transfer-via-wrapper-local
2+
3+
A rented `ArrayPool<T>` buffer handed to a **wrapper object bound to a local**, where that local
4+
then **leaves the method** — `var w = new Wrapper(buf); return w;` / `Sink(m, w);` — is an ownership
5+
**transfer** (the wrapper carries the buffer out and is responsible for `Return`), not a leak here.
6+
Generalises the existing direct `return new Wrapper(buf)` / `_field = new Wrapper(buf)` transfer to
7+
the one-extra-hop case an intermediate local introduces.
8+
9+
Mined on **StackExchange.Redis** (2026-07-01 oracle sweep):
10+
11+
- `Lease<T>.Create` — `var arr = ArrayPool<T>.Shared.Rent(length); var lease = new Lease<T>(arr,
12+
length); … return lease;`
13+
- `RedisServer` scan — `keys = ArrayPool<RedisKey>.Shared.Rent(count); … var r = new ScanResult(
14+
cursor, keys, count, true); SetResult(message, r);`
15+
16+
Both were false `OWN001` "rented but never returned" — the buffer is transferred to `Lease`/
17+
`ScanResult`, which owns the `Return`.
18+
19+
- **before.cs** — the buffer is wrapped into a **method-scoped** `Holder` that is dropped (never
20+
disposed / returned / handed out) → the buffer genuinely leaks → `OWN001` (the bug is caught; the
21+
transfer exemption must **not** cover a wrapper that never leaves the method).
22+
- **after.cs** — the `Holder` local is **returned** → the buffer transfers out with it → **clean**.
23+
24+
## Recognition rule
25+
26+
`PassedToEscapingCtor` already exempts a pooled buffer passed to a constructor whose result is the
27+
direct `return` value or is assigned to a real field. `WrapperLocalEscapes` adds the one-extra-hop
28+
case: the `new Wrapper(buf)` is bound to a **local** `w`, and `w` provably leaves the method —
29+
`return w`, `<field> = w`, or `w` handed as a **call argument**. The Codex one-level rule is
30+
preserved for the non-escaping case: a wrapper local that stays method-scoped is a borrow and the
31+
buffer still leaks.
32+
33+
## Honesty caveat
34+
35+
Precision-first, mirroring the direct-transfer rule: we cannot prove the wrapper actually `Return`s
36+
the buffer, so a wrapper that escapes but silently drops the buffer would be a (rare) missed leak.
37+
The `w`-as-call-argument signal is the loosest — a `Sink(w)` that merely reads `w` and drops it would
38+
be exempted — but handing a buffer-owning wrapper to a call is a transfer in idiomatic pooling code,
39+
and erring toward no-false-positive matches the existing transfer stance.

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

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2103,7 +2103,55 @@ static bool PassedToEscapingCtor(IdentifierNameSyntax idn, SemanticModel model)
21032103
{ Parent: BaseObjectCreationExpressionSyntax oce } }
21042104
&& (oce.Parent is ReturnStatementSyntax
21052105
|| (oce.Parent is AssignmentExpressionSyntax a && a.Right == oce
2106-
&& model.GetSymbolInfo(a.Left).Symbol is IFieldSymbol));
2106+
&& model.GetSymbolInfo(a.Left).Symbol is IFieldSymbol)
2107+
// One extra hop: `var w = new Wrapper(…, buf, …); … return w / _field = w / Sink(…, w, …)`.
2108+
// The buffer transfers to the wrapper, which then ESCAPES through the local. Mined FP on
2109+
// StackExchange.Redis (Lease<T>.Create `return new Lease(arr)` via a local; RedisServer scan
2110+
// `new ScanResult(keys)` handed to SetResult). The Codex one-level rule is PRESERVED for the
2111+
// non-escaping case: a wrapper local that never leaves the method (and never Returns the
2112+
// buffer) still leaks — WrapperLocalEscapes returns false there, so it stays flagged.
2113+
|| WrapperLocalEscapes(oce, model));
2114+
2115+
// The object-creation `oce` (`new Wrapper(…, buf, …)`) is bound to a LOCAL that itself provably
2116+
// leaves the enclosing method — `var w = new Wrapper(buf); … return w` / `this._f = w` / `Sink(…,
2117+
// w, …)`. Only then is the buffer an ownership TRANSFER (the wrapper carries it out); a wrapper local
2118+
// that stays method-scoped is a borrow and the buffer still leaks (Codex). Precision-first, mirroring
2119+
// the direct `return new Wrapper(buf)` rule: we cannot prove the wrapper Returns the buffer, but a
2120+
// pooled buffer handed to an escaping owner is a transfer, not a leak here.
2121+
static bool WrapperLocalEscapes(BaseObjectCreationExpressionSyntax oce, SemanticModel model)
2122+
{
2123+
// Bind the `new` to a local symbol: `var w = new …` (declarator) or `w = new …` (local assign).
2124+
ISymbol? w = oce.Parent switch
2125+
{
2126+
EqualsValueClauseSyntax { Parent: VariableDeclaratorSyntax vd } => model.GetDeclaredSymbol(vd),
2127+
AssignmentExpressionSyntax { Right: var r } asg when r == oce
2128+
&& asg.Left is IdentifierNameSyntax lid
2129+
&& model.GetSymbolInfo(lid).Symbol is ILocalSymbol ls => ls,
2130+
_ => null,
2131+
};
2132+
if (w is null)
2133+
return false;
2134+
var method = oce.FirstAncestorOrSelf<BaseMethodDeclarationSyntax>();
2135+
SyntaxNode? body = method?.Body ?? (SyntaxNode?)method?.ExpressionBody;
2136+
if (body is null)
2137+
return false;
2138+
foreach (var id in body.DescendantNodes().OfType<IdentifierNameSyntax>())
2139+
{
2140+
if (!SymbolEqualityComparer.Default.Equals(model.GetSymbolInfo(id).Symbol, w))
2141+
continue;
2142+
// return w;
2143+
if (id.Parent is ReturnStatementSyntax)
2144+
return true;
2145+
// <field> = w; (w on the RHS, LHS a real field — not a look-alike local)
2146+
if (id.Parent is AssignmentExpressionSyntax fa && fa.Right == id
2147+
&& model.GetSymbolInfo(fa.Left).Symbol is IFieldSymbol)
2148+
return true;
2149+
// Sink(…, w, …); — w handed as a call argument (the wrapper, and thus the buffer, leaves)
2150+
if (id.Parent is ArgumentSyntax { Parent: ArgumentListSyntax { Parent: InvocationExpressionSyntax } })
2151+
return true;
2152+
}
2153+
return false;
2154+
}
21072155

21082156
// Is `t` the System.Buffers.MemoryPool<T> type — the Dispose-based pool. Mirrors IsArrayPoolType
21092157
// (checked on the resolved symbol, so an aliased/injected `MemoryPool<T>` receiver binds and a

0 commit comments

Comments
 (0)