Files
ladybird/Libraries/RustAllocator.rs
Andreas Kling b23aa38546 AK: Adopt mimalloc v2 as main allocator
Use mimalloc for Ladybird-owned allocations without overriding malloc().
Route kmalloc(), kcalloc(), krealloc(), and kfree() through mimalloc,
and put the embedded Rust crates on the same allocator via a shared
shim in AK/kmalloc.cpp.

This also lets us drop kfree_sized(), since it no longer used its size
argument. StringData, Utf16StringData, JS object storage, Rust error
strings, and the CoreAudio playback helpers can all free their AK-backed
storage with plain kfree().

Sanitizer builds still use the system allocator. LeakSanitizer does not
reliably trace references stored in mimalloc-managed AK containers, so
static caches and other long-lived roots can look leaked. Pass the old
size into the Rust realloc shim so aligned fallback reallocations can
move posix_memalign-backed blocks safely.

Static builds still need a little linker help. macOS app binaries need
the Rust allocator entry points forced in from liblagom-ak.a, while
static ELF links can pull in identical allocator shim definitions from
multiple Rust staticlibs. Keep the Apple -u flags and allow those
duplicate shim symbols for LibJS and LibRegex links on Linux and BSD.
2026-04-08 09:57:53 +02:00

43 lines
1.3 KiB
Rust

/*
* Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
use std::alloc::{GlobalAlloc, Layout};
unsafe extern "C" {
fn ladybird_rust_alloc(size: usize, alignment: usize) -> *mut u8;
fn ladybird_rust_alloc_zeroed(size: usize, alignment: usize) -> *mut u8;
fn ladybird_rust_dealloc(ptr: *mut u8, alignment: usize);
fn ladybird_rust_realloc(
ptr: *mut u8,
old_size: usize,
new_size: usize,
alignment: usize,
) -> *mut u8;
}
struct LadybirdAllocator;
#[global_allocator]
static LADYBIRD_ALLOCATOR: LadybirdAllocator = LadybirdAllocator;
unsafe impl GlobalAlloc for LadybirdAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
unsafe { ladybird_rust_alloc(layout.size(), layout.align()) }
}
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
unsafe { ladybird_rust_alloc_zeroed(layout.size(), layout.align()) }
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
unsafe { ladybird_rust_dealloc(ptr, layout.align()) }
}
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
unsafe { ladybird_rust_realloc(ptr, layout.size(), new_size, layout.align()) }
}
}