Thursday, October 27, 2011

Debugging static object destruction order

If you like to avoid the “static initialization order fiasco” by using construct on first use idiom but with a static object instead of a static object pointer, you might also run into static destruction order fiasco. One solution is to reorder the static constructors so that the destructors are called in the right order, by forcing the static object to be referenced before its first use.

In order to do decide how to reorder the destruction sequence, we need to tell how it will be carried out. The static destructors are called in reverse order the static constructors are called. Leveraging the fact that destructors are registered using __cxa_atexit (this is part of Itanium C++ ABI, which is adopted by Linux Standard Base and implemented in GCC) as soon as the constructor finishes, we can set breakpoint for __cxa_atexit to see the constructor order, which in turn means the destructors will be called in reverse.

The gdb recipe here will print the name of the function that contains the static object whenever the static object is constructed, but will continue execution.
(gdb) b __cxa_atexit  # assume this is breakpoint n
# set commands to automatically execute for breakpoint n
(gdb) commands n
>where 2

(gdb) b __cxa_finalize
This allows you to generate a log of construction order without breaking and analyze it offline.
Post a Comment