Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug: Using foreach, it's possible to accidentally mutate a ref readonly without any unsafe code #66135

Closed
hamarb123 opened this issue Dec 27, 2022 · 0 comments · Fixed by #66189
Assignees
Labels
4 - In Review A fix for the issue is submitted for review. Area-Compilers Bug
Milestone

Comments

@hamarb123
Copy link

Version Used:

  • Sharplab.io
  • VS 17.4.0 with .NET 7.0.100 SDK

Steps to Reproduce:

  1. Implement IEnumerable<T> explicitly on a struct, and do not mark the implementations as readonly
  2. Cause mutation in your GetEnumerable implementation
  3. Run a loop over a ref readonly or in parameter of your type

Minimal repro:
https://sharplab.io/#v2:EYLgtghglgdgNAFxAJwK4wD4AEBMBGAWACgsAGAAizwDoBhAewBtGBTAYwSnpgGcBuYmUp4ALAJIUq1ADKwAjuMEBmSjnK1iAb2LldqnDr3aie0+QDK5AG4RGqFuQC85GCwDuACgCU4s3uQsAGbkARAAJtyMAJ4W1rb2AEpBTiHJNnYsvn7CAJwe6YlBPoZ+ALIesHEZSYHFJtlUeQUsNXWmAL4llCpUAGyUIuTllZbNXl3G2eQA9NMAkjw89uRQPOQIABYOmw5s9GAADlCsyOQRLDwwAOQI5DwsLGDr9ORsW2wA1iuBXaazVEoADywBAAPmoAHEWAgAKIwVBgFjICAIeinVbkSDID4sMLkCBrUIRGDRai/PSBNEsCBvcj5CCnAAeKxgVXsXnImnInXquh5POUdwQaA4sRAwiBINBWi6IPxWV0WBURMiMXoViRyCgYQcVAoABV6OZhbAAObeJyg/HUQ3GrUwc1tPQHLU2BAOOZwhFIlFo4EwMHkKGw+GI5Go5AWxxWr1hiDAVjUBIQB0sDykODkADUWYgXkh0NjPoj3gV5E9oeLfqlEv9YILIe94bRUatwaLzcjTt0FabvtOAIbHf7raDhcrndLxB5QA

Expected Behavior:

Since the explicit implementations are not marked as readonly, the compiler must assume they can mutate, and therefore should create a defensive copy before calling GetEnumerable.

Actual Behavior:

The compiler doesn't recognise that it needs to create a defensive copy, and thus at the point of foreach, it can mutate the readonly reference.

@dotnet-issue-labeler dotnet-issue-labeler bot added Area-Compilers untriaged Issues and PRs which have not yet been triaged by a lead labels Dec 27, 2022
@jcouv jcouv self-assigned this Jan 2, 2023
@jcouv jcouv removed the untriaged Issues and PRs which have not yet been triaged by a lead label Jan 2, 2023
@jcouv jcouv added this to the 17.5 milestone Jan 2, 2023
@jcouv jcouv added Bug 4 - In Review A fix for the issue is submitted for review. labels Jan 2, 2023
@jaredpar jaredpar modified the milestones: 17.5, 17.6 Jan 12, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
4 - In Review A fix for the issue is submitted for review. Area-Compilers Bug
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants