3

What happens with the following code in a DLL ?

#include <vector>
std::vector<int> global_vector;

BOOL WINAPI DllMain(HANDLE hModule, DWORD fdwReason, LPVOID lpReserved)
{
    if (fdwReason == DLL_PROCESS_ATTACH)
    {
        global_vector.push_back(1);
    }

    return TRUE;
}

... if compiled with /MD ? The code called by the vector's constructor and push_back (ie memory management, exception handling...) lie in MSVCRT.DLL... which as far as I understand is not guaranteed to be mapped at this stage. Does it get special treatment ?

docdocdoc9
  • 138
  • 5

1 Answers1

1

From here:

In a nutshell, when DllMain is called, OS loader is in a rather fragile state. First off, it has applied a lock on its structures to prevent internal corruption while inside that call, and secondly, some of your dependencies may not be in a fully loaded state. Before a binary gets loaded, OS Loader looks at its static dependencies. If those require additional dependencies, it looks at them as well. As a result of this analysis, it comes up with a sequence in which DllMains of those binaries need to be called. It's pretty smart about things and in most cases you can even get away with not following most of the rules described in MSDN - but not always.

user541686
  • 205,094
  • 128
  • 528
  • 886