From 1ef4f5d9248b3885035cfd269cca050b6d94c3dc Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Tue, 27 Aug 2024 12:21:35 +0200 Subject: [PATCH 1/2] clarify that addr_of creates read-only pointers --- library/core/src/ptr/mod.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/library/core/src/ptr/mod.rs b/library/core/src/ptr/mod.rs index 859fad9e069ca..b83a18027193e 100644 --- a/library/core/src/ptr/mod.rs +++ b/library/core/src/ptr/mod.rs @@ -2285,6 +2285,10 @@ impl fmt::Debug for F { /// `addr_of!(expr)` is equivalent to `&raw const expr`. The macro is *soft-deprecated*; /// use `&raw const` instead. /// +/// It is still an open question whether writing through an `addr_of!`-created pointer is permitted +/// or not. Until that is decided, the same rules as for shared references apply: it is UB to write +/// through a pointer created with this operation, except for bytes located inside an `UnsafeCell`. +/// /// Creating a reference with `&`/`&mut` is only allowed if the pointer is properly aligned /// and points to initialized data. For cases where those requirements do not hold, /// raw pointers should be used instead. However, `&expr as *const _` creates a reference From b5bd0fe48a0427a82804759a5acd795851c65e4b Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Tue, 27 Aug 2024 15:08:45 +0200 Subject: [PATCH 2/2] addr_of on places derived from raw pointers should preserve permissions --- library/core/src/ptr/mod.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/library/core/src/ptr/mod.rs b/library/core/src/ptr/mod.rs index b83a18027193e..5a9c5ed5be3b4 100644 --- a/library/core/src/ptr/mod.rs +++ b/library/core/src/ptr/mod.rs @@ -2285,9 +2285,13 @@ impl fmt::Debug for F { /// `addr_of!(expr)` is equivalent to `&raw const expr`. The macro is *soft-deprecated*; /// use `&raw const` instead. /// -/// It is still an open question whether writing through an `addr_of!`-created pointer is permitted -/// or not. Until that is decided, the same rules as for shared references apply: it is UB to write -/// through a pointer created with this operation, except for bytes located inside an `UnsafeCell`. +/// It is still an open question under which conditions writing through an `addr_of!`-created +/// pointer is permitted. If the place `expr` evaluates to is based on a raw pointer, then the +/// result of `addr_of!` inherits all permissions from that raw pointer. However, if the place is +/// based on a reference, local variable, or `static`, then until all details are decided, the same +/// rules as for shared references apply: it is UB to write through a pointer created with this +/// operation, except for bytes located inside an `UnsafeCell`. Use `&raw mut` (or [`addr_of_mut`]) +/// to create a raw pointer that definitely permits mutation. /// /// Creating a reference with `&`/`&mut` is only allowed if the pointer is properly aligned /// and points to initialized data. For cases where those requirements do not hold,