Skip to content

Commit

Permalink
rust: Add allocator support
Browse files Browse the repository at this point in the history
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]>
  • Loading branch information
d3zd3z committed Sep 17, 2024
1 parent 7725e34 commit 767e201
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 0 deletions.
12 changes: 12 additions & 0 deletions Kconfig
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,16 @@ config RUST
help
This option enables the use of applications written in Rust.

if RUST

config RUST_ALLOC
bool "Support an allocator in Rust code"
help
If enabled, the Rust zephyr support library will include support for
an allocator. This allocator will use the currently configured
Zephyr allocator (malloc/free). This this enabled, Rust
applications can use the `alloc` crate.

endif # RUST

endmenu
41 changes: 41 additions & 0 deletions zephyr/src/alloc.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
//! A Rust global allocator that uses the stdlib allocator in Zephyr
// This entire module is only use if CONFIG_RUST_ALLOC is enabled.
extern crate alloc;

use core::alloc::{GlobalAlloc, Layout};

use alloc::alloc::handle_alloc_error;

/// Define size_t, as it isn't defined within the FFI.
#[allow(non_camel_case_types)]
type c_size_t = usize;

extern "C" {
fn malloc(size: c_size_t) -> *mut u8;
fn free(ptr: *mut u8);
}

pub struct ZephyrAllocator;

unsafe impl GlobalAlloc for ZephyrAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
let size = layout.size();
let align = layout.align();

// The C allocation library assumes an alignment of 8. For now, just panic if this cannot
// be satistifed.
if align > 8 {
handle_alloc_error(layout);
}

malloc(size)
}

unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
free(ptr)
}
}

#[global_allocator]
static ZEPHYR_ALLOCATOR: ZephyrAllocator = ZephyrAllocator;
4 changes: 4 additions & 0 deletions zephyr/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,3 +129,7 @@ pub mod raw {
pub mod _export {
pub use core::format_args;
}

/// If allocation has been requested, provide the allocator.
#[cfg(CONFIG_RUST_ALLOC)]
mod alloc;

0 comments on commit 767e201

Please sign in to comment.