Skip to content

Commit 5291fa9

Browse files
committed
feat(extractor): emit fresh-returning factory facts for D5.2 (real-C# interprocedural leaks)
Wire the Roslyn extractor (--flow-locals) to produce the OwnIR the D5.2 fresh-return machinery consumes, so first-party factory leaks are caught on real C# (not just synthetic unit tests): - A new'd IDisposable returned BARE outside a try stays tracked and lowers to acquire + return <var>, so the core classifies the method returnsOwned: fresh (the return discharges it -> the factory itself stays silent). A return inside a try, or a using/pool/owning-factory local, keeps its existing behaviour. - var r = FirstPartyFactory() (a source-visible method returning an owned IDisposable) emits a new call callee=... result=r op. The core mints the acquire only when it proves the callee fresh, so a non-fresh first-party call is never falsely owned. IsFirstPartyDisposableFactory gates on source-declared, non-void, disposable, non-dispose-optional return; overloads resolve to unknown (silent). Adds FactoryLeakSample.cs + a CI assertion: a dropped factory result leaks interprocedurally (OWN001 at the call site), the disposed caller and the factory stay silent. Bridge side already proven by the D5.2 unit tests; this closes the extractor gap so the capability fires on real code. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Fmwk5ruExKy5fQ77CJ2NtF
1 parent 1b82c24 commit 5291fa9

4 files changed

Lines changed: 118 additions & 7 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -642,7 +642,8 @@ jobs:
642642
# detector cannot catch (use-after-dispose, double-dispose, leak-on-path).
643643
dotnet run --project frontend/roslyn/OwnSharp.Extractor -- \
644644
frontend/roslyn/samples/FlowLocalsSample.cs \
645-
frontend/roslyn/samples/MemoryOwnerEscapeSample.cs --flow-locals -o "$RUNNER_TEMP/flow.json"
645+
frontend/roslyn/samples/MemoryOwnerEscapeSample.cs \
646+
frontend/roslyn/samples/FactoryLeakSample.cs --flow-locals -o "$RUNNER_TEMP/flow.json"
646647
out=$(python -m ownlang ownir "$RUNNER_TEMP/flow.json" || true)
647648
echo "$out"
648649
echo "$out" | grep -q "OWN002" || { echo "FAIL: expected OWN002 (use-after-dispose)"; exit 1; }
@@ -821,6 +822,16 @@ jobs:
821822
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 handedOwner tdClean vtc tif; do
822823
if echo "$out" | grep -q "'$ok'"; then echo "FAIL: silent/exempt case '$ok' was reported"; exit 1; fi
823824
done
825+
# P-005 D5.2 INTERPROCEDURAL fresh-returning factory (FactoryLeakSample.cs): the core
826+
# infers `StreamFactory.Make` returns `fresh` (its `acquire; return <var>` body), so a
827+
# caller that binds the result and drops it leaks at the CALL SITE — a finding the flat,
828+
# intra-procedural detectors cannot see. The disposed caller and the factory itself stay
829+
# silent (the factory transfers ownership out via its return).
830+
echo "$out" | grep -qE "OWN001.*'factoryLeak'" \
831+
|| { echo "FAIL: expected the interprocedural OWN001 on the dropped factory result"; exit 1; }
832+
for ok in factoryOk made; do
833+
if echo "$out" | grep -q "'$ok'"; then echo "FAIL: D5.2 silent case '$ok' was reported"; exit 1; fi
834+
done
824835
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)"
825836
- name: Opt-in body-throw-edges tier (--body-throw-edges, P-016 throw firehose)
826837
run: |

‎docs/notes/d5-ownership-transfer.md‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -294,9 +294,19 @@ escape-without-transfer and all `unknown`/`may` lower to **silence** in the defa
294294
never `fresh` (that is wrap/alias, T4/D5.4), and a non-fresh / unknown return makes no claim —
295295
the result is never falsely owned. Proven by synthetic OwnIR tests: factory-result leak
296296
(OWN001 @ the call), disposed-clean, use-after-dispose (OWN002), forward-return propagation,
297-
and the param-return precision guard. **Remaining T1 door:** `out`/`ref`-owned parameters
298-
(another `fresh` source) — extractor-side recognition of an out-assignment as a fresh acquire
299-
— rides into a later slice before async.
297+
and the param-return precision guard. **Extractor emission (shipped).** The Roslyn extractor
298+
now produces the facts that drive this on real C# (`--flow-locals`): a `new`'d local returned
299+
bare outside a `try` stays tracked and emits `acquire …; return <var>` (so a first-party
300+
factory is classified `fresh`), and `var r = FirstPartyFactory()` — a call to a source-visible
301+
method returning an owned `IDisposable` — emits a `call callee=… result=r` op (the core mints
302+
the acquire only when it proves the callee `fresh`, so a non-fresh call is never falsely owned).
303+
`IsFirstPartyDisposableFactory` gates on a source-declared, non-void, disposable, non-dispose-
304+
optional return; overloads (non-unique names) resolve to `unknown` and stay silent. Validated
305+
end-to-end by `FactoryLeakSample.cs` in CI: a dropped factory result leaks **interprocedurally**
306+
(OWN001 at the call site — beyond the flat detectors), while the disposed caller and the factory
307+
itself stay silent. **Remaining T1 door:** `out`/`ref`-owned parameters (another `fresh` source)
308+
— extractor-side recognition of an out-assignment as a fresh acquire — rides into a later slice
309+
before async.
300310
- **Bridge branch-scope fix (shipped — separate from the D5 transfer ladder).** The OwnIR→core
301311
bridge uses a *flat* `localmap` but emitted each synthetic `Let` *inside* the branch block it
302312
occurred in, so a local `acquire`d in **both** branches of an `if` and released **after** the

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

Lines changed: 58 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -560,6 +560,28 @@ oce.ArgumentList is { } args
560560
_ => "?",
561561
};
562562

563+
// P-005 D5.2: a FIRST-PARTY method call whose result is an owned IDisposable — the
564+
// caller side of a fresh-returning factory. Because the callee is defined in source (not
565+
// the BCL), the core can see its body and infer whether it returns `fresh`; if so, a
566+
// `var r = Factory()` binding is an acquire and a caller that drops `r` leaks. The emitted
567+
// `callee` matches the `functions[]` key `{TypeName}.{MethodName}`. A null/extern symbol,
568+
// a void/non-disposable return, or a dispose-optional return is rejected (no claim); an
569+
// overload (non-unique name) resolves to `unknown` in the core and is silently safe.
570+
static bool IsFirstPartyDisposableFactory(ExpressionSyntax? expr, SemanticModel model, out string callee)
571+
{
572+
callee = "";
573+
if (expr is not InvocationExpressionSyntax inv)
574+
return false;
575+
if (model.GetSymbolInfo(inv).Symbol is not IMethodSymbol m)
576+
return false;
577+
if (m.ReturnsVoid || m.DeclaringSyntaxReferences.Length == 0)
578+
return false; // void, or not first-party (no visible body to infer `fresh` from)
579+
if (!ImplementsIDisposable(m.ReturnType) || IsDisposeOptional(m.ReturnType))
580+
return false;
581+
callee = $"{m.ContainingType.Name}.{m.Name}";
582+
return true;
583+
}
584+
563585
// A `Dispose()`/`Close()`/`DisposeAsync()` call — through member access (`x.Dispose()`)
564586
// or member binding (`x?.Dispose()`), and seen through a trailing `.ConfigureAwait(false)`
565587
// (the idiomatic `await x.DisposeAsync().ConfigureAwait(false)` is the release, not a
@@ -758,6 +780,13 @@ or ImplicitObjectCreationExpressionSyntax
758780
// — the flow path previously mislabelled a pool buffer leaked on a throw edge.
759781
nodes.Add(new { op = "acquire", var = v.Identifier.Text, line = LineOf(v),
760782
kind = IsPoolRent(v.Initializer?.Value, model) ? "pool" : "disposable" });
783+
// P-005 D5.2: `var r = FirstPartyFactory()` — emit a `call` op (NOT an
784+
// acquire); the core mints the acquire only if it proves the callee returns
785+
// `fresh`, so a non-fresh first-party call is never falsely owned.
786+
else if (tracked.Contains(v.Identifier.Text)
787+
&& IsFirstPartyDisposableFactory(v.Initializer?.Value, model, out var fpCallee))
788+
nodes.Add(new { op = "call", callee = fpCallee, args = Array.Empty<string>(),
789+
result = v.Identifier.Text, line = LineOf(v) });
761790
// POOL005: a full-length view in the initializer — `var copy = buf.AsSpan().ToArray();`
762791
// — over-reads the pooled tail just as `Emit(buf.AsSpan());` does. EmitFlowExpr is not
763792
// called on a non-acquire initializer, so scan it here for the overspan (Codex review).
@@ -849,7 +878,16 @@ or ImplicitObjectCreationExpressionSyntax
849878
nodes.AddRange(chain);
850879
}
851880
else
852-
nodes.Add(new { op = "return", var = (string?)null, line = LineOf(rs) });
881+
{
882+
// P-005 D5.2: a tracked local returned BARE (outside any `finally`) is a
883+
// fresh-factory transfer — emit it as the return's `var` so the core models the
884+
// escape (a discharge: ownership moves to the caller) and classifies the method
885+
// `returnsOwned: fresh`. A non-identifier / non-tracked return is a bare CFG exit.
886+
var rvar = rs.Expression is IdentifierNameSyntax rid
887+
&& tracked.Contains(rid.Identifier.Text)
888+
? rid.Identifier.Text : (string?)null;
889+
nodes.Add(new { op = "return", var = rvar, line = LineOf(rs) });
890+
}
853891
return true;
854892
}
855893
case WhileStatementSyntax ws:
@@ -3181,6 +3219,12 @@ or ImplicitObjectCreationExpressionSyntax } init
31813219
candidates.Add(v.Identifier.Text);
31823220
else if (IsMemoryPoolRent(v.Initializer?.Value, model)) // MemoryPool<T> IMemoryOwner (Dispose-released, NOT a poolBuffer)
31833221
candidates.Add(v.Identifier.Text);
3222+
else if (IsFirstPartyDisposableFactory(v.Initializer?.Value, model, out _))
3223+
// P-005 D5.2: `var r = FirstPartyFactory()` — a candidate acquire
3224+
// IFF the core proves the callee returns `fresh` (it emits a `call`
3225+
// op, not an `acquire`; the core decides). Checked last so `new` /
3226+
// pool / BCL-factory initializers keep their existing classification.
3227+
candidates.Add(v.Identifier.Text);
31843228
}
31853229
// `using (IMemoryOwner owner = MemoryPool.Rent(...)) { … }` STATEMENT form: track the owner
31863230
// too, so its returned view dangles after the scope-exit dispose (the desugar mirrors the
@@ -3254,9 +3298,20 @@ or ImplicitObjectCreationExpressionSyntax } init
32543298
// use of the returned owner trips OWN002 — the bare-owner twin of the returned-view
32553299
// dangle. A NON-using returned owner stays a genuine transfer (escaped → untracked →
32563300
// silent), so this never fires on `var o = Rent(); return o;`.
3257-
if (idn.Parent is ReturnStatementSyntax)
3301+
if (idn.Parent is ReturnStatementSyntax rsp)
32583302
{
3259-
if (!usingMemoryOwners.Contains(nm))
3303+
// P-005 D5.2: a `new`'d IDisposable returned BARE outside any `try` is a
3304+
// fresh-returning FACTORY — keep it tracked so the flow body emits
3305+
// `acquire …; return <var>`. The core then classifies the method
3306+
// `returnsOwned: fresh` (and the `return <var>` discharges it, so the
3307+
// factory itself stays silent), letting a caller that drops the result
3308+
// leak. A return INSIDE a try threads `finally` edges the fresh path does
3309+
// not model yet, so keep the old transfer (escape) there; a `using` owner
3310+
// also stays tracked (its scope-exit dispose dangles the returned value).
3311+
var freshFactory = newedDisposables.Contains(nm)
3312+
&& !rsp.Ancestors().TakeWhile(a => a != mbody)
3313+
.OfType<TryStatementSyntax>().Any();
3314+
if (!usingMemoryOwners.Contains(nm) && !freshFactory)
32603315
escapedLocals.Add(nm);
32613316
}
32623317
// A pooled buffer handed as an argument is normally a BORROW (the renter Returns it),
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
using System.IO;
2+
3+
namespace Factories;
4+
5+
// P-005 D5.2: a fresh-returning factory + its callers. The factory `Make` creates and
6+
// hands back a NEW owned stream; the core infers `returnsOwned: fresh` from its
7+
// `acquire; return <var>` body. A caller that binds the result and drops it (`Leaks`)
8+
// is then charged the leak at the call site — an INTERPROCEDURAL finding the flat,
9+
// intra-procedural detectors cannot see. A caller that disposes the result (`Clean`)
10+
// stays silent, and the factory itself stays silent (it transfers ownership out).
11+
public static class StreamFactory
12+
{
13+
public static Stream Make()
14+
{
15+
var made = new MemoryStream(); // freshly owned, handed to the caller
16+
return made;
17+
}
18+
}
19+
20+
public static class FactoryConsumers
21+
{
22+
// Drops the fresh factory result without disposing -> OWN001 at the call site.
23+
public static void Leaks()
24+
{
25+
var factoryLeak = StreamFactory.Make();
26+
factoryLeak.WriteByte(1);
27+
}
28+
29+
// Disposes the fresh factory result -> clean (silent).
30+
public static void Clean()
31+
{
32+
var factoryOk = StreamFactory.Make();
33+
factoryOk.Dispose();
34+
}
35+
}

0 commit comments

Comments
 (0)