1# Initializers/Constructors and Finalizers/Destructors in Picolibc 2 3The `__libc_init_array` and `__libc_fini_array` functions in Picolibc 4are called by Picocrt during application startup and shutdown. If you 5have custom start up code that replaces Picocrt, you probably want to 6call these as well. 7 8## `__libc_init_array` 9 10This function performs application initialization by calling: 11 12 1) Functions listed in the preinit array 13 2) _init function 14 3) Functions listed in the init array 15 16### _init function 17 18Your program may declare an optional initialization function called 19`_init`. If such a function is included in the binary it will be 20called before the init array contents are evaluated. 21 22## `__libc_fini_array` 23 24Most embedded applications never return from main, but if yours does, 25Picocrt will call: 26 27 1) Functions listed in the fini array 28 2) _fini function 29 30### _fini function 31 32Your program may declare an optional finalization function called 33`_fini`. If such a function is included in the binary it will be 34called after the fini array contents are evaluated. 35 36## Automatically generated arrays of function pointers 37 38The `.preinit_array`, `.init_array` and `.fini_array` segments are 39built by the linker using data generated by the compiler. When you 40decorate a function with `__attribute__((constructor))`, the compiler 41places the address of the function into the `.init_array` 42segment. Decorate a function with `__attribute__((destructor))` and 43the compiler will place its address in the `.fini_array` segment. The 44`.preinit_array` segment is generated internally by the compiler for 45things like C++ vtable validation 46 47The linker script should collect all of the data from these segments 48into memory (probably flash as it doesn't change) so that the image 49ends up with arrays of function pointers. For data from the 50`.init_array` segment, the array should start with the symbol 51`__init_array_start` and ending with `__init_array_end`. For data from 52the `.fini_array` segment, the array should start with the symbol 53`__fini_array_start` and end with `__fini_array_end`. Finally, for 54data from the `.preinit_array` segment, the array starts with 55`__preinit_array_start` and ends with `__preinit_array_end`. 56 57Each of these arrays are complicated by the optional priority assigned 58to destructors and constructors, and the presense of the deprecated 59`.ctors` and `.dtors` segments. 60