fix(scripting): #971 review — guard script catch/finally handlers so unwinding cannot overflow the stack

Sibling hunt for the #779 stack guard: a catch or finally runs as a funclet on
top of the frames being unwound, so a handler that throws starts a nested
dispatch deeper still (~6 KB/level). 'catch { throw; }' on every frame killed
the host while unwinding from the guard's own exception, and 300 frames that
each rethrow (or whose finally throws) killed it with no guard involvement.

The stack-guard rewrite now gives every script catch the filter
'when (ScriptStackGuard.CanHandle() && (filter))' and wraps every finally body
in 'if (ScriptStackGuard.CanHandle())'. Once the stack is low, script handlers
are skipped and the in-flight exception reaches the host in one dispatch.
Verified on 1.5 MB / 1 MB / 512 KB / 256 KB threads. Seven new child-process
scenarios in ScriptRecursionContainmentTests (all crashed before), plus
semantics-preservation rows for filters, declaration-less catch, pattern
variables and finally on both paths.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-12-03 12:05:33 -05:00
parent 7ecaeea82e
commit 052fdf0769
6 changed files with 100 additions and 6 deletions
@@ -43,6 +43,40 @@ public sealed class ScriptRecursionContainmentTests
"System.Action<int> a = null!; System.Func<int, int> h = n => { a(n); return n; }; a = n => h(n + 1); a(0); return 0;",
["anonymous-method"] =
"System.Func<int, int> f = null!; f = delegate (int n) { return f(n + 1) + 1; }; return f(0);",
// lmxopcua#971 review: exception handlers on every frame. A catch / finally runs as a funclet ON TOP of the
// frames being unwound, so a handler that throws starts a nested dispatch deeper still (~6 KB a level on
// macOS). Before the fix each of these terminated the process — the unbounded ones after the guard fired
// (its margin cannot hold a nested dispatch per frame), the bounded ones with no guard involvement at all:
// 300 frames that each catch-and-rethrow are enough.
["catch-rethrow-per-frame"] =
"int Rec(int d) { try { return Rec(d + 1); } catch (System.Exception) { throw; } } return Rec(0);",
["catch-throw-new-per-frame"] =
"int Rec(int d) { try { return Rec(d + 1); } catch (System.Exception) { throw new System.InvalidOperationException(); } } return Rec(0);",
["catch-recurse-again"] =
"int Rec(int d) { try { return Rec(d + 1); } catch (System.Exception) { return Rec(d + 1); } } return Rec(0);",
["finally-throw-per-frame"] =
"int Rec(int d) { try { return Rec(d + 1); } finally { if (d >= 0) throw new System.InvalidOperationException(); } } return Rec(0);",
["bounded-catch-rethrow"] =
"int Rec(int d) { try { if (d >= 300) throw new System.InvalidOperationException(); return Rec(d + 1); } catch (System.Exception) { throw; } } return Rec(0);",
["bounded-catch-wrap"] =
"int Rec(int d) { try { if (d >= 300) throw new System.InvalidOperationException(); return Rec(d + 1); } catch (System.InvalidOperationException) { throw new System.ArgumentException(); } catch (System.ArgumentException) { throw new System.InvalidOperationException(); } } return Rec(0);",
["bounded-finally-throw"] =
"int Rec(int d) { try { if (d >= 300) throw new System.InvalidOperationException(); return Rec(d + 1); } finally { if (d >= 0) throw new System.InvalidOperationException(); } } return Rec(0);",
["filter-recurses"] =
"int Rec(int d) { try { return Rec(d + 1); } catch (System.Exception) when (Rec(d + 1) > 0) { return 0; } } return Rec(0);",
};
/// <summary>
/// Scenarios whose surviving fault is not <see cref="ScriptStackExhaustedException"/>: the exception in flight
/// when the stack ran low is the script's own, and the run fails with it (null = any exception type).
/// </summary>
private static readonly Dictionary<string, string?> ExpectedFaultOverrides = new(StringComparer.Ordinal)
{
["finally-throw-per-frame"] = null,
["bounded-catch-rethrow"] = nameof(InvalidOperationException),
["bounded-catch-wrap"] = null,
["bounded-finally-throw"] = nameof(InvalidOperationException),
};
public static TheoryData<string> ScenarioNames => new(Scenarios.Keys);
@@ -58,9 +92,10 @@ public sealed class ScriptRecursionContainmentTests
var outcome = File.Exists(resultFile) ? await File.ReadAllTextAsync(resultFile, TestContext.Current.CancellationToken) : "<no result file>";
// Assert the artifact first: what the child itself recorded about the run.
outcome.ShouldBe(
$"FAULTED:{nameof(ScriptStackExhaustedException)}",
$"child exit {exitCode}; stderr head: {Head(stderr)}; stderr tail: {Tail(stderr)}; stdout tail: {Tail(stdout)}");
var context = $"child exit {exitCode}; stderr head: {Head(stderr)}; stderr tail: {Tail(stderr)}; stdout tail: {Tail(stdout)}";
var expected = ExpectedFaultOverrides.TryGetValue(scenario, out var over) ? over : nameof(ScriptStackExhaustedException);
if (expected is null) outcome.ShouldStartWith("FAULTED:", Case.Sensitive, context);
else outcome.ShouldBe($"FAULTED:{expected}", context);
exitCode.ShouldBe(0, $"the process must survive the script; stderr tail: {Tail(stderr)}");
}
finally