Skip to content

Commit 19d35d9

Browse files
authored
Merge pull request #88 from PhysShell/claude/fp-appdomain-shutdown-events
fix(extractor): exempt process-host AppDomain event subscriptions from OWN014 (mined Npgsql)
2 parents 78c234b + 63b0bc5 commit 19d35d9

3 files changed

Lines changed: 133 additions & 1 deletion

File tree

‎.github/workflows/ci.yml‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,7 @@ jobs:
142142
frontend/roslyn/samples/ResolvedDisposableSample.cs \
143143
frontend/roslyn/samples/FieldReleaseSample.cs \
144144
frontend/roslyn/samples/StaticClassEscapeSample.cs \
145+
frontend/roslyn/samples/AppDomainShutdownSample.cs \
145146
-o "$RUNNER_TEMP/facts.json"
146147
cat "$RUNNER_TEMP/facts.json"
147148
- name: Check facts through the core
@@ -317,6 +318,20 @@ jobs:
317318
|| { echo "FAIL: expected OWN014 region escape on the static-event instance subscription"; exit 1; }
318319
echo "$out" | grep -q "region escape" \
319320
|| { echo "FAIL: expected the region-escape wording on the static-event capture"; exit 1; }
321+
# P-004 process-lifetime AppDomain-event exemption (mined: Npgsql PoolManager): a
322+
# NON-CAPTURING handler on a process-host AppDomain event (ProcessExit/DomainUnload/
323+
# UnhandledException/FirstChanceException) is a shutdown/diagnostics hook meant to live
324+
# for the process -> NOT a region escape -> silent. (Scoped to ShutdownCleanup, the
325+
# exempt class — CapturingShutdownSubscriber in the same file MUST still raise OWN014.)
326+
if echo "$out" | grep -qE "OWN014.*'ShutdownCleanup'"; then
327+
echo "FAIL: ShutdownCleanup's non-capturing AppDomain subscriptions were wrongly reported as OWN014"; exit 1
328+
fi
329+
# scope guards: a lambda on a NON-AppDomain static event still escapes; and an AppDomain
330+
# handler that CAPTURES instance state is still pinned to the process -> still OWN014 (Codex).
331+
echo "$out" | grep -qE "OWN014.*NonAppDomainSubscriber" \
332+
|| { echo "FAIL: a lambda on a non-AppDomain static event must still raise OWN014 (exemption stays scoped)"; exit 1; }
333+
echo "$out" | grep -qE "OWN014.*CapturingShutdownSubscriber" \
334+
|| { echo "FAIL: an instance-capturing AppDomain handler must still raise OWN014 (exemption is non-capturing only)"; exit 1; }
320335
# the unsubscribed variant (a matching `-=`, released capture) is mitigated
321336
# -> silent. Must NOT be reported.
322337
if echo "$out" | grep -q "CleanStaticEventViewModel"; then

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

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,61 @@ static bool IsStaticHandler(ExpressionSyntax right, SemanticModel model)
203203
return cands.Length > 0 && cands.All(c => c is IMethodSymbol { IsStatic: true });
204204
}
205205

206+
// P-004 process-lifetime exemption: a subscription to a PROCESS-HOST `System.AppDomain`
207+
// event — ProcessExit / DomainUnload (shutdown cleanup hooks) or UnhandledException /
208+
// FirstChanceException (process-wide diagnostics) — is never a region escape. The handler
209+
// is MEANT to live for the whole process: it runs at shutdown, or on every unhandled throw,
210+
// and the AppDomain IS the process host. Promoting the subscriber to "the AppDomain's
211+
// lifetime" is therefore the intent, not a leak. Mined: Npgsql's PoolManager static ctor
212+
// `AppDomain.CurrentDomain.{DomainUnload,ProcessExit} += (_,_) => ClearAll()` — a deliberate
213+
// "close idle connectors on appdomain unload (web-app redeployment)" hook (#491).
214+
static bool IsProcessLifetimeAppDomainEvent(IEventSymbol ev) =>
215+
ev.Name is "ProcessExit" or "DomainUnload" or "UnhandledException" or "FirstChanceException"
216+
&& ev.ContainingType is { Name: "AppDomain" } ct
217+
&& IsInNamespace(ct, "System");
218+
219+
// Does this handler retain NO subscriber instance? A static method group has a null delegate
220+
// target; a lambda / anonymous method retains nothing only when it captures neither `this`
221+
// (explicit, or implicit via an instance member) nor an enclosing local/parameter. Keeps the
222+
// AppDomain process-lifetime exemption sound — a CAPTURING handler is still pinned to the
223+
// process until shutdown and stays OWN014 (Codex); only a non-capturing one (Npgsql's
224+
// `(_,_) => ClearAll()`, a static call) is safe to drop.
225+
static bool HandlerRetainsNoInstance(ExpressionSyntax right, SemanticModel model)
226+
{
227+
if (IsStaticHandler(right, model))
228+
return true;
229+
if (right is not AnonymousFunctionExpressionSyntax lambda)
230+
return false; // a delegate-typed value is opaque -> conservatively assume it captures
231+
foreach (var node in lambda.DescendantNodes())
232+
{
233+
if (node is ThisExpressionSyntax or BaseExpressionSyntax)
234+
return false;
235+
if (node is not IdentifierNameSyntax id
236+
|| (id.Parent is MemberAccessExpressionSyntax m && m.Name == id)) // `x.Member`: name resolved via x
237+
continue;
238+
var sym = model.GetSymbolInfo(id).Symbol;
239+
if (sym is IFieldSymbol { IsStatic: false } or IPropertySymbol { IsStatic: false }
240+
or IEventSymbol { IsStatic: false }
241+
or IMethodSymbol { IsStatic: false, MethodKind: MethodKind.Ordinary })
242+
return false; // an instance member by SIMPLE name -> implicit `this` capture
243+
if (sym is ILocalSymbol or IParameterSymbol && !DeclaredWithin(sym, lambda))
244+
return false; // an enclosing local / parameter -> captured
245+
}
246+
return true;
247+
}
248+
249+
// Is EVERY declaration of `sym` inside `scope`? A lambda's own parameters/locals are; an
250+
// enclosing local/parameter is not — so a reference to the latter is a capture.
251+
static bool DeclaredWithin(ISymbol sym, SyntaxNode scope)
252+
{
253+
if (sym.DeclaringSyntaxReferences.Length == 0)
254+
return false;
255+
foreach (var r in sym.DeclaringSyntaxReferences)
256+
if (!scope.FullSpan.Contains(r.Span))
257+
return false;
258+
return true;
259+
}
260+
206261
// P-004 process-lived-subscriber exemption: the WPF application object (`App`) is a
207262
// process-lived singleton — exactly one instance, created at startup, alive until
208263
// the process exits. Subscribing it to a process-lived static event
@@ -2078,8 +2133,16 @@ or ImplicitObjectCreationExpressionSyntax
20782133
// constructs) — the source<->this cycle is GC-collectable;
20792134
// - static handler — a static method has a null delegate target,
20802135
// so no instance is retained and nothing can leak.
2136+
// - a process-host AppDomain event (ProcessExit/DomainUnload/Unhandled-
2137+
// Exception/FirstChanceException) whose handler retains NO instance — the
2138+
// handler is meant to live for the whole process, so the "escape" is the
2139+
// intent, not a leak (mined: Npgsql PoolManager's `AppDomain.CurrentDomain.
2140+
// ProcessExit += (_,_) => ClearAll()` shutdown hook). A handler that captures
2141+
// instance state still pins it to the process, so it stays OWN014 (Codex).
20812142
if (!isTimer && (IsSelfOwnedSource(a.Left, ev, model, selfOwned)
2082-
|| IsStaticHandler(a.Right, model)))
2143+
|| IsStaticHandler(a.Right, model)
2144+
|| (IsProcessLifetimeAppDomainEvent(ev)
2145+
&& HandlerRetainsNoInstance(a.Right, model))))
20832146
continue;
20842147
// P-004 tiering: a local-variable source is method-bounded — it
20852148
// cannot outlive `this`, so it is not a heap leak; drop it (the same
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
using System;
2+
3+
namespace Own.Samples;
4+
5+
// P-004 process-lifetime AppDomain-event exemption (mined: Npgsql PoolManager). Subscribing to
6+
// AppDomain's process-host events — ProcessExit / DomainUnload (shutdown cleanup hooks) and
7+
// UnhandledException / FirstChanceException (process-wide diagnostics) — is never a region
8+
// escape: the handler is meant to live for the whole process. Must be SILENT. Contrast:
9+
// NonAppDomainSubscriber below — a non-AppDomain static event with a lambda still raises OWN014,
10+
// proving the exemption keys off the AppDomain source, not any process-lived static event.
11+
12+
public sealed class ShutdownCleanup
13+
{
14+
public ShutdownCleanup()
15+
{
16+
AppDomain.CurrentDomain.ProcessExit += (_, _) => Cleanup(); // shutdown hook -> SILENT
17+
AppDomain.CurrentDomain.DomainUnload += (_, _) => Cleanup(); // shutdown hook -> SILENT
18+
AppDomain.CurrentDomain.UnhandledException += (_, _) => Cleanup(); // process diagnostics -> SILENT
19+
AppDomain.CurrentDomain.FirstChanceException += (_, _) => Cleanup(); // process diagnostics -> SILENT
20+
}
21+
22+
private static void Cleanup() { }
23+
}
24+
25+
// Codex control: a process-host AppDomain event is exempt only when the handler retains NO
26+
// instance. A lambda that CAPTURES instance state (here `_count`) pins this subscriber to the
27+
// process until shutdown — a real region escape that must STILL raise OWN014.
28+
public sealed class CapturingShutdownSubscriber
29+
{
30+
private int _count;
31+
32+
public CapturingShutdownSubscriber()
33+
{
34+
AppDomain.CurrentDomain.ProcessExit += (_, _) => _count++; // captures `this` -> OWN014
35+
}
36+
}
37+
38+
public static class SomeBus
39+
{
40+
public static event EventHandler? Pinged;
41+
42+
public static void Raise() => Pinged?.Invoke(null, EventArgs.Empty);
43+
}
44+
45+
// Control: a lambda on a NON-AppDomain process-lived (static) event -> region escape -> must WARN.
46+
public sealed class NonAppDomainSubscriber
47+
{
48+
public NonAppDomainSubscriber()
49+
{
50+
SomeBus.Pinged += (_, _) => Handle(); // static event, lambda, not AppDomain -> OWN014
51+
}
52+
53+
private static void Handle() { }
54+
}

0 commit comments

Comments
 (0)