| 1 | use std::{ |
| 2 | alloc::{self, handle_alloc_error}, |
| 3 | cell::Cell, |
| 4 | num::NonZeroUsize, |
| 5 | ops::{Deref, DerefMut}, |
| 6 | ptr::{self, NonNull}, |
| 7 | rc::Rc, |
| 8 | }; |
| 9 | |
| 10 | struct ArenaElement { |
| 11 | value: *mut u8, |
| 12 | drop: unsafe fn(*mut u8), |
| 13 | } |
| 14 | |
| 15 | impl Drop for ArenaElement { |
| 16 | #[inline(always)] |
| 17 | fn drop(&mut self) { |
| 18 | unsafe { (self.drop)(self.value) }; |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | struct Chunk { |
| 23 | start: *mut u8, |
| 24 | end: *mut u8, |
| 25 | offset: *mut u8, |
| 26 | } |
| 27 | |
| 28 | impl Drop for Chunk { |
| 29 | fn drop(&mut self) { |
| 30 | unsafe { |
| 31 | let chunk_size = self.end.offset_from_unsigned(self.start); |
| 32 | // SAFETY: This succeeded during allocation. |
| 33 | let layout = alloc::Layout::from_size_align_unchecked(chunk_size, 1); |
| 34 | alloc::dealloc(self.start, layout); |
| 35 | } |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | impl Chunk { |
| 40 | fn new(chunk_size: NonZeroUsize) -> Self { |
| 41 | // this only fails if chunk_size is unreasonably huge |
| 42 | let layout = alloc::Layout::from_size_align(chunk_size.get(), 1).unwrap(); |
| 43 | let start = unsafe { alloc::alloc(layout) }; |
| 44 | if start.is_null() { |
| 45 | handle_alloc_error(layout); |
| 46 | } |
| 47 | let end = unsafe { start.add(chunk_size.get()) }; |
| 48 | Self { |
| 49 | start, |
| 50 | end, |
| 51 | offset: start, |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | fn allocate(&mut self, layout: alloc::Layout) -> Option<NonNull<u8>> { |
| 56 | // Compute the allocation bounds in integer address space so that the |
| 57 | // bounds check happens before any pointer offsetting. Offsetting a |
| 58 | // pointer past the end of its allocation is undefined behavior even if |
| 59 | // the result is never dereferenced (as happens on the chunk-spill |
| 60 | // path), so `ptr::add` cannot be used until we know the result stays |
| 61 | // in bounds. `checked_add` also handles the documented case where |
| 62 | // `align_offset` returns `usize::MAX`. |
| 63 | let base = self.offset.addr(); |
| 64 | let aligned_addr = base.checked_add(self.offset.align_offset(layout.align()))?; |
| 65 | let next_addr = aligned_addr.checked_add(layout.size())?; |
| 66 | |
| 67 | if next_addr <= self.end.addr() { |
| 68 | let aligned = self.offset.with_addr(aligned_addr); |
| 69 | self.offset = self.offset.with_addr(next_addr); |
| 70 | NonNull::new(aligned) |
| 71 | } else { |
| 72 | None |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | fn reset(&mut self) { |
| 77 | self.offset = self.start; |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | pub struct Arena { |
| 82 | chunks: Vec<Chunk>, |
| 83 | elements: Vec<ArenaElement>, |
| 84 | valid: Rc<Cell<bool>>, |
| 85 | current_chunk_index: usize, |
| 86 | chunk_size: NonZeroUsize, |
| 87 | scope_depth: usize, |
| 88 | } |
| 89 | |
| 90 | impl Drop for Arena { |
| 91 | fn drop(&mut self) { |
| 92 | self.force_clear(); |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | impl Arena { |
| 97 | pub fn new(chunk_size: usize) -> Self { |
| 98 | let chunk_size = NonZeroUsize::try_from(chunk_size).unwrap(); |
| 99 | Self { |
| 100 | chunks: vec![Chunk::new(chunk_size)], |
| 101 | elements: Vec::new(), |
| 102 | valid: Rc::new(Cell::new(true)), |
| 103 | current_chunk_index: 0, |
| 104 | chunk_size, |
| 105 | scope_depth: 0, |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | pub fn capacity(&self) -> usize { |
| 110 | self.chunks.len() * self.chunk_size.get() |
| 111 | } |
| 112 | |
| 113 | /// Marks the start of a scope (e.g. a window draw) whose allocations must stay |
| 114 | /// live until the scope ends, even if `clear` is called by a nested scope in |
| 115 | /// the meantime. |
| 116 | pub fn begin_scope(&mut self) { |
| 117 | self.scope_depth += 1; |
| 118 | } |
| 119 | |
| 120 | /// Ends the innermost scope started with `begin_scope`. |
| 121 | /// |
| 122 | /// Panics if no scope is active: an unbalanced `end_scope` would let `clear` |
| 123 | /// run while an enclosing scope still references arena memory, which is |
| 124 | /// exactly the use-after-free this bookkeeping exists to prevent, so failing |
| 125 | /// loudly here is preferable. |
| 126 | pub fn end_scope(&mut self) { |
| 127 | self.scope_depth = self |
| 128 | .scope_depth |
| 129 | .checked_sub(1) |
| 130 | .expect("Arena::end_scope called without a matching begin_scope"); |
| 131 | } |
| 132 | |
| 133 | /// Drops all allocations and resets the arena, unless a scope is still active. |
| 134 | /// |
| 135 | /// When a draw triggers a nested draw (e.g. re-entrant window procedure |
| 136 | /// invocations on Windows, or opening a window from within a draw), the nested |
| 137 | /// draw's clear must not free memory the outer draw still references, so it is |
| 138 | /// deferred: the outer draw's own clear will drop both draws' allocations. |
| 139 | pub fn clear(&mut self) { |
| 140 | if self.scope_depth == 0 { |
| 141 | self.force_clear(); |
| 142 | } else { |
| 143 | log::debug!( |
| 144 | "deferring arena clear; {} enclosing scope(s) still active", |
| 145 | self.scope_depth |
| 146 | ); |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | fn force_clear(&mut self) { |
| 151 | self.valid.set(false); |
| 152 | self.valid = Rc::new(Cell::new(true)); |
| 153 | self.elements.clear(); |
| 154 | for chunk_index in 0..=self.current_chunk_index { |
| 155 | self.chunks[chunk_index].reset(); |
| 156 | } |
| 157 | self.current_chunk_index = 0; |
| 158 | } |
| 159 | |
| 160 | #[inline(always)] |
| 161 | pub fn alloc<T>(&mut self, f: impl FnOnce() -> T) -> ArenaBox<T> { |
| 162 | #[inline(always)] |
| 163 | unsafe fn inner_writer<T, F>(ptr: *mut T, f: F) |
| 164 | where |
| 165 | F: FnOnce() -> T, |
| 166 | { |
| 167 | unsafe { ptr::write(ptr, f()) }; |
| 168 | } |
| 169 | |
| 170 | unsafe fn drop<T>(ptr: *mut u8) { |
| 171 | unsafe { std::ptr::drop_in_place(ptr.cast::<T>()) }; |
| 172 | } |
| 173 | |
| 174 | let layout = alloc::Layout::new::<T>(); |
| 175 | let current_chunk = &mut self.chunks[self.current_chunk_index]; |
| 176 | let ptr = if let Some(ptr) = current_chunk.allocate(layout) { |
| 177 | ptr.as_ptr() |
| 178 | } else { |
| 179 | self.allocate_next_chunk(layout) |
| 180 | }; |
| 181 | |
| 182 | unsafe { inner_writer(ptr.cast(), f) }; |
| 183 | self.elements.push(ArenaElement { |
| 184 | value: ptr, |
| 185 | drop: drop::<T>, |
| 186 | }); |
| 187 | |
| 188 | ArenaBox { |
| 189 | ptr: ptr.cast(), |
| 190 | valid: self.valid.clone(), |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | #[inline(never)] |
| 195 | fn allocate_next_chunk(&mut self, layout: alloc::Layout) -> *mut u8 { |
| 196 | self.current_chunk_index += 1; |
| 197 | if self.current_chunk_index >= self.chunks.len() { |
| 198 | self.chunks.push(Chunk::new(self.chunk_size)); |
| 199 | assert_eq!(self.current_chunk_index, self.chunks.len() - 1); |
| 200 | log::trace!( |
| 201 | "increased element arena capacity to {}kb", |
| 202 | self.capacity() / 1024, |
| 203 | ); |
| 204 | } |
| 205 | let current_chunk = &mut self.chunks[self.current_chunk_index]; |
| 206 | if let Some(pointer) = current_chunk.allocate(layout) { |
| 207 | pointer.as_ptr() |
| 208 | } else { |
| 209 | panic!( |
| 210 | "Arena chunk_size of {} is too small to allocate {} bytes", |
| 211 | self.chunk_size, |
| 212 | layout.size() |
| 213 | ); |
| 214 | } |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | pub struct ArenaBox<T: ?Sized> { |
| 219 | ptr: *mut T, |
| 220 | valid: Rc<Cell<bool>>, |
| 221 | } |
| 222 | |
| 223 | impl<T: ?Sized> ArenaBox<T> { |
| 224 | #[inline(always)] |
| 225 | pub fn map<U: ?Sized>(mut self, f: impl FnOnce(&mut T) -> &mut U) -> ArenaBox<U> { |
| 226 | ArenaBox { |
| 227 | ptr: f(&mut self), |
| 228 | valid: self.valid, |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | #[track_caller] |
| 233 | fn validate(&self) { |
| 234 | assert!( |
| 235 | self.valid.get(), |
| 236 | "attempted to dereference an ArenaRef after its Arena was cleared" |
| 237 | ); |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | impl<T: ?Sized> Deref for ArenaBox<T> { |
| 242 | type Target = T; |
| 243 | |
| 244 | #[inline(always)] |
| 245 | fn deref(&self) -> &Self::Target { |
| 246 | self.validate(); |
| 247 | unsafe { &*self.ptr } |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | impl<T: ?Sized> DerefMut for ArenaBox<T> { |
| 252 | #[inline(always)] |
| 253 | fn deref_mut(&mut self) -> &mut Self::Target { |
| 254 | self.validate(); |
| 255 | unsafe { &mut *self.ptr } |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | #[cfg(test)] |
| 260 | mod tests { |
| 261 | use std::{cell::Cell, rc::Rc}; |
| 262 | |
| 263 | use super::*; |
| 264 | |
| 265 | #[test] |
| 266 | fn test_arena() { |
| 267 | let mut arena = Arena::new(1024); |
| 268 | let a = arena.alloc(|| 1u64); |
| 269 | let b = arena.alloc(|| 2u32); |
| 270 | let c = arena.alloc(|| 3u16); |
| 271 | let d = arena.alloc(|| 4u8); |
| 272 | assert_eq!(*a, 1); |
| 273 | assert_eq!(*b, 2); |
| 274 | assert_eq!(*c, 3); |
| 275 | assert_eq!(*d, 4); |
| 276 | |
| 277 | arena.clear(); |
| 278 | let a = arena.alloc(|| 5u64); |
| 279 | let b = arena.alloc(|| 6u32); |
| 280 | let c = arena.alloc(|| 7u16); |
| 281 | let d = arena.alloc(|| 8u8); |
| 282 | assert_eq!(*a, 5); |
| 283 | assert_eq!(*b, 6); |
| 284 | assert_eq!(*c, 7); |
| 285 | assert_eq!(*d, 8); |
| 286 | |
| 287 | // Ensure drop gets called. |
| 288 | let dropped = Rc::new(Cell::new(false)); |
| 289 | struct DropGuard(Rc<Cell<bool>>); |
| 290 | impl Drop for DropGuard { |
| 291 | fn drop(&mut self) { |
| 292 | self.0.set(true); |
| 293 | } |
| 294 | } |
| 295 | arena.alloc(|| DropGuard(dropped.clone())); |
| 296 | arena.clear(); |
| 297 | assert!(dropped.get()); |
| 298 | } |
| 299 | |
| 300 | #[test] |
| 301 | fn test_arena_grow() { |
| 302 | let mut arena = Arena::new(8); |
| 303 | arena.alloc(|| 1u64); |
| 304 | arena.alloc(|| 2u64); |
| 305 | |
| 306 | assert_eq!(arena.capacity(), 16); |
| 307 | |
| 308 | arena.alloc(|| 3u32); |
| 309 | arena.alloc(|| 4u32); |
| 310 | |
| 311 | assert_eq!(arena.capacity(), 24); |
| 312 | } |
| 313 | |
| 314 | #[test] |
| 315 | fn test_arena_alignment() { |
| 316 | let mut arena = Arena::new(256); |
| 317 | let x1 = arena.alloc(|| 1u8); |
| 318 | let x2 = arena.alloc(|| 2u16); |
| 319 | let x3 = arena.alloc(|| 3u32); |
| 320 | let x4 = arena.alloc(|| 4u64); |
| 321 | let x5 = arena.alloc(|| 5u64); |
| 322 | |
| 323 | assert_eq!(*x1, 1); |
| 324 | assert_eq!(*x2, 2); |
| 325 | assert_eq!(*x3, 3); |
| 326 | assert_eq!(*x4, 4); |
| 327 | assert_eq!(*x5, 5); |
| 328 | |
| 329 | assert_eq!(x1.ptr.align_offset(std::mem::align_of_val(&*x1)), 0); |
| 330 | assert_eq!(x2.ptr.align_offset(std::mem::align_of_val(&*x2)), 0); |
| 331 | } |
| 332 | |
| 333 | #[test] |
| 334 | #[should_panic(expected = "attempted to dereference an ArenaRef after its Arena was cleared")] |
| 335 | fn test_arena_use_after_clear() { |
| 336 | let mut arena = Arena::new(16); |
| 337 | let value = arena.alloc(|| 1u64); |
| 338 | |
| 339 | arena.clear(); |
| 340 | let _read_value = *value; |
| 341 | } |
| 342 | |
| 343 | #[test] |
| 344 | fn test_clear_deferred_while_scope_active() { |
| 345 | struct DropCounter(Rc<Cell<usize>>); |
| 346 | impl Drop for DropCounter { |
| 347 | fn drop(&mut self) { |
| 348 | self.0.set(self.0.get() + 1); |
| 349 | } |
| 350 | } |
| 351 | |
| 352 | let drops = Rc::new(Cell::new(0)); |
| 353 | let mut arena = Arena::new(1024); |
| 354 | |
| 355 | // Outer draw starts and allocates. |
| 356 | arena.begin_scope(); |
| 357 | let outer = arena.alloc(|| 42u64); |
| 358 | arena.alloc({ |
| 359 | let drops = drops.clone(); |
| 360 | || DropCounter(drops) |
| 361 | }); |
| 362 | |
| 363 | // Nested draw runs to completion and requests a clear. |
| 364 | arena.begin_scope(); |
| 365 | let inner = arena.alloc(|| 7u64); |
| 366 | arena.alloc({ |
| 367 | let drops = drops.clone(); |
| 368 | || DropCounter(drops) |
| 369 | }); |
| 370 | arena.end_scope(); |
| 371 | arena.clear(); |
| 372 | |
| 373 | // The clear must be deferred: the outer draw's allocations are still live. |
| 374 | assert_eq!(*outer, 42); |
| 375 | assert_eq!(*inner, 7); |
| 376 | assert_eq!(drops.get(), 0); |
| 377 | |
| 378 | // Once the outer draw finishes, its clear drops both draws' allocations. |
| 379 | arena.end_scope(); |
| 380 | arena.clear(); |
| 381 | assert_eq!(drops.get(), 2); |
| 382 | } |
| 383 | |
| 384 | #[test] |
| 385 | fn test_clear_without_scope_is_immediate() { |
| 386 | let mut arena = Arena::new(1024); |
| 387 | let value = arena.alloc(|| 1u64); |
| 388 | assert_eq!(*value, 1); |
| 389 | arena.clear(); |
| 390 | assert!(!value.valid.get()); |
| 391 | } |
| 392 | |
| 393 | #[test] |
| 394 | #[should_panic(expected = "Arena::end_scope called without a matching begin_scope")] |
| 395 | fn test_unbalanced_end_scope_panics() { |
| 396 | let mut arena = Arena::new(1024); |
| 397 | arena.begin_scope(); |
| 398 | arena.end_scope(); |
| 399 | arena.end_scope(); |
| 400 | } |
| 401 | } |