Skip to content

Commit 9230647

Browse files
committed
fix(pool): also catch the using (...) STATEMENT form of the MemoryPool view escape (CodeRabbit)
#74's using-desugar only matched the `using` DECLARATION form (LocalDeclarationStatementSyntax with UsingKeyword). The equivalent `using (IMemoryOwner owner = MemoryPool.Rent(n)) { return owner.Memory; }` STATEMENT form has the same scope-exit dispose, so the returned view dangles the same way — but UsingStatementSyntax only lowered its body and the candidate pass only scanned LocalDeclarationStatementSyntax, so the statement-form owner was untracked and silent. Extend both: the candidate pass now scans UsingStatementSyntax declarations for IsMemoryPoolRent, and the UsingStatementSyntax flow case desugars a tracked MemoryPool owner into `acquire; try { body } finally { release }` exactly like the declaration form. Corpus: memorypool-using-statement-view-escape (-> OWN002; after.cs returns the owner -> silent). Benchmark recall floor 18 -> 19. Not in scope (distinct follow-up, Codex review): `using owner; return owner;` — returning the OWNER itself (not a view) stays silent because the escape pass untracks directly-returned owners as ownership transfers; catching it needs the escape pass to treat a using-owner's direct return as a dangling rather than a transfer. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Rg8kSk1YT14x7A1vo5zgED
1 parent 609fdbd commit 9230647

7 files changed

Lines changed: 121 additions & 3 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -798,5 +798,5 @@ jobs:
798798
# (`ViewOwner`), so reading it after Dispose trips OWN002 (POOL002 — `memorypool-view-after-
799799
# dispose`). Remaining backlog: a FIELD-mediated cross-method use-after-dispose, a view stored in
800800
# a FIELD, and an injected-source region-escape. A drop below the floor is a regression.
801-
run: python scripts/benchmark.py --min-recall 18
801+
run: python scripts/benchmark.py --min-recall 19
802802

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// AFTER (fixed). Ownership is TRANSFERRED to the caller: the method returns the
2+
// `IMemoryOwner<T>` directly (no `using` scope), so nothing is disposed here and the pooled
3+
// buffer stays alive for as long as the caller keeps the owner. No dangling borrow, so the
4+
// checker is silent.
5+
using System;
6+
using System.Buffers;
7+
8+
static class MemoryPoolUsingStatementViewEscape
9+
{
10+
static IMemoryOwner<byte> Borrow(int n)
11+
{
12+
return MemoryPool<byte>.Shared.Rent(n); // transfer ownership — the caller disposes it
13+
}
14+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// BEFORE (buggy). The STATEMENT form of `memorypool-using-view-escape` (POOL004). The
2+
// MemoryPool owner is scoped by a `using (...)` STATEMENT rather than a `using`
3+
// declaration, but the dispose semantics are identical: the owner is `Dispose()`d as the
4+
// block exits, so `return owner.Memory` hands the caller a `Memory<T>` backed by buffer
5+
// already returned to the pool — a dangling borrow. Both `using` syntaxes need the same
6+
// scope-exit desugaring (CodeRabbit review on #74). The fix is to transfer ownership:
7+
// return the `IMemoryOwner` itself (see after.cs).
8+
//
9+
// Wrapped in a class so the extractor's per-class flow pass visits it.
10+
using System;
11+
using System.Buffers;
12+
13+
static class MemoryPoolUsingStatementViewEscape
14+
{
15+
static Memory<byte> Borrow(int n)
16+
{
17+
using (IMemoryOwner<byte> owner = MemoryPool<byte>.Shared.Rent(n))
18+
{
19+
return owner.Memory; // <-- BUG: owner is disposed as the using block exits, so the
20+
// caller reads a view of buffer already back in the pool
21+
}
22+
}
23+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// OwnLang model of the MemoryPool `using`-STATEMENT view escape (the `using (...) { … }`
2+
// form of memorypool-using-view-escape). `acquire` == MemoryPool.Rent, `release` == the
3+
// implicit scope-exit Dispose of the `using` statement. The block returns `owner.Memory`
4+
// — a borrow of the owner — but the `using` disposes the owner FIRST, so the caller reads
5+
// a view of memory already returned to the pool: a use-after-release lowered to OWN002.
6+
// (The `.own` model is the same as the declaration form — the OwnLang reduction does not
7+
// distinguish the two C# `using` syntaxes; the extractor desugars both identically.)
8+
module Corpus
9+
resource MemoryOwner {
10+
acquire Rent
11+
release Dispose
12+
}
13+
fn lease(n: int) {
14+
let owner = acquire MemoryOwner(n); // using (... = MemoryPool.Rent)
15+
release owner; // implicit scope-exit Dispose
16+
use owner; // return owner.Memory — read by the caller AFTER Dispose -> OWN002
17+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
OWN002
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# MemoryPool `using (...)`-statement view escape (POOL004, the statement form)
2+
3+
**Pattern:** identical to `memorypool-using-view-escape`, but the owner is scoped by a
4+
`using (...)` **statement** instead of a `using` **declaration**:
5+
`using (IMemoryOwner<byte> owner = MemoryPool<byte>.Shared.Rent(n)) { return owner.Memory; }`.
6+
Both syntaxes dispose the owner at scope exit, so the returned `Memory<T>` dangles either
7+
way — a use-after-free of pooled memory. The fix is the same: transfer ownership (return the
8+
`IMemoryOwner`).
9+
10+
**Why this case exists (CodeRabbit review on #74):** the `using`-declaration desugaring in
11+
#74 only matched `LocalDeclarationStatementSyntax` with a `using` keyword. The statement
12+
form (`UsingStatementSyntax`) was still lowered as a plain body, so its MemoryPool owner was
13+
neither tracked nor release-threaded — the same dangle, silent. This slice extends the
14+
desugaring (and the flow-locals candidate scan) to the `using (...)` statement form, so a
15+
tracked `using (owner = MemoryPool.Rent(…)) { return owner.Memory; }` is lowered to
16+
`acquire; try { body } finally { release }` exactly like the declaration form → **OWN002**.
17+
18+
**What the checker says:** the OwnLang model and the real `before.cs` both trip **OWN002**.
19+
The ownership-transfer fix in `after.cs` (return the owner directly, no `using`) is silent.
20+
21+
**Honesty / scope.** `case.own` is a faithful hand reduction (not C# ingested by the
22+
checker); `before.cs` / `after.cs` are representative of the bug and its fix. (Returning the
23+
owner itself from a `using` scope — `using owner; return owner;` — is a distinct, follow-up
24+
gap: the escape pass untracks directly-returned owners as ownership transfers.)
25+
26+
Reference: [P-007](../../../docs/proposals/P-007-arraypool-span.md); the declaration form is
27+
`memorypool-using-view-escape`.

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

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -524,9 +524,37 @@ or ImplicitObjectCreationExpressionSyntax
524524
return true;
525525
}
526526
case UsingStatementSyntax us:
527-
// using(...) {body}: the using local is auto-disposed (untracked); still
528-
// lower the body so a tracked plain local used inside is seen.
527+
{
528+
// using (IMemoryOwner owner = MemoryPool.Rent(...)) { body }: the STATEMENT form of the same
529+
// scope-exit dispose as the `using` declaration — desugar a tracked MemoryPool owner the same
530+
// way (acquire; thread the dispose onto the body's returns/throws; release on completion) so a
531+
// returned view of it dangles -> OWN002 (CodeRabbit). Other using-statements just lower the
532+
// body (the using local is auto-disposed, untracked).
533+
if (us.Declaration is { Variables.Count: 1 } ud
534+
&& tracked.Contains(ud.Variables[0].Identifier.Text)
535+
&& IsMemoryPoolRent(ud.Variables[0].Initializer?.Value, model))
536+
{
537+
var uv = ud.Variables[0];
538+
var owner = uv.Identifier.Text;
539+
var exit = new List<object> { new { op = "return", var = (string?)null, line = LineOf(us) } };
540+
nodes.Add(new { op = "acquire", var = owner, line = LineOf(uv) });
541+
var release = new { op = "release", var = owner, line = LineOf(uv) };
542+
var bodyOnReturn = new List<object> { release };
543+
bodyOnReturn.AddRange(onReturn ?? exit);
544+
List<object>? bodyOnThrow = null;
545+
if (canEscape)
546+
{
547+
bodyOnThrow = new List<object> { release };
548+
bodyOnThrow.AddRange(onThrow ?? exit);
549+
}
550+
if (us.Statement is not null
551+
&& !LowerFlowStmt(us.Statement, tracked, model, nodes, canEscape, bodyOnThrow, bodyOnReturn))
552+
return false;
553+
nodes.Add(release); // normal completion disposes at scope exit too
554+
return true;
555+
}
529556
return us.Statement is null || LowerFlowStmt(us.Statement, tracked, model, nodes, canEscape, onThrow, onReturn);
557+
}
530558
case ReturnStatementSyntax rs:
531559
{
532560
// A tracked local READ in the return value is a use at the return point —
@@ -2008,6 +2036,14 @@ or ImplicitObjectCreationExpressionSyntax } init
20082036
else if (IsMemoryPoolRent(v.Initializer?.Value, model)) // MemoryPool<T> IMemoryOwner (Dispose-released, NOT a poolBuffer)
20092037
candidates.Add(v.Identifier.Text);
20102038
}
2039+
// `using (IMemoryOwner owner = MemoryPool.Rent(...)) { … }` STATEMENT form: track the owner
2040+
// too, so its returned view dangles after the scope-exit dispose (the desugar mirrors the
2041+
// `using` DECLARATION form handled in the loop above).
2042+
foreach (var us in mbody.DescendantNodes().OfType<UsingStatementSyntax>())
2043+
if (us.Declaration is { } usd)
2044+
foreach (var v in usd.Variables)
2045+
if (IsMemoryPoolRent(v.Initializer?.Value, model))
2046+
candidates.Add(v.Identifier.Text);
20112047
if (candidates.Count == 0)
20122048
continue;
20132049
// A local that escapes (returned / assigned out) is conservatively not

0 commit comments

Comments
 (0)