Skip to content

Commit 735d59f

Browse files
committed
fix(extractor): a pooled buffer passed to an escaping constructor is an ownership transfer, not a leak (mined FP)
Second false positive from mining Pipelines.Sockets.Unofficial: ArrayPoolBufferWriter.CreateNewSegment does `var array = pool.Rent(size); return new ArrayPoolRefCountedSegment(pool, array, prev);`. The flow-locals escape analysis treats a pooled buffer passed as an argument as a BORROW (so `pool.Return(buf); Work(buf)` still trips use-after-return) and expects a same-method Return — missing that the buffer's ownership is TRANSFERRED to the constructed object (which Returns it on its own teardown) and leaves the method inside that returned object. Result: a false OWN001 "never disposed/returned". New PassedToEscapingCtor: a pooled buffer handed to a `new` whose result is the direct return value or a field-assignment RHS escapes (untracked), like a returned local. One level only — a `new` buried in a local or another expression stays a borrow (an honest limitation). Purely syntactic, so it holds for unresolved wrapper types. Only the --flow-locals path is affected (the syntactic D1 path already escapes all arg-passed locals); a plain borrow `Work(buf)` still leaks if unreturned. Regression guard: FlowLocalsSample.PooledIntoReturnedCtor (`ctorMoved` handed to a returned PooledHolder) added to the --flow-locals job's must-stay-silent list. No corpus case has this shape, so the recall floor is unchanged. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Rg8kSk1YT14x7A1vo5zgED
1 parent 70376da commit 735d59f

3 files changed

Lines changed: 48 additions & 2 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -510,7 +510,10 @@ jobs:
510510
# case disposes (no default) -> last case is the tail, no phantom no-match leak.
511511
# `ncf`: `ncf?.Dispose()` (null-conditional) in a threaded finally IS a release
512512
# (member-binding form), so it is disposed on the return path -> silent (Codex review).
513-
for ok in clean looped esc exemptTask whileClean asyncDisposed asyncDisposedCfg tfClean tfCatch tfRet tfNull cda daci cif ctorLater lamPrior other doClean swAll ncf captured shaClean stopped defer; do
513+
# `ctorMoved`: a pooled buffer handed to a constructor whose result is RETURNED transfers
514+
# ownership to the returned wrapper -> escaped -> silent (mined FP on
515+
# Pipelines.Sockets.Unofficial: ArrayPoolBufferWriter.CreateNewSegment).
516+
for ok in clean looped esc exemptTask whileClean asyncDisposed asyncDisposedCfg tfClean tfCatch tfRet tfNull cda daci cif ctorLater lamPrior other doClean swAll ncf captured shaClean stopped defer ctorMoved; do
514517
if echo "$out" | grep -q "'$ok'"; then echo "FAIL: silent/exempt case '$ok' was reported"; exit 1; fi
515518
done
516519
echo "OK: flow-sensitive OWN001/002/003 on real C# (path-sensitive, loops via while/foreach/for, try/finally sequential, never-vs-every-path wording, dispose-optional exempt, beyond flat)"

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

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1037,6 +1037,19 @@ e is InvocationExpressionSyntax i
10371037
&& i.ArgumentList.Arguments[0].Expression is IdentifierNameSyntax buf
10381038
? buf.Identifier.Text : null;
10391039

1040+
// Is `idn` a pooled buffer passed as an argument to a CONSTRUCTOR whose result ESCAPES this method —
1041+
// `return new Wrapper(…, buf, …)` or `_field = new Wrapper(…, buf, …)`? Such a `new` hands the buffer
1042+
// to the constructed object, which becomes responsible for Return, so the buffer leaves the method
1043+
// inside the escaping object (an ownership transfer, not a borrow). One level only: the `new` must be
1044+
// the direct return value or a field-assignment RHS (a `new` buried in a local or another expression
1045+
// stays a borrow — an honest limitation). Purely syntactic, so it holds even when the wrapper type
1046+
// does not resolve.
1047+
static bool PassedToEscapingCtor(IdentifierNameSyntax idn) =>
1048+
idn.Parent is ArgumentSyntax { Parent: ArgumentListSyntax
1049+
{ Parent: BaseObjectCreationExpressionSyntax oce } }
1050+
&& (oce.Parent is ReturnStatementSyntax
1051+
|| (oce.Parent is AssignmentExpressionSyntax a && a.Right == oce && FieldName(a.Left) is not null));
1052+
10401053
// Is `t` the System.Buffers.MemoryPool<T> type — the Dispose-based pool. Mirrors IsArrayPoolType
10411054
// (checked on the resolved symbol, so an aliased/injected `MemoryPool<T>` receiver binds and a
10421055
// look-alike does not).
@@ -2394,8 +2407,16 @@ or ImplicitObjectCreationExpressionSyntax } init
23942407
if (!usingMemoryOwners.Contains(nm))
23952408
escapedLocals.Add(nm);
23962409
}
2410+
// A pooled buffer handed as an argument is normally a BORROW (the renter Returns it),
2411+
// NOT an escape — so `pool.Return(buf); Work(buf)` still trips use-after-return. But a
2412+
// pooled buffer passed to a CONSTRUCTOR whose result ESCAPES this method (`return new
2413+
// Wrapper(buf)` / `_field = new Wrapper(buf)`) transfers ownership to that object, which
2414+
// becomes responsible for Return — so the buffer is NOT leaked here. Treat that as an
2415+
// escape (mined FP on Pipelines.Sockets.Unofficial: ArrayPoolBufferWriter.CreateNewSegment
2416+
// returns `new ArrayPoolRefCountedSegment(pool, array, prev)`).
23972417
else if ((idn.Parent is AssignmentExpressionSyntax asg && asg.Right == idn)
2398-
|| (idn.Parent is ArgumentSyntax && !poolBuffers.Contains(nm) && !consumedArg))
2418+
|| (idn.Parent is ArgumentSyntax && !poolBuffers.Contains(nm) && !consumedArg)
2419+
|| (poolBuffers.Contains(nm) && PassedToEscapingCtor(idn)))
23992420
escapedLocals.Add(nm);
24002421
}
24012422
var tracked = new HashSet<string>(candidates);

‎frontend/roslyn/samples/FlowLocalsSample.cs‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System;
2+
using System.Buffers;
23
using System.Collections.Generic;
34
using System.IO;
45
using System.Net;
@@ -504,6 +505,27 @@ public void DeferredHandoffNoFalsePositive()
504505
defer.WriteByte(1); // must NOT trip OWN002 (it would, without the fix)
505506
defer.Dispose(); // disposed here -> balanced -> silent
506507
}
508+
509+
// NOT a leak (mined FP on Pipelines.Sockets.Unofficial — ArrayPoolBufferWriter.CreateNewSegment):
510+
// a pooled buffer handed to a constructor whose result is RETURNED transfers ownership to the
511+
// returned wrapper (which Returns the buffer on its own teardown), so this method does not leak it
512+
// even though it never calls Return -> silent ('ctorMoved'). A plain borrow `Work(buf)` still
513+
// leaks if not returned, so this is specifically the escaping-constructor transfer.
514+
public PooledHolder PooledIntoReturnedCtor(int n)
515+
{
516+
var ctorMoved = ArrayPool<byte>.Shared.Rent(n);
517+
return new PooledHolder(ctorMoved);
518+
}
519+
}
520+
521+
// Takes ownership of a pooled buffer (Returns it on teardown) — the wrapper that
522+
// PooledIntoReturnedCtor hands its rented buffer to. Models the ownership transfer through a
523+
// constructor argument that the escape analysis must recognise.
524+
internal sealed class PooledHolder
525+
{
526+
private readonly byte[] _buffer;
527+
public PooledHolder(byte[] buffer) => _buffer = buffer;
528+
public void Release() => ArrayPool<byte>.Shared.Return(_buffer);
507529
}
508530

509531
// A domain exception type literally named `Exception`, in a non-System namespace — the

0 commit comments

Comments
 (0)