Rollup merge of #129748 - RalfJung:box-validity, r=workingjubilee

Box validity: update for new zero-sized rules

Fixes https://github.com/rust-lang/unsafe-code-guidelines/issues/529

Cc `@joshlf` `@rust-lang/opsem`
This commit is contained in:
Matthias Krüger 2024-09-02 22:35:18 +02:00 committed by GitHub
commit 003ddec7a6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 13 additions and 15 deletions

View File

@ -53,22 +53,20 @@
//! //!
//! # Memory layout //! # Memory layout
//! //!
//! For non-zero-sized values, a [`Box`] will use the [`Global`] allocator for //! For non-zero-sized values, a [`Box`] will use the [`Global`] allocator for its allocation. It is
//! its allocation. It is valid to convert both ways between a [`Box`] and a //! valid to convert both ways between a [`Box`] and a raw pointer allocated with the [`Global`]
//! raw pointer allocated with the [`Global`] allocator, given that the //! allocator, given that the [`Layout`] used with the allocator is correct for the type and the raw
//! [`Layout`] used with the allocator is correct for the type. More precisely, //! pointer points to a valid value of the right type. More precisely, a `value: *mut T` that has
//! a `value: *mut T` that has been allocated with the [`Global`] allocator //! been allocated with the [`Global`] allocator with `Layout::for_value(&*value)` may be converted
//! with `Layout::for_value(&*value)` may be converted into a box using //! into a box using [`Box::<T>::from_raw(value)`]. Conversely, the memory backing a `value: *mut T`
//! [`Box::<T>::from_raw(value)`]. Conversely, the memory backing a `value: *mut //! obtained from [`Box::<T>::into_raw`] may be deallocated using the [`Global`] allocator with
//! T` obtained from [`Box::<T>::into_raw`] may be deallocated using the //! [`Layout::for_value(&*value)`].
//! [`Global`] allocator with [`Layout::for_value(&*value)`].
//! //!
//! For zero-sized values, the `Box` pointer still has to be [valid] for reads //! For zero-sized values, the `Box` pointer has to be non-null and sufficiently aligned. The
//! and writes and sufficiently aligned. In particular, casting any aligned //! recommended way to build a Box to a ZST if `Box::new` cannot be used is to use
//! non-zero integer literal to a raw pointer produces a valid pointer, but a //! [`ptr::NonNull::dangling`].
//! pointer pointing into previously allocated memory that since got freed is //!
//! not valid. The recommended way to build a Box to a ZST if `Box::new` cannot //! On top of these basic layout requirements, a `Box<T>` must point to a valid value of `T`.
//! be used is to use [`ptr::NonNull::dangling`].
//! //!
//! So long as `T: Sized`, a `Box<T>` is guaranteed to be represented //! So long as `T: Sized`, a `Box<T>` is guaranteed to be represented
//! as a single pointer and is also ABI-compatible with C pointers //! as a single pointer and is also ABI-compatible with C pointers