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

Collection initializers can leak refs #75802

Open
jjonescz opened this issue Nov 7, 2024 · 1 comment
Open

Collection initializers can leak refs #75802

jjonescz opened this issue Nov 7, 2024 · 1 comment
Labels
Area-Compilers New Language Feature - Ref Fields untriaged Issues and PRs which have not yet been triaged by a lead

Comments

@jjonescz
Copy link
Member

jjonescz commented Nov 7, 2024

Version Used: 4.13.0-2.24555.1 (9dcb2a3)

Steps to Reproduce:

using System;
using System.Collections;
using System.Diagnostics.CodeAnalysis;

R r = M();
Console.WriteLine(r.F);

static R M()
{
    var local = 1;
    return new R() { local };
}

ref struct R : IEnumerable
{
    public ref readonly int F;

    public void Add([UnscopedRef] in int x)
    {
        F = ref x;
    }

    IEnumerator IEnumerable.GetEnumerator() => throw null;
}

Expected Behavior: Error on return new R() { local }; like there would be if explicitly written as var r = new R(); r.Add(local); return r;.

Actual Behavior: No errors. The code accesses a dead reference when executing.

@dotnet-issue-labeler dotnet-issue-labeler bot added the untriaged Issues and PRs which have not yet been triaged by a lead label Nov 7, 2024
@jjonescz
Copy link
Member Author

jjonescz commented Nov 7, 2024

Similar holes exist for other constructs that lower to method calls and aren't specifically handled by RefSafetyVisitor. I would expect collection builders via collection expressions to have a similar problem.

Also, for example, interpolated string handlers (EDIT: That seems to be already tracked by #63306):

using System;
using System.Diagnostics.CodeAnalysis;

R r = M();
Console.WriteLine(r.F);

static R M()
{
    var local = 1;
    return $"{local}";
}

[System.Runtime.CompilerServices.InterpolatedStringHandlerAttribute]
ref struct R
{
    public ref readonly int F;

    public R(int literalLength, int formattedCount) { }

    public void AppendFormatted([UnscopedRef] in int x)
    {
        F = ref x;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Area-Compilers New Language Feature - Ref Fields untriaged Issues and PRs which have not yet been triaged by a lead
Projects
None yet
Development

No branches or pull requests

1 participant