Skip to content

Commit 46a7f30

Browse files
PhysShellclaude
andauthored
feat(extractor): borrow checker — pooled-buffer Span view used after Return → OWN002 (POOL002) (#69)
The borrow checker's first bite on real C# (B4 / P-007 POOL002) — lifetime/aliasing analysis, the lever the flat "disposed anywhere?" scanners don't reach. The flat pass and the existing pool flow only caught a use-after-return when the BUFFER LOCAL ITSELF was referenced after Return. When the read goes through a stored Span view — `Span<byte> view = buf.AsSpan(0,n); pool.Return(buf); view[0] = 42;` — the buffer name never appears at the use site, so it looked released-and-untouched: a miss (and a nasty silent aliasing bug, since the array is recycled to another caller). A Span/ReadOnlySpan view of a tracked buffer is now modelled as a BORROW: a reference to the view local lowers to a use of the OWNER (ViewOwnerOf resolves the view through its declaration's initializer). The borrow is recognised by the RESOLVED BCL symbols — System.MemoryExtensions.AsSpan and the System.Span<T>/ReadOnlySpan<T> constructor (via IsInNamespace), not by name, so a project's own AsSpan / a look-alike Span type is not mistaken for a borrow (Codex). A use after Return then trips OWN002. Purely extractor-side: the core needs no borrow concept; it sees a plain use-after-release (facts identical to arraypool-use-after-return). A ref-struct Span cannot escape the method, which is what makes "use of the view = use of the owner, here" sound. Conservative (0 FP): a view of an untracked/escaped buffer, or one used before the Return, adds no finding. Pinned by corpus `arraypool-span-view-after-return` (before → OWN002, after silent), lifting the benchmark recall floor 11 → 12. First slice: Span/ReadOnlySpan via AsSpan() / new Span<T>; Memory<T> (escapable) and view reassignment left for later. ruff + mypy --strict clean, corpus 10/10, ownir 116/116; both extractor + both dog-food jobs green (no new FP). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Rg8kSk1YT14x7A1vo5zgED
1 parent 789255e commit 46a7f30

9 files changed

Lines changed: 161 additions & 10 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -783,9 +783,12 @@ jobs:
783783
# a first-party method that owns a by-value IDisposable param — by disposing it
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
786-
# after the handoff trips OWN002 (the cut is the signature, like Rust's move). Remaining
787-
# backlog: a FIELD-mediated cross-method use-after-dispose (dispose in one method, use in
788-
# another via shared state) and an injected-source region-escape. A drop below the floor
789-
# is a regression.
790-
run: python scripts/benchmark.py --min-recall 11
786+
# 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
791794

‎corpus/real-world/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,5 +43,6 @@ exception-path (анализ не моделирует исключения), co
4343
|------|-----|------------------|
4444
| `arraypool-use-after-return` | OWN002 | rented-буфер вернули в пул, потом ещё читали slice |
4545
| `arraypool-double-return` | OWN003 | один и тот же массив вернули в ArrayPool дважды ([#33767](https://github.com/dotnet/runtime/issues/33767)) |
46+
| `arraypool-span-view-after-return` | OWN002 | `Span`-вью пула (`buf.AsSpan()`) записали ПОСЛЕ `Return` — заём пережил владельца (borrow-checker) |
4647
| `ownership-handoff-use` | OWN002 | поток отдали потребителю (он его закрыл), потом ещё читали — use-after-handoff |
4748
| `ownership-handoff-use-transitive` | OWN002 | то же, но потребитель не закрывает сам, а **пробрасывает** владение дальше (transitive consume) |
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// AFTER (fixed). Finish all work through the Span view BEFORE returning the buffer to the pool, so
2+
// the borrow's lifetime ends before the owner is recycled and nothing aliases freed memory. Same
3+
// view, correct order — the case must stay SILENT (the no-false-positive arm).
4+
using System;
5+
using System.Buffers;
6+
7+
static class PoolSpanViewAfterReturn
8+
{
9+
static void Scramble(int n)
10+
{
11+
byte[] buf = ArrayPool<byte>.Shared.Rent(n);
12+
Span<byte> view = buf.AsSpan(0, n); // view BORROWS buf
13+
view[0] = 42; // written through the view BEFORE return
14+
ArrayPool<byte>.Shared.Return(buf); // returned only after the borrow is done -> silent
15+
}
16+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// BEFORE (buggy). A Span VIEW of a pooled buffer is written THROUGH after the buffer was returned
2+
// to the pool. `buf.AsSpan(..)` borrows the buffer's memory into a `Span<byte>` local; once
3+
// `Return(buf)` recycles the array the pool may hand it to another caller, so writing through the
4+
// view now corrupts someone else's data — a silent, nasty aliasing bug. The view is a ref-struct
5+
// BORROW: a use of it after the owner's release is a use-after-return. Unlike
6+
// `arraypool-use-after-return` (the array itself is read after return), here the read goes through
7+
// a STORED Span view, which the flat pass misses — the borrow has to be resolved to its owner.
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 PoolSpanViewAfterReturn
14+
{
15+
static void Scramble(int n)
16+
{
17+
byte[] buf = ArrayPool<byte>.Shared.Rent(n);
18+
Span<byte> view = buf.AsSpan(0, n); // view BORROWS buf
19+
ArrayPool<byte>.Shared.Return(buf); // buf goes back to the pool (recycled) ...
20+
view[0] = 42; // ... but written through here (use-after-return)
21+
}
22+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// OwnLang model. `acquire` == ArrayPool.Rent, `release` == ArrayPool.Return. The C# stores a Span
2+
// VIEW of the buffer in a local (`Span<byte> view = buf.AsSpan()`) and writes through it AFTER the
3+
// buffer was returned. A Span is a ref-struct BORROW of the buffer that cannot outlive the method,
4+
// so the extractor lowers a use of the view to a use of the OWNER buffer — the write after
5+
// `release` is the generic use-after-return (OWN002), the same code reading the buffer directly
6+
// would give. The borrow is resolved to its owner in the extractor; the core sees a plain
7+
// use-after-release.
8+
module Corpus
9+
resource Buffer {
10+
acquire rent
11+
release give
12+
}
13+
fn scramble(n: int) {
14+
let buf = acquire Buffer(n); // ArrayPool.Rent
15+
release buf; // ArrayPool.Return <-- too early
16+
use buf; // write through the Span view AFTER return -> OWN002
17+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
OWN002
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Pooled-buffer Span VIEW used after return — the borrow checker's first bite
2+
3+
**Pattern:** a rented `ArrayPool<T>` buffer is sliced into a `Span<T>`/`ReadOnlySpan<T>` local
4+
(`Span<byte> view = buf.AsSpan(0, n)`), the buffer is `Return`ed to the pool, and the code then
5+
reads/writes **through the view**. The `Span` borrows the buffer's memory; once the array is
6+
recycled the pool may hand it to another caller, so the view now aliases someone else's data — a
7+
silent corruption (the same family as a use-after-free). It is the use of a **borrow after its
8+
owner was released**.
9+
10+
**What the checker says:** using a resource after it was released is the generic **OWN002**
11+
(use-after-release) — the same code `arraypool-use-after-return` produces when the buffer itself is
12+
read after return.
13+
14+
**Why this case exists (the borrow / B4 frontier).** The flat pass and the existing pool flow only
15+
saw a use-after-return when the **buffer local itself** was referenced after `Return`. When the read
16+
goes through a **stored Span view** (`view[0]`), the buffer name never appears at the use site, so
17+
the buffer looked released-and-untouched — a **miss**. Now the extractor models a
18+
`Span`/`ReadOnlySpan` view of a tracked buffer as a **borrow**: a reference to the view local lowers
19+
to a **use of the owner** (`ViewOwnerOf` resolves the view through its declaration's `AsSpan(..)` /
20+
`new Span<T>(buf)` initializer, the owner confirmed via the SemanticModel). The use after `Return`
21+
then trips OWN002. This is the first slice of the **borrow checker on real C#** — lifetime/aliasing
22+
analysis that the flat "disposed anywhere?" tools (and most general scanners) do not do — kept
23+
purely in the extractor (the core needs no borrow concept; it sees a plain use-after-release).
24+
25+
**Conservative (0 FP).** A view of an untracked/escaped buffer, or a view used **before** the
26+
return (`after.cs`), adds no finding — the borrow only lowers to a use of an owner that is still
27+
tracked, so it can never invent a release. Ref-struct `Span` cannot escape the method, which is
28+
what makes "use of the view = use of the owner, here" sound.
29+
30+
**Honesty / scope.** `case.own` is a faithful hand reduction (the borrow collapses to a use of the
31+
owner, exactly what the extractor emits), not C# the `.own` checker ingested. `before.cs`/`after.cs`
32+
are representative of the bug and its fix. First slice: `Span`/`ReadOnlySpan` views via `AsSpan()` /
33+
`new Span<T>(buf)`; `Memory<T>` (which *can* escape) and view reassignment are deliberately left for
34+
later rounds.

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

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

3-
- **Status:** in progress (P1) — **POOL001 (rented-not-returned) built**;
4-
POOL002–005 (views, escape, double-return) next
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
59
- **Depends on:** `spec/OwnCore.md` (OWN001 leak, OWN002 use-after-release,
610
OWN003 double-release, OWN008 release-while-borrowed), the buffer/borrow model
711
in `spec/`, [P-001](P-001-csharp-extractor.md). See

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

Lines changed: 56 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -760,11 +760,23 @@ static void EmitFlowExpr(ExpressionSyntax expr, HashSet<string> tracked, Semanti
760760
if (tracked.Contains(c))
761761
nodes.Add(new { op = "release", var = c, line = LineOf(expr) });
762762
// any other reference to a tracked local -> use (once per local; a consumed arg is a
763-
// release above, never also a use).
763+
// release above, never also a use). A Span/ReadOnlySpan VIEW of a tracked buffer is a BORROW:
764+
// a reference to the view is a use of the OWNER, so using it after the owner was
765+
// Returned/Disposed trips OWN002 (the ref-struct view cannot outlive the method, so this is a
766+
// genuine use-after-release of the owner — `Span<byte> v = buf.AsSpan(); Return(buf); v[0]=…`).
764767
var used = new SortedSet<string>(StringComparer.Ordinal);
765768
foreach (var idn in expr.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>())
766-
if (tracked.Contains(idn.Identifier.Text) && !consumed.Contains(idn.Identifier.Text))
767-
used.Add(idn.Identifier.Text);
769+
{
770+
var nm = idn.Identifier.Text;
771+
if (tracked.Contains(nm))
772+
{
773+
if (!consumed.Contains(nm))
774+
used.Add(nm);
775+
}
776+
else if (ViewOwnerOf(idn, model) is { } owner
777+
&& tracked.Contains(owner) && !consumed.Contains(owner))
778+
used.Add(owner);
779+
}
768780
foreach (var u in used)
769781
nodes.Add(new { op = "use", var = u, line = LineOf(expr) });
770782
}
@@ -815,6 +827,47 @@ e is InvocationExpressionSyntax i
815827
&& i.ArgumentList.Arguments[0].Expression is IdentifierNameSyntax buf
816828
? buf.Identifier.Text : null;
817829

830+
// The owner buffer a Span/ReadOnlySpan VIEW expression borrows from: `owner.AsSpan(...)` or
831+
// `new Span<T>(owner, …)` / `new ReadOnlySpan<T>(owner)`, where the source is a local identifier.
832+
// Returns the owner local name, else null. The BORROW is recognised by the RESOLVED BCL symbols —
833+
// `System.MemoryExtensions.AsSpan` (which aliases its receiver array) and the `System.Span<T>` /
834+
// `System.ReadOnlySpan<T>` constructor (which wraps its array argument) — NOT by name, so a
835+
// project's own `AsSpan` extension, a non-`System` type named `Span<T>`, or an `AsSpan` returning a
836+
// span over a fresh copy is not mistaken for a borrow of `owner` (Codex). A `Span` is a ref-struct
837+
// borrow that cannot escape the method, so a use of the view after the owner is released is a use of
838+
// the owner after its release.
839+
static string? SpanViewOwner(ExpressionSyntax? e, SemanticModel model)
840+
{
841+
if (e is InvocationExpressionSyntax inv
842+
&& inv.Expression is MemberAccessExpressionSyntax m
843+
&& m.Name.Identifier.Text == "AsSpan"
844+
&& m.Expression is IdentifierNameSyntax recv
845+
&& model.GetSymbolInfo(inv).Symbol is IMethodSymbol { ContainingType: { Name: "MemoryExtensions" } mct }
846+
&& IsInNamespace(mct, "System"))
847+
return recv.Identifier.Text;
848+
if (e is ObjectCreationExpressionSyntax oc
849+
&& oc.ArgumentList is { Arguments.Count: > 0 }
850+
&& oc.ArgumentList.Arguments[0].Expression is IdentifierNameSyntax arg
851+
&& model.GetSymbolInfo(oc).Symbol is IMethodSymbol { ContainingType: { Name: "Span" or "ReadOnlySpan" } sct }
852+
&& IsInNamespace(sct, "System"))
853+
return arg.Identifier.Text;
854+
return null;
855+
}
856+
857+
// If `idn` references a Span/ReadOnlySpan VIEW local declared from an owner buffer
858+
// (`Span<T> view = owner.AsSpan(…)`), the owner buffer's local name — so a use of the view lowers
859+
// to a use of the owner (the borrow). Resolved through the view local's own declaration, so it is
860+
// inert for any identifier that is not such a view (returns null -> ordinary handling).
861+
static string? ViewOwnerOf(IdentifierNameSyntax idn, SemanticModel model)
862+
{
863+
if (model.GetSymbolInfo(idn).Symbol is not ILocalSymbol sym)
864+
return null;
865+
foreach (var r in sym.DeclaringSyntaxReferences)
866+
if (r.GetSyntax() is VariableDeclaratorSyntax { Initializer.Value: { } init })
867+
return SpanViewOwner(init, model);
868+
return null;
869+
}
870+
818871
// A factory call that CREATES and hands back a fresh owned IDisposable the caller must
819872
// release — recognised via the resolved symbol (curated, the same spirit as
820873
// IsDisposableType is for `new`). Two families:

0 commit comments

Comments
 (0)