Skip to content

Honor DirectPInvoke items for CoreCLR wasm apps - #137716

Merged
lewing merged 17 commits into
dotnet:mainfrom
lewing:lewing-wasi-coreclr-app-direct-pinvokes
Nov 23, 2026
Merged

lewing merged 17 commits into
dotnet:mainfrom
lewing:lewing-wasi-coreclr-app-direct-pinvokes

Conversation

@lewing

@lewing lewing commented Nov 17, 2026

Copy link
Copy Markdown
Member

Honor the DirectPInvoke and DirectPInvokeList items in CoreCLR wasm app builds, with the same semantics as NativeAOT, so apps can bind entry points from implicitly linked libraries such as libc!link.

  • The WASI and browser CoreCLR targets pass the items to both crossgen2 invocations (R2R compilation and call-helper generation), so the direct P/Invoke set and the generated table stay consistent. On browser they imply WasmBuildNative.
  • crossgen2 accepts module!entrypoint in --directpinvoke and adds --directpinvokelist. Parsing moves to a shared DirectPInvokeSet in tools/Common, which ILC's ConfigurablePInvokePolicy now uses.
  • The call-helper generator declares per-entry-point imports in a separate namespace, bound by asm label, so they don't conflict with system header declarations. It emits one declaration per entry point, and P/Invokes of one entry point that lower to different wasm signatures are now a build error rather than a C++ compile failure.

The checked-in call-helper tables are unchanged.

Note

This PR description was drafted with GitHub Copilot.

lewing and others added 5 commits November 16, 2026 17:07
CoreCLR WASI and browser apps could only statically bind P/Invokes to
framework modules or native files they link, so an app P/Invoke into a
library the native link provides implicitly, such as libc, threw
DllNotFoundException. Binding the whole libc module isn't an option: the
call-helper table would declare every libc import in the closure,
including ones wasi-libc lacks (statx), and fail the link.

Honor the NativeAOT DirectPInvoke and DirectPInvokeList items, including
the per-entry-point module!entrypoint form, when computing the modules
passed to crossgen2 for both ReadyToRun compilation and call-helper
generation. crossgen2's --directpinvoke now accepts the per-entry-point
form with the same meaning as ILC's.

Co-authored-by: Copilot App <[email protected]>
Entry points bound with the module!entrypoint form typically come from a
library the toolchain links implicitly, such as libc. The generated
call-helper source includes string.h through minipal/entrypoints.h, so a
metadata-derived declaration of, say, strlen conflicts with the header's
and fails to compile. Declare those entry points under a separate C
identifier bound to the same linker symbol, as the QCall table already
does, and reference that from the table.

Add a CoreCLR browser Wasm.Build.Tests case that publishes, with and
without ReadyToRun, an app binding libc!strlen through DirectPInvoke and
runs it, checking that an unlisted libc import stays unbound.

Co-authored-by: Copilot App <[email protected]>
A prefixed C identifier only makes a clash unlikely: the same file can
also declare an app entry point literally named with the prefix. Declare
the individually listed entry points with C++ linkage in a namespace the
generated file uses for nothing else, bound to the native symbol by an
asm label, so they cannot conflict with system headers or other
generated declarations.

Co-authored-by: Copilot App <[email protected]>
- Emit one declaration per entry point and path. Declarations that differ
  only in C types (uint against nuint) overloaded the name in the
  namespace, or conflicted as extern "C", although the table holds one
  address for them.
- Reject, with WASM0001, an entry point whose P/Invokes lower to
  different wasm signatures, as for apparent varargs; a single
  declaration would otherwise trap when called through the other one.
- Name the namespace so it cannot clash with a global declaration:
  entry points can be named anything, including direct_pinvoke.
- Omit a module whose imports were all rejected rather than emitting an
  empty array.

Extend the browser WBT with same-entry-point declarations that differ in
return and parameter types, and with a DirectPInvokeList variant.

Co-authored-by: Copilot App <[email protected]>
- Move the DirectPInvoke entry parsing and lookup into a shared
  DirectPInvokeSet under tools/Common, used by ILC's
  ConfigurablePInvokePolicy and by crossgen2, so the module and
  module!entrypoint forms have one implementation.
- Add crossgen2 --directpinvokelist, matching ILC, and map the
  DirectPInvoke and DirectPInvokeList items in the CoreCLR WASI and
  browser targets the way the NativeAOT targets do, instead of reading
  list files in ComputeWasmPInvokeModules. List files are ReadyToRun
  compiler inputs, so editing one recompiles.
- Make P/Invokes of one entry point that lower to different wasm
  signatures a generator error. Skipping them left callers that
  ReadyToRun bound directly with fixups the table could not satisfy.
- Replace the generator unit test with Wasm.Build.Tests coverage of
  the conflicting-signature error.

Co-authored-by: Copilot App <[email protected]>
@azure-pipelines

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

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/crossgen-contrib
See info in area-owners.md if you want to be subscribed.

Move the rule that module "*" is always a direct P/Invoke from ILC's
ConfigurablePInvokePolicy into the shared DirectPInvokeSet, and drop the
separate "*" handling in crossgen2's IsDirectPInvoke and call-helper
generator, so all AOT compilers apply it the same way.

Co-authored-by: Copilot App <[email protected]>
lewing and others added 2 commits November 17, 2026 08:46
Direct P/Invoke entries now match only the [DllImport] name and its
variations, as in ILC, so libStructABILib no longer matches
DllImport("StructABILib"). The test-specific wasm corerun named its
modules after the archives, lib prefix included, so every test with its
own native library lost its call-helper table entries and threw
DllNotFoundException. Strip the prefix, as ComputeWasmPInvokeModules
does for app builds.

Co-authored-by: Copilot App <[email protected]>
Derive each test archive's module name once in
CLRTest.WasmNativeLibraries.targets, which both the CoreCLR test corerun
and the NativeAOT wasm test build import, instead of repeating the
static-library-prefix normalization in each.

Co-authored-by: Copilot App <[email protected]>
Move the module name variations out of MarshalHelpers, where dotnet#133773
put them, and ILC's entry point variations out of
ConfigurablePInvokePolicy, into DirectPInvokeSet. TryGetDirectEntryPoint
returns the native symbol a direct P/Invoke binds to, so ILC, crossgen2
and the call-helper generator all resolve it the same way.

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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Active issues include whole-module P/Invoke declarations that can fail native compilation, stale ReadyToRun images after list changes, rejection of compatible signatures, and missing list files in repro packages.

4 open issues
What changed in this PR

This PR adds DirectPInvoke and DirectPInvokeList support to CoreCLR WebAssembly app builds, sharing NativeAOT’s selection logic so apps can bind functions from implicitly linked native libraries.

Changes:

  • Pass direct P/Invoke settings to ReadyToRun compilation and call-helper generation for browser and WASI builds.
  • Share parsing between crossgen2 and NativeAOT, add isolated entry-point declarations, and detect conflicting signatures.
  • Add browser build tests and centralize native test archive module naming.

Validation was limited to source inspection; builds and tests were not run.

File Description
src/​tests/​Directory.Build.targets Reuse shared archive metadata for NativeAOT test linking.
src/​tests/​Common/​CLRTest.WasmNativeLibraries.targets Compute archive module names and track native file references.
src/​tests/​Common/​CLRTest.WasmCorerun.targets Use shared module names for CoreCLR test imports.
src/​mono/​wasm/​Wasm.Build.Tests/​PInvokeTableGeneratorTests.cs Test direct bindings, list files, and signature conflicts.
src/​mono/​wasm/​testassets/​EntryPoints/​PInvoke/​DirectPInvoke.cs Add a sample covering selected and unresolved imports.
src/​mono/​wasi/​build/​WasiApp.CoreCLR.targets Forward direct import settings to both compilation stages.
src/​mono/​browser/​build/​BrowserWasmApp.CoreCLR.targets Forward settings and enable native relinking when needed.
src/​coreclr/​tools/​Common/​TypeSystem/​Interop/​IL/​MarshalHelpers.cs Remove module-name variation logic moved to the shared parser.
src/​coreclr/​tools/​Common/​Compiler/​DirectPInvokeSet.cs Centralize direct import parsing and matching.
src/​coreclr/​tools/​aot/​ILCompiler/​ConfigurablePInvokePolicy.cs Delegate NativeAOT selection to the shared implementation.
src/​coreclr/​tools/​aot/​ILCompiler.ReadyToRun/​PortableCallHelpers/​PortableCallHelpersGenerator.cs Pass list files to table generation.
src/​coreclr/​tools/​aot/​ILCompiler.ReadyToRun/​PortableCallHelpers/​PInvokeTableGenerator.cs Select individual imports, emit aliases, and check signatures.
src/​coreclr/​tools/​aot/​ILCompiler.ReadyToRun/​ILCompiler.ReadyToRun.csproj Include the shared direct import implementation.
src/​coreclr/​tools/​aot/​ILCompiler.ReadyToRun/​Compiler/​ReadyToRunCompilationModuleGroupBase.cs Use shared matching for direct-call classification.
src/​coreclr/​tools/​aot/​ILCompiler.Compiler/​ILCompiler.Compiler.csproj Include the shared implementation for NativeAOT.
src/​coreclr/​tools/​aot/​crossgen2/​Properties/​Resources.resx Update help text for direct import options.
src/​coreclr/​tools/​aot/​crossgen2/​Program.cs Connect parsed options to compilation and helper generation.
src/​coreclr/​tools/​aot/​crossgen2/​Crossgen2RootCommand.cs Register the --directpinvokelist option.

Review effort: Balanced

Whole-module DirectPInvoke items and "*" emitted plain extern "C"
declarations, which conflict with header declarations such as strlen in
string.h. Declare every non-[WasmImportLinkage] P/Invoke in the namespace
with an asm label (same linked symbol) and regenerate the checked-in tables.

Also from review:
- compare lowered WasmFuncType for the conflicting-signature check, so
  by-reference structs and pointers that lower alike aren't rejected
- include --directpinvokelist files in crossgen2 repro packages
- write DirectPInvokeList paths into the R2R manifest so removing one
  invalidates the R2R images
- WBT: whole-module libc case and a by-reference struct strlen overload

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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The cross-cutting WASM ABI, ReadyToRun, and shared NativeAOT changes require maintainer confirmation because browser/WASI native linking, execution, and NativeAOT regression validation remain unverified.

No open issues 🎉

4 resolved since last review

Review effort: Balanced

…orkload

- PInvokeTableGeneratorTests: the CoreCLR table now emits
  { "name", (void*)&direct_pinvoke::name } instead of DllImportEntry(name),
  and declarations carry an asm label after the parameter list.
- Items aren't available when the workload manifest evaluates
  _WasmNativeWorkloadNeeded, so like NativeFileReference, warn from
  _CheckBrowserWorkloadNeededButNotAvailable when CoreCLR browser apps
  have DirectPInvoke/DirectPInvokeList items but no workload.

Co-authored-by: Copilot App <[email protected]>
lewing added a commit to lewing/runtime that referenced this pull request Nov 20, 2026
…l-helper prototype

Squashed from the PR's 13 commits at 38e57c5, which the wasm P/Invoke
table emission builds on. Drop this commit once the PR merges.

Co-authored-by: Copilot App <[email protected]>
On CoreCLR, NativeFileReference, NativeLibrary, DirectPInvoke and
DirectPInvokeList items need a native relink. Without the workload they
were silently ignored (a warning for NativeFileReference, nothing for the
rest), and the P/Invokes threw DllNotFoundException at runtime.

Add a MissingWorkloadPack item for the WebAssembly SDK pack, as the
workload resolver adds for property-driven requirements, so the build
fails with NETSDK1147. Items can't feed _WasmNativeWorkloadNeeded, so:
- add it during evaluation, so VS and 'dotnet workload restore' suggest
  wasm-tools (GetSuggestedWorkloads checks its condition before any
  BeforeTargets run), and
- add it again from a target before _CheckForMissingWorkload, for items
  from Directory.Build.targets or package targets, which are imported
  after the workload manifest.

Mono keeps the NativeFileReference warning.

Co-authored-by: Copilot App <[email protected]>
Matches dotnet/sdk#57257, which moves the MissingWorkloadPack checks onto
the ShowMissingWorkloads tasks so targets running before
GetSuggestedWorkloads can add items. With that SDK, VS and
'dotnet workload restore' also suggest wasm-tools for native items from
Directory.Build.targets or package targets; with the current SDK the hook
is harmless.

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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Differing-arity signature conflicts bypass validation and only emit a warning, omitting the P/Invoke table entry and potentially leaving unresolved ReadyToRun fixups instead of failing the build.

No open issues 🎉

1 previously missed issue

In code that hasn't changed since last review

High severity Reject conflicting signatures before skipping variadic candidates

src/​coreclr/​tools/​aot/​ILCompiler.ReadyToRun/​PortableCallHelpers/​PInvokeTableGenerator.cs:121

Signature conflicts with different argument counts never reach this check: ShouldTreatAsVariadic marks every candidate as skipped and continues first. For example, direct libc!llabs declarations taking one and two long arguments produce only a warning and omit the entry from the table, rather than failing the build; ReadyToRun still treats both as direct and can retain unresolved fixups. Check the lowered signatures before the variadic skip, and add a differing-arity regression case.

Review effort: Balanced

@jkotas

jkotas commented Nov 23, 2026

Copy link
Copy Markdown
Member

1 previously missed issue Signature conflicts with different argument counts never reach this check: ShouldTreatAsVariadic marks every candidate as skipped and continues first. For example, direct libc!llabs declarations taking one and two long arguments produce only a warning and omit the entry from the table, rather than failing the build; ReadyToRun still treats both as direct and can retain unresolved fixups. Check the lowered signatures before the variadic skip, and add a differing-arity regression case.

This looks like a valid feedback to me.

Do vararg P/Invokes work at all in wasm? We do not support pinvoke varargs on non-Windows. Should the ShouldTreatAsVariadic check be deleted?

lewing and others added 2 commits November 22, 2026 21:32
…he build

A P/Invoke failing to bind is a runtime error, so P/Invokes of one native
entry point that lower to different WebAssembly signatures now get a WASM0001
warning and are left out of the call-helper table, like varargs (differing
arity) already were, instead of failing the build.

crossgen2 no longer binds those entry points directly on wasm: a direct call's
fixup fails when the calling method is prepared, so a method failed even on
paths that never made the call. It checks the P/Invokes the module declares
for the same entry point with the generator's test.

Co-authored-by: Copilot App <[email protected]>
@lewing
lewing merged commit 9bae407 into dotnet:main Nov 23, 2026
104 of 105 checks passed
lewing added a commit to lewing/runtime that referenced this pull request Nov 23, 2026
…rebase merge

ExecuteInterpretedMethodFromUnmanaged now returns the native code of a method
that gained it after its thunk was handed out (delayed R2R activation). The
emitted wasm reverse thunks keep that result and, when it is non-null, refresh
an export's cached entry point and call it, as the C++ thunks do.

Also restores PInvokeTableGenerator after the rebase onto main, which merged
dotnet#137716's final helpers (IsVariadic, LowerToDifferentSignatures,
HasIncompatibleSignatures; WASM0001 for conflicting signatures) into the wrong
methods of the table model.

Co-authored-by: Copilot App <[email protected]>
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 12.0-preview1 milestone Nov 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants