|
| 1 | +use crate::alloc::{GlobalAlloc, Layout, System}; |
| 2 | + |
| 3 | +static mut DLMALLOC: dlmalloc::Dlmalloc = dlmalloc::Dlmalloc::new(); |
| 4 | + |
| 5 | +#[stable(feature = "alloc_system_type", since = "1.28.0")] |
| 6 | +unsafe impl GlobalAlloc for System { |
| 7 | + #[inline] |
| 8 | + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { |
| 9 | + // SAFETY: DLMALLOC access is guaranteed to be safe because the lock gives us unique and non-reentrant access. |
| 10 | + // Calling malloc() is safe because preconditions on this function match the trait method preconditions. |
| 11 | + let _lock = lock::lock(); |
| 12 | + unsafe { DLMALLOC.malloc(layout.size(), layout.align()) } |
| 13 | + } |
| 14 | + |
| 15 | + #[inline] |
| 16 | + unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { |
| 17 | + // SAFETY: DLMALLOC access is guaranteed to be safe because the lock gives us unique and non-reentrant access. |
| 18 | + // Calling calloc() is safe because preconditions on this function match the trait method preconditions. |
| 19 | + let _lock = lock::lock(); |
| 20 | + unsafe { DLMALLOC.calloc(layout.size(), layout.align()) } |
| 21 | + } |
| 22 | + |
| 23 | + #[inline] |
| 24 | + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { |
| 25 | + // SAFETY: DLMALLOC access is guaranteed to be safe because the lock gives us unique and non-reentrant access. |
| 26 | + // Calling free() is safe because preconditions on this function match the trait method preconditions. |
| 27 | + let _lock = lock::lock(); |
| 28 | + unsafe { DLMALLOC.free(ptr, layout.size(), layout.align()) } |
| 29 | + } |
| 30 | + |
| 31 | + #[inline] |
| 32 | + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { |
| 33 | + // SAFETY: DLMALLOC access is guaranteed to be safe because the lock gives us unique and non-reentrant access. |
| 34 | + // Calling realloc() is safe because preconditions on this function match the trait method preconditions. |
| 35 | + let _lock = lock::lock(); |
| 36 | + unsafe { DLMALLOC.realloc(ptr, layout.size(), layout.align(), new_size) } |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +mod lock { |
| 41 | + use crate::sync::atomic::{AtomicI32, Ordering::SeqCst}; |
| 42 | + |
| 43 | + static LOCKED: AtomicI32 = AtomicI32::new(0); |
| 44 | + |
| 45 | + pub struct DropLock; |
| 46 | + |
| 47 | + pub fn lock() -> DropLock { |
| 48 | + loop { |
| 49 | + if LOCKED.swap(1, SeqCst) == 0 { |
| 50 | + return DropLock; |
| 51 | + } |
| 52 | + crate::os::xous::ffi::do_yield(); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + impl Drop for DropLock { |
| 57 | + fn drop(&mut self) { |
| 58 | + let r = LOCKED.swap(0, SeqCst); |
| 59 | + debug_assert_eq!(r, 1); |
| 60 | + } |
| 61 | + } |
| 62 | +} |
0 commit comments