Merge #205 205: Add a heap feature to libtock-rs/core. r=gendx a=gendx This pull request adds a `heap` feature to the core crate of libtock-rs. This allows to configure the core crate to only enable and initialize the `HEAP` variable, while leaving the choice of defining a custom allocator. Indeed, the `HEAP` is conveniently initialized in the entry point with the app's heap start/size. An example use case is in OpenSK (see this pull request https://github.com/google/OpenSK/pull/123), where the custom allocator can print some debugging information about allocations & deallocation to the console - while the heap implementation is the same as the default of libtock-rs (i.e. `linked_list_allocator`). --- An alternative to this feature could be to somehow communicate the app's heap start/size to the `main` function, so that each app can initialize its own allocator when the `alloc` feature is off. Co-authored-by: Guillaume Endignoux <guillaumee@google.com>
diff --git a/core/Cargo.toml b/core/Cargo.toml index 3f1723b..bfa9570 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml
@@ -5,7 +5,8 @@ edition = "2018" [features] -alloc = [ "linked_list_allocator" ] +alloc = ["alloc_init", "linked_list_allocator"] +alloc_init = [] custom_panic_handler = [] custom_alloc_error_handler = []
diff --git a/core/src/alloc.rs b/core/src/alloc.rs index 05e9669..f971849 100644 --- a/core/src/alloc.rs +++ b/core/src/alloc.rs
@@ -4,7 +4,12 @@ use core::ptr::NonNull; use linked_list_allocator::Heap; -pub static mut HEAP: Heap = Heap::empty(); +static mut HEAP: Heap = Heap::empty(); + +#[no_mangle] +unsafe fn libtock_alloc_init(app_heap_start: usize, app_heap_size: usize) { + HEAP.init(app_heap_start, app_heap_size); +} struct TockAllocator;
diff --git a/core/src/entry_point/mod.rs b/core/src/entry_point/mod.rs index 40bdb62..2ab2351 100644 --- a/core/src/entry_point/mod.rs +++ b/core/src/entry_point/mod.rs
@@ -127,8 +127,8 @@ // Tell the kernel the new app heap break. memop::set_brk(app_heap_end as *const u8); - #[cfg(feature = "alloc")] - crate::alloc::HEAP.init(app_heap_start, app_heap_size); + #[cfg(feature = "alloc_init")] + crate::libtock_alloc_init(app_heap_start, app_heap_size); main(0, ptr::null());
diff --git a/core/src/lib.rs b/core/src/lib.rs index f451950..3bdfe5b 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs
@@ -8,6 +8,11 @@ #[cfg(any(target_arch = "arm", target_arch = "riscv32"))] mod lang_items; +#[cfg(feature = "alloc_init")] +extern "Rust" { + fn libtock_alloc_init(app_heap_start: usize, app_heap_size: usize); +} + pub mod callback; pub mod debug; pub mod memop;