Ground Embedded KO Subscribe

Notes / Machine Code & Assembly

Startup code: what happens before main

Right after reset, the CPU copies .data to RAM and fills .bss with zeros, and only then calls main. Follow startup.s line by line.

GROUND EMBEDDED · NOTEMachine Code & Assembly 05Startup code 1ldr r0, =0x40020014 2ldr r1, [r0] 3orr r1, r1, #0x20 4str r1, [r0] 5bl main 6b .

Reset sequence

ResetRead SP, PC from the vector tableReset_HandlerCopy .data · zero .bssmain()
From reset to main.
  1. The CPU reads the initial stack pointer value from entry 0 of the vector table and puts it in sp
  2. It reads the address of Reset_Handler from entry 1 and jumps there
  3. Reset_Handler does the work below
  4. SystemInit(): basic settings such as clocks and Flash wait states
  5. main() is called

What Reset_Handler does

  • Copy .data: a global variable with an initial value, such as int count = 5;, has that initial value stored in Flash. It is copied to the variable's location in RAM.
  • Initialise .bss: the area for global variables without an initial value, such as int total;, is filled with 0, because the C standard guarantees that globals start at 0.
  • C++ constructors / library initialisation (__libc_init_array)

Problems you meet in practice

  • If variables have strange values after jumping from a bootloader to the application, check that the application's startup code ran properly.
  • Values that must survive a reset (a record of the reset cause, for example) go in a .noinit section to avoid .bss initialisation.
  • On chips with a lot of RAM, the time to zero .bss can affect the boot time.
FREE PDFGet the 3 free ebooksIf you want to keep reading this topic as one book: BLDC motor control, serial communication and sensors at book length. PDFs are in Korean.Get them free →