Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion bench/Benchmarks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
9 changes: 4 additions & 5 deletions docs/features/js-value-scopes.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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.
Expand All @@ -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())
Expand Down
2 changes: 1 addition & 1 deletion docs/features/type-definitions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
<ItemGroup>
<PackageReference Include="Microsoft.JavaScript.NodeApi.Generator" Version="0.9.*-*" />
<PackageReference Include="Microsoft.JavaScript.NodeApi.Generator" Version="0.10.*-*" />
</ItemGroup>
```

Expand Down
4 changes: 2 additions & 2 deletions docs/scenarios/js-dotnet-module.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ For a minimal example of this scenario, see
Afterward you should have the two references in your project file:
```xml
<ItemGroup>
<PackageReference Include="Microsoft.JavaScript.NodeApi" Version="0.9.*-*" />
<PackageReference Include="Microsoft.JavaScript.NodeApi.Generator" Version="0.9.*-*" />
<PackageReference Include="Microsoft.JavaScript.NodeApi" Version="0.10.*-*" />
<PackageReference Include="Microsoft.JavaScript.NodeApi.Generator" Version="0.10.*-*" />
</ItemGroup>
```

Expand Down
5 changes: 3 additions & 2 deletions examples/hermes-engine/HermesRuntime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Comment thread
vmoroz marked this conversation as resolved.
Resolved
CreatePolyfills();
}

Expand Down Expand Up @@ -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;
Expand Down
18 changes: 9 additions & 9 deletions src/NodeApi.DotNetHost/JSMarshaller.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down Expand Up @@ -1878,22 +1878,22 @@ private IEnumerable<Expression> BuildThisArgumentExpressions(

if (type.GetCustomAttributes<JSModuleAttribute>().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(
Expand Down
175 changes: 158 additions & 17 deletions src/NodeApi.DotNetHost/ManagedHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,15 @@ public sealed class ManagedHost : JSEventEmitter, IDisposable

#if !(NETFRAMEWORK || NETSTANDARD)
/// <summary>
/// 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).
/// </summary>
private readonly AssemblyLoadContext _loadContext = new(name: default);
#endif

private JSValueScope? _rootScope;
private JSRuntimeContext? _context;

/// <summary>
/// Component that dynamically exports types from loaded assemblies.
Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand All @@ -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]<nint, void>)&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
Expand All @@ -238,6 +290,69 @@ public static napi_value InitializeModule(napi_env env, napi_value exports)
#endif
}

#if !(NETFRAMEWORK || NETSTANDARD)
/// <summary>
/// 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.
/// </summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static void OnEnvironmentFinalize(nint addon) => OnEnvironmentFinalizeCore(addon);
#else
/// <summary>
/// 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.
/// </summary>
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();
}
}

/// <summary>
/// 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.
/// </summary>
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);
}
}

/// <summary>
/// Resolve references to Node API and other assemblies that loaded assemblies depend on.
/// </summary>
Expand Down Expand Up @@ -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
Expand Down
35 changes: 35 additions & 0 deletions src/NodeApi.DotNetHost/ManagedHostRegistration.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System;
using System.Runtime.InteropServices;

namespace Microsoft.JavaScript.NodeApi.DotNetHost;

/// <summary>
/// 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.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
[StructLayout(LayoutKind.Sequential)]
internal struct ManagedHostRegistration
{
/// <summary>
/// A strong <see cref="GCHandle"/> to the managed host, allocated and freed only by managed
/// code. The native host treats it as an opaque pointer.
/// </summary>
public nint AddonGCHandle;

/// <summary>
/// A native callback pointer (<c>delegate* unmanaged&lt;nint, void&gt;</c>) 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).
/// </summary>
public nint OnEnvFinalize;
}
Loading
Loading