052fdf0769
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>
177 lines
10 KiB
C#
177 lines
10 KiB
C#
using System.Diagnostics;
|
|
using Shouldly;
|
|
using Xunit;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests;
|
|
|
|
/// <summary>
|
|
/// lmxopcua#779 — can unbounded recursion in a user script take the whole host process down? A
|
|
/// <see cref="StackOverflowException"/> cannot be caught in .NET, so the only safe way to ask is in a
|
|
/// <b>separate process</b>: each case re-launches this test assembly (an xunit v3 executable) to run exactly one
|
|
/// <see cref="Child_runs_one_recursive_script_through_the_production_run_path"/> case, and inspects how that
|
|
/// process ended. The test runner itself never executes a recursive script.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Before the guard every case below ended the child with "Stack overflow." and SIGABRT (exit 134 on macOS) — the
|
|
/// reproduction recorded in the #779 commit. Now the script fails with
|
|
/// <see cref="ScriptStackExhaustedException"/>, which the run path reports as an ordinary script fault, and the
|
|
/// process lives on.
|
|
/// </remarks>
|
|
public sealed class ScriptRecursionContainmentTests
|
|
{
|
|
private const string ScenarioVariable = "OTOPCUA_RECURSION_CHILD_SCENARIO";
|
|
private const string ResultFileVariable = "OTOPCUA_RECURSION_CHILD_RESULT";
|
|
|
|
/// <summary>Recursive shapes a script can write. None of them is a class member, so the wrapper's
|
|
/// single-member check never sees them; the last two have no named self-reference at all.</summary>
|
|
public static readonly Dictionary<string, string> Scenarios = new(StringComparer.Ordinal)
|
|
{
|
|
["local-function"] =
|
|
"int Down(int n) => Down(n + 1) + 1; return Down(0);",
|
|
["mutual-local-functions"] =
|
|
"int Ping(int n) { return Pong(n + 1) + 1; } int Pong(int n) { return Ping(n + 1) + 1; } return Ping(0);",
|
|
["self-referencing-lambda"] =
|
|
"System.Func<int, int> f = null!; f = n => f(n + 1) + 1; return f(0);",
|
|
["anonymous-self-application"] =
|
|
"System.Func<object, int> g = s => ((System.Func<object, int>)s)(s) + 1; return g(g);",
|
|
["recursion-through-linq"] =
|
|
"System.Func<int, int> f = null!; f = n => System.Linq.Enumerable.Sum(new[] { n }, x => f(x + 1)) + 1; return f(0);",
|
|
// An expression-bodied VOID lambda (rewritten to `{ Check(); e; }`), recursing through a value lambda. A
|
|
// bare `a = n => a(n + 1)` is no test: the JIT turns that tail call into a loop, which never overflows and
|
|
// is the timeout's business.
|
|
["void-lambda"] =
|
|
"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);
|
|
|
|
[Theory]
|
|
[MemberData(nameof(ScenarioNames))]
|
|
public async Task A_recursive_script_fails_the_script_and_does_not_kill_the_process(string scenario)
|
|
{
|
|
var resultFile = Path.Combine(Path.GetTempPath(), $"otopcua-recursion-{Guid.NewGuid():N}.txt");
|
|
try
|
|
{
|
|
var (exitCode, stdout, stderr) = await RunChildAsync(scenario, resultFile);
|
|
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.
|
|
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
|
|
{
|
|
File.Delete(resultFile);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The child half. Skipped in a normal run; it executes only inside a process launched by
|
|
/// <see cref="RunChildAsync"/>, where it compiles one scenario and runs it the way the production seams do
|
|
/// (<see cref="ScriptRunGuard"/> on the thread pool), then records how the run ended.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task Child_runs_one_recursive_script_through_the_production_run_path()
|
|
{
|
|
var scenario = Environment.GetEnvironmentVariable(ScenarioVariable);
|
|
var resultFile = Environment.GetEnvironmentVariable(ResultFileVariable);
|
|
if (string.IsNullOrEmpty(scenario) || string.IsNullOrEmpty(resultFile))
|
|
Assert.Skip("Child half of ScriptRecursionContainmentTests; runs only in the process that test launches.");
|
|
|
|
var source = Scenarios[scenario];
|
|
using var evaluator = ScriptEvaluator<FakeScriptContext, int>.Compile(source);
|
|
var guard = new ScriptRunGuard();
|
|
string outcome;
|
|
try
|
|
{
|
|
var value = await guard.RunAsync(scenario, source, evaluator, new FakeScriptContext(), TimeSpan.FromSeconds(60), TestContext.Current.CancellationToken);
|
|
outcome = $"RETURNED:{value}";
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
outcome = $"FAULTED:{ex.GetType().Name}";
|
|
}
|
|
|
|
await File.WriteAllTextAsync(resultFile, outcome, TestContext.Current.CancellationToken);
|
|
}
|
|
|
|
private static async Task<(int ExitCode, string Stdout, string Stderr)> RunChildAsync(string scenario, string resultFile)
|
|
{
|
|
var assembly = typeof(ScriptRecursionContainmentTests).Assembly.Location;
|
|
var childTest = $"{typeof(ScriptRecursionContainmentTests).FullName}.{nameof(Child_runs_one_recursive_script_through_the_production_run_path)}";
|
|
var psi = new ProcessStartInfo("dotnet")
|
|
{
|
|
RedirectStandardOutput = true,
|
|
RedirectStandardError = true,
|
|
UseShellExecute = false,
|
|
};
|
|
psi.ArgumentList.Add("exec");
|
|
psi.ArgumentList.Add(assembly);
|
|
psi.ArgumentList.Add("-method");
|
|
psi.ArgumentList.Add(childTest);
|
|
psi.Environment[ScenarioVariable] = scenario;
|
|
psi.Environment[ResultFileVariable] = resultFile;
|
|
// A crash dump of a deliberate stack overflow is noise, not evidence.
|
|
psi.Environment["DOTNET_DbgEnableMiniDump"] = "0";
|
|
|
|
using var process = Process.Start(psi) ?? throw new InvalidOperationException("could not start the child test process");
|
|
var stdout = process.StandardOutput.ReadToEndAsync();
|
|
var stderr = process.StandardError.ReadToEndAsync();
|
|
using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(2));
|
|
try
|
|
{
|
|
await process.WaitForExitAsync(cts.Token);
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
process.Kill(entireProcessTree: true);
|
|
throw new TimeoutException($"child for '{scenario}' did not exit within 2 minutes");
|
|
}
|
|
|
|
return (process.ExitCode, await stdout, await stderr);
|
|
}
|
|
|
|
private static string Head(string text) => text.Length <= 200 ? text : text[..200];
|
|
|
|
private static string Tail(string text) => text.Length <= 600 ? text : text[^600..];
|
|
}
|