[release/5.0-rc2] AccessViolation when using ValueTypes as a Service #42213
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.
Backport of #42152 to release/5.0-rc2
/cc @eerhardt
Customer Impact
When a consumer of DependencyInjection is using a
struct
type as a service, we are generating incorrect IL. We can get scenarios of double unboxing a struct, or using a value type as anobject
reference. Both of which can cause memory corruption and Access Violations.This was a regression introduced early in .NET 5 which was fixing a different IL generation problem. Both the original issue and the regression are fixed by this change.
Testing
I added new regression tests that cover the affected scenario. Also ran the repro project reported by the customer, and the issue is fixed.
@ericstj and I statically analyzed the cases that could run into this issue and found another place - when using a collection of value types. Added a test case for this as well.
Risk
Since anything to do with IL generation is risky, I would say this is "medium" risk. The applied fix only affects value types, so typical usage of DI shouldn't be affected. All current and new tests pass with this change.