Place Functions in RAM before SystemInit with SEGGER Linker

From SEGGER Wiki
Jump to: navigation, search

This article will show how to copy a function into the RAM before the runtime init. This can be necessary for example when SystemInit needs to call code which only can be accessed from RAM e.g. to configure the flash controller.

If you are simply looking to place a generic function that is called from the application after booting up to main() you can find how to here: Place_Functions_in_RAM_with_SEGGER_Linker

How to

  • Create a function you want to place in RAM
void ExecuteInRamBeforeSysInit(void) {
  //
  // Your code goes here
  //
}
  • Open the SEGGER Linker script file and define 2 new blocks. The first block contains the function above. The second block is just a copy of the first defined block. After that it should look as follows:
define block BeforeSysInit       { symbol ExecuteInRamBeforeSysInit };
define block CopyOfBeforeSysInit { copy of block BeforeSysInit      };
  • Now we want to Place the BeforeSysInit block into the RAM and the copy of that into the FLASH.
place in RAM                     { block BeforeSysInit              };
place in FLASH                   { block CopyOfBeforeSysInit        };
  • Please also make sure to set the symbol ExecuteInRamBeforeSysInit as "do not initialize".
do not initialize                { symbol ExecuteInRamBeforeSysInit };
  • After that all changes to the linker script are finished. But we also need to edit the Startup Code for our Device because we have to make sure that the RAM function is actually copied before system init. The following code snipped copies the first defined block into the second block which was defined in the linker script before and executes it.
// Copy single function to RAM before executing SystemInit()
        ldr     r0, =ExecuteInRamBeforeSysInit
        bic     r0, r0, #1
        ldr     r1, =__CopyOfBeforeSysInit_start__
        ldr     r2, =__CopyOfBeforeSysInit_size__
        bl      memcpy

// Execute the function
        bl      ExecuteInRamBeforeSysInit
  • As a last step we have to place the function ExecuteInRamBeforeSysInit in the corresponding section as follows:
void __attribute__((section(".ExecuteInRamBeforeSysInit"))) ExecuteInRamBeforeSysInit(void) {
  //
  // Your code goes here
  //
}

Example project

The following example project will show an example implementation of such RAM function. A simple function ExecuteInRamBeforeSysInit() is created which is placed in RAM and executed.

Prerequisites

To be able to build and debug the project the following prerequisites must be met:

  • SEGGER Embedded Studio V6.34 or later

Project files

RAMCODE_Before_SysInit.zip