alloc.rs 16 KB

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