Pierre-Clément Tosi | fc53115 | 2022-10-20 12:22:23 +0100 | [diff] [blame] | 1 | // Copyright 2022, The Android Open Source Project |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | //! Heap implementation. |
| 16 | |
Pierre-Clément Tosi | db74cb1 | 2022-12-08 13:56:25 +0000 | [diff] [blame] | 17 | use alloc::alloc::alloc; |
| 18 | use alloc::alloc::Layout; |
| 19 | use alloc::boxed::Box; |
| 20 | |
Pierre-Clément Tosi | 54e71d0 | 2022-12-08 13:57:43 +0000 | [diff] [blame] | 21 | use core::alloc::GlobalAlloc as _; |
Pierre-Clément Tosi | 54e71d0 | 2022-12-08 13:57:43 +0000 | [diff] [blame] | 22 | use core::ffi::c_void; |
| 23 | use core::mem; |
| 24 | use core::num::NonZeroUsize; |
| 25 | use core::ptr; |
| 26 | use core::ptr::NonNull; |
| 27 | |
Pierre-Clément Tosi | fc53115 | 2022-10-20 12:22:23 +0100 | [diff] [blame] | 28 | use buddy_system_allocator::LockedHeap; |
| 29 | |
Pierre-Clément Tosi | f3681e8 | 2023-06-22 11:38:22 +0000 | [diff] [blame] | 30 | /// Configures the size of the global allocator. |
| 31 | #[macro_export] |
Pierre-Clément Tosi | 6a4808c | 2023-06-29 09:19:38 +0000 | [diff] [blame] | 32 | macro_rules! configure_heap { |
Pierre-Clément Tosi | f3681e8 | 2023-06-22 11:38:22 +0000 | [diff] [blame] | 33 | ($len:expr) => { |
| 34 | static mut __HEAP_ARRAY: [u8; $len] = [0; $len]; |
| 35 | #[export_name = "HEAP"] |
Andrew Walbran | c06e734 | 2023-07-05 14:00:51 +0000 | [diff] [blame] | 36 | // SAFETY: HEAP will only be accessed once as mut, from init(). |
Pierre-Clément Tosi | f3681e8 | 2023-06-22 11:38:22 +0000 | [diff] [blame] | 37 | static mut __HEAP: &'static mut [u8] = unsafe { &mut __HEAP_ARRAY }; |
| 38 | }; |
| 39 | } |
| 40 | |
| 41 | extern "Rust" { |
Pierre-Clément Tosi | 6a4808c | 2023-06-29 09:19:38 +0000 | [diff] [blame] | 42 | /// Slice used by the global allocator, configured using configure_heap!(). |
Pierre-Clément Tosi | f3681e8 | 2023-06-22 11:38:22 +0000 | [diff] [blame] | 43 | static mut HEAP: &'static mut [u8]; |
| 44 | } |
Pierre-Clément Tosi | fc53115 | 2022-10-20 12:22:23 +0100 | [diff] [blame] | 45 | |
Alan Stokes | a0e4296 | 2023-04-14 17:59:50 +0100 | [diff] [blame] | 46 | #[global_allocator] |
| 47 | static HEAP_ALLOCATOR: LockedHeap<32> = LockedHeap::<32>::new(); |
| 48 | |
Pierre-Clément Tosi | f3681e8 | 2023-06-22 11:38:22 +0000 | [diff] [blame] | 49 | /// Initialize the global allocator. |
| 50 | /// |
| 51 | /// # Safety |
| 52 | /// |
| 53 | /// Must be called no more than once. |
Pierre-Clément Tosi | 8ca7a44 | 2023-06-22 13:47:15 +0000 | [diff] [blame] | 54 | pub(crate) unsafe fn init() { |
Alan Stokes | a0e4296 | 2023-04-14 17:59:50 +0100 | [diff] [blame] | 55 | // SAFETY: Nothing else accesses this memory, and we hand it over to the heap to manage and |
| 56 | // never touch it again. The heap is locked, so there cannot be any races. |
| 57 | let (start, size) = unsafe { (HEAP.as_mut_ptr() as usize, HEAP.len()) }; |
| 58 | |
| 59 | let mut heap = HEAP_ALLOCATOR.lock(); |
| 60 | // SAFETY: We are supplying a valid memory range, and we only do this once. |
| 61 | unsafe { heap.init(start, size) }; |
Pierre-Clément Tosi | fc53115 | 2022-10-20 12:22:23 +0100 | [diff] [blame] | 62 | } |
Pierre-Clément Tosi | 54e71d0 | 2022-12-08 13:57:43 +0000 | [diff] [blame] | 63 | |
Pierre-Clément Tosi | db74cb1 | 2022-12-08 13:56:25 +0000 | [diff] [blame] | 64 | /// Allocate an aligned but uninitialized slice of heap. |
| 65 | pub fn aligned_boxed_slice(size: usize, align: usize) -> Option<Box<[u8]>> { |
| 66 | let size = NonZeroUsize::new(size)?.get(); |
| 67 | let layout = Layout::from_size_align(size, align).ok()?; |
Andrew Walbran | c06e734 | 2023-07-05 14:00:51 +0000 | [diff] [blame] | 68 | // SAFETY: We verify that `size` and the returned `ptr` are non-null. |
Pierre-Clément Tosi | db74cb1 | 2022-12-08 13:56:25 +0000 | [diff] [blame] | 69 | let ptr = unsafe { alloc(layout) }; |
| 70 | let ptr = NonNull::new(ptr)?.as_ptr(); |
| 71 | let slice_ptr = ptr::slice_from_raw_parts_mut(ptr, size); |
| 72 | |
Andrew Walbran | c06e734 | 2023-07-05 14:00:51 +0000 | [diff] [blame] | 73 | // SAFETY: The memory was allocated using the proper layout by our global_allocator. |
Pierre-Clément Tosi | db74cb1 | 2022-12-08 13:56:25 +0000 | [diff] [blame] | 74 | Some(unsafe { Box::from_raw(slice_ptr) }) |
| 75 | } |
| 76 | |
Pierre-Clément Tosi | 54e71d0 | 2022-12-08 13:57:43 +0000 | [diff] [blame] | 77 | #[no_mangle] |
| 78 | unsafe extern "C" fn malloc(size: usize) -> *mut c_void { |
Alan Stokes | a0e4296 | 2023-04-14 17:59:50 +0100 | [diff] [blame] | 79 | allocate(size, false).map_or(ptr::null_mut(), |p| p.cast::<c_void>().as_ptr()) |
Pierre-Clément Tosi | aaa0869 | 2023-03-10 13:55:19 +0000 | [diff] [blame] | 80 | } |
| 81 | |
| 82 | #[no_mangle] |
| 83 | unsafe extern "C" fn calloc(nmemb: usize, size: usize) -> *mut c_void { |
| 84 | let Some(size) = nmemb.checked_mul(size) else { |
| 85 | return ptr::null_mut() |
| 86 | }; |
Alan Stokes | a0e4296 | 2023-04-14 17:59:50 +0100 | [diff] [blame] | 87 | allocate(size, true).map_or(ptr::null_mut(), |p| p.cast::<c_void>().as_ptr()) |
Pierre-Clément Tosi | 54e71d0 | 2022-12-08 13:57:43 +0000 | [diff] [blame] | 88 | } |
| 89 | |
| 90 | #[no_mangle] |
Alan Stokes | a0e4296 | 2023-04-14 17:59:50 +0100 | [diff] [blame] | 91 | /// SAFETY: ptr must be null or point to a currently-allocated block returned by allocate (either |
| 92 | /// directly or via malloc or calloc). Note that this function is called directly from C, so we have |
| 93 | /// to trust that the C code is doing the right thing; there are checks below which will catch some |
| 94 | /// errors. |
Pierre-Clément Tosi | 54e71d0 | 2022-12-08 13:57:43 +0000 | [diff] [blame] | 95 | unsafe extern "C" fn free(ptr: *mut c_void) { |
Alan Stokes | a0e4296 | 2023-04-14 17:59:50 +0100 | [diff] [blame] | 96 | let Some(ptr) = NonNull::new(ptr) else { return }; |
| 97 | // SAFETY: The contents of the HEAP slice may change, but the address range never does. |
| 98 | let heap_range = unsafe { HEAP.as_ptr_range() }; |
| 99 | assert!( |
| 100 | heap_range.contains(&(ptr.as_ptr() as *const u8)), |
| 101 | "free() called on a pointer that is not part of the HEAP: {ptr:?}" |
| 102 | ); |
Andrew Walbran | c06e734 | 2023-07-05 14:00:51 +0000 | [diff] [blame] | 103 | // SAFETY: ptr is non-null and was allocated by allocate, which prepends a correctly aligned |
| 104 | // usize. |
Alan Stokes | a0e4296 | 2023-04-14 17:59:50 +0100 | [diff] [blame] | 105 | let (ptr, size) = unsafe { |
Alan Stokes | a0e4296 | 2023-04-14 17:59:50 +0100 | [diff] [blame] | 106 | let ptr = ptr.cast::<usize>().as_ptr().offset(-1); |
| 107 | (ptr, *ptr) |
| 108 | }; |
| 109 | let size = NonZeroUsize::new(size).unwrap(); |
| 110 | let layout = malloc_layout(size).unwrap(); |
| 111 | // SAFETY: If our precondition is satisfied, then this is a valid currently-allocated block. |
| 112 | unsafe { HEAP_ALLOCATOR.dealloc(ptr as *mut u8, layout) } |
| 113 | } |
| 114 | |
| 115 | /// Allocate a block of memory suitable to return from `malloc()` etc. Returns a valid pointer |
| 116 | /// to a suitable aligned region of size bytes, optionally zeroed (and otherwise uninitialized), or |
| 117 | /// None if size is 0 or allocation fails. The block can be freed by passing the returned pointer to |
| 118 | /// `free()`. |
| 119 | fn allocate(size: usize, zeroed: bool) -> Option<NonNull<usize>> { |
| 120 | let size = NonZeroUsize::new(size)?.checked_add(mem::size_of::<usize>())?; |
| 121 | let layout = malloc_layout(size)?; |
| 122 | // SAFETY: layout is known to have non-zero size. |
| 123 | let ptr = unsafe { |
| 124 | if zeroed { |
| 125 | HEAP_ALLOCATOR.alloc_zeroed(layout) |
| 126 | } else { |
| 127 | HEAP_ALLOCATOR.alloc(layout) |
Pierre-Clément Tosi | 54e71d0 | 2022-12-08 13:57:43 +0000 | [diff] [blame] | 128 | } |
Alan Stokes | a0e4296 | 2023-04-14 17:59:50 +0100 | [diff] [blame] | 129 | }; |
| 130 | let ptr = NonNull::new(ptr)?.cast::<usize>().as_ptr(); |
| 131 | // SAFETY: ptr points to a newly allocated block of memory which is properly aligned |
| 132 | // for a usize and is big enough to hold a usize as well as the requested number of |
| 133 | // bytes. |
| 134 | unsafe { |
| 135 | *ptr = size.get(); |
| 136 | NonNull::new(ptr.offset(1)) |
Pierre-Clément Tosi | 54e71d0 | 2022-12-08 13:57:43 +0000 | [diff] [blame] | 137 | } |
| 138 | } |
| 139 | |
Alan Stokes | a0e4296 | 2023-04-14 17:59:50 +0100 | [diff] [blame] | 140 | fn malloc_layout(size: NonZeroUsize) -> Option<Layout> { |
| 141 | // We want at least 8 byte alignment, and we need to be able to store a usize. |
| 142 | const ALIGN: usize = const_max_size(mem::size_of::<usize>(), mem::size_of::<u64>()); |
| 143 | Layout::from_size_align(size.get(), ALIGN).ok() |
Pierre-Clément Tosi | 54e71d0 | 2022-12-08 13:57:43 +0000 | [diff] [blame] | 144 | } |
| 145 | |
Alan Stokes | a0e4296 | 2023-04-14 17:59:50 +0100 | [diff] [blame] | 146 | const fn const_max_size(a: usize, b: usize) -> usize { |
| 147 | if a > b { |
| 148 | a |
| 149 | } else { |
| 150 | b |
| 151 | } |
Pierre-Clément Tosi | 54e71d0 | 2022-12-08 13:57:43 +0000 | [diff] [blame] | 152 | } |