fix(scripting): #971 review — refuse async lambdas/local functions, stackalloc and runtime-binding [MethodImpl] flags
Three scripts passed the allow-list and the deploy gate and then terminated the host (exit 134): an async void local function / async lambda (the compiler's AsyncVoidMethodBuilder rethrows on the thread pool) and an over-sized stackalloc (overflows in one frame, before the #779 guard). IsForbiddenSyntax now refuses every async form (await included) and both stackalloc forms. Siblings: [MethodImpl] may set only the JIT-hint bits (InternalCall passed the gate then failed to load; Synchronized is a lock; numeric casts are checked by constant value), and a collection initializer's compiler-called Add is checked like a named member. Regression rows for each, plus rows pinning the lowered constructs that stay safe (iterators, goto, checked, filters, collection expressions, interpolation handlers, params Span, using/deconstruction) and the declarations the wrapper already refuses (records, local types, finalizers, static ctors, unsafe/fixed, SkipLocalsInit, ThreadStatic). Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -49,7 +49,11 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Scripting;
|
||||
/// return-type check is what keeps reflection handles out of reach: <c>Exception.TargetSite</c> is a member
|
||||
/// of an allowed type but returns a <c>MethodBase</c>. (3) A few syntactic forms are refused outright
|
||||
/// (<see cref="IsForbiddenSyntax"/>): <c>__makeref</c>/<c>__refvalue</c>/<c>__reftype</c>/<c>__arglist</c>,
|
||||
/// <c>lock</c> (a blocking primitive on a possibly-shared object) and <c>extern</c> local functions.
|
||||
/// <c>lock</c> (a blocking primitive on a possibly-shared object), <c>extern</c> local functions,
|
||||
/// <c>async</c> lambdas / local functions and <c>stackalloc</c> (each terminated the host —
|
||||
/// lmxopcua#971 review 2026-12-02); <c>[MethodImpl]</c> is limited to the JIT hint bits. (4) Members the
|
||||
/// compiler calls without a name in the source — query operators, <c>foreach</c>'s enumerator pattern,
|
||||
/// <c>Deconstruct</c>, a collection initializer's <c>Add</c> — are checked like named ones.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Defence in depth.</b> <see cref="ScriptSandbox"/> also references only the handful of BCL assemblies
|
||||
@@ -255,9 +259,28 @@ public static class ForbiddenTypeAnalyzer
|
||||
|
||||
/// <summary>
|
||||
/// Syntax refused regardless of binding: the undocumented <c>TypedReference</c> keywords, <c>lock</c> (a
|
||||
/// blocking monitor on an object that may be shared with the host, e.g. <c>lock (typeof(string))</c>), and
|
||||
/// <c>extern</c> local functions (a native entry point).
|
||||
/// blocking monitor on an object that may be shared with the host, e.g. <c>lock (typeof(string))</c>),
|
||||
/// <c>extern</c> local functions (a native entry point), <c>async</c> lambdas / anonymous methods / local
|
||||
/// functions, and <c>stackalloc</c>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <b><c>async</c> (lmxopcua#971 review 2026-12-02).</b> The compiler lowers an async body into a state
|
||||
/// machine driven by a method builder the script never names, so no allow-list check sees it. An
|
||||
/// <c>async void</c> body's exception is not returned to the caller: <c>AsyncVoidMethodBuilder</c>
|
||||
/// rethrows it on the thread pool, where nothing catches it and the runtime terminates the host
|
||||
/// (<c>async void Boom() { throw … } Boom();</c> — and an <c>async</c> lambda converted to
|
||||
/// <c>Action</c> is the same thing). A script is synchronous by contract
|
||||
/// (<see cref="ScriptEvaluator{TContext, TResult}.RunAsync"/>) and <c>System.Threading.Tasks</c> is not
|
||||
/// on the allow-list, so there is no legitimate <c>async</c> script code: every form is refused, which
|
||||
/// also covers <c>await</c>, <c>await foreach</c> and <c>await using</c> (legal only inside one).
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b><c>stackalloc</c>.</b> One <c>stackalloc byte[1_500_000_000]</c> overflows the thread's stack inside
|
||||
/// a single frame — before the next <c>ScriptStackGuard.Check()</c> can run — and a stack overflow is
|
||||
/// uncatchable. Scripts have heap arrays and <c>Span</c> over them; there is no need for stack buffers.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <param name="node">The node.</param>
|
||||
/// <returns>A description of the construct, or null when the node is allowed.</returns>
|
||||
internal static string? IsForbiddenSyntax(SyntaxNode node) => node switch
|
||||
@@ -268,9 +291,28 @@ public static class ForbiddenTypeAnalyzer
|
||||
ExpressionSyntax e when e.IsKind(SyntaxKind.ArgListExpression) => "__arglist",
|
||||
LockStatementSyntax => "lock",
|
||||
LocalFunctionStatementSyntax f when f.Modifiers.Any(SyntaxKind.ExternKeyword) => "extern local function",
|
||||
LocalFunctionStatementSyntax f when f.Modifiers.Any(SyntaxKind.AsyncKeyword) => "async local function",
|
||||
AnonymousFunctionExpressionSyntax f when f.AsyncKeyword.IsKind(SyntaxKind.AsyncKeyword) => "async lambda",
|
||||
AwaitExpressionSyntax => "await",
|
||||
StackAllocArrayCreationExpressionSyntax or ImplicitStackAllocArrayCreationExpressionSyntax => "stackalloc",
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="System.Runtime.CompilerServices.MethodImplOptions"/> bits a script's <c>[MethodImpl]</c> may
|
||||
/// set: JIT inlining / optimization hints only. <c>InternalCall</c> / <c>ForwardRef</c> / <c>Unmanaged</c> /
|
||||
/// <c>PreserveSig</c> change how the runtime binds the method (an <c>InternalCall</c> local function passes the
|
||||
/// compiler and fails to load — the publish gate accepted what the runtime refuses), and <c>Synchronized</c>
|
||||
/// takes a monitor (the <c>lock</c> the analyzer refuses).
|
||||
/// </summary>
|
||||
private const int AllowedMethodImplBits =
|
||||
(int)(System.Runtime.CompilerServices.MethodImplOptions.NoInlining
|
||||
| System.Runtime.CompilerServices.MethodImplOptions.NoOptimization
|
||||
| System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining
|
||||
| System.Runtime.CompilerServices.MethodImplOptions.AggressiveOptimization);
|
||||
|
||||
private const string MethodImplAttributeFullName = "System.Runtime.CompilerServices.MethodImplAttribute";
|
||||
|
||||
private sealed class Walker(Compilation compilation, SemanticModel semantic, List<ForbiddenTypeRejection> rejections)
|
||||
{
|
||||
public void Visit(SyntaxNode node)
|
||||
@@ -283,9 +325,19 @@ public static class ForbiddenTypeAnalyzer
|
||||
}
|
||||
|
||||
// Members the compiler calls with no name in the source: query-clause operators, foreach's
|
||||
// GetEnumerator / MoveNext / Current, and a deconstruction's Deconstruct.
|
||||
// GetEnumerator / MoveNext / Current, a deconstruction's Deconstruct, and a collection initializer's Add.
|
||||
switch (node)
|
||||
{
|
||||
case AttributeSyntax attribute:
|
||||
CheckMethodImpl(attribute);
|
||||
break;
|
||||
case InitializerExpressionSyntax initializer when initializer.IsKind(SyntaxKind.CollectionInitializerExpression):
|
||||
foreach (var element in initializer.Expressions)
|
||||
{
|
||||
var addInfo = semantic.GetCollectionInitializerSymbolInfo(element);
|
||||
CheckOptional(addInfo.Symbol, element.Span);
|
||||
}
|
||||
break;
|
||||
case QueryClauseSyntax clause:
|
||||
var clauseInfo = semantic.GetQueryClauseInfo(clause);
|
||||
CheckOptional(clauseInfo.OperationInfo.Symbol, clause.Span);
|
||||
@@ -318,6 +370,26 @@ public static class ForbiddenTypeAnalyzer
|
||||
CheckType(typeInfo.ConvertedType, expr.Span);
|
||||
}
|
||||
|
||||
/// <summary>Refuses <c>[MethodImpl]</c> flags outside <see cref="AllowedMethodImplBits"/>, however spelled.</summary>
|
||||
private void CheckMethodImpl(AttributeSyntax attribute)
|
||||
{
|
||||
if (semantic.GetSymbolInfo(attribute).Symbol is not IMethodSymbol { ContainingType: { } attributeType }
|
||||
|| TypeKey(attributeType.OriginalDefinition) != MethodImplAttributeFullName
|
||||
|| attribute.ArgumentList is null)
|
||||
return;
|
||||
|
||||
foreach (var argument in attribute.ArgumentList.Arguments)
|
||||
{
|
||||
if (argument.NameEquals is not null) continue; // named (MethodCodeType = …): its type is checked as usual
|
||||
var constant = semantic.GetConstantValue(argument.Expression);
|
||||
var bits = constant is { HasValue: true, Value: { } value } ? Convert.ToInt64(value, System.Globalization.CultureInfo.InvariantCulture) : -1;
|
||||
if (bits < 0 || (bits & ~AllowedMethodImplBits) != 0)
|
||||
Add(argument.Span, "MethodImplOptions", "System.Runtime.CompilerServices",
|
||||
"[MethodImpl] may only set NoInlining, NoOptimization, AggressiveInlining or AggressiveOptimization " +
|
||||
"in a script (sandbox: see ForbiddenTypeAnalyzer.AllowedMethodImplBits).");
|
||||
}
|
||||
}
|
||||
|
||||
private void CheckOptional(ISymbol? symbol, TextSpan span)
|
||||
{
|
||||
if (symbol is not null) CheckSymbol(symbol, span);
|
||||
|
||||
@@ -28,8 +28,9 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Scripting;
|
||||
/// compiler actually picked, so the block form is compatible with the same delegate type and nothing
|
||||
/// re-binds differently. Lambdas converted to an expression tree (<c>Expression<T></c>) are left alone:
|
||||
/// a block body is not legal there and an expression tree does not execute script frames. Async lambdas and
|
||||
/// local functions are left alone (the sandbox denies <c>System.Threading.Tasks</c>, so a script cannot
|
||||
/// produce one that compiles).
|
||||
/// local functions are left alone: <see cref="ForbiddenTypeAnalyzer"/> refuses every <c>async</c> form
|
||||
/// (lmxopcua#971 review — an <c>async void</c> one compiled without naming <c>System.Threading.Tasks</c> and
|
||||
/// its exception terminated the host), so none reaches this rewrite.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Runs after <see cref="ForbiddenTypeAnalyzer"/>, so the analyzer only ever sees the user's code; the
|
||||
|
||||
Reference in New Issue
Block a user