Is there any way in C/C++ to detect if code is running during static initialization?
I'm writing a tracing开发者_如何学C library that is available as a DLL. It is consumed by basically every component in my system. One tricky requirement is that the tracing functions need to be invoked very early in the process lifetime, even before main() runs.
Consumers of this library include executables, statically linked DLLs, delay-loaded DLLs and dynamically loaded DLLs. All the variations.
Some tracing features do no play well with static initialization but others are fine. Ideally, I'd like to be able to offer consumers minimal safe functionality during init time and then full functionality after init is complete.
Asking consumers to make an explicit "I'm done init" call themselves doesn't work because of the fact that certain consumers are DLLs themselves and have no control over the executable hosting them. The same problem just moves one level up the chain.
What I'm hoping is that there is some way for me to ask the runtime whether or I'm currently running in static initialization or whether that stage is complete. Is such a thing possible?
To complicate matters further, I need to run on 5 platforms. I don't need a write-once solution but I do need to get it working somehow on all platforms.
Global variable? Something like:
bool initTime = true;
in your DLL and then
int main()
{
initTime = false;
// your main code comes here
}
in your executable.
You write that
Some tracing features do no play well with static initialization but others are fine.
However, most of the time the problem lies not in the static initialization phase of the executable (the process), but in the static initialization phase of the/a DLL. You must be aware that every DLL has it's own static initialization phase for it's static C++ object. Specifically your tracing DLL has too, and so has any other DLL that might use your DLL.
To sum up: Probably you do not care if the static initialization phase of the executable has finished but you do care if a) your own DLL has finished initializing and b) if while calling into your DLL the Loader Lock is currently held.
As to a) If your DLL is finished initializing is only a problem inside your code as noone can call into your DLL before it's initialized.
As to b) It does seem that there is no (portable, documented) way to determine from code if the loader lock is currently being held. I do not know any other way than to clearly document which functions must not be called while the Loader Lock is being held.
You may have to rewrite (well, modify) and then link with your rewritten crt0.o. That's obviously going to have to be different for each platform.
精彩评论