From ce2e687d016b348fa6b1c3f2affca8bf9335c288 Mon Sep 17 00:00:00 2001 From: clabby Date: Sat, 14 Nov 2026 09:45:02 -0500 Subject: [PATCH] Put the Allocator impls behind allocator-api and lower the MSRV to 1.88 The standard library's Allocator trait became stable in Rust 1.100, which set the crate's minimum version. Its implementations for Bcmalloc and Heap now live in the allocator module, compiled only with the new allocator-api feature, and the rest of the library builds on Rust 1.88, where let chains and const Cell::get became stable. The testing helper that zeroes slices allocates them with alloc_zeroed instead of Box::new_zeroed_slice (1.92). The library declares rust-version 1.88; the internal crates keep the workspace's 1.100. just msrv checks every feature combination but allocator-api on the declared version through cargo-hack, which installs the toolchain, and CI runs it. --- .github/workflows/ci.yaml | 17 ++++++ README.md | 8 ++- crates/bcmalloc/Cargo.toml | 7 ++- crates/bcmalloc/src/allocator.rs | 95 ++++++++++++++++++++++++-------- crates/bcmalloc/src/global.rs | 47 ++++++---------- crates/bcmalloc/src/heap.rs | 32 +---------- crates/bcmalloc/src/lib.rs | 1 + crates/bcmalloc/src/testing.rs | 15 ++++- crates/bcmalloc/tests/global.rs | 1 + justfile | 5 ++ 10 files changed, 136 insertions(+), 92 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 7f3d3d4..88f68ac 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -48,6 +48,23 @@ jobs: - name: Check every feature combination run: just hack --locked + msrv: + name: Minimum Rust version + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - name: Checkout sources + uses: actions/checkout@v7 + - name: Install Rust stable toolchain + uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + with: + cache-on-failure: true + - uses: taiki-e/install-action@just + - uses: taiki-e/install-action@cargo-hack + - name: Check every feature combination but allocator-api on the minimum version + run: just msrv --locked + lint: name: Clippy and rustfmt runs-on: ubuntu-latest diff --git a/README.md b/README.md index 0b802f3..a80945e 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # bcmalloc -License Rust 1.100+ Platforms +License Rust 1.88+ Platforms A global allocator for long-lived, highly concurrent Rust programs. It reserves one region of address space up front and serves small blocks from per-thread stacks of free pointers, without atomic operations and without touching the blocks. Blocks freed by another thread go home in batched messages, one compare-and-swap per batch. Memory freed by one size class is reused by every other, memory that stays idle goes back to the operating system, and the capacity you configure is a hard limit. @@ -47,9 +47,10 @@ unsafe { heap.dealloc(block, layout) }; # Ok::<(), bcmalloc::Error>(()) ``` -The allocator also implements the standard library's `Allocator` trait, which has been stable since Rust 1.100. A collection can then take it as a parameter without it being the global allocator. A heap implements the trait too, for code that wants one thread's heap. +With the `allocator-api` feature, the allocator also implements the standard library's `Allocator` trait, which has been stable since Rust 1.100. A collection can then take it as a parameter without it being the global allocator. A heap implements the trait too, for code that wants one thread's heap. ```rust +# #[cfg(feature = "allocator-api")] { use bcmalloc::Bcmalloc; static ALLOCATOR: Bcmalloc = Bcmalloc::new(); @@ -57,6 +58,7 @@ static ALLOCATOR: Bcmalloc = Bcmalloc::new(); let mut numbers = Vec::new_in(&ALLOCATOR); numbers.extend(0..1000_u32); assert_eq!(numbers.iter().sum::(), 499_500); +# } ``` ## Metrics @@ -111,7 +113,7 @@ The development suite has 51 synthetic workloads and is what the allocator is tu - A thread that finds all `max_heaps` heaps taken fails its allocations, which aborts the program. - The capacity is a hard limit. Nothing grows the region after start-up. - Linux and macOS are supported. Windows is not. -- The standard library's `Allocator` trait needs Rust 1.100 or later, which is the minimum supported version. +- The minimum supported Rust version is 1.88. The `allocator-api` feature needs 1.100, where the standard library's `Allocator` trait became stable. ## Testing diff --git a/crates/bcmalloc/Cargo.toml b/crates/bcmalloc/Cargo.toml index bc8cb89..9694752 100644 --- a/crates/bcmalloc/Cargo.toml +++ b/crates/bcmalloc/Cargo.toml @@ -2,7 +2,8 @@ name = "bcmalloc" version = "0.1.0" edition.workspace = true -rust-version.workspace = true +# The library's minimum, below the workspace's. The `allocator-api` feature needs 1.100. +rust-version = "1.88" license.workspace = true repository.workspace = true description = "A scalable global allocator that reserves its memory up front, for long-lived, highly concurrent programs." @@ -19,6 +20,10 @@ testing = [ "std" ] # Counts allocations, frees, slabs and slow-path events per heap, for `Region::metrics` and # `Bcmalloc::metrics`. The fast paths pay one add each on a cache line they already touch. metrics = [] +# Implements the standard library's `Allocator` trait for `Bcmalloc` and `Heap`, so that a +# collection can allocate from one without it being the global allocator. The trait needs Rust +# 1.100, above the crate's minimum. +allocator-api = [] [dependencies] libc.workspace = true diff --git a/crates/bcmalloc/src/allocator.rs b/crates/bcmalloc/src/allocator.rs index 0d82191..576e4e8 100644 --- a/crates/bcmalloc/src/allocator.rs +++ b/crates/bcmalloc/src/allocator.rs @@ -1,9 +1,9 @@ -//! The [`Allocator`](core::alloc::Allocator) trait, for collections that take an allocator as a -//! parameter. +//! The [`Allocator`] trait, for collections that take an allocator as a parameter. It is compiled +//! with the `allocator-api` feature, because the trait needs Rust 1.100, above the crate's minimum. //! -//! [`Bcmalloc`](crate::Bcmalloc) and [`Heap`](crate::Heap) both implement it, so a `Vec` or a -//! `Box` can allocate from one of them without it being the program's global allocator. Their -//! documentation has examples. +//! [`Bcmalloc`] and [`Heap`] both implement it, so a `Vec` or a `Box` can allocate from one of +//! them without it being the program's global allocator. The documentation of `Bcmalloc` has an +//! example. //! //! # How the trait's rules are met //! @@ -19,14 +19,21 @@ //! chunks can shrink or grow where it is. They always move it when the alignment changes, which //! that resize does not support. +#![allow(clippy::incompatible_msrv, reason = "the allocator-api feature needs Rust 1.100")] + +#[cfg(all(feature = "std", not(loom)))] +use crate::Bcmalloc; +use crate::Heap; +#[cfg(all(feature = "std", not(loom)))] +use core::alloc::GlobalAlloc; use core::{ - alloc::{AllocError, Layout}, + alloc::{AllocError, Allocator, Layout}, num::NonZero, ptr::{self, NonNull}, }; /// The operations that the allocator trait is built from. -pub(crate) trait Backend { +trait Backend { /// Allocates a block, or returns null. /// /// # Safety @@ -68,7 +75,7 @@ fn block(ptr: *mut u8, size: usize) -> Result, AllocError> { NonNull::new(ptr).map(|ptr| NonNull::slice_from_raw_parts(ptr, size)).ok_or(AllocError) } -pub(crate) fn allocate( +fn allocate( backend: &A, layout: Layout, zeroed: bool, @@ -83,11 +90,7 @@ pub(crate) fn allocate( block(ptr, layout.size()) } -pub(crate) unsafe fn deallocate( - backend: &A, - ptr: NonNull, - layout: Layout, -) { +unsafe fn deallocate(backend: &A, ptr: NonNull, layout: Layout) { if layout.size() != 0 { // SAFETY: the caller vouches for the block. unsafe { backend.deallocate_raw(ptr, layout) }; @@ -100,7 +103,7 @@ pub(crate) unsafe fn deallocate( /// /// The block must be live with the old layout. The new size must be at least the old size when /// growing and at most the old size when shrinking. -pub(crate) unsafe fn resize( +unsafe fn resize( backend: &A, ptr: NonNull, old: Layout, @@ -137,7 +140,7 @@ pub(crate) unsafe fn resize( block(moved, new.size()) } -/// Implements [`Allocator`](core::alloc::Allocator) for a type that implements [`Backend`]. +/// Implements [`Allocator`] for a type that implements [`Backend`]. macro_rules! allocator { ($($header:tt)*) => { // SAFETY: the blocks come from the backend, which hands out valid, aligned, disjoint memory @@ -145,16 +148,16 @@ macro_rules! allocator { // blocks are dangling and aligned, as the trait allows. unsafe impl $($header)* { fn allocate(&self, layout: Layout) -> Result, AllocError> { - $crate::allocator::allocate(self, layout, false) + allocate(self, layout, false) } fn allocate_zeroed(&self, layout: Layout) -> Result, AllocError> { - $crate::allocator::allocate(self, layout, true) + allocate(self, layout, true) } unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { // SAFETY: forwarded. - unsafe { $crate::allocator::deallocate(self, ptr, layout) } + unsafe { deallocate(self, ptr, layout) } } unsafe fn grow( @@ -164,7 +167,7 @@ macro_rules! allocator { new: Layout, ) -> Result, AllocError> { // SAFETY: forwarded. - unsafe { $crate::allocator::resize(self, ptr, old, new, false) } + unsafe { resize(self, ptr, old, new, false) } } unsafe fn grow_zeroed( @@ -174,7 +177,7 @@ macro_rules! allocator { new: Layout, ) -> Result, AllocError> { // SAFETY: forwarded. - unsafe { $crate::allocator::resize(self, ptr, old, new, true) } + unsafe { resize(self, ptr, old, new, true) } } unsafe fn shrink( @@ -184,18 +187,64 @@ macro_rules! allocator { new: Layout, ) -> Result, AllocError> { // SAFETY: forwarded. - unsafe { $crate::allocator::resize(self, ptr, old, new, false) } + unsafe { resize(self, ptr, old, new, false) } } } }; } -pub(crate) use allocator; + +impl Backend for Heap<'_> { + unsafe fn allocate_raw(&self, layout: Layout) -> *mut u8 { + self.alloc(layout).map_or(ptr::null_mut(), NonNull::as_ptr) + } + + unsafe fn allocate_zeroed_raw(&self, layout: Layout) -> *mut u8 { + self.alloc_zeroed(layout).map_or(ptr::null_mut(), NonNull::as_ptr) + } + + unsafe fn deallocate_raw(&self, ptr: NonNull, layout: Layout) { + // SAFETY: forwarded. + unsafe { self.dealloc(ptr, layout) }; + } + + unsafe fn resize_raw(&self, ptr: NonNull, old: Layout, new_size: usize) -> *mut u8 { + // SAFETY: forwarded. + unsafe { self.realloc(ptr, old, new_size) }.map_or(ptr::null_mut(), NonNull::as_ptr) + } +} + +allocator!(Allocator for Heap<'_>); + +#[cfg(all(feature = "std", not(loom)))] +impl Backend for Bcmalloc { + unsafe fn allocate_raw(&self, layout: Layout) -> *mut u8 { + // SAFETY: forwarded. + unsafe { GlobalAlloc::alloc(self, layout) } + } + + unsafe fn allocate_zeroed_raw(&self, layout: Layout) -> *mut u8 { + // SAFETY: forwarded. + unsafe { GlobalAlloc::alloc_zeroed(self, layout) } + } + + unsafe fn deallocate_raw(&self, ptr: NonNull, layout: Layout) { + // SAFETY: forwarded. + unsafe { GlobalAlloc::dealloc(self, ptr.as_ptr(), layout) }; + } + + unsafe fn resize_raw(&self, ptr: NonNull, old: Layout, new_size: usize) -> *mut u8 { + // SAFETY: forwarded. + unsafe { GlobalAlloc::realloc(self, ptr.as_ptr(), old, new_size) } + } +} + +#[cfg(all(feature = "std", not(loom)))] +allocator!(Allocator for Bcmalloc); #[cfg(all(test, not(loom)))] mod test { use super::*; use crate::testing::{TestRegion, iterations}; - use core::alloc::Allocator; use std::{boxed::Box, vec::Vec}; fn layout(size: usize, align: usize) -> Layout { diff --git a/crates/bcmalloc/src/global.rs b/crates/bcmalloc/src/global.rs index 0d7335c..9897495 100644 --- a/crates/bcmalloc/src/global.rs +++ b/crates/bcmalloc/src/global.rs @@ -29,7 +29,6 @@ //! or when more threads are running than the configuration has heaps for. use crate::{ - allocator::{Backend, allocator}, chunks::CHUNK_SHIFT, config::Config, heap::{Heap, HeapData}, @@ -39,7 +38,7 @@ use crate::{ tls, }; use core::{ - alloc::{AllocError, Allocator, GlobalAlloc, Layout}, + alloc::{GlobalAlloc, Layout}, ptr::{self, NonNull}, }; @@ -96,10 +95,12 @@ fn set_out_of_memory() { /// /// # As an `Allocator` /// -/// A `Bcmalloc` can also serve a single collection through the standard library's -/// [`Allocator`] trait, whether or not it is the global allocator. +/// With the `allocator-api` feature, a `Bcmalloc` can also serve a single collection through +/// the standard library's [`Allocator`](core::alloc::Allocator) trait, whether or not it is the +/// global allocator. /// /// ``` +/// # #[cfg(feature = "allocator-api")] { /// use bcmalloc::Bcmalloc; /// /// static ALLOCATOR: Bcmalloc = Bcmalloc::new(); @@ -110,6 +111,7 @@ fn set_out_of_memory() { /// /// let boxed = Box::new_in([7_u8; 100], &ALLOCATOR); /// assert_eq!(boxed[99], 7); +/// # } /// ``` /// /// A zero-sized request never reaches the allocator. A block is exactly as long as it was asked to @@ -436,30 +438,6 @@ impl Bcmalloc { } } -impl Backend for Bcmalloc { - unsafe fn allocate_raw(&self, layout: Layout) -> *mut u8 { - // SAFETY: forwarded. - unsafe { GlobalAlloc::alloc(self, layout) } - } - - unsafe fn allocate_zeroed_raw(&self, layout: Layout) -> *mut u8 { - // SAFETY: forwarded. - unsafe { GlobalAlloc::alloc_zeroed(self, layout) } - } - - unsafe fn deallocate_raw(&self, ptr: NonNull, layout: Layout) { - // SAFETY: forwarded. - unsafe { GlobalAlloc::dealloc(self, ptr.as_ptr(), layout) }; - } - - unsafe fn resize_raw(&self, ptr: NonNull, old: Layout, new_size: usize) -> *mut u8 { - // SAFETY: forwarded. - unsafe { GlobalAlloc::realloc(self, ptr.as_ptr(), old, new_size) } - } -} - -allocator!(Allocator for Bcmalloc); - impl Default for Bcmalloc { fn default() -> Self { Self::new() @@ -660,6 +638,7 @@ mod test { Box::leak(Box::new(Bcmalloc::with_config(config))) } + #[cfg(feature = "allocator-api")] #[test] fn collections_can_take_the_allocator_as_a_parameter() { let allocator = instance(); @@ -682,8 +661,10 @@ mod test { assert_eq!(allocator.stats().unwrap().heaps_in_use, 0); } + #[cfg(feature = "allocator-api")] #[test] fn a_zero_sized_request_does_not_create_the_region() { + use core::alloc::Allocator; let allocator = instance(); let empty = allocator.allocate(Layout::from_size_align(0, 32).unwrap()).unwrap(); assert_eq!(empty.len(), 0); @@ -828,9 +809,13 @@ mod test { fn flushing_a_thread_returns_what_its_heap_kept() { let allocator = instance(); std::thread::spawn(move || { - let blocks: Vec<_> = - (0..1000).map(|i| Box::new_in([i as u8; 100], allocator)).collect(); - drop(blocks); + let layout = Layout::new::<[u8; 100]>(); + // SAFETY: the layout is not zero sized. + let blocks: Vec<_> = (0..1000).map(|_| unsafe { allocator.alloc(layout) }).collect(); + for block in blocks { + // SAFETY: each block came from this allocator with this layout and is freed once. + unsafe { allocator.dealloc(block, layout) }; + } let held = allocator.stats().unwrap(); assert!(held.free < held.capacity, "the heap keeps some blocks and a slab"); allocator.flush_thread(); diff --git a/crates/bcmalloc/src/heap.rs b/crates/bcmalloc/src/heap.rs index 54d38d5..ad2287f 100644 --- a/crates/bcmalloc/src/heap.rs +++ b/crates/bcmalloc/src/heap.rs @@ -76,7 +76,6 @@ //! start picks it up. Messages that arrive in between wait in its inbox. use crate::{ - allocator::{Backend, allocator}, cache::CacheLine, chunks::CHUNK_SHIFT, region::{Entry, HUGE_PAGE_CHUNKS, Region}, @@ -84,14 +83,7 @@ use crate::{ slab::{Block, List, Owned, Returns, Slab}, sync::{AtomicBool, AtomicPtr, AtomicU64, Ordering}, }; -use core::{ - alloc::{AllocError, Allocator, Layout}, - cell::Cell, - fmt, - marker::PhantomData, - ptr, - ptr::NonNull, -}; +use core::{alloc::Layout, cell::Cell, fmt, marker::PhantomData, ptr, ptr::NonNull}; /// The tag on an inbox link that marks a node as a single block and not a message. const SINGLE: usize = 0b1; @@ -2456,28 +2448,6 @@ impl<'r> Heap<'r> { } } -impl Backend for Heap<'_> { - unsafe fn allocate_raw(&self, layout: Layout) -> *mut u8 { - self.alloc(layout).map_or(ptr::null_mut(), NonNull::as_ptr) - } - - unsafe fn allocate_zeroed_raw(&self, layout: Layout) -> *mut u8 { - self.alloc_zeroed(layout).map_or(ptr::null_mut(), NonNull::as_ptr) - } - - unsafe fn deallocate_raw(&self, ptr: NonNull, layout: Layout) { - // SAFETY: forwarded. - unsafe { self.dealloc(ptr, layout) }; - } - - unsafe fn resize_raw(&self, ptr: NonNull, old: Layout, new_size: usize) -> *mut u8 { - // SAFETY: forwarded. - unsafe { self.realloc(ptr, old, new_size) }.map_or(ptr::null_mut(), NonNull::as_ptr) - } -} - -allocator!(Allocator for Heap<'_>); - impl Drop for Heap<'_> { fn drop(&mut self) { // SAFETY: this handle holds the claim. diff --git a/crates/bcmalloc/src/lib.rs b/crates/bcmalloc/src/lib.rs index 973f82a..9c9820f 100644 --- a/crates/bcmalloc/src/lib.rs +++ b/crates/bcmalloc/src/lib.rs @@ -5,6 +5,7 @@ #[macro_use] extern crate std; +#[cfg(feature = "allocator-api")] mod allocator; mod cache; mod chunks; diff --git a/crates/bcmalloc/src/testing.rs b/crates/bcmalloc/src/testing.rs index 9bbeba8..59050c6 100644 --- a/crates/bcmalloc/src/testing.rs +++ b/crates/bcmalloc/src/testing.rs @@ -203,11 +203,20 @@ impl TestRegion { /// /// An all-zero bit pattern must be a valid `T` that equals what `make` returns. unsafe fn zeroed(len: usize, make: impl Fn() -> T) -> Box<[T]> { - if cfg!(loom) { + let layout = Layout::array::(len).expect("a slice that fits in memory"); + if cfg!(loom) || layout.size() == 0 { return (0..len).map(|_| make()).collect(); } - // SAFETY: the caller vouches for the zero bit pattern. - unsafe { Box::new_zeroed_slice(len).assume_init() } + // SAFETY: the layout is not zero sized, a non-null block from `alloc_zeroed` with it holds + // `len` zeroed values, which the caller vouches are valid, and `Box` frees it with the same + // layout through the global allocator. + unsafe { + let values = alloc_zeroed(layout).cast::(); + if values.is_null() { + std::alloc::handle_alloc_error(layout); + } + Box::from_raw(ptr::slice_from_raw_parts_mut(values, len)) + } } /// A block the harness is tracking, and the byte it was filled with. diff --git a/crates/bcmalloc/tests/global.rs b/crates/bcmalloc/tests/global.rs index 8a9b99e..1f47707 100644 --- a/crates/bcmalloc/tests/global.rs +++ b/crates/bcmalloc/tests/global.rs @@ -138,6 +138,7 @@ fn trimming_reports_consistent_statistics() { assert!(after.free <= after.capacity); } +#[cfg(feature = "allocator-api")] #[test] fn the_allocator_api_can_be_used_next_to_the_global_allocator() { let mut text = String::new(); diff --git a/justfile b/justfile index cecc3bd..e15219b 100644 --- a/justfile +++ b/justfile @@ -41,6 +41,11 @@ test *args: hack *args: cargo hack -p bcmalloc --feature-powerset check --lib "$@" +# Check the library under every feature combination but `allocator-api`, which needs Rust 1.100, on +# the minimum Rust version in its manifest. cargo-hack installs that toolchain if it is missing. +msrv *args: + cargo hack -p bcmalloc --feature-powerset --exclude-features allocator-api --rust-version check --lib "$@" + # Run the tests under Miri with strict provenance. miri *args: MIRIFLAGS="-Zmiri-strict-provenance" cargo +nightly miri nextest run -p bcmalloc --all-features --lib "$@"