-
Notifications
You must be signed in to change notification settings - Fork 11
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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
Showing
3 changed files
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters