Repository navigation
[WASM] Prototype first-call JSExport binding with per-method providers - #136922
Closed
pavelsavara wants to merge 12 commits into
Closed
pavelsavara wants to merge 12 commits into
pavelsavara wants to merge 12 commits into
Conversation
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]>
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]>
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]>
|
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
temporarily deployed
to
copilot-pat-pool
November 3, 2026 16:10 — with
GitHub Actions
Inactive
Contributor
|
Tagging subscribers to 'arch-wasm': @lewing, @pavelsavara |
pavelsavara
temporarily deployed
to
copilot-pat-pool
November 3, 2026 16:11 — with
GitHub Actions
Inactive
This was referenced Nov 3, 2026
Member
Author
|
Closing in favor of #136924 |
This was referenced Nov 3, 2026
This branch was previously deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 JSProxyis needed.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, andGetEnumeratorthrow 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:
Both types are browser-only and
EditorBrowsable(Never); their entry methods haveDebuggerNonUserCode.Bind()replaces the per-assembly prototype'sRegister(). The proposed function-pointer overload ofJSFunctionBinding.BindManagedFunctionis 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.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:
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=falsewas 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
84a41ea4d53from 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.