diff --git a/accepted/2025/memory-safety/caller-unsafe.md b/accepted/2025/memory-safety/caller-unsafe.md index 25381d54f..faa5a27fc 100644 --- a/accepted/2025/memory-safety/caller-unsafe.md +++ b/accepted/2025/memory-safety/caller-unsafe.md @@ -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 @@ -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** @@ -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.