Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions accepted/2025/memory-safety/caller-unsafe.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ public sealed class RequiresUnsafeAttribute : System.Attribute

### Global invariants

Two properties which should always hold in .NET programs are:
Properties which should always hold in .NET programs are:

* Memory safety
* No access to uninitialized memory
Expand Down Expand Up @@ -184,6 +184,15 @@ The last notable area of impact is source generation. Most users will only see c

One concession we could make to source generation would be to allow more fine-grained enabling and disabling of the warning scope. This proposal does **not** recommend such configuration switches. The `unsafe` feature is specifically designed to catch dangerous situations and source generation does not eliminate that risk. Therefore our recommendation would be to **avoid enabling the feature** until all source generators are updated to produce compatible code.

### Requirements

To uphold the global safety invariants, user code must uphold certain requirements.

In particular, managed references have the following requirements:

- In safe code, managed references must be aligned. .NET APIs expect managed references (including Spans) to be aligned. The behavior of .NET APIs on misaligned references is undefined. Additionally, managed references are often pinned as unmanaged pointers and passed to native code using C/C++ conventions. C/C++ requires that all pointers are properly aligned, the behavior is undefined otherwise and it can lead to memory safety violations.
- In both safe and unsafe code, managed references must follow the rules specified in https://github.com/dotnet/runtime/blob/main/docs/design/specs/Ecma-335-Augments.md#ii1442

### Examples and APIs

**ArrayPool.Rent**
Expand All @@ -201,7 +210,3 @@ All P/Invoke methods are unsafe because they may compromise memory safety if the
**SafeHandle, GCHandle, and other handle wrappers**

Safe subset of these APIs must guarantee that safe code cannot operate on invalid handle. For example, `SafeHandle.Dispose` is safe and `SafeFileHandle(IntPtr handle, bool ownsHandle)` constructor is unsafe.

**Alignment of managed references**

Safe code must be prohibited from creating unaligned managed references. Managed refereces are often pinned as unmanaged pointers and passed to native code using C/C++ conventions. C/C++ requires that all pointers are properly aligned, the behavior is undefined otherwise and it can lead to memory safety violations.
Loading