Skip to main content

regorus_mimalloc/
mimalloc.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4use core::alloc::{GlobalAlloc, Layout};
5use core::ffi::c_void;
6use core::ptr;
7use mimalloc_sys::{
8    mi_free, mi_malloc_aligned, mi_realloc_aligned, mi_zalloc_aligned, MI_ALIGNMENT_MAX,
9};
10
11#[cfg(feature = "allocator-memory-limits")]
12pub use crate::limits::{
13    allocation_stats_snapshot, current_thread_allocation_stats, current_thread_live_bytes,
14    flush_thread_counters, global_allocation_stats_snapshot, record_alloc, record_free,
15    set_thread_flush_threshold, GlobalAllocationStats, MemoryBudgetUsage, ThreadAllocationStats,
16};
17
18#[cfg(feature = "allocator-memory-limits")]
19use crate::limits::record_memory_budget_alloc;
20
21pub struct Mimalloc;
22
23unsafe impl GlobalAlloc for Mimalloc {
24    #[inline]
25    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
26        debug_assert!(layout.align() < MI_ALIGNMENT_MAX);
27        let ptr = mi_malloc_aligned(layout.size(), layout.align()).cast::<u8>();
28        #[cfg(feature = "allocator-memory-limits")]
29        if !ptr.is_null() {
30            record_memory_budget_alloc(layout.size());
31            record_alloc(layout.size());
32        }
33        ptr
34    }
35
36    #[inline]
37    unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
38        if ptr.is_null() {
39            return;
40        }
41        #[cfg(feature = "allocator-memory-limits")]
42        record_free(_layout.size());
43        mi_free(ptr.cast::<c_void>());
44    }
45
46    #[inline]
47    unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
48        debug_assert!(layout.align() < MI_ALIGNMENT_MAX);
49        let ptr = mi_zalloc_aligned(layout.size(), layout.align()).cast::<u8>();
50        #[cfg(feature = "allocator-memory-limits")]
51        if !ptr.is_null() {
52            record_memory_budget_alloc(layout.size());
53            record_alloc(layout.size());
54        }
55        ptr
56    }
57
58    #[inline]
59    unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
60        debug_assert!(layout.align() < MI_ALIGNMENT_MAX);
61        if ptr.is_null() || Layout::from_size_align(new_size, layout.align()).is_err() {
62            return ptr::null_mut();
63        }
64
65        #[cfg(all(test, feature = "allocator-memory-limits"))]
66        let result = if tests::take_next_native_realloc_failure_for_test() {
67            ptr::null_mut()
68        } else {
69            mi_realloc_aligned(ptr.cast::<c_void>(), new_size, layout.align()).cast::<u8>()
70        };
71        #[cfg(not(all(test, feature = "allocator-memory-limits")))]
72        let result =
73            mi_realloc_aligned(ptr.cast::<c_void>(), new_size, layout.align()).cast::<u8>();
74        if !result.is_null() {
75            #[cfg(feature = "allocator-memory-limits")]
76            record_memory_budget_alloc(new_size);
77            #[cfg(feature = "allocator-memory-limits")]
78            {
79                record_free(layout.size());
80                record_alloc(new_size);
81            }
82        }
83        result
84    }
85}
86
87#[cfg(test)]
88mod tests {
89    #[cfg(feature = "allocator-memory-limits")]
90    use super::MemoryBudgetUsage;
91    use super::*;
92    use std::error::Error;
93
94    #[cfg(feature = "allocator-memory-limits")]
95    struct TestBudgetUsage {
96        usage: Option<MemoryBudgetUsage>,
97    }
98
99    #[cfg(feature = "allocator-memory-limits")]
100    impl Default for TestBudgetUsage {
101        fn default() -> Self {
102            Self {
103                usage: Some(MemoryBudgetUsage::default()),
104            }
105        }
106    }
107
108    #[cfg(feature = "allocator-memory-limits")]
109    impl TestBudgetUsage {
110        fn new() -> Self {
111            Self::default()
112        }
113
114        fn requested_bytes(&self) -> u64 {
115            self.usage.map_or(0, MemoryBudgetUsage::requested_bytes)
116        }
117
118        fn with_scope<R>(&mut self, operation: impl FnOnce() -> R) -> R {
119            let initial = self.usage;
120            crate::limits::with_memory_budget_usage_scope(initial, &mut self.usage, operation)
121        }
122    }
123
124    #[cfg(feature = "allocator-memory-limits")]
125    fn current_requested_bytes() -> u64 {
126        crate::limits::current_memory_budget_usage().map_or(0, MemoryBudgetUsage::requested_bytes)
127    }
128
129    #[cfg(feature = "allocator-memory-limits")]
130    std::thread_local! {
131        static FAIL_NEXT_NATIVE_REALLOC_FOR_TEST: core::cell::Cell<bool> =
132            const { core::cell::Cell::new(false) };
133    }
134
135    #[cfg(feature = "allocator-memory-limits")]
136    struct FailNextNativeReallocGuard {
137        previous: bool,
138    }
139
140    #[cfg(feature = "allocator-memory-limits")]
141    impl FailNextNativeReallocGuard {
142        fn arm() -> Self {
143            let previous =
144                FAIL_NEXT_NATIVE_REALLOC_FOR_TEST.with(|should_fail| should_fail.replace(true));
145            Self { previous }
146        }
147    }
148
149    #[cfg(feature = "allocator-memory-limits")]
150    impl Drop for FailNextNativeReallocGuard {
151        fn drop(&mut self) {
152            FAIL_NEXT_NATIVE_REALLOC_FOR_TEST.with(|should_fail| should_fail.set(self.previous));
153        }
154    }
155
156    #[cfg(feature = "allocator-memory-limits")]
157    pub(super) fn take_next_native_realloc_failure_for_test() -> bool {
158        FAIL_NEXT_NATIVE_REALLOC_FOR_TEST.with(|should_fail| should_fail.replace(false))
159    }
160
161    #[test]
162    fn memory_can_be_allocated_and_freed() -> Result<(), Box<dyn Error>> {
163        let layout = Layout::from_size_align(8, 8)?;
164        let alloc = Mimalloc;
165
166        unsafe {
167            let ptr = alloc.alloc(layout);
168            if ptr.cast::<c_void>().is_null() {
169                assert!(!ptr.cast::<c_void>().is_null());
170            } else {
171                alloc.dealloc(ptr, layout);
172            }
173        }
174        Ok(())
175    }
176
177    #[test]
178    fn memory_can_be_alloc_zeroed_and_freed() -> Result<(), Box<dyn Error>> {
179        let layout = Layout::from_size_align(8, 8)?;
180        let alloc = Mimalloc;
181
182        unsafe {
183            let ptr = alloc.alloc_zeroed(layout);
184            if ptr.cast::<c_void>().is_null() {
185                assert!(!ptr.cast::<c_void>().is_null());
186            } else {
187                alloc.dealloc(ptr, layout);
188            }
189        }
190        Ok(())
191    }
192
193    #[cfg(all(feature = "allocator-memory-limits", target_pointer_width = "64"))]
194    #[test]
195    fn allocator_preserves_zeroed_aligned_reallocations() -> Result<(), Box<dyn Error>> {
196        let allocator = Mimalloc;
197        let alignments = [1, 8, 16, 64, 256];
198
199        for align in alignments {
200            let old_layout = Layout::from_size_align(17, align)?;
201            let ptr = unsafe { allocator.alloc_zeroed(old_layout) };
202            if ptr.is_null() {
203                assert!(!ptr.is_null());
204            } else {
205                assert_eq!((ptr as usize) % align, 0);
206                assert!((0..old_layout.size()).all(|index| unsafe { *ptr.add(index) == 0 }));
207                unsafe { ptr.write_bytes(0x5a, old_layout.size()) };
208
209                let new_size = 33;
210                let ptr = unsafe { allocator.realloc(ptr, old_layout, new_size) };
211                if ptr.is_null() {
212                    assert!(!ptr.is_null());
213                } else {
214                    assert_eq!((ptr as usize) % align, 0);
215                    assert!((0..old_layout.size()).all(|index| unsafe { *ptr.add(index) == 0x5a }));
216
217                    unsafe { allocator.dealloc(ptr, Layout::from_size_align(new_size, align)?) };
218                }
219            }
220        }
221        Ok(())
222    }
223
224    #[test]
225    fn large_chunks_of_memory_can_be_allocated_and_freed() -> Result<(), Box<dyn Error>> {
226        let layout = Layout::from_size_align(2 * 1024 * 1024 * 1024, 8)?;
227        let alloc = Mimalloc;
228
229        unsafe {
230            let ptr = alloc.alloc(layout);
231            assert!(!ptr.cast::<c_void>().is_null());
232            alloc.dealloc(ptr, layout);
233        }
234        Ok(())
235    }
236
237    #[cfg(feature = "allocator-memory-limits")]
238    #[test]
239    fn allocation_stats_report_live_usage() -> Result<(), Box<dyn Error>> {
240        let layout = Layout::from_size_align(4 * 1024, 8)?;
241        let alloc = Mimalloc;
242
243        let before_global = global_allocation_stats_snapshot().allocated;
244        let before_thread = current_thread_allocation_stats().allocated;
245
246        unsafe {
247            let ptr = alloc.alloc(layout);
248            assert!(!ptr.cast::<c_void>().is_null());
249            let during_thread = current_thread_allocation_stats().allocated;
250            assert!(during_thread >= before_thread + layout.size() as i64);
251            alloc.dealloc(ptr, layout);
252        }
253
254        let after_thread = current_thread_allocation_stats().allocated;
255        assert_eq!(after_thread, before_thread);
256
257        let after_global = global_allocation_stats_snapshot().allocated;
258        assert!(after_global >= before_global);
259        Ok(())
260    }
261
262    #[cfg(feature = "allocator-memory-limits")]
263    #[test]
264    fn execution_budget_tracks_requests_in_active_scopes_across_threads(
265    ) -> Result<(), Box<dyn Error>> {
266        let allocator = Mimalloc;
267        let mut outer = TestBudgetUsage::new();
268        let mut inner = TestBudgetUsage::default();
269        let unowned_layout = Layout::from_size_align(11, 8)?;
270        let outer_layout = Layout::from_size_align(13, 8)?;
271        let inner_layout = Layout::from_size_align(19, 64)?;
272        let after_inner_layout = Layout::from_size_align(7, 8)?;
273
274        let unowned = unsafe { allocator.alloc(unowned_layout) };
275        assert!(!unowned.is_null());
276        let (outer_ptr, after_inner_ptr, inner_ptr) = outer.with_scope(|| {
277            let outer_ptr = unsafe { allocator.alloc(outer_layout) };
278            assert!(!outer_ptr.is_null());
279            assert_eq!(current_requested_bytes(), 13);
280
281            let inner_ptr = inner.with_scope(|| unsafe { allocator.alloc_zeroed(inner_layout) });
282            assert!(!inner_ptr.is_null());
283
284            assert_eq!(current_requested_bytes(), 13);
285            assert_eq!(inner.requested_bytes(), 19);
286            assert_eq!((inner_ptr as usize) % 64, 0);
287            assert!((0..19).all(|offset| unsafe { *inner_ptr.add(offset) == 0 }));
288
289            let after_inner_ptr = unsafe { allocator.alloc(after_inner_layout) };
290            assert!(!after_inner_ptr.is_null());
291            assert_eq!(current_requested_bytes(), 20);
292            unsafe { allocator.dealloc(unowned, unowned_layout) };
293            assert_eq!(current_requested_bytes(), 20);
294            (outer_ptr, after_inner_ptr, inner_ptr)
295        });
296
297        let inner_address = inner_ptr as usize;
298        std::thread::spawn(move || unsafe {
299            Mimalloc.dealloc(inner_address as *mut u8, inner_layout);
300        })
301        .join()
302        .expect("cross-thread free");
303        assert_eq!(inner.requested_bytes(), 19);
304
305        unsafe {
306            allocator.dealloc(outer_ptr, outer_layout);
307            allocator.dealloc(after_inner_ptr, after_inner_layout);
308        }
309        assert_eq!(outer.requested_bytes(), 20);
310        Ok(())
311    }
312
313    #[cfg(feature = "allocator-memory-limits")]
314    #[test]
315    fn execution_budget_counts_gross_requests_at_the_exact_boundary() -> Result<(), Box<dyn Error>>
316    {
317        let allocator = Mimalloc;
318        let mut account = TestBudgetUsage::new();
319        let limit = 32_u64;
320        let layout = Layout::from_size_align(limit as usize, 8)?;
321        let extra_layout = Layout::from_size_align(1, 8)?;
322
323        let ptr = account.with_scope(|| {
324            let ptr = unsafe { allocator.alloc(layout) };
325            assert!(!ptr.is_null());
326            assert_eq!(current_requested_bytes(), limit);
327            assert!(current_requested_bytes() <= limit);
328
329            let extra = unsafe { allocator.alloc(extra_layout) };
330            assert!(!extra.is_null());
331            assert_eq!(current_requested_bytes(), limit + 1);
332            assert!(current_requested_bytes() > limit);
333            unsafe { allocator.dealloc(extra, extra_layout) };
334            assert_eq!(current_requested_bytes(), limit + 1);
335            ptr
336        });
337
338        let alias = ptr;
339        unsafe { allocator.dealloc(alias, layout) };
340        assert_eq!(account.requested_bytes(), limit + 1);
341        Ok(())
342    }
343
344    #[cfg(feature = "allocator-memory-limits")]
345    #[test]
346    fn successful_realloc_charges_current_account_and_failure_charges_nothing(
347    ) -> Result<(), Box<dyn Error>> {
348        let allocator = Mimalloc;
349        let mut first = TestBudgetUsage::new();
350        let mut second = TestBudgetUsage::new();
351        let old_layout = Layout::from_size_align(16, 16)?;
352        let new_layout = Layout::from_size_align(64, 16)?;
353
354        let mut ptr = first.with_scope(|| {
355            let ptr = unsafe { allocator.alloc(old_layout) };
356            if ptr.is_null() {
357                assert!(!ptr.is_null());
358            } else {
359                unsafe { ptr.write_bytes(0x5a, old_layout.size()) };
360            }
361            ptr
362        });
363        if ptr.is_null() {
364            assert!(!ptr.is_null());
365        } else {
366            assert_eq!(first.requested_bytes(), 16);
367
368            let live_bytes_before_failure = current_thread_live_bytes();
369            let failed =
370                second.with_scope(|| unsafe { allocator.realloc(ptr, old_layout, usize::MAX) });
371            assert!(failed.is_null());
372            assert_eq!(first.requested_bytes(), 16);
373            assert_eq!(second.requested_bytes(), 0);
374            assert_eq!(current_thread_live_bytes() - live_bytes_before_failure, 0);
375            assert!((0..16).all(|offset| unsafe { *ptr.add(offset) == 0x5a }));
376
377            ptr = second
378                .with_scope(|| unsafe { allocator.realloc(ptr, old_layout, new_layout.size()) });
379            if ptr.is_null() {
380                assert!(!ptr.is_null());
381            } else {
382                assert_eq!(first.requested_bytes(), 16);
383                assert_eq!(second.requested_bytes(), 64);
384                assert_eq!((ptr as usize) % new_layout.align(), 0);
385                assert!((0..16).all(|offset| unsafe { *ptr.add(offset) == 0x5a }));
386
387                unsafe { allocator.dealloc(ptr, new_layout) };
388                assert_eq!(second.requested_bytes(), 64);
389            }
390        }
391        Ok(())
392    }
393
394    #[cfg(feature = "allocator-memory-limits")]
395    #[test]
396    fn injected_native_realloc_failure_is_one_shot_without_accounting_side_effects(
397    ) -> Result<(), Box<dyn Error>> {
398        let allocator = Mimalloc;
399        let mut first = TestBudgetUsage::new();
400        let mut current = TestBudgetUsage::new();
401        let old_layout = Layout::from_size_align(16, 16)?;
402        let new_layout = Layout::from_size_align(64, 16)?;
403        let live_bytes_before = current_thread_live_bytes();
404
405        let ptr = first.with_scope(|| {
406            let ptr = unsafe { allocator.alloc(old_layout) };
407            if ptr.is_null() {
408                assert!(!ptr.is_null());
409            } else {
410                unsafe { ptr.write_bytes(0x5a, old_layout.size()) };
411            }
412            ptr
413        });
414        if ptr.is_null() {
415            assert!(!ptr.is_null());
416        } else {
417            assert_eq!(first.requested_bytes(), old_layout.size() as u64);
418            assert_eq!(current.requested_bytes(), 0);
419
420            let failure = FailNextNativeReallocGuard::arm();
421            let result = current
422                .with_scope(|| unsafe { allocator.realloc(ptr, old_layout, new_layout.size()) });
423            drop(failure);
424            if !result.is_null() {
425                unsafe { allocator.dealloc(result, new_layout) };
426            }
427            assert!(
428                result.is_null(),
429                "the fail-next test hook should force the native null-result path"
430            );
431            assert_eq!(first.requested_bytes(), old_layout.size() as u64);
432            assert_eq!(current.requested_bytes(), 0);
433            assert_eq!(
434                current_thread_live_bytes() - live_bytes_before,
435                i64::try_from(old_layout.size())?
436            );
437            assert!((0..old_layout.size()).all(|offset| unsafe { *ptr.add(offset) == 0x5a }));
438
439            unsafe { allocator.dealloc(ptr, old_layout) };
440
441            let next = current.with_scope(|| {
442                let ptr = unsafe { allocator.alloc(old_layout) };
443                if ptr.is_null() {
444                    assert!(!ptr.is_null());
445                } else {
446                    unsafe { ptr.write_bytes(0x6b, old_layout.size()) };
447                }
448                ptr
449            });
450            if next.is_null() {
451                assert!(!next.is_null());
452            } else {
453                let next = current.with_scope(|| unsafe {
454                    allocator.realloc(next, old_layout, new_layout.size())
455                });
456                if next.is_null() {
457                    assert!(!next.is_null());
458                } else {
459                    assert_eq!(
460                        current.requested_bytes(),
461                        (old_layout.size() + new_layout.size()) as u64
462                    );
463                    assert!(
464                        (0..old_layout.size()).all(|offset| unsafe { *next.add(offset) == 0x6b })
465                    );
466                    unsafe { allocator.dealloc(next, new_layout) };
467                    assert_eq!(
468                        current.requested_bytes(),
469                        (old_layout.size() + new_layout.size()) as u64
470                    );
471                    assert_eq!(current_thread_live_bytes() - live_bytes_before, 0);
472                }
473            }
474        }
475        Ok(())
476    }
477
478    #[cfg(feature = "allocator-memory-limits")]
479    #[test]
480    fn realloc_charges_each_success_to_its_current_execution_scope() -> Result<(), Box<dyn Error>> {
481        let allocator = Mimalloc;
482        let mut first = TestBudgetUsage::new();
483        let mut second = TestBudgetUsage::new();
484        let mut third = TestBudgetUsage::new();
485        let mut layout = Layout::from_size_align(23, 64)?;
486        let mut ptr = first.with_scope(|| {
487            let ptr = unsafe { allocator.alloc(layout) };
488            if ptr.is_null() {
489                assert!(!ptr.is_null());
490            } else {
491                unsafe { ptr.write_bytes(0x5a, layout.size()) };
492            }
493            ptr
494        });
495
496        let transitions: [(Option<usize>, usize, u64, u64, u64); 6] = [
497            (Some(0), 47, 70, 0, 0),
498            (Some(1), 31, 70, 31, 0),
499            (None, 63, 70, 31, 0),
500            (None, 55, 70, 31, 0),
501            (Some(2), 77, 70, 31, 77),
502            (Some(2), 51, 70, 31, 128),
503        ];
504        for (next_owner, new_size, first_total, second_total, third_total) in transitions {
505            let live_bytes_before_realloc = current_thread_live_bytes();
506            if ptr.is_null() {
507                assert!(!ptr.is_null());
508            } else {
509                ptr =
510                    if let Some(next_owner) = next_owner {
511                        match next_owner {
512                            0 => first
513                                .with_scope(|| unsafe { allocator.realloc(ptr, layout, new_size) }),
514                            1 => second
515                                .with_scope(|| unsafe { allocator.realloc(ptr, layout, new_size) }),
516                            _ => third
517                                .with_scope(|| unsafe { allocator.realloc(ptr, layout, new_size) }),
518                        }
519                    } else {
520                        unsafe { allocator.realloc(ptr, layout, new_size) }
521                    };
522                if ptr.is_null() {
523                    assert!(!ptr.is_null());
524                } else {
525                    assert_eq!((ptr as usize) % layout.align(), 0);
526                    assert!((0..23).all(|offset| unsafe { *ptr.add(offset) == 0x5a }));
527                    let expected_live_bytes_delta =
528                        i64::try_from(new_size)? - i64::try_from(layout.size())?;
529                    assert_eq!(
530                        current_thread_live_bytes() - live_bytes_before_realloc,
531                        expected_live_bytes_delta
532                    );
533
534                    layout = Layout::from_size_align(new_size, layout.align())?;
535                    assert_eq!(first.requested_bytes(), first_total);
536                    assert_eq!(second.requested_bytes(), second_total);
537                    assert_eq!(third.requested_bytes(), third_total);
538                }
539            }
540        }
541
542        if ptr.is_null() {
543            assert!(!ptr.is_null());
544        } else {
545            unsafe { allocator.dealloc(ptr, layout) };
546            assert_eq!(third.requested_bytes(), 128);
547        }
548        Ok(())
549    }
550
551    #[cfg(feature = "allocator-memory-limits")]
552    #[test]
553    fn realloc_charges_the_active_account_after_thread_migration() -> Result<(), Box<dyn Error>> {
554        let mut first = TestBudgetUsage::new();
555        let second = TestBudgetUsage::new();
556        let old_layout = Layout::from_size_align(17, 64)?;
557        let new_layout = Layout::from_size_align(257, 64)?;
558        let ptr = first.with_scope(|| {
559            let ptr = unsafe { Mimalloc.alloc(old_layout) };
560            if ptr.is_null() {
561                assert!(!ptr.is_null());
562            } else {
563                unsafe { ptr.write_bytes(0x5a, old_layout.size()) };
564            }
565            ptr
566        });
567        if ptr.is_null() {
568            assert!(!ptr.is_null());
569        } else {
570            let address = ptr as usize;
571            let worker_account = second;
572            let (sender, receiver) = std::sync::mpsc::channel();
573            let worker = std::thread::spawn(move || {
574                let mut worker_account = worker_account;
575                let ptr = address as *mut u8;
576                if ptr.is_null() {
577                    assert!(!ptr.is_null());
578                } else {
579                    let ptr = worker_account.with_scope(|| unsafe {
580                        Mimalloc.realloc(ptr, old_layout, new_layout.size())
581                    });
582                    sender
583                        .send((ptr as usize, worker_account))
584                        .expect("send reallocated pointer");
585                }
586            });
587            worker.join().expect("cross-thread realloc");
588            let (address, second) = receiver.recv().expect("receive reallocated pointer");
589            let ptr = address as *mut u8;
590
591            if ptr.is_null() {
592                assert!(!ptr.is_null());
593            } else {
594                assert_eq!(first.requested_bytes(), old_layout.size() as u64);
595                assert_eq!(second.requested_bytes(), new_layout.size() as u64);
596                assert_eq!((ptr as usize) % new_layout.align(), 0);
597                assert!((0..old_layout.size()).all(|offset| unsafe { *ptr.add(offset) == 0x5a }));
598
599                let address = ptr as usize;
600                let (sender, receiver) = std::sync::mpsc::channel();
601                let freer = std::thread::spawn(move || {
602                    let ptr = address as *mut u8;
603                    if ptr.is_null() {
604                        assert!(!ptr.is_null());
605                    } else {
606                        unsafe { Mimalloc.dealloc(ptr, new_layout) };
607                    }
608                    sender.send(()).expect("send free completion");
609                });
610                receiver.recv().expect("receive free completion");
611                freer.join().expect("cross-thread free");
612                assert_eq!(second.requested_bytes(), new_layout.size() as u64);
613            }
614        }
615        Ok(())
616    }
617
618    #[cfg(feature = "allocator-memory-limits")]
619    #[test]
620    fn native_aligned_realloc_reuses_a_same_bin_shrink() -> Result<(), Box<dyn Error>> {
621        let allocator = Mimalloc;
622        let mut account = TestBudgetUsage::new();
623        let old_layout = Layout::from_size_align(32, 8)?;
624        let ptr = account.with_scope(|| {
625            let ptr = unsafe { allocator.alloc(old_layout) };
626            if ptr.is_null() {
627                assert!(!ptr.is_null());
628            } else {
629                unsafe { ptr.write_bytes(0x5a, old_layout.size()) };
630            }
631            ptr
632        });
633
634        if ptr.is_null() {
635            assert!(!ptr.is_null());
636        } else {
637            // This characterizes vendored mimalloc's same-bin shrink, not GlobalAlloc pointer stability.
638            let original = ptr;
639            let ptr = account.with_scope(|| unsafe { allocator.realloc(ptr, old_layout, 31) });
640            if ptr.is_null() {
641                assert!(!ptr.is_null());
642            } else {
643                assert_eq!(ptr, original);
644                assert_eq!(account.requested_bytes(), 63);
645                assert!((0..31).all(|offset| unsafe { *ptr.add(offset) == 0x5a }));
646
647                unsafe { allocator.dealloc(ptr, Layout::from_size_align(31, 8)?) };
648                assert_eq!(account.requested_bytes(), 63);
649            }
650        }
651        Ok(())
652    }
653
654    #[cfg(feature = "allocator-memory-limits")]
655    #[test]
656    fn native_aligned_realloc_moves_for_small_to_large_growth() -> Result<(), Box<dyn Error>> {
657        let allocator = Mimalloc;
658        let mut account = TestBudgetUsage::new();
659        let old_layout = Layout::from_size_align(17, 16)?;
660        let new_layout = Layout::from_size_align(1024, 16)?;
661        let ptr = account.with_scope(|| {
662            let ptr = unsafe { allocator.alloc(old_layout) };
663            if ptr.is_null() {
664                assert!(!ptr.is_null());
665            } else {
666                unsafe { ptr.write_bytes(0x5a, old_layout.size()) };
667            }
668            ptr
669        });
670        if ptr.is_null() {
671            assert!(!ptr.is_null());
672        } else {
673            let original = ptr;
674            let ptr = account
675                .with_scope(|| unsafe { allocator.realloc(ptr, old_layout, new_layout.size()) });
676            if ptr.is_null() {
677                assert!(!ptr.is_null());
678            } else {
679                assert_ne!(
680                    ptr, original,
681                    "vendored aligned realloc must move when this growth needs a larger native block"
682                );
683                assert_eq!(
684                    account.requested_bytes(),
685                    (old_layout.size() + new_layout.size()) as u64
686                );
687                assert_eq!((ptr as usize) % new_layout.align(), 0);
688                assert!((0..old_layout.size()).all(|index| unsafe { *ptr.add(index) == 0x5a }));
689
690                unsafe { allocator.dealloc(ptr, new_layout) };
691                assert_eq!(
692                    account.requested_bytes(),
693                    (old_layout.size() + new_layout.size()) as u64
694                );
695            }
696        }
697        Ok(())
698    }
699
700    #[cfg(feature = "allocator-memory-limits")]
701    #[test]
702    fn unowned_realloc_does_not_change_the_execution_account() -> Result<(), Box<dyn Error>> {
703        let allocator = Mimalloc;
704        let mut account = TestBudgetUsage::new();
705        let old_layout = Layout::from_size_align(16, 16)?;
706        let new_layout = Layout::from_size_align(64, 16)?;
707
708        let ptr = account.with_scope(|| {
709            let ptr = unsafe { allocator.alloc(old_layout) };
710            assert!(!ptr.is_null());
711            ptr
712        });
713        assert_eq!(account.requested_bytes(), 16);
714
715        let ptr = unsafe { allocator.realloc(ptr, old_layout, new_layout.size()) };
716        assert!(!ptr.is_null());
717        assert_eq!(account.requested_bytes(), 16);
718        assert_eq!((ptr as usize) % new_layout.align(), 0);
719        unsafe { allocator.dealloc(ptr, new_layout) };
720        assert_eq!(account.requested_bytes(), 16);
721        Ok(())
722    }
723
724    #[cfg(feature = "allocator-memory-limits")]
725    #[test]
726    fn execution_budget_counts_requested_bytes_after_blocks_are_freed() -> Result<(), Box<dyn Error>>
727    {
728        let allocator = Mimalloc;
729        let mut account = TestBudgetUsage::new();
730        let layout = Layout::from_size_align(64, 8)?;
731
732        account.with_scope(|| {
733            let first = unsafe { allocator.alloc(layout) };
734            assert!(!first.is_null());
735            unsafe { allocator.dealloc(first, layout) };
736
737            let second = unsafe { allocator.alloc(layout) };
738            assert!(!second.is_null());
739            unsafe { allocator.dealloc(second, layout) };
740        });
741
742        assert_eq!(account.requested_bytes(), 128);
743        Ok(())
744    }
745
746    #[cfg(feature = "allocator-memory-limits")]
747    #[test]
748    fn execution_budget_counts_zeroed_allocations_after_blocks_are_freed(
749    ) -> Result<(), Box<dyn Error>> {
750        let allocator = Mimalloc;
751        let mut account = TestBudgetUsage::new();
752        let layout = Layout::from_size_align(64, 8)?;
753
754        account.with_scope(|| {
755            let first = unsafe { allocator.alloc_zeroed(layout) };
756            assert!(!first.is_null());
757            assert!((0..layout.size()).all(|index| unsafe { *first.add(index) == 0 }));
758            unsafe { allocator.dealloc(first, layout) };
759
760            let second = unsafe { allocator.alloc_zeroed(layout) };
761            assert!(!second.is_null());
762            unsafe { allocator.dealloc(second, layout) };
763        });
764
765        assert_eq!(account.requested_bytes(), 128);
766        Ok(())
767    }
768
769    #[cfg(feature = "allocator-memory-limits")]
770    #[test]
771    fn execution_budget_realloc_counts_full_new_size_only_after_success(
772    ) -> Result<(), Box<dyn Error>> {
773        let allocator = Mimalloc;
774        let mut account = TestBudgetUsage::new();
775        let old_layout = Layout::from_size_align(16, 16)?;
776        let new_layout = Layout::from_size_align(64, 16)?;
777        let ptr = account.with_scope(|| unsafe { allocator.alloc(old_layout) });
778        assert!(!ptr.is_null());
779        assert_eq!(account.requested_bytes(), 16);
780
781        let failed = account.with_scope(|| {
782            let _failure = FailNextNativeReallocGuard::arm();
783            unsafe { allocator.realloc(ptr, old_layout, new_layout.size()) }
784        });
785        assert!(failed.is_null());
786        assert_eq!(account.requested_bytes(), 16);
787
788        let resized =
789            account.with_scope(|| unsafe { allocator.realloc(ptr, old_layout, new_layout.size()) });
790        assert!(!resized.is_null());
791        assert_eq!(account.requested_bytes(), 80);
792        unsafe { allocator.dealloc(resized, new_layout) };
793        assert_eq!(account.requested_bytes(), 80);
794        Ok(())
795    }
796
797    #[cfg(feature = "allocator-memory-limits")]
798    #[test]
799    fn execution_budget_survives_cross_thread_free_and_account_migration(
800    ) -> Result<(), Box<dyn Error>> {
801        let mut account = TestBudgetUsage::new();
802        let layout = Layout::from_size_align(64, 8)?;
803        let first_address = account.with_scope(|| unsafe { Mimalloc.alloc(layout) }) as usize;
804        assert_ne!(first_address, 0);
805
806        let (account, second_address) = std::thread::spawn(move || {
807            let mut account = account;
808            unsafe { Mimalloc.dealloc(first_address as *mut u8, layout) };
809            let second = account.with_scope(|| unsafe { Mimalloc.alloc(layout) });
810            assert!(!second.is_null());
811            (account, second as usize)
812        })
813        .join()
814        .expect("allocation account migrates to another thread");
815
816        assert_eq!(account.requested_bytes(), 128);
817        unsafe { Mimalloc.dealloc(second_address as *mut u8, layout) };
818        assert_eq!(account.requested_bytes(), 128);
819        Ok(())
820    }
821
822    #[cfg(feature = "allocator-memory-limits")]
823    #[test]
824    fn execution_budget_scopes_restore_parent_and_exclude_unowned_allocations(
825    ) -> Result<(), Box<dyn Error>> {
826        let allocator = Mimalloc;
827        let mut outer = TestBudgetUsage::new();
828        let mut inner = TestBudgetUsage::new();
829        let layout = Layout::from_size_align(8, 8)?;
830
831        outer.with_scope(|| {
832            let outer_ptr = unsafe { allocator.alloc(layout) };
833            assert!(!outer_ptr.is_null());
834
835            crate::limits::with_unowned_memory_budget_scope(|| {
836                let unowned = unsafe { allocator.alloc(layout) };
837                assert!(!unowned.is_null());
838                unsafe { allocator.dealloc(unowned, layout) };
839            });
840
841            let inner_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
842                inner.with_scope(|| {
843                    let inner_ptr = unsafe { allocator.alloc(layout) };
844                    assert!(!inner_ptr.is_null());
845                    unsafe { allocator.dealloc(inner_ptr, layout) };
846                    panic!("inner scope unwind");
847                });
848            }));
849            assert!(inner_result.is_err());
850            assert_eq!(inner.requested_bytes(), 8);
851            assert_eq!(current_requested_bytes(), 8);
852
853            let after_unwind = unsafe { allocator.alloc(layout) };
854            assert!(!after_unwind.is_null());
855            assert_eq!(current_requested_bytes(), 16);
856            unsafe {
857                allocator.dealloc(outer_ptr, layout);
858                allocator.dealloc(after_unwind, layout);
859            }
860            assert_eq!(current_requested_bytes(), 16);
861        });
862
863        assert_eq!(outer.requested_bytes(), 16);
864        assert_eq!(inner.requested_bytes(), 8);
865        Ok(())
866    }
867
868    #[cfg(feature = "allocator-memory-limits")]
869    #[test]
870    fn execution_budget_scope_restores_nested_accounts_after_unwind() -> Result<(), Box<dyn Error>>
871    {
872        let allocator = Mimalloc;
873        let mut outer = TestBudgetUsage::new();
874        let mut inner = TestBudgetUsage::new();
875        let layout = Layout::from_size_align(8, 8)?;
876
877        let outer_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
878            outer.with_scope(|| {
879                let outer_ptr = unsafe { allocator.alloc(layout) };
880                assert!(!outer_ptr.is_null());
881                assert_eq!(current_requested_bytes(), 8);
882
883                let inner_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
884                    inner.with_scope(|| {
885                        let inner_ptr = unsafe { allocator.alloc(layout) };
886                        assert!(!inner_ptr.is_null());
887                        assert_eq!(current_requested_bytes(), 8);
888                        unsafe { allocator.dealloc(inner_ptr, layout) };
889                        panic!("inner scope unwind");
890                    });
891                }));
892                assert!(inner_result.is_err());
893                assert_eq!(inner.requested_bytes(), 8);
894                assert_eq!(current_requested_bytes(), 8);
895                unsafe { allocator.dealloc(outer_ptr, layout) };
896                assert_eq!(current_requested_bytes(), 8);
897                panic!("outer scope unwind");
898            });
899        }));
900
901        assert!(outer_result.is_err());
902        assert_eq!(outer.requested_bytes(), 8);
903        assert_eq!(inner.requested_bytes(), 8);
904        let unowned = unsafe { allocator.alloc(layout) };
905        assert!(!unowned.is_null());
906        assert_eq!(outer.requested_bytes(), 8);
907        assert_eq!(inner.requested_bytes(), 8);
908        unsafe { allocator.dealloc(unowned, layout) };
909        Ok(())
910    }
911}