using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace ZB.MOM.WW.OtOpcUa.Core.Scripting;
///
/// Stack-depth guard injected into compiled user scripts (lmxopcua#779). ScriptEvaluator.Compile inserts a
/// call to 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.
///
///
///
/// Why. A cannot be caught in .NET: the runtime terminates the
/// process. One script with unbounded recursion (a local function, a self-referencing Func<>, an
/// anonymous self-application) would take down the whole server — every OPC UA session, every driver, the
/// node's Akka membership. reports false while
/// there is still a safety margin of stack left, so a catchable exception is thrown instead: the
/// script fails like any other throwing script (Bad quality, script log) and the process lives.
///
///
/// Limits. 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).
///
///
[EditorBrowsable(EditorBrowsableState.Never)]
public static class ScriptStackGuard
{
/// Throws when the current thread is close to the end of its
/// stack. Called by compiled scripts; not part of the script authoring surface.
/// The remaining stack is below the runtime's safety margin.
public static void Check()
{
if (!RuntimeHelpers.TryEnsureSufficientExecutionStack())
throw new ScriptStackExhaustedException();
}
}
///
/// A script recursed (or nested calls) deep enough to exhaust its thread's stack. Thrown by
/// before the runtime would raise an uncatchable
/// ; the evaluating seam reports it like any other script exception.
///
public sealed class ScriptStackExhaustedException : Exception
{
/// Initializes a new instance of the class.
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.")
{
}
}