1use crate::Status;
2use alloc::alloc::{alloc, dealloc, realloc};
3use core::{alloc::Layout, ffi::c_void, mem::size_of, ptr};
4
5#[cfg(target_arch = "arm")]
8pub const XILA_HEAP_ALIGNMENT: usize = 8;
9#[cfg(not(target_arch = "arm"))]
11pub const XILA_HEAP_ALIGNMENT: usize = 16;
12
13struct Block {
16 previous: *mut Block,
17 next: *mut Block,
18 size: usize,
19 tag: usize,
22}
23
24const HEADER_SIZE: usize = size_of::<Block>().next_multiple_of(XILA_HEAP_ALIGNMENT);
25#[cfg(target_pointer_width = "32")]
27const _: () = assert!(HEADER_SIZE == 16);
28
29fn layout(size: usize) -> Result<Layout, Status> {
30 let total = HEADER_SIZE.checked_add(size).ok_or(Status::OutOfMemory)?;
31 Layout::from_size_align(total, XILA_HEAP_ALIGNMENT).map_err(|_| Status::OutOfMemory)
32}
33
34const KEY_SALT: usize = 0x5A17_A11C;
35#[cfg(target_pointer_width = "32")]
38const KEY_MULTIPLIER: usize = 0x9E37_79B9;
39#[cfg(target_pointer_width = "64")]
40const KEY_MULTIPLIER: usize = 0x9E37_79B9_7F4A_7C15;
41
42pub struct Heap {
58 head: *mut Block,
59 key: usize,
61}
62
63impl Default for Heap {
64 fn default() -> Self {
65 Self::new()
66 }
67}
68
69impl Heap {
70 pub const fn new() -> Self {
71 Self {
72 head: ptr::null_mut(),
73 key: 0,
74 }
75 }
76
77 fn tag(&self, block: *mut Block) -> usize {
78 self.key ^ block.addr()
79 }
80
81 fn block(&self, pointer: *mut c_void) -> Result<*mut Block, Status> {
86 if self.head.is_null()
88 || !pointer.addr().is_multiple_of(XILA_HEAP_ALIGNMENT)
89 || pointer.addr() <= HEADER_SIZE
90 {
91 return Err(Status::InvalidArgument);
92 }
93 let block = pointer.wrapping_byte_sub(HEADER_SIZE).cast::<Block>();
94 if unsafe { (*block).tag } != self.tag(block) {
97 return Err(Status::InvalidArgument);
98 }
99 Ok(block)
100 }
101
102 fn allocate(&mut self, size: usize) -> Result<*mut c_void, Status> {
103 let layout = layout(size)?;
104 let block = unsafe { alloc(layout).cast::<Block>() };
106 if block.is_null() {
107 return Err(Status::OutOfMemory);
108 }
109 if self.key == 0 {
110 let mixed = ptr::from_mut(self).addr().wrapping_mul(KEY_MULTIPLIER) ^ block.addr();
114 self.key = (mixed.wrapping_mul(KEY_MULTIPLIER) ^ KEY_SALT) | 1;
115 }
116 unsafe {
119 block.write(Block {
120 previous: ptr::null_mut(),
121 next: self.head,
122 size,
123 tag: self.tag(block),
124 });
125 self.update_links(ptr::null_mut(), block, self.head);
126 Ok(block.cast::<u8>().add(HEADER_SIZE).cast())
127 }
128 }
129
130 fn reallocate(&mut self, pointer: *mut c_void, size: usize) -> Result<*mut c_void, Status> {
131 if size == 0 {
132 self.free(pointer)?;
133 return Ok(ptr::null_mut());
134 }
135 if pointer.is_null() {
136 return self.allocate(size);
137 }
138 let old = self.block(pointer)?;
139 let new_layout = layout(size)?;
140 let old_layout = unsafe { layout((*old).size) };
143 let Ok(old_layout) = old_layout else {
144 unreachable!();
145 };
146 unsafe { ptr::addr_of_mut!((*old).tag).write_volatile(0) };
152 let block = unsafe { realloc(old.cast(), old_layout, new_layout.size()).cast::<Block>() };
154 if block.is_null() {
155 unsafe { (*old).tag = self.tag(old) };
158 return Err(Status::OutOfMemory);
159 }
160 unsafe {
163 (*block).size = size;
164 (*block).tag = self.tag(block);
165 self.update_links((*block).previous, block, (*block).next);
166 Ok(block.cast::<u8>().add(HEADER_SIZE).cast())
167 }
168 }
169
170 fn free(&mut self, pointer: *mut c_void) -> Result<(), Status> {
171 if pointer.is_null() {
172 return Ok(());
173 }
174 let block = self.block(pointer)?;
175 unsafe {
178 let Block {
179 previous,
180 next,
181 size,
182 ..
183 } = block.read();
184 if previous.is_null() {
185 self.head = next;
186 } else {
187 (*previous).next = next;
188 }
189 if !next.is_null() {
190 (*next).previous = previous;
191 }
192 ptr::addr_of_mut!((*block).tag).write_volatile(0);
195 let Ok(layout) = layout(size) else {
196 unreachable!();
197 };
198 dealloc(block.cast(), layout);
199 }
200 Ok(())
201 }
202
203 unsafe fn update_links(&mut self, previous: *mut Block, block: *mut Block, next: *mut Block) {
205 unsafe {
206 if previous.is_null() {
207 self.head = block;
208 } else {
209 (*previous).next = block;
210 }
211 if !next.is_null() {
212 (*next).previous = block;
213 }
214 }
215 }
216}
217
218impl Drop for Heap {
219 fn drop(&mut self) {
220 while !self.head.is_null() {
221 let pointer = unsafe { self.head.cast::<u8>().add(HEADER_SIZE).cast() };
223 let Ok(()) = self.free(pointer) else {
224 unreachable!();
225 };
226 }
227 }
228}
229
230pub unsafe extern "C" fn xila_heap_allocate(
235 heap: *mut Heap,
236 size: usize,
237 allocation: *mut *mut c_void,
238) -> Status {
239 unsafe { xila_heap_reallocate(heap, ptr::null_mut(), size.max(1), allocation) }
240}
241
242pub unsafe extern "C" fn xila_heap_reallocate(
252 heap: *mut Heap,
253 pointer: *mut c_void,
254 size: usize,
255 allocation: *mut *mut c_void,
256) -> Status {
257 let Some(heap) = (unsafe { heap.as_mut() }) else {
258 return Status::InvalidArgument;
259 };
260 if allocation.is_null() {
261 return Status::InvalidArgument;
262 }
263 match heap.reallocate(pointer, size) {
264 Ok(pointer) => {
265 unsafe { allocation.write(pointer) };
266 Status::Ok
267 }
268 Err(error) => error,
269 }
270}
271
272pub unsafe extern "C" fn xila_heap_free(heap: *mut Heap, pointer: *mut c_void) -> Status {
280 let Some(heap) = (unsafe { heap.as_mut() }) else {
281 return Status::InvalidArgument;
282 };
283 heap.free(pointer)
284 .map_or_else(|error| error, |()| Status::Ok)
285}
286
287#[cfg(all(
288 test,
289 target_os = "linux",
290 any(target_arch = "x86_64", target_arch = "aarch64")
291))]
292mod tests {
293 use super::*;
294
295 #[test]
297 #[cfg_attr(miri, ignore)]
298 fn owner_reclaims_heap_after_coroutine_cancellation() {
299 let before = testing::MemoryManager::thread_allocations();
300 let mut heap = Heap::new();
301 let capability = &mut heap as *mut Heap;
302 let mut coroutine = unsafe {
303 stackful::Coroutine::new(stackful::Stack::new(64 * 1024), move || {
304 let mut block = ptr::null_mut();
305 assert_eq!(xila_heap_allocate(capability, 123, &mut block), Status::Ok);
306 assert_eq!(xila_heap_allocate(capability, 45, &mut block), Status::Ok);
307 stackful::suspend_on(core::future::pending::<()>());
308 0
309 })
310 };
311 let before_resume = testing::MemoryManager::thread_allocations();
312 let mut context = core::task::Context::from_waker(core::task::Waker::noop());
313 assert!(coroutine.resume(&mut context).is_pending());
314 let delta = testing::MemoryManager::thread_allocations().since(before_resume);
315 assert_eq!(delta.allocations(), 2);
317 assert_eq!(delta.allocated_bytes(), 123 + 45 + 2 * HEADER_SIZE);
318
319 drop(coroutine);
322 drop(heap);
323 let delta = testing::MemoryManager::thread_allocations().since(before);
324 assert_eq!(delta.net_bytes(), 0);
325 }
326}
327
328#[cfg(all(test, target_os = "linux"))]
329mod regression_tests {
330 use super::*;
331
332 #[test]
333 fn header_stays_within_the_per_block_budget() {
334 assert_eq!(size_of::<Block>(), 4 * size_of::<usize>());
337 assert!(HEADER_SIZE >= size_of::<Block>());
338 assert!(HEADER_SIZE < size_of::<Block>() + XILA_HEAP_ALIGNMENT);
339 #[cfg(target_pointer_width = "32")]
340 assert_eq!(HEADER_SIZE, 16);
341 }
342
343 unsafe fn allocate_zeroed(heap: &mut Heap, size: usize) -> *mut c_void {
346 let mut pointer = ptr::null_mut();
347 unsafe {
348 assert_eq!(xila_heap_allocate(heap, size, &mut pointer), Status::Ok);
349 pointer.cast::<u8>().write_bytes(0, size);
350 }
351 pointer
352 }
353
354 #[test]
355 fn foreign_and_interior_pointers_are_rejected() {
356 let mut a = Heap::new();
357 let mut b = Heap::new();
358 unsafe {
359 let mut p = allocate_zeroed(&mut a, 64);
360 let q = allocate_zeroed(&mut b, 64);
361 assert_eq!(xila_heap_free(&mut a, q), Status::InvalidArgument);
363 assert_eq!(
364 xila_heap_reallocate(&mut a, q, 64, &mut p),
365 Status::InvalidArgument
366 );
367 assert_eq!(
369 xila_heap_free(&mut a, p.cast::<u8>().add(1).cast()),
370 Status::InvalidArgument
371 );
372 let interior = p.cast::<u8>().add(XILA_HEAP_ALIGNMENT).cast();
374 assert_eq!(xila_heap_free(&mut a, interior), Status::InvalidArgument);
375 assert_eq!(
376 xila_heap_reallocate(&mut a, interior, 64, &mut p),
377 Status::InvalidArgument
378 );
379 assert_eq!(xila_heap_free(&mut a, p), Status::Ok);
381 assert_eq!(xila_heap_free(&mut b, q), Status::Ok);
382 }
383 }
384
385 #[test]
388 #[cfg_attr(miri, ignore)]
389 fn double_free_is_rejected() {
390 let mut heap = Heap::new();
391 unsafe {
392 let first = allocate_zeroed(&mut heap, 32);
393 let second = allocate_zeroed(&mut heap, 32);
394 assert_eq!(xila_heap_free(&mut heap, first), Status::Ok);
395 assert_eq!(xila_heap_free(&mut heap, first), Status::InvalidArgument);
396 let mut out = ptr::null_mut();
397 assert_eq!(
398 xila_heap_reallocate(&mut heap, first, 64, &mut out),
399 Status::InvalidArgument
400 );
401 assert!(out.is_null());
402 assert_eq!(xila_heap_free(&mut heap, second), Status::Ok);
403 }
404 }
405
406 #[test]
407 fn empty_heap_rejects_without_reading() {
408 let mut heap = Heap::new();
409 let wild = ptr::without_provenance_mut(0x1000_0000);
411 assert_eq!(
412 unsafe { xila_heap_free(&mut heap, wild) },
413 Status::InvalidArgument
414 );
415 }
416
417 #[test]
419 #[cfg_attr(miri, ignore)]
420 fn reallocate_failure_keeps_old_block_and_output() {
421 let mut heap = Heap::new();
422 unsafe {
423 let mut p = ptr::null_mut();
424 assert_eq!(xila_heap_allocate(&mut heap, 8, &mut p), Status::Ok);
425 p.cast::<u64>().write(0x0123_4567_89AB_CDEF);
426 let mut out = p;
427 let huge = isize::MAX as usize - 4096;
429 let status = xila_heap_reallocate(&mut heap, p, huge, &mut out);
430 assert_eq!(status, Status::OutOfMemory);
431 assert_eq!(out, p);
432 assert_eq!(p.cast::<u64>().read(), 0x0123_4567_89AB_CDEF);
433 assert_eq!(
434 xila_heap_allocate(&mut heap, usize::MAX, &mut out),
435 Status::OutOfMemory
436 );
437 assert_eq!(out, p);
438 assert_eq!(xila_heap_free(&mut heap, p), Status::Ok);
439 }
440 }
441
442 fn assert_consistent(heap: &Heap, expected: usize) {
444 let mut count = 0;
445 let mut previous = ptr::null_mut();
446 let mut block = heap.head;
447 while !block.is_null() {
448 unsafe {
450 assert_eq!((*block).previous, previous);
451 assert_eq!((*block).tag, heap.tag(block));
452 previous = block;
453 block = (*block).next;
454 }
455 count += 1;
456 }
457 assert_eq!(count, expected);
458 }
459
460 #[test]
461 fn blocks_unlink_from_any_position_and_survive_resizes() {
462 let mut heap = Heap::new();
463 let mut blocks = [ptr::null_mut(); 6];
464 for (index, block) in blocks.iter_mut().enumerate() {
465 *block = heap
466 .allocate(16 + index)
467 .unwrap_or_else(|_| panic!("test allocation failed"));
468 unsafe { block.cast::<u8>().write(index as u8) };
470 }
471 assert_consistent(&heap, 6);
472 for index in [5, 0, 3] {
475 let grown = heap.reallocate(blocks[index], 4096);
476 blocks[index] = grown.unwrap_or_else(|_| panic!("grow failed"));
477 assert_consistent(&heap, 6);
478 let shrunk = heap.reallocate(blocks[index], 1);
479 blocks[index] = shrunk.unwrap_or_else(|_| panic!("shrink failed"));
480 assert_consistent(&heap, 6);
481 assert_eq!(unsafe { blocks[index].cast::<u8>().read() }, index as u8);
483 }
484 let mut live = 6;
486 for index in [5, 0, 3, 1, 4, 2] {
487 assert_eq!(heap.free(blocks[index]), Ok(()));
488 live -= 1;
489 assert_consistent(&heap, live);
490 }
491 assert!(heap.head.is_null());
492 }
493
494 #[test]
497 #[cfg_attr(miri, ignore = "reads the freed block's header")]
498 fn stale_pointer_after_moving_reallocate_is_rejected() {
499 let mut heap = Heap::new();
500 let mut moves = 0;
501 for _ in 0..16 {
502 let keep = heap
503 .allocate(32)
504 .unwrap_or_else(|_| panic!("allocation failed"));
505 let old = heap
506 .allocate(32)
507 .unwrap_or_else(|_| panic!("allocation failed"));
508 let new = heap
509 .reallocate(old, 1 << 20)
510 .unwrap_or_else(|_| panic!("grow failed"));
511 if new != old {
512 moves += 1;
513 assert_eq!(heap.free(old), Err(Status::InvalidArgument));
514 }
515 assert_eq!(heap.free(new), Ok(()));
516 assert_eq!(heap.free(keep), Ok(()));
517 }
518 assert!(moves > 0);
521 }
522
523 #[test]
526 fn heaps_at_equal_distances_get_distinct_keys() {
527 extern crate std;
528 use std::{boxed::Box, vec::Vec};
529 struct Process {
530 _state: [u8; 48],
531 heap: Heap,
532 }
533 let mut processes = Vec::new();
534 let mut firsts = Vec::new();
535 for _ in 0..64 {
536 let mut process = Box::new(Process {
537 _state: [0; 48],
538 heap: Heap::new(),
539 });
540 let first = process.heap.allocate(24);
541 firsts.push(first.unwrap_or_else(|_| panic!("allocation failed")));
542 processes.push(process);
543 }
544 let mut keys: Vec<usize> = processes.iter().map(|process| process.heap.key).collect();
545 keys.sort_unstable();
546 keys.dedup();
547 assert_eq!(keys.len(), processes.len());
548 for (process, first) in processes.iter_mut().zip(firsts) {
549 assert_eq!(process.heap.free(first), Ok(()));
550 }
551 }
552}