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