I was trying to compile a rust code for bare metal A32 and A64 toolchains which involves box pointers for accessing heap. But I saw that std support is not available for BareMetal. Can you please let me know why std support is missing for BareMetal targets in rust.
std is operating system dependent and bare metal targets are characterised by not having an operating system, so they can only support no_std. With no_std you instead have access to the core crate, which contains the operating system independent parts of std. If you can provide a memory allocator, then you can additionally use the alloc crate, which contains collections and things like Box that depend on memory allocation but not other parts of an operating system.
I have few follow up questions to the above one. Rust provides memory safety features and Concurrency, using entities like box pointers, vectors, rc, thread, sync::mpsc, std::sync::Mutex (which are provided by std) if it is executed on an os like linux.
If I have to leverage these memory safety and concurrency features of rust on baremetal environment like A32 and A64 is it possible to achieve it? as std support is missing for baremetal.
If I want to call few rust functions from c code in BareMetal environment do I get rust memory safety and concurrency features.
If you declare a global allocator with #[global_allocator] you'll be able to use Box, Vec and Rc (from those on that list). In case you cannot declare a global allocator there are crates that are no_std compatible that provide containers with a fixed maximum size (e.g. arrayvec and heapless), so you can use them without losing Rust's memory safety guarantees.
Threads as a OS feature, so they won't be available. Mpsc and Mutex also depend on OS features so you won't be able to use them. In case you're using some library/framework that implements threads on top of the baremetal features you'll still be able to use the Send and Sync traits to make a safe interface for them.
As long as the C side respects the Rust invariants (e.g. no aliasing references, references are valid etc etc) then yes.
Thanks for your reply. I was actually trying to implement your suggestion of using global_allocator for custom memory allocation on armv7baremetal target. Below is my code.
I am trying to call "allocate_memory" function from c file so that rust can allocate and deallocate the memory. Since [feature] is required for global allocator I am using nightly version of rust rather than stable as with stable build was failing at [feature] line. with nightly I am seeing below error.
Error:
error[E0463]: can't find crate for core
|
= note: the armv7a-none-eabi target may not be installed
= help: consider downloading the target with rustup target add armv7a-none-eabi
= help: consider building the standard library from source with cargo build -Zbuild-std
I have armv7a toolchain already installed.
Command used for compiling is "rustc + nightly --crate-type=lib --target armv7a-none-eabi"
Let me know if I am doing any mistake with my approach.
I was trying to use box pointer without std for a baremetal arm v7 target by defining custom allocator. However, I am seeing " error: in function rust_alloc': (.text.rust_alloc+0x54): undefined reference to alloc::raw_vec::handle_error' "
Please find my code below
C:
extern void* rust_alloc(size_t size);
extern void rust_free(void* ptr);
extern int __rust_no_alloc_shim_is_unstable = 0;
void * __rust_alloc(size_t len, size_t _align) {
// todo: proper align the pointer
return malloc(len);
}
void *__rust_alloc_zeroed(size_t len, size_t _align) {
return malloc(len);
}
void __rust_dealloc(void *ptr, size_t _size, size_t _align) {
free(ptr);
}
void __rust_alloc_error_handler(size_t size, size_t align) {
abort();
}
static int prioritythreads(int argc, const console_cmd_args *argv) {
size_t size = 16 * sizeof(int);
int* int_ptr = (int*)rust_alloc(size);
if (int_ptr != NULL) {
// Fill the allocated memory with some values
for (int i = 0; i < 16; i++) {
int_ptr[i] = i;
}
// Print the values
for (int i = 0; i < 16; i++) {
printf("Value %d: %d\n", i, int_ptr[i]);
}
// Free the allocated memory
rust_free(int_ptr);
} else {
printf("Failed to allocate memory.\n");
}
return 0;
}
Rust code:
#![no_std]
#![feature(lang_items)]
#![feature(default_alloc_error_handler)]
extern crate alloc;
use alloc::boxed::Box;
use alloc::vec;
use alloc::alloc::{GlobalAlloc, Layout};
use core::ptr::null_mut;
use core::panic::PanicInfo;
pub struct Dummy;
unsafe impl GlobalAlloc for Dummy {
unsafe fn alloc(&self, _layout: Layout) -> *mut u8 {
null_mut()
}
unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) {
panic!("dealloc should be never called")
}
}
#[no_mangle]
pub extern "C" fn rust_alloc(size: usize) -> *mut i32 {
let mut vec=Box::new(vec![0;size]);
let ptr =vec.as_mut_ptr();
core::mem::forget(vec);
ptr
}
#[no_mangle]
pub extern "C" fn rust_free(ptr:*mut i32, size:usize) {
if !ptr.is_null(){
unsafe {let _ = Box::from_raw(core::slice::from_raw_parts_mut(ptr,size));};
}
}
#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
loop {}
}
#[lang = "eh_personality"]
extern "C" fn eh_personality() {}
I am not sure how to fix this error. Can anybody please provide insights on this.
Instead of manually defining functions like __rust_alloc and globals like __rust_no_alloc_shim_is_unstable you should use #[global_allocator] static ALLOC: MyGlobalAlloc = MyGlobalAlloc; where MyGlobalAlloc is the type for which you implemented the GlobalAlloc trait. This will define all those functions and globals for you and doesn't depend on unstable implementation details.
Also your rust_alloc and rust_free methods are incorrect. You are creating a Box<Vec<u8>> but then freeing a Box<[u8]>. You probably want to use the alloc::alloc::alloc and alloc::alloc::dealloc methods directly.
I have implemented global allocator with static and removed all the functions related to alloc_shim etc but still I see
"n function alloc::alloc::exchange_malloc': TestRust.23a4d893b5ab48ca-cgu.0:(.text._ZN5alloc5alloc15exchange_malloc17h4da6d21f615b0a75E+0x0): undefined reference to __rust_no_alloc_shim_is_unstable'
arm-none-eabi-ld: TestRust.23a4d893b5ab48ca-cgu.0:(.text._ZN5alloc5alloc15exchange_malloc17h4da6d21f615b0a75E+0x8): undefined reference to __rust_no_alloc_shim_is_unstable' arm-none-eabi-ld: TestRust.23a4d893b5ab48ca-cgu.0:(.text._ZN5alloc5alloc15exchange_malloc17h4da6d21f615b0a75E+0x14): undefined reference to alloc::alloc::handle_alloc_error'
arm-none-eabi-ld: ./build-qemu-virt-arm32-test/app/prioritythreads.mod.o: in function rust_free': (.text.rust_free+0x20): undefined reference to core::panicking::panic'"
C code:
extern void* rust_alloc(size_t size);
extern void rust_free(void* ptr);
static int prioritythreads(int argc, const console_cmd_args *argv) {
size_t size = 16 * sizeof(int);
int* int_ptr = (int*)rust_alloc(size);
if (int_ptr != NULL) {
// Fill the allocated memory with some values
for (int i = 0; i < 16; i++) {
int_ptr[i] = i;
}
// Print the values
for (int i = 0; i < 16; i++) {
printf("Value %d: %d\n", i, int_ptr[i]);
}
// Free the allocated memory
rust_free(int_ptr);
} else {
printf("Failed to allocate memory.\n");
}
return 0;
}
rust code:
#![no_std]
#![feature(lang_items)]
#![feature(default_alloc_error_handler)]
extern crate alloc;
use alloc::boxed::Box;
use alloc::alloc::{GlobalAlloc, Layout};
use core::ptr::null_mut;
use core::panic::PanicInfo;
pub struct Dummy;
unsafe impl GlobalAlloc for Dummy {
unsafe fn alloc(&self, _layout: Layout) -> *mut u8 {
null_mut()
}
unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) {
panic!("dealloc should be never called")
}
}
#[global_allocator]
static GLOBAL_ALLOCATOR: Dummy = Dummy;
#[no_mangle]
pub extern "C" fn rust_alloc(size: usize) -> *mut i32 {
let mut data=Box::new(42);
let ptr:*mut i32 =&mut *data;
core::mem::forget(data);
ptr
}
#[no_mangle]
pub extern "C" fn rust_free(ptr:*mut i32, size:usize) {
if !ptr.is_null(){
unsafe {
let _ = Box::from_raw(core::slice::from_raw_parts_mut(ptr,size));};
}
}
#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
loop {}
}
#[lang = "eh_personality"]
extern "C" fn eh_personality() {}
Can you let me know how to get rid of those errors
Hii Bjorn3, if we use " // fetch only .rs files from all the source files
MODULE_RSSRCS := $(filter %.rs,$(MODULE_SRCS))
MODULE_RSOBJS := $(call TOBUILDDIR,$(patsubst %.rs,%.rs.o,$(MODULE_RSSRCS)))
We are building for armv7 target with no_std
RC --> rustc " for above code then in function alloc::alloc::exchange_malloc': undefined reference to __rust_no_alloc_shim_is_unstable', undefined reference to __rust_no_alloc_shim_is_unstable', undefined reference to alloc::alloc::handle_alloc_error'. occurs.
Try --crate-type=staticlib instead of --crate-type=lib and make sure you put all rust source files in a single crate and only pass the root of this crate to rustc. The output of --crate-type=lib is not guaranteed to be anything that you can directly pass to a linker. It misses all crate dependencies (like libcore and liballoc), while --crate-type=staticlib produces a bundle consisting of the local crate together with all it's dependencies and some extra object files defining for example __rust_no_alloc_shim_is_unstable.