Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to link my rust version of calloc and free to rust mbedtlsld in no_std enviroment correcly? #238

Open
yaoxin1995 opened this issue Mar 22, 2023 · 0 comments

Comments

@yaoxin1995
Copy link

yaoxin1995 commented Mar 22, 2023

Sorry @zugzwang , I can't reopen the old issue. So I create a new one.

Old issue How to link rust-mbedtls to a no_std project

I got a compilation error when I tried to link my rust calloc and free to mbedtls.

@DrTobe I have a follow up question of how to link the rust version 'calloc' and 'free' in no_std environment.

I implemented my own version of 'calloc' and 'free' as follows, and put the code in a random place of my project:

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 for some reason, I got the compilation error ld: failed to convert GOTPCREL relocation; relink with --no-relax.

Do you have any idea how to link my own version of calloc and free to mbedtls?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant