Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 37 ยท Memory, Registers and Peripherals

Startup Code, Linker Sections and the Stack

See how a firmware image is laid out: text, rodata, data, bss, the vector table, a linker script, startup code, stack growth, overflow and measuring stack usage.

When your firmware starts, nothing prepares the C world for you. The chip comes out of reset with RAM full of random bits and the stack pointer just loaded from a table. Before main() can use a global variable or call a function, someone must put every byte in its place. That someone is the startup code, guided by the linker script, which decides where each part of your program lives.

This lesson takes a program apart: the sections the compiler creates, the linker script that places them, the startup code that initializes RAM, and the stack and heap that share the leftover space. Then you simulate each step, so the numbers in a map file stop being mysterious.

Sections of a program

The compiler sorts everything in your source into sections:

Section Contents Lives in
.isr_vector interrupt vector table flash, at the very start
.text machine code flash
.rodata const data, string literals flash
.data globals and statics with non-zero initial values RAM at run time, initial image in flash
.bss globals and statics initialized to zero (or not at all) RAM only
stack local variables, return addresses RAM, top end
heap malloc memory RAM, grows toward the stack
C
const char *banner = "boot";         // pointer in .data, string "boot" in .rodata
int counter = 5;                      // .data: needs initial value 5 stored in flash
int table[100];                       // .bss: only RAM, no flash space for the zeros
static const uint16_t lut[4] = {1,2,3,4};   // .rodata: flash
void f(void) { int local; static int calls; }   // local: stack; calls: .bss

The reason for .bss: storing 100 zeros in flash would waste space, so the image only records "this region of RAM must be zeroed". The .data section is the opposite: the initial values must exist in flash, so a .data variable costs flash and RAM.

The linker script

The linker needs to know the memory regions of your chip and where to put each section. A minimal script for a chip with 64 KB flash at 0x0800_0000 and 20 KB RAM at 0x2000_0000 (read-only listing):

TEXT
MEMORY
{
  FLASH (rx)  : ORIGIN = 0x08000000, LENGTH = 64K
  RAM   (rwx) : ORIGIN = 0x20000000, LENGTH = 20K
}

_estack = ORIGIN(RAM) + LENGTH(RAM);        /* top of RAM: initial stack pointer */
_Min_Heap_Size  = 0x200;
_Min_Stack_Size = 0x400;

SECTIONS
{
  .isr_vector : { KEEP(*(.isr_vector)) } > FLASH
  .text       : { *(.text*) *(.rodata*) _etext = .; } > FLASH
  _sidata = LOADADDR(.data);                 /* where .data's initial values sit in flash */
  .data       : { _sdata = .; *(.data*) _edata = .; } > RAM AT> FLASH
  .bss        : { _sbss = .;  *(.bss*) *(COMMON) _ebss = .; } > RAM
  ._user_heap_stack : { . = ALIGN(8); . += _Min_Heap_Size; . += _Min_Stack_Size; } > RAM
}

Key ideas:

  • > FLASH and > RAM choose the region; AT> FLASH says ".data lives in RAM at run time but its initial image is stored in flash".
  • Symbols like _sdata, _edata, _sbss, _ebss, _sidata and _estack are not variables; they are addresses the linker defines, which the startup code uses.
  • The last block reserves heap and stack space so the build fails (rather than the product) when RAM is over-committed.

Startup code

The vendor's startup file (startup_stm32f446xx.s, or C code on newer templates) provides the vector table and Reset_Handler. In C it looks like this (read-only; it needs the linker symbols):

C
extern uint32_t _sidata, _sdata, _edata, _sbss, _ebss, _estack;

void Reset_Handler(void) {
    uint32_t *src = &_sidata, *dst = &_sdata;
    while (dst < &_edata) *dst++ = *src++;        // copy .data from flash
    for (dst = &_sbss; dst < &_ebss; ) *dst++ = 0; // zero .bss
    SystemInit();                                  // clocks, FPU enable
    __libc_init_array();                           // static constructors (C++)
    main();
    for (;;) { }                                   // main must never return
}

__attribute__((section(".isr_vector"), used))
void (*const vector_table[])(void) = {
    (void (*)(void))&_estack,   // initial stack pointer
    Reset_Handler,
    NMI_Handler, HardFault_Handler, /* ... */
};

Here is a runnable simulation of exactly these two loops. An array stands in for RAM; indices stand in for the linker symbols.

C Simulated Reset_Handler: copy .data, zero .bss

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The low hex digit of each word is shown for brevity: A is garbage, 5, 4, D, 8 are the copied values, 0 is zeroed .bss.

The stack

The stack holds a stack frame for each active function call: the return address, saved registers, local variables and parameters passed in memory. On ARM (and most CPUs) the stack grows downward: the first call pushes at the highest address, each deeper call uses lower addresses. The stack pointer starts at _estack (the top of RAM) and moves down. The heap grows upward from the end of .bss, so the two grow toward each other with free space between them:

flowchart TB
    A["High addresses: _estack<br/>(top of RAM)"] --> B["Stack<br/>grows down"]
    B --> C["free space"]
    C --> D["Heap<br/>grows up"]
    D --> E[".bss"]
    E --> F[".data"]
    F --> G["Low addresses: RAM start"]

If the stack grows past the free space it overwrites the heap, .bss or .data, corrupting variables in unpredictable ways. This is stack overflow, one of the nastiest embedded bugs because the crash may occur far from the cause. With no MMU there is no segmentation fault to catch it.

What consumes stack:

  • deep or recursive calls (recursion is usually avoided or bounded),
  • large local arrays (char buf[1024] inside a function),
  • interrupt handlers, which push a frame (8 words on Cortex-M) on top of whatever was running,
  • printf and similar library functions, which can need hundreds of bytes,
  • RTOS: each task has its own stack that you must size.

Measuring stack usage

Three techniques work on real chips:

  1. Static analysis: GCC's -fstack-usage writes the stack use of each function, and tools can sum the worst call chain (not through function pointers or recursion).
  2. Painting: fill the stack region with a pattern (0xA5A5A5A5) at startup, run the program under heavy load, and later find how far the pattern was overwritten (the high-water mark).
  3. Guard regions: the Cortex-M33 has stack limit registers, and the MPU can make a guard region fault when touched. RTOSes check a "canary" word at the stack bottom on each context switch.

The simulation below runs real recursion on your PC's stack and compares addresses. The stack grows downward on x86-64 as well, and the difference between two depths is proportional to the frame size.

C The stack grows downward

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Detecting overflow with a canary

A cheap defence is to place a known canary value at the end of the stack region and check it periodically (for example in the idle loop or on every RTOS context switch). If it has changed, the stack came too close.

C Stack canary and high-water mark

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The heap, briefly

The heap exists only if you call malloc. Most embedded rules (MISRA, many company standards) forbid or restrict it after initialization because it can fragment, its run time is not predictable and failure at run time (returning NULL) is hard to handle. If you use malloc, do it once at startup. The next lesson shows alternatives: Static Allocation and Memory Pools. Linker scripts often reserve a heap size; setting it to 0 removes the temptation.

Reading the map file

The linker can write a map file (-Wl,-Map=firmware.map) listing every symbol with its address and size. Search it to find what is eating your flash: a single printf with floating-point support can add 10 KB. The size output from the workflow lesson summarizes the same data by section, and -Wl,--gc-sections together with -ffunction-sections removes unused code.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does an initialized global like int x = 5; cost both flash and RAM?

    The variable lives in RAM (.data), but RAM is empty at power-up so the initial image must be kept in flash.
  2. 2. What is .bss for?

    The startup code simply zeroes the .bss range, so no initial values are stored.
  3. 3. Which direction does the stack grow on ARM Cortex-M?

    The stack pointer starts at the top of RAM (_estack) and decreases as functions are called.
  4. 4. What is a good way to find how much stack your program really uses?

    The high-water mark technique measures actual use, including interrupts.

Summary

  • The compiler sorts code and data into sections: .text and .rodata in flash, .data (initial values in flash, variables in RAM), .bss (RAM only), plus stack and heap.
  • The linker script defines memory regions, places sections and exports symbols like _sdata and _estack.
  • Startup code copies .data, zeroes .bss, initializes the system and calls main().
  • The stack grows down, the heap up; overflow silently corrupts memory, so size, measure (painting, -fstack-usage) and guard the stack.
  • Avoid dynamic allocation after startup; use the map file to see where flash and RAM go.

Next: Static Allocation and Memory Pools