Skip to content

Commit 9b8a432

Browse files
committed
zephyr: mempool implementation of GlobalAlloc
Allow a Rust app to bind the #[global_allocator] to a chosen Zephyr mempool. This overrides the default of k_malloc in libstd, which allows libstd and Box to work in user space.
1 parent 83a7478 commit 9b8a432

File tree

4 files changed

+39
-0
lines changed

4 files changed

+39
-0
lines changed

rust-app/zephyr-sys/wrapper.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
#include <rust_syscall_macros.h>
66
#include <kernel.h>
7+
#include <misc/mempool.h>
78
#include <device.h>
89
#include <uart.h>
910

rust-app/zephyr/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ extern crate derive_more;
66

77
pub mod device;
88
pub mod kobj;
9+
pub mod mempool;
910
pub mod mutex;
1011
pub mod semaphore;
1112
pub mod thread;

rust-app/zephyr/src/mempool.rs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
use core::alloc::{GlobalAlloc, Layout};
2+
3+
pub use zephyr_sys::raw::sys_mem_pool;
4+
5+
pub struct MempoolAlloc(pub &'static sys_mem_pool);
6+
7+
unsafe impl Send for MempoolAlloc {}
8+
unsafe impl Sync for MempoolAlloc {}
9+
10+
unsafe impl GlobalAlloc for MempoolAlloc {
11+
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
12+
zephyr_sys::raw::sys_mem_pool_alloc(self.0 as *const _ as *mut _, layout.size()) as *mut _
13+
}
14+
15+
unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
16+
zephyr_sys::raw::sys_mem_pool_free(ptr as *mut _)
17+
}
18+
}
19+
20+
/// Assign a Zephyr sys mem pool as #[global_allocator]
21+
///
22+
/// This should be defined with SYS_MEM_POOL_DEFINE and granted permission to any
23+
/// Rust threads that need to use libstd or alloc.
24+
#[macro_export]
25+
macro_rules! global_sys_mem_pool {
26+
($pool:ident) => {
27+
extern "C" {
28+
#[no_mangle]
29+
static $pool: $crate::mempool::sys_mem_pool;
30+
}
31+
32+
#[global_allocator]
33+
static GLOBAL: $crate::mempool::MempoolAlloc =
34+
$crate::mempool::MempoolAlloc(unsafe { &$pool });
35+
};
36+
}

syscall_thunk.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#define __ZEPHYR_DEFINE_SYSCALLS__
22
#include <rust_syscall_macros.h>
33
#include <kernel.h>
4+
#include <misc/mempool.h>
45
#include <device.h>
56
#include <uart.h>

0 commit comments

Comments
 (0)