]> git.lizzy.rs Git - rust.git/blob - library/std/src/alloc.rs
Auto merge of #94517 - aDotInTheVoid:inline_wrapping_next_power_two, r=yaahc
[rust.git] / library / std / src / alloc.rs
1 //! Memory allocation APIs.
2 //!
3 //! In a given program, the standard library has one “global” memory allocator
4 //! that is used for example by `Box<T>` and `Vec<T>`.
5 //!
6 //! Currently the default global allocator is unspecified. Libraries, however,
7 //! like `cdylib`s and `staticlib`s are guaranteed to use the [`System`] by
8 //! default.
9 //!
10 //! # The `#[global_allocator]` attribute
11 //!
12 //! This attribute allows configuring the choice of global allocator.
13 //! You can use this to implement a completely custom global allocator
14 //! to route all default allocation requests to a custom object.
15 //!
16 //! ```rust
17 //! use std::alloc::{GlobalAlloc, System, Layout};
18 //!
19 //! struct MyAllocator;
20 //!
21 //! unsafe impl GlobalAlloc for MyAllocator {
22 //!     unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
23 //!         System.alloc(layout)
24 //!     }
25 //!
26 //!     unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
27 //!         System.dealloc(ptr, layout)
28 //!     }
29 //! }
30 //!
31 //! #[global_allocator]
32 //! static GLOBAL: MyAllocator = MyAllocator;
33 //!
34 //! fn main() {
35 //!     // This `Vec` will allocate memory through `GLOBAL` above
36 //!     let mut v = Vec::new();
37 //!     v.push(1);
38 //! }
39 //! ```
40 //!
41 //! The attribute is used on a `static` item whose type implements the
42 //! [`GlobalAlloc`] trait. This type can be provided by an external library:
43 //!
44 //! ```rust,ignore (demonstrates crates.io usage)
45 //! extern crate jemallocator;
46 //!
47 //! use jemallocator::Jemalloc;
48 //!
49 //! #[global_allocator]
50 //! static GLOBAL: Jemalloc = Jemalloc;
51 //!
52 //! fn main() {}
53 //! ```
54 //!
55 //! The `#[global_allocator]` can only be used once in a crate
56 //! or its recursive dependencies.
57
58 #![deny(unsafe_op_in_unsafe_fn)]
59 #![stable(feature = "alloc_module", since = "1.28.0")]
60
61 use core::intrinsics;
62 use core::ptr::NonNull;
63 use core::sync::atomic::{AtomicPtr, Ordering};
64 use core::{mem, ptr};
65
66 #[stable(feature = "alloc_module", since = "1.28.0")]
67 #[doc(inline)]
68 pub use alloc_crate::alloc::*;
69
70 /// The default memory allocator provided by the operating system.
71 ///
72 /// This is based on `malloc` on Unix platforms and `HeapAlloc` on Windows,
73 /// plus related functions.
74 ///
75 /// This type implements the `GlobalAlloc` trait and Rust programs by default
76 /// work as if they had this definition:
77 ///
78 /// ```rust
79 /// use std::alloc::System;
80 ///
81 /// #[global_allocator]
82 /// static A: System = System;
83 ///
84 /// fn main() {
85 ///     let a = Box::new(4); // Allocates from the system allocator.
86 ///     println!("{a}");
87 /// }
88 /// ```
89 ///
90 /// You can also define your own wrapper around `System` if you'd like, such as
91 /// keeping track of the number of all bytes allocated:
92 ///
93 /// ```rust
94 /// use std::alloc::{System, GlobalAlloc, Layout};
95 /// use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
96 ///
97 /// struct Counter;
98 ///
99 /// static ALLOCATED: AtomicUsize = AtomicUsize::new(0);
100 ///
101 /// unsafe impl GlobalAlloc for Counter {
102 ///     unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
103 ///         let ret = System.alloc(layout);
104 ///         if !ret.is_null() {
105 ///             ALLOCATED.fetch_add(layout.size(), SeqCst);
106 ///         }
107 ///         return ret
108 ///     }
109 ///
110 ///     unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
111 ///         System.dealloc(ptr, layout);
112 ///         ALLOCATED.fetch_sub(layout.size(), SeqCst);
113 ///     }
114 /// }
115 ///
116 /// #[global_allocator]
117 /// static A: Counter = Counter;
118 ///
119 /// fn main() {
120 ///     println!("allocated bytes before main: {}", ALLOCATED.load(SeqCst));
121 /// }
122 /// ```
123 ///
124 /// It can also be used directly to allocate memory independently of whatever
125 /// global allocator has been selected for a Rust program. For example if a Rust
126 /// program opts in to using jemalloc as the global allocator, `System` will
127 /// still allocate memory using `malloc` and `HeapAlloc`.
128 #[stable(feature = "alloc_system_type", since = "1.28.0")]
129 #[derive(Debug, Default, Copy, Clone)]
130 pub struct System;
131
132 impl System {
133     #[inline]
134     fn alloc_impl(&self, layout: Layout, zeroed: bool) -> Result<NonNull<[u8]>, AllocError> {
135         match layout.size() {
136             0 => Ok(NonNull::slice_from_raw_parts(layout.dangling(), 0)),
137             // SAFETY: `layout` is non-zero in size,
138             size => unsafe {
139                 let raw_ptr = if zeroed {
140                     GlobalAlloc::alloc_zeroed(self, layout)
141                 } else {
142                     GlobalAlloc::alloc(self, layout)
143                 };
144                 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
145                 Ok(NonNull::slice_from_raw_parts(ptr, size))
146             },
147         }
148     }
149
150     // SAFETY: Same as `Allocator::grow`
151     #[inline]
152     unsafe fn grow_impl(
153         &self,
154         ptr: NonNull<u8>,
155         old_layout: Layout,
156         new_layout: Layout,
157         zeroed: bool,
158     ) -> Result<NonNull<[u8]>, AllocError> {
159         debug_assert!(
160             new_layout.size() >= old_layout.size(),
161             "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
162         );
163
164         match old_layout.size() {
165             0 => self.alloc_impl(new_layout, zeroed),
166
167             // SAFETY: `new_size` is non-zero as `new_size` is greater than or equal to `old_size`
168             // as required by safety conditions and the `old_size == 0` case was handled in the
169             // previous match arm. Other conditions must be upheld by the caller
170             old_size if old_layout.align() == new_layout.align() => unsafe {
171                 let new_size = new_layout.size();
172
173                 // `realloc` probably checks for `new_size >= old_layout.size()` or something similar.
174                 intrinsics::assume(new_size >= old_layout.size());
175
176                 let raw_ptr = GlobalAlloc::realloc(self, ptr.as_ptr(), old_layout, new_size);
177                 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
178                 if zeroed {
179                     raw_ptr.add(old_size).write_bytes(0, new_size - old_size);
180                 }
181                 Ok(NonNull::slice_from_raw_parts(ptr, new_size))
182             },
183
184             // SAFETY: because `new_layout.size()` must be greater than or equal to `old_size`,
185             // both the old and new memory allocation are valid for reads and writes for `old_size`
186             // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
187             // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
188             // for `dealloc` must be upheld by the caller.
189             old_size => unsafe {
190                 let new_ptr = self.alloc_impl(new_layout, zeroed)?;
191                 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_size);
192                 Allocator::deallocate(&self, ptr, old_layout);
193                 Ok(new_ptr)
194             },
195         }
196     }
197 }
198
199 // The Allocator impl checks the layout size to be non-zero and forwards to the GlobalAlloc impl,
200 // which is in `std::sys::*::alloc`.
201 #[unstable(feature = "allocator_api", issue = "32838")]
202 unsafe impl Allocator for System {
203     #[inline]
204     fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
205         self.alloc_impl(layout, false)
206     }
207
208     #[inline]
209     fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
210         self.alloc_impl(layout, true)
211     }
212
213     #[inline]
214     unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
215         if layout.size() != 0 {
216             // SAFETY: `layout` is non-zero in size,
217             // other conditions must be upheld by the caller
218             unsafe { GlobalAlloc::dealloc(self, ptr.as_ptr(), layout) }
219         }
220     }
221
222     #[inline]
223     unsafe fn grow(
224         &self,
225         ptr: NonNull<u8>,
226         old_layout: Layout,
227         new_layout: Layout,
228     ) -> Result<NonNull<[u8]>, AllocError> {
229         // SAFETY: all conditions must be upheld by the caller
230         unsafe { self.grow_impl(ptr, old_layout, new_layout, false) }
231     }
232
233     #[inline]
234     unsafe fn grow_zeroed(
235         &self,
236         ptr: NonNull<u8>,
237         old_layout: Layout,
238         new_layout: Layout,
239     ) -> Result<NonNull<[u8]>, AllocError> {
240         // SAFETY: all conditions must be upheld by the caller
241         unsafe { self.grow_impl(ptr, old_layout, new_layout, true) }
242     }
243
244     #[inline]
245     unsafe fn shrink(
246         &self,
247         ptr: NonNull<u8>,
248         old_layout: Layout,
249         new_layout: Layout,
250     ) -> Result<NonNull<[u8]>, AllocError> {
251         debug_assert!(
252             new_layout.size() <= old_layout.size(),
253             "`new_layout.size()` must be smaller than or equal to `old_layout.size()`"
254         );
255
256         match new_layout.size() {
257             // SAFETY: conditions must be upheld by the caller
258             0 => unsafe {
259                 Allocator::deallocate(&self, ptr, old_layout);
260                 Ok(NonNull::slice_from_raw_parts(new_layout.dangling(), 0))
261             },
262
263             // SAFETY: `new_size` is non-zero. Other conditions must be upheld by the caller
264             new_size if old_layout.align() == new_layout.align() => unsafe {
265                 // `realloc` probably checks for `new_size <= old_layout.size()` or something similar.
266                 intrinsics::assume(new_size <= old_layout.size());
267
268                 let raw_ptr = GlobalAlloc::realloc(self, ptr.as_ptr(), old_layout, new_size);
269                 let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
270                 Ok(NonNull::slice_from_raw_parts(ptr, new_size))
271             },
272
273             // SAFETY: because `new_size` must be smaller than or equal to `old_layout.size()`,
274             // both the old and new memory allocation are valid for reads and writes for `new_size`
275             // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap
276             // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract
277             // for `dealloc` must be upheld by the caller.
278             new_size => unsafe {
279                 let new_ptr = Allocator::allocate(&self, new_layout)?;
280                 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), new_size);
281                 Allocator::deallocate(&self, ptr, old_layout);
282                 Ok(new_ptr)
283             },
284         }
285     }
286 }
287
288 static HOOK: AtomicPtr<()> = AtomicPtr::new(ptr::null_mut());
289
290 /// Registers a custom allocation error hook, replacing any that was previously registered.
291 ///
292 /// The allocation error hook is invoked when an infallible memory allocation fails, before
293 /// the runtime aborts. The default hook prints a message to standard error,
294 /// but this behavior can be customized with the [`set_alloc_error_hook`] and
295 /// [`take_alloc_error_hook`] functions.
296 ///
297 /// The hook is provided with a `Layout` struct which contains information
298 /// about the allocation that failed.
299 ///
300 /// The allocation error hook is a global resource.
301 #[unstable(feature = "alloc_error_hook", issue = "51245")]
302 pub fn set_alloc_error_hook(hook: fn(Layout)) {
303     HOOK.store(hook as *mut (), Ordering::SeqCst);
304 }
305
306 /// Unregisters the current allocation error hook, returning it.
307 ///
308 /// *See also the function [`set_alloc_error_hook`].*
309 ///
310 /// If no custom hook is registered, the default hook will be returned.
311 #[unstable(feature = "alloc_error_hook", issue = "51245")]
312 pub fn take_alloc_error_hook() -> fn(Layout) {
313     let hook = HOOK.swap(ptr::null_mut(), Ordering::SeqCst);
314     if hook.is_null() { default_alloc_error_hook } else { unsafe { mem::transmute(hook) } }
315 }
316
317 fn default_alloc_error_hook(layout: Layout) {
318     #[cfg(not(bootstrap))]
319     extern "Rust" {
320         // This symbol is emitted by rustc next to __rust_alloc_error_handler.
321         // Its value depends on the -Zoom={panic,abort} compiler option.
322         static __rust_alloc_error_handler_should_panic: u8;
323     }
324     #[cfg(bootstrap)]
325     let __rust_alloc_error_handler_should_panic = 0;
326
327     #[allow(unused_unsafe)]
328     if unsafe { __rust_alloc_error_handler_should_panic != 0 } {
329         panic!("memory allocation of {} bytes failed\n", layout.size());
330     } else {
331         rtprintpanic!("memory allocation of {} bytes failed\n", layout.size());
332     }
333 }
334
335 #[cfg(not(test))]
336 #[doc(hidden)]
337 #[alloc_error_handler]
338 #[unstable(feature = "alloc_internals", issue = "none")]
339 pub fn rust_oom(layout: Layout) -> ! {
340     let hook = HOOK.load(Ordering::SeqCst);
341     let hook: fn(Layout) =
342         if hook.is_null() { default_alloc_error_hook } else { unsafe { mem::transmute(hook) } };
343     hook(layout);
344     crate::process::abort()
345 }
346
347 #[cfg(not(test))]
348 #[doc(hidden)]
349 #[allow(unused_attributes)]
350 #[unstable(feature = "alloc_internals", issue = "none")]
351 pub mod __default_lib_allocator {
352     use super::{GlobalAlloc, Layout, System};
353     // These magic symbol names are used as a fallback for implementing the
354     // `__rust_alloc` etc symbols (see `src/liballoc/alloc.rs`) when there is
355     // no `#[global_allocator]` attribute.
356
357     // for symbol names src/librustc_ast/expand/allocator.rs
358     // for signatures src/librustc_allocator/lib.rs
359
360     // linkage directives are provided as part of the current compiler allocator
361     // ABI
362
363     #[rustc_std_internal_symbol]
364     pub unsafe extern "C" fn __rdl_alloc(size: usize, align: usize) -> *mut u8 {
365         // SAFETY: see the guarantees expected by `Layout::from_size_align` and
366         // `GlobalAlloc::alloc`.
367         unsafe {
368             let layout = Layout::from_size_align_unchecked(size, align);
369             System.alloc(layout)
370         }
371     }
372
373     #[rustc_std_internal_symbol]
374     pub unsafe extern "C" fn __rdl_dealloc(ptr: *mut u8, size: usize, align: usize) {
375         // SAFETY: see the guarantees expected by `Layout::from_size_align` and
376         // `GlobalAlloc::dealloc`.
377         unsafe { System.dealloc(ptr, Layout::from_size_align_unchecked(size, align)) }
378     }
379
380     #[rustc_std_internal_symbol]
381     pub unsafe extern "C" fn __rdl_realloc(
382         ptr: *mut u8,
383         old_size: usize,
384         align: usize,
385         new_size: usize,
386     ) -> *mut u8 {
387         // SAFETY: see the guarantees expected by `Layout::from_size_align` and
388         // `GlobalAlloc::realloc`.
389         unsafe {
390             let old_layout = Layout::from_size_align_unchecked(old_size, align);
391             System.realloc(ptr, old_layout, new_size)
392         }
393     }
394
395     #[rustc_std_internal_symbol]
396     pub unsafe extern "C" fn __rdl_alloc_zeroed(size: usize, align: usize) -> *mut u8 {
397         // SAFETY: see the guarantees expected by `Layout::from_size_align` and
398         // `GlobalAlloc::alloc_zeroed`.
399         unsafe {
400             let layout = Layout::from_size_align_unchecked(size, align);
401             System.alloc_zeroed(layout)
402         }
403     }
404 }