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
@@ -26,6 +26,19 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Scripting;
/// that remains, not by a fixed count: the same script may fail at a different depth on a thread with a
/// different stack size (the platform's default thread stack size differs between Windows, Linux and macOS).
/// </para>
/// <para>
/// <b>Exception handlers (lmxopcua#971 review 2026-12-02).</b> Checking frames is not enough on its own: a
/// <c>catch</c> or <c>finally</c> block runs as a funclet <em>on top of</em> the frames being unwound, so a
/// handler that throws (<c>throw;</c>, <c>throw new …</c>, a call that fails the check) starts a nested
/// exception dispatch deeper still — several KB per level. A script that catches-and-rethrows on every frame
/// therefore overflowed the stack while unwinding from the guard's own exception, and 300 frames that each
/// rethrow overflowed with no guard involvement at all. The rewrite also guards every script handler with
/// <see cref="CanHandle"/>: a <c>catch</c> gains the filter <c>when (CanHandle() &amp;&amp; …)</c> and a
/// <c>finally</c> body runs only <c>if (CanHandle())</c>. Once the stack is low, script handlers are skipped,
/// the exception in flight passes to the host in one dispatch (a filter runs and returns without growing the
/// stack), and the run fails with it. Skipping a <c>finally</c> is only possible on a run that is already
/// failing on an exhausted stack.
/// </para>
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public static class ScriptStackGuard
@@ -38,6 +51,14 @@ public static class ScriptStackGuard
if (!RuntimeHelpers.TryEnsureSufficientExecutionStack())
throw new ScriptStackExhaustedException();
}
/// <summary>
/// True while the current thread has stack to spare for a script exception handler (see the remarks). Called
/// by compiled scripts from every <c>catch</c> filter and <c>finally</c> block; not part of the script
/// authoring surface.
/// </summary>
/// <returns>False when the remaining stack is below the runtime's safety margin.</returns>
public static bool CanHandle() => RuntimeHelpers.TryEnsureSufficientExecutionStack();
}
/// <summary>
@@ -33,6 +33,13 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Scripting;
/// its exception terminated the host), so none reaches this rewrite.
/// </para>
/// <para>
/// <b>Exception handlers (lmxopcua#971 review).</b> Every script <c>catch</c> also gets the filter
/// <c>when (ScriptStackGuard.CanHandle() &amp;&amp; (original filter))</c>, and every <c>finally</c> body is
/// wrapped in <c>if (ScriptStackGuard.CanHandle()) { … }</c>: a handler runs on top of the frames being
/// unwound, so one that throws on every frame overflowed the stack while unwinding (see
/// <see cref="ScriptStackGuard"/>). On a healthy stack both are no-ops.
/// </para>
/// <para>
/// Runs after <see cref="ForbiddenTypeAnalyzer"/>, so the analyzer only ever sees the user's code; the
/// inserted call names a type in <c>Core.Scripting.Abstractions</c>, which the sandbox already references.
/// </para>
@@ -40,6 +47,7 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Scripting;
internal static class ScriptStackGuardInjector
{
private const string CheckCall = "global::ZB.MOM.WW.OtOpcUa.Core.Scripting.ScriptStackGuard.Check()";
private const string CanHandleCall = "global::ZB.MOM.WW.OtOpcUa.Core.Scripting.ScriptStackGuard.CanHandle()";
/// <summary>Returns <paramref name="tree"/> with a stack check at the entry of every script-declared body.</summary>
/// <param name="compilation">The compiled (error-free, analyzer-clean) wrapper compilation.</param>
@@ -65,6 +73,25 @@ internal static class ScriptStackGuardInjector
private sealed class Rewriter(SemanticModel model) : CSharpSyntaxRewriter
{
/// <summary><c>catch … when (f)</c> becomes <c>catch … when (CanHandle() &amp;&amp; (f))</c> — see
/// <see cref="ScriptStackGuard"/>'s "Exception handlers" remarks.</summary>
public override SyntaxNode? VisitCatchClause(CatchClauseSyntax node)
{
var visited = (CatchClauseSyntax)base.VisitCatchClause(node)!;
ExpressionSyntax canHandle = ParseExpression(CanHandleCall);
var condition = visited.Filter is { } filter
? BinaryExpression(SyntaxKind.LogicalAndExpression, canHandle, ParenthesizedExpression(filter.FilterExpression))
: canHandle;
return visited.WithFilter(CatchFilterClause(condition));
}
/// <summary><c>finally { b }</c> becomes <c>finally { if (CanHandle()) { b } }</c>.</summary>
public override SyntaxNode? VisitFinallyClause(FinallyClauseSyntax node)
{
var visited = (FinallyClauseSyntax)base.VisitFinallyClause(node)!;
return visited.WithBlock(Block(IfStatement(ParseExpression(CanHandleCall), visited.Block)));
}
public override SyntaxNode? VisitMethodDeclaration(MethodDeclarationSyntax node)
{
// The only method in the wrapper is the synthesized CompiledScript.Run (ScriptEvaluator enforces that).