Skip to main content

abi_application/
heap.rs

1use crate::Status;
2use alloc::alloc::{alloc, dealloc, realloc};
3use core::{alloc::Layout, ffi::c_void, mem::size_of, ptr};
4
5// The doc comment appears on both cfg branches: cbindgen copies it per branch.
6/// Alignment guaranteed for every allocation, including zero-length requests.
7#[cfg(target_arch = "arm")]
8pub const XILA_HEAP_ALIGNMENT: usize = 8;
9/// Alignment guaranteed for every allocation, including zero-length requests.
10#[cfg(not(target_arch = "arm"))]
11pub const XILA_HEAP_ALIGNMENT: usize = 16;
12
13/// In-band block header: a doubly linked list keeps free and resize constant
14/// time, and the tag identifies the owning heap.
15struct Block {
16    previous: *mut Block,
17    next: *mut Block,
18    size: usize,
19    // Heap key XOR block address. Zero once the block is freed; a live tag is
20    // never zero because the key is odd and block addresses are even.
21    tag: usize,
22}
23
24const HEADER_SIZE: usize = size_of::<Block>().next_multiple_of(XILA_HEAP_ALIGNMENT);
25// Four words must stay the whole per-block cost on 32-bit targets.
26#[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// Fibonacci hashing constant. Multiplying spreads nearby addresses apart, so
36// heaps whose struct and first block sit at the same distance get different keys.
37#[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
42/// Opaque native heap capability. The process owner drops it after all native
43/// execution ends. Keep ownership outside any stack that can be abandoned.
44///
45/// Native applications are trusted, so misuse detection is cheap rather than
46/// hardened. Every block starts with a header whose tag is the heap's key XOR
47/// the block address. Free and resize read the header that would precede the
48/// pointer and reject it as `InvalidArgument` unless it is aligned and its tag
49/// matches: an interior pointer or a double free (including one through a
50/// pointer that a moving resize left stale) is caught, and so is a
51/// foreign-heap pointer unless the two heaps' keys collide, which is
52/// unlikely. Like a C allocator, this reads through the pointer, so it needs
53/// readable memory below it. It cannot detect a freed block whose memory was
54/// reused by a later allocation of this heap, which then identifies the new
55/// block. Metadata lives in the block, so no operation allocates it and a
56/// shrinking resize never fails because of it.
57pub struct Heap {
58    head: *mut Block,
59    // Zero until the first allocation. Never zero afterwards.
60    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    /// Return the block that owns `pointer`, which must be non-null.
82    ///
83    /// Trusted native contract: this reads the header below `pointer` before
84    /// it can know the pointer is valid.
85    fn block(&self, pointer: *mut c_void) -> Result<*mut Block, Status> {
86        // An empty heap owns nothing, so there is no reason to read memory.
87        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        // SAFETY: Trusted native contract. The pointer comes from some
95        // allocation, so the bytes below it are readable.
96        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        // SAFETY: The layout is never zero-sized.
105        let block = unsafe { alloc(layout).cast::<Block>() };
106        if block.is_null() {
107            return Err(Status::OutOfMemory);
108        }
109        if self.key == 0 {
110            // Live blocks have distinct addresses, so mixing in the first one
111            // keeps heaps that reuse an address apart. A plain XOR would mostly
112            // depend on their distance, which is the same for every process.
113            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        // SAFETY: The block is a fresh allocation with room for the header and
117        // the head is null or a live block of this heap.
118        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        // SAFETY: The tag matched, so the header belongs to a live block of
141        // this heap that was allocated with the stored size.
142        let old_layout = unsafe { layout((*old).size) };
143        let Ok(old_layout) = old_layout else {
144            unreachable!();
145        };
146        // A moving resize frees the old block without this heap writing to it
147        // again, so clear its tag first: a stale pointer must not match.
148        // Volatile: the allocator may free the block, and a plain store just
149        // before that could be removed as dead.
150        // SAFETY: The tag matched, so the old block is live.
151        unsafe { ptr::addr_of_mut!((*old).tag).write_volatile(0) };
152        // SAFETY: The old layout is the one the block was allocated with.
153        let block = unsafe { realloc(old.cast(), old_layout, new_layout.size()).cast::<Block>() };
154        if block.is_null() {
155            // The old block is untouched apart from its tag, restored here.
156            // SAFETY: Realloc failed, so the old block is still live.
157            unsafe { (*old).tag = self.tag(old) };
158            return Err(Status::OutOfMemory);
159        }
160        // SAFETY: Realloc moved the header with the block and the neighbors
161        // are live blocks of this heap that still point at the old address.
162        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        // SAFETY: The tag matched, so the block and its neighbors are live
176        // blocks of this heap.
177        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            // A second free of this pointer then fails the tag check. Volatile,
193            // so the store before dealloc is never removed as dead.
194            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    // SAFETY: Non-null neighbors must be live, distinct blocks in this heap.
204    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            // SAFETY: The head is a live block of this heap.
222            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
230/// Allocate uninitialized bytes. A zero-size request reserves one byte.
231/// # Safety
232/// Heap must be live and exclusively accessed. Output must be aligned, writable
233/// and disjoint from the heap and its allocations.
234pub 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
242/// Resize a block, preserving its contents up to the smaller of the old and
243/// new sizes. Failure leaves the old allocation and output unchanged. Size
244/// zero frees the block and stores null. A null pointer with nonzero size
245/// allocates a new block. A pointer that this heap does not own, an interior
246/// pointer or a freed block returns `InvalidArgument`, with the same trusted
247/// native contract as [`xila_heap_free`].
248/// # Safety
249/// Heap must be live and exclusively accessed. Output must be aligned, writable
250/// and disjoint from the heap and its allocations.
251pub 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
272/// Free a block owned by this heap. Null succeeds. A pointer that this heap
273/// does not own, an interior pointer or a block that was already freed returns
274/// `InvalidArgument`. This check reads the block header through the pointer, so
275/// the pointer must at least address readable memory (the trusted native
276/// contract; see [`Heap`]).
277/// # Safety
278/// Heap must be live and exclusively accessed.
279pub 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    // Stackful switches stacks with inline assembly, which Miri cannot run.
296    #[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        // Exactly the two blocks: the heap allocates no metadata.
316        assert_eq!(delta.allocations(), 2);
317        assert_eq!(delta.allocated_bytes(), 123 + 45 + 2 * HEADER_SIZE);
318
319        // Cancelling frees the suspended stack, which holds no owner of the heap's blocks:
320        // the heap releases them when the owner drops it. Nothing is left.
321        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        // 16 B of metadata per block on 32-bit targets; two words per link
335        // pair, the size and the tag on 64-bit ones.
336        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    // Initialize the payload so that header probes through interior pointers
344    // never read uninitialized bytes.
345    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            // Foreign pointer: rejected, both heaps intact.
362            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            // Misaligned interior pointer: rejected without reading memory.
368            assert_eq!(
369                xila_heap_free(&mut a, p.cast::<u8>().add(1).cast()),
370                Status::InvalidArgument
371            );
372            // An aligned interior address is rejected by its tag.
373            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            // Nothing was disturbed.
380            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    // Reads freed memory, which is the trusted native contract of the tag
386    // check and undefined behavior as far as Miri is concerned.
387    #[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        // Not dereferenceable: an empty heap owns nothing.
410        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    // Miri aborts on the near-isize::MAX request instead of failing it.
418    #[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            // Valid layout, but no allocator can satisfy it.
428            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    // Walk the list and check every block against its neighbors.
443    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            // SAFETY: Every linked block is live.
449            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            // SAFETY: The block has at least one byte.
469            unsafe { block.cast::<u8>().write(index as u8) };
470        }
471        assert_consistent(&heap, 6);
472        // Grow and shrink the newest, the oldest and a middle block. The
473        // neighbors must follow a block that moves.
474        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            // SAFETY: The first byte survives both resizes.
482            assert_eq!(unsafe { blocks[index].cast::<u8>().read() }, index as u8);
483        }
484        // Free the head, the tail, a middle block and then the rest.
485        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    // `free(p)` after `q = realloc(p, bigger)` moved the block is the most
495    // common C double free. The stale header must not match any more.
496    #[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        // Growing a small block to 1 MiB must move it at least once, or this
519        // test checks nothing.
520        assert!(moves > 0);
521    }
522
523    // Process owners laid out one after another put each heap at the same
524    // distance from its first block. Their keys must still differ.
525    #[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}