using System.Reflection; using System.Runtime.Loader; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; namespace ZB.MOM.WW.OtOpcUa.Core.Scripting; /// /// Compiles + runs user scripts against a subclass. Core /// evaluator — no caching, no timeout, no logging side-effects (those land in /// , /// , and /// respectively). /// /// /// /// Scripts are wrapped in a synthesized CompiledScript.Run(globals) method /// and compiled via into a regular .NET assembly /// that is loaded into a collectible /// . The collectible ALC fixes unbounded /// per-publish recompile accretion: previously /// Roslyn's CSharpScript.CreateDelegate emitted into the default ALC /// (non-collectible); now unloads the entire ALC and the /// emitted assembly becomes eligible for GC. /// /// /// Compile pipeline is a three-step gate, unchanged in intent from the legacy /// CSharpScript path: (1) Roslyn parse + compile against the /// allow-list — catches syntax errors, unresolved /// types (the sandbox's first line of defense), and most type-resolution /// failures, throwing ; (2) /// 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 ; (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 on entry to every script-declared body, so unbounded /// recursion fails the script instead of overflowing the stack and terminating the process /// (, lmxopcua#779). /// /// /// Runtime exceptions thrown from user code propagate unwrapped. The virtual-tag /// engine catches them per-tag and maps to BadInternalError quality; /// this layer doesn't swallow anything so tests can /// assert on the original exception type. /// /// /// Scripts are expected to be statement bodies that end with an explicit /// return …; — the wrapper provides only the surrounding method body, so /// the script's final-expression-yields-result behavior of legacy /// CSharpScript is replaced by ordinary C# method semantics. Every script /// in the existing test corpus already uses explicit return; this is a /// documented authoring convention. /// /// public sealed class ScriptEvaluator : IDisposable where TContext : ScriptContext { private readonly ScriptAssemblyLoadContext _alc; private readonly Func, TResult> _func; private bool _disposed; private ScriptEvaluator(ScriptAssemblyLoadContext alc, Func, TResult> func) { _alc = alc; _func = func; } /// Compiles user script source into an evaluator. /// The user script source code to compile. /// A ready-to-run wrapping the compiled script. public static ScriptEvaluator Compile(string scriptSource) => FromImage(CompileToImage(scriptSource)); /// /// The compile half of : parse, sandbox compile, , 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. /// /// The user script source code to compile. /// The emitted PE image. /// The source does not compile. /// The source uses a forbidden API. 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(); } /// /// Every step of that can reject a USER script — wrap + parse, the /// wrapper-injection guard, the sandbox compile and — with no stack-guard /// rewrite and no emit (those fail only on internal defects). The deploy-time script compile gate /// (lmxopcua#971 follow-up, RoslynDeployScriptChecker) calls this, and it builds its compilation /// through the SAME the runtime compile does, so the gate accepts a /// source exactly when the runtime compile would. /// /// The user script source code to check. /// The source does not compile. /// The source uses a forbidden API. public static void Verify(string scriptSource) => _ = BuildCheckedCompilation(scriptSource, out _); /// /// Steps 1–3 of the compile pipeline, shared by (runtime) and /// (deploy gate): returns the checked compilation and its wrapper tree, or throws. /// 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; } /// /// The load half of : loads a PE image produced by into a fresh /// collectible ALC and binds its Run 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. /// /// The image. /// A ready-to-run evaluator. public static ScriptEvaluator 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, 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, TResult>)Delegate.CreateDelegate( typeof(Func, TResult>), runMethod); } catch { alc.Unload(); throw; } return new ScriptEvaluator(alc, func); } /// /// A digest of everything that decides what 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 / . 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. /// public static byte[] CacheFingerprint => FingerprintHolder.Value; private static readonly Lazy 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())); } /// Runs the script against an already-constructed context. /// The script context. /// Cancellation token for the operation. /// A task carrying the script's result. public Task RunAsync(TContext context, CancellationToken ct = default) { if (_disposed) throw new ObjectDisposedException(nameof(ScriptEvaluator)); if (context is null) throw new ArgumentNullException(nameof(context)); ct.ThrowIfCancellationRequested(); var globals = new ScriptGlobals { ctx = context }; // The user's script is synchronous (Roslyn emits a static method that returns // TResult directly). We surface a Task 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); } /// /// Unload the collectible that holds the emitted /// script assembly so the runtime can reclaim it. After disposal the evaluator can /// no longer be invoked — call /// again for a fresh one. Dispose is idempotent. /// /// /// Unload is eligible-for-collection, not synchronous: the assembly is /// reclaimed when the GC determines no live references remain. The cache disposes /// evaluators in 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 /// + . /// public void Dispose() { if (_disposed) return; _disposed = true; _alc.Unload(); } /// /// The text the runtime pastes BEFORE the user's script body: the sandbox's using directives (so scripts can /// write Math.Abs), the CompiledScript class and the Run(ScriptGlobals<TContext>) /// signature, var ctx = globals.ctx;, then #line 1 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 \n line ends on every platform, so the text (and every offset into it) is stable. /// public static string WrapperPreamble => PreambleHolder.Value; /// The text the runtime appends AFTER the user's script body: closes Run and the class. public const string WrapperSuffix = "\n }\n}\n"; private static readonly Lazy PreambleHolder = new(() => BuildWrapperPreamble(ScriptSandbox.Build(typeof(TContext)).Imports), LazyThreadSafetyMode.ExecutionAndPublication); /// /// Synthesize the wrapper preamble. The user's script body is pasted verbatim after it, inside /// CompiledScript.Run, so explicit return semantics apply. /// private static string BuildWrapperPreamble(IReadOnlyList 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))) .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(); } /// /// Convert a runtime to a C# type-name string suitable for /// emitting into Roslyn source. Uses global::-qualified FQNs to avoid /// accidental capture by the wrapper's using directives, handles nested /// types (+ → .), and recurses for generic arguments so the /// ScriptGlobals<TContext> parameter is emitted correctly. /// 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.Inner) // emits as `global::Ns.Outer.Inner` — 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('+', '.'); } } /// /// Collectible that hosts a single emitted script /// assembly. Created per instance so /// 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. /// internal sealed class ScriptAssemblyLoadContext : AssemblyLoadContext { /// Initializes a new instance of the class. /// The name of the assembly load context. public ScriptAssemblyLoadContext(string name) : base(name, isCollectible: true) { } /// protected override Assembly? Load(AssemblyName assemblyName) => null; } /// /// Thrown by when Roslyn /// reports compile-time errors against the wrapper source. Mirrors the /// Microsoft.CodeAnalysis.Scripting.CompilationErrorException from the legacy /// CSharpScript path so callers (engines + the Admin test-harness) keep the /// same catch site after the rewrite. /// public sealed class CompilationErrorException : Exception { /// Gets the compilation diagnostics that caused the error. public IReadOnlyList Diagnostics { get; } /// Initializes a new instance of the class. /// The compilation diagnostics that caused the error. public CompilationErrorException(IReadOnlyList diagnostics) : base(BuildMessage(diagnostics)) { Diagnostics = diagnostics; } private static string BuildMessage(IReadOnlyList 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; } }