#![cfg_attr(target_os = "none", no_std)]
#[cfg(not(target_os = "none"))]
use log::info;
#[cfg(not(target_os = "none"))]
use once_cell::sync::Lazy;
use core::alloc::{GlobalAlloc, Layout};
use core::sync::atomic::{AtomicU8, Ordering};
#[cfg(not(target_os = "none"))]
use core::sync::atomic::AtomicBool;
#[cfg(not(target_os = "none"))]
use std::alloc;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AllocatorType {
MimallocSecure,
Mimalloc,
EmbeddedHeap,
System,
}
#[derive(Debug, Clone)]
pub struct AllocatorInfo {
pub allocator_type: AllocatorType,
#[cfg(not(target_os = "none"))]
pub reason: String,
#[cfg(target_os = "none")]
pub reason: &'static str,
pub system_info: SystemInfo,
}
#[derive(Debug, Clone)]
pub struct SystemInfo {
#[cfg(not(target_os = "none"))]
pub os_type: String,
#[cfg(target_os = "none")]
pub os_type: &'static str,
pub cpu_cores: usize,
pub total_memory_bytes: u64,
pub is_debug: bool,
pub is_wasm: bool,
#[cfg(not(target_os = "none"))]
pub target_arch: String,
#[cfg(target_os = "none")]
pub target_arch: &'static str,
}
#[cfg(not(target_os = "none"))]
pub fn format_memory_size(bytes: u64) -> String {
use std::format;
if bytes == 0 {
return "0B".to_string();
}
const UNITS: &[&str] = &["B", "KB", "MB", "GB", "TB", "PB"];
let unit_index = if bytes >= (1u64 << 50) {
5
}
else if bytes >= (1u64 << 40) {
4
}
else if bytes >= (1u64 << 30) {
3
}
else if bytes >= (1u64 << 20) {
2
}
else if bytes >= (1u64 << 10) {
1
}
else {
0
};
if unit_index == 0 {
format!("{}B", bytes)
} else {
let shift = unit_index * 10; let value = bytes >> shift;
let remainder = bytes & ((1u64 << shift) - 1);
if remainder == 0 {
format!("{}{}", value, UNITS[unit_index])
} else {
let fraction = (remainder * 10) >> shift;
if fraction == 0 {
format!("{}{}", value, UNITS[unit_index])
} else {
format!("{}.{}{}", value, fraction, UNITS[unit_index])
}
}
}
}
#[cfg(target_os = "none")]
pub fn format_memory_size(bytes: u64) -> &'static str {
if bytes == 0 {
"0B"
} else if bytes < 1024 {
"<1KB"
} else if bytes < (1024 * 1024) {
"~KB"
} else if bytes < (1024 * 1024 * 1024) {
"~MB"
} else {
"~GB"
}
}
const fn is_embedded_target() -> bool {
cfg!(target_os = "none")
}
const fn can_use_mimalloc() -> bool {
cfg!(all(
feature = "_mimalloc",
any(target_os = "windows", target_os = "macos", target_os = "linux"),
not(target_arch = "wasm32"),
not(debug_assertions)
))
}
const fn can_use_mimalloc_secure() -> bool {
cfg!(all(
feature = "_mimalloc_secure",
any(target_os = "windows", target_os = "macos", target_os = "linux"),
not(target_arch = "wasm32"),
not(debug_assertions)
))
}
static RUNTIME_ALLOCATOR_ID: AtomicU8 = AtomicU8::new(0);
#[cfg(not(target_os = "none"))]
static ALLOCATOR_LOGGED: AtomicBool = AtomicBool::new(false);
#[cfg(not(target_os = "none"))]
static LOG_FLUSHED: AtomicBool = AtomicBool::new(false);
const fn get_compile_time_allocator() -> Option<u8> {
if is_embedded_target() {
return Some(4); }
if cfg!(target_arch = "wasm32") {
return Some(1); }
if cfg!(debug_assertions) {
return Some(1); }
if cfg!(target_os = "android") {
return Some(1); }
if cfg!(target_os = "ios") {
return Some(1); }
if cfg!(any(target_os = "freebsd", target_os = "netbsd", target_os = "openbsd")) {
return Some(1); }
if cfg!(any(target_os = "solaris", target_os = "illumos")) {
return Some(1); }
None }
fn select_allocator_by_hardware() -> u8 {
if let Some(allocator_id) = get_compile_time_allocator() {
return allocator_id;
}
let cpu_cores = get_cpu_cores_safe();
if cpu_cores >= 2 && can_use_mimalloc_secure() {
return 5; }
if cpu_cores >= 2 && can_use_mimalloc() {
return 2; }
1 }
fn get_cpu_cores_safe() -> usize {
#[cfg(unix)]
{
unsafe {
let cores = libc::sysconf(libc::_SC_NPROCESSORS_ONLN);
if cores > 0 {
cores as usize
} else {
1
}
}
}
#[cfg(windows)]
{
use winapi::um::sysinfoapi::{GetSystemInfo, SYSTEM_INFO};
unsafe {
let mut sysinfo: SYSTEM_INFO = std::mem::zeroed();
GetSystemInfo(&mut sysinfo);
sysinfo.dwNumberOfProcessors as usize
}
}
#[cfg(not(any(unix, windows)))]
{
4
}
}
#[cfg(target_os = "none")]
mod embedded_heap_config {
use embedded_alloc::Heap;
#[cfg(not(target_os = "none"))]
use once_cell::sync::Lazy;
#[cfg(target_arch = "avr")]
pub const HEAP_SIZE: usize = 512;
#[cfg(target_arch = "msp430")]
pub const HEAP_SIZE: usize = 256;
#[cfg(target_arch = "riscv32")]
pub const HEAP_SIZE: usize = 2048;
#[cfg(target_arch = "riscv64")]
pub const HEAP_SIZE: usize = 4096;
#[cfg(target_arch = "xtensa")]
pub const HEAP_SIZE: usize = 4096;
#[cfg(target_arch = "arm")]
pub const HEAP_SIZE: usize = 1024;
#[cfg(not(any(
target_arch = "avr",
target_arch = "msp430",
target_arch = "riscv32",
target_arch = "riscv64",
target_arch = "xtensa",
target_arch = "arm"
)))]
pub const HEAP_SIZE: usize = 2048;
pub static mut HEAP_MEMORY: [u8; HEAP_SIZE] = [0; HEAP_SIZE];
#[cfg(not(target_os = "none"))]
pub static EMBEDDED_HEAP: Lazy<Heap> = Lazy::new(|| unsafe { Heap::new(&mut HEAP_MEMORY[..]) });
#[cfg(target_os = "none")]
static mut EMBEDDED_HEAP_INSTANCE: Option<Heap> = None;
#[cfg(target_os = "none")]
pub fn get_embedded_heap() -> &'static Heap {
unsafe {
if EMBEDDED_HEAP_INSTANCE.is_none() {
let heap = Heap::empty();
heap.init(HEAP_MEMORY.as_mut_ptr() as usize, HEAP_SIZE);
EMBEDDED_HEAP_INSTANCE = Some(heap);
}
EMBEDDED_HEAP_INSTANCE.as_ref().unwrap()
}
}
}
pub struct RuntimeAllocator;
impl RuntimeAllocator {
#[inline]
fn get_allocator_id() -> u8 {
let current_id = RUNTIME_ALLOCATOR_ID.load(Ordering::Acquire);
if unlikely(current_id == 0) {
let selected_id = select_allocator_by_hardware();
RUNTIME_ALLOCATOR_ID.store(selected_id, Ordering::Release);
Self::log_allocator_selection(selected_id);
selected_id
} else {
current_id
}
}
#[cold]
#[cfg(not(target_os = "none"))]
fn log_allocator_selection(allocator_id: u8) {
if ALLOCATOR_LOGGED
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
.is_ok()
{
let (name, reason) = Self::get_allocator_log_info(allocator_id);
record_allocator_selection(name, &reason);
}
}
#[cold]
#[cfg(target_os = "none")]
fn log_allocator_selection(_allocator_id: u8) {
}
#[cfg(not(target_os = "none"))]
fn get_allocator_log_info(allocator_id: u8) -> (&'static str, String) {
match allocator_id {
5 => {
let system_info = collect_system_info();
("mimalloc-secure", format!(
"security-hardened choice - runtime detected ({} cores, {} total RAM)",
system_info.cpu_cores,
format_memory_size(system_info.total_memory_bytes)
))
},
2 => {
let system_info = collect_system_info();
("mimalloc", format!(
"optimal performance choice - runtime detected ({} cores, {} total RAM)",
system_info.cpu_cores,
format_memory_size(system_info.total_memory_bytes)
))
},
4 => {
let system_info = collect_system_info();
("embedded-alloc", format!(
"embedded platform - compile-time selected ({} total RAM)",
format_memory_size(system_info.total_memory_bytes)
))
},
_ => {
if cfg!(debug_assertions) {
let system_info = collect_system_info();
("system", format!(
"debug build - compile-time selected ({} cores, {} total RAM)",
system_info.cpu_cores,
format_memory_size(system_info.total_memory_bytes)
))
} else if cfg!(target_arch = "wasm32") {
let system_info = collect_system_info();
("system", format!(
"WASM environment - compile-time selected ({} total RAM)",
format_memory_size(system_info.total_memory_bytes)
))
} else if cfg!(target_os = "android") {
let system_info = collect_system_info();
("system", format!(
"Android Scudo allocator - compile-time selected (security-first policy) ({} cores, {} total RAM)",
system_info.cpu_cores,
format_memory_size(system_info.total_memory_bytes)
))
} else if cfg!(target_os = "ios") {
let system_info = collect_system_info();
("system", format!(
"iOS libmalloc allocator - compile-time selected (Apple optimized) ({} cores, {} total RAM)",
system_info.cpu_cores,
format_memory_size(system_info.total_memory_bytes)
))
} else if cfg!(any(target_os = "freebsd", target_os = "netbsd")) {
let system_info = collect_system_info();
("system", format!(
"BSD native jemalloc - compile-time selected (platform optimized) ({} cores, {} total RAM)",
system_info.cpu_cores,
format_memory_size(system_info.total_memory_bytes)
))
} else if cfg!(target_os = "openbsd") {
let system_info = collect_system_info();
("system", format!(
"OpenBSD security-hardened allocator - compile-time selected ({} cores, {} total RAM)",
system_info.cpu_cores,
format_memory_size(system_info.total_memory_bytes)
))
} else if cfg!(any(target_os = "solaris", target_os = "illumos")) {
let system_info = collect_system_info();
("system", format!(
"Solaris libumem allocator - compile-time selected (enterprise grade) ({} cores, {} total RAM)",
system_info.cpu_cores,
format_memory_size(system_info.total_memory_bytes)
))
} else {
let system_info = collect_system_info();
("system", format!(
"runtime fallback - single-core or mimalloc unavailable ({} cores, {} total RAM)",
system_info.cpu_cores,
format_memory_size(system_info.total_memory_bytes)
))
}
},
}
}
}
#[inline(always)]
fn unlikely(b: bool) -> bool {
#[cold]
fn cold() {}
if b {
cold();
}
b
}
unsafe impl GlobalAlloc for RuntimeAllocator {
#[inline]
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
match Self::get_allocator_id() {
#[cfg(all(
feature = "_mimalloc_secure",
not(target_arch = "wasm32"),
not(debug_assertions),
not(target_os = "none")
))]
5 => {
use mimalloc::MiMalloc;
MiMalloc.alloc(layout)
}
#[cfg(all(
feature = "_mimalloc",
not(target_arch = "wasm32"),
not(debug_assertions),
not(target_os = "none")
))]
2 => {
use mimalloc::MiMalloc;
MiMalloc.alloc(layout)
}
#[cfg(all(
feature = "_embedded",
target_os = "none"
))]
4 => {
#[cfg(not(target_os = "none"))]
{
embedded_heap_config::EMBEDDED_HEAP.alloc(layout)
}
#[cfg(target_os = "none")]
{
embedded_heap_config::get_embedded_heap().alloc(layout)
}
}
#[cfg(not(target_os = "none"))]
_ => alloc::System.alloc(layout),
#[cfg(target_os = "none")]
_ => core::ptr::null_mut(),
}
}
#[inline]
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
match Self::get_allocator_id() {
#[cfg(all(
feature = "_mimalloc_secure",
not(target_arch = "wasm32"),
not(debug_assertions),
not(target_os = "none")
))]
5 => {
use mimalloc::MiMalloc;
MiMalloc.dealloc(ptr, layout)
}
#[cfg(all(
feature = "_mimalloc",
not(target_arch = "wasm32"),
not(debug_assertions),
not(target_os = "none")
))]
2 => {
use mimalloc::MiMalloc;
MiMalloc.dealloc(ptr, layout)
}
#[cfg(all(
feature = "_embedded",
target_os = "none"
))]
4 => {
#[cfg(not(target_os = "none"))]
{
embedded_heap_config::EMBEDDED_HEAP.dealloc(ptr, layout)
}
#[cfg(target_os = "none")]
{
embedded_heap_config::get_embedded_heap().dealloc(ptr, layout)
}
}
#[cfg(not(target_os = "none"))]
_ => alloc::System.dealloc(ptr, layout),
#[cfg(target_os = "none")]
_ => {},
}
}
}
#[global_allocator]
static GLOBAL: RuntimeAllocator = RuntimeAllocator;
#[cfg(not(target_os = "none"))]
static PENDING_LOG_MESSAGE: Lazy<std::sync::Mutex<Option<String>>> =
Lazy::new(|| std::sync::Mutex::new(None));
#[cfg(not(target_os = "none"))]
fn record_allocator_selection(allocator_name: &str, reason: &str) {
let message = format!("Auto-allocator: {} selected - {}", allocator_name, reason);
#[cfg(unix)]
{
let stderr_message = format!("[INFO] {}\n", message);
unsafe {
libc::write(
2,
stderr_message.as_ptr() as *const libc::c_void,
stderr_message.len(),
);
}
}
if let Ok(mut pending) = PENDING_LOG_MESSAGE.lock() {
*pending = Some(message);
}
}
#[cfg(not(target_os = "none"))]
fn try_flush_pending_log() {
if !LOG_FLUSHED.load(Ordering::Relaxed) {
if let Ok(mut pending) = PENDING_LOG_MESSAGE.lock() {
if let Some(message) = pending.take() {
let _ = std::panic::catch_unwind(|| {
info!("{}", message);
});
LOG_FLUSHED.store(true, Ordering::Relaxed);
}
}
}
}
#[cfg(not(target_os = "none"))]
fn smart_try_flush_log() {
if LOG_FLUSHED.load(Ordering::Relaxed) {
return;
}
try_flush_pending_log();
}
#[cfg(not(target_os = "none"))]
fn collect_system_info() -> SystemInfo {
let total_memory = get_total_memory_safe();
SystemInfo {
os_type: std::env::consts::OS.to_string(),
cpu_cores: std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(1),
total_memory_bytes: total_memory,
is_debug: cfg!(debug_assertions),
is_wasm: cfg!(target_arch = "wasm32"),
target_arch: std::env::consts::ARCH.to_string(),
}
}
#[cfg(target_os = "none")]
fn collect_system_info() -> SystemInfo {
let total_memory = get_total_memory_safe();
SystemInfo {
os_type: "embedded",
cpu_cores: 1, total_memory_bytes: total_memory,
is_debug: cfg!(debug_assertions),
is_wasm: false,
target_arch: {
#[cfg(target_arch = "riscv32")]
{ "riscv32" }
#[cfg(target_arch = "riscv64")]
{ "riscv64" }
#[cfg(target_arch = "arm")]
{ "arm" }
#[cfg(target_arch = "avr")]
{ "avr" }
#[cfg(target_arch = "msp430")]
{ "msp430" }
#[cfg(target_arch = "xtensa")]
{ "xtensa" }
#[cfg(not(any(
target_arch = "riscv32",
target_arch = "riscv64",
target_arch = "arm",
target_arch = "avr",
target_arch = "msp430",
target_arch = "xtensa"
)))]
{ "unknown" }
},
}
}
#[allow(unreachable_code)]
fn get_total_memory_safe() -> u64 {
#[cfg(target_arch = "wasm32")]
{
use core::arch::wasm32;
let pages = wasm32::memory_size(0); let total_bytes = (pages as u64) * 65536;
return total_bytes;
}
#[cfg(target_os = "macos")]
{
unsafe {
let mut total_size: u64 = 0;
let mut mib = [libc::CTL_HW, libc::HW_MEMSIZE];
let mut len = std::mem::size_of::<u64>();
if libc::sysctl(
mib.as_mut_ptr(),
2,
&mut total_size as *mut _ as *mut libc::c_void,
&mut len,
std::ptr::null_mut(),
0,
) == 0
{
return total_size;
} else {
return 16u64 << 30; }
}
}
#[cfg(all(target_os = "linux", not(target_arch = "wasm32")))]
{
unsafe {
let mut info: libc::sysinfo = std::mem::zeroed();
if libc::sysinfo(&mut info) == 0 {
let total = info.totalram as u64 * info.mem_unit as u64;
return total;
}
}
}
#[cfg(target_os = "windows")]
{
use std::mem;
use winapi::um::sysinfoapi::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
unsafe {
let mut mem_status: MEMORYSTATUSEX = mem::zeroed();
mem_status.dwLength = mem::size_of::<MEMORYSTATUSEX>() as u32;
if GlobalMemoryStatusEx(&mut mem_status) != 0 {
return mem_status.ullTotalPhys;
}
}
}
#[cfg(target_arch = "avr")]
{
return 2u64 << 10; }
#[cfg(target_arch = "msp430")]
{
return 1u64 << 10; }
#[cfg(target_arch = "riscv32")]
{
return 32u64 << 10; }
#[cfg(target_arch = "riscv64")]
{
return 128u64 << 10; }
#[cfg(target_arch = "xtensa")]
{
return 256u64 << 10; }
#[cfg(all(target_arch = "arm", target_os = "none"))]
{
return 16u64 << 10; }
2u64 << 30
}
#[cfg(target_os = "none")]
fn smart_try_flush_log() {
}
#[cfg(not(target_os = "none"))]
static ALLOCATOR_INFO: Lazy<AllocatorInfo> = Lazy::new(|| {
let system_info = collect_system_info();
let allocator_id = RUNTIME_ALLOCATOR_ID.load(Ordering::Acquire);
let final_allocator_id = if allocator_id == 0 {
RuntimeAllocator::get_allocator_id()
} else {
allocator_id
};
let (_, mut reason) = get_allocator_selection_result(&system_info);
let allocator_type = match final_allocator_id {
5 => AllocatorType::MimallocSecure,
2 => AllocatorType::Mimalloc,
4 => AllocatorType::EmbeddedHeap,
_ => AllocatorType::System,
};
let hardware_info = if reason.contains('(') && reason.contains(')') {
reason
.split_once('(')
.and_then(|(_prefix, suffix)| suffix.split_once(')').map(|(info, _)| info))
.unwrap_or("")
} else {
""
};
reason = match final_allocator_id {
5 => format!(
"mimalloc-secure selected by runtime hardware analysis ({})",
hardware_info
),
2 => format!(
"mimalloc selected by runtime hardware analysis ({})",
hardware_info
),
4 => {
reason
},
_ => {
reason
},
};
AllocatorInfo {
allocator_type,
reason,
system_info,
}
});
#[cfg(target_os = "none")]
static mut EMBEDDED_ALLOCATOR_INFO: Option<AllocatorInfo> = None;
#[cfg(not(target_os = "none"))]
fn ensure_allocator_info_ready() {
let _ = std::panic::catch_unwind(|| {
Lazy::force(&ALLOCATOR_INFO);
});
}
#[cfg(target_os = "none")]
fn ensure_allocator_info_ready() {
unsafe {
if EMBEDDED_ALLOCATOR_INFO.is_none() {
let system_info = collect_system_info();
EMBEDDED_ALLOCATOR_INFO = Some(AllocatorInfo {
allocator_type: AllocatorType::EmbeddedHeap,
reason: "embedded-alloc selected for no_std environment",
system_info,
});
}
}
}
#[cfg(not(target_os = "none"))]
pub fn get_allocator_info() -> &'static AllocatorInfo {
smart_try_flush_log();
ensure_allocator_info_ready();
&ALLOCATOR_INFO
}
#[cfg(target_os = "none")]
pub fn get_allocator_info() -> &'static AllocatorInfo {
ensure_allocator_info_ready();
unsafe { EMBEDDED_ALLOCATOR_INFO.as_ref().unwrap() }
}
pub fn get_allocator_type() -> AllocatorType {
smart_try_flush_log();
ensure_allocator_info_ready();
get_allocator_info().allocator_type
}
#[cfg(not(target_os = "none"))]
fn get_allocator_selection_result(system_info: &SystemInfo) -> (AllocatorType, String) {
let total_mem = format_memory_size(system_info.total_memory_bytes);
if system_info.is_wasm {
(
AllocatorType::System,
format!("system allocator - WASM environment ({} total RAM)", total_mem),
)
} else if system_info.is_debug {
(
AllocatorType::System,
format!(
"system allocator - debug build ({} cores, {} total RAM)",
system_info.cpu_cores, total_mem
),
)
} else if is_embedded_target() {
(
AllocatorType::EmbeddedHeap,
format!("embedded-alloc allocator - embedded environment ({} total RAM)", total_mem),
)
} else if system_info.os_type == "android" {
(
AllocatorType::System,
format!(
"Android platform - Scudo allocator (security-first, use-after-free protection) ({} cores, {} total RAM)",
system_info.cpu_cores, total_mem
),
)
} else if system_info.os_type == "ios" {
(
AllocatorType::System,
format!(
"iOS platform - libmalloc allocator (Apple-optimized, memory pressure handling) ({} cores, {} total RAM)",
system_info.cpu_cores, total_mem
),
)
} else if system_info.os_type == "freebsd" || system_info.os_type == "netbsd" {
(
AllocatorType::System,
format!(
"BSD platform - native jemalloc (highly optimized, deep system integration) ({} cores, {} total RAM)",
system_info.cpu_cores, total_mem
),
)
} else if system_info.os_type == "openbsd" {
(
AllocatorType::System,
format!(
"OpenBSD platform - security-hardened allocator (exploit mitigation, aggressive hardening) ({} cores, {} total RAM)",
system_info.cpu_cores, total_mem
),
)
} else if system_info.os_type == "solaris" || system_info.os_type == "illumos" {
(
AllocatorType::System,
format!(
"Solaris platform - libumem allocator (NUMA-aware, enterprise-grade performance) ({} cores, {} total RAM)",
system_info.cpu_cores, total_mem
),
)
} else if system_info.cpu_cores >= 2 {
(
AllocatorType::Mimalloc,
format!(
"mimalloc allocator - high-performance multi-threaded environment ({} cores, {} total RAM)",
system_info.cpu_cores, total_mem
),
)
} else {
(
AllocatorType::System,
format!(
"system allocator - low-performance environment ({} cores, {} total RAM)",
system_info.cpu_cores, total_mem
),
)
}
}
#[cfg(target_os = "none")]
fn get_allocator_selection_result(_system_info: &SystemInfo) -> (AllocatorType, &'static str) {
(AllocatorType::EmbeddedHeap, "embedded-alloc selected for no_std environment")
}
#[cfg(not(target_os = "none"))]
pub fn get_recommended_allocator() -> (AllocatorType, String) {
smart_try_flush_log();
let system_info = collect_system_info();
get_allocator_selection_result(&system_info)
}
#[cfg(target_os = "none")]
pub fn get_recommended_allocator() -> (AllocatorType, &'static str) {
let system_info = collect_system_info();
get_allocator_selection_result(&system_info)
}
#[cfg(not(target_os = "none"))]
pub fn check_allocator_optimization() -> (bool, Option<String>) {
smart_try_flush_log();
let current = get_allocator_type();
let (recommended, reason) = get_recommended_allocator();
if current == recommended {
(true, None)
} else {
let suggestion = format!(
"Current: {:?}, Recommended: {:?} ({})",
current, recommended, reason
);
(false, Some(suggestion))
}
}
#[cfg(target_os = "none")]
pub fn check_allocator_optimization() -> (bool, Option<&'static str>) {
(true, None)
}
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::*;
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen(start)]
pub fn wasm_auto_init() {
ensure_allocator_info_ready();
}