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