Skip to content

[mono] Decode UnmanagedCallConvAttribute without allocating managed objects - #136352

Merged
pavelsavara merged 3 commits into
dotnet:mainfrom
SimonCropp:mono-unmanagedcallconv-noalloc
Oct 27, 2026
Merged

pavelsavara merged 3 commits into
dotnet:mainfrom
SimonCropp:mono-unmanagedcallconv-noalloc

Conversation

@SimonCropp

Copy link
Copy Markdown
Contributor

Fixes #136351

mono_marshal_set_callconv_from_unmanaged_callconv_attribute decoded [UnmanagedCallConv] with mono_reflection_create_custom_attr_data_args, which builds the CallConvs argument as a managed Type[]. The function also runs inside the AOT compiler (add_managed_to_native_wrappers → mono_marshal_get_native_wrapper). A cross compiler lays classes out for the target (see mono_check_corlib_version_internal), so for browser-wasm, a 32-bit target on a 64-bit host, the array does not fit the allocation sgen makes for it. The next allocation then trips g_assert (*p == NULL) in sgen_try_alloc_obj_nolock.

The attribute is now decoded with mono_reflection_create_custom_attr_data_args_noalloc, as mono_marshal_set_callconv_from_unmanaged_callers_only_attribute and the UnmanagedFunctionPointer path already do. Two smaller differences come with it:

  • The types are resolved in the method's image rather than in corlib's, as the UnmanagedCallersOnly path does.
  • CallConvs = null and null elements are skipped. Before, both dereferenced null.

Testing

  • New EnsureUnmanagedCallConvCompilesInAOT in Wasm.Build.Tests publishes, with AOT, an app with three such P/Invokes: one convention, two (CallConvCdecl + CallConvSuppressGCTransition), and [UnmanagedCallConv] with no arguments.
  • The issue's repro was run locally, extended to those three shapes: a Blazor WebAssembly app on SDK 11.0.100-rc.2.26504.105 published with RunAOTCompilation=true. Each compiler below was built with build.cmd -s mono.aotcross -c Release /p:MonoCrossAOTTargetOS=browser at RC2's source (474ed96), which has the same marshal.c and custom-attrs.c as main:
    • shipped RC2 mono-aot-cross: asserts at sgen-alloc.c:409
    • local build, without this change: asserts at sgen-alloc.c:409
    • local build, with this change: all 39 assemblies compile, and the published app starts and renders in the browser

…bjects

mono_marshal_set_callconv_from_unmanaged_callconv_attribute decoded the
attribute with mono_reflection_create_custom_attr_data_args, which builds
the CallConvs argument as a managed Type[]. The function also runs in the
AOT compiler, and a cross compiler lays classes out for the target, so for
browser-wasm the array did not fit the allocation sgen made for it and the
next allocation asserted in sgen_try_alloc_obj_nolock.

Decode it with mono_reflection_create_custom_attr_data_args_noalloc, as the
UnmanagedCallersOnly path already does. Null CallConvs, and null elements
in it, are now skipped rather than dereferenced.

Fixes dotnet#136351
@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Oct 23, 2026
@azure-pipelines

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

@maraf

maraf commented Oct 23, 2026

Copy link
Copy Markdown
Member

@SimonCropp Thank you for the contribution!

WebAssembly is moving to CoreCLR runtime and Mono is going to be removed (not shipped in 12).

@SimonCropp

Copy link
Copy Markdown
Contributor Author

@maraf not sure what the impact is to this PR? should i close it? or retarget the change somewhere else?

@pavelsavara pavelsavara added area-Codegen-AOT-mono arch-wasm WebAssembly architecture and removed area-Build-mono labels Oct 23, 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 pavelsavara self-assigned this Oct 23, 2026
@maraf

maraf commented Oct 23, 2026

Copy link
Copy Markdown
Member

We have discussed it offline that it could be a servicing candidate for 11. @pavelsavara will work with you

pavelsavara and others added 2 commits October 26, 2026 15:14
Extend the AOT regression asset with empty arrays, null arrays, and
null array elements alongside the existing calling-convention cases.

Co-authored-by: Copilot <[email protected]>
@pavelsavara
pavelsavara merged commit 152ad96 into dotnet:main Oct 27, 2026
75 checks passed
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 12.0-preview1 milestone Oct 28, 2026
@pavelsavara

Copy link
Copy Markdown
Member

/backport to release/11.0

@github-actions

Copy link
Copy Markdown
Contributor

Started backporting to release/11.0 (link to workflow run)

@SimonCropp

Copy link
Copy Markdown
Contributor Author

thanks everyone

@SimonCropp
SimonCropp deleted the mono-unmanagedcallconv-noalloc branch November 2, 2026 22:25
akoeplinger pushed a commit that referenced this pull request Nov 16, 2026
…ating managed objects (#136627)

Fixes Issue #136351 (release/11.0 backport)

main PR #136352 <!-- Link to PR if any that fixed this in
the main branch. -->

Backport of #136352 to release/11.0.

/cc @pavelsavara @SimonCropp

# Description

<!-- Give a brief summary of the issue and how the pull request is
fixing it. -->

Decode `UnmanagedCallConvAttribute` using Mono's existing native-only
attribute decoder rather than constructing managed argument objects
inside the AOT cross-compiler.

The previous decoder allocated managed arrays, including `Type[]`, while
cross-compilation uses target class layouts. For a 64-bit host targeting
32-bit browser-wasm, this can corrupt the compiler's managed heap and
abort publishing with the `sgen-alloc.c:409` assertion (`*p == NULL`).

The fix follows the existing `UnmanagedCallersOnly` and delegate-wrapper
`UnmanagedFunctionPointer` decoding paths. It also handles explicitly
null arrays and null elements without dereferencing them.

# Customer Impact

<!-- What is the impact to customers of not taking this fix? -->

- [x] Customer reported
- [ ] Found internally

Reported in #136351. Blazor WebAssembly applications
cannot publish with `RunAOTCompilation=true` when a retained P/Invoke
has `[UnmanagedCallConv(CallConvs = ...)]`, even when the P/Invoke is
never executed.

This affects real applications using SixLabors.Fonts 3.1+ and,
transitively, ImageSharp.Drawing 3.x. Expected behavior is successful
AOT publishing; actual behavior is a compiler abort and failed publish.
The issue reports reproduction on .NET 11 RC2 and .NET 10.0.13.

The reported workaround requires customers to strip the attribute during
trimming.

# Regression

<!-- Is this fixing a problem that was introduced in the most recent
release, ie., fixing a regression? -->

- [ ] Yes
- [x] No

Unknown. Reproduced on .NET 10.0.13 and .NET 11 RC2; earlier releases
were not tested, and the introducing change has not been identified.

# Testing

<!-- What kind of testing has been done with the fix. -->

Added `EnsureUnmanagedCallConvCompilesInAOT` to Wasm.Build.Tests. It
publishes a Mono browser-wasm application with AOT enabled and retains
six P/Invoke attribute shapes: one convention, two conventions including
`CallConvSuppressGCTransition`, no named arguments, an empty array, a
null array, and an array containing a null element.

Local red/green validation was performed on the original PR before its
final main merge, on Windows x64 targeting browser-wasm in Release:

```powershell
.\build.cmd -bl -os browser -subset mono+libs+packs -c Release /p:RuntimeFlavor=Mono
```

Result: passed; baseline runtime and package build completed with zero
errors.

```powershell
.\build.cmd -bl -subset mono.aotcross -c Release /p:RuntimeFlavor=Mono /p:MonoCrossAOTTargetOS=browser
```

Result: passed for both the unfixed and fixed compiler variants, with
zero warnings or errors.

The following exact filtered test command was run unchanged against both
compiler variants:

```powershell
$env:SKIP_PROJECT_CLEANUP='1'
.\dotnet.cmd build -bl -p:TargetOS=browser -p:TargetArchitecture=wasm -p:RuntimeFlavor=Mono -c Release -t:Test .\src\mono\wasm\Wasm.Build.Tests -p:InstallWorkloadForTesting=false -p:TestUsingWorkloads=true -p:InstallChromeForTests=false -p:XUnitMethodName=Wasm.Build.Tests.PInvokeTableGeneratorTests.EnsureUnmanagedCallConvCompilesInAOT
```

- Without the fix: **1 failed, 0 skipped**, reproducing
`sgen-alloc.c:409`, condition `*p == NULL`, and compiler exit code
`-1073740791`.
- With the fix: **1 passed, 0 failed, 0 skipped**.

Compiler executable hashes were checked against the installed workload
to verify which compiler each run used. Inspection of the actual trimmed
AOT input confirmed that all six P/Invokes and their distinct attribute
encodings survived trimming.

The gap addressed by this regression test is attribute decoding during
cross-compiler wrapper generation; executing a P/Invoke is not required
to trigger the bug. The test validates publishing, not native-call
execution or GC-transition semantics.

These are original-PR validation results, not a local run of this
release/11.0 backport. The backport has not been built or tested
locally.

# Risk

<!-- Please assess the risk of taking this fix. Provide details backing
up your assessment. -->

**Low.** This is a focused replacement of one attribute-decoding path
with an existing decoder already used by neighboring marshalling paths.
There are no public API changes, new decoders, or changes to the GC
allocator.

The affected helper is shared by runtime and AOT wrapper generation, so
the change is not limited to browser-only code. The regression test
covers successful cross-compilation and null/empty inputs;
calling-convention execution semantics and other platforms were not
independently exercised locally.

**IMPORTANT**: If this backport is for a servicing release, please
verify that:

- For .NET 8 and .NET 9: The PR target branch is `release/X.0-staging`,
not `release/X.0`.
- For .NET 10+: The PR target branch is `release/X.0` (no `-staging`
suffix).

Verified: this PR targets `release/11.0`.

# Package authoring no longer needed in .NET 9

IMPORTANT: Starting with .NET 9, you no longer need to edit a NuGet
package's csproj to enable building and bump the version.
Keep in mind that we still need package authoring in .NET 8 and older
versions.

Resolves #136351

> [!NOTE]
> This description was generated by GitHub Copilot.

Co-authored-by: Simon Cropp <[email protected]>
Co-authored-by: Pavel Savara <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

arch-wasm WebAssembly architecture area-Codegen-AOT-mono community-contribution Indicates that the PR has been added by a community member

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[wasm][AOT] mono-aot-cross asserts at sgen-alloc.c:409 on a P/Invoke with [UnmanagedCallConv(CallConvs = ...)]

4 participants