Function Pointers in position independent code (-fpic) on stm32 gcc

196 views Asked by At

I am trying to write a position independent firmware for an stm32 arm-cortex microcontroller compiled with gcc.

So far I have managed to successfully launch my application firmware from an offsetted location (with respect to the one provided by the linker) using a bootloader.

Such bootloader patches the vector table and the .got section accordingly to such offset before launching the application, also uses r11 to correctly address the .got in the application firmware.

The problem arises in the application whenever I try to call a function pointer that has been initialized at compile time (so a global or static variable).

A global variable function pointer points at the address of a function within the code which is calculated in the .data section at compile time, so because of the offset, such function pointer no longer holds a valid address, and the global offset table does not seem to be used by gcc in such cases, so calling the function pointer results in hardfault!

This could be an example of the situation i am describing:

void function()
{
    //does stuff
}
// function pointer whose value is assigned at compile time
void (*function_ptr)() = &function;

void main(){
    function_ptr(); // hardfault when firmware is loaded with an offset
}

compile flags:

-fpic
-mno-pic-data-is-text-relative
-msingle-pic-base
-mpic-register=r11
-fno-jump-tables

linker flags

-pie

Is there a way to let the compiler know that the value of function pointers must be patched using the global offset table (or something like it) before jump instructions?

Edit: I think this question is related to this one but with no solution provided:

Position Independent Code on STM32 - pointers

0

There are 0 answers