moto_rt/
alloc.rs

1use core::{alloc::Layout, sync::atomic::Ordering};
2
3use crate::Result;
4use crate::RtVdsoVtable;
5use crate::into_result;
6
7#[inline(always)]
8pub fn alloc(layout: Layout) -> *mut u8 {
9    let vdso_alloc: extern "C" fn(u64, u64) -> u64 = unsafe {
10        core::mem::transmute(RtVdsoVtable::get().alloc.load(Ordering::Relaxed) as usize as *const ())
11    };
12
13    vdso_alloc(layout.size() as u64, layout.align() as u64) as usize as *mut u8
14}
15
16#[inline(always)]
17pub fn alloc_zeroed(layout: Layout) -> *mut u8 {
18    let vdso_alloc_zeroed: extern "C" fn(u64, u64) -> u64 = unsafe {
19        core::mem::transmute(
20            RtVdsoVtable::get().alloc_zeroed.load(Ordering::Relaxed) as usize as *const (),
21        )
22    };
23
24    vdso_alloc_zeroed(layout.size() as u64, layout.align() as u64) as usize as *mut u8
25}
26
27/// # Safety
28///
29/// ptr should be properly allocated.
30#[inline(always)]
31pub unsafe fn dealloc(ptr: *mut u8, layout: Layout) {
32    let vdso_dealloc: extern "C" fn(u64, u64, u64) = unsafe {
33        core::mem::transmute(
34            RtVdsoVtable::get().dealloc.load(Ordering::Relaxed) as usize as *const ()
35        )
36    };
37
38    vdso_dealloc(
39        ptr as usize as u64,
40        layout.size() as u64,
41        layout.align() as u64,
42    )
43}
44
45/// # Safety
46///
47/// ptr should be properly allocated.
48#[inline(always)]
49pub unsafe fn realloc(ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
50    let vdso_realloc: extern "C" fn(u64, u64, u64, u64) -> u64 = unsafe {
51        core::mem::transmute(
52            RtVdsoVtable::get().realloc.load(Ordering::Relaxed) as usize as *const ()
53        )
54    };
55
56    vdso_realloc(
57        ptr as usize as u64,
58        layout.size() as u64,
59        layout.align() as u64,
60        new_size as u64,
61    ) as usize as *mut u8
62}
63
64// Deallocate a buffer provided by vdso (i.e. no layout info).
65#[doc(hidden)]
66pub(crate) fn raw_dealloc(addr: u64) {
67    let vdso_dealloc: extern "C" fn(u64, u64, u64) = unsafe {
68        core::mem::transmute(
69            RtVdsoVtable::get().dealloc.load(Ordering::Relaxed) as usize as *const ()
70        )
71    };
72
73    vdso_dealloc(addr, 0, 0);
74}
75
76#[inline(always)]
77pub fn release_handle(handle: u64) -> Result<()> {
78    let vdso_release_handle: extern "C" fn(u64) -> crate::ErrorCode = unsafe {
79        core::mem::transmute(
80            RtVdsoVtable::get().release_handle.load(Ordering::Relaxed) as usize as *const (),
81        )
82    };
83
84    into_result(vdso_release_handle(handle))
85}