use crate::{
chunks::{CHUNK_SHIFT, Chunks},
heap::{Heap, HeapData},
region::{Parts, Region},
size_class::BIN_SLOTS,
slab::{Block, Slab},
sync::AtomicU64,
};
use core::{alloc::Layout, cell::Cell, ptr, ptr::NonNull};
use std::{
alloc::{alloc_zeroed, dealloc},
boxed::Box,
collections::BTreeMap,
vec::Vec,
};
#[derive(Clone, Debug)]
pub struct Rng(u64);
impl Rng {
pub const fn new(seed: u64) -> Self {
Self(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
}
pub const fn next_u64(&mut self) -> u64 {
self.0 ^= self.0 >> 12;
self.0 ^= self.0 << 25;
self.0 ^= self.0 >> 27;
self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
}
pub const fn below(&mut self, bound: usize) -> usize {
(self.next_u64() % bound as u64) as usize
}
pub const fn between(&mut self, low: usize, high: usize) -> usize {
low + self.below(high - low + 1)
}
}
pub const fn iterations(native: usize) -> usize {
if cfg!(miri) { native / 100 + 1 } else { native }
}
#[derive(Debug)]
pub(crate) struct Bitmap {
words: Vec<AtomicU64>,
len: usize,
granule: usize,
}
impl Bitmap {
#[cfg(test)]
pub(crate) fn new(len: usize) -> Self {
Self::with_granule(len, 1)
}
pub(crate) fn with_granule(len: usize, granule: usize) -> Self {
let words = (0..Chunks::storage_words(len)).map(|_| AtomicU64::new(0)).collect();
Self { words, len, granule }
}
pub(crate) fn chunks(&self) -> Chunks<'_> {
Chunks::with_granule(&self.words, self.len, self.granule)
}
}
#[derive(Debug)]
pub(crate) struct Buffer {
ptr: NonNull<u8>,
layout: Layout,
}
pub(crate) const SLAB_ALIGN: usize = 4 << 20;
impl Buffer {
pub(crate) fn new(size: usize) -> Self {
let layout = Layout::from_size_align(size, SLAB_ALIGN).expect("valid test layout");
let ptr = NonNull::new(unsafe { alloc_zeroed(layout) }).expect("test allocation failed");
Self { ptr, layout }
}
pub(crate) const fn as_ptr(&self) -> *mut u8 {
self.ptr.as_ptr()
}
}
impl Drop for Buffer {
fn drop(&mut self) {
unsafe { dealloc(self.ptr.as_ptr(), self.layout) };
}
}
unsafe impl Send for Buffer {}
unsafe impl Sync for Buffer {}
#[derive(Debug)]
pub struct TestRegion {
words: Box<[AtomicU64]>,
slabs: Box<[Slab]>,
map: Box<[AtomicU64]>,
heaps: Box<[HeapData]>,
spare_heaps: usize,
bins: Box<[Cell<*mut Block>]>,
memory: Buffer,
chunks: usize,
nodes: usize,
huge_zone: bool,
}
impl TestRegion {
pub fn new(chunks: usize, heaps: usize) -> Self {
assert!(chunks > 0, "a region needs at least one chunk");
unsafe {
Self {
words: zeroed(Chunks::storage_words(chunks), || AtomicU64::new(0)),
slabs: zeroed(chunks, Slab::new),
map: zeroed(chunks, || AtomicU64::new(0)),
heaps: zeroed(heaps, HeapData::new),
spare_heaps: 0,
bins: zeroed(heaps * BIN_SLOTS, || Cell::new(ptr::null_mut())),
memory: Buffer::new(chunks << CHUNK_SHIFT),
chunks,
nodes: 1,
huge_zone: false,
}
}
}
pub fn with_nodes(chunks: usize, heaps: usize, nodes: usize) -> Self {
Self { nodes, ..Self::new(chunks, heaps) }
}
#[must_use]
pub fn with_huge_zone(self) -> Self {
Self { huge_zone: true, ..self }
}
#[must_use]
pub fn with_spare_heaps(self, spares: usize) -> Self {
let slots = self.heaps.len() + spares;
unsafe {
Self {
heaps: zeroed(slots, HeapData::new),
spare_heaps: spares,
bins: zeroed(slots * BIN_SLOTS, || Cell::new(ptr::null_mut())),
..self
}
}
}
pub fn region(&self) -> Region<'_> {
unsafe {
Region::from_parts(Parts {
base: self.memory.as_ptr(),
words: &self.words,
chunk_count: self.chunks,
slabs: &self.slabs,
map: &self.map,
heaps: &self.heaps,
spare_heaps: self.spare_heaps,
bin_slots: self.bins.as_ptr().cast::<*mut Block>().cast_mut(),
nodes: self.nodes,
huge_zone: self.huge_zone,
})
}
}
}
unsafe fn zeroed<T>(len: usize, make: impl Fn() -> T) -> Box<[T]> {
let layout = Layout::array::<T>(len).expect("a slice that fits in memory");
if cfg!(loom) || layout.size() == 0 {
return (0..len).map(|_| make()).collect();
}
unsafe {
let values = alloc_zeroed(layout).cast::<T>();
if values.is_null() {
std::alloc::handle_alloc_error(layout);
}
Box::from_raw(ptr::slice_from_raw_parts_mut(values, len))
}
}
#[derive(Debug)]
struct Live {
ptr: NonNull<u8>,
layout: Layout,
stamp: u8,
}
#[derive(Debug)]
pub struct Harness<'r> {
region: &'r Region<'r>,
heaps: Vec<Heap<'r>>,
live: Vec<Live>,
spans: BTreeMap<usize, usize>,
stamp: u8,
}
impl<'r> Harness<'r> {
pub fn new(region: &'r Region<'r>, heaps: usize) -> Self {
let heaps = (0..heaps).map(|_| region.heap().expect("enough heap slots")).collect();
Self { region, heaps, live: Vec::new(), spans: BTreeMap::new(), stamp: 0 }
}
pub const fn live(&self) -> usize {
self.live.len()
}
pub fn heaps(&self) -> &[Heap<'r>] {
&self.heaps
}
pub fn alloc(&mut self, heap: usize, size: usize, align: usize) -> bool {
self.alloc_with(heap, size, align, false)
}
pub fn alloc_zeroed(&mut self, heap: usize, size: usize, align: usize) -> bool {
self.alloc_with(heap, size, align, true)
}
fn alloc_with(&mut self, heap: usize, size: usize, align: usize, zeroed: bool) -> bool {
let layout = Layout::from_size_align(size, align).expect("valid layout");
let heap = heap % self.heaps.len();
let heap = &self.heaps[heap];
let Some(ptr) = (if zeroed { heap.alloc_zeroed(layout) } else { heap.alloc(layout) })
else {
return false;
};
assert_eq!(ptr.as_ptr().addr() % align, 0, "misaligned block for {layout:?}");
assert!(self.region.contains(ptr.as_ptr()), "block outside the region");
if zeroed {
let bytes = unsafe { core::slice::from_raw_parts(ptr.as_ptr(), size) };
assert!(bytes.iter().all(|&byte| byte == 0), "a zeroed block of {size} bytes has data");
}
self.stamp = self.stamp.wrapping_add(1);
self.track(ptr, size);
unsafe { ptr.as_ptr().write_bytes(self.stamp, size) };
self.live.push(Live { ptr, layout, stamp: self.stamp });
true
}
pub fn free(&mut self, heap: usize, victim: usize) -> bool {
if self.live.is_empty() {
return false;
}
let block = self.live.swap_remove(victim % self.live.len());
Self::verify(&block, block.layout.size());
self.spans.remove(&block.ptr.as_ptr().addr());
unsafe { self.heaps[heap % self.heaps.len()].dealloc(block.ptr, block.layout) };
true
}
pub fn free_unsized(&mut self, heap: usize, victim: usize) -> bool {
if self.live.is_empty() {
return false;
}
let block = self.live.swap_remove(victim % self.live.len());
Self::verify(&block, block.layout.size());
self.spans.remove(&block.ptr.as_ptr().addr());
unsafe { self.heaps[heap % self.heaps.len()].free_unsized(block.ptr) };
true
}
pub fn realloc(&mut self, heap: usize, victim: usize, new_size: usize) -> bool {
if self.live.is_empty() {
return false;
}
let index = victim % self.live.len();
let (ptr, old, stamp) = {
let block = &self.live[index];
(block.ptr, block.layout, block.stamp)
};
Self::verify(&self.live[index], old.size());
let heap = heap % self.heaps.len();
let Some(new) = (unsafe { self.heaps[heap].realloc(ptr, old, new_size) }) else {
Self::verify(&self.live[index], old.size());
return false;
};
let kept = old.size().min(new_size);
let prefix = unsafe { core::slice::from_raw_parts(new.as_ptr(), kept) };
assert!(all_equal(prefix, stamp), "realloc lost the old contents");
assert_eq!(new.as_ptr().addr() % old.align(), 0, "realloc broke alignment");
self.spans.remove(&ptr.as_ptr().addr());
self.track(new, new_size);
unsafe { new.as_ptr().write_bytes(stamp, new_size) };
let layout = Layout::from_size_align(new_size, old.align()).expect("valid layout");
self.live[index] = Live { ptr: new, layout, stamp };
true
}
pub fn validate(&self) {
let mut seen: std::collections::BTreeSet<usize> =
self.live.iter().map(|block| block.ptr.as_ptr().addr()).collect();
for heap in &self.heaps {
heap.validate_into(&mut seen);
}
for block in &self.live {
if !crate::size_class::is_small(block.layout) {
seen.remove(&block.ptr.as_ptr().addr());
}
}
for &addr in &seen {
let block = NonNull::new(self.region.chunk_ptr(0).with_addr(addr)).expect("a block");
let free = unsafe { self.region.is_free_block(block) };
assert!(!free, "a block that is live or held is also free in its slab");
}
}
pub fn recycle(&mut self, heap: usize) {
let slot = heap % self.heaps.len();
drop(self.heaps.remove(slot));
self.heaps.insert(slot, self.region.heap().expect("the released slot is free"));
}
pub fn flush(&self, heap: usize) {
self.heaps[heap % self.heaps.len()].flush();
}
pub fn finish(mut self) {
self.validate();
let mut round = 0;
while self.free(round, 0) {
round += 1;
}
self.validate();
for _ in 0..3 {
for heap in &self.heaps {
heap.flush();
}
}
self.validate();
let stats = self.region.stats();
assert_eq!(stats.free, stats.capacity, "memory leaked or failed to coalesce");
}
fn track(&mut self, ptr: NonNull<u8>, size: usize) {
let (start, end) = (ptr.as_ptr().addr(), ptr.as_ptr().addr() + size.max(1));
if let Some((_, &previous_end)) = self.spans.range(..=start).next_back() {
assert!(previous_end <= start, "block at {start:#x} overlaps the one before it");
}
if let Some((&next_start, _)) = self.spans.range(start..).next() {
assert!(next_start >= end, "block at {start:#x} overlaps the one after it");
}
self.spans.insert(start, end);
}
fn verify(block: &Live, len: usize) {
let bytes = unsafe { core::slice::from_raw_parts(block.ptr.as_ptr(), len) };
assert!(all_equal(bytes, block.stamp), "block contents were overwritten");
}
}
fn all_equal(bytes: &[u8], value: u8) -> bool {
if !cfg!(miri) {
return bytes.iter().all(|&byte| byte == value);
}
let edge = bytes.len().min(64);
bytes[..edge]
.iter()
.chain(&bytes[bytes.len() - edge..])
.chain(bytes.iter().step_by(4099))
.all(|&byte| byte == value)
}
const fn random_size(rng: &mut Rng) -> usize {
match rng.below(10) {
0..=5 => rng.between(1, 256),
6..=7 => rng.between(1, 8 << 10),
8 => rng.between(1, 600 << 10),
_ => rng.between(1, 6 << 20),
}
}
pub fn random_traffic(region: &Region<'_>, seed: u64, steps: usize) {
let mut rng = Rng::new(seed);
let mut harness = Harness::new(region, 3);
for step in 0..steps {
let heap = rng.below(3);
match rng.below(23) {
0..=9 => {
let widest =
if rng.below(8) == 0 { crate::MAX_ALIGN.ilog2() as usize + 2 } else { 5 };
let align = 1 << rng.below(widest);
if rng.below(4) == 0 {
harness.alloc_zeroed(heap, random_size(&mut rng), align);
} else {
harness.alloc(heap, random_size(&mut rng), align);
}
}
10..=16 => {
harness.free(heap, rng.below(1 << 20));
}
17..=18 => {
harness.realloc(heap, rng.below(1 << 20), random_size(&mut rng));
}
19..=20 => {
harness.free_unsized(heap, rng.below(1 << 20));
}
21 => harness.flush(heap),
_ => harness.recycle(heap),
}
if step % if cfg!(miri) { 32 } else { 8 } == 0 {
harness.validate();
}
}
harness.finish();
}
pub fn run_ops(data: &[u8]) {
let test = TestRegion::new(160, 4);
let region = test.region();
let mut harness = Harness::new(®ion, 3);
let _ = interpret(&mut harness, &mut data.iter().map(|&byte| usize::from(byte)));
harness.finish();
}
fn interpret(harness: &mut Harness<'_>, bytes: &mut impl Iterator<Item = usize>) -> Option<()> {
for step in 0_usize.. {
let (op, heap) = (bytes.next()?, bytes.next()?);
if step % 4 == 0 {
harness.validate();
}
match op % 16 {
0..=7 => {
let limit = [256, 4 << 10, 600 << 10, 6 << 20][bytes.next()? % 4];
let size = (bytes.next()? | bytes.next()? << 8 | bytes.next()? << 16) % limit + 1;
let align = 1 << (bytes.next()? % 24);
if op % 16 < 6 {
harness.alloc(heap, size, align);
} else {
harness.alloc_zeroed(heap, size, align);
}
}
8..=10 => {
harness.free(heap, bytes.next()? | bytes.next()? << 8);
}
11 => {
harness.free_unsized(heap, bytes.next()? | bytes.next()? << 8);
}
12..=13 => {
let size =
(bytes.next()? | bytes.next()? << 8 | bytes.next()? << 16) % (1 << 20) + 1;
harness.realloc(heap, bytes.next()? | bytes.next()? << 8, size);
}
14 => harness.flush(heap),
_ => harness.recycle(heap),
}
}
None
}
#[derive(Debug)]
pub(crate) struct ChunkModel {
bitmap: Bitmap,
taken: Vec<bool>,
live: Vec<(usize, usize)>,
touched: Vec<bool>,
purged: Vec<bool>,
now: u64,
stamps: Vec<u64>,
granule: usize,
}
impl ChunkModel {
pub(crate) fn with_granule(len: usize, granule: usize) -> Self {
Self {
bitmap: Bitmap::with_granule(len, granule),
taken: std::vec![false; len],
live: Vec::new(),
touched: std::vec![false; len],
purged: std::vec![false; len],
now: 0,
stamps: std::vec![0; len.div_ceil(64)],
granule,
}
}
#[cfg(all(test, not(loom)))]
pub(crate) const fn live(&self) -> usize {
self.live.len()
}
pub(crate) fn alloc(&mut self, n: usize, align: usize, hint: usize) -> bool {
let found = self.bitmap.chunks().alloc(n, align, hint);
let succeeded = found.is_some();
match found {
Some(first) => {
assert_eq!(first % align, 0, "run is not aligned");
assert!(first + n <= self.taken.len(), "run is out of bounds");
assert!(self.taken[first..first + n].iter().all(|taken| !taken), "runs overlap");
self.taken[first..first + n].fill(true);
self.touched[first..first + n].fill(true);
self.live.push((first, n));
let mut reported = Vec::new();
self.bitmap.chunks().take_purged(first, n, |run| reported.extend(run));
let expected: Vec<usize> =
(first..first + n).filter(|&chunk| self.purged[chunk]).collect();
assert_eq!(reported, expected, "the purged chunks of the run were misreported");
self.purged[first..first + n].fill(false);
}
None => assert!(!self.has_room(n, align), "refused {n} chunks although they fit"),
}
self.check();
succeeded
}
pub(crate) fn free(&mut self, victim: usize) -> bool {
if self.live.is_empty() {
return false;
}
let (first, n) = self.live.swap_remove(victim % self.live.len());
self.now += 1;
self.bitmap.chunks().free_at(first, n, self.now);
self.taken[first..first + n].fill(false);
for word in first / 64..=(first + n - 1) / 64 {
self.stamps[word] = self.now;
}
self.check();
true
}
pub(crate) fn purge(&mut self, elapsed: u64) -> usize {
const DELAY: u64 = 5;
self.now += elapsed;
let mut visited = Vec::new();
let pending = self.bitmap.chunks().purge_pass(self.now, DELAY, |run| {
visited.extend(run);
true
});
let len = self.taken.len();
let groups: Vec<_> = (0..len)
.step_by(self.granule)
.map(|start| start..(start + self.granule).min(len))
.filter(|group| {
group.clone().all(|chunk| !self.taken[chunk]) &&
group.clone().any(|chunk| self.touched[chunk] && !self.purged[chunk])
})
.collect();
let mut expected = 0;
let mut waiting = false;
let mut taken = std::vec![false; len];
for group in groups {
if self.now.saturating_sub(self.stamps[group.start / 64]) >= DELAY {
for chunk in group {
taken[chunk] = true;
self.purged[chunk] = true;
expected += 1;
}
} else {
waiting = true;
}
}
for (chunk, &purge) in taken.iter().enumerate() {
assert_eq!(
visited.contains(&chunk),
purge,
"chunk {chunk} was purged at the wrong time"
);
}
assert_eq!(pending, waiting, "the pass misreports whether chunks are still waiting");
self.check();
expected
}
fn has_room(&self, n: usize, align: usize) -> bool {
let step = if n > 64 { 64 } else { align };
(0..(self.taken.len() + 1).saturating_sub(n))
.step_by(step)
.filter(|start| n > 64 || start / 64 == (start + n - 1) / 64)
.any(|start| self.taken[start..start + n].iter().all(|taken| !taken))
}
fn check(&self) {
let free = self.taken.iter().filter(|taken| !**taken).count();
assert_eq!(self.bitmap.chunks().free_chunks(), free, "free count disagrees with the model");
}
}
pub fn run_chunk_ops(data: &[u8]) {
let mut bytes = data.iter().map(|&byte| usize::from(byte));
let Some(len) = bytes.next() else { return };
let granule = if len & 0x80 != 0 { 32 } else { 1 };
let mut model = ChunkModel::with_granule(1 + len % 400, granule);
let _ = interpret_chunks(&mut model, &mut bytes);
}
fn interpret_chunks(model: &mut ChunkModel, bytes: &mut impl Iterator<Item = usize>) -> Option<()> {
loop {
let op = bytes.next()? % 7;
if op == 6 {
let elapsed = bytes.next()? % 12;
model.purge(elapsed as u64);
} else if op < 4 {
let n = match bytes.next()? % 4 {
0 => 1,
1 => 1 + bytes.next()? % 20,
2 => 64,
_ => 1 + bytes.next()? % 200,
};
model.alloc(n, 1 << (bytes.next()? % 7), bytes.next()? % 8);
} else {
model.free(bytes.next()?);
}
}
}