Skip to content

[release/10.0] [mono][interp] Preserve live locals across finally OSR - #135842

Merged
akoeplinger merged 2 commits into
release/10.0from
backport/pr-135625-to-release/10.0
Nov 16, 2026
Merged

akoeplinger merged 2 commits into
release/10.0from
backport/pr-135625-to-release/10.0

Conversation

@github-actions

@github-actions github-actions Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Backport of #135625 to release/10.0

/cc @BrzVlad @rzikm

Customer Impact

  • Customer reported
  • Found internally

When using mono interpreter (on wasm or iOS targets), tiering up from a finally clause (which could happen if the finally clause is looping) can end up generating incompatible code with the unoptimized version of the method. This means that the optimized and unoptimized code would use different offsets for the same variable value, leading to undefined program behavior, either immediate crashes or silently running managed code with invalid state.

Regression

  • Yes
  • No

While this is not a regression in .net10, in the past users have reported hard to reproduce issues related to mono interpreter optimizations which were mitigated by disabling some optimization via env vars. This fix addresses a rather common scenario so backporting might help reduce friction for users running into issues like this.

Testing

Tested on library suite from our CI that was previously failing without this fix. Added explicit test for this scenario.

Risk

Low. The fix reuses existing infrastructure in the optimization passes to block propagation of values in this particular scenario, where we detect that tiering could happen when calling a finally handler.

<!-- -->

## Summary

Fix Mono interpreter local-value corruption when on-stack replacement
happens inside a `finally` handler.

SSA copy propagation can replace a saved IL local with a temporary at a
different frame offset. A loop in `finally` can tier up the current
frame after that local was saved by unoptimized code. The optimized
continuation then reads the temporary instead of the original local.
This affects both pending return values and locals used after the
handler.

The existing tiering definitions protect regular CFG patchpoints, but EH
blocks are outside the SSA CFG. Reuse `MINT_DEF_TIER_VAR` at
finally-handler continuation markers to preserve the SSA-renamable IL
locals live out of the caller block. Only methods with EH backedge
patchpoints need this additional protection. SSA, tiering, and OSR
remain enabled.

Extend the existing `handlerloop` regression with pending-return and
live-local theories, covering zero, positive, negative, and maximum
integer values. There is no System.Net.Security workaround or test
quarantine.

## Minimized standalone repro

Originally hit on #135096, this
is a minimized version hitting the same failure

`FinallyOsrRepro.csproj`:

```xml
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net11.0</TargetFramework>
    <Optimize>false</Optimize>
  </PropertyGroup>
</Project>
```

`Program.cs`:

```csharp
using System;
using System.Runtime.CompilerServices;
using System.Threading;

internal static class Program
{
    private static int Main()
    {
        int actual = ThroughFinally(42);
        Console.WriteLine($"Expected 42, actual {actual}");
        return actual == 42 ? 0 : 1;
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    private static int ThroughFinally(int value)
    {
        try
        {
            return Identity(value);
        }
        finally
        {
            for (int i = 0; i < 1_000; i++)
            {
                Thread.SpinWait(1);
            }
        }
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    private static int Identity(int value) => value;
}
```

### Run on Linux or Ubuntu WSL

From the `dotnet/runtime` repository root, build a Mono testhost:

```bash
./build.sh mono+libs -rc Release -c Debug -rf Mono -keepnativesymbols
repo="$PWD"
```

Save the two repro files above under `artifacts/tmp/FinallyOsrRepro`,
then run:

```bash
"$repo/.dotnet/dotnet" build \
  "$repo/artifacts/tmp/FinallyOsrRepro/FinallyOsrRepro.csproj" \
  -c Release --disable-build-servers

env -u MONO_INTERPRETER_OPTIONS MONO_ENV_OPTIONS=--interpreter \
  "$repo/artifacts/bin/testhost/net11.0-linux-Debug-x64/dotnet" \
  exec --roll-forward Major \
  "$repo/artifacts/tmp/FinallyOsrRepro/bin/Release/net11.0/FinallyOsrRepro.dll"
```

`--roll-forward Major` accommodates the built testhost's internal
framework version, without depending on another test project's
runtimeconfig.

On the unfixed runtime this printed `Expected 42, actual 1` and exited
with code 1 in five of five fresh processes. With this fix it printed
`Expected 42, actual 42` and exited with code 0 in five of five
processes. The wrong value is not part of the repro's contract; the
assertion is that it must remain 42.

Ordinary SDK `dotnet run` uses CoreCLR, not this Mono interpreter. For a
Mono JIT control, use the same built host and DLL but replace the
environment prefix with `env -u MONO_ENV_OPTIONS -u
MONO_INTERPRETER_OPTIONS`.

## Validation

Linux x64, Ubuntu 25.10 under WSL; Release Mono and Debug libraries,
matching the failing CI leg's runtime/library configuration.

The incremental native build passed with zero warnings/errors:

```bash
./build.sh mono+libs.pretest -rc Release -c Debug -rf Mono \
  -keepnativesymbols --build \
  /p:EnableSourceControlManagerQueries=false \
  /p:EnableSourceLink=false \
  /p:SourceRevisionId=0fbca90b2ea9b25ca7b876f70cf67719c339a4d4
```

The source-control flags are local accommodations for the
Windows-created Git worktree used from WSL. An existing successful
`mono+libs` baseline was reused.

Build and run the repository regression:

```bash
./build.sh clr.hosts -c Release -keepnativesymbols
./src/tests/build.sh mono release -test:JIT/opt/OSR/handlerloop.csproj \
  /p:LibrariesConfiguration=Debug
./src/tests/build.sh mono release -GenerateLayoutOnly \
  /p:LibrariesConfiguration=Debug

CORE_ROOT="$PWD/artifacts/tests/coreclr/linux.x64.Release/Tests/Core_Root"
env -u MONO_INTERPRETER_OPTIONS MONO_ENV_OPTIONS=--interpreter \
  bash artifacts/tests/coreclr/linux.x64.Release/JIT/opt/OSR/handlerloop/handlerloop.sh \
  -coreroot="$CORE_ROOT"
```

These builds also used the local source-control flag suffix above.
Generated `.sh` wrappers had their CRLF line endings normalized for the
WSL checkout.

- **Fail before / pass after:** the identical `handlerloop.dll` fails
with an assertion on the preserved unfixed Mono interpreter (`0` becomes
`999`) and passes on the fixed interpreter. Mono JIT also passes.
Separately invoking all eight new theory inputs confirms both new paths
fail independently on baseline and all eight pass with the fix.
- **Original boolean repro:** three fresh runs of four million calls
each passed on the final fixed default interpreter, without disabling
SSA or tiering.
- **System.Net.Security functional suite:** 5,100 total, 5,092 passed, 0
failed, 8 existing environment skips, 0 errors on the final patch; two
xUnit collection threads. Three earlier complete repeats also passed
before narrowing the protection to EH-patchpoint methods.
- **OSR subtree:** `./src/tests/build.sh mono release -tree:JIT/opt/OSR
-priority1 /p:LibrariesConfiguration=Debug` built successfully. Ran
every generated standalone `.sh` wrapper with
`MONO_ENV_OPTIONS=--interpreter` and the fixed `CORE_ROOT`: **38 passed,
0 failed**, including the handler regression and regular-loop/try-region
coverage.

The full security suite was launched from its test-output directory so
its certificate test data resolves correctly:

```bash
repo="$PWD"
runner="$HOME/.nuget/packages/microsoft.dotnet.xunitconsolerunner/2.9.3-beta.26471.108/tools/net/xunit.console.dll"
cd "$repo/artifacts/bin/System.Net.Security.Tests/Debug/net11.0-unix"
env -u MONO_INTERPRETER_OPTIONS -u DOTNET_STARTUP_HOOKS \
  MONO_ENV_OPTIONS=--interpreter XUNIT_HIDE_PASSING_OUTPUT_DIAGNOSTICS=1 \
  "$repo/artifacts/bin/testhost/net11.0-linux-Debug-x64/dotnet" exec \
  --runtimeconfig System.Net.Security.Tests.runtimeconfig.json \
  --depsfile System.Net.Security.Tests.deps.json \
  "$runner" System.Net.Security.Tests.dll \
  -nologo -nocolor -notrait category=OuterLoop -notrait category=failing \
  -maxthreads 2
```

### Performance check

Local BenchmarkDotNet 0.16.0-preview.2, in-process/no-emit toolchain,
default Mono interpreter tiering, CPU affinity to logical CPU 2, five
warmups and ten measured iterations. Baseline and fixed hosts use the
same managed libraries.

| Kernel | Baseline mean (StdDev), ns | Fixed mean (StdDev), ns |
| --- | ---: | ---: |
| Plain return | 24.98 (0.51) | 24.34 (0.45) |
| Return with non-looping `finally` | 35.73 (0.21) | 43.12 (9.40) |
| Return with four cleanup iterations | 121.81 (24.38) | 105.16 (3.85) |

The WSL measurements are noisy and do not support a reliable throughput
gain/regression claim. A separate before/after codegen comparison with
`MONO_INTERPRETER_OPTIONS=-tiering,-inline` confirmed identical bytecode
for the plain-return and non-looping-finally kernels (three and eight
instructions respectively). The EH-patchpoint guard avoids adding
preservation barriers to ordinary finally methods. The barrier itself is
compile-time-only and emits no instruction.

Windows, macOS, ARM64, browser, and mobile execution have not been
tested locally.

Resolves #135096

> [!NOTE]
> This PR and its description were prepared with GitHub Copilot.

---------

Copilot-Session: 0a9ce4db-571d-41e6-9c33-6c78e8a37c7f
@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: @vitek-karas, @BrzVlad, @kotlarmilos
See info in area-owners.md if you want to be subscribed.

@BrzVlad BrzVlad added Servicing-consider Issue for next servicing release review Servicing-approved Approved for servicing release and removed Servicing-consider Issue for next servicing release review labels Oct 15, 2026
@avdynut

avdynut commented Oct 29, 2026 •

Copy link
Copy Markdown

We hit this in production on .NET 10 Blazor WebAssembly, in an OpenSilver app. A fix in a 10.0 servicing release would help us.

Symptom. OpenSilver passes browser input events to .NET through a synchronous [JSInvokable] method that returns object. Inside it, CallMethod does try { return callback.DynamicInvoke(args); } finally { foreach (var a in args.OfType<IDisposable>()) a.Dispose(); }. The delegate returns void, but sometimes the value that comes back is not null. It's a stale reference to an object the callee used, for example a property-name string or a RuntimeType. Blazor then serializes it and fails with:

  • ArgumentNullException: Value cannot be null. (Parameter 'key') from JsonSerializerOptions.CachingContext.GetOrAddCacheEntry, because GetType() on the stale object returns null; or
  • RuntimeError: memory access out of bounds.

It happened in about 6 of 10 runs of one UI test, and small code changes in that method made it disappear, which made it hard to track down.

Minimal repro (Blazor WebAssembly, dotnet new blazorwasm --empty). It fails on every page load on affected runtimes:

public static class Repro
{
    private static readonly object Expected = new();
    private static object? _sink;

    [MethodImpl(MethodImplOptions.NoInlining)] private static object GetExpected() => Expected;
    [MethodImpl(MethodImplOptions.NoInlining)] private static void Touch(object o) => _sink = o;
    private static void VoidHandler(string s) => _sink = s;

    [MethodImpl(MethodImplOptions.NoInlining)]
    private static object ReturnValueFromTry(object[] items)
    {
        try { return GetExpected(); }
        finally { foreach (object item in items) Touch(item); }
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    private static object? DynamicInvokeVoid(object[] items)
    {
        Delegate d = new Action<string>(VoidHandler);
        try { return d.DynamicInvoke("x"); }
        finally { foreach (object item in items) Touch(item); }
    }

    public static string Run()
    {
        var items = Enumerable.Range(0, 1500).Select(i => (object)("item " + i)).ToArray();
        bool valueOk = ReferenceEquals(ReturnValueFromTry(items), Expected);
        bool voidOk = DynamicInvokeVoid(items) is null;
        return $"value: {(valueOk ? "PASS" : "FAIL")}, void DynamicInvoke: {(voidOk ? "PASS" : "FAIL")}";
    }
}

Call Repro.Run() from OnInitialized in Home.razor and print the result. With 500 items, below the 1000-hit tier-up threshold, both checks pass. Calling GetType() or ToString() on the wrong value traps with "memory access out of bounds".

Results. All are Release publishes running in Chrome. The .NET 12 rows use the same app, SDK and Blazor packages; only the browser runtime pack differs (-p:RuntimeFrameworkVersion=...).

Runtime (Microsoft.NETCore.App.Runtime.Mono.browser-wasm) Contains #135625 Result
10.0.14 (SDK 10.0.403) no FAIL on every load
11.0.0-rc.3.26522.148 no FAIL on every load
12.0.0-alpha.1.26513.120 (runtime 0d73c1f) no FAIL on every load
12.0.0-alpha.1.26528.120 (runtime 6dbcdc1) yes PASS on every load
any of the above with MONO_INTERPRETER_OPTIONS=-ssa n/a PASS

So #135625 fixes it. For anyone else who hits this, the workaround we're using until a servicing release is to set MONO_INTERPRETER_OPTIONS=-ssa, via Blazor.start({ configureRuntime: b => b.withEnvironmentVariable('MONO_INTERPRETER_OPTIONS', '-ssa') }).

11.0 RC3 is also affected, so the release/11.0 backport (#135841) matters too.

Thanks!

@ViveliDuCh

Copy link
Copy Markdown
Member

Hi,

the code complete date for 10.0.16 (the December 2026 release) is Monday 16 November. Make sure to merge this PR on that date at the latest, or it won't make it into that release.

As a reminder, if this is a product change, you also need Tactics approval before merging this PR (test-only or infra-only changes don't require Tactics approval).

Happy to help with the merge if needed!

@akoeplinger

Copy link
Copy Markdown
Member

/ba-g unrelated test failure on coreclr which can't be affected by this mono-only change

@akoeplinger
akoeplinger merged commit 6c54564 into release/10.0 Nov 16, 2026
118 of 120 checks passed
@akoeplinger
akoeplinger deleted the backport/pr-135625-to-release/10.0 branch November 16, 2026 17:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants