Files
lmxopcua/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Abstractions/ScriptStackGuard.cs
T
Joseph Doherty 9e8b5b0ea7 fix(scripting): stop unbounded script recursion from killing the server (lmxopcua#779)
Reproduced first, out of process (ScriptRecursionContainmentTests re-launches
the xunit v3 test assembly to run one recursive script through
ScriptEvaluator + ScriptRunGuard, so the runner never executes one): before
this change every shape — local function, mutual local functions,
self-referencing Func<>, anonymous self-application, recursion through LINQ,
an expression-bodied void lambda, an anonymous method — ended the child with
exit 134 (SIGABRT, "Stack overflow."). A StackOverflowException cannot be
caught, so in production one script takes the whole node down.

Fix: ScriptEvaluator.Compile now rewrites the validated wrapper
(ScriptStackGuardInjector, after ForbiddenTypeAnalyzer) so the script body and
every lambda, anonymous method and local function starts with
ScriptStackGuard.Check(), which throws ScriptStackExhaustedException when
RuntimeHelpers.TryEnsureSufficientExecutionStack reports the stack nearly
spent. The script then fails like any throwing script (Bad, script log) and
the process lives.

Why a runtime check, not an analyzer rule: recursion is not decidable from
syntax (anonymous self-application never names itself), and bounded recursion
must keep working. Expression-bodied lambdas/local functions become blocks
(`return e;` or `e;`, chosen from the bound symbol, so the same overload
binds); expression-tree and async lambdas are left alone. Limits (documented
on ScriptStackGuard and in docs/VirtualTags.md): depth depends on the thread's
stack size; a recursion that never re-enters script code is not seen; a script
may catch the exception, which only unwinds it.

Tests: ScriptRecursionContainmentTests (7 shapes, child process each; all 7
fail with exit 134 when the rewrite is disabled), ScriptStackGuardInjectionTests
(bounded recursion and every rewritten lambda/local-function shape keep their
value; the expression-tree case fails if those lambdas are rewritten).

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
2026-11-09 17:44:35 -05:00

57 lines
3.2 KiB
C#

using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace ZB.MOM.WW.OtOpcUa.Core.Scripting;
/// <summary>
/// Stack-depth guard injected into compiled user scripts (lmxopcua#779). <c>ScriptEvaluator.Compile</c> inserts a
/// call to <see cref="Check"/> as the first statement of the script body and of every lambda, anonymous method
/// and local function the script declares, so every frame of a recursive cycle that runs script code passes
/// through it.
/// </summary>
/// <remarks>
/// <para>
/// <b>Why.</b> A <see cref="StackOverflowException"/> cannot be caught in .NET: the runtime terminates the
/// process. One script with unbounded recursion (a local function, a self-referencing <c>Func&lt;&gt;</c>, an
/// anonymous self-application) would take down the whole server — every OPC UA session, every driver, the
/// node's Akka membership. <see cref="RuntimeHelpers.TryEnsureSufficientExecutionStack"/> reports false while
/// there is still a safety margin of stack left, so a <em>catchable</em> exception is thrown instead: the
/// script fails like any other throwing script (Bad quality, script log) and the process lives.
/// </para>
/// <para>
/// <b>Limits.</b> The check runs on entry to script-declared code only. A recursion that never re-enters
/// script code (a BCL call that recurses on its own) is not seen — the sandbox gives scripts no such API
/// today. Frames of BCL code between two script frames (a LINQ operator invoking a script lambda) must fit
/// in the margin; they are a few hundred bytes. The check is per frame, so it bounds depth by the stack
/// 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>
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public static class ScriptStackGuard
{
/// <summary>Throws <see cref="ScriptStackExhaustedException"/> when the current thread is close to the end of its
/// stack. Called by compiled scripts; not part of the script authoring surface.</summary>
/// <exception cref="ScriptStackExhaustedException">The remaining stack is below the runtime's safety margin.</exception>
public static void Check()
{
if (!RuntimeHelpers.TryEnsureSufficientExecutionStack())
throw new ScriptStackExhaustedException();
}
}
/// <summary>
/// A script recursed (or nested calls) deep enough to exhaust its thread's stack. Thrown by
/// <see cref="ScriptStackGuard.Check"/> before the runtime would raise an uncatchable
/// <see cref="StackOverflowException"/>; the evaluating seam reports it like any other script exception.
/// </summary>
public sealed class ScriptStackExhaustedException : Exception
{
/// <summary>Initializes a new instance of the <see cref="ScriptStackExhaustedException"/> class.</summary>
public ScriptStackExhaustedException()
: base("Script stack exhausted: unbounded or too-deep recursion. The script was stopped before it could " +
"overflow the stack and terminate the server.")
{
}
}