January 27, 2020
I had a problem recently where I needed to allocate memory before constructors for global objects that I have initialized outside of a function. We know that constructs are called when an object is created, but it’s less obvious when and where this takes place on program startup for these types of objects.
In my case I’ll be using Atollic TrueSTUDIO and CubeMX , tools for STM products, for my examples.
When analyzing microcontroller startup, we should look to the startup file that’s provided by whatever manufacturer makes your microcontroller. These files are typically .s or .asm assembly files and will be specific to your controller’s model number. In my case, my file was generated inside a folder labeled “Startup” and is named startup_stm32f072xb.s
Inside this file you should find assembly functions such as Reset_Handler: and g_pfnVectors: Reset_handler is the first function that executes when the processor exits from reset and g_pfnVectors defines your IRQ vector table locations in Flash memory. These names may be different if they were generated by a GNU C compiler.
Also in this file you should find another assembly function named LoopFillZerobss: or similar. This is the last function that executes from startup before branching to your program’s main() function. Inside mine, you can see calls to a couple more setup functions:
The one we’re interested in is __libc_init_array. If your project supports C++, this is the code related to constructors and other library initialization necessary before calling main. In other words, this is the specific line that calls all of your constructors for global objects in your program! In my use case, I created a function that allocates the memory required for one of my global objects and inserted a call to it after SystemInit but before __libc_init_array.