static object destruction in shared library

Jeff Greif jmg@trivida.com
Wed Dec 1 18:32:00 GMT 1999


Sorry, I've lost the exact subject line of the message to which I'm 
replying.  The issue is how to handle destruction of static objects created 
in a shared library.  When atexit is used to cause the destruction, there 
are potential bad interactions with premature unloading of the dll.
 
Windows NT attempts to address this problem by having an atexit() call from 
a dll use an atexit registry that is maintained in the dll itself, and is 
traversed when the dll is unloaded.  There is a standard atexit registry in 
the main executable which is handled in the normal way.  This idea seems 
pretty good at first glance, but it also has problems in the case where a 
disorderly process shutdown occurs, or in the case where process shutdown occurs 
normally but various different stages cannot always be arranged to occur in the 
correct order.  For example, suppose you use a static thread-related object 
in a dll.  When you shut down a process that has multiple threads by 
calling exit or returning from main(), the outstanding threads other than the 
main thread just happen to be destroyed before any dlls are unloaded.  
Running the destructor of the dll's static object may then cause an illegal 
memory access.  It's likely that the order thread destruction preceding dll 
unload was chosen based on other nasty interactions (an obvious candidate being 
the the thread-related functions of the runtime library usually loaded 
dynamically).
 
Probably the correct solution for this problem will involve some kind 
of dependency graph of the various exit/unload-related activities, with a 
topological sort on the nodes dictating the order of processing.  It's not 
clear to me that the compiler or linker has enough information available to 
always produce valid results.
 
Jeff



More information about the Gcc-bugs mailing list