Skip to content

Commit 58f7fbc

Browse files
lewingCopilot
andauthored
JIT: don't fall through from a Wasm callfinally across a try_table end (#134758)
On Wasm, `genCallFinally` omitted the branch to the callfinally continuation whenever it was the lexically next block. When a `try_table` interval ends between the `BBJ_CALLFINALLYRET` and its continuation, codegen emits a validation `unreachable` after the `try_table` `end`, so the fall-through traps at runtime with `RuntimeError: unreachable`. This hit `ManagedWebSocket.<WaitForServerToCloseConnectionAsync>d__64.MoveNext` under browser-wasm R2R. Disassembly showed the normal path calling the finally funclet and then falling into the `try_table` `end`, while other paths to the same continuation used `call finally; br N`. ## Changes - `genCallFinally` now uses `BasicBlock::CanRemoveJumpToTarget`, which already refuses fall-through across a Try/ExnRefWrapper end for `BBJ_ALWAYS` and `BBJ_COND` (#133528). Its assert is widened to accept `BBJ_CALLFINALLYRET`. - A DEBUG check in `fgWasmControlFlow` asserts that every adjacent forward edge that cannot fall through because a Try/ExnRefWrapper ends at its target has an enclosing Block interval, so the explicit branch has a label. - New regression test `JIT/Regression_2/Runtime_134264`. The bug needs an async method ending in a user try/catch/finally whose finally is too large to be cloned; a nested try/finally-in-try/catch variant is included. - Re-enable `WebSocketReceiveErrorMessageTests` on Wasm R2R. ## Validation - `System.Net.WebSockets.Tests`, browser-wasm CoreCLR, trimmed R2R on Chrome: before the fix, reproduces the trap; after, 278 run, 0 failed, including the 4 re-enabled tests. - `Runtime_134264` via `src/tests/run.sh wasm --runcrossgen2tests` (browser): passes with the fix; with the pre-fix JIT it traps with `RuntimeError: unreachable` in `TryCatchFinallyAsync_d__2.MoveNext`. - Checked cross-targeting Wasm JIT: crossgen2 of System.Private.CoreLib and 14 framework assemblies with no asserts. Temporarily disabling block creation for try/catch exits makes the new check fire on both test methods. - `jitformat.py` clean. `JIT/Regression_2` is not yet in the curated WASI runtime-test trees; #133265 adds the WASI R2R lane and should include `-tree:JIT/Regression_2` to cover this test there. Resolves #134264 > [!NOTE] > This PR description was generated with GitHub Copilot. --------- Co-authored-by: Copilot App <[email protected]>
1 parent 238ad22 commit 58f7fbc

6 files changed

Lines changed: 172 additions & 5 deletions

File tree

‎src/coreclr/jit/block.cpp‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -414,15 +414,15 @@ bool BasicBlock::CanRemoveJumpToNext(Compiler* compiler) const
414414
// CanRemoveJumpToTarget: determine if jump to target can be omitted
415415
//
416416
// Arguments:
417-
// target - target of the BBJ_ALWAYS or true/false target of the BBJ_COND block
417+
// target - target of the BBJ_ALWAYS/BBJ_CALLFINALLYRET or true/false target of the BBJ_COND block
418418
// compiler - current compiler instance
419419
//
420420
// Returns:
421421
// true if this block can fall into target
422422
//
423423
bool BasicBlock::CanRemoveJumpToTarget(BasicBlock* target, Compiler* compiler) const
424424
{
425-
assert((KindIs(BBJ_ALWAYS) && (GetTarget() == target)) ||
425+
assert((KindIs(BBJ_ALWAYS, BBJ_CALLFINALLYRET) && (GetTarget() == target)) ||
426426
(KindIs(BBJ_COND) && (TrueTargetIs(target) || FalseTargetIs(target))));
427427
if (!NextIs(target) || IsLastHotBlock(compiler))
428428
{

‎src/coreclr/jit/codegenwasm.cpp‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4162,13 +4162,13 @@ void CodeGen::genCallFinally(BasicBlock* block)
41624162
return;
41634163
}
41644164

4165-
// Branch to the continuation block if it's not the next block.
4165+
// Branch to the continuation block unless we can fall into it.
41664166
assert(block->isBBCallFinallyPair());
41674167
BasicBlock* const callFinallyRet = block->Next();
41684168
assert(callFinallyRet->KindIs(BBJ_CALLFINALLYRET));
41694169
BasicBlock* const continuation = callFinallyRet->GetTarget();
41704170

4171-
if (continuation != callFinallyRet->Next())
4171+
if (!callFinallyRet->CanRemoveJumpToTarget(continuation, m_compiler))
41724172
{
41734173
inst_JMP(EJ_jmp, continuation);
41744174
}

‎src/coreclr/jit/fgwasm.cpp‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2022,6 +2022,61 @@ PhaseStatus Compiler::fgWasmControlFlow()
20222022
}
20232023
}
20242024
}
2025+
2026+
// Verify that an adjacent forward edge that cannot fall through, because a Try or
2027+
// ExnRefWrapper interval ends at its target (see BasicBlock::CanRemoveJumpToTarget),
2028+
// has a plain Block interval enclosing the source and ending at the target, so the
2029+
// explicit branch codegen emits has a label to bind to. For example, a callfinally
2030+
// whose continuation follows the end of a try_table:
2031+
//
2032+
// block ;; Block interval ending at the continuation
2033+
// try_table ...
2034+
// ...
2035+
// call_indirect ;; call the finally
2036+
// br 1 ;; branch to the continuation
2037+
// end ;; end of try_table
2038+
// unreachable ;; fall-through from the try_table would trap here
2039+
// end
2040+
// ... ;; continuation
2041+
//
2042+
for (unsigned cursor = 0; cursor < numBlocks; cursor++)
2043+
{
2044+
BasicBlock* const block = initialLayout[cursor];
2045+
BasicBlock* const next = initialLayout[cursor + 1];
2046+
2047+
bool const fallsToNext = (block->KindIs(BBJ_ALWAYS, BBJ_CALLFINALLYRET) && block->TargetIs(next)) ||
2048+
(block->KindIs(BBJ_COND) && block->FalseTargetIs(next));
2049+
if (!fallsToNext)
2050+
{
2051+
continue;
2052+
}
2053+
2054+
bool endsTryOrWrapper = false;
2055+
bool hasBlockTarget = false;
2056+
for (WasmInterval* const interval : *fgWasmIntervals)
2057+
{
2058+
if (interval->End() != (cursor + 1))
2059+
{
2060+
continue;
2061+
}
2062+
2063+
if (interval->IsTry() || interval->IsExnRefWrapper())
2064+
{
2065+
endsTryOrWrapper = true;
2066+
}
2067+
else if (!interval->IsLoop() && (interval->Start() <= cursor))
2068+
{
2069+
hasBlockTarget = true;
2070+
}
2071+
}
2072+
2073+
if (endsTryOrWrapper && !hasBlockTarget)
2074+
{
2075+
JITDUMP(FMT_BB "[%u] -> " FMT_BB "[%u] crosses a Try/ExnRefWrapper end without a Block target\n",
2076+
block->bbNum, cursor, next->bbNum, cursor + 1);
2077+
assert(!"Wasm fall-through across a Try/ExnRefWrapper end needs a Block target");
2078+
}
2079+
}
20252080
#endif
20262081

20272082
// -----------------------------------------------

‎src/libraries/System.Net.WebSockets/tests/WebSocketReceiveErrorMessageTests.cs‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99

1010
namespace System.Net.WebSockets.Tests
1111
{
12-
[ActiveIssue("https://github.com/dotnet/runtime/issues/134264", typeof(PlatformDetection), nameof(PlatformDetection.IsWasmReadyToRun))]
1312
public class WebSocketReceiveErrorMessageTests
1413
{
1514
// The test WebSocket is created with isServer:false, so received frames must NOT be masked
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
4+
// Regression test for a WebAssembly R2R (crossgen) codegen bug in finally
5+
// calls. When a callfinally's continuation was the lexically next block,
6+
// codegen fell through to it without a branch. If a try_table ended between
7+
// the two, the fall-through landed on the validation `unreachable` emitted
8+
// after the try_table `end` and trapped (RuntimeError: unreachable).
9+
//
10+
// The shape needs a user try/finally that ends the async method (so the
11+
// continuation is outside the state machine's try/catch) and a finally too
12+
// large to be cloned onto the normal path.
13+
//
14+
// Reproduces only under crossgen wasm R2R (TargetOS=browser). Passes trivially
15+
// on all other targets.
16+
17+
using System;
18+
using System.Runtime.CompilerServices;
19+
using System.Threading.Tasks;
20+
using Xunit;
21+
22+
public class Runtime_134264
23+
{
24+
private static int s_value;
25+
26+
[MethodImpl(MethodImplOptions.NoInlining)]
27+
private static void Touch(int value) => s_value += value;
28+
29+
private static async Task TryCatchFinallyAsync(bool enter)
30+
{
31+
bool entered = false;
32+
try
33+
{
34+
if (enter)
35+
{
36+
await Task.CompletedTask;
37+
entered = true;
38+
}
39+
40+
Touch(1);
41+
}
42+
catch (Exception ex)
43+
{
44+
GC.KeepAlive(ex);
45+
Touch(-100);
46+
}
47+
finally
48+
{
49+
if (entered)
50+
{
51+
Touch(1); Touch(2); Touch(3); Touch(4); Touch(5); Touch(6); Touch(7); Touch(8);
52+
Touch(9); Touch(10); Touch(11); Touch(12); Touch(13); Touch(14); Touch(15); Touch(16);
53+
}
54+
55+
Touch(1000);
56+
}
57+
}
58+
59+
private static async Task NestedTryFinallyAsync(bool enter)
60+
{
61+
bool entered = false;
62+
try
63+
{
64+
try
65+
{
66+
if (enter)
67+
{
68+
await Task.CompletedTask;
69+
entered = true;
70+
}
71+
72+
Touch(1);
73+
}
74+
finally
75+
{
76+
if (entered)
77+
{
78+
Touch(1); Touch(2); Touch(3); Touch(4); Touch(5); Touch(6); Touch(7); Touch(8);
79+
Touch(9); Touch(10); Touch(11); Touch(12); Touch(13); Touch(14); Touch(15); Touch(16);
80+
}
81+
82+
Touch(1000);
83+
}
84+
}
85+
catch (Exception ex)
86+
{
87+
GC.KeepAlive(ex);
88+
Touch(-100);
89+
}
90+
}
91+
92+
[Theory]
93+
[InlineData(true, 1137)]
94+
[InlineData(false, 1001)]
95+
public static async Task TestEntryPoint(bool enter, int expected)
96+
{
97+
s_value = 0;
98+
await TryCatchFinallyAsync(enter);
99+
Assert.Equal(expected, s_value);
100+
101+
s_value = 0;
102+
await NestedTryFinallyAsync(enter);
103+
Assert.Equal(expected, s_value);
104+
}
105+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
<PropertyGroup>
3+
<Optimize>True</Optimize>
4+
</PropertyGroup>
5+
<ItemGroup>
6+
<Compile Include="$(MSBuildProjectName).cs" />
7+
</ItemGroup>
8+
</Project>

0 commit comments

Comments
 (0)