Skip to content

Commit 6acf93e

Browse files
PhysShellclaude
andauthored
feat(extractor): borrow checker — Memory<T> view that escapes after Return → OWN002 (POOL004) (#70)
The borrow checker's second bite, and the dangerous one the C# compiler does NOT prevent. A `Span` is a ref struct the compiler keeps inside the method; a `Memory<T>` is not — it can be returned or stored in a field, so a `Memory` view of a pooled buffer can leave the method and dangle in the caller's hands after the buffer was recycled (a silent cross-tenant corruption). `ViewOwner` (renamed from SpanViewOwner) now recognises `AsMemory` / `new Memory<T>` / `new ReadOnlyMemory<T>` (and target-typed `new(buf,…)` via BaseObjectCreationExpressionSyntax) alongside the Span forms, resolved via the BCL symbols (System.MemoryExtensions, System.Memory<T> ctor) so a look-alike is not mistaken for a borrow. A reference to a view lowers to a use of the owner, so a view used/returned after Return(buf) trips OWN002. Crucially the ESCAPE is modelled past the finally: a returned view is used by the caller AFTER the method's cleanup, so its owner-use is re-emitted just before the exit of the onReturn chain (`[finally…, exit]`). That catches THE idiomatic form `try { return view; } finally { Return(buf); }` — where the return is evaluated first but the caller receives the view only once the finally has recycled the buffer. `ReturnedViewOwners` follows only the returned value (a view local, an inline view expression, through casts/parens/?:), so `return view.Length` (an int) does not escape — no false positive. Purely extractor-side; the core sees a plain use-after-release. Pinned by corpus `arraypool-memory-view-escape` (try/finally before → OWN002; ToArray-copy after silent), lifting the recall floor 12 → 13 (benchmark: 13/15 caught, 0 FP). A view stored in a FIELD and view reassignment are left for later. ruff + mypy --strict clean, corpus 11/11, ownir 116/116. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Rg8kSk1YT14x7A1vo5zgED
1 parent 46a7f30 commit 6acf93e

9 files changed

Lines changed: 209 additions & 36 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -784,11 +784,12 @@ jobs:
784784
# directly OR by forwarding it to another first-party consumer (the TRANSITIVE chain,
785785
# `ConsumesParam`) — is a handoff that releases the argument at the call site, so a use
786786
# after the handoff trips OWN002 (the cut is the signature, like Rust's move). The BORROW
787-
# checker has its first bite: a `Span`/`ReadOnlySpan` view of a pooled buffer
788-
# (`buf.AsSpan()`) is a ref-struct borrow lowered to a use of the OWNER, so writing through
789-
# the view after `Return(buf)` trips OWN002 (`ViewOwnerOf`). Remaining backlog: a
790-
# FIELD-mediated cross-method use-after-dispose (dispose in one method, use in another via
791-
# shared state), `Memory<T>`/escaping views, and an injected-source region-escape. A drop
792-
# below the floor is a regression.
793-
run: python scripts/benchmark.py --min-recall 12
787+
# checker covers both view kinds: a `Span`/`Memory` view of a pooled buffer (`buf.AsSpan()` /
788+
# `buf.AsMemory()`) is a borrow lowered to a use of the OWNER (`ViewOwner`), so using it
789+
# after `Return(buf)` trips OWN002 — including RETURNING a `Memory<T>` view (which, unlike a
790+
# ref-struct `Span`, can ESCAPE the method), a dangling borrow handed to the caller. Remaining
791+
# backlog: a FIELD-mediated cross-method use-after-dispose (dispose in one method, use in
792+
# another via shared state), a view stored in a FIELD, and an injected-source region-escape.
793+
# A drop below the floor is a regression.
794+
run: python scripts/benchmark.py --min-recall 13
794795

‎corpus/real-world/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,5 +44,6 @@ exception-path (анализ не моделирует исключения), co
4444
| `arraypool-use-after-return` | OWN002 | rented-буфер вернули в пул, потом ещё читали slice |
4545
| `arraypool-double-return` | OWN003 | один и тот же массив вернули в ArrayPool дважды ([#33767](https://github.com/dotnet/runtime/issues/33767)) |
4646
| `arraypool-span-view-after-return` | OWN002 | `Span`-вью пула (`buf.AsSpan()`) записали ПОСЛЕ `Return` — заём пережил владельца (borrow-checker) |
47+
| `arraypool-memory-view-escape` | OWN002 | `Memory`-вью пула вернули наружу (escape) ПОСЛЕ `Return` — dangling-заём ушёл вызывающему (POOL004) |
4748
| `ownership-handoff-use` | OWN002 | поток отдали потребителю (он его закрыл), потом ещё читали — use-after-handoff |
4849
| `ownership-handoff-use-transitive` | OWN002 | то же, но потребитель не закрывает сам, а **пробрасывает** владение дальше (transitive consume) |
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// FIX: copy the data OUT of the pooled buffer and return the COPY — no view of the recycled buffer
2+
// escapes. Same try/finally cleanup, but nothing borrowed leaves the method, so it stays SILENT
3+
// (the no-false-positive arm).
4+
using System;
5+
using System.Buffers;
6+
7+
static class PoolMemoryViewEscape
8+
{
9+
static byte[] Render(int n)
10+
{
11+
byte[] buf = ArrayPool<byte>.Shared.Rent(n);
12+
try
13+
{
14+
return buf.AsSpan(0, n).ToArray(); // copy OUT -> a fresh array escapes, not a view
15+
}
16+
finally
17+
{
18+
ArrayPool<byte>.Shared.Return(buf);
19+
}
20+
}
21+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// A Memory<T> VIEW of a pooled buffer ESCAPES the method — returned from inside a `try` whose
2+
// `finally` returns the buffer to the pool (THE idiomatic ArrayPool cleanup). The `return view`
3+
// expression is evaluated before the finally runs, but the caller receives the `Memory<byte>` only
4+
// AFTER the finally has recycled the buffer — so the caller then reads/writes memory the pool has
5+
// already handed to someone else (a silent cross-tenant corruption). Unlike a `Span` (a ref struct
6+
// the compiler keeps inside the method), a `Memory<T>` CAN leave the method, so the borrow outlives
7+
// its owner: a dangling escape past the finally.
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 PoolMemoryViewEscape
14+
{
15+
static Memory<byte> Render(int n)
16+
{
17+
byte[] buf = ArrayPool<byte>.Shared.Rent(n);
18+
try
19+
{
20+
Memory<byte> view = buf.AsMemory(0, n); // view BORROWS buf
21+
return view; // escapes -> caller gets it AFTER the finally
22+
}
23+
finally
24+
{
25+
ArrayPool<byte>.Shared.Return(buf); // buf recycled here -> returned view dangles (OWN002)
26+
}
27+
}
28+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// OwnLang model. `acquire` == ArrayPool.Rent, `release` == ArrayPool.Return (run by the `finally`).
2+
// The C# returns a Memory<byte> VIEW of the buffer from inside a `try` whose `finally` returns the
3+
// buffer to the pool. A Memory<T> — unlike a ref-struct Span — can leave the method, so the caller
4+
// receives the view AFTER the finally recycled the buffer: a dangling escape. The extractor models
5+
// the escaped view's use AFTER the finally release, so it reduces to a plain use-after-return
6+
// (OWN002), the same code reading the buffer directly after return would give.
7+
module Corpus
8+
resource Buffer {
9+
acquire rent
10+
release give
11+
}
12+
fn render(n: int) {
13+
let buf = acquire Buffer(n); // ArrayPool.Rent
14+
release buf; // ArrayPool.Return <-- the finally, before the caller sees the view
15+
use buf; // the escaped Memory view, used by the caller AFTER the finally -> OWN002
16+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
OWN002
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Pooled-buffer `Memory<T>` view that ESCAPES after return — the borrow checker, second bite
2+
3+
**Pattern:** a rented `ArrayPool<T>` buffer is sliced into a `Memory<T>` local
4+
(`Memory<byte> view = buf.AsMemory(0, n)`) and **returned from inside a `try` whose `finally`
5+
returns the buffer to the pool** — *the* idiomatic ArrayPool cleanup. The `return view` is evaluated
6+
before the finally, but the caller receives the `Memory<byte>` only **after** the finally has
7+
recycled the array, so the borrow **escapes** its owner: the caller holds a view into an array the
8+
pool has already handed to someone else — a silent cross-tenant corruption (read/write of
9+
freed-and-reused memory).
10+
11+
**What the checker says:** the view's escape (the `return`) is a use of the owner after it was
12+
released → the generic **OWN002** (use-after-release), surfaced at the escape site.
13+
14+
**Why this case exists (P-007 POOL004 — view escape).** [`arraypool-span-view-after-return`](../arraypool-span-view-after-return)
15+
caught a `Span` view used after `Return` **inside** the method. But a `Span` is a **ref struct** —
16+
the C# compiler keeps it inside the method, so it cannot escape. A **`Memory<T>` is not a ref
17+
struct**: it *can* be returned or stored in a field, which is the genuinely dangerous escape the
18+
borrow checker must catch. The view recognition (`ViewOwner`) is now extended from `AsSpan` /
19+
`new Span<T>` to **`AsMemory` / `new Memory<T>`** (and the `ReadOnly*` forms), resolved via the same
20+
BCL symbols (`System.MemoryExtensions`, `System.Memory<T>`). Because a reference to the view lowers
21+
to a use of the owner — and `return view` is such a reference — the escape of a dangling view after
22+
`Return(buf)` trips OWN002. Before this slice the `Memory` view was unrecognised, so the dangling
23+
return looked balanced (acquire + release) — a **miss**.
24+
25+
Crucially, the escaped view's use is modelled **after the `finally`**: a returned borrow is used by
26+
the caller *after* the method's cleanup, so the owner-use is re-emitted just before the method exits
27+
the `onReturn` (finally) chain. That is what catches the idiomatic
28+
`try { return view; } finally { Return(buf); }` — where the `return` is evaluated first but the
29+
caller only receives the view once the finally has recycled the buffer (a dangling escape the C#
30+
compiler does **not** prevent for `Memory<T>`).
31+
32+
**Conservative (0 FP).** Only a view of a **tracked** owner that is used/returned **after** the
33+
owner's release fires. The fix (`after.cs`) copies out of the buffer (`AsSpan(..).ToArray()`) and
34+
returns the **copy**, so no view escapes — silent. A view used before the return, or a view of an
35+
untracked buffer, adds no finding; the borrow can never invent a release.
36+
37+
**Honesty / scope.** `case.own` is a faithful hand reduction (the escaping view collapses to a use
38+
of the owner, exactly what the extractor emits), not C# the `.own` checker ingested.
39+
`before.cs`/`after.cs` are representative of the bug and its fix. This slice covers the **return**
40+
escape; storing the view in a **field** (object-level escape) and view **reassignment** are left for
41+
later rounds.

‎docs/proposals/P-007-arraypool-span.md‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
# P-007 — ArrayPool / Span borrow-view profile
22

3-
- **Status:** in progress (P1) — **POOL001 (rented-not-returned) built**; **POOL002
4-
(Span/ReadOnlySpan view used after `Return` → OWN002) first slice built** — a
5-
`buf.AsSpan()` / `new Span<T>(buf)` view is a ref-struct borrow lowered to a use of the
6-
owner (`ViewOwnerOf` in the extractor; corpus `arraypool-span-view-after-return`); the
7-
borrow checker's first bite on real C#. POOL003–005 (double-return via flow already
8-
catches OWN003, `Memory<T>`/escaping views, clear-past-length) next
3+
- **Status:** in progress (P1) — **POOL001 (rented-not-returned) built**; **POOL002 (Span/Memory
4+
view used after `Return` → OWN002) built** and **POOL004 (view ESCAPE) first slice built** — a
5+
`buf.AsSpan()` / `buf.AsMemory()` / `new Span<T>(buf)` view is a borrow lowered to a use of the
6+
owner (`ViewOwner` in the extractor), so using it after `Return` trips OWN002; because a
7+
`Memory<T>` (unlike a ref-struct `Span`) can leave the method, RETURNING a dangling `Memory` view
8+
is caught at the escape (corpus `arraypool-span-view-after-return`, `arraypool-memory-view-escape`).
9+
The borrow checker on real C#. POOL003 (double-return — flow already catches OWN003), a view
10+
stored in a FIELD, and POOL005 (clear-past-length) next
911
- **Depends on:** `spec/OwnCore.md` (OWN001 leak, OWN002 use-after-release,
1012
OWN003 double-release, OWN008 release-while-borrowed), the buffer/borrow model
1113
in `spec/`, [P-001](P-001-csharp-extractor.md). See

0 commit comments

Comments
 (0)