]> git.lizzy.rs Git - rust.git/blob - library/core/src/alloc/mod.rs
Auto merge of #102755 - pcc:data-local-tmp, r=Mark-Simulacrum
[rust.git] / library / core / src / alloc / mod.rs
1 //! Memory allocation APIs
2
3 #![stable(feature = "alloc_module", since = "1.28.0")]
4
5 mod global;
6 mod layout;
7
8 #[stable(feature = "global_alloc", since = "1.28.0")]
9 pub use self::global::GlobalAlloc;
10 #[stable(feature = "alloc_layout", since = "1.28.0")]
11 pub use self::layout::Layout;
12 #[stable(feature = "alloc_layout", since = "1.28.0")]
13 #[deprecated(
14     since = "1.52.0",
15     note = "Name does not follow std convention, use LayoutError",
16     suggestion = "LayoutError"
17 )]
18 #[allow(deprecated, deprecated_in_future)]
19 pub use self::layout::LayoutErr;
20
21 #[stable(feature = "alloc_layout_error", since = "1.50.0")]
22 pub use self::layout::LayoutError;
23
24 use crate::error::Error;
25 use crate::fmt;
26 use crate::ptr::{self, NonNull};
27
28 /// The `AllocError` error indicates an allocation failure
29 /// that may be due to resource exhaustion or to
30 /// something wrong when combining the given input arguments with this
31 /// allocator.
32 #[unstable(feature = "allocator_api", issue = "32838")]
33 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
34 pub struct AllocError;
35
36 #[unstable(
37     feature = "allocator_api",
38     reason = "the precise API and guarantees it provides may be tweaked.",
39     issue = "32838"
40 )]
41 impl Error for AllocError {}
42
43 // (we need this for downstream impl of trait Error)
44 #[unstable(feature = "allocator_api", issue = "32838")]
45 impl fmt::Display for AllocError {
46     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47         f.write_str("memory allocation failed")
48     }
49 }
50
51 /// An implementation of `Allocator` can allocate, grow, shrink, and deallocate arbitrary blocks of
52 /// data described via [`Layout`][].
53 ///
54 /// `Allocator` is designed to be implemented on ZSTs, references, or smart pointers because having
55 /// an allocator like `MyAlloc([u8; N])` cannot be moved, without updating the pointers to the
56 /// allocated memory.
57 ///
58 /// Unlike [`GlobalAlloc`][], zero-sized allocations are allowed in `Allocator`. If an underlying
59 /// allocator does not support this (like jemalloc) or return a null pointer (such as
60 /// `libc::malloc`), this must be caught by the implementation.
61 ///
62 /// ### Currently allocated memory
63 ///
64 /// Some of the methods require that a memory block be *currently allocated* via an allocator. This
65 /// means that:
66 ///
67 /// * the starting address for that memory block was previously returned by [`allocate`], [`grow`], or
68 ///   [`shrink`], and
69 ///
70 /// * the memory block has not been subsequently deallocated, where blocks are either deallocated
71 ///   directly by being passed to [`deallocate`] or were changed by being passed to [`grow`] or
72 ///   [`shrink`] that returns `Ok`. If `grow` or `shrink` have returned `Err`, the passed pointer
73 ///   remains valid.
74 ///
75 /// [`allocate`]: Allocator::allocate
76 /// [`grow`]: Allocator::grow
77 /// [`shrink`]: Allocator::shrink
78 /// [`deallocate`]: Allocator::deallocate
79 ///
80 /// ### Memory fitting
81 ///
82 /// Some of the methods require that a layout *fit* a memory block. What it means for a layout to
83 /// "fit" a memory block means (or equivalently, for a memory block to "fit" a layout) is that the
84 /// following conditions must hold:
85 ///
86 /// * The block must be allocated with the same alignment as [`layout.align()`], and
87 ///
88 /// * The provided [`layout.size()`] must fall in the range `min ..= max`, where:
89 ///   - `min` is the size of the layout most recently used to allocate the block, and
90 ///   - `max` is the latest actual size returned from [`allocate`], [`grow`], or [`shrink`].
91 ///
92 /// [`layout.align()`]: Layout::align
93 /// [`layout.size()`]: Layout::size
94 ///
95 /// # Safety
96 ///
97 /// * Memory blocks returned from an allocator must point to valid memory and retain their validity
98 ///   until the instance and all of its clones are dropped,
99 ///
100 /// * cloning or moving the allocator must not invalidate memory blocks returned from this
101 ///   allocator. A cloned allocator must behave like the same allocator, and
102 ///
103 /// * any pointer to a memory block which is [*currently allocated*] may be passed to any other
104 ///   method of the allocator.
105 ///
106 /// [*currently allocated*]: #currently-allocated-memory
107 #[unstable(feature = "allocator_api", issue = "32838")]
108 #[const_trait]
109 pub unsafe trait Allocator {
110     /// Attempts to allocate a block of memory.
111     ///
112     /// On success, returns a [`NonNull<[u8]>`][NonNull] meeting the size and alignment guarantees of `layout`.
113     ///
114     /// The returned block may have a larger size than specified by `layout.size()`, and may or may
115     /// not have its contents initialized.
116     ///
117     /// # Errors
118     ///
119     /// Returning `Err` indicates that either memory is exhausted or `layout` does not meet
120     /// allocator's size or alignment constraints.
121     ///
122     /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
123     /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
124     /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
125     ///
126     /// Clients wishing to abort computation in response to an allocation error are encouraged to
127     /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
128     ///
129     /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
130     fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>;
131
132     /// Behaves like `allocate`, but also ensures that the returned memory is zero-initialized.
133     ///
134     /// # Errors
135     ///
136     /// Returning `Err` indicates that either memory is exhausted or `layout` does not meet
137     /// allocator's size or alignment constraints.
138     ///
139     /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
140     /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
141     /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
142     ///
143     /// Clients wishing to abort computation in response to an allocation error are encouraged to
144     /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
145     ///
146     /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
147     fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
148         let ptr = self.allocate(layout)?;
149         // SAFETY: `alloc` returns a valid memory block
150         unsafe { ptr.as_non_null_ptr().as_ptr().write_bytes(0, ptr.len()) }
151         Ok(ptr)
152     }
153
154     /// Deallocates the memory referenced by `ptr`.
155     ///
156     /// # Safety
157     ///
158     /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator, and
159     /// * `layout` must [*fit*] that block of memory.
160     ///
161     /// [*currently allocated*]: #currently-allocated-memory
162     /// [*fit*]: #memory-fitting
163     unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout);
164
165     /// Attempts to extend the memory block.
166     ///
167     /// Returns a new [`NonNull<[u8]>`][NonNull] containing a pointer and the actual size of the allocated
168     /// memory. The pointer is suitable for holding data described by `new_layout`. To accomplish
169     /// this, the allocator may extend the allocation referenced by `ptr` to fit the new layout.
170     ///
171     /// If this returns `Ok`, then ownership of the memory block referenced by `ptr` has been
172     /// transferred to this allocator. The memory may or may not have been freed, and should be
173     /// considered unusable.
174     ///
175     /// If this method returns `Err`, then ownership of the memory block has not been transferred to
176     /// this allocator, and the contents of the memory block are unaltered.
177     ///
178     /// # Safety
179     ///
180     /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator.
181     /// * `old_layout` must [*fit*] that block of memory (The `new_layout` argument need not fit it.).
182     /// * `new_layout.size()` must be greater than or equal to `old_layout.size()`.
183     ///
184     /// Note that `new_layout.align()` need not be the same as `old_layout.align()`.
185     ///
186     /// [*currently allocated*]: #currently-allocated-memory
187     /// [*fit*]: #memory-fitting
188     ///
189     /// # Errors
190     ///
191     /// Returns `Err` if the new layout does not meet the allocator's size and alignment
192     /// constraints of the allocator, or if growing otherwise fails.
193     ///
194     /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
195     /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
196     /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
197     ///
198     /// Clients wishing to abort computation in response to an allocation error are encouraged to
199     /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
200     ///
201     /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
202     unsafe fn grow(
203         &self,
204         ptr: NonNull<u8>,
205         old_layout: Layout,
206         new_layout: Layout,
207     ) -> Result<NonNull<[u8]>, AllocError> {
208         debug_assert!(
209             new_layout.size() >= old_layout.size(),
210             "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
211         );
212
213         let new_ptr = self.allocate(new_layout)?;
214
215         // SAFETY: because `new_layout.size()` must be greater than or equal to
216         // `old_layout.size()`, both the old and new memory allocation are valid for reads and
217         // writes for `old_layout.size()` bytes. Also, because the old allocation wasn't yet
218         // deallocated, it cannot overlap `new_ptr`. Thus, the call to `copy_nonoverlapping` is
219         // safe. The safety contract for `dealloc` must be upheld by the caller.
220         unsafe {
221             ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_layout.size());
222             self.deallocate(ptr, old_layout);
223         }
224
225         Ok(new_ptr)
226     }
227
228     /// Behaves like `grow`, but also ensures that the new contents are set to zero before being
229     /// returned.
230     ///
231     /// The memory block will contain the following contents after a successful call to
232     /// `grow_zeroed`:
233     ///   * Bytes `0..old_layout.size()` are preserved from the original allocation.
234     ///   * Bytes `old_layout.size()..old_size` will either be preserved or zeroed, depending on
235     ///     the allocator implementation. `old_size` refers to the size of the memory block prior
236     ///     to the `grow_zeroed` call, which may be larger than the size that was originally
237     ///     requested when it was allocated.
238     ///   * Bytes `old_size..new_size` are zeroed. `new_size` refers to the size of the memory
239     ///     block returned by the `grow_zeroed` call.
240     ///
241     /// # Safety
242     ///
243     /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator.
244     /// * `old_layout` must [*fit*] that block of memory (The `new_layout` argument need not fit it.).
245     /// * `new_layout.size()` must be greater than or equal to `old_layout.size()`.
246     ///
247     /// Note that `new_layout.align()` need not be the same as `old_layout.align()`.
248     ///
249     /// [*currently allocated*]: #currently-allocated-memory
250     /// [*fit*]: #memory-fitting
251     ///
252     /// # Errors
253     ///
254     /// Returns `Err` if the new layout does not meet the allocator's size and alignment
255     /// constraints of the allocator, or if growing otherwise fails.
256     ///
257     /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
258     /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
259     /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
260     ///
261     /// Clients wishing to abort computation in response to an allocation error are encouraged to
262     /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
263     ///
264     /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
265     unsafe fn grow_zeroed(
266         &self,
267         ptr: NonNull<u8>,
268         old_layout: Layout,
269         new_layout: Layout,
270     ) -> Result<NonNull<[u8]>, AllocError> {
271         debug_assert!(
272             new_layout.size() >= old_layout.size(),
273             "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
274         );
275
276         let new_ptr = self.allocate_zeroed(new_layout)?;
277
278         // SAFETY: because `new_layout.size()` must be greater than or equal to
279         // `old_layout.size()`, both the old and new memory allocation are valid for reads and
280         // writes for `old_layout.size()` bytes. Also, because the old allocation wasn't yet
281         // deallocated, it cannot overlap `new_ptr`. Thus, the call to `copy_nonoverlapping` is
282         // safe. The safety contract for `dealloc` must be upheld by the caller.
283         unsafe {
284             ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_layout.size());
285             self.deallocate(ptr, old_layout);
286         }
287
288         Ok(new_ptr)
289     }
290
291     /// Attempts to shrink the memory block.
292     ///
293     /// Returns a new [`NonNull<[u8]>`][NonNull] containing a pointer and the actual size of the allocated
294     /// memory. The pointer is suitable for holding data described by `new_layout`. To accomplish
295     /// this, the allocator may shrink the allocation referenced by `ptr` to fit the new layout.
296     ///
297     /// If this returns `Ok`, then ownership of the memory block referenced by `ptr` has been
298     /// transferred to this allocator. The memory may or may not have been freed, and should be
299     /// considered unusable.
300     ///
301     /// If this method returns `Err`, then ownership of the memory block has not been transferred to
302     /// this allocator, and the contents of the memory block are unaltered.
303     ///
304     /// # Safety
305     ///
306     /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator.
307     /// * `old_layout` must [*fit*] that block of memory (The `new_layout` argument need not fit it.).
308     /// * `new_layout.size()` must be smaller than or equal to `old_layout.size()`.
309     ///
310     /// Note that `new_layout.align()` need not be the same as `old_layout.align()`.
311     ///
312     /// [*currently allocated*]: #currently-allocated-memory
313     /// [*fit*]: #memory-fitting
314     ///
315     /// # Errors
316     ///
317     /// Returns `Err` if the new layout does not meet the allocator's size and alignment
318     /// constraints of the allocator, or if shrinking otherwise fails.
319     ///
320     /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
321     /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
322     /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
323     ///
324     /// Clients wishing to abort computation in response to an allocation error are encouraged to
325     /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
326     ///
327     /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
328     unsafe fn shrink(
329         &self,
330         ptr: NonNull<u8>,
331         old_layout: Layout,
332         new_layout: Layout,
333     ) -> Result<NonNull<[u8]>, AllocError> {
334         debug_assert!(
335             new_layout.size() <= old_layout.size(),
336             "`new_layout.size()` must be smaller than or equal to `old_layout.size()`"
337         );
338
339         let new_ptr = self.allocate(new_layout)?;
340
341         // SAFETY: because `new_layout.size()` must be lower than or equal to
342         // `old_layout.size()`, both the old and new memory allocation are valid for reads and
343         // writes for `new_layout.size()` bytes. Also, because the old allocation wasn't yet
344         // deallocated, it cannot overlap `new_ptr`. Thus, the call to `copy_nonoverlapping` is
345         // safe. The safety contract for `dealloc` must be upheld by the caller.
346         unsafe {
347             ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), new_layout.size());
348             self.deallocate(ptr, old_layout);
349         }
350
351         Ok(new_ptr)
352     }
353
354     /// Creates a "by reference" adapter for this instance of `Allocator`.
355     ///
356     /// The returned adapter also implements `Allocator` and will simply borrow this.
357     #[inline(always)]
358     fn by_ref(&self) -> &Self
359     where
360         Self: Sized,
361     {
362         self
363     }
364 }
365
366 #[unstable(feature = "allocator_api", issue = "32838")]
367 unsafe impl<A> Allocator for &A
368 where
369     A: Allocator + ?Sized,
370 {
371     #[inline]
372     fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
373         (**self).allocate(layout)
374     }
375
376     #[inline]
377     fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
378         (**self).allocate_zeroed(layout)
379     }
380
381     #[inline]
382     unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
383         // SAFETY: the safety contract must be upheld by the caller
384         unsafe { (**self).deallocate(ptr, layout) }
385     }
386
387     #[inline]
388     unsafe fn grow(
389         &self,
390         ptr: NonNull<u8>,
391         old_layout: Layout,
392         new_layout: Layout,
393     ) -> Result<NonNull<[u8]>, AllocError> {
394         // SAFETY: the safety contract must be upheld by the caller
395         unsafe { (**self).grow(ptr, old_layout, new_layout) }
396     }
397
398     #[inline]
399     unsafe fn grow_zeroed(
400         &self,
401         ptr: NonNull<u8>,
402         old_layout: Layout,
403         new_layout: Layout,
404     ) -> Result<NonNull<[u8]>, AllocError> {
405         // SAFETY: the safety contract must be upheld by the caller
406         unsafe { (**self).grow_zeroed(ptr, old_layout, new_layout) }
407     }
408
409     #[inline]
410     unsafe fn shrink(
411         &self,
412         ptr: NonNull<u8>,
413         old_layout: Layout,
414         new_layout: Layout,
415     ) -> Result<NonNull<[u8]>, AllocError> {
416         // SAFETY: the safety contract must be upheld by the caller
417         unsafe { (**self).shrink(ptr, old_layout, new_layout) }
418     }
419 }