Skip to content
systemcoding.dev
Embedded

The Complete Guide to Cortex-M Startup Code and Linker Scripts

Build a Cortex-M boot path from scratch: vector table, reset handler, linker script, .data and .bss, heap, stack, constructors and debugging, with a Makefile.

29 min read
Summarize in AI
Flat illustration of source code passing through a compiler and linker into a binary, with the Arm, GNU and C logos.

Every Cortex-M program starts the same way, and almost every beginner project hides the way behind a vendor-generated folder of files. The startup file and the linker script decide where your code lives in flash, where your variables live in RAM, how the first instruction gets to run, and what happens when something goes wrong before main. When they are right nobody looks at them. When they are wrong the board does nothing, and there is no error message to read. This guide builds both from nothing, for a Cortex-M4 on an STM32F407, with the Arm GNU Toolchain 13.2 (arm-none-eabi-gcc), GNU binutils 2.42 and newlib 4.3. By the end you will have a small project that boots, initialises its variables, runs C++ constructors, allocates from a bounded heap, catches faults and can be read with a debugger and a map file. Each section adds one piece, and each piece is also useful on its own.

The guide is for the first time you meet these files. It defines every term, and it goes as far as the cases that matter in real projects: relocating the vector table, running code from RAM and reading a map. It does not cover a particular vendor's HAL, and it does not cover Cortex-A, which boots differently. The clock setup that follows boot is the subject of the next cluster in this series, so the program here runs at the 16 MHz reset clock.

What the toolchain has to produce

A microcontroller has no operating system and no loader. When power comes up, the CPU reads memory at fixed places and starts running whatever it finds. Your build has to leave the right bytes in the right places. That takes three steps, and understanding them removes most of the mystery:

StepToolInputOutput
Compilearm-none-eabi-gcc -c.c and .S files.o object files with sections
Linkarm-none-eabi-gcc (calls ld).o files and a linker script.elf, one file with addresses assigned
Convertarm-none-eabi-objcopy.elf.bin or .hex, raw bytes for the flash tool

An object file groups its content into sections. The compiler puts machine code in .text, constants in .rodata, initialised variables in .data and zero-initialised variables in .bss. The linker script tells the linker which memory each kind of section goes to and in what order. The ELF output records both what is stored where and what each section's run address is; the debugger and flash tool read it.

Two addresses matter for every section, and their difference is the key to this whole guide. The load address (LMA) is where the bytes sit in the stored image, in flash. The run address (VMA) is where the code expects them when it runs. For code in flash the two are equal. For .data they are not: the bytes are stored in flash but the variables live in RAM, so something must copy them. That something is the reset handler.

The memory map you are targeting

The STM32F407VG has the following regions, from the reference manual RM0090 and the datasheet. The addresses are the part's, so another chip has different ones.

RegionAddressSizeUse
Flash0x080000001 MiBCode and constants
SRAM1 and SRAM20x20000000128 KiBVariables, heap, stack
CCM RAM0x1000000064 KiBFast CPU-only RAM, unused here
Peripherals0x40000000Registers
Cortex-M system0xE0000000NVIC, SysTick, SCB

After reset the flash is also visible at address zero, because the boot configuration aliases it there, and that alias is how the core finds your vector table. Everything else in this guide is arranging for the right bytes to be at the right addresses within these regions.

The first two words: what the core does at reset

The Armv7-M architecture defines what a Cortex-M does on reset, and it is short. The core reads two 32-bit words from the beginning of the vector table at address zero:

AddressWordThe core loads it into
0x00000000Initial main stack pointerSP (MSP)
0x00000004Reset vectorPC, then runs

Then it executes instructions from the reset vector address. It runs no code of its own before that, so everything else, including the initialisation of RAM, is the job of your first function.

The reset vector's lowest bit must be 1. Cortex-M executes only Thumb instructions, and the architecture signals the instruction set in bit 0 of branch targets; the core clears the bit when it loads the PC. A table entry with bit 0 clear faults immediately. In C you do not write the bit: a function pointer to a Thumb function already has it set, so the compiler and linker do it.

The Arm Cortex-M4 Devices Generic User Guide describes the exception model, and it is the primary source for this section.

The vector table in C

The table holds the stack pointer, the reset vector and the handlers for exceptions and interrupts. Declare it as a constant array in its own section, so the linker script can place it first. This version includes the 15 system entries and a few STM32F407 interrupts; the full device list has 82. Add the others from the vendor's header when you need them.

startup.cc
#include <stdint.h>

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

extern int  main(void);
extern void SystemInit(void);
extern void __libc_init_array(void);

void Reset_Handler(void);
void Default_Handler(void);

#define WEAK_DEFAULT(name) \
	void name(void) __attribute__((weak, alias("Default_Handler")))

WEAK_DEFAULT(NMI_Handler);
WEAK_DEFAULT(HardFault_Handler);
WEAK_DEFAULT(MemManage_Handler);
WEAK_DEFAULT(BusFault_Handler);
WEAK_DEFAULT(UsageFault_Handler);
WEAK_DEFAULT(SVC_Handler);
WEAK_DEFAULT(DebugMon_Handler);
WEAK_DEFAULT(PendSV_Handler);
WEAK_DEFAULT(SysTick_Handler);
WEAK_DEFAULT(WWDG_IRQHandler);
WEAK_DEFAULT(TIM2_IRQHandler);
WEAK_DEFAULT(USART2_IRQHandler);

__attribute__((section(".isr_vector"), used))
void (*const vector_table[])(void) = {
	(void (*)(void))(&_estack),   /* 0: initial stack pointer */
	Reset_Handler,                /* 1 */
	NMI_Handler,                  /* 2 */
	HardFault_Handler,            /* 3 */
	MemManage_Handler,            /* 4 */
	BusFault_Handler,             /* 5 */
	UsageFault_Handler,           /* 6 */
	0, 0, 0, 0,                   /* 7 to 10: reserved */
	SVC_Handler,                  /* 11 */
	DebugMon_Handler,             /* 12 */
	0,                            /* 13: reserved */
	PendSV_Handler,               /* 14 */
	SysTick_Handler,              /* 15 */
	WWDG_IRQHandler,              /* 16: IRQ 0 */
};

Some details are worth a pause.

Weak aliases. WEAK_DEFAULT(SysTick_Handler) declares a weak symbol with the same address as Default_Handler. Weak means "use this only if nobody else defines the name". When your program later defines void SysTick_Handler(void), the linker prefers that strong definition, and the table entry points at your function with no registration step. When you never write a handler, the entry points at Default_Handler, so an unexpected interrupt lands in a known place instead of in random memory.

The first entry is not a function. The cast of &_estack to a function pointer is how the table is typed as one array; the value is the address of the top of RAM, a plain number. _estack is defined in the linker script, and the & takes its address, which is the value of the symbol.

**section(".isr_vector") and used.** The section name is a label the linker script refers to. used tells the compiler to keep the array although nothing in C references it.

The table has only two jobs at reset, to name the stack and the first function, and one job later, to route interrupts. A deeper treatment of how the core finds the table and where it may live is in the vector table post of this cluster.

The reset handler

The reset handler is the first C function that runs. By the time main starts, the language promises that initialised globals hold their values and that zero-initialised globals are zero. RAM has neither at power-on, so the reset handler creates both, then calls the setup functions and main.

startup.cc
void Reset_Handler(void)
{
	uint32_t *src = &_sidata;
	uint32_t *dst = &_sdata;

	while (dst < &_edata)
		*dst++ = *src++;

	for (dst = &_sbss; dst < &_ebss; )
		*dst++ = 0;

	SystemInit();
	__libc_init_array();
	main();

	for (;;)
		;
}

void Default_Handler(void)
{
	for (;;)
		;
}

The first loop copies the .data image from flash (_sidata) to its RAM home (_sdata to _edata), one 32-bit word at a time. The second loop writes zeros over .bss. SystemInit is the vendor's function for early hardware setup (on the F4 it enables the FPU and sets the vector table location; the project can provide an empty one). __libc_init_array is newlib's routine that runs C++ constructors and functions marked constructor, covered below. The loop after main is a safety net if main returns.

Two traps lie here. The first is that the compiler may turn the clearing loop into a call to memset, which depends on a runtime that is not initialised yet; compile this file with -fno-tree-loop-distribute-patterns or add __attribute__((optimize("no-tree-loop-distribute-patterns"))) to the function. The second is that the reset handler must not use any global before the loops finish. A function called here that reads a global may find garbage.

The boundary symbols (_sidata and the others) are not variables in C. The linker defines them as addresses, and the C code takes their address with &. Reading the symbol's value would read whatever bytes happen to sit at that address.

The linker script, part one: memory and symbols

A linker script is written in GNU ld's own language. It has two big blocks: MEMORY, which declares the regions, and SECTIONS, which places things in them. Start with the regions and a few symbols:

link.ldText
ENTRY(Reset_Handler)

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

_estack          = ORIGIN(RAM) + LENGTH(RAM);
_Min_Heap_Size   = 0x1000;
_Min_Stack_Size  = 0x1000;

MEMORY gives each region a name, attributes (r readable, w writable, x executable, used by the linker to place sections you did not mention) and a position. If the content you place in a region is bigger than its LENGTH, the link fails with a message such as region 'FLASH' overflowed by 312 bytes. That check is one of the most useful things a linker script gives you for free.

ENTRY names the program's entry symbol. The core ignores it, because the reset vector decides where execution starts, but debuggers and tools use it, and it also protects Reset_Handler from being garbage collected.

_estack is the end of RAM, one byte past the last valid address, which is where a full-descending stack begins. A full-descending stack is how Cortex-M works: the stack pointer starts at the top and moves toward lower addresses as you push, and the first push stores at _estack - 4.

The linker script, part two: placing code

The SECTIONS block lists output sections, in order. The first one must be the vector table, because the core reads it from the start of flash:

link.ldText
SECTIONS
{
  .isr_vector :
  {
    . = ALIGN(4);
    KEEP(*(.isr_vector))
    . = ALIGN(4);
  } > FLASH

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

The period . is the location counter, the current address within the section. ALIGN(4) rounds it up to a multiple of four. Each output section is a name, a colon and a block that lists input patterns: *(.text*) means every section whose name starts with .text from every input file (the star before the parenthesis is "any file"). > FLASH puts the output section in the FLASH region.

KEEP is a message to the garbage collector. With -ffunction-sections and --gc-sections, the linker discards sections that nothing references. The vector table is referenced only by the hardware, so it needs KEEP or it disappears, and the symptom is a board with a valid-looking image that does not start.

The order in the script is the order in the image, so .isr_vector is at 0x08000000 and .text follows it directly.

The linker script, part three: the two-address sections

.data is the section with two addresses, written with a keyword that says so:

link.ldText
  _sidata = LOADADDR(.data);

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

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

> RAM AT > FLASH is the line that makes .data work. It means: this section's addresses (its VMA) are in RAM, and its bytes are stored (its LMA) in FLASH, directly after the previous section there. The linker then assigns every .data variable a RAM address and puts the initial values in flash. LOADADDR(.data) is the flash address of those values, exported as _sidata, which the reset handler uses as the copy source. _sdata and _edata mark the destination in RAM.

.bss has no stored bytes at all: it is zeros, and the reset handler creates them. NOLOAD states that it is not part of the loaded image. It goes to RAM after .data, and the symbols _sbss and _ebss bound the clear loop.

After this you can see the arrangement with objdump:

Text
arm-none-eabi-objdump -h firmware.elf
Text
Idx Name          Size      VMA       LMA       File off  Algn
  0 .isr_vector   00000044  08000000  08000000  00010000  2**2
  1 .text         00000320  08000044  08000044  00010044  2**2
  2 .data         00000010  20000000  08000364  00020000  2**2
  3 .bss          00000028  20000010  20000010  00020010  2**2

.data has VMA 20000000 and LMA 08000364, which is right after .text ends in flash. .bss has the same VMA and LMA because it has no stored content. The numbers are an example for a small build; your sizes will differ. The pattern, VMA and LMA different only for .data, is the check to remember.

Reserving the heap and stack

The remaining RAM is for the heap (growing up from the end of static data) and the stack (growing down from the end of RAM). The linker script can check that the two have room:

link.ldText
  ._user_heap_stack :
  {
    . = ALIGN(8);
    PROVIDE(end = .);
    PROVIDE(_end = .);
    . = . + _Min_Heap_Size;
    . = . + _Min_Stack_Size;
    . = ALIGN(8);
  } > RAM

  /DISCARD/ :
  {
    libc.a ( * )
    libm.a ( * )
    libgcc.a ( * )
  }

  .ARM.attributes 0 : { *(.ARM.attributes) }
}

The ._user_heap_stack section holds no data. It advances the location counter by the minimum heap and stack sizes, so that if static data plus those reservations exceed RAM, the link fails with a region overflow instead of the program failing at run time. end and _end are the conventional names newlib's heap code expects for the first free address after static data. /DISCARD/ receives sections no earlier rule claimed, and the linker applies the first matching rule to each input section, so the useful content of the libraries has already been placed by .text and .data above.

This reservation is a floor, not a guarantee. The stack can grow past _Min_Stack_Size into the heap, and the linker cannot tell. The next sections show how to guard against it.

The syscalls newlib needs

If the program uses malloc, printf or scanf through newlib, the library calls a small set of functions you must provide because there is no operating system. The linker reports the missing ones as undefined references, such as _sbrk, _write, _close, _fstat, _isatty, _lseek and _read. Define minimal ones in a file:

syscalls.cc
#include <errno.h>
#include <stddef.h>
#include <sys/stat.h>

extern char end;
extern char _estack;

void *_sbrk(ptrdiff_t incr)
{
	static char *brk;
	char *prev;
	char *limit = &_estack - 0x1000;

	if (brk == NULL)
		brk = &end;

	prev = brk;
	if (incr > limit - brk) {
		errno = ENOMEM;
		return (void *)-1;
	}
	brk += incr;
	return prev;
}

int _write(int fd, const char *buf, int len)
{
	(void)fd; (void)buf;
	return len;                 /* discard output until a UART is wired up */
}

int _close(int fd)   { (void)fd; return -1; }
int _fstat(int fd, struct stat *st) { (void)fd; st->st_mode = S_IFCHR; return 0; }
int _isatty(int fd)  { (void)fd; return 1; }
int _lseek(int fd, int off, int whence) { (void)fd; (void)off; (void)whence; return 0; }
int _read(int fd, char *buf, int len) { (void)fd; (void)buf; (void)len; return 0; }

_sbrk is the allocator's source of memory: it moves a break pointer up from end and refuses when the heap would reach the stack reserve. The bounded version shown returns ENOMEM instead of letting malloc run into the stack. A later post in this cluster covers the details. _write here discards output; replacing its body with a UART transmit makes printf visible.

An alternative to writing these is --specs=nosys.specs, which links a stub library that defines them to fail harmlessly, at the price of a heap that always fails because its _sbrk is a stub.

Fault handlers worth having

A default handler that spins is the correct minimum. For development, a handler that records what happened is better. The Cortex-M pushes a stack frame on exception entry holding eight registers, and a hard fault handler can find the program counter that faulted:

fault.cc
#include <stdint.h>

struct fault_frame {
	uint32_t r0, r1, r2, r3, r12, lr, pc, psr;
};

volatile struct fault_frame g_fault;
volatile uint32_t g_cfsr;

void hardfault_c(const struct fault_frame *f)
{
	g_fault = *f;
	g_cfsr = *(volatile uint32_t *)0xE000ED28u;   /* Configurable Fault Status Register */

	for (;;)
		;
}

__attribute__((naked)) void HardFault_Handler(void)
{
	__asm volatile (
		"tst   lr, #4        \n"
		"ite   eq            \n"
		"mrseq r0, msp       \n"
		"mrsne r0, psp       \n"
		"b     hardfault_c   \n"
	);
}

The assembly picks the stack the faulting code was using from bit 2 of LR (the exception return value: 0 means MSP, 1 means PSP) and passes its address to the C function. g_fault.pc is then the address of the instruction that faulted, and arm-none-eabi-addr2line -e firmware.elf <pc> turns it into a source line. CFSR at 0xE000ED28 says why: a bit in the usage fault part for an undefined instruction or an invalid state, in the bus fault part for a bad access, in the memory management part for an MPU violation. Reading these in a debugger after a crash turns "the board hangs" into "line 42, a null pointer dereference".

Constructors and the init array

C++ global objects and C functions marked __attribute__((constructor)) need code to run before main. The compiler emits pointers to those functions into an array section, .init_array. The linker script must keep that section and expose its bounds, and the reset handler must call something that walks it, which is what __libc_init_array does. Add this to the script, between .text and .data:

link.ldText
  .preinit_array :
  {
    PROVIDE_HIDDEN(__preinit_array_start = .);
    KEEP(*(.preinit_array*))
    PROVIDE_HIDDEN(__preinit_array_end = .);
  } > FLASH

  .init_array :
  {
    PROVIDE_HIDDEN(__init_array_start = .);
    KEEP(*(SORT(.init_array.*)))
    KEEP(*(.init_array*))
    PROVIDE_HIDDEN(__init_array_end = .);
  } > FLASH

  .fini_array :
  {
    PROVIDE_HIDDEN(__fini_array_start = .);
    KEEP(*(SORT(.fini_array.*)))
    KEEP(*(.fini_array*))
    PROVIDE_HIDDEN(__fini_array_end = .);
  } > FLASH

Without these sections the program builds and boots, and every global constructor is silently skipped, so a C++ Led led(GPIOD, 12); at file scope is a block of zeros. With them, __libc_init_array runs each entry in the order the linker sorted them. A test is a global with a constructor that leaves evidence:

main.cc
#include <stdint.h>

static volatile uint32_t evidence;
__attribute__((constructor)) static void ctor(void) { evidence = 0xC0DE; }

int initialised_global = 0x1234;
int zeroed_global;

int main(void)
{
	for (;;) {
		if (evidence == 0xC0DE && initialised_global == 0x1234 && zeroed_global == 0)
			__asm volatile ("nop");
	}
}

If the three conditions hold, the startup code worked: the constructor ran, .data was copied and .bss was cleared. A debugger breakpoint at the first line of main and a read of these three values is the quickest way to prove a new startup file.

Following one interrupt through the whole path

The pieces so far meet when an interrupt fires, and tracing one end to end shows why the table, the weak aliases and the stack all matter. Suppose the program configures SysTick for a one-millisecond tick and defines a handler:

tick.cc
#include <stdint.h>

static volatile uint32_t ms;

void SysTick_Handler(void)
{
	ms++;
}

void systick_start(uint32_t core_hz)
{
	*(volatile uint32_t *)0xE000E014u = core_hz / 1000u - 1u;   /* SYST_RVR */
	*(volatile uint32_t *)0xE000E018u = 0;                      /* SYST_CVR */
	*(volatile uint32_t *)0xE000E010u = 7u;                     /* enable, interrupt, core clock */
}

When the counter reaches zero, the following happens, in order, with no software involved until the last step:

  1. The core finishes the current instruction and, since the interrupt is enabled and no higher-priority exception is active, takes the exception.

  2. It pushes eight registers onto the active stack: R0 to R3, R12, LR, the return address and the program status register. This is why the stack must be valid before the first interrupt can occur, and why _estack has to be a real RAM address.

  3. It reads the vector for exception number 15 (SysTick) from VTOR + 15 * 4, which is the table entry written as SysTick_Handler. Because the program defines that name, the strong definition replaced the weak alias, and the entry holds its address with the Thumb bit set.

  4. It loads a special value into LR (0xFFFFFFF9 or 0xFFFFFFFD depending on the stack in use) that tells the core how to return, and jumps to the handler.

  5. The handler runs as an ordinary C function. The Arm EABI ensures that the callee-saved registers are preserved by the compiler's prologue and epilogue, so the handler needs no assembly.

  6. The handler returns with bx lr, and the core, seeing the special value in LR, pops the eight registers and resumes the interrupted code.

If the program had not defined SysTick_Handler, step 3 would have found Default_Handler, step 5 would spin there forever, and the symptom would be a board that runs until the tick is enabled and then stops. A debugger would show the PC in Default_Handler and the exception number in SCB->ICSR.

This is also the practical test for a new table: enable one interrupt, trigger it and confirm the handler runs. SysTick is the easiest, because it needs no peripheral clock or pin.

The FPU and the startup code

A Cortex-M4F or M7 has a floating-point unit that is switched off at reset. Code compiled with hardware floating point (-mfloat-abi=hard -mfpu=fpv4-sp-d16) faults with a usage fault on the first floating-point instruction unless the coprocessors are enabled. The enabling is two bits in the Coprocessor Access Control Register, and it belongs in SystemInit or at the top of the reset handler, before any code that might use floating point, including memcpy implementations that use vector registers:

c
void SystemInit(void)
{
#if defined(__FPU_PRESENT) && (__FPU_PRESENT == 1U)
	*(volatile uint32_t *)0xE000ED88u |= (3u << 20) | (3u << 22);   /* CPACR: CP10 and CP11 full access */
#endif
}

CPACR is at 0xE000ED88, and setting CP10 and CP11 to 0b11 gives full access. After the write a data synchronisation barrier and an instruction barrier are recommended before the first floating-point instruction, which CMSIS's own SystemInit includes. A project that compiles with -mfloat-abi=soft does not need any of this, and a project that compiles with hard and forgets it sees a usage fault with the NOCP bit set in CFSR, which names the cause precisely.

The compiler flag choice also decides which library variant newlib links: -mfloat-abi=hard -mfpu=fpv4-sp-d16 picks the multilib built for it, and a mismatch between object files fails at link time with a message about "uses VFP register arguments" and incompatible ABIs. Compile every file, including the startup file, with the same -mcpu and float options.

A section that survives reset

Sometimes a value must outlive a soft reset: a boot counter, a crash record, a flag that tells the bootloader which image to run. The standard .bss clear destroys it. A dedicated section that the reset handler does not clear keeps it. In the linker script:

link.ldText
  .noinit (NOLOAD) :
  {
    . = ALIGN(4);
    *(.noinit)
    *(.noinit*)
    . = ALIGN(4);
  } > RAM

In C:

c
__attribute__((section(".noinit"))) volatile uint32_t boot_magic;
__attribute__((section(".noinit"))) volatile uint32_t boot_count;

#define BOOT_MAGIC 0xB007C0DEu

void note_boot(void)
{
	if (boot_magic != BOOT_MAGIC) {
		boot_magic = BOOT_MAGIC;
		boot_count = 0;               /* cold start: RAM held random bits */
	}
	boot_count++;
}

The magic value distinguishes a warm reset, where RAM kept its contents, from a power-up, where it did not and is probably not equal to the magic. The test is not perfect: a random power-up pattern can equal the magic with probability about two to the minus thirty-two, so add a checksum for data that matters. Place this section after .bss in the script and outside the range the reset handler clears. Some parts lose RAM contents in certain reset modes (a power-on reset always, a watchdog reset on most, a standby wake-up on some), so check the reference manual for which resets preserve SRAM before relying on it.

The Makefile

A short Makefile ties the compiler options, the link command and the conversion together:

MakefileText
CC      = arm-none-eabi-gcc
OBJCOPY = arm-none-eabi-objcopy
SIZE    = arm-none-eabi-size

CPU     = -mcpu=cortex-m4 -mthumb
CFLAGS  = $(CPU) -Os -g -Wall -ffunction-sections -fdata-sections \
          -fno-tree-loop-distribute-patterns
LDFLAGS = $(CPU) -T link.ld -nostartfiles --specs=nano.specs \
          -Wl,--gc-sections -Wl,-Map=firmware.map -Wl,--print-memory-usage

OBJS    = startup.o fault.o syscalls.o main.o

firmware.elf: $(OBJS) link.ld
	$(CC) $(OBJS) $(LDFLAGS) -o $@
	$(SIZE) $@

firmware.bin: firmware.elf
	$(OBJCOPY) -O binary $< $@

%.o: %.c
	$(CC) $(CFLAGS) -c $< -o $@

clean:
	rm -f *.o firmware.elf firmware.bin firmware.map

The pieces of the command line that matter:

  • -mcpu=cortex-m4 -mthumb targets the core. -mthumb is mandatory: the compiler might otherwise generate Arm-state code the core cannot run.

  • -ffunction-sections -fdata-sections give each function and variable its own section, so --gc-sections can drop the unused ones.

  • -nostartfiles leaves out the C library's own start-up object, because this project supplies its own. The library itself still links.

  • --specs=nano.specs selects newlib-nano, the size-optimised variant of the library.

  • -Wl,-Map=... writes the map file, and -Wl,--print-memory-usage prints how full each region is.

A build prints:

Text
arm-none-eabi-gcc startup.o fault.o syscalls.o main.o -mcpu=cortex-m4 -mthumb -T link.ld ... -o firmware.elf
Memory region         Used Size  Region Size  %age Used
           FLASH:        1964 B         1 MB      0.19%
             RAM:        8232 B       128 KB      6.28%
   text	   data	    bss	    dec	    hex	filename
   1964	      4	     36	   2004	    7d4	firmware.elf

The RAM figure of 8232 bytes includes the 8 KiB reserved for heap and stack, which explains why it is much larger than data plus bss. The numbers here are an example; yours depend on the code and the compiler.

Flashing and the first run

With OpenOCD and an ST-LINK on the Discovery board:

Text
openocd -f interface/stlink.cfg -f target/stm32f4x.cfg \
        -c "program firmware.elf verify reset exit"

OpenOCD loads each ELF segment to its load address, which is why the .data image ends up after .text in flash without any extra step from you. The reset at the end starts the program.

To look at the state at the first line of main, start a debug session:

Text
openocd -f interface/stlink.cfg -f target/stm32f4x.cfg
arm-none-eabi-gdb firmware.elf
(gdb) target extended-remote :3333
(gdb) monitor reset halt
(gdb) break main
(gdb) continue
(gdb) print/x initialised_global
(gdb) print/x zeroed_global
(gdb) print/x evidence
Text
$1 = 0x1234
$2 = 0x0
$3 = 0xc0de

All three correct means the whole boot path works: the table, the copy, the clear, the constructors. If any is wrong, the table in the failure section below says where to look.

Reading the map file

The map file lists every section and the file each came from. It is the tool to use when the flash fills up unexpectedly. A fragment:

Text
.text           0x08000044      0x320
 *(.text)
 .text          0x08000044       0x1c startup.o
 *(.text*)
 .text.main     0x08000060       0x58 main.o
 .text.Reset_Handler
                0x080000b8       0x4c startup.o
                0x080000b8                Reset_Handler

Each line gives an address, a size in hexadecimal, and the object file. The cross-reference table at the end lists, for each symbol, where it is defined and used. When a library function appears that you did not call, the first section of the map ("Archive member included to satisfy reference by file") shows the chain of references that pulled it in.

You can rank what is big without reading the map, with the symbol table:

Text
arm-none-eabi-nm --size-sort -S firmware.elf | tail -3
Text
00000058 T main
0000004c T Reset_Handler
00000044 R vector_table

The columns are size and symbol with a type letter: T is code, R is read-only data, D is initialised data, B is zero-initialised data. Uppercase means global.

The ways boot goes wrong

Most failures before main have one of a small number of causes. The table is in order of how often they occur.

SymptomLikely causeHow to confirm
Nothing happens, debugger shows PC in Default_HandlerA fault or unhandled interruptRead CFSR, read the stacked PC in HardFault_Handler
Nothing happens, PC at 0x00000000 or randomVector table not at the start of flash, or missing KEEPobjdump -h shows .isr_vector at 0x08000000
Hard fault right after resetReset vector without the Thumb bit, or wrong stack topx/2wx 0x08000000: second word odd, first word at the RAM end
Globals have wrong values.data copy symbols wrong, or _sidata at the wrong placeCompare _sidata with the .data LMA in objdump -h
Zero-initialised variables are not zero after a warm reset.bss clear missing or truncated by the compilerDisassemble Reset_Handler, look for memset
Constructors do not run.init_array not in the script, or __libc_init_array not callednm shows __init_array_start equal to __init_array_end
malloc returns NULL early_sbrk limit wrong, or heap reserve too smallPrint end, _estack and the limit
Link error undefined reference to _sbrkSyscalls missingProvide them or use nosys.specs
Link error region RAM overflowedStatic data plus reservations larger than RAMThe map file shows the biggest sections
Random crashes under loadStack overflow into heap or .bssFill the stack with a pattern and check the low-water mark

The stack check in the last row is a technique worth keeping. At startup, fill the reserved stack region with a known pattern such as 0xDEADBEEF words, and later scan upward from the bottom for the first word that differs: that is the deepest the stack has been.

c
extern uint32_t _estack;
extern uint32_t _Min_Stack_Size;

void stack_paint(void)
{
	uint32_t *p = (uint32_t *)((char *)&_estack - 0x1000);
	uint32_t *sp;

	__asm volatile ("mov %0, sp" : "=r" (sp));
	while (p < sp - 16)
		*p++ = 0xDEADBEEFu;
}

uint32_t stack_free_words(void)
{
	uint32_t *p = (uint32_t *)((char *)&_estack - 0x1000);
	uint32_t n = 0;

	while (*p == 0xDEADBEEFu) {
		p++;
		n++;
	}
	return n;
}

stack_paint runs early and marks everything below the current stack pointer. stack_free_words counts how many words are still untouched at the bottom. It reports how much of the reserve was never used, so you can size the reserve with evidence, not a guess.

Relocating the vector table

The reset vector lives at the start of flash, but the vector table can be moved afterward with the Vector Table Offset Register, SCB->VTOR. A bootloader uses this to give control to an application whose table is at another address, and an application can copy the table to RAM to install handlers at run time. The register takes an address aligned to the table size rounded up to a power of two, at least 128 bytes; for the 98 entries of an STM32F407 that is 512 bytes. A bootloader at 0x08000000 that starts an application linked at 0x08008000 does this before the jump:

boot.cc
#include <stdint.h>
#include "stm32f407xx.h"

#define APP_BASE 0x08008000u

void jump_to_app(void)
{
	uint32_t sp = *(volatile uint32_t *)(APP_BASE + 0);
	uint32_t pc = *(volatile uint32_t *)(APP_BASE + 4);

	__disable_irq();
	SCB->VTOR = APP_BASE;
	__set_MSP(sp);

	((void (*)(void))pc)();
}

The application's linker script uses FLASH ORIGIN = 0x08008000 and a shorter LENGTH, so its table sits at the offset the bootloader reads. The application's own start-up must not reset VTOR to 0x08000000, which the vendor's SystemInit does unless its VECT_TAB_OFFSET is set to the same offset. A symptom of getting that wrong is an application that runs until the first interrupt, then jumps into the bootloader's handlers.

Running code from RAM

Sometimes a function should run from RAM: flash erase and program routines, or a loop that must not stall on flash wait states. Mark the function with a section name, give the section both addresses in the script and copy it at start-up:

ram.cc
#define RAMFUNC __attribute__((section(".ramfunc"), noinline, long_call))

RAMFUNC void flash_wait_idle(void)
{
	while (*(volatile uint32_t *)0x40023C0Cu & (1u << 16))
		;
}
link.ldText
  _siramfunc = LOADADDR(.ramfunc);

  .ramfunc :
  {
    . = ALIGN(4);
    _sramfunc = .;
    *(.ramfunc)
    *(.ramfunc*)
    . = ALIGN(4);
    _eramfunc = .;
  } > RAM AT > FLASH

The reset handler copies _siramfunc to _sramfunc as it copies .data. The long_call attribute is required, because a plain bl instruction cannot reach from flash at 0x08000000 to RAM at 0x20000000. A dedicated post in this cluster covers the details and the traps.

Reading the first bytes of the image

The fastest check that a build is bootable needs no board. Convert the ELF to a raw binary and look at its first eight bytes, which are exactly the two words the core will read:

Text
arm-none-eabi-objcopy -O binary firmware.elf firmware.bin
xxd -l 16 firmware.bin
Text
00000000: 0000 0220 b500 0008 a900 0008 a900 0008  ... ............

The bytes are little-endian, so the first word reads 0x20020000: the end of the 128 KiB of RAM that starts at 0x20000000, which is the right initial stack pointer. The second word reads 0x080000b5. It is odd, so the Thumb bit is set, and 0x080000b4 should be the address of Reset_Handler, which nm confirms. The third and fourth words are the NMI and HardFault entries, both 0x080000a9 here, the weak default handler with the Thumb bit set. If the first word is anything other than a RAM-end address, or the second is even or points outside flash, the board will not start, and you have found the bug without touching hardware. The values in this dump are an example for one build.

Do the same check in CI. A three-line script that extracts the first two words from the binary and asserts the first equals the RAM end and the second is odd and inside flash costs nothing and catches every "vector table not first" mistake.

Changing the layout as the project grows

The script above is the starting point. These are the usual edits and where each goes:

ChangeWhere to editWhat else must change
Use a second RAM region such as CCMAdd a region to MEMORY, a section with > CCMRAMStartup copy loop if it holds initialised data; DMA must not use it on the STM32F4
Reserve space for a bootloaderRaise the FLASH ORIGIN, shorten LENGTHVECT_TAB_OFFSET or SCB->VTOR in SystemInit; the bootloader's jump address
Add a configuration page at the end of flashShorten LENGTH so code stops before the pageCode that writes the page uses the new fixed address
Add a version recordNew section placed after .isr_vector with KEEPA tool or bootloader that reads the fixed offset
Run a function from RAM.ramfunc with > RAM AT > FLASHA copy loop in the reset handler; long_call on the function
Split code across two flash banksTwo regions and two sets of sectionsEach bank's start-up and any table that points across

Every one of these is a few lines in the script and a few in the startup code, and every one follows the pattern set out above: decide the addresses in the script, export a symbol for each boundary, and use the symbol in the startup code. When a change does not work, the question to ask is which of those three steps was skipped.

Checks that belong in the build

A linker script has cheap safety nets that cost a line each and prevent a class of silent bugs. Add them at the end of the SECTIONS block:

link.ldText
ASSERT(ADDR(.isr_vector) == ORIGIN(FLASH), "vector table must be first in flash")
ASSERT(_estack == 0x20020000, "RAM size changed: check MEMORY and _estack")
ASSERT(LOADADDR(.data) + SIZEOF(.data) <= ORIGIN(FLASH) + LENGTH(FLASH), "data image does not fit")

ASSERT stops the link with your message when the condition is false. The first protects against someone adding a section above the table. The second protects _estack when the part changes. The third verifies that the .data image, which sits after the code, still fits in flash, a case the region check might not report clearly.

Pair them with a CI step that fails the build when a section grows by more than a set amount, using arm-none-eabi-size output, as the size budget post in this cluster describes.

Where this does not apply

The code and script above are for the Armv7-M profile: Cortex-M3, M4 and M7. Nearby cores differ in ways worth knowing.

Cortex-M0 and M0+ (Armv6-M). The vector table is the same shape, but the instruction set is a smaller Thumb subset, so -mcpu=cortex-m0plus is required, and there is no VTOR on the M0 (the M0+ has it as an option). There is no hardware divide, and the compiler emits library calls. The fault handling registers (CFSR and friends) do not exist; a HardFault gives only the stacked frame.

Cortex-M23 and M33 (Armv8-M). The table is the same, with a Secure and a Non-secure copy on parts with TrustZone, each with its own VTOR. They also add the stack limit registers MSPLIM and PSPLIM, which turn a stack overflow into a fault, and a post in this cluster covers them.

Cortex-A and Cortex-R. They boot differently: the reset vector is code, not an address, the exception table has a different layout, and a cache and MMU must be set up. This guide does not apply.

Parts with a boot ROM. Many microcontrollers run a ROM bootloader first (STM32 system memory, LPC ISP, RP2040 boot ROM and its second-stage boot loader). The start-up path described here begins after the ROM hands over; the RP2040, for example, needs a 256-byte second-stage image at the start of flash that the ROM checks before it runs your table.

A checklist for a new project

When you start a new board or a new chip, walk this list, and most boot problems will not appear:

  1. Read the memory map in the reference manual and write the MEMORY block from it, with the real origins and lengths.

  2. Check where the boot configuration points address zero, and put the vector table there.

  3. Write the table with the right number of entries for the device and every handler weak.

  4. Copy .data, clear .bss, call SystemInit and __libc_init_array, then main.

  5. Keep the vector table, the init arrays and anything else the hardware or runtime references with KEEP.

  6. Compile with -ffunction-sections -fdata-sections and link with --gc-sections.

  7. Reserve heap and stack in the script and bound _sbrk.

  8. Add a fault handler that records the stacked frame and CFSR.

  9. Add the ASSERT lines and --print-memory-usage.

  10. Verify with the three-variable test at the first line of main.

Also inToolchains
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.