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

[CallerMustBeUnsafe] type attribute #5111

Closed
benaadams opened this issue Feb 11, 2016 · 4 comments
Closed

[CallerMustBeUnsafe] type attribute #5111

benaadams opened this issue Feb 11, 2016 · 4 comments

Comments

@benaadams
Copy link
Member

To mark a function to be only be able to be called in an unsafe block.

It came up as an issue with having an IntPtr based api for Vector.Copy be equally could apply to something like a .ctor where you are passing an internal buffer to use (e.g. https://github.com/dotnet/coreclr/issues/3142)

Or risk of use of buffers with overlapped I/O tasks and dispose dotnet/corefx#5954 (comment)

To indicate that the caller is aware there are risks and to be careful.

@jkotas
Copy link
Member

jkotas commented Feb 11, 2016

This is what security transparent vs. security critical code has been about...

@benaadams
Copy link
Member Author

I might have missed it then; but what I am suggesting is something where .ctor 2 is forced to be unsafe in the same way .ctor 3 is:

public BufferedThing(int bufferSize){}

[CallerMustBeUnsafe]
public BufferedThing(byte[] internalBuffer){}

public BufferedThing(byte* internalBuffer, int bufferLength){}

e.g.

var buffer0 = new BufferedThing(10); // fine

var buffer1 = new BufferedThing(new byte[10]); // compile error

unsafe {
    var buffer2 = new BufferedThing(new byte[10]); // fine
}

unsafe {
    var buffer = new byte[10];
    fixed (byte* pBuffer = &buffer[0]) {
        var buffer3 = new BufferedThing(pBuffer, 10); // fine
    }
}

@morganbr
Copy link
Contributor

I like this for a couple reasons:

  1. It can be a compile-time check with no runtime overhead (though that means you'd need to re-file this in https://github.com/dotnet/roslyn) -- this is especially important for runtimes like .NET Native and CoreRT that don't implement transparent/critical code.
  2. It makes it clear that even if you're not directly using pointers, what you're doing isn't safe.
  3. By default, all code is critical, so calling critical methods doesn't necessary attract special attention.

A real-world example of this would be methods on the Marshal class such as Copy and StructureToPtr.

@benaadams
Copy link
Member Author

@morganbr refiled there if you want to add your comment? dotnet/roslyn#8663

@msftgits msftgits transferred this issue from dotnet/coreclr Jan 30, 2020
@ghost ghost locked as resolved and limited conversation to collaborators Jan 2, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants