diff --git a/bench/Benchmarks.cs b/bench/Benchmarks.cs
index c3461ab5..937ff8f6 100644
--- a/bench/Benchmarks.cs
+++ b/bench/Benchmarks.cs
@@ -144,7 +144,7 @@ protected void Setup()
_reference = new JSReference(_jsFunction);
}
- private static JSValueScope NewJSScope() => new(JSValueScopeType.Callback);
+ private static JSValueScope NewJSScope() => JSValueScope.CreateRuntimeScope();
// Benchmarks in the base class run in both CLR and AOT environments.
diff --git a/docs/features/js-value-scopes.md b/docs/features/js-value-scopes.md
index de332411..0a25fc59 100644
--- a/docs/features/js-value-scopes.md
+++ b/docs/features/js-value-scopes.md
@@ -7,9 +7,8 @@ A value is only valid within its scope; if the scope is closed (disposed), then
access or use the value will throw
[`JSValueScopeClosedException`](../reference/dotnet/Microsoft.JavaScript.NodeApi/JSValueScopeClosedException).
-Values received by a .NET method that is a JS callback are associated with a `Callback`
-[scope type](../reference/dotnet/Microsoft.JavaScript.NodeApi/JSValueScopeType). When the method
-returns, the callback scope is closed and any values in that scope become invalid.
+Values received by a .NET method that is a JS callback belong to the current scope for that call.
+When the method returns, that scope is closed and any values in it become invalid.
## Nesting and escaping scopes
@@ -23,7 +22,7 @@ JSFunction jsFunction = …
foreach (string item in array)
{
- using (var nestedScope = new JSValueScope())
+ using (var nestedScope = JSValueScope.CreateHandleScope())
{
// Passing a .NET string to JS requires converting it to JSValue.
// The conversion is implicit; the explicit cast is for illustration.
@@ -44,7 +43,7 @@ public JSValue EscapableScopeExample(JSCallbackArgs args)
foreach (string item in array)
{
- using (var escapableScope = new JSValueScope(JSValueScopeType.Escapable))
+ using (var escapableScope = JSValueScope.CreateEscapableScope())
{
JSValue result = jsFunction.Call(thisArg: default, (JSValue)item);
if (!result.IsUndefined())
diff --git a/docs/features/type-definitions.md b/docs/features/type-definitions.md
index 3d2ce4b5..aafbfb66 100644
--- a/docs/features/type-definitions.md
+++ b/docs/features/type-definitions.md
@@ -20,7 +20,7 @@ The easiest way to generate type definitions is to leverage the provided MSBuild
the `Microsoft.JavaScript.NodeApi.Generator` NuGet package:
```xml
-
+
```
diff --git a/docs/scenarios/js-dotnet-module.md b/docs/scenarios/js-dotnet-module.md
index 08b04808..23329fcc 100644
--- a/docs/scenarios/js-dotnet-module.md
+++ b/docs/scenarios/js-dotnet-module.md
@@ -20,8 +20,8 @@ For a minimal example of this scenario, see
Afterward you should have the two references in your project file:
```xml
-
-
+
+
```
diff --git a/examples/hermes-engine/HermesRuntime.cs b/examples/hermes-engine/HermesRuntime.cs
index 1e862c99..37df0ede 100644
--- a/examples/hermes-engine/HermesRuntime.cs
+++ b/examples/hermes-engine/HermesRuntime.cs
@@ -30,7 +30,8 @@ private HermesRuntime(JSDispatcherQueue dispatcherQueue)
JSRuntime runtime = HermesApi.Load("hermes.dll");
using HermesConfig tempConfig = new();
hermes_create_runtime((hermes_config)tempConfig, out _runtime).ThrowIfFailed();
- _rootScope = new JSValueScope(JSValueScopeType.Root, (napi_env)this, runtime);
+ JSRuntimeContext context = JSRuntimeContext.Create((napi_env)this, runtime);
+ _rootScope = JSValueScope.CreateRuntimeScope((napi_env)this, context);
CreatePolyfills();
}
@@ -98,7 +99,7 @@ public static explicit operator napi_env(HermesRuntime value)
private void CreatePolyfills()
{
VerifyElseThrow(JSDispatcherQueue.GetForCurrentThread() == _dispatcherQueue);
- using var scope = new JSValueScope();
+ using var scope = JSValueScope.CreateHandleScope();
// Add global
JSValue global = JSValue.Global;
diff --git a/src/NodeApi.DotNetHost/JSMarshaller.cs b/src/NodeApi.DotNetHost/JSMarshaller.cs
index 25c164b2..8f8e00b8 100644
--- a/src/NodeApi.DotNetHost/JSMarshaller.cs
+++ b/src/NodeApi.DotNetHost/JSMarshaller.cs
@@ -89,9 +89,9 @@ public JSMarshaller()
typeof(JSRuntimeContext).GetStaticProperty(nameof(JSRuntimeContext.Current))
?? throw new NotImplementedException("JSRuntimeContext.Current");
- private static readonly PropertyInfo s_moduleContext =
- typeof(JSModuleContext).GetStaticProperty(nameof(JSModuleContext.Current))
- ?? throw new NotImplementedException("JSModuleContext.Current");
+ private static readonly PropertyInfo s_currentScope =
+ typeof(JSValueScope).GetStaticProperty(nameof(JSValueScope.Current))
+ ?? throw new NotImplementedException("JSValueScope.Current");
private static readonly PropertyInfo s_valueItem =
typeof(JSValue).GetIndexer(typeof(string))
@@ -1878,22 +1878,22 @@ private IEnumerable BuildThisArgumentExpressions(
if (type.GetCustomAttributes().Any())
{
- // For a method on a module class, the .NET object is stored in the module context.
+ // For a method on a module class, the .NET object is the current module instance.
// `ThisArg` is ignored for module-level methods.
/*
- * ObjectType? __this = JSRuntimeContext.Current.Module as ObjectType;
+ * ObjectType? __this = JSValueScope.Current.Module as ObjectType;
* if (__this == null) return JSValue.Undefined;
*/
- PropertyInfo moduleProperty = typeof(JSModuleContext).GetProperty(
- nameof(JSModuleContext.Module))
- ?? throw new NotImplementedException("JSModuleContext.Module");
+ PropertyInfo moduleProperty = typeof(JSValueScope).GetProperty(
+ nameof(JSValueScope.Module))
+ ?? throw new NotImplementedException("JSValueScope.Module");
yield return Expression.Assign(
thisVariable,
Expression.TypeAs(
Expression.Property(
- Expression.Property(null, s_moduleContext),
+ Expression.Property(null, s_currentScope),
moduleProperty),
type));
yield return Expression.IfThen(
diff --git a/src/NodeApi.DotNetHost/ManagedHost.cs b/src/NodeApi.DotNetHost/ManagedHost.cs
index 402befe6..37542681 100644
--- a/src/NodeApi.DotNetHost/ManagedHost.cs
+++ b/src/NodeApi.DotNetHost/ManagedHost.cs
@@ -34,13 +34,15 @@ public sealed class ManagedHost : JSEventEmitter, IDisposable
#if !(NETFRAMEWORK || NETSTANDARD)
///
- /// Each instance of a managed host uses a separate assembly load context.
- /// That way, static data is not shared across multiple host instances.
+ /// Each instance of a managed host uses a separate assembly load context, so static data is not
+ /// shared across host instances. It is not collectible: JSInterfaceMarshaller emits interface
+ /// adapter types with Reflection.Emit, which a collectible load context does not support, so the
+ /// context cannot be unloaded at teardown (only its resolve handlers are unsubscribed).
///
private readonly AssemblyLoadContext _loadContext = new(name: default);
#endif
- private JSValueScope? _rootScope;
+ private JSRuntimeContext? _context;
///
/// Component that dynamically exports types from loaded assemblies.
@@ -177,10 +179,14 @@ public static unsafe int InitializeModule(string argument)
napi_env env = new((nint)ulong.Parse(args[0], NumberStyles.HexNumber));
napi_value exports = new((nint)ulong.Parse(args[1], NumberStyles.HexNumber));
napi_value* pResult = (napi_value*)(nint)ulong.Parse(args[2], NumberStyles.HexNumber);
+ ManagedHostRegistration* registration = args.Length > 3 ?
+ (ManagedHostRegistration*)(nint)ulong.Parse(args[3], NumberStyles.HexNumber) : null;
#else
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
- public static napi_value InitializeModule(napi_env env, napi_value exports)
+ public static unsafe napi_value InitializeModule(
+ napi_env env, napi_value exports, nint registrationPtr)
{
+ ManagedHostRegistration* registration = (ManagedHostRegistration*)registrationPtr;
Trace($"> ManagedHost.InitializeModule({env.Handle:X8})");
Trace($" .NET Runtime version: {Environment.Version}");
#endif
@@ -198,10 +204,20 @@ public static napi_value InitializeModule(napi_env env, napi_value exports)
runtime = new TracingJSRuntime(runtime, trace);
}
- JSValueScope scope = new(JSValueScopeType.Root, env, runtime);
+ // The managed host registers its context in the environment instance-data block (at the
+ // module slot). When hosted, the native host owns that block and its finalizer signals
+ // environment teardown, so the managed context is a non-owner: it writes its own slot but
+ // does not claim the finalizer, and is disposed via the registration notification below.
+ bool hosted = registration != null;
+ JSRuntimeContext? context = null;
try
{
+ // Context creation (fallible instance-data registration) and scope creation are inside
+ // the try so a failure returns a JS error instead of escaping this unmanaged entry point.
+ context = new(env, runtime);
+ using JSValueScope scope = JSValueScope.CreateRuntimeScope(env, context);
+
JSObject exportsObject = (JSObject)new JSValue(exports, scope);
// Save the require() and import() functions that were passed in by the init script.
@@ -219,15 +235,51 @@ public static napi_value InitializeModule(napi_env env, napi_value exports)
ManagedHost host = new(exportsObject)
{
- _rootScope = scope
+ _context = context
};
+ // Dispose the host with its environment: as a disposable annotation on the context, the
+ // host's full Dispose (which unsubscribes the process-wide resolve handlers) runs when
+ // the context is disposed at environment teardown. Mirrors the native host.
+ context.SetDisposableAnnotation(host);
+
+ if (hosted)
+ {
+ // Root the managed host for the environment lifetime and give the native host a
+ // native callback to invoke at teardown (never a JS call -- see OnEnvironmentFinalize).
+ registration->AddonGCHandle = (nint)GCHandle.Alloc(host);
+#if !(NETFRAMEWORK || NETSTANDARD)
+ registration->OnEnvFinalize =
+ (nint)(delegate* unmanaged[Cdecl])&OnEnvironmentFinalize;
+#endif
+ }
+
Trace("< ManagedHost.InitializeModule()");
}
catch (Exception ex)
{
Trace($"Failed to load CLR managed host module: {ex}");
- JSError.ThrowError(ex);
+ try
+ {
+ // Throw via the runtime directly: context or scope creation may have failed, and the
+ // disposed context below would make a scope-bound JSError's lazy stack getter unusable.
+ runtime.ThrowError(env, code: null, ex.ToString());
+ }
+ finally
+ {
+ // The module-slot context does not own the instance-data finalizer, so a failed init
+ // must dispose it here; tolerate construction not having completed. Swallow a teardown
+ // failure -- JSRuntimeContext.Dispose rethrows its first cleanup error, which must not
+ // escape this UnmanagedCallersOnly entry point.
+ try
+ {
+ context?.Dispose();
+ }
+ catch (Exception disposeError)
+ {
+ Trace($"Failed to dispose context after failed module init: {disposeError}");
+ }
+ }
}
#if NETFRAMEWORK || NETSTANDARD
@@ -238,6 +290,69 @@ public static napi_value InitializeModule(napi_env env, napi_value exports)
#endif
}
+#if !(NETFRAMEWORK || NETSTANDARD)
+ ///
+ /// Called natively by the native host when the environment is being torn down. Runs during
+ /// environment finalization where calling into JavaScript is forbidden, so it touches only
+ /// managed state.
+ ///
+ [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
+ private static void OnEnvironmentFinalize(nint addon) => OnEnvironmentFinalizeCore(addon);
+#else
+ ///
+ /// Called by the native host (through the default AppDomain) when the environment is being
+ /// torn down. Runs during environment finalization where calling into JavaScript is forbidden,
+ /// so it touches only managed state.
+ ///
+ public static int OnEnvironmentFinalize(string argument)
+ {
+ OnEnvironmentFinalizeCore((nint)ulong.Parse(argument, NumberStyles.HexNumber));
+ return 0;
+ }
+#endif
+
+ private static void OnEnvironmentFinalizeCore(nint addon)
+ {
+ if (addon == default)
+ {
+ return;
+ }
+
+ GCHandle handle = GCHandle.FromIntPtr(addon);
+ try
+ {
+ (handle.Target as ManagedHost)?.DisposeOnEnvironmentFinalize();
+ }
+ catch (Exception ex)
+ {
+ Trace($"Failed to dispose managed host on environment finalize: {ex}");
+ }
+ finally
+ {
+ handle.Free();
+ }
+ }
+
+ ///
+ /// Disposes the managed host in response to environment teardown. No JavaScript may be called
+ /// here; disposing the context marks it disposed (so any late cross-thread post becomes a
+ /// no-op), disposes the host (a disposable annotation on the context) so its process-wide
+ /// resolve handlers are unsubscribed, and frees the context's GC handles. The context's
+ /// references are reclaimed by Node as the environment is torn down.
+ ///
+ private void DisposeOnEnvironmentFinalize()
+ {
+ JSRuntimeContext? context = _context;
+ _context = null;
+ if (context is not null)
+ {
+ // Defer disposal until any open value scope closes -- the notification can arrive while a
+ // managed callback scope is on the stack (managed calling JS calling dispose) -- mirroring
+ // the native host's dispose() hook. With no scope open it disposes immediately.
+ JSValueScope.DisposeRuntimeContextWhenIdle(context);
+ }
+ }
+
///
/// Resolve references to Node API and other assemblies that loaded assemblies depend on.
///
@@ -588,23 +703,49 @@ private JSValue RunWorker(JSCallbackArgs args)
}
}
+ private bool _isDisposed;
+
protected override void Dispose(bool disposing)
{
- if (disposing)
- {
- _rootScope?.Dispose();
- _rootScope = null;
+ if (_isDisposed) return;
+ _isDisposed = true;
+ try
+ {
+ if (disposing)
+ {
+ try
+ {
+ // The context disposes this host (a disposable annotation) at teardown, so this
+ // re-entrant dispose is a guarded no-op; on an explicit dispose it runs the
+ // context teardown, which can throw.
+ _context?.Dispose();
+ _context = null;
+ }
+ finally
+ {
+ // Unsubscribe the process-wide resolve handlers even if context disposal threw,
+ // so a torn-down environment's host is not left rooted (a retry no-ops on
+ // _isDisposed).
#if NETFRAMEWORK || NETSTANDARD
- AppDomain.CurrentDomain.AssemblyResolve -= OnResolvingAssembly;
+ AppDomain.CurrentDomain.AssemblyResolve -= OnResolvingAssembly;
#else
- AssemblyLoadContext.Default.Resolving -= OnResolvingAssembly;
- _loadContext.Resolving -= OnResolvingAssembly;
- _loadContext.Unload();
+ AssemblyLoadContext.Default.Resolving -= OnResolvingAssembly;
+ _loadContext.Resolving -= OnResolvingAssembly;
+
+ // A non-collectible load context cannot be unloaded; only unload one created collectible.
+ if (_loadContext.IsCollectible)
+ {
+ _loadContext.Unload();
+ }
#endif
+ }
+ }
+ }
+ finally
+ {
+ base.Dispose(disposing);
}
-
- base.Dispose(disposing);
}
#if NETSTANDARD
diff --git a/src/NodeApi.DotNetHost/ManagedHostRegistration.cs b/src/NodeApi.DotNetHost/ManagedHostRegistration.cs
new file mode 100644
index 00000000..00869630
--- /dev/null
+++ b/src/NodeApi.DotNetHost/ManagedHostRegistration.cs
@@ -0,0 +1,35 @@
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+
+using System;
+using System.Runtime.InteropServices;
+
+namespace Microsoft.JavaScript.NodeApi.DotNetHost;
+
+///
+/// Native handshake structure the managed host fills in at initialization, so the native host can
+/// keep the managed host alive for the environment lifetime and notify it when the environment is
+/// torn down.
+///
+///
+/// The layout must exactly match the native host's own copy of this structure (in the NodeApi
+/// assembly). Both are two pointer-sized fields, passed by pointer across the native/managed
+/// boundary. The native host and managed host run in separate .NET runtimes, so the structure is
+/// defined independently in each and only its binary layout is shared.
+///
+[StructLayout(LayoutKind.Sequential)]
+internal struct ManagedHostRegistration
+{
+ ///
+ /// A strong to the managed host, allocated and freed only by managed
+ /// code. The native host treats it as an opaque pointer.
+ ///
+ public nint AddonGCHandle;
+
+ ///
+ /// A native callback pointer (delegate* unmanaged<nint, void> ) the native host
+ /// invokes at environment teardown, or default when the native host uses another channel
+ /// (the .NET Framework host invokes the finalize method through the default AppDomain instead).
+ ///
+ public nint OnEnvFinalize;
+}
diff --git a/src/NodeApi.Generator/ModuleGenerator.cs b/src/NodeApi.Generator/ModuleGenerator.cs
index d4c3bd87..7fb3a703 100644
--- a/src/NodeApi.Generator/ModuleGenerator.cs
+++ b/src/NodeApi.Generator/ModuleGenerator.cs
@@ -24,6 +24,7 @@ public class ModuleGenerator : SourceGenerator, ISourceGenerator
{
private const string ModuleInitializerClassName = "Module";
private const string ModuleInitializeMethodName = "Initialize";
+ private const string ModuleExportsMethodName = "InitializeExports";
private const string ModuleRegisterFunctionName = "napi_register_module_v1";
private readonly JSMarshaller _marshaller = new()
@@ -287,26 +288,48 @@ private SourceBuilder GenerateModuleInitializer(
s += $"public static class {ModuleInitializerClassName}";
s += "{";
- // The module scope is not disposed after a successful initialization. It becomes
- // the parent of callback scopes, allowing the JS runtime instance to be inherited.
- s += "private static JSValueScope _moduleScope;";
-
- // The unmanaged entrypoint is used only when the AOT-compiled module is loaded.
+ // The unmanaged entrypoint is used only when the AOT-compiled module is loaded. As the
+ // root it creates the runtime context; there is no host to resolve it from.
s += "#if !NETFRAMEWORK";
s += $"[UnmanagedCallersOnly(EntryPoint = \"{ModuleRegisterFunctionName}\")]";
s += $"public static napi_value _{ModuleInitializeMethodName}(napi_env env, napi_value exports)";
- s += $"{s.Indent}=> {ModuleInitializeMethodName}(env, exports);";
+ s += "{";
+ // Guard the fallible context/module-scope setup (instance-data registration, lazy
+ // sync-context creation) so a failure returns a JS error instead of escaping this
+ // UnmanagedCallersOnly entry point; the catch throws scope-lessly since setup itself failed.
+ s += "try";
+ s += "{";
+ s += "JSRuntimeContext context = JSRuntimeContext.Create(env);";
+ s += "using var moduleScope = JSValueScope.CreateModuleScope(env, context);";
+ s += $"return {ModuleExportsMethodName}(moduleScope, exports);";
+ s += "}";
+ s += "catch (System.Exception ex)";
+ s += "{";
+ s += "System.Console.Error.WriteLine($\"Failed to initialize module: {ex}\");";
+ s += "new Microsoft.JavaScript.NodeApi.Runtime.NodejsRuntime().ThrowError(env, null, ex.ToString());";
+ s += "return exports;";
+ s += "}";
+ s += "}";
s += "#endif";
s++;
- // The main initialization entrypoint is called by the `ManagedHost`, and by the unmanaged entrypoint.
+ // The main initialization entrypoint is called by the `ManagedHost` that loaded this
+ // module; the scope resolves the runtime context from that host.
s += $"public static napi_value {ModuleInitializeMethodName}(napi_env env, napi_value exports)";
s += "{";
- s += "_moduleScope = new JSValueScope(JSValueScopeType.Module, env, runtime: default);";
+ s += "using var moduleScope = JSValueScope.CreateModuleScope(env);";
+ s += $"return {ModuleExportsMethodName}(moduleScope, exports);";
+ s += "}";
+ s++;
+
+ // The shared body builds the exports within the module scope opened by an entrypoint
+ // above; the scope stays alive through the catch so it can build the JS error.
+ s += $"private static napi_value {ModuleExportsMethodName}(JSValueScope moduleScope, napi_value exports)";
+ s += "{";
s += "try";
s += "{";
- s += "JSRuntimeContext context = _moduleScope.RuntimeContext;";
- s += "JSValue exportsValue = new(exports, _moduleScope);";
+ s += "JSRuntimeContext context = moduleScope.RuntimeContext;";
+ s += "JSValue exportsValue = new(exports, moduleScope);";
s++;
if (moduleInitializer is IMethodSymbol moduleInitializerMethod)
@@ -340,7 +363,6 @@ private SourceBuilder GenerateModuleInitializer(
s += "{";
s += "System.Console.Error.WriteLine($\"Failed to export module: {ex}\");";
s += "JSError.ThrowError(ex);";
- s += "_moduleScope.Dispose();";
s += "return exports;";
s += "}";
s += "}";
diff --git a/src/NodeApi/DotNetHost/NativeHost.cs b/src/NodeApi/DotNetHost/NativeHost.cs
index e925cb19..eabef070 100644
--- a/src/NodeApi/DotNetHost/NativeHost.cs
+++ b/src/NodeApi/DotNetHost/NativeHost.cs
@@ -7,6 +7,7 @@
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
+using Microsoft.JavaScript.NodeApi.Interop;
using Microsoft.JavaScript.NodeApi.Runtime;
using static Microsoft.JavaScript.NodeApi.DotNetHost.HostFxr;
using static Microsoft.JavaScript.NodeApi.DotNetHost.MSCorEE;
@@ -28,9 +29,14 @@ internal unsafe partial class NativeHost : IDisposable
private string? _managedHostPath;
private ICLRRuntimeHost* _runtimeHost;
private hostfxr_handle _hostContextHandle;
- private readonly JSValueScope _hostScope;
private JSReference? _exports;
+ // Filled in by the managed host during initialization via the registration struct: a GCHandle
+ // (owned by the managed runtime) that roots the managed host, and a native callback the native
+ // host invokes at environment teardown. Both are default until a managed host is initialized.
+ private nint _addonGCHandle;
+ private nint _onEnvFinalize;
+
public static bool IsTracingEnabled { get; } =
Environment.GetEnvironmentVariable("NODE_API_TRACE_HOST") == "1";
@@ -194,15 +200,22 @@ public static napi_value InitializeModule(napi_env env, napi_value exports)
s_jsRuntime ??= new NodejsRuntime();
- // The native host JSValueScope is not disposed after a successful initialization. It
- // becomes the parent of callback scopes, allowing the JS runtime instance to be inherited.
- JSValueScope hostScope = new(JSValueScopeType.NoContext, env, s_jsRuntime);
+ // The native host's context occupies the host instance-data slot, so the initialize()/
+ // dispose() callbacks (dispatched later with no parent scope) recover it via FromEnv.
+ JSRuntimeContext.UseHostContextSlot();
+
try
{
- NativeHost host = new(hostScope);
+ // Context creation (fallible instance-data registration) and scope creation are inside
+ // the try so a failure returns a JS error instead of escaping this unmanaged entry point.
+ // The context outlives the scope -- rooted by its instance-data slot, disposed by that
+ // slot's finalizer (which disposes the NativeHost).
+ JSRuntimeContext context = new(env, s_jsRuntime, new JSInlineSynchronizationContext());
+ using JSValueScope hostScope = JSValueScope.CreateRuntimeScope(env, context);
+
+ NativeHost host = new();
+ context.SetDisposableAnnotation(host);
- // Do not use JSModuleBuilder here because it relies on having a current context.
- // But the context will be set by the managed host.
new JSValue(exports, hostScope).DefineProperties(
// The package index.js will invoke the initialize method with the path to
// the managed host assembly.
@@ -212,8 +225,11 @@ public static napi_value InitializeModule(napi_env env, napi_value exports)
{
string message = $"Failed to load CLR native host module: {ex}";
Trace(message);
- s_jsRuntime.Throw(env, (napi_value)JSValue.CreateError(null, (JSValue)message));
- hostScope.Dispose();
+ // Scope-less throw: context or scope creation may have failed, so no scope exists.
+ // Not disposed here: the host-slot context owns the instance-data finalizer that
+ // disposes it at env teardown even if partly initialized -- unlike the managed host's
+ // module-slot context, whose failure path must dispose it.
+ s_jsRuntime.ThrowError(env, code: null, message);
}
Trace("< NativeHost.InitializeModule()");
@@ -221,9 +237,37 @@ public static napi_value InitializeModule(napi_env env, napi_value exports)
return exports;
}
- private NativeHost(JSValueScope hostScope)
+ [StructLayout(LayoutKind.Sequential)]
+ private struct ManagedHostRegistration
+ {
+ public nint AddonGCHandle;
+ public nint OnEnvFinalize;
+ }
+
+ private void NotifyManagedHostEnvironmentFinalize()
{
- _hostScope = hostScope;
+ if (_onEnvFinalize != default)
+ {
+ // hostfxr (.NET 5+): the managed host provided a native callback pointer.
+ ((delegate* unmanaged[Cdecl])_onEnvFinalize)(_addonGCHandle);
+ }
+ else if (_runtimeHost is not null && _addonGCHandle != default && _managedHostPath is not null)
+ {
+ // .NET Framework: invoke the managed finalize through the default AppDomain. This is a
+ // native call into the (still-loaded) CLR, never a JavaScript call.
+ try
+ {
+ _runtimeHost->ExecuteInDefaultAppDomain(
+ _managedHostPath,
+ s_managedHostTypeName,
+ "OnEnvironmentFinalize",
+ ((ulong)_addonGCHandle).ToString("X8"));
+ }
+ catch (Exception ex)
+ {
+ Trace("Failed to notify managed host on environment finalize: " + ex);
+ }
+ }
}
///
@@ -350,8 +394,10 @@ private JSValue InitializeFrameworkHost(
napi_value exports = (napi_value)exportsValue;
// The method to be executed must take a single string argument and return a uint.
- // So, encode the parameters and retval pointer in the argument string.
- string argument = $"{(ulong)env.Handle:X8},{(ulong)exports.Handle:X8},{(ulong)&exports:X8}";
+ // So, encode the parameters, retval pointer, and registration pointer in the argument.
+ ManagedHostRegistration registration = default;
+ string argument = $"{(ulong)env.Handle:X8},{(ulong)exports.Handle:X8}," +
+ $"{(ulong)&exports:X8},{(ulong)®istration:X8}";
Trace($" Calling {s_managedHostTypeName}.{nameof(InitializeModule)}({argument})");
_runtimeHost->ExecuteInDefaultAppDomain(
@@ -360,6 +406,9 @@ private JSValue InitializeFrameworkHost(
nameof(InitializeModule),
argument);
+ _addonGCHandle = registration.AddonGCHandle;
+ _onEnvFinalize = registration.OnEnvFinalize;
+
exportsValue = exports;
return exportsValue;
}
@@ -446,23 +495,34 @@ private JSValue InitializeDotNetHost(
Trace(" Invoking managed host method: " + nameof(InitializeModule));
- // Invoke the managed host initialize method.
- // (It will define some properties on the exports object passed in.)
- napi_register_module_v1 initializeModule =
- Marshal.GetDelegateForFunctionPointer(
- initializeModulePointer);
-
// Create an "exports" object for the managed host module initialization.
var exports = JSValue.CreateObject();
exports.SetProperty("require", require);
exports.SetProperty("import", import);
- // Define a dispose method implemented by the native host that closes the CLR context.
- // The managed host proxy will pass through dispose calls to this callback.
+ // Defer disposing the host context until this callback (and any value scope it is nested in)
+ // has closed: dispose() is a native call dispatched through Node-API, so disposing the context
+ // while a scope is open would leave that scope to close its napi handle scope on a disposed
+ // context as it unwinds. Disposing the host context runs the full host teardown via its
+ // disposable annotation -- notifying the managed host and closing the runtime-host channel.
exports.DefineProperties(new JSPropertyDescriptor(
- "dispose", (_) => { Dispose(); return default; }));
-
- exports = initializeModule((napi_env)exports.Scope, (napi_value)exports);
+ "dispose", (_) =>
+ {
+ JSValueScope.DisposeRuntimeContextWhenIdle(JSValueScope.Current.RuntimeContext);
+ return default;
+ }));
+
+ // Invoke the managed host initialize method. It defines properties on the exports object
+ // and fills in the registration so the native host can keep the managed host alive and
+ // notify it when the environment is torn down.
+ ManagedHostRegistration registration = default;
+ var initializeModule =
+ (delegate* unmanaged[Cdecl])
+ initializeModulePointer;
+ exports = initializeModule((napi_env)exports.Scope, (napi_value)exports, (nint)(®istration));
+
+ _addonGCHandle = registration.AddonGCHandle;
+ _onEnvFinalize = registration.OnEnvFinalize;
return exports;
}
@@ -498,6 +558,37 @@ private hostfxr_handle InitializeManagedRuntime(
public void Dispose()
{
+ // Runs as the host context's disposable annotation when that context is disposed: at env
+ // teardown by its instance-data finalizer, or (deferred to scope close) by the JS dispose() hook.
+ try
+ {
+ NotifyManagedHostEnvironmentFinalize();
+ }
+ finally
+ {
+ // Clear the registration before the fallible CloseRuntimeHost: the notification frees the
+ // addon GCHandle, so a later retry that re-invoked it would pass an already-freed handle
+ // across the unmanaged finalizer boundary.
+ _addonGCHandle = default;
+ _onEnvFinalize = default;
+ }
+
+ CloseRuntimeHost();
+
+ // Both dispose paths now run while the host context is disposed, so JSReference.Dispose
+ // short-circuits and Node reclaims the napi_ref at env teardown; the assignment drops the
+ // managed reference so it can be collected.
+ _exports?.Dispose();
+ _exports = null;
+ }
+
+ private void CloseRuntimeHost()
+ {
+ // Closes this environment's CLR host: the hostfxr context handle (.NET 5+) or the
+ // ICLRRuntimeHost COM reference (.NET Framework). Each environment initializes its own, so
+ // this is per-environment teardown (the underlying shared CLR is not unloaded). Invoked at
+ // environment teardown and by the optional JS dispose() hook; idempotent.
+
// Close the CLR host context handle, if it's still open.
if (_hostContextHandle != default)
{
diff --git a/src/NodeApi/Interop/JSCallbackDescriptor.cs b/src/NodeApi/Interop/JSCallbackDescriptor.cs
index 682f0752..e865acf5 100644
--- a/src/NodeApi/Interop/JSCallbackDescriptor.cs
+++ b/src/NodeApi/Interop/JSCallbackDescriptor.cs
@@ -3,6 +3,7 @@
using System;
using System.Diagnostics;
+using System.Runtime.CompilerServices;
namespace Microsoft.JavaScript.NodeApi.Interop;
@@ -15,10 +16,10 @@ namespace Microsoft.JavaScript.NodeApi.Interop;
public readonly struct JSCallbackDescriptor
{
///
- /// Saves the module context under which the callback was defined, so that multiple .NET
+ /// Saves the module instance holder under which the callback was defined, so that multiple .NET
/// modules in the same process can register callbacks for module-level functions.
///
- internal JSModuleContext? ModuleContext { get; }
+ internal StrongBox? ModuleHolder { get; }
///
/// Gets the name of the callback, for debugging purposes.
@@ -37,27 +38,27 @@ public readonly struct JSCallbackDescriptor
public object? Data { get; }
public JSCallbackDescriptor(JSCallback callback, object? data = null)
- : this(null, callback, data, JSValueScope.Current.ModuleContext)
+ : this(null, callback, data, JSValueScope.Current.ModuleHolder)
{
}
public JSCallbackDescriptor(string? name, JSCallback callback, object? data = null)
- : this(name, callback, data, JSValueScope.Current.ModuleContext)
+ : this(name, callback, data, JSValueScope.Current.ModuleHolder)
{
}
- internal JSCallbackDescriptor(JSCallback callback, object? data, JSModuleContext? moduleContext)
- : this(null, callback, data, moduleContext)
+ internal JSCallbackDescriptor(JSCallback callback, object? data, StrongBox? moduleHolder)
+ : this(null, callback, data, moduleHolder)
{
}
internal JSCallbackDescriptor(
- string? name, JSCallback callback, object? data, JSModuleContext? moduleContext)
+ string? name, JSCallback callback, object? data, StrongBox? moduleHolder)
{
Name = name;
Callback = callback ?? throw new ArgumentNullException(nameof(callback));
Data = data;
- ModuleContext = moduleContext;
+ ModuleHolder = moduleHolder;
}
public static implicit operator JSCallbackDescriptor(JSCallback callback) => new(callback);
diff --git a/src/NodeApi/Interop/JSModuleBuilderOfT.cs b/src/NodeApi/Interop/JSModuleBuilderOfT.cs
index 072c55af..f659e04e 100644
--- a/src/NodeApi/Interop/JSModuleBuilderOfT.cs
+++ b/src/NodeApi/Interop/JSModuleBuilderOfT.cs
@@ -19,7 +19,7 @@ public JSModuleBuilder() : base(Unwrap)
private static new T? Unwrap(JSCallbackArgs _)
{
- return (T?)JSModuleContext.Current.Module;
+ return (T?)JSValueScope.Current.Module;
}
///
@@ -33,7 +33,15 @@ public JSModuleBuilder() : base(Unwrap)
/// The module exports.
public JSValue ExportModule(T module, JSObject exports)
{
- JSModuleContext.Current.Module = module;
+ // Write through the holder the descriptors captured, so callbacks bound before the module
+ // instance existed observe it.
+ JSValueScope.Current.ModuleHolder!.Value = module;
+
+ if (module is IDisposable disposable)
+ {
+ JSValueScope.Current.RuntimeContext.AddModuleDisposable(disposable);
+ }
+
exports.DefineProperties(Properties.ToArray());
return exports;
}
diff --git a/src/NodeApi/Interop/JSModuleContext.cs b/src/NodeApi/Interop/JSModuleContext.cs
deleted file mode 100644
index 371e56a4..00000000
--- a/src/NodeApi/Interop/JSModuleContext.cs
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-using System;
-
-namespace Microsoft.JavaScript.NodeApi.Interop;
-
-///
-/// Manages JavaScript interop context for the lifetime of a .NET module.
-///
-///
-/// A instance is constructed when the module is loaded and disposed
-/// when the module is unloaded.
-///
-public sealed class JSModuleContext : IDisposable
-{
- ///
- /// Gets the current module context.
- ///
- public static JSModuleContext Current => JSValueScope.Current.ModuleContext
- ?? throw new InvalidCastException("No current module context.");
-
- ///
- /// Gets an instance of the class that represents the module, or null if there is no module
- /// class.
- ///
- public object? Module { get; internal set; }
-
- public bool IsDisposed { get; private set; }
-
- public void Dispose()
- {
- if (IsDisposed) return;
-
- IsDisposed = true;
-
- if (Module is IDisposable module)
- {
- module.Dispose();
- }
- }
-}
diff --git a/src/NodeApi/Interop/JSRuntimeContext.cs b/src/NodeApi/Interop/JSRuntimeContext.cs
index 9799b54a..18051f1e 100644
--- a/src/NodeApi/Interop/JSRuntimeContext.cs
+++ b/src/NodeApi/Interop/JSRuntimeContext.cs
@@ -8,6 +8,7 @@
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
+using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
@@ -22,12 +23,12 @@ namespace Microsoft.JavaScript.NodeApi.Interop;
///
///
/// A instance is constructed when the .NET Node API managed host is
-/// loaded, and disposed when the host is unloaded. (For AOT there is no "host" component, so each
-/// AOT module has a context that matches the module lifetime.) The context tracks several kinds
-/// of JS references used internally by this assembly, so that the references can be re-used for
-/// the lifetime of the host and disposed when the context is disposed.
+/// loaded, and the hosting infrastructure tears it down when the host is unloaded. (For AOT there
+/// is no "host" component, so each AOT module has a context that matches the module lifetime.) The
+/// context tracks several kinds of JS references used internally by this assembly, so that the
+/// references can be re-used for the lifetime of the host and released during context teardown.
///
-public sealed class JSRuntimeContext : IDisposable
+public sealed class JSRuntimeContext
{
///
/// Name of a global object that may hold context specific to Node API .NET.
@@ -37,8 +38,6 @@ public sealed class JSRuntimeContext : IDisposable
///
public const string GlobalObjectName = "node_api_dotnet";
- private readonly napi_env _env;
-
// Track JS constructors and instance JS wrappers for exported classes, enabling
// .NET objects to be automatically wrapped when returned to JS, and re-wrapped as needed
// if the (weakly-referenced) JS wrapper has been released.
@@ -113,6 +112,39 @@ public sealed class JSRuntimeContext : IDisposable
private readonly ConcurrentDictionary _collectionProxyHandlerMap = new();
+ // Two buckets so ownership is explicit: DisposableAnnotations are disposed at context teardown;
+ // Annotations are not. Both are lazy and touched only on the JS thread.
+ private Dictionary? _annotations;
+ private Dictionary? _disposableAnnotations;
+
+ // Module instances disposed at context teardown. Unlike the type-keyed annotations, several
+ // modules share one context, so these are appended rather than keyed by type.
+ private List? _moduleDisposables;
+
+ // Env instance-data layout: one GCHandle slot per runtime sharing the napi_env. Slot 0 is the
+ // module context (managed host / AOT module / embedding); slot 1 is the native host context.
+ // A runtime reads and writes only its own slot, so it never dereferences the other runtime's
+ // GCHandle (which belongs to a separate GC heap).
+ private const int ModuleContextSlot = 0;
+ private const int HostContextSlot = 1;
+ private const int InstanceDataSlotCount = 2;
+
+ // Written into a slot when its context is disposed, so an env is associated with a runtime
+ // context exactly once: RegisterInstanceData rejects a non-empty slot (a live handle or this
+ // tombstone), and FromEnv/FinalizeInstanceData treat the tombstone as "no live context". A real
+ // GCHandle is never -1.
+ private static readonly nint s_disposedSlot = -1;
+
+ // This runtime's slot in the instance-data block: the module slot by default, or the host slot
+ // once the native host calls UseHostContextSlot() at startup.
+ private static int s_instanceDataSlot = ModuleContextSlot;
+
+ // Runtime v-table used by FromEnv to read env-keyed instance data. NodejsRuntime is stateless,
+ // and wrappers such as TracingJSRuntime delegate instance-data access to it, so any registered
+ // production runtime can read every env. The env check in FromEnv makes an instance-backed
+ // custom runtime fail closed if this field is stale.
+ private static JSRuntime? s_instanceDataRuntime;
+
internal napi_env EnvironmentHandle
{
get
@@ -122,19 +154,74 @@ internal napi_env EnvironmentHandle
throw new ObjectDisposedException(nameof(JSRuntimeContext));
}
- return _env;
+ return UncheckedEnvironmentHandle;
}
}
+ ///
+ /// Gets the environment handle without checking whether the context is disposed. For use
+ /// only where a checked access is unnecessary, such as capturing the env to release a
+ /// reference on the JS thread (where a disposed context makes the release a safe no-op).
+ ///
+ internal napi_env UncheckedEnvironmentHandle { get; }
+
+ ///
+ /// Gets the GCHandle that roots this context and is stored in its env instance-data slot. It is
+ /// freed when the context is disposed at env teardown; finalizers resolve the context via
+ /// rather than this handle, so freeing it leaves nothing dangling.
+ ///
+ internal nint ContextHandle { get; }
+
+ ///
+ /// The managed thread that constructed this context — its environment's JS thread. A runtime
+ /// scope may be entered only on this thread.
+ ///
+ internal int OwningThreadId { get; }
+
public static explicit operator napi_env(JSRuntimeContext context)
{
if (context is null) throw new ArgumentNullException(nameof(context));
return context.EnvironmentHandle;
}
- public static explicit operator JSRuntimeContext(napi_env env)
- => JSValue.GetInstanceData(env) as JSRuntimeContext
- ?? throw new InvalidCastException("Context is not found in napi_env instance data.");
+ ///
+ /// Resolves the for the calling runtime from a napi_env, via the
+ /// env instance-data block, or null if none is registered. Unlike this
+ /// does not require a current scope, so callback dispatch can recover the context when no scope
+ /// is on the thread-static stack yet.
+ ///
+ public static unsafe JSRuntimeContext? FromEnv(napi_env env)
+ {
+ JSRuntime? runtime = s_instanceDataRuntime;
+ if (runtime is null)
+ {
+ return null;
+ }
+
+ runtime.GetInstanceData(env, out nint instanceData).ThrowIfFailed();
+ if (instanceData == default)
+ {
+ return null;
+ }
+
+ nint slotHandle = ((nint*)instanceData)[s_instanceDataSlot];
+ if (slotHandle == default || slotHandle == s_disposedSlot)
+ {
+ return null;
+ }
+
+ // The production runtime lookup is env-keyed, but an instance-backed custom runtime could
+ // return another env's block when the process-wide runtime is stale. Fail closed unless the
+ // resolved context owns the requested env.
+ JSRuntimeContext? context = GCHandle.FromIntPtr(slotHandle).Target as JSRuntimeContext;
+ return context is not null && context.UncheckedEnvironmentHandle == env ? context : null;
+ }
+
+ ///
+ /// Configures the calling runtime to use the native host's instance-data slot. Called once by
+ /// the native host at startup; every other runtime keeps the default module slot.
+ ///
+ internal static void UseHostContextSlot() => s_instanceDataSlot = HostContextSlot;
public bool IsDisposed { get; private set; }
@@ -147,7 +234,53 @@ public static explicit operator JSRuntimeContext(napi_env env)
public JSRuntime Runtime { get; }
- public JSSynchronizationContext SynchronizationContext { get; }
+ private JSSynchronizationContext? _synchronizationContext;
+
+ ///
+ /// Gets the synchronization context that marshals callbacks and continuations to the JS thread.
+ /// A default one is created on first access, which must happen while a scope for this context is
+ /// current, because creating it captures the current scope's runtime and environment.
+ ///
+ public JSSynchronizationContext SynchronizationContext
+ {
+ get
+ {
+ if (_synchronizationContext is not null)
+ {
+ return _synchronizationContext;
+ }
+
+ // Lazy creation captures the CURRENT scope's env/thread, so it must run only while this
+ // context is current -- otherwise it would bind this context to a different environment.
+ if (IsDisposed)
+ {
+ throw new ObjectDisposedException(nameof(JSRuntimeContext));
+ }
+ if (JSValueScope.Current.RuntimeContext != this)
+ {
+ throw new InvalidOperationException(
+ "The synchronization context must be created while its runtime context is current.");
+ }
+
+ return _synchronizationContext = JSSynchronizationContext.Create();
+ }
+ }
+
+ ///
+ /// Creates a runtime context for a JS environment. Used by AOT module entry points and other
+ /// embedders that own the environment and therefore create the context rather than resolving
+ /// it from a host.
+ ///
+ /// The JS environment handle.
+ /// The JS runtime interface; defaults to a .
+ ///
+ /// The synchronization context owned by this context; a
+ /// default one is created when omitted.
+ public static JSRuntimeContext Create(
+ napi_env env,
+ JSRuntime? runtime = null,
+ JSSynchronizationContext? synchronizationContext = null)
+ => new(env, runtime ?? new NodejsRuntime(), synchronizationContext);
internal JSRuntimeContext(
napi_env env,
@@ -156,10 +289,115 @@ internal JSRuntimeContext(
{
if (env.IsNull) throw new ArgumentNullException(nameof(env));
- _env = env;
+ UncheckedEnvironmentHandle = env;
Runtime = runtime;
- JSValue.SetInstanceData(env, this);
- SynchronizationContext = synchronizationContext ?? JSSynchronizationContext.Create();
+ OwningThreadId = Environment.CurrentManagedThreadId;
+ ContextHandle = (nint)GCHandle.Alloc(this);
+ try
+ {
+ RegisterInstanceData(env, runtime);
+ }
+ catch
+ {
+ // Registration failed before any caller holds this context to dispose it; free the
+ // rooting handle so a failed construction leaks nothing (the block, if allocated, is
+ // freed by RegisterInstanceData).
+ GCHandle.FromIntPtr(ContextHandle).Free();
+ throw;
+ }
+
+ _synchronizationContext = synchronizationContext;
+ }
+
+ ///
+ /// Registers this context in the env instance-data block at this runtime's slot, allocating the
+ /// block and attaching the teardown finalizer if this runtime is the first to claim the slot.
+ ///
+ private unsafe void RegisterInstanceData(napi_env env, JSRuntime runtime)
+ {
+ runtime.GetInstanceData(env, out nint instanceData).ThrowIfFailed();
+ if (instanceData == default)
+ {
+ // One block per env, freed by FinalizeInstanceData when the last context on the env is
+ // disposed at teardown.
+ instanceData = Marshal.AllocHGlobal(IntPtr.Size * InstanceDataSlotCount);
+ for (int i = 0; i < InstanceDataSlotCount; i++)
+ {
+ ((nint*)instanceData)[i] = default;
+ }
+
+ napi_status status = runtime.SetInstanceData(
+ env,
+ instanceData,
+ new napi_finalize(s_finalizeInstanceData),
+ finalizeHint: default);
+ if (status != napi_status.napi_ok)
+ {
+ // Registration failed, so Node never took ownership of the block; free it here.
+ Marshal.FreeHGlobal(instanceData);
+ status.ThrowIfFailed();
+ }
+ }
+ else if (((nint*)instanceData)[s_instanceDataSlot] != default)
+ {
+ // An env is associated with a runtime context exactly once. The slot holds a live
+ // context's handle, or a tombstone after one was disposed; either way a second
+ // association is rejected rather than silently replacing the first.
+ throw new InvalidOperationException(
+ "The environment is already associated with a runtime context.");
+ }
+
+ ((nint*)instanceData)[s_instanceDataSlot] = ContextHandle;
+
+ // Publish the process-wide runtime that FromEnv uses only after registration succeeds, so a
+ // failed GetInstanceData/SetInstanceData or a rejected duplicate slot can't repoint FromEnv at
+ // a runtime that never registered a context on this env.
+ s_instanceDataRuntime = runtime;
+ }
+
+#if !UNMANAGED_DELEGATES
+ private static readonly napi_finalize.Delegate s_finalizeInstanceData = FinalizeInstanceData;
+#else
+ private static readonly unsafe delegate* unmanaged[Cdecl]
+ s_finalizeInstanceData = &FinalizeInstanceData;
+#endif
+
+#if UNMANAGED_DELEGATES
+ [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
+#endif
+ private static unsafe void FinalizeInstanceData(napi_env env, nint data, nint hint)
+ {
+ // Runs during env teardown, where calling into JS is forbidden. Dispose the owning
+ // runtime's context (which clears its slot and frees its rooting GCHandle). Only this
+ // runtime's slot is read, never the other runtime's (whose GCHandle belongs to a separate
+ // GC heap).
+ nint slotHandle = ((nint*)data)[s_instanceDataSlot];
+ if (slotHandle != default && slotHandle != s_disposedSlot)
+ {
+ try
+ {
+ (GCHandle.FromIntPtr(slotHandle).Target as JSRuntimeContext)?.Dispose();
+ }
+ catch
+ {
+ // A finalizer must never throw; teardown continues regardless.
+ }
+ }
+
+ // Free the shared block once no slot holds a live context (each is empty or tombstoned);
+ // disposing a host context cascades synchronously to the other slot. Do not null it out
+ // via napi_set_instance_data: that deletes this very TrackedFinalizer, which Node then
+ // deletes again (double free).
+ for (int i = 0; i < InstanceDataSlotCount; i++)
+ {
+ nint slot = ((nint*)data)[i];
+ if (slot != default && slot != s_disposedSlot)
+ {
+ return;
+ }
+ }
+
+ Marshal.FreeHGlobal(data);
}
///
@@ -700,22 +938,162 @@ public async Task ImportAsync(
return value;
}
- public void Dispose()
+ ///
+ /// Gets a non-owning annotation associated with this context by its type, or null if none.
+ ///
+ public T? GetAnnotation() where T : class
+ => _annotations != null && _annotations.TryGetValue(typeof(T), out object? value)
+ ? (T)value : null;
+
+ ///
+ /// Associates a non-owning annotation with this context, keyed by its type. The context never
+ /// disposes it.
+ ///
+ public void SetAnnotation(T value) where T : class
+ {
+ if (value is null) throw new ArgumentNullException(nameof(value));
+ (_annotations ??= new())[typeof(T)] = value;
+ }
+
+ ///
+ /// Gets an owning annotation associated with this context by its type, or null if none.
+ ///
+ public T? GetDisposableAnnotation() where T : class, IDisposable
+ => _disposableAnnotations != null &&
+ _disposableAnnotations.TryGetValue(typeof(T), out IDisposable? value)
+ ? (T)value : null;
+
+ ///
+ /// Associates an owning annotation with this context, keyed by its type. The context disposes
+ /// it when the context itself is disposed (at environment teardown). Replacing an existing
+ /// annotation of the same type disposes the one being displaced.
+ ///
+ /// The context is already disposed, so the value
+ /// would never be disposed.
+ public void SetDisposableAnnotation(T value) where T : class, IDisposable
+ {
+ if (value is null) throw new ArgumentNullException(nameof(value));
+ if (IsDisposed) throw new ObjectDisposedException(nameof(JSRuntimeContext));
+
+ _disposableAnnotations ??= new();
+ if (_disposableAnnotations.TryGetValue(typeof(T), out IDisposable? existing) &&
+ !ReferenceEquals(existing, value))
+ {
+ existing.Dispose();
+ }
+
+ _disposableAnnotations[typeof(T)] = value;
+ }
+
+ ///
+ /// Registers a module instance to be disposed at environment teardown. Unlike
+ /// , several modules can share one context, so instances
+ /// are appended rather than keyed by type, and each is disposed once.
+ ///
+ internal void AddModuleDisposable(IDisposable disposable)
+ {
+ if (disposable is null) throw new ArgumentNullException(nameof(disposable));
+ _moduleDisposables ??= new();
+
+ // Dedupe by identity, not Equals: a module class may override equality, but each distinct
+ // instance must be disposed once.
+ foreach (IDisposable existing in _moduleDisposables)
+ {
+ if (ReferenceEquals(existing, disposable))
+ {
+ return;
+ }
+ }
+
+ _moduleDisposables.Add(disposable);
+ }
+
+ internal void Dispose()
{
if (IsDisposed) return;
+ // Disposal calls thread-affine napi (the sync context's RemoveEnvCleanupHook), so it must
+ // run on the thread that created the context -- where the instance-data finalizer and the
+ // JS dispose functions, the only expected callers, both run.
+ if (OwningThreadId != Environment.CurrentManagedThreadId)
+ {
+ throw new JSInvalidThreadAccessException(
+ currentScope: null,
+ "A runtime context may be disposed only on the thread that created it.");
+ }
+
IsDisposed = true;
- SynchronizationContext.Dispose();
+ // Run every teardown phase even if an earlier one throws, then release the context root and
+ // rethrow the first failure. A throwing phase must not skip a later phase or the root
+ // release: IsDisposed is already set, so a retry returns immediately and could otherwise
+ // strand module instances, annotations, or the context root and its shared block.
+ ExceptionDispatchInfo? firstFailure = null;
+
+ // Dispose an already-created sync context only; never construct one here. Disposal can run
+ // during env finalization when no scope is current, and creating one then would throw.
+ try { _synchronizationContext?.Dispose(); }
+ catch (Exception ex) { firstFailure ??= ExceptionDispatchInfo.Capture(ex); }
#if !(NETFRAMEWORK || NETSTANDARD)
- // ConditionalWeakTable<> is not enumerable in .NET Framework.
- // The JS references will still be released eventually by their finalizers.
- DisposeReferences(_objectMap.Select((entry) => entry.Value));
+ // ConditionalWeakTable<> is not enumerable in .NET Framework; those references are released
+ // by their finalizers instead.
+ try { DisposeReferences(_objectMap.Select((entry) => entry.Value)); }
+ catch (Exception ex) { firstFailure ??= ExceptionDispatchInfo.Capture(ex); }
#endif
- DisposeReferences(_classMap.Values);
- DisposeReferences(_staticClassMap.Values);
- DisposeReferences(_structMap.Values);
+ try { DisposeReferences(_classMap.Values); }
+ catch (Exception ex) { firstFailure ??= ExceptionDispatchInfo.Capture(ex); }
+ try { DisposeReferences(_staticClassMap.Values); }
+ catch (Exception ex) { firstFailure ??= ExceptionDispatchInfo.Capture(ex); }
+ try { DisposeReferences(_structMap.Values); }
+ catch (Exception ex) { firstFailure ??= ExceptionDispatchInfo.Capture(ex); }
+
+ // Disposed after IsDisposed is set, so a late cross-thread post is already a no-op. Each item
+ // is guarded so one failure does not skip the rest.
+ if (_moduleDisposables != null)
+ {
+ foreach (IDisposable moduleDisposable in _moduleDisposables)
+ {
+ try { moduleDisposable.Dispose(); }
+ catch (Exception ex) { firstFailure ??= ExceptionDispatchInfo.Capture(ex); }
+ }
+ }
+
+ if (_disposableAnnotations != null)
+ {
+ foreach (IDisposable annotation in _disposableAnnotations.Values)
+ {
+ try { annotation.Dispose(); }
+ catch (Exception ex) { firstFailure ??= ExceptionDispatchInfo.Capture(ex); }
+ }
+ }
+
+ // Release this context's root so it can be collected, even if a phase above threw. The
+ // shared block is freed by FinalizeInstanceData once every context on the env is gone.
+ if (ContextHandle != default)
+ {
+ Runtime.GetInstanceData(UncheckedEnvironmentHandle, out nint instanceData);
+ if (instanceData != default)
+ {
+ unsafe
+ {
+ // Tombstone the slot (not empty) so the env can never re-associate a new context
+ // (see RegisterInstanceData). The one-context invariant means the slot still
+ // holds this context, but stay defensive.
+ if (((nint*)instanceData)[s_instanceDataSlot] == ContextHandle)
+ {
+ ((nint*)instanceData)[s_instanceDataSlot] = s_disposedSlot;
+ }
+ }
+
+ // Free this context's now-unregistered rooting handle. The slot was tombstoned above,
+ // so no later FromEnv or finalizer can dereference the freed handle.
+ GCHandle.FromIntPtr(ContextHandle).Free();
+ }
+ }
+
+ // Surface the first teardown failure now that every phase has run and the root is released.
+ firstFailure?.Throw();
}
private static void DisposeReferences(
diff --git a/src/NodeApi/Interop/JSSynchronizationContext.cs b/src/NodeApi/Interop/JSSynchronizationContext.cs
index 4a729708..4d4c461a 100644
--- a/src/NodeApi/Interop/JSSynchronizationContext.cs
+++ b/src/NodeApi/Interop/JSSynchronizationContext.cs
@@ -443,3 +443,39 @@ public override void OpenAsyncScope() { }
public override void CloseAsyncScope() { }
}
+
+///
+/// A synchronization context that runs work inline when already on the JS thread and drops it
+/// otherwise, without a thread-safe function. Used by the native host, which only ever operates
+/// on the JS thread and must not stand up a TSFN (which would ref the environment and require an
+/// env cleanup hook).
+///
+///
+/// Because there is no TSFN to marshal to, work posted from another thread (such as a
+/// finalizer running on the GC thread) is dropped rather than
+/// scheduled. That is safe for the native host: its references are env-lifetime and reclaimed by
+/// Node at teardown, so a dropped off-thread delete never leaves a live reference behind and never
+/// touches a dead environment.
+///
+internal sealed class JSInlineSynchronizationContext : JSSynchronizationContext
+{
+ public override void OpenAsyncScope() { }
+
+ public override void CloseAsyncScope() { }
+
+ public override void Post(SendOrPostCallback callback, object? state)
+ {
+ if (!IsDisposed && Current == this)
+ {
+ callback(state);
+ }
+ }
+
+ public override void Send(SendOrPostCallback callback, object? state)
+ {
+ if (!IsDisposed && Current == this)
+ {
+ callback(state);
+ }
+ }
+}
diff --git a/src/NodeApi/Interop/JSThreadSafeFunction.cs b/src/NodeApi/Interop/JSThreadSafeFunction.cs
index a7dbef68..e7d7ef69 100644
--- a/src/NodeApi/Interop/JSThreadSafeFunction.cs
+++ b/src/NodeApi/Interop/JSThreadSafeFunction.cs
@@ -231,7 +231,7 @@ private static unsafe void CustomCallJS(napi_env env, napi_value jsCallback, nin
try
{
- using JSValueScope scope = new(JSValueScopeType.Callback, env, runtime: null);
+ using JSValueScope scope = JSValueScope.CreateRuntimeScope(env);
object? callbackData = null;
if (data != default)
@@ -265,7 +265,7 @@ private static unsafe void DefaultCallJS(napi_env env, napi_value jsCallback, ni
try
{
- using JSValueScope scope = new(JSValueScopeType.Callback, env, runtime: null);
+ using JSValueScope scope = JSValueScope.CreateRuntimeScope(env);
if (data != default)
{
diff --git a/src/NodeApi/JSError.cs b/src/NodeApi/JSError.cs
index 74cf119f..942acefd 100644
--- a/src/NodeApi/JSError.cs
+++ b/src/NodeApi/JSError.cs
@@ -200,34 +200,28 @@ private static JSValue CreateErrorValueForException(Exception exception, out str
JSValue error = (exception as JSException)?.Error?.Value ??
JSValue.CreateError(code: null, (JSValue)message);
- // A no-context scope is used when initializing the host. In that case, do not attempt
- // to override the stack property, because if initialization fails the scope may not
- // be available for the stack callback.
- if (JSValueScope.Current.ScopeType != JSValueScopeType.NoContext)
+ // When running on V8, the `Error.captureStackTrace()` function and `Error.stack`
+ // property can be used to add the .NET stack info to the JS error stack.
+ JSValue captureStackTrace = JSValue.Global["Error"]["captureStackTrace"];
+ if (captureStackTrace.IsFunction())
{
- // When running on V8, the `Error.captureStackTrace()` function and `Error.stack`
- // property can be used to add the .NET stack info to the JS error stack.
- JSValue captureStackTrace = JSValue.Global["Error"]["captureStackTrace"];
- if (captureStackTrace.IsFunction())
- {
- // Capture the stack trace of the .NET exception, which will be combined with
- // the JS stack trace when requested.
- JSValue dotnetStack = exception.StackTrace?.Replace("\r", string.Empty)
- ?? string.Empty;
-
- // Capture the current JS stack trace as an object.
- // Defer formatting the stack as a string until requested.
- JSObject jsStack = new();
- captureStackTrace.Call(default, jsStack);
-
- // Override the `stack` property of the JS Error object, and add private
- // properties that the overridden property getter uses to construct the stack.
- error.DefineProperties(
- JSPropertyDescriptor.AccessorProperty(
- "stack", GetErrorStack, setter: null, JSPropertyAttributes.DefaultProperty),
- JSPropertyDescriptor.DataProperty("__dotnetStack", dotnetStack),
- JSPropertyDescriptor.DataProperty("__jsStack", jsStack));
- }
+ // Capture the stack trace of the .NET exception, which will be combined with
+ // the JS stack trace when requested.
+ JSValue dotnetStack = exception.StackTrace?.Replace("\r", string.Empty)
+ ?? string.Empty;
+
+ // Capture the current JS stack trace as an object.
+ // Defer formatting the stack as a string until requested.
+ JSObject jsStack = new();
+ captureStackTrace.Call(default, jsStack);
+
+ // Override the `stack` property of the JS Error object, and add private
+ // properties that the overridden property getter uses to construct the stack.
+ error.DefineProperties(
+ JSPropertyDescriptor.AccessorProperty(
+ "stack", GetErrorStack, setter: null, JSPropertyAttributes.DefaultProperty),
+ JSPropertyDescriptor.DataProperty("__dotnetStack", dotnetStack),
+ JSPropertyDescriptor.DataProperty("__jsStack", jsStack));
}
return error;
@@ -238,7 +232,7 @@ public readonly void ThrowError()
if (_errorRef is null)
return;
- using var scope = new JSValueScope(JSValueScopeType.Handle);
+ using var scope = JSValueScope.CreateHandleScope();
if (IsExceptionPending())
throw new JSException(new JSError());
diff --git a/src/NodeApi/JSPropertyDescriptor.cs b/src/NodeApi/JSPropertyDescriptor.cs
index a2e34289..3b5e1c20 100644
--- a/src/NodeApi/JSPropertyDescriptor.cs
+++ b/src/NodeApi/JSPropertyDescriptor.cs
@@ -3,7 +3,7 @@
using System;
using System.Diagnostics;
-using Microsoft.JavaScript.NodeApi.Interop;
+using System.Runtime.CompilerServices;
namespace Microsoft.JavaScript.NodeApi;
@@ -16,10 +16,10 @@ namespace Microsoft.JavaScript.NodeApi;
public readonly struct JSPropertyDescriptor
{
///
- /// Saves the module context under which the callback was defined, so that multiple .NET
+ /// Saves the module instance holder under which the callback was defined, so that multiple .NET
/// modules in the same process can register callbacks for module-level functions.
///
- internal JSModuleContext? ModuleContext { get; init; }
+ internal StrongBox? ModuleHolder { get; init; }
// Either Name or NameValue should be non-null.
// NameValue supports non-string property names like symbols.
@@ -49,7 +49,7 @@ public JSPropertyDescriptor(
JSPropertyAttributes attributes = JSPropertyAttributes.Default,
object? data = null)
{
- ModuleContext = JSValueScope.Current.ModuleContext;
+ ModuleHolder = JSValueScope.Current.ModuleHolder;
Name = name;
Method = method;
@@ -72,7 +72,7 @@ public JSPropertyDescriptor(
JSPropertyAttributes attributes = JSPropertyAttributes.Default,
object? data = null)
{
- ModuleContext = JSValueScope.Current.ModuleContext;
+ ModuleHolder = JSValueScope.Current.ModuleHolder;
NameValue = name;
Method = method;
diff --git a/src/NodeApi/JSReference.cs b/src/NodeApi/JSReference.cs
index d0c6e862..33f16194 100644
--- a/src/NodeApi/JSReference.cs
+++ b/src/NodeApi/JSReference.cs
@@ -2,7 +2,6 @@
// Licensed under the MIT License.
using System;
-using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using Microsoft.JavaScript.NodeApi.Interop;
@@ -31,32 +30,7 @@ namespace Microsoft.JavaScript.NodeApi;
public class JSReference : IDisposable
{
private readonly napi_ref _handle;
- private readonly napi_env _env;
- private readonly JSRuntimeContext? _context;
-
- ///
- /// Environment-scoped queue of no-context references whose finalizers could not release them
- /// on the JS thread, keyed by the owning environment handle.
- ///
- ///
- /// A no-context reference has no , so when its finalizer
- /// runs on the GC finalizer thread (which has no JS scope) it cannot marshal
- /// DeleteReference back to the owning JS thread. Rather than leaking the
- /// napi_ref until the environment is destroyed, the finalizer enqueues the handle here.
- /// The deletion is then performed the next time a scope for the same environment is active on
- /// its JS thread (see ), and a final drain runs when that
- /// environment's root scope is disposed. Deferred handles are always drained while the
- /// environment is still alive, so the queued napi_ref remains valid.
- ///
- private static readonly ConcurrentDictionary>
- s_pendingFinalizerDeletions = new();
-
- ///
- /// Total number of deferred deletions pending across all environments. Used as a cheap
- /// fast-path gate so that the common case (nothing pending) avoids a dictionary lookup on
- /// every scope entry.
- ///
- private static int s_pendingFinalizerDeletionCount;
+ private readonly JSRuntimeContext _context;
///
/// Creates a new instance of a that holds a strong or weak
@@ -90,7 +64,6 @@ public JSReference(napi_ref handle, bool isWeak = false)
JSValueScope currentScope = JSValueScope.Current;
// Thread access to the env will be checked on reference handle use.
- _env = currentScope.UncheckedEnvironmentHandle;
_handle = handle;
_context = currentScope.RuntimeContext;
IsWeak = isWeak;
@@ -160,7 +133,7 @@ public static bool TryCreateReference(
/// accesses the referenced value, if there is a possibility that the current execution
/// context is not already on the correct thread.
///
- public JSSynchronizationContext? SynchronizationContext => _context?.SynchronizationContext;
+ public JSSynchronizationContext? SynchronizationContext => _context.SynchronizationContext;
private napi_env Env
{
@@ -168,7 +141,7 @@ private napi_env Env
{
ThrowIfDisposed();
ThrowIfInvalidThreadAccess();
- return _env;
+ return _context.UncheckedEnvironmentHandle;
}
}
@@ -262,6 +235,8 @@ public bool TryGetValue(out JSValue value)
///
public void Run(Action action)
{
+ ThrowIfDisposed();
+
void GetValueAndRunAction()
{
JSValue? value = GetValue();
@@ -298,6 +273,8 @@ void GetValueAndRunAction()
///
public T Run(Func action)
{
+ ThrowIfDisposed();
+
T GetValueAndRunAction()
{
JSValue? value = GetValue();
@@ -332,7 +309,9 @@ T GetValueAndRunAction()
private void ThrowIfDisposed()
{
- if (IsDisposed)
+ // Once the owning context is disposed its env was torn down and the napi_ref is invalid, so
+ // every access must fail -- not only after the reference itself was explicitly disposed.
+ if (IsDisposed || _context.IsDisposed)
{
throw new ObjectDisposedException(nameof(JSReference));
}
@@ -347,7 +326,7 @@ private void ThrowIfDisposed()
private void ThrowIfInvalidThreadAccess()
{
JSValueScope currentScope = JSValueScope.Current;
- if ((napi_env)currentScope != _env)
+ if ((napi_env)currentScope != _context.UncheckedEnvironmentHandle)
{
int threadId = Environment.CurrentManagedThreadId;
string? threadName = Thread.CurrentThread.Name;
@@ -377,69 +356,45 @@ protected virtual void Dispose(bool disposing)
return;
}
+ // A disposed context never deletes its napi_refs, and this one flag invalidates every
+ // reference at once. At env teardown Node runs finalizers in no defined order, so a napi_ref
+ // may already be finalized and freed -- deleting it again would crash; on an explicit
+ // dispose() the env is still alive and the few undeleted refs are reclaimed at env teardown.
+ if (_context.IsDisposed)
+ {
+ IsDisposed = true;
+ return;
+ }
+
IsDisposed = true;
+ // The guard above handles an already-disposed context; if it is disposed concurrently after
+ // that check, the posted delete is still a safe no-op (the napi_ref went with the env).
+ napi_env env = _context.UncheckedEnvironmentHandle;
+ napi_ref handle = _handle;
+ JSRuntime runtime = _context.Runtime;
+
if (disposing)
{
- // Explicit disposal preserves the documented behavior, including asserting that a
- // no-context reference is disposed from the JS thread.
- if (_context == null)
- {
- ThrowIfInvalidThreadAccess();
- JSValueScope.CurrentRuntime.DeleteReference(_env, _handle).ThrowIfFailed();
- }
- else
- {
- _context.SynchronizationContext.Post(
- () => _context.Runtime.DeleteReference(
- _env, _handle).ThrowIfFailed(), allowSync: true);
- }
+ // Delete the reference on the JS thread (inline if already there).
+ _context.SynchronizationContext.Post(
+ () => runtime.DeleteReference(env, handle).ThrowIfFailed(), allowSync: true);
}
else
{
// The finalizer runs on the GC finalizer thread and MUST NOT throw: an exception
// escaping a finalizer terminates the process (observed as a fatal
- // JSInvalidThreadAccessException / SIGSEGV during worker-thread teardown). Release the
- // native reference only if it can be done without switching threads or asserting an
- // active JS scope, and never let an exception propagate.
- DisposeFromFinalizer();
- }
- }
-
- private void DisposeFromFinalizer()
- {
- try
- {
- if (_context == null)
- {
- // A no-context reference (for example one created from the native host scope) can
- // only be deleted on the JS thread. CurrentOrNull is thread-static, so on the real
- // GC finalizer thread it is null and the inline delete below is skipped; the
- // handle is instead deferred to be deleted the next time a scope for this
- // environment is active on its JS thread (see JSValueScope). The guarded delete
- // still runs directly if Dispose(disposing: false) is ever invoked on the owning
- // JS thread. This releases the napi_ref promptly instead of leaking it until the
- // JS environment is destroyed.
- JSValueScope? scope = JSValueScope.CurrentOrNull;
- if (scope != null && scope.UncheckedEnvironmentHandle == _env)
- {
- scope.Runtime.DeleteReference(_env, _handle);
- }
- else
- {
- EnqueuePendingDeletion(_env, _handle);
- }
- }
- else
+ // JSInvalidThreadAccessException / SIGSEGV during worker-thread teardown). Post the
+ // delete to the JS thread; the synchronization context is a safe no-op once it (and
+ // the environment) are gone.
+ try
{
- // Post the delete to the JS thread. The synchronization context is a safe no-op
- // once it has been disposed (that is, after the worker has been torn down).
- _context.SynchronizationContext?.Post(
+ _context.SynchronizationContext.Post(
() =>
{
try
{
- _context.Runtime.DeleteReference(_env, _handle);
+ runtime.DeleteReference(env, handle);
}
catch
{
@@ -448,81 +403,9 @@ private void DisposeFromFinalizer()
},
allowSync: false);
}
- }
- catch
- {
- // Never allow an exception to escape the finalizer.
- }
- }
-
- ///
- /// Records a no-context reference handle whose deletion was deferred because its finalizer
- /// could not run on the owning JS thread. The handle is deleted later by
- /// or .
- ///
- private static void EnqueuePendingDeletion(napi_env env, napi_ref handle)
- {
- s_pendingFinalizerDeletions
- .GetOrAdd(env, _ => new ConcurrentQueue())
- .Enqueue(handle);
- Interlocked.Increment(ref s_pendingFinalizerDeletionCount);
- }
-
- ///
- /// Deletes any no-context reference handles that were deferred by a finalizer for the given
- /// environment. Must be called on the JS thread that owns with an
- /// active scope, so that DeleteReference is valid.
- ///
- /// The environment whose deferred deletions should be released.
- /// The JS runtime for the environment.
- internal static void DrainPendingDeletions(napi_env env, JSRuntime runtime)
- {
- // Fast path: avoid a dictionary lookup on every scope entry when nothing is pending.
- if (Volatile.Read(ref s_pendingFinalizerDeletionCount) == 0)
- {
- return;
- }
-
- if (!s_pendingFinalizerDeletions.TryGetValue(
- env, out ConcurrentQueue? queue))
- {
- return;
- }
-
- DeletePendingHandles(env, runtime, queue);
- }
-
- ///
- /// Performs a final drain of deferred deletions for an environment that is being torn down and
- /// removes its queue, so the registry does not retain entries for environments that no longer
- /// exist. Must be called on the owning JS thread while the environment is still alive.
- ///
- /// The environment being torn down.
- /// The JS runtime for the environment.
- internal static void RemovePendingDeletions(napi_env env, JSRuntime runtime)
- {
- if (!s_pendingFinalizerDeletions.TryRemove(
- env, out ConcurrentQueue? queue))
- {
- return;
- }
-
- DeletePendingHandles(env, runtime, queue);
- }
-
- private static void DeletePendingHandles(
- napi_env env, JSRuntime runtime, ConcurrentQueue queue)
- {
- while (queue.TryDequeue(out napi_ref handle))
- {
- Interlocked.Decrement(ref s_pendingFinalizerDeletionCount);
- try
- {
- runtime.DeleteReference(env, handle);
- }
catch
{
- // Best effort: the environment may already be gone.
+ // Never allow an exception to escape the finalizer.
}
}
}
diff --git a/src/NodeApi/JSValue.cs b/src/NodeApi/JSValue.cs
index 52f30e3b..c2f7da44 100644
--- a/src/NodeApi/JSValue.cs
+++ b/src/NodeApi/JSValue.cs
@@ -194,9 +194,7 @@ public static unsafe JSValue CreateFunction(
new JSCallbackDescriptor(name, callback, callbackData));
JSValue func = CreateFunction(
name,
- new napi_callback(
- JSValueScope.Current?.ScopeType == JSValueScopeType.NoContext ?
- s_invokeJSCallbackNC : s_invokeJSCallback),
+ new napi_callback(s_invokeJSCallback),
(nint)descriptorHandle);
func.AddGCHandleFinalizer((nint)descriptorHandle);
return func;
@@ -230,7 +228,7 @@ public static unsafe JSValue CreateExternal(object value)
currentScope.UncheckedEnvironmentHandle,
(nint)valueHandle,
new napi_finalize(s_finalizeGCHandle),
- currentScope.RuntimeContextHandle,
+ default,
out napi_value result)
.ThrowIfFailed(result);
}
@@ -801,9 +799,7 @@ public static unsafe JSValue DefineClass(
{
GCHandle descriptorHandle = JSRuntimeContext.Current.AllocGCHandle(constructorDescriptor);
JSValue? func = null;
- napi_callback callback = new(
- Current?.ScopeType == JSValueScopeType.NoContext
- ? s_invokeJSCallbackNC : s_invokeJSCallback);
+ napi_callback callback = new(s_invokeJSCallback);
nint[] handles = ToUnmanagedPropertyDescriptors(
name, propertyDescriptors, (name, descriptorsPtr) =>
@@ -829,7 +825,7 @@ public unsafe JSValue Wrap(object value)
handle,
(nint)valueHandle,
new napi_finalize(s_finalizeGCHandle),
- _scope!.RuntimeContextHandle).ThrowIfFailed();
+ default).ThrowIfFailed();
return this;
}
@@ -848,7 +844,7 @@ public unsafe JSValue Wrap(object value, out JSReference wrapperWeakRef)
handle,
(nint)valueHandle,
new napi_finalize(s_finalizeGCHandle),
- _scope!.RuntimeContextHandle,
+ default,
out napi_ref weakRef).ThrowIfFailed();
wrapperWeakRef = new JSReference(weakRef, isWeak: true);
return this;
@@ -1096,7 +1092,7 @@ public unsafe void AddFinalizer(Action finalize)
handle,
(nint)finalizeHandle,
new napi_finalize(s_callFinalizeAction),
- _scope!.RuntimeContextHandle).ThrowIfFailed();
+ default).ThrowIfFailed();
}
public unsafe void AddFinalizer(Action finalize, out JSReference finalizerRef)
@@ -1108,7 +1104,7 @@ public unsafe void AddFinalizer(Action finalize, out JSReference finalizerRef)
handle,
(nint)finalizeHandle,
new napi_finalize(s_callFinalizeAction),
- _scope!.RuntimeContextHandle,
+ default,
out napi_ref reference).ThrowIfFailed();
finalizerRef = new JSReference(reference, isWeak: true);
}
@@ -1163,36 +1159,6 @@ public JSValue GetAllPropertyNames(
(napi_key_conversion)conversion,
out napi_value result).ThrowIfFailed(result);
- //TODO: (vmoroz) What env parameter does here?
- //TODO: (vmoroz) Move instance data to somewhere else. It must be not in the public API
- internal static unsafe void SetInstanceData(napi_env env, object? data)
- {
- JSRuntime runtime = CurrentRuntime;
- runtime.GetInstanceData(env, out nint handlePtr).ThrowIfFailed();
- if (handlePtr != default)
- {
- // Current napi_set_instance_data implementation does not call finalizer when we replace existing instance data.
- // It means that we only remove the GC root, but do not call Dispose.
- GCHandle.FromIntPtr(handlePtr).Free();
- }
-
- if (data != null)
- {
- GCHandle handle = GCHandle.Alloc(data);
- runtime.SetInstanceData(
- env,
- (nint)handle,
- new napi_finalize(s_finalizeGCHandleToDisposable),
- finalizeHint: default).ThrowIfFailed();
- }
- }
-
- internal static object? GetInstanceData(napi_env env)
- {
- CurrentRuntime.GetInstanceData(env, out nint data).ThrowIfFailed();
- return (data != default) ? GCHandle.FromIntPtr(data).Target : null;
- }
-
public void DetachArrayBuffer() => GetRuntime(out napi_env env, out napi_value handle)
.DetachArrayBuffer(env, handle).ThrowIfFailed();
@@ -1218,13 +1184,8 @@ public void Seal() => GetRuntime(out napi_env env, out napi_value handle)
internal static readonly napi_callback.Delegate s_invokeJSMethod = InvokeJSMethod;
internal static readonly napi_callback.Delegate s_invokeJSGetter = InvokeJSGetter;
internal static readonly napi_callback.Delegate s_invokeJSSetter = InvokeJSSetter;
- internal static readonly napi_callback.Delegate s_invokeJSCallbackNC = InvokeJSCallbackNoContext;
- internal static readonly napi_callback.Delegate s_invokeJSMethodNC = InvokeJSMethodNoContext;
- internal static readonly napi_callback.Delegate s_invokeJSGetterNC = InvokeJSGetterNoContext;
- internal static readonly napi_callback.Delegate s_invokeJSSetterNC = InvokeJSSetterNoContext;
internal static readonly napi_finalize.Delegate s_finalizeGCHandle = FinalizeGCHandle;
- internal static readonly napi_finalize.Delegate s_finalizeGCHandleToDisposable = FinalizeGCHandleToDisposable;
internal static readonly napi_finalize.Delegate s_finalizeGCHandleToPinnedMemory = FinalizeGCHandleToPinnedMemory;
internal static readonly napi_finalize.Delegate s_callFinalizeAction = CallFinalizeAction;
#else
@@ -1236,19 +1197,9 @@ internal static readonly unsafe delegate* unmanaged[Cdecl]
s_invokeJSGetter = &InvokeJSGetter;
internal static readonly unsafe delegate* unmanaged[Cdecl]
s_invokeJSSetter = &InvokeJSSetter;
- internal static readonly unsafe delegate* unmanaged[Cdecl]
- s_invokeJSCallbackNC = &InvokeJSCallbackNoContext;
- internal static readonly unsafe delegate* unmanaged[Cdecl]
- s_invokeJSMethodNC = &InvokeJSMethodNoContext;
- internal static readonly unsafe delegate* unmanaged[Cdecl]
- s_invokeJSGetterNC = &InvokeJSGetterNoContext;
- internal static readonly unsafe delegate* unmanaged[Cdecl]
- s_invokeJSSetterNC = &InvokeJSSetterNoContext;
internal static readonly unsafe delegate* unmanaged[Cdecl]
s_finalizeGCHandle = &FinalizeGCHandle;
- internal static readonly unsafe delegate* unmanaged[Cdecl]
- s_finalizeGCHandleToDisposable = &FinalizeGCHandleToDisposable;
internal static readonly unsafe delegate* unmanaged[Cdecl]
s_finalizeGCHandleToPinnedMemory = &FinalizeGCHandleToPinnedMemory;
internal static readonly unsafe delegate* unmanaged[Cdecl]
@@ -1262,7 +1213,7 @@ internal static unsafe napi_value InvokeJSCallback(
napi_env env, napi_callback_info callbackInfo)
{
return InvokeCallback(
- env, callbackInfo, JSValueScopeType.Callback, (descriptor) => descriptor);
+ env, callbackInfo, (descriptor) => descriptor);
}
#if UNMANAGED_DELEGATES
@@ -1271,11 +1222,11 @@ internal static unsafe napi_value InvokeJSCallback(
private static unsafe napi_value InvokeJSMethod(napi_env env, napi_callback_info callbackInfo)
{
return InvokeCallback(
- env, callbackInfo, JSValueScopeType.Callback, (propertyDescriptor) => new(
+ env, callbackInfo, (propertyDescriptor) => new(
propertyDescriptor.Name,
propertyDescriptor.Method!,
propertyDescriptor.Data,
- propertyDescriptor.ModuleContext));
+ propertyDescriptor.ModuleHolder));
}
#if UNMANAGED_DELEGATES
@@ -1284,11 +1235,11 @@ private static unsafe napi_value InvokeJSMethod(napi_env env, napi_callback_info
private static unsafe napi_value InvokeJSGetter(napi_env env, napi_callback_info callbackInfo)
{
return InvokeCallback(
- env, callbackInfo, JSValueScopeType.Callback, (propertyDescriptor) => new(
+ env, callbackInfo, (propertyDescriptor) => new(
propertyDescriptor.Name,
propertyDescriptor.Getter!,
propertyDescriptor.Data,
- propertyDescriptor.ModuleContext));
+ propertyDescriptor.ModuleHolder));
}
#if UNMANAGED_DELEGATES
@@ -1297,126 +1248,77 @@ private static unsafe napi_value InvokeJSGetter(napi_env env, napi_callback_info
private static napi_value InvokeJSSetter(napi_env env, napi_callback_info callbackInfo)
{
return InvokeCallback(
- env, callbackInfo, JSValueScopeType.Callback, (propertyDescriptor) => new(
- propertyDescriptor.Name,
- propertyDescriptor.Setter!,
- propertyDescriptor.Data,
- propertyDescriptor.ModuleContext));
- }
-
-#if UNMANAGED_DELEGATES
- [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
-#endif
- internal static unsafe napi_value InvokeJSCallbackNoContext(
- napi_env env, napi_callback_info callbackInfo)
- {
- return InvokeCallback(
- env, callbackInfo, JSValueScopeType.NoContext, (descriptor) => descriptor);
- }
-
-#if UNMANAGED_DELEGATES
- [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
-#endif
- private static unsafe napi_value InvokeJSMethodNoContext(napi_env env, napi_callback_info callbackInfo)
- {
- return InvokeCallback(
- env, callbackInfo, JSValueScopeType.NoContext, (propertyDescriptor) => new(
- propertyDescriptor.Name,
- propertyDescriptor.Method!,
- propertyDescriptor.Data,
- propertyDescriptor.ModuleContext));
- }
-
-#if UNMANAGED_DELEGATES
- [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
-#endif
- private static unsafe napi_value InvokeJSGetterNoContext(napi_env env, napi_callback_info callbackInfo)
- {
- return InvokeCallback(
- env, callbackInfo, JSValueScopeType.NoContext, (propertyDescriptor) => new(
- propertyDescriptor.Name,
- propertyDescriptor.Getter!,
- propertyDescriptor.Data,
- propertyDescriptor.ModuleContext));
- }
-
-#if UNMANAGED_DELEGATES
- [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
-#endif
- private static napi_value InvokeJSSetterNoContext(napi_env env, napi_callback_info callbackInfo)
- {
- return InvokeCallback(
- env, callbackInfo, JSValueScopeType.NoContext, (propertyDescriptor) => new(
+ env, callbackInfo, (propertyDescriptor) => new(
propertyDescriptor.Name,
propertyDescriptor.Setter!,
propertyDescriptor.Data,
- propertyDescriptor.ModuleContext));
+ propertyDescriptor.ModuleHolder));
}
private static unsafe napi_value InvokeCallback(
napi_env env,
napi_callback_info callbackInfo,
- JSValueScopeType scopeType,
Func getCallbackDescriptor)
{
- using var scope = new JSValueScope(scopeType, env, runtime: default);
- try
- {
- JSCallbackArgs.GetDataAndLength(scope, callbackInfo, out object? data, out int length);
- Span args = stackalloc napi_value[length];
- JSCallbackDescriptor descriptor = getCallbackDescriptor((TDescriptor)data!);
- scope.ModuleContext = descriptor.ModuleContext;
- return (napi_value)descriptor.Callback(
- new JSCallbackArgs(scope, callbackInfo, args, descriptor.Data));
- }
- catch (Exception ex)
+ // The scope references the context inherited from the parent scope, or -- when the native
+ // host dispatches a callback with no scope on the thread -- recovered from env instance data.
+ // A retained JS function invoked after its context was disposed resolves none, so the call
+ // is a no-op instead of throwing across the unmanaged boundary.
+ JSValueScope? scope = JSValueScope.TryCreateRuntimeScope(env);
+ if (scope is null)
{
- JSError.ThrowError(ex);
return napi_value.Null;
}
- }
-#if UNMANAGED_DELEGATES
- [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
-#endif
- internal static unsafe void FinalizeGCHandle(napi_env env, nint data, nint hint)
- {
- GCHandle handle = GCHandle.FromIntPtr(data);
- if (hint != default)
+ // The inner catch reports a callback error as a JS exception while the scope is still
+ // current; the outer catch keeps the scope's disposal -- which validates LIFO order and can
+ // throw when callback code left a nested scope open -- from escaping the unmanaged boundary.
+ try
{
- GCHandle contextHandle = GCHandle.FromIntPtr(hint);
- JSRuntimeContext context = (JSRuntimeContext)contextHandle.Target!;
- context.FreeGCHandle(handle);
+ using (scope)
+ {
+ try
+ {
+ JSCallbackArgs.GetDataAndLength(scope, callbackInfo, out object? data, out int length);
+ Span args = stackalloc napi_value[length];
+ JSCallbackDescriptor descriptor = getCallbackDescriptor((TDescriptor)data!);
+ scope.ModuleHolder = descriptor.ModuleHolder;
+ return (napi_value)descriptor.Callback(
+ new JSCallbackArgs(scope, callbackInfo, args, descriptor.Data));
+ }
+ catch (Exception ex)
+ {
+ JSError.ThrowError(ex);
+ return napi_value.Null;
+ }
+ }
}
- else
+ catch (Exception)
{
- handle.Free();
+ return napi_value.Null;
}
}
#if UNMANAGED_DELEGATES
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
#endif
- internal static unsafe void FinalizeGCHandleToDisposable(napi_env env, nint data, nint hint)
+ internal static unsafe void FinalizeGCHandle(napi_env env, nint data, nint hint)
{
GCHandle handle = GCHandle.FromIntPtr(data);
+ JSRuntimeContext? context = null;
try
{
- (handle.Target as IDisposable)?.Dispose();
+ // Resolve the context from the env rather than a finalize hint, so the context's
+ // rooting GCHandle can be freed at teardown.
+ context = JSRuntimeContext.FromEnv(env);
}
- finally
+ catch (Exception)
{
- if (hint != default)
- {
- GCHandle contextHandle = GCHandle.FromIntPtr(hint);
- JSRuntimeContext context = (JSRuntimeContext)contextHandle.Target!;
- context.FreeGCHandle(handle);
- }
- else
- {
- handle.Free();
- }
+ // A finalizer must not throw across the native boundary; a failed context lookup falls
+ // back to the best-effort untracked free below.
}
+
+ FreeFinalizerGCHandle(handle, context);
}
#if UNMANAGED_DELEGATES
@@ -1427,14 +1329,18 @@ internal static unsafe void FinalizeGCHandleToPinnedMemory(napi_env env, nint da
// The GC handle is passed via the hint parameter.
// (The data parameter is the pointer to raw memory.)
GCHandle handle = GCHandle.FromIntPtr(hint);
- PinnedMemory pinnedMemory = (PinnedMemory)handle.Target!;
+ PinnedMemory? pinnedMemory = handle.Target as PinnedMemory;
try
{
- pinnedMemory.Dispose();
+ pinnedMemory?.Dispose();
+ }
+ catch (Exception)
+ {
+ // A finalizer must not throw across the native boundary; teardown continues regardless.
}
finally
{
- pinnedMemory.RuntimeContext.FreeGCHandle(handle);
+ FreeFinalizerGCHandle(handle, pinnedMemory?.RuntimeContext);
}
}
@@ -1444,18 +1350,58 @@ internal static unsafe void FinalizeGCHandleToPinnedMemory(napi_env env, nint da
private static unsafe void CallFinalizeAction(napi_env env, nint data, nint hint)
{
GCHandle gcHandle = GCHandle.FromIntPtr(data);
- GCHandle contextHandle = GCHandle.FromIntPtr(hint);
- JSRuntimeContext context = (JSRuntimeContext)contextHandle.Target!;
+ JSRuntimeContext? context = null;
try
{
+ // Resolve the context from the env rather than a finalize hint (see FinalizeGCHandle).
+ context = JSRuntimeContext.FromEnv(env);
+
// TODO: [vmoroz] In future we will be not allowed to run JS in finalizers.
// We must remove creation of the scope.
- using var scope = new JSValueScope(JSValueScopeType.Callback);
+ // Without a live context there is no scope to enter, but the action still runs so its
+ // managed cleanup is not lost.
+ using JSValueScope? scope = context is { IsDisposed: false }
+ ? JSValueScope.CreateRuntimeScope(env, context)
+ : null;
((Action)gcHandle.Target!)();
}
+ catch (Exception)
+ {
+ // A finalizer must not throw across the native boundary and cannot report a JS error
+ // during teardown; a failed lookup, scope, or action is swallowed.
+ }
finally
{
- context.FreeGCHandle(gcHandle);
+ FreeFinalizerGCHandle(gcHandle, context);
+ }
+ }
+
+ // Frees a finalizer's GC handle exactly once without throwing across the native boundary. When
+ // the owning context is still usable the free is tracked; otherwise -- teardown already ran, or
+ // the tracked free itself failed before releasing the handle -- the handle is freed untracked.
+ private static void FreeFinalizerGCHandle(GCHandle handle, JSRuntimeContext? context)
+ {
+ try
+ {
+ if (context != null && !context.IsDisposed)
+ {
+ context.FreeGCHandle(handle);
+ return;
+ }
+ }
+ catch (Exception)
+ {
+ // The tracked free failed (e.g. a debug handle-map mismatch) before releasing the
+ // handle; fall back to an untracked free below.
+ }
+
+ try
+ {
+ handle.Free();
+ }
+ catch (Exception)
+ {
+ // The handle was already freed or is invalid; nothing more to do.
}
}
@@ -1605,7 +1551,7 @@ public unsafe void AddGCHandleFinalizer(nint finalizeData)
handle,
finalizeData,
new napi_finalize(s_finalizeGCHandle),
- Scope.RuntimeContextHandle).ThrowIfFailed();
+ default).ThrowIfFailed();
}
}
@@ -1654,22 +1600,9 @@ private static unsafe nint[] ToUnmanagedPropertyDescriptors(
IReadOnlyCollection descriptors,
UseUnmanagedDescriptors action)
{
- napi_callback methodCallback;
- napi_callback getterCallback;
- napi_callback setterCallback;
- if (JSValueScope.Current?.ScopeType == JSValueScopeType.NoContext)
- {
- // The NativeHost and ManagedHost set up callbacks without a current module context.
- methodCallback = new napi_callback(s_invokeJSMethodNC);
- getterCallback = new napi_callback(s_invokeJSGetterNC);
- setterCallback = new napi_callback(s_invokeJSSetterNC);
- }
- else
- {
- methodCallback = new napi_callback(s_invokeJSMethod);
- getterCallback = new napi_callback(s_invokeJSGetter);
- setterCallback = new napi_callback(s_invokeJSSetter);
- }
+ napi_callback methodCallback = new(s_invokeJSMethod);
+ napi_callback getterCallback = new(s_invokeJSGetter);
+ napi_callback setterCallback = new(s_invokeJSSetter);
nint[] handlesToFinalize = new nint[descriptors.Count];
int count = descriptors.Count;
diff --git a/src/NodeApi/JSValueScope.cs b/src/NodeApi/JSValueScope.cs
index 7e938a8e..10a2fdfe 100644
--- a/src/NodeApi/JSValueScope.cs
+++ b/src/NodeApi/JSValueScope.cs
@@ -2,6 +2,7 @@
// Licensed under the MIT License.
using System;
+using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.JavaScript.NodeApi.Interop;
@@ -13,47 +14,23 @@ namespace Microsoft.JavaScript.NodeApi;
///
/// Indicates the type of within the hierarchy of scopes.
///
-public enum JSValueScopeType
+internal enum JSValueScopeType
{
///
- /// A limited scope without any or .
- /// Used by the Node API .NET native host to set up callbacks before the managed host is
- /// initialized.
+ /// References a and marks the call/context boundary for a JS
+ /// environment. Opens no napi handle scope; it is the scope a falls back
+ /// to for validity when no handle scope is open.
///
- NoContext,
+ RuntimeContext,
///
- /// A parent scope shared by all (non-AOT) .NET modules loaded in the same process. It has
- /// a but no .
- ///
- ///
- /// AOT modules do not have any root scope, so each module scope has a separate
- /// .
- ///
- Root,
-
- ///
- /// A scope specific to each module. It inherits the from the root
- /// scope, and has a unique .
- ///
- ///
- /// AOT modules do not have any root scope, so each module also has a separate
- /// .
- ///
- Module,
-
- ///
- /// Callback scope within a module; inherits context from the module.
- ///
- Callback,
-
- ///
- /// Handle scope within a callback; inherits context from the module.
+ /// Opens a napi handle scope nested within a parent scope, from which it inherits the context.
///
Handle,
///
- /// Escapable handle scope within a callback; inherits context from the module.
+ /// Opens an escapable napi handle scope nested within a parent scope, and can escape one value
+ /// to the parent scope.
///
Escapable,
}
@@ -76,8 +53,9 @@ public sealed class JSValueScope : IDisposable
#pragma warning restore IDE0032
private readonly SynchronizationContext? _previousSyncContext;
private readonly nint _scopeHandle;
+ private bool _disposeRuntimeContextOnClose;
- public JSValueScopeType ScopeType { get; }
+ internal JSValueScopeType ScopeType { get; }
///
/// Gets the current JS value scope.
@@ -142,176 +120,182 @@ public static explicit operator napi_env(JSValueScope scope)
public JSRuntime Runtime { get; }
public JSRuntimeContext RuntimeContext { get; }
- internal nint RuntimeContextHandle { get; }
internal static JSRuntime CurrentRuntime => Current.Runtime;
internal static JSRuntimeContext? CurrentRuntimeContext => CurrentOrNull?.RuntimeContext;
- public JSModuleContext? ModuleContext { get; internal set; }
+ ///
+ /// Holds the instance of the module class for the current module. It is a shared mutable cell
+ /// so callback descriptors can capture it during initialization, before the module instance
+ /// exists, and observe the instance once it is assigned.
+ ///
+ internal StrongBox? ModuleHolder { get; set; }
+
+ ///
+ /// Gets the instance of the module class for the current module, used as the 'this' argument
+ /// for module-level instance members, or null if there is no module class.
+ ///
+ public object? Module => ModuleHolder?.Value;
+
+ ///
+ /// Creates a scope that references a and marks the call/context
+ /// boundary for a JS environment. It opens no napi handle scope.
+ ///
+ /// The JS environment handle.
+ /// The runtime context to reference. When null it is inherited from the
+ /// parent scope, or recovered from the environment instance data.
+ public static JSValueScope CreateRuntimeScope(
+ napi_env env = default, JSRuntimeContext? context = null)
+ => new(env, context);
///
- /// Creates a new instance of a with a specified scope type.
+ /// Attempts to create a scope for a callback
+ /// entering from JS, returning null when no live context can be resolved for the environment --
+ /// for example a retained JS function invoked after its context was disposed. Callback adapters
+ /// use it to become a no-op in that case. It never throws: an exception escaping an
+ /// callback would cross the
+ /// native boundary and terminate the process.
///
- /// The type of scope to create; default is
- /// .
- public JSValueScope(JSValueScopeType scopeType = JSValueScopeType.Handle)
- : this(scopeType, env: default, runtime: default)
+ internal static JSValueScope? TryCreateRuntimeScope(napi_env env)
{
+ try
+ {
+ // Inherit the current scope's context -- every scope on a thread shares one context per
+ // environment -- or recover it from env instance data when no scope is open yet.
+ JSRuntimeContext? context = CurrentOrNull?.RuntimeContext ?? JSRuntimeContext.FromEnv(env);
+ return context is { IsDisposed: false } ? new JSValueScope(env, context) : null;
+ }
+ catch (Exception)
+ {
+ return null;
+ }
}
///
- /// Creates a new instance of a , which may be a parentless scope
- /// with initial environment handle and JS runtime.
+ /// Creates a scope that starts a fresh module
+ /// boundary: it references the same (inherited or supplied) but
+ /// begins a new module holder, so each loaded module resolves its own module instance via
+ /// .
///
- /// The type of scope to create.
- /// JS environment handle, required only for creating a scope
- /// without a parent, otherwise the environment is inherited from the parent scope.
- /// JS runtime interface, required only for creating a scope
- /// without a parent, otherwise the JS runtime is inherited from the parent scope.
- /// Optional synchronization context to use for async
- /// operations; if omitted then a default synchronization context is used.
- public JSValueScope(
- JSValueScopeType scopeType,
- napi_env env,
- JSRuntime? runtime,
- JSSynchronizationContext? synchronizationContext = null)
- {
- ScopeType = scopeType;
+ /// The JS environment handle.
+ /// The runtime context to reference. When null it is inherited from the
+ /// parent scope, or recovered from the environment instance data.
+ public static JSValueScope CreateModuleScope(
+ napi_env env = default, JSRuntimeContext? context = null)
+ => new(env, context, moduleBoundary: true);
- if (scopeType == JSValueScopeType.NoContext)
- {
- // A NoContext scope can inherit the env from a parent NoContext scope.
- _parentScope = CurrentOrNull;
- if (_parentScope != null && _parentScope.ScopeType != JSValueScopeType.NoContext)
- {
- throw new InvalidOperationException(
- "A NoContext scope cannot be created within another type of scope.");
- }
+ ///
+ /// Creates a napi handle scope nested within the current scope. JS values created within it
+ /// are released when it is disposed, unless held by a .
+ ///
+ public static JSValueScope CreateHandleScope() => new(JSValueScopeType.Handle);
- if (env.IsNull)
- {
- env = _parentScope?._env ??
- throw new ArgumentNullException(nameof(env), "An environment is required.");
- }
+ ///
+ /// Creates an escapable napi handle scope nested within the current scope. One value may be
+ /// promoted to the parent scope with .
+ ///
+ public static JSValueScope CreateEscapableScope() => new(JSValueScopeType.Escapable);
- runtime ??= _parentScope?.Runtime ??
- throw new ArgumentNullException(nameof(runtime), "A runtime is required.");
+ ///
+ /// Creates a scope that references an existing
+ /// (it never creates one). When
+ /// is true it starts a fresh module holder even if the context is inherited from the parent.
+ ///
+ private JSValueScope(napi_env env, JSRuntimeContext? context, bool moduleBoundary = false)
+ {
+ ScopeType = JSValueScopeType.RuntimeContext;
+ _parentScope = CurrentOrNull;
+
+ // Inherit the parent scope's context, else recover it from the env instance data.
+ context ??= _parentScope?.RuntimeContext
+ ?? JSRuntimeContext.FromEnv(env)
+ ?? throw new InvalidOperationException(
+ "A runtime context could not be resolved for the scope.");
+
+ // Every scope on a thread's stack shares one runtime context (one per environment per loaded
+ // module -- separate modules have separate thread-static scope stacks), so a nested scope must
+ // continue its parent's context. A mismatch is a caller error, not something to reconcile.
+ if (_parentScope is not null && context != _parentScope.RuntimeContext)
+ {
+ throw new InvalidOperationException(
+ "A nested value scope must use the same runtime context as its parent scope.");
+ }
- _env = env;
- ThreadId = Environment.CurrentManagedThreadId;
- Runtime = runtime;
+ // A disposed context's environment is torn down; entering it would call Node-API on a
+ // dead env, which the scope's own unchecked handle would not catch.
+ if (context.IsDisposed)
+ {
+ throw new ObjectDisposedException(nameof(JSRuntimeContext));
}
- else if (scopeType == JSValueScopeType.Root)
+
+ // A supplied env must match the resolved context — whether passed explicitly (a root
+ // boundary: host, AOT module, or embedding) or inherited from the parent — otherwise this
+ // scope would wrap handles from a different environment.
+ if (!env.IsNull && env != context.UncheckedEnvironmentHandle)
{
- _parentScope = CurrentOrNull;
- if (_parentScope != null)
- {
- if (_parentScope.ScopeType == JSValueScopeType.Root)
- {
- // When there are multiple instances of the managed host in a process
- // (created by separate workers), they do not inherit scope.
- _parentScope = null;
- }
- else
- {
- throw new InvalidOperationException(
- "A Root scope cannot be created within another scope.");
- }
- }
+ throw new ArgumentException(
+ "Environment does not match the runtime context.", nameof(env));
+ }
- if (env.IsNull)
- {
- throw new ArgumentNullException(
- nameof(env), "An environment is required for a root scope.");
- }
- else if (runtime == null)
- {
- throw new ArgumentNullException(
- nameof(runtime), "A runtime is required for a root scope.");
- }
+ _env = context.UncheckedEnvironmentHandle;
- _env = env;
- ThreadId = Environment.CurrentManagedThreadId;
- Runtime = runtime;
- }
- else
+ // A runtime context is bound to the thread that created it (its env's JS thread); entering it
+ // from another thread would allow napi to be called off that thread.
+ if (context.OwningThreadId != Environment.CurrentManagedThreadId)
{
- _parentScope = CurrentOrNull;
+ throw new JSInvalidThreadAccessException(
+ _parentScope,
+ "A runtime context may be entered only on the thread that created it.");
+ }
- if (scopeType == JSValueScopeType.Module &&
- _parentScope != null && _parentScope.ScopeType == JSValueScopeType.Module)
- {
- // When there are multiple AOT modules in a process, they do not inherit scope.
- _parentScope = null;
- }
+ ThreadId = Environment.CurrentManagedThreadId;
+ Runtime = context.Runtime;
- if (_parentScope == null)
- {
- // Module scopes may be created without a parent scope (for AOT modules).
- if (scopeType != JSValueScopeType.Module)
- {
- throw new InvalidOperationException(
- $"A {scopeType} scope cannot be created without a parent scope.");
- }
-
- // AOT module scopes are constructed with an env parameter
- // but without a pre-initialized runtime.
- _env = env.IsNull ? throw new ArgumentNullException(nameof(env)) : env;
- ThreadId = Environment.CurrentManagedThreadId;
- Runtime = runtime ?? new NodejsRuntime();
- }
- else if (_parentScope.IsDisposed)
- {
- // This should never happen because disposing a scope removes it from
- // s_currentScope (which is used to initialize _parentScope above).
- throw new InvalidOperationException("Parent scope is disposed.");
- }
- else if (scopeType == JSValueScopeType.Callback &&
- _parentScope.ScopeType != JSValueScopeType.Callback &&
- _parentScope.ScopeType != JSValueScopeType.Module &&
- _parentScope.ScopeType != JSValueScopeType.Root &&
- _parentScope.ScopeType != JSValueScopeType.NoContext)
- {
- throw new InvalidOperationException(
- $"A Callback scope must be created within a Root, Module, or Callback scope. " +
- $"Current scope: {scopeType}");
- }
- else if (!env.IsNull && env != _parentScope._env)
- {
- throw new ArgumentException(
- "Environment must not be provided for a non-root scope.",
- nameof(env));
- }
- else if (runtime != null && runtime != _parentScope.Runtime)
- {
- throw new ArgumentException(
- "Runtime must not be provided for a non-root scope.",
- nameof(runtime));
- }
- else
- {
- _parentScope.ThrowIfInvalidThreadAccess();
- _env = _parentScope._env;
- ThreadId = _parentScope.ThreadId;
- Runtime = _parentScope.Runtime;
- }
+ // A nested runtime scope that continues the parent's context inherits its module holder; a
+ // module boundary, or a root with a new/explicit context, starts a fresh one so each loaded
+ // module resolves its own module instance.
+ ModuleHolder = !moduleBoundary && _parentScope?.RuntimeContext == context
+ ? _parentScope.ModuleHolder
+ : new StrongBox();
- if (scopeType == JSValueScopeType.Module)
- {
- if (_parentScope?.ModuleContext != null)
- {
- throw new InvalidOperationException("Module scope cannot be nested.");
- }
+ JSValueScope? previousScope = CurrentOrNull;
+ try
+ {
+ CurrentOrNull = this;
+ RuntimeContext = context;
- ModuleContext = new JSModuleContext();
- }
- else
- {
- ModuleContext = _parentScope!.ModuleContext;
- }
+ _previousSyncContext = SynchronizationContext.Current;
+ SynchronizationContext.SetSynchronizationContext(context.SynchronizationContext);
+ }
+ catch (Exception)
+ {
+ CurrentOrNull = previousScope;
+ throw;
+ }
+ }
+
+ ///
+ /// Creates a or
+ /// scope that opens a napi handle scope nested within the current scope.
+ ///
+ private JSValueScope(JSValueScopeType scopeType)
+ {
+ ScopeType = scopeType;
+ _parentScope = CurrentOrNull ?? throw new InvalidOperationException(
+ $"A {scopeType} scope cannot be created without a parent scope.");
+
+ if (_parentScope.IsDisposed)
+ {
+ throw new InvalidOperationException("Parent scope is disposed.");
}
- _scopeHandle = ScopeType switch
+ _parentScope.ThrowIfInvalidThreadAccess();
+ _env = _parentScope._env;
+ ThreadId = _parentScope.ThreadId;
+ Runtime = _parentScope.Runtime;
+ ModuleHolder = _parentScope.ModuleHolder;
+
+ _scopeHandle = scopeType switch
{
JSValueScopeType.Handle
=> Runtime.OpenHandleScope(_env, out napi_handle_scope handleScope)
@@ -320,88 +304,99 @@ public JSValueScope(
=> Runtime.OpenEscapableHandleScope(
_env, out napi_escapable_handle_scope handleScope)
.ThrowIfFailed(handleScope).Handle,
- _ => default,
+ _ => throw new ArgumentException(
+ $"Invalid handle scope type: {scopeType}", nameof(scopeType)),
};
JSValueScope? previousScope = CurrentOrNull;
try
{
CurrentOrNull = this;
-
- if (scopeType == JSValueScopeType.NoContext)
- {
- // NoContext scopes do not have a runtime context.
- RuntimeContext = null!;
- RuntimeContextHandle = default;
- }
- else if (_parentScope?.RuntimeContext != null)
- {
- // Nested scopes inherit the runtime context from the parent scope.
- RuntimeContext = _parentScope.RuntimeContext;
- RuntimeContextHandle = _parentScope.RuntimeContextHandle;
- }
- else
- {
- // Unparented scopes initialize a new runtime context.
- RuntimeContext = new JSRuntimeContext(env, Runtime, synchronizationContext);
- RuntimeContextHandle = (nint)GCHandle.Alloc(RuntimeContext);
- }
-
- if (scopeType == JSValueScopeType.Root || scopeType == JSValueScopeType.Callback)
- {
- _previousSyncContext = SynchronizationContext.Current;
- SynchronizationContext.SetSynchronizationContext(
- RuntimeContext.SynchronizationContext);
- }
+ RuntimeContext = _parentScope.RuntimeContext;
}
catch (Exception)
{
CurrentOrNull = previousScope;
throw;
}
+ }
- // Release any no-context reference deletions that a finalizer had to defer because it could
- // not run on the JS thread. This scope is active on the owning JS thread, so deleting the
- // deferred handles here is valid. The call is a cheap no-op when nothing is pending.
- JSReference.DrainPendingDeletions(_env, Runtime);
+ ///
+ /// Disposes once every value scope open on it has closed, or
+ /// immediately if none is open. A dispose request can arrive through a native callback nested
+ /// inside open value scopes (JS calling native calling JS…); disposing the context then would
+ /// leave those scopes to close their napi handle scopes on a disposed context as they unwind, an
+ /// unbalanced close that Node-API rejects. Every scope on the stack shares this one context, so
+ /// the innermost open scope is flagged and the outermost disposes the context as it closes.
+ ///
+ internal static void DisposeRuntimeContextWhenIdle(JSRuntimeContext runtimeContext)
+ {
+ if (CurrentOrNull is { } scope)
+ {
+ scope._disposeRuntimeContextOnClose = true;
+ }
+ else
+ {
+ runtimeContext.Dispose();
+ }
}
public void Dispose()
{
if (IsDisposed) return;
- IsDisposed = true;
- if (ScopeType == JSValueScopeType.Root || ScopeType == JSValueScopeType.NoContext)
+ // A scope must be disposed on its creating thread and in reverse order of creation: an
+ // off-thread or out-of-order close calls napi on the wrong thread or restores the wrong parent.
+ if (CurrentOrNull != this)
{
- // This environment-scoped scope is going away, so perform a final drain of any deferred
- // no-context reference deletions and remove the environment's queue, preventing the
- // registry from retaining entries for environments that no longer exist. The scope is
- // still current here, so deletion runs on the owning JS thread while the environment is
- // alive.
- JSReference.RemovePendingDeletions(_env, Runtime);
+ if (CurrentOrNull?._env != _env)
+ {
+ throw new JSInvalidThreadAccessException(
+ currentScope: CurrentOrNull,
+ targetScope: this,
+ "A value scope must be disposed on the thread that created it.");
+ }
+
+ throw new InvalidOperationException(
+ "A value scope cannot be disposed while a scope created within it is still open.");
}
- if (ScopeType != JSValueScopeType.NoContext)
+ switch (ScopeType)
{
- napi_env env = RuntimeContext.EnvironmentHandle;
+ // Fetch the env only where it is used, so disposing a runtime scope after its context
+ // is torn down does not throw from the checked handle accessor.
+ case JSValueScopeType.Handle:
+ Runtime.CloseHandleScope(
+ RuntimeContext.EnvironmentHandle,
+ new napi_handle_scope(_scopeHandle)).ThrowIfFailed();
+ break;
+ case JSValueScopeType.Escapable:
+ Runtime.CloseEscapableHandleScope(
+ RuntimeContext.EnvironmentHandle,
+ new napi_escapable_handle_scope(_scopeHandle)).ThrowIfFailed();
+ break;
+ default:
+ SynchronizationContext.SetSynchronizationContext(_previousSyncContext);
+ break;
+ }
- switch (ScopeType)
+ IsDisposed = true;
+ CurrentOrNull = _parentScope;
+
+ // Carry a deferred context-disposal request (see DisposeRuntimeContextWhenIdle) out to the
+ // parent, or -- at the outermost scope, where none of the context's scopes remain open --
+ // dispose the context now.
+ if (_disposeRuntimeContextOnClose)
+ {
+ if (_parentScope is null)
{
- case JSValueScopeType.Handle:
- Runtime.CloseHandleScope(
- env, new napi_handle_scope(_scopeHandle)).ThrowIfFailed();
- break;
- case JSValueScopeType.Escapable:
- Runtime.CloseEscapableHandleScope(
- env, new napi_escapable_handle_scope(_scopeHandle)).ThrowIfFailed();
- break;
- default:
- SynchronizationContext.SetSynchronizationContext(_previousSyncContext);
- break;
+ RuntimeContext.Dispose();
+ }
+ else
+ {
+ _parentScope._disposeRuntimeContextOnClose = true;
}
}
-
- CurrentOrNull = _parentScope;
}
public JSValue Escape(JSValue value)
diff --git a/src/NodeApi/NodeApi.csproj b/src/NodeApi/NodeApi.csproj
index 3727e35e..dde29bad 100644
--- a/src/NodeApi/NodeApi.csproj
+++ b/src/NodeApi/NodeApi.csproj
@@ -29,6 +29,7 @@
+
diff --git a/src/NodeApi/Runtime/NodeEmbedding.cs b/src/NodeApi/Runtime/NodeEmbedding.cs
index 5224f9ba..dd908e9a 100644
--- a/src/NodeApi/Runtime/NodeEmbedding.cs
+++ b/src/NodeApi/Runtime/NodeEmbedding.cs
@@ -9,6 +9,7 @@ namespace Microsoft.JavaScript.NodeApi.Runtime;
using System.Runtime.CompilerServices;
#endif
using System.Runtime.InteropServices;
+using Microsoft.JavaScript.NodeApi.Interop;
using static JSRuntime;
using static NodejsRuntime;
@@ -352,6 +353,31 @@ internal static unsafe NodeEmbeddingStatus RuntimeConfigureCallbackAdapter(
}
}
+ // The embedding invokes these adapters (and opens Node-API scopes) repeatedly for the same
+ // env; reuse the env's registered context to keep one context per env, instead of leaking a new
+ // context and overwriting the instance-data slot on each call. The instance-data finalizer
+ // disposes the context at env teardown.
+ internal static JSRuntimeContext GetOrCreateContext(napi_env env)
+ => JSRuntimeContext.FromEnv(env) ?? new JSRuntimeContext(env, JSRuntime);
+
+ // Opens the runtime scope for an embedding callback inside a guarded path: context resolution
+ // (instance-data registration) and scope creation are fallible, and every caller is an
+ // UnmanagedCallersOnly adapter, so a failure is reported through the embedding error path
+ // rather than escaping the native boundary. Returns null (with the last error set) on failure.
+ private static JSValueScope? TryEnterRuntimeScope(napi_env env)
+ {
+ try
+ {
+ JSRuntimeContext context = GetOrCreateContext(env);
+ return JSValueScope.CreateRuntimeScope(env, context);
+ }
+ catch (Exception ex)
+ {
+ JSRuntime.EmbeddingSetLastErrorMessage(ex.Message.AsSpan());
+ return null;
+ }
+ }
+
#if UNMANAGED_DELEGATES
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
#endif
@@ -362,16 +388,27 @@ internal static unsafe void RuntimePreloadCallbackAdapter(
napi_value process,
napi_value require)
{
- using var jsValueScope = new JSValueScope(JSValueScopeType.Root, env, JSRuntime);
+ JSValueScope? jsValueScope = TryEnterRuntimeScope(env);
+ if (jsValueScope is null) return;
try
{
- var callback = (PreloadCallback)GCHandle.FromIntPtr(cb_data).Target!;
- NodeEmbeddingRuntime embeddingRuntime = NodeEmbeddingRuntime.FromHandle(runtime);
- callback(embeddingRuntime, new JSValue(process), new JSValue(require));
+ using (jsValueScope)
+ {
+ try
+ {
+ var callback = (PreloadCallback)GCHandle.FromIntPtr(cb_data).Target!;
+ NodeEmbeddingRuntime embeddingRuntime = NodeEmbeddingRuntime.FromHandle(runtime);
+ callback(embeddingRuntime, new JSValue(process), new JSValue(require));
+ }
+ catch (Exception ex)
+ {
+ JSError.ThrowError(ex);
+ }
+ }
}
- catch (Exception ex)
+ catch (Exception)
{
- JSError.ThrowError(ex);
+ // A scope-disposal exception must not escape the unmanaged boundary.
}
}
@@ -386,17 +423,28 @@ internal static unsafe napi_value RuntimeLoadingCallbackAdapter(
napi_value require,
napi_value run_cjs)
{
- using var jsValueScope = new JSValueScope(JSValueScopeType.Root, env, JSRuntime);
+ JSValueScope? jsValueScope = TryEnterRuntimeScope(env);
+ if (jsValueScope is null) return napi_value.Null;
try
{
- var callback = (LoadingCallback)GCHandle.FromIntPtr(cb_data).Target!;
- NodeEmbeddingRuntime embeddingRuntime = NodeEmbeddingRuntime.FromHandle(runtime);
- return (napi_value)callback(
- embeddingRuntime, new JSValue(process), new JSValue(require), new JSValue(run_cjs));
+ using (jsValueScope)
+ {
+ try
+ {
+ var callback = (LoadingCallback)GCHandle.FromIntPtr(cb_data).Target!;
+ NodeEmbeddingRuntime embeddingRuntime = NodeEmbeddingRuntime.FromHandle(runtime);
+ return (napi_value)callback(
+ embeddingRuntime, new JSValue(process), new JSValue(require), new JSValue(run_cjs));
+ }
+ catch (Exception ex)
+ {
+ JSError.ThrowError(ex);
+ return napi_value.Null;
+ }
+ }
}
- catch (Exception ex)
+ catch (Exception)
{
- JSError.ThrowError(ex);
return napi_value.Null;
}
}
@@ -410,16 +458,27 @@ internal static unsafe void RuntimeLoadedCallbackAdapter(
napi_env env,
napi_value loading_result)
{
- using var jsValueScope = new JSValueScope(JSValueScopeType.Root, env, JSRuntime);
+ JSValueScope? jsValueScope = TryEnterRuntimeScope(env);
+ if (jsValueScope is null) return;
try
{
- var callback = (LoadedCallback)GCHandle.FromIntPtr(cb_data).Target!;
- NodeEmbeddingRuntime embeddingRuntime = NodeEmbeddingRuntime.FromHandle(runtime);
- callback(embeddingRuntime, new JSValue(loading_result));
+ using (jsValueScope)
+ {
+ try
+ {
+ var callback = (LoadedCallback)GCHandle.FromIntPtr(cb_data).Target!;
+ NodeEmbeddingRuntime embeddingRuntime = NodeEmbeddingRuntime.FromHandle(runtime);
+ callback(embeddingRuntime, new JSValue(loading_result));
+ }
+ catch (Exception ex)
+ {
+ JSError.ThrowError(ex);
+ }
+ }
}
- catch (Exception ex)
+ catch (Exception)
{
- JSError.ThrowError(ex);
+ // A scope-disposal exception must not escape the unmanaged boundary.
}
}
@@ -435,29 +494,35 @@ internal static unsafe napi_value ModuleInitializeCallbackAdapter(
{
// 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,
+ // module; a scope for it would need its own runtime context, which cannot be nested in
+ // the runtime's scope. Initialize the module within the runtime's scope instead,
// so that its exports share the runtime context and later callbacks into them work.
- // 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;
+ JSValueScope? jsValueScope = TryEnterRuntimeScope(
+ JSValueScope.CurrentOrNull?.UncheckedEnvironmentHandle ?? env);
+ if (jsValueScope is null) return napi_value.Null;
+ napi_env scopeEnv = jsValueScope.UncheckedEnvironmentHandle;
try
{
- var callback = (InitializeModuleCallback)GCHandle.FromIntPtr(cb_data).Target!;
- NodeEmbeddingRuntime embeddingRuntime = NodeEmbeddingRuntime.FromHandle(runtime);
- return (napi_value)callback(
- embeddingRuntime,
- Utf8StringArray.PtrToStringUTF8((byte*)module_name),
- new JSValue(exports));
+ using (jsValueScope)
+ {
+ try
+ {
+ var callback = (InitializeModuleCallback)GCHandle.FromIntPtr(cb_data).Target!;
+ NodeEmbeddingRuntime embeddingRuntime = NodeEmbeddingRuntime.FromHandle(runtime);
+ return (napi_value)callback(
+ embeddingRuntime,
+ Utf8StringArray.PtrToStringUTF8((byte*)module_name),
+ new JSValue(exports));
+ }
+ catch (Exception ex)
+ {
+ JSError.ThrowError(ex);
+ return napi_value.Null;
+ }
+ }
}
- catch (Exception ex)
+ catch (Exception)
{
- JSError.ThrowError(ex);
return napi_value.Null;
}
finally
@@ -526,15 +591,26 @@ internal static unsafe NodeEmbeddingStatus TaskPostCallbackAdapter(
#endif
internal static unsafe void NodeApiRunCallbackAdapter(nint cb_data, napi_env env)
{
- using var jsValueScope = new JSValueScope(JSValueScopeType.Root, env, JSRuntime);
+ JSValueScope? jsValueScope = TryEnterRuntimeScope(env);
+ if (jsValueScope is null) return;
try
{
- var callback = (RunNodeApiCallback)GCHandle.FromIntPtr(cb_data).Target!;
- callback();
+ using (jsValueScope)
+ {
+ try
+ {
+ var callback = (RunNodeApiCallback)GCHandle.FromIntPtr(cb_data).Target!;
+ callback();
+ }
+ catch (Exception ex)
+ {
+ JSError.ThrowError(ex);
+ }
+ }
}
- catch (Exception ex)
+ catch (Exception)
{
- JSError.ThrowError(ex);
+ // A scope-disposal exception must not escape the unmanaged boundary.
}
}
}
diff --git a/src/NodeApi/Runtime/NodeEmbeddingNodeApiScope.cs b/src/NodeApi/Runtime/NodeEmbeddingNodeApiScope.cs
index 6513384b..5bfb61b4 100644
--- a/src/NodeApi/Runtime/NodeEmbeddingNodeApiScope.cs
+++ b/src/NodeApi/Runtime/NodeEmbeddingNodeApiScope.cs
@@ -4,6 +4,7 @@
namespace Microsoft.JavaScript.NodeApi.Runtime;
using System;
+using Microsoft.JavaScript.NodeApi.Interop;
using static JSRuntime;
using static NodejsRuntime;
@@ -19,8 +20,18 @@ public NodeEmbeddingNodeApiScope(NodeEmbeddingRuntime runtime)
NodeEmbedding.JSRuntime.EmbeddingRuntimeOpenNodeApiScope(
runtime.Handle, out _nodeApiScope, out napi_env env)
.ThrowIfFailed();
- _valueScope = new JSValueScope(
- JSValueScopeType.Root, env, NodeEmbedding.JSRuntime);
+ try
+ {
+ JSRuntimeContext context = NodeEmbedding.GetOrCreateContext(env);
+ _valueScope = JSValueScope.CreateRuntimeScope(env, context);
+ }
+ catch
+ {
+ // A throwing constructor cannot be disposed, so close the native scope opened above
+ // before rethrowing, or it would leak for the lifetime of the embedding runtime.
+ NodeEmbedding.JSRuntime.EmbeddingRuntimeCloseNodeApiScope(runtime.Handle, _nodeApiScope);
+ throw;
+ }
}
///
@@ -34,11 +45,14 @@ public NodeEmbeddingNodeApiScope(NodeEmbeddingRuntime runtime)
public void Dispose()
{
if (IsDisposed) return;
- IsDisposed = true;
+ // Mark disposal only after both closes succeed: the value scope's LIFO/thread check can throw
+ // if a nested scope is still open, and marking first would leave that unretryable and leak the
+ // native Node-API scope.
_valueScope.Dispose();
NodeEmbedding.JSRuntime.EmbeddingRuntimeCloseNodeApiScope(
_runtime.Handle, _nodeApiScope)
.ThrowIfFailed();
+ IsDisposed = true;
}
}
diff --git a/src/NodeApi/Runtime/TracingJSRuntime.cs b/src/NodeApi/Runtime/TracingJSRuntime.cs
index e78de8df..68ddc96d 100644
--- a/src/NodeApi/Runtime/TracingJSRuntime.cs
+++ b/src/NodeApi/Runtime/TracingJSRuntime.cs
@@ -377,57 +377,71 @@ private static readonly unsafe delegate* unmanaged[Cdecl]
s_traceSetterCallback = &TraceSetterCallback;
#endif
+ // Like JSValue.InvokeCallback (which these replace when tracing is on): a callback that can no
+ // longer resolve a context -- for example a retained JS function invoked after its context was
+ // disposed -- is a no-op instead of throwing across the UnmanagedCallersOnly callbacks below.
+ private static napi_value InvokeTraceCallback(
+ napi_env env,
+ napi_callback_info cbinfo,
+ Func getCallbackDescriptor)
+ {
+ JSValueScope? scope = JSValueScope.TryCreateRuntimeScope(env);
+ if (scope is null)
+ {
+ return napi_value.Null;
+ }
+
+ // TraceCallback reports callback errors as JS exceptions itself; the outer try only keeps a
+ // scope-disposal exception from escaping the UnmanagedCallersOnly boundary.
+ try
+ {
+ using (scope)
+ {
+ return ((TracingJSRuntime)scope.Runtime).TraceCallback(
+ scope, cbinfo, getCallbackDescriptor);
+ }
+ }
+ catch (Exception)
+ {
+ return napi_value.Null;
+ }
+ }
+
#if UNMANAGED_DELEGATES
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
#endif
private static unsafe napi_value TraceFunctionCallback(napi_env env, napi_callback_info cbinfo)
- {
- using var scope = new JSValueScope(JSValueScopeType.Callback);
- return ((TracingJSRuntime)scope.Runtime).TraceCallback(
- scope, cbinfo, (descriptor) => descriptor);
- }
+ => InvokeTraceCallback(env, cbinfo, (descriptor) => descriptor);
#if UNMANAGED_DELEGATES
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
#endif
private static unsafe napi_value TraceMethodCallback(napi_env env, napi_callback_info cbinfo)
- {
- using var scope = new JSValueScope(JSValueScopeType.Callback);
- return ((TracingJSRuntime)scope.Runtime).TraceCallback(
- scope, cbinfo, (propertyDescriptor) => new(
- propertyDescriptor.Name,
- propertyDescriptor.Method!,
- propertyDescriptor.Data,
- propertyDescriptor.ModuleContext));
- }
+ => InvokeTraceCallback(env, cbinfo, (propertyDescriptor) => new(
+ propertyDescriptor.Name,
+ propertyDescriptor.Method!,
+ propertyDescriptor.Data,
+ propertyDescriptor.ModuleHolder));
#if UNMANAGED_DELEGATES
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
#endif
private static unsafe napi_value TraceGetterCallback(napi_env env, napi_callback_info cbinfo)
- {
- using var scope = new JSValueScope(JSValueScopeType.Callback);
- return ((TracingJSRuntime)scope.Runtime).TraceCallback(
- scope, cbinfo, (propertyDescriptor) => new(
- propertyDescriptor.Name,
- propertyDescriptor.Getter!,
- propertyDescriptor.Data,
- propertyDescriptor.ModuleContext));
- }
+ => InvokeTraceCallback(env, cbinfo, (propertyDescriptor) => new(
+ propertyDescriptor.Name,
+ propertyDescriptor.Getter!,
+ propertyDescriptor.Data,
+ propertyDescriptor.ModuleHolder));
#if UNMANAGED_DELEGATES
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
#endif
private static unsafe napi_value TraceSetterCallback(napi_env env, napi_callback_info cbinfo)
- {
- using var scope = new JSValueScope(JSValueScopeType.Callback);
- return ((TracingJSRuntime)scope.Runtime).TraceCallback(
- scope, cbinfo, (propertyDescriptor) => new(
- propertyDescriptor.Name,
- propertyDescriptor.Setter!,
- propertyDescriptor.Data,
- propertyDescriptor.ModuleContext));
- }
+ => InvokeTraceCallback(env, cbinfo, (propertyDescriptor) => new(
+ propertyDescriptor.Name,
+ propertyDescriptor.Setter!,
+ propertyDescriptor.Data,
+ propertyDescriptor.ModuleHolder));
///
/// Traces a callback function, method, getter, or setter, including args and return value.
@@ -443,6 +457,9 @@ public napi_value TraceCallback(
throw new InvalidOperationException("Callback data is null."));
JSCallbackDescriptor descriptor = getCallbackDescriptor(data);
+ // Mirror InvokeCallback: make the module instance available to module-level members.
+ scope.ModuleHolder = descriptor.ModuleHolder;
+
Span argsSpan = stackalloc napi_value[length];
JSCallbackArgs args = new(scope, cbinfo, argsSpan, descriptor.Data);
@@ -548,7 +565,7 @@ public override napi_status GetInstanceData(napi_env env, out nint result)
nint value = default;
napi_status status = TraceCall(
[],
- () => (_runtime.GetInstanceData(env, out value), Format(value)));
+ () => (_runtime.GetInstanceData(env, out value), FormatAddress(value)));
result = value;
return status;
}
@@ -557,11 +574,14 @@ public override napi_status SetInstanceData(
napi_env env, nint data, napi_finalize finalize_cb, nint finalize_hint)
{
napi_status status = TraceCall(
- [Format(data)],
+ [FormatAddress(data)],
() => _runtime.SetInstanceData(env, data, finalize_cb, finalize_hint));
return status;
}
+ // Instance data is an opaque native pointer, not a GCHandle, so only its address is formatted.
+ private static string FormatAddress(nint value) => value == 0 ? "null" : $"0x{value:X16}";
+
#endregion
#region Error handling
diff --git a/test/GCTests.cs b/test/GCTests.cs
index dc1b4f04..b6a0765f 100644
--- a/test/GCTests.cs
+++ b/test/GCTests.cs
@@ -44,7 +44,7 @@ public void GCHandles()
// - JSPropertyDescriptor: DotnetClass.toString
Assert.Equal(3 + 5, JSRuntimeContext.Current.GCHandleCount);
- using JSValueScope innerScope = new(JSValueScopeType.Callback);
+ using JSValueScope innerScope = JSValueScope.CreateRuntimeScope();
jsCreateInstanceFunction.CallAsStatic(dotnetClass);
// Two more handles should have been allocated by the JS create-instance function call.
@@ -93,7 +93,7 @@ public void GCObjects()
Assert.Equal(8, JSRuntimeContext.Current.GCHandleCount);
- using (JSValueScope innerScope = new(JSValueScopeType.Callback))
+ using (JSValueScope innerScope = JSValueScope.CreateRuntimeScope())
{
jsCreateInstanceFunction.CallAsStatic(dotnetClass);
}
diff --git a/test/JSReferenceTests.cs b/test/JSReferenceTests.cs
index fb2cbffd..bd2c024d 100644
--- a/test/JSReferenceTests.cs
+++ b/test/JSReferenceTests.cs
@@ -13,20 +13,28 @@ public class JSReferenceTests
{
private readonly MockJSRuntime _mockRuntime = new();
- private JSValueScope TestScope(JSValueScopeType scopeType)
- => TestScope(scopeType, new MockJSRuntime.SynchronizationContext());
+ private JSValueScope TestScope()
+ => TestScope(new MockJSRuntime.SynchronizationContext());
- private JSValueScope TestScope(
- JSValueScopeType scopeType, JSSynchronizationContext synchronizationContext)
+ private JSValueScope TestScope(JSSynchronizationContext synchronizationContext)
{
napi_env env = new(Environment.CurrentManagedThreadId);
- return new(scopeType, env, _mockRuntime, synchronizationContext);
+ var context = new JSRuntimeContext(env, _mockRuntime, synchronizationContext);
+ return JSValueScope.CreateRuntimeScope(env, context);
+ }
+
+ private static JSValueScope TestScope(MockJSRuntime runtime)
+ {
+ napi_env env = new(Environment.CurrentManagedThreadId);
+ var context = new JSRuntimeContext(
+ env, runtime, new MockJSRuntime.SynchronizationContext());
+ return JSValueScope.CreateRuntimeScope(env, context);
}
[Fact]
public void GetReferenceFromSameScope()
{
- using JSValueScope rootScope = TestScope(JSValueScopeType.Root);
+ using JSValueScope rootScope = TestScope();
JSValue value = JSValue.CreateObject();
JSReference reference = new(value);
@@ -36,10 +44,10 @@ public void GetReferenceFromSameScope()
[Fact]
public void GetReferenceFromParentScope()
{
- using JSValueScope rootScope = TestScope(JSValueScopeType.Root);
+ using JSValueScope rootScope = TestScope();
JSReference reference;
- using (JSValueScope handleScope = new(JSValueScopeType.Handle))
+ using (JSValueScope handleScope = JSValueScope.CreateHandleScope())
{
JSValue value = JSValue.CreateObject();
reference = new JSReference(value);
@@ -51,7 +59,7 @@ public void GetReferenceFromParentScope()
[Fact]
public void GetReferenceFromDifferentThread()
{
- using JSValueScope rootScope = TestScope(JSValueScopeType.Root);
+ using JSValueScope rootScope = TestScope();
JSValue value = JSValue.CreateObject();
JSReference reference = new(value);
@@ -66,7 +74,7 @@ public void GetReferenceFromDifferentThread()
[Fact]
public void GetReferenceFromDifferentRootScope()
{
- using JSValueScope rootScope1 = TestScope(JSValueScopeType.Root);
+ using JSValueScope rootScope1 = TestScope();
JSValue value = JSValue.CreateObject();
JSReference reference = new(value);
@@ -74,7 +82,8 @@ public void GetReferenceFromDifferentRootScope()
// Run in a new thread and establish another root scope there.
TestUtils.RunInThread(() =>
{
- using JSValueScope rootScope2 = TestScope(JSValueScopeType.Root);
+ // Separate runtime so rootScope2's env has its own instance data (one context per env).
+ using JSValueScope rootScope2 = JSReferenceTests.TestScope(new MockJSRuntime());
Assert.Throws(() => reference.GetValue());
}).Wait();
}
@@ -82,7 +91,7 @@ public void GetReferenceFromDifferentRootScope()
[Fact]
public void GetWeakReferenceUnavailable()
{
- using JSValueScope rootScope = TestScope(JSValueScopeType.Root);
+ using JSValueScope rootScope = TestScope();
JSValue value = JSValue.CreateObject();
var reference = new JSReference(value, isWeak: true);
@@ -94,7 +103,7 @@ public void GetWeakReferenceUnavailable()
[Fact]
public void TryGetWeakReferenceValue()
{
- using JSValueScope rootScope = TestScope(JSValueScopeType.Root);
+ using JSValueScope rootScope = TestScope();
JSValue value = JSValue.CreateObject();
JSReference reference = new(value);
@@ -105,7 +114,7 @@ public void TryGetWeakReferenceValue()
[Fact]
public void TryGetWeakReferenceUnavailable()
{
- using JSValueScope rootScope = TestScope(JSValueScopeType.Root);
+ using JSValueScope rootScope = TestScope();
JSValue value = JSValue.CreateObject();
var reference = new JSReference(value, isWeak: true);
@@ -114,103 +123,109 @@ public void TryGetWeakReferenceUnavailable()
Assert.False(reference.TryGetValue(out _));
}
- // A reference created from a NoContext scope (as the native host does) has a null runtime
- // context, so its finalizer takes the branch that previously asserted thread access. The GC
- // finalizer runs on a thread with no JS scope, so that assertion threw
- // JSInvalidThreadAccessException out of the finalizer, which terminates the process (the
- // reported worker-teardown crash). The finalizer must instead complete without throwing.
- [Fact]
- public void FinalizeNoContextReferenceFromDifferentThreadDoesNotThrow()
- {
- using JSValueScope noContextScope = TestScope(JSValueScopeType.NoContext);
-
- JSValue value = JSValue.CreateObject();
- var reference = new FinalizerTestReference(value);
-
- // Run on a new thread that has no current scope, simulating the GC finalizer thread.
- TestUtils.RunInThread(() => reference.SimulateFinalize()).Wait();
-
- Assert.True(reference.IsDisposed);
- }
-
- // A no-context reference finalized off the JS thread cannot be deleted inline (there is no
- // synchronization context to marshal the delete back to the JS thread). Instead of leaking the
- // napi_ref until the environment is destroyed, the finalizer defers the deletion, which is then
- // performed the next time a scope for the same environment is active on its JS thread.
+ // A reference with a runtime context posts its cleanup to the JS thread instead of deleting it
+ // inline. The finalizer must never throw when it runs on a thread with no current scope, and
+ // the posted delete must actually release the native reference once the JS thread pumps it.
[Fact]
- public void FinalizeNoContextReferenceDefersDeletionUntilNextScope()
+ public void FinalizeContextReferenceFromDifferentThreadDoesNotThrow()
{
- napi_env env = new(Environment.CurrentManagedThreadId);
- using JSValueScope noContextScope = new(
- JSValueScopeType.NoContext, env, _mockRuntime,
- new MockJSRuntime.SynchronizationContext());
+ var syncContext = new MockJSRuntime.RecordingSynchronizationContext();
+ using JSValueScope rootScope = TestScope(syncContext);
JSValue value = JSValue.CreateObject();
var reference = new FinalizerTestReference(value);
napi_ref handle = reference.Handle;
Assert.True(_mockRuntime.HasReference(handle));
- // Simulate the GC finalizer thread: no current scope, so the delete cannot run inline.
TestUtils.RunInThread(() => reference.SimulateFinalize()).Wait();
+
Assert.True(reference.IsDisposed);
- // The delete is deferred, not run on the finalizer thread, so the reference still exists.
+ // The delete is deferred to the JS thread, not run inline on the finalizer thread.
Assert.True(_mockRuntime.HasReference(handle));
+ Assert.Equal(1, syncContext.PendingCount);
- // Entering a scope for the same environment on the JS thread drains the deferred deletion.
- using (JSValueScope drainScope = new(JSValueScopeType.NoContext))
- {
- }
-
+ // Pumping the sync context runs the posted delete, releasing the native reference.
+ Assert.Equal(1, syncContext.RunPendingCallbacks());
Assert.False(_mockRuntime.HasReference(handle));
}
- // When the environment-scoped scope that owns a deferred no-context deletion is disposed, a
- // final drain runs so the napi_ref is released even if no further scope is entered.
- [Fact]
- public void DisposingScopeDrainsDeferredNoContextDeletion()
+ // Both release paths retain native-host references until env teardown when dispatch is unavailable.
+ [Theory]
+ [InlineData(false)]
+ [InlineData(true)]
+ public void InlineContextReferenceReleaseDoesNotDeleteOffThreadOrAfterDispose(bool dispose)
{
- napi_env env = new(Environment.CurrentManagedThreadId);
- napi_ref handle;
-
- var noContextScope = new JSValueScope(
- JSValueScopeType.NoContext, env, _mockRuntime,
- new MockJSRuntime.SynchronizationContext());
- try
+ JSRuntimeContext context;
+ FinalizerTestReference offThreadReference;
+ FinalizerTestReference afterDisposeReference;
+ napi_ref offThreadHandle;
+ napi_ref afterDisposeHandle;
+ using (JSValueScope scope = TestScope(new JSInlineSynchronizationContext()))
{
- JSValue value = JSValue.CreateObject();
- var reference = new FinalizerTestReference(value);
- handle = reference.Handle;
+ context = scope.RuntimeContext;
+ offThreadReference = new FinalizerTestReference(JSValue.CreateObject());
+ afterDisposeReference = new FinalizerTestReference(JSValue.CreateObject());
+ offThreadHandle = offThreadReference.Handle;
+ afterDisposeHandle = afterDisposeReference.Handle;
+
+ TestUtils.RunInThread(() => Release(offThreadReference)).Wait();
+ Assert.True(offThreadReference.IsDisposed);
+ Assert.True(_mockRuntime.HasReference(offThreadHandle));
+ }
+
+ Assert.True(_mockRuntime.HasReference(offThreadHandle));
+ context.Dispose();
+ TestUtils.RunInThread(() => Release(afterDisposeReference)).Wait();
+ Assert.True(afterDisposeReference.IsDisposed);
+ Assert.True(_mockRuntime.HasReference(afterDisposeHandle));
+ Assert.True(_mockRuntime.HasReference(offThreadHandle));
- TestUtils.RunInThread(() => reference.SimulateFinalize()).Wait();
- Assert.True(_mockRuntime.HasReference(handle));
+ void Release(FinalizerTestReference reference)
+ {
+ if (dispose) reference.Dispose();
+ else reference.SimulateFinalize();
}
- finally
+ }
+
+ // A torn-down context's synchronization context skips posted work, so Run must fail up front
+ // instead of silently doing nothing or returning a default value.
+ [Fact]
+ public void RunAfterContextDisposedThrows()
+ {
+ JSRuntimeContext context;
+ JSReference reference;
+ using (JSValueScope scope = TestScope(new JSInlineSynchronizationContext()))
{
- // Disposing the environment-scoped scope performs the final drain.
- noContextScope.Dispose();
+ context = scope.RuntimeContext;
+ reference = new JSReference(JSValue.CreateObject());
}
- Assert.False(_mockRuntime.HasReference(handle));
+ context.Dispose();
+
+ Assert.Throws(() => reference.Run((value) => { }));
+ Assert.Throws(() => reference.Run((value) => 1));
}
- // inline. The finalizer must never throw when it runs on a thread with no current scope, and
- // the posted delete must actually release the native reference once the JS thread pumps it.
+
+ // Explicit Dispose() from a thread with no current scope must not throw. The pre-refactor
+ // no-context path asserted thread access and threw JSInvalidThreadAccessException here; every
+ // reference is now context-backed, so the delete is posted to the JS thread instead.
[Fact]
- public void FinalizeContextReferenceFromDifferentThreadDoesNotThrow()
+ public void DisposeReferenceFromDifferentThreadPostsDelete()
{
var syncContext = new MockJSRuntime.RecordingSynchronizationContext();
- using JSValueScope rootScope = TestScope(JSValueScopeType.Root, syncContext);
+ using JSValueScope rootScope = TestScope(syncContext);
JSValue value = JSValue.CreateObject();
- var reference = new FinalizerTestReference(value);
+ var reference = new JSReference(value);
napi_ref handle = reference.Handle;
Assert.True(_mockRuntime.HasReference(handle));
- TestUtils.RunInThread(() => reference.SimulateFinalize()).Wait();
+ TestUtils.RunInThread(() => reference.Dispose()).Wait();
Assert.True(reference.IsDisposed);
- // The delete is deferred to the JS thread, not run inline on the finalizer thread.
+ // The delete is deferred to the JS thread, not run inline on the disposing thread.
Assert.True(_mockRuntime.HasReference(handle));
Assert.Equal(1, syncContext.PendingCount);
@@ -219,22 +234,6 @@ public void FinalizeContextReferenceFromDifferentThreadDoesNotThrow()
Assert.False(_mockRuntime.HasReference(handle));
}
- // Explicit disposal (disposing: true) preserves the documented behavior of asserting thread
- // access for a no-context reference; only the finalizer path is made non-throwing.
- [Fact]
- public void DisposeNoContextReferenceFromDifferentThreadThrows()
- {
- using JSValueScope noContextScope = TestScope(JSValueScopeType.NoContext);
-
- JSValue value = JSValue.CreateObject();
- JSReference reference = new(value);
-
- TestUtils.RunInThread(() =>
- {
- Assert.Throws(() => reference.Dispose());
- }).Wait();
- }
-
// The finalizer invokes the virtual Dispose(bool), so a derived override can throw before or
// after the base implementation runs. ~JSReference() must catch at its entry point, otherwise
// the exception escapes the finalizer and terminates the process. This drives real GC
@@ -243,7 +242,7 @@ public void DisposeNoContextReferenceFromDifferentThreadThrows()
[Fact]
public void FinalizerSwallowsExceptionsFromDerivedDisposeOverride()
{
- using JSValueScope rootScope = TestScope(JSValueScopeType.Root);
+ using JSValueScope rootScope = TestScope();
CreateAndAbandonThrowingReference();
diff --git a/test/JSValueScopeTests.cs b/test/JSValueScopeTests.cs
index 201d2608..50b1da22 100644
--- a/test/JSValueScopeTests.cs
+++ b/test/JSValueScopeTests.cs
@@ -2,6 +2,8 @@
// Licensed under the MIT License.
using System;
+using System.Runtime.CompilerServices;
+using Microsoft.JavaScript.NodeApi.Interop;
using Xunit;
using static Microsoft.JavaScript.NodeApi.Runtime.JSRuntime;
@@ -16,272 +18,178 @@ public class JSValueScopeTests
{
private readonly MockJSRuntime _mockRuntime = new();
- private JSValueScope TestScope(JSValueScopeType scopeType)
- {
- napi_env env = new(Environment.CurrentManagedThreadId);
- return new(scopeType, env, _mockRuntime, new MockJSRuntime.SynchronizationContext());
- }
+ private JSValueScope TestRuntimeScope() => JSValueScopeTests.TestRuntimeScope(_mockRuntime);
- [Fact]
- public void CreateNoContextScope()
+ private static JSValueScope TestRuntimeScope(MockJSRuntime runtime)
{
- using JSValueScope noContextScope = TestScope(JSValueScopeType.NoContext);
- Assert.Null(noContextScope.RuntimeContext);
- Assert.Equal(JSValueScopeType.NoContext, JSValueScope.Current.ScopeType);
+ napi_env env = new(Environment.CurrentManagedThreadId);
+ var context = new JSRuntimeContext(
+ env, runtime, new MockJSRuntime.SynchronizationContext());
+ return JSValueScope.CreateRuntimeScope(env, context);
}
[Fact]
- public void CreateRootScope()
+ public void CreateRuntimeScope()
{
- using JSValueScope rootScope = TestScope(JSValueScopeType.Root);
- Assert.NotNull(rootScope.RuntimeContext);
- Assert.Equal(JSValueScopeType.Root, JSValueScope.Current.ScopeType);
+ using JSValueScope runtimeScope = TestRuntimeScope();
+ Assert.NotNull(runtimeScope.RuntimeContext);
+ Assert.Equal(JSValueScopeType.RuntimeContext, JSValueScope.Current.ScopeType);
}
[Fact]
- public void CreateModuleScopeWithinNoContextScope()
+ public void CreateNestedRuntimeScope()
{
- using JSValueScope noContextScope = TestScope(JSValueScopeType.NoContext);
+ using JSValueScope runtimeScope = TestRuntimeScope();
- using (JSValueScope moduleScope = TestScope(JSValueScopeType.Module))
+ using (JSValueScope nestedScope = JSValueScope.CreateRuntimeScope())
{
- Assert.NotNull(moduleScope.RuntimeContext);
- Assert.Equal(JSValueScopeType.Module, JSValueScope.Current.ScopeType);
+ Assert.Same(runtimeScope.RuntimeContext, nestedScope.RuntimeContext);
+ Assert.Equal(JSValueScopeType.RuntimeContext, JSValueScope.Current.ScopeType);
}
- Assert.Equal(JSValueScopeType.NoContext, JSValueScope.Current.ScopeType);
+ Assert.Equal(JSValueScopeType.RuntimeContext, JSValueScope.Current.ScopeType);
}
[Fact]
- public void CreateModuleScopeWithinRootScope()
+ public void CreateHandleScopeWithinRuntimeScope()
{
- using JSValueScope rootScope = TestScope(JSValueScopeType.Root);
+ using JSValueScope runtimeScope = TestRuntimeScope();
- using (JSValueScope moduleScope = new(JSValueScopeType.Module))
+ using (JSValueScope handleScope = JSValueScope.CreateHandleScope())
{
- Assert.NotNull(moduleScope.RuntimeContext);
- Assert.Equal(JSValueScopeType.Module, JSValueScope.Current.ScopeType);
+ Assert.Equal(JSValueScopeType.Handle, JSValueScope.Current.ScopeType);
}
- Assert.Equal(JSValueScopeType.Root, JSValueScope.Current.ScopeType);
- }
-
- [Fact]
- public void CreateModuleScopeWithoutRoot()
- {
- using JSValueScope moduleScope = TestScope(JSValueScopeType.Module);
- Assert.NotNull(moduleScope.RuntimeContext);
- Assert.Equal(JSValueScopeType.Module, JSValueScope.Current.ScopeType);
+ Assert.Equal(JSValueScopeType.RuntimeContext, JSValueScope.Current.ScopeType);
}
[Fact]
- public void CreateCallbackScope()
+ public void CreateHandleScopeWithinNestedRuntimeScope()
{
- using JSValueScope moduleScope = TestScope(JSValueScopeType.Module);
+ using JSValueScope runtimeScope = TestRuntimeScope();
- using (JSValueScope callbackScope = new(JSValueScopeType.Callback))
+ using (JSValueScope nestedScope = JSValueScope.CreateRuntimeScope())
{
- Assert.NotNull(moduleScope.RuntimeContext);
- Assert.Equal(JSValueScopeType.Callback, JSValueScope.Current.ScopeType);
+ using (JSValueScope handleScope = JSValueScope.CreateHandleScope())
+ {
+ Assert.Equal(JSValueScopeType.Handle, JSValueScope.Current.ScopeType);
+ }
+
+ Assert.Equal(JSValueScopeType.RuntimeContext, JSValueScope.Current.ScopeType);
}
- Assert.Equal(JSValueScopeType.Module, JSValueScope.Current.ScopeType);
+ Assert.Equal(JSValueScopeType.RuntimeContext, JSValueScope.Current.ScopeType);
}
[Fact]
- public void CreateHandleScopeWithinRoot()
+ public void CreateEscapableScopeWithinRuntimeScope()
{
- using JSValueScope rootScope = TestScope(JSValueScopeType.Root);
+ using JSValueScope runtimeScope = TestRuntimeScope();
- using (JSValueScope handleScope = new(JSValueScopeType.Handle))
+ using (JSValueScope escapableScope = JSValueScope.CreateEscapableScope())
{
- Assert.Equal(JSValueScopeType.Handle, JSValueScope.Current.ScopeType);
+ Assert.Equal(JSValueScopeType.Escapable, JSValueScope.Current.ScopeType);
}
- Assert.Equal(JSValueScopeType.Root, JSValueScope.Current.ScopeType);
+ Assert.Equal(JSValueScopeType.RuntimeContext, JSValueScope.Current.ScopeType);
}
[Fact]
- public void CreateHandleScopeWithinModule()
+ public void HandleScopeRequiresParentScope()
{
- using JSValueScope moduleScope = TestScope(JSValueScopeType.Module);
+ Assert.Throws(
+ () => JSValueScope.CreateHandleScope());
+ Assert.Throws(
+ () => JSValueScope.CreateEscapableScope());
+ }
- using (JSValueScope handleScope = new(JSValueScopeType.Handle))
- {
- Assert.Equal(JSValueScopeType.Handle, JSValueScope.Current.ScopeType);
- }
+ private sealed class DisposableModule : IDisposable
+ {
+ public int DisposeCount { get; private set; }
- Assert.Equal(JSValueScopeType.Module, JSValueScope.Current.ScopeType);
+ public void Dispose() => DisposeCount++;
}
[Fact]
- public void CreateHandleScopeWithinCallback()
+ public void DisposableModulesShareContextAndAreDisposedOnceAtTeardown()
{
- using JSValueScope moduleScope = TestScope(JSValueScopeType.Module);
+ var moduleA = new DisposableModule();
+ var moduleB = new DisposableModule();
+
+ napi_env env = new(Environment.CurrentManagedThreadId);
+ var context = new JSRuntimeContext(
+ env, _mockRuntime, new MockJSRuntime.SynchronizationContext());
- using (JSValueScope callbackScope = new(JSValueScopeType.Callback))
+ using (JSValueScope.CreateRuntimeScope(env, context))
{
- using (JSValueScope handleScope = new(JSValueScopeType.Handle))
+ // Two generated modules loaded into one managed host share this context; each opens a
+ // module-boundary scope and exports its instance.
+ using (JSValueScope.CreateModuleScope(env))
{
- Assert.Equal(JSValueScopeType.Handle, JSValueScope.Current.ScopeType);
+ new JSModuleBuilder().ExportModule(
+ moduleA, (JSObject)JSValue.CreateObject());
}
- Assert.Equal(JSValueScopeType.Callback, JSValueScope.Current.ScopeType);
- }
-
- Assert.Equal(JSValueScopeType.Module, JSValueScope.Current.ScopeType);
- }
-
- [Fact]
- public void CreateEscapableScopeWithinCallback()
- {
- using JSValueScope moduleScope = TestScope(JSValueScopeType.Module);
-
- using (JSValueScope callbackScope = new(JSValueScopeType.Callback))
- {
- using (JSValueScope escapableScope = new(JSValueScopeType.Escapable))
+ using (JSValueScope.CreateModuleScope(env))
{
- Assert.Equal(JSValueScopeType.Escapable, JSValueScope.Current.ScopeType);
+ new JSModuleBuilder().ExportModule(
+ moduleB, (JSObject)JSValue.CreateObject());
}
- Assert.Equal(JSValueScopeType.Callback, JSValueScope.Current.ScopeType);
+ // Loading the second module must not dispose the first.
+ Assert.Equal(0, moduleA.DisposeCount);
+ Assert.Equal(0, moduleB.DisposeCount);
}
- Assert.Equal(JSValueScopeType.Module, JSValueScope.Current.ScopeType);
- }
-
- [Fact]
- public void InvalidNoContextScopeNesting()
- {
- using JSValueScope rootScope = TestScope(JSValueScopeType.Root);
- Assert.Throws(() =>
- {
- using JSValueScope noContextScope = new(JSValueScopeType.NoContext);
- });
- Assert.Equal(JSValueScopeType.Root, JSValueScope.Current.ScopeType);
-
- using JSValueScope moduleScope = new(JSValueScopeType.Module);
- Assert.Throws(() =>
- {
- using JSValueScope noContextScope = new(JSValueScopeType.NoContext);
- });
- Assert.Equal(JSValueScopeType.Module, JSValueScope.Current.ScopeType);
-
- using JSValueScope callbackScope = new(JSValueScopeType.Callback);
- Assert.Throws(() =>
- {
- using JSValueScope noContextScope = new(JSValueScopeType.NoContext);
- });
- Assert.Equal(JSValueScopeType.Callback, JSValueScope.Current.ScopeType);
-
- using JSValueScope handleScope = new(JSValueScopeType.Handle);
- Assert.Throws(() =>
- {
- using JSValueScope noContextScope = new(JSValueScopeType.NoContext);
- });
- Assert.Equal(JSValueScopeType.Handle, JSValueScope.Current.ScopeType);
+ context.Dispose();
- using JSValueScope escapableScope = new(JSValueScopeType.Escapable);
- Assert.Throws(() =>
- {
- using JSValueScope noContextScope = new(JSValueScopeType.NoContext);
- });
- Assert.Equal(JSValueScopeType.Escapable, JSValueScope.Current.ScopeType);
+ // Each module instance is disposed exactly once at env teardown.
+ Assert.Equal(1, moduleA.DisposeCount);
+ Assert.Equal(1, moduleB.DisposeCount);
}
- [Fact]
- public void InvalidRootContextScopeNesting()
+ private sealed class EqualDisposable : IDisposable
{
- using JSValueScope noContextScope = TestScope(JSValueScopeType.NoContext);
- Assert.Throws(() =>
- {
- using JSValueScope rootScope = new(JSValueScopeType.Root);
- });
- Assert.Equal(JSValueScopeType.NoContext, JSValueScope.Current.ScopeType);
+ public int DisposeCount { get; private set; }
- using JSValueScope moduleScope = TestScope(JSValueScopeType.Module);
- Assert.Throws(() =>
- {
- using JSValueScope rootScope = new(JSValueScopeType.Root);
- });
- Assert.Equal(JSValueScopeType.Module, JSValueScope.Current.ScopeType);
+ public void Dispose() => DisposeCount++;
- using JSValueScope callbackScope = new(JSValueScopeType.Callback);
- Assert.Throws(() =>
- {
- using JSValueScope rootScope = new(JSValueScopeType.Root);
- });
- Assert.Equal(JSValueScopeType.Callback, JSValueScope.Current.ScopeType);
-
- using JSValueScope handleScope = new(JSValueScopeType.Handle);
- Assert.Throws(() =>
- {
- using JSValueScope rootScope = new(JSValueScopeType.Root);
- });
- Assert.Equal(JSValueScopeType.Handle, JSValueScope.Current.ScopeType);
+ // All instances compare equal, to prove module disposables dedupe by identity, not Equals.
+ public override bool Equals(object? obj) => obj is EqualDisposable;
- using JSValueScope escapableScope = new(JSValueScopeType.Escapable);
- Assert.Throws(() =>
- {
- using JSValueScope rootScope = new(JSValueScopeType.Root);
- });
- Assert.Equal(JSValueScopeType.Escapable, JSValueScope.Current.ScopeType);
+ public override int GetHashCode() => 0;
}
[Fact]
- public void InvalidModuleContextScopeNesting()
+ public void ModuleDisposablesAreDedupedByIdentityNotEquality()
{
- using JSValueScope moduleScope = TestScope(JSValueScopeType.Module);
- using JSValueScope callbackScope = new(JSValueScopeType.Callback);
- Assert.Throws(() =>
- {
- using JSValueScope nestedModuleScope = new(JSValueScopeType.Module);
- });
- Assert.Equal(JSValueScopeType.Callback, JSValueScope.Current.ScopeType);
-
- using JSValueScope handleScope = new(JSValueScopeType.Handle);
- Assert.Throws(() =>
- {
- using JSValueScope nestedModuleScope = new(JSValueScopeType.Module);
- });
- Assert.Equal(JSValueScopeType.Handle, JSValueScope.Current.ScopeType);
+ var moduleA = new EqualDisposable();
+ var moduleB = new EqualDisposable();
+ Assert.True(moduleA.Equals(moduleB));
- using JSValueScope escapableScope = new(JSValueScopeType.Escapable);
- Assert.Throws(() =>
- {
- using JSValueScope nestedModuleScope = new(JSValueScopeType.Module);
- });
- Assert.Equal(JSValueScopeType.Escapable, JSValueScope.Current.ScopeType);
- }
+ napi_env env = new(Environment.CurrentManagedThreadId);
+ var context = new JSRuntimeContext(
+ env, _mockRuntime, new MockJSRuntime.SynchronizationContext());
- [Fact]
- public void InvalidCallbackContextScopeNesting()
- {
- using JSValueScope rootScope = TestScope(JSValueScopeType.Root);
+ context.AddModuleDisposable(moduleA);
+ context.AddModuleDisposable(moduleB);
+ context.AddModuleDisposable(moduleA); // Re-adding the same instance is a no-op.
- using JSValueScope handleScope = new(JSValueScopeType.Handle);
- Assert.Throws(() =>
- {
- using JSValueScope callbackScope = new(JSValueScopeType.Callback);
- });
- Assert.Equal(JSValueScopeType.Handle, JSValueScope.Current.ScopeType);
+ context.Dispose();
- using JSValueScope escapableScope = new(JSValueScopeType.Escapable);
- Assert.Throws(() =>
- {
- using JSValueScope callbackScope = new(JSValueScopeType.Callback);
- });
- Assert.Equal(JSValueScopeType.Escapable, JSValueScope.Current.ScopeType);
+ // Both distinct instances are disposed once, despite comparing equal.
+ Assert.Equal(1, moduleA.DisposeCount);
+ Assert.Equal(1, moduleB.DisposeCount);
}
[Fact]
public void AccessValueFromClosedScope()
{
- using JSValueScope rootScope = TestScope(JSValueScopeType.Root);
+ using JSValueScope rootScope = TestRuntimeScope();
JSValueScope handleScope;
JSValue objectValue;
- using (handleScope = new(JSValueScopeType.Handle))
+ using (handleScope = JSValueScope.CreateHandleScope())
{
objectValue = JSValue.CreateObject();
Assert.True(objectValue.IsObject());
@@ -296,13 +204,13 @@ public void AccessValueFromClosedScope()
[Fact]
public void AccessPropertyKeyFromClosedScope()
{
- using JSValueScope rootScope = TestScope(JSValueScopeType.Root);
+ using JSValueScope rootScope = TestRuntimeScope();
JSValue objectValue = JSValue.CreateObject();
JSValue propertyKey;
JSValueScope handleScope;
- using (handleScope = new(JSValueScopeType.Handle))
+ using (handleScope = JSValueScope.CreateHandleScope())
{
propertyKey = "test";
Assert.True(propertyKey.IsString());
@@ -321,7 +229,7 @@ public void AccessPropertyKeyFromClosedScope()
[Fact]
public void CreateValueFromDifferentThread()
{
- using JSValueScope rootScope = TestScope(JSValueScopeType.Root);
+ using JSValueScope rootScope = TestRuntimeScope();
// Run in a new thread which will not have any current scope.
TestUtils.RunInThread(() =>
@@ -337,7 +245,7 @@ public void CreateValueFromDifferentThread()
[Fact]
public void AccessValueFromDifferentThread()
{
- using JSValueScope rootScope = TestScope(JSValueScopeType.Root);
+ using JSValueScope rootScope = TestRuntimeScope();
JSValue objectValue = JSValue.CreateObject();
// Run in a new thread which will not have any current scope.
@@ -354,18 +262,384 @@ public void AccessValueFromDifferentThread()
[Fact]
public void AccessValueFromDifferentRootScope()
{
- using JSValueScope rootScope1 = TestScope(JSValueScopeType.Root);
+ using JSValueScope rootScope1 = TestRuntimeScope();
JSValue objectValue = JSValue.CreateObject();
// Run in a new thread and establish another root scope there.
TestUtils.RunInThread(() =>
{
- using JSValueScope rootScope2 = TestScope(JSValueScopeType.Root);
- Assert.Equal(JSValueScopeType.Root, JSValueScope.Current.ScopeType);
+ // Separate runtime so rootScope2's env has its own instance data (one context per env).
+ using JSValueScope rootScope2 = JSValueScopeTests.TestRuntimeScope(new MockJSRuntime());
+ Assert.Equal(JSValueScopeType.RuntimeContext, JSValueScope.Current.ScopeType);
JSInvalidThreadAccessException ex = Assert.Throws(
() => objectValue.IsObject());
Assert.Equal(rootScope2, ex.CurrentScope);
Assert.Equal(rootScope1, ex.TargetScope);
}).Wait();
}
+
+ [Fact]
+ public void EnterRuntimeContextFromDifferentThreadThrows()
+ {
+ napi_env env = new(Environment.CurrentManagedThreadId);
+ var context = new JSRuntimeContext(
+ env, _mockRuntime, new MockJSRuntime.SynchronizationContext());
+
+ // A runtime context may be entered only on the thread that created it.
+ TestUtils.RunInThread(() =>
+ {
+ Assert.Throws(
+ () => JSValueScope.CreateRuntimeScope(env, context));
+ }).Wait();
+ }
+
+ [Fact]
+ public void EnterDisposedRuntimeContextThrows()
+ {
+ napi_env env = new(Environment.CurrentManagedThreadId);
+ var context = new JSRuntimeContext(
+ env, _mockRuntime, new MockJSRuntime.SynchronizationContext());
+ context.Dispose();
+
+ // A disposed context's environment is torn down, so a scope must not adopt it.
+ Assert.Throws(
+ () => JSValueScope.CreateRuntimeScope(env, context));
+ }
+
+ [Fact]
+ public void DisposeRuntimeContextFromDifferentThreadThrows()
+ {
+ napi_env env = new(Environment.CurrentManagedThreadId);
+ var context = new JSRuntimeContext(
+ env, _mockRuntime, new MockJSRuntime.SynchronizationContext());
+
+ // A runtime context may be disposed only on the thread that created it, because teardown
+ // calls thread-affine napi.
+ TestUtils.RunInThread(() =>
+ {
+ Assert.Throws(() => context.Dispose());
+ }).Wait();
+
+ // The failed off-thread attempt left the context live, so disposing on the owning thread
+ // still succeeds.
+ context.Dispose();
+ }
+
+ [Fact]
+ public void SynchronizationContextRejectsLazyCreateWhenContextNotCurrent()
+ {
+ napi_env env = new(Environment.CurrentManagedThreadId);
+
+ // Separate runtimes so each context has its own instance data (an env is associated with a
+ // single context), letting contextB be current while contextA is not.
+ var contextA = new JSRuntimeContext(env, new MockJSRuntime()); // no sync context -> lazy
+ var contextB = new JSRuntimeContext(
+ env, new MockJSRuntime(), new MockJSRuntime.SynchronizationContext());
+
+ using (JSValueScope.CreateRuntimeScope(env, contextB))
+ {
+ // contextB is current, so lazily creating contextA's sync context (which would capture
+ // the current scope's environment) must be rejected.
+ Assert.Throws(() => contextA.SynchronizationContext);
+ }
+
+ contextA.Dispose();
+
+ // After disposal, lazy creation is rejected too.
+ Assert.Throws(() => contextA.SynchronizationContext);
+ contextB.Dispose();
+ }
+
+ [Fact]
+ public void DisposeScopeWhileNestedScopeOpenThrows()
+ {
+ using JSValueScope runtimeScope = TestRuntimeScope();
+ JSValueScope handleScope = JSValueScope.CreateHandleScope();
+
+ // A scope cannot be disposed while a scope created within it is still open (LIFO order).
+ Assert.Throws(() => runtimeScope.Dispose());
+
+ // Disposing in the correct reverse order succeeds.
+ handleScope.Dispose();
+ }
+
+ [Fact]
+ public void DisposeScopeFromDifferentThreadThrows()
+ {
+ using JSValueScope runtimeScope = TestRuntimeScope();
+
+ // A scope must be disposed on the thread that created it, not another thread.
+ TestUtils.RunInThread(() =>
+ {
+ Assert.Throws(() => runtimeScope.Dispose());
+ }).Wait();
+ }
+
+ private sealed class ThrowOnceOnScopeCloseRuntime : MockJSRuntime
+ {
+ private bool _throwOnClose = true;
+
+ private void ThrowOnce()
+ {
+ if (_throwOnClose)
+ {
+ _throwOnClose = false;
+ throw new InvalidOperationException("scope close failure");
+ }
+ }
+
+ public override napi_status CloseHandleScope(
+ napi_env env, napi_handle_scope scope)
+ {
+ ThrowOnce();
+ return base.CloseHandleScope(env, scope);
+ }
+
+ public override napi_status CloseEscapableHandleScope(
+ napi_env env, napi_escapable_handle_scope scope)
+ {
+ ThrowOnce();
+ return base.CloseEscapableHandleScope(env, scope);
+ }
+ }
+
+ [Theory]
+ [InlineData(false)]
+ [InlineData(true)]
+ public void FailedScopeCloseCanBeRetried(bool escapable)
+ {
+ var runtime = new ThrowOnceOnScopeCloseRuntime();
+ using JSValueScope runtimeScope = TestRuntimeScope(runtime);
+ JSValueScope scope = escapable
+ ? JSValueScope.CreateEscapableScope()
+ : JSValueScope.CreateHandleScope();
+
+ Assert.Throws(() => scope.Dispose());
+ Assert.False(scope.IsDisposed);
+ Assert.Same(scope, JSValueScope.Current);
+
+ scope.Dispose();
+ Assert.True(scope.IsDisposed);
+ Assert.Same(runtimeScope, JSValueScope.Current);
+ }
+
+ [Fact]
+ public void DisposeRuntimeContextWhenIdleDefersUntilOutermostScopeCloses()
+ {
+ napi_env env = new(Environment.CurrentManagedThreadId);
+ var context = new JSRuntimeContext(
+ env, _mockRuntime, new MockJSRuntime.SynchronizationContext());
+
+ using (JSValueScope outerScope = JSValueScope.CreateRuntimeScope(env, context))
+ {
+ using (JSValueScope handleScope = JSValueScope.CreateHandleScope())
+ {
+ // A disposal request while scopes are open must be deferred: disposing now would
+ // leave the handle scope to close on a disposed context as it unwinds.
+ JSValueScope.DisposeRuntimeContextWhenIdle(context);
+ Assert.False(context.IsDisposed);
+ }
+
+ // The inner scope closed, but the outer scope keeps the context alive.
+ Assert.False(context.IsDisposed);
+ }
+
+ // The outermost scope closed, so the context is disposed once no scope remains open.
+ Assert.True(context.IsDisposed);
+ }
+
+ [Fact]
+ public void DisposeRuntimeContextWhenIdleDisposesImmediatelyWithNoScope()
+ {
+ napi_env env = new(Environment.CurrentManagedThreadId);
+ var context = new JSRuntimeContext(
+ env, _mockRuntime, new MockJSRuntime.SynchronizationContext());
+
+ // With no value scope open, the request is applied immediately.
+ JSValueScope.DisposeRuntimeContextWhenIdle(context);
+ Assert.True(context.IsDisposed);
+ }
+
+ [Fact]
+ public void NestedRuntimeScopeWithDifferentContextThrows()
+ {
+ napi_env env = new(Environment.CurrentManagedThreadId);
+
+ // Separate runtimes so each context owns its own instance data.
+ var contextA = new JSRuntimeContext(
+ env, new MockJSRuntime(), new MockJSRuntime.SynchronizationContext());
+ var contextB = new JSRuntimeContext(
+ env, new MockJSRuntime(), new MockJSRuntime.SynchronizationContext());
+
+ using (JSValueScope.CreateRuntimeScope(env, contextA))
+ {
+ // Every scope on a thread's stack shares one runtime context, so nesting a scope for a
+ // different context is rejected.
+ Assert.Throws(
+ () => JSValueScope.CreateRuntimeScope(env, contextB));
+ }
+
+ contextA.Dispose();
+ contextB.Dispose();
+ }
+
+ [Fact]
+ public void RegisteringSecondContextOnEnvIsRejected()
+ {
+ napi_env env = new(Environment.CurrentManagedThreadId);
+ var context = new JSRuntimeContext(
+ env, _mockRuntime, new MockJSRuntime.SynchronizationContext());
+
+ // An env is associated with a runtime context exactly once.
+ Assert.Throws(
+ () => new JSRuntimeContext(env, _mockRuntime, new MockJSRuntime.SynchronizationContext()));
+
+ context.Dispose();
+
+ // Even after disposal the env cannot be re-associated (the slot is tombstoned).
+ Assert.Throws(
+ () => new JSRuntimeContext(env, _mockRuntime, new MockJSRuntime.SynchronizationContext()));
+ }
+
+ [Fact]
+ public void ContextRootReleasedWhenTeardownStepThrows()
+ {
+ napi_env env = new(Environment.CurrentManagedThreadId);
+ var context = new JSRuntimeContext(env, _mockRuntime, new ThrowingSynchronizationContext());
+ var module = new DisposableModule();
+ context.AddModuleDisposable(module);
+
+ // The sync context's Dispose throws, but every later teardown phase still runs: the module
+ // disposable is disposed and the context root is released. The failure surfaces after cleanup.
+ Assert.Throws(() => context.Dispose());
+ Assert.Equal(1, module.DisposeCount);
+ Assert.Null(JSRuntimeContext.FromEnv(env));
+ }
+
+ private sealed class ThrowingSynchronizationContext : JSSynchronizationContext
+ {
+ public override void Dispose() => throw new InvalidOperationException("teardown failure");
+ public override void OpenAsyncScope() { }
+ public override void CloseAsyncScope() { }
+ }
+
+ // The module instance is captured through a shared holder: descriptors take the holder during
+ // initialization (before the instance exists) and observe the instance once dispatch assigns it.
+ // Nested handle/escapable scopes inherit the same holder, so Current.Module round-trips through it.
+ [Fact]
+ public void ModuleInstanceRoundTripsThroughSharedHolder()
+ {
+ using JSValueScope runtimeScope = TestRuntimeScope();
+
+ // The runtime scope mints a holder; the module instance is not assigned yet.
+ StrongBox holder = JSValueScope.Current.ModuleHolder!;
+ Assert.NotNull(holder);
+ Assert.Null(JSValueScope.Current.Module);
+
+ object moduleInstance = new();
+ using (JSValueScope handleScope = JSValueScope.CreateHandleScope())
+ {
+ // Inner scopes inherit the same holder instance.
+ Assert.Same(holder, JSValueScope.Current.ModuleHolder);
+
+ // Assigning through the shared holder (as dispatch does) is visible as Current.Module.
+ holder.Value = moduleInstance;
+ Assert.Same(moduleInstance, JSValueScope.Current.Module);
+ }
+
+ // The instance remains visible in the parent scope after the nested scope closes.
+ Assert.Same(moduleInstance, JSValueScope.Current.Module);
+ }
+
+ // An escapable scope promotes one value to its parent so the value stays usable after the inner
+ // scope closes, while a value that was not escaped becomes invalid once the scope is disposed.
+ [Fact]
+ public void EscapableScopeEscapesValue()
+ {
+ using JSValueScope rootScope = TestRuntimeScope();
+
+ JSValue escaped;
+ JSValue notEscaped;
+ JSValueScope escapableScope;
+ using (escapableScope = JSValueScope.CreateEscapableScope())
+ {
+ notEscaped = JSValue.CreateObject();
+ escaped = escapableScope.Escape(JSValue.CreateObject());
+
+ Assert.True(escaped.IsObject());
+ Assert.True(notEscaped.IsObject());
+ }
+
+ // The escaped value was promoted to the parent scope, so it remains usable.
+ Assert.True(escapableScope.IsDisposed);
+ Assert.True(escaped.IsObject());
+
+ // The value that was not escaped belonged to the now-closed scope.
+ JSValueScopeClosedException ex = Assert.Throws(
+ () => notEscaped.IsObject());
+ Assert.Equal(escapableScope, ex.Scope);
+ }
+
+ // With no explicit context and no parent scope, CreateRuntimeScope recovers the context from the
+ // env instance data (JSRuntimeContext.FromEnv) -- the path the dynamic module entry point relies
+ // on to resolve the context when no scope is on the thread yet.
+ [Fact]
+ public void CreateRuntimeScopeResolvesContextFromEnv()
+ {
+ napi_env env = new(Environment.CurrentManagedThreadId);
+ var context = new JSRuntimeContext(
+ env, _mockRuntime, new MockJSRuntime.SynchronizationContext());
+
+ // The context registered itself in the env instance data, so FromEnv resolves it.
+ Assert.Same(context, JSRuntimeContext.FromEnv(env));
+
+ using JSValueScope runtimeScope = JSValueScope.CreateRuntimeScope(env);
+ Assert.Same(context, runtimeScope.RuntimeContext);
+ Assert.Same(context, JSValueScope.Current.RuntimeContext);
+ }
+
+ // JSRuntimeContext.Create is the public factory used by AOT entry points and embedders. It uses
+ // the provided runtime, and a runtime scope over the context resolves it as the current context.
+ [Fact]
+ public void CreateRuntimeContextFactoryUsesProvidedRuntime()
+ {
+ napi_env env = new(Environment.CurrentManagedThreadId);
+ JSRuntimeContext context = JSRuntimeContext.Create(
+ env, _mockRuntime, new MockJSRuntime.SynchronizationContext());
+
+ Assert.Same(_mockRuntime, context.Runtime);
+ Assert.False(context.IsDisposed);
+
+ using JSValueScope runtimeScope = JSValueScope.CreateRuntimeScope(env, context);
+ Assert.Same(context, JSValueScope.Current.RuntimeContext);
+ Assert.Same(context, JSRuntimeContext.Current);
+ }
+
+ [Fact]
+ public void RuntimeContextDisposalIsInfrastructureOnly()
+ {
+ Assert.False(typeof(IDisposable).IsAssignableFrom(typeof(JSRuntimeContext)));
+ Assert.Null(typeof(JSRuntimeContext).GetMethod(nameof(IDisposable.Dispose)));
+ }
+
+ // A runtime-context scope installs the context's synchronization context as the thread's current
+ // one for its lifetime (so await continuations marshal back to the JS thread) and restores the
+ // previously-current one when disposed.
+ [Fact]
+ public void RuntimeScopeInstallsAndRestoresSynchronizationContext()
+ {
+ System.Threading.SynchronizationContext? previous =
+ System.Threading.SynchronizationContext.Current;
+
+ napi_env env = new(Environment.CurrentManagedThreadId);
+ var syncContext = new MockJSRuntime.SynchronizationContext();
+ var context = new JSRuntimeContext(env, _mockRuntime, syncContext);
+
+ using (JSValueScope runtimeScope = JSValueScope.CreateRuntimeScope(env, context))
+ {
+ Assert.Same(syncContext, System.Threading.SynchronizationContext.Current);
+ }
+
+ Assert.Same(previous, System.Threading.SynchronizationContext.Current);
+ }
}
diff --git a/test/MockJSRuntime.cs b/test/MockJSRuntime.cs
index 39a84a9f..b7df9bee 100644
--- a/test/MockJSRuntime.cs
+++ b/test/MockJSRuntime.cs
@@ -83,6 +83,30 @@ public override napi_status CloseEscapableHandleScope(
return napi_ok;
}
+ public override napi_status EscapeHandle(
+ napi_env env,
+ napi_escapable_handle_scope scope,
+ napi_value escapee,
+ out napi_value result)
+ {
+ // Promote the value to the parent scope by mirroring it under a new handle, mimicking
+ // napi_escape_handle returning a new value that is valid in the outer scope.
+ if (!_values.TryGetValue(escapee.Handle, out MockJSValue? mockValue))
+ {
+ result = default;
+ return napi_invalid_arg;
+ }
+
+ nint handle = ++s_handleCounter;
+ _values.Add(handle, new MockJSValue
+ {
+ ValueType = mockValue.ValueType,
+ Value = mockValue.Value,
+ });
+ result = new napi_value(handle);
+ return napi_ok;
+ }
+
public override napi_status CreateString(
napi_env env, ReadOnlySpan utf16Str, out napi_value result)
{
@@ -105,6 +129,10 @@ public override napi_status CreateObject(
return napi_ok;
}
+ public override napi_status DefineProperties(
+ napi_env env, napi_value js_object, ReadOnlySpan properties)
+ => napi_ok;
+
public override napi_status GetValueType(
napi_env env, napi_value value, out napi_valuetype result)
{
diff --git a/test/NodejsEmbeddingTests.cs b/test/NodejsEmbeddingTests.cs
index 72742639..3e54aa98 100644
--- a/test/NodejsEmbeddingTests.cs
+++ b/test/NodejsEmbeddingTests.cs
@@ -525,7 +525,7 @@ public void LinkedModuleFromHandleScope()
nodejs.Run(() =>
{
- using JSValueScope handleScope = new();
+ using JSValueScope handleScope = JSValueScope.CreateHandleScope();
Assert.Equal(
"test-linked",
(string)JSValue.RunScript("process._linkedBinding('test-linked').moduleName"));
diff --git a/test/TestCases/napi-dotnet/worker_teardown_stress.js b/test/TestCases/napi-dotnet/worker_teardown_stress.js
new file mode 100644
index 00000000..796d1a01
--- /dev/null
+++ b/test/TestCases/napi-dotnet/worker_teardown_stress.js
@@ -0,0 +1,56 @@
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+
+// Stress variant of worker_teardown.js. It repeatedly creates a Worker that loads the .NET host
+// (only inside the worker), waits for it to initialize, then terminates it. Each load initializes
+// a native host and a managed host for that worker's environment; terminating the worker tears the
+// environment down, which runs the native host's instance-data finalizer. That finalizer notifies
+// the managed host to dispose its context, all without calling into JavaScript (the environment is
+// being destroyed). Looping exercises that per-environment init/teardown path many times to
+// surface teardown-ordering crashes or leaked references (the crash class this guards against).
+//
+// The workers run one at a time (each is terminated before the next is created), so this never
+// holds two host instances at once. As with worker_teardown.js this validates the hosted host
+// module and runs under HostedClrTests only (the name contains "worker_teardown", which also
+// excludes it from NativeAotTests).
+
+const assert = require('assert');
+const { Worker, isMainThread, parentPort } = require('worker_threads');
+
+const iterations = 8;
+
+if (isMainThread) {
+ (async () => {
+ for (let i = 0; i < iterations; i++) {
+ const worker = new Worker(__filename);
+ // Fail the test on any worker error for the worker's full lifetime -- including during
+ // terminate() -- not just while awaiting readiness (as worker_teardown.js does).
+ worker.on('error', (err) => { throw err; });
+ await new Promise((resolve, reject) => {
+ worker.once('message', (message) => {
+ try {
+ assert.strictEqual(message, 'ready');
+ resolve();
+ } catch (err) {
+ reject(err);
+ }
+ });
+ // A worker that exits before signaling 'ready' without an error would otherwise leave this
+ // promise pending, letting the test process exit successfully after a failed iteration.
+ worker.once('exit', (code) => {
+ reject(new Error(`Worker exited before signaling ready (code ${code}).`));
+ });
+ });
+ await worker.terminate();
+ }
+
+ // Keep the process alive briefly so any teardown crash surfaces as a non-zero exit code
+ // instead of being skipped by an immediate process exit.
+ setTimeout(() => process.exit(0), 300);
+ })().catch((err) => { throw err; });
+} else {
+ // Load the native host ONLY in the worker.
+ const binding = require('../common').binding;
+ assert.ok(binding);
+ parentPort.postMessage('ready');
+}
diff --git a/version.json b/version.json
index 97ff12e1..25ea6c76 100644
--- a/version.json
+++ b/version.json
@@ -1,7 +1,7 @@
{
"$schema": "https://raw.githubusercontent.com/AArnott/Nerdbank.GitVersioning/master/src/NerdBank.GitVersioning/version.schema.json",
- "version": "0.9",
+ "version": "0.10",
"publicReleaseRefSpec": [
"^refs/heads/main$",