1//! Memory allocation APIs
2
3#![stable(feature = "alloc_module", since = "1.28.0")]
4
5#[cfg(not(test))]
6use core::hint;
7
8#[cfg(not(test))]
9use core::ptr::{self, NonNull};
10
11#[stable(feature = "alloc_module", since = "1.28.0")]
12#[doc(inline)]
13pub use core::alloc::*;
14
15#[cfg(test)]
16mod tests;
17
18extern "Rust" {
19 // These are the magic symbols to call the global allocator. rustc generates
20 // them to call `__rg_alloc` etc. if there is a `#[global_allocator]` attribute
21 // (the code expanding that attribute macro generates those functions), or to call
22 // the default implementations in std (`__rdl_alloc` etc. in `library/std/src/alloc.rs`)
23 // otherwise.
24 // The rustc fork of LLVM 14 and earlier also special-cases these function names to be able to optimize them
25 // like `malloc`, `realloc`, and `free`, respectively.
26 #[rustc_allocator]
27 #[rustc_nounwind]
28 fn __rust_alloc(size: usize, align: usize) -> *mut u8;
29 #[rustc_deallocator]
30 #[rustc_nounwind]
31 fn __rust_dealloc(ptr: *mut u8, size: usize, align: usize);
32 #[rustc_reallocator]
33 #[rustc_nounwind]
34 fn __rust_realloc(ptr: *mut u8, old_size: usize, align: usize, new_size: usize) -> *mut u8;
35 #[rustc_allocator_zeroed]
36 #[rustc_nounwind]
37 fn __rust_alloc_zeroed(size: usize, align: usize) -> *mut u8;
38
39 static __rust_no_alloc_shim_is_unstable: u8;
40}
41
42/// The global memory allocator.
43///
44/// This type implements the [`Allocator`] trait by forwarding calls
45/// to the allocator registered with the `#[global_allocator]` attribute
46/// if there is one, or the `std` crate’s default.
47///
48/// Note: while this type is unstable, the functionality it provides can be
49/// accessed through the [free functions in `alloc`](self#functions).
50#[unstable(feature = "allocator_api", issue = "32838")]
51#[derive(Copy, Clone, Default, Debug)]
52#[cfg(not(test))]
53pub struct Global;
54
55#[cfg(test)]
56pub use std::alloc::Global;
57
58/// Allocate memory with the global allocator.
59///
60/// This function forwards calls to the [`GlobalAlloc::alloc`] method
61/// of the allocator registered with the `#[global_allocator]` attribute
62/// if there is one, or the `std` crate’s default.
63///
64/// This function is expected to be deprecated in favor of the `alloc` method
65/// of the [`Global`] type when it and the [`Allocator`] trait become stable.
66///
67/// # Safety
68///
69/// See [`GlobalAlloc::alloc`].
70///
71/// # Examples
72///
73/// ```
74/// use std::alloc::{alloc, dealloc, handle_alloc_error, Layout};
75///
76/// unsafe {
77/// let layout = Layout::new::<u16>();
78/// let ptr = alloc(layout);
79/// if ptr.is_null() {
80/// handle_alloc_error(layout);
81/// }
82///
83/// *(ptr as *mut u16) = 42;
84/// assert_eq!(*(ptr as *mut u16), 42);
85///
86/// dealloc(ptr, layout);
87/// }
88/// ```
89#[stable(feature = "global_alloc", since = "1.28.0")]
90#[must_use = "losing the pointer will leak memory"]
91#[inline]
92pub unsafe fn alloc(layout: Layout) -> *mut u8 {
93 unsafe {
94 // Make sure we don't accidentally allow omitting the allocator shim in
95 // stable code until it is actually stabilized.
96 core::ptr::read_volatile(&__rust_no_alloc_shim_is_unstable);
97
98 __rust_alloc(layout.size(), layout.align())
99 }
100}
101
102/// Deallocate memory with the global allocator.
103///
104/// This function forwards calls to the [`GlobalAlloc::dealloc`] method
105/// of the allocator registered with the `#[global_allocator]` attribute
106/// if there is one, or the `std` crate’s default.
107///
108/// This function is expected to be deprecated in favor of the `dealloc` method
109/// of the [`Global`] type when it and the [`Allocator`] trait become stable.
110///
111/// # Safety
112///
113/// See [`GlobalAlloc::dealloc`].
114#[stable(feature = "global_alloc", since = "1.28.0")]
115#[inline]
116pub unsafe fn dealloc(ptr: *mut u8, layout: Layout) {
117 unsafe { __rust_dealloc(ptr, layout.size(), layout.align()) }
118}
119
120/// Reallocate memory with the global allocator.
121///
122/// This function forwards calls to the [`GlobalAlloc::realloc`] method
123/// of the allocator registered with the `#[global_allocator]` attribute
124/// if there is one, or the `std` crate’s default.
125///
126/// This function is expected to be deprecated in favor of the `realloc` method
127/// of the [`Global`] type when it and the [`Allocator`] trait become stable.
128///
129/// # Safety
130///
131/// See [`GlobalAlloc::realloc`].
132#[stable(feature = "global_alloc", since = "1.28.0")]
133#[must_use = "losing the pointer will leak memory"]
134#[inline]
135pub unsafe fn realloc(ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
136 unsafe { __rust_realloc(ptr, old_size:layout.size(), layout.align(), new_size) }
137}
138
139/// Allocate zero-initialized memory with the global allocator.
140///
141/// This function forwards calls to the [`GlobalAlloc::alloc_zeroed`] method
142/// of the allocator registered with the `#[global_allocator]` attribute
143/// if there is one, or the `std` crate’s default.
144///
145/// This function is expected to be deprecated in favor of the `alloc_zeroed` method
146/// of the [`Global`] type when it and the [`Allocator`] trait become stable.
147///
148/// # Safety
149///
150/// See [`GlobalAlloc::alloc_zeroed`].
151///
152/// # Examples
153///
154/// ```
155/// use std::alloc::{alloc_zeroed, dealloc, Layout};
156///
157/// unsafe {
158/// let layout = Layout::new::<u16>();
159/// let ptr = alloc_zeroed(layout);
160///
161/// assert_eq!(*(ptr as *mut u16), 0);
162///
163/// dealloc(ptr, layout);
164/// }
165/// ```
166#[stable(feature = "global_alloc", since = "1.28.0")]
167#[must_use = "losing the pointer will leak memory"]
168#[inline]
169pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 {
170 unsafe { __rust_alloc_zeroed(layout.size(), layout.align()) }
171}
172
173#[cfg(not(test))]
174impl Global {
175 #[inline]
176 fn alloc_impl(&self, layout: Layout, zeroed: bool) -> Result<NonNull<[u8]>, AllocError> {
177 match layout.size() {
178 0 => Ok(NonNull::slice_from_raw_parts(layout.dangling(), 0)),
179 // SAFETY: `layout` is non-zero in size,
180 size => unsafe {
181 let raw_ptr = if zeroed { alloc_zeroed(layout) } else { alloc(layout) };
182 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
183 Ok(NonNull::slice_from_raw_parts(ptr, size))
184 },
185 }
186 }
187
188 // SAFETY: Same as `Allocator::grow`
189 #[inline]
190 unsafe fn grow_impl(
191 &self,
192 ptr: NonNull<u8>,
193 old_layout: Layout,
194 new_layout: Layout,
195 zeroed: bool,
196 ) -> Result<NonNull<[u8]>, AllocError> {
197 debug_assert!(
198 new_layout.size() >= old_layout.size(),
199 "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
200 );
201
202 match old_layout.size() {
203 0 => self.alloc_impl(new_layout, zeroed),
204
205 // SAFETY: `new_size` is non-zero as `old_size` is greater than or equal to `new_size`
206 // as required by safety conditions. Other conditions must be upheld by the caller
207 old_size if old_layout.align() == new_layout.align() => unsafe {
208 let new_size = new_layout.size();
209
210 // `realloc` probably checks for `new_size >= old_layout.size()` or something similar.
211 hint::assert_unchecked(new_size >= old_layout.size());
212
213 let raw_ptr = realloc(ptr.as_ptr(), old_layout, new_size);
214 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
215 if zeroed {
216 raw_ptr.add(old_size).write_bytes(0, new_size - old_size);
217 }
218 Ok(NonNull::slice_from_raw_parts(ptr, new_size))
219 },
220
221 // SAFETY: because `new_layout.size()` must be greater than or equal to `old_size`,
222 // both the old and new memory allocation are valid for reads and writes for `old_size`
223 // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
224 // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
225 // for `dealloc` must be upheld by the caller.
226 old_size => unsafe {
227 let new_ptr = self.alloc_impl(new_layout, zeroed)?;
228 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_size);
229 self.deallocate(ptr, old_layout);
230 Ok(new_ptr)
231 },
232 }
233 }
234}
235
236#[unstable(feature = "allocator_api", issue = "32838")]
237#[cfg(not(test))]
238unsafe impl Allocator for Global {
239 #[inline]
240 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
241 self.alloc_impl(layout, false)
242 }
243
244 #[inline]
245 fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
246 self.alloc_impl(layout, true)
247 }
248
249 #[inline]
250 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
251 if layout.size() != 0 {
252 // SAFETY: `layout` is non-zero in size,
253 // other conditions must be upheld by the caller
254 unsafe { dealloc(ptr.as_ptr(), layout) }
255 }
256 }
257
258 #[inline]
259 unsafe fn grow(
260 &self,
261 ptr: NonNull<u8>,
262 old_layout: Layout,
263 new_layout: Layout,
264 ) -> Result<NonNull<[u8]>, AllocError> {
265 // SAFETY: all conditions must be upheld by the caller
266 unsafe { self.grow_impl(ptr, old_layout, new_layout, false) }
267 }
268
269 #[inline]
270 unsafe fn grow_zeroed(
271 &self,
272 ptr: NonNull<u8>,
273 old_layout: Layout,
274 new_layout: Layout,
275 ) -> Result<NonNull<[u8]>, AllocError> {
276 // SAFETY: all conditions must be upheld by the caller
277 unsafe { self.grow_impl(ptr, old_layout, new_layout, true) }
278 }
279
280 #[inline]
281 unsafe fn shrink(
282 &self,
283 ptr: NonNull<u8>,
284 old_layout: Layout,
285 new_layout: Layout,
286 ) -> Result<NonNull<[u8]>, AllocError> {
287 debug_assert!(
288 new_layout.size() <= old_layout.size(),
289 "`new_layout.size()` must be smaller than or equal to `old_layout.size()`"
290 );
291
292 match new_layout.size() {
293 // SAFETY: conditions must be upheld by the caller
294 0 => unsafe {
295 self.deallocate(ptr, old_layout);
296 Ok(NonNull::slice_from_raw_parts(new_layout.dangling(), 0))
297 },
298
299 // SAFETY: `new_size` is non-zero. Other conditions must be upheld by the caller
300 new_size if old_layout.align() == new_layout.align() => unsafe {
301 // `realloc` probably checks for `new_size <= old_layout.size()` or something similar.
302 hint::assert_unchecked(new_size <= old_layout.size());
303
304 let raw_ptr = realloc(ptr.as_ptr(), old_layout, new_size);
305 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
306 Ok(NonNull::slice_from_raw_parts(ptr, new_size))
307 },
308
309 // SAFETY: because `new_size` must be smaller than or equal to `old_layout.size()`,
310 // both the old and new memory allocation are valid for reads and writes for `new_size`
311 // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
312 // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
313 // for `dealloc` must be upheld by the caller.
314 new_size => unsafe {
315 let new_ptr = self.allocate(new_layout)?;
316 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), new_size);
317 self.deallocate(ptr, old_layout);
318 Ok(new_ptr)
319 },
320 }
321 }
322}
323
324/// The allocator for unique pointers.
325#[cfg(all(not(no_global_oom_handling), not(test)))]
326#[lang = "exchange_malloc"]
327#[inline]
328unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 {
329 let layout: Layout = unsafe { Layout::from_size_align_unchecked(size, align) };
330 match Global.allocate(layout) {
331 Ok(ptr: NonNull<[u8]>) => ptr.as_mut_ptr(),
332 Err(_) => handle_alloc_error(layout),
333 }
334}
335
336// # Allocation error handler
337
338#[cfg(not(no_global_oom_handling))]
339extern "Rust" {
340 // This is the magic symbol to call the global alloc error handler. rustc generates
341 // it to call `__rg_oom` if there is a `#[alloc_error_handler]`, or to call the
342 // default implementations below (`__rdl_oom`) otherwise.
343 fn __rust_alloc_error_handler(size: usize, align: usize) -> !;
344}
345
346/// Signal a memory allocation error.
347///
348/// Callers of memory allocation APIs wishing to cease execution
349/// in response to an allocation error are encouraged to call this function,
350/// rather than directly invoking [`panic!`] or similar.
351///
352/// This function is guaranteed to diverge (not return normally with a value), but depending on
353/// global configuration, it may either panic (resulting in unwinding or aborting as per
354/// configuration for all panics), or abort the process (with no unwinding).
355///
356/// The default behavior is:
357///
358/// * If the binary links against `std` (typically the case), then
359/// print a message to standard error and abort the process.
360/// This behavior can be replaced with [`set_alloc_error_hook`] and [`take_alloc_error_hook`].
361/// Future versions of Rust may panic by default instead.
362///
363/// * If the binary does not link against `std` (all of its crates are marked
364/// [`#![no_std]`][no_std]), then call [`panic!`] with a message.
365/// [The panic handler] applies as to any panic.
366///
367/// [`set_alloc_error_hook`]: ../../std/alloc/fn.set_alloc_error_hook.html
368/// [`take_alloc_error_hook`]: ../../std/alloc/fn.take_alloc_error_hook.html
369/// [The panic handler]: https://doc.rust-lang.org/reference/runtime.html#the-panic_handler-attribute
370/// [no_std]: https://doc.rust-lang.org/reference/names/preludes.html#the-no_std-attribute
371#[stable(feature = "global_alloc", since = "1.28.0")]
372#[rustc_const_unstable(feature = "const_alloc_error", issue = "92523")]
373#[cfg(all(not(no_global_oom_handling), not(test)))]
374#[cold]
375pub const fn handle_alloc_error(layout: Layout) -> ! {
376 const fn ct_error(_: Layout) -> ! {
377 panic!("allocation failed");
378 }
379
380 #[inline]
381 fn rt_error(layout: Layout) -> ! {
382 unsafe {
383 __rust_alloc_error_handler(layout.size(), layout.align());
384 }
385 }
386
387 #[cfg(not(feature = "panic_immediate_abort"))]
388 unsafe {
389 core::intrinsics::const_eval_select((layout,), called_in_const:ct_error, called_at_rt:rt_error)
390 }
391
392 #[cfg(feature = "panic_immediate_abort")]
393 ct_error(layout)
394}
395
396// For alloc test `std::alloc::handle_alloc_error` can be used directly.
397#[cfg(all(not(no_global_oom_handling), test))]
398pub use std::alloc::handle_alloc_error;
399
400#[cfg(all(not(no_global_oom_handling), not(test)))]
401#[doc(hidden)]
402#[allow(unused_attributes)]
403#[unstable(feature = "alloc_internals", issue = "none")]
404pub mod __alloc_error_handler {
405 // called via generated `__rust_alloc_error_handler` if there is no
406 // `#[alloc_error_handler]`.
407 #[rustc_std_internal_symbol]
408 pub unsafe fn __rdl_oom(size: usize, _align: usize) -> ! {
409 extern "Rust" {
410 // This symbol is emitted by rustc next to __rust_alloc_error_handler.
411 // Its value depends on the -Zoom={panic,abort} compiler option.
412 static __rust_alloc_error_handler_should_panic: u8;
413 }
414
415 if unsafe { __rust_alloc_error_handler_should_panic != 0 } {
416 panic!("memory allocation of {size} bytes failed")
417 } else {
418 core::panicking::panic_nounwind_fmt(
419 fmt:format_args!("memory allocation of {size} bytes failed"),
420 /* force_no_backtrace */ force_no_backtrace:false,
421 )
422 }
423 }
424}
425
426#[cfg(not(no_global_oom_handling))]
427/// Specialize clones into pre-allocated, uninitialized memory.
428/// Used by `Box::clone` and `Rc`/`Arc::make_mut`.
429pub(crate) trait WriteCloneIntoRaw: Sized {
430 unsafe fn write_clone_into_raw(&self, target: *mut Self);
431}
432
433#[cfg(not(no_global_oom_handling))]
434impl<T: Clone> WriteCloneIntoRaw for T {
435 #[inline]
436 default unsafe fn write_clone_into_raw(&self, target: *mut Self) {
437 // Having allocated *first* may allow the optimizer to create
438 // the cloned value in-place, skipping the local and move.
439 unsafe { target.write(self.clone()) };
440 }
441}
442
443#[cfg(not(no_global_oom_handling))]
444impl<T: Copy> WriteCloneIntoRaw for T {
445 #[inline]
446 unsafe fn write_clone_into_raw(&self, target: *mut Self) {
447 // We can always copy in-place, without ever involving a local value.
448 unsafe { target.copy_from_nonoverlapping(self, count:1) };
449 }
450}
451