]> git.lizzy.rs Git - rust.git/blob - src/libstd/alloc.rs
Rollup merge of #72807 - xiaotianrandom:fix-assoc-type-diagnostics, r=estebank
[rust.git] / src / libstd / 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 //! [`System`]: struct.System.html
11 //!
12 //! # The `#[global_allocator]` attribute
13 //!
14 //! This attribute allows configuring the choice of global allocator.
15 //! You can use this to implement a completely custom global allocator
16 //! to route all default allocation requests to a custom object.
17 //!
18 //! ```rust
19 //! use std::alloc::{GlobalAlloc, System, Layout};
20 //!
21 //! struct MyAllocator;
22 //!
23 //! unsafe impl GlobalAlloc for MyAllocator {
24 //!     unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
25 //!         System.alloc(layout)
26 //!     }
27 //!
28 //!     unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
29 //!         System.dealloc(ptr, layout)
30 //!     }
31 //! }
32 //!
33 //! #[global_allocator]
34 //! static GLOBAL: MyAllocator = MyAllocator;
35 //!
36 //! fn main() {
37 //!     // This `Vec` will allocate memory through `GLOBAL` above
38 //!     let mut v = Vec::new();
39 //!     v.push(1);
40 //! }
41 //! ```
42 //!
43 //! The attribute is used on a `static` item whose type implements the
44 //! [`GlobalAlloc`] trait. This type can be provided by an external library:
45 //!
46 //! [`GlobalAlloc`]: ../../core/alloc/trait.GlobalAlloc.html
47 //!
48 //! ```rust,ignore (demonstrates crates.io usage)
49 //! extern crate jemallocator;
50 //!
51 //! use jemallocator::Jemalloc;
52 //!
53 //! #[global_allocator]
54 //! static GLOBAL: Jemalloc = Jemalloc;
55 //!
56 //! fn main() {}
57 //! ```
58 //!
59 //! The `#[global_allocator]` can only be used once in a crate
60 //! or its recursive dependencies.
61
62 #![stable(feature = "alloc_module", since = "1.28.0")]
63
64 use core::intrinsics;
65 use core::ptr::NonNull;
66 use core::sync::atomic::{AtomicPtr, Ordering};
67 use core::{mem, ptr};
68
69 use crate::sys_common::util::dumb_print;
70
71 #[stable(feature = "alloc_module", since = "1.28.0")]
72 #[doc(inline)]
73 pub use alloc_crate::alloc::*;
74
75 /// The default memory allocator provided by the operating system.
76 ///
77 /// This is based on `malloc` on Unix platforms and `HeapAlloc` on Windows,
78 /// plus related functions.
79 ///
80 /// This type implements the `GlobalAlloc` trait and Rust programs by default
81 /// work as if they had this definition:
82 ///
83 /// ```rust
84 /// use std::alloc::System;
85 ///
86 /// #[global_allocator]
87 /// static A: System = System;
88 ///
89 /// fn main() {
90 ///     let a = Box::new(4); // Allocates from the system allocator.
91 ///     println!("{}", a);
92 /// }
93 /// ```
94 ///
95 /// You can also define your own wrapper around `System` if you'd like, such as
96 /// keeping track of the number of all bytes allocated:
97 ///
98 /// ```rust
99 /// use std::alloc::{System, GlobalAlloc, Layout};
100 /// use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
101 ///
102 /// struct Counter;
103 ///
104 /// static ALLOCATED: AtomicUsize = AtomicUsize::new(0);
105 ///
106 /// unsafe impl GlobalAlloc for Counter {
107 ///     unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
108 ///         let ret = System.alloc(layout);
109 ///         if !ret.is_null() {
110 ///             ALLOCATED.fetch_add(layout.size(), SeqCst);
111 ///         }
112 ///         return ret
113 ///     }
114 ///
115 ///     unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
116 ///         System.dealloc(ptr, layout);
117 ///         ALLOCATED.fetch_sub(layout.size(), SeqCst);
118 ///     }
119 /// }
120 ///
121 /// #[global_allocator]
122 /// static A: Counter = Counter;
123 ///
124 /// fn main() {
125 ///     println!("allocated bytes before main: {}", ALLOCATED.load(SeqCst));
126 /// }
127 /// ```
128 ///
129 /// It can also be used directly to allocate memory independently of whatever
130 /// global allocator has been selected for a Rust program. For example if a Rust
131 /// program opts in to using jemalloc as the global allocator, `System` will
132 /// still allocate memory using `malloc` and `HeapAlloc`.
133 #[stable(feature = "alloc_system_type", since = "1.28.0")]
134 #[derive(Debug, Default, Copy, Clone)]
135 pub struct System;
136
137 // The AllocRef impl checks the layout size to be non-zero and forwards to the GlobalAlloc impl,
138 // which is in `std::sys::*::alloc`.
139 #[unstable(feature = "allocator_api", issue = "32838")]
140 unsafe impl AllocRef for System {
141     #[inline]
142     fn alloc(&mut self, layout: Layout, init: AllocInit) -> Result<MemoryBlock, AllocErr> {
143         unsafe {
144             let size = layout.size();
145             if size == 0 {
146                 Ok(MemoryBlock { ptr: layout.dangling(), size: 0 })
147             } else {
148                 let raw_ptr = match init {
149                     AllocInit::Uninitialized => GlobalAlloc::alloc(self, layout),
150                     AllocInit::Zeroed => GlobalAlloc::alloc_zeroed(self, layout),
151                 };
152                 let ptr = NonNull::new(raw_ptr).ok_or(AllocErr)?;
153                 Ok(MemoryBlock { ptr, size })
154             }
155         }
156     }
157
158     #[inline]
159     unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout) {
160         if layout.size() != 0 {
161             GlobalAlloc::dealloc(self, ptr.as_ptr(), layout)
162         }
163     }
164
165     #[inline]
166     unsafe fn grow(
167         &mut self,
168         ptr: NonNull<u8>,
169         layout: Layout,
170         new_size: usize,
171         placement: ReallocPlacement,
172         init: AllocInit,
173     ) -> Result<MemoryBlock, AllocErr> {
174         let size = layout.size();
175         debug_assert!(
176             new_size >= size,
177             "`new_size` must be greater than or equal to `memory.size()`"
178         );
179
180         if size == new_size {
181             return Ok(MemoryBlock { ptr, size });
182         }
183
184         match placement {
185             ReallocPlacement::InPlace => Err(AllocErr),
186             ReallocPlacement::MayMove if layout.size() == 0 => {
187                 let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
188                 self.alloc(new_layout, init)
189             }
190             ReallocPlacement::MayMove => {
191                 // `realloc` probably checks for `new_size > size` or something similar.
192                 intrinsics::assume(new_size > size);
193                 let ptr = GlobalAlloc::realloc(self, ptr.as_ptr(), layout, new_size);
194                 let memory =
195                     MemoryBlock { ptr: NonNull::new(ptr).ok_or(AllocErr)?, size: new_size };
196                 init.init_offset(memory, size);
197                 Ok(memory)
198             }
199         }
200     }
201
202     #[inline]
203     unsafe fn shrink(
204         &mut self,
205         ptr: NonNull<u8>,
206         layout: Layout,
207         new_size: usize,
208         placement: ReallocPlacement,
209     ) -> Result<MemoryBlock, AllocErr> {
210         let size = layout.size();
211         debug_assert!(
212             new_size <= size,
213             "`new_size` must be smaller than or equal to `memory.size()`"
214         );
215
216         if size == new_size {
217             return Ok(MemoryBlock { ptr, size });
218         }
219
220         match placement {
221             ReallocPlacement::InPlace => Err(AllocErr),
222             ReallocPlacement::MayMove if new_size == 0 => {
223                 self.dealloc(ptr, layout);
224                 Ok(MemoryBlock { ptr: layout.dangling(), size: 0 })
225             }
226             ReallocPlacement::MayMove => {
227                 // `realloc` probably checks for `new_size < size` or something similar.
228                 intrinsics::assume(new_size < size);
229                 let ptr = GlobalAlloc::realloc(self, ptr.as_ptr(), layout, new_size);
230                 Ok(MemoryBlock { ptr: NonNull::new(ptr).ok_or(AllocErr)?, size: new_size })
231             }
232         }
233     }
234 }
235 static HOOK: AtomicPtr<()> = AtomicPtr::new(ptr::null_mut());
236
237 /// Registers a custom allocation error hook, replacing any that was previously registered.
238 ///
239 /// The allocation error hook is invoked when an infallible memory allocation fails, before
240 /// the runtime aborts. The default hook prints a message to standard error,
241 /// but this behavior can be customized with the [`set_alloc_error_hook`] and
242 /// [`take_alloc_error_hook`] functions.
243 ///
244 /// The hook is provided with a `Layout` struct which contains information
245 /// about the allocation that failed.
246 ///
247 /// The allocation error hook is a global resource.
248 ///
249 /// [`set_alloc_error_hook`]: fn.set_alloc_error_hook.html
250 /// [`take_alloc_error_hook`]: fn.take_alloc_error_hook.html
251 #[unstable(feature = "alloc_error_hook", issue = "51245")]
252 pub fn set_alloc_error_hook(hook: fn(Layout)) {
253     HOOK.store(hook as *mut (), Ordering::SeqCst);
254 }
255
256 /// Unregisters the current allocation error hook, returning it.
257 ///
258 /// *See also the function [`set_alloc_error_hook`].*
259 ///
260 /// If no custom hook is registered, the default hook will be returned.
261 ///
262 /// [`set_alloc_error_hook`]: fn.set_alloc_error_hook.html
263 #[unstable(feature = "alloc_error_hook", issue = "51245")]
264 pub fn take_alloc_error_hook() -> fn(Layout) {
265     let hook = HOOK.swap(ptr::null_mut(), Ordering::SeqCst);
266     if hook.is_null() { default_alloc_error_hook } else { unsafe { mem::transmute(hook) } }
267 }
268
269 fn default_alloc_error_hook(layout: Layout) {
270     dumb_print(format_args!("memory allocation of {} bytes failed", layout.size()));
271 }
272
273 #[cfg(not(test))]
274 #[doc(hidden)]
275 #[alloc_error_handler]
276 #[unstable(feature = "alloc_internals", issue = "none")]
277 pub fn rust_oom(layout: Layout) -> ! {
278     let hook = HOOK.load(Ordering::SeqCst);
279     let hook: fn(Layout) =
280         if hook.is_null() { default_alloc_error_hook } else { unsafe { mem::transmute(hook) } };
281     hook(layout);
282     crate::process::abort()
283 }
284
285 #[cfg(not(test))]
286 #[doc(hidden)]
287 #[allow(unused_attributes)]
288 #[unstable(feature = "alloc_internals", issue = "none")]
289 pub mod __default_lib_allocator {
290     use super::{GlobalAlloc, Layout, System};
291     // These magic symbol names are used as a fallback for implementing the
292     // `__rust_alloc` etc symbols (see `src/liballoc/alloc.rs`) when there is
293     // no `#[global_allocator]` attribute.
294
295     // for symbol names src/librustc_ast/expand/allocator.rs
296     // for signatures src/librustc_allocator/lib.rs
297
298     // linkage directives are provided as part of the current compiler allocator
299     // ABI
300
301     #[rustc_std_internal_symbol]
302     pub unsafe extern "C" fn __rdl_alloc(size: usize, align: usize) -> *mut u8 {
303         let layout = Layout::from_size_align_unchecked(size, align);
304         System.alloc(layout)
305     }
306
307     #[rustc_std_internal_symbol]
308     pub unsafe extern "C" fn __rdl_dealloc(ptr: *mut u8, size: usize, align: usize) {
309         System.dealloc(ptr, Layout::from_size_align_unchecked(size, align))
310     }
311
312     #[rustc_std_internal_symbol]
313     pub unsafe extern "C" fn __rdl_realloc(
314         ptr: *mut u8,
315         old_size: usize,
316         align: usize,
317         new_size: usize,
318     ) -> *mut u8 {
319         let old_layout = Layout::from_size_align_unchecked(old_size, align);
320         System.realloc(ptr, old_layout, new_size)
321     }
322
323     #[rustc_std_internal_symbol]
324     pub unsafe extern "C" fn __rdl_alloc_zeroed(size: usize, align: usize) -> *mut u8 {
325         let layout = Layout::from_size_align_unchecked(size, align);
326         System.alloc_zeroed(layout)
327     }
328 }