Skip to content

Enable normal-completion finally emission for NativeAOT Wasm - #135666

Merged
MichalStrehovsky merged 1 commit into
dotnet:mainfrom
MichalStrehovsky:finally
Oct 13, 2026
Merged

MichalStrehovsky merged 1 commit into
dotnet:mainfrom
MichalStrehovsky:finally

Conversation

@MichalStrehovsky

Copy link
Copy Markdown
Member

Classify funclets from the JIT's EH clauses during shared code publication and retain the resulting array in both NativeAOT and ReadyToRun method nodes. This preserves clause order and finally/fault distinctions without decoding serialized EH records.

Translate parent-method-plus-funclet-ordinal references into relocations to named funclet symbols so that the linker can assign table slots independently. Keep EH information and dependencies intact.

Repro

Apply the following patch to src\coreclr\tools\aot\ILCompiler\reproZero\zerosharp.cs. It exercises ordinary and generic function pointers, a generic dictionary lookup, and normal completion through finally without throwing.

diff --git a/src/coreclr/tools/aot/ILCompiler/reproZero/zerosharp.cs b/src/coreclr/tools/aot/ILCompiler/reproZero/zerosharp.cs
index a7d8d9dad84..3d04f0099f7 100644
--- a/src/coreclr/tools/aot/ILCompiler/reproZero/zerosharp.cs
+++ b/src/coreclr/tools/aot/ILCompiler/reproZero/zerosharp.cs
@@ -3,6 +3,7 @@

 using System;
 using System.Runtime;
+using System.Runtime.InteropServices;

 #region A couple very basic things
 namespace System
@@ -77,6 +78,13 @@ public sealed class DllImportAttribute : Attribute
     {
         public DllImportAttribute(string dllName) { }
     }
+
+    sealed class SuppressGCTransitionAttribute : Attribute { }
+
+    public sealed class UnmanagedCallersOnlyAttribute : Attribute
+    {
+        public string EntryPoint;
+    }
 }
 #endregion

@@ -113,6 +121,9 @@ static void RhpPInvokeReturn(IntPtr frame) { }
         [RuntimeExport("RhpPInvokeReturn")]
         static void RhpPInvokeReturn(IntPtr frame) { }

+        [RuntimeExport("RhpGcPoll")]
+        static void RhpGcPoll() { }
+
         [RuntimeExport("RhpFallbackFailFast")]
         static void RhpFallbackFailFast() { while (true) ; }
     }
@@ -121,8 +132,37 @@ static void RhpPInvokeReturn(IntPtr frame) { }

 unsafe class Program
 {
-    static int Main()
+    [DllImport("*"), SuppressGCTransition]
+    static extern unsafe int puts(byte* str);
+
+    [UnmanagedCallersOnly(EntryPoint = "__main_argc_argv")]
+    static int NativeMain(int argc, byte** argv)
+    {
+        Main();
+        return 0;
+    }
+
+    static unsafe void Main()
+    {
+        try
+        {
+            Call(&Print);
+        }
+        finally
+        {
+            Call(&PrintGeneric<string>);
+        }
+    }
+
+    static void Call(delegate*<void> d) => d();
+
+    static void PrintGeneric<T>() => PrintGenericCore<T>();
+
+    static void PrintGenericCore<T>() => Print();
+
+    static unsafe void Print()
     {
-        return 42;
+        int abc = 'H' | 'i' << 8;
+        puts((byte*)&abc);
     }
 }

Build and run

Run from the repository root on Windows with the native build prerequisites, LLVM/Clang, Wasmtime, and a WASI preview1 sysroot available. Adjust the LLVM and sysroot paths for the local installation.

Build the Checked Wasm JIT/compiler, refresh managed ILC and crossgen2, and build the runtime-less repro:

.\src\coreclr\build-runtime.cmd -checked -x64 -component wasmjit
if ($LASTEXITCODE -ne 0) { throw 'Wasm JIT build failed.' }

.\dotnet.cmd build src\coreclr\tools\aot\ILCompiler\ILCompiler.csproj -c Checked
if ($LASTEXITCODE -ne 0) { throw 'ILC build failed.' }

.\dotnet.cmd build src\coreclr\tools\aot\crossgen2\crossgen2.csproj -c Checked
if ($LASTEXITCODE -ne 0) { throw 'Crossgen2 build failed.' }

.\dotnet.cmd build src\coreclr\tools\aot\ILCompiler\reproZero\reproZero.csproj `
    -c Debug -p:CoreCLRConfiguration=Checked -p:IsSourceProject=false
if ($LASTEXITCODE -ne 0) { throw 'Repro IL build failed.' }

Compile to a relocatable object, link with WASI libc, and execute:

$llvm = 'C:\Programs\clang\bin'
$sysroot = Join-Path $PWD 'artifacts\tmp\nativeaot-wasi\wasi-sysroot-34.0'
$out = Join-Path $PWD 'artifacts\bin\repro\x64\Debug'
New-Item -ItemType Directory -Force $out | Out-Null

& .\.dotnet\dotnet.exe `
    .\artifacts\bin\coreclr\windows.x64.Checked\ilc\ilc.dll `
    --targetarch:wasm --targetos:wasi `
    .\artifacts\bin\reproZero\x64\Debug\reproZero.dll `
    "-o:$out\repro.obj" --systemmodule:reproZero `
    -O --noscan --codegenopt:JitMinOpts=1
if ($LASTEXITCODE -ne 0) { throw 'ILC compilation failed.' }

& "$llvm\clang.exe" --target=wasm32-wasip1 "--sysroot=$sysroot" `
    -nodefaultlibs "$out\repro.obj" -lc -o "$out\reproZero.wasm"
if ($LASTEXITCODE -ne 0) { throw 'WASI link failed.' }

wasmtime run "$out\reproZero.wasm"
if ($LASTEXITCODE -ne 0) { throw 'WASI execution failed.' }

Expected output is two lines of Hi and exit code 0. The x64 directory is the host/project output convention; the generated program targets wasm32. The repro uses a minimal system module, not target CoreLib or a full runtime. Managed throwing and exceptional unwinding are outside this change's scope.

Classify funclets from the JIT's EH clauses during shared code publication
and retain the resulting array in both NativeAOT and ReadyToRun method
nodes. This preserves clause order and finally/fault distinctions without
decoding serialized EH records.

Translate parent-method-plus-funclet-ordinal references into relocations
to named funclet symbols so that the linker can assign table slots
independently. Keep EH information and dependencies intact.

Repro
-----

Apply the following patch to src\coreclr\tools\aot\ILCompiler\reproZero\zerosharp.cs.
It exercises ordinary and generic function pointers, a generic dictionary
lookup, and normal completion through finally without throwing.

```diff
diff --git a/src/coreclr/tools/aot/ILCompiler/reproZero/zerosharp.cs b/src/coreclr/tools/aot/ILCompiler/reproZero/zerosharp.cs
index a7d8d9d..3d04f0099f7 100644
--- a/src/coreclr/tools/aot/ILCompiler/reproZero/zerosharp.cs
+++ b/src/coreclr/tools/aot/ILCompiler/reproZero/zerosharp.cs
@@ -3,6 +3,7 @@

 using System;
 using System.Runtime;
+using System.Runtime.InteropServices;

 #region A couple very basic things
 namespace System
@@ -77,6 +78,13 @@ public sealed class DllImportAttribute : Attribute
     {
         public DllImportAttribute(string dllName) { }
     }
+
+    sealed class SuppressGCTransitionAttribute : Attribute { }
+
+    public sealed class UnmanagedCallersOnlyAttribute : Attribute
+    {
+        public string EntryPoint;
+    }
 }
 #endregion

@@ -113,6 +121,9 @@ static void RhpPInvokeReturn(IntPtr frame) { }
         [RuntimeExport("RhpPInvokeReturn")]
         static void RhpPInvokeReturn(IntPtr frame) { }

+        [RuntimeExport("RhpGcPoll")]
+        static void RhpGcPoll() { }
+
         [RuntimeExport("RhpFallbackFailFast")]
         static void RhpFallbackFailFast() { while (true) ; }
     }
@@ -121,8 +132,37 @@ static void RhpPInvokeReturn(IntPtr frame) { }

 unsafe class Program
 {
-    static int Main()
+    [DllImport("*"), SuppressGCTransition]
+    static extern unsafe int puts(byte* str);
+
+    [UnmanagedCallersOnly(EntryPoint = "__main_argc_argv")]
+    static int NativeMain(int argc, byte** argv)
+    {
+        Main();
+        return 0;
+    }
+
+    static unsafe void Main()
+    {
+        try
+        {
+            Call(&Print);
+        }
+        finally
+        {
+            Call(&PrintGeneric<string>);
+        }
+    }
+
+    static void Call(delegate*<void> d) => d();
+
+    static void PrintGeneric<T>() => PrintGenericCore<T>();
+
+    static void PrintGenericCore<T>() => Print();
+
+    static unsafe void Print()
     {
-        return 42;
+        int abc = 'H' | 'i' << 8;
+        puts((byte*)&abc);
     }
 }
```

Build and run
-------------

Run from the repository root on Windows with the native build prerequisites,
LLVM/Clang, Wasmtime, and a WASI preview1 sysroot available. Adjust the LLVM
and sysroot paths for the local installation.

Build the Checked Wasm JIT/compiler, refresh managed ILC and crossgen2,
and build the runtime-less repro:

```powershell
.\src\coreclr\build-runtime.cmd -checked -x64 -component wasmjit
if ($LASTEXITCODE -ne 0) { throw 'Wasm JIT build failed.' }

.\dotnet.cmd build src\coreclr\tools\aot\ILCompiler\ILCompiler.csproj -c Checked
if ($LASTEXITCODE -ne 0) { throw 'ILC build failed.' }

.\dotnet.cmd build src\coreclr\tools\aot\crossgen2\crossgen2.csproj -c Checked
if ($LASTEXITCODE -ne 0) { throw 'Crossgen2 build failed.' }

.\dotnet.cmd build src\coreclr\tools\aot\ILCompiler\reproZero\reproZero.csproj `
    -c Debug -p:CoreCLRConfiguration=Checked -p:IsSourceProject=false
if ($LASTEXITCODE -ne 0) { throw 'Repro IL build failed.' }
```

Compile to a relocatable object, link with WASI libc, and execute:

```powershell
$llvm = 'C:\Programs\clang\bin'
$sysroot = Join-Path $PWD 'artifacts\tmp\nativeaot-wasi\wasi-sysroot-34.0'
$out = Join-Path $PWD 'artifacts\bin\repro\x64\Debug'
New-Item -ItemType Directory -Force $out | Out-Null

& .\.dotnet\dotnet.exe `
    .\artifacts\bin\coreclr\windows.x64.Checked\ilc\ilc.dll `
    --targetarch:wasm --targetos:wasi `
    .\artifacts\bin\reproZero\x64\Debug\reproZero.dll `
    "-o:$out\repro.obj" --systemmodule:reproZero `
    -O --noscan --codegenopt:JitMinOpts=1
if ($LASTEXITCODE -ne 0) { throw 'ILC compilation failed.' }

& "$llvm\clang.exe" --target=wasm32-wasip1 "--sysroot=$sysroot" `
    -nodefaultlibs "$out\repro.obj" -lc -o "$out\reproZero.wasm"
if ($LASTEXITCODE -ne 0) { throw 'WASI link failed.' }

wasmtime run "$out\reproZero.wasm"
if ($LASTEXITCODE -ne 0) { throw 'WASI execution failed.' }
```

Expected output is two lines of Hi and exit code 0. The x64 directory is
the host/project output convention; the generated program targets wasm32.
The repro uses a minimal system module, not target CoreLib or a full runtime.
Managed throwing and exceptional unwinding are outside this change's scope.

Co-authored-by: Copilot <[email protected]>
Copilot-Session: 945908e0-da5c-41a7-8a58-6d39d9fadd25
@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.

@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.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

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

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

The new relocatable NativeAOT Wasm finally path lacks an automated regression test.

1 open finding
What changed in this PR

Enables NativeAOT Wasm normal completion through finally funclets by preserving funclet metadata and emitting linker-safe relocations.

Changes:

  • Retains JIT-derived funclet kinds in NativeAOT and ReadyToRun nodes.
  • Converts parent-plus-ordinal references into named funclet relocations.
  • Centralizes Wasm funclet symbol naming.
File Description
CorInfoImpl.cs Classifies and publishes Wasm funclet kinds.
WasmRelocatableObjectWriter.cs Rewrites funclet relocations to named symbols.
WasmObjectWriter.cs Centralizes funclet naming and updates parameter comments.
MethodCodeNode.cs Stores NativeAOT funclet metadata.
MethodWithGCInfo.cs Stores ReadyToRun funclet metadata directly.

🧠 Review effort: Balanced

@jtschuster jtschuster left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the inline explanations, it made it much easier to review.

@MichalStrehovsky
MichalStrehovsky merged commit 00cc051 into dotnet:main Oct 13, 2026
113 checks passed
@MichalStrehovsky
MichalStrehovsky deleted the finally branch October 13, 2026 23:28
@MichalStrehovsky MichalStrehovsky added the arch-wasm WebAssembly architecture label Oct 13, 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.

@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 12.0-preview1 milestone Oct 14, 2026
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 14, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

arch-wasm WebAssembly architecture area-NativeAOT-coreclr

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants