use std::alloc::{GlobalAlloc, Layout, System};
use std::sync::atomic::{AtomicPtr, AtomicUsize, Ordering};
use std::sync::Mutex;
static TRACKED_PTR: AtomicPtr<u8> = AtomicPtr::new(std::ptr::null_mut());
static TRACKED_DEALLOC_COUNT: AtomicUsize = AtomicUsize::new(0);
static TEST_LOCK: Mutex<()> = Mutex::new(());
struct DetectingAllocator;
unsafe impl GlobalAlloc for DetectingAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
unsafe { System.alloc(layout) }
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
let tracked = TRACKED_PTR.load(Ordering::SeqCst);
if !tracked.is_null() && ptr == tracked {
TRACKED_DEALLOC_COUNT.fetch_add(1, Ordering::SeqCst);
}
unsafe { System.dealloc(ptr, layout) }
}
}
#[global_allocator]
static ALLOC: DetectingAllocator = DetectingAllocator;
#[test]
fn vec_from_raw_parts_routes_through_global_allocator() {
let _guard = TEST_LOCK.lock().unwrap();
let layout = Layout::array::<u64>(4).unwrap();
let ptr = unsafe { System.alloc(layout) };
assert!(!ptr.is_null());
TRACKED_PTR.store(ptr, Ordering::SeqCst);
TRACKED_DEALLOC_COUNT.store(0, Ordering::SeqCst);
#[allow(
clippy::cast_ptr_alignment,
clippy::ptr_as_ptr,
clippy::same_item_push,
clippy::same_length_and_capacity,
clippy::manual_slice_size_calculation
)]
unsafe {
drop(Vec::from_raw_parts(ptr.cast::<u64>(), 4, 4));
}
TRACKED_PTR.store(std::ptr::null_mut(), Ordering::SeqCst);
let count = TRACKED_DEALLOC_COUNT.load(Ordering::SeqCst);
assert!(
count > 0,
"Vec::from_raw_parts SHOULD route through global allocator (count={count}). \
This proves the bug: with a real custom allocator like mimalloc, this would crash."
);
}
#[test]
fn system_dealloc_bypasses_global_allocator() {
let _guard = TEST_LOCK.lock().unwrap();
let layout = Layout::array::<u64>(4).unwrap();
let ptr = unsafe { System.alloc(layout) };
assert!(!ptr.is_null());
TRACKED_PTR.store(ptr, Ordering::SeqCst);
TRACKED_DEALLOC_COUNT.store(0, Ordering::SeqCst);
unsafe {
System.dealloc(ptr, layout);
}
TRACKED_PTR.store(std::ptr::null_mut(), Ordering::SeqCst);
let count = TRACKED_DEALLOC_COUNT.load(Ordering::SeqCst);
assert_eq!(
count, 0,
"System.dealloc should NOT route through global allocator (count={count})"
);
}