]> git.lizzy.rs Git - rust.git/blob - library/core/src/alloc/layout.rs
Rollup merge of #73945 - est31:unused_externs, r=Mark-Simulacrum
[rust.git] / library / core / src / alloc / layout.rs
1 use crate::cmp;
2 use crate::fmt;
3 use crate::mem;
4 use crate::num::NonZeroUsize;
5 use crate::ptr::NonNull;
6
7 // While this function is used in one place and its implementation
8 // could be inlined, the previous attempts to do so made rustc
9 // slower:
10 //
11 // * https://github.com/rust-lang/rust/pull/72189
12 // * https://github.com/rust-lang/rust/pull/79827
13 const fn size_align<T>() -> (usize, usize) {
14     (mem::size_of::<T>(), mem::align_of::<T>())
15 }
16
17 /// Layout of a block of memory.
18 ///
19 /// An instance of `Layout` describes a particular layout of memory.
20 /// You build a `Layout` up as an input to give to an allocator.
21 ///
22 /// All layouts have an associated size and a power-of-two alignment.
23 ///
24 /// (Note that layouts are *not* required to have non-zero size,
25 /// even though `GlobalAlloc` requires that all memory requests
26 /// be non-zero in size. A caller must either ensure that conditions
27 /// like this are met, use specific allocators with looser
28 /// requirements, or use the more lenient `Allocator` interface.)
29 #[stable(feature = "alloc_layout", since = "1.28.0")]
30 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
31 #[lang = "alloc_layout"]
32 pub struct Layout {
33     // size of the requested block of memory, measured in bytes.
34     size_: usize,
35
36     // alignment of the requested block of memory, measured in bytes.
37     // we ensure that this is always a power-of-two, because API's
38     // like `posix_memalign` require it and it is a reasonable
39     // constraint to impose on Layout constructors.
40     //
41     // (However, we do not analogously require `align >= sizeof(void*)`,
42     //  even though that is *also* a requirement of `posix_memalign`.)
43     align_: NonZeroUsize,
44 }
45
46 impl Layout {
47     /// Constructs a `Layout` from a given `size` and `align`,
48     /// or returns `LayoutError` if any of the following conditions
49     /// are not met:
50     ///
51     /// * `align` must not be zero,
52     ///
53     /// * `align` must be a power of two,
54     ///
55     /// * `size`, when rounded up to the nearest multiple of `align`,
56     ///    must not overflow (i.e., the rounded value must be less than
57     ///    or equal to `usize::MAX`).
58     #[stable(feature = "alloc_layout", since = "1.28.0")]
59     #[rustc_const_stable(feature = "const_alloc_layout", since = "1.50.0")]
60     #[inline]
61     pub const fn from_size_align(size: usize, align: usize) -> Result<Self, LayoutError> {
62         if !align.is_power_of_two() {
63             return Err(LayoutError { private: () });
64         }
65
66         // (power-of-two implies align != 0.)
67
68         // Rounded up size is:
69         //   size_rounded_up = (size + align - 1) & !(align - 1);
70         //
71         // We know from above that align != 0. If adding (align - 1)
72         // does not overflow, then rounding up will be fine.
73         //
74         // Conversely, &-masking with !(align - 1) will subtract off
75         // only low-order-bits. Thus if overflow occurs with the sum,
76         // the &-mask cannot subtract enough to undo that overflow.
77         //
78         // Above implies that checking for summation overflow is both
79         // necessary and sufficient.
80         if size > usize::MAX - (align - 1) {
81             return Err(LayoutError { private: () });
82         }
83
84         // SAFETY: the conditions for `from_size_align_unchecked` have been
85         // checked above.
86         unsafe { Ok(Layout::from_size_align_unchecked(size, align)) }
87     }
88
89     /// Creates a layout, bypassing all checks.
90     ///
91     /// # Safety
92     ///
93     /// This function is unsafe as it does not verify the preconditions from
94     /// [`Layout::from_size_align`].
95     #[stable(feature = "alloc_layout", since = "1.28.0")]
96     #[rustc_const_stable(feature = "alloc_layout", since = "1.36.0")]
97     #[inline]
98     pub const unsafe fn from_size_align_unchecked(size: usize, align: usize) -> Self {
99         // SAFETY: the caller must ensure that `align` is greater than zero.
100         Layout { size_: size, align_: unsafe { NonZeroUsize::new_unchecked(align) } }
101     }
102
103     /// The minimum size in bytes for a memory block of this layout.
104     #[stable(feature = "alloc_layout", since = "1.28.0")]
105     #[rustc_const_stable(feature = "const_alloc_layout", since = "1.50.0")]
106     #[inline]
107     pub const fn size(&self) -> usize {
108         self.size_
109     }
110
111     /// The minimum byte alignment for a memory block of this layout.
112     #[stable(feature = "alloc_layout", since = "1.28.0")]
113     #[rustc_const_stable(feature = "const_alloc_layout", since = "1.50.0")]
114     #[inline]
115     pub const fn align(&self) -> usize {
116         self.align_.get()
117     }
118
119     /// Constructs a `Layout` suitable for holding a value of type `T`.
120     #[stable(feature = "alloc_layout", since = "1.28.0")]
121     #[rustc_const_stable(feature = "alloc_layout_const_new", since = "1.42.0")]
122     #[inline]
123     pub const fn new<T>() -> Self {
124         let (size, align) = size_align::<T>();
125         // SAFETY: the align is guaranteed by Rust to be a power of two and
126         // the size+align combo is guaranteed to fit in our address space. As a
127         // result use the unchecked constructor here to avoid inserting code
128         // that panics if it isn't optimized well enough.
129         unsafe { Layout::from_size_align_unchecked(size, align) }
130     }
131
132     /// Produces layout describing a record that could be used to
133     /// allocate backing structure for `T` (which could be a trait
134     /// or other unsized type like a slice).
135     #[stable(feature = "alloc_layout", since = "1.28.0")]
136     #[inline]
137     pub fn for_value<T: ?Sized>(t: &T) -> Self {
138         let (size, align) = (mem::size_of_val(t), mem::align_of_val(t));
139         debug_assert!(Layout::from_size_align(size, align).is_ok());
140         // SAFETY: see rationale in `new` for why this is using the unsafe variant
141         unsafe { Layout::from_size_align_unchecked(size, align) }
142     }
143
144     /// Produces layout describing a record that could be used to
145     /// allocate backing structure for `T` (which could be a trait
146     /// or other unsized type like a slice).
147     ///
148     /// # Safety
149     ///
150     /// This function is only safe to call if the following conditions hold:
151     ///
152     /// - If `T` is `Sized`, this function is always safe to call.
153     /// - If the unsized tail of `T` is:
154     ///     - a [slice], then the length of the slice tail must be an intialized
155     ///       integer, and the size of the *entire value*
156     ///       (dynamic tail length + statically sized prefix) must fit in `isize`.
157     ///     - a [trait object], then the vtable part of the pointer must point
158     ///       to a valid vtable for the type `T` acquired by an unsizing coersion,
159     ///       and the size of the *entire value*
160     ///       (dynamic tail length + statically sized prefix) must fit in `isize`.
161     ///     - an (unstable) [extern type], then this function is always safe to
162     ///       call, but may panic or otherwise return the wrong value, as the
163     ///       extern type's layout is not known. This is the same behavior as
164     ///       [`Layout::for_value`] on a reference to an extern type tail.
165     ///     - otherwise, it is conservatively not allowed to call this function.
166     ///
167     /// [trait object]: ../../book/ch17-02-trait-objects.html
168     /// [extern type]: ../../unstable-book/language-features/extern-types.html
169     #[unstable(feature = "layout_for_ptr", issue = "69835")]
170     pub unsafe fn for_value_raw<T: ?Sized>(t: *const T) -> Self {
171         // SAFETY: we pass along the prerequisites of these functions to the caller
172         let (size, align) = unsafe { (mem::size_of_val_raw(t), mem::align_of_val_raw(t)) };
173         debug_assert!(Layout::from_size_align(size, align).is_ok());
174         // SAFETY: see rationale in `new` for why this is using the unsafe variant
175         unsafe { Layout::from_size_align_unchecked(size, align) }
176     }
177
178     /// Creates a `NonNull` that is dangling, but well-aligned for this Layout.
179     ///
180     /// Note that the pointer value may potentially represent a valid pointer,
181     /// which means this must not be used as a "not yet initialized"
182     /// sentinel value. Types that lazily allocate must track initialization by
183     /// some other means.
184     #[unstable(feature = "alloc_layout_extra", issue = "55724")]
185     #[rustc_const_unstable(feature = "alloc_layout_extra", issue = "55724")]
186     #[inline]
187     pub const fn dangling(&self) -> NonNull<u8> {
188         // SAFETY: align is guaranteed to be non-zero
189         unsafe { NonNull::new_unchecked(self.align() as *mut u8) }
190     }
191
192     /// Creates a layout describing the record that can hold a value
193     /// of the same layout as `self`, but that also is aligned to
194     /// alignment `align` (measured in bytes).
195     ///
196     /// If `self` already meets the prescribed alignment, then returns
197     /// `self`.
198     ///
199     /// Note that this method does not add any padding to the overall
200     /// size, regardless of whether the returned layout has a different
201     /// alignment. In other words, if `K` has size 16, `K.align_to(32)`
202     /// will *still* have size 16.
203     ///
204     /// Returns an error if the combination of `self.size()` and the given
205     /// `align` violates the conditions listed in [`Layout::from_size_align`].
206     #[stable(feature = "alloc_layout_manipulation", since = "1.44.0")]
207     #[inline]
208     pub fn align_to(&self, align: usize) -> Result<Self, LayoutError> {
209         Layout::from_size_align(self.size(), cmp::max(self.align(), align))
210     }
211
212     /// Returns the amount of padding we must insert after `self`
213     /// to ensure that the following address will satisfy `align`
214     /// (measured in bytes).
215     ///
216     /// e.g., if `self.size()` is 9, then `self.padding_needed_for(4)`
217     /// returns 3, because that is the minimum number of bytes of
218     /// padding required to get a 4-aligned address (assuming that the
219     /// corresponding memory block starts at a 4-aligned address).
220     ///
221     /// The return value of this function has no meaning if `align` is
222     /// not a power-of-two.
223     ///
224     /// Note that the utility of the returned value requires `align`
225     /// to be less than or equal to the alignment of the starting
226     /// address for the whole allocated block of memory. One way to
227     /// satisfy this constraint is to ensure `align <= self.align()`.
228     #[unstable(feature = "alloc_layout_extra", issue = "55724")]
229     #[rustc_const_unstable(feature = "const_alloc_layout", issue = "67521")]
230     #[inline]
231     pub const fn padding_needed_for(&self, align: usize) -> usize {
232         let len = self.size();
233
234         // Rounded up value is:
235         //   len_rounded_up = (len + align - 1) & !(align - 1);
236         // and then we return the padding difference: `len_rounded_up - len`.
237         //
238         // We use modular arithmetic throughout:
239         //
240         // 1. align is guaranteed to be > 0, so align - 1 is always
241         //    valid.
242         //
243         // 2. `len + align - 1` can overflow by at most `align - 1`,
244         //    so the &-mask with `!(align - 1)` will ensure that in the
245         //    case of overflow, `len_rounded_up` will itself be 0.
246         //    Thus the returned padding, when added to `len`, yields 0,
247         //    which trivially satisfies the alignment `align`.
248         //
249         // (Of course, attempts to allocate blocks of memory whose
250         // size and padding overflow in the above manner should cause
251         // the allocator to yield an error anyway.)
252
253         let len_rounded_up = len.wrapping_add(align).wrapping_sub(1) & !align.wrapping_sub(1);
254         len_rounded_up.wrapping_sub(len)
255     }
256
257     /// Creates a layout by rounding the size of this layout up to a multiple
258     /// of the layout's alignment.
259     ///
260     /// This is equivalent to adding the result of `padding_needed_for`
261     /// to the layout's current size.
262     #[stable(feature = "alloc_layout_manipulation", since = "1.44.0")]
263     #[inline]
264     pub fn pad_to_align(&self) -> Layout {
265         let pad = self.padding_needed_for(self.align());
266         // This cannot overflow. Quoting from the invariant of Layout:
267         // > `size`, when rounded up to the nearest multiple of `align`,
268         // > must not overflow (i.e., the rounded value must be less than
269         // > `usize::MAX`)
270         let new_size = self.size() + pad;
271
272         Layout::from_size_align(new_size, self.align()).unwrap()
273     }
274
275     /// Creates a layout describing the record for `n` instances of
276     /// `self`, with a suitable amount of padding between each to
277     /// ensure that each instance is given its requested size and
278     /// alignment. On success, returns `(k, offs)` where `k` is the
279     /// layout of the array and `offs` is the distance between the start
280     /// of each element in the array.
281     ///
282     /// On arithmetic overflow, returns `LayoutError`.
283     #[unstable(feature = "alloc_layout_extra", issue = "55724")]
284     #[inline]
285     pub fn repeat(&self, n: usize) -> Result<(Self, usize), LayoutError> {
286         // This cannot overflow. Quoting from the invariant of Layout:
287         // > `size`, when rounded up to the nearest multiple of `align`,
288         // > must not overflow (i.e., the rounded value must be less than
289         // > `usize::MAX`)
290         let padded_size = self.size() + self.padding_needed_for(self.align());
291         let alloc_size = padded_size.checked_mul(n).ok_or(LayoutError { private: () })?;
292
293         // SAFETY: self.align is already known to be valid and alloc_size has been
294         // padded already.
295         unsafe { Ok((Layout::from_size_align_unchecked(alloc_size, self.align()), padded_size)) }
296     }
297
298     /// Creates a layout describing the record for `self` followed by
299     /// `next`, including any necessary padding to ensure that `next`
300     /// will be properly aligned, but *no trailing padding*.
301     ///
302     /// In order to match C representation layout `repr(C)`, you should
303     /// call `pad_to_align` after extending the layout with all fields.
304     /// (There is no way to match the default Rust representation
305     /// layout `repr(Rust)`, as it is unspecified.)
306     ///
307     /// Note that the alignment of the resulting layout will be the maximum of
308     /// those of `self` and `next`, in order to ensure alignment of both parts.
309     ///
310     /// Returns `Ok((k, offset))`, where `k` is layout of the concatenated
311     /// record and `offset` is the relative location, in bytes, of the
312     /// start of the `next` embedded within the concatenated record
313     /// (assuming that the record itself starts at offset 0).
314     ///
315     /// On arithmetic overflow, returns `LayoutError`.
316     ///
317     /// # Examples
318     ///
319     /// To calculate the layout of a `#[repr(C)]` structure and the offsets of
320     /// the fields from its fields' layouts:
321     ///
322     /// ```rust
323     /// # use std::alloc::{Layout, LayoutError};
324     /// pub fn repr_c(fields: &[Layout]) -> Result<(Layout, Vec<usize>), LayoutError> {
325     ///     let mut offsets = Vec::new();
326     ///     let mut layout = Layout::from_size_align(0, 1)?;
327     ///     for &field in fields {
328     ///         let (new_layout, offset) = layout.extend(field)?;
329     ///         layout = new_layout;
330     ///         offsets.push(offset);
331     ///     }
332     ///     // Remember to finalize with `pad_to_align`!
333     ///     Ok((layout.pad_to_align(), offsets))
334     /// }
335     /// # // test that it works
336     /// # #[repr(C)] struct S { a: u64, b: u32, c: u16, d: u32 }
337     /// # let s = Layout::new::<S>();
338     /// # let u16 = Layout::new::<u16>();
339     /// # let u32 = Layout::new::<u32>();
340     /// # let u64 = Layout::new::<u64>();
341     /// # assert_eq!(repr_c(&[u64, u32, u16, u32]), Ok((s, vec![0, 8, 12, 16])));
342     /// ```
343     #[stable(feature = "alloc_layout_manipulation", since = "1.44.0")]
344     #[inline]
345     pub fn extend(&self, next: Self) -> Result<(Self, usize), LayoutError> {
346         let new_align = cmp::max(self.align(), next.align());
347         let pad = self.padding_needed_for(next.align());
348
349         let offset = self.size().checked_add(pad).ok_or(LayoutError { private: () })?;
350         let new_size = offset.checked_add(next.size()).ok_or(LayoutError { private: () })?;
351
352         let layout = Layout::from_size_align(new_size, new_align)?;
353         Ok((layout, offset))
354     }
355
356     /// Creates a layout describing the record for `n` instances of
357     /// `self`, with no padding between each instance.
358     ///
359     /// Note that, unlike `repeat`, `repeat_packed` does not guarantee
360     /// that the repeated instances of `self` will be properly
361     /// aligned, even if a given instance of `self` is properly
362     /// aligned. In other words, if the layout returned by
363     /// `repeat_packed` is used to allocate an array, it is not
364     /// guaranteed that all elements in the array will be properly
365     /// aligned.
366     ///
367     /// On arithmetic overflow, returns `LayoutError`.
368     #[unstable(feature = "alloc_layout_extra", issue = "55724")]
369     #[inline]
370     pub fn repeat_packed(&self, n: usize) -> Result<Self, LayoutError> {
371         let size = self.size().checked_mul(n).ok_or(LayoutError { private: () })?;
372         Layout::from_size_align(size, self.align())
373     }
374
375     /// Creates a layout describing the record for `self` followed by
376     /// `next` with no additional padding between the two. Since no
377     /// padding is inserted, the alignment of `next` is irrelevant,
378     /// and is not incorporated *at all* into the resulting layout.
379     ///
380     /// On arithmetic overflow, returns `LayoutError`.
381     #[unstable(feature = "alloc_layout_extra", issue = "55724")]
382     #[inline]
383     pub fn extend_packed(&self, next: Self) -> Result<Self, LayoutError> {
384         let new_size = self.size().checked_add(next.size()).ok_or(LayoutError { private: () })?;
385         Layout::from_size_align(new_size, self.align())
386     }
387
388     /// Creates a layout describing the record for a `[T; n]`.
389     ///
390     /// On arithmetic overflow, returns `LayoutError`.
391     #[stable(feature = "alloc_layout_manipulation", since = "1.44.0")]
392     #[inline]
393     pub fn array<T>(n: usize) -> Result<Self, LayoutError> {
394         let (layout, offset) = Layout::new::<T>().repeat(n)?;
395         debug_assert_eq!(offset, mem::size_of::<T>());
396         Ok(layout.pad_to_align())
397     }
398 }
399
400 #[stable(feature = "alloc_layout", since = "1.28.0")]
401 #[rustc_deprecated(
402     since = "1.52.0",
403     reason = "Name does not follow std convention, use LayoutError",
404     suggestion = "LayoutError"
405 )]
406 pub type LayoutErr = LayoutError;
407
408 /// The parameters given to `Layout::from_size_align`
409 /// or some other `Layout` constructor
410 /// do not satisfy its documented constraints.
411 #[stable(feature = "alloc_layout_error", since = "1.50.0")]
412 #[derive(Clone, PartialEq, Eq, Debug)]
413 pub struct LayoutError {
414     private: (),
415 }
416
417 // (we need this for downstream impl of trait Error)
418 #[stable(feature = "alloc_layout", since = "1.28.0")]
419 impl fmt::Display for LayoutError {
420     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
421         f.write_str("invalid parameters to Layout::from_size_align")
422     }
423 }