zerocopy/
layout.rs

1// Copyright 2024 The Fuchsia Authors
2//
3// Licensed under the 2-Clause BSD License <LICENSE-BSD or
4// https://opensource.org/license/bsd-2-clause>, Apache License, Version 2.0
5// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
6// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
7// This file may not be copied, modified, or distributed except according to
8// those terms.
9
10use core::{mem, num::NonZeroUsize};
11
12use crate::util;
13
14/// The target pointer width, counted in bits.
15const POINTER_WIDTH_BITS: usize = mem::size_of::<usize>() * 8;
16
17/// The layout of a type which might be dynamically-sized.
18///
19/// `DstLayout` describes the layout of sized types, slice types, and "slice
20/// DSTs" - ie, those that are known by the type system to have a trailing slice
21/// (as distinguished from `dyn Trait` types - such types *might* have a
22/// trailing slice type, but the type system isn't aware of it).
23///
24/// Note that `DstLayout` does not have any internal invariants, so no guarantee
25/// is made that a `DstLayout` conforms to any of Rust's requirements regarding
26/// the layout of real Rust types or instances of types.
27#[doc(hidden)]
28#[allow(missing_debug_implementations, missing_copy_implementations)]
29#[cfg_attr(any(kani, test), derive(Debug, PartialEq, Eq))]
30#[derive(Copy, Clone)]
31pub struct DstLayout {
32    pub(crate) align: NonZeroUsize,
33    pub(crate) size_info: SizeInfo,
34    // Is it guaranteed statically (without knowing a value's runtime metadata)
35    // that the top-level type contains no padding? This does *not* apply
36    // recursively - for example, `[(u8, u16)]` has `statically_shallow_unpadded
37    // = true` even though this type likely has padding inside each `(u8, u16)`.
38    pub(crate) statically_shallow_unpadded: bool,
39}
40
41#[cfg_attr(any(kani, test), derive(Debug, PartialEq, Eq))]
42#[derive(Copy, Clone)]
43pub(crate) enum SizeInfo<E = usize> {
44    Sized { size: usize },
45    SliceDst(TrailingSliceLayout<E>),
46}
47
48#[cfg_attr(any(kani, test), derive(Debug, PartialEq, Eq))]
49#[derive(Copy, Clone)]
50pub(crate) struct TrailingSliceLayout<E = usize> {
51    // The offset of the first byte of the trailing slice field. Note that this
52    // is NOT the same as the minimum size of the type. For example, consider
53    // the following type:
54    //
55    //   struct Foo {
56    //       a: u16,
57    //       b: u8,
58    //       c: [u8],
59    //   }
60    //
61    // In `Foo`, `c` is at byte offset 3. When `c.len() == 0`, `c` is followed
62    // by a padding byte.
63    pub(crate) offset: usize,
64    // The size of the element type of the trailing slice field.
65    pub(crate) elem_size: E,
66}
67
68impl SizeInfo {
69    /// Attempts to create a `SizeInfo` from `Self` in which `elem_size` is a
70    /// `NonZeroUsize`. If `elem_size` is 0, returns `None`.
71    #[allow(unused)]
72    const fn try_to_nonzero_elem_size(&self) -> Option<SizeInfo<NonZeroUsize>> {
73        Some(match *self {
74            SizeInfo::Sized { size } => SizeInfo::Sized { size },
75            SizeInfo::SliceDst(TrailingSliceLayout { offset, elem_size }) => {
76                if let Some(elem_size) = NonZeroUsize::new(elem_size) {
77                    SizeInfo::SliceDst(TrailingSliceLayout { offset, elem_size })
78                } else {
79                    return None;
80                }
81            }
82        })
83    }
84}
85
86#[doc(hidden)]
87#[derive(Copy, Clone)]
88#[cfg_attr(test, derive(Debug))]
89#[allow(missing_debug_implementations)]
90pub enum CastType {
91    Prefix,
92    Suffix,
93}
94
95#[cfg_attr(test, derive(Debug))]
96pub(crate) enum MetadataCastError {
97    Alignment,
98    Size,
99}
100
101impl DstLayout {
102    /// The minimum possible alignment of a type.
103    const MIN_ALIGN: NonZeroUsize = match NonZeroUsize::new(1) {
104        Some(min_align) => min_align,
105        None => const_unreachable!(),
106    };
107
108    /// The maximum theoretic possible alignment of a type.
109    ///
110    /// For compatibility with future Rust versions, this is defined as the
111    /// maximum power-of-two that fits into a `usize`. See also
112    /// [`DstLayout::CURRENT_MAX_ALIGN`].
113    pub(crate) const THEORETICAL_MAX_ALIGN: NonZeroUsize =
114        match NonZeroUsize::new(1 << (POINTER_WIDTH_BITS - 1)) {
115            Some(max_align) => max_align,
116            None => const_unreachable!(),
117        };
118
119    /// The current, documented max alignment of a type \[1\].
120    ///
121    /// \[1\] Per <https://doc.rust-lang.org/reference/type-layout.html#the-alignment-modifiers>:
122    ///
123    ///   The alignment value must be a power of two from 1 up to
124    ///   2<sup>29</sup>.
125    #[cfg(not(kani))]
126    #[cfg(not(target_pointer_width = "16"))]
127    pub(crate) const CURRENT_MAX_ALIGN: NonZeroUsize = match NonZeroUsize::new(1 << 28) {
128        Some(max_align) => max_align,
129        None => const_unreachable!(),
130    };
131
132    #[cfg(not(kani))]
133    #[cfg(target_pointer_width = "16")]
134    pub(crate) const CURRENT_MAX_ALIGN: NonZeroUsize = match NonZeroUsize::new(1 << 15) {
135        Some(max_align) => max_align,
136        None => const_unreachable!(),
137    };
138
139    /// Assumes that this layout lacks static shallow padding.
140    ///
141    /// # Panics
142    ///
143    /// This method does not panic.
144    ///
145    /// # Safety
146    ///
147    /// If `self` describes the size and alignment of type that lacks static
148    /// shallow padding, unsafe code may assume that the result of this method
149    /// accurately reflects the size, alignment, and lack of static shallow
150    /// padding of that type.
151    const fn assume_shallow_unpadded(self) -> Self {
152        Self { statically_shallow_unpadded: true, ..self }
153    }
154
155    /// Constructs a `DstLayout` for a zero-sized type with `repr_align`
156    /// alignment (or 1). If `repr_align` is provided, then it must be a power
157    /// of two.
158    ///
159    /// # Panics
160    ///
161    /// This function panics if the supplied `repr_align` is not a power of two.
162    ///
163    /// # Safety
164    ///
165    /// Unsafe code may assume that the contract of this function is satisfied.
166    #[doc(hidden)]
167    #[must_use]
168    #[inline]
169    pub const fn new_zst(repr_align: Option<NonZeroUsize>) -> DstLayout {
170        let align = match repr_align {
171            Some(align) => align,
172            None => Self::MIN_ALIGN,
173        };
174
175        const_assert!(align.get().is_power_of_two());
176
177        DstLayout {
178            align,
179            size_info: SizeInfo::Sized { size: 0 },
180            statically_shallow_unpadded: true,
181        }
182    }
183
184    /// Constructs a `DstLayout` which describes `T` and assumes `T` may contain
185    /// padding.
186    ///
187    /// # Safety
188    ///
189    /// Unsafe code may assume that `DstLayout` is the correct layout for `T`.
190    #[doc(hidden)]
191    #[must_use]
192    #[inline]
193    pub const fn for_type<T>() -> DstLayout {
194        // SAFETY: `align` is correct by construction. `T: Sized`, and so it is
195        // sound to initialize `size_info` to `SizeInfo::Sized { size }`; the
196        // `size` field is also correct by construction. `unpadded` can safely
197        // default to `false`.
198        DstLayout {
199            align: match NonZeroUsize::new(mem::align_of::<T>()) {
200                Some(align) => align,
201                None => const_unreachable!(),
202            },
203            size_info: SizeInfo::Sized { size: mem::size_of::<T>() },
204            statically_shallow_unpadded: false,
205        }
206    }
207
208    /// Constructs a `DstLayout` which describes a `T` that does not contain
209    /// padding.
210    ///
211    /// # Safety
212    ///
213    /// Unsafe code may assume that `DstLayout` is the correct layout for `T`.
214    #[doc(hidden)]
215    #[must_use]
216    #[inline]
217    pub const fn for_unpadded_type<T>() -> DstLayout {
218        Self::for_type::<T>().assume_shallow_unpadded()
219    }
220
221    /// Constructs a `DstLayout` which describes `[T]`.
222    ///
223    /// # Safety
224    ///
225    /// Unsafe code may assume that `DstLayout` is the correct layout for `[T]`.
226    pub(crate) const fn for_slice<T>() -> DstLayout {
227        // SAFETY: The alignment of a slice is equal to the alignment of its
228        // element type, and so `align` is initialized correctly.
229        //
230        // Since this is just a slice type, there is no offset between the
231        // beginning of the type and the beginning of the slice, so it is
232        // correct to set `offset: 0`. The `elem_size` is correct by
233        // construction. Since `[T]` is a (degenerate case of a) slice DST, it
234        // is correct to initialize `size_info` to `SizeInfo::SliceDst`.
235        DstLayout {
236            align: match NonZeroUsize::new(mem::align_of::<T>()) {
237                Some(align) => align,
238                None => const_unreachable!(),
239            },
240            size_info: SizeInfo::SliceDst(TrailingSliceLayout {
241                offset: 0,
242                elem_size: mem::size_of::<T>(),
243            }),
244            statically_shallow_unpadded: true,
245        }
246    }
247
248    /// Constructs a complete `DstLayout` reflecting a `repr(C)` struct with the
249    /// given alignment modifiers and fields.
250    ///
251    /// This method cannot be used to match the layout of a record with the
252    /// default representation, as that representation is mostly unspecified.
253    ///
254    /// # Safety
255    ///
256    /// For any definition of a `repr(C)` struct, if this method is invoked with
257    /// alignment modifiers and fields corresponding to that definition, the
258    /// resulting `DstLayout` will correctly encode the layout of that struct.
259    ///
260    /// We make no guarantees to the behavior of this method when it is invoked
261    /// with arguments that cannot correspond to a valid `repr(C)` struct.
262    #[must_use]
263    #[inline]
264    pub const fn for_repr_c_struct(
265        repr_align: Option<NonZeroUsize>,
266        repr_packed: Option<NonZeroUsize>,
267        fields: &[DstLayout],
268    ) -> DstLayout {
269        let mut layout = DstLayout::new_zst(repr_align);
270
271        let mut i = 0;
272        #[allow(clippy::arithmetic_side_effects)]
273        while i < fields.len() {
274            #[allow(clippy::indexing_slicing)]
275            let field = fields[i];
276            layout = layout.extend(field, repr_packed);
277            i += 1;
278        }
279
280        layout = layout.pad_to_align();
281
282        // SAFETY: `layout` accurately describes the layout of a `repr(C)`
283        // struct with `repr_align` or `repr_packed` alignment modifications and
284        // the given `fields`. The `layout` is constructed using a sequence of
285        // invocations of `DstLayout::{new_zst,extend,pad_to_align}`. The
286        // documentation of these items vows that invocations in this manner
287        // will accurately describe a type, so long as:
288        //
289        //  - that type is `repr(C)`,
290        //  - its fields are enumerated in the order they appear,
291        //  - the presence of `repr_align` and `repr_packed` are correctly accounted for.
292        //
293        // We respect all three of these preconditions above.
294        layout
295    }
296
297    /// Like `Layout::extend`, this creates a layout that describes a record
298    /// whose layout consists of `self` followed by `next` that includes the
299    /// necessary inter-field padding, but not any trailing padding.
300    ///
301    /// In order to match the layout of a `#[repr(C)]` struct, this method
302    /// should be invoked for each field in declaration order. To add trailing
303    /// padding, call `DstLayout::pad_to_align` after extending the layout for
304    /// all fields. If `self` corresponds to a type marked with
305    /// `repr(packed(N))`, then `repr_packed` should be set to `Some(N)`,
306    /// otherwise `None`.
307    ///
308    /// This method cannot be used to match the layout of a record with the
309    /// default representation, as that representation is mostly unspecified.
310    ///
311    /// # Safety
312    ///
313    /// If a (potentially hypothetical) valid `repr(C)` Rust type begins with
314    /// fields whose layout are `self`, and those fields are immediately
315    /// followed by a field whose layout is `field`, then unsafe code may rely
316    /// on `self.extend(field, repr_packed)` producing a layout that correctly
317    /// encompasses those two components.
318    ///
319    /// We make no guarantees to the behavior of this method if these fragments
320    /// cannot appear in a valid Rust type (e.g., the concatenation of the
321    /// layouts would lead to a size larger than `isize::MAX`).
322    #[doc(hidden)]
323    #[must_use]
324    #[inline]
325    pub const fn extend(self, field: DstLayout, repr_packed: Option<NonZeroUsize>) -> Self {
326        use util::{max, min, padding_needed_for};
327
328        // If `repr_packed` is `None`, there are no alignment constraints, and
329        // the value can be defaulted to `THEORETICAL_MAX_ALIGN`.
330        let max_align = match repr_packed {
331            Some(max_align) => max_align,
332            None => Self::THEORETICAL_MAX_ALIGN,
333        };
334
335        const_assert!(max_align.get().is_power_of_two());
336
337        // We use Kani to prove that this method is robust to future increases
338        // in Rust's maximum allowed alignment. However, if such a change ever
339        // actually occurs, we'd like to be notified via assertion failures.
340        #[cfg(not(kani))]
341        {
342            const_debug_assert!(self.align.get() <= DstLayout::CURRENT_MAX_ALIGN.get());
343            const_debug_assert!(field.align.get() <= DstLayout::CURRENT_MAX_ALIGN.get());
344            if let Some(repr_packed) = repr_packed {
345                const_debug_assert!(repr_packed.get() <= DstLayout::CURRENT_MAX_ALIGN.get());
346            }
347        }
348
349        // The field's alignment is clamped by `repr_packed` (i.e., the
350        // `repr(packed(N))` attribute, if any) [1].
351        //
352        // [1] Per https://doc.rust-lang.org/reference/type-layout.html#the-alignment-modifiers:
353        //
354        //   The alignments of each field, for the purpose of positioning
355        //   fields, is the smaller of the specified alignment and the alignment
356        //   of the field's type.
357        let field_align = min(field.align, max_align);
358
359        // The struct's alignment is the maximum of its previous alignment and
360        // `field_align`.
361        let align = max(self.align, field_align);
362
363        let (interfield_padding, size_info) = match self.size_info {
364            // If the layout is already a DST, we panic; DSTs cannot be extended
365            // with additional fields.
366            SizeInfo::SliceDst(..) => const_panic!("Cannot extend a DST with additional fields."),
367
368            SizeInfo::Sized { size: preceding_size } => {
369                // Compute the minimum amount of inter-field padding needed to
370                // satisfy the field's alignment, and offset of the trailing
371                // field. [1]
372                //
373                // [1] Per https://doc.rust-lang.org/reference/type-layout.html#the-alignment-modifiers:
374                //
375                //   Inter-field padding is guaranteed to be the minimum
376                //   required in order to satisfy each field's (possibly
377                //   altered) alignment.
378                let padding = padding_needed_for(preceding_size, field_align);
379
380                // This will not panic (and is proven to not panic, with Kani)
381                // if the layout components can correspond to a leading layout
382                // fragment of a valid Rust type, but may panic otherwise (e.g.,
383                // combining or aligning the components would create a size
384                // exceeding `isize::MAX`).
385                let offset = match preceding_size.checked_add(padding) {
386                    Some(offset) => offset,
387                    None => const_panic!("Adding padding to `self`'s size overflows `usize`."),
388                };
389
390                (
391                    padding,
392                    match field.size_info {
393                        SizeInfo::Sized { size: field_size } => {
394                            // If the trailing field is sized, the resulting layout
395                            // will be sized. Its size will be the sum of the
396                            // preceding layout, the size of the new field, and the
397                            // size of inter-field padding between the two.
398                            //
399                            // This will not panic (and is proven with Kani to not
400                            // panic) if the layout components can correspond to a
401                            // leading layout fragment of a valid Rust type, but may
402                            // panic otherwise (e.g., combining or aligning the
403                            // components would create a size exceeding
404                            // `usize::MAX`).
405                            let size = match offset.checked_add(field_size) {
406                                Some(size) => size,
407                                None => const_panic!("`field` cannot be appended without the total size overflowing `usize`"),
408                            };
409                            SizeInfo::Sized { size }
410                        }
411                        SizeInfo::SliceDst(TrailingSliceLayout {
412                            offset: trailing_offset,
413                            elem_size,
414                        }) => {
415                            // If the trailing field is dynamically sized, so too
416                            // will the resulting layout. The offset of the trailing
417                            // slice component is the sum of the offset of the
418                            // trailing field and the trailing slice offset within
419                            // that field.
420                            //
421                            // This will not panic (and is proven with Kani to not
422                            // panic) if the layout components can correspond to a
423                            // leading layout fragment of a valid Rust type, but may
424                            // panic otherwise (e.g., combining or aligning the
425                            // components would create a size exceeding
426                            // `usize::MAX`).
427                            let offset = match offset.checked_add(trailing_offset) {
428                                Some(offset) => offset,
429                                None => const_panic!("`field` cannot be appended without the total size overflowing `usize`"),
430                            };
431                            SizeInfo::SliceDst(TrailingSliceLayout { offset, elem_size })
432                        }
433                    },
434                )
435            }
436        };
437
438        let statically_shallow_unpadded = self.statically_shallow_unpadded
439            && field.statically_shallow_unpadded
440            && interfield_padding == 0;
441
442        DstLayout { align, size_info, statically_shallow_unpadded }
443    }
444
445    /// Like `Layout::pad_to_align`, this routine rounds the size of this layout
446    /// up to the nearest multiple of this type's alignment or `repr_packed`
447    /// (whichever is less). This method leaves DST layouts unchanged, since the
448    /// trailing padding of DSTs is computed at runtime.
449    ///
450    /// The accompanying boolean is `true` if the resulting composition of
451    /// fields necessitated static (as opposed to dynamic) padding; otherwise
452    /// `false`.
453    ///
454    /// In order to match the layout of a `#[repr(C)]` struct, this method
455    /// should be invoked after the invocations of [`DstLayout::extend`]. If
456    /// `self` corresponds to a type marked with `repr(packed(N))`, then
457    /// `repr_packed` should be set to `Some(N)`, otherwise `None`.
458    ///
459    /// This method cannot be used to match the layout of a record with the
460    /// default representation, as that representation is mostly unspecified.
461    ///
462    /// # Safety
463    ///
464    /// If a (potentially hypothetical) valid `repr(C)` type begins with fields
465    /// whose layout are `self` followed only by zero or more bytes of trailing
466    /// padding (not included in `self`), then unsafe code may rely on
467    /// `self.pad_to_align(repr_packed)` producing a layout that correctly
468    /// encapsulates the layout of that type.
469    ///
470    /// We make no guarantees to the behavior of this method if `self` cannot
471    /// appear in a valid Rust type (e.g., because the addition of trailing
472    /// padding would lead to a size larger than `isize::MAX`).
473    #[doc(hidden)]
474    #[must_use]
475    #[inline]
476    pub const fn pad_to_align(self) -> Self {
477        use util::padding_needed_for;
478
479        let (static_padding, size_info) = match self.size_info {
480            // For sized layouts, we add the minimum amount of trailing padding
481            // needed to satisfy alignment.
482            SizeInfo::Sized { size: unpadded_size } => {
483                let padding = padding_needed_for(unpadded_size, self.align);
484                let size = match unpadded_size.checked_add(padding) {
485                    Some(size) => size,
486                    None => const_panic!("Adding padding caused size to overflow `usize`."),
487                };
488                (padding, SizeInfo::Sized { size })
489            }
490            // For DST layouts, trailing padding depends on the length of the
491            // trailing DST and is computed at runtime. This does not alter the
492            // offset or element size of the layout, so we leave `size_info`
493            // unchanged.
494            size_info @ SizeInfo::SliceDst(_) => (0, size_info),
495        };
496
497        let statically_shallow_unpadded = self.statically_shallow_unpadded && static_padding == 0;
498
499        DstLayout { align: self.align, size_info, statically_shallow_unpadded }
500    }
501
502    /// Produces `true` if `self` requires static padding; otherwise `false`.
503    #[must_use]
504    #[inline(always)]
505    pub const fn requires_static_padding(self) -> bool {
506        !self.statically_shallow_unpadded
507    }
508
509    /// Produces `true` if there exists any metadata for which a type of layout
510    /// `self` would require dynamic trailing padding; otherwise `false`.
511    #[must_use]
512    #[inline(always)]
513    pub const fn requires_dynamic_padding(self) -> bool {
514        // A `% self.align.get()` cannot panic, since `align` is non-zero.
515        #[allow(clippy::arithmetic_side_effects)]
516        match self.size_info {
517            SizeInfo::Sized { .. } => false,
518            SizeInfo::SliceDst(trailing_slice_layout) => {
519                // SAFETY: This predicate is formally proved sound by
520                // `proofs::prove_requires_dynamic_padding`.
521                trailing_slice_layout.offset % self.align.get() != 0
522                    || trailing_slice_layout.elem_size % self.align.get() != 0
523            }
524        }
525    }
526
527    /// Validates that a cast is sound from a layout perspective.
528    ///
529    /// Validates that the size and alignment requirements of a type with the
530    /// layout described in `self` would not be violated by performing a
531    /// `cast_type` cast from a pointer with address `addr` which refers to a
532    /// memory region of size `bytes_len`.
533    ///
534    /// If the cast is valid, `validate_cast_and_convert_metadata` returns
535    /// `(elems, split_at)`. If `self` describes a dynamically-sized type, then
536    /// `elems` is the maximum number of trailing slice elements for which a
537    /// cast would be valid (for sized types, `elem` is meaningless and should
538    /// be ignored). `split_at` is the index at which to split the memory region
539    /// in order for the prefix (suffix) to contain the result of the cast, and
540    /// in order for the remaining suffix (prefix) to contain the leftover
541    /// bytes.
542    ///
543    /// There are three conditions under which a cast can fail:
544    /// - The smallest possible value for the type is larger than the provided
545    ///   memory region
546    /// - A prefix cast is requested, and `addr` does not satisfy `self`'s
547    ///   alignment requirement
548    /// - A suffix cast is requested, and `addr + bytes_len` does not satisfy
549    ///   `self`'s alignment requirement (as a consequence, since all instances
550    ///   of the type are a multiple of its alignment, no size for the type will
551    ///   result in a starting address which is properly aligned)
552    ///
553    /// # Safety
554    ///
555    /// The caller may assume that this implementation is correct, and may rely
556    /// on that assumption for the soundness of their code. In particular, the
557    /// caller may assume that, if `validate_cast_and_convert_metadata` returns
558    /// `Some((elems, split_at))`, then:
559    /// - A pointer to the type (for dynamically sized types, this includes
560    ///   `elems` as its pointer metadata) describes an object of size `size <=
561    ///   bytes_len`
562    /// - If this is a prefix cast:
563    ///   - `addr` satisfies `self`'s alignment
564    ///   - `size == split_at`
565    /// - If this is a suffix cast:
566    ///   - `split_at == bytes_len - size`
567    ///   - `addr + split_at` satisfies `self`'s alignment
568    ///
569    /// Note that this method does *not* ensure that a pointer constructed from
570    /// its return values will be a valid pointer. In particular, this method
571    /// does not reason about `isize` overflow, which is a requirement of many
572    /// Rust pointer APIs, and may at some point be determined to be a validity
573    /// invariant of pointer types themselves. This should never be a problem so
574    /// long as the arguments to this method are derived from a known-valid
575    /// pointer (e.g., one derived from a safe Rust reference), but it is
576    /// nonetheless the caller's responsibility to justify that pointer
577    /// arithmetic will not overflow based on a safety argument *other than* the
578    /// mere fact that this method returned successfully.
579    ///
580    /// # Panics
581    ///
582    /// `validate_cast_and_convert_metadata` will panic if `self` describes a
583    /// DST whose trailing slice element is zero-sized.
584    ///
585    /// If `addr + bytes_len` overflows `usize`,
586    /// `validate_cast_and_convert_metadata` may panic, or it may return
587    /// incorrect results. No guarantees are made about when
588    /// `validate_cast_and_convert_metadata` will panic. The caller should not
589    /// rely on `validate_cast_and_convert_metadata` panicking in any particular
590    /// condition, even if `debug_assertions` are enabled.
591    #[allow(unused)]
592    #[inline(always)]
593    pub(crate) const fn validate_cast_and_convert_metadata(
594        &self,
595        addr: usize,
596        bytes_len: usize,
597        cast_type: CastType,
598    ) -> Result<(usize, usize), MetadataCastError> {
599        // `debug_assert!`, but with `#[allow(clippy::arithmetic_side_effects)]`.
600        macro_rules! __const_debug_assert {
601            ($e:expr $(, $msg:expr)?) => {
602                const_debug_assert!({
603                    #[allow(clippy::arithmetic_side_effects)]
604                    let e = $e;
605                    e
606                } $(, $msg)?);
607            };
608        }
609
610        // Note that, in practice, `self` is always a compile-time constant. We
611        // do this check earlier than needed to ensure that we always panic as a
612        // result of bugs in the program (such as calling this function on an
613        // invalid type) instead of allowing this panic to be hidden if the cast
614        // would have failed anyway for runtime reasons (such as a too-small
615        // memory region).
616        //
617        // FIXME(#67): Once our MSRV is 1.65, use let-else:
618        // https://blog.rust-lang.org/2022/11/03/Rust-1.65.0.html#let-else-statements
619        let size_info = match self.size_info.try_to_nonzero_elem_size() {
620            Some(size_info) => size_info,
621            None => const_panic!("attempted to cast to slice type with zero-sized element"),
622        };
623
624        // Precondition
625        __const_debug_assert!(
626            addr.checked_add(bytes_len).is_some(),
627            "`addr` + `bytes_len` > usize::MAX"
628        );
629
630        // Alignment checks go in their own block to avoid introducing variables
631        // into the top-level scope.
632        {
633            // We check alignment for `addr` (for prefix casts) or `addr +
634            // bytes_len` (for suffix casts). For a prefix cast, the correctness
635            // of this check is trivial - `addr` is the address the object will
636            // live at.
637            //
638            // For a suffix cast, we know that all valid sizes for the type are
639            // a multiple of the alignment (and by safety precondition, we know
640            // `DstLayout` may only describe valid Rust types). Thus, a
641            // validly-sized instance which lives at a validly-aligned address
642            // must also end at a validly-aligned address. Thus, if the end
643            // address for a suffix cast (`addr + bytes_len`) is not aligned,
644            // then no valid start address will be aligned either.
645            let offset = match cast_type {
646                CastType::Prefix => 0,
647                CastType::Suffix => bytes_len,
648            };
649
650            // Addition is guaranteed not to overflow because `offset <=
651            // bytes_len`, and `addr + bytes_len <= usize::MAX` is a
652            // precondition of this method. Modulus is guaranteed not to divide
653            // by 0 because `align` is non-zero.
654            #[allow(clippy::arithmetic_side_effects)]
655            if (addr + offset) % self.align.get() != 0 {
656                return Err(MetadataCastError::Alignment);
657            }
658        }
659
660        let (elems, self_bytes) = match size_info {
661            SizeInfo::Sized { size } => {
662                if size > bytes_len {
663                    return Err(MetadataCastError::Size);
664                }
665                (0, size)
666            }
667            SizeInfo::SliceDst(TrailingSliceLayout { offset, elem_size }) => {
668                // Calculate the maximum number of bytes that could be consumed
669                // - any number of bytes larger than this will either not be a
670                // multiple of the alignment, or will be larger than
671                // `bytes_len`.
672                let max_total_bytes =
673                    util::round_down_to_next_multiple_of_alignment(bytes_len, self.align);
674                // Calculate the maximum number of bytes that could be consumed
675                // by the trailing slice.
676                //
677                // FIXME(#67): Once our MSRV is 1.65, use let-else:
678                // https://blog.rust-lang.org/2022/11/03/Rust-1.65.0.html#let-else-statements
679                let max_slice_and_padding_bytes = match max_total_bytes.checked_sub(offset) {
680                    Some(max) => max,
681                    // `bytes_len` too small even for 0 trailing slice elements.
682                    None => return Err(MetadataCastError::Size),
683                };
684
685                // Calculate the number of elements that fit in
686                // `max_slice_and_padding_bytes`; any remaining bytes will be
687                // considered padding.
688                //
689                // Guaranteed not to divide by zero: `elem_size` is non-zero.
690                #[allow(clippy::arithmetic_side_effects)]
691                let elems = max_slice_and_padding_bytes / elem_size.get();
692                // Guaranteed not to overflow on multiplication: `usize::MAX >=
693                // max_slice_and_padding_bytes >= (max_slice_and_padding_bytes /
694                // elem_size) * elem_size`.
695                //
696                // Guaranteed not to overflow on addition:
697                // - max_slice_and_padding_bytes == max_total_bytes - offset
698                // - elems * elem_size <= max_slice_and_padding_bytes == max_total_bytes - offset
699                // - elems * elem_size + offset <= max_total_bytes <= usize::MAX
700                #[allow(clippy::arithmetic_side_effects)]
701                let without_padding = offset + elems * elem_size.get();
702                // `self_bytes` is equal to the offset bytes plus the bytes
703                // consumed by the trailing slice plus any padding bytes
704                // required to satisfy the alignment. Note that we have computed
705                // the maximum number of trailing slice elements that could fit
706                // in `self_bytes`, so any padding is guaranteed to be less than
707                // the size of an extra element.
708                //
709                // Guaranteed not to overflow:
710                // - By previous comment: without_padding == elems * elem_size +
711                //   offset <= max_total_bytes
712                // - By construction, `max_total_bytes` is a multiple of
713                //   `self.align`.
714                // - At most, adding padding needed to round `without_padding`
715                //   up to the next multiple of the alignment will bring
716                //   `self_bytes` up to `max_total_bytes`.
717                #[allow(clippy::arithmetic_side_effects)]
718                let self_bytes =
719                    without_padding + util::padding_needed_for(without_padding, self.align);
720                (elems, self_bytes)
721            }
722        };
723
724        __const_debug_assert!(self_bytes <= bytes_len);
725
726        let split_at = match cast_type {
727            CastType::Prefix => self_bytes,
728            // Guaranteed not to underflow:
729            // - In the `Sized` branch, only returns `size` if `size <=
730            //   bytes_len`.
731            // - In the `SliceDst` branch, calculates `self_bytes <=
732            //   max_toatl_bytes`, which is upper-bounded by `bytes_len`.
733            #[allow(clippy::arithmetic_side_effects)]
734            CastType::Suffix => bytes_len - self_bytes,
735        };
736
737        Ok((elems, split_at))
738    }
739}
740
741pub(crate) use cast_from::CastFrom;
742mod cast_from {
743    use crate::*;
744
745    pub(crate) struct CastFrom<Dst: ?Sized> {
746        _never: core::convert::Infallible,
747        _marker: PhantomData<Dst>,
748    }
749
750    // SAFETY: The implementation of `Project::project` preserves the address
751    // of the referent – it only modifies pointer metadata.
752    unsafe impl<Src, Dst> crate::pointer::cast::Cast<Src, Dst> for CastFrom<Dst>
753    where
754        Src: KnownLayout + ?Sized,
755        Dst: KnownLayout + ?Sized,
756    {
757    }
758
759    // SAFETY: The implementation of `Project::project` preserves the size of
760    // the referent (see inline comments for a more detailed proof of this).
761    unsafe impl<Src, Dst> crate::pointer::cast::CastExact<Src, Dst> for CastFrom<Dst>
762    where
763        Src: KnownLayout + ?Sized,
764        Dst: KnownLayout + ?Sized,
765    {
766    }
767
768    // SAFETY: `project` produces a pointer which refers to the same referent
769    // bytes as its input, or to a subset of them (see inline comments for a
770    // more detailed proof of this). It does this using provenance-preserving
771    // operations.
772    unsafe impl<Src, Dst> crate::pointer::cast::Project<Src, Dst> for CastFrom<Dst>
773    where
774        Src: KnownLayout + ?Sized,
775        Dst: KnownLayout + ?Sized,
776    {
777        /// # PME
778        ///
779        /// Generates a post-monomorphization error if it is not possible to
780        /// implement soundly.
781        //
782        // FIXME(#1817): Support Sized->Unsized and Unsized->Sized casts
783        fn project(src: PtrInner<'_, Src>) -> *mut Dst {
784            /// The parameters required in order to perform a pointer cast from
785            /// `Src` to `Dst`.
786            ///
787            /// These are a compile-time function of the layouts of `Src`
788            /// and `Dst`.
789            ///
790            /// # Safety
791            ///
792            /// `Src`'s alignment must not be smaller than `Dst`'s alignment.
793            struct CastParams<Src: ?Sized, Dst: ?Sized> {
794                inner: CastParamsInner,
795                _src: PhantomData<Src>,
796                _dst: PhantomData<Dst>,
797            }
798
799            #[derive(Copy, Clone)]
800            enum CastParamsInner {
801                // At compile time (specifically, post-monomorphization time),
802                // we need to compute two things:
803                // - Whether, given *any* `*Src`, it is possible to construct a
804                //   `*Dst` which addresses the same number of bytes (ie,
805                //   whether, for any `Src` pointer metadata, there exists `Dst`
806                //   pointer metadata that addresses the same number of bytes)
807                // - If this is possible, any information necessary to perform
808                //   the `Src`->`Dst` metadata conversion at runtime.
809                //
810                // Assume that `Src` and `Dst` are slice DSTs, and define:
811                // - `S_OFF = Src::LAYOUT.size_info.offset`
812                // - `S_ELEM = Src::LAYOUT.size_info.elem_size`
813                // - `D_OFF = Dst::LAYOUT.size_info.offset`
814                // - `D_ELEM = Dst::LAYOUT.size_info.elem_size`
815                //
816                // We are trying to solve the following equation:
817                //
818                //   D_OFF + d_meta * D_ELEM = S_OFF + s_meta * S_ELEM
819                //
820                // At runtime, we will be attempting to compute `d_meta`, given
821                // `s_meta` (a runtime value) and all other parameters (which
822                // are compile-time values). We can solve like so:
823                //
824                //   D_OFF + d_meta * D_ELEM = S_OFF + s_meta * S_ELEM
825                //
826                //   d_meta * D_ELEM = S_OFF - D_OFF + s_meta * S_ELEM
827                //
828                //   d_meta = (S_OFF - D_OFF + s_meta * S_ELEM)/D_ELEM
829                //
830                // Since `d_meta` will be a `usize`, we need the right-hand side
831                // to be an integer, and this needs to hold for *any* value of
832                // `s_meta` (in order for our conversion to be infallible - ie,
833                // to not have to reject certain values of `s_meta` at runtime).
834                // This means that:
835                //
836                // - `s_meta * S_ELEM` must be a multiple of `D_ELEM`
837                // - Since this must hold for any value of `s_meta`, `S_ELEM`
838                //   must be a multiple of `D_ELEM`
839                // - `S_OFF - D_OFF` must be a multiple of `D_ELEM`
840                //
841                // Thus, let `OFFSET_DELTA_ELEMS = (S_OFF - D_OFF)/D_ELEM` and
842                // `ELEM_MULTIPLE = S_ELEM/D_ELEM`. We can rewrite the above
843                // expression as:
844                //
845                //   d_meta = (S_OFF - D_OFF + s_meta * S_ELEM)/D_ELEM
846                //
847                //   d_meta = OFFSET_DELTA_ELEMS + s_meta * ELEM_MULTIPLE
848                //
849                // Thus, we just need to compute the following and confirm that
850                // they have integer solutions in order to both a) determine
851                // whether infallible `Src` -> `Dst` casts are possible and, b)
852                // pre-compute the parameters necessary to perform those casts
853                // at runtime. These parameters are encapsulated in
854                // `CastParams`, which acts as a witness that such infallible
855                // casts are possible.
856                /// The parameters required in order to perform an
857                /// unsized-to-unsized pointer cast from `Src` to `Dst` as
858                /// described above.
859                ///
860                /// # Safety
861                ///
862                /// `Src` and `Dst` must both be slice DSTs.
863                ///
864                /// `offset_delta_elems` and `elem_multiple` must be valid as
865                /// described above.
866                UnsizedToUnsized { offset_delta_elems: usize, elem_multiple: usize },
867
868                /// The metadata of a `Dst` which has the same size as `Src:
869                /// Sized`.
870                ///
871                /// # Safety
872                ///
873                /// `Src: Sized` and `Dst` must be a slice DST.
874                ///
875                /// A raw `Dst` pointer with metadata `dst_meta` must address
876                /// `size_of::<Src>()` bytes.
877                SizedToUnsized { dst_meta: usize },
878
879                /// The metadata of a `Dst` which has the same size as `Src:
880                /// Sized`.
881                ///
882                /// # Safety
883                ///
884                /// `Src` and `Dst` must both be `Sized` and `size_of::<Src>()
885                /// == size_of::<Dst>()`.
886                SizedToSized,
887            }
888
889            impl<Src: ?Sized, Dst: ?Sized> Copy for CastParams<Src, Dst> {}
890            impl<Src: ?Sized, Dst: ?Sized> Clone for CastParams<Src, Dst> {
891                fn clone(&self) -> Self {
892                    *self
893                }
894            }
895
896            impl<Src: ?Sized, Dst: ?Sized> CastParams<Src, Dst> {
897                const fn try_compute(
898                    src: &DstLayout,
899                    dst: &DstLayout,
900                ) -> Option<CastParams<Src, Dst>> {
901                    if src.align.get() < dst.align.get() {
902                        return None;
903                    }
904
905                    let inner = match (src.size_info, dst.size_info) {
906                        (
907                            SizeInfo::Sized { size: src_size },
908                            SizeInfo::Sized { size: dst_size },
909                        ) => {
910                            if src_size != dst_size {
911                                return None;
912                            }
913
914                            // SAFETY: We checked above that `src_size ==
915                            // dst_size`.
916                            CastParamsInner::SizedToSized
917                        }
918                        (SizeInfo::Sized { size: src_size }, SizeInfo::SliceDst(dst)) => {
919                            let offset_delta = if let Some(od) = src_size.checked_sub(dst.offset) {
920                                od
921                            } else {
922                                return None;
923                            };
924
925                            let dst_elem_size = if let Some(e) = NonZeroUsize::new(dst.elem_size) {
926                                e
927                            } else {
928                                return None;
929                            };
930
931                            // PANICS: `dst_elem_size: NonZeroUsize`, so this won't
932                            // divide by zero.
933                            #[allow(clippy::arithmetic_side_effects)]
934                            let delta_mod_other_elem = offset_delta % dst_elem_size.get();
935
936                            if delta_mod_other_elem != 0 {
937                                return None;
938                            }
939
940                            // PANICS: `dst_elem_size: NonZeroUsize`, so this won't
941                            // divide by zero.
942                            #[allow(clippy::arithmetic_side_effects)]
943                            let dst_meta = offset_delta / dst_elem_size.get();
944
945                            // SAFETY: The preceding math ensures that a `Dst`
946                            // with `dst_meta` addresses `src_size` bytes.
947                            CastParamsInner::SizedToUnsized { dst_meta }
948                        }
949                        (SizeInfo::SliceDst(src), SizeInfo::SliceDst(dst)) => {
950                            let offset_delta = if let Some(od) = src.offset.checked_sub(dst.offset)
951                            {
952                                od
953                            } else {
954                                return None;
955                            };
956
957                            let dst_elem_size = if let Some(e) = NonZeroUsize::new(dst.elem_size) {
958                                e
959                            } else {
960                                return None;
961                            };
962
963                            // PANICS: `dst_elem_size: NonZeroUsize`, so this won't
964                            // divide by zero.
965                            #[allow(clippy::arithmetic_side_effects)]
966                            let delta_mod_other_elem = offset_delta % dst_elem_size.get();
967
968                            // PANICS: `dst_elem_size: NonZeroUsize`, so this won't
969                            // divide by zero.
970                            #[allow(clippy::arithmetic_side_effects)]
971                            let elem_remainder = src.elem_size % dst_elem_size.get();
972
973                            if delta_mod_other_elem != 0
974                                || src.elem_size < dst.elem_size
975                                || elem_remainder != 0
976                            {
977                                return None;
978                            }
979
980                            // PANICS: `dst_elem_size: NonZeroUsize`, so this won't
981                            // divide by zero.
982                            #[allow(clippy::arithmetic_side_effects)]
983                            let offset_delta_elems = offset_delta / dst_elem_size.get();
984
985                            // PANICS: `dst_elem_size: NonZeroUsize`, so this won't
986                            // divide by zero.
987                            #[allow(clippy::arithmetic_side_effects)]
988                            let elem_multiple = src.elem_size / dst_elem_size.get();
989
990                            CastParamsInner::UnsizedToUnsized {
991                                // SAFETY: We checked above that this is an exact ratio.
992                                offset_delta_elems,
993                                // SAFETY: We checked above that this is an exact ratio.
994                                elem_multiple,
995                            }
996                        }
997                        _ => return None,
998                    };
999
1000                    // SAFETY: We checked above that `src.align >= dst.align`.
1001                    Some(CastParams { inner, _src: PhantomData, _dst: PhantomData })
1002                }
1003            }
1004
1005            impl<Src: KnownLayout + ?Sized, Dst: KnownLayout + ?Sized> CastParams<Src, Dst> {
1006                /// # Safety
1007                ///
1008                /// `src_meta` describes a `Src` whose size is no larger than
1009                /// `isize::MAX`.
1010                ///
1011                /// The returned metadata describes a `Dst` of the same size as
1012                /// the original `Src`.
1013                #[inline(always)]
1014                unsafe fn cast_metadata(
1015                    self,
1016                    src_meta: Src::PointerMetadata,
1017                ) -> Dst::PointerMetadata {
1018                    #[allow(unused)]
1019                    use crate::util::polyfills::*;
1020
1021                    let dst_meta = match self.inner {
1022                        CastParamsInner::UnsizedToUnsized { offset_delta_elems, elem_multiple } => {
1023                            let src_meta = src_meta.to_elem_count();
1024                            #[allow(
1025                                unstable_name_collisions,
1026                                clippy::multiple_unsafe_ops_per_block
1027                            )]
1028                            // SAFETY: `self` is a witness that the following
1029                            // equation holds:
1030                            //
1031                            //   D_OFF + d_meta * D_ELEM = S_OFF + s_meta * S_ELEM
1032                            //
1033                            // Since the caller promises that `src_meta` is
1034                            // valid `Src` metadata, this math will not
1035                            // overflow, and the returned value will describe a
1036                            // `Dst` of the same size.
1037                            unsafe {
1038                                offset_delta_elems
1039                                    .unchecked_add(src_meta.unchecked_mul(elem_multiple))
1040                            }
1041                        }
1042                        CastParamsInner::SizedToUnsized { dst_meta } => dst_meta,
1043                        CastParamsInner::SizedToSized => 0,
1044                    };
1045                    Dst::PointerMetadata::from_elem_count(dst_meta)
1046                }
1047            }
1048
1049            trait Params<Src: ?Sized> {
1050                const CAST_PARAMS: CastParams<Src, Self>;
1051            }
1052
1053            impl<Src, Dst> Params<Src> for Dst
1054            where
1055                Src: KnownLayout + ?Sized,
1056                Dst: KnownLayout + ?Sized,
1057            {
1058                const CAST_PARAMS: CastParams<Src, Dst> =
1059                    match CastParams::try_compute(&Src::LAYOUT, &Dst::LAYOUT) {
1060                        Some(params) => params,
1061                        None => const_panic!(
1062                            "cannot `transmute_ref!` or `transmute_mut!` between incompatible types"
1063                        ),
1064                    };
1065            }
1066
1067            let src_meta = <Src as KnownLayout>::pointer_to_metadata(src.as_ptr());
1068            let params = <Dst as Params<Src>>::CAST_PARAMS;
1069
1070            // SAFETY: `src: PtrInner` guarantees that `src`'s referent is zero
1071            // bytes or lives in a single allocation, which means that it is no
1072            // larger than `isize::MAX` bytes [1].
1073            //
1074            // [1] https://doc.rust-lang.org/1.92.0/std/ptr/index.html#allocation
1075            let dst_meta = unsafe { params.cast_metadata(src_meta) };
1076
1077            <Dst as KnownLayout>::raw_from_ptr_len(src.as_non_null().cast(), dst_meta).as_ptr()
1078        }
1079    }
1080}
1081
1082// FIXME(#67): For some reason, on our MSRV toolchain, this `allow` isn't
1083// enforced despite having `#![allow(unknown_lints)]` at the crate root, but
1084// putting it here works. Once our MSRV is high enough that this bug has been
1085// fixed, remove this `allow`.
1086#[allow(unknown_lints)]
1087#[cfg(test)]
1088mod tests {
1089    use super::*;
1090
1091    #[test]
1092    fn test_dst_layout_for_slice() {
1093        let layout = DstLayout::for_slice::<u32>();
1094        match layout.size_info {
1095            SizeInfo::SliceDst(TrailingSliceLayout { offset, elem_size }) => {
1096                assert_eq!(offset, 0);
1097                assert_eq!(elem_size, 4);
1098            }
1099            _ => panic!("Expected SliceDst"),
1100        }
1101        assert_eq!(layout.align.get(), 4);
1102    }
1103
1104    /// Tests of when a sized `DstLayout` is extended with a sized field.
1105    #[allow(clippy::decimal_literal_representation)]
1106    #[test]
1107    fn test_dst_layout_extend_sized_with_sized() {
1108        // This macro constructs a layout corresponding to a `u8` and extends it
1109        // with a zero-sized trailing field of given alignment `n`. The macro
1110        // tests that the resulting layout has both size and alignment `min(n,
1111        // P)` for all valid values of `repr(packed(P))`.
1112        macro_rules! test_align_is_size {
1113            ($n:expr) => {
1114                let base = DstLayout::for_type::<u8>();
1115                let trailing_field = DstLayout::for_type::<elain::Align<$n>>();
1116
1117                let packs =
1118                    core::iter::once(None).chain((0..29).map(|p| NonZeroUsize::new(2usize.pow(p))));
1119
1120                for pack in packs {
1121                    let composite = base.extend(trailing_field, pack);
1122                    let max_align = pack.unwrap_or(DstLayout::CURRENT_MAX_ALIGN);
1123                    let align = $n.min(max_align.get());
1124                    assert_eq!(
1125                        composite,
1126                        DstLayout {
1127                            align: NonZeroUsize::new(align).unwrap(),
1128                            size_info: SizeInfo::Sized { size: align },
1129                            statically_shallow_unpadded: false,
1130                        }
1131                    )
1132                }
1133            };
1134        }
1135
1136        test_align_is_size!(1);
1137        test_align_is_size!(2);
1138        test_align_is_size!(4);
1139        test_align_is_size!(8);
1140        test_align_is_size!(16);
1141        test_align_is_size!(32);
1142        test_align_is_size!(64);
1143        test_align_is_size!(128);
1144        test_align_is_size!(256);
1145        test_align_is_size!(512);
1146        test_align_is_size!(1024);
1147        test_align_is_size!(2048);
1148        test_align_is_size!(4096);
1149        test_align_is_size!(8192);
1150        test_align_is_size!(16384);
1151        test_align_is_size!(32768);
1152        test_align_is_size!(65536);
1153        test_align_is_size!(131072);
1154        test_align_is_size!(262144);
1155        test_align_is_size!(524288);
1156        test_align_is_size!(1048576);
1157        test_align_is_size!(2097152);
1158        test_align_is_size!(4194304);
1159        test_align_is_size!(8388608);
1160        test_align_is_size!(16777216);
1161        test_align_is_size!(33554432);
1162        test_align_is_size!(67108864);
1163        test_align_is_size!(33554432);
1164        test_align_is_size!(134217728);
1165        test_align_is_size!(268435456);
1166    }
1167
1168    /// Tests of when a sized `DstLayout` is extended with a DST field.
1169    #[test]
1170    fn test_dst_layout_extend_sized_with_dst() {
1171        // Test that for all combinations of real-world alignments and
1172        // `repr_packed` values, that the extension of a sized `DstLayout`` with
1173        // a DST field correctly computes the trailing offset in the composite
1174        // layout.
1175
1176        let aligns = (0..29).map(|p| NonZeroUsize::new(2usize.pow(p)).unwrap());
1177        let packs = core::iter::once(None).chain(aligns.clone().map(Some));
1178
1179        for align in aligns {
1180            for pack in packs.clone() {
1181                let base = DstLayout::for_type::<u8>();
1182                let elem_size = 42;
1183                let trailing_field_offset = 11;
1184
1185                let trailing_field = DstLayout {
1186                    align,
1187                    size_info: SizeInfo::SliceDst(TrailingSliceLayout { elem_size, offset: 11 }),
1188                    statically_shallow_unpadded: false,
1189                };
1190
1191                let composite = base.extend(trailing_field, pack);
1192
1193                let max_align = pack.unwrap_or(DstLayout::CURRENT_MAX_ALIGN).get();
1194
1195                let align = align.get().min(max_align);
1196
1197                assert_eq!(
1198                    composite,
1199                    DstLayout {
1200                        align: NonZeroUsize::new(align).unwrap(),
1201                        size_info: SizeInfo::SliceDst(TrailingSliceLayout {
1202                            elem_size,
1203                            offset: align + trailing_field_offset,
1204                        }),
1205                        statically_shallow_unpadded: false,
1206                    }
1207                )
1208            }
1209        }
1210    }
1211
1212    /// Tests that calling `pad_to_align` on a sized `DstLayout` adds the
1213    /// expected amount of trailing padding.
1214    #[test]
1215    fn test_dst_layout_pad_to_align_with_sized() {
1216        // For all valid alignments `align`, construct a one-byte layout aligned
1217        // to `align`, call `pad_to_align`, and assert that the size of the
1218        // resulting layout is equal to `align`.
1219        for align in (0..29).map(|p| NonZeroUsize::new(2usize.pow(p)).unwrap()) {
1220            let layout = DstLayout {
1221                align,
1222                size_info: SizeInfo::Sized { size: 1 },
1223                statically_shallow_unpadded: true,
1224            };
1225
1226            assert_eq!(
1227                layout.pad_to_align(),
1228                DstLayout {
1229                    align,
1230                    size_info: SizeInfo::Sized { size: align.get() },
1231                    statically_shallow_unpadded: align.get() == 1
1232                }
1233            );
1234        }
1235
1236        // Test explicitly-provided combinations of unpadded and padded
1237        // counterparts.
1238
1239        macro_rules! test {
1240            (unpadded { size: $unpadded_size:expr, align: $unpadded_align:expr }
1241                    => padded { size: $padded_size:expr, align: $padded_align:expr }) => {
1242                let unpadded = DstLayout {
1243                    align: NonZeroUsize::new($unpadded_align).unwrap(),
1244                    size_info: SizeInfo::Sized { size: $unpadded_size },
1245                    statically_shallow_unpadded: false,
1246                };
1247                let padded = unpadded.pad_to_align();
1248
1249                assert_eq!(
1250                    padded,
1251                    DstLayout {
1252                        align: NonZeroUsize::new($padded_align).unwrap(),
1253                        size_info: SizeInfo::Sized { size: $padded_size },
1254                        statically_shallow_unpadded: false,
1255                    }
1256                );
1257            };
1258        }
1259
1260        test!(unpadded { size: 0, align: 4 } => padded { size: 0, align: 4 });
1261        test!(unpadded { size: 1, align: 4 } => padded { size: 4, align: 4 });
1262        test!(unpadded { size: 2, align: 4 } => padded { size: 4, align: 4 });
1263        test!(unpadded { size: 3, align: 4 } => padded { size: 4, align: 4 });
1264        test!(unpadded { size: 4, align: 4 } => padded { size: 4, align: 4 });
1265        test!(unpadded { size: 5, align: 4 } => padded { size: 8, align: 4 });
1266        test!(unpadded { size: 6, align: 4 } => padded { size: 8, align: 4 });
1267        test!(unpadded { size: 7, align: 4 } => padded { size: 8, align: 4 });
1268        test!(unpadded { size: 8, align: 4 } => padded { size: 8, align: 4 });
1269
1270        let current_max_align = DstLayout::CURRENT_MAX_ALIGN.get();
1271
1272        test!(unpadded { size: 1, align: current_max_align }
1273                => padded { size: current_max_align, align: current_max_align });
1274
1275        test!(unpadded { size: current_max_align + 1, align: current_max_align }
1276                => padded { size: current_max_align * 2, align: current_max_align });
1277    }
1278
1279    /// Tests that calling `pad_to_align` on a DST `DstLayout` is a no-op.
1280    #[test]
1281    fn test_dst_layout_pad_to_align_with_dst() {
1282        for align in (0..29).map(|p| NonZeroUsize::new(2usize.pow(p)).unwrap()) {
1283            for offset in 0..10 {
1284                for elem_size in 0..10 {
1285                    let layout = DstLayout {
1286                        align,
1287                        size_info: SizeInfo::SliceDst(TrailingSliceLayout { offset, elem_size }),
1288                        statically_shallow_unpadded: false,
1289                    };
1290                    assert_eq!(layout.pad_to_align(), layout);
1291                }
1292            }
1293        }
1294    }
1295
1296    // This test takes a long time when running under Miri, so we skip it in
1297    // that case. This is acceptable because this is a logic test that doesn't
1298    // attempt to expose UB.
1299    #[test]
1300    #[cfg_attr(miri, ignore)]
1301    fn test_validate_cast_and_convert_metadata() {
1302        #[allow(non_local_definitions)]
1303        impl From<usize> for SizeInfo {
1304            fn from(size: usize) -> SizeInfo {
1305                SizeInfo::Sized { size }
1306            }
1307        }
1308
1309        #[allow(non_local_definitions)]
1310        impl From<(usize, usize)> for SizeInfo {
1311            fn from((offset, elem_size): (usize, usize)) -> SizeInfo {
1312                SizeInfo::SliceDst(TrailingSliceLayout { offset, elem_size })
1313            }
1314        }
1315
1316        fn layout<S: Into<SizeInfo>>(s: S, align: usize) -> DstLayout {
1317            DstLayout {
1318                size_info: s.into(),
1319                align: NonZeroUsize::new(align).unwrap(),
1320                statically_shallow_unpadded: false,
1321            }
1322        }
1323
1324        /// This macro accepts arguments in the form of:
1325        ///
1326        ///           layout(_, _).validate(_, _, _), Ok(Some((_, _)))
1327        ///                  |  |           |  |  |            |  |
1328        ///    size ---------+  |           |  |  |            |  |
1329        ///    align -----------+           |  |  |            |  |
1330        ///    addr ------------------------+  |  |            |  |
1331        ///    bytes_len ----------------------+  |            |  |
1332        ///    cast_type -------------------------+            |  |
1333        ///    elems ------------------------------------------+  |
1334        ///    split_at ------------------------------------------+
1335        ///
1336        /// `.validate` is shorthand for `.validate_cast_and_convert_metadata`
1337        /// for brevity.
1338        ///
1339        /// Each argument can either be an iterator or a wildcard. Each
1340        /// wildcarded variable is implicitly replaced by an iterator over a
1341        /// representative sample of values for that variable. Each `test!`
1342        /// invocation iterates over every combination of values provided by
1343        /// each variable's iterator (ie, the cartesian product) and validates
1344        /// that the results are expected.
1345        ///
1346        /// The final argument uses the same syntax, but it has a different
1347        /// meaning:
1348        /// - If it is `Ok(pat)`, then the pattern `pat` is supplied to
1349        ///   a matching assert to validate the computed result for each
1350        ///   combination of input values.
1351        /// - If it is `Err(Some(msg) | None)`, then `test!` validates that the
1352        ///   call to `validate_cast_and_convert_metadata` panics with the given
1353        ///   panic message or, if the current Rust toolchain version is too
1354        ///   early to support panicking in `const fn`s, panics with *some*
1355        ///   message. In the latter case, the `const_panic!` macro is used,
1356        ///   which emits code which causes a non-panicking error at const eval
1357        ///   time, but which does panic when invoked at runtime. Thus, it is
1358        ///   merely difficult to predict the *value* of this panic. We deem
1359        ///   that testing against the real panic strings on stable and nightly
1360        ///   toolchains is enough to ensure correctness.
1361        ///
1362        /// Note that the meta-variables that match these variables have the
1363        /// `tt` type, and some valid expressions are not valid `tt`s (such as
1364        /// `a..b`). In this case, wrap the expression in parentheses, and it
1365        /// will become valid `tt`.
1366        macro_rules! test {
1367                (
1368                    layout($size:tt, $align:tt)
1369                    .validate($addr:tt, $bytes_len:tt, $cast_type:tt), $expect:pat $(,)?
1370                ) => {
1371                    itertools::iproduct!(
1372                        test!(@generate_size $size),
1373                        test!(@generate_align $align),
1374                        test!(@generate_usize $addr),
1375                        test!(@generate_usize $bytes_len),
1376                        test!(@generate_cast_type $cast_type)
1377                    ).for_each(|(size_info, align, addr, bytes_len, cast_type)| {
1378                        // Temporarily disable the panic hook installed by the test
1379                        // harness. If we don't do this, all panic messages will be
1380                        // kept in an internal log. On its own, this isn't a
1381                        // problem, but if a non-caught panic ever happens (ie, in
1382                        // code later in this test not in this macro), all of the
1383                        // previously-buffered messages will be dumped, hiding the
1384                        // real culprit.
1385                        let previous_hook = std::panic::take_hook();
1386                        // I don't understand why, but this seems to be required in
1387                        // addition to the previous line.
1388                        std::panic::set_hook(Box::new(|_| {}));
1389                        let actual = std::panic::catch_unwind(|| {
1390                            layout(size_info, align).validate_cast_and_convert_metadata(addr, bytes_len, cast_type)
1391                        }).map_err(|d| {
1392                            let msg = d.downcast::<&'static str>().ok().map(|s| *s.as_ref());
1393                            assert!(msg.is_some() || cfg!(no_zerocopy_panic_in_const_and_vec_try_reserve_1_57_0), "non-string panic messages are not permitted when usage of panic in const fn is enabled");
1394                            msg
1395                        });
1396                        std::panic::set_hook(previous_hook);
1397
1398                        assert!(
1399                            matches!(actual, $expect),
1400                            "layout({:?}, {}).validate_cast_and_convert_metadata({}, {}, {:?})" ,size_info, align, addr, bytes_len, cast_type
1401                        );
1402                    });
1403                };
1404                (@generate_usize _) => { 0..8 };
1405                // Generate sizes for both Sized and !Sized types.
1406                (@generate_size _) => {
1407                    test!(@generate_size (_)).chain(test!(@generate_size (_, _)))
1408                };
1409                // Generate sizes for both Sized and !Sized types by chaining
1410                // specified iterators for each.
1411                (@generate_size ($sized_sizes:tt | $unsized_sizes:tt)) => {
1412                    test!(@generate_size ($sized_sizes)).chain(test!(@generate_size $unsized_sizes))
1413                };
1414                // Generate sizes for Sized types.
1415                (@generate_size (_)) => { test!(@generate_size (0..8)) };
1416                (@generate_size ($sizes:expr)) => { $sizes.into_iter().map(Into::<SizeInfo>::into) };
1417                // Generate sizes for !Sized types.
1418                (@generate_size ($min_sizes:tt, $elem_sizes:tt)) => {
1419                    itertools::iproduct!(
1420                        test!(@generate_min_size $min_sizes),
1421                        test!(@generate_elem_size $elem_sizes)
1422                    ).map(Into::<SizeInfo>::into)
1423                };
1424                (@generate_fixed_size _) => { (0..8).into_iter().map(Into::<SizeInfo>::into) };
1425                (@generate_min_size _) => { 0..8 };
1426                (@generate_elem_size _) => { 1..8 };
1427                (@generate_align _) => { [1, 2, 4, 8, 16] };
1428                (@generate_opt_usize _) => { [None].into_iter().chain((0..8).map(Some).into_iter()) };
1429                (@generate_cast_type _) => { [CastType::Prefix, CastType::Suffix] };
1430                (@generate_cast_type $variant:ident) => { [CastType::$variant] };
1431                // Some expressions need to be wrapped in parentheses in order to be
1432                // valid `tt`s (required by the top match pattern). See the comment
1433                // below for more details. This arm removes these parentheses to
1434                // avoid generating an `unused_parens` warning.
1435                (@$_:ident ($vals:expr)) => { $vals };
1436                (@$_:ident $vals:expr) => { $vals };
1437            }
1438
1439        const EVENS: [usize; 8] = [0, 2, 4, 6, 8, 10, 12, 14];
1440        const ODDS: [usize; 8] = [1, 3, 5, 7, 9, 11, 13, 15];
1441
1442        // base_size is too big for the memory region.
1443        test!(
1444            layout(((1..8) | ((1..8), (1..8))), _).validate([0], [0], _),
1445            Ok(Err(MetadataCastError::Size))
1446        );
1447        test!(
1448            layout(((2..8) | ((2..8), (2..8))), _).validate([0], [1], Prefix),
1449            Ok(Err(MetadataCastError::Size))
1450        );
1451        test!(
1452            layout(((2..8) | ((2..8), (2..8))), _).validate([0x1000_0000 - 1], [1], Suffix),
1453            Ok(Err(MetadataCastError::Size))
1454        );
1455
1456        // addr is unaligned for prefix cast
1457        test!(layout(_, [2]).validate(ODDS, _, Prefix), Ok(Err(MetadataCastError::Alignment)));
1458        test!(layout(_, [2]).validate(ODDS, _, Prefix), Ok(Err(MetadataCastError::Alignment)));
1459
1460        // addr is aligned, but end of buffer is unaligned for suffix cast
1461        test!(layout(_, [2]).validate(EVENS, ODDS, Suffix), Ok(Err(MetadataCastError::Alignment)));
1462        test!(layout(_, [2]).validate(EVENS, ODDS, Suffix), Ok(Err(MetadataCastError::Alignment)));
1463
1464        // Unfortunately, these constants cannot easily be used in the
1465        // implementation of `validate_cast_and_convert_metadata`, since
1466        // `panic!` consumes a string literal, not an expression.
1467        //
1468        // It's important that these messages be in a separate module. If they
1469        // were at the function's top level, we'd pass them to `test!` as, e.g.,
1470        // `Err(TRAILING)`, which would run into a subtle Rust footgun - the
1471        // `TRAILING` identifier would be treated as a pattern to match rather
1472        // than a value to check for equality.
1473        mod msgs {
1474            pub(super) const TRAILING: &str =
1475                "attempted to cast to slice type with zero-sized element";
1476            pub(super) const OVERFLOW: &str = "`addr` + `bytes_len` > usize::MAX";
1477        }
1478
1479        // casts with ZST trailing element types are unsupported
1480        test!(layout((_, [0]), _).validate(_, _, _), Err(Some(msgs::TRAILING) | None),);
1481
1482        // addr + bytes_len must not overflow usize
1483        test!(layout(_, _).validate([usize::MAX], (1..100), _), Err(Some(msgs::OVERFLOW) | None));
1484        test!(layout(_, _).validate((1..100), [usize::MAX], _), Err(Some(msgs::OVERFLOW) | None));
1485        test!(
1486            layout(_, _).validate(
1487                [usize::MAX / 2 + 1, usize::MAX],
1488                [usize::MAX / 2 + 1, usize::MAX],
1489                _
1490            ),
1491            Err(Some(msgs::OVERFLOW) | None)
1492        );
1493
1494        // Validates that `validate_cast_and_convert_metadata` satisfies its own
1495        // documented safety postconditions, and also a few other properties
1496        // that aren't documented but we want to guarantee anyway.
1497        fn validate_behavior(
1498            (layout, addr, bytes_len, cast_type): (DstLayout, usize, usize, CastType),
1499        ) {
1500            if let Ok((elems, split_at)) =
1501                layout.validate_cast_and_convert_metadata(addr, bytes_len, cast_type)
1502            {
1503                let (size_info, align) = (layout.size_info, layout.align);
1504                let debug_str = format!(
1505                    "layout({:?}, {}).validate_cast_and_convert_metadata({}, {}, {:?}) => ({}, {})",
1506                    size_info, align, addr, bytes_len, cast_type, elems, split_at
1507                );
1508
1509                // If this is a sized type (no trailing slice), then `elems` is
1510                // meaningless, but in practice we set it to 0. Callers are not
1511                // allowed to rely on this, but a lot of math is nicer if
1512                // they're able to, and some callers might accidentally do that.
1513                let sized = matches!(layout.size_info, SizeInfo::Sized { .. });
1514                assert!(!(sized && elems != 0), "{}", debug_str);
1515
1516                let resulting_size = match layout.size_info {
1517                    SizeInfo::Sized { size } => size,
1518                    SizeInfo::SliceDst(TrailingSliceLayout { offset, elem_size }) => {
1519                        let padded_size = |elems| {
1520                            let without_padding = offset + elems * elem_size;
1521                            without_padding + util::padding_needed_for(without_padding, align)
1522                        };
1523
1524                        let resulting_size = padded_size(elems);
1525                        // Test that `validate_cast_and_convert_metadata`
1526                        // computed the largest possible value that fits in the
1527                        // given range.
1528                        assert!(padded_size(elems + 1) > bytes_len, "{}", debug_str);
1529                        resulting_size
1530                    }
1531                };
1532
1533                // Test safety postconditions guaranteed by
1534                // `validate_cast_and_convert_metadata`.
1535                assert!(resulting_size <= bytes_len, "{}", debug_str);
1536                match cast_type {
1537                    CastType::Prefix => {
1538                        assert_eq!(addr % align, 0, "{}", debug_str);
1539                        assert_eq!(resulting_size, split_at, "{}", debug_str);
1540                    }
1541                    CastType::Suffix => {
1542                        assert_eq!(split_at, bytes_len - resulting_size, "{}", debug_str);
1543                        assert_eq!((addr + split_at) % align, 0, "{}", debug_str);
1544                    }
1545                }
1546            } else {
1547                let min_size = match layout.size_info {
1548                    SizeInfo::Sized { size } => size,
1549                    SizeInfo::SliceDst(TrailingSliceLayout { offset, .. }) => {
1550                        offset + util::padding_needed_for(offset, layout.align)
1551                    }
1552                };
1553
1554                // If a cast is invalid, it is either because...
1555                // 1. there are insufficient bytes at the given region for type:
1556                let insufficient_bytes = bytes_len < min_size;
1557                // 2. performing the cast would misalign type:
1558                let base = match cast_type {
1559                    CastType::Prefix => 0,
1560                    CastType::Suffix => bytes_len,
1561                };
1562                let misaligned = (base + addr) % layout.align != 0;
1563
1564                assert!(insufficient_bytes || misaligned);
1565            }
1566        }
1567
1568        let sizes = 0..8;
1569        let elem_sizes = 1..8;
1570        let size_infos = sizes
1571            .clone()
1572            .map(Into::<SizeInfo>::into)
1573            .chain(itertools::iproduct!(sizes, elem_sizes).map(Into::<SizeInfo>::into));
1574        let layouts = itertools::iproduct!(size_infos, [1, 2, 4, 8, 16, 32])
1575                .filter(|(size_info, align)| !matches!(size_info, SizeInfo::Sized { size } if size % align != 0))
1576                .map(|(size_info, align)| layout(size_info, align));
1577        itertools::iproduct!(layouts, 0..8, 0..8, [CastType::Prefix, CastType::Suffix])
1578            .for_each(validate_behavior);
1579    }
1580
1581    #[test]
1582    #[cfg(__ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS)]
1583    fn test_validate_rust_layout() {
1584        use core::{
1585            convert::TryInto as _,
1586            ptr::{self, NonNull},
1587        };
1588
1589        use crate::util::testutil::*;
1590
1591        // This test synthesizes pointers with various metadata and uses Rust's
1592        // built-in APIs to confirm that Rust makes decisions about type layout
1593        // which are consistent with what we believe is guaranteed by the
1594        // language. If this test fails, it doesn't just mean our code is wrong
1595        // - it means we're misunderstanding the language's guarantees.
1596
1597        #[derive(Debug)]
1598        struct MacroArgs {
1599            offset: usize,
1600            align: NonZeroUsize,
1601            elem_size: Option<usize>,
1602        }
1603
1604        /// # Safety
1605        ///
1606        /// `test` promises to only call `addr_of_slice_field` on a `NonNull<T>`
1607        /// which points to a valid `T`.
1608        ///
1609        /// `with_elems` must produce a pointer which points to a valid `T`.
1610        fn test<T: ?Sized, W: Fn(usize) -> NonNull<T>>(
1611            args: MacroArgs,
1612            with_elems: W,
1613            addr_of_slice_field: Option<fn(NonNull<T>) -> NonNull<u8>>,
1614        ) {
1615            let dst = args.elem_size.is_some();
1616            let layout = {
1617                let size_info = match args.elem_size {
1618                    Some(elem_size) => {
1619                        SizeInfo::SliceDst(TrailingSliceLayout { offset: args.offset, elem_size })
1620                    }
1621                    None => SizeInfo::Sized {
1622                        // Rust only supports types whose sizes are a multiple
1623                        // of their alignment. If the macro created a type like
1624                        // this:
1625                        //
1626                        //   #[repr(C, align(2))]
1627                        //   struct Foo([u8; 1]);
1628                        //
1629                        // ...then Rust will automatically round the type's size
1630                        // up to 2.
1631                        size: args.offset + util::padding_needed_for(args.offset, args.align),
1632                    },
1633                };
1634                DstLayout { size_info, align: args.align, statically_shallow_unpadded: false }
1635            };
1636
1637            for elems in 0..128 {
1638                let ptr = with_elems(elems);
1639
1640                if let Some(addr_of_slice_field) = addr_of_slice_field {
1641                    let slc_field_ptr = addr_of_slice_field(ptr).as_ptr();
1642                    // SAFETY: Both `slc_field_ptr` and `ptr` are pointers to
1643                    // the same valid Rust object.
1644                    // Work around https://github.com/rust-lang/rust-clippy/issues/12280
1645                    let offset: usize =
1646                        unsafe { slc_field_ptr.byte_offset_from(ptr.as_ptr()).try_into().unwrap() };
1647                    assert_eq!(offset, args.offset);
1648                }
1649
1650                // SAFETY: `ptr` points to a valid `T`.
1651                #[allow(clippy::multiple_unsafe_ops_per_block)]
1652                let (size, align) = unsafe {
1653                    (mem::size_of_val_raw(ptr.as_ptr()), mem::align_of_val_raw(ptr.as_ptr()))
1654                };
1655
1656                // Avoid expensive allocation when running under Miri.
1657                let assert_msg = if !cfg!(miri) {
1658                    format!("\n{:?}\nsize:{}, align:{}", args, size, align)
1659                } else {
1660                    String::new()
1661                };
1662
1663                let without_padding =
1664                    args.offset + args.elem_size.map(|elem_size| elems * elem_size).unwrap_or(0);
1665                assert!(size >= without_padding, "{}", assert_msg);
1666                assert_eq!(align, args.align.get(), "{}", assert_msg);
1667
1668                // This encodes the most important part of the test: our
1669                // understanding of how Rust determines the layout of repr(C)
1670                // types. Sized repr(C) types are trivial, but DST types have
1671                // some subtlety. Note that:
1672                // - For sized types, `without_padding` is just the size of the
1673                //   type that we constructed for `Foo`. Since we may have
1674                //   requested a larger alignment, `Foo` may actually be larger
1675                //   than this, hence `padding_needed_for`.
1676                // - For unsized types, `without_padding` is dynamically
1677                //   computed from the offset, the element size, and element
1678                //   count. We expect that the size of the object should be
1679                //   `offset + elem_size * elems` rounded up to the next
1680                //   alignment.
1681                let expected_size =
1682                    without_padding + util::padding_needed_for(without_padding, args.align);
1683                assert_eq!(expected_size, size, "{}", assert_msg);
1684
1685                // For zero-sized element types,
1686                // `validate_cast_and_convert_metadata` just panics, so we skip
1687                // testing those types.
1688                if args.elem_size.map(|elem_size| elem_size > 0).unwrap_or(true) {
1689                    let addr = ptr.addr().get();
1690                    let (got_elems, got_split_at) = layout
1691                        .validate_cast_and_convert_metadata(addr, size, CastType::Prefix)
1692                        .unwrap();
1693                    // Avoid expensive allocation when running under Miri.
1694                    let assert_msg = if !cfg!(miri) {
1695                        format!(
1696                            "{}\nvalidate_cast_and_convert_metadata({}, {})",
1697                            assert_msg, addr, size,
1698                        )
1699                    } else {
1700                        String::new()
1701                    };
1702                    assert_eq!(got_split_at, size, "{}", assert_msg);
1703                    if dst {
1704                        assert!(got_elems >= elems, "{}", assert_msg);
1705                        if got_elems != elems {
1706                            // If `validate_cast_and_convert_metadata`
1707                            // returned more elements than `elems`, that
1708                            // means that `elems` is not the maximum number
1709                            // of elements that can fit in `size` - in other
1710                            // words, there is enough padding at the end of
1711                            // the value to fit at least one more element.
1712                            // If we use this metadata to synthesize a
1713                            // pointer, despite having a different element
1714                            // count, we still expect it to have the same
1715                            // size.
1716                            let got_ptr = with_elems(got_elems);
1717                            // SAFETY: `got_ptr` is a pointer to a valid `T`.
1718                            let size_of_got_ptr = unsafe { mem::size_of_val_raw(got_ptr.as_ptr()) };
1719                            assert_eq!(size_of_got_ptr, size, "{}", assert_msg);
1720                        }
1721                    } else {
1722                        // For sized casts, the returned element value is
1723                        // technically meaningless, and we don't guarantee any
1724                        // particular value. In practice, it's always zero.
1725                        assert_eq!(got_elems, 0, "{}", assert_msg)
1726                    }
1727                }
1728            }
1729        }
1730
1731        macro_rules! validate_against_rust {
1732                ($offset:literal, $align:literal $(, $elem_size:literal)?) => {{
1733                    #[repr(C, align($align))]
1734                    struct Foo([u8; $offset]$(, [[u8; $elem_size]])?);
1735
1736                    let args = MacroArgs {
1737                        offset: $offset,
1738                        align: $align.try_into().unwrap(),
1739                        elem_size: {
1740                            #[allow(unused)]
1741                            let ret = None::<usize>;
1742                            $(let ret = Some($elem_size);)?
1743                            ret
1744                        }
1745                    };
1746
1747                    #[repr(C, align($align))]
1748                    struct FooAlign;
1749                    // Create an aligned buffer to use in order to synthesize
1750                    // pointers to `Foo`. We don't ever load values from these
1751                    // pointers - we just do arithmetic on them - so having a "real"
1752                    // block of memory as opposed to a validly-aligned-but-dangling
1753                    // pointer is only necessary to make Miri happy since we run it
1754                    // with "strict provenance" checking enabled.
1755                    let aligned_buf = Align::<_, FooAlign>::new([0u8; 1024]);
1756                    let with_elems = |elems| {
1757                        let slc = NonNull::slice_from_raw_parts(NonNull::from(&aligned_buf.t), elems);
1758                        #[allow(clippy::as_conversions)]
1759                        NonNull::new(slc.as_ptr() as *mut Foo).unwrap()
1760                    };
1761                    let addr_of_slice_field = {
1762                        #[allow(unused)]
1763                        let f = None::<fn(NonNull<Foo>) -> NonNull<u8>>;
1764                        $(
1765                            // SAFETY: `test` promises to only call `f` with a `ptr`
1766                            // to a valid `Foo`.
1767                            let f: Option<fn(NonNull<Foo>) -> NonNull<u8>> = Some(|ptr: NonNull<Foo>| unsafe {
1768                                NonNull::new(ptr::addr_of_mut!((*ptr.as_ptr()).1)).unwrap().cast::<u8>()
1769                            });
1770                            let _ = $elem_size;
1771                        )?
1772                        f
1773                    };
1774
1775                    test::<Foo, _>(args, with_elems, addr_of_slice_field);
1776                }};
1777            }
1778
1779        // Every permutation of:
1780        // - offset in [0, 4]
1781        // - align in [1, 16]
1782        // - elem_size in [0, 4] (plus no elem_size)
1783        validate_against_rust!(0, 1);
1784        validate_against_rust!(0, 1, 0);
1785        validate_against_rust!(0, 1, 1);
1786        validate_against_rust!(0, 1, 2);
1787        validate_against_rust!(0, 1, 3);
1788        validate_against_rust!(0, 1, 4);
1789        validate_against_rust!(0, 2);
1790        validate_against_rust!(0, 2, 0);
1791        validate_against_rust!(0, 2, 1);
1792        validate_against_rust!(0, 2, 2);
1793        validate_against_rust!(0, 2, 3);
1794        validate_against_rust!(0, 2, 4);
1795        validate_against_rust!(0, 4);
1796        validate_against_rust!(0, 4, 0);
1797        validate_against_rust!(0, 4, 1);
1798        validate_against_rust!(0, 4, 2);
1799        validate_against_rust!(0, 4, 3);
1800        validate_against_rust!(0, 4, 4);
1801        validate_against_rust!(0, 8);
1802        validate_against_rust!(0, 8, 0);
1803        validate_against_rust!(0, 8, 1);
1804        validate_against_rust!(0, 8, 2);
1805        validate_against_rust!(0, 8, 3);
1806        validate_against_rust!(0, 8, 4);
1807        validate_against_rust!(0, 16);
1808        validate_against_rust!(0, 16, 0);
1809        validate_against_rust!(0, 16, 1);
1810        validate_against_rust!(0, 16, 2);
1811        validate_against_rust!(0, 16, 3);
1812        validate_against_rust!(0, 16, 4);
1813        validate_against_rust!(1, 1);
1814        validate_against_rust!(1, 1, 0);
1815        validate_against_rust!(1, 1, 1);
1816        validate_against_rust!(1, 1, 2);
1817        validate_against_rust!(1, 1, 3);
1818        validate_against_rust!(1, 1, 4);
1819        validate_against_rust!(1, 2);
1820        validate_against_rust!(1, 2, 0);
1821        validate_against_rust!(1, 2, 1);
1822        validate_against_rust!(1, 2, 2);
1823        validate_against_rust!(1, 2, 3);
1824        validate_against_rust!(1, 2, 4);
1825        validate_against_rust!(1, 4);
1826        validate_against_rust!(1, 4, 0);
1827        validate_against_rust!(1, 4, 1);
1828        validate_against_rust!(1, 4, 2);
1829        validate_against_rust!(1, 4, 3);
1830        validate_against_rust!(1, 4, 4);
1831        validate_against_rust!(1, 8);
1832        validate_against_rust!(1, 8, 0);
1833        validate_against_rust!(1, 8, 1);
1834        validate_against_rust!(1, 8, 2);
1835        validate_against_rust!(1, 8, 3);
1836        validate_against_rust!(1, 8, 4);
1837        validate_against_rust!(1, 16);
1838        validate_against_rust!(1, 16, 0);
1839        validate_against_rust!(1, 16, 1);
1840        validate_against_rust!(1, 16, 2);
1841        validate_against_rust!(1, 16, 3);
1842        validate_against_rust!(1, 16, 4);
1843        validate_against_rust!(2, 1);
1844        validate_against_rust!(2, 1, 0);
1845        validate_against_rust!(2, 1, 1);
1846        validate_against_rust!(2, 1, 2);
1847        validate_against_rust!(2, 1, 3);
1848        validate_against_rust!(2, 1, 4);
1849        validate_against_rust!(2, 2);
1850        validate_against_rust!(2, 2, 0);
1851        validate_against_rust!(2, 2, 1);
1852        validate_against_rust!(2, 2, 2);
1853        validate_against_rust!(2, 2, 3);
1854        validate_against_rust!(2, 2, 4);
1855        validate_against_rust!(2, 4);
1856        validate_against_rust!(2, 4, 0);
1857        validate_against_rust!(2, 4, 1);
1858        validate_against_rust!(2, 4, 2);
1859        validate_against_rust!(2, 4, 3);
1860        validate_against_rust!(2, 4, 4);
1861        validate_against_rust!(2, 8);
1862        validate_against_rust!(2, 8, 0);
1863        validate_against_rust!(2, 8, 1);
1864        validate_against_rust!(2, 8, 2);
1865        validate_against_rust!(2, 8, 3);
1866        validate_against_rust!(2, 8, 4);
1867        validate_against_rust!(2, 16);
1868        validate_against_rust!(2, 16, 0);
1869        validate_against_rust!(2, 16, 1);
1870        validate_against_rust!(2, 16, 2);
1871        validate_against_rust!(2, 16, 3);
1872        validate_against_rust!(2, 16, 4);
1873        validate_against_rust!(3, 1);
1874        validate_against_rust!(3, 1, 0);
1875        validate_against_rust!(3, 1, 1);
1876        validate_against_rust!(3, 1, 2);
1877        validate_against_rust!(3, 1, 3);
1878        validate_against_rust!(3, 1, 4);
1879        validate_against_rust!(3, 2);
1880        validate_against_rust!(3, 2, 0);
1881        validate_against_rust!(3, 2, 1);
1882        validate_against_rust!(3, 2, 2);
1883        validate_against_rust!(3, 2, 3);
1884        validate_against_rust!(3, 2, 4);
1885        validate_against_rust!(3, 4);
1886        validate_against_rust!(3, 4, 0);
1887        validate_against_rust!(3, 4, 1);
1888        validate_against_rust!(3, 4, 2);
1889        validate_against_rust!(3, 4, 3);
1890        validate_against_rust!(3, 4, 4);
1891        validate_against_rust!(3, 8);
1892        validate_against_rust!(3, 8, 0);
1893        validate_against_rust!(3, 8, 1);
1894        validate_against_rust!(3, 8, 2);
1895        validate_against_rust!(3, 8, 3);
1896        validate_against_rust!(3, 8, 4);
1897        validate_against_rust!(3, 16);
1898        validate_against_rust!(3, 16, 0);
1899        validate_against_rust!(3, 16, 1);
1900        validate_against_rust!(3, 16, 2);
1901        validate_against_rust!(3, 16, 3);
1902        validate_against_rust!(3, 16, 4);
1903        validate_against_rust!(4, 1);
1904        validate_against_rust!(4, 1, 0);
1905        validate_against_rust!(4, 1, 1);
1906        validate_against_rust!(4, 1, 2);
1907        validate_against_rust!(4, 1, 3);
1908        validate_against_rust!(4, 1, 4);
1909        validate_against_rust!(4, 2);
1910        validate_against_rust!(4, 2, 0);
1911        validate_against_rust!(4, 2, 1);
1912        validate_against_rust!(4, 2, 2);
1913        validate_against_rust!(4, 2, 3);
1914        validate_against_rust!(4, 2, 4);
1915        validate_against_rust!(4, 4);
1916        validate_against_rust!(4, 4, 0);
1917        validate_against_rust!(4, 4, 1);
1918        validate_against_rust!(4, 4, 2);
1919        validate_against_rust!(4, 4, 3);
1920        validate_against_rust!(4, 4, 4);
1921        validate_against_rust!(4, 8);
1922        validate_against_rust!(4, 8, 0);
1923        validate_against_rust!(4, 8, 1);
1924        validate_against_rust!(4, 8, 2);
1925        validate_against_rust!(4, 8, 3);
1926        validate_against_rust!(4, 8, 4);
1927        validate_against_rust!(4, 16);
1928        validate_against_rust!(4, 16, 0);
1929        validate_against_rust!(4, 16, 1);
1930        validate_against_rust!(4, 16, 2);
1931        validate_against_rust!(4, 16, 3);
1932        validate_against_rust!(4, 16, 4);
1933    }
1934}
1935
1936#[cfg(kani)]
1937mod proofs {
1938    use core::alloc::Layout;
1939
1940    use super::*;
1941
1942    impl kani::Arbitrary for DstLayout {
1943        fn any() -> Self {
1944            let align: NonZeroUsize = kani::any();
1945            let size_info: SizeInfo = kani::any();
1946
1947            kani::assume(align.is_power_of_two());
1948            kani::assume(align < DstLayout::THEORETICAL_MAX_ALIGN);
1949
1950            // For testing purposes, we most care about instantiations of
1951            // `DstLayout` that can correspond to actual Rust types. We use
1952            // `Layout` to verify that our `DstLayout` satisfies the validity
1953            // conditions of Rust layouts.
1954            kani::assume(
1955                match size_info {
1956                    SizeInfo::Sized { size } => Layout::from_size_align(size, align.get()),
1957                    SizeInfo::SliceDst(TrailingSliceLayout { offset, elem_size: _ }) => {
1958                        // `SliceDst` cannot encode an exact size, but we know
1959                        // it is at least `offset` bytes.
1960                        Layout::from_size_align(offset, align.get())
1961                    }
1962                }
1963                .is_ok(),
1964            );
1965
1966            Self { align: align, size_info: size_info, statically_shallow_unpadded: kani::any() }
1967        }
1968    }
1969
1970    impl kani::Arbitrary for SizeInfo {
1971        fn any() -> Self {
1972            let is_sized: bool = kani::any();
1973
1974            match is_sized {
1975                true => {
1976                    let size: usize = kani::any();
1977
1978                    kani::assume(size <= isize::MAX as _);
1979
1980                    SizeInfo::Sized { size }
1981                }
1982                false => SizeInfo::SliceDst(kani::any()),
1983            }
1984        }
1985    }
1986
1987    impl kani::Arbitrary for TrailingSliceLayout {
1988        fn any() -> Self {
1989            let elem_size: usize = kani::any();
1990            let offset: usize = kani::any();
1991
1992            kani::assume(elem_size < isize::MAX as _);
1993            kani::assume(offset < isize::MAX as _);
1994
1995            TrailingSliceLayout { elem_size, offset }
1996        }
1997    }
1998
1999    #[kani::proof]
2000    fn prove_requires_dynamic_padding() {
2001        let layout: DstLayout = kani::any();
2002
2003        let SizeInfo::SliceDst(size_info) = layout.size_info else {
2004            kani::assume(false);
2005            loop {}
2006        };
2007
2008        let meta: usize = kani::any();
2009
2010        let Some(trailing_slice_size) = size_info.elem_size.checked_mul(meta) else {
2011            // The `trailing_slice_size` exceeds `usize::MAX`; `meta` is invalid.
2012            kani::assume(false);
2013            loop {}
2014        };
2015
2016        let Some(unpadded_size) = size_info.offset.checked_add(trailing_slice_size) else {
2017            // The `unpadded_size` exceeds `usize::MAX`; `meta`` is invalid.
2018            kani::assume(false);
2019            loop {}
2020        };
2021
2022        if unpadded_size >= isize::MAX as usize {
2023            // The `unpadded_size` exceeds `isize::MAX`; `meta` is invalid.
2024            kani::assume(false);
2025            loop {}
2026        }
2027
2028        let trailing_padding = util::padding_needed_for(unpadded_size, layout.align);
2029
2030        if !layout.requires_dynamic_padding() {
2031            assert!(trailing_padding == 0);
2032        }
2033    }
2034
2035    #[kani::proof]
2036    fn prove_dst_layout_extend() {
2037        use crate::util::{max, min, padding_needed_for};
2038
2039        let base: DstLayout = kani::any();
2040        let field: DstLayout = kani::any();
2041        let packed: Option<NonZeroUsize> = kani::any();
2042
2043        if let Some(max_align) = packed {
2044            kani::assume(max_align.is_power_of_two());
2045            kani::assume(base.align <= max_align);
2046        }
2047
2048        // The base can only be extended if it's sized.
2049        kani::assume(matches!(base.size_info, SizeInfo::Sized { .. }));
2050        let base_size = if let SizeInfo::Sized { size } = base.size_info {
2051            size
2052        } else {
2053            unreachable!();
2054        };
2055
2056        // Under the above conditions, `DstLayout::extend` will not panic.
2057        let composite = base.extend(field, packed);
2058
2059        // The field's alignment is clamped by `max_align` (i.e., the
2060        // `packed` attribute, if any) [1].
2061        //
2062        // [1] Per https://doc.rust-lang.org/reference/type-layout.html#the-alignment-modifiers:
2063        //
2064        //   The alignments of each field, for the purpose of positioning
2065        //   fields, is the smaller of the specified alignment and the
2066        //   alignment of the field's type.
2067        let field_align = min(field.align, packed.unwrap_or(DstLayout::THEORETICAL_MAX_ALIGN));
2068
2069        // The struct's alignment is the maximum of its previous alignment and
2070        // `field_align`.
2071        assert_eq!(composite.align, max(base.align, field_align));
2072
2073        // Compute the minimum amount of inter-field padding needed to
2074        // satisfy the field's alignment, and offset of the trailing field.
2075        // [1]
2076        //
2077        // [1] Per https://doc.rust-lang.org/reference/type-layout.html#the-alignment-modifiers:
2078        //
2079        //   Inter-field padding is guaranteed to be the minimum required in
2080        //   order to satisfy each field's (possibly altered) alignment.
2081        let padding = padding_needed_for(base_size, field_align);
2082        let offset = base_size + padding;
2083
2084        // For testing purposes, we'll also construct `alloc::Layout`
2085        // stand-ins for `DstLayout`, and show that `extend` behaves
2086        // comparably on both types.
2087        let base_analog = Layout::from_size_align(base_size, base.align.get()).unwrap();
2088
2089        match field.size_info {
2090            SizeInfo::Sized { size: field_size } => {
2091                if let SizeInfo::Sized { size: composite_size } = composite.size_info {
2092                    // If the trailing field is sized, the resulting layout will
2093                    // be sized. Its size will be the sum of the preceding
2094                    // layout, the size of the new field, and the size of
2095                    // inter-field padding between the two.
2096                    assert_eq!(composite_size, offset + field_size);
2097
2098                    let field_analog =
2099                        Layout::from_size_align(field_size, field_align.get()).unwrap();
2100
2101                    if let Ok((actual_composite, actual_offset)) = base_analog.extend(field_analog)
2102                    {
2103                        assert_eq!(actual_offset, offset);
2104                        assert_eq!(actual_composite.size(), composite_size);
2105                        assert_eq!(actual_composite.align(), composite.align.get());
2106                    } else {
2107                        // An error here reflects that composite of `base`
2108                        // and `field` cannot correspond to a real Rust type
2109                        // fragment, because such a fragment would violate
2110                        // the basic invariants of a valid Rust layout. At
2111                        // the time of writing, `DstLayout` is a little more
2112                        // permissive than `Layout`, so we don't assert
2113                        // anything in this branch (e.g., unreachability).
2114                    }
2115                } else {
2116                    panic!("The composite of two sized layouts must be sized.")
2117                }
2118            }
2119            SizeInfo::SliceDst(TrailingSliceLayout {
2120                offset: field_offset,
2121                elem_size: field_elem_size,
2122            }) => {
2123                if let SizeInfo::SliceDst(TrailingSliceLayout {
2124                    offset: composite_offset,
2125                    elem_size: composite_elem_size,
2126                }) = composite.size_info
2127                {
2128                    // The offset of the trailing slice component is the sum
2129                    // of the offset of the trailing field and the trailing
2130                    // slice offset within that field.
2131                    assert_eq!(composite_offset, offset + field_offset);
2132                    // The elem size is unchanged.
2133                    assert_eq!(composite_elem_size, field_elem_size);
2134
2135                    let field_analog =
2136                        Layout::from_size_align(field_offset, field_align.get()).unwrap();
2137
2138                    if let Ok((actual_composite, actual_offset)) = base_analog.extend(field_analog)
2139                    {
2140                        assert_eq!(actual_offset, offset);
2141                        assert_eq!(actual_composite.size(), composite_offset);
2142                        assert_eq!(actual_composite.align(), composite.align.get());
2143                    } else {
2144                        // An error here reflects that composite of `base`
2145                        // and `field` cannot correspond to a real Rust type
2146                        // fragment, because such a fragment would violate
2147                        // the basic invariants of a valid Rust layout. At
2148                        // the time of writing, `DstLayout` is a little more
2149                        // permissive than `Layout`, so we don't assert
2150                        // anything in this branch (e.g., unreachability).
2151                    }
2152                } else {
2153                    panic!("The extension of a layout with a DST must result in a DST.")
2154                }
2155            }
2156        }
2157    }
2158
2159    #[kani::proof]
2160    #[kani::should_panic]
2161    fn prove_dst_layout_extend_dst_panics() {
2162        let base: DstLayout = kani::any();
2163        let field: DstLayout = kani::any();
2164        let packed: Option<NonZeroUsize> = kani::any();
2165
2166        if let Some(max_align) = packed {
2167            kani::assume(max_align.is_power_of_two());
2168            kani::assume(base.align <= max_align);
2169        }
2170
2171        kani::assume(matches!(base.size_info, SizeInfo::SliceDst(..)));
2172
2173        let _ = base.extend(field, packed);
2174    }
2175
2176    #[kani::proof]
2177    fn prove_dst_layout_pad_to_align() {
2178        use crate::util::padding_needed_for;
2179
2180        let layout: DstLayout = kani::any();
2181
2182        let padded = layout.pad_to_align();
2183
2184        // Calling `pad_to_align` does not alter the `DstLayout`'s alignment.
2185        assert_eq!(padded.align, layout.align);
2186
2187        if let SizeInfo::Sized { size: unpadded_size } = layout.size_info {
2188            if let SizeInfo::Sized { size: padded_size } = padded.size_info {
2189                // If the layout is sized, it will remain sized after padding is
2190                // added. Its sum will be its unpadded size and the size of the
2191                // trailing padding needed to satisfy its alignment
2192                // requirements.
2193                let padding = padding_needed_for(unpadded_size, layout.align);
2194                assert_eq!(padded_size, unpadded_size + padding);
2195
2196                // Prove that calling `DstLayout::pad_to_align` behaves
2197                // identically to `Layout::pad_to_align`.
2198                let layout_analog =
2199                    Layout::from_size_align(unpadded_size, layout.align.get()).unwrap();
2200                let padded_analog = layout_analog.pad_to_align();
2201                assert_eq!(padded_analog.align(), layout.align.get());
2202                assert_eq!(padded_analog.size(), padded_size);
2203            } else {
2204                panic!("The padding of a sized layout must result in a sized layout.")
2205            }
2206        } else {
2207            // If the layout is a DST, padding cannot be statically added.
2208            assert_eq!(padded.size_info, layout.size_info);
2209        }
2210    }
2211}