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 | 54e71d0 | 2022-12-08 13:57:43 +0000 | [diff] [blame^] | 17 | use core::alloc::GlobalAlloc as _; |
| 18 | use core::alloc::Layout; |
| 19 | use core::ffi::c_void; |
| 20 | use core::mem; |
| 21 | use core::num::NonZeroUsize; |
| 22 | use core::ptr; |
| 23 | use core::ptr::NonNull; |
| 24 | |
Pierre-Clément Tosi | fc53115 | 2022-10-20 12:22:23 +0100 | [diff] [blame] | 25 | use buddy_system_allocator::LockedHeap; |
| 26 | |
| 27 | #[global_allocator] |
| 28 | static HEAP_ALLOCATOR: LockedHeap<32> = LockedHeap::<32>::new(); |
| 29 | |
| 30 | static mut HEAP: [u8; 65536] = [0; 65536]; |
| 31 | |
| 32 | pub unsafe fn init() { |
| 33 | HEAP_ALLOCATOR.lock().init(HEAP.as_mut_ptr() as usize, HEAP.len()); |
| 34 | } |
Pierre-Clément Tosi | 54e71d0 | 2022-12-08 13:57:43 +0000 | [diff] [blame^] | 35 | |
| 36 | #[no_mangle] |
| 37 | unsafe extern "C" fn malloc(size: usize) -> *mut c_void { |
| 38 | malloc_(size).map_or(ptr::null_mut(), |p| p.cast::<c_void>().as_ptr()) |
| 39 | } |
| 40 | |
| 41 | #[no_mangle] |
| 42 | unsafe extern "C" fn free(ptr: *mut c_void) { |
| 43 | if let Some(ptr) = NonNull::new(ptr).map(|p| p.cast::<usize>().as_ptr().offset(-1)) { |
| 44 | if let Some(size) = NonZeroUsize::new(*ptr) { |
| 45 | if let Some(layout) = malloc_layout(size) { |
| 46 | HEAP_ALLOCATOR.dealloc(ptr as *mut u8, layout); |
| 47 | } |
| 48 | } |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | unsafe fn malloc_(size: usize) -> Option<NonNull<usize>> { |
| 53 | let size = NonZeroUsize::new(size)?.checked_add(mem::size_of::<usize>())?; |
| 54 | let ptr = HEAP_ALLOCATOR.alloc(malloc_layout(size)?); |
| 55 | let ptr = NonNull::new(ptr)?.cast::<usize>().as_ptr(); |
| 56 | *ptr = size.get(); |
| 57 | NonNull::new(ptr.offset(1)) |
| 58 | } |
| 59 | |
| 60 | fn malloc_layout(size: NonZeroUsize) -> Option<Layout> { |
| 61 | const ALIGN: usize = mem::size_of::<u64>(); |
| 62 | Layout::from_size_align(size.get(), ALIGN).ok() |
| 63 | } |