Files
lmxopcua/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptEvaluator.cs
T
Joseph Doherty 73f49eaf32 fix(scripting): #1063 one compile-refusal authority for editor and deploy gate (ScriptCompileRules + the runtime's own wrapper text) — CS0161 and wrapper injection are now flagged in the editor; #1065 {{equip}} in a Calculation script is refused by the gate and by a new Calculation editor mode
#1063: the Monaco diagnostics dropped every Roslyn error located in the synthesized
wrapper as 'phantom', so CS0161 (not all code paths return a value, pinned on Run)
passed the editor and failed the deploy gate. ScriptCompileRules (Core.Scripting) now
states which diagnostics refuse (every Error, wherever located; LMX001/002 injection)
and which sources skip the compile (blank/passthrough value scripts); ScriptEvaluator
and the editor both use it, and the editor wraps with ScriptEvaluator.WrapperPreamble/
WrapperSuffix instead of its own copy. Wrapper-located refusals are drawn on the
script's last line. EditorGateParityTests runs one corpus through editor and gate in
all three modes.

#1065: a Calculation tag is raw/device-level with no equipment and its seam never
substitutes {{equip}}, so such a script deployed clean and read Bad forever. Refused
rather than substituted: EquipTokenLiteralScanner.FindInCalculation is run by
RoslynDeployScriptChecker for every Calculation use (before the passthrough shortcut,
outside the shared VT/Calc cache) and by the editor in the new 'calculation' mode
(Calculation tag editor; ScriptEdit defaults to it when a Calculation tag uses the
script).
2026-12-03 16:47:14 -05:00

474 lines
25 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Reflection;
using System.Runtime.Loader;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
namespace ZB.MOM.WW.OtOpcUa.Core.Scripting;
/// <summary>
/// Compiles + runs user scripts against a <see cref="ScriptContext"/> subclass. Core
/// evaluator — no caching, no timeout, no logging side-effects (those land in
/// <see cref="CompiledScriptCache{TContext, TResult}"/>,
/// <see cref="TimedScriptEvaluator{TContext, TResult}"/>, and
/// <see cref="ScriptLogCompanionSink"/> respectively).
/// </summary>
/// <remarks>
/// <para>
/// Scripts are wrapped in a synthesized <c>CompiledScript.Run(globals)</c> method
/// and compiled via <see cref="CSharpCompilation"/> into a regular .NET assembly
/// that is loaded into a <b>collectible</b>
/// <see cref="AssemblyLoadContext"/>. The collectible ALC fixes unbounded
/// per-publish recompile accretion: previously
/// Roslyn's <c>CSharpScript.CreateDelegate</c> emitted into the default ALC
/// (non-collectible); now <see cref="Dispose"/> unloads the entire ALC and the
/// emitted assembly becomes eligible for GC.
/// </para>
/// <para>
/// Compile pipeline is a three-step gate, unchanged in intent from the legacy
/// <c>CSharpScript</c> path: (1) Roslyn parse + compile against the
/// <see cref="ScriptSandbox"/> allow-list — catches syntax errors, unresolved
/// types (the sandbox's first line of defense), and most type-resolution
/// failures, throwing <see cref="CompilationErrorException"/>; (2)
/// <see cref="ForbiddenTypeAnalyzer"/> runs against the semantic model — the sandbox gate: every
/// symbol, expression type and member must be on its allow-list (lmxopcua#971),
/// else it throws <see cref="ScriptSandboxViolationException"/>; (3) emit
/// to an in-memory PE stream + load into the collectible ALC — throws at this
/// layer only for internal Roslyn bugs, not user error. Between (2) and (3) the tree is rewritten to
/// call <see cref="ScriptStackGuard.Check"/> on entry to every script-declared body, so unbounded
/// recursion fails the script instead of overflowing the stack and terminating the process
/// (<see cref="ScriptStackGuardInjector"/>, lmxopcua#779).
/// </para>
/// <para>
/// Runtime exceptions thrown from user code propagate unwrapped. The virtual-tag
/// engine catches them per-tag and maps to <c>BadInternalError</c> quality;
/// this layer doesn't swallow anything so tests can
/// assert on the original exception type.
/// </para>
/// <para>
/// Scripts are expected to be statement bodies that end with an explicit
/// <c>return …;</c> — the wrapper provides only the surrounding method body, so
/// the script's final-expression-yields-result behavior of legacy
/// <c>CSharpScript</c> is replaced by ordinary C# method semantics. Every script
/// in the existing test corpus already uses explicit <c>return</c>; this is a
/// documented authoring convention.
/// </para>
/// </remarks>
public sealed class ScriptEvaluator<TContext, TResult> : IDisposable
where TContext : ScriptContext
{
private readonly ScriptAssemblyLoadContext _alc;
private readonly Func<ScriptGlobals<TContext>, TResult> _func;
private bool _disposed;
private ScriptEvaluator(ScriptAssemblyLoadContext alc, Func<ScriptGlobals<TContext>, TResult> func)
{
_alc = alc;
_func = func;
}
/// <summary>Compiles user script source into an evaluator.</summary>
/// <param name="scriptSource">The user script source code to compile.</param>
/// <returns>A ready-to-run <see cref="ScriptEvaluator{TContext, TResult}"/> wrapping the compiled script.</returns>
public static ScriptEvaluator<TContext, TResult> Compile(string scriptSource) => FromImage(CompileToImage(scriptSource));
/// <summary>
/// The compile half of <see cref="Compile"/>: parse, sandbox compile, <see cref="ForbiddenTypeAnalyzer"/>, the
/// stack-guard rewrite and the emit — returning the PE bytes without loading them. The out-of-process worker
/// caches these bytes on disk (lmxopcua#780 design §7) so a restart does not re-enter Roslyn.
/// </summary>
/// <param name="scriptSource">The user script source code to compile.</param>
/// <returns>The emitted PE image.</returns>
/// <exception cref="CompilationErrorException">The source does not compile.</exception>
/// <exception cref="ScriptSandboxViolationException">The source uses a forbidden API.</exception>
public static byte[] CompileToImage(string scriptSource)
{
var compilation = BuildCheckedCompilation(scriptSource, out var syntaxTree);
// Step 3a — stack-depth guard (lmxopcua#779). Insert ScriptStackGuard.Check() at the entry of the script
// body and of every lambda / anonymous method / local function, so unbounded recursion fails the script with
// a catchable exception instead of a StackOverflowException that terminates the server. After the analyzer,
// so the analyzer and its diagnostics only ever see the user's code. The rewrite is designed to bind exactly
// as the original did; an emit failure here is an internal defect, reported like any other emit failure.
var guardedTree = ScriptStackGuardInjector.Inject(compilation, syntaxTree);
compilation = compilation.ReplaceSyntaxTree(syntaxTree, guardedTree);
// Step 4 — emit to an in-memory PE stream and load into a collectible ALC.
using var peStream = new MemoryStream();
var emitResult = compilation.Emit(peStream);
if (!emitResult.Success)
{
var emitErrors = emitResult.Diagnostics
.Where(d => d.Severity == DiagnosticSeverity.Error)
.ToArray();
throw new CompilationErrorException(emitErrors);
}
return peStream.ToArray();
}
/// <summary>
/// Every step of <see cref="CompileToImage"/> that can reject a USER script — wrap + parse, the
/// wrapper-injection guard, the sandbox compile and <see cref="ForbiddenTypeAnalyzer"/> — with no stack-guard
/// rewrite and no emit (those fail only on internal defects). The deploy-time script compile gate
/// (lmxopcua#971 follow-up, <c>RoslynDeployScriptChecker</c>) calls this, and it builds its compilation
/// through the SAME <see cref="BuildCheckedCompilation"/> the runtime compile does, so the gate accepts a
/// source exactly when the runtime compile would.
/// </summary>
/// <param name="scriptSource">The user script source code to check.</param>
/// <exception cref="CompilationErrorException">The source does not compile.</exception>
/// <exception cref="ScriptSandboxViolationException">The source uses a forbidden API.</exception>
public static void Verify(string scriptSource) => _ = BuildCheckedCompilation(scriptSource, out _);
/// <summary>
/// Steps 1–3 of the compile pipeline, shared by <see cref="CompileToImage"/> (runtime) and
/// <see cref="Verify"/> (deploy gate): returns the checked compilation and its wrapper tree, or throws.
/// </summary>
private static CSharpCompilation BuildCheckedCompilation(string scriptSource, out SyntaxTree syntaxTree)
{
if (scriptSource is null) throw new ArgumentNullException(nameof(scriptSource));
var sandbox = ScriptSandbox.Build(typeof(TContext));
// Step 1 — synthesize a wrapper class around the script body and parse it. The
// wrapper's `Run` method is what we invoke at runtime; the user's source is
// pasted in as its body so explicit `return` semantics apply.
var wrapperSource = WrapperPreamble + scriptSource + WrapperSuffix;
syntaxTree = CSharpSyntaxTree.ParseText(wrapperSource);
// Step 1a — defend against wrapper-source injection.
// A script body of `return 0; } public static int Evil() { return 0;` would
// close the synthesized `Run` method early, declare a sibling `Evil` method
// inside the synthesized `CompiledScript` class, and leave the wrapper's
// trailing `}` balanced. ForbiddenTypeAnalyzer still walks the injected
// members so this isn't a direct sandbox escape, but it relaxes the
// documented "method body" authoring contract and widens the analyzer's
// surface. Reject by requiring that the parsed `CompiledScript` class
// contains exactly one member declaration (the `Run` method).
// The rule lives in ScriptCompileRules so the Monaco editor applies the identical check (lmxopcua#1063).
if (ScriptCompileRules.WrapperInjection(syntaxTree) is { } injection)
throw new CompilationErrorException(new[] { injection });
// Step 2 — Roslyn compile against the sandbox allow-list. Anything not in the
// references set is unresolved and produces a compiler error.
var assemblyName = "ZB.MOM.WW.OtOpcUa.Core.Scripting.Compiled." +
Guid.NewGuid().ToString("N");
var compileOptions = new CSharpCompilationOptions(
OutputKind.DynamicallyLinkedLibrary,
optimizationLevel: OptimizationLevel.Release,
allowUnsafe: false,
// Don't generate XML doc warnings for the synthesized wrapper.
warningLevel: 4,
nullableContextOptions: NullableContextOptions.Enable);
var compilation = CSharpCompilation.Create(
assemblyName,
syntaxTrees: new[] { syntaxTree },
references: sandbox.References,
options: compileOptions);
// Every Error-severity diagnostic, wherever Roslyn pins it — including the ones it reports on the wrapper
// (CS0161 "not all code paths return a value" sits on Run). ScriptCompileRules is the one statement of this
// rule; the editor's diagnostics use it too (lmxopcua#1063).
var compileErrors = ScriptCompileRules.CompileErrors(compilation);
if (compileErrors.Count > 0)
throw new CompilationErrorException(compileErrors);
// Step 3 — the sandbox gate: the allow-list analyzer (lmxopcua#971). The narrowed
// reference set in step 2 is only defence in depth (CoreLib alone carries File / Thread / Assembly).
var rejections = ForbiddenTypeAnalyzer.Analyze(compilation);
if (rejections.Count > 0)
throw new ScriptSandboxViolationException(rejections);
return compilation;
}
/// <summary>
/// The load half of <see cref="Compile"/>: loads a PE image produced by <see cref="CompileToImage"/> into a fresh
/// collectible ALC and binds its <c>Run</c> method. The caller vouches for the image — only bytes this pipeline
/// emitted (the worker's HMAC-verified PE cache) may be passed, because loading arbitrary PE bytes would run
/// code the analyzer never saw.
/// </summary>
/// <param name="peImage">The image.</param>
/// <returns>A ready-to-run evaluator.</returns>
public static ScriptEvaluator<TContext, TResult> FromImage(byte[] peImage)
{
ArgumentNullException.ThrowIfNull(peImage);
using var peStream = new MemoryStream(peImage, writable: false);
var alc = new ScriptAssemblyLoadContext("ZB.MOM.WW.OtOpcUa.Core.Scripting.Compiled." + Guid.NewGuid().ToString("N"));
Assembly assembly;
try
{
assembly = alc.LoadFromStream(peStream);
}
catch
{
// Failed to load — drop the ALC so we don't leak a half-initialised one.
alc.Unload();
throw;
}
// Step 5 — resolve the wrapper's Run method and bind a typed delegate. The
// wrapper source above puts the type in this exact namespace + class — keep the
// names in sync with BuildWrapperPreamble.
Func<ScriptGlobals<TContext>, TResult> func;
try
{
var wrapperType = assembly.GetType(
"ZB.MOM.WW.OtOpcUa.Core.Scripting.Compiled.CompiledScript",
throwOnError: true)!;
var runMethod = wrapperType.GetMethod(
"Run",
BindingFlags.Public | BindingFlags.Static)
?? throw new InvalidOperationException(
"Synthesized wrapper is missing the public static Run method.");
func = (Func<ScriptGlobals<TContext>, TResult>)Delegate.CreateDelegate(
typeof(Func<ScriptGlobals<TContext>, TResult>), runMethod);
}
catch
{
alc.Unload();
throw;
}
return new ScriptEvaluator<TContext, TResult>(alc, func);
}
/// <summary>
/// A digest of everything that decides what <see cref="CompileToImage"/> emits for a given source, other than
/// the source itself (lmxopcua#780 design §7): the Roslyn version, this assembly's build identity (the
/// analyzer's allow-list, the wrapper template, the stack-guard rewrite), the sandbox reference set, the
/// runtime version and <typeparamref name="TContext"/> / <typeparamref name="TResult"/>. A compiled-PE cache
/// keys on it, so an analyzer or compiler change invalidates every cached image and a cached PE can never skip
/// a newer sandbox rule.
/// </summary>
public static byte[] CacheFingerprint => FingerprintHolder.Value;
private static readonly Lazy<byte[]> FingerprintHolder = new(ComputeFingerprint, LazyThreadSafetyMode.ExecutionAndPublication);
private static byte[] ComputeFingerprint()
{
var sb = new StringBuilder("otopcua-script-pe/1\n");
static void AppendAssembly(StringBuilder b, System.Reflection.Assembly a)
=> b.Append(a.FullName).Append('|').Append(a.ManifestModule.ModuleVersionId.ToString("N")).Append('\n');
AppendAssembly(sb, typeof(CSharpCompilation).Assembly);
AppendAssembly(sb, typeof(Compilation).Assembly);
AppendAssembly(sb, typeof(ScriptEvaluator<,>).Assembly);
sb.Append(Environment.Version).Append('\n');
sb.Append(typeof(TContext).AssemblyQualifiedName).Append('\n');
sb.Append(typeof(TResult).AssemblyQualifiedName).Append('\n');
foreach (var identity in ScriptSandbox.ReferenceIdentities(typeof(TContext))) sb.Append(identity).Append('\n');
return System.Security.Cryptography.SHA256.HashData(Encoding.UTF8.GetBytes(sb.ToString()));
}
/// <summary>Runs the script against an already-constructed context.</summary>
/// <param name="context">The script context.</param>
/// <param name="ct">Cancellation token for the operation.</param>
/// <returns>A task carrying the script's result.</returns>
public Task<TResult> RunAsync(TContext context, CancellationToken ct = default)
{
if (_disposed) throw new ObjectDisposedException(nameof(ScriptEvaluator<TContext, TResult>));
if (context is null) throw new ArgumentNullException(nameof(context));
ct.ThrowIfCancellationRequested();
var globals = new ScriptGlobals<TContext> { ctx = context };
// The user's script is synchronous (Roslyn emits a static method that returns
// TResult directly). We surface a Task<TResult> only to keep the existing
// RunAsync contract consumers depend on. TimedScriptEvaluator wraps this in
// Task.Run so a long-running script still honours its wall-clock budget.
// The run token is the script-visible ctx.CancellationToken for exactly this call. ScriptRunGuard passes
// the token it cancels on timeout, so a polling script can end its own abandoned run.
TResult result;
using (ScriptContext.EnterRun(ct))
{
result = _func(globals);
}
return Task.FromResult(result);
}
/// <summary>
/// Unload the collectible <see cref="AssemblyLoadContext"/> that holds the emitted
/// script assembly so the runtime can reclaim it. After disposal the evaluator can
/// no longer be invoked — call <see cref="ScriptEvaluator{TContext, TResult}.Compile"/>
/// again for a fresh one. Dispose is idempotent.
/// </summary>
/// <remarks>
/// Unload is <i>eligible-for-collection</i>, not synchronous: the assembly is
/// reclaimed when the GC determines no live references remain. The cache disposes
/// evaluators in <see cref="CompiledScriptCache{TContext, TResult}.Clear"/> so a
/// config-generation publish releases the prior generation in one sweep; the
/// reclaim then races with the next GC cycle. Tests verify the reclaim via
/// <see cref="WeakReference"/> + <see cref="GC.Collect()"/>.
/// </remarks>
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_alc.Unload();
}
/// <summary>
/// The text the runtime pastes BEFORE the user's script body: the sandbox's <c>using</c> directives (so scripts can
/// write <c>Math.Abs</c>), the <c>CompiledScript</c> class and the <c>Run(ScriptGlobals&lt;TContext&gt;)</c>
/// signature, <c>var ctx = globals.ctx;</c>, then <c>#line 1</c> so Roslyn's mapped positions are user-source
/// coordinates. Public so the Monaco editor analyses the exact same wrapper (lmxopcua#1063) — never rebuild it
/// elsewhere. Built with <c>\n</c> line ends on every platform, so the text (and every offset into it) is stable.
/// </summary>
public static string WrapperPreamble => PreambleHolder.Value;
/// <summary>The text the runtime appends AFTER the user's script body: closes <c>Run</c> and the class.</summary>
public const string WrapperSuffix = "\n }\n}\n";
private static readonly Lazy<string> PreambleHolder =
new(() => BuildWrapperPreamble(ScriptSandbox.Build(typeof(TContext)).Imports), LazyThreadSafetyMode.ExecutionAndPublication);
/// <summary>
/// Synthesize the wrapper preamble. The user's script body is pasted verbatim after it, inside
/// <c>CompiledScript.Run</c>, so explicit <c>return</c> semantics apply.
/// </summary>
private static string BuildWrapperPreamble(IReadOnlyList<string> imports)
{
var sb = new StringBuilder();
foreach (var import in imports)
sb.Append("using ").Append(import).Append(";\n");
sb.Append('\n');
sb.Append("namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Compiled;\n");
sb.Append('\n');
sb.Append("public static class CompiledScript\n");
sb.Append("{\n");
sb.Append(" public static ").Append(ToCSharpTypeName(typeof(TResult)))
.Append(" Run(").Append(ToCSharpTypeName(typeof(ScriptGlobals<TContext>)))
.Append(" globals)\n");
sb.Append(" {\n");
sb.Append(" var ctx = globals.ctx;\n");
// The user source ends with `return X;` per the authoring convention and is pasted verbatim after this line.
// #line 1 keeps Roslyn diagnostics' mapped line numbers usable by operators (errors point at the user's source
// line, not the wrapper).
sb.Append("#line 1\n");
return sb.ToString();
}
/// <summary>
/// Convert a runtime <see cref="Type"/> to a C# type-name string suitable for
/// emitting into Roslyn source. Uses <c>global::</c>-qualified FQNs to avoid
/// accidental capture by the wrapper's <c>using</c> directives, handles nested
/// types (<c>+</c> → <c>.</c>), and recurses for generic arguments so the
/// <c>ScriptGlobals&lt;TContext&gt;</c> parameter is emitted correctly.
/// </summary>
private static string ToCSharpTypeName(Type t)
{
if (t == typeof(void)) return "void";
// Primitive aliases keep the synthesized source readable when diagnostic
// logging dumps it; functionally identical to the FQN form.
if (t == typeof(bool)) return "bool";
if (t == typeof(byte)) return "byte";
if (t == typeof(sbyte)) return "sbyte";
if (t == typeof(short)) return "short";
if (t == typeof(ushort)) return "ushort";
if (t == typeof(int)) return "int";
if (t == typeof(uint)) return "uint";
if (t == typeof(long)) return "long";
if (t == typeof(ulong)) return "ulong";
if (t == typeof(float)) return "float";
if (t == typeof(double)) return "double";
if (t == typeof(decimal)) return "decimal";
if (t == typeof(string)) return "string";
if (t == typeof(object)) return "object";
if (Nullable.GetUnderlyingType(t) is { } inner)
return ToCSharpTypeName(inner) + "?";
if (t.IsArray)
return ToCSharpTypeName(t.GetElementType()!) + "[]";
if (t.IsGenericType)
{
// Walk the FullName by '.' segments (after '+ → .'). For each segment
// ending with `Name\`N`, consume N generic arguments and emit them as
// `<…>` on that segment. Nested generic-in-generic (Outer<T>.Inner<U>)
// emits as `global::Ns.Outer<T>.Inner<U>` — valid C#. The pre-fix code
// used `IndexOf('`')` to find the FIRST backtick and truncated the
// entire name there, silently dropping the rest of the nested-generic
// closed args.
var rawName = t.GetGenericTypeDefinition().FullName!.Replace('+', '.');
var allArgs = t.GetGenericArguments();
var segments = rawName.Split('.');
var argIndex = 0;
var sb = new StringBuilder("global::");
for (int i = 0; i < segments.Length; i++)
{
if (i > 0) sb.Append('.');
var seg = segments[i];
var backtick = seg.IndexOf('`');
if (backtick >= 0)
{
var arity = int.Parse(seg.AsSpan(backtick + 1));
sb.Append(seg, 0, backtick);
sb.Append('<');
for (int j = 0; j < arity; j++)
{
if (j > 0) sb.Append(", ");
sb.Append(ToCSharpTypeName(allArgs[argIndex++]));
}
sb.Append('>');
}
else
{
sb.Append(seg);
}
}
return sb.ToString();
}
return "global::" + t.FullName!.Replace('+', '.');
}
}
/// <summary>
/// Collectible <see cref="AssemblyLoadContext"/> that hosts a single emitted script
/// assembly. Created per <see cref="ScriptEvaluator{TContext, TResult}"/> instance so
/// <see cref="AssemblyLoadContext.Unload"/> releases exactly that script. Resolves
/// dependencies via the default ALC — script assemblies reference the BCL + the
/// application's own types, all of which live in the default context.
/// </summary>
internal sealed class ScriptAssemblyLoadContext : AssemblyLoadContext
{
/// <summary>Initializes a new instance of the <see cref="ScriptAssemblyLoadContext"/> class.</summary>
/// <param name="name">The name of the assembly load context.</param>
public ScriptAssemblyLoadContext(string name) : base(name, isCollectible: true)
{
}
/// <inheritdoc />
protected override Assembly? Load(AssemblyName assemblyName) => null;
}
/// <summary>
/// Thrown by <see cref="ScriptEvaluator{TContext, TResult}.Compile"/> when Roslyn
/// reports compile-time errors against the wrapper source. Mirrors the
/// <c>Microsoft.CodeAnalysis.Scripting.CompilationErrorException</c> from the legacy
/// <c>CSharpScript</c> path so callers (engines + the Admin test-harness) keep the
/// same catch site after the rewrite.
/// </summary>
public sealed class CompilationErrorException : Exception
{
/// <summary>Gets the compilation diagnostics that caused the error.</summary>
public IReadOnlyList<Diagnostic> Diagnostics { get; }
/// <summary>Initializes a new instance of the <see cref="CompilationErrorException"/> class.</summary>
/// <param name="diagnostics">The compilation diagnostics that caused the error.</param>
public CompilationErrorException(IReadOnlyList<Diagnostic> diagnostics)
: base(BuildMessage(diagnostics))
{
Diagnostics = diagnostics;
}
private static string BuildMessage(IReadOnlyList<Diagnostic> diagnostics)
{
if (diagnostics.Count == 0) return "Script compile failed.";
// Operators see this — match the legacy Roslyn format ("(line,col): error CSxxxx:
// message") so existing operator runbooks still match.
var first = diagnostics[0];
var rest = diagnostics.Count == 1 ? "" : $" (and {diagnostics.Count - 1} more)";
return first.ToString() + rest;
}
}