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>
80 lines
5.9 KiB
C#
80 lines
5.9 KiB
C#
using Shouldly;
|
|
using Xunit;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests;
|
|
|
|
/// <summary>
|
|
/// lmxopcua#779 — the stack-guard rewrite (<see cref="ScriptStackGuardInjector"/>) must not change what a script
|
|
/// means: every lambda / local-function shape still binds to the same overload and returns the same value, and
|
|
/// bounded recursion keeps working. The process-level proof that unbounded recursion no longer kills the host is
|
|
/// <see cref="ScriptRecursionContainmentTests"/>; this class runs only scripts that terminate.
|
|
/// </summary>
|
|
public sealed class ScriptStackGuardInjectionTests
|
|
{
|
|
private static object? Run(string source)
|
|
{
|
|
using var evaluator = ScriptEvaluator<FakeScriptContext, object?>.Compile(source);
|
|
return evaluator.RunAsync(new FakeScriptContext(), TestContext.Current.CancellationToken).Result;
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData("int F(int n) => n <= 0 ? 0 : F(n - 1) + 1; return F(500);", 500)]
|
|
[InlineData("int F(int n) { if (n <= 0) return 0; return F(n - 1) + 1; } return F(500);", 500)]
|
|
[InlineData("System.Func<int, int> f = null!; f = n => n <= 0 ? 0 : f(n - 1) + 1; return f(500);", 500)]
|
|
[InlineData("System.Func<int, int> f = null!; f = delegate (int n) { return n <= 0 ? 0 : f(n - 1) + 1; }; return f(500);", 500)]
|
|
public void Bounded_recursion_still_returns_its_value(string source, int expected) =>
|
|
Run(source).ShouldBe(expected);
|
|
|
|
[Theory]
|
|
// Expression lambdas through LINQ: Select / Where / Sum / Aggregate overloads resolve as before.
|
|
[InlineData("return System.Linq.Enumerable.Sum(System.Linq.Enumerable.Select(new[] { 1, 2, 3 }, x => x * 2));", 12)]
|
|
[InlineData("return System.Linq.Enumerable.Count(new[] { 1, 2, 3, 4 }, x => x % 2 == 0);", 2)]
|
|
[InlineData("return System.Linq.Enumerable.Aggregate(new[] { 1, 2, 3 }, 10, (acc, x) => acc + x);", 16)]
|
|
// An expression-bodied VOID lambda (List.ForEach takes an Action): rewritten to `{ Check(); e; }`.
|
|
[InlineData("var acc = new System.Collections.Generic.List<int>(); new System.Collections.Generic.List<int> { 1, 2 }.ForEach(x => acc.Add(x * 5)); return acc[1];", 10)]
|
|
// Expression-bodied void local function, and a local function returning a lambda (nested rewrite).
|
|
[InlineData("var box = new int[1]; void Set(int v) => box[0] = v; Set(7); return box[0];", 7)]
|
|
[InlineData("System.Func<int, int> Make(int k) => x => x + k; return Make(3)(4);", 7)]
|
|
// 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);
|
|
|
|
/// <summary>A lambda converted to an expression tree is left as it is (a block body is illegal there and an
|
|
/// expression tree runs no script frame); rewriting it would turn a compiling script into an emit failure.</summary>
|
|
/// <remarks>
|
|
/// Since lmxopcua#971 a script cannot write an expression tree at all (<c>System.Linq.Expressions</c> is off the
|
|
/// sandbox allow-list and out of the reference set — it was a by-name reflection escape), so the injector's
|
|
/// expression-tree carve-out is exercised directly on a compilation that references it.
|
|
/// </remarks>
|
|
[Fact]
|
|
public void An_expression_tree_lambda_is_not_rewritten()
|
|
{
|
|
Should.Throw<CompilationErrorException>(() => ScriptEvaluator<FakeScriptContext, object?>.Compile(
|
|
"System.Linq.Expressions.Expression<System.Func<int, int>> e = x => x + 1; return 0;"));
|
|
|
|
var tree = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(
|
|
"class C { static object Run() { System.Linq.Expressions.Expression<System.Func<int, int>> e = x => x + 1; return e; } }",
|
|
cancellationToken: TestContext.Current.CancellationToken);
|
|
var tpa = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!).Split(Path.PathSeparator);
|
|
var compilation = Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create(
|
|
"ExprTree", [tree], tpa.Select(p => Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(p)),
|
|
new Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(Microsoft.CodeAnalysis.OutputKind.DynamicallyLinkedLibrary));
|
|
|
|
var rewritten = ScriptStackGuardInjector.Inject(compilation, tree).GetRoot(TestContext.Current.CancellationToken).ToFullString();
|
|
|
|
rewritten.ShouldContain("e = x => x + 1;"); // the expression lambda is untouched
|
|
rewritten.Split("ScriptStackGuard.Check()").Length.ShouldBe(2); // only Run's body got the check
|
|
}
|
|
}
|