Copy function to RAM and call it with function pointer

Hello,

I am trying to copy the function to RAM and then call it using a function pointer like below:

It forced a system restart and it should have encountered an error.

Can you please help me deal with it? Thanks in advance!

uint8_t ram_func(uint8_t data_in)
{
  data_in++;
  return data_in;
}
/*---------------------------------------------------------------*/
int main() {
    typedef uint8_t (*func_ptr)(uint8_t);
    uint8_t func_buffer[256];
    memset(func_buffer, 0, 256);
    // Copy the machine code of func into func_buffer
    memcpy(&func_buffer, (uint8_t*)ram_func, 255);

    // Create a function pointer and cast the buffer address to it
    func_ptr fp = (func_ptr)func_buffer;

    // Call the function through the function pointer
    uint8_t data_out = fp(3);

    printf("Result = %d\n", data_out);
    return 0;
}

Parents
  • Hi,

    We do not use position independent code, so copying out a function to a different location will not work. If you want a function to reside in RAM, you need to tell the compiler to place it there (and then all offsets and jumps etc. will be correct for that position). You can read more about how ths is done under Code And Data Relocation.

  • Thanks Einar for your prompt reply!
    As I understood, the Code And Data Relocation example you provided is actually allocating the function in the Flash by the liner and calling it in the main file.

    I attempt to call the function directly from RAM buffers (copying the machine code of function) in the runtime without changing the Liner sections architecture. Do you think we have to use the position independent code for the compiler itself to specify the location where I copy the function in RAM on the basis of nRF5280 DK?

    Thanks again for your support!

  • Hi,

    I am sorry, the example I linked to was a bad one. You can refer to zephyr/tests/application_development/code_relocation. This demonstrates relocation in different wayt, includign to RAM. It runs out of the box on the nRF52840.

    There is no need for position independent code, the point is that you instruct the build system to place the function in RAM (it is then copied there automatically during startup).

Reply
  • Hi,

    I am sorry, the example I linked to was a bad one. You can refer to zephyr/tests/application_development/code_relocation. This demonstrates relocation in different wayt, includign to RAM. It runs out of the box on the nRF52840.

    There is no need for position independent code, the point is that you instruct the build system to place the function in RAM (it is then copied there automatically during startup).

Children
No Data
Related