File tree Expand file tree Collapse file tree 3 files changed +57
-0
lines changed Expand file tree Collapse file tree 3 files changed +57
-0
lines changed Original file line number Diff line number Diff line change @@ -19,4 +19,16 @@ config RUST
19
19
help
20
20
This option enables the use of applications written in Rust.
21
21
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
+
22
34
endmenu
Original file line number Diff line number Diff line change
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 ;
Original file line number Diff line number Diff line change @@ -129,3 +129,7 @@ pub mod raw {
129
129
pub mod _export {
130
130
pub use core:: format_args;
131
131
}
132
+
133
+ /// If allocation has been requested, provide the allocator.
134
+ #[ cfg( CONFIG_RUST_ALLOC ) ]
135
+ mod alloc;
You can’t perform that action at this time.
0 commit comments