Skip to content

[WASM] Prototype first-call JSExport binding with per-method providers - #136922

Closed
pavelsavara wants to merge 12 commits into
mainfrom
jsexport-typemap-per-method
Closed

pavelsavara wants to merge 12 commits into
mainfrom
jsexport-typemap-per-method

Conversation

@pavelsavara

Copy link
Copy Markdown
Member

Summary

Another comparison prototype for #136464, based on the per-assembly alternative in #136858 and retaining the managed function-pointer dispatch from #134923.

Generate one type-map provider per JSExport and postpone its activation and binding until the first invocation, not property access.

  • getAssemblyExports() discovers names and creates ordinary JS namespace objects containing stable deferred functions. No JS Proxy is needed.
  • Reading or capturing an exported function does not activate its method provider or construct its marshalers.
  • The first call binds synchronously through an existing managed-delegate callback; subsequent calls reuse the binding. Synchronous exports remain synchronous.
  • Preserve plain-name aliases, hash-qualified names, function identity, nested object lookup, and normal property enumeration.
  • Retain the existing eager registration fallback for legacy generated assemblies.
  • Keep binder callbacks alive across ordinary proxy cleanup, and dispose them with runtime/method state.

No new native export or generated CoreCLR callhelper is required.

Discovery and API shape

CoreCLR's lazy type maps deliberately do not support enumeration, despite returning IReadOnlyDictionary. Keys, Values, Count, and GetEnumerator throw to protect trimmer invariants.

Consequently, this prototype has one additional name-only catalog per assembly. Discovery activates that catalog, obtains its literal export-key list, and uses supported type-map lookups. Individual method providers remain uninstantiated until first call. Both catalog and method-provider constructors are explicitly preserved for trimming.

The generator-facing API shape is:

namespace System.Runtime.InteropServices.JavaScript;

public abstract class JSExportCatalog
{
    protected JSExportCatalog();
    public abstract string[] GetExportNames();
}

public abstract class JSExportProvider
{
    protected JSExportProvider();
    public abstract void Bind();
}

Both types are browser-only and EditorBrowsable(Never); their entry methods have DebuggerNonUserCode. Bind() replaces the per-assembly prototype's Register(). The proposed function-pointer overload of JSFunctionBinding.BindManagedFunction is unchanged.

Canonical method keys include the FQN and signature hash; plain-name map entries identify the default overload. A separate catalog map associates each assembly name with its catalog type. Referenced assemblies receive targets for both map groups.

The browser entry-assembly configuration and native bootstrap trimming root from the per-assembly prototype remain necessary. This does not reintroduce a module initializer or explicit RunModuleConstructor.

Validation

Windows, browser-wasm, CoreCLR Debug runtime. Commands below omit only per-session binary-log destinations.

  • .\build.cmd -bl -os browser -subset clr+libs+host -c Debug /p:RuntimeFlavor=CoreCLR /p:EnableHotReloadInRuntimeConfigDevFile=false — baseline passed, zero warnings/errors.
  • .\build.cmd -bl -os browser -subset libs.sfx+libs.native+host.native+libs.pretest -c Debug /p:RuntimeFlavor=CoreCLR /p:EnableHotReloadInRuntimeConfigDevFile=false — catalog-based implementation staging passed, zero warnings/errors.
  • .\dotnet.cmd build -bl /p:TargetOS=windows /p:TargetArchitecture=x64 /p:Configuration=Debug /p:RuntimeFlavor=CoreCLR /p:UseDefaultTestHost=true /p:UseLocalTargetingRuntimePack=false /p:NetCoreAppCurrentTestHostPath=D:\.dotnet /t:Test src\libraries\System.Runtime.InteropServices.JavaScript\tests\JSImportGenerator.UnitTest\JSImportGenerator.Unit.Tests.csproj — 43 passed, zero failed/skipped. Includes source snapshots and catalog-only reference propagation. The per-method-provider regression was verified failing with the original per-assembly generator.
  • .\dotnet.cmd build -bl /p:TargetOS=browser /p:TargetArchitecture=wasm /p:Configuration=Debug /p:RuntimeFlavor=CoreCLR /t:Test src\mono\wasm\Wasm.Build.Tests /p:TestUsingWorkloads=false /p:InstallWorkloadForTesting=false /p:InstallChromeForTests=false /p:XUnitClassName=Wasm.Build.Tests.LibraryInitializerTests — 5 passed, zero failed/skipped.
  • .\dotnet.cmd build -bl /p:TargetOS=browser /p:TargetArchitecture=wasm /p:Configuration=Debug /p:RuntimeFlavor=CoreCLR /t:Test /p:Scenario=WasmTestOnChrome /p:InstallChromeForTests=false src\libraries\System.Runtime.InteropServices.JavaScript\tests\System.Runtime.InteropServices.JavaScript.UnitTests\System.Runtime.InteropServices.JavaScript.Tests.csproj — 511 total: 509 passed, zero failed, 2 existing skips. Includes runtime isolation and captured-export disposal. A final targeted disposal rerun passed both bound and never-bound cases.
  • Existing TypeScript ESLint checks and npm run rollup:debug — passed.
  • GenerateReferenceAssemblySource — passed; the generated catalog/provider declarations were checked against the curated reference API.

The five WBT cases cover Debug/Release trimmed and Debug untrimmed provider apps, plus Debug/Release .NET 10 legacy compatibility apps. Counting fixture providers assert the exact sequence:

discovery -> property read -> constructor -> bind -> first invocation -> repeated invocation

The first invocation throws a user exception; the following call succeeds without rebinding. An unused provider throws if activated, and remains untouched. Tests also cover overload aliases, async returns, function identity, enumeration, and JS-only referenced libraries.

The current targeting pack/generator was selected explicitly for both test app and helper libraries. EnableHotReloadInRuntimeConfigDevFile=false was inherited by child builds as a command-line/environment-only workaround for an unrelated SDK DotNetWatch failure. The Selenium suite used a cached matching Chrome/ChromeDriver pair. No SDK files or persistent build configuration were modified.

Limitations / review questions

  • API prototype only: the catalog contract and per-method provider shape are not approved API. The existing proposal has not been rewritten to this alternative.
  • CoreCLR-first: Mono retains eager method binding in this prototype; its existing untrimmed type-map limitation remains. Mono and NativeAOT execution have not been validated.
  • Stable function identity retains a JS forwarding function on subsequent calls. Download size, allocations, startup cost, and steady-state overhead have not been benchmarked.
  • Discovery still constructs the export-name/object tree up front; only method-provider activation and binding are deferred.
  • This branch is based on 84a41ea4d53 from the per-assembly prototype. Both earlier prototype PRs are unchanged.

Delta from the per-assembly prototype.

Note

This pull request description was generated with GitHub Copilot.

pavelsavara and others added 12 commits September 23, 2026 10:26
Two changes that do not need new public API.

CoreCLR already binds exports by storing the generated wrapper in
JSProxyContext.JSExportByHandle and letting JavaScript call CallJSExport with
that handle. Mono instead looked the wrapper up natively by name and invoked
the MonoMethod directly, so the two runtimes disagreed about how a bound
export is reached, and a wrapper signature change would not be diagnosed:
mono_class_get_method_from_name is passed -1 for the signature. Move
BindManagedFunction into a file shared by both flavors, give Mono a
CallJSExport and a handle-dispatching invoke in driver.c, and delete the
SystemInteropJS_GetAssemblyExport internal call. BindAssemblyExports stays
per-flavor: that is assembly bootstrap rather than dispatch, and the two
implementations differ in whether an assembly without exports is an error.

The generated JSImport stub no longer opens an unsafe context or calls
Unsafe.SkipInit, so a project using only [JSImport] no longer needs
AllowUnsafeBlocks and SYSLIB1074 is gone. [JSExport] still generates a
pointer-based wrapper, so SYSLIB1075 remains until that changes.

Also drop Interop.Runtime.BindAssemblyExports and GetAssemblyExport from the
CoreCLR declarations. They were already unreachable: GetAssemblyExport has no
implementation in the CoreCLR native library, and BindAssemblyExports there is
the reverse thunk into managed code, so calling it as a P/Invoke would recurse.
Generated JSExport registration now passes the wrapper as a method group to
a new BindManagedFunction overload, so the binding no longer needs
reflection, DynamicDependency, or unsafe code in user assemblies.

API (proposal pending):
- JSExportCallback(Span<JSMarshalerArgument>) delegate
- JSFunctionBinding.BindManagedFunction(..., JSExportCallback)
- JSFunctionBinding.RegisterAssemblyExports(string, Action)

The wrapper now takes Span<JSMarshalerArgument> rather than a pointer, so
the runtime constructs the span and generated code stays safe. The argument
count travels with the callback via JSProxyContext.JSExportEntry so the
runtime can size the span. Assemblies register their export initializer from
__TrimmingPreserve_; BindAssemblyExports consults that registry first and
falls back to the reflection path for assemblies built with an older
generator.

Types nested in a type that is not referenceable by a method group (generic
or file-local containers) keep the legacy reflection path and report the new
SYSLIB1076 warning. SYSLIB1075 (AllowUnsafeBlocks required for [JSExport])
is no longer reported.

Shared interop generator gains SignatureBehavior.RefToNativeType and
ValueBoundaryBehavior.RefNativeIdentifier so the inner stub can take its
argument slots by ref instead of by pointer.
The wasmbrowser template and the two JS interop test libraries enabled
unsafe code only because the [JSImport]/[JSExport] generators used to emit
it. Neither contains hand-written unsafe code, so the flag can go.

Left in place where unsafe code is genuinely used: WasmBasicTestApp/App
(fixed block in MemoryTest), the JS interop test project (void* imports and
stackalloc), and the PInvoke test assets.
PR #134507 landed on main, so the dispatch-unification work and its review fixes
now come from upstream. Conflicts were in the three files both sides touched:

- JSProxyContext: keep the JSExportEntry value (callback + frame size) from this
  branch, inside the private fields and locked accessors that landed on main.
  AllocJSExportHandle/TryGetJSExport now carry JSExportEntry.
- JSHostImplementation.Exports (add/add): keep the assembly-exports registry, the
  4-arg BindManagedFunction and BindManagedFunctionCore from this branch, and take
  main's reflection class-name fix, BindingContextOrMain and locked registration.
- JavaScriptExports.Mono: main's locked TryGetJSExport lookup with this branch's
  Span-based callback invocation.

Note main reverted the AllowUnsafeBlocks removal, so SYSLIB1074 and the SkipInit
emission are back. This branch still carries its own AllowUnsafeBlocks removal,
which is now reconsidered separately.

Co-authored-by: Copilot <[email protected]>
Generated JSExport registration now passes each wrapper's function pointer to a
new BindManagedFunction overload. The runtime stores that pointer in the
per-context handle table and invokes it directly, removing the reflection,
object array and Pointer.Box allocations from export dispatch.

Legacy wrappers retain their existing ABI and are resolved once through
MethodHandle.GetFunctionPointer, so they use the same direct dispatch path.
Assemblies self-register their export entry point through the module initializer;
BindAssemblyExports runs the module constructor and retains reflection only as a
fallback for legacy and non-referenceable wrappers.

AllowUnsafeBlocks remains required. The pointer-generation changes and
SYSLIB1074/SYSLIB1075 requirements are restored to main's behavior.

Co-authored-by: Copilot <[email protected]>
Build a library with the released .NET 10 targeting pack and run its
legacy JSExports in a trimmed current-framework browser application.
Cover marshaling, nested exports, exceptions, and async returns in the
no-workload CI lane.

Co-authored-by: Copilot <[email protected]>
Apply EditorBrowsable(Never) and DebuggerNonUserCode to the new
JSFunctionBinding binding and assembly registration APIs, including
their reference declarations.

Co-authored-by: Copilot <[email protected]>
Replace module-initializer callback registration with a generated
JSExportProvider and a type-map entry per assembly. Preserve the provider
constructor and native binding bootstrap during trimming, and configure
the browser type-map entry assembly before managed Main runs.

Retain managed function-pointer dispatch and the legacy generated-code
fallback. Cover JS-only library discovery in trimmed and untrimmed apps.

Co-authored-by: Copilot <[email protected]>
Separate name discovery from export binding using a name-only assembly
catalog and one type-map provider per method. Publish stable deferred
JavaScript functions and bind through the existing managed delegate bridge
only when an export is first invoked.

Preserve overload aliases and legacy registration, manage binder lifetime,
and test trimming, unused providers, first-call exceptions and disposal.

Co-authored-by: Copilot <[email protected]>
@dotnet-policy-service dotnet-policy-service Bot added the linkable-framework Issues associated with delivering a linker friendly framework label Nov 3, 2026
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 4 pipeline(s).
11 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@pavelsavara pavelsavara added arch-wasm WebAssembly architecture os-browser Browser variant of arch-wasm labels Nov 3, 2026
@pavelsavara pavelsavara added this to the 12.0.0 milestone Nov 3, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to 'arch-wasm': @lewing, @pavelsavara
See info in area-owners.md if you want to be subscribed.

@pavelsavara

Copy link
Copy Markdown
Member Author

Closing in favor of #136924

This branch was previously deployed

1 inactive deployment
copilot-pat-pool — c3e784ab Deployed Nov 3, 2026 by pavelsavara via conclusion #11655
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

arch-wasm WebAssembly architecture area-System.Runtime.InteropServices.JavaScript linkable-framework Issues associated with delivering a linker friendly framework os-browser Browser variant of arch-wasm

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant