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