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:
@@ -242,8 +242,10 @@ scripted-alarm predicates) runs scripts through the shared `ScriptRunGuard`:
|
||||
`ScriptStackExhaustedException` (Bad, script log) instead of overflowing the
|
||||
stack, which would terminate the whole server. The runtime compile inserts a
|
||||
stack check at the entry of the script and of every lambda, anonymous method
|
||||
and local function (lmxopcua#779); the editor does not show it and does not
|
||||
flag recursion, and bounded recursion still works.
|
||||
and local function (lmxopcua#779), and guards every `catch` / `finally` so a
|
||||
handler that throws on every frame cannot overflow the stack while unwinding
|
||||
(lmxopcua#971 review); the editor does not show it and does not flag
|
||||
recursion, and bounded recursion still works.
|
||||
- **Configuration keys and their ranges.** All four knobs are node-wide (the
|
||||
`Scripting` appsettings section, shared by virtual tags, Calculation tags and
|
||||
scripted alarms) and are clamped when bound, with one startup Warning per
|
||||
|
||||
+1
-1
@@ -70,7 +70,7 @@ Absent, blank or unrecognised values mean `Error` — a typo never silently weak
|
||||
|
||||
#### Known resource limits (accepted trade-offs)
|
||||
|
||||
The sandbox cannot pre-empt a script. **Memory:** each run's own-thread allocation is sampled (`GC.GetAllocatedBytesForCurrentThread`) and a run over `Scripting:MaxAllocBytesPerRun` (default 64 MB) quarantines the script — but the sample is taken after the run returns, so a script that allocates fast enough (`new byte[int.MaxValue]` in a loop) can still OOM the process first. **CPU:** a tight loop keeps its pool thread after the timeout fires; `ScriptRunGuard` bounds that to one orphan per script by refusing further runs while it spins (Bad `"previous evaluation still running"`) and quarantines after three consecutive timeouts (a refusal is not a strike) — or immediately on a refusal behind an orphan that has run longer than `Scripting:StuckOrphanQuarantineFactor` (default 10) × the timeout, which is what quarantines a never-returning `while(true)`. Both are mitigations; pre-emptive CPU/memory limits need the out-of-process runner (→ #750 design, #780; opt-in via `Scripting:Runner=OutOfProcess`, below). **Stack:** unbounded recursion used to terminate the whole server — a `StackOverflowException` cannot be caught, and lmxopcua#779 reproduced it out of process (local function, mutual recursion, self-referencing `Func<>`, anonymous self-application, recursion through LINQ: the child process died with "Stack overflow." / SIGABRT). `ScriptEvaluator.Compile` now rewrites the script so the body and every lambda, anonymous method and local function starts with `ScriptStackGuard.Check()` (`RuntimeHelpers.TryEnsureSufficientExecutionStack`), so the recursion fails the script with `ScriptStackExhaustedException` — Bad quality and a script-log entry like any throwing script — while there is still stack left. A runtime check rather than an analyzer rule because recursion is not decidable from syntax (anonymous self-application never names itself); bounded recursion keeps working. Limits: the depth reached depends on the evaluating thread's stack size; a recursion that never re-enters script code is not seen (the sandbox exposes no such API); a script can catch the exception, which only unwinds it. Pinned by `ScriptRecursionContainmentTests` (one child process per shape) and `ScriptStackGuardInjectionTests`. Script authoring is gated by the AdminUI `ConfigEditor` policy — **`Administrator` or `Designer`**, not Administrator alone — and that same policy gates deploy, so a Designer can author a script and put it into production; that gate is the primary control (AdminUI-001 deliberately admitted Designers to the script pages and `/api/script-analysis/*`; lmxopcua#779 corrected this sentence, which used to say Admin-only). See `docs/ScriptEditor.md` §"Runtime safety".
|
||||
The sandbox cannot pre-empt a script. **Memory:** each run's own-thread allocation is sampled (`GC.GetAllocatedBytesForCurrentThread`) and a run over `Scripting:MaxAllocBytesPerRun` (default 64 MB) quarantines the script — but the sample is taken after the run returns, so a script that allocates fast enough (`new byte[int.MaxValue]` in a loop) can still OOM the process first. **CPU:** a tight loop keeps its pool thread after the timeout fires; `ScriptRunGuard` bounds that to one orphan per script by refusing further runs while it spins (Bad `"previous evaluation still running"`) and quarantines after three consecutive timeouts (a refusal is not a strike) — or immediately on a refusal behind an orphan that has run longer than `Scripting:StuckOrphanQuarantineFactor` (default 10) × the timeout, which is what quarantines a never-returning `while(true)`. Both are mitigations; pre-emptive CPU/memory limits need the out-of-process runner (→ #750 design, #780; opt-in via `Scripting:Runner=OutOfProcess`, below). **Stack:** unbounded recursion used to terminate the whole server — a `StackOverflowException` cannot be caught, and lmxopcua#779 reproduced it out of process (local function, mutual recursion, self-referencing `Func<>`, anonymous self-application, recursion through LINQ: the child process died with "Stack overflow." / SIGABRT). `ScriptEvaluator.Compile` now rewrites the script so the body and every lambda, anonymous method and local function starts with `ScriptStackGuard.Check()` (`RuntimeHelpers.TryEnsureSufficientExecutionStack`), so the recursion fails the script with `ScriptStackExhaustedException` — Bad quality and a script-log entry like any throwing script — while there is still stack left. A runtime check rather than an analyzer rule because recursion is not decidable from syntax (anonymous self-application never names itself); bounded recursion keeps working. Limits: the depth reached depends on the evaluating thread's stack size; a recursion that never re-enters script code is not seen (the sandbox exposes no such API); a script can catch the exception, which only unwinds it. **Exception handlers (2026-12-02 review, lmxopcua#971):** 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) — `catch { throw; }` on every frame overflowed while unwinding from the guard's own exception, and 300 frames that each rethrow overflowed with no guard involvement. The rewrite therefore also gives every script `catch` the filter `when (ScriptStackGuard.CanHandle() && …)` and wraps every `finally` body in `if (ScriptStackGuard.CanHandle())`: once the stack is low, script handlers are skipped and the exception in flight reaches the host in one dispatch (the run fails with it). On a healthy stack both are no-ops. Pinned by `ScriptRecursionContainmentTests` (one child process per shape) and `ScriptStackGuardInjectionTests`. Script authoring is gated by the AdminUI `ConfigEditor` policy — **`Administrator` or `Designer`**, not Administrator alone — and that same policy gates deploy, so a Designer can author a script and put it into production; that gate is the primary control (AdminUI-001 deliberately admitted Designers to the script pages and `/api/script-analysis/*`; lmxopcua#779 corrected this sentence, which used to say Admin-only). See `docs/ScriptEditor.md` §"Runtime safety".
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -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() && …)</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() && (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() && (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).
|
||||
|
||||
+38
-3
@@ -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
|
||||
|
||||
@@ -38,6 +38,15 @@ public sealed class ScriptStackGuardInjectionTests
|
||||
// Static lambda and a lambda capturing ctx.
|
||||
[InlineData("System.Func<int, int> f = static x => x - 1; return f(9);", 8)]
|
||||
[InlineData("System.Func<string, bool> known = p => ctx.GetTag(p).StatusCode == 0u; return known(\"missing\") ? 1 : 0;", 0)]
|
||||
// lmxopcua#971 review: guarded handlers keep their meaning on a healthy stack — an existing filter still
|
||||
// decides, a declaration-less catch still catches, pattern variables from the filter stay in scope, and a
|
||||
// finally still runs on both the normal and the exceptional path.
|
||||
[InlineData("try { throw new InvalidOperationException(\"a\"); } catch (InvalidOperationException e) when (e.Message == \"b\") { return 1; } catch (Exception) { return 2; }", 2)]
|
||||
[InlineData("try { throw new InvalidOperationException(); } catch { return 4; }", 4)]
|
||||
[InlineData("try { throw new ArgumentException(\"x\"); } catch (Exception e) when (e is ArgumentException a && a.Message == \"x\") { return a.Message.Length + 2; }", 3)]
|
||||
[InlineData("var n = 0; try { n = 1; } finally { n += 10; } return n;", 11)]
|
||||
[InlineData("var n = 0; try { try { throw new Exception(); } finally { n = 5; } } catch { n += 1; } return n;", 6)]
|
||||
[InlineData("int Rec(int d) { try { if (d >= 50) throw new InvalidOperationException(); return Rec(d + 1); } catch (InvalidOperationException) { throw; } } try { return Rec(0); } catch (InvalidOperationException) { return 50; }", 50)]
|
||||
public void Rewritten_lambdas_and_local_functions_keep_their_meaning(string source, int expected) =>
|
||||
Run(source).ShouldBe(expected);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user