Files
regorus/mimalloc/mimalloc-sys/src/lib.rs
Anand Krishnamoorthi fd59bb5a91 feat(memory): Allocator-backed global memory limits (#544)
Policy evaluation at scale needs to be able to set memory limits
so that a bad policy does not hog memory or to ensure that
policy evaluation itself does not use too much memory which could
cause other components to suffer.

This PR introduces capability to set and enforce global memory limits.
It also lays the groundwork for enabling per evaluation limits in future.

Once a global memory limit is set, Regorus maintains per thread counters
to track memory activity (allocation, deallocation) of a thread.
These counters are periodically flushed to global memory counters.
Per thread counters avoid the contention that updating global counters
on each alloc/free would cause.

Policy evaluation periodically checks these counters and raises errors
if allocated memory has exceeded the configured limit.

Currently memory limit capability is exposed only to FFI and C#.

Also update mimalloc to v2.2.6

Signed-off-by: Anand Krishnamoorthi <anakrish@microsoft.com>
2026-01-24 07:08:54 +05:30

51 lines
1.7 KiB
Rust

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
use core::ffi::c_void;
pub const MI_ALIGNMENT_MAX: usize = 1024 * 1024; // 1 MiB
// Define core functions from mimalloc needed for the allocator
extern "C" {
/// Allocate `size` bytes aligned by `alignment`.
/// Returns a pointer to the allocated memory, or null if out of memory. The returned pointer is aligned by `alignment`.
pub fn mi_malloc_aligned(size: usize, alignment: usize) -> *mut c_void;
pub fn mi_zalloc_aligned(size: usize, alignment: usize) -> *mut c_void;
/// Free previously allocated memory.
/// The pointer `p` must have been allocated before (or be nullptr).
pub fn mi_free(p: *mut c_void);
pub fn mi_realloc_aligned(p: *mut c_void, newsize: usize, alignment: usize) -> *mut c_void;
/// Reset allocator statistics.
pub fn mi_stats_reset();
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn memory_can_be_allocated_and_freed() {
let ptr = unsafe { mi_malloc_aligned(8, 8) }.cast::<u8>();
assert!(!ptr.cast::<c_void>().is_null());
unsafe { mi_free(ptr.cast::<c_void>()) };
}
#[test]
fn memory_can_be_allocated_zeroed_and_freed() {
let ptr = unsafe { mi_zalloc_aligned(8, 8) }.cast::<u8>();
assert!(!ptr.cast::<c_void>().is_null());
unsafe { mi_free(ptr.cast::<c_void>()) };
}
#[test]
fn memory_can_be_reallocated_and_freed() {
let ptr = unsafe { mi_malloc_aligned(8, 8) }.cast::<u8>();
assert!(!ptr.cast::<c_void>().is_null());
let realloc_ptr = unsafe { mi_realloc_aligned(ptr.cast::<c_void>(), 8, 8) }.cast::<u8>();
assert!(!realloc_ptr.cast::<c_void>().is_null());
unsafe { mi_free(ptr.cast::<c_void>()) };
}
}