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.
Reset sequence
- The CPU reads the initial stack pointer value from entry 0 of the vector table and puts it in sp
- It reads the address of Reset_Handler from entry 1 and jumps there
- Reset_Handler does the work below
SystemInit(): basic settings such as clocks and Flash wait statesmain()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
.noinitsection to avoid .bss initialisation. - On chips with a lot of RAM, the time to zero .bss can affect the boot time.