cancel
Showing results for 
Search instead for 
Did you mean: 

Position independent code for STM32F4

squeamz
Associate
Posted on July 06, 2015 at 04:18

MCU: STM32F4 (ARM Cortex M4)

Build environment: arm-none-eabi-gcc 4.8.4 20140725

My goal is to build an image that can be run from any properly-aligned offset in internal flash.

My ideal scenario is for the code would be position-independent, but the data and bss sections to be located at fixed offsets in SRAM.  Function pointers would need to be called via the GOT, of course.  Unfortunately, I wasn't able to find a combination of gcc flags that would let me generate code in this way.  The generated code always seemed to assume that data variables could be found at an offset relative to the program counter.  This assumption fails because the code can run from a variety of locations, but the data is always at a fixed memory address.

The next best thing I found is the following combination of flags:

 

   # Generate position independent code.

    -fPIC

    # Access bss via the GOT.

    -mno-pic-data-is-text-relative

    # GOT is not PC-relative; store GOT location in a register.

    -msingle-pic-base

    # Store GOT location in r9.

    -mpic-register=r9

The problem I'm having with this set of build flags is that r9 seems to get clobbered when the processor transitions from thread mode to handler mode.  This leads a hard fault when my exception handler attempts to read something from the GOT.  I tried using r10 instead of r9, but I observed the same behavior.

So, my questions are as follows:

1. Does anyone know of a way to get gcc to generate position independent code that assumes fixed addresses for data and bss?

2. If not, any suggestions for using -msingle-pic-base safely in handler mode?

All input is greatly appreciated.
2 REPLIES 2
squeamz
Associate
Posted on July 06, 2015 at 23:49

Just a quick follow up-

I got it working with the single-pic-base solution.  I was wrong about L9 getting overwritten by handler mode; it was my own code doing the overwriting!

If anyone knows of a way to generate position-independent code with fixed data and bss, I would still be interested in hearing about it.

Thanks

Posted on July 07, 2015 at 01:48

I don't think the Linux .ELF model is a good one here. I'd probably just look to build the code without absolute code references, and then fix up the vector table entries.

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..