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