I want to use rust-mbedtls
in my no-std
rust project. But, in no_std without libc, I need to provide my own version of the standard C function calloc()/free()
Therefore, I wrote my rust version calloc()/free()
as showed in the following so that the rust-mbedtls
can use it as C calloc and free
:
const ALIGNMENT: usize = 16;
#[no_mangle]
pub extern "C" fn calloc(number_of_elements: core::ffi::c_ulong, element_size: core::ffi::c_ulong) -> *mut core::ffi::c_void {
// TODO: CHECK number_of_elements or element_size is null
// 0 as *mut c_void;
//core::mem::transmute(0) as *mut c_void
if number_of_elements == 0 || element_size == 0 {
return core::ptr::null_mut() as *mut core::ffi::c_void;
}
let total_size = number_of_elements * element_size;
let layout = Layout::from_size_align(total_size as usize, ALIGNMENT).unwrap();
let ptr;
unsafe {
ptr = alloc(layout);
}
let pointer_addr = ptr.addr();
{
let mut allocator_tracker = ALLCATOR_RECODER.write();
allocator_tracker.memory_layout_records.insert(pointer_addr, layout.clone());
}
ptr as *mut core::ffi::c_void
}
#[no_mangle]
pub extern "C" fn free(ptr: *mut core::ffi::c_void) {
if ptr.is_null() { return }
let ptr = ptr as *mut u8;
let ptr_addr = ptr.addr();
let layout;
{
let allocator_tracker = ALLCATOR_RECODER.write();
layout = match allocator_tracker.memory_layout_records.get(&ptr_addr) {
Some(e) => e.clone(),
None => return,
};
}
unsafe{
dealloc(ptr, layout);
}
}
But I got a compilation error when I tried to link my rust calloc and free to mbedtls:
ld: failed to convert GOTPCREL relocation; relink with --no-relax
make[1]: *** [makefile:20: ../build/qkernel.bin] Error 1
make[1]: Leaving directory '/home/yaoxin/master-thesis-quark/qkernel'
make: *** [makefile:5: release] Error 2
Do you have any idea what should I do?
I also tried to add the --no-relax
flag, but I failed, see Failed to add linker flag to rust project - Stack Overflow
Could you please give me some help?