axlibc/
malloc.rs

1//! Provides the corresponding malloc(size_t) and free(size_t) when using the C user program.
2//!
3//! The normal malloc(size_t) and free(size_t) are provided by the library malloc.h, and
4//! sys_brk is used internally to apply for memory from the kernel. But in a unikernel like
5//! `ArceOS`, we noticed that the heap of the Rust user program is shared with the kernel. In
6//! order to maintain consistency, C user programs also choose to share the kernel heap,
7//! skipping the sys_brk step.
8
9use alloc::alloc::{alloc, dealloc};
10use core::alloc::Layout;
11use core::ffi::c_void;
12
13use crate::ctypes;
14
15struct MemoryControlBlock {
16    size: usize,
17}
18
19const CTRL_BLK_SIZE: usize = core::mem::size_of::<MemoryControlBlock>();
20
21/// Allocate memory and return the memory address.
22///
23/// Returns 0 on failure (the current implementation does not trigger an exception)
24#[unsafe(no_mangle)]
25pub unsafe extern "C" fn malloc(size: ctypes::size_t) -> *mut c_void {
26    // Allocate `(actual length) + 8`. The lowest 8 Bytes are stored in the actual allocated space size.
27    // This is because free(uintptr_t) has only one parameter representing the address,
28    // So we need to save in advance to know the size of the memory space that needs to be released
29    let layout = Layout::from_size_align(size + CTRL_BLK_SIZE, 8).unwrap();
30    unsafe {
31        let ptr = alloc(layout).cast::<MemoryControlBlock>();
32        assert!(!ptr.is_null(), "malloc failed");
33        ptr.write(MemoryControlBlock { size });
34        ptr.add(1).cast()
35    }
36}
37
38/// Deallocate memory.
39///
40/// (WARNING) If the address to be released does not match the allocated address, an error should
41/// occur, but it will NOT be checked out. This is due to the global allocator `Buddy_system`
42/// (currently used) does not check the validity of address to be released.
43#[unsafe(no_mangle)]
44pub unsafe extern "C" fn free(ptr: *mut c_void) {
45    if ptr.is_null() {
46        return;
47    }
48    let ptr = ptr.cast::<MemoryControlBlock>();
49    assert!(ptr as usize > CTRL_BLK_SIZE, "free a null pointer");
50    unsafe {
51        let ptr = ptr.sub(1);
52        let size = ptr.read().size;
53        let layout = Layout::from_size_align(size + CTRL_BLK_SIZE, 8).unwrap();
54        dealloc(ptr.cast(), layout)
55    }
56}