Try Embedded

Linker scripts

MEMORY, SECTIONS, the location counter, KEEP and ALIGN.

The linker needs a map of the chip

On a desktop the linker has a default memory layout. A microcontroller has fixed regions of flash and RAM at addresses only the datasheet knows, and a vector table that must sit at a precise address. The linker script (.ld) tells the linker what memory exists and which sections go where.

You rarely write one from scratch; vendors ship one per part. You will edit one to reserve space for a bootloader, add a section for persistent data, or move code into RAM, and you must be able to read one in an interview.

MEMORY: what exists

MEMORY
{
  FLASH (rx)  : ORIGIN = 0x08000000, LENGTH = 512K
  RAM   (rwx) : ORIGIN = 0x20000000, LENGTH = 128K
}

Each region has a name, attributes (r read, w write, x execute), an origin and a length. If sections assigned to a region do not fit, the link fails with "region `FLASH' overflowed by N bytes", which is exactly what you want.

SECTIONS: what goes where

ENTRY(Reset_Handler)
_estack = ORIGIN(RAM) + LENGTH(RAM);      /* initial stack pointer: top of RAM */
_min_stack_size = 0x800;

SECTIONS
{
  .isr_vector : {
    . = ALIGN(4);
    KEEP(*(.isr_vector))                  /* vector table first in flash */
    . = ALIGN(4);
  } > FLASH

  .text : {
    . = ALIGN(4);
    *(.text) *(.text*)                     /* code */
    *(.rodata) *(.rodata*)                 /* constants */
    KEEP(*(.init)) KEEP(*(.fini))
    . = ALIGN(4);
    _etext = .;
  } > FLASH

  .data : {
    . = ALIGN(4);
    _sdata = .;
    *(.data) *(.data*)
    . = ALIGN(4);
    _edata = .;
  } > RAM AT> FLASH
  _sidata = LOADADDR(.data);

  .bss (NOLOAD) : {
    . = ALIGN(4);
    _sbss = .;
    *(.bss) *(.bss*) *(COMMON)
    . = ALIGN(4);
    _ebss = .;
  } > RAM

  ._stack_check (NOLOAD) : {
    . = ALIGN(8);
    . = . + _min_stack_size;               /* fail the link if the stack would not fit */
  } > RAM
}

Reading it:

  • An output section (.text : { ... }) collects input sections from object files. *(.text*) means "the .text sections, and any section whose name starts with .text, from every file". With -ffunction-sections, each function is in its own .text.name section, which this pattern matches.
  • > FLASH sets where the section runs (VMA); AT> FLASH sets where it is stored (LMA).
  • (NOLOAD) marks a section that occupies memory but has no bytes in the image.

The location counter

. is the current address. Assigning to it moves it; reading it records it in a symbol.

  • . = ALIGN(4); rounds the counter up to a multiple of 4 so the next section starts aligned, which the word-by-word copy loop in the startup code relies on.
  • _sdata = .; defines a symbol at the current address. C code sees it as extern uint32_t _sdata; and uses &_sdata.
  • . = . + 0x800; reserves space.

KEEP

With --gc-sections, the linker removes any section nothing refers to. Nothing in the code calls the vector table, so it would be deleted, and the chip would not boot. KEEP(...) exempts a section from garbage collection. Use it for the vector table, constructor tables (.init_array) and anything else found by address rather than by reference, such as a firmware header read by a bootloader.

Common edits

Reserve space for a bootloader

The application starts after the bootloader's 32 KB:

MEMORY
{
  FLASH (rx)  : ORIGIN = 0x08008000, LENGTH = 512K - 32K
  RAM   (rwx) : ORIGIN = 0x20000000, LENGTH = 128K
}

The application must also point SCB->VTOR at 0x08008000 before enabling interrupts, or exceptions will use the bootloader's vectors.

A section for persistent settings

Reserve the last flash page so the application can store configuration without the code growing into it:

MEMORY
{
  FLASH  (rx) : ORIGIN = 0x08000000, LENGTH = 508K
  CONFIG (r)  : ORIGIN = 0x0807F000, LENGTH = 4K
  RAM   (rwx) : ORIGIN = 0x20000000, LENGTH = 128K
}
SECTIONS
{
  .config (NOLOAD) : { KEEP(*(.config)) } > CONFIG
}
__attribute__((section(".config"))) const settings_t stored_settings;

Place a buffer in a specific RAM

Parts with several RAM blocks (tightly-coupled memory, a separate DMA-capable SRAM) need buffers placed deliberately:

.dma_buffers (NOLOAD) : { *(.dma_buffers*) } > SRAM2
__attribute__((section(".dma_buffers"))) static uint8_t adc_samples[1024];

Linker symbols from C

Symbols defined in a linker script have an address but no storage. Declare them as extern and take their address; never read their "value":

#include <stdio.h>
#include <stdint.h>

/* Here ordinary arrays stand in for linker-defined symbols marking a region's bounds. */
static uint8_t region[64];
#define REGION_START (&region[0])
#define REGION_END   (&region[64])

int main(void) {
  uintptr_t size = (uintptr_t)(REGION_END - REGION_START);
  printf("region from 0x%08X to 0x%08X, %u bytes\n",
         (unsigned)(uintptr_t)REGION_START, (unsigned)(uintptr_t)REGION_END, (unsigned)size);
  return 0;
}

With real linker symbols this is extern uint8_t _sbss[], _ebss[]; and _ebss - _sbss.

Interview question: What do MEMORY and SECTIONS do in a linker script?

Answer: MEMORY declares the physical regions: name, attributes, origin and length, for example FLASH at 0x08000000 and RAM at 0x20000000. SECTIONS lists output sections, says which input sections from the object files go into each, and assigns each to a region for its run address (> RAM) and optionally a different load address (AT> FLASH). It also defines symbols such as _sdata, _ebss and _estack that the startup code uses, and controls alignment with the location counter.

Interview question: How would you change a project's linker script so the application runs after a 16 KB bootloader?

Answer: Move the FLASH region's ORIGIN up by 16 KB and reduce its LENGTH by the same amount, so the vector table and code are linked at the new address. Make sure the bootloader jumps to that address (loading the application's stack pointer and reset vector from its vector table), and have the application set SCB->VTOR to its own vector table early in start-up. Check the offset meets the VTOR alignment requirement for the number of vectors.

Build it: will the new firmware fit?

This is step 1 of the module project, the firmware of a smart electricity meter. A new feature is ready, and the question before the release is whether the image still fits the chip's flash and RAM, with room left for the stack. The linker answers it from the linker script; write the same placement so the build can explain why something does not fit.

Lab: Place sections in flash and RAM like a linker script

The chip has FLASH at 0x08000000 (FLASH_SIZE bytes) and RAM at 0x20000000 (RAM_SIZE bytes). The linker script places, in order:

  1. In flash: .isr_vector, then .text, then .rodata, each starting at the next multiple of its align.
  2. .data runs in RAM, from the start of RAM, but its initial values are loaded in flash, right after .rodata (aligned too): it takes space in both.
  3. .bss follows .data in RAM (aligned); it takes no flash.
  4. The last STACK_SIZE bytes of RAM are reserved for the stack.

Write layout(s, n, out). It fills out with each section's run address (vma) and load address (lma, the same as vma except for .data), and returns LAYOUT_OK, LAYOUT_FLASH_FULL if the flash contents end past the flash, or LAYOUT_RAM_FULL if .bss ends past the start of the stack. Sections are given in the order above, identified by name.

Going deeper

Interview question: How would you lay out flash and RAM for a bootloader and an updatable application?

Answer: Give the bootloader a fixed region at the start of flash and the application (or two slots for updates) after it, each with its own linker script and vector table. Reserve a small no-init RAM area both can see for messages across a reset, and a region for a version header the bootloader checks before jumping.

Interview question: How do you place a function in RAM using the linker script and a section attribute?

Answer: Mark the function with __attribute__((section(".ramfunc"))), and in the linker script add an output section that collects *(.ramfunc*) with its run address in RAM and load address in flash (> RAM AT> FLASH), exporting start, end and load symbols. The startup code copies it from flash to RAM like .data. Calls then execute from RAM, which is needed for flash-programming routines and can speed up hot code.

Interview question: What does --gc-sections need in order to remove unused code, and what must be protected from it?

Answer: It removes input sections that nothing references, so code must be compiled with -ffunction-sections and -fdata-sections to give each function and variable its own section. Anything found by address rather than by symbol reference, such as the vector table, constructor tables, firmware headers and data read by a bootloader, must be wrapped in KEEP() so it is not discarded.

Explain it: In your own words, explain what > RAM AT> FLASH means for the .data section.

Answer: It gives the section two addresses. > RAM is where the variables live while the program runs, their run (virtual) address, so code accesses them in RAM. AT> FLASH is where their initial values are stored in the firmware image, the load address, so the values survive power-off. The startup code uses linker-script symbols marking both locations to copy the bytes from flash to RAM before main runs.