Skip to content

[WASM] Bind CoreCLR JSExports lazily using assembly type-map providers - #136924

Open
pavelsavara wants to merge 37 commits into
mainfrom
jsexport-typemap-assembly-lazy
Open

pavelsavara wants to merge 37 commits into
mainfrom
jsexport-typemap-assembly-lazy

Conversation

@pavelsavara

@pavelsavara pavelsavara commented Nov 3, 2026 •

Copy link
Copy Markdown
Member

Summary

The CoreCLR Browser/Wasm JSExport generator emits one approved JSExportProvider and one local type-map entry per exporting assembly. It does not scan referenced assemblies or generate links to their export maps. getAssemblyExports() reads only the requested assembly's metadata or ReadyToRun map, without loading unrelated lazy assemblies. Public application-wide type-map queries still follow explicit assembly-target edges.

Trimming and compatibility

  • ILLink preserves the local JSExport map in an assembly it already keeps. If reachable managed code keeps a library, the library needs no additional root. For a library used only from JavaScript, the library author can supply a root descriptor for the publishing app to include as a TrimmerRootDescriptor. Embedding a descriptor in an otherwise-unrooted library does not keep that library.
  • Trimmed publishes require an SDK that selects an ILLink package with local JSExport discovery. An older linker can keep a library DLL but remove its export map, leaving no exports for the runtime to discover. The Browser SDK's compatibility target forwards the type-map root; it does not select the linker. Removal of the forwarding bridge is tracked in [Browser] Remove type-map forwarding bridge after ILLink SDK flow #137651.
  • The runtime and linker use the same type-map root: TypeMapEntryAssembly if set, then the explicit System.Runtime.InteropServices.TypeMappingEntryAssembly runtime host option, then the app assembly. The selected root takes precedence over a raw linker argument and works for library-mode apps that have no managed entry point.
  • Assemblies generated with the released .NET 10 and .NET 11 generators keep working through the legacy registration path. Assemblies with neither a provider nor a legacy initializer return empty exports. Lazy assemblies must be downloaded before their exports are requested.

Discovery and invocation

  • The provider publishes export names and signature metadata. JavaScript copies the signatures and exposes stable functions without binding their managed wrappers on property access. On the first invocation, the dispatcher binds the selected wrapper using the existing marshaled frame.
  • Preserve overload aliases, synchronous and asynchronous results, exceptions, and disposal. Failed bindings release unused argument payloads, including draining Promise arguments without creating an unobserved managed task. Reentrant binding is rejected, and a failed binding can be retried.
  • Bind wrappers directly by managed function pointer where possible. Wrappers whose declaring types cannot be referenced directly, including error-obsolete types, use managed unsafe accessors or the reflection fallback. Provider activation uses Activator.CreateInstance with generated constructor dependencies.

Validation

Local validation Result
JS import/export generator suite 53 passed
CoreCLR Browser Debug interop suite in Chrome 523 passed, 2 skipped, 0 failed
No-workload CoreCLR Browser LibraryMode build/publish cases 4 passed

The trimmed Chrome suite exercises a managed-referenced library's JSExport with in-tree ILLink. The LibraryMode cases verify explicit runtime root preservation and linker argument precedence. These runs do not establish that an ordinary SDK publish selects a linker with local JSExport discovery.

Resolves #136464
Resolves #120215

Note

This pull request description was generated with GitHub Copilot.

pavelsavara and others added 13 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]>
Combine export-name discovery and first-call binding in one generated
assembly-keyed type-map provider. Dispatch Bind(string methodId) using
invariant decimal catalog indexes, retaining ordinary JS objects,
stable overload aliases, cached bindings and legacy compatibility.

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
@pavelsavara pavelsavara changed the title [WASM] Prototype lazy JSExport binding with one provider per assembly [WIP][WASM] Prototype lazy JSExport binding with one provider per assembly 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.

Configure the ILLink argument at target execution time so WebAssembly SDK
imports can provide the root after the linker targets have been evaluated.
Add a shared duplicate-safe Browser fallback until the ILLink fix flows
through supported SDKs, and include it in both WebAssembly packages.

Verify exact-once root forwarding in the existing LibraryMode publish test.

Co-authored-by: Copilot <[email protected]>
@pavelsavara

Copy link
Copy Markdown
Member Author

CI issue UnusedCoreLibEntryPointsAreTrimmed is fixed by #137527

Keep shared JSExport trimming configuration independent of native relinking
and move checkout-specific imports into the in-tree and local-build adapters.
Track removal of the SDK-flow forwarding fallback in #137651.

Reuse WasmBasicTestApp with opt-in provider and legacy fixtures, preserve
single-file JavaScript bundling, and use the stable .NET 11 targeting pack.
Verify LibraryMode forwarding through the actual ILLink binlog arguments.

Validated on CoreCLR and Mono: provider/legacy 7/7, LibraryMode 4/4, and
the existing bundled initializer 1/1 per runtime. Both SDK package builds
passed for each runtime.

Co-authored-by: Copilot <[email protected]>
pavelsavara and others added 2 commits November 20, 2026 14:16
Remove Mono-specific assembly discovery and JavaScript binding changes.
Keep the existing legacy Mono dispatch in shared managed sources, and
scope provider configuration and new regression tests to CoreCLR.

Move the export-name parser into CoreCLR interop and remove the Mono-only
provider accommodations, resources, and package dependency.

Validated after merging fresh main: full CoreCLR Browser Debug build,
46 generator tests, 372 ILLink task tests, 522 interop tests passed with
2 existing skips, and 12 focused WBT cases passed.

Co-authored-by: Copilot <[email protected]>
@pavelsavara pavelsavara changed the title [WASM] Bind JSExports lazily using assembly type-map providers [WASM] Bind CoreCLR JSExports lazily using assembly type-map providers Nov 20, 2026
pavelsavara and others added 5 commits November 23, 2026 10:29
Use the existing reflection fallback for inaccessible struct exports
instead of emitting an unsupported UnsafeAccessorType target.
Keep the configured type-map entry assembly authoritative when raw
linker arguments specify a different root.

Co-authored-by: Copilot <[email protected]>
Discover JSExport maps when ILLink marks their assemblies instead of scanning references in the generator. Libraries reached only from JavaScript still need an explicit publish root.

Co-authored-by: Copilot <[email protected]>
Keep explicit runtime type-map roots unless TypeMapEntryAssembly overrides them. Drain unused Promise arguments on binding failure, and avoid direct wrapper references through error-obsolete types.

Run the secondary runtime disposal test only in browsers and cover root precedence and the binding regressions.

Co-authored-by: Copilot <[email protected]>
Read the runtimeconfig template before defaulting to the app assembly. Track the effective root so changing or clearing it reruns ILLink without invalidating unchanged publishes, including with older SDK linker targets.

Co-authored-by: Copilot <[email protected]>
@pavelsavara
pavelsavara requested a review from lewing November 24, 2026 16:27
pavelsavara and others added 2 commits November 25, 2026 13:08
Use the shared no-workload Wasm build test targets to select the current reference pack and generator for both child projects.

Co-authored-by: Copilot <[email protected]>

This branch was previously deployed

1 inactive (outdated) deployment
copilot-pat-pool — a3e3c1d1 Deployed Nov 3, 2026 by pavelsavara via conclusion #11681
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

5 participants