Write the Reset Handler
Before main() runs, start-up code must copy the .data section's initial values from flash to RAM and zero .bss. Implement reset_init() using the linker-provided symbols. In this simulation the "flash" and "RAM" are arrays, and the symbols are pointers into them.
Write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.
Two loops over word pointers: copy from _sidata to _sdata until _edata, then write zero from _sbss until _ebss.
#include <stdio.h>
#include <stdint.h>
#include <string.h>
static const uint32_t flash_image[3] = { 0x11111111u, 0x22222222u, 0x33333333u };
static uint32_t ram[8] = { 0xDEAD, 0xDEAD, 0xDEAD, 0xDEAD, 0xDEAD, 0xDEAD, 0xDEAD, 0xDEAD };
static const uint32_t *_sidata = flash_image;
static uint32_t *_sdata = &ram[0], *_edata = &ram[3];
static uint32_t *_sbss = &ram[3], *_ebss = &ram[7];
void reset_init(void)
{
const uint32_t *src = _sidata;
for (uint32_t *dst = _sdata; dst < _edata; )
*dst++ = *src++;
for (uint32_t *dst = _sbss; dst < _ebss; )
*dst++ = 0;
}
On real hardware the symbols come from the linker script, declared as extern uint32_t _sdata, _edata, ...; and used by address (&_sdata). The linker script aligns the sections to 4 bytes so word copies are safe.
A real reset handler then calls SystemInit() (clocks, FPU enable), __libc_init_array() for C++ constructors, and finally main(). It must not rely on any initialised global data before these loops run, and it must be careful not to let the compiler turn the loops into calls to memcpy/memset that themselves depend on initialised data (-ffreestanding or -fno-builtin help). Some projects write this in assembly for that reason.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
reset_init();
CHECK(ram[0] == 0x11111111u && ram[1] == 0x22222222u && ram[2] == 0x33333333u);
CHECK(ram[3] == 0 && ram[4] == 0 && ram[5] == 0 && ram[6] == 0);
CHECK(ram[7] == 0xDEAD); /* must not touch memory past _ebss */
puts(fails ? "Some tests failed" : "All tests passed");
return fails != 0;
}