Skip to content

Refresh stale callee-saved registers in ProcessCLRException's second pass - #138244

Open
pcshrosbree wants to merge 3 commits into
dotnet:mainfrom
pcshrosbree:fix/eh-second-pass-callee-saved
Open

pcshrosbree wants to merge 3 commits into
dotnet:mainfrom
pcshrosbree:fix/eh-second-pass-callee-saved

Conversation

@pcshrosbree

Copy link
Copy Markdown
Contributor

TL;DR: On Windows x64 and arm64, handling a thread abort or an exception raised in the runtime's native code can use stale object references after a compacting GC, so the process crashes or reads corrupted objects (#137606). This change refreshes the affected callee-saved registers from the explicit Frame the GC keeps current, in one runtime file, with regression tests. Could a maintainer please run the Windows x64 and arm64 legs of the three CI pipelines listed under Tests, which I cannot trigger?

Three evidence words are used: "measured" means seen in a run, "read" means read from source or a listing, and "inferred" means reasoned from what was measured or read, without being seen directly.

Cause and origin

The second pass pops the explicit Frames below the target and fills a SoftwareExceptionFrame from pContextRecord, the OS unwinder's copy of the context. A compacting GC before the fill updates the Frame, not that copy. My diagnosis comment on #137606 gives the sequence.

Three routes reach this code: the abort route (an asynchronous abort) and two call routes, the interface-cast route and the prestub route. The table under Tests names them.

First seen in 11.0. The fill is traced to #130321 (read), which first shipped in 11.0 preview 7; no .NET 10 release contains it (read from the release tags: no v10 tag contains its commit).

Fix

In the second pass, the handler first looks for a register-reporting explicit Frame below the target whose SP and IP (stack and instruction pointers) equal the target's, skipping active InlinedCallFrames. If one matches, it copies the callee-saved registers through that Frame's context pointers. That covers both call routes and most aborts. No Frame matches when an abort is redirected onto an epilog's first instruction: the OS gives that frame no handler and dispatches its caller. The evidence for each platform is under "The miss condition" below. If no Frame matches, the handler unwinds managed frames from the nearest register-reporting explicit Frame up to the target's SP, and refreshes only on an exact landing. Otherwise it logs a miss and changes nothing. The change is one file in the runtime, exceptionhandling.cpp, for Windows x64 and arm64 only.

The refresh runs on every second-pass call of ProcessCLRException that reaches managed exception dispatch. Each such call zeroes a register display, and for each register-reporting Frame it checks, copies the context into the register display and makes a virtual call to the Frame. The register display takes about 3 KB of stack on x64 and about 2.4 KB on arm64, in a function kept out of ProcessCLRException's own frame. Its performance was not measured.

Tests

The tests are in the GitHub_137606 regression test folder. Fails-before is on main 8fef9c34678b without the fix. Main's failures are confirmed on clean Release builds of that commit on both platforms. The source of each of the "Results, per test and platform" table's own main builds is given under "How this was produced" (on x64, that build has no recorded commit). A test that never fails on main is not included.

Route How the thread reaches the second pass Tests
abort route an asynchronous abort, by redirect or hijack AbortThroughRedirect, AbortThroughHijack (detect by crash only, by design); AbortAtEpilogStart
interface-cast route a throw from IDynamicInterfaceCastable resolution DynamicInterfaceCastableThrows (validates twelve references after the throw)
prestub route a throw from the prestub (a failed JIT) FailingJitWithForcedCollections (validates after the throw)

On main, each test fails under at least one of three conditions: run alone, four at once, or a Release build under GCStress=0x3. With this change, no counted run failed on either platform. The tables, the stress-leg analysis and the runs of existing tests are in the collapsed sections below.

The three CI pipelines are runtime-coreclr gcstress0x3-gcstress0xc, runtime-coreclr gcstress-extra and runtime-coreclr outerloop, each on its Windows x64 and arm64 legs. The new tests are priority 1, and the default PR checks run only priority-0 tests (read), so the default checks do not run them on any platform; the outerloop pipeline does.

Limits

  • A rude abort at a funclet's epilog start is declined with a logged miss (read; not run).
  • Debugger function evaluation: a FuncEvalFrame without a hijack leaves the register display unchanged, which gives a logged miss (read, not end to end; not run).
  • Every unwound refresh observed on the fix was a single frame (10,543 of 10,543 on this change: 9,202 on x64, 1,341 on arm64). Multi-step unwinds are therefore not exercised. On x64 the OS cannot skip more than one managed frame (read); on arm64 the same is expected but rests on an assumption about how the OS finds a caller after a call. This count covers four run sets; later runs on this change are not included in it.
  • The unwind fallback declines a frame in interpreted code, which gives a logged miss (read).
  • On x64, the fallback's unwind passes Windows' RtlVirtualUnwind a plain copy of the context. If that copy kept the extended-state flag without its area, I assume the unwinder does not read the area; Windows' unwinder is not part of the dotnet/runtime tree. The redirect Frames clear the flag (read). In every run whose refresh source could be read, the source of each fallback was a redirect Frame; runs that logged no source are not covered (measured).
  • Of the 13 Frame types the fix accepts as a source for the refresh, runs on this change used five: RedirectedThreadFrame, ResumableFrame, PrestubMethodFrame and StubDispatchFrame, and HijackFrame on arm64 and on Windows x64 with shadow stacks off (measured; on Windows x64 with shadow stacks off, read from its off-machine summary). In the runs that logged the source of each refresh, no other type appeared. Two runs on x64 that logged a source could not be read in full, and four runs on arm64 have incomplete logs; no other type appeared in the parts read. That the GC's own stack walk uses and writes back the register slots of every type the fix's filter accepts is read from source only, at the base commit. A comparison of the register locations against the GC's own stack walk was made on both machines; it is not cited because its review is not finished.
  • The refresh assumes that the storage it reads is still valid at that point: the register storage the Frame points to and, after an unwind, the stack of the managed frames it unwound through. In runs of this PR's own build (read) where the five types above were the source, the tests passed (measured). On Windows x64, with shadow stacks off, those passes were read from a summary kept off the machine (read). Among this PR's tests, ResumableFrame (on x64 only) and HijackFrame were each a source only in the two abort tests (counts measured; attribution read from the runs' test lists). That statement about ResumableFrame and HijackFrame uses only runs whose refresh sources can be attributed to one test, or to a run of only the two abort tests. Those two tests detect by crash (read), so for those refreshes a pass shows only that no crash followed. For the other types, and for how long each Frame's storage stays valid, I rely on inference from reading the source, which does not cover every case.
  • On arm64, the refresh copies the frame pointer (x29) with x19-x28, although the GC's stack decoder classes x29 as a scratch register there (read). In 20 runs of AbortAtEpilogStart under GCStress=0x3 on this change's build, 4,000 refreshes were examined: 1,257 changed at least one of x19-x28, and none changed x29 (measured). This covers one test, on arm64, under GCStress=0x3. It shows that x29 was not changed in those refreshes, not that a refresh can never change it.
  • Under GC stress, abort-route tests may complete only one abort within their budget (seen on arm64): a test stops once 60 s have passed, provided one abort has completed (read).
  • The path used when the special user-mode APC (asynchronous procedure call) is unavailable was not run.
  • The ReadyToRun-only routes (DynamicHelperFrame, ExternalMethodFrame) were read only, not run.
  • AbortAtEpilogStart needs fast tail calls. DOTNET_FastTailCalls=0 declines them (read); the test then still runs but, by inference, tests an ordinary abort, not the epilog start.
  • On the Windows x64 and arm64 builds this change covers, the following applies when a thread reaches exception dispatch with a profiler filter context set. Each code lookup on such a thread that reads the scan flags (ExecutionManager::GetScanFlags) while the context is set takes the code-range reader-lock path. Main already makes such a lookup at the handler's entry on every call that reaches this code, and in its exception stack walk (read); the fallback adds lookups of the same kind earlier in the same dispatch. How a thread can be in that state was not determined: one possible way, not shown to be reachable, is a profiler resuming a runtime suspension while another of its threads is taking a stack snapshot (inferred; not run).
  • The tests detect the defect only while the JIT keeps each holder's objects in callee-saved registers across the throwing call. That was read from method listings of these tests on both platforms, at default settings; nothing in the tests checks it, so a JIT change could make a test pass without exercising the defect.
  • The tests were not run on Windows x86. The fix is not compiled there and the test projects do not exclude x86, so the runtime-coreclr outerloop pipeline's x86 legs (read) run them against the unchanged second pass; whether the defect occurs on x86 was not examined. If they fail there, I can exclude x86 in the test projects.

Alternatives considered

  • Exact match plus deferring the abort at an epilog-start PC (program counter) (not built, reviewed or run). It would cover an abort redirected where the OS gives no handler, including the rude-abort case. It would not cover any other route, and has no fallback if its test and the OS disagree, so where this change logs a miss it would leave a stale register silently (inferred).
  • Exact match with a stack-walk fallback (considered, not built): the same exact match with a StackFrameIterator walk as the fallback. It would cover what this change covers without listing Frame types, at the cost of a full stack walk inside the OS's second pass.
  • Padding the APC stub (x64 Windows: ApcActivationCallbackStub's call sits directly before its epilog, so its exception handler is never called #138240): on x64, one nop after ApcActivationCallbackStub's call lets its existing handler run, which removed the misses on one test (0 of 14,400 aborts missed with the nop, against 1,139 of 14,200 without it, measured), but it does nothing on arm64 and does not close the defect (inferred). Whether the nop alone stops the abort route failing on main was not measured.
Results, per test and platform

Each entry gives failed runs of counted runs, first on main and then on this change. Test sizing describes the default-settings conditions. Intervals are 95 % Wilson score intervals.

Test Platform Run alone: main / fix Four at once: main / fix GCStress=0x3: main / fix
AbortThroughRedirect x64 0 of 455 (0.0-0.8 %) / 0 of 455 (0.0-0.8 %) 20 of 347 (3.8-8.7 %; all by crash) / 0 of 347 (0.0-1.1 %) 30 of 30 (88.6-100.0 %; all by crash) / 0 of 30 (0.0-11.4 %)
AbortThroughRedirect arm64 0 of 100 (0.0-3.7 %) / 0 of 100 (0.0-3.7 %) 4 of 455 (0.3-2.2 %; all by crash) / 0 of 455 (0.0-0.8 %) 7 of 19 (19.1-59.0 %; all by crash; 11 void: runs that passed with 1 abort, under the floor of 2) / 0 of 27 (0.0-12.5 %; 12 void, 1 timed out; the 60-min window ended 3 counted passes short of 30)
AbortThroughHijack x64 0 of 455 (0.0-0.8 %) / 0 of 455 (0.0-0.8 %) 17 of 455 (2.3-5.9 %; all by crash) / 0 of 455 (0.0-0.8 %) 30 of 30 (88.6-100.0 %; all by crash) / 0 of 30 (0.0-11.4 %)
AbortThroughHijack arm64 0 of 100 (0.0-3.7 %) / 0 of 100 (0.0-3.7 %) 1 of 455 (0.0-1.2 %; all by crash) / 0 of 455 (0.0-0.8 %) 26 of 30 (70.3-94.7 %; all by crash) / 0 of 24 (0.0-13.8 %; 14 void, 3 timed out; the 60-min window ended 6 counted passes short of 30)
AbortAtEpilogStart x64 7 of 455 (0.7-3.1 %; 2 by validation, 5 by crash) / 0 of 455 (0.0-0.8 %) 60 of 570 (8.3-13.3 %; 4 by validation, 56 by crash) / 0 of 538 (0.0-0.7 %) 30 of 30 (88.6-100.0 %; all by crash) / 0 of 30 (0.0-11.4 %)
AbortAtEpilogStart arm64 0 of 100 (0.0-3.7 %) / 0 of 100 (0.0-3.7 %) 51 of 455 (8.6-14.4 %; 14 by validation, 37 by crash) / 0 of 455 (0.0-0.8 %) 30 of 30 (88.6-100.0 %; all by crash) / 0 of 25 (0.0-13.3 %; 21 void, 1 run's outcome not recorded; the 60-min window ended 5 counted passes short of 30)
DynamicInterfaceCastableThrows x64 20 of 410 (3.2-7.4 %; all by validation) / 0 of 410 (0.0-0.9 %) 11 of 455 (1.4-4.3 %; all by validation) / 0 of 455 (0.0-0.8 %) 0 of 30 (0.0-11.4 %) / 0 of 30 (0.0-11.4 %)
DynamicInterfaceCastableThrows arm64 20 of 31 (46.9-78.9 %; 12 by validation, 8 by crash) / 0 of 100 (0.0-3.7 %) 23 of 23 (85.7-100.0 %; 18 by validation, 5 by crash) / 0 of 100 (0.0-3.7 %) 0 of 30 (0.0-11.4 %) / 0 of 33 (0.0-10.4 %)
FailingJitWithForcedCollections x64 9 of 100 (4.8-16.2 %; 3 by validation, 6 by crash) / 0 of 100 (0.0-3.7 %) 20 of 445 (2.9-6.8 %; 15 by validation, 5 by crash) / 0 of 369 (0.0-1.0 %) 0 of 30 (0.0-11.4 %) / 0 of 30 (0.0-11.4 %)
FailingJitWithForcedCollections arm64 20 of 22 (72.2-97.5 %; 12 by validation, 8 by crash) / 0 of 100 (0.0-3.7 %) 23 of 23 (85.7-100.0 %; 18 by validation, 5 by crash) / 0 of 100 (0.0-3.7 %) no run did enough work to count: 30 runs, 1-9 counted iterations each (median 2) against a floor of 12; not a rate / no run did enough work to count: 60 runs, all void (work 1-7 against a floor of 32); not a rate

Work is the number of iterations or aborts a test reports. A cell is a set of runs of one test on one platform and build, with the same settings. A run is void, and not counted, if it passed with work below its floor. The floor is 10 % of the median work of quiet runs (run alone, no GC stress) of the same test DLL (the compiled test) on the same build and side, rounded down, with a minimum of 1. The median is taken over the quiet cell's passing runs; failed and timed-out runs are excluded. The floor applies to passes only. Every run's raw work count stays in its record. Timeouts are their own class, counted separately from failures: not passes, not failures, not dropped. A timeout is a run that reached the 600 s limit; it was then stopped, or it ended by itself while it was being dumped. A run whose outcome was not recorded ended on its own after the time limit without being killed, with no exit code and no pass, failure or crash shown. Entries that stopped at 20 failures have approximate intervals, because the stopping point depends on the count.

A failure counts as "by validation" only where the run's own console output shows the failure message of the test's check of the objects it holds. Any other exit with code 101 is an "other test failure", and any other failing exit is "by crash".

Every entry ran on test DLLs compiled from this PR's test sources, unchanged (hash-checked before each build). Each DLL holds one test: it was built with the test build's standard TestFilter property set to that test, so its generated entry point runs only that one. The DLLs were built in a separate local source tree, not in a checkout of this PR's commit, so the test library and the wrapper generator came from that tree: a local working commit on arm64, and a tree whose commit is not recorded on x64. The DLL's hash was recorded at the copy step and in every run. The confirmation runs and the runs in the Checked table used the same DLLs: this is read from the run records on x64 and for the arm64 Checked runs; for the arm64 confirmation runs it is read for two of the five tests on the base side and inferred for the rest. Before every run, a check confirmed that no build or test host was running other than these runs; Test sizing gives each machine's check.

Can the upstream stress legs catch a regression?

Every run in the "Results, per test and platform" table, including the GCStress=0x3 runs, used a Release runtime with tiered compilation at its default (read); the upstream gcstress0x3 and gcstress0xc legs run on Checked builds with tiered compilation off (read).

The table below shows whether those legs can catch a regression in each test, judged from main's runs under GC stress. Each figure is main's failed runs of counted runs: the table's Release GCStress=0x3 entry, then runs on a Checked build of main with tiered compilation off, as in the legs, under GCStress=0x3 and then GCStress=0xC (measured). The Checked runs were one to three per test and setting, so they are not rates.

Test x64: Release 0x3; Checked 0x3; Checked 0xC arm64: the same Can the stress legs catch a regression?
AbortThroughRedirect 30 of 30; 1 of 1; 0 of 3 7 of 19; 2 of 2; 0 of 3 yes, under GCStress=0x3, on both platforms
AbortThroughHijack 30 of 30; 1 of 1; 0 of 3 26 of 30; 2 of 2; 0 of 3 yes, under GCStress=0x3, on both platforms
AbortAtEpilogStart 30 of 30; 1 of 1; 0 of 3 30 of 30; 2 of 2; 0 of 3 yes, under GCStress=0x3, on both platforms
DynamicInterfaceCastableThrows 0 of 30; 0 of 3; 0 of 3 0 of 30; 0 of 3; 0 of 3 not shown: the test starts no collector thread under GC stress (read), and main did not fail it under GC stress in the runs made
FailingJitWithForcedCollections 0 of 30; 0 of 3 (work 1 each); 0 of 3 no Release run did enough work to count; 0 of 3 (work 1 each); 0 of 3 (work 87, 80 and 2) not shown: main did not fail it under GC stress in the runs made

On arm64, main's floor for those Checked FailingJitWithForcedCollections runs is the minimum of 1, because main's own quiet run failed validation (measured).

Under GCStress=0xC, main did not fail any of these tests on either machine in the runs made, so a pass under 0xC does not show that the fix works. These tests carry no GCStressIncompatible marker; if you would rather the stress legs skip the ones not shown to fail on main under GC stress, I can add it.

Existing tests and the default build of the new tests

The extended set is the existing exception-handling tests (baseservices/exceptions, the Methodical EH tests, GitHub_135530, nestedfinallycall and throwisfirstinstruction), seven other test trees (Interop/IDynamicInterfaceCastable, GitHub_76531, InlineArray, an explicit-layout overlap tree, ByRefLike, binder tracing and InvalidFriendAssemblyName), and this PR's three test projects. On x64, the items of the extended set were each run once, in a plain pass, on a clean Checked build of this PR's commit. Of the 101 existing items, 94 exited 100 (measured). The other 7, which are 5 distinct tests in the InlineArray and explicit-layout class loader groups, did not start: each exited with a MissingMethodException ("Entry point not found") before any test code ran (measured). I take this to be a fault in my local build of those two test trees (inferred). Two of those five, case13 and InlineArrayInvalid, passed on arm64. On arm64, the 84 existing test items of the extended set, which include case13 and InlineArrayInvalid built as standalone programs, were each run twice on a clean Checked build of this PR's commit. All exited 100 in both passes: a plain pass and a pass with the runtime's stress log recording each refresh (measured). The test BinderTracingTest.DefaultProbing was not run: its project is disabled for all CoreCLR builds (#57786).

On x64, the three test projects in GitHub_137606 (test137606, test137606noabort and test137606prestub) were also built the default way, with no TestFilter, from this PR's commit, and each was run 5 times alone with plain corerun and no GC stress on a clean Release build of the same commit: all 15 runs exited 100, and each test137606 run printed the lines of all three of its tests (AbortThroughRedirect, AbortThroughHijack and AbortAtEpilogStart) in one process (measured). On arm64, the unfiltered test137606 ran in both passes of the extended set, on the clean Checked build of this PR's commit, and exited 100 each time; its output was not kept, so that all three tests ran is not shown.

How this was produced

What was run: the tests above and the reproducers, on self-built main, on stock 11.0.0 and on a pre-release 11.0.2 daily build, on Windows x64 and arm64, plus the crash-dump readings.

The "Results, per test and platform" table's entries come from the original builds of main and of this change. Their records show this about the source of each:

  • x64 main: built in a source tree that is not a git repository, so no commit is recorded for it (read).
  • x64, this change: built after this change's exceptionhandling.cpp was copied into a source tree whose commit is not recorded (read). The copy differs from this PR's file only in two comment lines (read).
  • arm64 main: built in a worktree whose checked-out commit, by its reflog, was the base commit when the build was written (read). Whether the worktree had uncommitted changes then is not recorded.
  • arm64, this change: built at a commit that descends from the base and, under src/coreclr, differs from it only in the same version of exceptionhandling.cpp (read). The worktree had no uncommitted changes when that commit was made (read).

The Checked builds of this PR's commit, one per platform, were each built at that commit with no uncommitted changes before or after the build (read). On x64 the build was made in a new clone; on arm64, in a worktree with no earlier Checked output (read). Earlier Checked builds of this change were made in trees that had held other builds (read); the x64 one was incremental (read). On x64, that build followed the same copy of exceptionhandling.cpp as the x64 Release build, and the tree's commit is not recorded (read). On arm64, it was built at the same commit as the arm64 Release build of this change, with no uncommitted changes before or after (read).

The stress-legs table's Checked runs of main used the following builds. On x64, the Checked build of main was built in a fresh clone at 8fef9c34678b on 23 Nov, with its tree clean before and after (read). Every quoted run recorded that build's coreclr.dll, clrjit.dll and System.Private.CoreLib.dll hashes before and after the run (measured from the run records). On arm64, the Checked build of main was made in a worktree with no earlier Checked output and no uncommitted changes before or after the build (read). Its build log records that the worktree was at the base commit when the build was made (read).

On arm64, two clean Release builds of the base commit, made one after the other in two worktrees with no uncommitted changes, were not byte-identical (measured). In clrjit.dll and System.Private.CoreLib.dll every difference was a path, a timestamp or build identity, but coreclr.dll also differed in code and layout, including one function placed in a different order (measured). On x64, two clean Release builds of the base commit were also not byte-identical. Neither were two clean builds of this PR's commit: one a Release build, the other a build whose configuration was not recorded. Each was made in a new clone with no uncommitted changes (read), and in both pairs coreclr.dll differed in code and layout (measured). So comparing binaries could not show which commit a runtime was built from, and that comparison was abandoned. In its place, the three abort tests (under GCStress=0x3) and the two call-route tests (at default settings) were run again on clean Release builds of the base and of this PR's commit (measured):

  • arm64, the base: AbortThroughRedirect failed in 25 of 30 runs, AbortThroughHijack in 29 of 30 and AbortAtEpilogStart in 30 of 30; DynamicInterfaceCastableThrows and FailingJitWithForcedCollections failed in all 23 of their runs each, which ran to a stop at 20 failures.
  • arm64, this PR's commit: AbortThroughHijack reached its 30 counted passes with no failure (32 passes in 44 runs), and DynamicInterfaceCastableThrows and FailingJitWithForcedCollections passed 100 of 100 runs each. On arm64, on a clean Release build of this PR's commit under GCStress=0x3, AbortThroughRedirect reached 20 counted passes in 39 runs and AbortAtEpilogStart 21 in 47, short of the 30 planned in the 60-minute window. No run failed; the other runs did too little work to count, timed out, or were cut at the window's end. In those two sets, 9 runs timed out (measured). Of those, 4 ended by themselves, with the test's pass exit, while their dumps were being taken (measured). The other 5 were dumped: four have two dumps each, and one has a single dump because its second was never written (measured). Each of those 9 dumps shows 8 or 9 threads, and in none is either of the fix's refresh functions (UpdateNonvolatileRegistersFromExplicitFrame, UnwindRegDisplayToSp) on any stack (measured). Between each run's two dumps, the thread doing the GC had moved on (measured). So the four runs with two dumps were slow runs under GC stress, not hangs (inferred), and for the run with a single dump, progress was not observed.
  • x64, the base: AbortThroughRedirect failed in 29 of 30 runs, AbortThroughHijack in 29 of 30 and AbortAtEpilogStart in 30 of 30; DynamicInterfaceCastableThrows failed in 9 of 455 and FailingJitWithForcedCollections in 20 of 449.
  • x64, this PR's commit: AbortThroughRedirect, AbortThroughHijack and AbortAtEpilogStart under GCStress=0x3 each passed 30 of 30 runs, and DynamicInterfaceCastableThrows and FailingJitWithForcedCollections passed 100 of 100 runs each; no run failed.

I did not run the ReadyToRun-only routes or the path used when the special user-mode APC is unavailable. Statements marked "read" or "inferred" were not checked in a run. The OS unwinder's behaviour could be neither run in isolation nor read, because its source is not in the tree.

In the sections below, the figures come from runs that recorded the hashes of the runtime binaries they loaded; any figure from an earlier run without that record is marked "earlier run".

The miss condition

The exact match fails only when a special-APC redirect interrupts a thread at the first instruction of an epilog, and nothing makes the OS dispatch that frame anyway. The rude-abort and FuncEvalFrame limits above give a logged miss for a different reason.

  • Both platforms: the OS gives a frame no handler when its PC is at an epilog start, so it dispatches the caller, and the exact match fails. On x64 this was measured at every observed miss; the mechanism was read from the tree's copy of the unwinder, since Windows runs its own.
  • x64: the APC stub registers a handler that would force dispatch of the interrupted frame, but the stub's own call sits directly before its epilog, so the handler never runs (inferred from CoreCLR's copy of the unwinder). On an exact-match-only build (an earlier version of this change, with the exact match and no unwind fallback), with the stub padded, 0 of 14,400 aborts missed in 72 runs, and the handler ran twice per abort (measured). Without the padding, 1,139 of 14,200 aborts missed (8.0 %) in the 71 passing runs, 2 of 73 runs crashed, and the handler never ran (measured). These runs used an earlier AbortAtEpilogStart, which did not yet catch each abort to validate after it.
  • arm64: the APC stub registers no handler (read). On an exact-match-only build, redirects missed in 626 of 8,039 refresh attempts (7.8 %) and hijacks in 0 of 3,961 (measured). Each of the 626 interrupted PCs was read as an epilog's first instruction from method listings taken in a separate run of the same build.
  • A return address never misses.
    • x64: on x64 a return address never sits on an epilog start, because the JIT pads a call that precedes an epilog (source and listings). The call routes showed no miss, measured with test variants that are not part of this PR. In those variants, the throwing call is followed directly by the callee's epilog (on x64, after the padding the JIT inserts). Interface-cast: 22 runs with complete logs, 0 misses in 591 refreshes; prestub: 16 runs, 0 misses in 32,988 refreshes. The test binary's hash was recorded when each run set started, not per run.
    • arm64: On arm64, the JIT does not pad a call before an epilog, but the exact match alone still found the frame. The results were measured with the same test variants, in which on arm64 the throwing call is followed directly by the epilog's first instruction, with no padding (listings). On the exact-match-only build, the interface-cast variant gave 151,440 throws in its 8 runs with complete logs, and the prestub variant gave 39,073 throws in 10 complete runs. Every throw produced an exact refresh, with 0 misses. A log-volume check before the prestub runs failed (2,757 of 2,854 throws logged), so each run was judged on its own log, and all 10 logged every throw the test reports. The test binary's hash was recorded at build, not per run. The variants are not included because they do not fail on main, and I can share them on request.
  • So the call routes never need the fallback. It serves only an abort delivered by redirect onto an epilog start.
  • The fallback's own assumptions:
    • On arm64, a skip of more than one managed frame is ruled out only if the OS looks a caller up at the return address minus 4, which lands on the call instruction (inferred; that code is not in the tree).
    • The loop can attempt multiple unwind steps; it refreshes only if it reaches the target's exact SP and IP (read).
    • On x64 the context pointers the fallback reads come from Windows' RtlVirtualUnwind, which is not in the tree; the GC's walk calls it on the same frame (read).
Engagement counts, by mechanism
Platform Test Mechanism Throws Exact After unwinding Miss
x64 abort route special-APC redirect 10,885 10,855 30 0
x64 abort route CET hijack (inferred) 7,275 7,275 0 0
x64 AbortAtEpilogStart special-APC redirect 49,800 of 49,800 43,454 6,346 0
x64 AbortAtEpilogStart, GCStress=0x3 special-APC redirect (22,344 exact, 2,826 after unwinding); prestub (30 exact) 25,200 of 25,200 22,374 2,826 0
x64 interface-cast route dispatch stub 77 of 77 77 0 0
x64 prestub route prestub 1,953 of 1,865 1,953 0 0
arm64 AbortAtEpilogStart special-APC redirect 10,000 of 10,000 8,659 1,341 0

Measured on this change with logging on, per abort or throw; "Throws" counts aborts and other throws; where two counts appear, they are the throws examined and the throws the test reports. In the prestub row, the 88 extra throws are one dependency-check raise per run (read from source). The two abort-route rows split one run set's 18,160 aborts, of 18,160 the test reports, by the Frame the refresh used, not by test: RedirectedThreadFrame for the redirect, ResumableFrame for the hijack. That hijack is inferred to be a CET (Control-flow Enforcement Technology) hijack, because user-mode shadow stacks are on for the test host on the x64 machine. In the GCStress=0x3 row, the 30 prestub refreshes are all aborts, since the 25,200 throws are the 200 aborts of each of 126 runs; an abort reached a thread while it was inside the prestub (inferred from the Frame type, PrestubMethodFrame). The runs record the runtime's hashes; the test DLL's hash is recorded once per run set on both platforms, not per run; on arm64, that this DLL was built from the tests under review is inferred. The arm64 abort-route and call-route rows were not measured. "Special-APC redirect" is inferred from the Frame, RedirectedThreadFrame (measured), and the runtime's probe for the special APC.

On x64 at GCStress=0x3, 1,737 of the 2,826 refreshes after unwinding changed a register. The test holds an object in each of eight callee-saved registers and compares all of them after every abort (read from the method listing). Among the 1,737 refreshes, 1,703 changed r12, 1,718 changed r13 and 1,667 changed r15; these counts overlap (measured). Validation failed in 0 of 126 runs (0 of 25,200 aborts; measured). Every run recorded collections, at least 98,628 each (measured). That the listing, taken at default settings, matches the code that ran under GCStress=0x3 is inferred.

Reproduction, versions run, and 11.0.0 versus the pre-release 11.0.2 daily build

On stock 11.0.0 the abort route reproduces on x64 (under GC stress, and at default settings with a concurrent collector). On arm64 it failed in 80 of 84 runs under GC stress in an earlier run, and the other 4 hung (no control).

Stock 11.0.0, one row per route per platform. "Validation inferred": the app exited with the code its source gives for a failed check of the objects it holds; the source copy read is not tied by hash to the binary that ran.

Route Platform Failed / runs Control failed / runs How the control differs Provenance
abort route x64 both with an app that holds an object in every callee-saved register: 304 / 304 under GCStress=0x3, tiering off; 176 / 1,826 with no GCStress, default tiering and a collector thread no control; mechanism shown by the dump readings earlier run
abort route arm64 80 / 84 under GCStress=0x3, tiering off; the other 4 hung no control; mechanism shown by the dump readings earlier run
interface-cast route x64 1,126 / 1,398, with no GCStress, default tiering and a collector thread; 1,091 by validation (inferred), 34 fatal, 1 other 0 / 8,064 the castable resolves earlier run
interface-cast route arm64 11 / 6,044, all by validation (inferred) 0 / 6,567; every run recorded gen0 collections (2 to 4) the call works runtime hashes match the published archive
prestub route x64 42,487 / 47,589 with tiering off and a collector thread; 42,478 by validation (inferred), 9 fatal 0 / 20,229 dependency present; matched collections runtime hashes match the published archive
prestub route arm64 121 / 153 with stress logging on and tiering off; 119 by crash, 2 by validation (inferred) 0 / 126 dependency present; collections kept high runtime hashes match the published archive

For the x64 prestub row, that the runs loaded the published release files is inferred from the runtime path each run used, and the app's hash was recorded once per start of the run driver, not per run.

How the controls differ, in full:

  • Interface-cast route: one change on each platform. On x64 the castable resolves instead of throwing; on arm64 the call goes from throwing to working.
  • Prestub route, x64: three changes. (1) A different app: the same app plus a loop that keeps each control run going until it has seen at least REPRO_MIN_COMPACTING compacting collections. (2) The dependency is present, so nothing throws. (3) REPRO_MIN_COMPACTING=33, the stock runs' exposure, so the control has matched GC exposure (gen0 median 33 against 32).
  • Prestub route, arm64: three changes. (1) A different app, the same change as on x64 (its source is byte-equal to x64's; that the arm64 binary was built from it is not recorded). (2) The dependency is present, so nothing throws. (3) REPRO_MIN_COMPACTING=61296, the median compacting count of the completed runs of an earlier failing run set, which keeps its collections high (61,295 to 67,543 gen0, a higher median than in the 34 stock runs that recorded a count; not matched run by run).

The ReadyToRun-only routes (DynamicHelperFrame, ExternalMethodFrame) were read only. The IDynamicInterfaceCastable cast path was read as not exposed to this defect, and running it did not reproduce the defect.

Versions run: main 8fef9c34678b, and 11.0.0 and the pre-release 11.0.2 daily build on x64 and arm64. Earlier releases, on x64 with the abort reproducer under GCStress=0x3:

  • 8.0.34: a different failure on the same trigger, not analysed here.
  • 9.0.23: the reproducer cannot test the defect there; it does not complete even without stress, because the abort is never delivered.

Under GCStress=0x3, the abort reproducer used for the bisect, not the all-registers one, fails on the pre-release 11.0.2 daily build on x64 but not on 11.0.0 (earlier runs). That bisects to 43955593de5f, a profile-data update that changed ControlledExecution.Run's register saves. It changes exposure, not the defect: the all-registers reproducer fails on 11.0.0 x64 too.

The stock counts are by exit status, with controls where available; how each differs is listed above. Dump readings exist for the abort route on x64 and arm64. Stock 11.0.0 was checked against the release's published sha512 hashes on both platforms.

Delivery mechanisms, per OS
Test x64 arm64
AbortThroughRedirect, AbortThroughHijack special-APC redirect; CET hijack (inferred) special-APC redirect; return-address hijack
AbortAtEpilogStart special-APC redirect special-APC redirect (all 10,000 refreshes under the redirect frame, 8,659 exact and 1,341 after a one-frame unwind)
DynamicInterfaceCastableThrows dispatch stub dispatch stub
FailingJitWithForcedCollections prestub prestub

In this table, "special-APC redirect" is inferred from the Frame and the runtime's probe for the special APC; "CET hijack" is inferred from the shadow-stack setting.

My arm64 machine runs Windows 11 build 26300 and exports QueueUserAPC2; its aborts arrive as RedirectedThreadFrame or HijackFrame. My x64 machine and upstream's x64 and arm64 queues use build 26100; from the build and the runtime's probe for the special APC, I infer they use the special APC too. So, by that inference, the path used when the special user-mode APC is unavailable, which reaches Thread::ThrowControlForThread, runs on none of them. x86 is untouched.

Test sizing

At default settings, how often a test catches a regression varies with the test, the platform and the load (see "Results, per test and platform"); run alone, some do not fail at all (named below).

Run alone is one copy of the test on an otherwise idle machine. Four at once is four copies of the same test running together, each under the load of the other three. A run set counts as four at once only if its median number of runs in flight is at least 4, from the counts logged at each run's start and end. A run set below that is reported and not quoted. Every GCStress=0x3 entry in the table also ran four at once, on both machines: each of those run sets had a median of 4 runs in flight (measured). Rates at default settings vary with load.

Run alone at default settings, AbortThroughRedirect and AbortThroughHijack did not fail on main on either platform (455 runs on x64, 100 on arm64), and neither did AbortAtEpilogStart on arm64 (100 runs). These cases need GC stress or the load of four at once to fail on main; AbortAtEpilogStart on x64 and the other two tests also fail on main run alone (see "Results, per test and platform").

Test Work and time budget per run (read) Run alone, median wall time of a passing run, process start included, main / fix (measured)
AbortThroughRedirect, AbortThroughHijack up to 20 aborts; stops once 60 s have passed AbortThroughRedirect: x64 0.8 s / 0.8 s, arm64 0.8 s / 0.8 s; AbortThroughHijack: x64 0.8 s / 0.8 s, arm64 0.8 s / 0.8 s
AbortAtEpilogStart up to 200 aborts; stops once 60 s have passed x64 7.2 s / 7.3 s; arm64 7.7 s / 7.7 s
DynamicInterfaceCastableThrows up to 40,000 iterations; stops once 20 s have passed x64 23.0 s / 22.6 s; arm64 20.1 s (11 passing runs) / 20.1 s
FailingJitWithForcedCollections up to 1,000 iterations; stops once 20 s have passed x64 24.4 s / 25.9 s; arm64 20.4 s (2 passing runs) / 20.2 s

FailingJitWithForcedCollections: median iterations per passing run, with the number of passing runs in brackets (measured).

Platform Run alone: main Run alone: fix GCStress=0x3: main GCStress=0x3: fix
x64 4 (91) 3 (100) 1 (30) 1 (30)
arm64 128.5 (2) 323 (100) 2 (30) 1 (60)

On arm64 under GCStress=0x3, no passing run reached its floor (12 on main, 32 on this change). Why the two platforms differ was not determined.

On x64, a check ran before every run in the "Results, per test and platform" table, including the stress runs. It confirmed that the machine's CI runners were paused with no job running or pending, that no build or test host was running other than these runs, and that WSL was idle. The WSL part did not apply to the first run of each run-alone cell.

The x64 test drivers left their own WSL monitoring processes running after each run, so these accumulated. They were counted only for the later x64 runs (from 23 Nov): the confirmation runs on clean builds and the Checked runs of main and of this change. Of these, 59 were already running when the first of those runs ended, so they were left by earlier x64 runs (inferred). For the results table's x64 runs, how many were alive, and how often the check held a run, was not recorded.

During the later runs at least 91 were alive at the peak. Each run started only after the WSL check read under its limit. The check held runs for WSL activity 30 times in the confirmation runs on the clean base build, 5 times in the Checked runs of main and not at all in the Checked runs of this change, for up to 26 s. Only the first failed check of each hold was logged, so these counts are of holds whose first logged reason was WSL activity. Four other holds were logged on the runner or process checks, and the first run of each cell was held for up to 46 s, before the check had its first WSL reading.

The processes matched to these runs' own launches were then stopped. The confirmation runs on the clean Release build of this PR's commit ran after that. The check did not hold any of them for WSL activity; each cell's first run waited up to 20 s for the check's first WSL reading. At least 38 of the earlier monitoring processes were still alive during each cell of those runs (measured, a lower bound); their effect on the results was not measured.

On arm64, a check ran before every run in the "Results, per test and platform" table, including the stress runs. It confirmed that no build or test host was running other than these runs. From the run-alone main runs of FailingJitWithForcedCollections on, it also confirmed that the machine's CI runners were paused and that WSL was idle (read from the run records). The run-alone runs before them were made before those two checks were added (read from the run records). Neither check looks at other processes, at CPU load, or at anything during a run. Their WSL busy readings use different sampling windows, each with its own controls: on arm64 1-s readings, and on x64 a form that depends on the driver version. On x64, the run-alone cells' driver took a single WSL reading at each check (for one of them, the driver is inferred from the fields its records carry); the four-at-once and GCStress=0x3 cells' drivers took a rate over 20 s from a background sampler. On that single-reading driver, the first run of a cell could start before any WSL reading was taken; it ran the run-alone cells of all five tests, main and fix. The later x64 runs took a rate over 2 s in the Checked runs and over 20 s in the confirmation runs on clean builds.

Each run's identity was checked differently on the two machines. On x64, each run's hashes were taken before and after the run and compared with the copy step. On arm64, each run's hashes were taken at its start only, and no hash was taken after the run. The hashes were compared with the cell's start hashes and the recorded build's coreclr.dll hash; the test DLL's hash was compared with its hash at the copy step.

The GC stress runs show the contrast with main; the fix's failure rate is bounded by the default-settings runs. For DynamicInterfaceCastableThrows on x64 and arm64 and FailingJitWithForcedCollections on x64, the GC stress runs did not fail on main in 30 runs each, so they do not show the contrast. For these, the fix's failure rate rests on the default-settings runs alone. For FailingJitWithForcedCollections on arm64, no main or fix run of the Release build under GCStress=0x3 did enough work to count.

In the x64 AbortAtEpilogStart four-at-once runs on the fix, collections per run, from the test's own count: minimum 4,755 and median 5,377 over its 538 passing runs; on main, 4,771 and 5,252 over 510 passing runs (measured).

In the arm64 AbortAtEpilogStart four-at-once runs, every run's test DLL hash equalled the copy step's (measured). On the fix, collections per run, from the test's own count: minimum 7,233 and median 8,352 over all 455 runs (measured). On main, 418 of the 455 runs recorded the count, with a minimum of 7,396 and a median of 8,486 (measured). Collections in those runs come from the test's own collector thread, which runs when GCStress is off (inferred from source).

Each test holds movable references in callee-saved registers. It detects corruption by validation where it can observe the register, and by a crash otherwise. AbortThroughRedirect and AbortThroughHijack detect by crash only, by design: ControlledExecution.Run never returns normally after an abort, so the holder cannot check its objects afterwards. The prestub-route test uses a dependency that is never deployed, and sets CrossGenTest=false.

DynamicInterfaceCastableThrows runs its throwing path once before its collector thread starts, so the first throw's one-time costs are paid without collections running. With a PDB (debug symbols file) beside the test DLL, as in a local build, that first throw otherwise waits behind forced collections for minutes. Upstream CI strips test PDBs from its payloads by default (read), so CI would not hit it.

AbortAtEpilogStart has two methods tail-call each other with IL tail. call, so an abort can land on a framed epilog's first instruction. The method RunAndCatch, between the holder and ControlledExecution.Run, catches the exception ControlledExecution.Run throws after each abort, so the holder runs on and validates its objects after every abort. HoldAcrossCatchingRun (the holder) and RunAndCatch are both marked AggressiveOptimization (read). At default settings, four at once, AbortAtEpilogStart failed on main in 60 of 570 runs on x64, 56 by crash and 4 by validation, and in 51 of 455 runs on arm64, 37 by crash and 14 by validation. The test reaches an epilog start only if the JIT emits those tail. calls as fast tail calls, and for their signatures, with every argument in a register and no return buffer, only DOTNET_FastTailCalls=0 prevents that (read).

Resolves #137606

Note

This analysis and fix was prepared with AI assistance (Anthropic Claude, OpenAI Codex, Google Gemini) at my request. I reviewed the fix and tests before opening.

@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Nov 24, 2026
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).
12 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: @agocke
See info in area-owners.md if you want to be subscribed.

@pcshrosbree

Copy link
Copy Markdown
Contributor Author

I pushed a second commit, 4cb9723, that changes only comments in the fix and its tests. The evidence in the description was produced on the first commit, 789f9dc.

On Windows x64 and arm64, when a thread abort, or an exception raised in
the runtime's native code, reaches ProcessCLRException's second pass,
the SoftwareExceptionFrame is filled from the OS unwinder's copy of the
context. A compacting GC before the fill updates the explicit Frame, not
that copy, so the next GC can report stale object references.

The second pass now looks for a register-reporting explicit Frame below
the target whose SP and IP equal the target's, and copies the
callee-saved registers through its context pointers. If none matches, it
unwinds managed frames from the nearest such Frame up to the target's
SP and refreshes only on an exact landing; otherwise it logs a miss.

Adds regression tests for the abort, interface-cast and prestub routes.

Fixes dotnet#137606
This changes comments only; the code is the same as in the previous commit.
dotnet#138306 asserts that, when the thread's innermost explicit Frame is a
RedirectedThreadFrame below the second pass's target, the OS dispatched
the interrupted frame itself, so the context's SP and IP equal the
interrupted ones. The OS can dispatch a caller instead: for a thread
abort redirected onto an epilog start, the OS unwinder finds no handler
there and goes one frame up. On Checked builds the SP assert then fails
in test137606 on x64 and arm64, and not only in AbortAtEpilogStart; the
other cases were not investigated. With the flag set on a caller's
context, the managed exception stack walk would use the caller's return
address without adjusting it back into the call (inferred; not tested).

Replace the asserts with a check: set the flag only when both the SP and
the IP match the interrupted context.
@pcshrosbree
pcshrosbree force-pushed the fix/eh-second-pass-callee-saved branch from 4cb9723 to dc8646b Compare November 27, 2026 05:10
@pcshrosbree

Copy link
Copy Markdown
Contributor Author

TL;DR: After rebasing onto main with #138306, test137606 hits #138306's new SP assert on Checked x64 and arm64, and so does main. The asserts assume the OS dispatched the interrupted frame; in diagnostic runs of AbortAtEpilogStart it dispatched the caller instead. A new, separate commit turns the two asserts into a check, and with it test137606 and ControlledExecutionTests pass on both platforms.

I rebased this onto main at b31d004, which includes #138306. The first commit needed only a context fix in exceptionhandling.cpp; its code is unchanged.

After the rebase, test137606 fails on Checked builds on #138306's new assert, GetSP(static_cast<RedirectedThreadFrame*>(pFrame)->GetContext()) == GetSP(pContextRecord), and main without this PR fails it the same way. It fired in 3 of 3 runs on Windows x64 and 3 of 3 on arm64, on both builds (measured; on arm64 with a local copy of the test that marks where each sub-test starts). On x64, the diagnostic runs show it in AbortAtEpilogStart; in two runs on main it fired before AbortThroughHijack printed its line. On arm64, each build fired twice in AbortAtEpilogStart and once in AbortThroughHijack. The cases outside AbortAtEpilogStart were not investigated.

What the diagnostic runs show. On x64, during AbortAtEpilogStart, the interrupted context was in PopSpin or PopSpin2 at +0x39, and the second pass received a context in the caller, SpinAtEpilogStart at +0x73, with SP 0x50 higher (measured). One arm64 run showed the same pattern: PopSpin2 at +0x74 and SpinAtEpilogStart at +0xbc, with SP 0x30 higher (measured). This is consistent with the epilog-start case under "The miss condition" in the PR description, where the OS gives the interrupted frame no handler and dispatches its caller (inferred).

  • On x64, ApcActivationCallbackStub registers FixRedirectContextHandler, which would make the OS dispatch the interrupted frame, and the stub's call is followed directly by its epilog (both read). In the diagnostic runs the handler was never called (measured). With one nop after the call, the handler was called and the assert did not fire in 10 runs (measured), as x64 Windows: ApcActivationCallbackStub's call sits directly before its epilog, so its exception handler is never called #138240 describes. With the nop, main still crashed in 2 of 5 runs, both in AbortAtEpilogStart: one reported a possible GC hole, the other an access violation in clr (measured).
  • On arm64, the stub registers no handler (read).

The new commit replaces the two asserts with a check: CONTEXT_EXCEPTION_ACTIVE is set only when both the SP and the IP match the interrupted context. With it, on Checked builds (measured):

  • test137606 passes 3 of 3 on arm64 at default settings. Under GCStress=0x3 it passes 3 of 3 on x64 and 1 of 1 on arm64, with 200 aborts in AbortAtEpilogStart in each run.
  • ControlledExecutionTests passes 12 of 12 on x64. On arm64, 11 pass and 1 is skipped: CancelAtStartOfTryRunsHandlers runs only on x64 (read).

Main with this check, and without the first commit, still crashes with GCStress=0x3 set, on pMT->Validate() in AbortThroughRedirect: 3 of 3 runs on x64 and 1 of 1 on arm64 (measured). Each crashed before the test printed its GC counts, so these runs do not show how much stress ran. The crash is consistent with the stale references of #137606 remaining (inferred), so #138306 alone does not fix it.

@janvorli, I kept this as a separate commit so it is easy to drop, or to move to its own PR if you would rather fix it another way, for example in the stub; on arm64 the stub has no handler, so padding it would not be enough there. If the flag is set on a caller's context, the managed exception stack walk (SfiInitWorker) uses the caller's return address without the usual adjustment back into the call (read); I have not tested whether that changes which handler runs.

// points to the interrupted instruction, not a return address, unless the OS
// dispatched a caller instead, as after an interruption at an epilog start.
T_CONTEXT* pInterruptedContext = static_cast<RedirectedThreadFrame*>(pFrame)->GetContext();
if ((GetSP(pInterruptedContext) == GetSP(pContextRecord)) && (GetIP(pInterruptedContext) == GetIP(pContextRecord)))

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.

The fact that it sometimes doesn't match (happens on arm64) is a bug caused by the fact that the pContextRecord doesn't point at the interrupted frame, but at its caller instead. This is a difference on Windows arm64 relative to x64 that I've missed. So this conditional just hides the issue. I am working on figuring out solution, this manifested itself as #138392.
In general, creating the SoftwareExceptionFrame from the pContextRecord on arm64 here is wrong.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

TL;DR: From what I measured, the caller is dispatched on Windows x64 as well as arm64 when an abort lands on the first instruction of an epilog. Would your fix also cover x64? And should I drop the gate now and mark the affected tests [ActiveIssue], or wait for your fix?

Thanks, that makes sense: the gate doesn't fix the context problem. I added it because the new asserts fired in this PR's tests on Checked x64 and arm64.

Some data that may help with #138392. #138306's asserts assume that, in this branch, the OS hands ProcessCLRException the interrupted frame's context. From what I measured, that doesn't hold when an APC abort lands on the first instruction of an epilog, on x64 as well as arm64: the unwinder unwinds the epilog itself, gets no handler for that frame, and dispatches the caller.

  • x64 Checked: this PR's AbortAtEpilogStart lands there on purpose and hits the assert in 3 of 3 runs on both main and this PR's fix build (without the nop below). The diagnostics show PopSpin/PopSpin2 interrupted and its caller SpinAtEpilogStart dispatched.
  • arm64 Checked, in 7 runs without the gate: AbortThroughRedirect (20 aborts per run) never hit it. AbortAtEpilogStart hit it in 5 of the runs, and the one mismatch I captured with diagnostics there was again PopSpin2 interrupted and SpinAtEpilogStart dispatched. AbortThroughHijack, which uses the loop of test135530's CancelInGenericFrames, hit it in the other 2 runs (1 of 3 on main, 1 of 3 with the fix), without jitstress.
  • Assert failure: GetSP(static_cast<RedirectedThreadFrame*>(pFrame)->GetContext()) == GetSP(pContextRecord) #138392 looks consistent with this, though its log doesn't show where the abort landed. CancelInGenericFrames(False) had finished and printed its line before the assert; the other theory case, CancelInGenericFrames(True), runs the same GenericFrame<T> loop and never printed its line. (TestEntryPoint prints nothing, so I can't rule it out.)

On x64, ApcActivationCallbackStub names FixRedirectContextHandler as its personality routine, and FixupDispatcherContext has a prolog/epilog fallback that dispatches the interrupted frame. But the call to ApcActivationCallback is followed directly by add rsp, 30h; pop rbp; ret, so when unwinding out of ApcActivationCallback the OS takes the return address as being in an epilog and never calls FixRedirectContextHandler. With a nop after the call it is called, and the assert went away (0 of 10 runs). That layout dates from 2021 and I haven't validated the path the nop wakes, so I'm not proposing it. Even with the nop, main still crashed in AbortAtEpilogStart in 2 of 5 runs (a corrupted OBJECTREF assert and an AV), against 5 of 5 passes with this PR's refresh. The arm64 stub has no personality routine.

One coupling with this PR: its UnwindRegDisplayToSp fallback is there for exactly this case, where the second pass runs for the caller and the explicit Frame describes a frame below it, and AbortAtEpilogStart is the test that covers it. If your fix always dispatches the interrupted frame, that fallback may no longer be needed here, and I'd drop it if nothing else reaches it.

Without the gate, this PR's tests hit the assert on Checked builds: AbortAtEpilogStart on x64 and arm64, and AbortThroughHijack on arm64. Would your fix also cover x64? And would you prefer that I:

  1. drop the gate now and mark those tests [ActiveIssue] against Assert failure: GetSP(static_cast<RedirectedThreadFrame*>(pFrame)->GetContext()) == GetSP(pContextRecord) #138392, so this PR can be reviewed and merged on its own (the fallback above would then have no active test); or
  2. leave the PR until your fix lands, then rebase, drop the gate, and keep or drop the fallback depending on what your fix does?

Could you also look at the main change, the callee-saved register refresh in the second pass? You know this code far better than I do, and I'd value your view on whether it belongs there.

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.

Hmm, it seems to be the case only for the case when EH unwinds through the APC callback.

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.

I was replying to myself

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.

So, the issue with the context being the context of the caller was actually an unwinding issue through the ApcActivationCallback on arm64. Adding nop after the call fixed that. Without it, the OS unwinds the ApcActivationCallback incorrectly and somehow the unwinding ends up skipping the interrupted frame. Even though there is no FixRedirectContext personality routine for arm64.
Will look more into it after the weekend.

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.

I've found the problem. It is actually very similar to the amd64 issue with the ApcActivationCallbackStub not calling the personality routine. In this case, it is the ProcessCLRException, which is a personality routine for all managed frames, that is not being called. The interrupted managed method is interrupted at the first epilog instruction. Then we throw the thread abort from the APC callback and expect that the OS would call ProcessCLRException for the first managed frame it hits. But due to the issue, it skips the first managed frame's personality routine call.
As a quick check, I've added skipping the thread abort generation in the HandleSuspensionForInterruptedThread when the interruption happened in epilog and the issue is gone.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks, that matches what I measured: all the mismatches I captured were aborts on an epilog's first instruction. Does your change cover x64 too? This PR's AbortAtEpilogStart hits the same case there. When you have it, I'm happy to run it on x64 and arm64 Checked with test137606: AbortAtEpilogStart passes an epilog start on every iteration, with up to 200 aborts per run, so it should show quickly whether the case is gone. With it in, that test may no longer reach this PR's UnwindRegDisplayToSp fallback, so I'd revisit the fallback then.

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.

I have created a PR for the fix (#138532).
I will review the refresh of callee saved registers in this PR later today.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks! I ran #138532 on Windows x64 Checked, on this PR's fix commit with #138306's asserts left in (without the gate commit):

  • test137606 passes in 3 of 3 runs with no assert, and AbortAtEpilogStart takes 200 aborts in each. In the runs I posted on 11-27, this tree without Fix ThreadAbort from APC callback #138532 hit the SP assert in 3 of 3.
  • With DOTNET_GCStress=0x3, it passes in the one run I did (AbortAtEpilogStart: 200 aborts, about 157,000 GCs).
  • In one run of a build with a local diagnostic that prints when the frame's context and the dispatched context differ in SP or IP, nothing was printed in 200 aborts. So AbortAtEpilogStart should no longer reach this PR's UnwindRegDisplayToSp fallback, though I didn't instrument the fallback itself.
  • Main with Fix ThreadAbort from APC callback #138532 and without this PR's fix passes 3 of 3 at default settings. Under GCStress=0x3 it still fails pMT->Validate() in AbortThroughRedirect (1 run), as main did on 11-27.

So on x64, #138532 removes the epilog-start case in these runs. The arm64 run is next; I'll post it here. Once #138532 is in, I'll rebase, drop the gate commit, and drop the fallback unless you'd rather keep it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The arm64 run gives the same picture. On Windows arm64 Checked, with this PR's fix commit and #138306's asserts left in:

So #138532 removes the epilog-start case on arm64 in these runs as well.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-VM-coreclr 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.

Assert failure: !CREATE_CHECK_STRING(pMT && pMT->Validate()) in _coreclr_GitHub_135463_test135463::Runtime_135463.TestEntryPoint()

2 participants