Skip to content

Fix software EH memory leak on Unix - #135290

Merged
janvorli merged 2 commits into
dotnet:mainfrom
janvorli:fix-eh-memory-leak
Oct 8, 2026
Merged

janvorli merged 2 commits into
dotnet:mainfrom
janvorli:fix-eh-memory-leak

Conversation

@janvorli

@janvorli janvorli commented Oct 6, 2026

Copy link
Copy Markdown
Member

The DispatchManagedException for software managed exceptions thrown from native runtime code was not taking ownership of the context and exception records in cases they were dynamically allocated. That was resulting in memory leak.

This change ensures that the ExInfo takes ownership of these records when needed.

Close #135234

The DispatchManagedException for software managed exceptions
thrown from native runtime code was not taking ownership of
the context and exception records in cases they were dynamically
allocated. That was resulting in memory leak.

This change ensures that the ExInfo takes ownership of these
records when needed.

Close dotnet#135234
@janvorli janvorli added this to the 12.0.0 milestone Oct 6, 2026
@janvorli
janvorli requested a review from jkotas October 6, 2026 16:49
@janvorli janvorli self-assigned this Oct 6, 2026
@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: @agocke
See info in area-owners.md if you want to be subscribed.

Comment thread src/coreclr/vm/exceptionhandling.cpp Resolved

@jkotas jkotas left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks

@janvorli

janvorli commented Oct 6, 2026

Copy link
Copy Markdown
Member Author

@jkotas I've removed the limitations to R2R and Windows

@janvorli
janvorli merged commit d37a516 into dotnet:main Oct 8, 2026
117 of 119 checks passed
@jkotas

jkotas commented Oct 8, 2026

Copy link
Copy Markdown
Member

@janvorli Backport candidate? (.NET 11 at least)

@janvorli

janvorli commented Oct 8, 2026

Copy link
Copy Markdown
Member Author

/backport to release/11.0

@github-actions

github-actions Bot commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

Started backporting to release/11.0 (link to workflow run)

@github-actions

github-actions Bot commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

@janvorli backporting to release/11.0 failed, the patch most likely resulted in conflicts. Please backport manually!

git am output
$ git cherry-pick d37a5164e281e6f08fdb4a9e2347ba32ad74610b

Auto-merging src/coreclr/vm/exceptionhandling.cpp
CONFLICT (content): Merge conflict in src/coreclr/vm/exceptionhandling.cpp
error: could not apply d37a5164e28... Fix software EH memory leak on Unix (#135290)
hint: After resolving the conflicts, mark them with
hint: "git add/rm <pathspec>", then run
hint: "git cherry-pick --continue".
hint: You can instead skip this commit with "git cherry-pick --skip".
hint: To abort and get back to the state before "git cherry-pick",
hint: run "git cherry-pick --abort".
hint: Disable this message with "git config set advice.mergeConflict false"


$ git am --3way --empty=keep --ignore-whitespace --keep-non-patch changes.patch

Applying: Fix software EH memory leak on Unix
Using index info to reconstruct a base tree...
M	src/coreclr/vm/exceptionhandling.cpp
Falling back to patching base and 3-way merge...
Auto-merging src/coreclr/vm/exceptionhandling.cpp
CONFLICT (content): Merge conflict in src/coreclr/vm/exceptionhandling.cpp
error: Failed to merge in the changes.
hint: Use 'git am --show-current-patch=diff' to see the failed patch
hint: When you have resolved this problem, run "git am --continue".
hint: If you prefer to skip this patch, run "git am --skip" instead.
hint: To restore the original branch and stop patching, run "git am --abort".
hint: Disable this message with "git config set advice.mergeConflict false"
Patch failed at 0001 Fix software EH memory leak on Unix
Error: The process '/usr/bin/git' failed with exit code 128

Link to workflow output

radekdoulik added a commit that referenced this pull request Oct 9, 2026
<!-- -->

Skip `test135234` on Browser and WASI, where
`Process.GetCurrentProcess()` is unsupported, and iOS and tvOS, where
`WorkingSet64` throws `PlatformNotSupportedException`.

This fixes the Browser/Wasm interpreter failure introduced with the
regression test in
[#135290](#135290). Both Boolean
inputs and the native working-set leak assertion are unchanged. Desktop,
MacCatalyst, and Android coverage remains enabled; all project settings
are unchanged.

**Validation:** Targeted managed-only builds passed for macOS, Browser,
WASI, iOS, tvOS, both Apple simulators, MacCatalyst, and Android.
Generated wrappers omit unsupported dispatch and retain both inputs on
supported targets. On the matching main-CI macOS runtime, the generated
entrypoint returned 100 and supplemental xUnit XML recorded 2 passed, 0
failed, and 0 skipped inputs. Live Browser/WASI execution was not
performed.

> [!NOTE]
> Prepared with GitHub Copilot.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: db5a4b8d-2258-4e39-b7e6-e240858b82f0
@Brimerland

Copy link
Copy Markdown

@janvorli The same leak also affects .NET 9.0 (9.0.18 and 9.0.20) and 10.0.12, not only 11.0.
Data and a minimal repro without Npgsql are in #135234 (comment).

Would you consider backporting to release/10.0, release/9.0 and release/8.0 (still LTS until Nov 2026) as well?

@jkotas

jkotas commented Oct 9, 2026

Copy link
Copy Markdown
Member

release/9.0 and release/8.0 are in maintenance support. During the maintenance support period, .NET releases are updated to mitigate security vulnerabilities, only.

https://dotnet.microsoft.com/en-us/platform/support/policy/dotnet-core

JulieLeeMSFT pushed a commit that referenced this pull request Oct 12, 2026
Backport of #135290 to release/10.0

/cc @janvorli

## Customer Impact

- [x] Customer reported -
#135234
- [ ] Found internally

There is a memory leak of `CONTEXT` and `EXCEPTION_RECORD` data
structures on Unix (about 3400 bytes on amd64) when the
`DispatchManagedException` for software managed exceptions thrown from
native runtime code is executed. The managed exception handling is not
taking ownership of the context and exception records in cases they were
dynamically allocated.

## Regression

- [x] Yes - introduced in .NET 9 by the new exception handling
#88034
- [ ] No

## Testing

Coreclr and libraries tests, directed test for the issue that was added
with the fix

## Risk

Low, it changes software exception handling to the same plan as was
always there for hardware exception handling w.r.t. to the ownership of
the contexts.

Co-authored-by: Jeremy Barton <[email protected]>
Copilot-Session: 9fe58a3a-d045-4e26-af87-9b85acdea60d
JulieLeeMSFT pushed a commit that referenced this pull request Oct 12, 2026
Backport of #135290 to release/11.0

/cc @janvorli

## Customer Impact

- [x] Customer reported -
#135234
- [ ] Found internally

There is a memory leak of `CONTEXT` and `EXCEPTION_RECORD` data
structures on Unix (about 3400 bytes on amd64) when the
`DispatchManagedException` for software managed exceptions thrown from
native runtime code is executed. The managed exception handling is not
taking ownership of the context and exception records in cases they were
dynamically allocated.

## Regression

- [x] Yes - introduced in .NET 9 by the new exception handling
#88034
- [ ] No

## Testing

Coreclr and libraries tests, directed test for the issue that was added
with the fix

## Risk

Low, it changes software exception handling to the same plan as was
always there for hardware exception handling w.r.t. to the ownership of
the contexts.

Copilot-Session: 9fe58a3a-d045-4e26-af87-9b85acdea60d
BrzVlad pushed a commit that referenced this pull request Oct 13, 2026
…ed helper (#135464)

Fixes #135455.

The native-helper exits of `INTOP_CALL_HELPER_*` and
`INTOP_UNBOX_ANY[_GENERIC]` left `pFrame->ip` at the start of the
instruction while the helper ran. The helpers that can throw there are
managed code, so an exception from one reaches the interpreter frame
through managed dispatch: the frame is not marked faulting, and
`SfiInitWorker`/`SfiNextWorker` treat its ip as a return address and
subtract `STACKWALK_CONTROLPC_ADJUST_OFFSET`. When the helper call is
the first instruction of a try region, as the static-base helper is for
a static field access on a type with a `.cctor`, the adjusted ip falls
before the region and its handlers do not run.

`INTOP_CALL`, and the IL-target exits of the same opcodes (`ip += N;
goto CALL_INTERP_METHOD`), already record the next instruction's ip. The
native helper exits now do the same: they advance `ip` and store it
before the helper call.

The `pFrame->ip = ip` at the top of each case is gone where only
`GetPossiblyIndirectHelper` runs before the helper. It stays in the five
opcodes that call `DoGenericLookup` first (`INTOP_CALL_HELPER_P_G`,
`P_GS`, `P_GA`, `V_AGS` and `INTOP_UNBOX_ANY_GENERIC`): that lookup can
throw and can trigger a GC, and its exceptions are C++ exceptions, which
the unwind-and-continue handler in `InterpExecMethod` catches and marks
the frame faulting, so the instruction start is right for them.

Test: `src/tests/Regressions/coreclr/GitHub_135455` puts the static
access first in both a try/finally and an enclosing try/catch. It covers
the first access, the access that rethrows the recorded failure, and a
shared-generic instantiation, which takes the `INTOP_CALL_HELPER_P_G`
path. The project sets `Optimize` so that the access stays the first
instruction of the region in every build configuration.

Validation (Checked runtime, at this PR's base), with the test run under
the JIT and under `DOTNET_InterpMode` 1, 2 and 3:

| | without the fix | with the fix |
|---|---|---|
| linux-x64: the test | fails under the interpreter
(`TypeInitializationException` escapes) | passes |
| linux-x64: issue repro, cases 1 and 2 | handlers skipped | handlers
run |
| osx-arm64: the test | fails under the interpreter
(`TypeInitializationException` escapes) | passes |
| osx-arm64: issue repro, cases 1 and 2 | handlers skipped | handlers
run |
| windows-x64: the test | fails under the interpreter
(`TypeInitializationException` escapes) | passes |
| windows-x64: issue repro, cases 1 and 2 | handlers skipped | handlers
run |

Storing the instruction start again in `INTOP_CALL_HELPER_P_P` makes the
test fail under the interpreter on all three platforms. Under the JIT
the test passes with and without the fix.

The test ran through the merged `Regressions` runner, as it does in CI.
The existing `Regressions/coreclr/GitHub_135234` test (from #135290)
hits the same bug: on osx-arm64 it fails under `DOTNET_InterpMode` 1 and
3 at this PR's base and passes with the fix.

With the fix, `JIT/interpreter` passes on linux-x64 and osx-arm64. On
windows-x64 it passes up to `TestPInvoke`, which I could not run there
because the native test assets did not build on that machine; the test
assemblies used there were the ones built on macOS.

Other places that store the start of an instruction and then call out,
and why they are not changed here:
- `INTOP_NEWARR[_GENERIC]`: the allocation failure is raised from the
helper's own `DynamicHelperFrame`, so the frame is not faulting there
either. A `newarr` cannot be the first instruction of a try region,
though: its length is always loaded by a separate instruction inside the
region, and nothing folds that load away today. It would become
reachable with copy propagation.
- The continuation allocation in the async suspend path always directly
follows the awaited call, in the same region, so the adjusted ip stays
in that call.
- The thread-abort dispatch after resuming from a catch has a separate,
larger problem: #135463.

> [!NOTE]
> This PR was prepared with AI assistance (Anthropic Claude, reviewed by
OpenAI Codex). The builds and runs it cites were done at the PR's base
commit.
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 9, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Linux x64: native memory leak for each rethrown TypeInitializationException

3 participants