Skip to content

NonCopyable structs attribute and analyzer #50389

@jkotas

Description

@jkotas

Background and Motivation

New high-performance APIs are often exposed as structs to avoid GC heap allocation. Callers of such APIs have to be careful to avoid creating accidental copies of the struct. Failure to do so can lead to correctness or security issues. We need a capability to prevent or detect this class of bugs at build time.

ValueStringBuilder is an example of an API where creating accidental copy is a potential security bug: #25587 (comment)

Existing implementations of similar analyzers:

Proposed API

Promote https://github.com/ufcpp/NonCopyableAnalyzer developed by @ufcpp into .NET platform API so that it can be used by the platform itself.

 namespace System
 {
+    [AttributeUsage(AttributeTargets.Struct)]
+    public class NonCopyableAttribute : Attribute
+    {
+    }
 }

Usage Examples

[NonCopyable]
public struct ValueStringBuilder
{
...
}

ValueStringBuilder vsb = new ValueStringBuilder();
f(vsb); // Error. ValueStringBuilder must by passed by reference

Alternative Designs

Full C# language feature. The difficulty in doing so is described in https://blog.paranoidcoding.com/2019/12/02/borrowing.html .

Risks

Corner cases that are missed by the analyzer, e.g. use of reflection.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Securityapi-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-System.Runtimecode-analyzerMarks an issue that suggests a Roslyn analyzer

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions