Skip to content
Merged
Changes from 4 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
11 changes: 10 additions & 1 deletion 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:

- Managed references must be aligned in safe code. 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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is almost exact duplicate of what's written a few paragraphs below. Did you mean to consolidate it?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yup, my mistake

- Managed references may be null, but if they are non-null then they must point to valid memory, _even in unsafe code_. For these purposes, one element past the end of an array is considered valid memory, as is pointing just past the end of the object. Managed references pointing past objects may not be dereferenced in either safe or unsafe code.

### Examples and APIs

**ArrayPool.Rent**
Expand Down
Loading