From 1894eb47f58458315345897898f43fae68fa7c6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Larch?= Date: Wed, 21 Oct 2026 21:06:48 +0200 Subject: [PATCH 1/5] Initialize linked modules within the current JS value scope Calling process._linkedBinding() for a module registered through NodeEmbeddingRuntimeSettings.Modules failed or crashed the process (#464): - From a script run via NodeEmbeddingThreadRuntime.Run: "A Root scope cannot be created within another scope." - From MainScript: the nested root scope dropped its parent on dispose, so the thread was left without a current scope ("There is no active JS value scope", reported as a stack overflow in the issue). - From an ES module imported via ImportAsync: native assertion "(v8_scope_data_->nest_level()) == (nest_level)" in CloseV8Scope. ModuleInitializeCallbackAdapter always opened a new root scope for the napi_env that Node.js creates for each linked module. Modules are initialized lazily, while the runtime's scope is normally current on the JS thread, so open a callback scope within it instead and only fall back to a root scope when no scope is current. The module's exports then share the runtime's context, and later calls from JS into the exported .NET callbacks find a matching parent scope. Fixes #464. Co-Authored-By: Claude Opus 5.5 --- src/NodeApi/Runtime/NodeEmbedding.cs | 9 ++- test/NodejsEmbeddingTests.cs | 97 ++++++++++++++++++++++++++++ test/test-linked-module.mjs | 2 + 3 files changed, 107 insertions(+), 1 deletion(-) create mode 100644 test/test-linked-module.mjs diff --git a/src/NodeApi/Runtime/NodeEmbedding.cs b/src/NodeApi/Runtime/NodeEmbedding.cs index 7c9b74d1..fb0e06df 100644 --- a/src/NodeApi/Runtime/NodeEmbedding.cs +++ b/src/NodeApi/Runtime/NodeEmbedding.cs @@ -433,7 +433,14 @@ internal static unsafe napi_value ModuleInitializeCallbackAdapter( nint module_name, napi_value exports) { - using var jsValueScope = new JSValueScope(JSValueScopeType.Root, env, JSRuntime); + // Linked modules are initialized lazily by process._linkedBinding(), so the runtime's + // scope is usually current on this thread. Node.js passes a separate napi_env for each + // module; nesting a root scope for it would fail or, on dispose, leave the thread + // without a current scope. Initialize the module within the runtime's scope instead, + // so that its exports share the runtime context and later callbacks into them work. + using var jsValueScope = JSValueScope.CurrentOrNull != null + ? new JSValueScope(JSValueScopeType.Callback) + : new JSValueScope(JSValueScopeType.Root, env, JSRuntime); try { var callback = (InitializeModuleCallback)GCHandle.FromIntPtr(cb_data).Target!; diff --git a/test/NodejsEmbeddingTests.cs b/test/NodejsEmbeddingTests.cs index 5fd80188..78502b7c 100644 --- a/test/NodejsEmbeddingTests.cs +++ b/test/NodejsEmbeddingTests.cs @@ -5,6 +5,7 @@ using System; using System.Diagnostics; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; @@ -420,6 +421,102 @@ public void ThrowTypedError(string errorType, string? code) }); } + private static NodeEmbeddingThreadRuntime CreateRuntimeWithLinkedModule( + string mainScript = "") + { + NodeEmbeddingModuleInfo linkedModule = new() + { + Name = "test-linked", + NodeApiVersion = NodeEmbedding.NodeApiVersion, + OnInitialize = (runtime, moduleName, exports) => + { + exports.SetProperty("moduleName", moduleName); + exports.SetProperty("add", JSValue.CreateFunction( + "add", (args) => (int)args[0] + (int)args[1])); + return exports; + }, + }; + + // Modules are registered on the runtime thread while it is configured, so dirty the + // array pool lazily from there, right before the module name is marshalled. + static IEnumerable WithGarbageInArrayPool( + NodeEmbeddingModuleInfo module) + { + FillArrayPoolWithGarbage(); + yield return module; + } + + return NodejsPlatform.CreateThreadRuntime( + Path.Combine(GetRepoRootDirectory(), "test"), + new NodeEmbeddingRuntimeSettings + { + MainScript = MainScript + mainScript, + Modules = WithGarbageInArrayPool(linkedModule), + }); + } + + private static void AssertJSThreadIsUsable(NodeEmbeddingThreadRuntime nodejs) + { + nodejs.Run(() => + { + Assert.Equal(3, (int)JSValue.RunScript("1 + 2")); + }); + } + + [Fact] + public void LinkedModuleFromScript() + { + using NodeEmbeddingThreadRuntime nodejs = CreateRuntimeWithLinkedModule(); + + nodejs.Run(() => + { + JSValue linked = JSValue.RunScript("process._linkedBinding('test-linked')"); + Assert.Equal("test-linked", (string)linked["moduleName"]); + Assert.Equal(3, (int)linked.CallMethod("add", 1, 2)); + + // The scope that was current before the module was initialized must be restored. + Assert.Equal(3, (int)JSValue.RunScript("1 + 2")); + }); + + AssertJSThreadIsUsable(nodejs); + nodejs.Dispose(); + Assert.Equal(0, nodejs.ExitCode); + } + + [Fact] + public void LinkedModuleFromMainScript() + { + using NodeEmbeddingThreadRuntime nodejs = CreateRuntimeWithLinkedModule( + "globalThis.linked = process._linkedBinding('test-linked');\n"); + + nodejs.Run(() => + { + Assert.Equal(3, (int)JSValue.RunScript("globalThis.linked.add(1, 2)")); + }); + + AssertJSThreadIsUsable(nodejs); + nodejs.Dispose(); + Assert.Equal(0, nodejs.ExitCode); + } + + [Fact] + public async Task LinkedModuleFromESModule() + { + using NodeEmbeddingThreadRuntime nodejs = CreateRuntimeWithLinkedModule(); + + int result = await nodejs.RunAsync(async () => + { + JSValue testModule = await nodejs.ImportAsync( + "./test-linked-module.mjs", null, esModule: true); + return (int)testModule["result"]; + }); + Assert.Equal(3, result); + + AssertJSThreadIsUsable(nodejs); + nodejs.Dispose(); + Assert.Equal(0, nodejs.ExitCode); + } + [Fact] public async Task WorkerIsMainThread() { diff --git a/test/test-linked-module.mjs b/test/test-linked-module.mjs new file mode 100644 index 00000000..0d0e31e2 --- /dev/null +++ b/test/test-linked-module.mjs @@ -0,0 +1,2 @@ +const { add } = process._linkedBinding('test-linked'); +export const result = add(1, 2); From e853a6fe4f3732f63de4167be03816ca0b695dea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Larch?= Date: Wed, 21 Oct 2026 22:28:44 +0200 Subject: [PATCH 2/5] Report linked module init errors to the module's env Addresses review feedback on #512: - Node-API tracks pending exceptions per napi_env, and Node.js only reports those of the module's env to the caller of process._linkedBinding(). Errors thrown by the initializer within the runtime's scope were only logged as "Uncaught N-API callback exception" (DEP0168). Move a pending exception from the scope's env to the module's env before returning. - A callback scope cannot be nested in a handle or escapable scope, so initializing a module while one is current threw outside the adapter's try/catch. Use the current scope as is in that case. Co-Authored-By: Claude Opus 5.5 --- src/NodeApi/Runtime/NodeEmbedding.cs | 24 +++++++++-- test/NodejsEmbeddingTests.cs | 59 ++++++++++++++++++++++++++-- 2 files changed, 77 insertions(+), 6 deletions(-) diff --git a/src/NodeApi/Runtime/NodeEmbedding.cs b/src/NodeApi/Runtime/NodeEmbedding.cs index fb0e06df..5224f9ba 100644 --- a/src/NodeApi/Runtime/NodeEmbedding.cs +++ b/src/NodeApi/Runtime/NodeEmbedding.cs @@ -438,9 +438,14 @@ internal static unsafe napi_value ModuleInitializeCallbackAdapter( // module; nesting a root scope for it would fail or, on dispose, leave the thread // without a current scope. Initialize the module within the runtime's scope instead, // so that its exports share the runtime context and later callbacks into them work. - using var jsValueScope = JSValueScope.CurrentOrNull != null - ? new JSValueScope(JSValueScopeType.Callback) - : new JSValueScope(JSValueScopeType.Root, env, JSRuntime); + // A callback scope cannot be nested in a handle scope, so that is used as is. + using JSValueScope? jsValueScope = JSValueScope.CurrentOrNull?.ScopeType switch + { + null => new JSValueScope(JSValueScopeType.Root, env, JSRuntime), + JSValueScopeType.Handle or JSValueScopeType.Escapable => null, + _ => new JSValueScope(JSValueScopeType.Callback), + }; + napi_env scopeEnv = JSValueScope.Current.UncheckedEnvironmentHandle; try { var callback = (InitializeModuleCallback)GCHandle.FromIntPtr(cb_data).Target!; @@ -455,6 +460,19 @@ internal static unsafe napi_value ModuleInitializeCallbackAdapter( JSError.ThrowError(ex); return napi_value.Null; } + finally + { + // Pending exceptions are tracked per napi_env, and Node.js only reports those of the + // module's env to the caller of process._linkedBinding(). + if (scopeEnv != env && + JSRuntime.IsExceptionPending(scopeEnv, out bool isPending) == napi_status.napi_ok && + isPending && + JSRuntime.GetAndClearLastException(scopeEnv, out napi_value error) == + napi_status.napi_ok) + { + JSRuntime.Throw(env, error); + } + } } #if UNMANAGED_DELEGATES diff --git a/test/NodejsEmbeddingTests.cs b/test/NodejsEmbeddingTests.cs index 78502b7c..9b0cf0cd 100644 --- a/test/NodejsEmbeddingTests.cs +++ b/test/NodejsEmbeddingTests.cs @@ -422,19 +422,20 @@ public void ThrowTypedError(string errorType, string? code) } private static NodeEmbeddingThreadRuntime CreateRuntimeWithLinkedModule( - string mainScript = "") + string mainScript = "", + NodeEmbedding.InitializeModuleCallback? onInitialize = null) { NodeEmbeddingModuleInfo linkedModule = new() { Name = "test-linked", NodeApiVersion = NodeEmbedding.NodeApiVersion, - OnInitialize = (runtime, moduleName, exports) => + OnInitialize = onInitialize ?? ((runtime, moduleName, exports) => { exports.SetProperty("moduleName", moduleName); exports.SetProperty("add", JSValue.CreateFunction( "add", (args) => (int)args[0] + (int)args[1])); return exports; - }, + }), }; // Modules are registered on the runtime thread while it is configured, so dirty the @@ -517,6 +518,58 @@ public async Task LinkedModuleFromESModule() Assert.Equal(0, nodejs.ExitCode); } + [Fact] + public void LinkedModuleFromHandleScope() + { + using NodeEmbeddingThreadRuntime nodejs = CreateRuntimeWithLinkedModule(); + + nodejs.Run(() => + { + using JSValueScope handleScope = new(); + Assert.Equal( + "test-linked", + (string)JSValue.RunScript("process._linkedBinding('test-linked').moduleName")); + }); + + AssertJSThreadIsUsable(nodejs); + nodejs.Dispose(); + Assert.Equal(0, nodejs.ExitCode); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void LinkedModuleInitializationError(bool throwJSError) + { + using NodeEmbeddingThreadRuntime nodejs = CreateRuntimeWithLinkedModule( + onInitialize: (runtime, moduleName, exports) => + { + if (throwJSError) + { + JSError.ThrowError("init failed"); + return exports; + } + + throw new InvalidOperationException("init failed"); + }); + + nodejs.Run(() => + { + // The error must reach the caller of process._linkedBinding(). + JSValue result = JSValue.RunScript(""" + (() => { + try { process._linkedBinding('test-linked'); } catch (e) { return e.message; } + return 'not thrown'; + })() + """); + Assert.Equal("init failed", (string)result); + }); + + AssertJSThreadIsUsable(nodejs); + nodejs.Dispose(); + Assert.Equal(0, nodejs.ExitCode); + } + [Fact] public async Task WorkerIsMainThread() { From 2bce6a1e42f52a13a69ee00c8a0a2edf74cb7a27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Larch?= Date: Wed, 18 Nov 2026 10:48:40 +0100 Subject: [PATCH 3/5] Adapt the linked module init error test to LibNode 26 With LibNode 26 the error thrown by a linked module's init function no longer reaches the caller of process._linkedBinding(): Node.js GetLinkedBinding() reads module.exports after the init function returns, and that V8 API call clears the pending exception. This affects every linked binding and is fixed in https://github.com/nodejs/node/pull/67571. The test now checks that the error does not stay pending on the runtime's env, which fails without moving it to the module's env. Co-Authored-By: Claude Opus 5.5 --- test/NodejsEmbeddingTests.cs | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/test/NodejsEmbeddingTests.cs b/test/NodejsEmbeddingTests.cs index 9b0cf0cd..0774ffb5 100644 --- a/test/NodejsEmbeddingTests.cs +++ b/test/NodejsEmbeddingTests.cs @@ -555,14 +555,12 @@ public void LinkedModuleInitializationError(bool throwJSError) nodejs.Run(() => { - // The error must reach the caller of process._linkedBinding(). - JSValue result = JSValue.RunScript(""" - (() => { - try { process._linkedBinding('test-linked'); } catch (e) { return e.message; } - return 'not thrown'; - })() - """); - Assert.Equal("init failed", (string)result); + // The error is moved to the module's env. It does not reach this catch with + // LibNode 26 (https://github.com/nodejs/node/pull/67571), but it must not stay + // pending on the runtime's env either, or the next call fails. + JSValue.RunScript("try { process._linkedBinding('test-linked'); } catch {}"); + + Assert.Equal(3, (int)JSValue.RunScript("1 + 2")); }); AssertJSThreadIsUsable(nodejs); From 2167f6334d7728a6ba510e789045f69c7e345617 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Larch?= Date: Wed, 18 Nov 2026 23:57:06 +0100 Subject: [PATCH 4/5] Fix imports ordering in NodejsEmbeddingTests Co-Authored-By: Claude Opus 5.5 --- test/NodejsEmbeddingTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/NodejsEmbeddingTests.cs b/test/NodejsEmbeddingTests.cs index 0774ffb5..7ca71adf 100644 --- a/test/NodejsEmbeddingTests.cs +++ b/test/NodejsEmbeddingTests.cs @@ -4,8 +4,8 @@ #pragma warning disable CA1822 // Mark members as static using System; -using System.Diagnostics; using System.Collections.Generic; +using System.Diagnostics; using System.IO; using System.Linq; using System.Text; From 1a01c64f278605f2d66c011e35b707f2091325b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Larch?= Date: Thu, 19 Nov 2026 11:19:12 +0100 Subject: [PATCH 5/5] Assert linked module init errors again with LibNode 26.1.2 LibNode 26.1.2 includes the fix for the init error being cleared in GetLinkedBinding() (microsoft/v8-jsi#289), so the error reaches the caller of process._linkedBinding() again. Co-Authored-By: Claude Opus 5.5 --- test/NodejsEmbeddingTests.cs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/test/NodejsEmbeddingTests.cs b/test/NodejsEmbeddingTests.cs index 7ca71adf..72742639 100644 --- a/test/NodejsEmbeddingTests.cs +++ b/test/NodejsEmbeddingTests.cs @@ -555,12 +555,14 @@ public void LinkedModuleInitializationError(bool throwJSError) nodejs.Run(() => { - // The error is moved to the module's env. It does not reach this catch with - // LibNode 26 (https://github.com/nodejs/node/pull/67571), but it must not stay - // pending on the runtime's env either, or the next call fails. - JSValue.RunScript("try { process._linkedBinding('test-linked'); } catch {}"); - - Assert.Equal(3, (int)JSValue.RunScript("1 + 2")); + // The error must reach the caller of process._linkedBinding(). + JSValue result = JSValue.RunScript(""" + (() => { + try { process._linkedBinding('test-linked'); } catch (e) { return e.message; } + return 'not thrown'; + })() + """); + Assert.Equal("init failed", (string)result); }); AssertJSThreadIsUsable(nodejs);