Fix tail call emission for methods containing pinned locals to prevent runtime crashes #18892
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Problem
The F# compiler was emitting
.tail.
prefixes for method calls within functions that contain pinned locals (created using thefixed
keyword). This could lead to runtime crashes and memory corruption because tail calls can cause stack unwinding that invalidates pinned memory references before they are unpinned.Consider this example:
The generated IL would include
tail.
before the recursive call, which is unsafe when pinned locals are present.Solution
This PR implements a fix that suppresses tail call emission when any method contains pinned local variables. The implementation:
ILLocal.IsPinned
in the method bodyemitTailcalls = false
when pinned locals are detectedemitILMethodBody
inilreflect.fs
(Reflection.Emit path)GenILMethodBody
inilwrite.fs
(direct IL writing path)Changes
emitILMethodBody
to check for pinned locals and suppress tail callsGenILMethodBody
to check for pinned locals and suppress tail callsValidation
The fix ensures that:
.tail.
prefixes, preventing memory safety issuesThis is a conservative approach that prioritizes memory safety over potential performance optimizations in the specific case of methods containing pinned locals.
✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.