Repository navigation
[release/10.0] [mono][interp] Preserve live locals across finally OSR - #135842
Conversation
<!-- --> ## 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: 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. |
|
Tagging subscribers to this area: @vitek-karas, @BrzVlad, @kotlarmilos |
|
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
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, 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 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 (
So #135625 fixes it. For anyone else who hits this, the workaround we're using until a servicing release is to set 11.0 RC3 is also affected, so the release/11.0 backport (#135841) matters too. Thanks! |
|
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! |
|
/ba-g unrelated test failure on coreclr which can't be affected by this mono-only change |
Backport of #135625 to release/10.0
/cc @BrzVlad @rzikm
Customer Impact
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
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.