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
@@ -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).