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