Skip to content

Commit 767e201

Browse files
committed
rust: Add allocator support
Create a config `CONFIG_RUST_ALLOC` that will hook Rust's allocation system into the `malloc`/`free` allocator provided on Zephyr. This will allow the `alloc` crate in rust to be used. Signed-off-by: David Brown <[email protected]>
1 parent 7725e34 commit 767e201

File tree

3 files changed

+57
-0
lines changed

3 files changed

+57
-0
lines changed

Kconfig

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,4 +19,16 @@ config RUST
1919
help
2020
This option enables the use of applications written in Rust.
2121

22+
if RUST
23+
24+
config RUST_ALLOC
25+
bool "Support an allocator in Rust code"
26+
help
27+
If enabled, the Rust zephyr support library will include support for
28+
an allocator. This allocator will use the currently configured
29+
Zephyr allocator (malloc/free). This this enabled, Rust
30+
applications can use the `alloc` crate.
31+
32+
endif # RUST
33+
2234
endmenu

zephyr/src/alloc.rs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
//! A Rust global allocator that uses the stdlib allocator in Zephyr
2+
3+
// This entire module is only use if CONFIG_RUST_ALLOC is enabled.
4+
extern crate alloc;
5+
6+
use core::alloc::{GlobalAlloc, Layout};
7+
8+
use alloc::alloc::handle_alloc_error;
9+
10+
/// Define size_t, as it isn't defined within the FFI.
11+
#[allow(non_camel_case_types)]
12+
type c_size_t = usize;
13+
14+
extern "C" {
15+
fn malloc(size: c_size_t) -> *mut u8;
16+
fn free(ptr: *mut u8);
17+
}
18+
19+
pub struct ZephyrAllocator;
20+
21+
unsafe impl GlobalAlloc for ZephyrAllocator {
22+
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
23+
let size = layout.size();
24+
let align = layout.align();
25+
26+
// The C allocation library assumes an alignment of 8. For now, just panic if this cannot
27+
// be satistifed.
28+
if align > 8 {
29+
handle_alloc_error(layout);
30+
}
31+
32+
malloc(size)
33+
}
34+
35+
unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
36+
free(ptr)
37+
}
38+
}
39+
40+
#[global_allocator]
41+
static ZEPHYR_ALLOCATOR: ZephyrAllocator = ZephyrAllocator;

zephyr/src/lib.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,3 +129,7 @@ pub mod raw {
129129
pub mod _export {
130130
pub use core::format_args;
131131
}
132+
133+
/// If allocation has been requested, provide the allocator.
134+
#[cfg(CONFIG_RUST_ALLOC)]
135+
mod alloc;

0 commit comments

Comments
 (0)