moto_rt/
alloc.rs

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