-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Description
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:
- https://github.com/ufcpp/NonCopyableAnalyzer
- Implement RS0042 (Do not copy value) roslyn-analyzers#3420
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 referenceAlternative 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.