alloc/alloc.rs
1//! Memory allocation APIs
2
3#![stable(feature = "alloc_module", since = "1.28.0")]
4
5#[stable(feature = "alloc_module", since = "1.28.0")]
6#[doc(inline)]
7pub use core::alloc::*;
8use core::mem::Alignment;
9use core::ptr::{self, NonNull};
10use core::{cmp, hint};
11
12unsafe extern "Rust" {
13 // These are the magic symbols to call the global allocator. rustc generates
14 // them to call the global allocator if there is a `#[global_allocator]` attribute
15 // (the code expanding that attribute macro generates those functions), or to call
16 // the default implementations in std (`__rdl_alloc` etc. in `library/std/src/alloc.rs`)
17 // otherwise.
18 #[rustc_allocator]
19 #[rustc_nounwind]
20 #[rustc_std_internal_symbol]
21 #[rustc_allocator_zeroed_variant = "__rust_alloc_zeroed"]
22 fn __rust_alloc(size: usize, align: Alignment) -> *mut u8;
23 #[rustc_deallocator]
24 #[rustc_nounwind]
25 #[rustc_std_internal_symbol]
26 fn __rust_dealloc(ptr: NonNull<u8>, size: usize, align: Alignment);
27 #[rustc_reallocator]
28 #[rustc_nounwind]
29 #[rustc_std_internal_symbol]
30 fn __rust_realloc(
31 ptr: NonNull<u8>,
32 old_size: usize,
33 align: Alignment,
34 new_size: usize,
35 ) -> *mut u8;
36 #[rustc_allocator_zeroed]
37 #[rustc_nounwind]
38 #[rustc_std_internal_symbol]
39 fn __rust_alloc_zeroed(size: usize, align: Alignment) -> *mut u8;
40
41 #[rustc_nounwind]
42 #[rustc_std_internal_symbol]
43 fn __rust_no_alloc_shim_is_unstable_v2();
44}
45
46/// The global memory allocator.
47///
48/// This type implements the [`Allocator`] trait by forwarding calls
49/// to the allocator registered with the `#[global_allocator]` attribute
50/// if there is one, or the `std` crate’s default.
51///
52/// Note: while this type is unstable, the functionality it provides can be
53/// accessed through the [free functions in `alloc`](self#functions).
54#[unstable(feature = "allocator_api", issue = "32838")]
55#[derive(Copy, Debug)]
56#[derive_const(Clone, Default)]
57// the compiler needs to know when a Box uses the global allocator vs a custom one
58#[lang = "global_alloc_ty"]
59pub struct Global;
60
61#[unstable(feature = "allocator_api", issue = "32838")]
62unsafe impl core::alloc::AllocatorClone for Global {}
63
64#[unstable(feature = "allocator_api", issue = "32838")]
65unsafe impl core::alloc::StaticAllocator for Global {}
66
67/// Allocates memory with the global allocator.
68///
69/// This function forwards calls to the [`GlobalAlloc::alloc`] method
70/// of the allocator registered with the `#[global_allocator]` attribute
71/// if there is one, or the `std` crate’s default.
72///
73/// Note, however, that invoking this function is *not* equivalent to invoking the underlying
74/// [`GlobalAlloc::alloc`] method of the registered allocator directly. Users of this function
75/// cannot assume anything about what the allocator does, other than the documented requirements.
76/// This means:
77///
78/// - This function may non-deterministically entirely skip the underlying allocator, e.g. if the
79/// compiler can show that this allocation can be replaced by a stack variable. The compiler may
80/// also merge multiple allocation operations into one, as long as it can also adjust all
81/// corresponding deallocation operations accordingly.
82/// - An allocation created by invoking this function has exactly the size and minimum alignment
83/// defined by `layout`, even if the underlying allocator makes stronger promises.
84/// - The allocation can only be freed by invoking [`dealloc`] or [`realloc`]. In particular,
85/// passing a pointer to such an allocation directly to the underlying method on [`GlobalAlloc`] is
86/// not permitted. Until one of those functions is called, it is undefined behavior to access the
87/// memory that backs this allocation with any pointer not derived from the return value of this
88/// function (e.g., with internal pointers the allocator might keep around).
89/// - This function de-initializes the contents of the allocation before handing it to the user. So even
90/// if you control the underlying allocator and know that it explicitly initialized this memory,
91/// you cannot rely on it being initialized.
92///
93/// Users of this function have to consider that in the future, allocators may be allowed to unwind.
94///
95/// This function is expected to be deprecated in favor of the `allocate` method
96/// of the [`Global`] type when it and the [`Allocator`] trait become stable.
97///
98/// # Safety
99///
100/// See [`GlobalAlloc::alloc`].
101///
102/// # Examples
103///
104/// ```
105/// use std::alloc::{alloc, dealloc, handle_alloc_error, Layout};
106///
107/// unsafe {
108/// let layout = Layout::new::<u16>();
109/// let ptr = alloc(layout);
110/// if ptr.is_null() {
111/// handle_alloc_error(layout);
112/// }
113///
114/// *(ptr as *mut u16) = 42;
115/// assert_eq!(*(ptr as *mut u16), 42);
116///
117/// dealloc(ptr, layout);
118/// }
119/// ```
120#[stable(feature = "global_alloc", since = "1.28.0")]
121#[must_use = "losing the pointer will leak memory"]
122#[inline]
123#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
124pub unsafe fn alloc(layout: Layout) -> *mut u8 {
125 // SAFETY: Upheld by caller.
126 unsafe {
127 // Make sure we don't accidentally allow omitting the allocator shim in
128 // stable code until it is actually stabilized.
129 __rust_no_alloc_shim_is_unstable_v2();
130
131 __rust_alloc(layout.size(), layout.alignment())
132 }
133}
134
135/// Deallocates memory with the global allocator.
136///
137/// This function forwards calls to the [`GlobalAlloc::dealloc`] method
138/// of the allocator registered with the `#[global_allocator]` attribute
139/// if there is one, or the `std` crate’s default.
140///
141/// Note, however, that invoking this function is *not* equivalent to invoking the underlying
142/// [`GlobalAlloc::dealloc`] method of the registered allocator directly. Users of this function
143/// cannot assume anything about what the allocator does, other than the documented requirements.
144/// This means:
145///
146/// - This function may non-deterministically entirely skip the underlying allocator, e.g. if the
147/// compiler can show that this allocation can be replaced by a stack variable. The compiler may
148/// also merge multiple allocation operations into one, as long as it can also adjust all
149/// corresponding deallocation operations accordingly.
150/// - The pointer passed to this function must have been obtained by invoking [`alloc`],
151/// [`alloc_zeroed`], or [`realloc`]. In particular, passing a pointer returned by the underlying
152/// methods on [`GlobalAlloc`] is not permitted.
153/// - This function de-initializes the contents of the allocation before handing it to the allocator.
154/// So even if you know that the program previously initialized that memory, the allocator cannot
155/// rely on it being initialized.
156///
157/// Users of this function have to consider that in the future, allocators may be allowed to unwind.
158///
159/// This function is expected to be deprecated in favor of the `deallocate` method
160/// of the [`Global`] type when it and the [`Allocator`] trait become stable.
161///
162/// # Safety
163///
164/// See [`GlobalAlloc::dealloc`].
165#[stable(feature = "global_alloc", since = "1.28.0")]
166#[inline]
167#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
168pub unsafe fn dealloc(ptr: *mut u8, layout: Layout) {
169 // SAFETY: Upheld by caller.
170 unsafe { dealloc_nonnull(NonNull::new_unchecked(ptr), layout) }
171}
172
173/// Same as [`dealloc`] but when you already have a non-null pointer
174#[inline]
175#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
176unsafe fn dealloc_nonnull(ptr: NonNull<u8>, layout: Layout) {
177 // SAFETY: Upheld by caller.
178 unsafe { __rust_dealloc(ptr, layout.size(), layout.alignment()) }
179}
180
181/// Reallocates memory with the global allocator.
182///
183/// This function forwards calls to the [`GlobalAlloc::realloc`] method
184/// of the allocator registered with the `#[global_allocator]` attribute
185/// if there is one, or the `std` crate’s default.
186///
187/// Note, however, that invoking this function is *not* equivalent to invoking the underlying
188/// [`GlobalAlloc::realloc`] method of the registered allocator directly. Users of this function
189/// cannot assume anything about what the allocator does, other than the documented requirements.
190/// This means:
191///
192/// - This function may non-deterministically entirely skip the underlying allocator, e.g. if the
193/// compiler can show that this allocation can be replaced by a stack variable. The compiler may
194/// also merge multiple allocation operations into one, as long as it can also adjust all
195/// corresponding deallocation operations accordingly.
196/// - The pointer passed to this function must have been obtained by invoking [`alloc`],
197/// [`alloc_zeroed`], or [`realloc`]. In particular, passing a pointer returned by the underlying
198/// methods on [`GlobalAlloc`] is not permitted.
199/// - An allocation created by invoking this function has exactly the size and minimum alignment
200/// defined by `layout`, even if the underlying allocator makes stronger promises.
201/// - The allocation can only be freed by invoking [`dealloc`] or [`realloc`]. In particular,
202/// passing a pointer to such an allocation directly to the underlying method on [`GlobalAlloc`] is
203/// not permitted. Until one of those functions is called, it is undefined behavior to access the
204/// memory that backs this allocation with any pointer not derived from the return value of this
205/// function (e.g., with internal pointers the allocator might keep around).
206/// - If this grows the allocation, the contents of the grown part of the new allocation allocation
207/// are de-initialized by this function before returning.
208/// - If this shrinks the allocation, the contents of the removed part of the old allocation are
209/// de-initialized by this function before invoking the underlying allocator.
210///
211/// Users of this function have to consider that in the future, allocators may be allowed to unwind.
212///
213/// This function is expected to be deprecated in favor of the `grow` and `shrink` methods
214/// of the [`Global`] type when it and the [`Allocator`] trait become stable.
215///
216/// # Safety
217///
218/// See [`GlobalAlloc::realloc`].
219#[stable(feature = "global_alloc", since = "1.28.0")]
220#[must_use = "losing the pointer will leak memory"]
221#[inline]
222#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
223pub unsafe fn realloc(ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
224 // SAFETY: Upheld by caller.
225 unsafe { realloc_nonnull(NonNull::new_unchecked(ptr), layout, new_size) }
226}
227
228/// Same as [`realloc`] but when you already have a non-null pointer
229#[inline]
230#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
231unsafe fn realloc_nonnull(ptr: NonNull<u8>, layout: Layout, new_size: usize) -> *mut u8 {
232 // SAFETY: Upheld by caller.
233 unsafe { __rust_realloc(ptr, layout.size(), layout.alignment(), new_size) }
234}
235
236/// Allocates zero-initialized memory with the global allocator.
237///
238/// This function forwards calls to the [`GlobalAlloc::alloc_zeroed`] method
239/// of the allocator registered with the `#[global_allocator]` attribute
240/// if there is one, or the `std` crate’s default.
241///
242/// Note, however, that invoking this function is *not* equivalent to invoking the underlying
243/// [`GlobalAlloc::alloc_zeroed`] method of the registered allocator directly. Users of this
244/// function cannot assume anything about what the allocator does, other than the documented
245/// requirements. This means:
246///
247/// - This function may non-deterministically entirely skip the underlying allocator, e.g. if the
248/// compiler can show that this allocation can be replaced by a stack variable. The compiler may
249/// also merge multiple allocation operations into one, as long as it can also adjust all
250/// corresponding deallocation operations accordingly.
251/// - The allocation can only be freed by invoking [`dealloc`] or [`realloc`]. In particular,
252/// passing a pointer to such an allocation directly to the underlying method on [`GlobalAlloc`] is
253/// not permitted. Until one of those functions is called, it is undefined behavior to access the
254/// memory that backs this allocation with any pointer not derived from the return value of this
255/// function (e.g., with internal pointers the allocator might keep around).
256/// - An allocation created by invoking this function has exactly the size and minimum alignment
257/// defined by `layout`, even if the underlying allocator makes stronger promises.
258///
259/// Users of this function have to consider that in the future, allocators may be allowed to unwind.
260///
261/// This function is expected to be deprecated in favor of the `allocate_zeroed` method
262/// of the [`Global`] type when it and the [`Allocator`] trait become stable.
263///
264/// # Safety
265///
266/// See [`GlobalAlloc::alloc_zeroed`].
267///
268/// # Examples
269///
270/// ```
271/// use std::alloc::{alloc_zeroed, dealloc, handle_alloc_error, Layout};
272///
273/// unsafe {
274/// let layout = Layout::new::<u16>();
275/// let ptr = alloc_zeroed(layout);
276/// if ptr.is_null() {
277/// handle_alloc_error(layout);
278/// }
279///
280/// assert_eq!(*(ptr as *mut u16), 0);
281///
282/// dealloc(ptr, layout);
283/// }
284/// ```
285#[stable(feature = "global_alloc", since = "1.28.0")]
286#[must_use = "losing the pointer will leak memory"]
287#[inline]
288#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
289pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 {
290 // SAFETY: Upheld by caller.
291 unsafe {
292 // Make sure we don't accidentally allow omitting the allocator shim in
293 // stable code until it is actually stabilized.
294 __rust_no_alloc_shim_is_unstable_v2();
295
296 __rust_alloc_zeroed(layout.size(), layout.alignment())
297 }
298}
299
300impl Global {
301 #[inline]
302 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
303 fn alloc_impl_runtime(layout: Layout, zeroed: bool) -> Result<NonNull<[u8]>, AllocError> {
304 match layout.size() {
305 0 => Ok(layout.dangling_ptr().cast_slice(0)),
306 // SAFETY: `layout` is non-zero in size,
307 size => unsafe {
308 let raw_ptr = if zeroed { alloc_zeroed(layout) } else { alloc(layout) };
309 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
310 Ok(ptr.cast_slice(size))
311 },
312 }
313 }
314
315 #[inline]
316 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
317 fn deallocate_impl_runtime(ptr: NonNull<u8>, layout: Layout) {
318 if layout.size() != 0 {
319 // SAFETY:
320 // * We have checked that `layout` is non-zero in size.
321 // * The caller is obligated to provide a layout that "fits", and in this case,
322 // "fit" always means a layout that is equal to the original, because our
323 // `allocate()`, `grow()`, and `shrink()` implementations never returns a larger
324 // allocation than requested.
325 // * Other conditions must be upheld by the caller, as per `Allocator::deallocate()`'s
326 // safety documentation.
327 unsafe { dealloc_nonnull(ptr, layout) }
328 }
329 }
330
331 // SAFETY: Same as `Allocator::grow`
332 #[inline]
333 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
334 fn grow_impl_runtime(
335 &self,
336 ptr: NonNull<u8>,
337 old_layout: Layout,
338 new_layout: Layout,
339 zeroed: bool,
340 ) -> Result<NonNull<[u8]>, AllocError> {
341 debug_assert!(
342 new_layout.size() >= old_layout.size(),
343 "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
344 );
345
346 match old_layout.size() {
347 0 => self.alloc_impl(new_layout, zeroed),
348
349 // SAFETY: `new_size` is non-zero as `old_size` is greater than or equal to `new_size`
350 // as required by safety conditions. Other conditions must be upheld by the caller
351 old_size if old_layout.align() == new_layout.align() => unsafe {
352 let new_size = new_layout.size();
353
354 // `realloc` probably checks for `new_size >= old_layout.size()` or something similar.
355 hint::assert_unchecked(new_size >= old_layout.size());
356
357 let raw_ptr = realloc_nonnull(ptr, old_layout, new_size);
358 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
359 if zeroed {
360 raw_ptr.add(old_size).write_bytes(0, new_size - old_size);
361 }
362 Ok(ptr.cast_slice(new_size))
363 },
364
365 // SAFETY: because `new_layout.size()` must be greater than or equal to `old_size`,
366 // both the old and new memory allocation are valid for reads and writes for `old_size`
367 // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
368 // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
369 // for `dealloc` must be upheld by the caller.
370 old_size => unsafe {
371 let new_ptr = self.alloc_impl(new_layout, zeroed)?;
372 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_size);
373 self.deallocate(ptr, old_layout);
374 Ok(new_ptr)
375 },
376 }
377 }
378
379 // SAFETY: Same as `Allocator::grow`
380 #[inline]
381 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
382 fn shrink_impl_runtime(
383 &self,
384 ptr: NonNull<u8>,
385 old_layout: Layout,
386 new_layout: Layout,
387 _zeroed: bool,
388 ) -> Result<NonNull<[u8]>, AllocError> {
389 debug_assert!(
390 new_layout.size() <= old_layout.size(),
391 "`new_layout.size()` must be smaller than or equal to `old_layout.size()`"
392 );
393
394 match new_layout.size() {
395 // SAFETY: conditions must be upheld by the caller
396 0 => unsafe {
397 self.deallocate(ptr, old_layout);
398 Ok(new_layout.dangling_ptr().cast_slice(0))
399 },
400
401 // SAFETY: `new_size` is non-zero. Other conditions must be upheld by the caller
402 new_size if old_layout.align() == new_layout.align() => unsafe {
403 // `realloc` probably checks for `new_size <= old_layout.size()` or something similar.
404 hint::assert_unchecked(new_size <= old_layout.size());
405
406 let raw_ptr = realloc_nonnull(ptr, old_layout, new_size);
407 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
408 Ok(ptr.cast_slice(new_size))
409 },
410
411 // SAFETY: because `new_size` must be smaller than or equal to `old_layout.size()`,
412 // both the old and new memory allocation are valid for reads and writes for `new_size`
413 // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
414 // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
415 // for `dealloc` must be upheld by the caller.
416 new_size => unsafe {
417 let new_ptr = self.allocate(new_layout)?;
418 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), new_size);
419 self.deallocate(ptr, old_layout);
420 Ok(new_ptr)
421 },
422 }
423 }
424
425 // SAFETY: Same as `Allocator::allocate`
426 #[inline]
427 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
428 #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
429 const fn alloc_impl(&self, layout: Layout, zeroed: bool) -> Result<NonNull<[u8]>, AllocError> {
430 core::intrinsics::const_eval_select(
431 (layout, zeroed),
432 Global::alloc_impl_const,
433 Global::alloc_impl_runtime,
434 )
435 }
436
437 // SAFETY: Same as `Allocator::deallocate`
438 #[inline]
439 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
440 #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
441 const unsafe fn deallocate_impl(&self, ptr: NonNull<u8>, layout: Layout) {
442 core::intrinsics::const_eval_select(
443 (ptr, layout),
444 Global::deallocate_impl_const,
445 Global::deallocate_impl_runtime,
446 )
447 }
448
449 // SAFETY: Same as `Allocator::grow`
450 #[inline]
451 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
452 #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
453 const unsafe fn grow_impl(
454 &self,
455 ptr: NonNull<u8>,
456 old_layout: Layout,
457 new_layout: Layout,
458 zeroed: bool,
459 ) -> Result<NonNull<[u8]>, AllocError> {
460 core::intrinsics::const_eval_select(
461 (self, ptr, old_layout, new_layout, zeroed),
462 Global::grow_shrink_impl_const,
463 Global::grow_impl_runtime,
464 )
465 }
466
467 // SAFETY: Same as `Allocator::shrink`
468 #[inline]
469 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
470 #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
471 const unsafe fn shrink_impl(
472 &self,
473 ptr: NonNull<u8>,
474 old_layout: Layout,
475 new_layout: Layout,
476 ) -> Result<NonNull<[u8]>, AllocError> {
477 core::intrinsics::const_eval_select(
478 (self, ptr, old_layout, new_layout, false),
479 Global::grow_shrink_impl_const,
480 Global::shrink_impl_runtime,
481 )
482 }
483
484 #[inline]
485 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
486 #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
487 const fn alloc_impl_const(layout: Layout, zeroed: bool) -> Result<NonNull<[u8]>, AllocError> {
488 match layout.size() {
489 0 => Ok(layout.dangling_ptr().cast_slice(0)),
490 // SAFETY: `layout` is non-zero in size,
491 size => unsafe {
492 let raw_ptr = core::intrinsics::const_allocate(layout.size(), layout.align());
493 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
494 if zeroed {
495 // SAFETY: the pointer returned by `const_allocate` is valid to write to.
496 ptr.write_bytes(0, size);
497 }
498 Ok(ptr.cast_slice(size))
499 },
500 }
501 }
502
503 #[inline]
504 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
505 #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
506 const fn deallocate_impl_const(ptr: NonNull<u8>, layout: Layout) {
507 if layout.size() != 0 {
508 // SAFETY: We checked for nonzero size; other preconditions must be upheld by caller.
509 unsafe {
510 core::intrinsics::const_deallocate(ptr.as_ptr(), layout.size(), layout.align());
511 }
512 }
513 }
514
515 #[inline]
516 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
517 #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
518 const fn grow_shrink_impl_const(
519 &self,
520 ptr: NonNull<u8>,
521 old_layout: Layout,
522 new_layout: Layout,
523 zeroed: bool,
524 ) -> Result<NonNull<[u8]>, AllocError> {
525 let new_ptr = self.alloc_impl(new_layout, zeroed)?;
526 // SAFETY: both pointers are valid and this operations is in bounds.
527 unsafe {
528 ptr::copy_nonoverlapping(
529 ptr.as_ptr(),
530 new_ptr.as_mut_ptr(),
531 cmp::min(old_layout.size(), new_layout.size()),
532 );
533 }
534 // SAFETY: Caller ensures the ptr & layout are correct.
535 unsafe {
536 self.deallocate_impl(ptr, old_layout);
537 }
538 Ok(new_ptr)
539 }
540}
541
542#[unstable(feature = "allocator_api", issue = "32838")]
543#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
544const unsafe impl Allocator for Global {
545 #[inline]
546 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
547 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
548 self.alloc_impl(layout, false)
549 }
550
551 #[inline]
552 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
553 fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
554 self.alloc_impl(layout, true)
555 }
556
557 #[inline]
558 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
559 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
560 // SAFETY: all conditions must be upheld by the caller
561 unsafe { self.deallocate_impl(ptr, layout) }
562 }
563
564 #[inline]
565 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
566 unsafe fn grow(
567 &self,
568 ptr: NonNull<u8>,
569 old_layout: Layout,
570 new_layout: Layout,
571 ) -> Result<NonNull<[u8]>, AllocError> {
572 // SAFETY: all conditions must be upheld by the caller
573 unsafe { self.grow_impl(ptr, old_layout, new_layout, false) }
574 }
575
576 #[inline]
577 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
578 unsafe fn grow_zeroed(
579 &self,
580 ptr: NonNull<u8>,
581 old_layout: Layout,
582 new_layout: Layout,
583 ) -> Result<NonNull<[u8]>, AllocError> {
584 // SAFETY: all conditions must be upheld by the caller
585 unsafe { self.grow_impl(ptr, old_layout, new_layout, true) }
586 }
587
588 #[inline]
589 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
590 unsafe fn shrink(
591 &self,
592 ptr: NonNull<u8>,
593 old_layout: Layout,
594 new_layout: Layout,
595 ) -> Result<NonNull<[u8]>, AllocError> {
596 // SAFETY: all conditions must be upheld by the caller
597 unsafe { self.shrink_impl(ptr, old_layout, new_layout) }
598 }
599}
600
601// # Allocation error handler
602
603#[cfg(not(no_global_oom_handling))]
604unsafe extern "Rust" {
605 // This is the magic symbol to call the global alloc error handler. rustc generates
606 // it to call `__rg_oom` if there is a `#[alloc_error_handler]`, or to call the
607 // default implementations below (`__rdl_alloc_error_handler`) otherwise.
608 #[rustc_std_internal_symbol]
609 fn __rust_alloc_error_handler(size: usize, align: usize) -> !;
610}
611
612/// Signals a memory allocation error.
613///
614/// Callers of memory allocation APIs wishing to cease execution
615/// in response to an allocation error are encouraged to call this function,
616/// rather than directly invoking [`panic!`] or similar.
617///
618/// This function is guaranteed to diverge (not return normally with a value), but depending on
619/// global configuration, it may either panic (resulting in unwinding or aborting as per
620/// configuration for all panics), or abort the process (with no unwinding).
621///
622/// The default behavior is:
623///
624/// * If the binary links against `std` (typically the case), then
625/// print a message to standard error and abort the process.
626/// This behavior can be replaced with [`set_alloc_error_hook`] and [`take_alloc_error_hook`].
627/// Future versions of Rust may panic by default instead.
628///
629/// * If the binary does not link against `std` (all of its crates are marked
630/// [`#![no_std]`][no_std]), then call [`panic!`] with a message.
631/// [The panic handler] applies as to any panic.
632///
633/// [`set_alloc_error_hook`]: ../../std/alloc/fn.set_alloc_error_hook.html
634/// [`take_alloc_error_hook`]: ../../std/alloc/fn.take_alloc_error_hook.html
635/// [The panic handler]: https://doc.rust-lang.org/reference/runtime.html#the-panic_handler-attribute
636/// [no_std]: https://doc.rust-lang.org/reference/names/preludes.html#the-no_std-attribute
637#[stable(feature = "global_alloc", since = "1.28.0")]
638#[rustc_const_unstable(feature = "const_alloc_error", issue = "92523")]
639#[cfg(not(no_global_oom_handling))]
640#[cold]
641#[optimize(size)]
642pub const fn handle_alloc_error(layout: Layout) -> ! {
643 const fn ct_error(_: Layout) -> ! {
644 panic!("allocation failed");
645 }
646
647 #[inline]
648 fn rt_error(layout: Layout) -> ! {
649 // SAFETY: Safe to call; we control this function.
650 unsafe {
651 __rust_alloc_error_handler(layout.size(), layout.align());
652 }
653 }
654
655 #[cfg(not(panic = "immediate-abort"))]
656 {
657 core::intrinsics::const_eval_select((layout,), ct_error, rt_error)
658 }
659
660 #[cfg(panic = "immediate-abort")]
661 ct_error(layout)
662}
663
664#[cfg(not(no_global_oom_handling))]
665#[doc(hidden)]
666#[allow(unused_attributes)]
667#[unstable(feature = "alloc_internals", issue = "none")]
668pub mod __alloc_error_handler {
669 // called via generated `__rust_alloc_error_handler` if there is no
670 // `#[alloc_error_handler]`.
671 #[rustc_std_internal_symbol]
672 pub unsafe fn __rdl_alloc_error_handler(size: usize, _align: usize) -> ! {
673 core::panicking::panic_nounwind_fmt(
674 format_args!("memory allocation of {size} bytes failed"),
675 /* force_no_backtrace */ false,
676 )
677 }
678}